branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>JiangBaohan/DrawerLayout_TabLayout<file_sep>/drawelayout/src/main/java/com/example/demo04_drawelayout/MainActivity.java
package com.example.demo04_drawelayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.List;
/**
* 1.完成布局
* 2.初始化控件
* 3.初始化ActionBar
* 4.初始化viewpager
* 5.使两两之间关联
*/
public class MainActivity extends AppCompatActivity {
private DrawerLayout drawerLayout;
private TabLayout tabLayout;
private ActionBarDrawerToggle mToggle;
private ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();//初始化控件对象
initActionBar();//初始化ActionBar
initViewPager();//初始化ViewPager
}
private void initView() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
tabLayout = (TabLayout) findViewById(R.id.tab);
viewPager = (ViewPager) findViewById(R.id.viewpager);
}
private void initActionBar() {
//获取一个ActionBar
ActionBar actionBar = getSupportActionBar();
//给左上角的左边加一个返回的图标
actionBar.setDisplayHomeAsUpEnabled(true);
//这个类提供了一种方便的方式来绑定的功能
//参数上下文 2.drawerLayout 3.4R.string.资源(照顾盲人,点击时有声音)
mToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.open, R.string.close);
//将抽屉指示器的状态与连接的drawerlayout同步其状态
mToggle.syncState();
drawerLayout.addDrawerListener(mToggle);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void initViewPager() {
//创建一个集合,用来装fragment
List<Fragment> fragments = new ArrayList<>();
//把VR全景图和视频的fragment对象装入集合显示
fragments.add(new VRPanoFrament());
fragments.add(new VrVideoFrament());
//创建viewpager适配器对象
MyPagerAdpater adpater = new MyPagerAdpater(getSupportFragmentManager());
//把集合传给适配器
adpater.setFragment(fragments);
//viewpager设置适配器
viewPager.setAdapter(adpater);
//-----------------tabLayout知识---要再build.gradle依赖-android.support.design.widget.TabLayout------------------------
//tablayout指示器有几个就创建几个
tabLayout.addTab(tabLayout.newTab());
tabLayout.addTab(tabLayout.newTab());
//使用tablayout与viewpager相关联
tabLayout.setupWithViewPager(viewPager);
//给tablayout指示器是这文本,万物从0开始,0就是给第一个指示器设置的文本
tabLayout.getTabAt(0).setText("第一栏");
tabLayout.getTabAt(1).setText("第2222栏");
}
}
| fea62fa60fc90bf28adb088e8c1f5c8ff023f5e9 | [
"Java"
] | 1 | Java | JiangBaohan/DrawerLayout_TabLayout | ca9ef69a26e78333aa3af044b45b743d401fdf20 | e777cd854a0f017369ccd3aac3763588c51f36a1 |
refs/heads/master | <file_sep># R-P-S-L-S-Game
Rock, Paper, Scissors, Lizard, Spock
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace R_P_S_L_S_GameProject
{
class Game
{
//member variables
public Player playerOne;
public Player playerTwo;
//constructor
public Game()
{
}
public void RunGame()
{
//1.Display rules
//2.ChooseGameType***
//a. Player vs Computer***
//b. Player vs Player***
//3. Get player name***
//4.Players choose gestures***
//a. playerOne.ChoosGesture***
//b. playerTwo.ChooseGesture***
//5.CompareGestures***
//6.Determine round winner***
//7. Determine if there is a Game winner
//if Yes; end game, declare winner, "play again?"
//if No; loop back to step 4
//DisplayRules Method
string numberOfPlayers = ChooseGameType();
CreatePlayers(numberOfPlayers);
while(playerOne.score !=2 && playerTwo.score !=2)
{
playerOne.ChooseGesture();
playerTwo.ChooseGesture();
CompareGestures();
}
DisplayWinner();
}
//Member methods
public void DisplayRules()
{
//RULES OF RPSLS
//"Rock crushes Scissors:
//"Scissors cuts Paper"
//"Paper covers Rock"
//"Rock crushes Lizard"
//"Lizard poisons Spock"
//"Spock smashes Scissors"
//"Scissors decapitates Lizard"
//"Lizard eats Paper"
//"Paper disproves Spock"
//"Spock vaporizes Rock"
}
public string ChooseGameType()
{
Console.WriteLine("Welcome to Rock, Paper, Scissors, Lizard, Spock!\n\n\n How would you like to play ?\n\n 1) Player vs. Player\n 2) Player vs. Computer\n");
string input = Console.ReadLine();
return input;
}
public void CreatePlayers(string numberOfPlayers)
{
if (numberOfPlayers == "1")
{
playerOne = new Human();
playerTwo = new Human();
}
else if (numberOfPlayers == "2")
{
playerOne = new Human();
playerTwo = new Computer();
}
}
public void CompareGestures()
{
//Check Tie
if(playerOne.gesture == playerTwo.gesture)
{
Console.WriteLine("Both players tied!\n");
}
//Player One Compare Gesture
else if(playerOne.gesture == "Rock" && (playerTwo.gesture == "Scissors" || playerTwo.gesture == "Lizard"))
{
Console.WriteLine(playerOne.name +" wins the round!\n");////playerOne.name
playerOne.score++;
}
else if (playerOne.gesture == "Paper" && (playerTwo.gesture == "Rock" || playerTwo.gesture == "Spock"))
{
Console.WriteLine("Player One Wins the Round!\n");
playerOne.score++;
}
else if (playerOne.gesture == "Scissors" && (playerTwo.gesture == "Paper" || playerTwo.gesture == "Lizard"))
{
Console.WriteLine("Player One Wins the Round!\n");
playerOne.score++;
}
else if (playerOne.gesture == "Lizard" && (playerTwo.gesture == "Spock" || playerTwo.gesture == "Paper"))
{
Console.WriteLine("Player One Wins the Round!\n");
playerOne.score++;
}
else if (playerOne.gesture == "Spock" && (playerTwo.gesture == "Scissors" || playerTwo.gesture == "Rock"))
{
Console.WriteLine("Player One Wins the Round!\n");
playerOne.score++;
}
//Player Two Compare Gesture
else if (playerTwo.gesture == "Rock" && (playerOne.gesture == "Scissors" || playerTwo.gesture == "Lizard"))
{
Console.WriteLine("Player Two Wins the Round!\n");
playerTwo.score++;
}
else if (playerTwo.gesture == "Paper" && (playerOne.gesture == "Rock" || playerTwo.gesture == "Spock"))
{
Console.WriteLine("Player Two Wins the Round!\n");
playerTwo.score++;
}
else if (playerTwo.gesture == "Scissors" && (playerOne.gesture == "Paper" || playerTwo.gesture == "Lizard"))
{
Console.WriteLine("Player Two Wins the Round!\n");
playerTwo.score++;
}
else if (playerTwo.gesture == "Lizard" && (playerOne.gesture == "Spock" || playerTwo.gesture == "Paper"))
{
Console.WriteLine("Player Two Wins the Round!\n");
playerTwo.score++;
}
else if (playerTwo.gesture == "Spock" && (playerOne.gesture == "Scissors" || playerTwo.gesture == "Rock"))
{
Console.WriteLine("Player Two Wins the Round!\n");
playerTwo.score++;
}
}
public void DisplayWinner()
{
if(playerOne.score >= 2)
{
Console.WriteLine(playerOne.name + " wins the game!!!");
}
else
{
Console.WriteLine(playerTwo.name + " wins the game!!!");
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace R_P_S_L_S_GameProject
{
public abstract class Player
{
//member variables
//public int score
public string name;
public int score;
public string gesture;
public List<string> gestures;
//constructor
public Player()
{
score = 0;
gestures = new List<string>();
gestures.Add("Rock");
gestures.Add("Paper");
gestures.Add("Scissors");
gestures.Add("Lizard");
gestures.Add("Spock");
SetName();
}
//member methods
public abstract void SetName();
public abstract void ChooseGesture();
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace R_P_S_L_S_GameProject
{
public class Human : Player
{
//member variables
//constructor
public Human()
{
}
//member methods
public override void SetName()
{
Console.WriteLine("\nPlease enter your name:\n");
name = Console.ReadLine();
}
public override void ChooseGesture()
{
//Disply Gesture List Choices with string capture of "number" for each index
Console.WriteLine("\n Rock\n Paper\n Scissors\n Lizard\n Spock\n");
gesture = Console.ReadLine();
//if....user validation
//else
}
//public override string "ChooseGesture" method...must return result
//"userInput" variable to hold value for "player.gesture" index
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace R_P_S_L_S_GameProject
{
class Computer : Player
{
Random random;
//member variables
//constructor
public Computer()
{
random = new Random();
}
//member methods
public override void SetName()
{
name = "Computer";
Console.WriteLine("You are playing against the Computer!");
}
public override void ChooseGesture()
{
int randomNumber = random.Next(0, 4);
gesture = gestures[randomNumber];
}
//public override string "ChooseGesture" method...must return result
// create random number generator to pick index of "player.gestures
}
}
| b3eb95a1426cda0011c9c0e2ccdcec76a9a24760 | [
"Markdown",
"C#"
] | 5 | Markdown | dane-hoffman/R-P-S-L-S-Game | 025730a328a57129b1fa4289783a1d5bb3c5273e | 88cb5df5c6e408315402e314e1c28e5d45296ae9 |
refs/heads/master | <repo_name>CarmaSys/CarmaLinkSDK<file_sep>/PHP/example/index.php
<?php
/**
* This serves as a simple example of how you would utilize the PHP SDK for simple queries / configurations
* You could run this in a browser or on the command line
*/
require_once realpath(__DIR__."/../CarmaLinkAPI.php");
// API key provided by CarmaSys
define('CARMALINK_KEY','YOUR KEY HERE');
// API secret provided by CarmaSys
define('CARMALINK_SECRET','YOUR SUPER SECRET HERE');
// General info about the API URI
$apiInfo = array(
'HOST'=>'api.somewhere.net',
'PORT'=>8282,
'HTTPS'=>true
);
$carmaLinkAPI = new CarmaLink\CarmaLinkAPI(CARMALINK_KEY, CARMALINK_SECRET, $apiInfo, TRUE);
// Note: serials must be from CarmaLinks owned by the API key used above.
$serials = array(
"single" => "517",
"multiple_range" => "10050-10100",
"multiple_ranges" => "2000-3000.5000-5500",
"nonconsecutive_single" => "10050.10055",
"mixed" => "100.104.110-115.200"
);
$res = $carmaLinkAPI->getReportData($serials["single"],'all_activity');
print_r($res);
$res = $carmaLinkAPI->getReportData($serials["multiple_range"],'hard_braking',array('limit'=>10));
print_r($res);
$res = $carmaLinkAPI->getReportData($serials["nonconsecutive_single"],'trip_report',array('limit'=>30,'since'=>1346780257804));
print_r($res);
<file_sep>/PHP/lib/CarmaLinkAPI.php
<?php
namespace CarmaLink;
/**
* Monolog for debug/info logging (MIT license)
*
* @see https://github.com/Seldaek/monolog.git
*/
require_once realpath(__DIR__. '/../monolog/src/Monolog/Logger.php');
require_once realpath(__DIR__. '/../monolog/src/Monolog/Handler/HandlerInterface.php');
require_once realpath(__DIR__. '/../monolog/src/Monolog/Handler/AbstractHandler.php');
require_once realpath(__DIR__. '/../monolog/src/Monolog/Handler/AbstractProcessingHandler.php');
require_once realpath(__DIR__. '/../monolog/src/Monolog/Handler/StreamHandler.php');
require_once realpath(__DIR__. '/../monolog/src/Monolog/Formatter/FormatterInterface.php');
require_once realpath(__DIR__. '/../monolog/src/Monolog/Formatter/NormalizerFormatter.php');
require_once realpath(__DIR__. '/../monolog/src/Monolog/Formatter/LineFormatter.php');
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
/**
* Main interface to use the CarmaLink API.
*
* @class CarmaLinkAPI
*/
class CarmaLinkAPI {
/**
* @access public
* @var int
* The current API level used in construction of CarmaLinkAPI URIs
*/
const API_LEVEL = 1;
/**
* @access public
* @var string
* The current API version
*/
const API_VERSION = "1.8.1";
const API_NAME = "CarmaLinkAPI";
/**
* @access public
* @var string
* This is the *default* path to the log file where API requests/responses will be logged if DEBUG is set to TRUE
* To specify an alternative path include it in the constructor.
* @see CarmaLinkAPI::__construct
*/
const API_LOG_FILE_DIR = "/var/log/httpd";
/**
* @access public
* @var int
* This is the maximum value of the per-request record "limit" API query parameter
*/
const API_RECORD_LIMIT = 50;
const API_METHOD_GET = 'GET';
const API_METHOD_PUT = 'PUT';
const API_METHOD_DELETE = 'DELETE';
const RESPONSE_CODE = 'response_code';
const RESPONSE_BODY = 'response_body';
const API_METHOD_PUT_SUCCESS = 204;
const API_METHOD_SUCCESS = 200;
/**
* @access private
* @var array Optional cURL options. Can be set depending on need.
*/
private static $CURL_OPTS = array(
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_SSL_VERIFYHOST => 0
);
/**
* @access public
* @var bool Whether to use additional cURL options when sending API requests
* @see CarmaLinkAPI::$CURL_OPTIONS
*/
public $use_curl_options = false;
/**
* @access public
* @var string Hostname of API URI
*/
public $host;
/**
* @access public
* @var int Port to use.
*/
public $port = 80;
/**
* @access public
* @var bool Whether to use SSL, should be true for production.
*/
public $isHttps = false;
/**
* @access public
* @var bool Whether to use debug, should be false for production.
*/
public $isDebugMode = false;
/**
* @access private
* @var _logger Monolog\Logger
*/
private static $_logger = NULL;
/**
* getLogger gets the static Monolog logging handler if debug is set to true
* @access protected
* @return Monolog\Logger
*/
protected static function getLogger() {
if (!self::$_logger) { self::setLogger(); }
return self::$_logger;
}
protected static function setLogger($path = NULL) {
$logfilePath = ($path === NULL) ? self::API_LOG_FILE_DIR."/".self::API_NAME.".log" : $path;
// Attempt to open the file or create if it doesn't exist.
$handle = fopen($logfilePath,"a+");
if (!$handle || !fclose($handle)) { throw new CarmaLinkAPIException("Could not create or open log file at path - ".$logfilePath); }
self::$_logger = new Logger(self::API_NAME);
self::$_logger->pushHandler(new StreamHandler($logfilePath,Logger::DEBUG));
}
/**
* Constructor
*
* Creates a new instance of an CarmaLinkAPI based on OAuth keys and server address.
* Additionally you can specify if you would like debugging enabled.
*
* @param string consumer_key Valid API key provided by CarmaSys
* @param string consumer_secret Valid API secret provided by CarmaSys
* @param array server_options Array of 'HOST','PORT', and 'HTTPS' which the API will use
* @param bool is_debug_mode Enable debugging
* @return void
*/
public function __construct($consumer_key = null, $consumer_secret = null, $server_options = array(), $is_debug_mode = false, $log_path = NULL) {
if (!$consumer_key || !$consumer_secret || strlen($consumer_key) === 0 || strlen($consumer_secret) === 0) {
throw new CarmaLinkAPIException(CarmaLinkAPIException::INVALID_API_KEYS_PROVIDED);
}
$this->host = isset($server_options['HOST']) ? $server_options['HOST'] : null;
$this->port = isset($server_options['PORT']) ? $server_options['PORT'] : null;
$this->isHttps = isset($server_options['HTTPS']) ? (bool)$server_options['HTTPS'] : false;
$this->isDebugMode = $is_debug_mode;
if ($this->isDebugMode) { self::setLogger($log_path); }
\OAuthStore::instance("2Leg", array('consumer_key' => $consumer_key, 'consumer_secret' => $consumer_secret));
}
/**
* Gets the relative path to the root endpoint of the API
* @return string
*/
public static function getEndpointRelativeRoot() { return 'v' . self::API_LEVEL; }
/**
* Gets the root URI for and API endpoint
* @return string
*/
public function getEndpointRootURI() { return 'http' . ($this->isHttps ? 's' : '') . '://' . $this->host . ':' . $this->port; }
/**
* If parameter is an array it will join it using "."
* @example sanitizeSerials(array("204",209,300)) // "204.209.300"
* @todo Verify serial string is valid
* @param int|string|array serials Serial numbers to parse
* @return string
*/
private function sanitizeSerials($serials) { return (is_array($serials)) ? implode(".", $serials) : $serials; }
/**
* Shortcut to getReportData w/ TRUE for the returnAllData param
* @param string|int|array serials Serial number(s) of CarmaLink
* @param string report_type Report/view type to query
* @param array parameters Key=>value parameters for data filtering to be added to the query string
* @return array Assoc. array of HTTP response code and HTTP body content
*/
public function getReportDataArray($serials, $report_type, $parameters) { return $this->getReportData($serials, $report_type, $parameters, TRUE); }
/**
* Gets a CarmaLink data view/report based on provided parameters.
*
* @param string|int|array serials Serial number(s) of CarmaLink
* @param string report_type Report/view type to query
* @param array parameters Key=>value parameters for data filtering to be added to the query string
* @param bool returnAllData If set to true will return assoc. array of HTTP code and HTTP body
* @return bool|string|array If returnAllData param is true will return assoc. array of HTTP code and HTTP body
* otherwise, will return false on error and a JSON string on success
* @throws CarmaLink\CarmaLinkAPIException
*/
public function getReportData($serials = 0, $report_type, $parameters = array(), $returnAllData = FALSE) {
if ($serials === 0 || empty($serials)) { throw new CarmaLinkAPIException("Missing valid serial number for querying API for report data (given:".$serials.")"); }
if(!ConfigType::isValidReportConfigType($report_type)) { throw new CarmaLinkAPIException('API getReportData can only operate on valid report configs.'); }
$serials = $this->sanitizeSerials($serials);
$uri = $this->getEndpointRootURI()."/".$this->getEndpointRelativeRoot()."/".$serials."/data/".$report_type;
$response_data = $this->get($uri, $parameters);
if ($returnAllData === TRUE) { return $response_data; }
if ((int)$response_data[self::RESPONSE_CODE] !== self::API_METHOD_SUCCESS) { return FALSE; }
return $response_data[self::RESPONSE_BODY];
}
/**
* Sets up parameters for a configuration update call
*
* @param string|int|array serials Serial number(s) of the CarmaLink(s)
* @param string endpoint Empty endpoint reference for the API call
* @param string config_type Valid configuration type
* @return void
*/
protected function setupConfigCall(&$serials, &$endpoint, $config_type) {
$config_resource = "";
if (ConfigType::isValidReportConfigType($config_type) ) { $config_resource = "report_config"; }
else if(ConfigType::isValidGeneralConfigType($config_type)) { $config_resource = "config"; }
else { throw new CarmaLinkAPIException("API does not support config type ".$config_type); }
$serials = $this->sanitizeSerials($serials);
$endpoint = $this->getEndpointRootURI()."/".$this->getEndpointRelativeRoot()."/".$serials."/".$config_resource."/".$config_type;
}
/**
* Get all configurations given a serial
*
* @todo this only works for one serial, make it work w/ array of serials
*
* @param string|int serial Serial number of the CarmaLink
* @return array Associative array of configurations
*/
public function getAllConfigs($serial = 0) {
if ($serial === 0) { return false; }
$configs = array();
foreach (ConfigType::$valid_report_config_types as $config_type) {
$new_config = ReportConfig::Factory($this->getConfig($serial, $config_type), $config_type);
$configs[] = array($config_type => $new_config);
}
//one resource for general config.
$configs[] = array("general_config" => GeneralConfig::Factory($this->getConfig($serial, ConfigType::CONFIG_GENERAL)));
return $configs;
}
/**
* Retrieves a configuration object from the CarmaLink based on parameters
*
* @param string|int|array serials Serial number(s) of the CarmaLink(s)
* @param string config_type Valid configuration type
* @param int configId If querying a specific config
* @return bool|string On success returns JSON-formatted object, on failure false
*/
public function getConfig($serials = 0, $config_type, $configId = 0) {
if ($serials === 0 || empty($serials)) { return false; }
$endpoint = "";
$params = ($configId === 0) ? NULL : array("id" => $configId);
$this->setupConfigCall($serials, $endpoint, $config_type);
$response_data = $this->get($endpoint, $params);
if ((int)$response_data[self::RESPONSE_CODE] !== self::API_METHOD_SUCCESS) { return false; }
return $response_data[self::RESPONSE_BODY];
}
/**
* Takes a response array from a putConfig or deleteConfig request
* and returns the proper type / value. Mostly a utility DRY method.
*
* @param array response_data Associative array of response code and body
* @return bool|string for single queries will return true/false, for multiple queries will return JSON string
*/
private function getProperResponse($response_data = NULL) {
if ($response_data === NULL) { return false; }
switch ((int)$response_data[self::RESPONSE_CODE]) {
// For single queries
case self::API_METHOD_PUT_SUCCESS: return true;
// For multiple queries a JSON object is always returned with embedded data
case self::API_METHOD_SUCCESS :
$body = $response_data[self::RESPONSE_BODY];
return (strlen($body) > 0) ? $response_data[self::RESPONSE_BODY] : true;
// Otherwise there was an error
default: return false;
}
}
/**
* Put / send a CarmaLink a new configuration
*
* @param string|int|array serials Serial number(s) of the CarmaLink(s)
* @param array|Config config Config object or Array representation
* @param string config_type Valid configuration type
* @return bool
*/
public function putConfig($serials = 0, $config, $config_type) {
if ($serials === 0 || empty($serials)) { return false; }
$endpoint = "";
$this->setupConfigCall($serials, $endpoint, $config_type);
if(ConfigType::isValidGeneralConfigType($config_type)) {
if(ConfigType::isValidWritableGeneralConfigType($config_type)) {
$config = ($config instanceof GeneralConfig) ? $config->getPartialArrayFromGeneralConfigType($config_type) : $config;
if(empty($config) || $config === null) {
//these changes will do nothing. therefore, no reason to send.
return true;
}
} else if ($config_type === ConfigType::CONFIG_GENERAL) { //special breakup check for the all config, just to make things easier for everyone.
//create array of all 3 general configs contaied in GET ALL.
$responseArray = array(
ConfigType::CONFIG_GENERAL_ENGINE => $this->putConfig($serials, $config, ConfigType::CONFIG_GENERAL_ENGINE),
ConfigType::CONFIG_GENERAL_CONNECTIVITY => $this->putConfig($serials, $config, ConfigType::CONFIG_GENERAL_CONNECTIVITY),
ConfigType::CONFIG_GENERAL_OPERATION => $this->putConfig($serials, $config, ConfigType::CONFIG_GENERAL_OPERATION),
);
return $responseArray;
}
else {
throw new CarmaLinkAPIException("API putConfig config parameter of '$config_type' was not a valid writable config type");
}
} else if(ConfigType::isValidWritableReportConfigType($config_type)) {
$config = ($config instanceof ReportConfig) ? $config->toArray() : $config;
} else {
throw new CarmaLinkAPIException("API putConfig config parameter of '$config_type' was not a valid writable config type.");
}
// If config is instance of CarmaLink\Config then convert to associative array, otherwise use given argument assuming array.
if (!is_array($config) && empty($config) || !$config_type) {
throw new CarmaLinkAPIException('API putConfig config parameter was not of type array or not a valid configuration type.');
}
return $this->getProperResponse($this->put($endpoint, $config));
}
/**
* Delete a configuration from a CarmaLink
* @param string|int|array serials Serial number of the CarmaLink
* @param string config_type Valid configuration type
* @return bool
*/
public function deleteConfig($serials = 0, $config_type) {
if ($serials === 0 || empty($serials)) { return false; }
if (!ConfigType::isValidWritableReportConfigType($config_type)) { throw new CarmaLinkAPIException('API deleteConfig config parameter must be a valid report config only'); }
$endpoint = "";
$this->setupConfigCall($serials, $endpoint, $config_type);
$response_data = $this->delete($endpoint);
switch ((int)$response_data[self::RESPONSE_CODE]) {
// For single queries
case self::API_METHOD_PUT_SUCCESS: return true;
// For multiple queries a JSON object is always returned with embedded data
case self::API_METHOD_SUCCESS: return $response_data[self::RESPONSE_BODY];
// Otherwise there was an error
default: return false;
}
}
/**
* Performs GET request to API
* @param string endpoint
* @param array parameters Any query string parameters to send
* @return array
*/
public function get($endpoint, $parameters = NULL) {
return $this->api($endpoint, self::API_METHOD_GET, $parameters);
}
/**
* Performs PUT request to API
* @param string endpoint
* @param array parameters Associative array of options to send
* @return array
*/
public function put($endpoint, $parameters = NULL) {
return $this->api($endpoint, self::API_METHOD_PUT, $parameters);
}
/**
* Performs DELETE request to API
* @param string endpoint
* @return array
*/
public function delete($endpoint) {
return $this->api($endpoint, self::API_METHOD_DELETE);
}
/**
* All API requests filter through this method.
* @param string endpoint
* @param string method default is 'GET'
* @param string[] parameters Key=>values to send
* @param string[] options Array for future consideration
* @return (int|string)[]
*/
private function api($endpoint, $method = self::API_METHOD_GET, $parameters = NULL, $options = array()) {
$put_data = NULL;
$curl_options = $this->use_curl_options ? self::$CURL_OPTS : array();
if ($method === self::API_METHOD_PUT) {
$put_data = json_encode($parameters);
// if no data was being put.
if ($put_data == NULL) { return array(self::RESPONSE_CODE => 202, self::RESPONSE_BODY => "Nothing to put, no request sent"); }
$curl_options[CURLOPT_HTTPHEADER] = array('Content-Type: application/json');
$parameters = NULL;
}
if ($this->isDebugMode) {
if (is_array($parameters)) { $debugParams = $parameters; }
else if ($parameters === NULL && strlen($put_data)) { $debugParams = json_decode($put_data,TRUE); }
else { $debugParams = array(); }
self::getLogger()->addDebug("Request - ".$method." ".$endpoint." ",$debugParams);
unset($debugParams);
}
$oauth_request = new \OAuthRequester($endpoint, $method, $parameters, $put_data);
$response = $oauth_request->doRequest(0, $curl_options);
if ($this->isDebugMode) { self::getLogger()->addDebug("Response - ".$response['code']." body: ".$response['body']); }
return array(self::RESPONSE_CODE => $response['code'], self::RESPONSE_BODY => $response['body']);
}
} // End of class CarmaLinkAPI
?>
<file_sep>/PHP/docs/report_parse_markers.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>CarmaLinkSDK PHP</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="css/template.css" type="text/css" />
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="js/jquery.tools.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.2.custom.min.js"></script>
<script type="text/javascript" src="js/template.js"></script>
</head>
<body>
<div id="content">
<h1>Compilation Errors</h1>
<div id="marker-accordion">
<h3>
<a href="#lib/GeneralConfig.php">lib/GeneralConfig.php<small>18</small></a>
</h3>
<div>
<table>
<tr>
<th>Type</th>
<th>Line</th>
<th>Description</th>
</tr>
<tr>
<td>error</td>
<td>0</td>
<td>No summary was found for this file</td>
</tr>
<tr>
<td>error</td>
<td>232</td>
<td>Argument $device is missing from the Docblock of createConfigFromDevice</td>
</tr>
<tr>
<td>error</td>
<td>232</td>
<td>No summary for method createConfigFromDevice()</td>
</tr>
<tr>
<td>error</td>
<td>15</td>
<td>No summary for property $fuelType</td>
</tr>
<tr>
<td>error</td>
<td>21</td>
<td>No summary for property $engineDisplacement_L</td>
</tr>
<tr>
<td>error</td>
<td>27</td>
<td>No summary for property $isPaused</td>
</tr>
<tr>
<td>error</td>
<td>33</td>
<td>No summary for property $connectInterval_Mins</td>
</tr>
<tr>
<td>error</td>
<td>39</td>
<td>No summary for property $agpsConnectInterval_Hrs</td>
</tr>
<tr>
<td>error</td>
<td>44</td>
<td>No summary for property $pingInteval_Mins</td>
</tr>
<tr>
<td>error</td>
<td>49</td>
<td>No summary for property $chargingVoltage_V</td>
</tr>
<tr>
<td>error</td>
<td>54</td>
<td>No summary for property $lowBatteryVoltage_V</td>
</tr>
<tr>
<td>error</td>
<td>59</td>
<td>No summary for property $lowBatteryMinutes</td>
</tr>
<tr>
<td>error</td>
<td>64</td>
<td>No summary for property $minimumRunVoltageEnergy</td>
</tr>
<tr>
<td>error</td>
<td>69</td>
<td>No summary for property $maximumOffVoltageEnergy</td>
</tr>
<tr>
<td>error</td>
<td>74</td>
<td>No summary for property $obdDetection</td>
</tr>
<tr>
<td>error</td>
<td>79</td>
<td>No summary for property $ledMode</td>
</tr>
<tr>
<td>error</td>
<td>84</td>
<td>No summary for property $maximumUptimeHours</td>
</tr>
<tr>
<td>error</td>
<td>90</td>
<td>No summary for property $__api_version</td>
</tr>
</table>
</div>
<h3>
<a href="#lib/CarmaLinkAPI.php">lib/CarmaLinkAPI.php<small>4</small></a>
</h3>
<div>
<table>
<tr>
<th>Type</th>
<th>Line</th>
<th>Description</th>
</tr>
<tr>
<td>error</td>
<td>0</td>
<td>No summary was found for this file</td>
</tr>
<tr>
<td>error</td>
<td>126</td>
<td>Argument $path is missing from the Docblock of setLogger</td>
</tr>
<tr>
<td>error</td>
<td>126</td>
<td>No summary for method setLogger()</td>
</tr>
<tr>
<td>error</td>
<td>150</td>
<td>Argument $log_path is missing from the Docblock of __construct</td>
</tr>
</table>
</div>
<h3>
<a href="#lib/ConfigType.php">lib/ConfigType.php<small>1</small></a>
</h3>
<div>
<table>
<tr>
<th>Type</th>
<th>Line</th>
<th>Description</th>
</tr>
<tr>
<td>error</td>
<td>0</td>
<td>No summary was found for this file</td>
</tr>
</table>
</div>
<h3>
<a href="#lib/ReportConfig.php">lib/ReportConfig.php<small>12</small></a>
</h3>
<div>
<table>
<tr>
<th>Type</th>
<th>Line</th>
<th>Description</th>
</tr>
<tr>
<td>error</td>
<td>0</td>
<td>No summary was found for this file</td>
</tr>
<tr>
<td>error</td>
<td>103</td>
<td>Argument $config_type is missing from the Docblock of __construct</td>
</tr>
<tr>
<td>error</td>
<td>35</td>
<td>No summary for property $id</td>
</tr>
<tr>
<td>error</td>
<td>41</td>
<td>No summary for property $threshold</td>
</tr>
<tr>
<td>error</td>
<td>47</td>
<td>No summary for property $allowance</td>
</tr>
<tr>
<td>error</td>
<td>53</td>
<td>No summary for property $location</td>
</tr>
<tr>
<td>error</td>
<td>59</td>
<td>No summary for property $buzzer</td>
</tr>
<tr>
<td>error</td>
<td>65</td>
<td>No summary for property $params</td>
</tr>
<tr>
<td>error</td>
<td>71</td>
<td>No summary for property $conditions</td>
</tr>
<tr>
<td>error</td>
<td>77</td>
<td>No summary for property $state</td>
</tr>
<tr>
<td>error</td>
<td>83</td>
<td>No summary for property $_config_type</td>
</tr>
<tr>
<td>error</td>
<td>89</td>
<td>No summary for property $__api_version</td>
</tr>
</table>
</div>
</div>
</div>
</body>
</html>
<file_sep>/PHP/lib/CarmaLink.php
<?php
/**
* CarmaLink Device Class
*
*
*/
namespace CarmaLink;
/**
* "Abstract" class representing minimum properties of a CarmaLink
*
* This class represents a possible starting point for an abstraction
* of a CarmaLink. The getters/setters below are required for some of
* the functionality in this SDK.
*
* @class CarmaLink
*/
abstract class CarmaLink {
/**
* Set CarmaLink serial number
* @param int serialNumber of CarmaLink
* @return void
*/
public function setSerialNumber($serialNumber) { if ($this->serialNumber !== $serialNumber) { $this->serialNumber = (int)$serialNumber; } }
/**
* CarmaLink's serial
* @return int
*/
public function getSerialNumber() { return $this->serialNumber; }
/**
* Set CarmaLink location tracking / GPS functionality
* @param bool useGps On/Off
* @return void
*/
public function setUseGps($useGps) { $this->useGps = (bool)$useGps; }
/**
* Get CarmaLink location functionality
* @return bool
*/
public function getUseGps() { return $this->useGps; }
//functions that are being called to perform all of the above functions.
/*
* Sets threshold of values passed in based on configuration type.
* @param ConfigType configType valid config type to change
* @param int|float value value to set threshold too.
*/
public function setThreshold($configType, $value = 0.0) {
if(!is_numeric($value)) { throw new CarmaLinkAPIException("Error: setThreshold for ".$configType." expected value to be numeric, ".$value." received"); }
switch($configType) {
case ConfigType::CONFIG_OVERSPEEDING:
$this->speedLimit_kmph = (float)$value;
break;
case ConfigType::CONFIG_IDLING:
$this->idleTimeLimit_kmph = (float)$value;
break;
case ConfigType::CONFIG_HARD_ACCEL:
$this->accelLimit_Mpss = (float)$value;
break;
case ConfigType::CONFIG_HARD_BRAKING:
$this->brakeLimit_Mpss = (float)$value;
break;
case ConfigType::CONFIG_HARD_CORNERING:
$this->corneringLimit_Mpss = (float)$value;
break;
case ConfigType::CONFIG_ENGINE_OVERSPEED:
$this->engineSpeedLimit_rpm = (int)$value;
break;
case ConfigType::CONFIG_PARKING_BRAKE:
$this->parkingBrakeLimit_kmph = (float)$value;
break;
case ConfigType::CONFIG_SEATBELT:
$this->seatbeltLimit_kmph = (float)$value;
break;
case ConfigType::CONFIG_PARKING:
$this->parkingTimeoutThreshold_Msec = (int)$value;
break;
case ConfigType::CONFIG_TRANSPORTED:
$this->transportedPingTime_Msec = (int)$value;
break;
case ConfigType::CONFIG_STATUS:
$this->statusPingTime_Msec = (int)$value;
break;
case ConfigType::CONFIG_HEALTH:
case ConfigType::CONFIG_TRIP_REPORT:
case ConfigType::CONFIG_DIGITAL_INPUT_0:
case ConfigType::CONFIG_DIGITAL_INPUT_1:
case ConfigType::CONFIG_DIGITAL_INPUT_2:
case ConfigType::CONFIG_DIGITAL_INPUT_3:
case ConfigType::CONFIG_DIGITAL_INPUT_4:
case ConfigType::CONFIG_DIGITAL_INPUT_5:
case ConfigType::CONFIG_DIGITAL_INPUT_6:
case ConfigType::CONFIG_DRIVER_LOG:
case ConfigType::CONFIG_GREEN_BAND:
throw new CarmaLinkAPIException("Error: setThreshold for '".$configType."' is illegal, as it does not support the threshold parameter.");
break;
default:
throw new CarmaLinkAPIException("Error: setThreshold for '".$configType."' has failed since '".$configType."' is not recognized as valid.");
}
}
/*
* Gets threshold for config type
* @return null|int|float null if not supported, otherwise expect a numeral
*/
public function getThreshold($configType) {
switch($configType) {
case ConfigType::CONFIG_OVERSPEEDING:
return $this->speedLimit_kmph;
case ConfigType::CONFIG_IDLING:
return $this->idleTimeLimit_kmph;
case ConfigType::CONFIG_HARD_ACCEL:
return $this->accelLimit_Mpss;
case ConfigType::CONFIG_HARD_BRAKING:
return $this->brakeLimit_Mpss;
case ConfigType::CONFIG_HARD_CORNERING:
return $this->corneringLimit_Mpss;
case ConfigType::CONFIG_ENGINE_OVERSPEED:
return $this->engineSpeedLimit_rpm;
case ConfigType::CONFIG_PARKING_BRAKE:
return $this->parkingBrakeLimit_kmph;
case ConfigType::CONFIG_SEATBELT:
return $this->seatbeltLimit_kmph;
case ConfigType::CONFIG_PARKING:
return $this->parkingTimeoutThreshold_Msec;
case ConfigType::CONFIG_TRANSPORTED:
return $this->transportedPingTime_Msec;
case ConfigType::CONFIG_STATUS:
return $this->statusPingTime_Msec;
case ConfigType::CONFIG_HEALTH:
case ConfigType::CONFIG_TRIP_REPORT:
case ConfigType::CONFIG_DIGITAL_INPUT_0:
case ConfigType::CONFIG_DIGITAL_INPUT_1:
case ConfigType::CONFIG_DIGITAL_INPUT_2:
case ConfigType::CONFIG_DIGITAL_INPUT_3:
case ConfigType::CONFIG_DIGITAL_INPUT_4:
case ConfigType::CONFIG_DIGITAL_INPUT_5:
case ConfigType::CONFIG_DIGITAL_INPUT_6:
case ConfigType::CONFIG_DRIVER_LOG:
case ConfigType::CONFIG_GREEN_BAND:
return NULL;
break;
default:
throw new CarmaLinkAPIException("Error: getThreshold for '".$configType."' has failed since '".$configType."' is not recognized as valid.");
}
}
/*
* Sets allowance of values passed in based on configuration type.
* @param ConfigType configType valid config type to change
* @param int value value to set allowance too.
*/
public function setAllowance($configType, $value = 0) {
if(!is_integer($value)) { throw new CarmaLinkAPIException("Error: setAllowance for ".$configType." expected value to be integer, ".$value." received"); }
switch($configType) {
case ConfigType::CONFIG_OVERSPEEDING:
$this->speedLimitAllowance_Msec = (int)$value;
break;
case ConfigType::CONFIG_IDLING:
$this->idleTimeLimitAllowance_Msec = (int)$value;
break;
case ConfigType::CONFIG_HARD_ACCEL:
$this->accelLimitAllowance_Msec = (int)$value;
break;
case ConfigType::CONFIG_HARD_BRAKING:
$this->brakeLimitAllowance_Msec = (int)$value;
break;
case ConfigType::CONFIG_HARD_CORNERING:
$this->corneringLimitAllowance_Msec = (int)$value;
break;
case ConfigType::CONFIG_ENGINE_OVERSPEED:
$this->engineSpeedLimitAllowance_Msec = (int)$value;
break;
case ConfigType::CONFIG_PARKING_BRAKE:
$this->parkingBrakeLimitAllowance_Msec = (int)$value;
break;
case ConfigType::CONFIG_SEATBELT:
$this->seatbeltLimitAllowance_Msec = (int)$value;
break;
case ConfigType::CONFIG_PARKING:
$this->parkingTimeoutAllowance_Msec = (int)$value;
break;
case ConfigType::CONFIG_TRANSPORTED:
$this->transportedPingTimeAllowance_Msec = (int)$value;
break;
case ConfigType::CONFIG_STATUS:
$this->statusPingTimeAllowance_Msec = (int)$value;
break;
case ConfigType::CONFIG_HEALTH:
case ConfigType::CONFIG_TRIP_REPORT:
case ConfigType::CONFIG_DIGITAL_INPUT_0:
case ConfigType::CONFIG_DIGITAL_INPUT_1:
case ConfigType::CONFIG_DIGITAL_INPUT_2:
case ConfigType::CONFIG_DIGITAL_INPUT_3:
case ConfigType::CONFIG_DIGITAL_INPUT_4:
case ConfigType::CONFIG_DIGITAL_INPUT_5:
case ConfigType::CONFIG_DIGITAL_INPUT_6:
case ConfigType::CONFIG_DRIVER_LOG:
case ConfigType::CONFIG_GREEN_BAND:
throw new CarmaLinkAPIException("Error: setAllowance for '".$configType."' is illegal, as it does not support the allowance parameter.");
break;
default:
throw new CarmaLinkAPIException("Error: setAllowance for '".$configType."' has failed since '".$configType."' is not recognized as valid.");
}
}
/*
* Gets allowance for config type
* @return null|int null if not supported, otherwise expect an int
*/
public function getAllowance($configType) {
switch($configType) {
case ConfigType::CONFIG_OVERSPEEDING:
return $this->speedLimitAllowance_Msec;
case ConfigType::CONFIG_IDLING:
return $this->idleTimeLimitAllowance_Msec;
case ConfigType::CONFIG_HARD_ACCEL:
return $this->accelLimitAllowance_Msec;
case ConfigType::CONFIG_HARD_BRAKING:
return $this->brakeLimitAllowance_Msec;
case ConfigType::CONFIG_HARD_CORNERING:
return $this->corneringLimitAllowance_Msec;
case ConfigType::CONFIG_ENGINE_OVERSPEED:
return $this->engineSpeedLimitAllowance_Msec;
case ConfigType::CONFIG_PARKING_BRAKE:
return $this->parkingBrakeLimitAllowance_Msec;
case ConfigType::CONFIG_SEATBELT:
return $this->seatbeltLimitAllowance_Msec;
case ConfigType::CONFIG_PARKING:
return $this->parkingTimeoutAllowance_Msec;
case ConfigType::CONFIG_TRANSPORTED:
return $this->transportedPingTimeAllowance_Msec;
case ConfigType::CONFIG_STATUS:
return $this->statusPingTimeAllowance_Msec;
case ConfigType::CONFIG_HEALTH:
case ConfigType::CONFIG_TRIP_REPORT:
case ConfigType::CONFIG_DIGITAL_INPUT_0:
case ConfigType::CONFIG_DIGITAL_INPUT_1:
case ConfigType::CONFIG_DIGITAL_INPUT_2:
case ConfigType::CONFIG_DIGITAL_INPUT_3:
case ConfigType::CONFIG_DIGITAL_INPUT_4:
case ConfigType::CONFIG_DIGITAL_INPUT_5:
case ConfigType::CONFIG_DIGITAL_INPUT_6:
case ConfigType::CONFIG_DRIVER_LOG:
case ConfigType::CONFIG_GREEN_BAND:
return NULL;
default:
throw new CarmaLinkAPIException("Error: getAllowance for '".$configType."' has failed since '".$configType."' is not recognized as valid.");
}
}
/*
* Sets buzzer volume for use by report events, is called by other functions.
* @param ConfigType configType valid config type to change
* @param BuzzerVolume value valid buzzer volume to set.
*/
public function setBuzzerVolume($configType, $value) {
switch($value) {
case BuzzerVolume::HIGH:
case BuzzerVolume::MED:
case BuzzerVolume::OFF:
break;
default:
throw new CarmaLinkAPIException("Error: setBuzzer for ".$configType." expected value to be of type 'BuzzerVolume' - ".$value." received");
}
switch($configType) {
case ConfigType::CONFIG_OVERSPEEDING:
$this->speedLimitBuzzer_Volume = $value;
break;
case ConfigType::CONFIG_IDLING:
$this->idleTimeLimitBuzzer_Volume = $value;
break;
case ConfigType::CONFIG_HARD_ACCEL:
$this->accelLimitBuzzer_Volume = $value;
break;
case ConfigType::CONFIG_HARD_BRAKING:
$this->brakeLimitBuzzer_Volume = $value;
break;
case ConfigType::CONFIG_HARD_CORNERING:
$this->corneringLimitBuzzer_Volume = $value;
break;
case ConfigType::CONFIG_ENGINE_OVERSPEED:
$this->engineSpeedLimitBuzzer_Volume = $value;
break;
case ConfigType::CONFIG_PARKING_BRAKE:
$this->parkingBrakeLimitBuzzer_Volume = $value;
break;
case ConfigType::CONFIG_SEATBELT:
$this->seatbeltLimitBuzzer_Volume = $value;
break;
case ConfigType::CONFIG_PARKING:
case ConfigType::CONFIG_TRANSPORTED:
case ConfigType::CONFIG_STATUS:
case ConfigType::CONFIG_HEALTH:
case ConfigType::CONFIG_TRIP_REPORT:
case ConfigType::CONFIG_DIGITAL_INPUT_0:
case ConfigType::CONFIG_DIGITAL_INPUT_1:
case ConfigType::CONFIG_DIGITAL_INPUT_2:
case ConfigType::CONFIG_DIGITAL_INPUT_3:
case ConfigType::CONFIG_DIGITAL_INPUT_4:
case ConfigType::CONFIG_DIGITAL_INPUT_5:
case ConfigType::CONFIG_DIGITAL_INPUT_6:
case ConfigType::CONFIG_DRIVER_LOG:
case ConfigType::CONFIG_GREEN_BAND:
throw new CarmaLinkAPIException("Error: setBuzzerVolume for '".$configType."' ' is illegal, as it does not support the buzzer parameter");
break;
default:
throw new CarmaLinkAPIException("Error: setBuzzer for '".$configType."' has failed since '".$configType."' is not recognized as valid.");
}
}
/*
* Gets buzzer volume for config type if supported, null if not set or unsupported
* @param ConfigType configType valid config type
* @return BuzzerVolume|null returns buzzer volume if set, otherwise null.
*/
public function getBuzzerVolume($configType) {
switch($configType) {
case ConfigType::CONFIG_OVERSPEEDING:
return $this->speedLimitBuzzer_Volume;
case ConfigType::CONFIG_IDLING:
return $this->idleTimeLimitBuzzer_Volume;
case ConfigType::CONFIG_HARD_ACCEL:
return $this->accelLimitBuzzer_Volume;
case ConfigType::CONFIG_HARD_BRAKING:
return $this->brakeLimitBuzzer_Volume;
case ConfigType::CONFIG_HARD_CORNERING:
return $this->corneringLimitBuzzer_Volume;
case ConfigType::CONFIG_ENGINE_OVERSPEED:
return $this->engineSpeedLimitBuzzer_Volume;
case ConfigType::CONFIG_PARKING_BRAKE:
return $this->parkingBrakeLimitBuzzer_Volume;
case ConfigType::CONFIG_SEATBELT:
return $this->seatbeltLimitBuzzer_Volume;
case ConfigType::CONFIG_PARKING:
case ConfigType::CONFIG_TRANSPORTED:
case ConfigType::CONFIG_STATUS:
case ConfigType::CONFIG_HEALTH:
case ConfigType::CONFIG_TRIP_REPORT:
case ConfigType::CONFIG_DIGITAL_INPUT_0:
case ConfigType::CONFIG_DIGITAL_INPUT_1:
case ConfigType::CONFIG_DIGITAL_INPUT_2:
case ConfigType::CONFIG_DIGITAL_INPUT_3:
case ConfigType::CONFIG_DIGITAL_INPUT_4:
case ConfigType::CONFIG_DIGITAL_INPUT_5:
case ConfigType::CONFIG_DIGITAL_INPUT_6:
case ConfigType::CONFIG_DRIVER_LOG:
case ConfigType::CONFIG_GREEN_BAND:
return NULL;
break;
default:
throw new CarmaLinkAPIException("Error: setBuzzer for '".$configType."' has failed since '".$configType."' is not recognized as valid.");
}
}
/*
* Sets optional parameters for use by report events
* @param ConfigType configType valid config type to change
* @param array valueArray array object of all optional parameters.
*/
public function setOptionalParameters($configType, $valueArray) {
if(!is_array($valueArray)) { throw new CarmaLinkAPIException("Error: setOptionalParameters for '".$configType."' must be of type array."); }
$properFormattedArray;
if(isset($valueArray[0]) && is_string($valueArray[0]) && !is_bool($valueArray[0])) {
$properFormattedArray = array();
foreach($valueArray as $value) {
$properFormattedArray[$value] = true;
}
//convert to proper array.
} else{
$properFormattedArray = $valueArray;
}
switch($configType) {
case ConfigType::CONFIG_OVERSPEEDING:
$this->speedLimitOptionalParameters = $properFormattedArray;
break;
case ConfigType::CONFIG_IDLING:
$this->idleTimeLimitOptionalParameters = $properFormattedArray;
break;
case ConfigType::CONFIG_HARD_ACCEL:
$this->accelLimitOptionalParameters = $properFormattedArray;
break;
case ConfigType::CONFIG_HARD_BRAKING:
$this->brakeLimitOptionalParameters = $properFormattedArray;
break;
case ConfigType::CONFIG_HARD_CORNERING:
$this->corneringLimitOptionalParameters = $properFormattedArray;
break;
case ConfigType::CONFIG_ENGINE_OVERSPEED:
$this->engineSpeedLimitOptionalParameters = $properFormattedArray;
break;
case ConfigType::CONFIG_PARKING_BRAKE:
$this->parkingBrakeLimitOptionalParameters = $properFormattedArray;
break;
case ConfigType::CONFIG_SEATBELT:
$this->seatbeltLimitOptionalParameters = $properFormattedArray;
break;
case ConfigType::CONFIG_PARKING:
$this->parkingTimeoutOptionalParameters = $properFormattedArray;
break;
case ConfigType::CONFIG_TRANSPORTED:
$this->transportedPingTimeOptionalParameters = $properFormattedArray;
break;
case ConfigType::CONFIG_STATUS:
$this->statusPingTimeOptionalParameters = $properFormattedArray;
break;
case ConfigType::CONFIG_HEALTH:
$this->healthOptionalParameters = $properFormattedArray;
break;
case ConfigType::CONFIG_TRIP_REPORT:
$this->tripOptionalParameters = $properFormattedArray;
break;
case ConfigType::CONFIG_DIGITAL_INPUT_0:
case ConfigType::CONFIG_DIGITAL_INPUT_1:
case ConfigType::CONFIG_DIGITAL_INPUT_2:
case ConfigType::CONFIG_DIGITAL_INPUT_3:
case ConfigType::CONFIG_DIGITAL_INPUT_4:
case ConfigType::CONFIG_DIGITAL_INPUT_5:
case ConfigType::CONFIG_DIGITAL_INPUT_6:
case ConfigType::CONFIG_DRIVER_LOG:
case ConfigType::CONFIG_GREEN_BAND:
throw new CarmaLinkAPIException("Error: setOptionalParameters for '".$configType."' ' is illegal, as it does not support optional parameters");
break;
default:
throw new CarmaLinkAPIException("Error: setOptionalParameters for '".$configType."' has failed since '".$configType."' is not recognized as valid.");
}
}
/*
* Gets optional parameters used by report events
* @param ConfigType configType valid config type to get optoinal parameters are
* @return array|null valueArray array object of all optional parameters.
*/
public function getOptionalParameters($configType) {
switch($configType) {
case ConfigType::CONFIG_OVERSPEEDING:
return $this->speedLimitOptionalParameters;
case ConfigType::CONFIG_IDLING:
return $this->idleTimeLimitOptionalParameters;
case ConfigType::CONFIG_HARD_ACCEL:
return $this->accelLimitOptionalParameters;
case ConfigType::CONFIG_HARD_BRAKING:
return $this->brakeLimitOptionalParameters;
case ConfigType::CONFIG_HARD_CORNERING:
return $this->corneringLimitOptionalParameters;
case ConfigType::CONFIG_ENGINE_OVERSPEED:
return $this->engineSpeedLimitOptionalParameters;
case ConfigType::CONFIG_PARKING_BRAKE:
return $this->parkingBrakeLimitOptionalParameters;
case ConfigType::CONFIG_SEATBELT:
return $this->seatbeltLimitOptionalParameters;
case ConfigType::CONFIG_PARKING:
return $this->parkingTimeoutOptionalParameters;
case ConfigType::CONFIG_TRANSPORTED:
return $this->transportedPingTimeOptionalParameters;
case ConfigType::CONFIG_STATUS:
return $this->statusPingTimeOptionalParameters;
case ConfigType::CONFIG_HEALTH:
return $this->healthOptionalParameters;
case ConfigType::CONFIG_TRIP_REPORT:
return $this->tripOptionalParameters;
case ConfigType::CONFIG_DIGITAL_INPUT_0:
case ConfigType::CONFIG_DIGITAL_INPUT_1:
case ConfigType::CONFIG_DIGITAL_INPUT_2:
case ConfigType::CONFIG_DIGITAL_INPUT_3:
case ConfigType::CONFIG_DIGITAL_INPUT_4:
case ConfigType::CONFIG_DIGITAL_INPUT_5:
case ConfigType::CONFIG_DIGITAL_INPUT_6:
case ConfigType::CONFIG_DRIVER_LOG:
case ConfigType::CONFIG_GREEN_BAND:
return null;
default:
throw new CarmaLinkAPIException("Error: getOptionalParameters for '".$configType."' has failed since '".$configType."' is not recognized as valid.");
}
}
/*
* Sets optional conditions for use by report events
* @param ConfigType configType valid config type to change
* @param array valueArray array object of all optional conditions.
*/
public function setOptionalConditions($configType, $valueArray) {
if(!is_array($valueArray)) { throw new CarmaLinkAPIException("Error: setOptionalParameters for '".$configType."' must be of type array."); }
$properFormattedArray;
if(isset($valueArray[0]) && is_string($valueArray[0]) && !is_bool($valueArray[0])) {
$properFormattedArray = array();
foreach($valueArray as $value) {
$properFormattedArray[$value] = true;
}
//convert to proper array.
} else{
$properFormattedArray = $valueArray;
}
switch($configType) {
case ConfigType::CONFIG_OVERSPEEDING:
$this->speedLimitOptionalConditions = $properFormattedArray;
break;
case ConfigType::CONFIG_IDLING:
$this->idleTimeLimitOptionalConditions = $properFormattedArray;
break;
case ConfigType::CONFIG_HARD_ACCEL:
$this->accelLimitOptionalConditions = $properFormattedArray;
break;
case ConfigType::CONFIG_HARD_BRAKING:
$this->brakeLimitOptionalConditions = $properFormattedArray;
break;
case ConfigType::CONFIG_HARD_CORNERING:
$this->corneringLimitOptionalConditions = $properFormattedArray;
break;
case ConfigType::CONFIG_ENGINE_OVERSPEED:
$this->engineSpeedLimitOptionalConditions = $properFormattedArray;
break;
case ConfigType::CONFIG_PARKING_BRAKE:
$this->parkingBrakeLimitOptionalConditions = $properFormattedArray;
break;
case ConfigType::CONFIG_SEATBELT:
$this->seatbeltLimitOptionalConditions = $properFormattedArray;
break;
case ConfigType::CONFIG_PARKING:
$this->parkingTimeoutOptionalConditions = $properFormattedArray;
break;
case ConfigType::CONFIG_TRANSPORTED:
$this->transportedPingTimeOptionalConditions = $properFormattedArray;
break;
case ConfigType::CONFIG_STATUS:
$this->statusPingTimeOptionalConditions = $properFormattedArray;
break;
case ConfigType::CONFIG_HEALTH:
$this->healthOptionalConditions = $properFormattedArray;
break;
case ConfigType::CONFIG_TRIP_REPORT:
$this->tripOptionalConditions = $properFormattedArray;
break;
case ConfigType::CONFIG_DIGITAL_INPUT_0:
case ConfigType::CONFIG_DIGITAL_INPUT_1:
case ConfigType::CONFIG_DIGITAL_INPUT_2:
case ConfigType::CONFIG_DIGITAL_INPUT_3:
case ConfigType::CONFIG_DIGITAL_INPUT_4:
case ConfigType::CONFIG_DIGITAL_INPUT_5:
case ConfigType::CONFIG_DIGITAL_INPUT_6:
case ConfigType::CONFIG_DRIVER_LOG:
case ConfigType::CONFIG_GREEN_BAND:
throw new CarmaLinkAPIException("Error: setOptionalConditions for '".$configType."' ' is illegal, as it does not support optional conditions");
break;
default:
throw new CarmaLinkAPIException("Error: setOptionalConditions for '".$configType."' has failed since '".$configType."' is not recognized as valid.");
}
}
/*
* Gets optional conditions used by report events
* @param ConfigType configType valid config type to get optoinal conditoins are
* @return array|null valueArray array object of all optional conditions.
*/
public function getOptionalConditions($configType) {
switch($configType) {
case ConfigType::CONFIG_OVERSPEEDING:
return $this->speedLimitOptionalConditions;
case ConfigType::CONFIG_IDLING:
return $this->idleTimeLimitOptionalConditions;
case ConfigType::CONFIG_HARD_ACCEL:
return $this->accelLimitOptionalConditions;
case ConfigType::CONFIG_HARD_BRAKING:
return $this->brakeLimitOptionalConditions;
case ConfigType::CONFIG_HARD_CORNERING:
return $this->corneringLimitOptionalConditions;
case ConfigType::CONFIG_ENGINE_OVERSPEED:
return $this->engineSpeedLimitOptionalConditions;
case ConfigType::CONFIG_PARKING_BRAKE:
return $this->parkingBrakeLimitOptionalConditions;
case ConfigType::CONFIG_SEATBELT:
return $this->seatbeltLimitOptionalConditions;
case ConfigType::CONFIG_PARKING:
return $this->parkingTimeoutOptionalConditions;
case ConfigType::CONFIG_TRANSPORTED:
return $this->transportedPingTimeOptionalConditions;
case ConfigType::CONFIG_STATUS:
return $this->statusPingTimeOptionalConditions;
case ConfigType::CONFIG_HEALTH:
return $this->healthOptionalConditions;
case ConfigType::CONFIG_TRIP_REPORT:
return $this->tripOptionalConditions;
case ConfigType::CONFIG_DIGITAL_INPUT_0:
case ConfigType::CONFIG_DIGITAL_INPUT_1:
case ConfigType::CONFIG_DIGITAL_INPUT_2:
case ConfigType::CONFIG_DIGITAL_INPUT_3:
case ConfigType::CONFIG_DIGITAL_INPUT_4:
case ConfigType::CONFIG_DIGITAL_INPUT_5:
case ConfigType::CONFIG_DIGITAL_INPUT_6:
case ConfigType::CONFIG_DRIVER_LOG:
case ConfigType::CONFIG_GREEN_BAND:
return NULL;
default:
throw new CarmaLinkAPIException("Error: getOptionalConditions for '".$configType."' has failed since '".$configType."' is not recognized as valid.");
}
}
/*
* Sets if the report is enabled or disabled
* @param ConfigType configType valid config type to change
* @param bool value is report enabled or not?
*/
public function setReportEnabled($configType, $value = FALSE) {
$rVal = ($value === FALSE);
switch($configType) {
case ConfigType::CONFIG_OVERSPEEDING:
$this->speedLimitReportEnabled = $rVal;
break;
case ConfigType::CONFIG_IDLING:
$this->idleTimeLimitReportEnabled = $rVal;
break;
case ConfigType::CONFIG_HARD_ACCEL:
$this->accelLimitReportEnabled = $rVal;
break;
case ConfigType::CONFIG_HARD_BRAKING:
$this->brakeLimitReportEnabled = $rVal;
break;
case ConfigType::CONFIG_HARD_CORNERING:
$this->corneringLimitReportEnabled = $rVal;
break;
case ConfigType::CONFIG_ENGINE_OVERSPEED:
$this->engineSpeedLimitReportEnabled = $rVal;
break;
case ConfigType::CONFIG_PARKING_BRAKE:
$this->parkingBrakeLimitReportEnabled = $rVal;
break;
case ConfigType::CONFIG_SEATBELT:
$this->seatbeltLimitReportEnabled = $rVal;
break;
case ConfigType::CONFIG_PARKING:
$this->parkingTimeoutReportEnabled = $rVal;
break;
case ConfigType::CONFIG_TRANSPORTED:
$this->transportedPingTimeReportEnabled = $rVal;
break;
case ConfigType::CONFIG_STATUS:
$this->statusPingTimeReportEnabled = $rVal;
break;
case ConfigType::CONFIG_HEALTH:
$this->healthReportEnabled = $rVal;
break;
case ConfigType::CONFIG_TRIP_REPORT:
$this->tripReportEnabled = $rVal;
break;
case ConfigType::CONFIG_DIGITAL_INPUT_0:
case ConfigType::CONFIG_DIGITAL_INPUT_1:
case ConfigType::CONFIG_DIGITAL_INPUT_2:
case ConfigType::CONFIG_DIGITAL_INPUT_3:
case ConfigType::CONFIG_DIGITAL_INPUT_4:
case ConfigType::CONFIG_DIGITAL_INPUT_5:
case ConfigType::CONFIG_DIGITAL_INPUT_6:
case ConfigType::CONFIG_DRIVER_LOG:
case ConfigType::CONFIG_GREEN_BAND:
throw new CarmaLinkAPIException("Error: setReportEnabled for '".$configType."' ' is illegal, as these reports are not properly implemented.");
break;
default:
throw new CarmaLinkAPIException("Error: setReportEnabled for '".$configType."' has failed since '".$configType."' is not recognized as valid.");
}
}
/*
* Gets optional conditions used by report events
* @param ConfigType configType valid config type to get if the report is enabled or not
* @return bool|null boolean of if the report is enabled, null is report is unset.
*/
public function getReportEnabled($configType) {
switch($configType) {
case ConfigType::CONFIG_OVERSPEEDING:
return $this->speedLimitReportEnabled;
case ConfigType::CONFIG_IDLING:
return $this->idleTimeLimitReportEnabled;
case ConfigType::CONFIG_HARD_ACCEL:
return $this->accelLimitReportEnabled;
case ConfigType::CONFIG_HARD_BRAKING:
return $this->brakeLimitReportEnabled;
case ConfigType::CONFIG_HARD_CORNERING:
return $this->corneringLimitReportEnabled;
case ConfigType::CONFIG_ENGINE_OVERSPEED:
return $this->engineSpeedLimitReportEnabled;
case ConfigType::CONFIG_PARKING_BRAKE:
return $this->parkingBrakeLimitReportEnabled;
case ConfigType::CONFIG_SEATBELT:
return $this->seatbeltLimitReportEnabled;
case ConfigType::CONFIG_PARKING:
return $this->parkingTimeoutReportEnabled;
case ConfigType::CONFIG_TRANSPORTED:
return $this->transportedPingTimeReportEnabled;
case ConfigType::CONFIG_STATUS:
return $this->statusPingTimeReportEnabled;
case ConfigType::CONFIG_HEALTH:
return $this->healthReportEnabled;
case ConfigType::CONFIG_TRIP_REPORT:
return $this->tripReportEnabled;
case ConfigType::CONFIG_DIGITAL_INPUT_0:
case ConfigType::CONFIG_DIGITAL_INPUT_1:
case ConfigType::CONFIG_DIGITAL_INPUT_2:
case ConfigType::CONFIG_DIGITAL_INPUT_3:
case ConfigType::CONFIG_DIGITAL_INPUT_4:
case ConfigType::CONFIG_DIGITAL_INPUT_5:
case ConfigType::CONFIG_DIGITAL_INPUT_6:
case ConfigType::CONFIG_DRIVER_LOG:
case ConfigType::CONFIG_GREEN_BAND:
return NULL;
default:
throw new CarmaLinkAPIException("Error: getReportEnabled for '".$configType."' has failed since '".$configType."' is not recognized as valid.");
}
}
/**
* Set a full config based on a series on inputs.
* If a field is null, it is skipped
*@uses setThreshold
*@uses setAllowance
*@uses setBuzzer
*@uses setOptionalParameters
*@uses setOptionalConditions
*@uses setReportEnabled
*@param ConfigType configType ConfigType to be updated
*@param float|null threshold Optional param of setting threshold
*@param int|null allowance Null if skipped, else sets allowance parameter
*@param BuzzerVolume|null buzzer Null if skipped, else sets buzzer_volume parameter
*@param array|null optionalParameters Null if skipped, else sets OptionalParameters to a proper array.
*@param array|null optionalConditions Null if skipped, else sets OptionalConditions to a proper array.
*@param bool|null reportEnabled is the report enabled or not?
*/
public function setConfig($configType, $threshold = NULL, $allowance = NULL, $buzzer = NULL,
$optionalParameters = NULL, $optionalConditions = NULL, $reportEnabled = NULL) {
if($threshold !== NULL) { $this->setThreshold($configType, $threshold); }
if($allowance !== NULL) { $this->setAllowance($configType, $allowance); }
if($buzzer !== NULL) { $this->setBuzzerVolume($configType, $buzzer); }
if($optionalParameters !== NULL) { $this->setOptionalParameters($configType, $optionalParameters); }
if($optionalConditions !== NULL) { $this->setOptionalConditions($configType, $optionalConditions); }
if($reportEnabled !== NULL) { $this->setReportEnabled($configType, $reportEnabled); }
}
/*
* Gets Object of a conglomoration of the configuration's setting in the device.
*@param ConfigType configType configuration to get.
*@return StdObj object containing all relevant configuration information
*/
public function getConfig($configType) {
$obj = new \StdObj();
$obj->threshold = $this->getThreshold($configType);
$obj->allowance = $this->getAllowance($configType);
$obj->buzzer_volume = $this->getBuzzerVolume($configType);
$obj->optionalParameters = $this->getOptionalParameters($configType);
$obj->optionalConditions = $this->getOptionalConditions($configType);
$obj->reportEnabled = $this->getReportEnabled($configType);
if($obj->threshold === NULL && $obj->allowance === NULL && $obj->buzzer_volume === NULL &&
$obj->optionalParameters === NULL && $obj->optionalConditions === NULL && $obj->reportEnabled !== FALSE) {
unset($obj);
return NULL;
}
$obj->config_type = $configType;
//this setting is global
$obj->location = $this->getUseGps();
return $obj;
}
/**
* Set attached automobile's fuel type
* @param CarmaLink\FuelType fuel type
* @return void
*/
public function setFuelType($fuelType) { $this->fuelType = $fuelType; }
/**
* Get attached automobile's fuel type
* @return CarmaLink\FuelType
*/
public function getFuelType() { return $this->fuelType; }
/**
* Set attached auto's engine displacement
* @param float engine displacement in litres
* @return void
*/
public function setDisplacement_L($displacement_L = 2.0) { $this->displacement_L = $displacement_L; }
/**
* Get attached auto's engine displacement
* @return float litres
*/
public function getDisplacement_L() { return $this->displacement_L; }
/**
* Set state of device paused (true = paused, false = not).
* @param bool Is in paused state (true/false). converted to bool if not bool.
* @return void
*/
public function setDevicePaused($devicePaused = false) { $this->isPaused = (true && $devicePaused); }
/**
* Get device state is paused
* @return bool isPaused
*/
public function getDevicePaused() { return $this->isPaused; }
/**
* Set state of device connect interval in minutes
* @param int connectInterval_Mins
* @return void
*/
public function setConnectInterval_Mins($connectInterval_Mins = 0) { $this->connectInterval_Mins = $connectInterval_Mins; }
/**
* Get device connect interval
* @return int connectInterval_Mins
*/
public function getConnectInterval_Mins() { return $this->connectInterval_Mins; }
/**
* Set state of device agps connect interval in hours
* @param int agpsConnectInterval_Hrs
* @return void
*/
public function setAGPSConnectInterval_Hrs($agpsConnectInterval_Hrs = 0) { $this->agpsConnectInterval_Hrs = $agpsConnectInterval_Hrs; }
/**
* Get device agps connect interval
* @return int agpsConnectInterval_Hrs
*/
public function getAGPSConnectInterval_Hrs() { return $this->agpsConnectInterval_Hrs; }
/**
* Set state of device ping interval in munytes
* @param int pingInterval_Mins
* @return void
*/
public function setPingInterval_Mins($pingInterval_Mins = 0) { $this->pingInterval_Mins = $pingInterval_Mins; }
/**
* Get device agps connect interval
* @return int pingInterval_Mins
*/
public function getPingInterval_Mins() { return $this->pingInterval_Mins; }
/**
* Set device charging battery voltage of generalconfig
* @param int chargingVoltage_V
* @return void
*/
public function setChargingVoltage_V($chargingVoltage_V = 0) { $this->chargingVoltage_V = $chargingVoltage_V; }
/**
* Get device charging battery voltage
* @return int chargingVoltage_V
*/
public function getChargingVoltage_V() { return $this->chargingVoltage_V; }
/**
* Set device low battery voltage
* @param int lowBatteryVoltage_V
* @return void
*/
public function setLowBatteryVoltage_V($lowBatteryVoltage_V = 0) { $this->lowBatteryVoltage_V = $lowBatteryVoltage_V; }
/**
* Get low battery voltage threshold
* @return int lowBatteryVoltage_V
*/
public function getLowBatteryVoltage_V() { return $this->lowBatteryVoltage_V; }
/**
* Set device low battery minutes threshold
* @param int lowBatteryMinutes
* @return void
*/
public function setLowBatteryMinutes($lowBatteryMinutes = 0) { $this->lowBatteryMinutes = $lowBatteryMinutes; }
/**
* Get low battery voltage time threshold (in minutes)
* @return int lowBatteryMinutes
*/
public function getLowBatteryMinutes() { return $this->lowBatteryMinutes; }
/**
* Set device minimum run voltage energy
* @param int minimumRunVoltageEnergy
* @return void
*/
public function setMinimumRunVoltageEnergy($minimumRunVoltageEnergy = 0) { $this->minimumRunVoltageEnergy = $minimumRunVoltageEnergy; }
/**
* Get minimum run voltage energy
* @return int minimumRunVoltageEnergy
*/
public function getMinimumRunVoltageEnergy() { return $this->minimumRunVoltageEnergy; }
/**
* Set device maximum off voltage energy
* @param int maximumOffVoltageEnergy
* @return void
*/
public function setMaximumOffVoltageEnergy($maximumOffVoltageEnergy = 0) { $this->maximumOffVoltageEnergy = $maximumOffVoltageEnergy; }
/**
* Get maximum off voltage energy
* @return int maximumOffVoltageEnergy
*/
public function getMaximumOffVoltageEnergy() { return $this->maximumOffVoltageEnergy; }
/**
* Set device obd detection protocol
* @param string|OBDDetectionType obdDetection
* @return void
*/
public function setOBDDetection($obdDetection = "") { $this->obdDetection = $obdDetection; }
/**
* Get obd detection protocol
* @return string|OBDDetectionType obdDetection
*/
public function getOBDDetection() { return $this->obdDetection; }
/**
* Set device led pattern mode
* @param string|LEDModeType ledMode
* @return void
*/
public function setLEDMode($ledMode = "") { $this->ledMode = $ledMode; }
/**
* Get device led patter mode
* @return string|LEDModeType ledMode
*/
public function getLEDMode() { return $this->ledMode; }
/**
* Set device maximum uptime hours
* @param maximumUptimeHours
* @return void
*/
public function setMaximumUptimeHours($maximumUptimeHours = 0) { $this->maximumUptimeHours = $maximumUptimeHours; }
/**
* Get device maximum uptime hours
* @return int maximumUptimeHours
*/
public function getMaximumUptimeHours() { return $this->maximumUptimeHours; }
} //End of class CarmaLink
?>
<file_sep>/PHP/lib/ReportConfig.php
<?php
namespace CarmaLink;
/**
* Represents a CarmaLink configuration.
*
* @class ReportConfig
*/
class ReportConfig {
const API_THRESHOLD = "threshold";
const API_ALLOWANCE = "allowance";
const API_LOCATION = "location";
const API_BUZZER = "buzzer";
const API_DELETE_CONFIG = "OFF";
const API_PARAMS = "optionalParams";
const API_CONDITIONS = "optionalConditions";
const SPEEDING = "SPEEDING";
const ODOMETER = "ODOMETER";
const DURATION_TO_SERVICE = "DURATION_TO_SERVICE";
const DISTANCE_TO_SERVICE = "DISTANCE_TO_SERVICE";
const BATTERY_VOLTAGE = "BATTERY_VOLTAGE";
const BATTERY_VOLTAGE_LOW = "IS_LOW_BATTERY_VOLTAGE";
const EMISSION_MONITORS = "EMISSION_MONITORS";
const FUEL_LEVEL = "FUEL_LEVEL";
const TIRE_PRESSURE_LOW = "IS_LOW_TIRE_PRESSURE";
const FUEL_RATE = "FUEL_RATE";
/**
* @access public
* @var int
*/
public $id = 0;
/**
* @access public
* @var int|float
*/
public $threshold = 0;
/**
* @access public
* @var int|float
*/
public $allowance = 0.0;
/**
* @access public
* @var bool
*/
public $location = false;
/**
* @access public
* @var string
*/
public $buzzer = NULL;
/**
* @access public
* @var array
*/
public $params = null;
/**
* @access public
* @var array
*/
public $conditions = null;
/**
* @access public
* @var ConfigStatus
*/
public $state = ConfigStatus::UNKNOWN_STATUS;
/**
* @access protected
* @var ConfigType
*/
protected $_config_type;
/**
* @access private
* @var string
*/
private $__api_version;
/**
* Constructor
*
* @param int|float threshold
* @param int|float allowance
* @param bool location
* @param bool location
* @param array optional params
* @param array optional condition
* @param CarmaLink\ConfigStatus status
* @return void
*/
public function __construct($id = 0, $threshold = NULL, $allowance = NULL, $location = NULL, $params = NULL, $conditions = NULL, $state = NULL, $config_type = NULL) {
$this->__api_version = CarmaLinkAPI::API_VERSION;
$this->id = $id;
$this->threshold = $threshold;
$this->allowance = $allowance;
$this->location = $location;
$this->params = $params;
$this->conditions = $conditions;
if ($state) { $this->state = $state; }
}
/**
* Sets the protected member variable if valid.
*
* @param string|ConfigType config_type
* @return bool
*/
public function setReportConfigType($config_type) {
if ($config_type === $this->_config_type || !ConfigType::isValidReportConfigType($config_type)) { return false; }
$this->_config_type = $config_type;
return true;
}
/**
* Converts object to associative array.
*
* @return array
*/
public function toArray() {
$a = Array();
// The reasoning behind all of the null checks:
// If an object is null when sent, it should not, by default, consider that a 0. It should consider it as
// NULL, and a thing to be ignored. This allows a person to do simple updates to a threshold via simple
// requests, such as JUST updating the buzzer, or threshold.
if ($this->threshold !== NULL) { $a[self::API_THRESHOLD] = (float) $this->threshold; }
if ($this->allowance !== NULL) { $a[self::API_ALLOWANCE] = (float) $this->allowance; }
if ($this->params !== NULL) { $a[self::API_PARAMS] = (!empty($this->params) ? $this->params : null); }
if ($this->location !== NULL) { $a[self::API_LOCATION] = (bool)$this->location; }
if ($this->conditions !== NULL) { $a[self::API_CONDITIONS] = $this->conditions; }
if ($this->buzzer !== NULL) { $a[self::API_BUZZER] = (string)$this->buzzer; }
return $a;
}
/**
* Utility to setup a config's optional parameters based on a device
* @param CarmaLink device Custom data object representing CarmaLink
* @param Config config Config object to setup
* @return array|NULL
*/
protected static function setupConfigParams($parameters) {
if (!$parameters) { return NULL; }
$a = array();
//all functions are set.
if ($parameters->odometer) { $a[] = self::ODOMETER; }
if ($parameters->distanceToService) { $a[] = self::DISTANCE_TO_SERVICE; }
if ($parameters->durationToService) { $a[] = self::DURATION_TO_SERVICE; }
if ($parameters->batteryVoltage) { $a[] = self::BATTERY_VOLTAGE; $a[] = self::BATTERY_VOLTAGE_LOW; }
if ($parameters->tirePressure) { $a[] = self::TIRE_PRESSURE_LOW; }
if ($parameters->emissionMonitors) { $a[] = self::EMISSION_MONITORS; }
if ($parameters->fuelLevel) { $a[] = self::FUEL_LEVEL; }
if ($parameters->fuelRate) { $a[] = self::FUEL_RATE; }
return $a;
}
/**
* Utility to setup a config's optional conditions based on booleans sent in from a device.
* @param bool useBatteryVoltage is low battery voltage condition set?
* @param bool useTirePressure is low tire pressure condition set?
* @param bool useEmissionMonitors is emission Monitors condition set?
* @return array|NULL
*/
protected static function setupConfigConds($conditions) {
if(!$conditions) { return NULL; }
$a = array();
//all functions are set.
if ($conditions->batteryVoltage) { $a[] = self::BATTERY_VOLTAGE_LOW; }
if ($conditions->tirePressure) { $a[] = self::TIRE_PRESSURE_LOW; }
if ($conditions->emissionMonitors) { $a[] = self::EMISSION_MONITORS; }
return $a;
}
/**
* Utility method to create a new Config instance based on a device and report type. assets don't have any of these configurations, so nothing happens there.
*
* @param CarmaLink device A custom data object representing a CarmaLink
* @param string|ConfigType config_type
* @return Config|bool return new config object, or false to delete configuration
*/
private static function createConfigFromDevice(CarmaLink $device, $config_type) {
$config = new ReportConfig();
if (!$config->setReportConfigType($config_type)) {
throw new CarmaLinkAPIException("Invalid configuration type : " . $config_type);
}
$config->location = (bool) $device->getUseGps();
switch ($config->_config_type) {
case ConfigType::CONFIG_DIGITAL_INPUT_0:
case ConfigType::CONFIG_DIGITAL_INPUT_1:
case ConfigType::CONFIG_DIGITAL_INPUT_2:
case ConfigType::CONFIG_DIGITAL_INPUT_3:
case ConfigType::CONFIG_DIGITAL_INPUT_4:
case ConfigType::CONFIG_DIGITAL_INPUT_5:
case ConfigType::CONFIG_DIGITAL_INPUT_6:
case ConfigType::CONFIG_DRIVER_LOG:
case ConfigType::CONFIG_GREEN_BAND:
/* These are not supported yet*/
return NULL;
break;
case ConfigType::CONFIG_HARD_ACCEL:
case ConfigType::CONFIG_HARD_BRAKING:
case ConfigType::CONFIG_HARD_CORNERING:
case ConfigType::CONFIG_STATUS:
case ConfigType::CONFIG_IDLING:
case ConfigType::CONFIG_OVERSPEEDING:
case ConfigType::CONFIG_ENGINE_OVERSPEED:
case ConfigType::CONFIG_PARKING_BRAKE:
case ConfigType::CONFIG_PARKING:
case ConfigType::CONFIG_SEATBELT:
case ConfigType::CONFIG_TRANSPORTED:
case ConfigType::CONFIG_TRIP_REPORT:
case ConfigType::CONFIG_HEALTH:
$deviceConfig = $device->getConfig($config_type);
if($deviceConfig === NULL) { return NULL; }
if ($deviceConfig->reportEnabled === FALSE) { return FALSE; }
if($deviceConfig->config_type === ConfigType::CONFIG_STATUS) {
if ((int)$deviceConfig->threshold < ConfigType::CONFIG_STATUS_MINIMUM_PING) { return FALSE; }
} else if($deviceConfig->config_type === ConfigType::CONFIG_IDLING) {
if ((int)$deviceConfig->allowance < ConfigType::CONFIG_IDLING_MINIMUM_ALLOWANCE) { return FALSE; }
}
$config->threshold = $deviceConfig->threshold;
$config->allowance = $deviceConfig->allowance;
$config->buzzer = $deviceConfig->buzzer_volume;
$config->params = self::setupConfigParams($deviceConfig->optionalParameters);
$config->conditions = self::setupConfigConds($deviceConfig->optionalConditions);
break;
}
return $config;
}
/**
* Shortcut method which retreives a configuration object and converts to an array.
*
* @uses ReportConfig::createConfigFromDevice()
* @uses ReportConfig::toArray()
*
* @param CarmaLink device Representation of CarmaLink
* @param string|ConfigType config_type
* @return array|bool|null returns array of config parameters or false if it should be deleted, and null if the device does not support that config type.
*/
public static function getConfigArray(CarmaLink $device, $config_type) {
$newConfig = self::createConfigFromDevice($device, $config_type);
return ($newConfig !== FALSE && $newConfig !== NULL) ? $newConfig->toArray() : $newConfig;
}
/**
* Static factory
*
* @param string|stdClass obj Either a JSON string or a stdClass object representing a Config
* @param ConfigType config_type A valid ConfigType
* @return ReportConfig
*/
public static function Factory($obj, $config_type) {
if (!$obj) { return FALSE; }
if (!is_object($obj) && is_string($obj)) {
try { $obj = json_decode($obj); }
catch(Exception $e) { throw new CarmaLinkAPIException("Could not instantiate ReportConfig with provided JSON data ".$e->getMessage()); }
}
// set any missing fields to NULL
foreach (array("configId","threshold","allowance","location","buzzer","optionalParams","optionalConditions","status") as $prop) {
$obj->$prop = isset($obj->$prop) ? $obj->$prop : NULL;
}
$config = new ReportConfig(
(int)$obj->configId,
(float)$obj->threshold,
(float)$obj->allowance,
(bool)$obj->location,
$obj->optionalParams,
$obj->optionalConditions,
$obj->status
);
if($obj->buzzer) {
$config->buzzer = $obj->buzzer; }
$config->setReportConfigType($config_type);
return $config;
}
}
<file_sep>/PHP/lib/ConfigType.php
<?php
namespace CarmaLink;
/**
* Type of CarmaLink configuration.
*
* When querying the API by either retrieving data or setting the CarmaLink,
* one of the class constants should be used as the report_type parameter.
*
* @class ConfigType
*/
class ConfigType {
const CONFIG_IDLING_MINIMUM_ALLOWANCE = 5000; // 5 seconds
const CONFIG_STATUS_MINIMUM_PING = 5000; // 5 seconds
//report configuration types
const CONFIG_DIGITAL_INPUT_X = 'digital_input_';
const CONFIG_DIGITAL_INPUT_0 = 'digital_input_0';
const CONFIG_DIGITAL_INPUT_1 = 'digital_input_1';
const CONFIG_DIGITAL_INPUT_2 = 'digital_input_2';
const CONFIG_DIGITAL_INPUT_3 = 'digital_input_3';
const CONFIG_DIGITAL_INPUT_4 = 'digital_input_4';
const CONFIG_DIGITAL_INPUT_5 = 'digital_input_5';
const CONFIG_DIGITAL_INPUT_6 = 'digital_input_6';
const CONFIG_DRIVER_LOG = 'driver_log';
const CONFIG_GREEN_BAND = 'green_band';
const CONFIG_HARD_ACCEL = 'hard_accel';
const CONFIG_HARD_BRAKING = 'hard_braking';
const CONFIG_HARD_CORNERING = 'hard_cornering';
const CONFIG_STATUS = 'status';
const CONFIG_IDLING = 'idling';
const CONFIG_OVERSPEEDING = 'overspeeding';
const CONFIG_PARKING_BRAKE = 'parking_brake';
const CONFIG_SEATBELT = 'seatbelt';
const CONFIG_TRIP_REPORT = 'trip_report';
const CONFIG_HEALTH = 'vehicle_health';
const CONFIG_PARKING = 'parking';
const CONFIG_ENGINE_OVERSPEED= 'engine_overspeed';
const CONFIG_TRANSPORTED = 'transported';
const CONFIG_NEW_DEPLOYMENT = 'new_deployment';
//general config types
const CONFIG_GENERAL_ENGINE = 'engine';
const CONFIG_GENERAL_CONNECTIVITY = 'connectivity';
const CONFIG_GENERAL_OPERATION = 'operation';
//general config get all resource. fetches all the general config information together.
const CONFIG_GENERAL = 'all';
/**
* @access public
* @var array Configuration types which use the buzzer property.
*/
public static $buzzer_config_types = array(
self::CONFIG_IDLING,
self::CONFIG_OVERSPEEDING,
self::CONFIG_HARD_BRAKING,
self::CONFIG_HARD_CORNERING,
self::CONFIG_HARD_ACCEL,
self::CONFIG_PARKING_BRAKE,
self::CONFIG_SEATBELT,
self::CONFIG_ENGINE_OVERSPEED
);
/**
* valid read-write report config types
* @access public
* @var array
*/
public static $valid_rw_report_config_types = array(
self::CONFIG_DIGITAL_INPUT_0,
self::CONFIG_DIGITAL_INPUT_1,
self::CONFIG_DIGITAL_INPUT_2,
self::CONFIG_DIGITAL_INPUT_3,
self::CONFIG_DIGITAL_INPUT_4,
self::CONFIG_DIGITAL_INPUT_5,
self::CONFIG_DIGITAL_INPUT_6,
self::CONFIG_DRIVER_LOG,
self::CONFIG_GREEN_BAND,
self::CONFIG_HARD_ACCEL,
self::CONFIG_HARD_BRAKING,
self::CONFIG_HARD_CORNERING,
self::CONFIG_STATUS,
self::CONFIG_IDLING,
self::CONFIG_OVERSPEEDING,
self::CONFIG_PARKING_BRAKE,
self::CONFIG_SEATBELT,
self::CONFIG_TRIP_REPORT,
self::CONFIG_HEALTH,
self::CONFIG_PARKING,
self::CONFIG_ENGINE_OVERSPEED,
self::CONFIG_TRANSPORTED
);
/** Valid READ-ONLY report config types
* @access public
* @var array
*/
public static $valid_r_report_config_types = array(
self::CONFIG_NEW_DEPLOYMENT
);
/** Valid READ-WRITE general configuraiton endpoints.
* @access public
* @var array
*/
public static $valid_rw_general_config_types = array(
self::CONFIG_GENERAL_ENGINE,
self::CONFIG_GENERAL_CONNECTIVITY,
self::CONFIG_GENERAL_OPERATION,
);
/** Valid READ-ONLY general configuration endpoints
* @access public
* @var array
*/
public static $valid_r_general_config_types = array(
self::CONFIG_GENERAL
);
/** Configurations that use allowances
* @access public
* @var array
*/
public static $allowance_config_types = array(
self::CONFIG_DIGITAL_INPUT_0,
self::CONFIG_DIGITAL_INPUT_1,
self::CONFIG_DIGITAL_INPUT_2,
self::CONFIG_DIGITAL_INPUT_3,
self::CONFIG_DIGITAL_INPUT_4,
self::CONFIG_DIGITAL_INPUT_5,
self::CONFIG_DIGITAL_INPUT_6,
self::CONFIG_GREEN_BAND,
self::CONFIG_HARD_ACCEL,
self::CONFIG_HARD_BRAKING,
self::CONFIG_HARD_CORNERING,
self::CONFIG_STATUS,
self::CONFIG_IDLING,
self::CONFIG_OVERSPEEDING,
self::CONFIG_PARKING_BRAKE,
self::CONFIG_SEATBELT,
self::CONFIG_ENGINE_OVERSPEED
);
/**
* Helper to determine if a string matches a valid READ-WRITE report configuration type
*
* @param string|ConfigType config_type
* @return bool
*/
public static function isValidWritableReportConfigType($config_type) { return (array_search($config_type, self::$valid_rw_report_config_types) !== false); }
/**
* Helper to determine if a string matches a valid report configuration type. will have read access
*
* @param string|ConfigType config_type
* @return bool
*/
public static function isValidReportConfigType($config_type) {
return (array_search($config_type, self::$valid_rw_report_config_types) !== false ? true :
(array_search($config_type, self::$valid_r_report_config_types) !== false));
}
/**
* Helper to determine if a string matches a valid READ-WRITE general configuration endpoint
*
* @param string|ConfigType config_type
* @return bool
*/
public static function isValidWritableGeneralConfigType($config_type) { return (array_search($config_type, self::$valid_rw_general_config_types) !== false); }
/**
* Helper to determine if a string matches a valid general configuration type, with read access.
*
* @param string|ConfigType config_type
* @return bool
*/
public static function isValidGeneralConfigType($config_type) {
return (array_search($config_type, self::$valid_rw_general_config_types) !== false ? true :
(array_search($config_type, self::$valid_r_general_config_types) !== false));
}
/**
* Helper to determine if a string matches a valid configuration type.
*
* @param string|ConfigType config_type
* @return bool
*/
public static function isAllowanceConfigType($config_type) { return (array_search($config_type, self::$allowance_config_types) !== false); }
/**
* Helper to determine if a configuration type uses the buzzer property.
*
* @param string|ConfigType config_type
* @return bool
*/
public static function isBuzzerConfigType($config_type) { return (array_search($config_type, self::$buzzer_config_types) !== false); }
}
<file_sep>/PHP/tests/CarmaLinkAPITests.php
<?php
namespace CarmaLink;
/**
* Unit Tests for the CarmaLink PHP SDK
*/
require_once realpath(__DIR__."/../CarmaLinkAPI.php");
require_once realpath(__DIR__."/config.inc");
class CarmaLinkAPITest extends \PHPUnit_Framework_TestCase
{
const API_HOST_KEY = 'HOST';
const API_PORT_KEY = 'PORT';
const API_SSL_KEY = 'HTTPS';
protected $validAPI, $validAPIDebug;
protected $invalidAPI, $invalidAPIDebug;
protected $validOptions, $invalidOptions;
protected $validKeys, $invalidKeys;
protected function setUp()
{
$this->validOptions = array(
self::API_HOST_KEY => CarmaLinkAPITestConfig::VALID_API_HOST,
self::API_PORT_KEY => CarmaLinkAPITestConfig::VALID_API_PORT,
self::API_SSL_KEY => CarmaLinkAPITestConfig::VALID_API_USES_SSL
);
$this->invalidOptions = array(
self::API_HOST_KEY => CarmaLinkAPITestConfig::INVALID_API_HOST,
self::API_PORT_KEY => CarmaLinkAPITestConfig::INVALID_API_PORT
);
// Enter your valid API keys here
$this->validKeys = array('key'=>CarmaLinkAPITestConfig::API_KEY,'secret'=>CarmaLinkAPITestConfig::API_SECRET);
$this->invalidKeys = array('key'=>'ashdf436sfasd43fa7sdfasdf','secret'=>'<KEY>');
$this->validAPI = new CarmaLinkAPI($this->validKeys['key'],$this->validKeys['secret'],$this->validOptions);
$this->validAPI->use_curl_options = CarmaLinkAPITestConfig::VALID_API_TRUST_INSECURE_CERTS;
$this->invalidAPI = new CarmaLinkAPI($this->validKeys['key'],$this->validKeys['secret'],$this->invalidOptions);
}
/**
* @expectedException CarmaLink\CarmaLinkAPIException
*/
public function testConstructWithNoParams()
{
// No params
$newAPI = new CarmaLinkAPI();
}
/**
* @expectedException CarmaLink\CarmaLinkAPIException
*/
public function testConstructWithAPIKeyNoSecret()
{
// No secret
$newAPI = new CarmaLinkAPI('someAPIkey');
}
/**
* @expectedException CarmaLink\CarmaLinkAPIException
*/
public function testConstructWithEmptyAPIKeyHasSecret()
{
// Empty key
$newAPI = new CarmaLinkAPI('','somesecretkey');
}
/**
* @expectedException CarmaLink\CarmaLinkAPIException
*/
public function testConstructWithHasAPIKeyEmptySecret()
{
// Empty secret
$newAPI = new CarmaLinkAPI('someAPIkey','');
}
/**
* @covers CarmaLinkAPI::getEndpointRelativeRoot
*/
public function testGetEndpointRelativeRoot()
{
$realEndpoint = 'v' . CarmaLinkAPI::API_VERSION;
$this->assertEquals($realEndpoint, CarmaLinkAPI::getEndpointRelativeRoot() );
}
/**
* @covers CarmaLinkAPI::getEndpointRootURI
*/
public function testGetEndpointRootURI()
{
$proto = CarmaLinkAPITestConfig::VALID_API_USES_SSL ? "https://" : "http://";
$this->assertEquals($proto.CarmaLinkAPITestConfig::VALID_API_HOST.":".CarmaLinkAPITestConfig::VALID_API_PORT, $this->validAPI->getEndpointRootURI());
}
/**
* @covers CarmaLinkAPI::getReportData
*/
public function testGetReportData()
{
// invalid serial
$serial = "sadflkasdfjlkasjdflkjasdflkj";
$this->assertFalse($this->validAPI->getReportData($serial, ConfigType::CONFIG_IDLING));
// serial with known device status data
$serial = CarmaLinkAPITestConfig::$KNOWN_DEVICE_WITH_STATUS_DATA;
$this->assertStringStartsWith('[{',$this->validAPI->getReportData($serial, ConfigType::CONFIG_STATUS));
// invalid endpoint/config type
$this->assertFalse($this->validAPI->getReportData($serial, 'asdfasdfasdfasdf'));
}
/**
* Should time-out w/ cURL
* @expectedException OAuthException2
*/
public function testInvalidAPIRequests()
{
//invalid api credentials
$this->invalidAPI->getReportData(200, ConfigType::CONFIG_IDLING);
}
}
<file_sep>/PHP/CarmaLinkAPI.php
<?php
/**
* CarmaLink SDK for PHP
*
* @version 1.5.0
*
* @author <NAME> <<EMAIL>>
* @version 1.8.0
* @author <NAME> <<EMAIL>>
* @license MIT
*
*/
namespace CarmaLink {
/**
* OAuth-PHP (MIT License) is required to use this library.
*
* @see http://code.google.com/p/oauth-php/ This library uses oauth-php.
*/
require_once realpath(__DIR__ . '/oauth-php/library/OAuthStore.php');
require_once realpath(__DIR__ . '/oauth-php/library/OAuthRequester.php');
//carmalink types.
require_once realpath(__DIR__. '/lib/CarmaLink.php');
//configs
require_once realpath(__DIR__. '/lib/ConfigType.php');
require_once realpath(__DIR__. '/lib/ReportConfig.php');
require_once realpath(__DIR__. '/lib/GeneralConfig.php');
//the request api
require_once realpath(__DIR__. '/lib/CarmaLinkAPI.php');
/**
* Exception class exclusive to this namespace.
*
* @class CarmaLinkAPIException
* @todo Add custom error codes, perhaps include any HTTP codes received.
*/
class CarmaLinkAPIException extends \Exception {
const INVALID_API_KEYS_PROVIDED = "The API key or API secret provided was incorrect.";
/**
* Constructor
*
* @param string message Exception message
* @return void
*/
public function __construct($message) {
parent::__construct($message);
}
}
/**
* Emulates an enum which defines the status of a CarmaLink configuration.
*
* @class ConfigStatus
*/
class ConfigStatus {
const UNKNOWN_STATUS = 0;
const PENDING_ACTIVATION = 1;
const ACTIVATED = 2;
const PENDING_DEACTIVATION = 3;
const DEACTIVATED = 4;
}
/**
* When sending configurations for buzzer volume, please use these constants.
*
* @class BuzzerVolume
*/
class BuzzerVolume {
const BUZZER_HIGH = "HIGH";
const BUZZER_MED = "MEDIUM";
const BUZZER_OFF = "OFF";
}
/**
* Type of fuel automobile uses.
*
* When setting or getting the CONFIG_GENERAL fuel parameters, use these values.
*
* @class FuelType
*/
class FuelType {
const FUEL_GASOLINE = "FUEL_GASOLINE";
const FUEL_DIESEL = "FUEL_DIESEL";
}
/**
* Type of protocol detection a device uses
*
* When setting or getting the CONFIG_GENERAL_OPERATION obdDetection, use these values
*
* @class OBDDetectionType
*/
class OBDDetectionType {
const J1939 = "OBD_DETECTION_J1939";
const AUTO = "OBD_DETECTION_AUTOMATIC";
const DISABLED = "OBD_DETECTION_DISABLED";
}
/**
* Type of led pattern the device uses
*
* When setting or getting the CONFIG_GENERAL_OPERATION ledMode, use these values
*
* @class LEDModeType
*/
class LEDModeType {
const OFF = "OFF";
const DEBUG = "DEBUG";
const INSTALLER = "INSTALLER";
}
} // End of namespace CarmaLink
<file_sep>/README.md
Carma Systems Inc. CarmaLinkSDK 1.8.1
===============================
CarmaLink is a vehicle telematics device providing users with programmable access to their car's onboard data through OBD2, Unified Diagnostic Service (UDS) and other manufacturer specific protocols. CarmaLink also contains onboard GPS and accelerometer chipsets providing users with high quality up to the second data about vehicles and their driver's behavior.
Also included is an audible live feedback mechanism to notify drivers of unwanted behavior. CarmaLink utilizes a wireless high-speed (currently 3G) cellular network connection to communicate with its backend data processing and warehousing systems known as CarmaLinkAPI. Users are given access to their CarmaLink(s) through the CarmaLinkAPI.
The CarmaLinkSDK represents a layer of abstraction for interfacing the CarmaLinkAPI which utilizes
a RESTful style interface over HTTPS. Authentication is handled by a two-legged OAuth 1.0a implementation.
The latest CarmaLinkAPI documentation can be found ([here](https://github.com/CarmaSys/CarmaLinkAPI/tree/master))
The SDK currently supports the following languages:
* PHP >= 5.4 ([docs](http://carmasys.github.io/CarmaLinkSDK/))
Future releases aim to support:
* Ruby
* C#/.NET
* Node.js
* Python
* Java
Getting Started
---------------
* Download the SDK as a zip or clone it locally using the public GitHub URL.
* Obtain your CarmaLinkAPI Key and Secret by emailing a request to <EMAIL>
* Create a new instance of the CarmaLinkAPI class sending in required arguments (see language-specific documentation)
```PHP
$carmaLinkAPI = new CarmaLink\CarmaLinkAPI(CARMALINK_KEY, CARMALINK_SECRET, HOST_INFO_ARRAY, DEBUG);
```
* Using a valid serial and the report 'all_activity' as arguments, make an API request using the getReportData method.
```PHP
$result = $carmaLinkAPI->getReportData("517","all_activity");
```
* This will return a JSON encoded string representing the activity for the given CarmaLink serial.
```javascript
{
"statusReports": [
{
"configId": 491,
"serial": 517,
"eventStart": 1350512037502,
"reportTimestamp": 1350513187373,
"duration": 1149871,
"location": {
"longitude": -73.7788637,
"latitude": 42.6692501,
"accuracy": 1.9810001,
"heading": 215.39035,
"speed": 0
},
"vehicleVoltage": 13.594035,
"gsmSignalStrength": -77,
},
{
"configId": 491,
"serial": 517,
"eventStart": 1350512037502,
"reportTimestamp": 1350513173783,
"duration": 1136281,
"location": {
"longitude": -73.7787286,
"latitude": 42.6691727,
"accuracy": 1.9520001,
"heading": 300.98834,
"speed": 9
},
"vehicleVoltage": 14.085941,
"gsmSignalStrength": -77,
}
],
"faultReports": [],
"accelerationReports": [],
"hardBrakingReports": [],
"idlingReports": [
{
"configId": 493,
"serial": 517,
"eventStart": 1350512097220,
"reportTimestamp": 1350512110210,
"duration": 12990,
"location": {
"longitude": -73.8228948,
"latitude": 42.6262894,
"accuracy": 3.2250001,
"heading": 67.06507,
"speed": 5
},
"fuelConsumed": null
}
],
"overspeedingReports": [],
"summaryReports": [
{
"configId": 489,
"serial": 517,
"eventStart": 1350512037160,
"reportTimestamp": 1350513186969,
"duration": 1149809,
"location": {
"longitude": -73.7788637,
"latitude": 42.6692501,
"accuracy": 1.9810001,
"heading": 215.39035,
"speed": 0
},
"fuelConsumed": null,
"distance": 17.099472,
"voltage": 14.284793,
"inProgress": false
}
]
}
```
Need help?
----------------------
If you need help using the SDK or have an issue, please email <EMAIL>.
<file_sep>/PHP/lib/GeneralConfig.php
<?php
namespace CarmaLink;
/**
* Represents a CarmaLink configuration.
*
* @class GeneralConfig
*/
class GeneralConfig {
/**
* @access public
* @var string|FuelType
*/
public $fuelType = NULL;
/**
* @access public
* @var float|int
*/
public $engineDisplacement_L = NULL;
/**
* @access public
* @var boolean
*/
public $isPaused = NULL; //not set to false on purpose.
/**
* @access public
* @var int
*/
public $connectInterval_Mins = NULL;
/**
* @access public
* @var int
*/
public $agpsConnectInterval_Hrs = NULL;
/**
* @access public
* @var int
*/
public $pingInteval_Mins = NULL;
/**
* @access public
* @var float
*/
public $chargingVoltage_V = NULL;
/**
* @access public
* @var float
*/
public $lowBatteryVoltage_V = NULL;
/**
* @access public
* @var int
*/
public $lowBatteryMinutes = NULL; //note: units are already included in resource name, and therefore not added.
/**
* @access public
* @var int
*/
public $minimumRunVoltageEnergy = NULL;
/**
* @access public
* @var int
*/
public $maximumOffVoltageEnergy = NULL;
/**
* @access public
* @var string|OBDDetectionType
*/
public $obdDetection = NULL;
/**
* @access public
* @var string|LEDModeType
*/
public $ledMode = NULL;
/**
* @access public
* @var int
*/
public $maximumUptimeHours = NULL;
/**
* @access private
* @var string
*/
private $__api_version;
/**
* Constructor
*
* @param string|FuelType fuelType
* @param float|int engineDisplacement_L
* @param bool isPaused
* @param int connectInterval_Mins
* @param int agpsConnectInterval_Hrs
* @param int pingInterval_Mins
* @param float|int chargingVoltage_V
* @param float|int lowBatteryVoltage_V
* @param int lowBatteryMinutes
* @param int minimumRunVoltageEnergy
* @param int maximumOffVoltageEnergy
* @param string|OBDDetectionType obdDetection
* @param string|LEDModeType ledMode
* @param int maximumUptimeHours
* @return void
*/
public function __construct($fuelType = NULL, $engineDisplacement_L = NULL, $isPaused = NULL, $connectInterval_Mins = NULL,
$agpsConnectInterval_Hrs = NULL, $pingInterval_Mins = NULL, $chargingVoltage_V = NULL,
$lowBatteryVoltage_V = NULL, $lowBatteryMinutes = NULL, $minimumRunVoltageEnergy = NULL,
$maximumOffVoltageEnergy = NULL, $obdDetection = NULL, $ledMode = NULL, $maximumUptimeHours = NULL) {
$this->__api_version = CarmaLinkAPI::API_VERSION;
$this->fuelType = $fuelType;
$this->engineDisplacement_L = $engineDisplacement_L;
$this->isPaused = $isPaused;
$this->connectInterval_Mins = $connectInterval_Mins;
$this->agpsConnectInterval_Hrs = $agpsConnectInterval_Hrs;
$this->pingInterval_Mins = $pingInterval_Mins;
$this->chargingVoltage_V = $chargingVoltage_V;
$this->lowBatteryVoltage_V = $lowBatteryVoltage_V;
$this->lowBatteryMinutes = $lowBatteryMinutes;
$this->minimumRunVoltageEnergy = $minimumRunVoltageEnergy;
$this->maximumOffVoltageEnergy = $maximumOffVoltageEnergy;
$this->obdDetection = $obdDetection;
$this->ledMode = $ledMode;
$this->maximumUptimeHours = $maximumUptimeHours;
}
/**
* Converts object to an associative array.
*
* @return array
*/
public function toArray() {
//convert to an array with proper SDK names, and then also remove all NULL fields.
$arr = array(
"fuel" => $this->fuelType,
"displacement" => $this->engineDisplacement_L,
"isPaused" => $this->isPaused,
"connectInterval" => $this->connectInterval_Mins,
"agpsConnectInterval" => $this->agpsConnectInterval_Hrs,
"pingInterval" => $this->pingInterval_Mins,
"chargingVoltage" => $this->chargingVoltage_V,
"lowBatteryVoltage" => $this->lowBatteryVoltage_V,
"lowBatteryMinutes" => $this->lowBatteryMinutes,
"minimumRunVoltageEnergy" => $this->minimumRunVoltageEnergy,
"maximumOffVoltageEnergy" => $this->maximumOffVoltageEnergy,
"obdDetection" => $this->obdDetection,
"ledMode" => $this->ledMode,
"maximumUptimeHours" => $this->maximumUptimeHours);
$nullVals = array();
foreach($arr as $key=>$value) {
if($value === NULL) {
array_push($nullVals, $key);
}
}
//remove nulls
foreach($nullVals as $key) {
unset($arr[$key]);
}
return $arr;
}
/**
* pulls only partial array from the general config based on the resource type of the config
* Example being sending in operation. Fails when no general config resource is found.
* @param string|ConfigType config_type
* @return array
*/
public function getPartialArrayFromGeneralConfigType($config_type) {
if(!ConfigType::isValidGeneralConfigType($config_type)) {
throw new CarmaLinkAPIException("Error on getPartialArrayFromGeneralConfigType, $config_type is not recognized as a valid general config resource");
}
$configArray = array();
//convert to an array with proper SDK names, and then also remove all NULL fields.
switch($config_type) {
case ConfigType::CONFIG_GENERAL_ENGINE:
$configArray = array(
"fuel" => $this->fuelType,
"displacement" => $this->engineDisplacement_L
);
break;
case ConfigType::CONFIG_GENERAL_CONNECTIVITY:
$configArray = array(
"isPaused" => $this->isPaused,
"connectInterval" => $this->connectInterval_Mins,
"agpsConnectInterval" => $this->agpsConnectInterval_Hrs,
"pingInterval" => $this->pingInterval_Mins
);
break;
case ConfigType::CONFIG_GENERAL_OPERATION:
$configArray = array(
"chargingVoltage" => $this->chargingVoltage_V,
"lowBatteryVoltage" => $this->lowBatteryVoltage_V,
"lowBatteryMinutes" => $this->lowBatteryMinutes,
"minimumRunVoltageEnergy" => $this->minimumRunVoltageEnergy,
"maximumOffVoltageEnergy" => $this->maximumOffVoltageEnergy,
"obdDetection" => $this->obdDetection,
"ledMode" => $this->ledMode,
"maximumUptimeHours" => $this->maximumUptimeHours
);
break;
default:
//function already removes nulls.
return $this->toArray();
}
//get keys of nulls
$nullVals = array();
foreach($configArray as $key=>$value) {
if($value === NULL) {
array_push($nullVals, $key);
}
}
//remove nulls
foreach($nullVals as $key) {
unset($configArray[$key]);
}
return $configArray;
}
/* Utility method to create a new Config instance based on a device
*
* @param CarmaLink device A custom data object representing a CarmaLink
* @return Config|bool return new config object, or false to delete configuration
*/
private static function createConfigFromDevice(CarmaLink $device) {
$config = new GeneralConfig();
$config->fuelType = $device->getFuelType();
$config->engineDisplacement_L = $device->getDisplacement_L();
$config->isPaused = $device->getDevicePaused();
$config->connectInterval_Mins = $device->getConnectInterval_Mins();
$config->agpsConnectInterval_Hrs = $device->getAGPSConnectInterval_Hrs();
$config->pingInterval_Mins = $device->getPingInterval_Mins();
$config->chargingVoltage_V = $device->getChargingVoltage_V();
$config->lowBatteryVoltage_V = $device->getLowBatteryVoltage_V();
$config->lowBatteryMinutes = $device->getLowBatteryMinutes();
$config->minimumRunVoltageEnergy = $device->getMinimumRunVoltageEnergy();
$config->maximumOffVoltageEnergy = $device->getMaximumOffVoltageEnergy();
$config->obdDetection = $device->getOBDDetection();
$config->ledMode = $device->getLEDMode();
$config->maximumUptimeHours = $device->getMaximumUptimeHours();
return $config;
}
/**
* Shortcut method which retreives a configuration object and converts to an array.
*
* @uses GeneralConfig::createConfigFromDevice()
* @uses GeneralConfig::toArray()
*
* @param CarmaLink device Representation of CarmaLink
* @return array|bool returns array of config parameters or false if it should be deleted
*/
public static function getConfigArray($device) {
$newConfig = self::createConfigFromDevice($device);
return ($newConfig !== FALSE) ? $newConfig->toArray() : FALSE;
}
/**
* Static factory
*
* @param string|stdClass obj Either a JSON string or a stdClass object representing a general config from the API (no units)
* @return GeneralConfig
*/
public static function Factory($obj) {
if (!$obj) { return FALSE; }
if (!is_object($obj) && is_string($obj)) {
try { $obj = json_decode($obj); }
catch(Exception $e) { throw new CarmaLinkAPIException("Could not instantiate GeneralConfig with provided JSON data ".$e->getMessage()); }
}
//remember, this is the information from the api. the information stored here is with units, api without units.
$config = new GeneralConfig(
isset($obj->fuel) ? $obj->fuel : NULL,
isset($obj->displacement) ? $obj->displacement : NULL,
isset($obj->isPaused) ? $obj->isPaused : NULL,
isset($obj->connectInterval) ? $obj->connectInterval : NULL,
isset($obj->agpsConnectInterval) ? $obj->agpsConnectInterval : NULL,
isset($obj->pingInterval) ? $obj->pingInterval : NULL,
isset($obj->chargingVoltage) ? $obj->chargingVoltage : NULL,
isset($obj->lowBatteryVoltage) ? $obj->lowBatteryVoltage : NULL,
isset($obj->lowBatteryMinutes) ? $obj->lowBatteryMinutes : NULL,
isset($obj->minimumRunVoltageEnergy) ? $obj->minimumRunVoltageEnergy : NULL,
isset($obj->maximumOffVoltageEnergy) ? $obj->maximumOffVoltageEnergy : NULL,
isset($obj->obdDetection) ? $obj->obdDetection : NULL,
isset($obj->ledMode) ? $obj->ledMode : NULL,
isset($obj->maximumUptimeHours) ? $obj->maximumUptimeHours : NULL
);
return $config;
}
}
?>
| bc64e0f612a98d678516e16c2f73e720aa4e40fa | [
"Markdown",
"HTML",
"PHP"
] | 10 | PHP | CarmaSys/CarmaLinkSDK | 5025f764d0105961e80dd729da27d13946964fd2 | a6c6e3c7b6f5814169a01c423211358bed3b6441 |
refs/heads/master | <file_sep>all:
gcc pnameUser.c -o testPname
sudo ./testPname
<file_sep>#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <linux/kernel.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <string.h>
int main(){
int fd = open("in.txt",O_WRONLY | O_CREAT | O_APPEND);
printf("FILE DESCRIPTION: %d\n",fd);
if(write(fd, "He Dieu Hanh\n", 13) == 13) {
printf("WRITE SUCCESSFULLY\n");
}
else{
printf("WRITE FAILURE\n");
}
return 0;
}
/////
<file_sep>//// PNAMETOID và PIDTONAME
- Chạy Userspace test:
make all
-> pnametoid: Nhập name vào sẽ trả về id
-> pidtoname: Nhập id sẽ trả về name
---> Kết quả trả về được in thẳng vào Userspace
- Vào dmesg để kiểm tra kết quả: Nếu trong dmesg có in ra tên của tiến trình thì syscall chạy thành công<file_sep>#include <linux/syscalls.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/tty.h>
#include <linux/string.h>
#define MAX 32
asmlinkage long sys_pnametoid(char* name){
printk("WELCOME TO PNAMETOID \n"); /// DEBUG ONLY
struct task_struct *task;
char charname[MAX]; //Placeholder
copy_from_user(charname, name, MAX); ///Get data from user
printk("Process name: = %s \n",charname); ///DEBUG ONLY
for_each_process(task){
/*compares the current process name (defined in task->comm) to the passed in name*/
if(strcmp(task->comm,charname) == 0){
return task_pid_nr(task); /// return the PID
}
}
return -1; //// Not found anything
}
<file_sep># Systemcall-and-Hook
Student ID:
18127104 - <NAME>
18127081 - <NAME>
18127243 - <NAME>
Systemcall and Hook
----> Read the Report to Understand all the conception and the fundamental knowledge about Systemcall and Hook
Thanks :D
University of Science - K2018 - Excellent Program - Faculty of Information Technology
<NAME>
Request:
Đồ Án 2: Viết systemcall cho hệ thống và hook vào một system call có sẵn
Nhóm: tối đa 3 sinh viên
Deadline: 3 tuần
Yêu cầu: 1. Các bạn hãy cài đặt hai syscall duới đây:
int pnametoid (char *name)
Syscall này sẽ nhận vào name và trả về pid nếu tìm thấy và trả về -1 nếu không tìm thấy
int pidtoname (int pid, char* buf, int len)
Syscall này sẽ nhận vào pid, ghi process name vào trong biến buff với max len là len – 1 phần từ
cuối cùng sẽ tự động thêm NULL Giá trị trả về là -1 nếu lỗi, 0 nếu len buffer truyền vào lớn hơn
len của process name, và n với n là độ dài thật sự của process name, trong trường hợp len buffer
chuyền vào nhỏ hơn len của proccess name.
Yêu cầu 2: Hook vào 2 syscall dưới đây:
syscall open => ghi vào dmesg tên tiến trình mở file và tên file được mở
syscall write => ghi vào dmesg tên tiến trình, tên file bị ghi và số byte được ghi
Link tham khảo https://uwnthesis.wordpress.com/2016/12/26/basics-of-making-a-rootkit-fromsyscall-to-hook
<file_sep>Link tải UBUNTU: http://old-releases.ubuntu.com/releases/14.04.0/ubuntu-14.04-desktop-amd64.iso
---> Ubuntu phiên bản 14.04
Bước 1: Cài cái gói tin mở rộng:
- Trong Terminal
sudo apt-get install libncurses5-dev libncursesw5-dev
sudo apt-get install libssl-dev
sudo apt-get install libelf-dev
sudo apt-get install bison
sudo apt-get install flex
sudo apt-get install bc
sudo apt-get install perl
sudo apt-get install gcc
sudo apt-get install build-essential
sudo apt-get update
sudo apt-get upgrade
----> Phải chắc chắn là cài thành công các gói tin trên
Bước 2: Download gói Kernel về -> Tải theo cùng phiên bản Kernel -> Vì phiên bản hiện tại đang là 3.13 nên tải kernel
bản 13.13
- Trong Terminal, gõ:
wget https://mirrors.edge.kernel.org/pub/linux/kernel/v3.x/linux-3.13.11.tar.xz
Bước 3: Giải nén gói tin vào thư mục usr
- Trong Terminak, gõ:
sudo tar -xvf linux-3.13.11.tar.xz -C /usr/src/
Bước 4:
- Cài đặt code -> Trong báo cáo
Bước 5: Tạo Menuconfig
- Trong Terminal, gõ:
sudo make menuconfig -> save -> exit
Bước 6: Build kernel
- Trong Terminal, gõ:
sudo make -j 8 && sudo make modules_install -j 8 && sudo make install -j 8
Bước 7:
Build xong restart lại máy, trong Ubuntu boot menu chọn Advance option ubuntu chọn bản 3.13.11
<file_sep>#include <asm/unistd.h>
#include <asm/cacheflush.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/syscalls.h>
#include <asm/pgtable_types.h>
#include <linux/highmem.h>
#include <linux/fs.h>
#include <linux/sched.h>
#include <linux/moduleparam.h>
#include <linux/unistd.h>
#include <asm/cacheflush.h>
#include <linux/fdtable.h>
MODULE_LICENSE("GPL");
/*MY sys_call_table address*/
void **system_call_table_addr;
/*my custom syscall that takes process name*/
asmlinkage long (*open) (const char*, int, umode_t);
asmlinkage long (*write) (unsigned int, const char*, size_t);
///*hook*/
asmlinkage long hook_open(const char* filename, int flags, umode_t mode)
{
char buff[100];
copy_from_user(buff, filename, 100);
if(strcmp(current->comm,"test") == 0){
printk(KERN_INFO "process name opens file: %s | hooked open: filename = %s\n", current->comm , buff);}
return open(filename, flags, mode);
}
asmlinkage long hook_write(unsigned int fd, const char* buf, size_t len)
{
char *tmp;
char *pathname;
struct file *file;
struct path *path;
spin_lock(¤t->files->file_lock);
file = fcheck_files(current->files, fd);
if (!file) {
spin_unlock(¤t->files->file_lock);
return -ENOENT;
}
path = &file->f_path;
path_get(path);
spin_unlock(¤t->files->file_lock);
tmp = (char *)__get_free_page(GFP_KERNEL);
if (!tmp) {
path_put(path);
return -ENOMEM;
}
pathname = d_path(path, tmp, PAGE_SIZE);
path_put(path);
if (IS_ERR(pathname)) {
free_page((unsigned long)tmp);
return PTR_ERR(pathname);
}
ssize_t bytes;
bytes = (*write)(fd, buf, len);
if(strcmp(current->comm,"test") == 0){
printk(KERN_INFO "process name writes file: %s | hooked write: filename = %s, len = %d\n", current->comm, pathname, bytes);}
free_page((unsigned long)tmp);
return bytes;
}
/*Make page writeable*/
int make_rw(unsigned long address){
unsigned int level;
pte_t *pte = lookup_address(address, &level);
if(pte->pte &~_PAGE_RW){
pte->pte |=_PAGE_RW;
}
return 0;
}
/* Make the page write protected */
int make_ro(unsigned long address){
unsigned int level;
pte_t *pte = lookup_address(address, &level);
pte->pte = pte->pte & ~_PAGE_RW;
return 0;
}
static int __init entry_point(void){
printk(KERN_INFO "Hook loaded successfully..\n");
/*MY sys_call_table address*/
system_call_table_addr = (void*)0xffffffff81801680;
/* Replace custom syscall with the correct system call name
(write,open,etc) to hook*/
open = system_call_table_addr[__NR_open];
write = system_call_table_addr[__NR_write];
/*Disable page protection*/
make_rw((unsigned long)system_call_table_addr);
/*Change syscall to our syscall function*/
system_call_table_addr[__NR_open] = hook_open;
system_call_table_addr[__NR_write] = hook_write;
return 0;
}
static int __exit exit_point(void){
printk(KERN_INFO "Unloaded Captain Hook successfully\n");
/*Restore original system call */
system_call_table_addr[__NR_open] = open;
system_call_table_addr[__NR_write] = write;
/*Renable page protection*/
make_ro((unsigned long)system_call_table_addr);
return 0;
}
module_init(entry_point);
module_exit(exit_point);
<file_sep>///HOOK
- Trước khi insmod ráp module hook vào kernel, clear dmesg:
dmesg -C
- Theo dõi dmesg theo thời gian thực:
dmesg -wH
- Tạo module:
make all
- Ráp module vào Kernel
sudo insmod hook.ko
- Build file test trong Userspace
gcc test.c -o test
- Chạy file test hook, trong thư mục Test hook
sudo ./test
- Remove module
sudo rmmod hook
----> Xong các bước thì gõ dmesg trong Terminal để xem kết quả
<file_sep>#include <stdio.h>
#include <linux/kernel.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <string.h>
#define MAX 32
/////// 314 -> PNAMETOID
/////// 315 -> PIDTONAME
int main(){
char process_name[MAX]; ///PNAMETOID
printf("Enter process' name to find: ");
scanf("%s",process_name);
strtok(process_name, "\n");
printf("Your Input: %s \n",process_name);
long int id = syscall(314,process_name); //syscall number 314 and passing in the string.
printf("System call return: %ld \n",id);
if(id==-1){
printf("Status: Process' name not found!\n");}
else{
printf("Status: success!\n");
printf("Name = %s \n",process_name);
printf("PID = %ld \n",id);
}
char process_name_out[MAX]; ///PIDTONAME -> NAME OUT
int ID; //----> Input ID
printf("Input ID of process to find: \n");
scanf("%d", &ID);
int ret = syscall(315, ID, process_name_out, MAX);//syscall number 314 and passing in the ID
if(ret!=-1){
printf("Status: Success!\n");
printf("Process' name: = %s\n",process_name_out);
printf("PID = %d \n",ID);
}
return 0;
}
| 9c8915910e36ad5664382abb31292ce84ddd95a3 | [
"Text",
"C",
"Makefile",
"Markdown"
] | 9 | Makefile | DinhPhongPhu/Systemcall_and_Hook | 5a88830739d67521c1778fc2ec0aa927a849b177 | 0648fce6cc616a2c3d448a28f0bde1b37aa91890 |
refs/heads/master | <file_sep>package io.github.sagar15795.kotlindemo.data.remote
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
class RestAPI() {
private val redditApi: RedditApi
init {
val interceptor = HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.BODY
val client = OkHttpClient.Builder().addInterceptor(interceptor).build()
val retrofit = Retrofit.Builder()
.baseUrl("https://www.reddit.com")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build()
redditApi = retrofit.create(RedditApi::class.java)
}
fun getRestApiClient(): RedditApi {
return redditApi
}
}<file_sep>package io.github.sagar15795.kotlindemo.ui.main
import io.github.sagar15795.kotlindemo.data.DataManager
import io.github.sagar15795.kotlindemo.data.model.RedditNewsResponse
import io.github.sagar15795.kotlindemo.ui.base.BasePresenter
import rx.Observer
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
class MainPresenter(private var dataManager: DataManager) : BasePresenter<MainContract.View>(),
MainContract.Presenter {
override fun getTop() {
subscriber = dataManager.getTop("", "10")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : Observer<RedditNewsResponse> {
override fun onError(e: Throwable?) {
}
override fun onNext(t: RedditNewsResponse?) {
mvpView!!.showNewsList(t)
}
override fun onCompleted() {
}
})
}
private lateinit var subscriber: Subscription
override fun attachView(mvpView: MainContract.View) {
super.attachView(mvpView)
}
override fun detachView() {
super.detachView()
}
}<file_sep>package io.github.sagar15795.kotlindemo.ui.main
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import io.github.sagar15795.kotlindemo.R
import io.github.sagar15795.kotlindemo.data.DataManager
import io.github.sagar15795.kotlindemo.data.model.RedditNewsResponse
class MainActivity : AppCompatActivity(), MainContract.View {
override fun showNewsList(t: RedditNewsResponse?) {
val layoutManager : LinearLayoutManager = LinearLayoutManager(this)
recyclerViewNewsList.layoutManager = layoutManager
recyclerViewNewsList.adapter = MainAdapter(t!!,this)
}
private lateinit var recyclerViewNewsList: RecyclerView
private lateinit var mainPresenter: MainPresenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mainPresenter=MainPresenter(DataManager)
mainPresenter.attachView(this)
mainPresenter.getTop()
recyclerViewNewsList = findViewById(R.id.rv_news_list)
}
}
<file_sep>package io.github.sagar15795.kotlindemo.ui.main
import io.github.sagar15795.kotlindemo.data.model.RedditNewsResponse
import io.github.sagar15795.kotlindemo.ui.base.MvpView
interface MainContract {
interface View : MvpView{
fun showNewsList(t: RedditNewsResponse?)
}
interface Presenter{
fun getTop()
}
}<file_sep>package io.github.sagar15795.kotlindemo.ui.main
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.squareup.picasso.Picasso
import io.github.sagar15795.kotlindemo.R
import io.github.sagar15795.kotlindemo.data.model.RedditNewsResponse
import io.github.sagar15795.kotlindemo.utils.getFriendlyTime
class MainAdapter(var itemsList: RedditNewsResponse,var context : Context) : RecyclerView
.Adapter<MainAdapter
.NewsViewHolder>() {
override fun getItemCount(): Int {
return itemsList.data.children.size
}
override fun onBindViewHolder(holder: NewsViewHolder?, position: Int) {
holder!!.comments!!.text = "${itemsList.data.children[position].data.num_comments}"
holder.description!!.text = itemsList.data.children[position].data.title
holder.author!!.text = itemsList.data.children[position].data.author
holder.time!!.text = itemsList.data.children[position].data.created.getFriendlyTime()
Picasso.with(context).load(itemsList.data.children[position].data.thumbnail).into(holder
.imgThumbnail);
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): NewsViewHolder {
return NewsViewHolder(LayoutInflater.from(parent!!.context).inflate(
R.layout.item_news_list, parent, false))
}
inner class NewsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var imgThumbnail: ImageView? = null
var description: TextView? = null
var author: TextView? = null
var comments: TextView? = null
var time: TextView? = null
init {
imgThumbnail = itemView.findViewById(R.id.img_thumbnail)
description = itemView.findViewById(R.id.description)
author = itemView.findViewById(R.id.author)
comments = itemView.findViewById(R.id.comments)
time = itemView.findViewById(R.id.time)
}
}
}
<file_sep># Kotlin Demo App
This is a demo app using `Reddit` top news api with MVP architecture.<file_sep>package io.github.sagar15795.kotlindemo.data
import io.github.sagar15795.kotlindemo.data.model.RedditNewsResponse
import io.github.sagar15795.kotlindemo.data.remote.RestAPI
import rx.Observable
object DataManager {
private var apiManger= RestAPI()
fun getTop(after: String, limit: String): Observable<RedditNewsResponse> {
return apiManger.getRestApiClient().getTop(after, limit)
}
}
<file_sep>package io.github.sagar15795.kotlindemo.data.remote
import io.github.sagar15795.kotlindemo.data.model.RedditNewsResponse
import retrofit2.http.GET
import retrofit2.http.Query
import rx.Observable
interface RedditApi {
@GET("/top.json")
fun getTop(@Query("after") after: String,
@Query("limit") limit: String)
: Observable<RedditNewsResponse>;
} | cb6207bb1d47998e734dfb8d086ba040d6ed597b | [
"Markdown",
"Kotlin"
] | 8 | Kotlin | sagar15795/KotlinDemo | de04ac11392de54f1b5cf120f6ddf9e4f0a70c02 | d9e218772dd240eb669a0be227dde3781f6ddd8d |
refs/heads/main | <file_sep># Project-with-MEAN-Stack
With MEAN, we can build an application that is completely written using JavaScript technologies from frontend to backend and also at the database level.
Delve deeper into MEAN Stack by building a real-world project.
I have cover the complete code of end-to-end web application development with MongoDB, Express, Angular, and Node .js
The goal of this code is to help you master MEAN stack development, and will get a broader understanding of MEAN applications and build amazing application.
- MEAN Stack is an acronym for MongoDB, Express, Angular and Node.js
– whereby all these four are integrated to form solution-built full-stack JavaScript applications
Why MEAN Stack App Development such a great choice?.
- Using the same programming language in both the front and back ends of the application has multiple benefits.
For one thing, it makes data communication between server and client simpler and faster.
It makes modifications to either end easier. It also promotes reusing code across the multiple technologies that in turn helps keep the application secure and stable.
You will learn how to:
- Create Nodejs server with Express.js
- Use ES6 with Nodejs
- Create Restful APIS with Nodejs, Express and Mongoose
- Secure Restful APIS with Passport and JWT
- Social Authentication in Node Js
- CRUD(Create, Read, Update, Delete) Operation in Angular
- Build Angular App with Angular11, Bootstrap4.5
- Learn how to use Angular 11 Components in Real world Application
- JSON Web Token Authentication in Angular
Steps
- Download the code
- Go to the folder & npm i
- Npm start (http://localhost:5000/users)
- Go to angular-src & npm i
- Ng serve
- http://localhost:4200/home
<file_sep>const express = require("express");
const app = express();
const path = require("path");
const bodyParser = require("body-parser");
const cors = require("cors");
const passport = require("passport");
const users = require("./routes/users");
const connectDB = require("./config/db");
/*********************** Connecting To MongoDB *****/
connectDB();
/*********************** CORS Middleware *************/
app.use(cors());
/**************** Body Parser Middleware **********/
app.use(bodyParser.json());
/*********************** Routes *************/
app.use("/users", users);
/*********************** Passport Middleware *************/
app.use(passport.initialize());
app.use(passport.session());
require('./config/passport')(passport);
/*********************** Set static Files *************/
app.use(express.static(path.join(__dirname, "public")));
app.get('*' ,(req ,res ) =>{
res.sendFile(path.join(__dirname,public/index.html));
})
/*********************** Server Connection ********************/
app.get("/", (req, res) => {
res.send({
msg: "this is response",
status: 200,
});
});
var port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Env port : ${port}`);
console.log(`Server is listening at ${port} , http://localhost/${port}`);
});
| 9099cf372f8e9f66badd6ff258cd8f93263fd497 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | manish0502/Project-with-MEAN-Stack | c0bea442aa6aa92a0f93e4d737fd137d0cf5e0f2 | 73f7b066a78a0a89bc81ecf55dad2c2763dc0445 |
refs/heads/master | <repo_name>HelenaSewell/Payment-List-App<file_sep>/app/src/main/java/com/example/helenasewell/paymentdatabaseapp/PaymentMethods.java
package com.example.helenasewell.paymentdatabaseapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.sql.SQLException;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
/**
* Created by <NAME> on 23/07/2014.
* Methods relating to payments
*/
public class PaymentMethods {
private SQLiteDatabase database;
private PaymentHistoryHelper dbHelper;
private String[] allColumns={ PaymentHistoryHelper.COLUMN_ID,PaymentHistoryHelper.COLUMN_DATE,
PaymentHistoryHelper.COLUMN_GROSS,PaymentHistoryHelper.COLUMN_NET};
public PaymentMethods(Context context){
dbHelper=new PaymentHistoryHelper(context);
}
public void open() throws SQLException {
database=dbHelper.getWritableDatabase();
}
public void close(){
dbHelper.close();
}
//creating a test payment object
public Payment createPayment(){
String dateIn=randomDate();
int grossIn= 120+(int) Math.round(Math.random() * (500 - 120));
int netIn= grossIn-100;
//creates an entry to add values to
ContentValues values=new ContentValues();
values.put(PaymentHistoryHelper.COLUMN_DATE,dateIn);
values.put(PaymentHistoryHelper.COLUMN_GROSS,grossIn);
values.put(PaymentHistoryHelper.COLUMN_NET,netIn);
//placing it in the database
long insertId=database.insert(PaymentHistoryHelper.TABLE_PAYMENT,null,values);
//returns the payment so the activity can add it to the PaymentAdapter
Payment p=new Payment();
p.setId(insertId);
p.setDate(dateIn);
p.setGross(grossIn);
p.setNet(netIn);
return p;
}
//creating a random date
public String randomDate(){
GregorianCalendar c=new GregorianCalendar();
int year= 2000+(int) Math.round(Math.random() * (2020 - 2000));
c.set(GregorianCalendar.YEAR,year);
int day=1+(int) Math.round(Math.random() * c.getActualMaximum(GregorianCalendar.DAY_OF_YEAR)-1);
c.set(GregorianCalendar.DAY_OF_YEAR,day);
Date d=c.getTime();
DateFormat df= DateFormat.getDateInstance();
return df.format(d);
}
//retrieves a single Payment from the database
public Payment getPayment(int id){
String[] projection= new String[]{
PaymentHistoryHelper.COLUMN_ID,PaymentHistoryHelper.COLUMN_DATE,
PaymentHistoryHelper.COLUMN_GROSS,PaymentHistoryHelper.COLUMN_NET};
Cursor c=database.query(PaymentHistoryHelper.TABLE_PAYMENT,projection,
PaymentHistoryHelper.COLUMN_ID+"=?",new String[]{String.valueOf(id)},null,null,null);
if(c!=null)c.moveToFirst();
Payment p=new Payment();
p.setId(c.getLong(0));
p.setDate(c.getString(1));
p.setGross(c.getInt(2));
p.setNet(c.getInt(3));
c.close();
return p;
}
//deletes a Payment
public void deletePayment(Payment p){
database.delete(PaymentHistoryHelper.TABLE_PAYMENT,PaymentHistoryHelper.COLUMN_ID
+" = ?",new String[]{String.valueOf(p.getID())});
}
//retrieves all Payments in List<> form
public List<Payment> getAllPayments(){
List<Payment> paymentList=new ArrayList<Payment>();
String[] projection= new String[]{
PaymentHistoryHelper.COLUMN_ID,PaymentHistoryHelper.COLUMN_DATE,
PaymentHistoryHelper.COLUMN_GROSS,PaymentHistoryHelper.COLUMN_NET};
Cursor c=database.query(PaymentHistoryHelper.TABLE_PAYMENT,projection,
PaymentHistoryHelper.COLUMN_ID,null,null,null,null);
c.moveToFirst();
while (!c.isAfterLast()){
Payment p=new Payment();
p.setId(c.getLong(0));
p.setDate(c.getString(1));
p.setGross(c.getInt(2));
p.setNet(c.getInt(3));
paymentList.add(p);
c.moveToNext();
}
c.close();
return paymentList;
}
}
<file_sep>/app/src/main/java/com/example/helenasewell/paymentdatabaseapp/HistoryListActivity.java
package com.example.helenasewell.paymentdatabaseapp;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.text.NumberFormat;
import java.util.List;
//This activity creates and manages a database of Payments. It also displays them in a listview.
public class HistoryListActivity extends Activity {
ArrayAdapter mAdapter;
private PaymentMethods data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history_list);
data=new PaymentMethods(this);
try {
data.open();
}catch (Exception e){
Log.e("historylist oncreate", e.toString());
}
//taking data from the database and making a list from it
List<Payment> vals=data.getAllPayments();
//create an adapter for the list of Payments, using the "listitem" layout
mAdapter=new PaymentAdapter(this,R.layout.listitem,vals);
//creating a Listview to populate with "listitems"
ListView v=(ListView)findViewById(android.R.id.list);
v.setDivider(getResources().getDrawable(R.drawable.list_divider));
v.setDividerHeight(1);
v.setAdapter(mAdapter);
}
//custom ArrayAdapter specially for the List<> of Payments: takes the Payments and makes views for each of them
private class PaymentAdapter extends ArrayAdapter<Payment> {
public PaymentAdapter(Context context,int v,List<Payment> values){
super(context,v,values);
}
@Override
public View getView(int pos,View convertView,ViewGroup parent){
if(convertView==null){
LayoutInflater inflater=(LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
convertView=inflater.inflate(R.layout.listitem,null);
}
TextView date=(TextView)convertView.findViewById(R.id.date);
TextView gross=(TextView)convertView.findViewById(R.id.gross);
TextView net=(TextView)convertView.findViewById(R.id.net);
//retrieves the Payment and its data
Payment p=getItem(pos);
String stringGross=moneyAdapter(p.getGross());
String stringNet=moneyAdapter(p.getNet());
Log.d("getview", date.toString());
//applies the data from that Payment to the view
date.setText("Date: "+p.getDate());
gross.setText("Gross: "+stringGross);
net.setText("Net: "+stringNet);
return convertView;
}
//for displaying money properly
String moneyAdapter(int value){
NumberFormat nf= NumberFormat.getCurrencyInstance();
return nf.format(value);
}
}
public void onClick(View v){
Payment p=null;
switch (v.getId()){
case R.id.add:
p=data.createPayment();
mAdapter.add(p);
break;
case R.id.delete:
if(mAdapter.getCount()>0){
p=(Payment)mAdapter.getItem(0);
data.deletePayment(p);
mAdapter.remove(p);
}
break;
}
//remember to tell the PaymentAdapter that data has been altered, updating the views
mAdapter.notifyDataSetChanged();
}
//important to open and close access to the database when the app is paused
@Override
protected void onResume() {
try{data.open();}catch (Exception e){
Log.e("historylist onresume", e.toString());}
super.onResume();
}
@Override
protected void onPause() {
data.close();
super.onPause();
}
}
<file_sep>/README.md
# Payment-List-App
https://github.com/HelenaSewell/Payment-List-App/tree/master/app/src/main/java/com/example/helenasewell/paymentdatabaseapp
This is an Android activity (which can run as an app) which creates and manages a database of Payments.
It contains methods to create test payments and use them to populate a list, as well as delete them.
| 941255cf7bd2264395333907941c1260189af75a | [
"Markdown",
"Java"
] | 3 | Java | HelenaSewell/Payment-List-App | 4ec1b8cd7ea5dea4fb8d60ee4c96e4249c74f00d | 39327cb67becfefe1fd22dd4b757a64dd9a883b3 |
refs/heads/master | <repo_name>napentathol/angular-experience<file_sep>/html/partials/intro.html
<div>
<div class="panel panel-primary">
<div class="panel-heading">Introduction</div>
<div class="panel-body">
<p>My name is <NAME>. I currently work at GoHealth LLC as a software engineer. I am primarily a Java developer, however I have worked with javascript extensively for personal projects, and I maintain an angular single page application for GoHealth LLC. I am currently looking to move back to the Rochester area as a software engineer.</p>
<p>Since I have worked more with java, I figured I would demonstrate my talent with javascript and angular to make a simple single page app.</p>
</div>
</div>
</div><file_sep>/README.md
angular-experience
==================
My Experience with angular and java.
<file_sep>/html/js/controllers.js
/**
* Created by Alex on 8/14/2014.
*/
(function() {
function right($scope){
$scope.class = 'right';
$scope.$parent.class = 'right';
}
function left($scope){
$scope.class = 'left';
$scope.$parent.class = 'left';
}
function transition($scope) {
$scope.class = $scope.$parent.class;
}
xpApp.addParentController = function parentController($scope, $location) {
$scope.next = function introNext(){
xpApp.java($location);
};
$scope.prev = function angularPrev(){
xpApp.angular($location);
};
};
xpApp.addIntroController = function introController($scope, $location) {
transition($scope);
$scope.$parent.next = function(){
right($scope);
xpApp.java($location);
};
$scope.$parent.prev = function(){
left($scope);
xpApp.angular($location);
};
};
xpApp.addJavaController = function javaController($scope, $location) {
transition($scope);
$scope.$parent.next = function(){
right($scope);
xpApp.angular($location);
};
$scope.$parent.prev = function(){
left($scope);
xpApp.intro($location);
};
};
xpApp.addAngularController = function angularController($scope, $location) {
transition($scope);
$scope.$parent.next = function(){
right($scope);
xpApp.intro($location);
};
$scope.$parent.prev = function(){
left($scope);
xpApp.java($location);
};
};
xpApp.$ng.controller('ParentController', ['$scope', '$location', xpApp.addParentController]);
xpApp.$ng.controller('IntroController', ['$scope', '$location', xpApp.addIntroController]);
xpApp.$ng.controller('JavaController', ['$scope', '$location', xpApp.addJavaController]);
xpApp.$ng.controller('AngularController', ['$scope', '$location', xpApp.addAngularController]);
}()); | 6ae82a5ef9550b8f839790fe3de0a41c06383065 | [
"Markdown",
"JavaScript",
"HTML"
] | 3 | HTML | napentathol/angular-experience | e94c0aa2c116d0c49785ef7b6eedb0339d3f034b | b9de8b37192196e3cc9e53dc718ea116a3d5ed32 |
refs/heads/main | <repo_name>ViniOtacilio/Dog-List<file_sep>/README.md
# dog-list
## Como baixar as depêndencias do projeto?
Basta abrir a pasta onde você instalou o projeto e rodar o comando
```
npm install
```
## Como rodar o projeto?
Basta abrir a pasta onde você instalou o projeto e rodar o comando
```
npm run serve
```
<file_sep>/src/http-common.js
import axios from "axios";
export default axios.create({
baseURL: "https://dog.ceo/api/breeds",
headers: {
"Content-type": "application/json"
}
});<file_sep>/src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from "vuex-persistedstate";
Vue.use(Vuex);
const store = new Vuex.Store({
plugins: [createPersistedState({
storage: window.sessionStorage,
})],
state: {
favoriteDogs: []
},
mutations: {
updateFavoriteDogs (state, dog) {
state.favoriteDogs = dog;
}
}
});
export default store | 568de80b492c5d0e0a818d7c57c901f504676444 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | ViniOtacilio/Dog-List | 34ad0adedb2395ba8fe68da504db6caf84b475e5 | 79802a4df4567dce5c4b0f94c9be0aad2bb9ccc3 |
refs/heads/master | <repo_name>dhairavc/DATA607-FinalProject<file_sep>/environment_setup.R
if (!require('dplyr')) install.packages ('dplyr')
if (!require('RSocrata')) install.packages ('RSocrata')
if (!require('tidyverse')) install.packages ('tidyverse')
if (!require('ggplot2')) install.packages ('ggplot2')
if (!require('readxl')) install.packages ('readxl')
if (!require('plyr')) install.packages('plyr')
if (!require('treemap')) install.packages('treemap')
if (!require('leaflet')) install.packages ('leaflet')
if (!require('forcats')) install.packages('forcats')
if (!require('ggExtra')) install.packages('ggExtra')
if (!require('GGally')) install.packages('GGally')<file_sep>/complain_dataset.R
# ################# complain dataset #######################
app_token <- "<KEY>"
dat <- read.socrata("https://data.cityofnewyork.us/resource/qgea-i56i.csv?$where=cmplnt_fr_dt between '2014-01-01T00:00:00' and '2018-12-31T00:00:00'&$select=date_extract_y(cmplnt_fr_dt) as year,ofns_desc,boro_nm,susp_age_group, susp_sex, susp_race",
app_token = app_token)
<file_sep>/data607-finalproject.Rmd
---
title: "DATA607 Final Project"
author: "<NAME>, <NAME>, <NAME>"
date: "11/18/2019"
output:
html_document:
theme: united
df_print: paged
toc: true
toc_float:
collapsed: true
smooth_scroll: true
number_sections: true
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# A Socio-Economic Investigation into Crime
Presented by:
+ <NAME> [salma71](https://github.com/salma71)
+ <NAME> [dhairavc](https://github.com/dhairavc)
+ <NAME> [maelillien](https://github.com/maelillien)
## Introduction
This project provided us with the opportunity of showcasing many of the skills we have learned throughout this course and of applying them to an investigation into datasets of our choosing. We narrowed our scope to a few datasets containing information on socio-economic information, namely unemployment and crime data in NYC. Specifically we wanted to explore the impact of unemployment on crime within New York City. The guiding question for our statistical analysis is the following hypothesis:
\[H0: Unemployment \ does \ not \ impact \ crime\ (R^2 = 0) \]
\[HA: Unemployment \ does \ impact \ crime\ (R^2 > 0) \]
We hoped that this investigation alongside exploratory data analysis would provide us with useful information that could be used to formulate policy proposals. We used the following process for each dataset:
1. Data Import (API and .csv)
2. Data Transformation (handling missing data, tidying)
3. Data Exploration & Analysis (commentary, visualizations)
We then merged the datasets to explore further and try to draw some final conslusions based on the resulting model.
## Work flow-chart

## Sources of Datasets
- [NYPD Arrests Data Historic](https://data.cityofnewyork.us/Public-Safety/NYPD-Arrests-Data-Historic-/8h9b-rp9u)
- [Unemployment data from the Department of Labor](https://www.labor.ny.gov/stats/nyc/)
## Environment Setup
The packages are loaded from a separate R file.
```{r environment setup, message=FALSE, warning=FALSE}
source("environment_setup.R", echo = T, prompt.echo = "", spaced = F)
```
# NYPD Arrests
We will start with the NYPD Arrests Data (Historic) data from NYC Open Data found below and conduct some exploratory data analysis to find out how arrests are distributed in general. We will explore demographic trends as well as trends in particular kinds of arrest or by boroughs.
This dataset provides observations of confirmed (individuals NOT acquitted of all charges) crimes as recorded New York City Police Department (NYPD).
## NYPD Arrests - Data Import via API
There are 4.8M rows, there are 18 columns and each row is an arrest.
variable | description
---------------- | -----------
`arrest_date` | Exact date of arrest for the reported event.
`ofns_desc` | Description of internal classification corresponding with KY code (more general category than PD description).
`arrest_boro` | Borough of arrest. B(Bronx), S(Staten Island), K(Brooklyn), M(Manhattan), Q(Queens)
`age_group` | Perpetrator’s age within a category.
`perp_sex` | Perpetrator’s sex description.
`perp_race` | Perpetrator’s race description.
`x_coord_cd` | Midblock X-coordinate for New York State Plane Coordinate System, Long Island Zone, NAD 83, units feet (FIPS 3104).
`y_coord_cd` | Midblock Y-coordinate for New York State Plane Coordinate System, Long Island Zone, NAD 83, units feet (FIPS 3104)
`latitude` | Latitude coordinate for Global Coordinate System, WGS 1984, decimal degrees (EPSG 4326)
`longitude` | Longitude coordinate for Global Coordinate System, WGS 1984, decimal degrees (EPSG 4326)
The loaded R script will read the data into R using the RSocrata API.
```{r arrests, warning=FALSE, message=FALSE}
source("arrests_dataset.R", echo = F, prompt.echo = "", spaced = F)
head(arrests_df, 10)
```
## NYPD Arrests - Data Transformation
Rename the borough letters to proper names.
```{r change boro names, message=FALSE, warning=FALSE}
arrests_df$arrest_boro <- revalue(arrests_df$arrest_boro, c("Q"="Queens", "K"="Brooklyn", "M"="Manhattan", "S"="Staten Island", "B" = "Bronx"))
```
Remove missing values where no offense description is recorded.
```{r remove empty ofns, warning=FALSE, message=FALSE}
arrests_df <- arrests_df %>% filter(ofns_desc != "")
```
We generate a series of data frames aggregating the data in different manners for analysis and plotting. For example, we look at arrests by race, borough, offense.
```{r aggregation, message=FALSE, warning=FALSE}
murder_counts <- arrests_df %>%
group_by(arrest_boro, year, perp_race) %>%
dplyr::summarise(murder_counts = n()) %>%
arrange(desc(year))
murder_counts
```
```{r arrests counts, message=FALSE, warning=FALSE}
# get the count of arrests per year, by borough
grouped_boro <- arrests_df %>%
group_by(year, arrest_boro) %>%
dplyr::summarize(count = n()) %>%
arrange(desc(count))
```
```{r ofnse counts, message=FALSE, warning=FALSE}
# get the count of offenses per year, by borough
grouped_offenses <- arrests_df %>%
group_by(year, arrest_boro, ofns_desc) %>%
dplyr::summarize(count = n()) %>%
arrange(desc(count))
```
```{r top five ofnse, message=FALSE, warning=FALSE}
# get the top five offense per borough
t5 <- grouped_offenses %>% top_n(5)
```
```{r counts ofns overall, message=FALSE, warning=FALSE}
# get the counts of offenses overall
crime_counts <- arrests_df %>%
group_by(ofns_desc) %>%
dplyr::summarize(count = n()) %>%
arrange(desc(count))
```
```{r arrests count relative to dangerous drugs, message=FALSE, warning=FALSE}
# get the count of arrests related to dangerous drugs by year, by borough
drugs <- arrests_df %>%
filter(ofns_desc == 'DANGEROUS DRUGS') %>%
group_by(year, arrest_boro) %>%
dplyr::summarize(count = n())
```
## NYPD Arrest - Data Exploration & Analysis
Let's study the evolution of crime over the period of interest (2014-2018).
What the plot below reveals is that overall crime is decreasing for all boroughs of NYC. The data year over year is very similar, appearing to simply scale down over time.
```{r crimes by boro time series, echo=FALSE, message=FALSE, warning=FALSE}
ggplot(grouped_boro, aes(x = reorder(year, -count), y = count, fill = arrest_boro)) +
geom_bar(stat = 'identity', position = position_dodge()) +
scale_y_continuous(labels=function(x) format(x, big.mark = ",", scientific = FALSE), breaks = seq(0,120000,10000)) +
xlab("year") + ylab("total crime") + ggtitle("Crime by Borough Time Series") +
scale_fill_brewer(palette="Blues") + theme_minimal()
```
What we can note as suprising is the fact that total crime between Manhattan and Brooklyn is at fairly similar levels. Total crime is aggregated without accounting for different types of crime so we will further our investigation by looking at top crimes overall, and then dissecting crime per borough.
Here is a plot of the top 10 most common crimes for the 2014-2018 period across all boroughs. We learn that dangerous drugs related offenses are the most prevailent followed by 3rd degree assaults.
```{r most common crimes, echo=FALSE, message=FALSE, warning=FALSE}
ggplot(crime_counts %>% top_n(10), aes(x = reorder(ofns_desc, -count), y = count)) +
geom_bar(stat = 'identity', fill= 'lightblue') +
scale_y_continuous(labels=function(x) format(x, big.mark = ",", scientific = FALSE), breaks = seq(0,300000,50000)) +
geom_text(aes(label = count), hjust = 1.25, color='white') +
coord_flip() +
xlab("offense") + ylab("count") + ggtitle("Most Common Crimes 2014-2018") +
theme(axis.text.x = element_text(size=10), axis.text.y = element_text(size=8))
```
A peek at the bottom 10 crimes for the same period reveals somewhat unexpected crimes like disruption of a religious service. It is interesting to note that while dangerous drugs offenses are the most common crime, only 1 person was arrested for being under the influence of drugs.
```{r least commo crimes, message=FALSE, warning=FALSE, echo=FALSE}
ggplot(crime_counts %>% top_n(-10), aes(x = reorder(ofns_desc, -count), y = count)) +
geom_bar(stat = 'identity', fill= 'lightblue') +
scale_y_continuous(labels=function(x) format(x, big.mark = ",", scientific = FALSE), breaks = seq(0,75,5)) +
geom_text(aes(label = count), hjust = 1.25, color='white') +
coord_flip() +
xlab("offense") + ylab("count") + ggtitle("Least Common Crimes 2014-2018") +
theme(axis.text.x = element_text(size=10), axis.text.y = element_text(size=8))
```
Following from the exploration above, we take a deeper look at the most common crimes by borough. On the plot below, we once again see that how drug related offenses are the most common crimes and that this is consistent across boroughs. We notice that while Brooklyn and Manhattan had the most crimes, the Bronx captures the most drug arrests.
```{r top 5 crimes by boro, message=FALSE, warning=FALSE, echo=FALSE}
ggplot(t5, aes(x = reorder(arrest_boro, -count), y = count, fill=ofns_desc)) +
geom_bar(stat = 'identity', position = position_dodge()) +
scale_y_continuous(labels=function(x) format(x, big.mark = ",", scientific = FALSE), breaks = seq(0,80000,5000)) +
xlab("borough") + ylab("crime rate") + ggtitle("Top 5 Crimes by Borough") +
scale_fill_brewer(palette="Blues") + theme_minimal()
```
The plot below explores that relationship over time for each borough. We observe that similarly to crime in general, drug related arrests are going down.
```{r dangerous drug crime, echo=FALSE, message=FALSE, warning=FALSE}
ggplot(drugs, aes(x = year, y = count, color = arrest_boro)) +
geom_line() +
scale_y_continuous(labels=function(x) format(x, big.mark = ",", scientific = FALSE), breaks = seq(0,30000,2500)) +
xlab("year") + ylab("count") + ggtitle("Dangerous Drugs Crime by Bourough") +
theme(axis.text.x = element_text(size=10), axis.text.y = element_text(size=8))
```
We continue investigating the demographics and take a look at the distribution of crime by gender. Male adults between the ages of 25-44 remain the most common perpetrators. This age group is also the common for female perpetrators.
```{r age group gender distribution, message=FALSE, warning=FALSE, echo=FALSE}
ggplot(arrests_df, aes(x = age_group, fill = perp_sex)) +
geom_histogram(stat = "count", position=position_dodge()) +
scale_fill_brewer(palette="Blues") +
xlab("age group") + ylab("count") + ggtitle("Perpetrator Age Group and Gender Distribution") +
scale_y_continuous(labels=function(x) format(x, big.mark = ",", scientific = FALSE), breaks = seq(0,7000000,100000))
```
By exploring age group futher by borough, we can see that the 25-44 age category is also the largest age category density for committing crimes across all boroughs. As also shown below, the Bronx seems to have the highest density of crimes for all age categories across boroughs.
```{r density plot for age, message=FALSE, warning=FALSE, echo=FALSE, fig.width=10}
theme_set(theme_classic())
# Plot
g <- ggplot(arrests_df, aes(arrest_boro))
g + geom_density(aes(fill=factor(age_group)), alpha=0.8) +
labs(title="Density plot",
subtitle="Number of crimes per boro per age group distribution",
caption="Source: arrests_df",
x="Borough",
fill="Age group")
```
The treemap below was used to study which perpetrator race is the most common by borough. As illustrated, BLACK is the greatest proportion. However, Brooklyn appears to have more crimes committed by BLACK than the Bronx.
```{r treemap for arrests, message=FALSE, warning=FALSE, echo=FALSE}
map <- murder_counts %>% filter(year == 2018)
treemap(map, #Your data frame object
index=c("perp_race","arrest_boro"), #A list of your categorical variables
vSize = "murder_counts", #This is your quantitative variable
type="categorical", #Type sets the organization and color scheme of your treemap
vColor = "arrest_boro", #Type sets the organization and color scheme of your treemap
palette = "Set1", #Select your color palette from the RColorBrewer presets or make your own.
title="Crime distribution committed by different races - year 2018", #Customize your title
fontsize.title = 14 #Change the font size of the title
)
```
To take the investigation even further, this interactive map will let you explore the distribution of crime geographically.
```{r map for arrests,echo=FALSE, fig.align='center', message=FALSE, warning=FALSE}
arrests_map <- arrests_df %>% filter(year == 2018)
singleicon <- makeIcon(iconUrl = "https://image.flaticon.com/icons/svg/1331/1331396.svg",
iconWidth = 45,
iconHeight = 45,
iconAnchorX = 0,
iconAnchorY = 0)
leaflet(arrests_map, width = '100%') %>% addTiles() %>%
addMarkers(lng = ~longitude, lat = ~latitude,
clusterOptions = markerClusterOptions(),
popup = paste("<b>Offense: </b>", arrests_map$ofns_desc, "<br/>",
"<b>Age Group: </b>", arrests_map$age_group, "<br/>",
"<b>Sex: </b>", arrests_map$perp_sex, "<br/>",
"<b>Race: </b>", arrests_map$perp_race),
icon = singleicon)
```
# Labor Bureau
We wanted to investigate if there is a correlation between crimes and unemployment rate. So we extended our analysis with another dataset from the labor bureau. The dataset has five tables for the five boroghs for a period of four years from 2014 - 2018.
This dataset provides socio-economic observations like unemployed population and the unemployment rate of the active labor force.
## Labor Bureau - Data Import via .csv
We load the script below to import the data into R. Here is a snapshot of the data for Manhattan.
```{r dataset per boro, message=FALSE, warning=FALSE, paged.print=TRUE}
source("unemployed_dataset.R", echo = F, prompt.echo = "", spaced = F)
head(manhattan)
```
## Labor Bureau - Data Transformation
We perfomed typical data transformation operations to clean the table. This involves removing missing values and renaming columns.
```{r clean, message=FALSE, warning=FALSE}
clean_table <- function (table) {
table_content <- table %>%
na.omit()
colnames(table_content) = c("arrest_boro","year","month","labor_force","employed","unemployed","unemployment_rate")
final_table <- table_content %>%
select(arrest_boro, year, labor_force, employed, unemployed, unemployment_rate)
return(final_table)
}
```
```{r clean unemployed, message=FALSE, warning=FALSE}
bronx_income <- clean_table(bronx)
queens_income <- clean_table(queens)
brooklyn_income <- clean_table(brooklyn)
manhattan_income <- clean_table(manhattan)
staten_income <- clean_table(staten)
income_table <- Reduce(function(...) merge(..., all=T), list(bronx_income, queens_income, brooklyn_income, manhattan_income, staten_income))
income_table
```
```{r summarize avg unemployed, message=FALSE, warning=FALSE}
by_avg_unemployment <- income_table %>%
group_by(arrest_boro, year) %>%
dplyr::summarise(avg_unemployment_rate = max(unemployment_rate)) %>%
arrange(desc(year))
by_avg_unemployment$arrest_boro <- revalue(by_avg_unemployment$arrest_boro, c("Queens "="Queens"))
by_avg_unemployment
```
## Labor Bureau - Data Exploration & Analysis
The following boxplot shows the unemployment rate distribution per borough per year. We can see that there is a decreasing trend in the unemployment rate over the years. However, the Bronx county seems to have the highest unemployment rate over the years and it remains the highest in 2018 with a range of 5 - 6%.
```{r explore income by boro, message=FALSE, warning=FALSE, echo=FALSE}
theme_set(theme_bw())
ggplot(income_table, aes(x=arrest_boro, y=unemployment_rate)) +
geom_boxplot(main = "Different boxplot for uneployment rate in the 5 counties over years",
ylab = "Unemployment rate %",
xlab = "",
col = "blue",
border = "blue") +
facet_wrap(~year, scale="free") +
theme(axis.text.x = element_text(angle=60, vjust = 0.6)) +
ggtitle("Unemployment rate dsitributed by year and by borough")
```
# Combined Datasets
After understanding our datasets individually, we merged them into a single data frame based on the variable that were shared between the two sources, namely `year` and `arrest_boro`. This allowed us to extend our analysis to the variables in the combined dataset and to study how they behave in relation to each other.
```{r merge crime and by income, message=FALSE, warning=FALSE}
merged <- Reduce(function(...) merge(..., all=T), list(murder_counts, by_avg_unemployment)) %>%
na.omit() %>%
arrange(desc(year))
merged
```
## Combined - Data Transformation
We transform our datasets to prepare them to be merged.
```{r change to lowercase, message=FALSE, warning=FALSE, paged.print=TRUE}
by_crime <- arrests_df %>% select(year, arrest_boro) %>% group_by(year, arrest_boro) %>% dplyr::summarise(crimes = n())
colnames(by_crime) <- c("year", "boro_nm", "crimes" )
by_crime
```
```{r filter by unemployed, message=FALSE, warning=FALSE, paged.print=TRUE}
dat2 <- income_table
dat2$unemployed <- as.numeric(gsub(",", "", dat2$unemployed))
names(dat2)[1] <- "boro_nm"
subet <- dat2[c(1:2,5)]
by_unemployment <- subet %>%
group_by(year, boro_nm) %>%
dplyr::summarise(unemployed = round(mean(unemployed), 2)) #%>%
#mutate_if(is.character, str_to_lower)
by_unemployment$boro_nm <- revalue(by_unemployment$boro_nm, c("Queens "="Queens"))
by_unemployment
```
```{r merge crime and unemployed, message=FALSE, warning=FALSE, paged.print=TRUE}
joined <- left_join(by_crime, by_unemployment, by = c("year"="year", "boro_nm"="boro_nm"))
joined
```
```{r aggregate by category, message=FALSE, warning=FALSE}
by_cat <- arrests_df %>% select(year, arrest_boro, age_group, perp_sex, perp_race) %>% group_by(year, arrest_boro, age_group, perp_sex, perp_race) %>% dplyr::summarise(crimes=n())
colnames(by_cat) <- c("year", "boro_nm", "susp_age_group", "susp_sex", "susp_race", "crimes")
by_cat
```
Categorize age-group preparing for dummy variables
```{r construct dummy variables, message=FALSE, warning=FALSE}
dummy_df <- by_cat
dummy_df$susp_age_group <- revalue(by_cat$susp_age_group, c("<18"="child", "18-24"="youth", "25-44"="adult", "45-64"="senior", "65+" = "senior"))
dummy_df
```
Converting the independent variables into factors
```{r convert variables into factors, message=FALSE, warning=FALSE}
#function to categorize and indicate the cofounder variable
#
# function to categorise - dummy variables
filtered <- dummy_df %>%
filter(susp_age_group %in% c("child", "youth", "adult", "senior"))
## change to factor level
filtered$boro_nm <- as.factor(filtered$boro_nm)
filtered$susp_age_group <- as.factor(filtered$susp_age_group)
filtered$susp_sex <- as.factor(filtered$susp_sex)
filtered$susp_race <- as.factor(filtered$susp_race)
# contrasts(filtered$susp_race)
# reference variable is AMERICAN INDIAN/ALASKAN NATIVE, we can rereference by using relevel(var, ref = "new_ref")
```
## Combined - Data Exploration & Analysis
We tried to plot a diverging plot to investigate which borough is above or below average. So we normalized the average unemployment rate and the number of crimes. Both Brooklyn and Bronx seem to have the most significant above average for crimes committed and the unemployment rate.
```{r normalize unemployed, message=FALSE, warning=FALSE, echo=FALSE}
# Data Prep
merged$boro <- rownames(merged) # create new column for boro names
merged$unemployment_z <- round((merged$avg_unemployment_rate - mean(merged$avg_unemployment_rate))/sd(merged$avg_unemployment_rate), 2) # compute normalized
merged$unemployyment_type <- ifelse(merged$unemployment_z < 0, "below", "above") # above / below avg flag
merged <- merged[order(merged$unemployment_z), ] # sort
# merged$arrest_boro <- factor(merged$arrest_boro, levels = merged$arrest_boro) # convert to factor to retain sorted order in plot.
merged$arrest_boro <- factor(merged$arrest_boro, levels = rev(unique(merged$arrest_boro)), ordered=TRUE)
# Diverging Barcharts
ggplot(merged, aes(x=`arrest_boro`, y=unemployment_z, label=unemployment_z)) +
geom_bar(stat='identity', aes(fill=unemployyment_type), width=.5) +
scale_fill_manual(name="Unemployment",
labels = c("Above Average", "Below Average"),
values = c("above"="#f8766d", "below"="#00ba38")) +
labs(subtitle="Normalised unemployment rate from 'merged'",
title= "Diverging Bars of unemployment rates in boro") +
coord_flip()
```
```{r normalize crime, message=FALSE, warning=FALSE, echo=FALSE}
# Data Prep
merged$boro <- rownames(merged) # create new column for boro names
merged$crime_z <- round((merged$murder_counts - mean(merged$murder_counts))/sd(merged$murder_counts), 2) # compute normalized
merged$murder_type <- ifelse(merged$crime_z < 0, "below", "above") # above / below avg flag
merged <- merged[order(merged$crime_z), ] # sort
# merged$arrest_boro <- factor(merged$arrest_boro, levels = merged$arrest_boro) # convert to factor to retain sorted order in plot.
merged$arrest_boro <- factor(merged$arrest_boro, levels = rev(unique(merged$arrest_boro)), ordered=TRUE)
# Diverging Barcharts
ggplot(merged, aes(x=`arrest_boro`, y=crime_z, label=crime_z)) +
geom_bar(stat='identity', aes(fill=murder_type), width=.5) +
scale_fill_manual(name="Crimes",
labels = c("Above Average", "Below Average"),
values = c("above"="#f8766d", "below"="#00ba38")) +
labs(subtitle="Normalised crimes'",
title= "Diverging Bars of number of crimes per county") +
coord_flip()
```
# Statistical Analysis & Modeling
To answer the initial hypothesized question, the combined dataset is utilized in a linear regression modeling exercise to understand the relationship between the variables. In this process we were able to identify which variables are the greatest predictors of the number of crimes commited.
We will also verify the conditions for inference for linear modeling.
## Linear Regression
To start building the predictive model, we need to see if there is a correlation between our predictor and response. In this case, crimes and unemployed. We will begin by doing some exploratory data visualization to verify the conditions for inference. The function `ggpairs()` from the `GGally package` was used to create a plot matrix demonstrating how the variables relate to one another.
```{r correlation between crime and unemployed, message=FALSE, warning=FALSE, echo=FALSE}
ggpairs(data=joined, columns = 3:4, title="Crimes employed data")
```
There is essential regard that correlation doesn't imply causation, so constructing a regression model is imperative to comprehend whether we can use this variable as a predictor.
We started by scrutinizing the relationship between the outcome and covariant. In our case, it is the number of crimes committed and the unemployment rate. It seems that their relationship is linear.
```{r explore-unemployed as predictor, message=FALSE, warning=FALSE, echo=FALSE}
theme_set(theme_bw()) # pre-set the bw theme.
g <- ggplot(joined, aes(unemployed, crimes)) +
geom_jitter() +
geom_smooth(method="lm") +
scale_y_continuous(labels=function(x) format(x, big.mark = ",", scientific = FALSE), breaks = seq(0,150000,25000)) +
labs(y="Crimes",
x="Unemployed Population",
title="Crimes vs Unemployed Population",
caption="Source: joined")
ggMarginal(g, type = "boxplot", fill="transparent")
```
```{r unemployed regression, message=FALSE, warning=FALSE}
m_unemployed <- lm(crimes ~ unemployed, data = joined)
summary(m_unemployed)
```
As pointed by the simple linear regression, unemployment has an **R-squared ~0.75**. This makes it a better predictor of the number of crimes.
With an R-squared value of 0.75 and significant p-value for the unemployed variable, **we have sufficient evidence to reject the null hypothesis, and accept the alternate that unemployment is a good predictor of crime.**
However, to make sure that our predictor model is reliable, we need to see if the residuals are so close to the actual value. This would give us a quality indicator of how is our prediction is fitting.
```{r message=FALSE, warning=FALSE, echo=FALSE}
plot(m_unemployed, which=2, col=c("red")) # Q-Q Plot
```
For our model, **the Q-Q plot** testing the normality of the residuals shows pretty good alignment to the the line with a few points at the top slightly offset indicating some skew.
```{r message=FALSE, warning=FALSE, echo=FALSE}
plot(m_unemployed, which=3, col=c("blue")) # Scale-Location Plot
```
The residuals are not reasonably well spread above and below a pretty non horizontal line. This may raise a concern for us, this means that the relationship between the two variables are not linear.
Since the model above may not be convincing, we looked at other factors within the arrests dataset. The model below based on race only explains ~20% of the variance in the data but it indicates that the predictors of black, white and white hispanic are significant.
```{r change reference to M, message=FALSE, warning=FALSE}
m_race <- lm(crimes ~ susp_race, data = filtered)
summary(m_race) # no significance
```
To further our analysis we investigated adding more variables to build a mutlivariable regression model taking other variables into account.
## Multiple Regression
We will start with some exploratory analysis on the filtered dataset.
Having some information shown on plots would give a good idea as to which categorical variables are good predictive features and can be used to build a machine learning model.
Best plots for factor to factor variable comparison would be any of a jitter plot or heat map. I would use a jitter plot in this case for all of our factor-factor plots.
```{r exploratory analysis, warning=FALSE, message=FALSE, echo=FALSE, fig.height=6}
ggplot(data = filtered, mapping = aes(x = susp_race, y = crimes)) +
geom_jitter(aes(colour = susp_race)) +
theme(axis.text.x = element_text(angle=90, vjust=0.6))
ggplot(data = filtered, mapping = aes(x = susp_sex, y = crimes)) +
geom_jitter(aes(colour = susp_sex))
ggplot(data = filtered, mapping = aes(x = susp_age_group, y = crimes)) +
geom_jitter(aes(colour = susp_age_group))
ggplot(data = filtered, mapping = aes(x = boro_nm, y = crimes)) +
geom_jitter(aes(colour = boro_nm)) +
theme(axis.text.x = element_text(angle=65, vjust=0.6))
```
We then took other variables (susp_age_group, susp_sex, and boro_nm) into account.
```{r regression summary, warning=FALSE, message=FALSE}
m_all <- lm(crimes ~ susp_age_group + susp_sex + susp_race + boro_nm, data = filtered)
summary(m_all)
```
It can be seen that other factors remaining the same, **Black** is associated with an average increase of 3219 in crime rates compared to other races.
We study the residuals to verify the validity of our model and similarly to when we used the unemployed variable, we have concerns about the residuals distribution revealed by the **Q-Q plot**.
```{r qqplot, message=FALSE, warning=FALSE, echo=FALSE}
plot(m_all, which=2, col=c("red")) # Q-Q Plot
```
## ANOVA
Given that for our model we had an Adjusted R-squared: 0.4175, this would indicate that the model does explain 41.75% of the variability.
We know that multiple regression models are written in the form below, where $\beta_i$ represents the predictor variables coefficients.
$y = \beta_0x_0+...+\beta_nx_n + residuals$
To test the significance of our findings, we postulate a secondary hypothesis:
\[H0: \beta_0 = ... = \beta_n = 0\]
\[HA: \beta_j \neq 0; j = 1,...,n\]
In order to test if these predictors are significant, we analyze the variances with ANOVA. Since the p-values of the variances are near zero,
**we have sufficient evidence to reject the null hypothesis and accept the alternate that at least one of the variables used in the model is predictive of crime.**
```{r}
anova(m_all)
```
# Conclusion
## Summary of findings
Our investigation allows us to make a number of findings:
1. While crime overall is decreasing in NYC, black individuals are still disportionaly inclined to commit more crimes. The largest coefficent in the regression model is where the suspect race is black, 3219.82.
2. The Bronx remains the borough with the highest unemployment rate, but Brooklyn and Manhattan have the highest crime rates of the 5 boroughs.
3. The 25-44 age groups is the most likely to commit crimes for both genders.
3. At a macro level, each increase in unemployment by one, results in a crime increase of 1.2209. At a more micro level, being a black or white/hispanic male is a good predictor of a crime.
5. We built a geographic map of the distribution of commited crimes per borough.
6. With an R-squared of ~75% we found that unemployment is indeed a good predictor of crime but the model assumptions may not be valid for linear regression. The question could be investigated further with non-linear regression.
7. With an R-squared of ~42% we found that our multivariable model explains some of the variability in the data but the significant skew makes us cautious.
## Why is this important?
1. This kind of study is important in evaluating the success of policies over time by seeing the impact and relationships between crime and particular demographics.
2. It can also be used to shape the future of police enforcement policy by allowin the department to better use their resources to tackle most common crimes where they are more likely to be concentrated.
3. By merging crimes obersvations with socio-economic factor, we can identify connections to other variables like unemployment and shape policy by arguing that an investment in labor resources could have a significant beneficial impact on crime.
## Future Work
Future work would involve collecting more variables for demographics and socio economic conditions like health and eduction and building a more encompassing model to predict crime rates.
## Challenges
Throughout this assignment, we encountered a series of challenges like the following:
1. Working with very large data sets and we filtering them down
2. Sourcing external scripts into Rmarkdown to speed up knitting
3. Merging datasets with no distinct identifiers across each observations
4. Merging dataset with different inconsistent observation values
5. Determining which set of variables are a better fit for regression modeling
## References
+ [GitHub Repo](https://github.com/dhairavc/DATA607-FinalProject)
<file_sep>/arrests_dataset.R
# ################# arrests dataset #######################
app_token <- "<KEY>"
## used SoQl to filter the imported columns and to extract years as an integer from the date
arrests_df <- read.socrata("https://data.cityofnewyork.us/resource/8h9b-rp9u.csv?$where=arrest_date >= '2014-01-01T00:00:00.000'&$select=date_extract_y(arrest_date) as year,ofns_desc,arrest_boro,age_group, perp_sex, perp_race, latitude, longitude",
app_token = app_token)
<file_sep>/unemployed_dataset.R
# ################# unemployed dataset #######################
#
bronx_url <- "https://docs.google.com/spreadsheets/d/e/2<KEY>_3O2tigtla2EM/pub?gid=0&single=true&output=csv"
queens_url <- "https://docs.google.com/spreadsheets/d/e/2<KEY>/pub?gid=1191228861&single=true&output=csv"
brooklyn_url <- "https://docs.google.com/spreadsheets/d/e/2<KEY>/pub?gid=1054422077&single=true&output=csv"
manhattan_url <- "https://docs.google.com/spreadsheets/d/e/2<KEY>/pub?gid=652704166&single=true&output=csv"
staten_url <- "https://docs.google.com/spreadsheets/d/e/2<KEY>/pub?gid=1149424970&single=true&output=csv"
bronx <- read.csv(bronx_url, skip = 2, stringsAsFactors = FALSE)
queens <- read.csv(queens_url, skip = 2, stringsAsFactors = FALSE)
brooklyn <- read.csv(brooklyn_url, skip = 2, stringsAsFactors = FALSE)
manhattan <- read.csv(manhattan_url, skip = 2, stringsAsFactors = FALSE)
staten <- read.csv(staten_url, skip = 2, stringsAsFactors = FALSE)
<file_sep>/Proposal.Rmd
---
title: "DATA607 - Final Project Proposal"
author: "<NAME>, <NAME>, <NAME>"
date: "11/11/2019"
output:
html_document:
highlight: pygments
theme: cerulean
toc: yes
toc_float: yes
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Motivation
We want to try and answer the general question: What happens when there is a spike in arrests by the NYPD?
We will start with the NYPD Arrests Data (Historic) data from NYC Open Data and conduct some exploratory data analysis to find out how arrests are distributed in general. We will explore trends like for example investigating seasonality trends or trends in particular kinds of arrest or by boroughs.
To dig into the research question further, we will include data from the Civilian Complaint Review Board. We will look at the number and types of complaints received and see if there is any link to the number of arrests by the NYPD during the period of study.
[Optional] We will then supplement our study with sentiment analysis based on data extracted via the Twitter API. We will search for NYPD related tweets for the study period of interest (specify years) and perform sentiment analysis in order to score the tweets and match them against the number of arrests.
Overall, amongst the exploratory analysis we hope to uncover what happens when there is a spike in arrests by the NYPD and whether there is civilian discontent as expressed by complaints filed against the police force? We will provide some analysis around this by conducting the following hypothesis test:
\[H0: There\;is\;no\; change\;in \; public\; discontent \; following \; NYPD \; arrests\]
\[HA: There\; is\; a\; change\; in \; public \; discontent \; following \; NYPD \; arrests\]
## Datasets
Our analysis will be around 2 datasets.
### NYPD Arrests
List of every arrest in NYC going back to 2006. Each record represents an arrest effected in NYC by the NYPD and includes information about the type of crime, suspect demographic, the location and time of enforcement.
[NYPD Arrests Data Historic](https://data.cityofnewyork.us/Public-Safety/NYPD-Arrests-Data-Historic-/8h9b-rp9u)
#### Dataset desctiption
List of every arrest in NYC going back to 2006 through the end of the previous calendar year. This is a breakdown of every arrest effected in NYC by the NYPD going back to 2006 through the end of the previous calendar year. This data is manually extracted every quarter and reviewed by the Office of Management Analysis and Planning before being posted on the NYPD website. Each record represents an arrest effected in NYC by the NYPD and includes information about the type of crime, the location and time of enforcement. In addition, information related to suspect demographics is also included. This data can be used by the public to explore the nature of police enforcement activity. Please refer to the attached data footnotes for additional information about this dataset. This dataset has about 4.8M rows and 18 colums.
We will access it with via the Socrata API as shown below. The data shown below is from a subset of the NYPD data of year 2019. The full dataset is very large and we will use a downsampled version for our analysis.
```{r include=FALSE}
app_token <- "<KEY>"
```
```{r}
## install.packages("RSocrata")
library("RSocrata")
year_to_date <- "https://data.cityofnewyork.us/resource/uip8-fykc.json"
nypd_fullset <- "https://data.cityofnewyork.us/resource/8h9b-rp9u.json"
nypd <- read.socrata(year_to_date, app_token = app_token)
```
```{r include=FALSE}
library(kableExtra)
showtable <- function(data, title="", nrows=10) {
kable(head(data, nrows), caption = title) %>%
kable_styling(bootstrap_options = c("striped", "hover", "condensed"), latex_options = "scale_down")
}
```
```{r}
showtable(nypd,"NYPD Data", 10)
```
### Civilian Complaint Review Board (CCRB)
List of complaints against New York City police officers alleging the use of excessive or unnecessary force, abuse of authority, discourtesy, or the use of offensive language.
[Civilian Complaint Review Board (CCRB) - Complaints Received](https://data.cityofnewyork.us/Public-Safety/Civilian-Complaint-Review-Board-CCRB-Complaints-Re/63nx-cpi9)
#### Dataset description
The New York City Civilian Complaint Review Board (CCRB) is an independent agency. It is empowered to receive, investigate, mediate, hear, make findings, and recommend action on complaints against New York City police officers alleging the use of excessive or unnecessary force, abuse of authority, discourtesy, or the use of offensive language. The Board’s investigative staff, composed entirely of civilian employees, conducts investigations in an impartial fashion. The Board forwards its findings to the police commissioner. This dataset is about ~240K rows and 10 colums.
```{r message=FALSE, warning=FALSE}
library(readr)
ccrb <- read_csv("https://raw.githubusercontent.com/dhairavc/DATA607-FinalProject/master/ccrb.csv", col_names = TRUE)
```
```{r}
showtable(ccrb, "CCRB Data", 10)
```
## Exploratory Data Analysis
We will look at:
- Trends in seasonality of arrests
- Trends in types of arrests
- Trends in location of arrests
- Geographical distribution of arrests in NYC
- Trends in types of complaints
- Trends in reporting method of complaints
## Data Transformation
Our two datasets share two main variables: arrest date and borough of incident. The date variable differs slightly between datasets. The NYPD Data is in the MM/DD/YYYY format and ranges from 01/01/2006 to 12/31/2018. The CCRB data only provides the year in the YYYY format ranging from 2000 to 2017. We will need to split the date variable in order join the datasets on the year.
In order to combine data from the two sources, we will need aggregate the variables by year for ease of comparison.
## Data Analysis
We will try to build a model to predit crime rates and predict the subsequent effect of compliants filed against the NYPD. We will model this prediction using linear regression, etc.
## Workflow scheme
The diagram below is a representation of our overall methodology. Two factors were determinant in how the team approached this project;
* Overall duration of project: 3 Weeks
* How the work would flow downstream
* Satisfying and cover all the requirements.
```{r echo=FALSE}
library(DiagrammeR)
DiagrammeR::grViz("digraph {
graph [layout = dot, rankdir = LR]
# define the global styles of the nodes. We can override these in box if we wish
node [shape = rectangle, style = filled, fillcolor = Linen]
data1 [label = 'NYPD dataset', shape = folder, fillcolor = cyan]
data2 [label = 'CCRB dataset', shape = folder, fillcolor = cyan]
process [label = 'Process \n Data', fillcolor = green]
tidy [label = 'Tidy \n Data', fillcolor = green]
statistical [label = 'Statistical \n Analysis', fillcolor = orange]
results [label= 'Results', shape = oval, fillcolor = honeydew]
conclusion [label= 'Conclusion', fillcolor = powderBlue]
# edge definitions with the node IDs
{data1 data2} -> process -> tidy -> statistical -> {results conclusion}
}")
```
So we set a preliminary timeframe plan with the required tasks to keep them team on track and easy for us to track progress.
```{r echo=FALSE}
DiagrammeR::mermaid("
gantt
dateFormat YYYY-MM-DD
title Flowchart of the work flow estimated for the final project
section Data acquisition
Brain storm ideas :done, des1, 2014-01-06,2014-01-08
Data collecting :done, des2, 2014-01-07, 2d
Proposal draft :done, des3, 2014-01-07, 2d
section Data processing
Database API fetching :active, des4, after des3, 1d
Clean-up :active, des5, after des4, 3d
Transform : des6, after des5, 3d
Exploratory analysis : des7, after des6, 3d
section Statistical analysis
Regression model : a1, after des6, 4d
Visualization : a2, after des7 , 2d
section Documentation
final submission :doc1, after a2, 3d
presentation : after doc1, 2d
")
```
| 6b72646caa619dddc60b6059dcca19371218dad9 | [
"R",
"RMarkdown"
] | 6 | R | dhairavc/DATA607-FinalProject | 1db9cd0592c757f1300690e027aaf8133d769a04 | 3e683a5d30c7701e834ced717b4afdcdde884a85 |
refs/heads/master | <repo_name>sp2020jarvan2/TechStuff<file_sep>/Password-Management-System/src/test/java/com/self/pms/common/util/TestStringUtils.java
package com.self.pms.common.util;
import org.junit.Test;
/**
* This is a test class to test all the methods available in {@link StringUtils} class.
*
* @author <NAME>
*
*/
public class TestStringUtils {
//@Test
public void testIsEmpty() {
}
/**
* Test method to test isEqual() method
* In this, we have passed two strings and checking it whether they are equal or not.
*/
@Test
public void testIsEqual() {
String str1 = "Welcome";
String str2 = "Welcome";
boolean isEqual = new StringUtils().isEqual(str1, str2);
System.out.println("The result is: "+ isEqual);
}
}
<file_sep>/README.md
TechStuff
===========
This is a Password Management System API where in we are providing authentication and authorization of the users.
This project is made using tools and techonologies as follows:
1. Eclipse
2. Java
3. Spring
4. Hibernate
5. MySql
6. Maven
7. JUNIT
| 7a23455100bc23c21a3b3fac0a27f67ea075f980 | [
"Markdown",
"Java"
] | 2 | Java | sp2020jarvan2/TechStuff | 480dab72c3ebd23694495eac37ddba0612860278 | edbd5f757177f15ee7804029eefef669ebbd6f67 |
refs/heads/master | <repo_name>Asmaa-k/UiTestingPart3<file_sep>/README.md
# UiTestingPart3
Material Dialogs Espresso Testing
### Test Includes
#### 1. Dialogs (Material Dialogs, Is dialog visible?, Capturing input from user)
#### 2. Toasts: (Is toast visible?)

<file_sep>/app/src/androidTest/java/com/example/materialdialogstesting/MainActivityTest.kt
package com.example.materialdialogstesting
import androidx.test.core.app.ActivityScenario
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.typeText
import androidx.test.espresso.assertion.ViewAssertions.doesNotExist
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner
import com.example.materialdialogstesting.MainActivity.Companion.buildToastMessage
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4ClassRunner::class)
class MainActivityTest() {
@Test
fun test_showDialog_captureNameInput() {
//open activity
val scenario = ActivityScenario.launch(MainActivity::class.java)
//setup
val expectedName = "Asmaa"
// open dialog
onView(withId(R.id.button_launch_dialog)).perform(click())
//check if the dialog is displayed
onView(withText(R.string.text_enter_name)).check(matches(isDisplayed()))
//try to close the dialog on empty text
onView(withText(R.string.text_ok)).perform(click())
// make sure dialog is still visible (can't click ok without entering a name)
onView(withText(R.string.text_enter_name)).check(matches(isDisplayed()))
// enter a name
onView(withId(R.id.md_input_message)).perform(typeText(expectedName))
//click ok
onView(withText(R.string.text_ok)).perform(click())
// make sure dialog is gone
onView(withText(R.string.text_enter_name)).check(doesNotExist())
// Is the input name matches the text on textview
onView(withId(R.id.text_name)).check(matches(withText(expectedName)))
// Is toast displayed and is the message correct?
onView(withText(buildToastMessage(expectedName)))
.inRoot(ToastMatcher()).check(matches(isDisplayed()))
}
}<file_sep>/settings.gradle
include ':app'
rootProject.name = "MaterialDialogsTesting" | 433ce9ec8a5420694f28acc675db7c5a7f8b6f56 | [
"Markdown",
"Kotlin",
"Gradle"
] | 3 | Markdown | Asmaa-k/UiTestingPart3 | 574a458e2c047d7a5fc3cb82a78d201244b7a279 | 01c92c5cb1299ada5faffac7b3d336751f5689aa |
refs/heads/master | <file_sep>"""
The sum of the squares of the first ten natural numbers is,
12 + 22 + ... + 102 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)2 = 552 = 3025
Hence the difference between the sum of the squares of the first ten
natural numbers and the square of the sum is 3025 − 385 = 2640.
Find the difference between the sum of the squares of the first
one hundred natural numbers and the square of the sum.
"""
#function for the sum of the squares of numbers from 1 to max
def sumSqu(maxi):
tally=0 #for counting up the squares
for i in range(maxi):
tally+=((i+1)**2) #add squared number to tally
return tally #return the sum of all te squares
#function for the square of the sum of numbers from 1 to max
def sqSum(maxi):
tally=0 #for getting the sum of the numbers
for i in range(maxi):
tally+=(i+1)
return (tally**2) #return to square of the sum of numbers
print("Difference is:",sqSum(100)-sumSqu(100)) #result
<file_sep>"""
A palindromic number reads the same both ways.
The largest palindrome made from the product of
two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
#function to chck for palindromes
def bigPalin(small,big):
num1=big
num2=big
maxi=0
while num1 >= small:
while num2 >= small:
if(str(num1*num2)==str(num1*num2)[::-1]): #if is same number forward and backward
if(maxi< num1*num2): #if current maximum is less than palindrom result
maxi=num1*num2
print(maxi)
num2-=1
num1-=1
num2=big
return maxi
pal=bigPalin(100,999) #min + max for 3-digits
if(pal != 0): print("Maximum Palindrome:",pal)
else: print("No palindrome for digit range")
<file_sep>#WARNING: this program takes about 7hrs to complete
#(tested on 2GHz-Dual Core)
'''
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
'''
#prime func again
def isPrime(num):
for i in range(2,int(num/2)+1):
if not num%i:
return False
return True
maxi=2000000
tally=0
for i in reversed(range(2,maxi)): #reversed just gives an idea of time scale
if(isPrime(i)):
tally+=i #add to tally if prime
print(i)
print("\nTally:",tally)
input("\n\n[ENTER] to close...")
<file_sep>"""
By listing the first six prime numbers: 2, 3, 5, 7, 11,and 13,
we can see that the 6th prime is 13.
What is the 10 001st prime number?
"""
#previously used function for prime
def isPrime(num):
for i in range(2,int(num/2)+1):
if not num%i:
return False
return True
maxi=10001 #this is the Nth prime number (i.e. 1st is 2, 2nd is 3)
pri=1
i=0
while i < 10001: #keep goinguntil we find the maxi prime
pri+=1
while not isPrime(pri): pri+=1 #keep in loop until prime is found
i+=1 #escapes; so increases prime iteration (i.e. which prime we're at)
print("prime #",maxi," is:",pri)
<file_sep>"""
A Pythagorean triplet is a set of three natural numbers, a < b < c,
for which a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
A=B=C=0 #the triplet variables to be found
for a in range (1,333): #logically worked out this as the only valid range for a
if A is not 0: break
for b in range (a+1,499): #only valid range for b
if A is not 0: break
c=1000-b-a #and c makes up the 1000, for a+b+c=1000
if c <= b: break
#print(a,b,c)
if (a**2+b**2) == c**2: #if triplet found, done. store it.
A=a
B=b
C=c
#print(a,b,c)
print("Product of triplet: ",A*B*C) #print ABC (i.e. product)
<file_sep>"""
Each new term in the Fibonacci sequence is generated by adding
the previous two terms. By starting with 1 and 2, the first 10 terms
will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values
do not exceedfour million, find the sum of the even-valued terms.
"""
pre,fib,tally=0,1,0 #initialize variables, pre is last term fib is current
MAX=4000000 #4million is maximum value of a term
while fib <= MAX:
if(fib%2): tally+=fib #add to tally is fib term is even
pre,fib=fib,pre+fib #get new values for pre and fib
print("\ntally is: ",tally) #print result
input("\n[press ENTER to end program]")
<file_sep>"""
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
print("Sum of multiples of 3 or 5 under 1000")
input("[press start to begin]")
i=0
total=0
while i < 1000: #stop when we reach multiple bigger than 1000
if(i%5==0 or i%3==0): #ie if multiple of 5 or 3
total+=i #add multiple to cumulative tally
i+=1 #next number (will be used only if a valid multiple)
print("Answer is: ",total) #prints answer
<file_sep>"""
The four adjacent digits in the 1000-digit
number that have the greatest product are 9 × 9 × 8 × 9 = 5832.
Find the thirteen adjacent digits in the 1000-digit number that have
the greatest product. What is the value of this product?
"""
#the 100 digit number
block="\
73167176531330624919225119674426574742355349194934\
96983520312774506326239578318016984801869478851843\
85861560789112949495459501737958331952853208805511\
12540698747158523863050715693290963295227443043557\
66896648950445244523161731856403098711121722383113\
62229893423380308135336276614282806444486645238749\
30358907296290491560440772390713810515859307960866\
70172427121883998797908792274921901699720888093776\
65727333001053367881220235421809751254540594752243\
52584907711670556013604839586446706324415722155397\
53697817977846174064955149290862569321978468622482\
83972241375657056057490261407972968652414535100474\
82166370484403199890008895243450658541227588666881\
16427171479924442928230863465674813919123162824586\
17866458359124566529476545682848912883142607690042\
24219022671055626321111109370544217506941658960408\
07198403850962455444362981230987879927244284909188\
84580156166097919133875499200524063689912560717606\
05886116467109405077541002256983155200055935729725\
71636269561882670428252483600823257530420752963450"
i=0
top=0
temp=1 #used for multiplying digits together
while i<1000:
if(len(block[i:i+13])==13): #check if at end of block
for ch in block[i:i+13]: #loop through segment 13 digits long
temp*=int(ch) #multiply the 13 digits together (cast each as int)
if temp > top: #if its biggest number yet
top=temp #store it
print(top)
temp=1 #reset temp for next multiplication set
i+=1 #move along to next set set of 13 digits
print("Biggest product",top)
<file_sep>'''
The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have over five hundred divisors?
'''
#gets next natural number
def nextNat(nat,i):
return nat+i
#finds number of products a natural number has
def natProds(nat):
prods=2
for i in range(2,nat/2+1):
if nat%i==0: prods+=1
return prods
topProds=1
prods=1
nat=1
i=2
#until a natural number with over 500 products is found, keep checking for natural numbers and counting their products
while topProds < 500:
nat=nextNat(nat,i)
prods=natProds(nat)
if prods > topProds:
topProds=prods
print("Number {}: {} products".format(nat,topProds))
i+=1
print ("\nNatural number {} has {} products.\n".format(nat,topProds))
<file_sep>"""
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
"""
#function to test if a numbr is prime or not
def isPrime(num):
for i in range(2,int(num/2)+1): #valid range for checking prime
if not num%i: #if remainder is 0 for any num in range, then not prime
return False
return True #must be prime if reaches here
#function to find the next prime factor
def getNextFactor(fac,num):
for i in range(int(fac)+1,int(num/2)+1): #from last factor to half of num (valid range)
if (not num%i): #is a factor
return i
return int(num/2)+1 #no more factors, sets off end progam
num= 600851475143 #big number
fac,pfac=1,1 #factor, prime factor
while(fac<(num/2)): # as long as factor is less than half the number
fac=getNextFactor(fac,num) #find next factor
print("factor",fac)
if (isPrime(fac)): #is it a prime factor?
print("-- Prime factor of ",num,": ",fac,)
pfac=fac
print("\nGreatest prime factor is:",pfac)
<file_sep>for i in range(10):
print("loop: ",i+1)
<file_sep>"""
2520 is the smallest number that can be divided by each
of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly
divisible by all of the numbers from 1 to 20?
"""
num=loop=20 #init vaiables
found=0
while not found:
found=1 #will break loop if not changed in the following loop
for i in range(loop):
if(num%(i+1)): #from 1-20, check for remainders
found=0 #if so number is not the answer
num+=1 # so add 1 and try again
print(num)
<file_sep>'''
The following iterative sequence is defined for the set of positive integers:
n - n/2 (n is even)
n - 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 - 40 - 20 - 10 - 5 - 16 - 8 - 4 - 2 - 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million.
'''
hiChain=0
hiNo=0
for i in range(2,1000000):
n=i
chain=0
while n!=1:
if n%2==0: n=n/2
else: n=(n*3)+1
chain+=1
if chain>hiChain:
hiChain=chain
hiNo=i
print(i,": ",chain," chains")
print("Starter number",hiNo," has the highest chains at: ",hiChain," chains")<file_sep>'''
What is the greatest product of four adjacent numbers in the same
direction (up, down, left, right, or diagonally) in the 20×20 grid?
'''
#function that checks all possible horizonally adjecent groups of four numbers
#returns the maximum product of any group in the entire block
def scanHorizontal(normGrid): #takes in the grid of numbers
i=0
top=0
while i < 397: #logically the last place i could be in the 400 number block
if i%20 is 17: i+=3 #reached end of row? go to the next
tmp=int(normGrid[i])*\
int(normGrid[i+1])*\
int(normGrid[i+2])*\
int(normGrid[i+3])
if tmp>top: top=tmp #updates top if a successor is found
#print("{}: {}".format(i,top))
i+=1 #goto next quadruplet in the row
return top #returns largest product of 4 numbers horizontally adjecent
#same function as above but check verically adject numbers, rather
def scanVertical(normGrid):
i=0
top=0
while i < 340: #last place before i reading down yields out of bounds
tmp=int(normGrid[i])*\
int(normGrid[i+20])*\
int(normGrid[i+40])*\
int(normGrid[i+60])
if tmp>top: top=tmp
i+=1
return top
#function that scans diagonally right, like a blend of previous two functions, almost
def scanDiagR(normGrid):
i=0
top=0
while i < 337: #last place for i; no wrap-around
if i%20 is 17: i+=3 #same as horiz, virtually
tmp=int(normGrid[i])*\
int(normGrid[i+21])*\
int(normGrid[i+42])*\
int(normGrid[i+63])
if tmp>top: top=tmp
i+=1
return top
def scanDiagL(normGrid):
i=3
top=0
while i < 340: #last place for i; no wrap-around
if i%20 is 0: i+=3 #same as horiz, virtually
tmp=int(normGrid[i])*\
int(normGrid[i+19])*\
int(normGrid[i+38])*\
int(normGrid[i+57])
#the tmp is multipling diagagonally (down 1 row, across 1 column)
if tmp>top: top=tmp
i+=1
return top
top=0 #result we are looking for, yet to be found
#the block of 400 2-digit numbers
grid = "\
08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 \
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 \
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 \
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 \
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 \
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 \
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 \
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 \
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 \
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 \
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 \
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 \
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 \
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 \
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 \
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 \
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 \
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 \
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 \
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 \
"
normGrid=grid.split() #splits grid into its normalised digit pairs (array)
topHoriz=scanHorizontal(normGrid)
print("Maximum Horizontal: ",topHoriz)
if topHoriz > top: top=topHoriz #replace top if bigger
topVert=scanVertical(normGrid)
print("Maximum Vertical: ",topVert)
if topVert > top: top=topVert
topDiagR=scanDiagR(normGrid)
print("Maximum Right Diagonal: ",topDiagR)
if topDiagR > top: top=topDiagR
topDiagL=scanDiagL(normGrid)
print("Maximum Left Diagonal: ",topDiagL)
if topDiagL > top: top=topDiagL
#finally we have the result after all possible directions are scanned
print("\nGreatest Product: ",top)
| 851845748a52926e6309cf1951c2f2e269582d86 | [
"Python"
] | 14 | Python | mcgettin/githubLabNMG | 0021ff24abf0e2ae0d609fa337fa02d28dd36981 | 52eb652638b61bbe8e99d372b8f25e3a7ced1c7e |
refs/heads/master | <repo_name>bblovecc0816/Node<file_sep>/README.md
# Node
my node app
express web api
<file_sep>/config.js
var config = {};
config.development = {
database:{
userName: 'dpnweb', // update me
password: '<PASSWORD>', // update me
server: '172.16.58.3',
options: {
database: 'DPMonitor',
instanceName:'sql2',
rowCollectionOnRequestCompletion:true
}
}
};
config.production = {
database:{
userName: 'dpnweb', // update me
password: '<PASSWORD>', // update me
server: '172.16.58.3',
options: {
database: 'EUD',
instanceName:'sql1',
rowCollectionOnRequestCompletion:true
}
}
};
config.environment = 'development';
module.exports = config; | ca85c3ff6a4f98c8f069ced9e23b7fd31fd32195 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | bblovecc0816/Node | ebaaf6f5a9b71c9169a52dda5c1e162575f92558 | 69ed1553923f1dab6456f647625b5668b20cfedc |
refs/heads/master | <repo_name>yuanzhou15/pupper<file_sep>/middlewares/redirect.js
const redirect = {};
redirect.ifLoggedIn = (route) =>
(req, res, next) => (req.user ? res.redirect(route) : next());
redirect.ifNotLoggedInNoSetUp = (route = '/login') =>
(req, res, next) => (req.user ? (req.user.profileId ? next() : res.redirect('/set-up')) : res.redirect(route));
redirect.ifSetUpComplete = (route = '/profile') =>
(req, res, next) => (req.user.profileId ? res.redirect(route) : next() );
redirect.ifNotLoggedIn = (route = '/login') =>
(req, res, next) => (req.user ? next() : res.redirect(route));
redirect.ifNotAuthorized = (route) =>
(req, res, next) => (req.user.username !== req.params.username ? res.redirect(route) : next());
redirect.ifNotAdmin = (route = '/profile') =>
(req, res, next) => (req.user ? (req.user.admin ? next() : res.redirect(route)) : res.redirect(route));
module.exports = redirect;
| e53ce252f02e1635dba8dd000c365329d7a71a58 | [
"JavaScript"
] | 1 | JavaScript | yuanzhou15/pupper | 85a69466cc807544221d986a6731729a48789b07 | e52424f1c94e51d649fd1d4ff1f42e24c6c03eb5 |
refs/heads/master | <file_sep>import React from 'react'
import sak from '../img/sak.jpg'
class PostBlog extends React.Component {
constructor (props){
super (props)
}
handleClick (e,_id) {
console.log(_id)
this.props.switchMode(false)
this.props.setActivePost(_id)
}
render () {
const {headline,pub_date,lead_paragraph, _id} = this.props.article
return(
<div className="card col-sm-4" style={myStyle}>
<img src={sak} className="card-img-top" alt="..." />
<div className="card-body">
<h5 className="card-title" onClick = {e => this.handleClick(e, _id)}>{headline.main}</h5>
<p className="card-text">{lead_paragraph}</p>
<p className="">{pub_date}</p>
</div>
</div>
)
}
}
const myStyle = {
width:"18rem"
}
export default PostBlog<file_sep>import React, {Component as ReactComponent} from 'react'
import PostBlog from '../components/PostBlog'
import PostBlogActive from '../components/PostBlogActive'
class Blog extends ReactComponent {
constructor () {
super()
this.state = {
listBlog : [],
blog:true,
activePost:''
}
}
componentDidMount() {
fetch ('https://api.nytimes.com/svc/search/v2/articlesearch.json?q=election&api-key=<KEY>')
.then(response => response.json())
// .then(({response}) => response.docs.map(article => this.setState({listBlog:[...this.state.listBlog, article]})))
.then(({response}) => this.setState({listBlog:[...this.state.listBlog, ...response.docs]}))
}
switchMode(mode) {
this.setState({blog:mode})
console.log('switch',this.state.blog)
console.log('switch', mode)
}
setActivePost (id) {
this.setState({activePost:id})
console.log('information received', this.state.activePost)
console.log('information received', id)
}
render(){
const post = this.state.listBlog.find(article => article._id ===this.state.activePost)
return(
<div className="container">
{
this.state.blog? (<div className="row">
{this.state.listBlog.map((article, index) => <PostBlog key={index} article={article} switchMode = {(elt) => this.switchMode(elt)} setActivePost = { (elt) => this.setActivePost(elt)} />)}
</div>): <PostBlogActive article = {post} switchMode = { (elt) => this.switchMode(elt)} />
}
</div>
)
}
}
export default Blog <file_sep>import React from 'react'
import sak from '../img/sak.jpg'
const PostBlogActive = ({article, switchMode})=> {
const {headline,pub_date,lead_paragraph, _id} = article
return(
<div className="card" style={myStyle}>
<img src={sak} className="card-img-top" alt="..." />
<div className="card-body">
<h5 className="card-title" onClick = {e => this.handleClick(e, _id)}>{headline.main}</h5>
<p className="card-text">{lead_paragraph}</p>
<p className="">{pub_date}</p>
</div>
<button className = "btn btn-primary" onClick={() => switchMode(true)}>Previous</button>
</div>
)
}
const myStyle = {
width:"18rem"
}
export default PostBlogActive | 143c4fda07430ba870389de750f00afea8f40082 | [
"JavaScript"
] | 3 | JavaScript | israelkoum/exoArticleReact | c30c58b6f426987b10b89755f847bce53fc6fc95 | 73877d03f14acb4a8c26a7ee5ca2f2aa86288a81 |
refs/heads/master | <file_sep># !/usr/bin/python3.4
import os
import sys
from asr_run import *
# import time
# import numpy as np
# import threading
# import threading
index = 0
# root_dir = sys.argv[1]
# video_dir = root_dir
# sound_dir = '../sound/'
# sound_dir = '../training-1/'
sound_dir = '/home/orcuslc/MED/training-1/sound/'
txt_dir = '/home/orcuslc/MED/training-1/txt/'
log_dir = '/home/orcuslc/MED/training-1/log/'
# file_list = sound_dir+'files.npy'
start_time = time.time()
count = 0
total_minute = 0
total_second = 0
file = sys.argv[1]
filename = file[-13:-4]
asr_run(file, filename, txt_dir, log_dir, start_time)
# listlock = threading.RLock()
# file_amount = 1
# while file_amount >= 1:
# time.sleep(np.random.random())
# count += 1
# # listlock.acquire()
# files = np.load(file_list).tolist()
# file_amount = len(files)
# file = files.pop(0)
# np.save(file_list, files)
# filename = file[:-4]
# file = sound_dir + file
# print(file+' Started!')
# asr_run(sound_dir+file, filename, txt_dir, log_dir)
# avg = int(file_amount/11)
# if index != 10:
# files = file_list[index*avg:(index+1)*avg]
# else:
# files = file_list[10*avg:]
# for file in files:
# count += 1
# filename = file[:-4]
# duration = run(file, filename, video_dir, sound_dir, txt_dir, log_dir).split(':')[1].split(' ')
# if len(duration) == 3:
# if 'mn' in duration[1]:
# minute = int(duration[1][:-2])
# second = int(duration[2][:-1])
# elif 's' in duration[1]:
# minute = 0
# second = int(duration[1][:-1])
# ms = int(duration[2][:-2])
# second += ms/1000
# elif len(duration) == 2:
# if 'mn' in duration[1]:
# minute = int(duration[1][:-2])
# second = 0
# elif 's' in duration[1]:
# minute = 0
# second = int(duration[1][:-1])
# else:
# minute = second = 0
# else:
# minute = second = 0
# total_minute += minute
# total_second += second
# for parent, dirs, files in os.walk(sound_dir):
# for file in files:
# if file[-4:] != '.wav':
# continue
# count += 1
# filename = file[:-4]
# print(file+' Started!')
# asr_run(sound_dir+file, filename, txt_dir, log_dir)
# duration = run(file, filename, video_dir, sound_dir, txt_dir, log_dir).split(':')[1].split(' ')
# if len(duration) == 3:
# if 'mn' in duration[1]:
# minute = int(duration[1][:-2])
# second = int(duration[2][:-1])
# elif 's' in duration[1]:
# minute = 0
# second = int(duration[1][:-1])
# ms = int(duration[2][:-2])
# second += ms/1000
# elif len(duration) == 2:
# if 'mn' in duration[1]:
# minute = int(duration[1][:-2])
# second = 0
# elif 's' in duration[1]:
# minute = 0
# second = int(duration[1][:-1])
# else:
# minute = second = 0
# else:
# minute = second = 0
# total_minute += minute
# total_second += second
# total_duration = total_minute + total_second/60.0
# end_time = time.time()
# f = open(log_dir+'REPORT-'+str(index)+'.log', 'w')
# result = str(count)
# result = str(count) + ' Videos, Total Duration ' + str(total_duration) + ' minutes, Total Time Cost ' + str((end_time - start_time)/60.0) + ' minutes.'
# f.write(result)
# f.close()<file_sep>import sys, os
files_path = sys.argv[1]
result_path = sys.argv[2]
n = int(sys.argv[3])
def prep(n, files_path, result_path):
files_list = os.listdir(files_path)
files_list = [files_path+i for i in files_list]
# print(files_list)
with open(result_path, 'a+') as f:
for i in range(len(files_list) // n):
f.write(' '.join(files_list[n*i:n*(i+1)]) + '\n')
# print(files_list[n*i:(n+1)*i])
f.write(' '.join(files_list[(len(files_list)//n) * n:]))
if __name__ == '__main__':
prep(n, files_path, result_path)<file_sep>import sys, os
method = sys.argv[1]
sentence_path = sys.argv[2]
sentence_name = sys.argv[3]
tmp_path = sys.argv[4]
result_path = sys.argv[5]
sentences = os.listdir(sentence_path)
sentence_names = [item[:-4] for item in sentences]
with open('./sentences', 'w') as f:
for i in sentence_names:
f.write(method+' '+sentence_path+' '+i+' '+tmp_path+' '+result_path+'\n')
<file_sep># Run-extract
from extract_keywords import extract_
import sys
sentence_path = sys.argv[2]
key_words_path = sys.argv[1]
sentence_name = sentence_path[-13:]
key_words_path = key_words_path+sentence_name
extract_(sentence_path, key_words_path)
<file_sep>import numpy as np
import os,sys
txt_list = os.listdir('./txt')
txt_name = [item[:-4] for item in txt_list]
sound_list = os.listdir('./sound')
diff = []
for item in sound_list:
name = item[-13:-4]
if name not in txt_name:
diff.append(item)
with open('diff', 'w') as f:
for i in diff:
f.write('./sound/'+i+'\n')
<file_sep># Filter
import numpy as np
import wave
import scipy.signal as signal
# import matplotlib.pyplot as plt
def sound_filter(sound, pass_region, stop_region, op):
wav = wave.open(sound)
params = wav.getparams()
nchannels, sampwidth, framerate, nframes = params[:4]
string_data = wav.readframes(nframes)
wav.close()
wave_data = np.fromstring(string_data, dtype=np.short)
if wave_data.size % 2 != 0:
wave_data = np.delete(wave_data, -1)
wave_data.shape = -1, 2
wave_data = wave_data.T
time = np.arange(0, nframes) * (1.0/framerate)
left_channel = wave_data[0]
wave_length = left_channel.size
right_channel = wave_data[1]
# if len(left_channel) == 0 or len(right_channe)
#plt.subplot(221)
#plt.plot(time, left_channel)
#plt.subplot(222)
#plt.plot(time, right_channel, c='g')
new_left_channel, new_right_channel = op(left_channel, right_channel, pass_region, stop_region, framerate)
wave_data = np.zeros(2*wave_length, dtype=np.short)
wave_data[::2] = new_left_channel
wave_data[1::2] = new_right_channel
wave_data = wave_data.tostring()
f = wave.open(sound, 'wb')
f.setnchannels(nchannels)
f.setsampwidth(sampwidth)
f.setframerate(framerate)
f.writeframes(wave_data)
f.close()
#plt.subplot(223)
#plt.plot(time, new_left_channel)
#plt.subplot(224)
#plt.plot(time, new_right_channel, c='g')
#plt.show()
def butterworth_bandpass_filter(left_channel, right_channel, pass_region, stop_region, framerate):
pass_region = 2*pass_region/framerate
stop_region = 2*stop_region/framerate
#print(pass_region, stop_region)
pass_max_damp = 2
stop_min_damp = 20
b, a = signal.iirdesign(pass_region, stop_region, pass_max_damp, stop_min_damp)
new_left_channel = signal.lfilter(b, a, left_channel)
new_right_channel = signal.lfilter(b, a, right_channel)
return new_left_channel, new_right_channel
def fft_bandpass_filter(left_channel, right_channel, pass_region, stop_region, framerate):
length = left_channel.size
'''Notice: Sampling frequency = 2*max signal frequency'''
low = int(pass_region[0]/framerate*length*2)+1
high = int(pass_region[1]/framerate*length*2)
left_channel = np.fft.fft(left_channel)
right_channel = np.fft.fft(right_channel)
left_channel[:low] = .0
left_channel[high:] = .0
right_channel[:low] = .0
right_channel[high:] = .0
left_channel = np.fft.ifft(left_channel)
right_channel = np.fft.ifft(right_channel)
return left_channel, right_channel
def set_eq(left, right, p_r, s_r, framerate):
rate1 = 1
rate2 = 0.8
rate3 = (2-2*rate2)
try:
left_freq = np.fft.fft(left) * rate2
right_freq = np.fft.fft(right) * rate2
except ValueError:
return left, right
length = left.size
# print(length)
f1 = np.vectorize(lambda x: rate1*(0.5*np.sin(np.pi*(x-1.5)) + 0.5))
f2 = np.vectorize(lambda x: rate1*(0.5*np.sin(0.5*np.pi*(x-1)) + 0.5))
freq = np.vectorize(lambda i: i*framerate/(length*2))
index = lambda freq: int(2*length/framerate*freq)
x250 = index(250)
x500 = index(500)
x1000 = index(1000)
xx1 = f1(np.asarray(range(x250, x500))*framerate/(length*2)/250)
# xx1 = f1(freq(np.asarray(range(x250, x500))/250))
# xx2 = f2(freq(np.asarray(range(x500, x1000))/250))
xx2 = f2(np.asarray(range(x500, x1000))*framerate/(length*2)/250)
left_freq[x250:x500] = left_freq[x250:x500] * (1+rate3*xx1)
right_freq[x250:x500] = right_freq[x250:x500] * (1+rate3*xx1)
left_freq[x500:x1000] = left_freq[x500:x1000] * (1+rate3*xx2)
right_freq[x500:x1000] = right_freq[x500:x1000] * (1+rate3*xx2)
left = np.fft.ifft(left_freq)
right = np.fft.ifft(right_freq)
return left, right
# def set_eq(left_channel, right_channel, pass_region, stop_region, framerate):
# '''We use the EQ set by NETEASE MUSIC, and we use ORDER-3 D1 SPLINE INTERPOLATION to simulate the filter function:
# f(250)=f'(250)=0;
# f(1000)=f'(1000)=0;
# f(500)=1,f'(500)=0'''
# '''We start with a linear transform of x'''
# '''The solution of the problem is:
# f1(x) = -2x^3+9x^2-12x+5, x = x0/250, 250<=x0<=500;
# f2(x) = 3/4x^3-9/4x^2+6x-4, x = 0/250, 500<=x0<=1000.
# '''
# left_frequency = np.fft.fft(left_channel)
# right_frequency = np.fft.fft(right_channel)
# abs_left = abs(left_frequency)
# abs_right = abs(right_frequency)
# length = left_channel.size
# freq = lambda i: i*framerate/(length*2)
# index = lambda freq: int(2*length/framerate*freq)
# #f1 = lambda x: 0.4*(-2*(x**3)+9*(x**2)-12*x+5)
# #f2 = lambda x: 0.4*(0.75*(x**3)-2.25*(x**2)+6*x-4)
# rate1 = 1
# rate2 = 0.8
# f1 = lambda x: rate1*(0.5*np.sin(np.pi*(x-1.5)) + 0.5)
# f2 = lambda x: rate1*(0.5*np.sin(0.5*np.pi*(x-1)) + 0.5)
# x250 = index(250)
# x500 = index(500)
# x1000 = index(1000)
# left_frequency = left_frequency * rate2
# right_frequency = right_frequency * rate2
# left_frequency[x250:x500] = [left_frequency[i]*(1+(2-2*rate2)*f1(freq(i)/250)) for i in range(x250, x500)]
# right_frequency[x250:x500] = [right_frequency[i]*(1+(2-2*rate2)*f1(freq(i)/250)) for i in range(x250, x500)]
# left_frequency[x500:x1000] = [left_frequency[i]*(1+(2-2*rate2)*f2(freq(i)/250)) for i in range(x500, x1000)]
# right_frequency[x500:x1000] = [right_frequency[i]*(1+(2-2*rate2)*f2(freq(i)/250)) for i in range(x500, x1000)]
# left_channel = np.fft.ifft(left_frequency)
# right_channel = np.fft.ifft(right_frequency)
# return left_channel, right_channel
if __name__ == '__main__':
sound = '/home/chuanlu/sound/HVC842379.wav'
pass_region = np.asarray([400, 500])
stop_region = np.asarray([150, 2500])
sound_filter(sound, pass_region, stop_region, set_eq)<file_sep>import os
import sys
rootdir = '/home/orcuslc/MED/TIMIT'
for parent, dirs, files in os.walk(rootdir):
for file in files:
print(file)
if file[:10] == 'index.html':
os.remove(os.path.join(parent, file))
<file_sep>import numpy as np
import wave
import matplotlib.pyplot as plt
import scipy.signal as signal
def segment_bandpass_filter(left, right, freq_low, freq_high, framerate):
length = len(left)
'''Sampling frequency = 2 * max frequency'''
low = int(freq_low/framerate*length*2)+1
high = int(freq_high/framerate*length*2)
left = np.fft.fft(left)
right = np.fft.fft(right)
left[:low] = 0.0
left[high:] = 0.0
right[:low] = 0.0
right[high:] = 0.0
left = np.fft.ifft(left)
right = np.fft.ifft(right)
return left, right
def noise_reduction(sound, freq_low = 499, freq_high = 3501, op = segment_bandpass_filter):
wav = wave.open(sound)
params = wav.getparams()
channels, sampwidth, framerate, frames = params[:4]
str_data = wav.readframes(frames)
wav.close()
wave_data = np.fromstring(str_data, dtype = np.short)
wave_data.shape = -1, 2
wave_data = wave_data.T
time = np.arange(0, frames) * (1.0/framerate)
left = wave_data[0]
length = len(left)
right = wave_data[1]
plt.subplot(221)
plt.plot(time, left)
plt.subplot(222)
plt.plot(time, right, c='g')
left, right = op(left, right, freq_low, freq_high, framerate)
plt.subplot(223)
plt.plot(time, left)
plt.subplot(224)
plt.plot(time, right, c='g')
plt.show()
wave_data = np.zeros(2*length, dtype = np.short)
wave_data[::2] = left
wave_data[1::2] = right
wave_data = wave_data.tostring()
f = wave.open('/home/chuanlu/test/HVC998004_changed.wav', 'wb')
f.setnchannels(channels)
f.setsampwidth(sampwidth)
f.setframerate(framerate)
f.writeframes(wave_data)
f.close()
def continuous_bandpass_filter(left, right, freq_low, freq_high, framerate):
pass_region = [0.075, 0.2]
stop_region = [0.05, 0.8]
pass_max_damp = 1
stop_min_damp = 80
b, a = signal.iirdesign(pass_region, stop_region, pass_max_damp, stop_min_damp)
w, h = signal.freqz(b, a)
new_left = signal.lfilter(b, a, left)
new_right = signal.lfilter(b, a, right)
return new_left, new_right
def naive_dsp(left, right, freq_low, freq_high, framerate):
low_pass = 0.05
low_stop = 0.1
high_pass = low_stop
high_stop = low_pass
pass_max_damp = 2
stop_min_damp = 40
b1, a1 = signal.iirdesign(low_pass, low_stop, pass_max_damp, stop_min_damp)
b2, a2 = signal.iirdesign(high_pass, high_stop, pass_max_damp, stop_min_damp)
left = signal.lfilter(b1, a1, left)
right = signal.lfilter(b1, a1, right)
new_left = left - right
new_right = left - right
left = signal.lfilter(b2, a2, new_left)
right = signal.lfilter(b2, a2, new_right)
return left, right
#def naive_naive_dsp(left, right, freq_low, freq_high, framerate):
if __name__ == '__main__':
sound = "/home/chuanlu/test/HVC998004.wav"
noise_reduction(sound, 300, 3000, continuous_bandpass_filter)<file_sep>#Word2Vec-API
This Server-Client structure is forked from https://github.com/3Top/word2vec-api/blob/master/word2vec-api.py, and was added some functions to satisfy our needs.
* Launching Service
```
python nserver.py --model /PATH/TO/MODEL --concept /PATH/TO/CONCEPT [--host host] [--port integer]
```
* Example Calls
* Direct Call
```
curl http://127.0.0.1:5000/word2vec/msc?word=apple
return: "fruit"
```
```
curl http://127.0.0.1:5000/word2vec/sc?word=apple
return: A list containing the sim('apple', attr) for attr in concept list
```
* Indirect Call:
Write the words in ```./words```, with each word in a line
```
python3 test.py method(sc or msc) /PATH/TO/WORDS /PATH/TO/RESULT(default: ./results)
return: the length of ./words ,total time cost
```
<!-- The result will be in ```./result``` -->
* Results
* When method is ```msc```:
For direct call, the result will be a string of the most similar word in the concepts.
For indirect call, the result will be in ```./results(default)``` or the input path. Each line contains the result of a word.
* When method is ```sc```:
For direct call, the result will be a list of similarity of the input word with each word in the concepts.
For indirect call, each line of the results file contains the result of a word.
* If the result of direct/indirect call is 0, that means the input word is not in the model's vocabulary.<file_sep># List all the files and save to a list
import os
<file_sep>import nltk
import sys
<file_sep>import os
import sys
import subprocess
from change_freq import change_frequency
from filt import *
import re
import time
framerate = 8000
kaldi_dir = '/home/orcuslc/MED/kaldi'
nnet = '/home/orcuslc/MED/nnet_a_gpu_online'
graph = '/home/orcuslc/MED/graph'
online2bin = 'online2-wav-nnet2-latgen-threaded'
def timeit(func):
def wrapper(*args, **kw):
time1 = time.time()
result = func(*args, **kw)
time2 = time.time()
print('Total time:', str(time2-time1), 's\n')
return result
return wrapper
def get_info(video, video_name, video_dir):
print(video_name + ' started!')
cmd = 'mediainfo ' + video_dir + video + ' |grep Duration'
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
a = p.wait()
(stdoutput, erroutput) = p.communicate()
stdoutput = stdoutput.decode('utf-8').split('\n')[0]
print(stdoutput)
return stdoutput
def dump_wav(video, video_name, video_dir, sound_dir):
cmd = 'mplayer ' + video_dir + video + ' -novideo -ao pcm:file="' + sound_dir + video_name + '.wav' + '" -srate ' + str(framerate)
# print(cmd)
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
a = p.wait()
(stdoutput, erroutput) = p.communicate()
print(video_name + ' dump succeeded!')
sound = sound_dir + video_name + '.wav'
sound_filter(sound, [300, 1000], [200, 2000], set_eq)
print(video_name + ' filting succeeded!')
return sound
# def handle_sound(sound, sound_name, tmp_dir):
# sound_filter(sound, [300, 1000], [200, 2000], set_eq)
def asr_run(sound, sound_name, txt_dir, log_dir, start_time):
# change_frequency(sound, framerate)
sound_filter(sound, [300, 1000], [200, 2000], set_eq)
online_decode_dir = kaldi_dir + '/src/online2bin/' + online2bin
param = ' --do-endpointing=false' + \
' --config=' + nnet + '/conf/online_nnet2_decoding.conf' + \
' --max-active=7000 --beam=15.0 --lattice-beam=6.0 --acoustic-scale=0.1' + \
' --word-symbol-table=' + graph + '/words.txt ' + \
nnet + '/final.mdl ' + graph + '/HCLG.fst ' + \
'"ark:echo utterance-id1 utterance-id1|"' + \
' "scp:echo utterance-id1 ' + sound + '|" ' + \
'ark:/dev/null'
p = subprocess.Popen(online_decode_dir + param, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
a = p.wait()
(stdoutput, erroutput) = p.communicate()
stdoutput = stdoutput.decode('utf-8')
# print(stdoutput)
# try:
res = re.findall(r'utterance-id1\s.+', stdoutput)[1][14:] + '\n'
# except IndexError:
# res = '\n'
f = open(txt_dir+sound_name+'.txt', 'w')
f.write(res)
f.close()
end_time = time.time()
f2 = open(log_dir + sound_name+'.log', 'w')
# f2.write(duration+'\n')
f2.write('Time cost: '+str(end_time - start_time)+'s\n')
f2.write(stdoutput)
f2.close()
# delete_command = 'rm -f '+ sound
# p2 = subprocess.Popen(delete_command, shell=True)
# b = p2.wait()
print(sound_name + ' Completed!')
# @timeit
# def run(video, video_name, video_dir, sound_dir, txt_dir, log_dir):
# start_time = time.time()
# duration = get_info(video, video_name, video_dir)
# sound = dump_wav(video, video_name, video_dir, sound_dir)
# asr_run(sound, video_name, txt_dir, log_dir, duration, start_time)
# # return duration
if __name__ == '__main__':
sound = sys.argv[1]
sound_name = sys.argv[2]
txt_dir = sys.argv[3]
log_dir = sys.argv[4]
asr_run(sound, sound_name, txt_dir, log_dir, duration='1', start_time=1)
<file_sep># Dump sound
import os, sys, subprocess, re, time
# from filt import *
# from change_freq import change_frequency
index = 0
framerate = 8000
sound_dir = '../sound/'
video_dir = '../'
log_dir = '../log/'
def get_info(video, video_name, video_dir):
print(video_name + ' started!')
cmd = 'mediainfo ' + video_dir + video + ' |grep Duration'
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
a = p.wait()
(stdoutput, erroutput) = p.communicate()
stdoutput = stdoutput.decode('utf-8').split('\n')[0]
print(stdoutput)
return stdoutput
def dump_wave(video, video_name, video_dir, sound_dir):
cmd = 'mplayer ' + video_dir + video + ' -novideo -ao pcm:file="' + sound_dir + video_name + '.wav' + '" -srate ' + str(framerate)
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
a = p.wait()
(stdoutput, erroutput) = p.communicate()
print(video_name + ' dump succeeded!')
# sound = sound_dir + video_name + '.wav'
if __name__ == '__main__':
root_dir = sys.argv[1]
start_time = time.time()
count = 0
total_minute = 0
total_second = 0
for parent, dirs, files in os.walk(root_dir):
for file in files:
count += 1
filename = file[:-4]
duration = get_info(file, filename, video_dir)
dump_wave(file, filename, video_dir, sound_dir)
if len(duration) == 3:
if 'mn' in duration[1]:
minute = int(duration[1][:-2])
second = int(duration[2][:-1])
elif 's' in duration[1]:
minute = 0
second = int(duration[1][:-1])
ms = int(duration[2][:-2])
second += ms/1000
elif len(duration) == 2:
if 'mn' in duration[1]:
minute = int(duration[1][:-2])
second = 0
elif 's' in duration[1]:
minute = 0
second = int(duration[1][:-1])
else:
minute = second = 0
else:
minute = second = 0
total_minute += minute
total_second += second
total_duration = total_minute + total_second/60.0
end_time = time.time()
f = open(log_dir+'DUMP_REPORT-'+str(index)+'.log', 'w')
result = str(count) + ' Videos, Total Duration ' + str(total_duration) + ' minutes, Total DUMP Time Cost ' + str((end_time - start_time)/60.0) + ' minutes.'
f.write(result)
f.close()<file_sep>import numpy as np
import matplotlib.pyplot as plt
f11 = lambda x: 0.4*(-2*(x**3)+9*(x**2)-12*x+5)
f12 = lambda x: 0.4*(0.75*(x**3)-2.25*(x**2)+6*x-4)
f21 = lambda x: 0.5*np.sin(np.pi*(x-1.5)) + 0.5
f22 = lambda x: 0.5*np.sin(0.5*np.pi*(x-1)) + 0.5
x1 = np.linspace(1, 2, num = 1e6)
x2 = np.linspace(2, 4, num = 2*1e6)
y11 = [f11(i) for i in x1]
y12 = [f12(i) for i in x2]
y21 = [f21(i) for i in x1]
y22 = [f22(i) for i in x2]
plt.subplot(221)
plt.plot(x1, y11)
plt.subplot(222)
plt.plot(x2, y12)
plt.subplot(223)
plt.plot(x1, y21)
plt.subplot(224)
plt.plot(x2, y22)
plt.show()<file_sep># Filter
import numpy as np
import wave
import scipy.signal as signal
import matplotlib.pyplot as plt
def sound_filter(sound, pass_region, stop_region, op):
wav = wave.open(sound)
params = wav.getparams()
nchannels, sampwidth, framerate, nframes = params[:4]
string_data = wav.readframes(nframes)
wav.close()
wave_data = np.fromstring(string_data, dtype=np.short)
wave_data.shape = -1, 2
wave_data = wave_data.T
time = np.arange(0, nframes) * (1.0/framerate)
left_channel = wave_data[0]
wave_length = left_channel.size
right_channel = wave_data[1]
#plt.subplot(221)
#plt.plot(time, left_channel)
#plt.subplot(222)
#plt.plot(time, right_channel, c='g')
new_left_channel, new_right_channel = op(left_channel, right_channel, pass_region, stop_region, framerate)
wave_data = np.zeros(2*wave_length, dtype=np.short)
wave_data[::2] = new_left_channel
wave_data[1::2] = new_right_channel
wave_data = wave_data.tostring()
f = wave.open(sound[:-4]+'_changed.wav', 'wb')
f.setnchannels(nchannels)
f.setsampwidth(sampwidth)
f.setframerate(framerate)
f.writeframes(wave_data)
f.close()
#plt.subplot(223)
#plt.plot(time, new_left_channel)
#plt.subplot(224)
#plt.plot(time, new_right_channel, c='g')
#plt.show()
def butterworth_bandpass_filter(left_channel, right_channel, pass_region, stop_region, framerate):
pass_region = 2*pass_region/framerate
stop_region = 2*stop_region/framerate
#print(pass_region, stop_region)
pass_max_damp = 2
stop_min_damp = 20
b, a = signal.iirdesign(pass_region, stop_region, pass_max_damp, stop_min_damp)
new_left_channel = signal.lfilter(b, a, left_channel)
new_right_channel = signal.lfilter(b, a, right_channel)
return new_left_channel, new_right_channel
def fft_bandpass_filter(left_channel, right_channel, pass_region, stop_region, framerate):
length = left_channel.size
'''Notice: Sampling frequency = 2*max signal frequency'''
low = int(pass_region[0]/framerate*length*2)+1
high = int(pass_region[1]/framerate*length*2)
left_channel = np.fft.fft(left_channel)
right_channel = np.fft.fft(right_channel)
left_channel[:low] = .0
left_channel[high:] = .0
right_channel[:low] = .0
right_channel[high:] = .0
left_channel = np.fft.ifft(left_channel)
right_channel = np.fft.ifft(right_channel)
return left_channel, right_channel
def set_eq(left_channel, right_channel, pass_region, stop_region, framerate):
'''We use the EQ set by NETEASE MUSIC, and we use ORDER-3 D1 SPLINE INTERPOLATION to simulate the filter function:
f(250)=f'(250)=0;
f(1000)=f'(1000)=0;
f(500)=1,f'(500)=0'''
'''We start with a linear transform of x'''
'''The solution of the problem is:
f1(x) = -2x^3+9x^2-12x+5, x = x0/250, 250<=x0<=500;
f2(x) = 3/4x^3-9/4x^2+6x-4, x = 0/250, 500<=x0<=1000.
'''
left_frequency = np.fft.fft(left_channel)
right_frequency = np.fft.fft(right_channel)
abs_left = abs(left_frequency)
abs_right = abs(right_frequency)
length = left_channel.size
freq = lambda i: i*framerate/(length*2)
index = lambda freq: int(2*length/framerate*freq)
#f1 = lambda x: 0.4*(-2*(x**3)+9*(x**2)-12*x+5)
#f2 = lambda x: 0.4*(0.75*(x**3)-2.25*(x**2)+6*x-4)
rate1 = 1
rate2 = 0.8
f1 = lambda x: rate1*(0.5*np.sin(np.pi*(x-1.5)) + 0.5)
f2 = lambda x: rate1*(0.5*np.sin(0.5*np.pi*(x-1)) + 0.5)
x250 = index(250)
x500 = index(500)
x1000 = index(1000)
left_frequency = left_frequency * rate2
right_frequency = right_frequency * rate2
left_frequency[x250:x500] = [left_frequency[i]*(1+(2-2*rate2)*f1(freq(i)/250)) for i in range(x250, x500)]
right_frequency[x250:x500] = [right_frequency[i]*(1+(2-2*rate2)*f1(freq(i)/250)) for i in range(x250, x500)]
left_frequency[x500:x1000] = [left_frequency[i]*(1+(2-2*rate2)*f2(freq(i)/250)) for i in range(x500, x1000)]
right_frequency[x500:x1000] = [right_frequency[i]*(1+(2-2*rate2)*f2(freq(i)/250)) for i in range(x500, x1000)]
left_channel = np.fft.ifft(left_frequency)
right_channel = np.fft.ifft(right_frequency)
return left_channel, right_channel
if __name__ == '__main__':
sound = '/home/chuanlu/test/HVC999998.wav'
pass_region = np.asarray([400, 500])
stop_region = np.asarray([150, 2500])
sound_filter(sound, pass_region, stop_region, set_eq)<file_sep>#!/usr/bin/bash
cd training-1/txt/ && ls -l|wc -l >> ../../count.txt
cd ../../training-2/txt/ && ls -l|wc -l >> ../../count.txt
cd ../../test-1/txt/ && ls -l|wc -l >> ../../count.txt
cd ../../test-2/txt/ && ls -l|wc -l >> ../../count.txt
cd ../../test-3/txt/ && ls -l|wc -l >> ../../count.txt
cd ../../ && cat count.txt <file_sep>def set_eq(left, right, p_r, s_r, framerate):
rate1 = 1
rate2 = 0.8
rate3 = (2-2*rate2)
left_freq = np.fft.fft(left) * rate2
right_freq = np.fft.fft(right) * rate2
length = left.size
f1 = np.vectorize(lambda x: rate1*(0.5*np.sin(np.pi*(x-1.5)) + 0.5))
f2 = np.vectorize(lambda x: rate1*(0.5*np.sin(0.5*np.pi*(x-1)) + 0.5))
freq = np.vectorize(lambda i: i*framerate/(length*2))
index = lambda freq: int(2*length/framerate*freq)
x250 = index(250)
x500 = index(500)
x1000 = index(1000)
xx1 = f1(freq(np.asarray(range(x250, x500))))
xx2 = f2(freq(np.asarray(range(x500, x1000))))
left_freq[x250:x500] = left_freq[x250:x500] * (1+rate3*xx1)
right_freq[x250:x500] = right_freq[x250:x500] * (1+rate3*xx1)
left_freq[x500:x1000] = left_freq[x500:x1000] * (1+rate3*xx2)
right_freq[x500:x1000] = right_freq[x500:x1000] * (1+rate3*xx2)
left = np.fft.ifft(left_freq)
right = np.fft.ifft(right_freq)
return left, right<file_sep>import os
path = '/home/orcuslc/MED/TIMIT'
def rename_dir(path):
for filename in os.listdir(path):
oldpath = path+'/'+filename
newpath = path+'/'+filename.upper()
if os.path.isdir(oldpath):
os.rename(oldpath, newpath)
rename_dir(newpath)
rename_dir(path)
<file_sep># Handle_words:
# The fusion of ../nltk_extract/extract_keywords.py and ./test.py
import sys, os
sys.path.insert(0, '..')
from time import time as t
# from nltk_extract.extract_keywords import extract_
from test import word2vec_
# from nltk_extract.extract_stem import *
method = 'sc'
# method = sys.argv[1]
# sentence_path = sys.argv[2]
keywords_path = sys.argv[2:]
# sentence_name = sys.argv[3]
name_list = [item[-13:] for item in keywords_path]
# tmp_path = sys.argv[4]
result_path = sys.argv[1]
def run(keywords_path, name_list, result_path):
# print sentence_path+sentence_name
# t1 = t()
# extract_(sentence_path+sentence_name, tmp_path+sentence_name)
# t2 = t()
keywords_list = []
for keywords in keywords_path:
with open(keywords_path) as f:
keywords_list.append(f.read().split('\n'))
word2vec_(method, keywords_list, name_list, result_path)
# t3 = t()
# print t2-t1, t3-t1
# def run_(sentence_path, result_path):
# files = os.listdir(sentence_path)
# extract_(sentence_path, result_path)
if __name__ == '__main__':
s = t()
run(sentence_path, sentence_name, result_path)
e = t()
print(e-s)<file_sep>import sys, time, subprocess
from nltk_extract.extract_stem import *
def word2vec(method, word_list, name_list, result_path):
start = time.time()
# word_path = './words'
# result_path = './results'
# with open(word_path, 'r') as f:
# # As the extract_keywords.py would bring another '\n' in the end.
# words = f.read().split('\n')[:-1]
# # print(len(words))
# f.close()
result_list = []
if method == 'msc':
for words in word_list:
result = []
for word in words:
if word == 'noise':
continue
cmd = 'curl http://127.0.0.1:5000/word2vec/msc?word=' + word
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
r = p.wait()
(stdoutput, erroutput) = p.communicate()
stdoutput = stdoutput.decode('utf-8').split('\n')[-2]
# print(stdoutput.split('\n'))
if stdoutput == '0':
word = extract(word)
cmd = 'curl http://127.0.0.1:5000/word2vec/msc?word=' + word
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
r = p.wait()
(stdoutput, erroutput) = p.communicate()
stdoutput = stdoutput.decode('utf-8').split('\n')[-2]
result.append(stdoutput)
result_list.append(result)
elif method == 'sc':
for words in word_list:
result = []
for word in words:
if word == 'noise':
continue
cmd = 'curl http://127.0.0.1:5000/word2vec/sc?word=' + word
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
r = p.wait()
(stdoutput, erroutput) = p.communicate()
stdoutput = stdoutput.decode('utf-8').split('\n')[-2]
# print(stdoutput.split('\n'))
if stdoutput == '0':
t1 = time.time()
word = extract(word)
t2 = time.time()
print t2-t1
cmd = 'curl http://127.0.0.1:5000/word2vec/sc?word=' + word
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
r = p.wait()
(stdoutput, erroutput) = p.communicate()
stdoutput = stdoutput.decode('utf-8').split('\n')[-2]
result.append(stdoutput)
result_list.append(result)
# print(result)
for index in range(len(name_list)):
with open(result_path+name_list[index], 'w') as f:
for item in result_list[index]:
f.write(item+'\n')
f.close()
# with open(result_path, 'w') as f:
# for item in result:
# f.write(item+'\n')
# f.close()
# end = time.time()
# print(end - start)
def word2vec_(method, key_words, result_path):
start = time.time()
key_word_list = []
with open(word_path, 'r') as f:
# As the extract_keywords.py would bring another '\n' in the end.
words = f.read().split('\n')[:-1]
key_word_list.append(words)
# print(len(words))
f.close()
result = []
if method == 'msc':
for word in words:
cmd = 'curl http://127.0.0.1:5000/word2vec/msc?word=' + word
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
r = p.wait()
(stdoutput, erroutput) = p.communicate()
stdoutput = stdoutput.decode('utf-8').split('\n')[-2]
# print(stdoutput.split('\n'))
if stdoutput == '0':
word = extract(word)
cmd = 'curl http://127.0.0.1:5000/word2vec/msc?word=' + word
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
r = p.wait()
(stdoutput, erroutput) = p.communicate()
stdoutput = stdoutput.decode('utf-8').split('\n')[-2]
result.append(stdoutput)
elif method == 'sc':
for word in words:
cmd = 'curl http://127.0.0.1:5000/word2vec/sc?word=' + word
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
r = p.wait()
(stdoutput, erroutput) = p.communicate()
stdoutput = stdoutput.decode('utf-8').split('\n')[-2]
# print(stdoutput.split('\n'))
if stdoutput == '0':
t1 = time.time()
word = extract(word)
t2 = time.time()
print t2-t1
cmd = 'curl http://127.0.0.1:5000/word2vec/sc?word=' + word
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
r = p.wait()
(stdoutput, erroutput) = p.communicate()
stdoutput = stdoutput.decode('utf-8').split('\n')[-2]
result.append(stdoutput)
# print(result)
with open(result_path, 'w') as f:
for item in result:
f.write(item+'\n')
f.close()
end = time.time()
if __name__ == '__main__':
method = sys.argv[1]
word_path = sys.argv[2]
if len(sys.argv) == 4:
result_path = sys.argv[3]
else:
result_path = './results'
word2vec(method, word_path, result_path)<file_sep>import wave
def change_frequency(sound, framerate):
wav = wave.open(sound, 'rb')
params = wav.getparams()
channels, sampwidth, original_framerate, frames = params[:4]
str_data = wav.readframes(frames)
wav.close()
wav2 = wave.open(sound, 'wb')
wav2.setnchannels(channels)
wav2.setsampwidth(sampwidth)
wav2.setframerate(framerate)
wav2.writeframes(str_data)
wav2.close()
# sound = sys.argv[1]
# framerate = sys.argv[2]
# change_frequency(sound, framerate)
if __name__ == '__main__':
framerate = 8000
sound = 'Downloads/male.wav'
change_frequency(sound, framerate)
wav = wave.open(sound[:-4]+'_changed.wav', 'rb')
params = wav.getparams()
channels, sampwidth, original_framerate, frames = params[:4]
print(original_framerate)
<file_sep>sentence_path = ./s
<file_sep>#!/usr/bin/bash
rm count.txt
cd training-1/txt/ && ls -l|wc -l >> ../../count.txt
cd ../../training-2/txt/ && ls -l|wc -l >> ../../count.txt
cd ../../test-1/txt/ && ls -l|wc -l >> ../../count.txt
cd ../../test-2/txt/ && ls -l|wc -l >> ../../count.txt
cd ../../test-3/txt/ && ls -l|wc -l >> ../../count.txt
cd ../../ && cat count.txt
<file_sep>from nltk.stem import *
wnl = WordNetLemmatizer()
# prt = porter.PorterStemmer()
def extract(word):
return wnl.lemmatize(word) | 484a076a7ea07e204b1fd76a5228e2493e3fb1e4 | [
"Markdown",
"Python",
"Shell"
] | 24 | Python | Orcuslc/MED2016-ASR | 6121974e93f29ba426eb61e2e1c63414bdbeb7c0 | db2ef278de7cb6007a0997d6437cecdd81d4c975 |
refs/heads/main | <repo_name>shoptsc/scelloo_leaveapp_backend<file_sep>/README.md
# scelloo_leaveapp_backend
https://scelloo-leaveapp.herokuapp.com/
http://scelloo-leaveapp.herokuapp.com/absencehistory
<file_sep>/routes/leaveRoute.js
const router = require("express").Router();
const {showLeave} = require("../config/leaveConfig");
const {postLeave} = require("../config/leaveConfig");
router.get("/leave", showLeave);
router.post("/leave", postLeave);
module.exports = router<file_sep>/seeder.js
require("dotenv/config");
const mongoose = require("mongoose");
const leaveData = require("./data/leaveData");
const Leave = require("./models/leaveDetails");
const connectDB = require("./db");
connectDB();
const importData = async () =>{
try{
await Leave.deleteMany()
await Leave.insertMany(leaveData)
console.log("Data Imported!")
process.exit()
}catch(error){
console.error(`${error}`)
process.exit(1)
}
}
const destroyData = async () =>{
try{
await Leave.deleteMany()
console.log("Data Destroyed!")
process.exit()
}catch(error){
console.error(`${error}`)
process.exit(1)
}
}
if(process.argv[2] === "-d"){
destroyData()
}else{
importData()
}<file_sep>/data/leaveData.js
module.exports = [
{
leave: "Paid Annual Leave",
details: "Vacation",
start: "11-Dec-2019",
end: "12-Dec-2019",
days: 2,
allowance: "Yes",
delegate: "<NAME>",
},
{
leave: "Exams",
details: "Vacation",
start: "13-Dec-2019",
end: "14-Dec-2019",
days: 1,
allowance: "No",
delegate: "<NAME>",
},
{
leave: "Paternity Leave",
details: "New Birth",
start: "15-Dec-2019",
end: "17-Dec-2019",
days: 3,
allowance: "Yes",
delegate: "<NAME>",
},
{
leave: "Sick Leave",
details: "Health",
start: "17-Dec-2019",
end: "18-Dec-2019",
days: 2,
allowance: "Yes",
delegate: "<NAME>",
},
]
| 6371c11b08e3f3cac21ed35544822cc1ddc28395 | [
"Markdown",
"JavaScript"
] | 4 | Markdown | shoptsc/scelloo_leaveapp_backend | bc8e423dd0beb90998b6ea9dfbeb012053021f1f | 808fbb9fd48b7c8888b5f8b3181aceaeb6ba7db6 |
refs/heads/master | <file_sep>export const symptomsDataAdult = [
{
symptom: 'Ketombe',
pepOil:
'Lavender , Lemon, Peppermint (bisa pilih atau dicampur) Cara 1. 1-2 tetes, massage di kulit kepala 30 menit sblm keramas, lalu keramas spt biasa. Cara 2. 1-2 tetes di shampoo, diamkan 1-3 menit di kulit kepala yg sdh basah, keramas spt biasa. ',
nonPepOil:
'Rosemary, Wintergreen, Tea Tree, Cedarwood, Cypress. Cara 1&2 idem.',
blend:
'Blend 1. Dalam botol spray 30 ml : + 5 Lemon + 3 Lavender + 3 Rosemary + 3 Tea Tree. Tambahkan air minum atau witch hazel hingga penuh. Spray 2x sehari di kulit kepala.',
supplement: 'Sulfurzyme',
personalCare:
'Pilih Shampoo senatural mungkin (minimal sintetiks) Gunakan Seedling Shampoo',
},
{
symptom: 'Rambut rontok',
pepOil:
'Lavender , Lemon, Peppermint (bisa pilih atau dicampur) Cara 1. 1-2 tetes, massage di kulit kepala 30 menit sblm keramas, lalu keramas spt biasa. Cara 2. 1-2 tetes di shampoo, diamkan 1-3 menit di kulit kepala yg sdh basah, keramas spt biasa. ',
nonPepOil:
'Rosemary, Cedarwood, Thyme, Ylang-Ylang, Clary Sage. Cara 1&2 idem.',
blend:
'Blend 1. Dalam botol spray 30 ml : + 5 Lavender + 5 Rosemary + 3 Thyme. Tambahkan air minum atau witch hazel hingga penuh. Spray 2x sehari di kulit kepala.',
supplement: 'Sulfurzyme',
personalCare:
'Pilih Shampoo senatural mungkin (minimal sintetiks) Gunakan Seedling Shampoo',
},
{
symptom: 'Rambut pitak',
pepOil:
'Lavender. Cara : oles langsung di area pitak, 1x/hari. Dilute bila perlu atau area luas.',
nonPepOil: 'Thyme, Rosemary, Cedarwood. Cara : idem',
blend:
'Blend 1 : Dalam botol dropper 5 ml : + 2 Cedarwood + 3 Lavender + 2 Thyme + 3 Rosemary. Top up dgn Mirah Hair Oil, atau Tamanu Oil. Oles 2x sehari di area pitak.',
supplement: 'Sulfurzyme',
personalCare:
'Pilih Shampoo senatural mungkin (minimal sintetiks) Gunakan Seedling Shampoo',
},
{
symptom: 'Rambut beruban',
pepOil:
'Lavender, Frankincense. Cara: 1 tetes di shampoo natural di tangan, lakukan setiap keramas.',
nonPepOil:
'Rosemary, Sandalwood, <NAME>, (Thyme +carrier oil), Ginger, Black Seed. Cara: Alternatif bikin Hair Serum. 5ml Black seed oil, 5 tetes EO pilihan, pake roll on, langsung oles di kulit kepala di malam hari, esok pagi keramas.',
blend:
'15ml botol kaca spray: isi 7 tetes lavender, 7 tetes rosemary, semprot ke kulit dan batang rambut.',
supplement: 'NingXia Red, Sulfurzyme, Omegagize',
personalCare:
'Pilih Shampoo senatural mungkin (minimal sintetiks) Gunakan Seedling Shampoo',
},
{
symptom: 'Kulit keriput (wrinkle)',
pepOil:
'Frankincense, Lavender, Copaiba. Cara 1: Buat Face Serum. Botol 5ml diisi 3/4 dengan carrier oil yang sesuai dengan kondisi kulit (misal: avocado oil / argan oil), Lalu teteskan EO masing-masing 2-3 tetes. Gunakan pagi dan malam di kulit yang sudah bersih. Cara 2: Teteskan 1 tetes masing-masing ke serum muka yang dimiliki di tangan. Gunakan pagi malam',
nonPepOil: 'Patchouli, Carrot Seed, Helichrysum, Geranium. Cara 1 & 2 sama',
blend:
'15 ml botol isi dengan Helichryum (3), Geranium (3), Lavnder (3), Frankincense (3), tambahkan di Carrier oil yang cocok dengan kondisi kulit (avocado oil, argan oil, dst) hingga 3/4 botol (tidak perlu penuh menghindari tumpah).',
supplement: 'NingXia Red, Sulfurzyme, Omegagize',
personalCare: 'Gunakan Bloom Essence sebagai serum muka',
},
{
symptom: 'Jerawat',
pepOil:
'Lavender, Frankincense, Lemon, Purification, Copaiba. Cara: Jerawat besar, bisa langsung pilih 1 oil dan ditotol di lokasi jerawat dengan tangan bersih. Ambil oil dari pinggir leher botol, jangan dari bolongan tengah botol (jadi ambil sedikit saja), atau gunakan cotton bud.',
nonPepOil: 'Tea Tree, Kunzea, Melrose. Cara sama.',
blend:
'5ml botol teteskan Melaleuca (3), Lavender (3), Copaiba (3), Frankincense (3), tambahkan Carrier oil yang cocok dengan kondisi kulit (avocado oil, argan oil, dst) hingga 3/4 botol (tidak perlu penuh menghindari tumpah).',
supplement: 'NingXia Red, Sulfurzyme, Omegagize',
personalCare:
'Gunakan Bloom Series untuk Facial Wash, Essence dan Lotion. Untuk jerawat kecil-kecil (baik muka dan punggung) bisa gunakan Charcoal Bar Soap.',
},
{
symptom: 'Flek hitam (dark spot)',
pepOil:
'Lavender, Lemon, Frankincence, Copaiba. Cara 1: Pilih salah satu dan teteskan kedalam serum muka yang digunakan pagi dan malam. Cara 2: Bikin sendiri Face Serum (cek DIY)',
nonPepOil: 'Helichrysum, myyrh. Cara sama.',
blend:
'5ml botol teteskan (3) Helichrysum, (3) Frankincense, (3) Copaiba, tambahkan Carrier oil yang cocok dengan kondisi kulit (Avocado oil, argan oil, dst) hingga 3/4 botol (tidak perlu penuh menghindari tumpah).',
supplement: 'NingXia Red, Sulfurzyme, Omegagize',
personalCare: 'Gunakan Bloom Series untuk Facial Wash, Essence dan Lotion.',
},
{
symptom: 'Mata lelah',
pepOil:
'Frankincense. Cara: Eye cupping. Teteskan 1 tetes ke telapak tangan, gosok dengan kedua tangan. Tutup mata dengan tangan membuat posisi seperti tenda. Lalu buka mata dan lirik mata ke kanan kiri atas bawah. Biarkan uap nya terkena mata (agak perih sedikit)',
nonPepOil: 'Carrot Seed, Lemongrass, Cypress. Cara sama.',
blend:
'5ml botol teteskan (3) Cypress, (3) Lemongrass (3) Frankincense, tambahkan Carrier oil secukupnya, tutup dengan aromaglide roller (atau gunakan botol roll on). Oleskan ke area mengelilingi mata.',
supplement: 'Ningxia Red, Illumineyes',
personalCare: 'Not available',
},
{
symptom: 'Mata merah',
pepOil:
'Frankincense. Cara: Eye cupping. Teteskan 1 tetes ke telapak tangan, gosok dengan kedua tangan. Tutup mata dengan tangan membuat posisi seperti tenda. Lalu buka mata dan lirik mata ke kanan kiri atas bawah. Biarkan uap nya terkena mata (agak perih sedikit).',
nonPepOil: 'Myrrh, Sacred Frankincence. Cara sama.',
blend:
'5ml botol teteskan (3) Copaiba (3) Lavender (3) Frankincense, tambahkan Carrier oil secukupnya, tutup dengan aromaglide roller (atau gunakan botol roll on). Oleskan ke area mengelilingi mata.',
supplement: 'Illumineyes (sesuai dosis).',
personalCare: 'Not available',
},
{
symptom: 'Sakit kepala',
pepOil:
'Peppermint, Panaway, Frankincense, Lavender. Oles salah satu oil di area sakit kepala & sekitarnya. Ulangi sering sesuai kebutuhan. Dilute bila perlu.',
nonPepOil: 'Aroma Seiz, Deep Relief, Relieve It. Cara sama.',
blend:
'5ml botol teteskan (3) Peppermint (3) Panaway (3) Lavender, tambahkan Carrier oil secukupnya, tutup dengan aromaglide roller (atau gunakan botol roll on). Oleskan ke area sesuai kebutuhan.',
supplement: 'Not available',
personalCare: 'Not available',
},
{
symptom: 'Migraine',
pepOil:
'Peppermint, Panaway, Lavender. Oles salah satu oil di area migraine. Ulangi sering sesuai kebutuhan. Dilute bila perlu.',
nonPepOil: 'M-Grain, Basil, Eucalyptus, Panaway, Deep Relief. Cara sama.',
blend:
'5ml botol teteskan (3) Peppermint (3) Panaway (3) Lavender, tambahkan Carrier oil secukupnya, tutup dengan aromaglide roller (atau gunakan botol roll on). Oleskan ke area sesuai kebutuhan.',
supplement: 'Not available',
personalCare: 'Not available',
},
{
symptom: 'Sulit tidur (insomnia)',
pepOil:
'Lavender, Stress away. 1. Diffuse salah satu oil @5 tetes. 2. Diffuse ke-2 oil @3 tetes. 3. Hand cupping : 1 tetes oil di telapak tangan, gosok di ke-2 telapak tangan, buat tenda menutup hidung dan hirup 5-15 menit.',
nonPepOil:
'Cedarwood, Vetiver, Rutavala, Bergamot, Citrus Fresh, Peace & Calming. Cara sama.',
blend:
'5ml botol teteskan (5) Lavender (5) Stress away (3) Lavender, tambahkan Carrier oil secukupnya, tutup dengan aromaglide roller (atau gunakan botol roll on). Oleskan ke area kepala sesuai kebutuhan.',
supplement: 'Sleep Essence (sesuai dosis).',
personalCare: 'Not available',
},
{
symptom: 'Konsentrasi',
pepOil:
'Peppermint, Lemon : 1. Diffuse tiap oil @3 tetes. 2. Inhaler tiap oil @3-5 tetes, hirup bergantian ke2 lubang hidung @1-2 menit, selama total 5-15 menit.',
nonPepOil: 'Rosemary, Cedarwood, Basil, Lavender, Scent Wise. Cara sama.',
blend:
'5ml botol teteskan (3) Peppermint (3) Lemon (3) Rosemary tambahkan Carrier oil secukupnya, tutup dengan aromaglide roller (atau gunakan botol roll on). Oleskan ke area sesuai kebutuhan.',
supplement: 'Mind Wise (sesuai dosis)',
personalCare: 'Not available',
},
{
symptom: 'Sakit otot (pegal)',
pepOil:
'Lavender, Panaway, Peppermint. Oleskan pada bagian yang sakit. Dilute sesuai kebutuhan.',
nonPepOil:
'Marjoram, Idaho Grand Fir, Cypress, Kunzea, Deep Relief, Relieve It, Wintergreen, Rosemary. Oles pada bagian yang sakit. Dilute sesuai kebutuhan.',
blend:
'Pine (5) + Rosemary (4) + Ginger (4) + Vetiver (2) + V6 di botol 10 ml, oles di bagian yang sakit.',
supplement: 'Agilease, BLM (sesuai dosis)',
personalCare: 'Not available',
},
{
symptom: 'Sakit otot (kram)',
pepOil:
'Lavender, Panaway, Peppermint. Oleskan pada bagian yang sakit. Dilute sesuai kebutuhan.',
nonPepOil:
'Marjoram, Idaho Grand Fir, Cypress, Kunzea, Deep Relief, Relieve It, Wintergreen, Rosemary. Oles pada bagian yang sakit. Dilute sesuai kebutuhan.',
blend:
'Peppermint (10) + Panaway (10) + Valor (10) + Lavender (5) + V6 di botol 15 ml, oles di bagian yang sakit.',
supplement: 'Agilease, BLM (sesuai dosis)',
personalCare: 'Not available',
},
{
symptom: 'Sakit pinggang',
pepOil:
'Lavender, Panaway, Peppermint. Oleskan pada bagian yang sakit. Dilute sesuai kebutuhan.',
nonPepOil:
'Marjoram, Idaho Grand Fir, Cypress, Kunzea, Deep Relief, Relieve It, Wintergreen, Rosemary. Oles pada bagian yang sakit. Dilute sesuai kebutuhan.',
blend:
'Pine (5) + Rosemary (4) + Ginger (4) + Vetiver (2) + V6 di botol 10 ml, oles di bagian yang sakit.',
supplement: 'Agilease, BLM (sesuai dosis)',
personalCare: 'Not available',
},
{
symptom: 'Keseleo (terkilir)',
pepOil:
'Copaiba, Lavender, Panaway, Peppermint. Oleskan pada bagian yang sakit. Dilute sesuai kebutuhan.',
nonPepOil:
'Marjoram, Idaho Grand Fir, Cypress, Kunzea, Deep Relief, Relieve It, Wintergreen, Rosemary. Oles pada bagian yang sakit. Dilute sesuai kebutuhan.',
blend:
'Lavender (3) + Marjoram (3) + Cypress (3) + Peppermint (5) + V6 di botol 10 ml, oles di bagian yang sakit',
supplement: 'Agilease, BLM (sesuai dosis)',
personalCare: 'Not available',
},
{
symptom: 'Sakit pada sendi (arthritis)',
pepOil:
'Copaiba, Frankincense, Lavender, Peppermint. Oles pada bagian yang sakit. Dilute sesuai kebutuhan.',
nonPepOil:
'Rosemary, Marjoram, Cypress, Wintergreen, Kunzea, Idaho Grand Fir. Oles pada bagian yang sakit. Dilute sesuai kebutuhan.',
blend:
'Lavender (3) + Marjoram (3) + Cypress (3) + Peppermint (5) + V6 di botol 10 ml, oles di bagian yang sakit',
supplement: 'Agilease, BLM, Sulfurzyme (sesuai dosis)',
personalCare: 'Not available',
},
{
symptom: 'Flu',
pepOil:
'Peppermint - Lavender - Lemon : untuk difuse bisa dicampurkan dengan perbandingan 1:1, total 6 -8 tetes, di oles kan pada dada, leher atau telapak kaki, dilute sesuai kebutuhan, bisa dicampurkan ke dalam inhaler dengan perbandingan 1:1 total 6 - 8 tetes. Thieves : diffuse atau dioleskan di sepanjang spine atau di telapak kaki, dilute sesuai kebutuhan. RC : difuse, di teteskan pada inhaler atau di oleskan di dada atau leher.',
nonPepOil:
'Thyme, Eucalyptus, Teatree : Diffuse atau di oleskan di telapak kaki dan atau spine, dilute sesuai kebutuhan.',
blend:
'Lavender (3) + Marjoram (3) + Cypress (3) + Peppermint (5) + V6 di botol 10 ml, oles di bagian yang sakit',
supplement: 'Innerdefense, ImmuPro',
personalCare: 'Not available',
},
{
symptom: 'Batuk',
pepOil:
'RC, Lemon, Frankincense, Thieves. 1. Diffuse salah satu oil @5 tetes. 2. Diffuse ke-2 oil @3 tetes. 3. Hand cupping : 1 tetes oil di telapak tangan, gosok di ke-2 telapak tangan, buat tenda menutup hidung dan hirup 5-15 menit. 4. Oleskan di leher (dilute sesuai kebutuhan)',
nonPepOil: 'Eucalyptus, Breathe Again',
blend:
'Campurkan thieves 1 - 2 tetes ke 1/2 gelas air minum, kemudian gargle.',
supplement: 'Not available',
personalCare: 'Not available',
},
{
symptom: 'Sakit perut',
pepOil:
'Digize, Aromaease, Peppermint pilih salah satu oil oles di pinggang, perut yang sakit dan perut bagian bawah. Dilute sesuai keperluan.',
nonPepOil: 'Ginger, Fennel',
blend: 'Not applicable',
supplement: 'Not available',
personalCare: 'Not available',
},
{
symptom: 'Diare',
pepOil: 'Peppermint, Digize',
nonPepOil:
'Ginger, Fennel pilih salah satu oil oles di pinggang, perut yang sakit dan perut bagian bawah. Dilute sesuai keperluan.',
blend: 'Not applicable',
supplement: 'Not available',
personalCare: 'Not available',
},
{
symptom: 'PMS',
pepOil: 'Lavender',
nonPepOil: 'Clary Sage, Fennel, Bergamot, Peace & Calming',
blend: 'Not applicable',
supplement: 'Not available',
personalCare: 'Not available',
},
{
symptom: 'Sembelit (susah BAB/konstipasi)',
pepOil:
'Digize, lemon. Cara 1: oles di perut searah jarum jam mengitari belly button. Cara 2: minum 2 tetes lemon di kapsul malam sebelum tidur.',
nonPepOil: 'Lemongrass, ginger. cara sama.',
blend:
'Lemon (10) + Digize (10) + V6 di botol roller 10 ml, oles di perut searah jarum jam.',
supplement: 'Ningxia Red',
personalCare: 'Not available',
},
{
symptom: 'GERD',
pepOil:
'Peppermint, Digize, Aromaease. Cara 1: oles di perut dan ulu hati. Cara 2: Digize 3 tetes di kapsul, langsung minum ketika dirasa gejala2 GERD akan muncul (agar efek terasa lebih cepat).',
nonPepOil: 'Lemongrass, ginger, fennel: sama dengan cara 1',
blend:
'Digize (10) + Peppermint (10) + Lemongrass (10) + V6 di botol roller 10ml, oles di perut dan ulu hati.',
supplement: 'Ningxia Red, Alkalime, Life 9',
personalCare: 'Not available',
},
{
symptom: 'Sakit maag (asam lambung)',
pepOil:
'Peppermint, Digize, Aromaease. Cara 1: oles di perut dan ulu hati. Cara 2: Digize 3 tetes di kapsul, langsung minum ketika dirasa gejala2 maag akan muncul (agar efek terasa lebih cepat).',
nonPepOil: 'Lemongrass, ginger, fennel : sama dengan cara 1',
blend:
'Digize (10) + Peppermint (10) + Lemongrass (10) + V6 di botol roller 10ml, oles di perut dan ulu hati.',
supplement: 'Ningxia Red, Alkalime',
personalCare: 'Not available',
},
{
symptom: 'Sakit perut (menstruasi)',
pepOil:
'Lavender, Peppermint, aromaease. oles di pinggang, perut yang sakit dan perut bagian bawah.',
nonPepOil:
'Clarysage + Basil, Dragon Time, Endoflex, Deep Relief, Cool Azul. Cara oles sama. Dragon time bisa dioles seminggu sebelum mens datang.',
blend:
'DragonTime 10 + Basil 4 taro di roller, oles di mata kaki, pinggang belakang dan perut bawah',
supplement: 'Not available',
personalCare: 'Not available',
},
{
symptom: 'Mens tidak teratur',
pepOil:
'Peppermint, Lavender, Frankincense. oles di mata kaki sebelah kanan secara rutin. Oles Frankincense di bagian kulit yang tipis (Lengan bagian dalam, leher)',
nonPepOil:
'Clarysage, Rosemary, PPP : oles rutin di bagian kulit yang tipis (seperti lengan bagian dalam, leher), oles di mata kaki sebelah kanan.',
blend:
'<NAME> (10) + Rosemary (5) + V6 di botol roller 5ml, oles di bagian kulit yg tipis (lengan bagian dalam, leher), oles di mata kaki sebelah kanan',
supplement: 'Ningxia Red',
personalCare: 'Not available',
},
{
symptom: 'Mata bintitan',
pepOil: 'Frankincense, lavender, Copaiba (Handcupping mata secara rutin).',
nonPepOil: 'Sacred Frankincense (Handcupping mata secara rutin).',
blend:
'1 Frankicence/Sacred Frankincense, 1 copaiba (Handcupping mata secara rutin).',
supplement: 'Not available',
personalCare: 'Not available',
},
{
symptom: 'Panic attack',
pepOil:
'Lavender, Frankincense, Lemon, Copaiba (Tetes diubun2, oles di dada, oles di root cakra/solar plexus dan handcupping lalu hirup dalam2).',
nonPepOil:
'Harmony, Idaho Blue Spruce, Sacred Frankincense Cedarwood, White Angelica, Peace and Calming, Valor, Orange (Tetes diubun2, oles di dada, oles di root cakra/solar plexus dan handcupping lalu hirup dalam2).',
blend:
'2 Frankincense, 2 Copaiba, 2 Whiteangelica, 1 Cedarwood (Tetes diubun2, oles di dada, oles di root cakra/solar plexus dan handcupping lalu hirup dalam2).',
supplement: 'Not available',
personalCare: 'Not available',
},
{
symptom: 'Grief (rasa duka)',
pepOil:
'Frankincense, Stressaway, Lavender, Aromaease (Difuse, handcupping, oles di heart cakra).',
nonPepOil:
'Joy, Bergamot, Palo Santo, Roman Chamomile, Forgiveness, Gentle Baby, Release, Sacred Mountain, Valor, Vetiver, Present time (Difuse, handcupping, oles di heart cakra).',
blend:
'Bergamot 1 + Frankincense 1 + Vetiver 1 , oles di belakang leher dan dada, kemudian hirup dalam.',
supplement: 'Cortisol',
personalCare: 'Not available',
},
{
symptom: 'Kulit memar (lebam)',
pepOil:
'Lavender, Copaiba, Panaway, Peppermint, (oles di memar segera mungkin).',
nonPepOil:
'Helicrycum (paling efektif neat di memar segera mungkin), Geranium (apply setelah , Clove, Cistus, Cypress, Roman Chamomile, Marjoram, Kidscent Care (oles di memar segera mungkin).',
blend:
'Blend 1: 5 Helichrysum, 4 lavender, 3 Cypress, 3 Cistus, 3 Geranium. Blend 2: 6 clove, 4 black pepper, 3 peppermint, 2 marjoram, 2 geranium, 2 cypress',
supplement: 'Super C, Multgreen, Juvatone, Juvapower, Ningxia Red',
personalCare:
'Cool Azul Pain Relief Cream, Cool Azul Sport Gel, Ortho Sport Masssage Oil, Orthoease Massage Oil',
},
{
symptom: 'Cantengan',
pepOil:
'Lavender, Frankincense, Lemon, Purification, Digize (oles/tetes di kuku).',
nonPepOil:
'TeaTree, Wintergreen, Myrrh, Sacred Frankincense, Idaho Balsam Fir (oles/tetes di kuku).',
blend:
'2 Frankincense/Sacred Frankincence, 2 Myrrh, 2 Lemon, 1 Wintergreen (oles/tetes di kuku).',
supplement: 'Sulfurzyme, Megacal, Master formula',
personalCare: 'Not available',
},
{
symptom: 'Luka/Lecet',
pepOil: 'Lavender, Copaiba (oles neat di luka atau cold compress).',
nonPepOil:
'Helichrysum, Geranium, Cypress, Cistus, Myrrh, Deep relief (oles neat di luka atau cold compress)',
blend:
'3 helichrysum, 2 copaiba, 2 geranium, 2 lavender (oles neat di luka atau cold compress)',
supplement: 'Not available',
personalCare: 'Baby Lotion',
},
{
symptom: 'Keputihan',
pepOil: 'Lavender (1-2 tetes di pakaian dalam).',
nonPepOil:
'TeaTre, Myrrh, Mountain Savory, Melissa, Melrose, Thieves (oral atau tetes di pakaian dalam).',
blend: '7 tea tree, 5 mountain savory, 2 myrrh (oral).',
supplement:
'ICP (pagi), Juvapower (mlm), Comfortone, Detoxzyme, Life 9 (60 days).',
personalCare: 'Claraderm',
},
{
symptom: 'Kulit kering/pecah-pecah',
pepOil:
'Lavender, Lemon, Frankincence, Copaiba. Cara: Pilih salah satu dan teteskan ke dalam lotion.',
nonPepOil:
'Geranium, Gentle Baby, Myrrh, Elemi, Patchouli. Cara: Pilih salah satu dan teteskan ke dalam lotion.',
blend: 'Not available',
supplement: 'Not available',
personalCare: 'Not available',
},
{
symptom: 'Gatal karena digigit binatang',
pepOil:
'Peppermint, Lavender, Lemon, Purification (oles di bagian yang gatal).',
nonPepOil: 'Tea Tree (oles di bagian yang gatal).',
blend: 'Not available',
supplement: 'Not available',
personalCare: 'Outdoor blend, Baby Lotion',
},
{
symptom: 'Gatal karena alergi',
pepOil:
'Peppermint, Lavender, Lemon, Purification (oles di bagian yang gatal).',
nonPepOil: 'Tea Tree (oles di bagian yang gatal).',
blend: '1 lavender, 1 lemon, 1 peppermint (oles di bagian yang gatal).',
supplement: 'Sulfurzyme',
personalCare: 'Not available',
},
{
symptom: 'Kolesterol',
pepOil:
'Lavender, cara: oles di titik vita flex, di dada daerah jantung, dan sepanjang lengan, 2-4 tetes, 2-3 kali sehari, dilute bila perlu.',
nonPepOil:
'Lemongrass, Helicrycum, Rosemary, Clove, German Chamomile, Aroma Life, Longevity, Cara : oles 2-4 tetes di titik denyut (daerah arteri yang dekat dengan kulit seperti pergelangan tangan, siku bagian dalam, leher bawah) oles 2-3 kali sehari. Bisa juga dioles di sepanjang tulang belakang 6-10 tetes, 3 kali sehari. Dilute bila perlu.',
blend:
'5 Roman Chamomile + 5 Lemongrass + 4 Rosemary +3 Helicrycum, cara sama dengan oil non PEP.',
supplement: 'OmegaGize, Juva Tone, slique tea',
personalCare: 'Not available',
},
{
symptom: 'Asam urat',
pepOil:
'Lemon, PanAway, Frankinsence. Cara: Oles di sendi yang sakit 2-3 kali sehari.',
nonPepOil:
'Fennel, Wintergreen, Pine, Juniper, Jade lemon, Lime, Idaho Blue spruce, Roman Chamomile, Tea Tree, JuvaCleanse, Cool Azul. Cara: sama dengan oil PEP.',
blend:
'Gout Blend : 10 Lemon + 5 Idaho Blue Spruce + 4 Juniper + 3 Tea Tree + 2 Roman Chamomile. Cara: sama',
supplement:
'AlkaLime, AgilEase, MultiGreens, ComforTone, Essentialzyme, JuvaPower, JuvaTone.',
personalCare: 'Not available',
},
{
symptom: 'Diabetes (kencing manis)',
pepOil:
'Lavender, Thieves. Cara: oles pada punggung, dada, telapak kaki, dan di atas pankreas 2-3 kali sehari, dilute bila perlu.',
nonPepOil:
'Ocotea, Clove, Coriander,Fennel, Dill, Cinamon bark, Lemongrass, Endoflex, DiGize, Slique Essence,TummyGize, Cara oles : sama. Oral ; ocotea dan coriander dalam capsul perbandingan 1:1, diminum 2 kali sehari.',
blend:
'Blend #1 :5 cinnamon bark + 5 cypress, Blend #2: 8 Clove + 8 Cinnamon bark + 15 rosemary + 10 Thyme dalam 60 ml V6 oil. Cara : oles di telapak kaki dan area pankreas.',
supplement:
'MultiGreens, MegaCal, Essentialzyme, master Formula, Ningxia Wolfberries, Slique Tea.',
personalCare: 'Not available',
},
{
symptom: 'UTI',
pepOil:
'Lemon, Lavender, Thieves, DiGize. Cara : dilute dengan V6 oil dan pijat pada daerah abdomen, pungung bawah, area pubik.',
nonPepOil:
'Myrrh, Tea Tree, Oregano, Sage, Juniper, Jade Lemon, Melissa, Rosemary, Melrose, Purification, Endoflex. Cara : #1 sama dengan oil PEP, #2 dilute dan gunakan dalam kompres hangat di area pubik 1-2 kali sehari.',
blend:
'Blend #1 sage + purification , Blend #2 Thyme + Melrose, Blend #3 Oregano + Thieves, Blend #4 Juniper + Endoflex. Cara oles sama.',
supplement: 'ImmuPro, Inner Defense, AlkaLime.',
personalCare: 'Not available',
},
{
symptom: 'Hipertensi (tekanan darah tinggi)',
pepOil:
'Lavender. Cara: oles di titik vitaflex jantung, lengan kiri, tangan, kaki dan di dada area jantung, pelipis dan belakang leher belakang beberapa kali dalam sehari.',
nonPepOil:
'Ylang ylang. Cara: teteskan di telapak tangan, gosok kedua telapak tangan, letakan menutupi hidung, bernafas dalam selama 5 menit. dan/atau oles di telapak kaki. Aroma Life, Peace & Calming,Citrus Fresh, Helichrysum, Rosemary, Clove, Marjoram, Cypress, Cinamon Bark. Cara : sama dengan oil PEP.',
blend:
'Blend #1: 5 Geranium + 8 Lemongrass + 3 Lavender + 30 ml V6 oil. Blend #2: 10 Ylang Ylang + 5 Marjoram + 5 Cypress + 30 ml V6 Oil. Cara: Oles di area jantung dan titik vitaflex jantung di kaki kiri dan tangan kiri.',
supplement:
'Essentialzyme, Detoxzyme, OmegaGize, ImmuPro, Super B, Mineral Essence, MegaCal, Ningxia Wolfberries, MindWise.',
personalCare: 'Not available',
},
{
symptom: 'Obesitas (kelebihan berat badan)',
pepOil:
'Lemon. Cara: oles di perut atau tetes di air putih hangat, minum setelah bangun pagi.',
nonPepOil: 'cel lite massage oil, grapefruit, citrus fresh',
blend: 'Not available',
supplement: 'ningxia red, slique tea',
personalCare: 'Not available',
},
{
symptom: 'Sakit kuping (telinga)',
pepOil:
'Thieves, Copaiba, Frankincense, panaway.cara: oles di sekitar telinga.',
nonPepOil: 'Basil, Myrrh, Purification.',
blend:
'Oles Helichrysum / Lavender di sekitar kuping. Panaway / peppermint untuk meredakan nyeri',
supplement: 'ImmuPro, Innerdefense',
personalCare: 'Not available',
},
{
symptom: 'Vertigo',
pepOil:
'Peppermint, Aromaease, Frankincense, panaway. Cara : bisa pilih salah satu oil (atau pakai semuanya secara bergantian), oles di belakang leher, tetes di kepala dan hirup.',
nonPepOil: 'Deep Relief',
blend:
'Oles peppermint dan atau deep relief di kepala & leher. Hirup juga.',
supplement: 'ningxia red',
personalCare: 'Not available',
},
{
symptom: 'Tinitus',
pepOil: 'Peppermint, Lavender. Cara: oles disekitar telinga.',
nonPepOil: 'Helicrycum, Juniper, Geranium, Rose, Basil, Purification.',
blend:
'Oles Helichrysum / Lavender di sekitar kuping. Panaway / peppermint untuk meredakan nyeri.',
supplement: 'ningxia red',
personalCare: 'Not available',
},
{
symptom: 'Demam',
pepOil:
'Peppermint, Copaiba, thieves, Frankincense. Cara : oles peppermint di telapak kaki (tekan area jempol agak lama)), oles juga di punggung. Bisa layer juga dengan Thieves atau copaiba. Tetes Frankincense di kepala, untuk mencegah kejang.',
nonPepOil: 'Eucalyptus Blue, Myrrh, Purification, Juniper.',
blend:
'Eucalyptus + Lavender (cold compress), Lemon + Lavender + Peppermint - oles di telapak kaki & punggung.',
supplement: 'innerdefense, immupro, ningxia red',
personalCare: 'Not available',
},
{
symptom: 'Kutu rambut',
pepOil: 'Peppermint',
nonPepOil: 'Cedarwood',
blend: 'Not applicable',
supplement: 'Not available',
personalCare: 'Not available',
},
{
symptom: 'Bisul',
pepOil: 'Thieves / purification / frankincense dioles di area bisul.',
nonPepOil: 'Tea Tree / thyme dilute dgn v6 (1 : 1) dioles di area bisul.',
blend:
'Lavender + tea tree +r oman chamomile + v6 (perbandingan sama), lalu dioles ke area bisul.',
supplement: 'Not available',
personalCare: 'Not available',
},
{
symptom: 'Jamur kuku',
pepOil: 'Lemon, Frankincense',
nonPepOil: 'Tea Tree',
blend: 'Lime, Oregano, Tea Tree + Vit E (oles di kuku)',
supplement: 'Not available',
personalCare: 'Not available',
},
{
symptom: 'Covid +',
pepOil: 'Inhaler: RC + lemon @20 drops',
nonPepOil:
'Inhaler: lemon + RC + eu glob + ravintsara @10 drops, top up setiap 3 hari',
blend: 'Raindrop 2-3x per hari',
supplement:
'Super B, super D, super C, ningxia, inner defense. omegagize, probiotic.',
personalCare: 'Gargle thieves mouthwash thieves, thieves hand soap/gel.',
},
{
symptom: 'Kontak erat dengan Covid +',
pepOil: 'Inhaler: RC + lemon @5 drops',
nonPepOil: 'Inhaler: eucalyptus 4 + RC 3 + lemon 3',
blend: 'Raindrop 1x per hari',
supplement: 'Super B, super D, super C, ningxia, inner defense.',
personalCare: 'Gargle thieves mouthwash thieves, thieves hand soap/gel.',
},
{
symptom: 'Lepuh (luka bakar)',
pepOil:
'Lavender dioles neat sering2 sampai sudah mereda lalu frekuensi dikurangi.',
nonPepOil:
'Heli, sering2 dioles sampai mereda, setelah itu dilute dengan V6 (1:4)',
blend: 'Not applicable',
supplement: 'Not available',
personalCare: 'Not available',
},
{
symptom: 'Post Covid',
pepOil: 'Inhaler: RC + lemon @5 drops',
nonPepOil: 'Inhaler: eucalyptus 4 + RC 3 + lemon 3',
blend: 'Raindrop 1x per minggu',
supplement: 'Super B, super D, super C, ningxia',
personalCare: 'Not available',
},
{
symptom: 'Meningkatkan imunitas',
pepOil:
'Thieves, Frankinsence, Lemon, Lavender, Tea Tree. Oleskan di telapak kaki dan spine',
nonPepOil:
'Oregano, Thyme, Clove, Cinnamon Bark, RDT Oils (Oregano, Thyme, Basil, Cypress, Wintergreen, Marjoram, Aroma Siez, Peppermint). Oleskan di telapak kaki dan spine',
blend:
'Blend Oregano, Thyme, Tea Tree, Peppermint and Clove dan dimasukkan di bottle roller untuk di diffuse, oles dan minum dalam kapsul.',
supplement:
'Super Vitamin C, ImmuPro, Innerdefense, Master Formula, Ningxia Red',
personalCare: 'Not available',
},
{
symptom: 'Pre/post vaksin Covid',
pepOil: 'Thives, RC, Lemon, Peppermint. Oleskan di telapak kaki',
nonPepOil:
'Raven, Breathe again, Ravintsara, RDT Oils (Oregano, Thyme, Basil, Cypress, Wintergreen, Marjoram, Aroma Siez, Peppermint). Oleskan di dada, dan diffuse.',
blend:
'Teteskan RC, Lemon, Ravintsara, Eucalyptus Globulus ke dalam inhaler dan hirup.',
supplement: 'Ningxia Red',
personalCare: 'Not available',
},
{
symptom: 'Hilang penciuman',
pepOil: 'RC, Lemon, Peppermint. Hirup (nose cuppling)/diffuse.',
nonPepOil:
'Raven, Breathe again, Ravintsara. Hirup (nose cuppling)/diffuse.',
blend:
'Teteskan RC, Lemon, Ravintsara, Eucalyptus Globulus ke dalam inhaler dan hirup dan teteskan 1-2 tetes dari salah satu oil di atas ke dalam baskom berisi air panas dan hirup.',
supplement: 'Ningxia Red',
personalCare: 'Not available',
},
{
symptom: 'Mimisan',
pepOil:
'Lavender, Frankinsence. Oles di batang hidung dan di lengan bagian dalam',
nonPepOil: 'Cypress dioles di lengan bagian dalam.',
blend: 'Not applicable',
supplement: 'Ningxia Red',
personalCare: 'Not available',
},
{
symptom: 'Sariawan',
pepOil: 'Thieves, Lavender, Copaiba, Purification.',
nonPepOil:
'Copaiba, Clove, Melissa, Cypress, Thyme, Thieves Spray, Thieves Mouthwash.',
blend: 'Blend Thieves, Peppermint and Lemon dimasukkan di bottle spray.',
supplement: 'Super Vitamin C, Ningxia Red, Alkalime',
personalCare: 'Not available',
},
{
symptom: 'Promil',
pepOil: 'Peppermint, Thieves.',
nonPepOil:
'PPP, Fennel, Clasry Sage, Sclaressense, Ylang ylang, Geranium, Dragon Time (oles pada perut bagian bawah, lengan bagian dalam).',
blend: 'Not applicable',
supplement: 'PD 80/20, Multigreens, Mineral Essense, Supercal, Endogize',
personalCare: 'Not available',
},
];
export const symptomsDataBaby = [
{
symptom: 'Flu',
pepOil:
'Lavender, Lemon, RC, Peppermint (dipilih 1-2 oil dan diluted). Oleskan di area dada dan punggung sesering mungkin. 1 sendok teh V6 EO nya sekitar 1-2 tetes sudah cukup. Pilihan diffuse: RC, Thieves, Lavender, Lemon, Peppermint',
nonPepOil:
'Kidscent Refresh. Oles di dada dengan V6, diulang sehari minimal 4-6x',
blend:
'5ml botol dengan V6 secukupnya, tetes Lavender (2) & Peppermint (2) atau RC (2) & Lemon (2). Oleskan di dada dan punggung sesering mungkin ',
supplement:
'KidScents Mightyvites (tablet kunyah), Mightypro (probiotik) diminum sesuai dosis',
personalCare: 'Not available',
},
{
symptom: 'Batuk',
pepOil:
'Lemon, RC, Peppermint, Frankincense (dipilih 1-2 oil dan diluted). Oleskan di area dada dan punggung sesering mungkin. 1 sendok teh V6 EO nya sekitar 1-2 tetes sudah cukup. Pilihan diffuse: RC, Lemon, Peppermint',
nonPepOil:
'Kidscent Refresh. Oles di dada dengan V6, diulang sehari minimal 4-6x. ',
blend:
'5ml botol dengan V6 secukupnya, tetes Frankincense (2) & Peppermint (2) atau RC (2) & Lemon (2). Oleskan di dada dan punggung sesering mungkin',
supplement:
'KidScents Mightyvites (tablet kunyah), Mightypro (probiotik) diminum sesuai dosis',
personalCare: 'Not available',
},
{
symptom: 'Demam',
pepOil:
'Pepermint, Lemon ; cara : dilute sesuai usia anak, oles di telapak kaki dan tulang belakang.',
nonPepOil:
'Eucalyptus Blue, Copaiba, Lime, Fennel, Bergamot; Cara : dilute sesuai usia anak, oles ditelapak kaki dan/atau tulang belakang.',
blend: 'Not applicable',
supplement: 'Not applicable',
personalCare: 'Not available',
},
{
symptom: 'Sakit perut',
pepOil: 'Digize (diluted).',
nonPepOil:
'KidScents T-gize, Gentle Baby, oles di bagian perut, diulang setiap 1-2 jam.',
blend:
'Digize (1) atau AromaEase (1) + V6 dalam botol 5 ml, oles di bagian perut. Ulangi setiap 1-2 jam.',
supplement: 'KidScents Mightyzyme (tablet kunyah), diminum sesuai dosis.',
personalCare: 'Not available',
},
{
symptom: 'Diare',
pepOil:
'Digize/lemongrass (salah satu) dilute (1 : 5) oles berlawanan arah jarum jam di area perut, ulang setiap 1-2 jam.',
nonPepOil:
'Tgize dilute (1 : 5) oles berlawanan arah jarum jam di area perut, ulang setiap 1-2 jam.',
blend: 'Not applicable',
supplement: 'Mightypro (probiotic)',
personalCare: 'Not available',
},
{
symptom: 'Sembelit (susah BAB/konstipasi)',
pepOil:
'Digize, aromaease, peppermint (dilute sesuai usia dan oles searah arah jarum jam di area perut, ulang setiap 1-2 jam).',
nonPepOil:
'Ginger, T-gize, lemongrass, fennel (dilute sesuai usia dan oles searah arah jarum jam di area perut, ulang setiap 1-2 jam).',
blend:
'1 peppermint + 1 lemongrass + 1 ginger + 1 fennel (dilute sesuai usia dan oles searah arah jarum jam di area perut, ulang setiap 1-2 jam).',
supplement: 'Mightypro (probiotic)',
personalCare: 'Not available',
},
{
symptom: 'Diaper rash (ruam popok)',
pepOil:
'Lavender, copaiba, frankincense (dilute sesuai usia dan oles di ruam secara rutin).',
nonPepOil:
'Helichrysum, Kidscents kidcare, Geranium (dilute sesuai usia dan oles di ruam secara rutin).',
blend:
'3 helichrysum, 2 copaiba, 2 geranium, 2 lavender ( dilute sesuai usia dan oles diruam secara rutin).',
supplement: 'Not available',
personalCare: 'Diaper rash cream, Baby Lotion.',
},
{
symptom: 'Colic',
pepOil:
'Lavender / Copaiba. Pilih salah satu: lakukan pijat ILU di perut bayi, lakukan setelah selesai mandi atau saat dibutuhkan.',
nonPepOil:
'Lavender / Copaiba. Pilih salah satu: lakukan pijat ILU di perut bayi, lakukan setelah mandi atau saat dibutuhkan.',
blend:
'Not applicable',
supplement: 'Not available',
personalCare: 'Not available',
},
{
symptom: 'Cranky (rewel)',
pepOil:
'Lavender (Diffuse), Digize diluted (oles di perut), Tea Tree (oles di telapak kaki).',
nonPepOil:
'KidScents T-gize, KidScents SleepIze, KidScents Refresh, Gentle Baby (diffuse/oles di telapak kaki atau dada).',
blend:
'Not applicable',
supplement: 'Not available',
personalCare: 'Not available',
},
{
symptom: 'Mimisan',
pepOil:
'Lavender, Frankincense. Oleskan EO di lengan anak bagian atas dalam dekat ketiak dan cara 1: Teteskan di kapas dan tempelkan pada hidung anak. Cara 2: ambil dari leher botol dengan tangan bersih, lalu oleskan di hidung anak (sedikit saja).',
nonPepOil:
'Cypress. Cara sama',
blend:
'Not applicable',
supplement: 'Not available',
personalCare: 'Not available',
},
{
symptom: 'Luka/lecet',
pepOil:
'Lavender, copaiba. Tetes langsung di luka yang sudah dibersihkan.',
nonPepOil:
'Kidscents kidcare. Tetes langsung di luka yang sudah dibsersihkan.',
blend:
'Not applicable',
supplement: 'Not available',
personalCare: 'Not available',
},
];<file_sep>import { symptomsDataAdult, symptomsDataBaby } from './SymptomsData';
export function symptomSearch(whichOne, symptomName) {
let pepOil = 'Not found';
let nonPepOil = 'Not found';
let blend = 'Not found';
let supplement = 'Not found';
let personalCare = 'Not found';
let symptomsData = [];
if (whichOne === 'Adult') {
symptomsData = symptomsDataAdult;
} else {
symptomsData = symptomsDataBaby;
}
for (let i = 0; i < symptomsData.length; i++) {
if (
symptomsData[i].symptom.toLowerCase().trim() ===
symptomName.toLowerCase().trim()
) {
pepOil = symptomsData[i].pepOil;
nonPepOil = symptomsData[i].nonPepOil;
blend = symptomsData[i].blend;
supplement = symptomsData[i].supplement;
personalCare = symptomsData[i].personalCare;
break;
}
}
return { pepOil, nonPepOil, blend, supplement, personalCare };
}
<file_sep>import { styled } from '@mui/material/styles';
import MuiToolbar from '@mui/material/Toolbar';
const Toolbar = styled(MuiToolbar)(({ theme }) => ({
height: 64,
[theme.breakpoints.up('sm')]: {
height: 70,
},
}));
export default Toolbar;<file_sep>import { useState, useRef } from 'react';
import {
Card,
CardContent,
Divider,
OutlinedInput,
Button,
CardActions,
InputAdornment,
IconButton,
} from '@mui/material';
import { Visibility, VisibilityOff } from '@mui/icons-material';
const Login = (props) => {
const [values, setValues] = useState({
password: '',
showPassword: false,
});
const inputRef = useRef(null);
const onChangeHandler = (event) => {
setValues(event.target.value);
inputRef.current.value = event.target.value;
};
const onClickShowPasswordHandler = () => {
setValues({
showPassword: !values.showPassword,
});
};
const onMouseDownPasswordHandler = (event) => {
event.preventDefault();
};
const onClickHandler = () => {
inputRef && props.onLogin(inputRef.current.value);
};
return (
<Card width="100%">
<CardContent>
<Divider variant="middle" textAlign="left">
Password
</Divider>
<OutlinedInput
id="outlined-password-input"
label="Password"
type={values.showPassword ? 'text' : 'password'}
size="small"
autoComplete="current-password"
value={values.password}
onChange={onChangeHandler}
ref={inputRef}
endAdornment={
<InputAdornment position="end">
<IconButton
aria-label="toggle password visibility"
onClick={onClickShowPasswordHandler}
onMouseDown={onMouseDownPasswordHandler}
edge="end"
>
{values.showPassword ? <VisibilityOff /> : <Visibility />}
</IconButton>
</InputAdornment>
}
/>
</CardContent>
<CardActions>
<Button size="small" variant="contained" onClick={onClickHandler}>
Login
</Button>
</CardActions>
</Card>
);
};
export default Login;
<file_sep>import { useState, useMemo } from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import CssBaseline from '@mui/material/CssBaseline';
import { createTheme, ThemeProvider } from '@mui/material';
import AuthContext from './components/context/loggin-context';
import ColorModeContext from './components/context/colormode-contex';
import ProtectedRoute from './components/Navigation/ProtectedRoute';
import TopNavigation from './components/Navigation/TopNavigation';
import Login from './components/Pages/Login';
import Home from './components/Pages/Home';
import AdultSymptom from './components/Pages/Adult';
import BabySymptom from './components/Pages/Baby';
const App = () => {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const loginHandler = (password) => {
if (password === '<PASSWORD>') {
setIsLoggedIn(true);
}
};
const [mode, setMode] = useState('light');
const colorMode = useMemo(
() => ({
toggleColorMode: () => {
setMode((prevMode) => (prevMode === 'light' ? 'dark' : 'light'));
},
}),
[]
);
const theme = useMemo(
() =>
createTheme({
palette: {
mode,
},
}),
[mode]
);
return (
<AuthContext.Provider value={{ isLoggedIn: isLoggedIn }}>
<ColorModeContext.Provider value={colorMode}>
<ThemeProvider theme={theme}>
<CssBaseline />
<Router>
<TopNavigation />
<Switch>
{!isLoggedIn && (
<Route exact path="/">
{' '}
<Login onLogin={loginHandler} />
</Route>
)}
<ProtectedRoute exact path="/" component={Home} />
<ProtectedRoute exact path="/dewasa" component={AdultSymptom} />
<ProtectedRoute
exact
path="/bayidanbalita"
component={BabySymptom}
/>
</Switch>
</Router>
</ThemeProvider>
</ColorModeContext.Provider>
</AuthContext.Provider>
);
};
export default App;
<file_sep>import SymptomInput from "../Main/SymptomsInput";
const AdultSymptom = () => {
return <SymptomInput whichOne={'Adult'} />;
};
export default AdultSymptom;
<file_sep>import { Card, CardMedia } from '@mui/material';
const Home = () => {
return (
<Card>
<CardMedia
component="img"
image="https://source.unsplash.com/R10kxddJNWk"
/>
</Card>
);
};
export default Home;<file_sep>import { useState, useRef } from 'react';
import {
Autocomplete,
TextField,
Divider,
Card,
CardHeader,
CardContent,
CardActions,
Typography,
} from '@mui/material';
import { symptomOptionAdult, symptomOptionBaby } from './SymptomsOptions';
import { symptomSearch } from './SymptomsSearch';
const SymptomInput = (props) => {
let symptomAutocompleteOption = [];
let title = '';
if (props.whichOne === 'Adult') {
symptomAutocompleteOption = symptomOptionAdult;
title = 'Campuran EO untuk Dewasa';
} else {
symptomAutocompleteOption = symptomOptionBaby;
title = 'Campuran EO untuk Balita & Bayi';
}
const [value, setValue] = useState('Ketik nama penyakit');
const [inputValue, setInputValue] = useState('');
const pepOilRef = useRef('');
const nonPepOilRef = useRef('');
const blendRef = useRef('');
const supplementRef = useRef('');
const personalCareRef = useRef('');
const setPepOilRefResult = (result) => {
pepOilRef && (pepOilRef.current.value = result);
};
const setNonPepOilRefResult = (result) => {
nonPepOilRef && (nonPepOilRef.current.value = result);
};
const setBlendRefResult = (result) => {
blendRef && (blendRef.current.value = result);
};
const setSupplementRefResult = (result) => {
supplementRef && (supplementRef.current.value = result);
};
const setPersonalCareRefResult = (result) => {
personalCareRef && (personalCareRef.current.value = result);
};
const onInputChangeHandler = (event, newInputValue) => {
setInputValue(newInputValue);
};
const selectedSymptomHandler = (event, newValue) => {
setValue(newValue);
console.log(props.whichOne);
console.log(newValue);
if (newValue != null) {
const symptomResult = symptomSearch(props.whichOne, newValue.label);
setPepOilRefResult(symptomResult.pepOil);
setNonPepOilRefResult(symptomResult.nonPepOil);
setBlendRefResult(symptomResult.blend);
setSupplementRefResult(symptomResult.supplement);
setPersonalCareRefResult(symptomResult.personalCare);
}
};
return (
<Card sx={{ maxWidth: 400 }}>
<CardHeader title={title} />
<CardActions>
<Autocomplete
value={value}
onChange={selectedSymptomHandler}
inputValue={inputValue}
onInputChange={onInputChangeHandler}
disablePortal
id="combo-box"
options={symptomAutocompleteOption}
sx={{ width: 312 }}
renderInput={(params) => (
<TextField
{...params}
label="Symptom"
variant="outlined"
size="small"
inputProps={{
...params.inputProps,
autoComplete: 'new-password', // disable autocomplete and autofill
}}
/>
)}
/>
</CardActions>
<CardContent>
<Divider variant="middle" textAlign="left">
Oil PEP
</Divider>
<Typography paragraph ref={pepOilRef}>{pepOilRef.current.value}</Typography>
<Divider variant="middle" textAlign="left">
Oil Non PEP
</Divider>
<Typography paragraph ref={nonPepOilRef}>{nonPepOilRef.current.value}</Typography>
<Divider variant="middle" textAlign="left">
Blend DIY
</Divider>
<Typography paragraph ref={blendRef}>{blendRef.current.value}</Typography>
<Divider variant="middle" textAlign="left">
Supplement
</Divider>
<Typography paragraph ref={supplementRef}>{supplementRef.current.value}</Typography>
<Divider variant="middle" textAlign="left">
Personal Care
</Divider>
<Typography paragraph ref={personalCareRef}>{personalCareRef.current.value}</Typography>
</CardContent>
</Card>
);
};
export default SymptomInput;
<file_sep>import { useContext } from 'react';
import { Box, Link, AppBar, Toolbar, useTheme, IconButton } from '@mui/material';
import { Link as RouterLink } from 'react-router-dom';
import ColorModeContext from '../context/colormode-contex';
import Brightness4Icon from '@mui/icons-material/Brightness4';
import Brightness7Icon from '@mui/icons-material/Brightness7';
//import AppBar from './AppBar';
//import Toolbar from './ToolBar';
const rightLink = {
fontSize: 16,
color: 'common.white',
ml: 3,
};
const TopNavigation = () => {
const theme = useTheme();
const colorMode = useContext(ColorModeContext);
return (
<div>
<AppBar position="fixed">
<Toolbar sx={{ justifyContent: 'flex-start' }}>
<Link
variant="h6"
underline="none"
color="inherit"
component={RouterLink}
to="/"
sx={{ fontSize: 24 }}
>
{'OilWiki'}
</Link>
<Box sx={{ flex: 1, display: 'flex', justifyContent: 'flex-end' }}>
<Link
color="inherit"
variant="h6"
underline="none"
component={RouterLink}
to="/dewasa"
sx={rightLink}
>
{'Dewasa'}
</Link>
<Link
color="inherit"
variant="h6"
underline="none"
component={RouterLink}
to="/bayidanbalita"
sx={rightLink}
>
{'Bayi & Balita'}
</Link>
</Box>
<IconButton
sx={{ ml: 1 }}
onClick={colorMode.toggleColorMode}
color="inherit"
>
{theme.palette.mode === 'dark' ? (
<Brightness4Icon />
) : (
<Brightness7Icon />
)}
</IconButton>
</Toolbar>
</AppBar>
<Toolbar />
</div>
);
};
export default TopNavigation;
<file_sep>import { symptomsDataAdult, symptomsDataBaby } from './SymptomsData';
const symptomsArrayAdult = [];
for (let i = 0; i < symptomsDataAdult.length; i++) {
symptomsArrayAdult.push({
label: symptomsDataAdult[i].symptom,
id: i+1,
});
}
export const symptomOptionAdult = symptomsArrayAdult.sort(function (a, b) {
const textA = a.label.toLowerCase();
const textB = b.label.toLowerCase();
return textA.localeCompare(textB);
});
const symptomsArrayBaby = [];
for (let i = 0; i < symptomsDataBaby.length; i++) {
symptomsArrayBaby.push({
label: symptomsDataBaby[i].symptom,
id: i+1,
});
}
export const symptomOptionBaby = symptomsArrayBaby.sort(function (a, b) {
const textA = a.label.toLowerCase();
const textB = b.label.toLowerCase();
return textA.localeCompare(textB);
});
| a9a236a9427afeba35708d38f5ad4aa233f71add | [
"JavaScript"
] | 10 | JavaScript | g4ndr1k/OilWiki | 980a6dbe8b74e038fd438f7c11f68c26dc6bc563 | a8c79a7651aa7c9906cbc42b4ce179cce0f9077c |
refs/heads/main | <file_sep>import webbrowser # Access Web portal through our code
import pyttsx3 # Facilitate text to speech module
import speech_recognition as sr # It is a speach recognition module as part of google Speech Api
import wikipedia # Browse or surf anything on Wikipedia
import datetime # Access System datetime
import os # Lauch or Open System Folders and application
import random # generate random numbers
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
print(voices[0].id)
engine.setProperty('voice',voices[0].id) #set the audio of voice assistant as david
rate = engine.getProperty('rate') # Go to Start Search for Microphone Setup
newrate = 130 # You will find David as default voice
engine.setProperty('rate', newrate) # We have encapsulated Hari with David's Voice
def speak(audio):
engine.say(audio) # Here is a function to intake audio
engine.runAndWait()
def wishMe():
speak("Hello miss pallavi. Welcome")
hour = int(datetime.datetime.now().hour)
if hour>=0 and hour<12:
speak("Good Morning!!") # This Function is to greet the Owner as per System Time
elif hour>=12 and hour<18:
speak("Good Afternoon !!!") # We can dyanamically modify as per requirements
elif hour>=18 and hour<22:
speak("Good Evening !")
else:
speak("Ma'am!! It's beyond 10pm We must Sleep")
speak("I am <NAME> . How may I help You ")
def takeCommand():
#It takes microphone input and returns string output
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening....")
r.non_speaking_duration = 0.6 # Actual Setup for Microphone based input
audio = r.listen(source)
try:
print("Recognizing...")
query = r.recognize_google(audio)
print("User Said: "+r.recognize_google(audio))
i = random.randrange(0,50)
if i<25: # Accepting voice and recognizing
speak("Copy that")
else:
speak("Roger that")
except Exception as e:
#print(e)
print("Ma'am I was unable to hear you Please Say again") # if there occurs some exception It will ask to
speak("Ma'am I was unable to hear you Please Say again") #Speak Again
return "None"
return query
if __name__ == "__main__":
wishMe() # function has been called to greet the owner
while True: # Infinite Loop
query = takeCommand().lower() # Converting Voice commands to lower in order to
# logic for execution tasks based on query # Relax for comparision
if 'ok bro' or 'bro' in query: # Activation point
if 'wikipedia' in query:
speak('Searching Wikipedia...') # Surf to Wikipedia
query = query.replace("wikipedia", "")
#print(query)
results = wikipedia.summary(query, sentences = 2)
speak("According to Wikipedia")
print(results)
speak(results)
elif 'open youtube' in query:
speak("Opening YouTube For You.")
webbrowser.open("https://www.youtube.com/")
elif 'google' in query: # Browse to google Services
if 'maps' in query:
speak("Opening Google Maps For you.")
webbrowser.open("https://www.google.co.in/maps/")
elif 'drive' in query:
speak("Opening Google Drive for you.")
webbrowser.open("https://drive.google.com/drive/")
elif 'translate' in query:
speak("Opening Google translate for you.")
webbrowser.open("https://translate.google.co.in/")
else:
speak("Opening Google for you.")
webbrowser.open("https://www.google.co.in/")
elif 'i am sad' in query:
webbrowser.open("https://music.amazon.in/?refMarker=dm_wcp_af_r&ref_=dm_lnd_pm_listn_f85b5c0b_sv_dmusic_0&")
speak("Playing Music for You as refreshment")
elif 'udemy' in query:
speak("Opening Udemy for You")
webbrowser.open("https://www.udemy.com/")
elif 'pluralsight' in query:
speak("Opening PluralSight for You.")
webbrowser.open("https://www.pluralsight.com/") # Access frequently used web portals
elif 'coursera' in query:
speak("Opening Coursera for You.")
webbrowser.open("https://www.coursera.org/")
elif 'thank you' in query:
speak("You are Most Welcome It's my Honor.") # Thank You
elif 'time' in query:
strTime = datetime.datetime.now().strftime("%H:%M:%S")
speak(f"The time is {strTime}")
elif 'open dev c' in query: # Open System Applications
codePath = "C:\Program Files (x86)\Dev-Cpp"
os.startfile(codePath)
elif 'microsoft teams' in query:
path = r"C:\Users\Pallavi Dhere\AppData\Local\Microsoft\Teams" # Another Example
os.startfile(path)
elif 'exit' in query:
print("Quiting")
speak("Bye Bye Sir. Hope to see you Soon.") # Come put of the code
break
<file_sep># Desktop-Voice-Assitance
It is an python application which uses voice commands to execute given task. Libraries used are speech recognition to provide aid for speech synthesis , pyttsx3 for offline use, datetime, OS , Web browser.
| 85ec6d8d156095a294929166de3a6ad7769306f3 | [
"Markdown",
"Python"
] | 2 | Python | pallavidhere23/Desktop-Voice-Assitance | e0572907658cab4b218a8c34a6bd0c3b1576f19e | 90c1cb48c325333b2a4c6732561414fc0aa2308a |
refs/heads/master | <file_sep>require 'dotenv'
Dotenv.load
require 'pry'
def multiply_by_6(var)
var = var * 2
binding.pry
var = var * 3
return var
end
multiply_by_6(5)
puts ENV['TWITTER_API_SECRET']
puts ENV
client.update("Mon premier tweet en Ruby !!!")
| f1ba61d43c622f126a3b7c364e26ccf48cb0e31b | [
"Ruby"
] | 1 | Ruby | hohemarie/bot-twitter-number-2 | 177f0aa4771a7436823ecc90e5bcc447a8f94652 | 28a3ce68eea3b8132194c123444b70886d28be62 |
refs/heads/master | <repo_name>einarprump/ScraperGUI<file_sep>/README.md
# ScraperGUI
2017: I've always wanted to make GUI program and I thought "why not Web scraper GUI?" because everyone would want to use it! So I sat down and brainstormed about what the public would want to see, the conclusion was what I have here. Then I realised this doesn't have any usability for neither me or the public. But here it is and I still have some ideas to improve it but that have to wait. There are some widgets there that I don't use but I will.. oyeah one day I'll show you and me.\
2023: Write text later...
## What is up next?
* Make a a HTTP call
* Print to file
* Modify the Interface and make more friendly with a little sex appeal
## Something else
* Python 3.11.0
* tKinter
* urllib.request
* html.parser
* We are here talking about beautiful written english
### RUN: python windowGUI.py<file_sep>/windowGUI.py
import tkinter as ttk
import tkinter.filedialog as openFile
from urllib import request
from Eparser import Eparser
class Manager(object):
def __init__(self, gui):
self.isWebsite = False
self.parser = Eparser()
self.gui = gui
self.gui.listbox_frame.manager = self
self.gui.input_frame.manager = self
self.gui.headers_frame.manager = self
def btnScrape(self, filename):
if len(filename) < 5:
print("Not a file or a url!")
else:
if filename[0:4] == ("http"):
req = request.Request(filename)
req.add_header('User-Agent', 'HomeMade-Browser/0.1 - In Development')
getResponse = request.urlopen(req)
print(getResponse.getheaders())
requestBytes = getResponse.read()
requestString = requestBytes.decode("utf-8")
self.parser.feed(requestString)
getResponse.close()
self.__create_widgets(getResponse.getheaders())
else:
f = open(filename, 'r', encoding='utf-8')
requestBytes = f.read()
self.parser.feed(requestBytes)
f.close()
for t in self.parser.htmlDoc.keys():
self.gui.listbox_frame.tagListbox.insert(ttk.END, t)
def __create_widgets(self, headers):
r = 0
for h in headers:
column = 0
ttk.Label(self.gui.headers_frame, text=h[0]).grid(row=r, column=column, sticky="W")
column += 1
ttk.Label(self.gui.headers_frame, text=h[1]).grid(row=r, column=column, columnspan=5, sticky="W")
r += 1
class HeadersFrame(ttk.Frame):
def __init__(self, container):
super().__init__(container)
self.manager = None
class InputFrame(ttk.Frame):
def __init__(self, container):
super().__init__(container)
self.__create_widgets()
self.manager = None
def __create_widgets(self):
self.urlFile = ttk.Label(self, text = "Url / File:").grid(column=0, row=0, sticky=ttk.W)
self.urlFileName = ttk.StringVar()
self.urlFileEntry = ttk.Entry(self, width=100, textvariable = self.urlFileName)
self.urlFileEntry.focus()
self.urlFileEntry.grid(column=1, row=0, sticky=ttk.W)
ttk.Button(self, text="Scrape", command=self.btnScrape, underline=0, takefocus=True).grid(column=2, row=0, ipadx=3, sticky="NEWS")
ttk.Button(self, text="Open file..", command=self.btnOpenFile, underline=0, takefocus=True).grid(column=3, row=0, ipadx=3, sticky="NEWS")
for widget in self.winfo_children():
widget.grid(padx=5, pady=5)
def btnScrape(self):
self.manager.btnScrape(self.urlFileName.get())
def btnOpenFile(self):
filename = openFile.askopenfilename(initialdir="/", title="Select file", filetypes=[('HTML', '*.html')])
self.urlFileName.set(filename)
class ListboxFrame(ttk.Frame):
def __init__(self, container):
super().__init__(container)
self.theWay = ttk.StringVar()
self.__create_widgets()
self.manager = None
self.selected = { 'tag': None, 'attr': None, 'prop': None }
def __create_widgets(self):
# TAG SCROLL AND LISTBOX #
ttk.Label(self, text = "Tags").grid(row=0, column=0, sticky=ttk.S+ttk.E+ttk.W+ttk.N)
tagScrollbar = ttk.Scrollbar(self, orient=ttk.VERTICAL)
tagScrollbar.grid(row=1, column=1, rowspan=8, sticky=ttk.N+ttk.S)
self.tagListbox = ttk.Listbox(self, yscrollcommand=tagScrollbar.set, selectmode=ttk.SINGLE, exportselection=False)
self.tagListbox.grid(row=1, column=0, rowspan=8, padx=(5,0), sticky=ttk.S+ttk.E+ttk.W+ttk.N)
self.tagListbox.bind("<<ListboxSelect>>", self.updateAttrListbox)
tagScrollbar['command'] = self.tagListbox.yview
# ATTR SCROLL AND LISTBOX
ttk.Label(self, text = "Attributes").grid(row=0, column=2, sticky=ttk.S+ttk.E+ttk.W+ttk.N)
attrScrollbar = ttk.Scrollbar(self, orient=ttk.VERTICAL)
attrScrollbar.grid(row=1, column=3, rowspan=8, padx=0, sticky=ttk.N+ttk.S)
self.attrListbox = ttk.Listbox(self, yscrollcommand=attrScrollbar.set, selectmode=ttk.SINGLE, exportselection=False)
self.attrListbox.grid(row=1, column=2, rowspan=8, padx=(10,0), sticky=ttk.S+ttk.E+ttk.W+ttk.N)
self.attrListbox.bind("<<ListboxSelect>>", self.updateValueListbox)
attrScrollbar['command'] = self.attrListbox.yview
# PROPERY SCROLL AND LISTBOX
self.columnconfigure(4, weight=2)
ttk.Label(self, text="Value").grid(row=0, column=4, sticky=ttk.S+ttk.E+ttk.W+ttk.N)
valueScrollbar = ttk.Scrollbar(self, orient=ttk.VERTICAL)
valueScrollbar.grid(row=1, column=5, rowspan=8, sticky=ttk.N+ttk.S)
self.valueListbox = ttk.Listbox(self, yscrollcommand=valueScrollbar.set, selectmode=ttk.SINGLE, exportselection=False)
self.valueListbox.grid(row=1, column=4, rowspan=8, padx=(5,0), sticky=ttk.S+ttk.E+ttk.W+ttk.N)
valueScrollbar['command'] = self.valueListbox.yview
self.valueListbox.bind("<<ListboxSelect>>", self.updateTheData)
# LABEL FOR DATA AND SELECTED TAG, ATTRIBUTE & (PROPERTY)
self.theData = ttk.StringVar()
self.columnconfigure(6, weight=1)
self.columnconfigure(7, weight=1)
ttk.Label(self, text="Traveling: ").grid(row=10, column=0, sticky=ttk.E+ttk.W+ttk.N)
ttk.Label(self, textvariable=self.theWay).grid(row=10, column=1, columnspan=5, sticky=ttk.E+ttk.W+ttk.N)
ttk.Label(self, text="DATA:").grid(row=11, column=0, sticky=ttk.E+ttk.W+ttk.N)
self.currentData = ttk.Label(self, textvariable=self.theData).grid(row=11, column=1, columnspan=4, sticky=ttk.W+ttk.N)
def updateTheData(self, e):
currProp = self.valueListbox.get(self.valueListbox.curselection())
data = self.manager.parser.htmlDoc[self.selected['tag']][self.selected['attr']][currProp][0]
self.theWay.set(f'{self.selected["tag"]} > {self.selected["attr"]} > {currProp}')
if (len(data) > 30):
self.theData.set(data[0:30])
else:
self.theData.set(data)
def updateAttrListbox(self, e):
if self.valueListbox.size() > 0:
self.valueListbox.delete(0, self.valueListbox.size())
self.theData.set("")
self.theWay.set("")
self.selected['tag'] = self.tagListbox.get(self.tagListbox.curselection())
self.theWay.set(self.selected['tag'])
if self.attrListbox.size() > 0:
self.attrListbox.delete(0, self.attrListbox.size())
for a in self.manager.parser.htmlDoc[self.selected['tag']].keys():
self.attrListbox.insert(ttk.END, a)
def updateValueListbox(self, e):
currSelectet = self.attrListbox.curselection()
if currSelectet != ():
self.selected['attr'] = self.attrListbox.get(self.attrListbox.curselection())
self.theWay.set(f'{self.selected["tag"]} > {self.selected["attr"]}')
self.valueListbox.delete(0, self.valueListbox.size())
for a in self.manager.parser.htmlDoc[self.selected['tag']][self.selected['attr']].keys():
self.valueListbox.insert(ttk.END, a)
class TreeView(ttk.Frame):
def __init__(self, container):
super().__init__(container)
def initialize(self, data):
print("INITIALIZING...")
tree = ttk.Treeview(self)
tree.heading('#0', text='Scraped', anchor=ttk.W)
tree.insert('', ttk.END)
class OptionsFrame(ttk.Frame):
TAGENTRY = "Ex: span,li,..."
ATTRENTRY = "Ex: rel,alt,..."
def __init__(self, container):
super().__init__(container)
self.__create_widgets()
self.manager = None
def __create_widgets(self):
ttk.Label(self, text="Normal scraping behavior is that all tags are harvested,\n to change that check tags and/or attributes to harvest.", anchor="e").grid(row=0, column=0, columnspan=2, sticky="WENS")
# TAGS TO SCRAPE #
self.head = ttk.StringVar()
self.img = ttk.StringVar()
self.a = ttk.StringVar()
self.div = ttk.StringVar()
self.meta = ttk.StringVar()
self.addTag = ttk.StringVar()
self.addTag.set(self.TAGENTRY)
tagLabelFrame = ttk.LabelFrame(self, text="Tags", borderwidth=1)
tagLabelFrame.grid(row=1, column=0, pady=10, padx=10, ipadx=5, ipady=5, sticky="NEWS")
ttk.Checkbutton(tagLabelFrame, text="head", variable=self.head, onvalue="head", offvalue="").grid(row=0, column=0, pady=(1,0), padx=(5,0), sticky="W")
ttk.Checkbutton(tagLabelFrame, text="img", variable=self.img, onvalue="img", offvalue="").grid(row=1, column=0, pady=(1,0), padx=(5,0), sticky="W")
ttk.Checkbutton(tagLabelFrame, text="a", variable=self.a, onvalue="a", offvalue="").grid(row=2, column=0, pady=(1,0), padx=(5,0), sticky="W")
ttk.Checkbutton(tagLabelFrame, text="div", variable=self.div, onvalue="div", offvalue="").grid(row=0, column=1, pady=(1,0), padx=(5,0), sticky="W")
ttk.Checkbutton(tagLabelFrame, text="meta", variable=self.div, onvalue="div", offvalue="").grid(row=1, column=1, pady=(1,0), padx=(5,0), sticky="W")
self.tagEntry = ttk.Entry(tagLabelFrame, textvariable=self.addTag)
self.tagEntry.grid(row=3, column=0, columnspan=2, padx=(5,0), pady=(8,0), sticky="NSEW")
ttk.Button(tagLabelFrame, command=self.do_nothing, text="Add").grid(row=3, column=3, pady=(8,0), sticky="NSEW")
self.tagEntry.bind("<FocusIn>", lambda event, arg=self.addTag: self.clean_example_text(event, arg))
self.tagEntry.bind("<FocusOut>", lambda event, arg=[self.addTag, self.TAGENTRY]: self.check_entry(event, arg))
self.class_atr = ttk.StringVar()
self.id_attr = ttk.StringVar()
self.style = ttk.StringVar()
self.href = ttk.StringVar()
self.addAttr = ttk.StringVar()
self.addAttr.set(self.ATTRENTRY)
attrLabelFrame = ttk.LabelFrame(self, text="Attributes", borderwidth=1)
attrLabelFrame.grid(row=1, column=1, pady=10, padx=10, ipadx=5, ipady=5, sticky="NEWS")
ttk.Checkbutton(attrLabelFrame, text="class", variable=self.class_atr, onvalue="head", offvalue="").grid(row=0, column=0, pady=(1,0), padx=(5,0), sticky="W")
ttk.Checkbutton(attrLabelFrame, text="id", variable=self.id_attr, onvalue="id", offvalue="").grid(row=1, column=0, pady=(1,0), padx=(5,0), sticky="W")
ttk.Checkbutton(attrLabelFrame, text="style", variable=self.style, onvalue="style", offvalue="").grid(row=2, column=0, pady=(1,0), padx=(5,0), sticky="W")
ttk.Checkbutton(attrLabelFrame, text="href", variable=self.href, onvalue="href", offvalue="").grid(row=0, column=1, pady=(1,0), padx=(5,0), sticky="W")
self.attrEntry = ttk.Entry(attrLabelFrame, textvariable=self.addAttr)
self.attrEntry.grid(row=3, column=0, columnspan=2, padx=(5,0), pady=(8,0), sticky="NSEW")
ttk.Button(attrLabelFrame, command=self.do_nothing, text="Add").grid(row=3, column=3, pady=(8,0), sticky="NSEW")
self.attrEntry.bind("<FocusIn>", lambda event, arg=self.addAttr: self.clean_example_text(event, arg))
self.attrEntry.bind("<FocusOut>", lambda event, arg=[self.addAttr, self.ATTRENTRY]: self.check_entry(event, arg))
def check_entry(self, event, arg):
if len(arg[0].get()) == 0:
arg[0].set(arg[1])
def do_nothing(self):
print("DO NOTHING!")
def clean_example_text(self, e, arg):
arg.set('')
class ApplicationGUI(ttk.Tk):
'''
classdocs
'''
def __init__(self):
super().__init__()
self.title("ScraperGUI - v0.1")
self.resizable(width = False, height = False)
#self.geometry("700x700")
self.attributes('-toolwindow', True)
self.columnconfigure(1, weight=1)
self.rowconfigure(1, weight=1)
self.__create_widgets()
def __create_widgets(self):
self.__create_menu()
self.input_frame = InputFrame(self)
self.input_frame.grid(column=0, row=0, columnspan=4, sticky="WENS")
self.listbox_frame = ListboxFrame(self)
self.listbox_frame.grid(column=0, row=1, sticky="WENS", pady=(0, 5), padx=5)
self.headers_frame = HeadersFrame(self)
self.headers_frame.grid(column=0, row=2, sticky="WENS")
self.options_frame = OptionsFrame(self)
self.options_frame.grid(column=1, row=0, rowspan=8, sticky=ttk.W+ttk.E, padx=(0,15))
def __create_menu(self):
menubar = ttk.Menu(self)
file_menu = ttk.Menu(menubar, tearoff=0)
file_menu.add_command(label="New", command=self.do_nothing)
file_menu.add_command(label="Open", command=self.do_nothing)
file_menu.add_command(label="Save", command=self.do_nothing)
file_menu.add_command(label="Save as...", command=self.do_nothing)
file_menu.add_command(label="Export Scrape", command=self.do_nothing)
file_menu.add_separator()
file_menu.add_command(label="Quit", command=self.quit)
menubar.add_cascade(label="File", menu=file_menu)
edit_menu = ttk.Menu(menubar, tearoff=0)
edit_menu.add_command(label="Find", command=self.do_nothing)
edit_menu.add_separator()
edit_menu.add_command(label="Configure Headers", command=self.do_nothing)
edit_menu.add_command(label="Configure Scraper", command=self.do_nothing)
menubar.add_cascade(label="Edit", menu=edit_menu)
help_menu = ttk.Menu(menubar, tearoff=0)
help_menu.add_command(label="About", command=self.do_nothing)
menubar.add_cascade(label="Help", menu=help_menu)
self.config(menu=menubar)
def do_nothing(self):
print("NOTHING!")
if __name__ == "__main__":
app = ApplicationGUI()
Manager(app)
app.mainloop()<file_sep>/Eparser.py
from html.parser import HTMLParser
from queue import LifoQueue
class ProperyData:
def __init__(self, prop, data = None):
self.attrs = prop
self.data = data
def getAttribute(self):
if len(self.attrs[0]) > 0:
return self.attrs[0][0]
def getProperty(self):
return self.attrs[0][1]
class Eparser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.htmlDoc = {}
self.tags = LifoQueue(0)
self.currentData = None
def handle_starttag(self, tag, attrs):
self.tags.put({'tag': tag, 'attrs': attrs})
def handle_endtag(self, tag):
if tag not in self.htmlDoc:
self.htmlDoc[tag] = {}
obj = self.tags.get()
if obj['attrs']:
print('ATTRS: ', obj['attrs'][0])
if obj['attrs'][0][0] not in self.htmlDoc[tag]:
self.htmlDoc[tag][obj['attrs'][0][0]] = {}
if obj['attrs'][0][1] not in self.htmlDoc[tag][obj['attrs'][0][0]]:
self.htmlDoc[tag][obj['attrs'][0][0]][obj['attrs'][0][1]] = []
if self.currentData:
self.htmlDoc[tag][obj['attrs'][0][0]][obj['attrs'][0][1]].append(self.currentData)
else:
self.htmlDoc[tag][obj['attrs'][0][0]][obj['attrs'][0][1]].append("NONE")
self.currentData = None
if tag == 'head':
self.head = False
def handle_data(self, data):
cleanString = data.rstrip("\t \n")
self.currentData = cleanString | b1a57f8832352e03c9873485f41e9c55f5345d81 | [
"Markdown",
"Python"
] | 3 | Markdown | einarprump/ScraperGUI | 171d30124960bf94a3ddc69af11713c8f4dba433 | 7f4833f992499f4a7a83e2395f975b045623598b |
refs/heads/master | <file_sep># frozen_string_literal: true
module NPlusOneControl
VERSION = "0.2.1"
end
| 11fa10e9d1e402449a77d564be4954b8c69d94ba | [
"Ruby"
] | 1 | Ruby | teachbase/n_plus_one_control | ee74e1335a93fdb1b47a9f4d6ec8301c6fa2e966 | b2c5a2b126c79c8ce47cd8937a36a10917af059c |
refs/heads/master | <file_sep>package fr.iutvalence.java.tp.tilepuzzle.ihm;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import fr.iutvalence.java.tp.tilepuzzle.Plateau;
import fr.iutvalence.java.tp.tilepuzzle.Position;
/**
* @author augsburs
* Gestion de l'affichage d'un plateau de TilePuzzle
*/
@SuppressWarnings("serial")
public class JPanelPlateau extends JPanel
{
/**
* Le plateau à afficher
*/
private Plateau plateau;
/**
* La hauteur du plateau
*/
private int hauteur;
/**
* La largeur du plateau
*/
private int largeur;
/**
* L'auditeur des boutons du plateau
*/
private ActionListener auditeurBoutons;
/**
* Affichage du plateau initial
* @param auditeurBoutons L'auditeur des boutons du plateau
*/
public JPanelPlateau(ActionListener auditeurBoutons)
{
this.auditeurBoutons = auditeurBoutons;
this.initJPanel();
}
/**
* Initialisation des boutons du plateau
*/
private void initBoutonsPlateau()
{
this.removeAll();
for (int ligne = 0; ligne < this.hauteur; ligne++)
for (int colonne = 0; colonne < this.largeur; colonne++)
{
Position p = new Position(ligne, colonne);
JButtonTilePuzzle boutonCourant;
if (this.plateau.estCaseAllumee(p))
boutonCourant = new JButtonTilePuzzle(p, true);
else
boutonCourant = new JButtonTilePuzzle(p, false);
boutonCourant.setFocusable(false);
boutonCourant.addActionListener(this.auditeurBoutons);
boutonCourant.setToolTipText("Cliquez moi !");
this.add(boutonCourant);
}
this.repaint();
this.revalidate();
}
/**
* Mettre à jour l'affichage du plateau
* @param plateau le nouveau plateau à mettre à jour
*/
public void mettreAJour(Plateau plateau)
{
this.removeAll();
this.initBoutonsPlateau();
this.repaint();
this.revalidate();
}
/**
* Initialisation de l'affichage du plateau
* @param plateau le plateau à afficher pour la première fois
*/
public void initialiserAffichagePlateau(Plateau plateau)
{
this.plateau = plateau;
this.hauteur = this.plateau.obtenirHauteur();
this.largeur = this.plateau.obtenirLargeur();
this.setLayout(new GridLayout(this.hauteur, this.largeur));
this.initBoutonsPlateau();
}
/**
* Initialisation du JPanel
*/
private void initJPanel()
{
this.setEnabled(false);
this.setBorder(null);
}
}<file_sep>package fr.iutvalence.java.tp.tilepuzzle.interfaces;
import fr.iutvalence.java.tp.tilepuzzle.Plateau;
/**
* Interface définissant les méthodes relatives à l'affichage
*/
public interface VueTilePuzzle
{
/**
* Affiche le plateau transmis
* @param plateau Plateau a afficher
*/
public void initialiserAffichagePlateau(Plateau plateau);
/**
* Met à jour le plateau affiché
* @param plateau Le plateau à mettre à jour
*/
public void mettreAJourPlateau(Plateau plateau);
/**
* Lorsque la partie a été gagnée !
*/
public void afficherPartieGagnee();
}
| b342d29b18791a8a07eb3de397ed3bf9bbac8166 | [
"Java"
] | 2 | Java | AugsburgerS/iutvalence-java-tp-2014-g1b-binome1 | 85b9f52995e37fba1b868b28d9fddcde81ef9f4e | e620674c43635c1019610a3da59c2a56cf9324ed |
refs/heads/master | <repo_name>Kerry-Jr/Playground_Testing_Kerry<file_sep>/src/containers/Layouts/Tictac8.js
import React from 'react'
export default function Tictac8() {
return (
<div className='bg-warning border border-dark w-100 h-100'>
</div>
)
}
<file_sep>/src/containers/Layouts/Tictac6.js
import React from 'react'
export default function Tictac6() {
return (
<div className='bg-primary border border-dark w-100 h-100'>
</div>
)
}
<file_sep>/src/containers/Layouts/index.js
import React, { Component } from 'react'
import Tictac1 from './Tictac1'
import Tictac2 from './Tictac2'
import Tictac3 from './Tictac3'
import Tictac4 from './Tictac4'
import Tictac5 from './Tictac5'
import Tictac6 from './Tictac6'
import Tictac7 from './Tictac7'
import Tictac8 from './Tictac8'
import Tictac9 from './Tictac9'
import './style.css';
export default class Layouts extends Component {
render() {
return (
<div className='container-fluid bg-dark'>
<div className='row no-gutters'>
<div className='col-4'>
<Tictac1 />
</div>
<div className='col-4'>
<Tictac4 />
</div>
<div className='col-4'>
<Tictac7 />
</div>
</div>
<div className='row no-gutters'>
<div className='col-4'>
<Tictac3 />
</div>
<div className='col-4'>
<Tictac6 />
</div>
<div className='col-4'>
<Tictac9 />
</div>
</div>
<div className='row no-gutters'>
<div className='col-4'>
<Tictac2 />
</div>
<div className='col-4'>
<Tictac5 />
</div>
<div className='col-4'>
<Tictac8 />
</div>
</div>
</div>
)
}
}
//Consolas, 'Courier New', monospace<file_sep>/src/containers/PassGen/index.js
import React, { Component } from 'react'
export default class PassGen extends Component {
render() {
return (
<div>
<p>Password Gen</p>
</div>
)
}
}
<file_sep>/src/components/ListCities/index.js
import React from 'react'
export default function Cities(props) {
return (
<div>
{props.cities.map(city => (
<h5>{city}</h5>
))}
</div>
)
}<file_sep>/src/containers/ShoppingList/index.js
import React, { Component } from 'react'
import ShoppingItem from '../../components/ShoppingItem'
export default class ShoppingList extends Component {
state = {
items: ['apples','oranages','cats','baseball'],
stuff: ['cars','computers','coding','dogs']
}
render() {
return (
<div className=' container mt-4 bg-warning text-center'>
<h1 className='text-danger'>{this.props.title}</h1>
<div className="row">
<div className="col-6">
<ShoppingItem items={this.state.items}/>
</div>
<div className="col-6">
<ShoppingItem items={this.state.stuff}/>
</div>
</div>
</div>
)
}
}
<file_sep>/src/containers/Cities/index.js
import React, { Component } from 'react'
import Cities from './../../components/ListCities'
export default class ListCities extends Component {
state = {
cities: ['Alameda','Oakland','San Jose','San Francisco'],
photos: []
}
render() {
return (
<div className='mt-4 bg-danger text-center' style={{color: 'whitesmoke', height: '100%'}}>
<p>These are cities I lived in!!</p>
<h2 className='bg-info'>{this.state.cities}</h2>
<img src='https://specials-images.forbesimg.com/imageserve/5daaf195616a450007041f83/960x0.jpg?fit=scale'alt='sunset' style={{height: '100px', width: '200px'}}></img>
</div>
)
}
}
<file_sep>/src/containers/Layouts/Tictac5.js
import React from 'react'
export default function Tictac5() {
return (
<div className='bg-info border border-dark w-100 h-100'>
</div>
)
}
| 16fd66f2ed70fb83d4aa7af0cff3263174b488ec | [
"JavaScript"
] | 8 | JavaScript | Kerry-Jr/Playground_Testing_Kerry | d07732399392c7eec3f04ba16d05ada37caae43a | 136354e9392c9ea350adadfd25b0990416b1d2a2 |
refs/heads/master | <file_sep>import pandas as pd
class DiscretizeDataset:
def __init__(self):
pass
def equaldistantbin(self,datasetframe,column_name,num_of_bins):
discretizedataset = None
maxvalue = datasetframe[column_name].max()
minvalue = datasetframe[column_name].min()
bin_width = (maxvalue-minvalue)/num_of_bins
# value = datasetframe['x1'][0]
# print(value)
valuebindict = {}
for value in datasetframe[column_name]:
minboundary = minvalue
maxboundary = minvalue + bin_width
# print("Value"+str(value))
for bin in range(num_of_bins):
# print("Bin"+str(bin))
# print("Range "+ str(minboundary)+'-'+str(maxboundary))
if value>=minboundary and value < maxboundary:
valuebindict[value] = 'bin'+str(bin)
minboundary = maxboundary
maxboundary = maxboundary+bin_width
if(value==maxvalue):
valuebindict[value]= 'bin'+str(num_of_bins-1)
# print(value)
datasetframe[column_name].replace(valuebindict, inplace=True)
# print(datasetframe)
discretizedataset = datasetframe
return discretizedataset
# ddobj = DiscretizeDataset()
# dataset = pd.read_csv('../input/synthetic-1.csv')
# print(ddobj.equaldistantbin(dataset,'x1',4))
<file_sep>import matplotlib.pyplot as plt
import numpy as np
def plot_predicted(x,y,theta_list,order,order_color,plot_title):
plt.figure()
X_grid = np.arange(min(x), max(x), 0.1)
X_grid = X_grid.reshape(len(X_grid),1)
label_holder = []
modelno = 0
for theta in theta_list:
line = theta[0]
label_holder.append('%.*f' % (2, theta[0]))
for i in np.arange(1, len(theta)):
line += theta[i] * X_grid ** i
# label_holder.append(' + ' + '%.*f' % (2, theta[i]) + r'$x^' + str(i) + '$')
plt.plot(X_grid, line, color=order_color[str(order[modelno])], label='Order'+str(order[modelno]))
modelno+=1
plt.scatter(x, y, s=30, c='blue')
plt.title(plot_title)
plt.xlabel('Input X')
plt.ylabel('Output Y')
plt.legend()
plt.show()
<file_sep>import tensorflow as tf
import numpy as np
import os
import time
text = open('../input/tiny-shakespeare.txt','rb').read().decode(encoding = 'utf-8')
vocab = sorted(set(text))
char2idx = {u:i for i, u in enumerate(vocab)}
idx2char = np.array(vocab)
text_as_int = np.array([char2idx[c] for c in text])
seq_length = 100
examples_per_epoch = len(text)//(seq_length+1)
# Create training examples / targets
char_dataset = tf.data.Dataset.from_tensor_slices(text_as_int)
sequences = char_dataset.batch(seq_length+1, drop_remainder=True)
def split_input_target(chunk):
input_text = chunk[:-1]
target_text = chunk[1:]
return input_text, target_text
dataset = sequences.map(split_input_target)
BATCH_SIZE = 64
BUFFER_SIZE = 10000
dataset = dataset.shuffle(BUFFER_SIZE).batch(BATCH_SIZE, drop_remainder=True)
vocab_size = len(vocab)
embedding_dim = 256
rnn_units = 1024
def build_model(vocab_size, embedding_dim, rnn_units, batch_size):
model = tf.keras.Sequential([
tf.keras.layers.Embedding(vocab_size, embedding_dim,
batch_input_shape=[batch_size, None]),
tf.keras.layers.GRU(rnn_units,
return_sequences=True,
stateful=True,
recurrent_initializer='glorot_uniform'),
tf.keras.layers.Dense(vocab_size)
])
return model
model = build_model(
vocab_size=len(vocab),
embedding_dim=embedding_dim,
rnn_units=rnn_units,
batch_size=BATCH_SIZE)
def loss(labels, logits):
return tf.keras.losses.sparse_categorical_crossentropy(labels, logits, from_logits=True)
for input_example_batch, target_example_batch in dataset.take(1):
example_batch_predictions = model(input_example_batch)
print(example_batch_predictions.shape, "# (batch_size, sequence_length, vocab_size)")
sampled_indices = tf.random.categorical(example_batch_predictions[0], num_samples=1)
sampled_indices = tf.squeeze(sampled_indices,axis=-1).numpy()
print("Input: \n", repr("".join(idx2char[input_example_batch[0]])))
print()
print("Next Char Predictions: \n", repr("".join(idx2char[sampled_indices ])))
example_batch_loss = loss(target_example_batch, example_batch_predictions)
print("Prediction shape: ", example_batch_predictions.shape, " # (batch_size, sequence_length, vocab_size)")
print("scalar_loss: ", example_batch_loss.numpy().mean())
model.compile(optimizer='adam', loss=loss)
# Directory where the checkpoints will be saved
checkpoint_dir = './training_checkpoints'
# Name of the checkpoint files
checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt_{epoch}")
checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(
filepath=checkpoint_prefix,
save_weights_only=True)
EPOCHS = 15
history = model.fit(dataset, epochs=EPOCHS, callbacks=[checkpoint_callback])
tf.train.latest_checkpoint(checkpoint_dir)
model = build_model(vocab_size, embedding_dim, rnn_units, batch_size=1)
model.load_weights(tf.train.latest_checkpoint(checkpoint_dir))
model.build(tf.TensorShape([1, None]))
model.summary()
def generate_text(model, start_string):
# Evaluation step (generating text using the learned model)
# Number of characters to generate
num_generate = 1000
# Converting our start string to numbers (vectorizing)
input_eval = [char2idx[s] for s in start_string]
input_eval = tf.expand_dims(input_eval, 0)
# Empty string to store our results
text_generated = []
# Low temperature results in more predictable text.
# Higher temperature results in more surprising text.
# Experiment to find the best setting.
temperature = 1.0
# Here batch size == 1
model.reset_states()
for i in range(num_generate):
predictions = model(input_eval)
# remove the batch dimension
predictions = tf.squeeze(predictions, 0)
# using a categorical distribution to predict the character returned by the model
predictions = predictions / temperature
predicted_id = tf.random.categorical(predictions, num_samples=1)[-1,0].numpy()
# Pass the predicted character as the next input to the model
# along with the previous hidden state
input_eval = tf.expand_dims([predicted_id], 0)
text_generated.append(idx2char[predicted_id])
return (start_string + ''.join(text_generated))
print(generate_text(model, start_string=u"QUEEN: "))<file_sep>import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
# Parameters
from Homework1DecisionTrees.decisiontree.ID3decisitiontree import DecisionTree
from Homework1DecisionTrees.utils.discretizedataset import DiscretizeDataset
def plotdecisionBoundary(trained_tree,dataset_path,dataset_name):
n_classes = 2
plot_colors = "rg"
plot_step = 0.2
# Load data
dataset = pd.read_csv(dataset_path)
X = dataset[['x1','x2']]
Y = dataset['class']
y = dataset['class']
target_names = [0,1]
# print(X)
# print(Y)
dt = DecisionTree()
# print(Z)
# plt.subplot(1, 1,1)
x_min, x_max = dataset['x1'].min()-1,dataset['x1'].max()+1
y_min, y_max = dataset['x2'].min()-1,dataset['x2'].max()+1
xx, yy = np.meshgrid(np.arange(x_min, x_max, plot_step),
np.arange(y_min, y_max, plot_step))
ds = pd.DataFrame(np.c_[xx.ravel(), yy.ravel()])
predicted = pd.DataFrame(columns=["predicted"])
ds.columns = ['x1','x2']
ddobj = DiscretizeDataset()
ddobj.equaldistantbin(ds,'x1',4)
ddobj.equaldistantbin(ds,'x2',4)
queries = ds.to_dict(orient="records")
for i in range(len(ds)):
# print(dt.predict(queries[i], trainedtree, 1.0))
predicted.loc[i, "predicted"] = dt.predict(queries[i], trained_tree, 1.0)
Z = predicted['predicted']
# print(Z.describe())
zz = Z.to_numpy().reshape(xx.shape)
# print(zz.shape)
# print(xx.shape)
# print(yy.shape)
#
plt.contourf(xx, yy, zz, cmap=plt.cm.RdYlBu)
dataset_label0 = dataset[dataset['class'].eq(0)]
dataset_label1 = dataset[dataset['class'].eq(1)]
plt.scatter(dataset_label0['x1'], dataset_label0['x2'], c='r', edgecolor='black',label='class 0')
plt.scatter(dataset_label1['x1'], dataset_label1['x2'], c='b', edgecolor='black',label='class_1')
plt.xlabel('x2')
plt.ylabel('x1')
plt.title(dataset_name)
# for idx in range(len(y)):
# # print(idx)
# # print(X['x1'][idx],X['x2'][idx])
# if(dataset['class'][idx]==0):
# color = 'r'
# label = 0
#
# else:
# color = 'b'
# label = 1
# plt.scatter(X['x1'][idx], X['x2'][idx],c=color,edgecolor='black')
# #
# for i, color in zip(range(n_classes), plot_colors):
# idx = np.where(y == i)
# for id in idx:
# print("index",id)
# # plt.scatter(X[id,0],X[id,1],c=color)
# # # print(idx)
# # print(X[idx, 0])
# # plt.scatter(X[idx, 0], X[idx, 1], c=color, label=target_names[i],
# # cmap=plt.cm.RdYlBu, edgecolor='black', s=15)
#
#
plt.legend()
plt.show()
# Z = Z.to_numpy().reshape(xx.shape)
# print(Z.reshape(xx.shape))
# clf = DecisionTreeClassifier().fit(X, y)
#
# # Plot the decision boundary
# plt.subplot(2, 3, pairidx + 1)
#
# x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
# y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
# xx, yy = np.meshgrid(np.arange(x_min, x_max, plot_step),
# np.arange(y_min, y_max, plot_step))
#
# Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
# Z = Z.reshape(xx.shape)
# cs = plt.contourf(xx, yy, Z, cmap=plt.cm.Paired)
#
# plt.xlabel(iris.feature_names[pair[0]])
# plt.ylabel(iris.feature_names[pair[1]])
# plt.axis("tight")
#
# # Plot the training points
# for i, color in zip(range(n_classes), plot_colors):
# idx = np.where(y == i)
# plt.scatter(X[idx, 0], X[idx, 1], c=color, label=iris.target_names[i],
# cmap=plt.cm.Paired)
#
# plt.axis("tight")
#
# plt.suptitle("Decision surface of a decision tree using paired features")
# plt.legend()
# plt.show()
# sns.set(style="white", color_codes=True)
#
# synthetic_dataset1 = pd.read_csv("../input/synthetic-1.csv")
# synthetic_dataset2 = pd.read_csv("../input/synthetic-2.csv")
# synthetic_dataset3 = pd.read_csv("../input/synthetic-3.csv")
# synthetic_dataset4 = pd.read_csv("../input/synthetic-4.csv")
#
# # print("class distribution of dataset 1")
# # print(synthetic_dataset1['class'].value_counts())
# #
# # print("class distribution of dataset 2")
# # print(synthetic_dataset2['class'].value_counts())
# #
# # print("class distribution of dataset 3")
# # print(synthetic_dataset3['class'].value_counts())
# #
# # print("class distribution of dataset 4")
# # print(synthetic_dataset4['class'].value_counts())
# sns.FacetGrid(synthetic_dataset1, hue= "class").map(plt.scatter,"x1","x2").add_legend()
#
# sns.FacetGrid(synthetic_dataset2, hue= "class").map(plt.scatter,"x1","x2").add_legend()
#
# sns.FacetGrid(synthetic_dataset3, hue= "class").map(plt.scatter,"x1","x2").add_legend()
#
# sns.FacetGrid(synthetic_dataset4, hue= "class").map(plt.scatter,"x1","x2").add_legend()
# plt.show()
<file_sep>from Homework2PolynomialRegression.polynomialregression.polynomialregression import PolynomialRegression
from Homework2PolynomialRegression.utils.visualize import plot_predicted
import pandas as pd
from tabulate import tabulate
synthetic_dataset_paths = {'Synthetic 1':'./input/synthetic-1.csv',
'Synthetic 2':'./input/synthetic-2.csv',
'Synthetic 3':'./input/synthetic-3.csv'}
dataset_mse = {}
dataset_theta = {}
order = [1, 2, 4, 7]
order_color = {'1':'green',
'2':'orange',
'4':'red',
'7':'purple'}
for dataset_name in synthetic_dataset_paths.keys():
dataset = pd.read_csv(synthetic_dataset_paths[dataset_name])
x = dataset.iloc[:, 0].values
y = dataset.iloc[:, -1].values
theta_list = {}
mse_list = {}
for degree in order:
plyregobj = PolynomialRegression(x, y)
theta_list['order'+str(degree)] = plyregobj.fit(order=degree, epochs=100000, alpha=0.002)
mse_list['order'+str(degree)] = plyregobj.getmse()
dataset_mse[dataset_name] = mse_list
dataset_theta[dataset_name] = theta_list
plot_predicted(x, y, theta_list.values(), order, order_color, dataset_name)
print('Training Thetha Values for each Dataset for various degree')
print(tabulate(pd.DataFrame.from_dict(dataset_theta).transpose(),headers='keys',tablefmt='grid'))
print('MSE for various dataset for various degree')
print(pd.DataFrame.from_dict(dataset_mse))
<file_sep>## Binary Classification ##
import pandas as pd
import numpy as np
from random import randrange
from Homework3MultiLayerPerceptron.utils.utils import sigmoid, error, cross_entropy, softmax,grad_sigmoid
class FeedForwardNN:
def __init__(self, x, y):
self.x = x
nodes = 256
self.lr = 0.2
input_shape = x.shape[1]
output_shape = y.shape[1]
self.w1 = np.random.randn(input_shape, nodes)
self.b1 = np.zeros((1, nodes))
self.w2 = np.random.randn(nodes, nodes)
self.b2 = np.zeros((1, nodes))
self.w3 = np.random.randn(nodes, output_shape)
self.b3 = np.zeros((1, output_shape))
self.y = y
def feedforward(self):
z1 = np.dot(self.x, self.w1) + self.b1
self.a1 = sigmoid(z1)
z2 = np.dot(self.a1, self.w2) + self.b2
self.a2 = sigmoid(z2)
z3 = np.dot(self.a2, self.w3) + self.b3
self.a3 = softmax(z3)
def backprop(self, x):
loss = error(self.a3, self.y)
x = x + 1
print('Epoch: %d, Error: ' % x, loss)
a3_delta = cross_entropy(self.a3, self.y)
z2_delta = np.dot(a3_delta, self.w3.T)
a2_delta = z2_delta * grad_sigmoid(self.a2)
z1_delta = np.dot(a2_delta, self.w2.T)
a1_delta = z1_delta * grad_sigmoid(self.a1)
self.w3 -= self.lr * np.dot(self.a2.T, a3_delta)
self.b3 -= self.lr * np.sum(a3_delta, axis=0, keepdims=True)
self.w2 -= self.lr * np.dot(self.a1.T, a2_delta)
self.b2 -= self.lr * np.sum(a2_delta, axis=0)
self.w1 -= self.lr * np.dot(self.x.T, a1_delta)
self.b1 -= self.lr * np.sum(a1_delta, axis=0)
def predict(self, data):
self.x = data
self.feedforward()
return self.a3.argmax()
def get_acc(X, Y):
crct = 0
for x, y in zip(X, Y):
s = model.predict(x)
if s == np.argmax(y):
crct += 1
return (crct / X.shape[0]) * 100
<file_sep>import numpy as np
import pandas as pd
from Homework3MultiLayerPerceptron.multilayerperceptron.FeedForwardNN import FeedForwardNN, get_acc
train_dataset_path = 'input/mnist_train_0_1.csv'
test_dataset_path = 'input/mnist_test_0_1.csv'
train = np.loadtxt(train_dataset_path, delimiter=',')
test = np.loadtxt(test_dataset_path, delimiter=',')
onehot_target1 = pd.get_dummies(np.transpose(train)[0])
onehot_target2 = pd.get_dummies(np.transpose(test)[0])
# print(onehot_target)
x_train = train[:, 1:]
y_train = onehot_target1
x_val = test[:, 1:]
y_val = onehot_target2
# print("\nTraining accuracy : ", get_acc(x_train, np.array(y_train)))
model = FeedForwardNN(x_train, np.array(y_train))
for xx, yy in zip(x_val, np.array(y_val)):
s = model.predict(xx)
# print("\nActual=%d, Predicted=%d" % (np.argmax(yy), s))
model = FeedForwardNN(x_train, np.array(y_train))
epochs = 30
for epoch in range(epochs):
model.feedforward()
model.backprop(epoch)
print("\nTest accuracy : ", get_acc(x_val, np.array(y_val)))
<file_sep>import numpy as np
import pandas as pd
from collections import OrderedDict
import matplotlib.pyplot as plt
from matplotlib import style
from Homework2PolynomialRegression.utils.visualize import plot_predicted
style.use('ggplot')
class PolynomialRegression(object):
def __init__(self, x, y):
self.x = x
self.y = y
def normalise(self, data):
n_data = (data - np.mean(data)) / (np.max(data) - np.min(data))
return n_data
def hypothesis(self, theta, x):
y_hat = theta[0]
for i in range(1, len(theta)):
y_hat = y_hat + theta[i] * x ** i
return y_hat
def mse(self, x, y, theta):
m = len(y)
y_hat = self.hypothesis(theta, x)
errors = abs((y_hat - y) ** 2)
return (1 / (m)) * np.sum(errors)
def fit(self, order, epochs, alpha):
d = {}
d['x' + str(0)] = np.ones([1, len(self.x)])[0]
for i in np.arange(1, order + 1):
d['x' + str(i)] = self.normalise(self.x ** (i))
d = OrderedDict(sorted(d.items(), key=lambda t: t[0]))
X = np.column_stack(d.values())
m = len(self.x)
theta = np.zeros(order + 1)
mse_list = []
mser = 0
for i in range(epochs):
h = self.hypothesis(theta, self.x)
errors = h - self.y
MSE = self.mse(self.x, self.y, theta)
mse_list.append(MSE)
theta += -alpha * (1 / m) * np.dot(errors, X)
self.mser = sum(mse_list) / epochs
self.epochs = epochs
self.theta = theta
return self.theta
def getmse(self):
print('Mean Square error = %.4f' % self.mser)
return self.mser
# Importing the dataset
# dataset = pd.read_csv('../input/synthetic-3.csv')
# x_pts = dataset.iloc[:, 0].values
# y_pts = dataset.iloc[:, -1].values
# # Performing Polynomial Regression
# plyregobj = PolynomialRegression(x_pts, y_pts)
# order = [1,2,4,7]
# theta_list = []
# order_color = {'1':'green',
# '2':'yellow',
# '4':'red',
# '7':'purple'}
# for degree in order:
#
# theta_list.append(plyregobj.fit(order=degree, epochs=100000, alpha=0.002))
#
#
#
#
#
# plot_predicted(x_pts,y_pts,theta_list,order,order_color)
# Res.printmse()<file_sep>from random import randrange
import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def grad_sigmoid(x):
return x * (1 - x)
def softmax(s):
exps = np.exp(s - np.max(s, axis=1, keepdims=True))
return exps / np.sum(exps, axis=1, keepdims=True)
def cross_entropy(pred, target):
n_samples = target.shape[0]
res = pred - target
return res / n_samples
def error(pred, target):
n_samples = target.shape[0]
logp = - np.log(pred[np.arange(n_samples), target.argmax(axis=1)])
loss = np.sum(logp) / n_samples
return loss
<file_sep>from Homework1DecisionTrees.decisiontree.ID3decisitiontree import DecisionTree
from Homework1DecisionTrees.utils.discretizedataset import DiscretizeDataset
from pprint import pprint
import pandas as pd
from Homework1DecisionTrees.utils.visualize import plotdecisionBoundary
ddobj = DiscretizeDataset()
dt = DecisionTree()
synthetic_dataset_paths = {'Synthetic 1':'./input/synthetic-1.csv',
'Synthetic 2':'./input/synthetic-2.csv',
'Synthetic 3':'./input/synthetic-3.csv',
'Synthetic 4':'./input/synthetic-4.csv'}
dataset_accuracy = {}
# Synthetic Dataset
for dataset_name in synthetic_dataset_paths.keys():
dataset = pd.read_csv(synthetic_dataset_paths[dataset_name])
for col in dataset.columns[:-1]:
# print(dataset[col].unique())
if len(dataset[col].unique()) > 2:
ddobj.equaldistantbin(dataset, col, 4)
else:
ddobj.equaldistantbin(dataset, col, 2)
trainedtree = dt.ID3(dataset, dataset, dataset.columns[:-1], 'class')
# pprint(trainedtree)
dataset_accuracy[dataset_name] = dt.test(dataset, trainedtree, 'class')*100
plotdecisionBoundary(trainedtree,synthetic_dataset_paths[dataset_name],dataset_name)
#pokemon dataset
pokemon_dataset_path = './input/pokemonStats.csv'
pokemon_dataset = pd.read_csv(pokemon_dataset_path)
for col in pokemon_dataset.columns[:-1]:
# print(dataset[col].unique())
if len(pokemon_dataset[col].unique()) > 2:
ddobj.equaldistantbin(pokemon_dataset, col, 4)
else:
ddobj.equaldistantbin(pokemon_dataset, col, 2)
pokemon_dt = DecisionTree()
pokemon_trained_tree = pokemon_dt.ID3(pokemon_dataset, pokemon_dataset, pokemon_dataset.columns[:-1], 'Legendary',True)
dataset_accuracy['Pokemon'] = pokemon_dt.test(pokemon_dataset, pokemon_trained_tree, 'Legendary')*100
print("Dataset Accuracy ",dataset_accuracy)<file_sep>import numpy as np
import pandas as pd
from pprint import pprint
from Homework1DecisionTrees.utils.discretizedataset import DiscretizeDataset
class DecisionTree:
no_of_splits = 1
def __init__(self):
pass
def entropy(self,datasetframe,target_column):
entropy = 0
target_values = datasetframe[target_column].unique()
# print("Target Values",target_values)
for value in target_values:
prob_of_value = datasetframe[target_column].value_counts()[value]/len(datasetframe[target_column])
# print('Prob ',prob_of_value)
entropy += -prob_of_value*np.log2(prob_of_value)
return entropy
def IG(self,datasetframe,split_column,target_column):
dataset_entropy = self.entropy(datasetframe,target_column)
# vals = datasetframe[split_column].unique()
# print(vals)
vals, counts = np.unique(datasetframe[split_column], return_counts=True)
#
spilt_column_Entropy = 0
for i in range(len(vals)):
# print((datasetframe.where(datasetframe[split_column] == vals[i]).dropna()))
# print(self.entropy(datasetframe.where(datasetframe[split_column] == vals[i]).dropna(),target_column))
# spilt_column_Entropy+= (counts[i] / np.sum(counts)) * self.entropy(datasetframe.where(datasetframe[split_column] == vals[i]).dropna()[target_column],target_column)
#
spilt_column_Entropy = np.sum([(counts[i] / np.sum(counts)) * self.entropy(datasetframe.where(datasetframe[split_column] == vals[i]).dropna(),target_column) for i in range(len(vals))])
info_gain = dataset_entropy-spilt_column_Entropy
return info_gain
def ID3(self,dataset,originalds, features, target_column="class",depthfixed='False',root_node_class=None):
if len(dataset[target_column].unique()) <= 1:
return dataset[target_column].unique()[0]
elif len(dataset) == 0:
return np.unique(originalds[target_column])[
np.argmax(np.unique(originalds[target_column], return_counts=True)[1])]
elif len(features) == 0:
return dataset[target_column].value_counts().idxmax()
else:
root_node_class = np.unique(dataset[target_column])[ np.argmax(np.unique(dataset[target_column], return_counts=True)[1])]
feature_ig_values = [self.IG(dataset, feature, target_column) for feature in features]
best_feature_index = np.argmax(feature_ig_values)
best_feature = features[best_feature_index]
# print("Split Feature",best_feature)
# print("No of splits",self.no_of_splits)
self.no_of_splits +=1
tree = {best_feature: {}}
features = [i for i in features if i != best_feature]
# print(tree)
# print(self.tree_depth(tree))
for value in np.unique(dataset[best_feature]):
value = value
sub_dataset = dataset.where(dataset[best_feature] == value).dropna()
subtree = self.ID3(sub_dataset, dataset,features, target_column,depthfixed,root_node_class)
tree[best_feature][value] = subtree
if (depthfixed == True):
if (self.no_of_splits > 3):
return tree
# if (self.no_of_splits > 3):
# return tree
return (tree)
def predict(self,query, tree, default=1):
for key in list(query.keys()):
if key in list(tree.keys()):
try:
result = tree[key][query[key]]
except:
return default
result = tree[key][query[key]]
if isinstance(result, dict):
return self.predict(query, result)
else:
return result
def test(self,dataset, tree,target_name):
queries = dataset.iloc[:, :-1].to_dict(orient="records")
predicted = pd.DataFrame(columns=["predicted"])
for i in range(len(dataset)):
predicted.loc[i, "predicted"] = self.predict(queries[i], tree, 1.0)
print('Accuracy : ', (np.sum(predicted["predicted"] == dataset[target_name]) / len(dataset)) * 100,
'%')
return (np.sum(predicted["predicted"] == dataset[target_name]) / len(dataset))
#
# ddobj = DiscretizeDataset()
# dataset = pd.read_csv('../input/synthetic-1.csv')
#
# for col in dataset.columns[:-1]:
# # print(dataset[col].unique())
# if len(dataset[col].unique())> 2:
# ddobj.equaldistantbin(dataset, col, 4)
# else:
# ddobj.equaldistantbin(dataset, col, 2)
# if (dataset[col].unique()>)
# ddobj.equaldistantbin(dataset, col, 4)
# dataset = ddobj.equaldistantbin(dataset,'x1',4)
# dataset = ddobj.equaldistantbin(dataset,'x2',4)
# # print(dataset.describe())
# dt = DecisionTree()
# depthlimit = 4
# trainedtree = dt.ID3(dataset,dataset,dataset.columns[:-1],'class',depthlimit)
# pprint(trainedtree)
# dt.test(dataset,trainedtree,'class')
# # # print("Entropy :",dt.entropy(dataset,'class'))
# # print("Info Gain:",dt.IG(dataset,'x1','class'))
| cbc83b9cc1ab60b20ccc0710c5c3933ac3191f4d | [
"Python"
] | 11 | Python | Sairam954/Machine-Learning-Course | 51fbdbbfc496774888d43e17e198a626c3f488a2 | 15fa0395815f6a5dbfb9205edab3a6654b50e925 |
refs/heads/master | <repo_name>web-fash/lianxiang<file_sep>/js/register.js
$(".input").focus(function(){
$(".input").css({
border: "1px solid #d6d6d6"
})
$(this).css({
border: "1px solid #424242"
});
}).blur(function(){
$(".input").css({
border: "1px solid #d6d6d6"
})
});
$(".header-phone").mouseover(function(){
$(".phone-hov").show();
}).mouseout(function(){
$(".phone-hov").hide();
})
$(".repwd").bind("input",function(){
$(".regist-msg").html("");
$(".regist-error").hide();
if($(this).val() !== ""){
$(".icon-clear").eq(2).css({
display:"block"
});
}else{
$(".icon-clear").eq(2).css({
display:"none"
});
}
})
$(".icon-clear").click(function(){
$(this).prev().val("")
})
$(".regist-button").click(function(){
let http = new XMLHttpRequest()
http.open("get",`http://10.35.161.137:8080/addUser?username=${$(".phone-person").val()}&password=${<PASSWORD>()}`)
http.send()
http.onreadystatechange = function(){
if(http.readyState === 4){
if(http.responseText === "success"){
alert("注册新用户成功,点击去登录");
location.href = "http://10.35.161.137/项目/src/index.html";
}
else{
alert("注册失败")
}
}
}
})<file_sep>/school.sql
/*
Navicat Premium Data Transfer
Source Server : 美好
Source Server Type : MySQL
Source Server Version : 50090
Source Host : localhost:3306
Source Schema : school
Target Server Type : MySQL
Target Server Version : 50090
File Encoding : 65001
Date: 05/03/2021 21:09:47
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for datas
-- ----------------------------
DROP TABLE IF EXISTS `datas`;
CREATE TABLE `datas` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`sex` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`age` int(11) NOT NULL,
`city` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`joinDate` datetime NOT NULL,
PRIMARY KEY USING BTREE (`id`)
) ENGINE = MyISAM AUTO_INCREMENT = 12 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of datas
-- ----------------------------
INSERT INTO `datas` VALUES (8, ' 胡歌', '1', 20, '北京', '2021-01-29 00:00:00');
INSERT INTO `datas` VALUES (2, '宋伟', '0', 22, '北京', '2021-01-04 17:39:05');
INSERT INTO `datas` VALUES (3, '王安石', '0', 13, '上海', '2021-02-07 17:39:10');
INSERT INTO `datas` VALUES (4, '强森', '1', 65, '天津', '2020-12-29 17:39:15');
INSERT INTO `datas` VALUES (5, 'C罗', '1', 33, '海口', '2021-01-18 17:39:22');
INSERT INTO `datas` VALUES (6, '霍元甲', '0', 43, '大连', '2021-01-12 17:39:26');
INSERT INTO `datas` VALUES (7, '飞侠', '1', 23, '大理', '2021-01-04 17:39:33');
INSERT INTO `datas` VALUES (9, '范伟', '0', 45, '上海', '2021-01-18 00:00:00');
INSERT INTO `datas` VALUES (10, '范伟', '1', 67, '北京', '2021-01-30 00:00:00');
INSERT INTO `datas` VALUES (11, '美丽', '0', 19, '广州', '2021-01-13 00:00:00');
-- ----------------------------
-- Table structure for star
-- ----------------------------
DROP TABLE IF EXISTS `star`;
CREATE TABLE `star` (
`id` int(222) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`password` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
PRIMARY KEY USING BTREE (`id`)
) ENGINE = MyISAM AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of star
-- ----------------------------
INSERT INTO `star` VALUES (1, '小小', '12345');
INSERT INTO `star` VALUES (2, '一一', '22222');
INSERT INTO `star` VALUES (3, '三三', '76543');
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`password` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
PRIMARY KEY USING BTREE (`id`)
) ENGINE = MyISAM AUTO_INCREMENT = 71 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, '张三', '123');
INSERT INTO `user` VALUES (2, '李四', '234');
INSERT INTO `user` VALUES (3, '胡歌', '345');
INSERT INTO `user` VALUES (4, 'rfv', '234');
INSERT INTO `user` VALUES (5, 'rfv', 'tgb');
INSERT INTO `user` VALUES (6, 'rfv', '567');
INSERT INTO `user` VALUES (7, 'ujm', '456');
INSERT INTO `user` VALUES (8, 'juyjy', 'jytjyt');
INSERT INTO `user` VALUES (9, 'ujmyum', 'hgrhn');
INSERT INTO `user` VALUES (10, 'ujm', 'regtre');
INSERT INTO `user` VALUES (11, 'eyrtyrty', 'hfghfh');
INSERT INTO `user` VALUES (12, 'jghj', 'gjgj');
INSERT INTO `user` VALUES (13, 'hgfhf', 'hgfh');
INSERT INTO `user` VALUES (14, 'hgfhfg', 'fsdfsfds');
INSERT INTO `user` VALUES (15, 'gergttred', 'fsaf');
INSERT INTO `user` VALUES (16, 'hfhf', 'fsdfs');
INSERT INTO `user` VALUES (17, 'hyh', 'gddgg');
INSERT INTO `user` VALUES (18, '', '');
INSERT INTO `user` VALUES (19, 'fsfsd', 'ffsfs');
INSERT INTO `user` VALUES (20, '123', '123');
INSERT INTO `user` VALUES (21, '', '');
INSERT INTO `user` VALUES (22, 'erty', 'ertyu');
INSERT INTO `user` VALUES (23, 'zxcvb', 'cvbnm');
INSERT INTO `user` VALUES (24, 'sdfg', 'sdfgh');
INSERT INTO `user` VALUES (25, 'sdfg', 'sdfgh');
INSERT INTO `user` VALUES (26, 'sdfg', 'asdfg');
INSERT INTO `user` VALUES (27, 'sdfgh', 'sdfg');
INSERT INTO `user` VALUES (28, 'wertyu', 'sdfg');
INSERT INTO `user` VALUES (29, 'sdfgh', 'sdfg');
INSERT INTO `user` VALUES (30, 'fghdfgh', 'sdfghj');
INSERT INTO `user` VALUES (31, 'sdfghj', 'sdfgh');
INSERT INTO `user` VALUES (32, 'sdfgh', 'ertyui');
INSERT INTO `user` VALUES (33, 'sdfgh', 'dfghjk');
INSERT INTO `user` VALUES (34, 'sdfghj', 'sdfgh');
INSERT INTO `user` VALUES (35, 'dfgh', 'sdfgh');
INSERT INTO `user` VALUES (36, '', '');
INSERT INTO `user` VALUES (37, 'ersdfgh', 'dfg');
INSERT INTO `user` VALUES (38, '', '');
INSERT INTO `user` VALUES (39, 'sdfghj', 'zxcvbnm');
INSERT INTO `user` VALUES (40, '', '');
INSERT INTO `user` VALUES (41, 'sdfgh', 'sdfghj');
INSERT INTO `user` VALUES (42, '', '');
INSERT INTO `user` VALUES (43, '', '');
INSERT INTO `user` VALUES (44, 'sdfghj', 'sdfghjk');
INSERT INTO `user` VALUES (45, 'sdfghj', 'sdfghjk');
INSERT INTO `user` VALUES (46, 'zsdfgh', 'sdfghj');
INSERT INTO `user` VALUES (47, 'dfghjkl', 'sdfghjk');
INSERT INTO `user` VALUES (48, 'sdfghj', 'asdfghjk');
INSERT INTO `user` VALUES (49, 'asdfgh', 'asdfghj');
INSERT INTO `user` VALUES (50, '', '');
INSERT INTO `user` VALUES (51, 'werty', 'sdfgh');
INSERT INTO `user` VALUES (52, 'sdfgh', 'sdfghj');
INSERT INTO `user` VALUES (53, 'ertyu', 'sdfghjk');
INSERT INTO `user` VALUES (54, 'sdfghj', 'sdfghj');
INSERT INTO `user` VALUES (55, 'ertyu', 'dfghjk');
INSERT INTO `user` VALUES (56, 'werty', 'ertyuio');
INSERT INTO `user` VALUES (57, 'ertyui', 'srty');
INSERT INTO `user` VALUES (58, '123', '123');
INSERT INTO `user` VALUES (59, '123', '123');
INSERT INTO `user` VALUES (60, '123', '123');
INSERT INTO `user` VALUES (61, '123', '123');
INSERT INTO `user` VALUES (62, '123', '123');
INSERT INTO `user` VALUES (63, 'sdfgyh', 'sdfghj');
INSERT INTO `user` VALUES (64, 'wertyu', 'ertyu');
INSERT INTO `user` VALUES (65, 'ertyui', 'ertyu');
INSERT INTO `user` VALUES (66, 'ertyui', 'ertyu');
INSERT INTO `user` VALUES (67, '34567', 'rtyu');
INSERT INTO `user` VALUES (68, '123', '123');
INSERT INTO `user` VALUES (69, '123', '123');
INSERT INTO `user` VALUES (70, '123', '123');
SET FOREIGN_KEY_CHECKS = 1;
<file_sep>/js/index.js
let num = 0;
function change(){
if(num == $(".banner-num>span").length - 1){
num = 0;
}else{
num++;
}
$(".banner-list").offset({
left:-(num * $(".banner-box").width())
});
$(".banner-num>span").removeClass("circle");
$(".banner-num>span").eq(num).addClass("circle");
$(".banner-num i").css({
background:"#fff"
});
$(".banner-num i").eq(num).css({
background:"rgba(0,0,0,0)"
});
}
$(".banner-num>span").mouseover(function(){
num = $(this).index()
$(".banner-list").offset({
left:-(num * $(".banner-box").width())
});
$(".banner-num>span").removeClass("circle");
$(this).addClass("circle");
$(".banner-num i").css({
background:"#fff"
});
$(this).find("i").css({
background:"rgba(0,0,0,0)"
})
});
timer = setInterval(change,3000);
$(".banner-left").click(function(){
if(num !== 0){
num--;
}else{
num = $(".banner-num>span").length-1;
}
$(".banner-num>span").removeClass("circle");
$(".banner-num>span").eq(num).addClass("circle");
$(".banner-num i").css({
background:"#fff"
});
$(".banner-num i").eq(num).css({
background:"rgba(0,0,0,0)"
});
$(".banner-list").offset({
left:-(num * $(".banner-box").width())
});
})
$("#banner").on("mouseover",function(){
clearInterval(timer);
$(".banner-dir").css({
display:"block"
});
}).on("mouseout",function(){
timer = setInterval(change,3000);
$(".banner-dir").css({
display:"none"
});
});
$(".banner-right").click(function(){
if(num < $(".banner-num>span").length - 1){
num++
$(".banner-num>span").removeClass("circle");
$(".banner-num>span").eq(num).addClass("circle");
$(".banner-list").offset({
left:-(num * $(".banner-box").width())
});
$(".banner-num i").css({
background:"#fff"
});
$(".banner-num i").eq(num).css({
background:"rgba(0,0,0,0)"
});
}else{
num = 0;
$(".banner-num>span").removeClass("circle");
$(".banner-num>span").eq(num).addClass("circle");
$(".banner-list").offset({
left: 0
});
$(".banner-num i").css({
background:"#fff"
});
$(".banner-num i").eq(num).css({
background:"rgba(0,0,0,0)"
});
}
})
$(".header-title").mouseover(function(){
$(".header-title em").css({
color:"#121212"
})
$(this).find("em").css({
color:"#395782"
})
$(".header-nav").removeClass("active")
$(this).find(".header-nav").addClass("active")
$(this).find(".header-nav").children().children().first().children().last().children().width($(".header-nav").width() / ($(this).find(".header-nav").children().children().first().children().last().children().length + 1));
}).mouseout(function () {
$(".header-nav").removeClass("active");
$(".header-title em").css({
color:"#121212"
})
})
$(".login").on("click",function(){
$("#login-clo").css({
display:"block"
});
$("#login").css({
display:"block"
})
});
$(".login-user").click(function(){
$(".login-fast-box").hide();
$(this).hide();
$(".login-normal-box").show();
$(".login-p").show();
});
$(".telephonea").focus(function(){
$(this).css({
border:"1px solid #424242"
});
}).blur(function(){
$(this).css({
border:"1px solid #d6d6d6"
});
});
$(".notea").focus(function(){
$(this).css({
border:"1px solid #424242"
});
}).blur(function(){
$(this).css({
border:"1px solid #d6d6d6"
});
});
$(".notea").bind("input",function(){
$(".error-msg").html("");
$(".error-box").hide();
})
function isTure(str){
var reg = /^1[123456789]\d{9}$/;
if(!reg.test(str)){
return false;
}
return true
};
$(".hd-login-show").mouseover(function(){
$(".top-phone").slideDown(function(){
$(".top-phone").css({
display:"block",
height:60
})
})
}).mouseout(function(){
$(".top-phone").slideUp(function(){
$(".top-phone").css({
display:"none",
height:0
})
})
})
$(".logout").click(function(){
removeCookie( $(".hd-login-show").html())
$(".hd-login").css({
display:"block"
});
$(".hd-login-show").html("").css({
display:"none"
});
})
$(".regist-btn-plat").click(function(){
location.href = "register.html"
})
$(".content-chren-img").click(function(){
let index = $(this).index()
location.href = `detailPage.html?id=${index}`
})
$(".shop").click(function(){
location.href = "shopping.html"
})
$(".submit").click(function(){
let http = new XMLHttpRequest()
http.open("get",`http://10.35.161.137:8080/login?username=${$(".telephone").val()}&password=${$(".note").val()}`)
http.send()
http.onreadystatechange = function(){
if(http.readyState === 4){
if(http.responseText === "error"){
alert("用户名或密码错误")
}
else{
sessionStorage.setItem("isLogin","1")
alert("登录成功")
location.href = "http://10.35.161.137/项目/src/index.html"
}
}
}
/* $.ajax({
url:"login.php",
type:"get",
data:{
username:$Name,
password:$Pwd
},
success:function(resText){
if(resText == "0"){
$(".error-msg").html("账号或密码错误");
}
if(resText == "1"){
alert("登陆成功")
}
}
}) */
})<file_sep>/js/shopping.js
$(".less").click(function(){
let num = $(this).next().val();
if(num > 1){
num--;
$(this).next().val(num);
}
computedTotal();
})
$(".add").click(function(){
let num = $(this).prev().val()
num++;
$(this).prev().val(num)
computedTotal();
})
$("#submit").click(function(){
let number=parseInt( $(".bc_red").val())
$(".counts").val()=$(".pro_num J_input").val()*number;
})
<file_sep>/js/detailPage.js
window.onscroll = function () {
if (document.documentElement.scrollTop > 50) {
$("#header-box").css({
height: "50px"
});
$(".search").css({
display: "none"
});
$(".search-btn").css({
display: "block"
});
$(".ul .lis").css({
lineHeight: "50px"
});
$(".search-nav-right").css({
display: "block"
});
$(".sort").css({
display: "block"
});
} else {
if (document.documentElement.scrollTop < 50) {
$("header").css({
position: "static"
});
$(".header-nav").css({
display: "block"
});
$("#header-box").css({
height: 70
});
$(".search").css({
display: "block"
});
$(".search-btn").css({
display: "none"
});
$(".ul .lis").css({
lineHeight: "70px"
});
$(".search-nav-right").css({
display: "none"
});
$(".sort").css({
display: "none"
});
}
}
}
$(".app-down").mouseover(function () {
$(".app-down img").show();
}).mouseout(function () {
$(".app-down img").hide();
});
$(".header-img").mouseover(function () {
$(".phone-hov").show();
}).mouseout(function () {
$(".phone-hov").hide();
});
$(".goTop").click(function () {
document.documentElement.scrollTop = 0;
});
$(".sort-list-item1").mouseover(function () {
$(this).next().css({
display: "block"
});
$(this).next().next().css({
display: "block",
paddingRight: 10,
top: 0,
right: 40
})
$(this).css({
display: "none"
})
}).mouseout(function () {
$(this).next().css({
display: "none"
});
$(this).css({
display: "block"
})
$(this).next().next().css({
display: "none",
paddingRight: 10,
top: 0,
right: 40
});
});
function getUrlParam(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
var strValue = "";
if (r != null) {
strValue = unescape(r[2]);
}
return strValue;
}
let id = getUrlParam("id")
$(".list-box-img").click(function () {
$(".list-box-img").css({ "border": "1px solid #dcdcdc" });
$(this).css({ "border": "1px solid #fff" });
var imgsrc = $(this).find("img").attr("src");
$(".pic").attr("src", imgsrc);
$(".bigBox-pic").attr("src", imgsrc);
});
$(".detail .content .list li").mouseover(function () {
$(".detail .nav ")
})
let $pic = $(".detail .content .bigBox .bigBox-pic");
let $mask = $(".detail .content .content-left .mask");
let $bigBox = $(".detail .content .bigBox");
$smallBox = $(".detail .content .content-left .small-box")
// console.log($pic,$mask,$bigBox)
$smallBox.mouseover(function () {
$mask.css({
display: "block"
})
$bigBox.css({
display: "block"
})
})
$smallBox.mouseout(function () {
$mask.css({
display: "none"
})
$bigBox.css({
display: "none"
})
})
$smallBox.mousemove(function (ev) {
let l = ev.clientX - $smallBox.offset().left - $mask.outerWidth() / 2;
let t = ev.clientY - $smallBox.offset().top - $mask.outerHeight() / 2 + 50;
if (l < 0) {
l = 0
}
if (t < 0) {
t = 0
}
if (l > $smallBox.outerWidth() - $mask.outerWidth()) {
l = $smallBox.outerWidth() - $mask.outerWidth()
}
if (t > $smallBox.outerHeight() - $mask.outerHeight()) {
t = $smallBox.outerHeight() - $mask.outerHeight()
}
$mask.css({
left: l,
top: t
});
let scaleX = l / ($smallBox.outerWidth() - $mask.outerWidth());
let scaleY = t / ($smallBox.outerHeight() - $mask.outerHeight());
let kL = $pic.outerWidth() - $bigBox.outerWidth();
let kT = $pic.outerHeight() - $bigBox.outerHeight();
$pic.css({
left: - kL * scaleX,
top: - kT * scaleY
})
});
let num = 1
$(".add").click(function () {
num++;
$(".txt").val(num);
});
$(".reduce").click(function () {
if (num > 1) {
num--;
$(".txt").val(num);
}
}) | 0b884ffa948a12274f7f526bc323e5ceb01bc545 | [
"JavaScript",
"SQL"
] | 5 | JavaScript | web-fash/lianxiang | 284d0669808716d7f327710ae2c8f68330e3f965 | a47eae41d3c37b866683024c20b099c2c87a09ab |
refs/heads/main | <repo_name>tihemetene/Reactex<file_sep>/src/pages/atividade4.jsx
import React, { useState } from 'react';
import {
Container, Row, Col, Form, Button, ListGroup,
} from 'react-bootstrap';
import { GiZeusSword, GiPencil } from 'react-icons/gi';
import Caixa2 from '../components/Card_ex04';
const App = () => {
// Declarando os estados
const [todos, setTodos] = useState([{
isCompleted: false,
}]);
const [text, setText] = useState('');
// Função de verificação da tarefa
const checkComplete = (id) => {
const newTodos = [...todos];
newTodos[id].isCompleted = !newTodos[id].isCompleted;
setTodos(newTodos);
};
// Função de adição de tarefa
const submitButtonAdd = () => {
if (!text.trim()) {
// eslint-disable-next-line no-alert
alert('Ta vazio');
return;
}
setTodos([...todos, { title: text }]);
setText('');
};
// Função de deletar a tarefa
const deleteTodo = (event) => {
todos.splice(event.target.value, 1);
setTodos([...todos]);
};
// Corpo da Aplicação
return (
<Caixa2 title="Todo App" className="m-4">
<Container>
<h2>
Lista de atividades
<GiPencil className="m-2" />
</h2>
<Row>
<Col xl={12} md={9}>
<Form>
<Form.Group>
<Form.Control
type="text"
value={text}
onChange={(event) => setText(event.target.value)}
placeholder="Insira sua atividade do dia"
/>
</Form.Group>
</Form>
</Col>
<Col>
<Button disabled={!text.trim()} onClick={submitButtonAdd} type="button">
Adicionar Todo
</Button>
</Col>
</Row>
<Row>
<ListGroup className="m-3">
{todos.map((todo, index) => (
<ListGroup.Item
key={todo.title}
style={{ textDecoration: todo.isCompleted ? 'line-through' : '' }}
variant="primary"
className="m-1"
>
<input
className="m-2"
type="checkbox"
onClick={() => checkComplete(index)}
/>
{todo.title}
<Button
type="button"
variant="danger"
className="m-2"
onClick={deleteTodo}
value={index}
>
Del
<GiZeusSword className="m-2" />
</Button>
</ListGroup.Item>
))}
</ListGroup>
</Row>
</Container>
</Caixa2>
);
};
export default App;
<file_sep>/src/App.jsx
import React from 'react';
import Caixa from './components/Card';
import './components/index.css';
const App = () => (
<div className="App">
<Caixa info="DÚVIDAS" cardTitle="Home"> </Caixa>
</div>
);
export default App;
<file_sep>/src/pages/Grupo.jsx
import React from 'react';
import caixaGrupo from '../components/Card_grupo';
const Grupo = () => (
<div>
<caixaGrupo
nomes="<NAME>
<NAME>
<NAME>
<NAME>
<NAME>"
cardTitle="Nomes"
/>
</div>
);
export default Grupo;
<file_sep>/src/components/Card_grupo.jsx
import React from 'react';
import { Card } from 'react-bootstrap';
const caixaGrupo = () => (
<Card className="m-4">
<Card.Header><b>Nomes</b></Card.Header>
<Card.Body className="p-2">
<div className="text-center texto">
<h1>
<p><NAME> </p>
<p><NAME> </p>
<p><NAME> </p>
<p><NAME> </p>
<p><NAME> </p>
</h1>
</div>
</Card.Body>
</Card>
);
export default caixaGrupo;
<file_sep>/src/components/Atividade4/Todo.jsx
import React, { useState } from 'react';
import TodoList from './TodoList';
import TodoForm from './TodoForm';
const Atividade4 = () => {
// estado do todo principal - será usado em TodoForm e TodoList
const [todos, setTodos] = useState([]);
// Corpo da Aplicação
return (
<div>
<TodoForm todos={todos} setTodos={setTodos} />
<TodoList todos={todos} setTodos={setTodos} />
</div>
);
};
export default Atividade4;
<file_sep>/src/components/Atividade4/TodoList.jsx
import React from 'react';
import {
Row, Button, ListGroup,
} from 'react-bootstrap';
import { GiPencil, GiTrashCan } from 'react-icons/gi';
import Caixa2 from '../Card_ex04';
const TodoList = ({ todos, setTodos }) => {
// Função de verificação da tarefa
const checkComplete = (id) => {
const newTodos = [...todos];
newTodos[id].isCompleted = !newTodos[id].isCompleted;
setTodos(newTodos);
};
// Função de deletar a tarefa
const deleteTodo = (event) => {
todos.splice(event.target.value, 1);
setTodos([...todos]);
};
// Funções para editar uma tarefa
// onEditTodo recebe os todos e atualiza com o setTodos
const onEditTodo = (index) => {
const newTodos = todos.map((todo, todoIndex) => {
if (todoIndex === index) {
return {
...todo,
edit: !todo.edit,
};
}
return todo;
});
setTodos(newTodos);
};
// onChangeTodo vai escrever o novo valor recebido no todo com o setTodos
const onChangeTodo = (event, index) => {
const newTodos = todos.map((todo, todoIndex) => {
if (todoIndex === index) {
return {
...todo,
title: event.target.value,
};
}
return todo;
});
setTodos(newTodos);
};
// Corpo da Aplicação
return (
<Caixa2 title="Atividades" className="m-4">
<Row>
<ListGroup className="m-2">
{todos.map((todo, index) => (
<ListGroup.Item
key={todo.title}
style={{ textDecoration: todo.isCompleted ? 'line-through' : '' }}
variant="primary"
className="m-1"
>
<input
className="m-2"
type="checkbox"
onClick={() => checkComplete(index)}
/>
{todo.title}
{todo.edit ? (
<input
value={todo.title}
onChange={(event) => onChangeTodo(event, index)}
/>
) : (
<span className={todo.completed ? 'completed' : ''} />
)}
<Button
className="m-2"
onClick={() => onEditTodo(index)}
>
<GiPencil className="m-2" />
</Button>
<Button
type="button"
variant="danger"
className="m-2"
onClick={deleteTodo}
value={index}
>
<GiTrashCan className="m-2" />
</Button>
</ListGroup.Item>
))}
</ListGroup>
</Row>
</Caixa2>
);
};
export default TodoList;
| 41ae78fd08b4ea0e7d9365ba7fdb4ecb6f6d3f80 | [
"JavaScript"
] | 6 | JavaScript | tihemetene/Reactex | 0ff9850af5097540e9a9b11751d8b1af7dff4d24 | eccb3ea992ea757df3d34b0cc59187b54dd9504a |
refs/heads/master | <file_sep>function a() return 'b' end
local minutes = 15
--> Minutos to give. By default is 15
Citizen.CreateThread(function(...)
while true do
Citizen.Wait(minutes*60000)
TriggerServerEvent('salaryJobs:GIVE',"0x089027928098908_", a());
end
end)
<file_sep># vorp_core_paycheck
Vorp Core paycheck Script by Nukkle
--> How to config?
--> You can add salarys into server.lua file in line 22 (follow the examples)
--> You can disable the console debugs in the first lines of server.lua
--> You can change the timer into first client.lua lines
Salary notification IMG: https://cdn.discordapp.com/attachments/697509082306969692/733754549839462541/unknown.png
<file_sep>--> Please don't touch
local isSalary = false
RegisterServerEvent("salaryJobs:GIVE")
scriptName = "vorp_salary"
local g = {}
------------------------------------------------------------------------
-- Config Zone (obviously, now you can touch :))
------------------------------------------------------------------------
local canServerConsoleDebugs = true
-- Let this false to remove console prints!
local salaryMessages= {
["Money_Salary_Recive"] = "Money: You Recived a Money Salary: $",
["Gold_Salary_Recive"] = "Gold:You Recived a Gold Salary: ",
["Xp_Salary_Recive"] = "XP:+"
}
local noSalaryMessages={
["Money_Salary_Recive_No_Recive"] = "Money: You job doesn't give money salary",
["Gold_Salary_Recive_No_Recive" ] = "Gold: You job doesn't give gold salary",
["Xp_Salary_Recive_No_Recive" ] = "XP: You job doesn't give xp salary"
}
-- Tip Notifications
local messageSecondsInScreen = 20 --20 by default
-- When the user recive a salary, a tip notif appear in screen. What secoends this notification needs to be on screen?
---------------- Salary Configuration:
-- :::: JOB l MONEY l GOLD l XP :::::
-- If you don't want to give gold, per exemple, leave the value on 0!
-- just follow the examples
-- don't forgot the [,] in final of }
------------------------------------------------------------------------------------------
g.salaryJobs = {
{"police", 19,0,100},
{"example_job2",19,0,0}
}
function g:giveSalary(_verifyAntiAbuse)
if _verifyAntiAbuse == "0x089027928098908" then
local source = source
for _k,_v in pairs (g.salaryJobs) do
local gold ={}
local xp = {}
local money = {}
if canServerConsoleDebugs then
print("--------------!!!!!!!! Alerta PayCheck !!!!!!!!--------------")
print("DEBUG: Trying to give salary to source: "..source)
print("--------------------------------------------------------------")
end
TriggerEvent("vorp:getCharacter",source,function(user)
if user.job == _v[1] then
isSalary=true
money [source] = _v[2]
gold [source] = _v[3]
xp [source] = _v[4]
if canServerConsoleDebugs then
print("--------------!!!!!!!! Alerta PayCheck !!!!!!!!--------------")
print("DEBUG: Giving Salary to Source: "..source.. " D_INFO>> ", money[source],gold[source],xp[source])
print("--------------------------------------------------------------")
end
if money[source]>=1 then
TriggerEvent("vorp:addMoney", source, 0, money[source]);
end
if gold[source]>=1 then
TriggerEvent("vorp:addMoney", source, 1, gold[source]);
end
if xp[source]>=1 then
TriggerEvent("vorp:addXp", source, xp[source])
end
local mensagens_U = {}
mensagens_U.gold = noSalaryMessages["Gold_Salary_Recive_No_Recive"]
mensagens_U.xp = noSalaryMessages["Money_Salary_Recive_No_Recive"]
mensagens_U.money= noSalaryMessages["Xp_Salary_Recive_No_Recive"]
if xp[source] >= 1 then
mensagens_U.xp = salaryMessages["Xp_Salary_Recive"]..xp[source].. " XP "
end
if money[source]>= 1 then
mensagens_U.money = salaryMessages["Money_Salary_Recive"]..money[source]
end
if gold[source]>=1 then
mensagens_U.gold = salaryMessages["Gold_Salary_Recive"]..gold[source]
end
mensagens_U.finalMessage = mensagens_U.money .."\n".. mensagens_U.gold .."\n"..mensagens_U.xp
if isSalary then
g:Notify(mensagens_U.finalMessage)
end
money [source] = 0
gold [source] = 0
xp [source] = 0
isSalary = false
end end) end
else
if canServerConsoleDebugs then
print("Salary: no;")
end end end
function g:Notify(msg)
local source=source
TriggerClientEvent("vorp:Tip", source, msg, messageSecondsInScreen*1000)
end
------------------------------------------------------------------------------------------
-- Evento para usar a função acima no client.lua
------------------------------------------------------------------------------------------
AddEventHandler("salaryJobs:GIVE",function (_verifyAntiAbuse,_2)
if _2 == 'b' then
if _verifyAntiAbuse == "0x089027928098908_" then
g:giveSalary("0x089027928098908");
end end end)
| 2ff61d26d46f64331a737de8ce295803b3d76182 | [
"Markdown",
"Lua"
] | 3 | Lua | nukkledev/vorp_core_paycheck | cd7aa71b696b1bb9912ab54e409e2330d806443b | 601c06d86bb8023d724b57d78442771553b39ced |
refs/heads/main | <file_sep>with handshake(round, public_key) as (
select 0, 1
union all
select
round+1,
(public_key * 7) % 20201227
from
handshake
where
round <= 20201228
)
select
public_key
from
(select round from handshake where public_key=8421034 limit 1) as card_loop,
(select round from handshake where public_key=15993936 limit 1) as door_loop,
handshake
where
handshake.round = (card_loop.round * door_loop.round) % 20201226;<file_sep>.load ../utils/split.dylib
create table inputs(line text);
.mode csv
.import 03_input.txt inputs
-- Preprocess input into table of tree coordinates
create temporary table coordinates as
select
inputs.rowid - 1 x, split.value square
from
inputs, split(inputs.line,"");
create temporary table trees as
select
x, (rowid-1) % 31 y
from
coordinates
where
square = "#";
-- Part 1
select count(*) from trees where y = (3 * x) % 31;
-- Part 2
select
count(*) filter (where y = x % 31) *
count(*) filter (where y = (3 * x) % 31) *
count(*) filter (where y = (5 * x) % 31) *
count(*) filter (where y = (7 * x) % 31) *
count(*) filter (where x % 2 = 0 and y = (x/2) % 31)
from
trees;
<file_sep># no items, sql only, final destination
This place is not a place of honor.
No highly esteemed deed is commemorated here.
Nothing valued is here.
What is here was dangerous and repulsive to us.
## Solutions
|Day|Solution|
|-|-|
|1|[SQL (SQLite)](./01/01_sqlite.sql)|
|2|[SQL (SQLite)](./02/02_sqlite.sql)|
|3|[SQL (SQLite)](./03/03_sqlite.sql)|
|4|[SQL (SQLite)](./04/04_sqlite.sql)|
|5|[SQL (SQLite)](./05/05_sqlite.sql)|
|6|[SQL (SQLite)](./06/06_sqlite.sql)|
|7|[SQL (SQLite)](./07/07_sqlite.sql)|
|8|[SQL (SQLite)](./08/08_sqlite.sql)|
|9|[SQL (SQLite)](./09/09_sqlite.sql)|
|10|[SQL (SQLite)](./10/10_sqlite.sql)|
|11|[SQL (SQLite)](./11/11_next_generation.sql)|
|12|[SQL (SQLite)](./12/12_sqlite.sql)|
<file_sep>.load ../utils/split.dylib
create temporary table input(line TEXT);
.mode csv
.import 11_input.txt input
create table all_seats as
select value from input, split(input.line, "");
create table seats(x int, y int, status int, unique(x,y));
with dimensions(d) as (
select max(length(line)) from input
) insert into seats select
(all_seats.rowid-1) / dimensions.d,
(all_seats.rowid-1) % dimensions.d,
CASE
WHEN value = "L" THEN 0 -- empty
ELSE 1 -- taken
END
from
all_seats,
dimensions
where
value != "."
order by 1, 2;
select count(*), max(length(line)), min(length(line)) from input;<file_sep>.load ../utils/split.dylib
.mode csv
create temporary table rules(field TEXT, lower int, upper int);
.import 16_real_bounds.txt rules
create temporary table input (line TEXT);
.separator \t
.import 16_real_tickets.txt input
create temporary table tickets as
select
input.rowid ticket_id,
cast(value as int) value
from
input,
split(input.line,",");
create temporary table invalid_fields as with validation(ticket_id, value, valid) as (
select
ticket_id,
value,
CASE
WHEN tickets.value between rules.lower and rules.upper THEN 1
ELSE 0
END
from
tickets,
rules
)
select ticket_id, value from validation group by 1,2 having sum(valid) = 0;
-- Part 1
select sum(value) from invalid_fields;
-- Part 2
-- We only care about valid tickets
create temporary table valid_tickets as
select
ticket_id,
((tickets.rowid-1) % (select count(*)/2 from rules))+1 as column,
tickets.value as value
from
tickets
where
ticket_id not in
(select distinct ticket_id from invalid_fields);
create temporary table final_result(column TEXT, name TEXT PRIMARY KEY);
-- Winnow out field names that have only one possible column
with candidates(col, name) as (
select
column col,
rules.field name
from
valid_tickets,
rules
where
valid_tickets.value between rules.lower and rules.upper
group by 1, 2
having
count(*) = (select count(distinct ticket_id) from valid_tickets)
)
insert into final_result
select
candidates.col,
candidates.name
from
(select col, count(*) total from candidates group by 1) a,
candidates
where
candidates.col = a.col
order by
total
on
conflict(name) do nothing;
-- Print out columns that need to be multiplied
select column from final_result where name like '%departure%';<file_sep>.load product.dylib
with range(i) as (
select 1 union select i+1 from range limit 5
)
select
product(i),
product(cast(i as float))
from
range; -- 120,120.0<file_sep>.load ../utils/binary_to_int.dylib
-- preprocess into CSV to avoid unnecessary joins
create table input(mask text, memory_location int, value text);
.mode csv
.import 14_input.csv input
create table plausible_memory_locations as with
locations(round, original, mask) as (
select distinct
0,
mask,
replace(replace(mask,"0","Y"),"1","Y")
from input
union all
select
round+1,
original,
case
when
instr(mask, "X") = length(mask)
then
substr(mask, 1, 35) || options.replacement
else
substr(mask, 1, instr(mask, "X")-1)
|| options.replacement
|| substr(mask, instr(mask,"X")+1)
end
from
locations,
(select 0 replacement union select 1) options
where
instr(mask, "X") > 0
) select
original,
binary_to_int(replace(mask,"Y",1)) lower_mask,
binary_to_int(replace(mask,"Y",0)) upper_mask
from locations where instr(mask, "X") = 0;
---- Part 2
with processing(round, memory_location, value) as (
select
input.rowid,
input.memory_location
| binary_to_int(replace(input.mask, "X", 0))
& plausible_memory_locations.lower_mask
| plausible_memory_locations.upper_mask,
cast(input.value as bigint)
from
input,
plausible_memory_locations
where
plausible_memory_locations.original = input.mask
),
last_entries(memory_location, round) as (
select
memory_location, max(round)
from
processing
where
memory_location != -1
group by
memory_location
)
select
sum(value)
from
(select
distinct processing.memory_location,
value
from
last_entries
join
processing
on
(processing.round = last_entries.round and processing.memory_location = last_entries.memory_location)
);<file_sep>.load ../utils/binary_to_int.dylib
create table input(memory_location int, value text);
.mode csv
.import 14_input.txt input
-- Part 1
with processing(round, memory_location, value, current_mask) as (
select 1, -1, 0, value from input where input.rowid = 1
union all
select
round+1,
input.memory_location,
case
when input.memory_location = -1 then -1
else
(cast(input.value as int) | binary_to_int(replace(current_mask, "X", 0)))
& binary_to_int(replace(current_mask, "X", 1))
end,
case
when input.memory_location = -1 then input.value
else current_mask
end
from
processing,
input
where
input.rowid = processing.round+1
),
last_entries(round) as (
select
max(round)
from
processing
where
memory_location != -1
group by
memory_location
)
select
sum(value)
from
processing
join
last_entries on (last_entries.round = processing.round);<file_sep>DROP TABLE IF EXISTS opcodes;
CREATE TABLE opcodes(instruction TEXT, value INT);
.mode csv
.separator ' '
.import 08_input.txt opcodes
-- Part 1
WITH running_program(idx, line, instruction, value, total) AS (
select 0, rowid, instruction, value, 0 from opcodes where rowid = 1
UNION ALL
select running_program.idx + 1,
opcodes.rowid,
opcodes.instruction,
opcodes.value,
CASE
WHEN running_program.instruction = "acc" THEN total+running_program.value
ELSE total
END
from opcodes, running_program
where opcodes.rowid = CASE
WHEN running_program.instruction = "jmp" THEN line+running_program.value
ELSE line+1
END
limit 1000000
) select "Part 1 = " || total from (
select
idx,
total,
row_number() over(
partition by line order by line asc
) as occurrences
from running_program
) where occurrences > 1 order by idx asc limit 1;
-- Part 2
DROP TABLE IF EXISTS expanded_codes;
CREATE TABLE expanded_codes(flip_line int, line int, instruction TEXT, value INT);
WITH flippable(line, instruction, value) AS (
select rowid, * from opcodes where instruction != "acc" and value != 0
) insert into expanded_codes select flippable.line as flip_line,
opcodes.rowid as line,
CASE
WHEN opcodes.instruction = "nop" AND flippable.line = opcodes.rowid THEN "jmp"
WHEN opcodes.instruction = "jmp" AND flippable.line = opcodes.rowid THEN "nop"
ELSE opcodes.instruction
END as instruction,
opcodes.value as value
from opcodes, flippable;
-- This gives you the flipped line that caused termination
with running_program(idx, flip, line, instruction, value, total) AS (
select 0, *, 0 from expanded_codes where line = 1
UNION ALL
select running_program.idx + 1,
opcodes.flip_line,
opcodes.line,
opcodes.instruction,
opcodes.value,
CASE
WHEN running_program.instruction = "acc" THEN total+running_program.value
ELSE total
END
from running_program, expanded_codes opcodes
where opcodes.line = CASE
WHEN running_program.instruction = "jmp" THEN running_program.line+running_program.value
ELSE running_program.line+1
END
and
running_program.flip = opcodes.flip_line
limit 100000
) select
"Flipped Instruction = #" || flip,
"Operations = " || count(*) operations
from running_program
group by 1
order by 2 asc
limit 1;
<file_sep>.load ../utils/split.dylib
create table customs_declarations(answer TEXT);
.mode csv
.import 06_input.txt customs_declarations
-- Generate a table of passenger groups and split each
-- passengers questions into a separate row so that we
-- notionally have a table of (group, passenger, answer)
create table answers as with passenger_groups(high, low) as (
select
rowid, lag(rowid,1,0) over (order by rowid asc) as next
from
customs_declarations where answer = ""
)
select
split.value answer,
low,
high,
customs_declarations.rowid row
from
passenger_groups,
customs_declarations,
split(customs_declarations.answer,"")
where
customs_declarations.rowid between low+1 and high-1
order by
2, 4;
-- Part 1
select sum(total) from
(select count(distinct answer) total from answers group by low, high);
-- Part 2
select count(*) from
(select count(distinct row) from answers
group by low, answer having count(answer) = high - (low+1));
<file_sep>#include "sqlite3ext.h"
SQLITE_EXTENSION_INIT1
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#ifndef SQLITE_OMIT_VIRTUALTABLE
#ifndef SQLITE_SPLIT_CONSTRAINT_VERIFY
# define SQLITE_SPLIT_CONSTRAINT_VERIFY 0
#endif
typedef struct split_cursor split_cursor;
struct split_cursor {
sqlite3_vtab_cursor base;
char* current;
char* rest;
char* delimiter;
bool finished;
sqlite3_int64 rowid;
};
// For debugging
static void printState(split_cursor *pCur) {
//printf("***\nDelimiter = %s\n", pCur->delimiter);
//printf("Current = %s\n", pCur->current);
//printf("Rest = %s\n", pCur->rest);
//printf("Finished = %d\n***\n", pCur->finished);
}
static int splitConnect(
sqlite3 *db, void *pUnused, int argcUnused,
const char *const*argvUnused, sqlite3_vtab **ppVtab, char **pzErrUnused
) {
sqlite3_vtab *pNew;
int rc;
/* Column numbers */
#define SPLIT_COLUMN_VALUE 0
#define SPLIT_COLUMN_STRING 1
#define SPLIT_COLUMN_DELIMITER 2
(void)pUnused;
(void)argcUnused;
(void)argvUnused;
(void)pzErrUnused;
rc = sqlite3_declare_vtab(db,"CREATE TABLE x(value,string hidden,delimiter hidden)");
if( rc==SQLITE_OK ){
pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
if( pNew==0 ) return SQLITE_NOMEM;
memset(pNew, 0, sizeof(*pNew));
sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
}
return rc;
}
static int splitDisconnect(sqlite3_vtab *pVtab){
sqlite3_free(pVtab);
return SQLITE_OK;
}
static int splitOpen(sqlite3_vtab *pUnused, sqlite3_vtab_cursor **ppCursor){
split_cursor *pCur;
(void)pUnused;
pCur = sqlite3_malloc( sizeof(*pCur) );
if( pCur==0 ) return SQLITE_NOMEM;
memset(pCur, 0, sizeof(*pCur));
*ppCursor = &pCur->base;
return SQLITE_OK;
}
static int splitClose(sqlite3_vtab_cursor *cur){
sqlite3_free(cur);
return SQLITE_OK;
}
static int splitNext(sqlite3_vtab_cursor *cur) {
split_cursor *pCur = (split_cursor*)cur;
char* ptr;
if (strlen(pCur->delimiter) == 0) {
if (pCur->rowid == strlen(pCur->rest)) {
pCur->finished = true;
} else {
pCur->rowid++;
}
return SQLITE_OK;
}
char *token = strsep(&pCur->rest, pCur->delimiter);
if (token == NULL) {
pCur->finished = true;
return SQLITE_OK;
}
pCur->current = token;
pCur->rowid++;
printState(pCur);
return SQLITE_OK;
}
static int splitColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
split_cursor *pCur = (split_cursor*)cur;
if (strlen(pCur->delimiter) == 0) {
strncpy(pCur->current, &pCur->rest[pCur->rowid-1], 1);
}
sqlite3_result_text(ctx, pCur->current, -1, SQLITE_TRANSIENT);
return SQLITE_OK;
}
static int splitRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
split_cursor *pCur = (split_cursor*)cur;
*pRowid = pCur->rowid;
return SQLITE_OK;
}
static int splitEof(sqlite3_vtab_cursor *cur){
split_cursor *pCur = (split_cursor*)cur;
return pCur->finished;
}
static int splitFilter(
sqlite3_vtab_cursor *pVtabCursor,
int idxNum, const char *idxStrUnused,
int argc, sqlite3_value **argv
){
split_cursor *pCur = (split_cursor *) pVtabCursor;
if (argc != 2) {
return SQLITE_ERROR;
}
pCur->rest = (char*) sqlite3_value_text(argv[0]);
pCur->delimiter = (char *) sqlite3_value_text(argv[1]);
pCur->finished = false;
pCur->rowid = 0;
if (strlen(pCur->delimiter) == 0) {
pCur->current = sqlite3_malloc(2);
pCur->current[2] = '\0';
}
return splitNext(pVtabCursor);
}
// Shamelessly borrowed
// no_idea_dog.png
static int splitBestIndex(sqlite3_vtab *tabUnused, sqlite3_index_info *pIdxInfo){
int i, j;
int idxNum = 0;
int unusableMask = 0;
int nArg = 0;
int aIdx[3];
const struct sqlite3_index_constraint *pConstraint;
(void)tabUnused;
aIdx[0] = aIdx[1] = aIdx[2] = -1;
pConstraint = pIdxInfo->aConstraint;
for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
int iCol; /* 0 for string, 1 for delimiter */
int iMask; /* bitmask for those column */
if( pConstraint->iColumn < SPLIT_COLUMN_STRING ) continue;
iCol = pConstraint->iColumn - SPLIT_COLUMN_STRING;
iMask = 1 << iCol;
if( pConstraint->usable==0 ){
unusableMask |= iMask;
continue;
}else if ( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
idxNum |= iMask;
aIdx[iCol] = i;
}
}
for(i=0; i<3; i++){
if( (j = aIdx[i])>=0 ){
pIdxInfo->aConstraintUsage[j].argvIndex = ++nArg;
pIdxInfo->aConstraintUsage[j].omit = !SQLITE_SPLIT_CONSTRAINT_VERIFY;
}
}
if( (unusableMask & ~idxNum)!=0 ){
return SQLITE_CONSTRAINT;
}
if( (idxNum & 3)==3 ){
pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0));
pIdxInfo->estimatedRows = 1000;
if( pIdxInfo->nOrderBy==1 ){
if( pIdxInfo->aOrderBy[0].desc ){
idxNum |= 8;
}else{
idxNum |= 16;
}
pIdxInfo->orderByConsumed = 1;
}
}else{
pIdxInfo->estimatedRows = 2147483647;
}
pIdxInfo->idxNum = idxNum;
return SQLITE_OK;
}
static sqlite3_module splitModule = {
0, /* iVersion */
0, /* xCreate */
splitConnect, /* xConnect */
splitBestIndex, /* xBestIndex */
splitDisconnect, /* xDisconnect */
0, /* xDestroy */
splitOpen, /* xOpen - open a cursor */
splitClose, /* xClose - close a cursor */
splitFilter, /* xFilter - configure scan constraints */
splitNext, /* xNext - advance a cursor */
splitEof, /* xEof - check for end of scan */
splitColumn, /* xColumn - read data */
splitRowid, /* xRowid - read data */
0, /* xUpdate */
0, /* xBegin */
0, /* xSync */
0, /* xCommit */
0, /* xRollback */
0, /* xFindMethod */
0, /* xRename */
0, /* xSavepoint */
0, /* xRelease */
0, /* xRollbackTo */
0 /* xShadowName */
};
#endif /* SQLITE_OMIT_VIRTUALTABLE */
int sqlite3_split_init(sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi) {
int rc = SQLITE_OK;
SQLITE_EXTENSION_INIT2(pApi);
#ifndef SQLITE_OMIT_VIRTUALTABLE
rc = sqlite3_create_module(db, "split", &splitModule, 0);
#endif
return rc;
}<file_sep>create table player1(card int);
create table player2(card int);
.mode csv
.import 22_player_1.txt player1
.import 22_player_2.txt player2
with
deck1(deck) as ( select json_group_array(card) from player1 ),
deck2(deck) as ( select json_group_array(card) from player2 ),
game(p1, p2) as (
select deck1.deck, deck2.deck from deck1, deck2
union all
select
case
when json_extract(p1, "$[0]") > json_extract(p2, "$[0]")
then json_remove(
json_insert(p1,
"$[#]", json_extract(p1, "$[0]"),
"$[#]", json_extract(p2, "$[0]")
)
,"$[0]")
else json_remove(p1, "$[0]")
end,
case
when json_extract(p1, "$[0]") > json_extract(p2, "$[0]")
then json_remove(p2, "$[0]")
else json_remove(
json_insert(p2,
"$[#]", json_extract(p2, "$[0]"),
"$[#]", json_extract(p1, "$[0]")
)
,"$[0]")
end
from
game
where
json_array_length(p1) > 0 and json_array_length(p2) > 0
),
winning_deck(deck) as (
select
case when json_array_length(p1) > 0 then p1 else p2 end
from
game
where
json_array_length(p1) * json_array_length(p2) = 0
)
select
sum(
((json_array_length(winning_deck.deck)+1) -json_each.id) * json_each.value
)
from
winning_deck,
json_each(winning_deck.deck);
<file_sep>.load binary_to_int.dylib
select
binary_to_int("01010"),
binary_to_int("11010"),
binary_to_int("0"),
binary_to_int("111111111");
<file_sep>.load split.dylib
select
group_concat(value,"|")
from
split("abc",""); -- a,b,c
<file_sep>.load ../utils/split.dylib
create temporary table input(line TEXT);
.mode csv
.import 17_chonky.txt input
create table all_cubes as
select value from input, split(input.line, "");
create table cubes as with dimensions(d) as (
select max(length(line)) from input
)
select
(all_cubes.rowid-1) / dimensions.d x,
(all_cubes.rowid-1) % dimensions.d y,
0 z,
0 w
from
all_cubes,
dimensions
where
value != "."
order by 1, 2;
-- Iterate x 6
create temporary table next_layout(x int, y int, z int, w int, state int);
with
one_away(i) as (
select 1 union select 0 union select -1
),
transforms(x, y, z, w) as (
select
a.i, b.i, c.i, d.i
from
one_away a,
one_away b,
one_away c,
one_away d
where
-- ignore the identity transform
abs(a.i) + abs(b.i) + abs(c.i) + abs(d.i) != 0
),
neighbours(x, y, z, w) as (
select
cubes.x + transforms.x,
cubes.y + transforms.y,
cubes.z + transforms.z,
cubes.w + transforms.w
from
cubes,
transforms
),
counts(x, y, z, w, total) as (
select
x, y, z, w, count(*) n
from
neighbours
group by
x, y, z, w
)
insert into next_layout
select
b.x, b.y, b.z, b.w,
CASE
-- Inactive cubes with 3 active neighbours become active
WHEN a.x IS NULL AND b.total = 3 THEN 1
-- Active cubes with 2 or 3 active neighbours remain active
WHEN a.x IS NOT NULL AND b.total BETWEEN 2 AND 3 THEN 1
-- All other cubes become inactive
ELSE 0
END
from
counts b
left join
cubes a
on
(a.x = b.x and a.y = b.y and a.z = b.z and a.w = b.w);
delete from cubes;
insert into cubes
select x, y, z, w from next_layout where state = 1;
select count(*) from cubes;<file_sep>#!/usr/bin/env bash
rm -rf aoc.db
sqlite3 aoc.db < 11_initialise.sql
STEPS=0
while true; do
echo ${STEPS}
NEXT=$(sqlite3 aoc.db < 11_next_generation.sql | tail -n 1)
if [[ ${STEPS} -eq ${NEXT} ]]; then
break;
fi
STEPS=${NEXT}
done<file_sep>create temporary table next_layout(x int, y int, status int);
with neighbours(x,y) as (
select x+1, y from seats where status = 1
union all
select x, y+1 from seats where status = 1
union all
select x-1, y from seats where status = 1
union all
select x, y-1 from seats where status = 1
union all
select x+1, y+1 from seats where status = 1
union all
select x-1, y+1 from seats where status = 1
union all
select x-1, y-1 from seats where status = 1
union all
select x+1, y-1 from seats where status = 1
), counts(x,y,total) as (
SELECT
x,
y,
COUNT(*) n
FROM neighbours
GROUP BY x,y
) insert into next_layout select
a.x,
a.y,
CASE
WHEN a.status = 0 AND coalesce(b.total, 0) = 0 THEN 1
WHEN a.status = 1 AND coalesce(b.total, 0) >= 4 THEN 0
ELSE a.status
END
from
seats a
left join
counts b
on
(a.x = b.x and a.y = b.y);
--
delete from seats;
insert into seats select * from next_layout;
select sum(status) from seats;<file_sep>.load ../utils/product.dylib
CREATE TEMPORARY TABLE adapters(voltage int);
.mode csv
.import 10_input.txt adapters
CREATE TEMPORARY TABLE connections(value int, next int);
WITH voltage_pairs(value, next, difference) as (
-- Possible connections out from the socket
select
0,
voltage
from adapters where voltage <= 3
union all
-- Connecting highest voltage to the device
select
max(voltage),
max(voltage) + 3
from adapters
union all
-- Everything in between
select
a.voltage,
b.voltage
from
adapters a,
adapters b
where
b.voltage > a.voltage
and
b.voltage - a.voltage <= 3
) insert into connections select * from voltage_pairs;
-- Part 1
with smallest_jumps(difference) as (
select
min(next - value)
from
connections
group by
value
)
select product(c) from (
select count(*) c from smallest_jumps group by difference
);
-- Part 2
with nearest_successor(value, next) as (
select
value, min(next)
from
connections
group by 1
), clusters(value, next, running, total) as (
-- Find out how often we get a run of
-- adapters that are 1 volt apart as these
-- are the parts which differ between possible sequences
select *, 1, 0 from nearest_successor where value = 0
union all
select
a.value,
a.next,
CASE
WHEN a.next = a.value + 1 THEN running+1 ELSE 0 END,
CASE
WHEN running = 2 AND a.next != a.value + 1 THEN 2
WHEN running = 3 AND a.next != a.value + 1 THEN 4
WHEN running = 4 AND a.next != a.value + 1 THEN 7
ELSE 0
END
from
nearest_successor a,
clusters
where
a.value = clusters.next
)
select product(total) from (
select
total,
lead(total, 1, 0) over (order by value) as is_end_of_cluster
from
clusters
) where is_end_of_cluster = 0 and total != 0;
<file_sep>#!/usr/bin/env bash
function run_test() {
TEST_FILE=$1
EXPECTED_OUTPUT=$2
ACTUAL_OUTPUT=$(sqlite3 < "$TEST_FILE" | tr -d '\r')
if [[ "$ACTUAL_OUTPUT" = "$EXPECTED_OUTPUT" ]]; then
echo "Test passed: ${TEST_FILE}"
else
echo "Test failed: ${TEST_FILE}. Expected \"${EXPECTED_OUTPUT}\" but was \"${ACTUAL_OUTPUT}\""
fi
}
for lib in *.c; do
echo "Compiling ${lib}"
gcc \
-dynamiclib \
-lsqlite3 \
-DSQLITE_VTAB_INNOCUOUS=0 \
${lib} \
-o $(echo $lib | sed 's/\.c/.dylib/')
done
run_test test_binary_to_int.sql "10|26|0|511"
run_test test_split.sql "a|b|c"
run_test test_product.sql "120|120.0"<file_sep>#include "sqlite3ext.h"
SQLITE_EXTENSION_INIT1
#include <assert.h>
#include <stdlib.h>
static void binary_to_int(
sqlite3_context *context,
int argc,
sqlite3_value **argv
){
if (sqlite3_value_type(argv[0]) == SQLITE_NULL) return;
const char *zIn = (const char*) sqlite3_value_text(argv[0]);
sqlite3_result_int64(context, strtol(zIn, NULL, 2));
}
int sqlite3_binarytoint_init(
sqlite3 *db,
char **pzErrMsg,
const sqlite3_api_routines *pApi
){
SQLITE_EXTENSION_INIT2(pApi);
(void) pzErrMsg;
return sqlite3_create_function(
db, "binary_to_int", 1, SQLITE_UTF8, 0, binary_to_int, 0, 0);
}<file_sep>create table data(line TEXT);
.mode csv
.import 18_test.txt data
create temporary table inputs(
_line TEXT,
line TEXT GENERATED ALWAYS AS (replace(_line," ",""))
);
insert into inputs select * from data;
create temporary table parsed as
with shunting_yard(round, input_line, operators, out, last_open_bracket) as (
select 1, line, json_array(), json_array(), json_array() from inputs
union all
select
round+1,
input_line,
CASE
WHEN
substr(input_line, round, 1) glob '[0-9]*'
and
json_array_length(operators) > 0
and
json_extract(operators, "$[#-1]") != "("
THEN
-- pop
json_remove(operators,'$[#-1]')
WHEN
substr(input_line, round, 1) in ("+","*","(")
THEN
-- push the operator onto operator stack
json_insert(operators,'$[#]',substr(input_line, round, 1))
WHEN
substr(input_line, round, 1) in (")")
THEN
-- push the operator onto operator stack
(select json_group_array(a) from (
select
json_each.value a
from
json_each(operators)
where
json_each.id < json_extract(last_open_bracket,"$[#-1]")
)
)
ELSE
operators
END,
CASE
WHEN
substr(input_line, round, 1) glob '[0-9]*'
THEN
-- push the number onto the output stack
(select json_group_array(a) from (
select json_each.value a from json_each(out)
union all
select substr(input_line, round, 1)
union all
select json_extract(operators, "$[#-1]")
) where a is not null and a != "(")
WHEN
substr(input_line, round, 1) = ')'
THEN
-- pop the operator stack until you meet first bracket
(select
json_group_array(a)
from (
select
json_each.id id,
json_each.value a
from
json_each(out)
union all
select
json_each.id id,
json_each.value a
from
json_each(operators)
where
json_each.id >= json_extract(last_open_bracket,"$[#-1]")
and
json_each.value not in ("(",")")
)
)
ELSE
out
END,
CASE
WHEN substr(input_line, round, 1) = "(" THEN json_insert(last_open_bracket, "$[#]", json_array_length(last_open_bracket)+1)
WHEN substr(input_line, round, 1) = ")" THEN json_remove(last_open_bracket, "$[#-1]")
ELSE last_open_bracket
END
from
shunting_yard
where
round <= length(trim(input_line,")"))
),
rpn(input_line, out, operators) as (
select
input_line, out, operators
from
shunting_yard
group by
1
having
round = max(round)
),
pop_final_stack(line, id, symbol) as (
select
input_line,
json_each.id id,
json_each.value a
from
rpn, json_each(rpn.out)
union all
select
input_line,
length(rpn.out) + length(rpn.operators) - json_each.id id,
json_each.value a
from
rpn,
json_each(rpn.operators)
order by
1, 2
)
--select * from shunting_yard;
--.mode table
--select * from parsed;
select line, json_group_array(symbol) reverse_polish_notation from pop_final_stack group by line;
.mode table
with calculate(equation, numbers, notation) as (
select
line,
json_array(),
reverse_polish_notation
from
parsed
union all
select
equation,
CASE
WHEN json_extract(notation, "$[0]") glob '[0-9]*'
THEN
json_insert(numbers, "$[#]", cast(json_extract(notation, "$[0]") as bigint))
WHEN json_extract(notation, "$[0]") = "+"
THEN
json_insert(
json_remove(numbers, "$[#-1]", "$[#-1]"),
"$[#]",
json_extract(numbers, "$[#-1]") + json_extract(numbers, "$[#-2]")
)
WHEN json_extract(notation, "$[0]") = "*"
THEN
json_insert(
json_remove(numbers, "$[#-1]", "$[#-1]"),
"$[#]",
json_extract(numbers, "$[#-1]") * json_extract(numbers, "$[#-2]")
)
ELSE
numbers
END,
json_remove(notation, "$[0]")
from
calculate
where
json_array_length(notation) > 0
)
select
sum(json_extract(numbers,"$[0]"))
from
calculate
where
json_array_length(notation) = 0;<file_sep>create table boarding_passes (
code text,
row int,
seat int,
seat_id int generated always as (row * 8 + seat) stored
);
-- HERE WE GO
-- Generate all pairs (0..127,0..8) and derive their boarding pass number
-- This is our precompute table so the problem-solving becomes "just" a lookup
insert into boarding_passes with
row_number(row) as ( select 0 union all select row+1 from row_number limit 128 ),
seat_number(seat) as ( select 0 union all select seat+1 from seat_number LIMIT 8 )
select
-- Row number
case when row & 64 then "B" else "F" end
|| case when row & 32 then "B" else "F" end
|| case when row & 16 then "B" else "F" end
|| case when row & 8 then "B" else "F" end
|| case when row & 4 then "B" else "F" end
|| case when row & 2 then "B" else "F" end
|| case when row % 2 then "B" else "F" end
-- Seat number
|| case when seat & 4 then "R" else "L" end
|| case when seat & 2 then "R" else "L" end
|| case when seat % 2 then "R" else "L" end,
row,
seat
from
row_number,
seat_number;
-- Load data
create table test_passes(code TEXT);
.mode csv
.import 05_input.txt test_passes
-- Part 1
select max(seat_id)
from boarding_passes bp
join test_passes tp on (bp.code = tp.code);
-- Part 2
create temporary table test_seat_ids as
select
bp.seat_id
from
boarding_passes bp,
test_passes tp
where
tp.code = bp.code;
select
seat_id
from
boarding_passes
where
row not in (0, 127)
and
seat_id not in (select * from test_seat_ids)
and
seat_id - 1 in (select * from test_seat_ids)
and
seat_id + 1 in (select * from test_seat_ids);
<file_sep>.load ../utils/split.dylib
.load ../utils/product.dylib
create temporary table input(line TXT);
.mode csv
.separator \t
.import 13_input.txt input
-- Setup
create temporary table earliest_departure
as select cast(line as int) time from input where rowid = 1;
create temporary table bus_intervals as
select
CASE
WHEN value = "x" THEN 0
ELSE cast(value as int)
END minutes
from
input, split(input.line, ",")
where
input.rowid = 2;
-- Part 1
with range(i) as (
select time from earliest_departure
union all
select i+1 from range limit
(select product(minutes) from bus_intervals)
)
select
(min(range.i) - earliest_departure.time) * bus_intervals.minutes
from
bus_intervals,
earliest_departure,
range
where
range.i % bus_intervals.minutes = 0
and
bus_intervals.minutes != 0;
-- Part 2
-- In which we implement the Chinese Remainder Theorem in SQL
with
pairs(x, mod) as (
select rowid-1, minutes from bus_intervals where minutes != 0
),
product(value) as (
select product(minutes) from bus_intervals where minutes != 0
),
multiplicative_inverse(key, a, b, x, y) as (
select
pairs.mod,
product.value / pairs.mod, pairs.mod,
0, 1
from
pairs, product
union all
select
key,
b, a%b,
y - (a/b)*x, x
from
multiplicative_inverse
where
a>0
) select
product.value - sum(
(pairs.mod+y % pairs.mod) * pairs.x * (product.value / pairs.mod)
) % product.value
from
multiplicative_inverse, product, pairs
where
a=1 and multiplicative_inverse.key = pairs.mod;
<file_sep>CREATE TEMPORARY TABLE input(code TEXT);
.mode csv
.import 12_input.txt input
-- Pre process
CREATE TEMPORARY TABLE instructions as
select
substr(code, 1, 1) as operation,
cast(substr(code, 2) as int) as amount
from
input
;
create temporary table range(i int);
with loop(i) as (
select 1
union all
select i+1 from loop
limit (select count(*) from instructions)
) insert into range select * from loop;
-- Part 1
with iteration(i, x, y, direction) as (
select 1, 0, 0, 90
union all
select
iteration.i+1,
CASE
WHEN
ins.operation = "E" or (iteration.direction = 90 and ins.operation = "F")
THEN
iteration.x + ins.amount
WHEN
ins.operation = "W" or (iteration.direction = 270 and ins.operation = "F")
THEN
iteration.x - ins.amount
ELSE
iteration.x
END,
CASE
WHEN
ins.operation = "N" or (iteration.direction = 0 and ins.operation = "F")
THEN
iteration.y + ins.amount
WHEN ins.operation = "S" or (iteration.direction = 180 and ins.operation = "F")
THEN iteration.y - ins.amount
ELSE
iteration.y
END,
CASE
WHEN ins.operation = "R" THEN (iteration.direction + ins.amount + 360) % 360
WHEN ins.operation = "L" THEN (iteration.direction - ins.amount + 360) % 360
ELSE iteration.direction
END
from
instructions ins,
range,
iteration
where
ins.rowid = range.i
and
iteration.i = range.i
limit
(select count(*) from instructions) + 1
)
select abs(x) + abs(y) from iteration order by i desc limit 1;
-- Part 2
with iteration(i, x, y, wx, wy) as (
select 1, 0, 0, 10, 1
union all
select
iteration.i+1,
CASE
WHEN ins.operation = "F" THEN iteration.x + (ins.amount * iteration.wx)
ELSE iteration.x
END,
CASE
WHEN ins.operation = "F" THEN iteration.y + (ins.amount * iteration.wy)
ELSE iteration.y
END,
CASE
WHEN ins.operation = "E" THEN iteration.wx + ins.amount
WHEN ins.operation = "W" THEN iteration.wx - ins.amount
WHEN (ins.operation = "L" and ins.amount = 90) THEN -iteration.wy
WHEN (ins.operation = "L" and ins.amount = 180) THEN -iteration.wx
WHEN (ins.operation = "L" and ins.amount = 270) THEN iteration.wy
WHEN (ins.operation = "R" and ins.amount = 90) THEN iteration.wy
WHEN (ins.operation = "R" and ins.amount = 180) THEN -iteration.wx
WHEN (ins.operation = "R" and ins.amount = 270) THEN -iteration.wy
ELSE
iteration.wx
END,
CASE
WHEN ins.operation = "N" THEN iteration.wy + ins.amount
WHEN ins.operation = "S" THEN iteration.wy - ins.amount
WHEN (ins.operation = "L" and ins.amount = 90) THEN iteration.wx
WHEN (ins.operation = "L" and ins.amount = 180) THEN -iteration.wy
WHEN (ins.operation = "L" and ins.amount = 270) THEN -iteration.wx
WHEN (ins.operation = "R" and ins.amount = 90) THEN -iteration.wx
WHEN (ins.operation = "R" and ins.amount = 180) THEN -iteration.wy
WHEN (ins.operation = "R" and ins.amount = 270) THEN iteration.wx
ELSE
iteration.wy
END
from
instructions ins,
range,
iteration
where
ins.rowid = range.i
and
iteration.i = range.i
limit
(select count(*) from instructions) + 1
)
select abs(x) + abs(y) from iteration order by i desc limit 1;<file_sep>create table expense_report(entry int);
.mode csv
.import 01_input.txt expense_report
-- Part 1
select
distinct (a.entry * b.entry)
from
expense_report a,
expense_report b
where
a.entry + b.entry = 2020;
-- Part 2
select
distinct (a.entry * b.entry * c.entry)
from
expense_report a,
expense_report b,
expense_report c
where
a.entry + b.entry + c.entry = 2020;
<file_sep>.load ../utils/split.dylib
create table inputs(line text);
.mode csv
.separator \t
.import 07_input.txt inputs
create table bag_rules as with cleanup(rule) as (
select
replace(
replace(
replace(
replace(line, ".", ""),
" bags contain ",
":"
),
" bags",
""
),
" bag",
""
)
from
inputs
),
outer_inner(outside, inside) as (
select
substr(rule, 0, instr(rule, ":")),
substr(rule, instr(rule, ":")+1)
from
cleanup
),
rules(colour, amount, other_colour) as (
select
outside colour,
cast(
substr(
trim(split.value," "),
0,
instr(trim(split.value), " ")
) as int) amount,
substr(
trim(split.value," "),
instr(trim(split.value), " ")+1
) other_colour
from
outer_inner,
split(outer_inner.inside, ",")
) select * from rules;
-- Part 1
WITH results(current_colour) as (
select "shiny gold"
UNION ALL
select colour from bag_rules, results where other_colour = current_colour
)
-- Knock off 1 for "shiny gold" being in the result set
select count(distinct current_colour) - 1 from results;
-- Part 2
WITH results(current_colour, running_total) as (
select "shiny gold", 1
UNION ALL
select other_colour, running_total * amount from bag_rules, results where colour = current_colour
)
-- Knock off 1 for "shiny gold" being in the result set
select sum(running_total) - 1 from results;<file_sep>-- Part 1
with game(round, last_number, entries) as (
select 7, 18, json_object(
"2", 1,
"0", 2,
"1", 3,
"7", 4,
"4", 5,
"14", 6
)
union all
select
round+1,
CASE
WHEN json_extract(entries, "$."|| last_number) IS NULL THEN 0
ELSE round - json_extract(entries, "$."||last_number)
END,
json_set(entries, "$."||last_number, round)
from
game
limit
2020
) select last_number from game where round=2020;<file_sep>DROP TABLE IF EXISTS passports;
-- From SQLite extensions. Download regexp.c and compile
-- https://www.sqlite.org/src/file?name=ext/misc/regexp.c
.load regexp.dylib
CREATE TABLE passports(
birth_year TEXT, issue_year INT, expiry_year INT, height INT,
hair_colour TEXT, eye_colour TEXT, passport_id TEXT, country_id INT,
-- Generated columns to pull out unit and value from height
height_unit TEXT GENERATED ALWAYS AS (substr(height, -2)) STORED,
height_value INT GENERATED ALWAYS AS (substr(height, 0, length(height)-1)) STORED
);
INSERT INTO passports SELECT
json_extract(value, '$.byr'),
json_extract(value, '$.iyr'),
json_extract(value, '$.eyr'),
json_extract(value, '$.hgt'),
json_extract(value, '$.hcl'),
json_extract(value, '$.ecl'),
json_extract(value, '$.pid'),
json_extract(value, '$.cid')
FROM json_each(readfile('04_input.json'));
-- Part 1
select count(*) from passports where "" not in (
birth_year, issue_year, expiry_year, height, hair_colour, eye_colour, passport_id
);
-- Part 2
select count(*) from passports where
birth_year between 1920 and 2002 AND
issue_year between 2010 and 2020 AND
expiry_year between 2020 and 2030 AND
(
height_unit = 'cm' AND height_value between 150 and 193
OR
height_unit = 'in' AND height_value between 59 and 76
) AND
hair_colour regexp "#[0-9a-f]{6}" AND
eye_colour in ("amb","blu","brn","gry","grn","hzl","oth") AND
length(passport_id) = 9 order by 1 desc;
<file_sep>#include "sqlite3ext.h"
#include <assert.h>
#include <stdio.h>
#include <math.h>
SQLITE_EXTENSION_INIT1
typedef struct {
int count;
double fProd;
long long iProd;
}
productCtx;
void validateTypes(sqlite3_context *context, int a) {
if (a == SQLITE_NULL) {
sqlite3_result_error(context, "Null type.", -1);
}
if (a != SQLITE_INTEGER && a != SQLITE_FLOAT) {
sqlite3_result_error(context, "Incompatible type.", -1);
}
}
void productStep(sqlite3_context *context, int argc, sqlite3_value **argv) {
productCtx *p;
int valueType;
p = sqlite3_aggregate_context(context, sizeof(*p));
valueType = sqlite3_value_numeric_type(argv[0]);
validateTypes(context, valueType);
if (p) {
if (valueType == SQLITE_INTEGER) {
int value = sqlite3_value_int64(argv[0]);
if (p->iProd == 0) {
p->iProd = value;
} else {
p->iProd *= value;
}
} else {
double value = sqlite3_value_double(argv[0]);
if (p->fProd == 0.0) {
p->fProd = value;
} else {
p->fProd *= value;
}
}
p->count++;
}
}
void productFinalize(sqlite3_context *context) {
productCtx *p;
p = sqlite3_aggregate_context(context, 0);
if (!p || p->count <= 0) {
sqlite3_result_error(context, "Error calculating value.", -1);
}
if (p->iProd != 0) {
sqlite3_result_int64(context, p->iProd);
} else {
sqlite3_result_double(context, p->fProd);
}
}
int sqlite3_extension_init(
sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi
) {
(void) pzErrMsg;
SQLITE_EXTENSION_INIT2(pApi);
sqlite3_create_function(
db, "product", 1, SQLITE_UTF8, NULL, NULL, &productStep, &productFinalize
);
return SQLITE_OK;
}<file_sep>DROP TABLE IF EXISTS preamble;
CREATE TABLE preamble(value INT);
.mode csv
.import 09_input.txt preamble
DROP TABLE IF EXISTS missing_values;
CREATE TABLE missing_values(value INT);
-- Magic number is 5 for example, 25 for real input
INSERT INTO missing_values select * from preamble where value not in (
select a.value from preamble a, preamble b, preamble c
where a.value = (b.value + c.value)
and b.rowid BETWEEN a.rowid - 5 and a.rowid - 1
and c.rowid BETWEEN a.rowid - 5 and a.rowid - 1
)
and rowid > 5;
-- Part 1
select * from missing_values limit 1;
-- Part 2
WITH
bounded_pairs(lower, upper) AS (
select
a.rowid, b.rowid
from
preamble a, preamble b
where
b.rowid > a.rowid
)
select
min(value) + max(value)
from
preamble a, bounded_pairs b
where
a.rowid between b.lower AND b.upper
group by
lower, upper
having
sum(value) = (select * from missing_values limit 1);<file_sep>create table passwords(lower int, upper int, letter char, password text);
.mode csv
.import 02_input.txt passwords
-- Part 1
select
count(*)
from
passwords
where
length(password) - length(replace(password, letter, '')) between lower and upper;;
-- Part 2
select
count(*)
from
passwords
where
(substr(password, lower, 1) = letter) +
(substr(password, upper, 1) = letter) = 1;
| 6fdba8368d138c5418ab0e6bae717ee6284d2ccb | [
"Markdown",
"SQL",
"C",
"Shell"
] | 31 | SQL | mrwilson/advent-of-code-2020 | c39b1be48407d560a67bf8cdfa6b38a7399059b6 | acb6684008a7f20cd2b4cb48add70387a5b7dd48 |
refs/heads/master | <repo_name>windymelt/mini-tools<file_sep>/get-project-root-dir
#!/usr/bin/env ruby
# Prints project-root path into stdout.
# - If directory has README.* file, the directory is considered as root.
# If root not found, prints "/".
def get_root_dir(dir)
# if dir has README.*, it is considered as root directory.
if (Dir.glob('README.*').length > 0)
return Dir.getwd()
else
if (Dir.getwd() == "/")
return "/"
else
Dir.chdir("../") {
get_root_dir(Dir.getwd())
}
end
end
end
puts get_root_dir(Dir.getwd())<file_sep>/README.md
# mini-tools
開発に使えるちょっとしたツール
| a1b2e2c089c06a79cb5376d33527316d835e35f0 | [
"Markdown",
"Ruby"
] | 2 | Ruby | windymelt/mini-tools | 3afde9501749168ff758bb82d284e3dac95ce48f | 23c6ebe10c89e9cacb8646c84936f6d6b562ba58 |
refs/heads/master | <file_sep>package gologger
import (
"fmt"
"github.com/fatih/color"
"os"
"reflect"
"time"
)
type outputType int
const (
OutputError outputType = 1000
OutputNormal outputType = 1001
OutputWarning outputType = 1002
)
func innerElement(a []interface{}) []interface{} {
aa := a[0]
v := reflect.ValueOf(aa)
if v.Kind() != reflect.Slice {
return a
}
return innerElement(aa.([]interface{}))
}
type GoLogger struct {
LogLevel outputType
LogPath string
timeFormat string
isSetup bool
}
// TODO: Add support for different log levels
func (l *GoLogger) Setup() {
if !l.isSetup {
if l.timeFormat == "" {
l.timeFormat = time.UnixDate
}
l.isSetup = true
}
}
func (l *GoLogger) coloredOutput(ot outputType, a ...interface{}) {
var c *color.Color
switch ot {
case OutputError:
c = color.New(color.FgRed).Add(color.Bold)
case OutputWarning:
c = color.New(color.FgYellow).Add(color.Bold)
default:
c = color.New(color.FgCyan)
}
c.Println(a...)
}
func (l *GoLogger) writeToFile(message string) {
l.Setup()
if l.LogPath == "" {
return
}
if l.LogLevel == 1 {
go func(msg string) {
f, err := os.OpenFile(l.LogPath, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
l.coloredOutput(OutputError, "Error: could not write to octopus log file:", l.LogPath)
return
}
defer f.Close()
msg += "\n"
_, err = f.WriteString(msg)
if err != nil {
l.coloredOutput(OutputError, "Error: failed to write message to log file:", l.LogPath)
}
}(message)
}
}
func (l *GoLogger) log(ot outputType, a ...interface{}) {
l.Setup()
aa := innerElement(a)
args := fmt.Sprint(aa)
var pre string
switch ot {
case OutputError:
pre = "ERROR: "
case OutputWarning:
pre = "WARNING: "
case OutputNormal:
pre = ""
default:
fmt.Println("Error: output type:", ot, "is unknown")
pre = ""
}
msg := time.Now().Format(time.UnixDate) + " :: " + pre + args[1: len(args) - 1]
l.coloredOutput(ot, msg)
l.writeToFile(msg)
}
func (l *GoLogger) Log(a ...interface{}) {
l.log(OutputNormal, a)
}
func (l *GoLogger) Error(a ...interface{}) {
l.log(OutputError, a)
}
func (l *GoLogger) Warn(a ...interface{}) {
l.log(OutputWarning, a)
}
| 290724972f3d5421dd04365ecc97d0eb1547713d | [
"Go"
] | 1 | Go | kapitol-app/gologger | c2cce723356f02cd5a0e25d464702dc42f14acbd | 7714b900e4eb91d8506679cf96c0c5018d19b8d2 |
refs/heads/main | <repo_name>vovchello82/ms_teams_reservation_bot<file_sep>/main.go
package main
import (
"bytes"
"container/list"
"context"
"fmt"
"log"
"net/http"
"os"
"strconv"
"time"
"github.com/infracloudio/msbotbuilder-go/core"
"github.com/infracloudio/msbotbuilder-go/core/activity"
"github.com/infracloudio/msbotbuilder-go/schema"
)
var deququeChan = make(chan string)
var enququeChan = make(chan string)
var nextTurnNotificationChan = make(chan *schema.ConversationReference)
var timeoutNotificationChan = make(chan *schema.ConversationReference)
var webhook = os.Getenv("BOT_WEBHOOK")
// HTTPHandler handles the HTTP requests from then connector service
type HTTPHandler struct {
core.Adapter
activity.HandlerFuncs
*ReservationQueue
timeout int
}
func (ht *HTTPHandler) OnMessageFunc(turn *activity.TurnContext) (schema.Activity, error) {
message := turn.Activity.Text
answer := "I undestand following commands: lock, free, info"
ref := &schema.ConversationReference{
ActivityID: turn.Activity.ID,
User: turn.Activity.From,
Bot: turn.Activity.Recipient,
Conversation: turn.Activity.Conversation,
ChannelID: turn.Activity.ChannelID,
ServiceURL: turn.Activity.ServiceURL,
}
lenght := ht.Len()
if message == "free" {
answer = "There were no reservations for you anymore"
if ht.findElementByConversationId(ref.Conversation.ID) != nil {
deququeChan <- ref.Conversation.ID
answer = "Your reservation was removed"
}
} else if message == "lock" {
answer = fmt.Sprintf("%s, your reservation is arrived. %d reservations before you", ref.User.Name, lenght)
if lenght == 0 {
answer = fmt.Sprintf("%s, your can immediately start", ref.User.Name)
}
ht.enquque(ref)
} else if message == "info" {
answer = fmt.Sprintf("The timeout is %d seconds. There are %d reservations in the quque", ht.timeout, lenght)
for e := ht.Front(); e != nil; e = e.Next() {
answer += fmt.Sprintf(" ->%s", e.Value.(*schema.ConversationReference).User.Name)
}
}
return turn.SendActivity(activity.MsgOptionText(answer))
}
func (ht *HTTPHandler) processMessage(w http.ResponseWriter, req *http.Request) {
ctx := context.Background()
act, err := ht.Adapter.ParseRequest(ctx, req)
if err != nil {
log.Printf("Failed to process request: %s", err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
err = ht.Adapter.ProcessActivity(ctx, act, ht.HandlerFuncs)
if err != nil {
log.Printf("Failed to process request: %s", err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
log.Println("Request processed successfully")
}
func NewHTTPHandler(adapter core.Adapter) *HTTPHandler {
timeout, err := strconv.Atoi(os.Getenv("BOT_TIMEOUT"))
if err != nil {
timeout = 15
}
quque := NewTimedReservationQueue(timeout)
ht := &HTTPHandler{adapter, activity.HandlerFuncs{}, quque, timeout}
ht.HandlerFuncs.OnMessageFunc = ht.OnMessageFunc
go func() {
for {
select {
case el := <-timeoutNotificationChan:
ht.sendNotificationToConversation(el, "you are timeouted. please make resources free")
case el := <-nextTurnNotificationChan:
if el == nil {
go sendWebHook(`{"text": "dev is free now"}`)
} else {
go sendWebHook(`{"text": "` + el.User.Name + ` locked dev"}`)
ht.sendNotificationToConversation(el, el.User.Name+", it's your turn!")
}
}
}
}()
return ht
}
func sendWebHook(text string) {
if webhook == "" {
return
}
var jsonStr = []byte(text)
req, err := http.NewRequest("POST", webhook, bytes.NewBuffer(jsonStr))
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Printf("Failed to process request: %s", err)
return
}
defer resp.Body.Close()
log.Printf("response Status: %s", resp.Status)
}
func (ht *HTTPHandler) sendNotificationToConversation(conv *schema.ConversationReference, text string) {
if conv != nil {
ht.Adapter.ProactiveMessage(context.TODO(), *conv, activity.HandlerFuncs{
OnMessageFunc: func(turn *activity.TurnContext) (schema.Activity, error) {
return turn.SendActivity(activity.MsgOptionText(text))
},
})
}
}
type ReservationQueue struct {
*list.List
}
func NewTimedReservationQueue(timeout int) *ReservationQueue {
reservation_quque := ReservationQueue{list.New()}
go func() {
duration := time.Duration(timeout) * time.Second
timer := time.NewTimer(duration)
if !timer.Stop() {
<-timer.C
}
running := false
for {
select {
case <-timer.C:
running = false
timeoutPop := reservation_quque.Front()
if timeoutPop != nil {
log.Printf("time is over for %s", timeoutPop.Value.(*schema.ConversationReference).Conversation.ID)
reservation_quque.Remove(timeoutPop)
timeoutNotificationChan <- timeoutPop.Value.(*schema.ConversationReference)
}
if reservation_quque.Len() > 0 {
nextReservation := reservation_quque.Front()
log.Printf("next reservation started for %s", nextReservation.Value.(*schema.ConversationReference).Conversation.ID)
nextTurnNotificationChan <- nextReservation.Value.(*schema.ConversationReference)
timer.Reset(duration)
running = true
} else {
nextTurnNotificationChan <- nil
}
case id := <-deququeChan:
element := reservation_quque.findElementByConversationId(id)
if element != nil {
if reservation_quque.Len() <= 1 {
if !timer.Stop() && running {
<-timer.C
}
running = false
log.Printf("quque is empty now")
nextTurnNotificationChan <- nil
} else if element == reservation_quque.Front() {
nextReservation := element.Next()
log.Printf("next reservation started for %s", nextReservation.Value.(*schema.ConversationReference).Conversation.ID)
nextTurnNotificationChan <- nextReservation.Value.(*schema.ConversationReference)
timer.Reset(duration)
}
reservation_quque.Remove(element)
}
case <-enququeChan:
if !running {
timer.Reset(duration)
log.Printf("start timer")
running = true
element := reservation_quque.Front()
nextTurnNotificationChan <- element.Value.(*schema.ConversationReference)
}
}
}
}()
return &reservation_quque
}
func (rq *ReservationQueue) findElementByConversationId(convId string) *list.Element {
for e := rq.Front(); e != nil; e = e.Next() {
foundElement := e.Value.(*schema.ConversationReference)
if foundElement.Conversation.ID == convId {
return e
}
}
return nil
}
func (rq *ReservationQueue) enquque(conversation *schema.ConversationReference) {
log.Printf("add %s to the reservation quque with conid %s", conversation.User.ID, conversation.Conversation.ID)
rq.PushBack(conversation)
enququeChan <- conversation.Conversation.ID
}
func main() {
setting := core.AdapterSetting{
AppID: os.Getenv("APP_ID"),
AppPassword: <PASSWORD>("APP_PASSWORD"),
}
adapter, err := core.NewBotAdapter(setting)
if err != nil {
log.Fatal("Error creating adapter: ", err)
}
httpHandler := NewHTTPHandler(adapter)
http.HandleFunc("/api/messages", httpHandler.processMessage)
log.Println("Starting server on port:3978...")
http.ListenAndServe(":3978", nil)
}
<file_sep>/build.sh
#!/bin/bash
targetOs="linux"
if [[ $# == 1 ]]
then
targetOs=$1
fi
echo "build a executable for $targetOs paltform amd64"
env GOOS=$targetOs GOARCH=amd64 go build
<file_sep>/README.md
# reservation_bot
reservation bot for MS teams
<file_sep>/go.mod
module reservation_bot
go 1.15
require (
github.com/gorilla/mux v1.8.0
github.com/infracloudio/msbotbuilder-go v0.2.2
)
| 4906a3509794da3c24ccaef679462bcc0658ca43 | [
"Markdown",
"Go Module",
"Go",
"Shell"
] | 4 | Go | vovchello82/ms_teams_reservation_bot | a90e584b038d393e131191257ed6d57ede735cb1 | 0a267f7ab595e204de6be76451e429f7862bd301 |
refs/heads/master | <repo_name>loewenstein/bosh-aws-cpi-release<file_sep>/src/bosh_aws_cpi/bin/test-integration
#!/bin/bash
set -e
: ${AWS_ACCESS_KEY_ID:?}
: ${AWS_SECRET_ACCESS_KEY:?}
: ${AWS_DEFAULT_REGION:=us-west-1}
: ${AWS_PUBLIC_KEY_NAME:?}
: ${AWS_KMS_KEY_ARN:?}
export AWS_DEFAULT_REGION
export STATE_FILE=/tmp/integration-terraform-state.tfstate
export METADATA_FILE=/tmp/integration-terraform-metadata.$$.json
echo "#######################################################"
echo "Applying terraform. Metadata file at $METADATA_FILE"
echo "#######################################################"
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
RELEASE_DIR="$( cd ${DIR}/../../.. && pwd )"
task_script="${RELEASE_DIR}/ci/tasks/run-integration.sh"
terraform apply -state="${STATE_FILE}" \
-var "access_key=${AWS_ACCESS_KEY_ID}" \
-var "secret_key=${AWS_SECRET_ACCESS_KEY}" \
-var "region=${AWS_DEFAULT_REGION}" \
-var "env_name=$(hostname)-local-integration" \
"${RELEASE_DIR}/ci/assets/terraform"
jq -e --raw-output '.modules[0].outputs | map_values(.value)' "$STATE_FILE" > $METADATA_FILE
${RELEASE_DIR}/ci/tasks/run-integration.sh
terraform destroy -force -state="${STATE_FILE}" \
-var "access_key=${AWS_ACCESS_KEY_ID}" \
-var "secret_key=${AWS_SECRET_ACCESS_KEY}" \
-var "region=${AWS_DEFAULT_REGION}" \
-var "env_name=$(hostname)-local-integration" \
"${RELEASE_DIR}/ci/assets/terraform"
<file_sep>/ci/tasks/teardown.sh
#!/usr/bin/env bash
set -e
source /etc/profile.d/chruby.sh
chruby 2.1.7
# input
input_dir=$(realpath director-state/)
bosh_cli=$(realpath bosh-cli/bosh-cli-*)
chmod +x $bosh_cli
if [ ! -e "${input_dir}/director-state.json" ]; then
echo "director-state.json does not exist, skipping..."
exit 0
fi
if [ -d "${input_dir}/.bosh" ]; then
# reuse compiled packages
cp -r ${input_dir}/.bosh $HOME/
fi
pushd ${input_dir} > /dev/null
echo "deleting existing BOSH Director VM..."
$bosh_cli -n delete-env director.yml
popd
| 271f2ba922b0e9af592adc4e2f2b43a2292d5fbc | [
"Shell"
] | 2 | Shell | loewenstein/bosh-aws-cpi-release | 327d5993bd9323a68b6df281b0d00b94c72fbce2 | c76194bec1bc46b4aec6e9b3b2f02470e11c33b9 |
refs/heads/master | <repo_name>trahim/alexa<file_sep>/src/index.js
var Alexa = require('alexa-sdk');
var http = require('http');
var utils = require('util');
| 55e6899b23e2250540b2d100d2b4449b7e4c7507 | [
"JavaScript"
] | 1 | JavaScript | trahim/alexa | 993382292d67143cbf728a1460b402d02db15710 | 0c3474a47bcccadcb013c8bbf9b23cc9dad94c60 |
refs/heads/master | <repo_name>itache/noter-server<file_sep>/src/main/java/me/itache/service/NoteService.java
package me.itache.service;
import me.itache.entity.Note;
import me.itache.repository.NoteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;
import java.util.Set;
@Service
public class NoteService {
@Autowired
private NoteRepository taskRepository;
public Set<Note> getAll() {
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return taskRepository.getByUsername(user.getUsername());
}
public Note add(Note task){
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
task.setUsername(user.getUsername());
return taskRepository.saveAndFlush(task);
}
public void delete(Long id){
taskRepository.delete(id);
}
public Note update(Note task){
if(taskRepository.getOne(task.getId()) == null){
throw new IllegalArgumentException("Task "+task+" not exists");
}
return taskRepository.saveAndFlush(task);
}
public Note get(Long id) {
return taskRepository.findOne(id);
}
}
<file_sep>/src/main/java/me/itache/repository/NoteRepository.java
package me.itache.repository;
import me.itache.entity.Note;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import javax.transaction.Transactional;
import java.util.Set;
@Repository
@Transactional
public interface NoteRepository extends JpaRepository<Note, Long> {
Set<Note> getByUsername(String username);
}
| 3129458a0883f345d56c88aae3dddb7ccf66b4e8 | [
"Java"
] | 2 | Java | itache/noter-server | f8c1fedff5a2cd95870eada94aecd9d0233f3294 | 86464ae35816843e895cf08bfeb8178b1b58f838 |
refs/heads/master | <file_sep>window.addEventListener("scroll", function () {
var video = document.getElementById("video");
var herstartervideo = document.getElementById("herstartervideo");
console.log("er div #herstartervideo synlig?" + elFllVsbl( herstartervideo ) );
if (elFllVsbl(herstartervideo)) {
if (!(video.currentTime > 0)) {
video.play();
}
} else {
video.pause();
video.currentTime = 0;
}
}
)
function elFllVsbl(el) {
return ( el.getBoundingClientRect().top>=0 && el.getBoundingClientRect().bottom<window.innerHeight);
}
// sidste video java
window.addEventListener("scroll", function () {
var videomedlyd = document.getElementById("videomedlyd");
var sidstevideo = document.getElementById("sidstevideo");
console.log("er div #sidstevideo synlig?" + elFllVsbl( sidstevideo ) );
if (elFllVsbl ( sidstevideo )) {
if (!(videomedlyd.currentTime > 0)) {
videomedlyd.play();
}
} else {
videomedlyd.pause();
videomedlyd.currentTime = 0;
}
}
)
function elFllVsbl(el) {
return ( el.getBoundingClientRect().top>=0 && el.getBoundingClientRect().bottom<window.innerHeight);
}
console.log("The Face in the Sky by Super_Sigil (c) copyright 2012 Licensed under a Creative Commons Attribution Noncommercial (3.0) license. http://dig.ccmixter.org/files/Super_Sigil/40194");
| fd2f25b521a9c218b6f897f41d88e7bbea670108 | [
"JavaScript"
] | 1 | JavaScript | Silletang/colorcloudstudioknit | f2c7d343a57c6d0d8c10cc29fbdf9ee095908a99 | 88c24a5b8d3c1e24fe7e39e358a3bad82a082abb |
refs/heads/master | <repo_name>SherryPing/qapmasrc<file_sep>/Component/OrderCard/LightDeliverOrderCard.jsx
/**
* @author moorwu
*/
import {Input,View, Text,ScrollView,Image,TouchableHighlight} from 'nuke';
import {createElement, Component,render} from 'rax';
import styles from './rxscss/OrderCard.rxscss';
import QN from 'QAP-SDK';
class LightDeliverOrderCard extends Component {
constructor() {
super();
this.mail_no=undefined;
this.state={
data:null,
orderStatus:null, //如果这个值存在,那么会覆盖订单信息中的对应状态,以这个信息作为显示
showOuterid:undefined,
refresh:false
}
}
componentWillMount() {
this.mail_no=this.props.mail_no;
}
barCode(tid){
QN.scan(result => {
// console.log(result.data);
this.mail_no=result.data.data;
this.refs['mail_no_'+tid].setState({value:this.mail_no});
// this.setState({refresh:!this.state.refresh});
});
}
renderStartOuterIdArea(trade){
if(this.state.showOuterid==undefined){
this.state.showOuterid=this.props.show_outerid;
}
if(this.state.showOuterid){
return (
<View style={{flexDirection:'row',alignItems:'center',paddingRight:'24rem',paddingTop:'16rem'}}>
<View style={{flex:8}}><Input ref={'mail_no_'+trade.tid} value={this.mail_no} inputStyle={{fontSize:'28rem'}} style={{paddingLeft:"0rem",marginLeft:"24rem",marginBottom:'16rem'}} type="enclosed" multiple={false} placeholder="填写快递单号或扫码" onInput={(value)=>{this.mail_no=value.value;}} /></View>
<TouchableHighlight onPress={this.barCode.bind(this,trade.tid)} style={{style:2,justifyContent:'center',alignItems:'center'}}><Image source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/smfh.png'}} style={{width:'50rem',height:'50rem'}}/></TouchableHighlight>
</View>
)
}
}
render(){
if(this.state.data==null){
this.state.data=this.props.dataSource;
}
let trade=this.state.data;
const self=this;
let customStyles=this.props.style?this.props.style:undefined;
return (
<View style={[styles.container,{marginTop:'20rem',marginBottom:'0rem',borderBottomWidth:'2rem',borderTopWidth:'2rem',borderColor:'#e2e3e8'},customStyles]}>
<View style={{paddingTop:'16rem',paddingBottom:'16rem',marginLeft:'24rem',marginRight:'24rem',borderBottomWidth:'2rem',borderColor:'#eff0f4'}}>
<View style={{flexDirection:'row',paddingBottom:'16rem',alignItems:'center'}}>
<Image source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/gn_01.png'}} style={{width:'28rem',height:'28rem'}}/>
<Text style={[grid_styles.order_buyernick]}>{trade.buyer_nick}</Text>
</View>
<View>
<Text style={grid_styles.order_address_block}>{trade.receiver_name},{trade.receiver_mobile},{trade.receiver_state},{trade.receiver_city},{trade.receiver_district},{trade.receiver_address}</Text>
</View>
</View>
{this.renderStartOuterIdArea(trade)}
</View>
);
}
}
const grid_styles={
titleconationer:{
borderStyle:'solid',
borderBottomWidth:'2rem',
borderTopWidth:'0rem',
borderLeftWidth:'0rem',
borderRightWidth:'0rem',
borderColor:'#e2e3e8',
justifyContent: 'center',
paddingTop:'20rem',
paddingBottom:'20rem',
paddingLeft:'20rem',
paddingRight:'20rem'
},
order_address_block:{
fontSize:'28rem',
lines:'2',
lineHeight:'34rem',
color:'#3D4145'
},
left:{
flex: 2,
flexWrap:'nowrap',
flexDirection:'row',
// paddingTop:'5rem',
paddingBottom:'0rem', //5
// marginTop:'8rem',
marginBottom:'0rem', //8
alignItems:'center',
},
right:{
flex: 3,
flexWrap:'nowrap',
flexDirection:'row',
justifyContent:'flex-end',
alignItems:'center',
paddingBottom:'0rem', //5
marginBottom:'0rem' //8
},
order_title_flag:{
alignSelf:'flex-end',
},
order_buyernick:{
color:'#5F646E',
fontSize:'28rem',
flexWrap:'nowrap',
marginLeft:'5rem'
},
buyer_comment:{
fontSize:'28rem',
marginRight:'5rem',
color:'#999999'
},
box:{
marginLeft:'10rem',
borderStyle:'solid',
borderWidth:'0rem',
borderTopWidth:'2rem',
borderColor:'#eff0f4',
paddingTop:'10rem',
marginTop:'10rem',
marginBottom:'0rem'
},
message:{
color:'#999999',
fontSize:'28rem',
paddingLeft:'24rem',
paddingRight:'2rem',
paddingTop:'10rem',
paddingBottom:'0rem',
}
}
export default LightDeliverOrderCard;
<file_sep>/Component/TradeDetails/TradeDetailsBuyerInfo.jsx
/**
* @author cbl
*/
import {createElement, Component,render} from 'rax';
import { View, Text, Image,TouchableHighlight,Modal} from 'nuke';
import QN from 'QAP-SDK';
class TradeDetailsBuyerInfo extends Component {
constructor() {
super();
}
copyMessage(){
QN.clipboard.setText(this.props.dataSource.buyer_message,(result)=>{
Modal.toast('买家留言已复制');
});
}
componentWillMount(){
}
render() {
const trade=this.props.dataSource;
if (trade.buyer_message == '' || trade.buyer_message == undefined) {
return ;
}
return (
<View style={styles.wrapper}>
<TouchableHighlight onPress={this.copyMessage.bind(this)} style={{paddingTop:'20rem',paddingBottom:'20rem',flex:1,flexDirection:'row',alignItems:'center'}}>
{/* <Image source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/gn_05.png'}} style={{width:'40rem',height:'40rem',marginTop:'5rem',marginLeft:'24rem',marginRight:'24rem'}} /> */}
<View style={{flex:1,paddingRight:'40rem',marginLeft:'24rem'}}>
<Text style={styles.text_buyer}>买家留言</Text>
<View style={{flexDirection:'row',alignItems:'flex-start',justifyContent:'space-between',flex:1}}>
<Text style={styles.text}>{trade.buyer_message}</Text>
<Image source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/fz_new.png'}} style={{width:'30rem',height:'30rem',marginTop:'10rem'}} />
</View>
</View>
</TouchableHighlight>
</View>
);
}
}
const styles={
wrapper:{
backgroundColor:'#FFFFFF',
borderBottomWidth:"2rem",
borderBottomStyle:"solid",
borderBottomColor:"#e2e3e8"
},
text_buyer:{
color:'#333333',
fontSize:'28rem'
},
text:{
color:'#999999',
fontSize:'24rem',
marginTop:'10rem',
lines:'0',
width:'670rem'
},
}
export default TradeDetailsBuyerInfo;
<file_sep>/AutoevaWaitLog.jsx
/*
*@author dsl
*/
import { ListView ,Modal,View, Text,TouchableHighlight,Image} from 'nuke';
import {createElement, Component,render} from 'rax';
import QN from 'QAP-SDK';
import {UserContact} from 'Biz/User/UserContact.jsx';
import {Network} from './Component/Common/Network.jsx';
import {GetTradeList} from './Biz/Order/GetTrade.jsx';
import {getAllUserInfos} from './Biz/User/GetAllUserInfos.jsx';
import {DoBeacon} from 'Biz/Common.jsx';
class AutoevaWaitLog extends Component {
constructor() {
super();
this.res=[];
this.page=0;
this.allpage=0;
this.userNick="";
this.state={
urightcor:"成功",
autorateLog:"success_log",
color_urg:"#00c279",
'radiock':1,
'dsqp_house':23,/*指定回评的参数*/
'dspj_day':5,
'dspj_house':23
}
}
componentWillMount(){
getAllUserInfos({
callback: (result)=>{
if(result.sub_user_nick){
this.userNick = result.sub_user_nick;
}else{
this.userNick = result.userNick;
}
this.isifget();
},
error_callback:(error)=>{
}
});
QN.showLoading({
query: {
text: '加载中~'
}
});
}
/*判断获取哪种数据*/
isifget(){
QN.localstore.get({
query:{
key: "autorate"
}
}).then(result => {
let res=result.data.autorate;
this.state.autorateLog=res;
this.laGetMoth();
}, error => {
QN.hideLoading();
Modal.toast("加载失败:"+error);
});
}
/*获取数据 */
laGetMoth(){
let page=this.page+1;
let autorateLog=this.state.autorateLog;
if(autorateLog=="wait_log"){
this.waitLog(page);
}else if(autorateLog=="success_log"||autorateLog=="fail_log"){
this.rateLog(page);
}else if(autorateLog=="black_log"){/*黑名单*/
this.getBlackLog(page);
}else{/*中差评提醒记录*/
this.getEmailLog(page);
}
}
/*发送旺旺信息*/
sendWorld(buyer_nick){
UserContact({
status:'other',
value:"",
buyer_nick:buyer_nick
});
}
/*查找中差评提醒记录*/
getEmailLog(page){
DoBeacon('TD20170114090141','zhongchapjl',this.userNick);/*进入中差评提醒记录埋点*/
Network.Post('/jy2/emaillogs',{page:page,allpage:'',total:'',tm:'near_one_week'},(rsp)=>{
let total=rsp.total>0?rsp.total:0;
if(total>0){
let allpage=rsp.allpage;
if(allpage<page){
return;
}else{
let allres=this.res;
let toal=allres.concat(rsp.zdpj);
this.setState({
res:this.res=toal,
page:this.page=page,
allpage:this.allpage=allpage
});
}
}
QN.hideLoading();
},{mode: 'jsonp'},(error_callback)=>{
QN.hideLoading();
Modal.toast(JSON.stringify(error_callback));
})
}
/*查找黑名单拦截记录*/
getBlackLog(page){
DoBeacon('TD20170114090141','heimingdanjilu',this.userNick);/*进入黑名单拦截记录埋点*/
Network.Post('/jy2/blacklogs',{page:page,allpage:'',total:'',tm:'near_one_week'},(rsp)=>{
let total=rsp.total>0?rsp.total:0;
if(total>0){
let allpage=rsp.allpage;
if(allpage<page){
return;
}else{
let allres=this.res;
let toal=allres.concat(rsp.zdpj);
this.setState({
res:this.res=toal,
page:this.page=page,
allpage:this.allpage=allpage
});
}
}
QN.hideLoading();
},{mode: 'jsonp'},(error_callback)=>{
QN.hideLoading();
Modal.toast(JSON.stringify(error_callback));
})
}
/*查找评价 成功 失败的订单*/
rateLog(page){
if(this.state.autorateLog=="fail_log"){
DoBeacon('TD20170114090141','shixiaosstck',this.userNick);/*失败的订单埋点*/
}else{
DoBeacon('TD20170114090141','sanshitianck',this.userNick);/*成功的订单埋点*/
}
let status=this.state.autorateLog=="fail_log"?0:1;
let urightcor=status==1?"成功":"失败";
let color_urg=status==1?"#00c279":"red";/*失败颜色 #e24b3e*/
Network.Post('/Jy2/zdratelogsx',{page: page,allpage: '',total: '',tm: 'near_one_mon',status: status},(rsp)=>{
let total=rsp.total>0?rsp.total:0;
if(total>0){
let allpage=rsp.allpage;
if(allpage<page){
return;
}else{
let allres=this.res;
let toal=allres.concat(rsp.zdpj);
this.setState({
res:this.res=toal,
page:this.page=page,
allpage:this.allpage=allpage,
urightcor:this.state.urightcor=urightcor,
color_urg:color_urg
});
}
}
QN.hideLoading();
},{mode: 'jsonp'},(error_callback)=>{
QN.hideLoading();
Modal.toast(JSON.stringify(error_callback));
})
}
format(datatime,pattern) {
/*初始化返回值字符串*/
var returnValue = pattern;
/*正则式pattern类型对象定义*/
var format = {
"y+": datatime.getFullYear(),
"M+": datatime.getMonth()+1,
"d+": datatime.getDate(),
"H+": datatime.getHours(),
"m+": datatime.getMinutes(),
"s+": datatime.getSeconds(),
"S": datatime.getMilliseconds(),
"h+": (datatime.getHours()%12),
"a": (datatime.getHours()/12) <= 1? "AM":"PM"
};
/*遍历正则式pattern类型对象构建returnValue对象*/
for(var key in format) {
var regExp = new RegExp("("+key+")");
if(regExp.test(returnValue)) {
var zero = "";
for(var i = 0; i < RegExp.$1.length; i++) { zero += "0"; }
var replacement = RegExp.$1.length == 1? format[key]:(zero+format[key]).substring(((""+format[key]).length));
returnValue = returnValue.replace(RegExp.$1, replacement);
}
}
return returnValue;
};
/*执行显示数据*/
showWaitAPI(page){
let self=this;
var radiock=this.state.radiock;
var dsqp_house=this.state.dsqp_house;
var dspj_day=this.state.dspj_day;
var dspj_house=this.state.dspj_house;
/*通过接口获取数据 `buyernick` ,tid,optime*/
let status='TRADE_FINISHED';
let rate_status='RATE_UNSELLER';
GetTradeList({
pageNo:page,
status:status,
rate_status:rate_status,
callback: (result)=>{
let waitCout=result.trades_sold_get_response.total_results;
if(waitCout>0){
let onehouse=3600000;
let oneDay=onehouse*24;
let trades=result.trades_sold_get_response.trades.trade;
for(let i=0;i<trades.length;i++){
let obj={};
let end_time=trades[i].end_time;
if(radiock==1){/*指定回评*/
let oneMouse=onehouse*dsqp_house;
end_time=Number(new Date(end_time).getTime() +(oneDay*15)-oneMouse);
}else if(radiock==2){/*定时评价*/
let times=Number((oneDay*dspj_day)+(onehouse*dspj_house));
end_time=new Date(end_time).getTime() +times;
}
let myDate = new Date(end_time);
let optime=self.format(myDate,'y-M-d H:m:s');
obj.buyer_nick=trades[i].buyer_nick;
obj.tid=trades[i].tid;
// obj.tid=trades[i].tid_str?trades[i].tid_str:trades[i].tid;
obj.optime=optime;
self.res.push(obj);
}
}
let allpage=Math.ceil(Number(waitCout)/40);
self.setState({
res:self.res,
page:self.page=page,
allpage:self.allpage=allpage,
urightcor:self.state.urightcor="待评价",
color_urg:"#0894ec"
});
},
error_callback:(error)=>{
Modal.toast(error);
}
});
}
/*查找待执行订单*/
waitLog(page){
DoBeacon('TD20170114090141','daizhixingck',this.userNick);/*查找待执行订单埋点*/
let self=this;
Network.Post('/Jy2/getevaluate',{page: page,allpage: '',total: '',tm: 'near_one_mon',status: 0},(rsp)=>{
let total=rsp.assessTotal>0?rsp.assessTotal:0;
if(total>0){
let allpage=Math.ceil(Number(total)/10);
if(allpage<page){
return;
}else{
let allres=this.res;
let toal= allres.concat(rsp.zdpj);
this.setState({
res:this.res=toal,
page:this.page=page,
allpage:this.allpage=allpage,
urightcor:this.state.urightcor="待评价",
color_urg:"#0894ec"
});
}
}
QN.hideLoading();
},{mode: 'jsonp'},(error_callback)=>{
QN.hideLoading();
Modal.toast(JSON.stringify(error_callback));
});
}
/**
* 加载到底部时触发的事件
*/
handleLoadMore() {
let self = this;
let page=this.page;
let allpage=this.allpage;
if (page==allpage||page>allpage) {//最后一页数据
return;
}else{
this.laGetMoth();
}
}
/**
* 无限滚动输出
*/
renderFoot=()=>{
if(this.page<this.allpage){
return <View style={BadStyles.loading}><Text style={BadStyles.loadingText}>正在加载中...</Text></View>
}else{
return <View style={BadStyles.loading}><Text style={[BadStyles.loadingText,{alignSelf:'flex-start'}]}>数据加载完毕</Text></View>
}
}
/*show moth 单行渲染添加数据*/
itemCont(e){
let autorateLog=this.state.autorateLog;
if(autorateLog=="success_log"){
return(
<View style={BadStyles.borderChilOne}>
<Text style={BadStyles.borderChilTwo}>评价内容:{e.content}</Text>
<Text style={[BadStyles.borderChilThree,{color:"#999"}]}>评价时间:{e.opttime}</Text>
</View>
);
}else if(autorateLog=="fail_log"){
return(
<View style={BadStyles.borderChilOne}>
<Text style={[BadStyles.borderChilTwo,{color:"red"}]}>失败原因:{e.content}</Text>
<Text style={[BadStyles.borderChilThree,{color:"#999"}]}>评价时间:{e.opttime}</Text>
</View>
);
}else if(autorateLog=="wait_log"){/*待评价*/
return(
<View style={BadStyles.borderChilOne}>
<Text style={[BadStyles.borderChilThree,{color:"#5f646e"}]}>预计评价时间:{e.optime}</Text>
</View>
);
}
}
/**
* 单行渲染
*/
renderItem (e,n){
let xtid = e.trade;
if(xtid!=undefined){
xtid = e.trade.split('-')[1];
}
let autorateLog=this.state.autorateLog;
if(autorateLog=="success_log"||autorateLog=="fail_log"||autorateLog=="wait_log"){
let color_urg=this.state.color_urg;
let tid="";
if(color_urg=="#0894ec"){
tid=e.tid;
}else{
tid=e.tradeid;
}
return(
<View style={{display:'flex',flexDirection:'column',backgroundColor:'#ffffff',marginBottom:'24rem'}}>
<View style={{flexDirection:'row',justifyContent:'space-between',alignItems:'center',borderBottomWidth:"2rem",borderBottomStyle:"solid",borderBottomColor:"#e8e8e8",paddingTop:"20rem",paddingBottom:"20rem",height:"80rem",fontSize:"28rem"}}>
<Text style={BadStyles.textLeft}>订单号:{tid}</Text>
<Text style={[BadStyles.textRight,{color:color_urg}]}>{this.state.urightcor}</Text>
</View>
<View style={{paddingTop:"10rem",paddingBottom:"10rem",flexDirection:"column"}}>
<TouchableHighlight onPress={this.sendWorld.bind(this,e.buyer_nick)} style={[BadStyles.textLeft,{flexDirection:"row",alignItems:'center'}]}>
<Image source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/gn_01.png'}} style={{width:'28rem',height:'28rem'}}/>
<Text style={{fontSize:"30rem",marginLeft:'10rem'}}>{e.buyer_nick}</Text>
</TouchableHighlight>
{this.itemCont(e)}
</View>
</View>
)
}else if(autorateLog=="black_log"){/*黑名单拦截*/
return(
<View style={{display:'flex',flexDirection:'column',backgroundColor:'#ffffff',marginBottom:'24rem'}}>
<View style={{flexDirection:'row',justifyContent:'space-between',alignItems:'center',borderBottomWidth:"2rem",borderBottomStyle:"solid",borderBottomColor:"#e8e8e8",paddingTop:"20rem",paddingBottom:"20rem",height:"80rem"}}>
<Text style={[BadStyles.textLeft,{fontSize:'28rem'}]}>订单号:{xtid}</Text>
</View>
<View style={{paddingTop:"24rem",flexDirection:"column"}}>
<TouchableHighlight onPress={this.sendWorld.bind(this,e.buyernick)} style={[BadStyles.textLeft,{flexDirection:"row",alignItems:'center'}]}>
<Image source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/gn_01.png'}} style={{width:'28rem',height:'28rem'}}/>
<Text style={{fontSize:"28rem",lineHeight:'34rem',marginLeft:'10rem'}}>{e.buyernick}</Text>
</TouchableHighlight>
<View style={[BadStyles.borderChilOne,{marginTop:"24rem"}]}>
<Text style={BadStyles.borderChilTwo}>{e.reason}</Text>
<Text style={[BadStyles.borderChilThree,{color:"#999"}]}>拦截时间:{e.mytime}</Text>
</View>
</View>
</View>
)
}else{/*中差评提醒*/
let starts=e.starts=="1"?"成功":"失败";
let stcolor=e.starts=="1"?"#00c279":"#e24b3e";
return(
<View style={{display:'flex',flexDirection:'column',backgroundColor:'#ffffff',marginBottom:'24rem'}}>
<View style={{flexDirection:'row',justifyContent:'space-between',alignItems:'center',borderBottomWidth:"2rem",borderBottomStyle:"solid",borderBottomColor:"#e8e8e8",paddingTop:"20rem",paddingBottom:"20rem",height:"80rem"}}>
<Text style={[BadStyles.textLeft,{fontSize:'28rem'}]}>订单号:{xtid}</Text>
<Text style={[BadStyles.textRight,{color:stcolor}]}>{starts}</Text>
</View>
<View style={{paddingTop:"10rem",paddingBottom:"10rem",flexDirection:"column"}}>
<TouchableHighlight onPress={this.sendWorld.bind(this,e.buyernick)} style={[BadStyles.textLeft,{flexDirection:"row",alignItems:'center'}]}>
<Image source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/gn_01.png'}} style={{width:'28rem',height:'28rem'}}/>
<Text style={{fontSize:"30rem",marginLeft:'10rem'}}>{e.buyernick}</Text>
</TouchableHighlight>
<View style={BadStyles.borderChilOne}>
<Text style={BadStyles.borderChilTwo}>{e.email}</Text>
<Text style={[BadStyles.borderChilThree,{color:"#999"}]}>发送时间:{e.logtime}</Text>
</View>
</View>
</View>
)
}
}
render() {
return (
<ListView
dataSource={this.res}
renderRow={this.renderItem.bind(this)}
onEndReached={this.handleLoadMore.bind(this)}
renderFooter={this.renderFoot}
style={{backgroundColor:'#eff0f4'}}
/>
)
}
}
const BadStyles={
borderChilOne:{
paddingLeft:"30rem",
paddingRight:"24rem"
},
borderChilTwo:{
paddingTop:"10rem",
paddingBottom:"10rem",
borderBottomWidth:"2rem",
borderBottomStyle:"solid",
borderBottomColor:"#e8e8e8",
fontSize:"30rem"
},
borderChilThree:{
fontSize:"30rem",
paddingTop:"15rem",
paddingBottom:"15rem",
},
textLis:{
paddingLeft:"30rem",
paddingBottom:"10rem",
fontSize:"28rem"
},
textLeft:{
paddingLeft:"30rem",
flex:1
},
textRight:{
paddingRight:"24rem",
/* width:"350rem",
textOverflow:"ellipsis",
lines:1,
textAlign:"right",*/
/*color:" #0066FF"*/
},
loading:{
height:"80rem",
display:"flex",
flexDirection:"row",
backgroundColor:"#eff0f4",
alignItems:"center",
justifyContent:"center"
},
loadingText:{
color:"#666666"
}
}
render(<AutoevaWaitLog/>);
<file_sep>/More.jsx
/**
* @author wp
*/
import { Modal,Link,Button,Text, View,Image,TouchableHighlight,Env,Tabbar, Icon, Iconfont,ScrollView,Navigator} from 'nuke';
import {createElement, Component,render} from 'rax';
import QN from 'QAP-SDK';
import {PUBLIC} from './rxscss/public-style.jsx';
import {GoToView} from 'Biz/View/GoToView.jsx';
import ListBlock from 'Component/Common/ListBlock.jsx';
import MySettingcard from 'Component/Common/MySettingcard.jsx';
import {UserContact} from 'Biz/User/UserContact.jsx';
import {getAllUserInfos} from './Biz/User/GetAllUserInfos.jsx';
import {DoBeacon} from './Biz/Common.jsx';
import {StorageOper} from './Biz/View/StorageOper.jsx';
import {Network} from 'Component/Common/Network.jsx';
import {QueryAddress,getLogistics,ModifyAddress} from 'Biz/Order/logistics.jsx';
const { isWeex, isWeb, isQNWeb , isQNWeex , appInfo } = Env;
class More extends Component{
constructor() {
super();
this.state={
flag:false,
vipText:'',
vipSubText:'',
version:'版本区别',
vipBut:'',
avatar:'',
activeKey: {key: 'tab1'},
editNum:'',
pjNum:'',
sendAddress:undefined,
returnAddress:undefined,
onlineLogistics:undefined,
offlineLogistics:undefined,
hasGetData:false
}
this.userNick;
this.appInfo;
this.vipFlag;
this.vipTime;
this.flag = true;
this.res=[];
this.data=[];
this.data2=[]
}
/**
* 会在render函数前被执行
*/
componentWillMount(){
let self=this;
DoBeacon('TD20170114090141','wode',self.userNick);/*埋点*/
self.userNick = this.props.userInfo.user_nick;
self.vipFlag = this.props.userInfo.vipFlag;
self.vipTime = this.props.userInfo.vipTime;
self.avatar = this.props.userInfo.avatar;
StorageOper.localGet({
key:'ipCheck_'+self.userNick,
callback:(result)=>{
self.flag = result['ipCheck_'+self.userNick];
self.setState({flag:true});
},
errCallback:(result)=>{ //取不到缓存会走error
self.flag = true;
self.setState({flag:true});
}
});
}
/**
* 测试,联系客服接口
*/
contactKf(value){
let infoStr = "";
let appInfo_JSON = QN.uri.parseQueryString(appInfo);
infoStr += "来自设备:" + appInfo_JSON.deviceModel + " \r\n系统:" + appInfo_JSON.platform + " \r\n千牛版本:" + appInfo_JSON.appVersion + " \r\n";
if (this.vipFlag == 1) {
infoStr += "高级版:"+this.vipTime;
}else{
infoStr += "初级版:"+this.vipTime;
}
if (value) {
infoStr = infoStr + " \r\n" + value;
}
UserContact({
value:infoStr,
});
}
/*设置值为了跳转页面*/
GoToView(value){
DoBeacon('TD20170109140115','20170109ClickUpdate',this.userNick)/*埋点*/
// console.log(value);
GoToView({
status:value,
query:{userNick:encodeURI(this.userNick), vipFlag:this.vipFlag}
});
}
cxsq(){
Modal.confirm('是否确认授权',[
{
onPress:()=>{
this.webauth();
},
text: '确认'
},
{
onPress:()=>{},
text: '取消'
},
]);
}
//重新授权
webauth(){
getAllUserInfos({
callback: (result)=>{
if(result.sub_user_nick){
Modal.alert("子账号不支持授权!",[
{
onPress:()=>{},
text:"确定"
}
])
}else{
let url = "https://oauth.taobao.com/authorize?response_type=code&client_id=" + "21085840" + "&redirect_uri=" + "http://mtrade.aiyongbao.com/" + "/tc/trades2?scope=item&view=wap&state=" + "jy" + ",qapmobile&code=trade"
QN.navigator.push({
url: url,
title: '爱用交易',
success(result) {
},
error(error) {
// console.error(error);
}
});
}
},
error_callback:(error)=>{
}
});
}
ClearStorage(){
Modal.confirm('您确定要初始化爱用交易吗?该操作不会删除您本地的登陆、聊天记录、设置等数据',[
{
onPress:()=>{
QN.localstore.clear({
success(result) {
},
error(error) {
// console.log(error);
}
}).then(result => {
Modal.alert("初始化交易缓存成功,请关闭插件后重进",[
{
onPress:(e)=>{QN.navigator.close()},
text:"确定"
}
])
}, error => {
// console.log(error);
});
},
text: '确认'
},
{
onPress:()=>{},
text: '取消'
},
]);
}
Call(){
Navigator.push('tel:18116496170');
}
render(){
let customStyle=this.props.style?this.props.style:{}
let customBadgetStyle=this.props.rightTextStyle?this.props.rightTextStyle:{};
return (
<ScrollView style={[styles.tabContent]}>
<View style={styles.myCard}>
<TouchableHighlight onPress={this.ClearStorage.bind(this)}>
<MySettingcard img_source={{uri: 'http://q.aiyongbao.com/trade/web/images/qap_img/mobile/csh.png'}} mainTitle="初始化爱用交易" style={{borderBottomWidth:'0rem'}}></MySettingcard>
</TouchableHighlight>
</View>
<View style={styles.myCard}>
<TouchableHighlight onPress={this.cxsq.bind(this)}>
<MySettingcard img_source={{uri: 'http://q.aiyongbao.com/trade/web/images/qap_img/mobile/cxsq.png'}} mainTitle="重新授权" style={{borderBottomWidth:'0rem'}}></MySettingcard>
</TouchableHighlight>
</View>
<View style={styles.myCard}>
<Link href="https://fuwu.taobao.com/serv/manage_service.htm?service_code=FW_GOODS-1827490">
<MySettingcard img_source={{uri: 'http://q.aiyongbao.com/trade/web/images/qap_img/mobile/zan.png'}} mainTitle="我给爱用点个赞" style={{borderBottomWidth:'0rem'}}></MySettingcard>
</Link>
</View>
<View style={styles.myCard}>
<TouchableHighlight onPress={this.contactKf.bind(this,'')}>
<MySettingcard img_source={{uri: 'http://q.aiyongbao.com/trade/web/images/qap_img/mobile/aykf.png'}} mainTitle="爱用交易问题联系爱用客服" style={{borderBottomWidth:'0rem'}} right={false}></MySettingcard>
</TouchableHighlight>
</View>
<View style={styles.myCard}>
<Link href="tbsellerplatform://?session_event=event_back_platform&operation=use&appkey=21661765&service_id=event%3drobot%26sourceId%3d1406141535%26pscId%3d1">
<MySettingcard img_source={{uri: 'http://q.aiyongbao.com/trade/web/images/qap_img/mobile/txkf.png'}} mainTitle="淘宝问题联系淘宝客服" style={{borderBottomWidth:'0rem'}} right={false}></MySettingcard>
</Link>
</View>
<View style={styles.myCard}>
<TouchableHighlight onPress={this.Call.bind(this)}>
<MySettingcard img_source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/kfdh.png'}} mainTitle="客服电话" style={{borderBottomWidth:'0rem'}} right={false} tel={18116496170}></MySettingcard>
</TouchableHighlight>
</View>
<View style={styles.myCard}>
<TouchableHighlight onPress={this.contactKf.bind(this,'')}>
<MySettingcard img_source={{uri: 'http://q.aiyongbao.com/trade/web/images/qap_img/mobile/wtfk.png'}} mainTitle="我有问题要反馈" style={{borderBottomWidth:'0rem'}}></MySettingcard>
</TouchableHighlight>
</View>
</ScrollView>
)
}
}
const styles = {
index:{
height:'9000rem',
backgroundColor:'#eff0f4'
},
adv:{
marginTop:"20rem",
height:'200rem',
backgroundColor:'#ffffff'
},
button:{
height:'50rem',
width:'200rem',
backgroundColor:'orange'
},
myCard:{
marginTop:"24rem",
backgroundColor:"#ffffff",
},
tabContent:{
height:'9000rem',
},
}
export default More;
<file_sep>/Component/OrderCard/OrderMessageBlock.jsx
/** @jsx createElement */
import {createElement, Component,render} from 'rax';
import { View, Text,Image,TouchableHighlight,Modal} from 'nuke';
import styles from './rxscss/OrderCard.rxscss';
import QN from 'QAP-SDK';
import {GoToView} from 'Biz/View/GoToView.jsx';
import {UserContact} from 'Biz/User/UserContact.jsx';
import {DoBeacon} from 'Biz/Common.jsx';
class OrderMessageBlock extends Component {
constructor(){
super();
this.state = {
value:-1,
input_value:undefined
};
}
copyMessage(info){
QN.clipboard.setText(info,(result)=>{
Modal.toast('留言已复制');
});
}
copyMemo(info){
QN.clipboard.setText(info,(result)=>{
Modal.toast('备注已复制');
});
}
renderMessage(message){
if(message && message!=''){
return (
<TouchableHighlight onPress={this.copyMessage.bind(this,message)} style={grid_styles.box}>
{/* <Image source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/yicg.png'}} style={{width:'28rem',height:'28rem',marginLeft:'20rem',marginRight:'5rem'}}/> */}
<Text style={[grid_styles.message,{marginLeft:'20rem',marginRight:'20rem'}]}>留言:{message}</Text>
</TouchableHighlight>
)
}
}
renderMemo(){
let trade=this.props.message;
if(trade.seller_memo){
return (
<TouchableHighlight onPress={this.copyMemo.bind(this,trade.seller_memo)} style={grid_styles.box}>
{/* <Image source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/ly.png'}} style={{width:'28rem',height:'28rem',marginLeft:'20rem',marginRight:'5rem'}}/> */}
<Text style={[grid_styles.message,{marginLeft:'20rem',marginRight:'20rem'}]}>备注:{trade.seller_memo}</Text>
</TouchableHighlight>
)
}
}
renderSellerFlag(){
let trade=this.props.message;
let jsx=[];
if(!trade.seller_flag)
trade.seller_flag=0;
switch(trade.seller_flag){
case 0:
default:
//默认是灰色的
jsx.push(<Image source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/bj_04.png'}} style={{width:'28rem',height:'28rem'}}/>);
break;
case 1:
//默认是红色的
jsx.push(<Image source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/bj_03.png'}} style={{width:'28rem',height:'28rem'}}/>);
break;
case 2:
//默认是黄色的
jsx.push(<Image source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/bj_02.png'}} style={{width:'28rem',height:'28rem'}}/>);
break;
case 3:
//默认是绿色的
jsx.push(<Image source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/bj_01.png'}} style={{width:'28rem',height:'28rem'}}/>);
break;
case 4:
//默认是蓝色的
jsx.push(<Image source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/bj_06.png'}} style={{width:'28rem',height:'28rem'}}/>);
break;
case 5:
//默认是粉色的
jsx.push(<Image source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/bj_05.png'}} style={{width:'28rem',height:'28rem'}}/>);
break;
}
// if(trade.seller_memo)
// jsx.push(<Text style={grid_styles.buyer_comment}>{trade.seller_memo}</Text>)
return jsx;
}
groupChange(value){
this.setState({value:value});
}
onChange(value){
// console.log('onChange');
// console.log(value);
}
gotoModifyMemoPage(){
let self=this;
// console.log(self.props.message);
//这里去修改备注
//首先写缓存
QN.localstore.set({
query: {
modify_memo_data: self.props.message
},
success(result) {
//这里处理打开页面
GoToView({
title:'修改卖家备注',
status:'ModifySellerMemoPage',
callback:(result)=>{
// console.log(result);
//注册全局事件
// console.log('注册全局事件');
QN.on('app.modifymemo',(data)=>{
//首先关闭这个事件的注册
// console.log('事件传回的信息');
// console.log(data);
QN.off('app.modifymemo');
let trade=self.props.message;
trade.seller_flag=data.data.seller_flag;
trade.seller_memo=data.data.seller_memo;
self.props.card.setState({data:trade});
});
}
});
},
error(error) {
// console.error(error);
}
}).then(result => {
// console.log(result);
}, error => {
// console.log(error);
});
DoBeacon('TD20170114090141','djbeizhu');
}
UserContact(buyer_nick){
// console.error(buyer_nick);
UserContact({status:'miao',buyer_nick:buyer_nick});
}
renderGreyFlag(){
if (!this.props.message.buyer_message) {
return(
<TouchableHighlight onPress={this.gotoModifyMemoPage.bind(this)} style={[grid_styles.right,{height:'36rem',marginRight:'20rem'}]}>
{this.renderSellerFlag()}
</TouchableHighlight>
)
}
}
render(){
let buyer_nick=this.props.buyer;
let m=this.props.message.buyer_message;
let buyer_comment=this.props.buyer_comment;
buyer_comment='';
return (
<View ref="message" style={grid_styles.titleconationer}>
<View style={[{flexDirection:'row'}]}>
<TouchableHighlight onPress={this.UserContact.bind(this,buyer_nick)} style={[grid_styles.left,{height:'36rem'}]}>
<Image source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/gn_01.png'}} style={{width:'28rem',height:'28rem',marginLeft:'20rem'}}/>
<Text style={[grid_styles.order_buyernick]}>{buyer_nick}</Text>
{/* <Image source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/jt_y.png'}} width="20rem" height="20rem" style={{width:'20rem',height:'20rem',marginLeft:'10rem'}}/> */}
</TouchableHighlight>
<TouchableHighlight onPress={this.gotoModifyMemoPage.bind(this)} style={[grid_styles.right,{height:'36rem',marginRight:'20rem'}]}>
{this.renderSellerFlag()}
</TouchableHighlight>
</View>
{this.renderMessage(m)}
{this.renderMemo(m)}
</View>
);
}
}
var modal_styles = {
wrapper: {
// height: height,
paddingLeft: '24rem',
paddingRight: '24rem',
paddingTop: '24rem'
},
click: {
height: '100rem',
lineHeight: '100rem',
textAlign: 'center',
borderWidth: '1rem',
borderStyle: 'solid',
borderColor: '#ccc'
},
modalStyle: {
width: '640rem',
height: '340rem'
},
body: {
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#e5e5e5',
// height: '220rem'
},
footer: {
alignItems: 'center',
justifyContent: 'center',
height: '120rem'
},
button: {
width: '300rem',
height: '60rem',
borderWidth: '1rem',
borderStyle: 'solid',
borderColor: '#ccc',
alignItems: 'center',
justifyContent: 'center'
},
close: {
borderWidth: '1rem',
borderStyle: 'solid',
borderColor: '#ccc',
position: 'absolute',
top: '-18rem',
right: '-18rem',
alignItems: 'center',
justifyContent: 'center',
width: '40rem',
height: '40rem',
borderRadius: '20rem',
backgroundColor: '#ffffff'
},
closeText: {
fontSize: '28rem',
color: '#000000'
}
};
const grid_styles={
titleconationer:{
borderStyle:'solid',
borderBottomWidth:'1rem',
borderTopWidth:'0rem',
borderLeftWidth:'0rem',
borderRightWidth:'0rem',
borderColor:'#e2e3e8',
justifyContent: 'center',
paddingTop:'15rem',
paddingBottom:'15rem',
// paddingLeft:'20rem',
// paddingRight:'20rem'
},
left:{
flex: 2,
flexWrap:'nowrap',
flexDirection:'row',
// paddingTop:'5rem',
paddingBottom:'0rem', //5
// marginTop:'8rem',
marginBottom:'0rem', //8
alignItems:'center',
},
right:{
flex: 3,
flexWrap:'nowrap',
flexDirection:'row',
justifyContent:'flex-end',
alignItems:'center',
paddingBottom:'0rem', //5
marginBottom:'0rem' //8
},
order_title_flag:{
alignSelf:'flex-end',
},
order_buyernick:{
color:'#5F646E',
fontSize:'28rem',
flexWrap:'nowrap',
marginLeft:'5rem'
},
buyer_comment:{
fontSize:'28rem',
marginRight:'5rem',
color:'#999999',
// lines:1,
// textOverflow:'ellipsis'
},
box:{
flexDirection:'row',
alignItems:'center',
// marginLeft:'20rem',
// marginRight:'20rem',
borderStyle:'solid',
borderTopWidth:'1rem',
borderColor:'#e2e3e8',
paddingTop:'15rem',
marginTop:'15rem',
marginBottom:'0rem'
},
message:{
color:'#999999',
fontSize:'28rem',
// paddingLeft:'5rem',
// paddingRight:'2rem',
marginRight:'20rem',
width:'682rem'
}
}
export default OrderMessageBlock;
<file_sep>/Component/Common/SmsBuyLink.jsx
import {createElement, Component,render} from 'rax';
import { View, Text,TouchableHighlight} from 'nuke';
import {PUBLIC} from './../../rxscss/public-style.jsx';
class SmsBuyLink extends Component{
constructor(){
super();
}
render(){
// console.log(this.props.dataSource);
let dataSource = this.props.dataSource;
let has_buttom = this.props.buttom;
let style_buttom = styles.text;
if (has_buttom) {
style_buttom = styles.text+styles.buttom;
}
return(
<View style={[styles.list]}>
<Text style={[styles.text]}>{dataSource}</Text>
<View style={{alignSelf:'flex-end',height:'55rem',flex:'1'}}>
{/* <Button style={{backgroundColor:'#FFC125',color:'#'}}></Button> */}
<TouchableHighlight style={{marginTop:'5rem',backgroundColor:'#FFC125',borderStyle:'solid',borderColor:'#FFC125',borderWidth:'1rem',borderRadius:'8rem',width:'110rem',height:'50rem',alignItems:'center',justifyContent:'center'}}>
<Text style={{fontSize:'28rem',color:'#ffffff'}}>充值</Text>
</TouchableHighlight>
</View>
</View>
);
}
}
const styles={
list:{
height:"40rem",
flex:'1',
justifyContent:'center',
flexDirection:'row',
paddingRight:'24rem'
},
text:{
height:"40rem",
lineHeight:"40rem",
flex:'5',
fontSize:PUBLIC.FONT_LARGE
},
buttom:{
borderBottomWidth:'1rem',
borderStyle:'solid',
borderColor:"#000fff",
},
}
export default SmsBuyLink;
<file_sep>/Component/NavBar/NavBarItem.jsx
/**
* @author moorwu
*/
import {createElement, Component,render} from 'rax';
class NavBarItem extends Component {
constructor() {
super();
this.state={
folding:true,
activeKey:''
}
}
render(){
// console.log('item');
}
}
export default NavBarItem;
<file_sep>/Component/OrderCard/OrderBlocks.jsx
/**
* @author moorwu
*/
import {createElement, Component,render} from 'rax';
import { View,Text,TouchableHighlight,Image} from 'nuke';
import SubOrderBlock from './SubOrderBlock.jsx';
class OrderBlocks extends Component{
constructor(){
super();
this.state={
expanded:false
}
}
foldOrders(){
this.setState({expanded:false})
}
expandOrders(){
this.setState({expanded:true})
}
getStatus(order){
let status='待付款';
status=undefined;
switch(order.status){
case "WAIT_BUYER_PAY": //待付款
status='待付款';
break;
case "WAIT_SELLER_SEND_GOODS": //待发货
case "SELLER_CONSIGNED_PART": //卖家部分发货
status='待发货';
break;
case "WAIT_BUYER_CONFIRM_GOODS": //已发货
status='已发货';
break;
case "TRADE_FINISHED": //已成功
if(order.rate_status=='RATE_UNSELLER'){
status='待评价';
break;
}
status='已成功';
break;
case "TRADE_CLOSED_BY_TAOBAO": //已关闭
status='已关闭';
break;
case "TRADE_CLOSED":
status='已关闭';
break;
}
// console.error(order);
// if(order.refund_status=='"SUCCESS"'){
// status='退款成功';
// }
return status;
}
renderSubOrders(){
let self=this;
let no_tag=self.props.no_tag;
if(this.props.dataSource.orders.order.length>1){
//有多笔订单
if(this.state.expanded){
//展开情况
let jsx=this.props.dataSource.orders.order.map(function(order,index){
let outerid='';
if(order.outer_sku_id){
outerid=order.outer_sku_id;
}
else if(order.outer_iid){
outerid=order.outer_iid;
}
let sku=['',''];
if(order.sku_properties_name){
sku=order.sku_properties_name.split(';');
}
let order_status=self.getStatus(order);
if(no_tag=="1"){
return <SubOrderBlock onPress={this.props.onPress} isDetail={this.props.isDetail} tid={this.props.tid} rate_info={this.props.rate_info} userInfo={self.props.userInfo} newSublist={this.props.newSublist} dataSource={order} mainorder={this.props.dataSourcem} supplyList={self.props.supplyList} oidArr={this.props.oidArr} last={index==self.props.dataSource.length-1?true:false} order_status="" ref={'index_'+index} checkbox={self.props.checkbox?self.props.checkbox:false} default_checked={self.props.default_checked?self.props.default_checked:false} showPrice="" img={order.pic_path} title={order.title} outerid={outerid} sku={sku} list_price="" price="" num=""></SubOrderBlock>;
}else{
return <SubOrderBlock onPress={this.props.onPress} isDetail={this.props.isDetail} tid={this.props.tid} rate_info={this.props.rate_info} userInfo={self.props.userInfo} newSublist={this.props.newSublist} dataSource={order} mainorder={this.props.dataSourcem} supplyList={self.props.supplyList} oidArr={this.props.oidArr} last={index==self.props.dataSource.length-1?true:false} order_status={order_status==self.props.trade_status?undefined:order_status} ref={'index_'+index} checkbox={self.props.checkbox?self.props.checkbox:false} default_checked={self.props.default_checked?self.props.default_checked:false} showPrice={self.props.showPrice?self.props.showPrice:true} img={order.pic_path} title={order.title} outerid={outerid} sku={sku} list_price={order.price} price={order.price} num={order.num}></SubOrderBlock>;
}
});
let expandView=(
<TouchableHighlight style={{paddingTop:'24rem',paddingBottom:'24rem',justifyContent:'center',alignItems:'center',borderColor:'#eff0f4',borderTopWidth:'2rem',flexDirection:'row'}} onPress={this.foldOrders.bind(this)}>
<Text style={{color:'#999999',fontSize:'28rem'}}>收起宝贝 </Text>
<Image source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/jt_s.png'}} width="20rem" height="20rem" style={{width:'20rem',height:'20rem'}}/>
</TouchableHighlight>
);
jsx.push(expandView);
return jsx;
}else{
//锁紧状态(默认状态)
let index=0;
let jsx=[];
let order=this.props.dataSource.orders.order[index];
let outerid='';
if(order.outer_sku_id){
outerid=order.outer_sku_id;
}else if(order.outer_iid){
outerid=order.outer_iid;
}
let sku=['',''];
if(order.sku_properties_name){
sku=order.sku_properties_name.split(';');
}
let order_status=self.getStatus(order);
if(no_tag=="1"){
jsx.push(<SubOrderBlock onPress={this.props.onPress} isDetail={this.props.isDetail} tid={this.props.tid} rate_info={this.props.rate_info} userInfo={self.props.userInfo} newSublist={this.props.newSublist} dataSource={order} mainorder={this.props.dataSourcem}supplyList={self.props.supplyList} oidArr={this.props.oidArr} last={true} order_status="" ref={'index_'+index} checkbox={self.props.checkbox?self.props.checkbox:false} default_checked={self.props.default_checked?self.props.default_checked:false} showPrice="" img={order.pic_path} title={order.title} outerid={outerid} sku={sku} list_price="" price="" num=""></SubOrderBlock>);
}else{
jsx.push( <SubOrderBlock onPress={this.props.onPress} isDetail={this.props.isDetail} tid={this.props.tid} rate_info={this.props.rate_info} userInfo={self.props.userInfo} newSublist={this.props.newSublist} dataSource={order} mainorder={this.props.dataSourcem}supplyList={self.props.supplyList} oidArr={this.props.oidArr} last={true} order_status={order_status==self.props.trade_status?undefined:order_status} ref={'index_'+index} checkbox={self.props.checkbox?self.props.checkbox:false} default_checked={self.props.default_checked?self.props.default_checked:false} showPrice={self.props.showPrice?self.props.showPrice:true} img={order.pic_path} title={order.title} outerid={outerid} sku={sku} list_price={order.price} price={order.price} num={order.num}></SubOrderBlock>);
}
let expandView=(
<TouchableHighlight style={{paddingTop:'24rem',paddingBottom:'24rem',justifyContent:'center',alignItems:'center',borderColor:'#eff0f4',borderTopWidth:'2rem',flexDirection:'row'}} onPress={this.expandOrders.bind(this)}>
<Text style={{color:'#999999',fontSize:'28rem'}}>展开宝贝 </Text>
<Image source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/jt_x.png'}} width="20rem" height="20rem" style={{width:'20rem',height:'20rem'}}/>
</TouchableHighlight>
);
jsx.push(expandView);
return jsx;
}
}else{
//只有一笔订单的情况
//展开情况
let jsx=this.props.dataSource.orders.order.map(function(order,index){
let outerid='';
if(order.outer_sku_id){
outerid=order.outer_sku_id;
}else if(order.outer_iid){
outerid=order.outer_iid;
}
let sku=['',''];
if(order.sku_properties_name){
sku=order.sku_properties_name.split(';');
}
let order_status=self.getStatus(order);
if(no_tag=="1"){
return <SubOrderBlock onPress={this.props.onPress} isDetail={this.props.isDetail} tid={this.props.tid} rate_info={this.props.rate_info} userInfo={self.props.userInfo} newSublist={this.props.newSublist} dataSource={order} mainorder={this.props.dataSourcem}supplyList={self.props.supplyList} oidArr={this.props.oidArr} last={index==self.props.dataSource.length-1?true:false} order_status="" ref={'index_'+index} checkbox={self.props.checkbox?self.props.checkbox:false} default_checked={self.props.default_checked?self.props.default_checked:false} showPrice="" img={order.pic_path} title={order.title} outerid={outerid} sku={sku} list_price="" price="" num=""></SubOrderBlock>;
}else{
return <SubOrderBlock onPress={this.props.onPress} isDetail={this.props.isDetail} tid={this.props.tid} rate_info={this.props.rate_info} userInfo={self.props.userInfo} newSublist={this.props.newSublist} dataSource={order} mainorder={this.props.dataSourcem}supplyList={self.props.supplyList} oidArr={this.props.oidArr} last={index==self.props.dataSource.length-1?true:false} order_status={order_status==self.props.trade_status?undefined:order_status} ref={'index_'+index} checkbox={self.props.checkbox?self.props.checkbox:false} default_checked={self.props.default_checked?self.props.default_checked:false} showPrice={self.props.showPrice?self.props.showPrice:true} img={order.pic_path} title={order.title} outerid={outerid} sku={sku} list_price={order.price} price={order.price} num={order.num}></SubOrderBlock>;
}
});
return jsx;
}
}
renderSubOrdersWithoutExpand(){
let self=this;
let no_tag=self.props.no_tag;
// let jsx=this.props.dataSource.orders.order.map(function(order,index){
// let outerid='';
// if(order.outer_sku_id){
// outerid=order.outer_sku_id;
// }
// else if(order.outer_iid){
// outerid=order.outer_iid;
// }
// let sku=['',''];
// if(order.sku_properties_name){
// sku=order.sku_properties_name.split(';');
// }
// let order_status=self.getStatus(order);
// if(no_tag=="1"){
// return <SubOrderBlock onPress={this.props.onPress} userInfo={self.props.userInfo} newSublist={this.props.newSublist} dataSource={order} mainorder={this.props.dataSourcem}supplyList={self.props.supplyList} oidArr={this.props.oidArr} last={index==self.props.dataSource.length-1?true:false} order_status="" ref={'index_'+index} checkbox={self.props.checkbox?self.props.checkbox:false} default_checked={self.props.default_checked?self.props.default_checked:false} showPrice="" img={order.pic_path} title={order.title} outerid={outerid} sku={sku} list_price="" price="" num=""></SubOrderBlock>;
// }else{
// return <SubOrderBlock onPress={this.props.onPress} userInfo={self.props.userInfo} newSublist={this.props.newSublist} dataSource={order} mainorder={this.props.dataSourcem}supplyList={self.props.supplyList} oidArr={this.props.oidArr} last={index==self.props.dataSource.length-1?true:false} order_status={order_status==self.props.trade_status?undefined:order_status} ref={'index_'+index} checkbox={self.props.checkbox?self.props.checkbox:false} default_checked={self.props.default_checked?self.props.default_checked:false} showPrice={self.props.showPrice?self.props.showPrice:true} img={order.pic_path} title={order.title} outerid={outerid} sku={sku} list_price={order.price} price={order.price} num={order.num}></SubOrderBlock>;
// }
// });
let jsx = [];
let orders = this.props.dataSource;
let isExpandRefund = true;
let index = 0;
for (let i = 0; i < orders.length; i++) {
let outerid='';
if(orders[i].outer_sku_id){
outerid=orders[i].outer_sku_id;
}
else if(orders[i].outer_iid){
outerid=orders[i].outer_iid;
}
let sku=['',''];
if(orders[i].sku_properties_name){
sku=orders[i].sku_properties_name.split(';');
}
let order_status=self.getStatus(orders[i]);
if (orders[i].refund_id) {
if(no_tag=="1"){
jsx.push(<SubOrderBlock
onPress={this.props.onPress}
isDetail={this.props.isDetail}
isExpandRefund={isExpandRefund}
userInfo={self.props.userInfo} newSublist={this.props.newSublist}
mainorder={this.props.dataSourcem}
supplyList={self.props.supplyList} oidArr={this.props.oidArr}
dataSource={orders[i]}
last={index==self.props.dataSource.length-1?true:false}
order_status="" ref={'index_'+index}
checkbox={self.props.checkbox?self.props.checkbox:false}
default_checked={self.props.default_checked?self.props.default_checked:false}
showPrice="" img={orders[i].pic_path} title={orders[i].title} outerid={outerid} sku={sku} list_price="" price="" num=""
></SubOrderBlock>);
}else{
jsx.push(<SubOrderBlock
onPress={this.props.onPress}
isDetail={this.props.isDetail}
isExpandRefund={isExpandRefund}
userInfo={self.props.userInfo} newSublist={this.props.newSublist}
mainorder={this.props.dataSourcem}
supplyList={self.props.supplyList} oidArr={this.props.oidArr}
dataSource={orders[i]}
last={index==self.props.dataSource.length-1?true:false}
order_status={order_status==self.props.trade_status?undefined:order_status}
ref={'index_'+index}
checkbox={self.props.checkbox?self.props.checkbox:false}
default_checked={self.props.default_checked?self.props.default_checked:false}
showPrice={self.props.showPrice?self.props.showPrice:true}
img={orders[i].pic_path} title={orders[i].title} outerid={outerid} sku={sku} list_price={orders[i].price} price={orders[i].price} num={orders[i].num}></SubOrderBlock>);
}
isExpandRefund = false;
}else{
if(no_tag=="1"){
jsx.push(<SubOrderBlock onPress={this.props.onPress} isDetail={this.props.isDetail} tid={this.props.tid} rate_info={this.props.rate_info} userInfo={self.props.userInfo} newSublist={self.props.newSublist} mainorder={this.props.dataSourcem} supplyList={self.props.supplyList} oidArr={this.props.oidArr} dataSource={orders[i]} last={index==self.props.dataSource.length-1?true:false} order_status="" ref={'index_'+index} checkbox={self.props.checkbox?self.props.checkbox:false} default_checked={self.props.default_checked?self.props.default_checked:false} showPrice="" img={orders[i].pic_path} title={orders[i].title} outerid={outerid} sku={sku} list_price="" price="" num=""></SubOrderBlock>);
}else{
jsx.push(<SubOrderBlock onPress={this.props.onPress} isDetail={this.props.isDetail} tid={this.props.tid} rate_info={this.props.rate_info} userInfo={self.props.userInfo} newSublist={this.props.newSublist} mainorder={this.props.dataSourcem} supplyList={self.props.supplyList} oidArr={this.props.oidArr} dataSource={orders[i]} last={index==self.props.dataSource.length-1?true:false} order_status={order_status==self.props.trade_status?undefined:order_status} ref={'index_'+index} checkbox={self.props.checkbox?self.props.checkbox:false} default_checked={self.props.default_checked?self.props.default_checked:false} showPrice={self.props.showPrice?self.props.showPrice:true} img={orders[i].pic_path} title={orders[i].title} outerid={outerid} sku={sku} list_price={orders[i].price} price={orders[i].price} num={orders[i].num}></SubOrderBlock>);
}
}
index++;
}
// for (let i = 0; i < orders.length; i++) {
// if (!orders[i].refund_id) {
// let outerid='';
// if(orders[i].outer_sku_id){
// outerid=orders[i].outer_sku_id;
// }
// else if(orders[i].outer_iid){
// outerid=orders[i].outer_iid;
// }
// let sku=['',''];
// if(orders[i].sku_properties_name){
// sku=orders[i].sku_properties_name.split(';');
// }
// let order_status=self.getStatus(orders[i]);
// if(no_tag=="1"){
// jsx.push(<SubOrderBlock onPress={this.props.onPress} isDetail={this.props.isDetail} tid={this.props.tid} rate_info={this.props.rate_info} userInfo={self.props.userInfo} dataSource={orders[i]} last={index==self.props.dataSource.length-1?true:false} order_status="" ref={'index_'+index} checkbox={self.props.checkbox?self.props.checkbox:false} default_checked={self.props.default_checked?self.props.default_checked:false} showPrice="" img={orders[i].pic_path} title={orders[i].title} outerid={outerid} sku={sku} list_price="" price="" num=""></SubOrderBlock>);
// }else{
// jsx.push(<SubOrderBlock onPress={this.props.onPress} isDetail={this.props.isDetail} tid={this.props.tid} rate_info={this.props.rate_info} userInfo={self.props.userInfo} dataSource={orders[i]} last={index==self.props.dataSource.length-1?true:false} order_status={order_status==self.props.trade_status?undefined:order_status} ref={'index_'+index} checkbox={self.props.checkbox?self.props.checkbox:false} default_checked={self.props.default_checked?self.props.default_checked:false} showPrice={self.props.showPrice?self.props.showPrice:true} img={orders[i].pic_path} title={orders[i].title} outerid={outerid} sku={sku} list_price={orders[i].price} price={orders[i].price} num={orders[i].num}></SubOrderBlock>);
// }
// index++;
// }
// }
return jsx;
}
render(){
//console.log(this);
if (this.props.hasExpandOrders) {
return (
<View style={{borderColor:'#e2e3e8',borderWidth:'0rem',borderBottomWidth:'1rem'}}>
{this.renderSubOrders()}
</View>
)
} else {
return (
<View style={{borderColor:'#e2e3e8',borderWidth:'0rem',borderBottomWidth:'1rem'}}>
{this.renderSubOrdersWithoutExpand()}
</View>
)
}
}
}
export default OrderBlocks;
<file_sep>/BatchDeliverGoodsPage.jsx
/** @jsx createElement */
import { ActionSheet,Button,Modal,Input,Image,ScrollView,View, Text,TouchableHighlight} from 'nuke';
import {createElement, Component,render} from 'rax';
import QN from 'QAP-SDK';
import ListBlock from 'Component/Common/ListBlock.jsx';
import {GoToView} from 'Biz/View/GoToView.jsx';
import {GetLogisticsCompanies,LogisticsSend,BatchLogisticsSend,BatchSendWithoutLogistics} from 'Biz/Order/DeliverTrade.jsx';
import LightDeliverOrderCard from 'Component/OrderCard/LightDeliverOrderCard.jsx';
import {GetUserInfo} from 'Biz/User/GetUserInfo.jsx';
import {getLogistics,SetLastLogisticsInfo} from 'Biz/Order/logistics.jsx';
import {PaddingStringLeft} from 'Component/Common/StringUtil.jsx';
import {DoBeacon} from 'Biz/Common.jsx';
import MyButton from './Component/Common/MyButton.jsx';
let App = class BatchDeliverGoodsPage extends Component{
constructor(){
super();
this.state={
data:undefined,
defaultLogistics:undefined,
defaultAddress:undefined,
currentLogistics:undefined,
custom_company:undefined,
mail_no:undefined,
need_logistics:true,
refresh:false
}
}
componentWillMount(){
//获取要发货的货物信息
this.getTradeInfo();
//然后获取默认物流公司
this.getLogistics();
//然后获取默认退货地址
// this.getAddress();
}
//从缓存中取物流公司
getLogistics(){
GetUserInfo({callback:(result)=>{
this.nick=result.userNick;
let nick=result.userNick;
getLogistics(nick,(result)=>{
this.setState({defaultLogistics:result,currentLogistics:result.last_info});
});
}});
}
//获取要发货的订单信息
getTradeInfo(){
let self=this;
if(this.state.data==undefined){
QN.localstore.get({
query: {
key: 'batch_deliver_trade_data'
},
success(result) {
// console.log(result);
self.setState({data:result.data.batch_deliver_trade_data});
},
error(error) {
// console.log(error);
}
})
}
}
selectMoreLogisticsCompany(style,names,codes,ids){
let options=[...names,'取消'];
let cancelIndex=options.length-1;
ActionSheet.show({
options: options,//[...this.state.menu,'取消'],
cancelButtonIndex: cancelIndex,
title:'选择物流公司'
}, (ret) => {
// console.log(this.state);
if(ret.type=='button'){
if(ret.buttonIndex==cancelIndex){
return;
}
//如果发货方式和物流公司都和当前一样,什么也不做
if(style==this.state.currentLogistics.style && options[ret.buttonIndex]==this.state.currentLogistics.name){
return;
}
//如果都不是,那么准备切换场景了
let change_info={};
change_info.style=style;
change_info.name=options[ret.buttonIndex];
change_info.code=codes[ret.buttonIndex];
change_info.lwid=ids[ret.buttonIndex];
this.setState({currentLogistics:change_info,need_logistics:true});
}
}, (fail) => {
}, (notify)=>{
});
}
changeLogisticsCompany(style){
if(!this.state.need_logistics){
//无需物流下点击没有反应
return;
}
if(this.state.defaultLogistics && this.state.defaultLogistics[style] && this.state.defaultLogistics[style].name && this.state.defaultLogistics[style].name.length>0){
// console.error('读取常用信息');
let options=[...this.state.defaultLogistics[style].name,'更多','取消'];
let cancelIndex=options.length-1;
let moreIndex=options.length-2;
ActionSheet.show({
options: options,//[...this.state.menu,'取消'],
cancelButtonIndex: cancelIndex,
title:'选择物流公司'
}, (ret) => {
if(ret.type=='button'){
if(ret.buttonIndex==cancelIndex){
return;
}
if(ret.buttonIndex==moreIndex){
//这里需要处理更多的物流公司,需要从接口中拉取所有的物流公司
//然后再进行选择
GetLogisticsCompanies({style:style,callback:(result)=>{
// console.log(result);
let companies=result.logistics_companies_get_response.logistics_companies.logistics_company;
let company_names=companies.map((data,index)=>{
return data.name;
});
let company_codes=companies.map((data,index)=>{
return data.code;
});
let company_ids=companies.map((data,index)=>{
return data.lwid;
});
//然后准备弹出更多的选项
this.selectMoreLogisticsCompany(style,company_names,company_codes,company_ids);
}});
return;
}
//如果发货方式和物流公司都和当前一样,什么也不做
if(style==this.state.currentLogistics.style && options[ret.buttonIndex]==this.state.currentLogistics.name){
return;
}
//如果都不是,那么准备切换场景了
let change_info={};
change_info.style=style;
change_info.name=options[ret.buttonIndex];
change_info.code=this.state.defaultLogistics[style].code[ret.buttonIndex];
change_info.lwid=this.state.defaultLogistics[style].lwid[ret.buttonIndex];
this.setState({currentLogistics:change_info,need_logistics:true});
}
}, (fail) => {
}, (notify)=>{
});
}else{
//只好读取全部的
//这里需要处理更多的物流公司,需要从接口中拉取所有的物流公司
//然后再进行选择
// console.error('读取全部信息');
GetLogisticsCompanies({style:style,callback:(result)=>{
// console.error(JSON.stringify(result));
let companies=result.logistics_companies_get_response.logistics_companies.logistics_company;
var POSTCODES={};
for(var i in companies){
POSTCODES[companies[i].code]=companies[i].name;
}
// console.log(JSON.stringify(POSTCODES));
let company_names=companies.map((data,index)=>{
return data.name;
});
let company_codes=companies.map((data,index)=>{
return data.code;
});
let company_ids=companies.map((data,index)=>{
return data.lwid;
});
//然后准备弹出更多的选项
this.selectMoreLogisticsCompany(style,company_names,company_codes,company_ids);
}});
return;
}
}
changeLogisticsStyle(){
ActionSheet.show({
options: ['自己联系物流','在线下单','无需物流','取消'],//[...this.state.menu,'取消'],
cancelButtonIndex: 3,
title:'选择发货方式'
}, (ret) => {
if(ret.type=='button'){
if(ret.buttonIndex==3){
return;
}
// console.error(this.state.currentLogistics);
// console.log(ret);
//如果和当前一样,什么也不做
if((ret.buttonIndex==0 && this.state.currentLogistics.style=='offline')||(ret.buttonIndex==1 && this.state.currentLogistics.style=='online')||(ret.buttonIndex==2 && this.state.currentLogistics.style=='no')){
return;
}
if(ret.buttonIndex==2){
let currentLogistics=this.state.currentLogistics;
currentLogistics.style='no';
this.setState({need_logistics:false,currentLogistics:currentLogistics});
return;
}
this.setState({need_logistics:true});
//如果都不是,那么准备切换场景了
let style='offline';
if(ret.buttonIndex==1)
style='online';
this.changeLogisticsCompany(style);
}
}, (fail) => {
}, (notify)=>{
});
}
//实际的发货接口
deliver(){
if(this.state.need_logistics){
let bMissing=false;
this.mail_no=this.state.data.map((trade,index)=>{
var ldc=this.refs[trade.tid];
var mail_no=ldc.mail_no;
if(mail_no==undefined || mail_no==''){
bMissing=true;
}
return mail_no;
});
if(bMissing){
Modal.alert('请确保所有的订单均已填写单号',[{
onPress:()=>{},
text:'确定'
}]);
return;
}
let postCode=this.state.currentLogistics.code;
if(this.state.currentLogistics.name=='其他'){
postCode=this.state.custom_company;
}
BatchLogisticsSend({trades:this.state.data,mail_no:this.mail_no,postCode:postCode,style:this.state.currentLogistics.style,callback:(result)=>{
SetLastLogisticsInfo(this.nick,this.state.currentLogistics);
Modal.toast('发货成功');
this.goBack(true);
}});
}else{
//无需物流发货
BatchSendWithoutLogistics({trades:this.state.data,callback:(result)=>{
SetLastLogisticsInfo(this.nick,this.state.currentLogistics);
Modal.toast('发货成功');
this.goBack(true);
}});
}
DoBeacon('TD20170114090141','querenfahck',this.nick);
}
goBack(refresh){
let self=this;
GoToView({page_status:'pop',callback:(result)=>{QN.emit('app.batchDeliverTrade',{refresh:refresh});}});
}
renderCustomCompany(){
if(this.state.currentLogistics.name!='其他')
return;
return(
<View style={{flexDirection:'row',backgroundColor:'#ffffff',borderWidth:'0rem',borderTopWidth:'2rem',borderColor:'#e2e3e8',alignItems:'center',paddingRight:'24rem'}}>
<View style={{flex:8}}><Input ref='custom_company' style={{marginTop:'0',borderWidth:'0rem'}} multiple={false} placeholder="填写快递公司名称" onInput={(value,e)=>{this.setState({custom_company:value.value})}}/></View>
</View>
);
}
renderLightOrderCard(){
let jsx=[];
// console.log(this.state.mail_no);
let counter=0;
for(var index in this.state.data){
let trade=this.state.data[index];
let mailNo=undefined;
if(this.state.mail_no && this.state.mail_no[index]){
mailNo=this.state.mail_no[index];
}
if(this.refs[trade.tid]){
this.refs[trade.tid].mail_no=mailNo;
}
jsx.push(<LightDeliverOrderCard ref={trade.tid} dataSource={trade} mail_no={mailNo} show_outerid={this.state.need_logistics}></LightDeliverOrderCard>);
if(counter==0 && this.state.need_logistics && this.state.data.length > 1){
jsx.push(
<View style={[buttonBlockStyle.container,{borderTopWidth:'0rem'}]}>
<MyButton style={{borderColor:'#3089dc',height:'50rem',width:'140rem',marginRight:'24rem'}} textStyle={{color:'#3089dc'}} size='medium' onPress={this.fillIncreasing.bind(this,trade.tid)} type="secondary" text='顺序递增'></MyButton>
<MyButton style={{borderColor:'#3089dc',height:'50rem',width:'140rem',marginRight:'24rem'}} textStyle={{color:'#3089dc'}} size='medium' onPress={this.fillDecreasing.bind(this,trade.tid)} type="secondary" text='顺序递减'></MyButton>
{/* <Button style={buttonBlockStyle.button} type='secondary' size='small' onPress={this.fillIncreasing.bind(this,trade.tid)}>顺序递增</Button>
<Button style={buttonBlockStyle.button} type='secondary' size='small' onPress={this.fillDecreasing.bind(this,trade.tid)}>顺序递减</Button> */}
</View>
);
}
counter++;
}
return jsx;
}
fillIncreasing(tid){
let start_mail_no=this.checkingStartNo(tid);
if(start_mail_no===false){
Modal.alert('请输入或扫描起始单号',[{
onPress:()=>{},
text:'确定'
}]);
return;
}
let mail_no=this.state.data.map((trade,index)=>{
if(index==0)
return start_mail_no;
var return_no=Number(start_mail_no.replace(/[^0-9]/ig,''))+index;
return_no=PaddingStringLeft(''+return_no,start_mail_no.length,'0',start_mail_no);
return return_no;
});
// console.error(mail_no);
// this.setState({mail_no:undefined});
this.setState({mail_no:mail_no});
}
fillDecreasing(tid){
let start_mail_no=this.checkingStartNo(tid);
if(start_mail_no===false){
Modal.alert('请输入或扫描起始单号',[{
onPress:()=>{},
text:'确定'
}]);
return;
}
let mail_no=this.state.data.map((trade,index)=>{
if(index==0)
return start_mail_no;
var return_no=Number(start_mail_no.replace(/[^0-9]/ig,''))-index;
return_no=PaddingStringLeft(''+return_no,start_mail_no.length,'0',start_mail_no);
return return_no;
});
// this.setState({mail_no:undefined});
this.setState({mail_no:mail_no});
}
checkingStartNo(tid){
let start_mail_no=this.refs[tid].mail_no;
if(start_mail_no==undefined || start_mail_no==''){
return false;
}
else {
return start_mail_no;
}
}
barCode(){
QN.scan(result => {
// console.error(this.refs);
this.start_mail_no=result.data.data;
// console.log(this.start_mail_no);
this.refs['start_mail_no'].setState({value:this.start_mail_no});
// this.setState({refresh:!this.state.refresh});
});
}
renderStartOuterIdArea(){
// console.log(this.state.need_logistics);
// if(this.state.need_logistics){
// let jsx=[];
// jsx.push(<View style={{backgroundColor:'#ffffff',borderWidth:'0rem',borderTopWidth:'2rem',borderColor:'#e2e3e8',marginTop:'24rem'}}>
// <Text style={{paddingLeft:'24rem',paddingTop:'16rem',paddingBottom:'16rem',fontSize:'28rem'}}>请输入起始单号</Text>
// <View style={{flexDirection:'row',alignItems:'center',paddingRight:'24rem'}}>
// <View style={{flex:8}}><Input value={this.start_mail_no} ref="start_mail_no" inputStyle={{fontSize:'28rem'}} style={{paddingLeft:"0rem",marginLeft:"24rem",marginBottom:'16rem'}} type="enclosed" multiple={false} placeholder="填写快递单号或扫码" onInput={(value)=>{console.log(value);this.start_mail_no=value;}} /></View>
// <TouchableHighlight onPress={this.barCode.bind(this)} style={{style:2,justifyContent:'center',alignItems:'center'}}><Image source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/smfh.png'}} style={{width:'50rem',height:'50rem'}}/></TouchableHighlight>
// </View>
// </View>
// );
// jsx.push(
// <View style={buttonBlockStyle.container}>
// <Button style={buttonBlockStyle.button} type='secondary' size='small' onPress={this.fillIncreasing.bind(this)}>顺序递增</Button>
// <Button style={buttonBlockStyle.button} type='secondary' size='small' onPress={this.fillDecreasing.bind(this)}>顺序递减</Button>
// </View>
// )
// return jsx;
// }
}
render(){
this.getTradeInfo();
if(this.state.data==undefined || this.state.defaultLogistics==undefined)
{
// console.log('nodata');
return;
}
let dataSource=this.state.data;
let deliverStyle='自己联系物流';
let company_name=this.state.currentLogistics.name;
if(this.state.need_logistics){
if(this.state.currentLogistics.style=='online')
deliverStyle='在线下单';
}else{
deliverStyle='无需物流';
company_name='';
}
return(
<View style={{flex:1}}>
<ScrollView style={[styles.container,{flex:1,}]}>
<ListBlock mainTitle='发货方式' subTitle={deliverStyle} onPress={this.changeLogisticsStyle.bind(this)} style={{borderBottomWidth:'0rem',borderTopWidth:'0rem'}}></ListBlock>
<ListBlock mainTitle='快递公司' subTitle={company_name} onPress={this.changeLogisticsCompany.bind(this,this.state.currentLogistics.style)} style={{borderBottomWidth:'0rem'}}></ListBlock>
{this.renderCustomCompany()}
{this.renderStartOuterIdArea()}
{this.renderLightOrderCard()}
{/* <ListBlock mainTitle='我的发货/退货地址' subTitle='上海市宝山区新二路55号11层' onPress={this.changeLogisticsCompany.bind(this)} style={{marginTop:'24rem'}}></ListBlock> */}
<View style={{alignItems:'flex-end',justifyContent:'flex-end',flexDirection:'row',backgroundColor:'#faf9fa',marginBottom:'20rem',paddingTop:'24rem',paddingBottom:'24rem',}}>
<MyButton style={{marginRight:'24rem'}} onPress={this.goBack.bind(this)} size='medium' text='取消'></MyButton>
{/* <MyButton style={{marginRight:'24rem'}} type='secondary' onPress={this.deliver.bind(this)} size='medium' text='确定'></MyButton> */}
<MyButton style={{borderColor:'#3089dc',marginRight:'24rem'}} textStyle={{color:'#3089dc'}} size='medium' onPress={this.deliver.bind(this)} type="secondary" text='确定'></MyButton>
</View>
</ScrollView>
</View>
)
}
}
let styles={
container:{
backgroundColor:'#eff0f3',
flex:1,
justifyContent:'flex-start'
},
ordercontainer:{
justifyContent: 'center',
backgroundColor:'#ffffff',
paddingBottom:'0rem',
marginBottom:'28rem',
marginTop:'15rem',
},
resoncontainer:{
backgroundColor:'#ffffff',
borderBottomWidth:'2rem',
borderBottomStyle:'solid',
borderBottomColor:'#e2e3e8',
borderBottomColor:'#e2e3e8',
},
btn_two:{
backgroundColor:'#3089dd',
flex:1,
height:'100rem'
},
btn_three:{
backgroundColor:'#106fba',
flex:1,
height:'100rem'
},
view:{
height:'100rem',
justifyContent:'center',
alignItems:'center'
},
text:{
color:'#FFFFFF',
fontSize:'28rem'
}
}
const buttonBlockStyle={
container:{
borderColor:'#e6e6eb',
borderWidth:'0rem',
borderBottomWidth:'2rem',
borderTopWidth:'2rem',
flexDirection:'row',
flexWrap:'nowrap',
justifyContent: 'flex-end',
alignItems:'center',
padding:'0rem',
paddingTop:'13rem',
paddingBottom:'13rem',
backgroundColor:'#faf9fa'
},
button:{
marginRight:'10rem'
}
}
render(<App/>);
<file_sep>/EvaluateMgt.jsx
/** @jsx createElement */
import {createElement, Component,render} from 'rax';
import { View, Text, TouchableHighlight,Modal,Image} from 'nuke';
import QN from 'QAP-SDK';
import {GoToView} from './Biz/View/GoToView.jsx';
import {GetUserInfo} from './Biz/User/GetUserInfo.jsx';
class EvaluateMgt extends Component {
constructor() {
super();
this.state = {deliveryScore:'',itemScore:'',serviceScore:'',good:'',neutral:'',bad:'',giveRate:'',goodRate:'0%',goodRateList:[],pic_path:undefined,title:undefined}
this.userNick = '';
this.shopScore = '';
this.deliveryScore = '';
this.itemScore = '';
this.serviceScore = '';
this.level = '0';
}
GoToView(value){
GoToView({
status:value,
});
}
getShopDSR(){
QN.top.invoke({
query: {
method: "taobao.shop.get",
nick: this.userNick,
fields:"shop_score,pic_path,title"
}
}).then((result) => {
this.state.itemScore = result.data.shop_get_response.shop.shop_score.item_score;
this.state.deliveryScore = result.data.shop_get_response.shop.shop_score.delivery_score;
this.state.serviceScore = result.data.shop_get_response.shop.shop_score.service_score;
this.getBadRate();
this.setState({pic_path:'http://logo.taobao.com/shop-logo'+result.data.shop_get_response.shop.pic_path,title:result.data.shop_get_response.shop.title});
}, (error) => {
// console.log(error);
});
}
getBadRate(){
let queryArr = [{
method:'taobao.traderates.get',
fields:'tid,nick,created,item_title,item_price,content,oid,result,valid_score',
rate_type:'get',
role:'buyer',
result:'good',
},{
method:'taobao.traderates.get',
fields:'tid,nick,created,item_title,item_price,content,oid,result,valid_score',
rate_type:'get',
role:'buyer',
result:'neutral',
},{
method:'taobao.traderates.get',
fields:'tid,nick,created,item_title,item_price,content,oid,result,valid_score',
rate_type:'get',
role:'buyer',
result:'bad',
},{
method:'taobao.traderates.get',
fields:'tid,nick,created,item_title,item_price,content,oid,result,valid_score',
rate_type:'give',
role:'seller',
}];
QN.top.batch({
query: queryArr,
}).then(result => {
// console.log(result);
let goodRate = '';
if(result.data[0].traderates_get_response.total_results != 0){
goodRate = result.data[0].traderates_get_response.total_results/(result.data[0].traderates_get_response.total_results+result.data[1].traderates_get_response.total_results+result.data[2].traderates_get_response.total_results)
goodRate = (goodRate*100).toFixed(2);
// console.log(goodRate);
}
this.setState({goodRate:goodRate,good:result.data[0].traderates_get_response.total_results,neutral:result.data[1].traderates_get_response.total_results,bad:result.data[2].traderates_get_response.total_results,giveRate:result.data[3].traderates_get_response.total_results,deliveryScore:this.state.deliveryScore,deliveryScore:this.state.deliveryScore,serviceScore:this.state.serviceScore});
}, error => {
// console.error(error);
});
}
componentWillMount(){
let self = this;
QN.top.invoke({
query: {
method: "taobao.user.seller.get",
fields: "type,nick,seller_credit"
}
}).then((result) => {
self.userNick = result.data.user_seller_get_response.user.nick;
self.level = result.data.user_seller_get_response.user.seller_credit.level;
this.getShopDSR();
}, (error) => {
});
}
render() {
let pic_path={uri:'https://img.alicdn.com/tps/TB1PcePLVXXXXaDXpXXXXXXXXXX-100-100.png_250x250.jpg'};
if(this.state.pic_path)
pic_path={uri:this.state.pic_path};
let level_pic_path = {uri:'https://q.aiyongbao.com/trade/web/images/qap_img/mobile/level_s_' + this.level + '.png'};
let level_pic_path_width = '36rem';
switch (this.level%5) {
case 1:
level_pic_path_width = '36rem';
break;
case 2:
level_pic_path_width = '72rem';
break;
case 3:
level_pic_path_width = '108rem';
break;
case 4:
level_pic_path_width = '144rem';
break;
case 0:
if (this.level == 0) {
level_pic_path_width = '36rem';
} else {
level_pic_path_width = '180rem';
}
break;
default:
level_pic_path_width = '36rem';
}
return(
<View style={{backgroundColor:'#e8e8e8'}}>
<View style={{height:'150rem',borderBottomWidth:"2rem",borderBottomStyle:"solid",borderBottomColor:"#e8e8e8",backgroundColor:'#ffffff',flexDirection:'row',marginTop:'20rem',alignItems:'center'}}>
<View style={{flex:'1.5'}}>
<Image source={pic_path} style={{width:'80rem',height:'80rem',marginLeft:'20rem'}} />
</View>
<View style={{flex:'7.5',marginLeft:'20rem',alignItems:'flex-start',justContent:'flex-start'}}>
<View style={{justifyContent:'flex-start',alignItems:'flex-start',flex:1}}><Text style={{fontSize:'28rem',color:'#333333'}}>{this.state.title}</Text></View>
<View style={{flexDirection:'row',alignItems:'flex-end',flex:1,marginTop:'5rem',marginBottom:'5rem'}}>
<Text style={{fontSize:'28rem',color:'#F57745'}}>店铺等级:</Text>
<Image source={level_pic_path} style={{width:level_pic_path_width,height:'30rem',marginLeft:'10rem'}} />
</View>
<View style={{flexDirection:'row',alignItems:'flex-end',flex:1}}>
<Text style={{fontSize:'28rem',color:'#999999'}}>好评率:</Text>
<Text style={{fontSize:'28rem',color:'#333333'}}>{this.state.goodRate}%</Text>
</View>
</View>
<View style={{flex:'1'}}>
<Text style={{color:'#999999',marginTop:'50rem',marginLeft:'20rem'}}> </Text>
</View>
</View>
<View style={{paddingTop:'24rem',backgroundColor:'#ffffff',justifyContent:'center',height:'200rem',borderBottomWidth:"2rem",borderBottomStyle:"solid",borderBottomColor:"#e8e8e8",flexDirection:'row'}}>
<View style={[style.line,{borderWidth:'0rem',borderRightWidth:'2rem',borderColor:'#e2e3e8'}]}>
<Text style={style.red}>
{this.state.itemScore}
</Text>
<Text style={style.garytext}>
描述相符
</Text>
</View>
<View style={[style.line,{borderWidth:'0rem',borderRightWidth:'2rem',borderColor:'#e2e3e8'}]}>
<Text style={style.red}>
{this.state.serviceScore}
</Text>
<Text style={style.garytext}>
服务态度
</Text>
</View>
<View style={[style.line]}>
<Text style={style.red}>
{this.state.deliveryScore}
</Text>
<Text style={style.garytext}>
物流服务
</Text>
</View>
</View>
<TouchableHighlight onPress={this.GoToView.bind(this,'BadRate')} style={{height:'100rem',borderBottomWidth:"2rem",borderBottomStyle:"solid",borderBottomColor:"#e8e8e8",backgroundColor:'#ffffff',display:'inline-flex',flexDirection:'row',paddingLeft:'30rem',marginTop:'20rem'}}>
<View style={{flex:'9'}}>
<Text style={{fontSize:'30rem',marginTop:'35rem'}}>收到的差评:{this.state.bad}</Text>
</View>
<View style={{flex:'1'}}>
<Text style={{fontSize:'30rem',color:'#999999',marginTop:'35rem',marginLeft:'20rem'}}>></Text>
</View>
</TouchableHighlight>
<TouchableHighlight onPress={this.GoToView.bind(this,'NeutralRate')} style={{height:'100rem',borderBottomWidth:"2rem",borderBottomStyle:"solid",borderBottomColor:"#e8e8e8",backgroundColor:'#ffffff',display:'inline-flex',flexDirection:'row',paddingLeft:'30rem'}}>
<View style={{flex:'9'}}>
<Text style={{fontSize:'30rem',marginTop:'35rem'}}>收到的中评:{this.state.neutral}</Text>
</View>
<View style={{flex:'1'}}>
<Text style={{fontSize:'30rem',color:'#999999',marginTop:'35rem',marginLeft:'20rem'}}>></Text>
</View>
</TouchableHighlight>
<TouchableHighlight onPress={this.GoToView.bind(this,'GoodRate')} item={this.state.goodRateList} style={{height:'100rem',borderBottomWidth:"2rem",borderBottomStyle:"solid",borderBottomColor:"#e8e8e8",backgroundColor:'#ffffff',display:'inline-flex',flexDirection:'row',paddingLeft:'30rem'}}>
<View style={{flex:'9'}}>
<Text style={{fontSize:'30rem',marginTop:'35rem'}}>收到的好评:{this.state.good}</Text>
</View>
<View style={{flex:'1'}}>
<Text style={{fontSize:'30rem',color:'#999999',marginTop:'35rem',marginLeft:'20rem'}}>></Text>
</View>
</TouchableHighlight>
<TouchableHighlight onPress={this.GoToView.bind(this,'ToBuyerRate')} item={this.state.toBuyerRateList} style={{height:'100rem',borderBottomWidth:"2rem",borderBottomStyle:"solid",borderBottomColor:"#e8e8e8",backgroundColor:'#ffffff',display:'inline-flex',flexDirection:'row',paddingLeft:'30rem'}}>
<View style={{flex:'9'}}>
<Text style={{fontSize:'30rem',marginTop:'35rem'}}>给买家的评价:{this.state.giveRate}</Text>
</View>
<View style={{flex:'1'}}>
<Text style={{fontSize:'30rem',color:'#999999',marginTop:'35rem',marginLeft:'20rem'}}>></Text>
</View>
</TouchableHighlight>
</View>
)}
}
const style={
garytext:{
fontSize:'28rem',
color:'#999999',
paddingTop:'10rem'
},
line :{
// height:'60rem',
// flexDirection:'row',
flex:1,
justifyContent:'center',
alignItems:'center',
marginBottom:'20rem'
},
red:{
fontSize:'48rem',
color:'#333333'
}
}
render(<EvaluateMgt/>)
<file_sep>/Component/Common/Messagecard.jsx
/**
* @author moorwu
*/
import {createElement, Component,render} from 'rax';
import { View, Text,TouchableHighlight,Image,ScrollView,Env,Modal} from 'nuke';
import QN from 'QAP-SDK';
import MyButton from './MyButton.jsx';
import {DateMinus} from 'Biz/User/GetFamilyInfo.jsx';
import {StorageOper} from 'Biz/View/StorageOper.jsx';
import {UserContact} from 'Biz/User/UserContact.jsx';
import {DoBeacon} from 'Biz/Common.jsx';
const { isWeex, isWeb, isQNWeb , isQNWeex , appInfo } = Env;
//交易订购链接
var links1 = [
'https://fuwu.taobao.com/ser/confirmOrder.htm?&commonParams=activityCode:ACT_877021141_170619135519;agentId:fuwu.taobao.com|marketing-0;marketKey:FWSPP_MARKETING_URL;promIds:[1002001304]&subParams=cycleNum:3,cycleUnit:2,itemCode:FW_GOODS-1827490-v2&sign=CF937004BDB2110BA622136014B81BB3',
'https://fuwu.taobao.com/ser/confirmOrder.htm?&commonParams=activityCode:ACT_877021141_170619135519;agentId:fuwu.taobao.com|marketing-0;marketKey:FWSPP_MARKETING_URL;promIds:[1002001304]&subParams=cycleNum:6,cycleUnit:2,itemCode:FW_GOODS-1827490-v2&sign=A7B9465322AC0229642DDBA1F93386CE',
'https://fuwu.taobao.com/ser/confirmOrder.htm?&commonParams=activityCode:ACT_877021141_170619135519;agentId:fuwu.taobao.com|marketing-0;marketKey:FWSPP_MARKETING_URL;promIds:[1002001304]&subParams=cycleNum:12,cycleUnit:2,itemCode:FW_GOODS-1827490-v2&sign=4AE2EF754279DFD16EA4829F99453871',
'https://fuwu.taobao.com/ser/confirmOrder.htm?&commonParams=activityCode:ACT_877021141_170619135519;agentId:fuwu.taobao.com|marketing-0;marketKey:FWSPP_MARKETING_URL;promIds:[1002001304]&subParams=cycleNum:12,cycleUnit:2,itemCode:FW_GOODS-1827490-v2&sign=4AE2EF754279DFD16EA4829F99453871'
];
//商品
var links2 = [
'https://fuwu.taobao.com/ser/confirmOrder.htm?&commonParams=activityCode:ACT_877021141_170619173305;agentId:fuwu.taobao.com|marketing-0;marketKey:FWSPP_MARKETING_URL;promIds:[1002001953]&subParams=cycleNum:3,cycleUnit:2,itemCode:FW_GOODS-1828810-v2&sign=44A4C0884FE0564344021FF10CCEE03B',
'https://fuwu.taobao.com/ser/confirmOrder.htm?&commonParams=activityCode:ACT_877021141_170619173305;agentId:fuwu.taobao.com|marketing-0;marketKey:FWSPP_MARKETING_URL;promIds:[1002001953]&subParams=cycleNum:6,cycleUnit:2,itemCode:FW_GOODS-1828810-v2&sign=E2D93669A2242AD06E302B4430BEFF11',
'https://fuwu.taobao.com/ser/confirmOrder.htm?&commonParams=activityCode:ACT_877021141_170619173305;agentId:fuwu.taobao.com|marketing-0;marketKey:FWSPP_MARKETING_URL;promIds:[1002001953]&subParams=cycleNum:12,cycleUnit:2,itemCode:FW_GOODS-1828810-v2&sign=6654E157A45D67421F40278AB0444CFC',
'https://fuwu.taobao.com/ser/confirmOrder.htm?&commonParams=activityCode:ACT_877021141_170619135611;agentId:fuwu.taobao.com|marketing-0;marketKey:FWSPP_MARKETING_URL;promIds:[1002001207]&subParams=cycleNum:12,cycleUnit:2,itemCode:FW_GOODS-1828810-v2&sign=8A59D65FFEECC66DA2D9A88BFFFC83AD'
];
//促销
var links3 = [
'https://fuwu.taobao.com/ser/confirmOrder.htm?&commonParams=activityCode:ACT_877021141_170606112010;agentId:fuwu.taobao.com%7Cmarketing-0;marketKey:FWSPP_MARKETING_URL;promIds:[1001968773]&subParams=cycleNum:3,cycleUnit:2,itemCode:FW_GOODS-1834215-1&sign=95104C14EA188F79026B6D120F745927',
'https://fuwu.taobao.com/ser/confirmOrder.htm?&commonParams=activityCode:ACT_877021141_170606112010;agentId:fuwu.taobao.com%7Cmarketing-0;marketKey:FWSPP_MARKETING_URL;promIds:[1001968773]&subParams=cycleNum:6,cycleUnit:2,itemCode:FW_GOODS-1834215-1&sign=1D6AE53E3CA409AF33536A924CD23BD1',
'https://fuwu.taobao.com/ser/confirmOrder.htm?&commonParams=activityCode:ACT_877021141_170606112010;agentId:fuwu.taobao.com%7Cmarketing-0;marketKey:FWSPP_MARKETING_URL;promIds:[1001968773]&subParams=cycleNum:12,cycleUnit:2,itemCode:FW_GOODS-1834215-1&sign=C19AC8DB080BD38425AC7A6FE9E06C02',
'https://fuwu.taobao.com/ser/confirmOrder.htm?&commonParams=activityCode:ACT_877021141_170606110700;agentId:fuwu.taobao.com%7Cmarketing-0;marketKey:FWSPP_MARKETING_URL;promIds:[1001969628]&subParams=cycleNum:12,cycleUnit:2,itemCode:FW_GOODS-1834215-1&sign=7E581BA343FCA90922FA0CFA4AC08BEA'
];
//数据
var links4 = [
'https://fuwu.taobao.com/ser/confirmOrder.htm?&commonParams=activityCode:ACT_877021141_170606111056;agentId:fuwu.taobao.com%7Cmarketing-0;marketKey:FWSPP_MARKETING_URL;promIds:[1001968487]&subParams=cycleNum:3,cycleUnit:2,itemCode:FW_GOODS-1887064-1&sign=0627916850948BBF2FF51A6512134711',
'https://fuwu.taobao.com/ser/confirmOrder.htm?&commonParams=activityCode:ACT_877021141_170606111056;agentId:fuwu.taobao.com%7Cmarketing-0;marketKey:FWSPP_MARKETING_URL;promIds:[1001968487]&subParams=cycleNum:6,cycleUnit:2,itemCode:FW_GOODS-1887064-1&sign=C9377E7E2AE9B620635C4AC35E110F6F',
'https://fuwu.taobao.com/ser/confirmOrder.htm?&commonParams=activityCode:ACT_877021141_170606111056;agentId:fuwu.taobao.com%7Cmarketing-0;marketKey:FWSPP_MARKETING_URL;promIds:[1001968487]&subParams=cycleNum:12,cycleUnit:2,itemCode:FW_GOODS-1887064-1&sign=49ED1325E3851975656984D09361C968',
'https://fuwu.taobao.com/ser/confirmOrder.htm?&commonParams=activityCode:ACT_877021141_170606111056;agentId:fuwu.taobao.com%7Cmarketing-0;marketKey:FWSPP_MARKETING_URL;promIds:[1001968487]&subParams=cycleNum:12,cycleUnit:2,itemCode:FW_GOODS-1887064-1&sign=49ED1325E3851975656984D09361C968'
];
var links5 = [
'http://fuwu.m.taobao.com/ser/assembleParam.htm?subParams=itemCode:FW_GOODS-1856541-v3,cycleNum:12,cycleUnit:2',
'http://fuwu.m.taobao.com/ser/assembleParam.htm?subParams=itemCode:FW_GOODS-1856541-v3,cycleNum:12,cycleUnit:2',
'http://fuwu.m.taobao.com/ser/assembleParam.htm?subParams=itemCode:FW_GOODS-1856541-v3,cycleNum:12,cycleUnit:2',
'http://fuwu.m.taobao.com/ser/assembleParam.htm?subParams=itemCode:FW_GOODS-1856541-v3,cycleNum:12,cycleUnit:2'
];
var links6 = [
'https://fuwu.taobao.com/ser/confirmOrder.htm?&commonParams=activityCode:ACT_877021141_170619135742;agentId:fuwu.taobao.com|marketing-0;marketKey:FWSPP_MARKETING_URL;promIds:[1002000463,%201002000464]&subParams=cycleNum:1,cycleUnit:2,itemCode:FW_GOODS-1827490-v2;cycleNum:1,cycleUnit:2,itemCode:FW_GOODS-1828810-v2&sign=88AD7033A6A34760114BF35BC2BF8478',
];
var links7 = [
'https://fuwu.taobao.com/ser/confirmOrder.htm?&commonParams=activityCode:ACT_877021141_170619135925;agentId:fuwu.taobao.com|marketing-0;marketKey:FWSPP_MARKETING_URL;promIds:[1002001801,%201002001802,%201002001803]&subParams=cycleNum:1,cycleUnit:2,itemCode:FW_GOODS-1827490-v2;cycleNum:1,cycleUnit:2,itemCode:FW_GOODS-1828810-v2;cycleNum:1,cycleUnit:2,itemCode:FW_GOODS-1834215-1&sign=8401AD3461CBD3D52E9EE8827205A194',
];
var linksIOS = [
'https://tb.cn/ka8ethw',
'https://tb.cn/noIethw',
'https://tb.cn/j6Spthw'
];
var beaconAn=[
'0614jiazujyxudingandroidf',
'0614jiazuspxudingandroidf',
'0614jiazujyshengjiandroidvip',
'0614jiazuspshengjiandroidvip',
'0614jiazusjspdinggandroidf'
]
var beaconIOS=[
'0614jiazujyxudingiosf',
'0614jiazuspxudingiosf',
'0614jiazujyshengjiiosvip',
'0614jiazuspshengjiiosvip',
'0614jiazusjspdinggiosf'
]
class Messagecard extends Component{
constructor(){
super()
this.flag =""
}
renderImage(){
if(this.props.count){
if(this.props.type ==1){
return (<View style={{flexDirection:'row',alignItems:'center',justifyContent:'center'}}>
<View style={{flex:1}}></View>
<View style={{flex:1,alignItems:'center',justifyContent:'center'}}><Image source={this.props.img_source} style={{width:'120rem',height:'120rem'}} /></View>+
<View style={{flex:1,alignItems:'center',justifyContent:'center'}}><Image source={this.props.img_source2} style={{width:'120rem',height:'120rem'}} /></View>
<View style={{flex:1}}></View>
</View>
)
}else{
return (<View style={{flexDirection:'row',alignItems:'center',justifyContent:'center'}}>
<View style={{flex:0.6}}></View>
<View style={{flex:1,alignItems:'center',justifyContent:'center'}}><Image source={this.props.img_source} style={{width:'120rem',height:'120rem'}} /></View>+
<View style={{flex:1,alignItems:'center',justifyContent:'center'}}><Image source={this.props.img_source2} style={{width:'120rem',height:'120rem'}} /></View>+
<View style={{flex:1,alignItems:'center',justifyContent:'center'}}><Image source={this.props.img_source3} style={{width:'120rem',height:'120rem'}} /></View>
<View style={{flex:0.6}}></View>
</View>
)
}
}else{
if(this.props.img_source){
return <Image source={this.props.img_source} style={{width:'120rem',height:'120rem',marginLeft:'12rem'}} />
}
}
}
go(e){
QN.navigator.push({
url: e,
title: '服务详情',
query: { x: 1, y: 2 },
settings: {
animate: true,
request: true,
},
success(result) {
console.log(result);
},
error(error) {
console.log(error);
}
})
}
takeMoney(value){
//首先判断是不是子账号
if(value == -1){
value = 0
}
let query={};
let linksAndroid = [];
let title = "";
let beaconIndex=null;
let feature='';
let iosUrl='';
if(this.props.type){
if(this.props.type == 1){
linksAndroid = links6;
title = '升级【爱用交易+商品】高级版需要订购,现优惠价仅40元/月。点击此链接:https://tb.cn/0bonthw ,即可订购。';
beaconIndex=4;
feature='mine_trade_and_auction_update';
iosUrl="https://tb.cn/0bonthw";
}else if(this.props.type == 2){
linksAndroid = links7;
title = '升级【爱用交易+商品+促销】高级版需要订购,现优惠价仅50元/月。点击此链接:https://tb.cn/6lPmthw ,即可订购。';
iosUrl="https://tb.cn/6lPmthw";
}
}
if(this.props.mainTitle){
if(this.props.mainTitle.indexOf('爱用交易')>=0){
linksAndroid = links1;
if(value == 3){
title = '升级【爱用交易】高级版需要订购,现优惠价148元/年。点击此链接:https://tb.cn/j6Spthw ,即可订购。';
beaconIndex=2;
feature='mine_trade_update';
iosUrl="https://tb.cn/j6Spthw";
}else{
title = '【爱用交易】续订专享,现优惠价148元/年。点击此链接:https://tb.cn/j6Spthw ,即可订购。';
beaconIndex=0;
feature='mine_trade_renew';
iosUrl="https://tb.cn/j6Spthw";
}
}else if(this.props.mainTitle.indexOf('爱用商品')>=0){
linksAndroid = links2;
if(value ==3){
title = '升级【爱用商品】高级版需要订购,现优惠价148元/年。点击此链接:https://tb.cn/TQcdthw ,即可订购。';
beaconIndex=3;
feature='mine_auction_update';
iosUrl="https://tb.cn/TQcdthw";
}else{
title = '【爱用商品】续订专享,现优惠价148元/年。点击此链接:https://tb.cn/TQcdthw ,即可订购。';
beaconIndex=1;
feature='mine_auction_renew';
iosUrl="https://tb.cn/TQcdthw";
}
}else if(this.props.mainTitle.indexOf('爱用促销')>=0){
linksAndroid = links3;
if(value ==3){
title = '升级【爱用促销】高级版需要订购,现优惠价128元/年。点击此链接:https://tb.cn/vTxZviw ,即可订购。';
iosUrl="https://tb.cn/vTxZviw";
}else{
title = '【爱用促销】续订专享,现优惠价128元/年。点击此链接:https://tb.cn/T8CiWiw ,即可订购。';
iosUrl="https://tb.cn/T8CiWiw";
}
}else if(this.props.mainTitle.indexOf('爱用供销')>=0){
linksAndroid = links5;
if(value ==3){
title = '升级【爱用供销】高级版需要订购,现优惠价0.01元/年。点击此链接:http://fuwu.m.taobao.com/ser/assembleParam.htm?subParams=itemCode:FW_GOODS-1856541-v3,cycleNum:12,cycleUnit:2 ,即可订购。';
iosUrl="http://fuwu.m.taobao.com/ser/assembleParam.htm?subParams=itemCode:FW_GOODS-1856541-v3,cycleNum:12,cycleUnit:2";
}else{
title = '【爱用供销】续订专享,现优惠价0.01元/年。点击此链接:http://t.cn/RVXSTIN ,即可订购。';
iosUrl="http://t.cn/RVXSTIN";
}
}else if(this.props.mainTitle.indexOf('爱用数据')>=0){
linksAndroid = links4;
if(value ==3){
title = '升级【爱用数据】高级版需要订购,现优惠价84元/年。点击此链接:https://tb.cn/2oGfviw ,即可订购。';
iosUrl="https://tb.cn/2oGfviw";
}else{
title = '【爱用数据】续订专享,现优惠价84元/年。点击此链接:https://tb.cn/OyshWiw ,即可订购。';
iosUrl="https://tb.cn/OyshWiw";
}
}
}
let self = this
StorageOper.localGet({
key:'last_sub_user_nick,last_user_nick',
callback:(result)=>{
StorageOper.localGet({
key:'ipCheck_'+result.last_user_nick,
callback:(result1)=>{
self.flag = result1['ipCheck_'+result.last_user_nick];
let beacon='';
let nick='';
if(result==undefined || result=='' || result['last_sub_user_nick']==undefined || result['last_sub_user_nick']==''){
//说明不是子账号
if(appInfo.platform == 'iOS'){
//isiOS = 'yes';
if(self.flag == 0){
var data = iosUrl;
console.log(data)
// let url=linksIOS[value];
QN.app.invoke({
api: 'openWebsite', // 通用协议接口名称
query: { // 请求参数
msg_id : "",
url : data
}
}).then(result => {
}, error => {
// console.log(error);
});
}else{
console.log(title)
UserContact({value:title});
}
beacon=beaconIOS[beaconIndex];
nick=result.last_user_nick;
DoBeacon(beacon,feature,nick);
}
else{
var data = linksAndroid[value];
QN.app.invoke({
api: 'openWebsite', // 通用协议接口名称
query: { // 请求参数
msg_id : "",
url : data
}
}).then(result => {
}, error => {
// console.log(error);
});
beacon=beaconAn[beaconIndex];
nick=result.last_user_nick;
DoBeacon(beacon,feature,nick);
}
}else{
//说明是子账号,向主账号发起请求
let url=linksAndroid[value];
if(appInfo.platform == 'iOS'){
url=linksIOS[value];
beacon=beaconIOS[beaconIndex];
nick=result.last_sub_user_nick;
DoBeacon(beacon,feature,nick);
}else{
beacon=beaconAn[beaconIndex];
nick=result.last_sub_user_nick;
DoBeacon(beacon,feature,nick);
}
console.log('是子账号')
UserContact({status:'',value:title,buyer_nick:result['last_user_nick']});
}
console.log("***************",beacon);
console.log("***************",feature);
console.log("***************",nick);
console.log("***************",value);
},
errCallback:(result)=>{ //取不到缓存会走error
self.flag = true;
}
});
}
});
}
GoTo(e){
let self = this;
if(this.props.mainTitle.indexOf('爱用促销')>=0 && this.props.time == 0 || this.props.mainTitle.indexOf('爱用供销')>=0 && this.props.time == 0 || this.props.mainTitle.indexOf('爱用数据')>=0 && this.props.time == 0){
Modal.alert("您还没有订购该插件,需要订购后再使用,您可以点击查看了解下该插件",[
{
onPress:(e)=>{
self.go(self.props.url)
},
text:"查看"
}
])
}else{
QN.app.invoke({
api: 'openPlugin',
query: {
appkey : e
}
})
}
}
renderFooter(time){
let type = -1;
console.log("+++++++++++++++++",this.props.middleTitle);
if(this.props.middleTitle=='初级版'){
type = 3;
}else{
if(time == 0 ){
type = 3
}else {
time = DateMinus(time)
console.log("--------------------",time);
if(time<90){
type = 2
}else if(90<=time<270){
type = 1
}else if(270<=time<365){
type = 0
}else if(time>365){
type = -1
}
}
}
let card =(<MyButton size="medium" style={buttonBlockStyle.button1} text='续订专享' onPress={this.takeMoney.bind(this,type)} textStyle={buttonBlockStyle.textStyle}></MyButton>)
if(time == 0 || time == '0'){
card = (<MyButton size="medium" style={buttonBlockStyle.button1} text='优惠订购' onPress={this.takeMoney.bind(this,type)} textStyle={buttonBlockStyle.textStyle}></MyButton>)
}
let firstcard2=(
<View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
<MyButton size="medium" style={buttonBlockStyle.button} text='查看详情' onPress={this.go.bind(this,this.props.url)}></MyButton>
</View>
);
let firstcard1;
if(this.props.middleTitle.indexOf('初级版')>=0){
firstcard1 = firstcard2;
firstcard2 = (
<View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
<MyButton size="medium" style={buttonBlockStyle.button1} text='优惠订购' onPress={this.takeMoney.bind(this,type)} textStyle={buttonBlockStyle.textStyle}></MyButton>
</View>
);
}else{
firstcard1 = firstcard2;
firstcard2 = (
<View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
<MyButton size="medium" style={buttonBlockStyle.button1} text='续订专享' onPress={this.takeMoney.bind(this,type)} textStyle={buttonBlockStyle.textStyle}></MyButton>
</View>
);
}
if(type==-1){
return (<View style={{flexDirection:'row',flex:1,height:'112rem',backgroundColor:'#faf9fa'}}>
<View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
</View>
<View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
</View>
<View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
<MyButton size="medium" style={buttonBlockStyle.button} text='查看详情' onPress={this.go.bind(this,this.props.url)}></MyButton>
</View>
<View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
<MyButton size="medium" style={buttonBlockStyle.button} text='立即使用' ></MyButton>
</View>
</View>)
}
if(this.props.index){
return(
<View style={{flexDirection:'row',flex:1,height:'112rem',backgroundColor:'#faf9fa'}}>
<View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
</View>
<View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
</View>
{firstcard1}
{firstcard2}
</View>
)
}else{
return (<View style={{flexDirection:'row',flex:1,height:'112rem',backgroundColor:'#faf9fa'}}>
<View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
</View>
<View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
<MyButton size="medium" style={buttonBlockStyle.button} text='查看详情' onPress={this.go.bind(this,this.props.url)}></MyButton>
</View>
<View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
<MyButton size="medium" style={buttonBlockStyle.button} text='立即使用' onPress={this.GoTo.bind(this,this.props.num)}></MyButton>
</View>
<View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
{card}
</View>
</View>)
}
}
render(){
let customStyle=this.props.style?this.props.style:{};
if(this.props.count){
return (
<View style={[BlockStyle.container,customStyle]}>
<TouchableHighlight onPress={this.props.onPress} style={{flexDirection:'row',flex:1,borderBottomWidth:'2rem',borderBottomStyle:'solid',borderBottomColor:'#e2e3e8',}}>
<View style={{marginLeft:'24rem',justifyContent:'center',height:'100rem',alignItems:'center'}}>
<Text style={{marginLeft:'24rem',fontSize:'28rem'}}>
套餐更优惠
</Text>
</View>
</TouchableHighlight>
<TouchableHighlight onPress={this.props.onPress} style={{flexDirection:'row',flex:1,borderBottomWidth:'2rem',borderBottomStyle:'solid',borderBottomColor:'#e2e3e8',}}>
<View style={{flex:1,marginLeft:'24rem',justifyContent:'center',height:'152rem'}}>
{
this.renderImage()
}
</View>
</TouchableHighlight>
<View style={{flexDirection:'row',flex:1,height:'112rem',backgroundColor:'#faf9fa'}}>
<View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
</View>
<View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
</View>
<View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
</View>
<View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
<MyButton size="medium" style={buttonBlockStyle.button1} textStyle={buttonBlockStyle.textStyle} text={this.props.price+'/月' }onPress={this.takeMoney.bind(this,-1)}></MyButton>
</View>
</View>
</View>
)
}else{
let time = this.props.time;
let a = '未订购';
if(time.length>5){
time = this.props.time.split(" ")[0];
}else{
time = this.props.time
}
let day = time;
let t = DateMinus(time);
// if(this.props.index){
// //当前插件
// }else{
// day='还有'+DateMinus(time)+'天到期'
// }
let card;
if(DateMinus(time)>90){
card = (<Text style={[BlockStyle.middleText,customStyle]}>{this.props.middleTitle+"到期时间:"+day}</Text>)
}else if(0<DateMinus(time)<=90){
card = (<Text style={[BlockStyle.middleText,customStyle]}>{this.props.middleTitle+":还有"+DateMinus(time)+'天到期'}</Text>)
}
if(this.props.mainTitle){
if(this.props.mainTitle.indexOf('爱用交易')>=0 || this.props.mainTitle.indexOf('爱用商品')>=0){
a = '初级版'
}
}
if(this.props.time == 0 || this.props.time == '0'){
card = (<Text style={[BlockStyle.middleText,customStyle]}>{a}</Text>)
}
if(this.props.middleTitle.indexOf('初级版')>=0){
card = (<Text style={[BlockStyle.middleText,customStyle]}>初级版</Text>)
}
return (
<View style={[BlockStyle.container,customStyle]}>
<TouchableHighlight onPress={this.props.onPress} style={{flexDirection:'row',flex:1,borderBottomWidth:'2rem',borderBottomStyle:'solid',borderBottomColor:'#e2e3e8',}}>
<View style={{flex:1,marginLeft:'24rem',justifyContent:'center',height:'152rem'}}>
<View style={{flexDirection:'row',alignItems:'center'}}>
{
this.renderImage()
}
<View >
<Text style={BlockStyle.mainText}>{this.props.mainTitle}</Text>
{card}
<Text style={BlockStyle.subText}>{this.props.subTitle}</Text>
</View>
</View>
</View>
</TouchableHighlight>
{this.renderFooter(this.props.time)}
</View>
)
}
}
}
const BlockStyle={
container:{
backgroundColor:'#ffffff',
borderBottomWidth:'2rem',
borderTopWidth:'2rem',
borderBottomStyle:'solid',
borderBottomColor:'#e2e3e8',
borderTopStyle:'solid',
borderTopColor:'#e2e3e8',
marginTop:'24rem',
// height:'9000rem',
},
mainText:{
fontSize:'28rem',
paddingLeft:'12rem',
marginBottom:'4rem'
},
subText:{
color:'#999999',
fontSize:'24rem',
lines:1,
textOverflow:'ellipsis',
paddingLeft:'12rem',
},
middleText:{
color:'#F57754',
fontSize:'24rem',
lines:1,
textOverflow:'ellipsis',
paddingLeft:'12rem',
marginBottom:'4rem'
}
}
const buttonBlockStyle={
button:{
marginRight:'24rem',
width:'160rem',
marginTop:'20rem',
marginBottom:'20rem'
},
button1:{
marginRight:'24rem',
width:'160rem',
marginTop:'20rem',
marginBottom:'20rem',
backgroundColor:'#F57745'
},
textStyle:{
color:'#fff'
}
}
export default Messagecard;
<file_sep>/Component/OrderCard/OrderButtonBlock.jsx
/**
* @author moorwu
*/
import { Button, View, Modal, Dialog, Text, Input, TouchableHighlight} from 'nuke';
import {createElement, Component,render} from 'rax';
import QN from 'QAP-SDK';
import {GoToView} from 'Biz/View/GoToView.jsx'
import {GetTradeWithTid} from '../../Biz/Order/GetTrade.jsx';
import {delayConfirmAction} from '../../DelayReceivetimeAction.jsx';
import VipButton from '../../Component/Common/VipButton.jsx';
import MyButton from '../../Component/Common/MyButton.jsx';
import {DoBeacon} from 'Biz/Common.jsx';
import {UserContact} from '../../Biz/User/UserContact.jsx';
import {Network} from '../../Component/Common/Network.jsx';
import {QNInvoke} from '../../Biz/Common.jsx'
import {StorageOper} from '../../Biz/View/StorageOper.jsx';
var yyJson = [
{title:'催付成功率高达30%',advantage:'实时展现已催付和催付成功率数据,催付结果一目了然'},
{title:'催付短语自定义',advantage:'22条系统模板,6个自定义标签,任意组合位置和内容。'},
{title:'场景催付',advantage:'根据下单时间选择不同催付短语成功率会更高。爱用独家-首日催付/次日催付/挽救催付。'}
];
let yyJson2 = [
{title:'地址/物流发错率减少30%',advantage:'及时核对地址,减少地址发错率,降低退货退款率'},
{title:'核对地址短语自定义',advantage:'7个自定义标签,任意组合位置和内容。'}
]
class OrderButtonBlock extends Component{
constructor(){
super();
this.counter=0;
this.state={
price:'',
isShow:true
}
}
/**
* 修改价格
*/
pressChangePrice(){
let tid=this.props.dataSource.tid;
// console.log(tid);
QN.app.invoke({
api: 'changePrice',
query: {
tid: ''+tid
}
}).then(result => {
// console.log(result);
if(result.res!='cancel'){
//更新这个卡片
let card=this.props.card;
card.refreshOrder();
}
}, error => {
// console.log(error);
});
DoBeacon('TD20170114090141','xgjiage');
}
/**
* 修改运费
*/
pressChangeLogistPrice(){
let self = this;
let tid=this.props.dataSource.tid;
let query={
method:'taobao.trade.postage.update',
tid:tid,
post_fee: this.state.price
}
QNInvoke(query,(result)=>{
if(result.trade_postage_update_response){
let card=self.props.card;
card.refreshOrder();
self.refs.modal.hide();
}else{
Modal.toast('修改运费失败',[{
onPress:()=>{},
text:'确定'
}]);
};
});
}
/**
* 关闭订单
*/
prcessCloseOrder(){
let self=this;
QN.localstore.set({
query: {
close_trade_data: self.props.dataSource
},
success(result) {
GoToView({
title:'关闭订单',
status:'CloseOrderPage',
callback:(result)=>{
// console.log(result);
//注册全局时间
QN.on('app.closeTrade',(data)=>{
//首先关闭这个事件的注册
// console.log('事件传回的信息');
// console.log(data);
QN.off('app.closeTrade');
if(data.data.orders){
//说明回传的整个订单,表明是拆单发货的
let status='待付款';
if(data.status)
status=data.status;
self.props.card.setState({data:data.data,orderStatus:status});
}
else{
let tid=data.data;
self.props.card.setState({orderStatus:'已关闭'});
}
});
}
});
},
error(error) {
// console.error(error);
}
}).then(result => {
// console.log(result);
// console.log('难道是这里?')
}, error => {
// console.log(error);
// console.log('或者这里?')
});
DoBeacon('TD20170114090141','gbdingdan');
}
//评价订单
evaluateTrade(){
// console.log('in evaluateTrade');
//打开新页面了
let self=this;
QN.localstore.set({
query: {
evaluate_trade_data: self.props.dataSource
},
success(result) {
// console.log(result);
GoToView({
title:'评价订单',
status:'RateTradePage',
callback:(result)=>{
// console.log(result);
//注册全局事件
QN.on('app.evaluateTrade',(data)=>{
//首先关闭这个事件的注册
// console.log('事件传回的信息');
// console.log(data);
QN.off('app.evaluateTrade');
let tid=data.data;
//这里还是重新取数据吧……
// self.refreshCard(tid,self.props.card);
self.props.card.setState({orderStatus:'已成功'})
});
}
});
},
error(error) {
// console.error(error);
}
}).then(result => {
// console.log(result);
}, error => {
// console.log(error);
});
DoBeacon('TD20170114090141','ljpingjia');
}
//处理退款
processRefund(){
// console.log('in evaluateTrade');
//打开新页面了
let self=this;
QN.localstore.set({
query: {
refund_trade_data: self.props.dataSource
},
success(result) {
// console.log(result);
GoToView({
title:'处理退款',
status:'ProcessRefundPage',
callback:(result)=>{
// console.log(result);
}
});
},
error(error) {
// console.error(error);
}
}).then(result => {
// console.log(result);
}, error => {
// console.log(error);
});
DoBeacon('TD20170114090141','tkxinxi');
}
//修改物流
changeLogistics(){
let self=this;
QN.localstore.set({
query: {
sendLogistics: self.props.dataSource
},
success(result) {
GoToView({
title:'修改物流',
status:'LogisticsInfoPage',
callback:(result)=>{
}
});
},
error(error) {
}
}).then(result => {
}, error => {
});
DoBeacon('TD20170114090141','xgwuliu');
}
//发货
pressDeliverGoods(b2bOrderId){
let self=this;
if(self.props.card.props.has_dx){
Modal.confirm('订单中含有1688代销宝贝,确定不通过1688下单?',[
{
onPress:()=>{self.readyDeliver()},
text:"确定"
},
{
onPress:()=>{},
text:"取消"
}
]);
}else {
self.readyDeliver()
}
}
readyDeliver(){
let self=this;
QN.localstore.set({
query: {
deliver_trade_data: self.props.dataSource,
userInfo: self.props.userInfo
},
success(result) {
// console.log(result);
GoToView({
title:'发货',
status:'DeliverGoodsPage',
callback:(result)=>{
// console.log(result);
//注册全局事件
// console.log('注册全局事件');
QN.on('app.deliverTrade',(data)=>{
//首先关闭这个事件的注册
// console.log('事件传回的信息');
// console.log(data);
QN.off('app.deliverTrade');
if(data.data.orders){
//说明回传的整个订单,表明是拆单发货的
let status='待发货';
if(data.status)
status=data.status;
self.props.card.setState({data:data.data,orderStatus:status});
// self.props.card.setState({});
}
else{
let tid=data.data;
//这里还是重新取数据吧……
//这里还是重新取数据吧……
// self.refreshCard(tid,self.props.card);
// console.log('setState 已发货');
self.refreshCard(tid,self.props.card);
// self.props.card.setState({orderStatus:'已发货'});
}
});
}
});
},
error(error) {
console.error(error);
}
}).then(result => {
// console.log(result);
}, error => {
// console.log(error);
});
DoBeacon('TD20170114090141','lbfahuo');
}
//延迟收货
pressDelayConfirm(){
delayConfirmAction(this.props.dataSource.tid,()=>{
//这里处理刷新
this.refreshCard(this.props.dataSource.tid,this.props.card);
});
DoBeacon('TD20170114090141','ysshouhuo');
}
refreshCard(tid,card){
GetTradeWithTid({tid:tid,callback:(result)=>{
// console.log('重新获取的订单:'+tid);
// console.log(result);
// result.trade_fullinfo_get_response.trade.tid = result.trade_fullinfo_get_response.trade.tid_str?result.trade_fullinfo_get_response.trade.tid_str:result.trade_fullinfo_get_response.trade.tid;
result.trade_fullinfo_get_response.trade.fullinfo=true;
card.setState({data:result.trade_fullinfo_get_response.trade});
}})
}
/*催付*/
payFastPress() {
let seller_nick = this.props.dataSource.seller_nick;
console.log('22222:'+seller_nick)
let day = this.getLastDate(this.props.dataSource.created);
let fastPayText = '';
Network.Post('/jy2/getFastPay',{nick:seller_nick},(data)=>{
data = JSON.parse(data);
if (day <= 1) {
switch(data.fastpaytype){
case '1':{
fastPayText = '我们仓库是四点前统一发货的哦,您四点前方便付款么,我们可以及时给您安排发货,这样您就能早一天收到我们的产品和礼物哦。<订单链接>';
break;
}
case '2':{
fastPayText = '亲爱的<买家姓名>您今日在我们店铺拍下的订单还没有付款哦,我们是下午5点发货的,晚了可能就要拖到明天发了哦。<订单链接>';
break;
}
case '11':{
fastPayText = '亲,您在我们店拍下的宝贝已经确认,亲现在我们每天前200名付款买家有精美赠品送哦,您现在付款还来得及哦~ <订单链接>';
break;
}
case '12':{
fastPayText = '您好,看到您这边没有支付,我们这边是7天无理由退还,还帮您购买了运费保险,收到以后包您满意,如果不满意也没有后顾之忧。<订单链接>';
break;
}
case '21':{
fastPayText = '亲爱的<买家姓名>,我是<卖家旺旺>,我看到了您在我们店里拍下了您要的宝贝哦,您已经是我们的老顾客了,所以会首先安排您的订单先发出的哦。<订单链接>';
break;
}
case '22':{
fastPayText = '您好,您在<卖家旺旺>店铺拍下的商品还没有付款,因为您是我们的老顾客了,我给店长申请了这次给您个超级会员价格,比您拍的时候少了很多哦。 <订单链接>';
break;
}
case '31':{
fastPayText = '您拍下的那小家伙,怕您不要了她们了,正哭哭啼啼的闹个不停,您快去看下吧!<订单链接>';
break;
}
case '32':{
fastPayText = '呜呜,麻麻你真的不要偶们了吗?赶紧来付款把我们带回家吧!不然又要回到一堆怪蜀黍的怀里了!<订单链接>';
break;
}
case '0':{
fastPayText = data.fastpay;
break;
}
}
} else if (day > 1 && day <=2) {
switch(data.lastfastpaytype){
case '1':{
fastPayText = '您好,我们的仓库人员已经在发货了,看到您的订单还没有支付,这里提醒您现在付款我们会优先发出,您可以很快收到包裹哦!<订单链接>';
break;
}
case '2':{
fastPayText = '亲,活动期间购买人数较多,为了您拍下的宝贝不因没货而取消,请及时完成付款哦,有问题请及时联系在线客服。<订单链接>';
break;
}
case '11':{
fastPayText = '亲,您眼光真好,这款衣服是我们的畅销款哦,已经打了5折呢,优惠了不少钱哦。<订单链接>';
break;
}
case '12':{
fastPayText = '亲,您真会挑选,这款是我们的新款,目前有尝新价哦,现在3折优惠,只有3天的优惠活动呢。<订单链接>';
break;
}
case '21':{
fastPayText = '您好,看到您的订单还没有支付,我现在给您申请了一份精美赠品哦,现在付款,明后天亲就可以收到了哦~<订单链接>';
break;
}
case '22':{
fastPayText = '您好,您在<卖家旺旺>店铺拍下的商品还没有付款,因为您是我们的老顾客了,我给店长申请了这次给您个超级会员价格,比您拍的时候少了很多哦。<订单链接>';
break;
}
case '31':{
fastPayText = '亲,伦家是<卖家旺旺>家的宝贝,哎呀,打滚求带走啦! 伦家好想快点见到你呢,赶紧带伦家走啦!<订单链接>';
break;
}
case '32':{
fastPayText = '亲爱的你已把我买下,老板让我跟你回家,付款后我立即飞奔亲家!<订单链接>';
break;
}
case '0':{
fastPayText = data.lastfastpay;
break;
}
}
} else {
switch(data.morefastpaytype){
case '1':{
fastPayText = '亲爱的<买家姓名>,估计最近有些小忙吧,两天前拍的订单还没有支付呢。亲抽空的时候记得要来把亲爱的宝贝带走哟~祝亲身体健康,万事如意!<订单链接>';
break;
}
case '2':{
fastPayText = '亲,您真会挑选,这款是我们的新款,目前有尝新价哦,现在3折优惠,只有3天的优惠活动呢。<订单链接>';
break;
}
case '11':{
fastPayText = '您好,看到您在活动中抢到了我们的宝贝,真的很幸运呢。您这边还有付款,不知道遇到什么问题呢,再过一会就要自动关闭交易了呢。有别的买家会在有货的时候支付掉,那您这边就失去这次机会了。<订单链接>';
break;
}
case '12':{
fastPayText = '亲,您在我们店拍下的宝贝已经确认,折扣仅限活动期间,亲可以尽快付款,以免错过哦!<订单链接>';
break;
}
case '21':{
fastPayText = '犹豫就收藏,喜欢就继续,实在舍不得,您就把它抱回家,到家请回信。<订单链接>';
break;
}
case '22':{
fastPayText = '亲爱的你已把我买下,老板让我跟你回家,付款后我立即飞奔亲家!<订单链接>';
break;
}
case '0':{
fastPayText = data.morefastpay;
break;
}
}
}
fastPayText=fastPayText.replace(/<买家姓名>/g,this.props.dataSource.receiver_name);
fastPayText=fastPayText.replace(/<买家旺旺>/g,this.props.dataSource.buyer_nick);
fastPayText=fastPayText.replace(/<卖家旺旺>/g,this.props.dataSource.seller_nick);
fastPayText=fastPayText.replace(/<下单时间>/g,this.props.dataSource.created);
fastPayText=fastPayText.replace(/<订单编号>/g,this.props.dataSource.tid);
fastPayText=fastPayText.replace(/<订单链接>/g,'http://trade.taobao.com/trade/detail/trade_item_detail.htm?bizOrderId=' + this.props.dataSource.tid);
UserContact({
status:'other',
value:fastPayText,
buyer_nick:this.props.dataSource.buyer_nick
});
});
}
/**
* 获取指定时间到今天的天数
* author: cbl
* @param {[type]} enddate [description]
* @return {[type]} [description]
*/
getLastDate(enddate) {
let date2 = new Date(Date.parse(enddate.replace(/-/g, "/")));
let s2 = date2.getTime();
let date1 = new Date();
let s1 = date1.getTime();
let ms = s1 - s2;
ms = ms/(3600*24*1000);
return ms;
}
/*核对地址 done*/
checkAddrPress() {
let trade = this.props.dataSource;
let self = this;
DoBeacon('TD20170114090141','heduidz');
if (this.props.userInfo.vipFlag == '0') {
let yyJson = [
{title:'地址/物流发错率减少30%',advantage:'及时核对地址,减少地址发错率,降低退货退款率'},
{title:'核对地址短语自定义',advantage:'7个自定义标签,任意组合位置和内容。'}
]
let name = '核对地址';/*来自哪一页,传入中文字符串*/
let feature = 'check_address';/*传入埋点值,不是项目编号哈!*/
let query = {xfrom:name, feature: feature} /*来自哪一页,传入中文字符串*/
QN.localstore.set({ /*将运营文本json存入localstorage*/
query: {
advertisment: yyJson
},
success(result) {
},
error(error) {
}
}).then(result => {
GoToView({status:'VipAd',query:query}); /*跳转页面*/
}, error => {
});
return;
}
StorageOper.localGet({
key: 'checkAddr_'+trade.seller_nick,
callback:(result)=>{
// console.log(result);
let checkAddr = result['checkAddr_'+trade.seller_nick];
let mydata = '';
if (checkAddr == undefined || checkAddr == '') {
mydata = '亲!请核对下地址哦:\n买家姓名:<买家姓名>\n联系方式:<联系方式>\n收货地址:<收货地址>\n买家邮编:<买家邮编>\n<商品属性\+数量>\n买家留言:<买家留言>\n卖家备注:<卖家备注>\n<微笑>';
} else {
mydata = checkAddr;
}
mydata = mydata.replace(/<买家姓名>/g, trade.receiver_name);
mydata = mydata.replace(/<联系方式>/g, trade.receiver_mobile + ' ' + trade.receiver_phone);
mydata = mydata.replace(/<收货地址>/g, trade.receiver_state + " " + trade.receiver_city + " " + trade.receiver_district + " " + trade.receiver_address);
mydata = mydata.replace(/<买家邮编>/g, trade.receiver_zip);
let sku_num = '';
for (let index in trade.orders.order) {
let order = this.props.dataSource.orders.order[index];
sku_num =sku_num + order.sku_properties_name+"*"+order.num+" ";
}
mydata = mydata.replace(/<商品属性\+数量>/g, sku_num);
mydata = mydata.replace(/<买家留言>/g, trade.buyer_message);
mydata = mydata.replace(/<卖家备注>/g, trade.seller_memo);
mydata = mydata.replace(/<吐舌头>/g, '/:Q');
mydata = mydata.replace(/<微笑>/g, '/:^_^');
mydata = mydata.replace(/<花痴>/g, '/:814');
mydata = mydata.replace(/<红唇>/g, '/:lip');
mydata = mydata.replace(/<天使>/g, '/:065');
mydata = mydata.replace(/<飞吻>/g, '/:087');
mydata = mydata.replace(/<爱慕>/g, '/:809');
mydata = mydata.replace(/undefined/g, '');
mydata = mydata.replace(/\n\n/g, '');
UserContact({
status:'other',
value:mydata,
buyer_nick:trade.buyer_nick
});
},
errCallback:(result)=>{
// console.log(result);
let mydata = '亲!请核对下地址哦:\n买家姓名:<买家姓名>\n联系方式:<联系方式>\n收货地址:<收货地址>\n买家邮编:<买家邮编>\n<商品属性\+数量>\n买家留言:<买家留言>\n卖家备注:<卖家备注>\n<微笑>';
mydata = mydata.replace(/<买家姓名>/g, trade.receiver_name);
mydata = mydata.replace(/<联系方式>/g, trade.receiver_mobile + ' ' + trade.receiver_phone);
mydata = mydata.replace(/<收货地址>/g, trade.receiver_state + " " + trade.receiver_city + " " + trade.receiver_district + " " + trade.receiver_address);
mydata = mydata.replace(/<买家邮编>/g, trade.receiver_zip);
let sku_num = '';
for (let index in trade.orders.order) {
let order = this.props.dataSource.orders.order[index];
sku_num =sku_num + order.sku_properties_name+"*"+order.num+" ";
}
mydata = mydata.replace(/<商品属性+数量>/g, sku_num);
mydata = mydata.replace(/<买家留言>/g, trade.buyer_message);
mydata = mydata.replace(/<卖家备注>/g, trade.seller_memo);
mydata = mydata.replace(/<吐舌头>/g, '/:Q');
mydata = mydata.replace(/<微笑>/g, '/:^_^');
mydata = mydata.replace(/<花痴>/g, '/:814');
mydata = mydata.replace(/<红唇>/g, '/:lip');
mydata = mydata.replace(/<天使>/g, '/:065');
mydata = mydata.replace(/<飞吻>/g, '/:087');
mydata = mydata.replace(/<爱慕>/g, '/:809');
mydata = mydata.replace(/undefined/g, '');
mydata = mydata.replace(/\n\n/g, '');
UserContact({
status:'other',
value:mydata,
buyer_nick:trade.buyer_nick
});
}
});
// Network.Post("/jy2/getCheckAddr",{nick:trade.seller_nick},(data)=>{
// let val = data.content.split('\n');
// let mydata = '';
// if (val != null && val.length > 1) {
// for (let index = 0; index <= val.length; index++) {
// if (val.length - 1 == index) {
// mydata += val[index];
// break;
// }
// mydata += val[index] + '\n';
// }
// } else {
// mydata = '亲!请核对下地址哦:\n买家姓名:<买家姓名>\n联系方式:<联系方式>\n收货地址:<收货地址>\n买家邮编:<买家邮编>\n<商品属性\+数量>\n买家留言:<买家留言>\n卖家备注:<卖家备注>\n<微笑>';
// }
//
// },{mode: 'jsonp'});
}
renderButton(order_status,order){
let jsx=[];
switch(order_status){
case '待付款':
jsx=[];
// jsx.push(<MyButton size="medium" style={{width:'160rem',marginRight:'16rem'}} text='短信催付' onPress={this.prcessCloseOrder.bind(this)}></MyButton>);
// if (this.props.userInfo.vipFlag == "1") {
//
// }
jsx.push(
<VipButton style={{width:'160rem',marginRight:'20rem'}} onPress={this.checkAddrPress.bind(this)} data={{name:'核对地址',isVip: this.props.userInfo.vipFlag,content: yyJson2 ,feature:'buy_check_address'}}></VipButton>
);
jsx.push(
// <View style={buttonBlockStyle.button}>
<VipButton style={{width:'160rem',marginRight:'20rem'}} onPress={this.payFastPress.bind(this)} data={{name:'旺旺催付',isVip: this.props.userInfo.vipFlag,content: yyJson ,feature:'buy_wangwang'}}></VipButton>
// </View>
);
jsx.push(<MyButton size="medium" style={buttonBlockStyle.button} text='关闭订单' onPress={this.prcessCloseOrder.bind(this)}></MyButton>);
if (this.props.userInfo.userType == 'C') {
// jsx.push(<Button style={buttonBlockStyle.button} size='medium' onPress={this.pressChangePrice.bind(this)}>修改价格</Button>);
jsx.push(<MyButton size="medium" style={buttonBlockStyle.button} onPress={this.pressChangePrice.bind(this)} text='修改价格'></MyButton>);
// jsx.push(<TouchableHighlight onPress={this.pressChangePrice.bind(this)} style={[buttonBlockStyle.button,{backgroundColor:'#fff',borderStyle:'solid',borderColor:'#dcdee3',borderWidth:'2rem',borderRadius:'8rem',width:'180rem',height:'60rem',alignItems:'center',justifyContent:'center'}]}>修改价格</TouchableHighlight>);
} else {
jsx.push(<MyButton size="medium" style={buttonBlockStyle.button} text='修改运费' onPress={()=>{this.refs.modal.show()}}></MyButton>);
}
return jsx;
case "待发货":
jsx=[];
// jsx.push(<MyButton size="medium" style={buttonBlockStyle.button} text='发货提醒' onPress={this.pressDeliverGoods.bind(this)}></MyButton>);
// if (this.props.userInfo.vipFlag == "1") {
//
// }
jsx.push(
// <View style={buttonBlockStyle.button}>
<VipButton style={{width:'160rem',marginRight:'20rem'}} onPress={this.checkAddrPress.bind(this)} data={{name:'核对地址',isVip: this.props.userInfo.vipFlag,content: yyJson2 ,feature:'to_send_checkaddress'}}></VipButton>
// </View>
);
jsx.push(<MyButton size="medium" style={buttonBlockStyle.button} text='发 货' onPress={this.pressDeliverGoods.bind(this)}></MyButton>);
// jsx.push(<Button style={buttonBlockStyle.button} size='small' onPress={this.pressDeliverGoods.bind(this)}>扫码发货</Button>);
return jsx;
case '已发货':
jsx=[];
// jsx.push(<MyButton size="medium" style={buttonBlockStyle.button} text='短信物流' onPress={this.pressDelayConfirm.bind(this)}></MyButton>);
jsx.push(<MyButton size="medium" style={buttonBlockStyle.button} text='延时收货' onPress={this.pressDelayConfirm.bind(this)}></MyButton>);
// jsx.push(<Button style={buttonBlockStyle.button} text='修改价格' tid={order.tid}>查看物流</Button>);
let trade=this.props.dataSource;
if(trade.consign_time){
var consignTime=trade.consign_time.replace(/-/g,"/");
var consign = new Date(consignTime);
var now = new Date();
var date3=now.getTime()-consign.getTime();
//计算出相差天数
var days=Math.floor(date3/(24*3600*1000));
if(days<=0 && this.state.isShow){
jsx.push(<MyButton size="medium" style={buttonBlockStyle.button} text='修改物流' onPress={this.changeLogistics.bind(this)}></MyButton>);
}
}
// jsx.push(<MyButton size="medium" style={buttonBlockStyle.button} text='旺旺物流' onPress={this.pressDelayConfirm.bind(this)}></MyButton>);
return jsx;
case '待评价':
jsx=[];
// if (!this.props.dataSource.buyer_rate) {
// jsx.push(<MyButton size="medium" style={buttonBlockStyle.button} text='评价提醒' onPress={this.evaluateTrade.bind(this)}></MyButton>);
// }
jsx.push(<MyButton size="medium" style={buttonBlockStyle.button} text='立即评价' onPress={this.evaluateTrade.bind(this)}></MyButton>);
return jsx;
case '退款中':
return <MyButton size="medium" style={buttonBlockStyle.button} text='处理退款' onPress={this.processRefund.bind(this)}></MyButton>
case '已成功':
jsx=[];
// if (!this.props.dataSource.buyer_rate) {
// jsx.push(<MyButton size="medium" style={buttonBlockStyle.button} text='评价提醒' onPress={this.evaluateTrade.bind(this)}></MyButton>);
// }
if (!this.props.dataSource.seller_rate) {
jsx.push(<MyButton size="medium" style={buttonBlockStyle.button} text='立即评价' onPress={this.evaluateTrade.bind(this)}></MyButton>);
}
return jsx;
}
}
hideModal = () => {
this.refs.modal.hide();
}
onShow = (param) => {
// console.log('modal show', param);
}
onHide = (param) => {
// console.log('modal hide', param);
}
render(){
let self=this;
let customStyles=this.props.style?this.propsstyle:undefined;
if(this.props.order_status=='已关闭'){
return;
}else if (this.props.order_status=='已成功' && (this.props.dataSource.seller_rate || this.getLastDate(this.props.dataSource.end_time)>15)) {
return;
}
if (this.props.order_status=='待付款' && this.props.page == "WwFastPay") {
return (
<View style={[buttonBlockStyle.container,customStyles]}>
<VipButton style={{width:'160rem',marginRight:'20rem'}} onPress={this.payFastPress.bind(this)} data={{name:'旺旺催付',isVip: this.props.userInfo.vipFlag,content: yyJson ,feature:'wangwang'}}></VipButton>
</View>
);
}
if (this.props.order_status=='待发货' && this.props.page == "CheckAddr") {
return (
<View style={[buttonBlockStyle.container,customStyles]}>
<VipButton style={{width:'160rem',marginRight:'20rem'}} onPress={this.checkAddrPress.bind(this)} data={{name:'核对地址',isVip: this.props.userInfo.vipFlag,content: yyJson2 ,feature:'check_address'}}></VipButton>
</View>
);
}
return (
<View style={[buttonBlockStyle.container,customStyles,{width:'750rem'}]}>
{
this.renderButton(this.props.order_status,this.props.dataSource)
}
<Dialog ref="modal" duration={200} contentStyle={styles.modalStyle} onShow={this.onShow} onHide={this.onHide}>
<View style={styles.body}>
<Text style={{color:'#333333',marginLeft:'35rem',marginTop:'20rem',fontSize:'28rem'}}>修改订单运费</Text>
<View style={{flexDirection:'row',alignItems:'center'}}>
<Input ref='price' style={{marginTop:'10rem',marginLeft:'35rem',width:'450rem',marginBottom:'15rem',borderWidth:'2rem',fontSize:'26rem'}} multiple={false} placeholder="填写运费价格" onInput={(value,e)=>{this.setState({price:value.value})}}/>
<Text style={{fontSize:'28rem',color:'#333333',marginTop:'10rem',marginLeft:'10rem'}}>元</Text>
</View>
</View>
<View style={styles.footer}>
<MyButton size="small" style={{marginRight:'24rem'}} onPress={()=>{this.refs.modal.hide()}} size='medium' text="取消"></MyButton>
<MyButton size="small" style={{marginRight:'24rem'}} type='secondary' size='medium' onPress={this.pressChangeLogistPrice.bind(this)} text="确定"></MyButton>
</View>
</Dialog>
</View>
);
}
}
const styles = {
modalStyle: {
width: '580rem',
},
body: {
alignItems: 'left',
justifyContent: 'center',
backgroundColor: '#ffffff',
flex:1
},
footer: {
alignItems: 'center',
justifyContent: 'flex-end',
height: '120rem',
flexDirection:'row',
backgroundColor:'#faf9fa'
}
}
const buttonBlockStyle={
container:{
borderColor:'#e2e3e8',
borderTopColor:'#dfdfe5',
borderWidth:'0rem',
flex:1,
// borderTopWidth:'1rem',
borderBottomWidth:'2rem',
flexDirection:'row',
flexWrap:'nowrap',
justifyContent: 'flex-end',
alignItems:'center',
padding:'0rem',
backgroundColor:'#faf9fa'
},
button:{
marginRight:'24rem',
width:'160rem',
marginTop:'20rem',
marginBottom:'20rem'
}
}
export default OrderButtonBlock;
<file_sep>/TradeData.jsx
/**
* 数据
* @author cbl
*/
import {Modal,View, Text, TouchableHighlight, ScrollView, Image, Icon, Link, Env, Button, Switch, Layout} from 'nuke';
import {createElement, Component,render} from 'rax';
import QN from 'QAP-SDK';
import {GoToView} from './Biz/View/GoToView.jsx';
import styles from './rxscss/tradeindex.rxscss';
import {StorageOper} from './Biz/View/StorageOper.jsx';
import IndexIcon from './Component/Trade/IndexIcon.jsx';
import PayFlag from './Component/Common/PayFlag.jsx';
import {Network} from 'Component/Common/Network.jsx';
import {getAllUserInfos} from 'Biz/User/GetAllUserInfos.jsx';
import {UserContact} from 'Biz/User/UserContact.jsx';
import AutoEvaData from './Component/TradeData/AutoEvaData.jsx';
import BadInterceptData from './Component/TradeData/BadInterceptData.jsx';
import CheckAddrData from './Component/TradeData/CheckAddrData.jsx';
import WwFastPayData from './Component/TradeData/WwFastPayData.jsx';
const { isWeex, isWeb, isQNWeb , isQNWeex , appInfo } = Env;
const { Col, Grid } = Layout;
class TradeIndex extends Component {
constructor() {
super();
this.state = {
autoEvaSwitch: false,
badInterceptSwitch: false,
flag:true
}
this.userNick = '';
this.vipFlag = '';
this.vipTime = '';
this.avatar = '';
}
/**
* 会在render函数前被执行
*/
componentWillMount(){
this.userNick = this.props.index.userNick;
this.vipFlag = this.props.index.vipFlag;
this.vipTime = this.props.index.vipTime;
this.avatar = this.props.index.avatar;
this.sub_user_nick = this.props.index.sub_user_nick;
}
GoToView(value){
GoToView({
status:value,
query:{userNick:encodeURI(this.userNick), vipFlag:this.vipFlag}
});
}
goToList(status){
let change_index = this.props.index;
change_index.goToList(status);
}
/**
* 重新授权
* by wp
*/
webauth(){
Network.Post('/Jy2/webauth', {content:result.data}, (res) => {
Modal.alert("授权成功请重新打开插件!",[
{
onPress:()=>{QN.navigator.close();},
text:"确定"
}
])
});
}
render(){
if(!this.state.flag){
return;
}
return(
<ScrollView style={{backgroundColor:'#eff0f4'}}>
<AutoEvaData dataIndex={this}></AutoEvaData>
<BadInterceptData dataIndex={this}></BadInterceptData>
<CheckAddrData dataIndex={this}></CheckAddrData>
<WwFastPayData dataIndex={this}></WwFastPayData>
</ScrollView>
);
}
}
export default TradeIndex;
<file_sep>/TradeListView.jsx
/**
* 订单列表
* @author Shitou
*/
import {createElement, Component,render} from 'rax';
import SearchBar from 'Component/Common/SearchBar.jsx';
import {View,Util,TouchableHighlight} from 'nuke';
import TradeList from 'TradeList.jsx';
import NavBar from './Component/NavBar/NavBar.jsx';
import NavBarItem from './Component/NavBar/NavBarItem.jsx';
import {DoBeacon,getQueryString} from 'Biz/Common.jsx';
import CustomTabbar from 'Component/OrderTabbar/CustomTabbar.jsx';
import ScrollableTabView from 'nuke-tab';
const Location = Util.Location;
import QN from 'QAP-SDK';
class TradeListView extends Component {
constructor() {
super();
this.state = {
key: 'dfh',
waitPayNum: 0,
waitSendNum: 0,
SendToNum: 0,
waitEvaNum: 0,
refundNum:0,
successNum:0,
closeNum:0,
search_key:undefined
};
this.userNick = '';
this.vipFlag = '';
this.vipTime = '';
this.avatar = '';
}
componentWillMount() {
this.userNick = this.props.index.userNick;
this.vipFlag = this.props.index.vipFlag;
this.vipTime = this.props.index.vipTime;
this.avatar = this.props.index.avatar;
this.userInfo = this.props.index.userInfo;
this.getStatusNum();
DoBeacon('TD20170114090141','ddlist');
}
componentDidMount(){
//以后列表的要直接跳到这里了
//去取得进来的默认状态
let url = document.URL;
let status=getQueryString(url,'status');
if(status!=undefined && status==''){
// console.log(status);
this.slideTo(status);
}
}
/**
* 获取各个状态的订单数量
*/
getStatusNum(){
let query = {
method: 'taobao.trades.sold.get',
fields:'timeout_action_time,end_time,pay_time,consign_time,rate_status,seller_nick,shipping_type,cod_status,orders.oid,orders.oid_str,orders.outer_iid,orders.outer_sku_id,orders.consign_time,tid,tid_str,status,end_time,buyer_nick,trade_from,credit_card_fee,buyer_rate,seller_rate,created,num,payment,pic_path,has_buyer_message,receiver_country,receiver_state,receiver_city,receiver_district,receiver_town,receiver_address,receiver_zip,receiver_name,receiver_mobile,receiver_phone,orders.timeout_action_time,orders.end_time,orders.title,orders.status,orders.price,orders.payment,orders.sku_properties_name,orders.num_iid,orders.refund_id,orders.pic_path,orders.refund_status,orders.num,orders.logistics_company,orders.invoice_no,seller_flag,type,post_fee,is_daixiao,has_yfx,yfx_fee,buyer_message,buyer_flag,buyer_memo,seller_memo',
type: 'tmall_i18n,fixed,auction,guarantee_trade,step,independent_simple_trade,independent_shop_trade,auto_delivery,ec,cod,game_equipment,shopex_trade,netcn_trade,external_trade,instant_trade,b2c_cod,hotel_trade,super_market_trade,super_market_cod_trade,taohua,waimai,nopaid,step,eticket',
};
let queryArr = [{
method:query.method,
fields:query.fields,
type:query.type,
status:'WAIT_BUYER_PAY'
}, {
method:query.method,
fields:query.fields,
type:query.type,
status:'WAIT_SELLER_SEND_GOODS'
}, {
method:query.method,
fields:query.fields,
type:query.type,
status:'WAIT_BUYER_CONFIRM_GOODS'
}, {
fields:query.fields,
method:query.method,
page_no:1,
page_size:100,
rate_status:"RATE_UNSELLER",
status:"TRADE_FINISHED",
type:query.type
}, {
method:"taobao.refunds.receive.get",
fields:"refund_id,status,tid",
pageSize:100
}, {
method:query.method,
fields:query.fields,
type:query.type,
status:'TRADE_FINISHED'
}, {
method:query.method,
fields:query.fields,
type:query.type,
status:'ALL_CLOSED'
}];
QN.top.batch({
query: queryArr,
}).then(result => {
if (result.data[0].error_response) {
if (result.data[0].error_response.sub_msg.indexOf('无此操作权限') > 0) {
Modal.alert("订单笔数获取失败!子账号无查看订单权限!请联系主账号开通权限");
}else{
Modal.alert(result.data[0].error_response.sub_msg);
}
return;
}
var waitPayNum = result.data[0].trades_sold_get_response.total_results;
var waitSendNum = result.data[1].trades_sold_get_response.total_results;
var SendToNum = result.data[2].trades_sold_get_response.total_results;
var waitEvaNum=0; //result.data[3].trades_sold_get_response.total_results;
if (result.data[3].trades_sold_get_response.trades != undefined) {
for(var i in result.data[3].trades_sold_get_response.trades.trade){
let trade=result.data[3].trades_sold_get_response.trades.trade[i];
//这里待评价叫做特殊处理
var order=trade;
let end_time_str=order.end_time;
end_time_str = end_time_str.replace(/-/g,"/");
var endTime = new Date(end_time_str);
var now=new Date;
var date3=now.getTime()-endTime.getTime();
//计算出相差天数
var days=Math.floor(date3/(24*3600*1000));
if(days>=15){
// console.log('时间大于15了 '+days);
continue;
}
waitEvaNum++;
}
} else {
waitEvaNum=0;
}
var refundNum =0; // result[4].refunds_receive_get_response.total_results;
let refundTids=[];
if (result.data[4].refunds_receive_get_response.refunds != undefined) {
for(var i in result.data[4].refunds_receive_get_response.refunds.refund){
let trade=result.data[4].refunds_receive_get_response.refunds.refund[i];
if(trade.status=='SUCCESS' || trade.status=='CLOSED'){
continue;
}
if(refundTids.indexOf(trade.tid)<0){
refundTids.push(trade.tid);
refundNum++;
}
}
} else {
refundNum =0;
refundTids=[];
}
var successNum = result.data[5].trades_sold_get_response.total_results;
var closeNum = result.data[6].trades_sold_get_response.total_results;
this.setState({
waitPayNum: waitPayNum,
waitSendNum: waitSendNum,
SendToNum: SendToNum,
waitEvaNum: waitEvaNum,
refundNum:refundNum,
successNum:successNum,
closeNum:closeNum
});
}, error => {
// console.error(error);
});
}
slideTo(status){
let index=0;
switch(status){
case 'dfk':
index=0;
break;
case 'dfh':
index=1;
break;
case 'dpj':
index=2;
break;
case 'tkz':
index=3;
break;
case 'yfh':
index=4;
break;
case 'ycg':
index=5;
break;
case 'ygb':
index=6;
break;
case 'all':
default:
index=7;
break;
}
this.refs.tabview.refs.tab.changeTab(index);
// this.setState({
// active:index
// })
}
renewSearchKey(searchKey){
this.setState({search_key:undefined})
this.setState({search_key:searchKey});
}
renderSearchArea(){
if(this.state.search_key){
return <TradeList userInfo={this.userInfo} order_status='搜索结果' view={this}></TradeList>;
}
}
render() {
if (this.props.tabKey) {
this.state.key = this.props.tabKey;
// console.error(this);
if(this.refs.navbar)
this.refs.navbar.setState({activeKey:this.state.key});
}
return (
<View style={{flex:1}}>
{/* <SearchBar
ref='searchbar'
placeholder="输入订单号/买家信息/宝贝信息/备注……"
onInput={this.props.onInput} onSearch={this.props.onSearch} /> */}
<View style={{flex:1}}>
{/* <NavBar ref="navbar" activeKey={this.state.key} title='待发货' onChange={this.OnStatusBarChange.bind(this)}>
<NavBarItem tabKey='all' title='近三个月'>
<TradeList userInfo={this.userInfo} hasHeader={true} order_status="近三个月"></TradeList>
</NavBarItem>
<NavBarItem tabKey='dfk' title='待付款'>
<TradeList userInfo={this.userInfo} hasHeader={true} order_status="待付款"></TradeList>
</NavBarItem>
<NavBarItem tabKey='dfh' title='待发货'>
<TradeList userInfo={this.userInfo} hasHeader={true} order_status="待发货"></TradeList>
</NavBarItem>
<NavBarItem tabKey='yfh' title='已发货'>
<TradeList userInfo={this.userInfo} hasHeader={true} order_status="已发货"></TradeList>
</NavBarItem>
<NavBarItem tabKey='tkz' title='退款中'>
<TradeList userInfo={this.userInfo} hasHeader={true} order_status="退款中"></TradeList>
</NavBarItem>
<NavBarItem tabKey='dpj' title='待评价'>
<TradeList userInfo={this.userInfo} hasHeader={true} order_status="待评价"></TradeList>
</NavBarItem>
<NavBarItem tabKey='success' title='已成功'>
<TradeList userInfo={this.userInfo} hasHeader={true} order_status="已成功"></TradeList>
</NavBarItem>
<NavBarItem tabKey='close' title='已关闭'>
<TradeList userInfo={this.userInfo} hasHeader={true} order_status="已关闭"></TradeList>
</NavBarItem>
<NavBarItem tabKey='search' title='搜索结果' hidden={true}>
{this.renderSearchArea()}
</NavBarItem>
</NavBar> */}
<ScrollableTabView ref="tabview" style={{flex:1,width:'750rem'}} tabHeight={80} renderTabBar={() => <CustomTabbar ref="tab" view={this} nick={this.userNick}/>} >
<TradeList userInfo={this.userInfo} hasHeader={true} tabLabel="待付款" order_status="待付款"></TradeList>
<TradeList userInfo={this.userInfo} hasHeader={true} tabLabel="待发货" order_status="待发货"></TradeList>
<TradeList userInfo={this.userInfo} hasHeader={true} tabLabel="待评价" order_status="待评价"></TradeList>
<TradeList userInfo={this.userInfo} hasHeader={true} tabLabel="退款中" order_status="退款中"></TradeList>
<TradeList userInfo={this.userInfo} hasHeader={true} tabLabel="已发货" order_status="已发货"></TradeList>
<TradeList userInfo={this.userInfo} hasHeader={true} tabLabel="已成功" order_status="已成功"></TradeList>
<TradeList userInfo={this.userInfo} hasHeader={true} tabLabel="已关闭" order_status="已关闭"></TradeList>
<TradeList userInfo={this.userInfo} hasHeader={true} tabLabel="近三个月" order_status="近三个月"></TradeList>
</ScrollableTabView>
</View>
</View>
);
}
}
export default TradeListView;
<file_sep>/RateTradePage.jsx
/** @jsx createElement */
import { ActionSheet,Button,Modal,Checkbox,Image,Input,View,ScrollView} from 'nuke';
import {createElement, Component,render} from 'rax';
import OrderBlocks from 'Component/OrderCard/OrderBlocks.jsx'
import QN from 'QAP-SDK';
import ListBlock from 'Component/Common/ListBlock.jsx';
import MyButton from 'Component/Common/MyButton.jsx';
import {RateTrade,BatchRateTrade} from 'Biz/Order/ProcessTrade.jsx';
import {GoToView} from 'Biz/View/GoToView.jsx';
import {Network} from 'Component/Common/Network.jsx';
const rate_result=['good','neutral','bad'];
let App = class RateTradePage extends Component{
constructor(){
super();
this.state={
data:undefined,
shortCuts:undefined,
comment:undefined,
checked:0,
}
}
componentWillMount(){
//获取快捷短语
this.queryShortCuts();
this.getTradeInfo();
this.initData();
}
initData(){
let self=this;
if(this.state.data==undefined){
QN.localstore.get({
query: {
key: 'evaluate_trade_data'
},
success(result) {
// console.log(result);
Network.Get('/jy2/getFastrate',(data)=>{
let data1=data.replace(/\\n/g , '\n');
self.setState({
data:result.data.evaluate_trade_data,
shortCuts:data1.split('\n'),
flag: true
});
});
},
error(error) {
// console.log(error);
}
})
}
}
getTradeInfo(){
let self=this;
if(this.state.data==undefined){
QN.localstore.get({
query: {
key: 'evaluate_trade_data'
},
success(result) {
// console.log(result);
self.setState({data:result.data.evaluate_trade_data});
},
error(error) {
// console.log(error);
}
})
}
}
//获取快捷短语
queryShortCuts(){
}
onSelectRateCheckbox(index){
// console.log(index);
this.setState({checked:index})
}
//实际做评价订单
evaluateOrder(){
let result=rate_result[this.state.checked];
let tid=this.state.data.tid;
// let content=this.refs.comment.props.value;
let content=this.value;
let self=this;
let oids=[];
// console.log(this.state.data);
if(this.state.data.orders.order){
for(var index in this.state.data.orders.order){
oids.push(this.state.data.orders.order[index].oid);
}
}
if(oids.length==0){
RateTrade({
tid:tid,
result:result,
content:content,
callback:(resp)=>{
Modal.alert('评价成功',[
{
onPress:(e)=>{
QN.emit('app.from',{data:'rate'});
self.goBack();
},
text:"确定"
}
]);
}
})
}
else{
BatchRateTrade({
tid:tid,
oids:oids,
result:result,
content:content,
callback:(resp)=>{
Modal.alert('评价成功',[
{
onPress:(e)=>{
QN.emit('app.from',{data:'rate'});
self.goBack();
},
text:"确定"
}
]);
}
})
}
}
goBack(){
let self=this;
GoToView({page_status:'pop',callback:(result)=>{QN.emit('app.evaluateTrade',{data:self.state.data.tid})}});
}
selectShortCuts(){
let self=this;
let cancelIndex=this.state.shortCuts.length;
ActionSheet.show({
options: [...this.state.shortCuts,'取消'],
cancelButtonIndex: cancelIndex,
title:'选择常用评价短语'
}, (ret) => {
if(ret.type=='button'){
// console.log(ret);
if(this.value==undefined){
this.value="";
}
this.value+=this.state.shortCuts[ret.buttonIndex];
self.setState({comment:this.value});
}
}, (fail) => {
}, (notify)=>{
});
}
renderInputbox(){
if(this.state.comment){
// console.log(this.state.comment);
return <Input ref='comment' value={this.state.comment} style={{height:'200rem',marginBottom:'0',marginTop:'0',borderWidth:'0rem',paddingLeft:'24rem',paddingRight:'24rem'}} multiple={true} placeholder="填写评价内容" onInput={(value,e)=>{ this.value=value.value; console.log(value.value);}}/>;
}
else{
return <Input ref='comment' style={{height:'200rem',marginBottom:'0',marginTop:'0',borderWidth:'0rem',paddingLeft:'24rem',paddingRight:'24rem'}} multiple={true} placeholder="填写评价内容" onFocus={(e) => console.log('onFocus',e)} onBlur={(e) => console.log('onBlur',e)} onInput={(value,e)=>{this.value=value.value; console.log(value.value);}}/>;
}
}
render(){
if(!this.state.flag){
return;
}
return(
<ScrollView style={[styles.container]}>
<View style={styles.ordercontainer}>
<OrderBlocks ref="orders" hasExpandOrders={false} checkbox={false} showPrice={false} dataSource={this.state.data.orders.order}></OrderBlocks>
</View>
<View style={[styles.ordercontainer,{marginBottom:'0rem',borderTopWidth:'2rem',borderBottomWidth:'2rem',borderColor:'#e6e6eb'}]}>
<View style={{flexDirection:'row',justifyContent:'space-between',marginRight:'30rem'}}>
<View style={{flexDirection:'row',justifyContent:'center',alignItems:'center'}}><Checkbox checked={0==this.state.checked} onChange={(checked,e)=>{if(checked) this.onSelectRateCheckbox(0)}}/><Image source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/gn_08.png'}} style={{width:'48rem',height:'48rem'}}/></View>
<View style={{flexDirection:'row',justifyContent:'center',alignItems:'center'}}><Checkbox checked={1==this.state.checked} onChange={(checked,e)=>{if(checked) this.onSelectRateCheckbox(1)}}/><Image source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/gn_09.png'}} style={{width:'48rem',height:'48rem'}}/></View>
<View style={{flexDirection:'row',justifyContent:'center',alignItems:'center'}}><Checkbox checked={2==this.state.checked} onChange={(checked,e)=>{if(checked) this.onSelectRateCheckbox(2)}}/><Image source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/gn_11.png'}} style={{width:'48rem',height:'48rem'}}/></View>
</View>
<ListBlock mainTitle='请选择常用评价短语' subTitle={this.state.refundReason} onPress={this.selectShortCuts.bind(this)}></ListBlock>
{this.renderInputbox()}
</View>
<View style={buttonBlockStyle.container}>
<MyButton style={buttonBlockStyle.button} type='secondary' size='medium' onPress={this.evaluateOrder.bind(this)} text="提交评价"></MyButton>
</View>
</ScrollView>
)
}
}
let styles={
container:{
backgroundColor:'#eff0f3',
flex:1,
justifyContent:'flex-start'
},
ordercontainer:{
justifyContent: 'center',
backgroundColor:'#ffffff',
paddingBottom:'0rem',
marginBottom:'28rem',
marginTop:'15rem',
},
resoncontainer:{
backgroundColor:'#ffffff',
borderBottomWidth:'2rem',
borderBottomStyle:'solid',
borderBottomColor:'#e2e3e8',
borderBottomColor:'#e2e3e8',
}
}
const buttonBlockStyle={
container:{
borderColor:'#e6e6eb',
borderWidth:'0rem',
borderBottomWidth:'2rem',
flexDirection:'row',
flexWrap:'nowrap',
justifyContent: 'flex-end',
alignItems:'center',
padding:'0rem',
paddingTop:'24rem',
paddingBottom:'24rem',
backgroundColor:'#faf9fa'
},
button:{
marginRight:'10rem'
}
}
render(<App/>);
<file_sep>/SmsLog.jsx
/**
* 短信关怀日志
* @author viper
*/
import QN from 'QAP-SDK';
import { ListView ,Icon,Picker,View, Text,TouchableHighlight,RefreshControl} from 'nuke';
import {createElement, Component,render} from 'rax';
import styles from './rxscss/smscare.rxscss';
import {Network} from 'Component/Common/Network.jsx';
import {DoBeacon} from './Biz/Common.jsx';
var logType = [{key:0,value:'全部'},{key:1,value:'催付提醒'},{key:2,value:'二次催付'},{key:3,value:'中差评提醒'},{key:4,value:'发货提醒'},{key:5,value:'收货提醒'},{key:6,value:'评价感谢'}];
var logTypeArr = ['all','smspay','smssecond','smsbad','smssend','smswl','smsgood'];
let listData = [];
var page_no = 1;
class SmsLog extends Component {
constructor() {
super();
/*let date = new Date();
date = date.toLocaleDateString()+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();*/
this.state = {
flag:false,
logType:'全部',
logTypeIndex:0,
data: listData,
page_num:0,
stop: false,
isRefreshing: false,
showLoading:true,
refreshText: '↓ 下拉刷新'
};
this.index = 0;
}
handleRefresh = (e) => {
let type = logTypeArr[this.state.logTypeIndex];
this.getLogdata(1,type);
this.setState({
isRefreshing: true,
refreshText: '加载中',
});
setTimeout(() => {
this.setState({
isRefreshing: false,
data: listData,
refreshText: '↓ 下拉刷新',
});
}, 1000);
};
handleLoadMore() {
var self = this;
// 这里进行异步操作
if (self.index == self.state.page_num) {
self.setState({showLoading:false})
return;
}else{
setTimeout(function() {
/*self.state.data.push({key: 'l1',text:'loadmore1'}, {key: 'l2',text:'loadmore2'}, {key: 'l3',text:'loadmore3'},{key: 'l4',text:'loadmore4'}, {key: 'l5',text:'loadmore5'});
self.setState(self.state);*/
self.index++;
page_no += 1;
let type = logTypeArr[self.state.logTypeIndex];
self.getLogdata(page_no,type);
}, 1000);
}
}
linkTo(item,e) {
}
/*切换日志类型,仅在切换类型时触发 by viper918*/
showLog(value) {
let self = this;
Picker.show({title:'请选择',dataSource:logType,selectedKey:'0',maskClosable:true},function(e){
self.index = 0;
self.setState({logType:e[0].value,logTypeIndex:e[0].key,page_num:0});
self.getLogdata(1,logTypeArr[e[0].key]);
},function(e){
});
listData = [];
}
/*获取日志数据 by viper918*/
getLogdata(page_no,type){
let self = this;
Network.Post('/jy2/smslog',{page:page_no,type:type},(data)=>{
for(var i=0; i<data.smslog.length;i++){
let status = '';
let color = '#3C3';/*控制发送状态字体颜色*/
if(data.smslog[i].status == '1'){
status = '发送成功'
}
else{
color = 'red';
if(data.smslog[i].status == '0'){
status = '提交失败';
}
else if(data.smslog[i].status == '2'){
status = '发送失败';
}
else {
status = '发送中';
}
}
let tid = data.smslog[i].tid.split('#')[0];/*根据tid长度判断来控制订单号显示的是tid还是buyernick*/
if(tid.length != 16){
tid = data.smslog[i].buyernick;
}
listData.push({key: i,text:data.smslog[i].smstext,tid:tid,status:status,smstime:data.smslog[i].smstime,smsnum:data.smslog[i].smsnum,color:color});
}
self.setState({data:listData,page_num:data.page_num});
});
}
/*在渲染组件前进行*/
componentWillMount(){
let self = this;
DoBeacon('TD20170114090141','duanxinrizhi');
self.getLogdata(1,'all');
}
renderItem (item, index){
return (
<TouchableHighlight style={[styles.cellItemList,{marginTop:'24rem',paddingLeft:'0'}]} onPress={this.linkTo.bind(this,item)}>
<View style={{paddingTop:'20rem'}}>
<View style={[styles.smsLogTitle,{borderBottomColor:'#c4c6cf',borderBottomWidth:'1rem'}]}>
<Text style={[styles.smsLogLabel,{flex:'50',paddingLeft:'24rem'}]}>订单号:{item.tid}</Text>
<Text style={[styles.smsLogLabel,{flex:'18',color:item.color}]}>{item.status}</Text>
<Text style={[styles.smsLogLabel,{flex:'15',color:'#999999'}]}>扣除条数</Text>
<Text style={[styles.smsLogLabel,{flex:'4',color:'red'}]}>{item.smsnum}</Text>
</View>
<View style={{padding:'24rem',borderBottomColor:'#c4c6cf',borderBottomWidth:'1rem'}}>
<Text style={[styles.itemTextList,{fontSize:'32rem'}]}>{item.text}</Text>
</View>
<View style={[styles.smsLogTitle,{paddingLeft:'24rem'}]}>
<Text style={[styles.smsLogLabel,{color:'#999999'}]}>发送时间:{item.smstime}</Text>
</View>
</View>
</TouchableHighlight>
);
}
renderHeader=()=>{
return (<RefreshControl style={styles.refresh} refreshing={this.state.isRefreshing} onRefresh={this.handleRefresh}><Text style={styles.loadingText}>{this.state.refreshText}</Text></RefreshControl>);
}
renderFooter=()=>{
return this.state.showLoading ?
<View style={[styles.loading]}><Text style={styles.loadingText}>加载中...</Text></View>
:null
}
render(){
return(
<View style={{flex:'1',backgroundColor:'#eff0f4'}}>
<View style={[styles.smsCard,styles.smsCardBorder,{flexDirection:'row',justifyContent:'center',height:'80rem'}]}>
<View style={[styles.smsCardTitle,styles.smsCardLabel,{flex:'5',top:'5rem'}]}>选择类型</View>
<TouchableHighlight style={{flex:'10',alignSelf:'flex-end'}} onPress={this.showLog.bind(this)} type="primary">
<Text style={{color:'#999',alignSelf:'flex-end'}}>{this.state.logType}</Text>
</TouchableHighlight>
<View style={{flex:'2'}}>
<Icon style={{marginTop:'10rem',color:'#c7c7c7',alignSelf:'flex-end'}} name="arrowRight" />
</View>
</View>
<ListView
renderHeader={this.renderHeader}
renderFooter={this.renderFooter}
renderRow={this.renderItem.bind(this)}
dataSource={this.state.data}
style={{flex:1}}
onEndReached={this.handleLoadMore.bind(this)}
/>
</View>
);
}
}
render(<SmsLog/>);
<file_sep>/Biz/User/GetUserInfo.jsx
/**
* @author shitou
*/
import QN from 'QAP-SDK';
import {StorageOper} from './../View/StorageOper.jsx';
import { IsEmpty } from './../View/IsEmpty.jsx';
import { UserSubscribe } from './UserSubscribe.jsx';
// import { Modal } from 'nuke';
let userNick;
let vipFlag;
let vipTime;
let addInfo;
var GetUserVipInfo = function({callback}){
let key = [];
key = key.concat('vipFlag_'+userNick);
key = key.concat('vipTime_'+userNick);
key = key.concat('seller_type_'+userNick);
key = key.concat('appInfo_'+userNick);
key = key.join(',');
StorageOper.localGet({
key:key,
callback:(result)=>{
if (!IsEmpty(result)) {
vipFlag = result['vipFlag_'+userNick];
vipTime = result['vipTime_'+userNick];
addInfo = result['appInfo_'+userNick];
var data = {};
data.vipFlag = vipFlag;
data.vipTime = vipTime;
data.userNick = userNick;
data.addInfo = addInfo;
callback(data);
}else{
UserSubscribe({
usernick:userNick,
callback: (result)=>{
var subscribes = result.vas_subscribe_get_response;
if (!IsEmpty(subscribes)) {
vipTime = subscribes.article_user_subscribes.article_user_subscribe[0].deadline;
vipFlag = subscribes.article_user_subscribes.article_user_subscribe[0].item_code;
if (vipFlag == 'FW_GOODS-1827490-v2') {
vipFlag = 1;
}else{
vipFlag = 0;
}
vipFlag = vipFlag;
vipTime = vipTime;
}else{
vipFlag = 0;
vipTime = 0;
}
var data = {};
data.vipFlag = vipFlag;
data.vipTime = vipTime;
data.userNick = userNick;
callback(data);
},
error_callback:(error)=>{
// console.error(error);
}
});
}
}
});
}
var GetUserInfo= function({callback}){
StorageOper.sessionGet({
key:'user_nick',
callback:(result)=>{
// console.error(result);
if (!IsEmpty(result)) {
userNick = result;
GetUserVipInfo({
callback:(result)=>{
// console.error(result);
callback(result);
}
});
}else{
QN.user.getInfo({
success(result) {
userNick = result.data.user_nick;
GetUserVipInfo({
callback:(result)=>{
// console.error(result);
callback(result);
}
});
},error(error){
// console.error(error);
}
});
}
},
errCallback:(result)=>{
QN.user.getInfo({
success(result) {
userNick = result.data.user_nick;
GetUserVipInfo({
callback:(result)=>{
// console.error(result);
callback(result);
}
});
},error(error){
// console.error(error);
}
});
}
});
};
export {GetUserInfo};
<file_sep>/BadIntercept.jsx
/*
*@author dsl
*/
import { Modal,Button,Icon,Checkbox,ActionSheet,View, Text,TouchableHighlight,Switch,ScrollView,TextInput} from 'nuke';
import {createElement, Component,render} from 'rax';
import QN from 'QAP-SDK';
import badStyles from './rxscss/BadIntercept.rxscss';
import {PUBLIC} from './rxscss/public-style.jsx';
import {Network} from './Component/Common/Network.jsx';
import {GoToView} from './Biz/View/GoToView.jsx';
import {QNInvoke} from 'Biz/Common.jsx';
import {UserVip} from './Biz/User/UserVip.jsx';
import ListBlock from 'Component/Common/ListBlock.jsx';
import {getAllUserInfos} from './Biz/User/GetAllUserInfos.jsx';
import {DoBeacon} from 'Biz/Common.jsx';
class BadIntercept extends Component {
/*初始化页面*/
constructor() {
super();
this.state = {
denfenon : false,
ceptTotal : 0,
addbiew:true,
flexzcp:false,
iconzcp:"arrowRight",
flexmjx:false,
iconmjx:"arrowRight",
flexsxysr:false,
iconsxysr:"arrowRight",
flexclosewhy:false,
iconclosewhy:"arrowRight",
flexItemtric:false,
iconItemtric:"arrowRight",
flexOrderInfo:false,
iconOrderInfo:"arrowRight",
publet:"zcplj",
publicval:"",
publicOnfoce:"sxysrlj",
publicIndex:0,
closewhyVal:0,
disabledSW:false,
gotoVip:""
};
this.userNick = "";
this.vipFlag = 0;
this.closewhyAry=["未及时付款","买家不想买了","买家信息填写错误,重新拍","恶意买家/同行捣乱","缺货","买家拍错了","同城见面交易"];
this.zcplj = [
{name:"zcplj",cked:false,mojs:"给过我中评的买家",moinput:"",val:"",last:"",lastext:""},
{name:"zcplj",cked:false,mojs:"给过我差评的买家",moinput:"",val:"",last:"",lastext:""},
{name:"zcplj",cked:false,mojs:"收到的好评率低于:",moinput:"可输入0~99.99",val:"",last:"%",lastext:""},
{name:"zcplj",cked:false,mojs:"",moinput:"",val:"",last:"",lastext:"*该好评率是卖家给买家发送的好评率【根据淘宝规则,第三方软件无法获取买家给卖家的好评率。请谨慎使用声称获取到该数据的软件】"}
];
this.mjxxlj=[
{name:"mjxxlj",cked:false,mojs:"买家信誉分数低于:",moinput:"可输入0~99999",val:"",last:"分",lastext:""},
{name:"mjxxlj",cked:false,mojs:"没有绑定支付宝账户的买家",moinput:"",val:"",last:"%",lastext:""},
{name:"mjxxlj",cked:false,mojs:"买家注册天数小于:",moinput:"可输入0~99999",val:"",last:"天",lastext:""}];
this.itemtric=[
{name:"itemtric",cked:false,mojs:"订单购买件数大于:",moinput:"可输入0~99999",val:"",last:"件",lastext:""},
{name:"itemtric",cked:false,mojs:"订单中同一件宝贝大于:",moinput:"可输入0~99999",val:"",last:"件",lastext:""}];
this.orderInfo=[
{name:"orderInfo",cked:false,mojs:"订单金额大于(含运费):",moinput:"最大输入99999",val:"",last:"元",lastext:""},
{name:"orderInfo",cked:false,mojs:"订单金额小于(含运费):",moinput:"最小输入1",val:"",last:"元",lastext:""}];
this.sxysrlj=[
{name:"sxysrlj",cked:false,mojs:"地址或留言中包含以下关键字",moinput:"",val:"",last:"",lastext:""},
{name:"sxysrlj",cked:"keyworld",mojs:"*关键字之间用逗号隔开",moinput:"",val:"",last:"",lastext:""}];
}
componentWillMount(){
QN.showLoading({
query: {
text: '加载中 ~~'
}
});
this.getSwitchStatus();
let self=this;
getAllUserInfos({
callback: (result)=>{
if(result.sub_user_nick){
self.userNick = result.sub_user_nick;
}else{
self.userNick = result.userNick;
}
self.vipFlag = result.vipFlag;
if(self.vipFlag==0){
self.state.gotoVip=self.getMoney();
}
if(RegExp(":").test(self.userNick)){
self.setState({
disabledSW:true
});
Modal.toast("子账号不支持操作差评拦截开关设置!");
}
},
error_callback:(error)=>{
}
});
}
getMoney(){
return(
<TouchableHighlight onPress={this.GoToView.bind(this)} style={{width:'750rem',height:'80rem',justifyContent:'center',backgroundColor:'#fff0e7',flexDirection:'row'}}>
<Icon style={{fontSize:'32rem',color:'#f95b1c',alignSelf:'center',textAlign:'center'}} name='warning' />
<Text style={{fontSize:'28rem',color:'#f95b1c',alignSelf:'center',textAlign:'center'}}> 亲,差评拦截是高级版功能,您需要</Text>
<TouchableHighlight style={{fontSize:'28rem',color:'#f95b1c',alignSelf:'center',textAlign:'center'}}>
<Text style={{fontSize:'28rem',color:'#0066FF ',alignSelf:'center',textAlign:'center',textDecoration:'underline'}}>升级</Text></TouchableHighlight>
<Text style={{fontSize:'28rem',color:'#f95b1c',alignSelf:'center',textAlign:'center'}}>才能使用</Text>
</TouchableHighlight>
);
}
/*听说这是张凝同学的坑*/
GoToView(value){
let yyJson = [
{title:'拦截80%差评买家', advantage:'根据设置拦截疑似差评买家,80%差评买家都会被拦截'},
{title:'11种拦截条件,独家百万云黑名单',advantage:'11中拦截条件全方位拦截,爱用独家云黑名单不放过任何一个差评师'},
{title:'白名单不拦截',advantage:'不是差评师,设置白名单以后不拦截'}
]; /*运营文本json,格式的话···往上翻就能看到*/
let name = '差评拦截';/*来自哪一页,传入中文字符串*/
let bid = '20170109ShowBadComment';/*传入埋点值,不是项目编号哈!*/
let query = {xfrom:name, bid: bid} /*来自哪一页,传入中文字符串*/
QN.localstore.set({ /*将运营文本json存入localstorage*/
query: {
advertisment: yyJson
},
success(result) {
},
error(error) {
}
}).then(result => {
GoToView({status:'VipAd',query:query}); /*跳转页面*/
}, error => {
Modal.toast(error);
});
}
/** 差评拦截开关状态**/
getSwitchStatus(){
let self = this;
Network.Post('/jy2/getdefenserate',{},(data)=>{
/*判断差评拦截各种开关状态*/
if(data.total==1){/*设置过开关*/
var rsp=data.res;
let zcplj=self.zcplj;
let mjxxlj=self.mjxxlj;
let orderInfo=self.orderInfo;
let itemtric=self.itemtric;
let sxysrlj=self.sxysrlj;
self.state.denfenon=rsp.denfenon=="on"?true:false;
zcplj[0].cked=rsp.neutralon=="on"?true:false;
zcplj[1].cked=rsp.badon=="on"?true:false;
let goodrate=rsp.goodrate;
if(RegExp(';').test(goodrate)){
let goodrates=goodrate.split(";")
zcplj[2].cked=goodrates[0]=="on"?true:false;
zcplj[2].val=goodrates[1];
}
let credit=rsp.credit;
if(RegExp(';').test(credit)){
let credits=credit.split(";")
mjxxlj[0].cked=credits[0]=="on"?true:false;
mjxxlj[0].val=credits[1];
}
mjxxlj[1].cked=rsp.noalipay=="on"?true:false;
let regdays=rsp.regdays;
if(RegExp(';').test(regdays)){
let regdayss=regdays.split(";")
mjxxlj[2].cked=regdayss[0]=="on"?true:false;
mjxxlj[2].val=regdayss[1];
}
let bigmoney=rsp.bigmoney;
if(RegExp(';').test(bigmoney)){
let bigmoneys=bigmoney.split(";")
orderInfo[0].cked=bigmoneys[0]=="on"?true:false;
orderInfo[0].val=bigmoneys[1];
}
let smallmoneys=rsp.smallmoney;
if(RegExp(';').test(smallmoneys)){
let smallmoneyss=smallmoneys.split(";")
orderInfo[1].cked=smallmoneyss[0]=="on"?true:false;
orderInfo[1].val=smallmoneyss[1];
}
let carnums=rsp.carnum;
if(RegExp(';').test(carnums)){
let carnumss=carnums.split(";")
itemtric[0].cked=carnumss[0]=="on"?true:false;
itemtric[0].val=carnumss[1];
}
let babynum=rsp.babynum;
if(RegExp(';').test(babynum)){
let babynums=babynum.split(";")
itemtric[1].cked=babynums[0]=="on"?true:false;
itemtric[1].val=babynums[1];
}
let conditions=rsp.conditions;
if(RegExp('|Y|').test(conditions)){
let conditionss=conditions.split("|Y|")
sxysrlj[0].cked=conditionss[0]== "on"?true:false;
sxysrlj[1].val=conditionss[1];
}
if(/^\d+$/.test(rsp.sellernote)){
let sellernote=Number(rsp.sellernote);
self.state.closewhyVal=sellernote;
}
self.state.addbiew=rsp.addbiew=="on"?true:false;
self.getIntercept();
}else{
self.childAccount();
}
QN.hideLoading();
},{mode: 'jsonp'},(error_callback)=>{
QN.hideLoading();
// Modal.toast(JSON.stringify(error_callback));
});
}
childAccount(){
let self=this;
self.setState({
ceptTotal:self.state.ceptTotal,
denfenon:self.state.denfenon,
addbiew:self.state.addbiew
});
}
/*获取拦截数量*/
getIntercept(){
let self = this;
Network.Post("/jy2/getblacklist2",{page_no:1},(rsp)=>{
self.state.ceptTotal=rsp.total;
self.childAccount();
});
}
goToNewPage(value){
if(this.vipFlag==0){
this.GoToView();
return;
}
GoToView({
title:"拦截日志",
status:value
});
}
twofun(){
if(this.vipFlag ==0){
this.GoToView();
return true;
}
if(RegExp(":").test(this.userNick)){
Modal.alert("子账号不支持修改差评拦截!",[{
onPress:()=>{},
text:'确定'
}]);
return true;
}
}
/*开启关闭差评拦截*/
onChecked(value,elent){
DoBeacon('TD20170114090141','kaiqicpljck',this.userNick);/*开启关闭差评拦截埋点*/
let self=this;
let km=self.twofun();
if(km){
return null;
}
if(value){/*开启差评拦截*/
let query={
method: 'taobao.tmc.user.permit' /*开启tmc*/
}
QNInvoke(query,(result)=>{
/*我听说子账号不能开启tmc,未完待续*/
if(result.tmc_user_permit_response.is_success){
Network.Post("/jy2/defenserateoff",{types:'on'},(rsp)=>{
Modal.alert("恭喜你,差评拦截开启成功!",[{
onPress:()=>{},
text:'确定'
}]);
},{mode: 'jsonp'},(error_callback)=>{
Modal.alert(JSON.stringify(error_callback),[{
onPress:()=>{},
text:'确定'
}]);
});
}else{
Modal.alert(JSON.stringify(result),[{
onPress:()=>{},
text:'确定'
}]);
}
},(error_callback)=>{
});
}else{/*关闭差评拦截*/
/**听说关闭差评拦截要先关闭后台数据库,然后才是关闭tmc推送
*但是 我又听说要先判断是否有其他功能使用tmc推送,俗话说不能一棒子打死*/
Network.Post("/jy2/gettmcinfo",{type:"defenserate"},(rsp)=>{
if(rsp=="yes"){
let query={
method: 'taobao.tmc.user.cancel', /*关闭tmc*/
nick:this.userNick
}
QNInvoke(query,(result)=>{
if(result.tmc_user_cancel_response.is_success){
Network.Post("/jy2/defenserateoff",{types:'off'},(rsp)=>{
Modal.alert("恭喜你,差评拦截关闭成功!",[{
onPress:()=>{},
text:'确定'
}]);
},{mode: 'jsonp'},(error_callback)=>{
Modal.alert(JSON.stringify(error_callback),[{
onPress:()=>{},
text:'确定'
}]);
});
}
},(error_callback)=>{
Modal.alert(JSON.stringify(error_callback),[{
onPress:()=>{},
text:'确定'
}]);
});
}else{
Modal.alert("恭喜你,差评拦截关闭成功!",[{
onPress:()=>{},
text:'确定'
}]);
}
},{mode: 'jsonp'},(error_callback)=>{
Modal.alert(JSON.stringify(error_callback),[{
onPress:()=>{},
text:'确定'
}]);
});
}
}
/*保存设置*/
saveBadInt(){
DoBeacon('TD20170114090141','baocunclick',this.userNick);/*点击保存设置埋点*/
let km=this.twofun();
if(km){
return null;
}
/*开始保存数据*/
let info=new Object();
info.Tzhongpingoff=this.zcplj[0].cked?"on":"off"; /*给过我中评*/
info.Tchapingoff=this.zcplj[1].cked?"on":"off"; /*给过我差评*/
info.Tgoodvalues=(this.zcplj[2].cked?"on;":"off;")+this.zcplj[2].val;/*好评率*/
info.crevalues=(this.mjxxlj[0].cked?"on;":"off;")+this.mjxxlj[0].val;/*买家信誉分株*/
info.Talipay=this.mjxxlj[1].cked?"on":"off";/*支付宝交易*/
info.Tregdayvalues=(this.mjxxlj[2].cked?"on;":"off;")+this.mjxxlj[2].val;/*买家注册天数*/
info.Tbigmoney=(this.orderInfo[0].cked?"on;":"off;")+this.orderInfo[0].val;/*订单最大金额*/
info.Tsmallmoney=(this.orderInfo[1].cked?"on;":"off;")+this.orderInfo[1].val;/*最小金额*/
info.car=(this.itemtric[0].cked?"on;":"off;")+this.itemtric[0].val;/*购物车数量*/
info.babysum=(this.itemtric[1].cked?"on;":"off;")+this.itemtric[1].val;/*宝贝数量*/
info.condikey=(this.sxysrlj[0].cked?"on|Y|":"off|Y|")+this.sxysrlj[1].val;/*关键字*/
info.addbeiw=this.state.addbiew?"on":"off";/*关闭原因添加到关闭备注*/
info.Tclosetent=this.state.closewhyVal;/*关闭解释*/
if (this.zcplj[2].cked && this.zcplj[2].val == '') {
Modal.alert("收到的好评率不能为空",[{
onPress:()=>{},
text:'确定'
}]);
return;
}
if (this.mjxxlj[0].cked && this.mjxxlj[0].val == '') {
Modal.alert("买家信誉分不能为空",[{
onPress:()=>{},
text:'确定'
}]);
return;
}
if (this.mjxxlj[2].cked && this.mjxxlj[2].val == '') {
Modal.alert("买家注册天数不能为空",[{
onPress:()=>{},
text:'确定'
}]);
return;
}
if (this.orderInfo[0].cked && this.orderInfo[0].val == '') {
Modal.alert("订单最大金额不能为空",[{
onPress:()=>{},
text:'确定'
}]);
return;
}
if (this.orderInfo[1].cked && this.orderInfo[1].val == '') {
Modal.alert("订单最小金额不能为空",[{
onPress:()=>{},
text:'确定'
}]);
return;
}
if (this.itemtric[0].cked && this.itemtric[0].val == '') {
Modal.alert("订单购买件数不能为空",[{
onPress:()=>{},
text:'确定'
}]);
return;
}
if (this.itemtric[1].cked && this.itemtric[1].val == '') {
Modal.alert("订单中同一宝贝数不能为空",[{
onPress:()=>{},
text:'确定'
}]);
return;
}
if (this.sxysrlj[0].cked && this.sxysrlj[1].val == '') {
Modal.alert("关键字不能为空",[{
onPress:()=>{},
text:'确定'
}]);
return;
}
Network.Post("/jy2/savedefenseratedsl",info,(rsp)=>{
Modal.alert("恭喜你,差评拦截设置保存成功!",[{
onPress:()=>{},
text:'确定'
}]);
},{mode: 'jsonp'},(error_callback)=>{
Modal.alert(JSON.stringify(error_callback),[{
onPress:()=>{},
text:'确定'
}]);
});
}
/*显示下拉狂的输入框*/
publicShow(keyvalue,index){
let name=keyvalue.name;
if(keyvalue.moinput||keyvalue.moinput!=""){
let self=this;
return (
<View style={{flexDirection:"row",justifyContent:"flex-start",alignItems:"center"}}>
<View style={{flex:1,borderColor:'#dddddd'}}>
<TextInput placeholder={keyvalue.moinput} maxLength={5} value={keyvalue.val} onInput={this.publicVal.bind(this,name,index)} style={{height:'100rem',flex:1}}/>
</View>
<View style={{paddingRight:'55rem'}}>
<Text style={{fontSize:"28rem"}}>{keyvalue.last}</Text>
</View>
</View>
)
}
}
/*textInput 输入参数公用*/
publicVal(name,index,val){
let publicval=val.value;
if((!isNaN(publicval)&&name!="sxysrlj"&&publicval>0&&publicval<99999) || publicval == ""){
if(name=="itemtric"){
this.itemtric[index].val=publicval;
}else if(name=="orderInfo"){
this.orderInfo[index].val=publicval;
}else if(name=="mjxxlj"){
this.mjxxlj[index].val=publicval;
}else if(name=="zcplj"){
if(Number(publicval)>0&&Number(publicval)<100){
this.zcplj[index].val=publicval;
}else{
Modal.toast("请输入0~100之间的合法数据!");
}
}
}else{
if(name=="sxysrlj"){
this.sxysrlj[index].val=publicval;
}else{
Modal.toast("请输入合法数据~");
}
}
}
textareass(keyvalue,index){
let self = this;
let name=keyvalue.name;
if(keyvalue.cked=="keyworld"){/*根据关键词拦截*/
return(
<View style={[badStyles.borderChileLi,{paddingLeft:"10rem",lines:'2'}]}>
<TextInput multiline={true} value={keyvalue.val} placeholder={keyvalue.mojs} onInput={this.publicVal.bind(this,name,index)} style={badStyles.keyWorld} />
</View>
)
}else if(keyvalue.lastext!=""){
let lastext_one=keyvalue.lastext;
return(
<View style={badStyles.explainRed}>
<Text style={{color:"#FF3333",fontSize:"28rem"}}>{lastext_one}</Text>
</View>
)
}else{
return(
<View style={badStyles.borderChileLi}>
<Checkbox defaultChecked={keyvalue.cked} size="small" name="1" onChange={()=>{this.caicai(name,index)}}></Checkbox>
<Text style={{fontSize:"28rem"}}>{keyvalue.mojs}</Text>
<View style={{flex:1}}>
{
self.publicShow(keyvalue,index)
}
</View>
</View>
)
}
}
/*复选框状态*/
caicai=(name,index)=>{
switch(name){
case "sxysrlj":
this.sxysrlj[index].cked=!this.sxysrlj[index].cked;
break;
case "itemtric":
this.itemtric[index].cked=!this.itemtric[index].cked;
break;
case "orderInfo":
this.orderInfo[index].cked=!this.orderInfo[index].cked;
break;
case "mjxxlj":
this.mjxxlj[index].cked=!this.mjxxlj[index].cked;
break;
case "zcplj":
this.zcplj[index].cked=!this.zcplj[index].cked;
break;
}
}
/*更改单选框按钮*/
updateRedio(redioval){
this.closewhy[0].val=redioval;
}
/*展示点击下拉框*/
moduleFill(module){
let self=this;
let List=module.map(function(e,n){
return(
<View>
{self.textareass(e,n)}
</View>
)
})
let name=module[0].name;
return (
<View>{List}</View>
)
}
moudleRenderzcp(){
if (this.state.flexzcp) {
return(<View>{this.moduleFill(this.zcplj)}</View>)
}
}
moudleRendermjxx(){
if (this.state.flexmjx) {
return(<View>{this.moduleFill(this.mjxxlj)}</View>)
}
}
moudleRendersxysr(){
if (this.state.flexsxysr) {
return(<View>{this.moduleFill(this.sxysrlj)}</View>)
}
}
moudleRenderOrderInfo(){
if (this.state.flexOrderInfo) {
return(<View>{this.moduleFill(this.orderInfo)}</View>)
}
}
moudleRenderItemtric(){
if (this.state.flexItemtric) {
return(<View>{this.moduleFill(this.itemtric)}</View>)
}
}
moduleState(name){
let arrow="arrowRight";
switch(name){
case "zcplj":
arrow=this.state.flexzcp?"arrowRight":"arrowDown";
this.setState({
flexzcp:!this.state.flexzcp,
publet:this.state.publet="zcplj",
iconzcp:arrow
})
break;
case "mjxxlj":
arrow=this.state.flexmjx?"arrowRight":"arrowDown";
this.setState({
flexmjx:!this.state.flexmjx,
publet:this.state.publet="mjxxlj",
iconmjx:arrow
})
break;
case "sxysrlj":
arrow=this.state.flexsxysr?"arrowRight":"arrowDown";
this.setState({
flexsxysr:!this.state.flexsxysr,
publet:this.state.publet="sxysrlj",
iconsxysr:arrow
})
break;
case "closewhy":
arrow=this.state.flexclosewhy?"arrowRight":"arrowDown";
this.setState({
flexclosewhy:!this.state.flexclosewhy,
publet:this.state.publet="closewhy",
iconclosewhy:arrow
})
break;
case "orderInfo":
arrow=this.state.flexOrderInfo?"arrowRight":"arrowDown";
this.setState({
flexOrderInfo:!this.state.flexOrderInfo,
publet:this.state.publet="orderInfo",
iconOrderInfo:arrow
})
break;
case "itemtric":
arrow=this.state.flexItemtric?"arrowRight":"arrowDown";
this.setState({
flexItemtric:!this.state.flexItemtric,
publet:this.state.publet="itemtric",
iconItemtric:arrow
})
break;
}
}
showTop(words,parameter,isif){
let self=this;
let arrow=false;
let style={marginTop:"20rem"};
if(isif==2){
style={borderTopWidth:"0rem"};
}
switch(words){
case "zcplj":
arrow=self.state.iconzcp=="arrowDown"?true:false;
break;
case "mjxxlj":
arrow=self.state.iconmjx=="arrowDown"?true:false;
break;
case "orderInfo":
arrow=self.state.iconOrderInfo=="arrowDown"?true:false;
break;
case "itemtric":
arrow=self.state.iconItemtric=="arrowDown"?true:false;
break;
case "sxysrlj":
arrow=self.state.iconsxysr=="arrowDown"?true:false;
break;
}
return(
<ListBlock expanded={arrow} onPress={this.moduleState.bind(this,words)} style={style} mainTitle={parameter} subTitle="" right_text='' ></ListBlock>
);
}
/*ActionSheet 显示关闭理由*/
pressSheet() {
ActionSheet.show({
options: ['未及时付款','买家不想买了','买家信息填写错误,重新拍','恶意买家/同行捣乱','缺货','买家拍错了','同城见面交易','取消'],
cancelButtonIndex: 7,
title:'关闭理由(买家可以看到)'
}, (notify)=>{
if(notify){
this.setState({
closewhyVal:notify.buttonIndex,
});
}
}, (show) => {
}, (fail) => {
});
}
/*填充数据到指定内容*/
render(){
let closewhyTxt=this.closewhyAry[this.state.closewhyVal];
return(
<View style={{backgroundColor:"#eff0f4",flex:1}}>
<View>{this.state.gotoVip}</View>
<ScrollView showsHorizontalScrollIndicator={false} style={{top:'0rem'}}>
<View style={[badStyles.BorderStyleLi,{borderBottomWidth:"0rem"}]}>
<Text style={[badStyles.textStyleLeft]}>差评师拦截</Text>
<View style={{marginRight:"20rem"}}>
<Switch disabled={this.state.disabledSW} onValueChange={this.onChecked.bind(this)} checked={this.state.denfenon}/>
</View>
</View>
<ListBlock rightTextStyle={{color:"#ffa033"}} onPress={this.goToNewPage.bind(this,'BadLogs')} mainTitle='已拦截日志' subTitle="" right_text={this.state.ceptTotal} ></ListBlock>
{this.showTop("zcplj","中差评买家拦截",1)}
{this.moudleRenderzcp()}
{this.showTop("mjxxlj","买家信息(信用分/注册天数)拦截",2)}
{this.moudleRendermjxx()}
{this.showTop("orderInfo","订单信息拦截",1)}
{this.moudleRenderOrderInfo()}
{this.showTop("itemtric","商品限购拦截",2)}
{this.moudleRenderItemtric()}
{this.showTop("sxysrlj","刷信用骚扰拦截",1)}
{this.moudleRendersxysr()}
<ListBlock style={{marginTop:"24rem"}} onPress={this.pressSheet.bind(this)} mainTitle='关闭理由(买家可以看到)' subTitle={closewhyTxt} right_text="" ></ListBlock>
<View style={[badStyles.BorderStyleLi,badStyles.topStyle]}>
<View style={{flexDirection:"row"}}>
<Checkbox checked={this.state.addbiew} onChange={()=>{this.setState({addbiew:!this.state.addbiew})}} size="small">
</Checkbox>
<View>
<Text style={{fontSize:"30rem"}}>将交易关闭原因添加到备注</Text>
<Text style={badStyles.promptInfo}>仅自己可以看到,买家看不到</Text>
</View>
</View>
</View>
<View style={[badStyles.topStyle,{paddingBottom:"0rem"}]}>
<Text style={badStyles.infoContent}>注:1、淘宝限制买家在提交订单10秒内,不允许关闭订单。拍下10秒内付款的订单不拦截</Text>
<Text style={[badStyles.infoContent,{paddingTop:"10rem"}]}>
2、收到好评率是卖家给买家的好评率【根据淘宝规则,服务商无法获取买家给卖家的好评率。请谨慎使用声称获取到该数据的软件】
</Text>
</View>
</ScrollView>
<View style={badStyles.lastView}>
<TouchableHighlight style={{backgroundColor:'#F57745', flex:1, height:'100rem'}} onPress={this.saveBadInt.bind(this)}>
<View style={{height:'100rem', justifyContent:'center', alignItems:'center', flexDirection: 'row'}}>
<Text style={{color:'#FFFFFF', fontSize:'30rem'}}>保存设置</Text>
</View>
</TouchableHighlight>
</View>
</View>
);
}
}
render(<BadIntercept/>);
<file_sep>/Component/OrderTabbar/CustomTabbar.jsx
/** @jsx createElement */
import {createElement, Component,cloneElement, findDOMNode,PropTypes} from 'rax';
import { View, Text ,TouchableHighlight} from 'nuke-components';
import {ActionSheet,Image,NativeDialog} from 'nuke';
import {DoBeacon} from '../../Biz/Common.jsx';
import Button from 'nuke-button';
import Icon from 'nuke-icon';
class CustomTabbar extends Component {
constructor(props) {
super(props);
this.state={
activeIndex:0,
isShow:false
}
}
renderBadget(badget,page,isTabActive){
if(page>3){
return;
}
const badgetColor=isTabActive? '#faaa72' : '#2C3036';
if(badget==0){
return;
}
return(
<View style={{height:'28rem'}}>
<Text style={{color:badgetColor,fontSize:'24rem',marginLeft:'8rem'}}>{badget}</Text>
</View>
)
}
renderTab(name, page, isTabActive, onPressHandler) {
/**
* 只绘制4个区域,最后一个区域是一个下拉列表
*/
let fontColor = isTabActive ? '#faaa72' : '#2C3036';
let borderStyle=isTabActive?{borderBottomColor:'#faaa72',borderBottomWidth:'2rem'}:{borderBottomColor:'#ccc',borderBottomWidth:'1px'};
let tabStyle = Object.assign({flex: 1 }, styles.tab, this.props.tabStyle);
let badget=0;
switch(name){
case '待付款':
badget=this.props.view.state.waitPayNum;
break;
case '待发货':
badget=this.props.view.state.waitSendNum;
break;
case '退款中':
badget=this.props.view.state.refundNum;
break;
case '待评价':
badget=this.props.view.state.waitEvaNum;
break;
case '已发货':
badget=this.props.view.state.SendToNum;
// fontColor = '#2C3036';
// borderStyle = {borderBottomColor:'#ccc',borderBottomWidth:'1px'}
break;
case '已成功':
badget=this.props.view.state.successNum;
// fontColor = '#2C3036';
// borderStyle = {borderBottomColor:'#ccc',borderBottomWidth:'1px'}
break;
case '已关闭':
badget=this.props.view.state.closeNum;
// fontColor = '#2C3036';
// borderStyle = {borderBottomColor:'#ccc',borderBottomWidth:'1px'}
break;
case '近3个月':
badget=this.props.view.state.waitPayNum;
// fontColor = '#2C3036';
// borderStyle = {borderBottomColor:'#ccc',borderBottomWidth:'1px'}
break;
}
if(borderStyle){
tabStyle= Object.assign({},tabStyle,borderStyle);
}
if(page<4){
//头4个直接绘制
return (<TouchableHighlight x={name}
key={name}
accessible={true}
accessibilityLabel={name}
style={[tabStyle,{flexDirection:'row',justifyContent:'center',alignItems:'center'}]} onPress={() => onPressHandler(page)}>
<View style={{flexDirection:'row',alignItems:'center'}}>
<Text style={[{color: fontColor,fontSize:'28rem'}]}>
{name}
</Text>
{this.renderBadget(badget,page,isTabActive)}
</View>
</TouchableHighlight>
);
}else{
//第5个要看情况
let tabText='更多';
// if(isTabActive){
// //说明当前没有选中任何一个状态,则显示更多
// tabText=name;
// }else{
badget=0;
// }
return(
<TouchableHighlight x={name}
key={name}
accessible={true}
accessibilityLabel={name}
style={[tabStyle,{flexDirection:'row'}]} onPress={() => onPressHandler(page)}>
<View style={{flexDirection:'row',alignItems:'flex-end'}}>
<Text style={[{color: fontColor,fontSize:'28rem'}]}>
{tabText}
</Text>
{this.renderBadget(badget,page,isTabActive)}
</View>
<Image source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/jt_x.png'}} width="28rem" height="28rem" style={{width:'28rem',height:'28rem',marginLeft:'16rem'}}/>
</TouchableHighlight>
)
}
}
getTabs(){
let arr=[];
//FIXME:默认是大于4个的
// console.log("activeTab: "+this.props.activeTab);
for (var i = 0; i < 4; i++) {
const isTabActive = this.props.activeTab === i;
arr.push(this.renderTab(this.props.tabs[i], i, isTabActive, this.changeTab.bind(this)));
}
//如果是前4个处于选中状态
if(this.props.activeTab<4){
arr.push(this.renderTab(this.props.tabs[4],4,false,this.loadMoreTab.bind(this)));
}else{
for(var i=4;i<this.props.tabs.length;i++){
const isTabActive = (this.props.activeTab) === i;
if(isTabActive){
arr.push(this.renderTab(this.props.tabs[i], 4, isTabActive, this.loadMoreTab.bind(this)));
break;
}else{
continue;
}
}
}
return arr;
}
changeTab(page){
// console.log('>>>>>>>>>>>>>>>>>>>> '+this.state);
console.log("this is page:",page);
if (this.state.isShow) {
// console.log(this.state.isShow);
this.setState({isShow:false})
}
this.setState(
{activeIndex:page}
)
this.props.goToPage(page);
// 埋点 0:待付款 1:待发货 2:待评价 3:退款中 4:已发货 5:已成功 6:已关闭 7:近三个月
switch(page){
case 0:DoBeacon('tab待付款','tab_pay',this.props.nick);break;
case 1:DoBeacon('tab待发货','tab_fahuo',this.props.nick);break;
case 2:DoBeacon('tab待评价','tab_pingjia',this.props.nick);break;
case 3:DoBeacon('tab退款中','tab_tuikuan',this.props.nick);break;
case 4:DoBeacon('tab已发货','tab_yifahuo',this.props.nick);break;
case 5:DoBeacon('tab已成功','tab_chenggong',this.props.nick);break;
case 6:DoBeacon('tab已关闭','tab_guanbi',this.props.nick);break;
case 7:DoBeacon('tab近三个月','tab_jinsangey',this.props.nick);break;
}
}
showDialog(src){
NativeDialog.show(src, {
width : '750rem',
height: '30000rem',
showMask:true,
cancelOnTouch:true,
data:{
id:123344444,
xx:'xxx'
}
}, (ret) => {
this.setState({'response':ret});
// console.log(ret);
}, (err) => {
this.setState({'response':err});
// console.log(err);
}, (info) => {
this.setState({'response':JSON.stringify(info)});
// console.log(JSON.stringify(info));
});
}
loadMoreTab(page){
console.log('现在到底是哪个page啊:'+page);
//这里弹出ActionSheet吧
let tabs=this.props.tabs.slice(4).map(
(tab,index)=>{
// console.log(tab+" "+index);
// if(tab=='待付款'){
// if(this.props.view.state.waitPayNum>0){
// return tab+"("+this.props.view.state.waitPayNum+")";
// }
// else return tab;
// }else
if(tab=="已发货"){
if(this.props.view.state.SendToNum>0){
return tab+"("+this.props.view.state.SendToNum+")";
}
else return tab;
}else if(tab=="已成功"){
if(this.props.view.state.successNum>0){
return tab+"("+this.props.view.state.successNum+")";
}
else return tab;
}else if(tab=="已关闭"){
if(this.props.view.state.closeNum>0){
return tab+"("+this.props.view.state.closeNum+")";
}
else return tab;
}else{
return tab;
}
}
);
// console.log('get tabs');
tabs.push('取消');//=[...this.props.tabs.slice(3),'取消'];
// console.log('add 取消');
let cancelIndex=tabs.length-1;
this.setState({isShow:!this.state.isShow});
// ActionSheet.show({
// options: tabs,
// cancelButtonIndex: cancelIndex,
// title:'更多订单'
// }, (notify)=>{
//
// if(notify.type=='button'){
// let next_page=4+Number(notify.buttonIndex);
// this.changeTab(next_page);
// }
// }, (show) => {
// }, (fail) => {
// });
// this.showDialog('qap://ShowBar.js');
}
render() {
const containerWidth = this.props.containerWidth;
const numberOfTabs = this.props.tabs.length;
const tabUnderlineStyle = {
position: 'absolute',
width: containerWidth / numberOfTabs,
height: '4rem',
backgroundColor: 'navy',
bottom: 0,
};
if (!this.state.isShow) {
return (
<View style={[styles.tabs, this.props.style ]}>
{this.getTabs()}
</View>
);
} else {
const badgetColor1=this.state.activeIndex == 4? '#faaa72' : '#ffffff';
const badgetColor2=this.state.activeIndex == 5? '#faaa72' : '#ffffff';
const badgetColor3=this.state.activeIndex == 6? '#faaa72' : '#ffffff';
const badgetColor4=this.state.activeIndex == 7? '#faaa72' : '#ffffff';
return (
<View style={[styles.tabs, this.props.style,{overflow:'visible'}]}>
{this.getTabs()}
<TouchableHighlight onPress={()=>{this.setState({isShow:false})}} style={{flex:1,backgroundColor:'rgba(0,0,0,0)',position:'fixed',width:'750rem',height:'2000rem',justifyContent:'flex-end',flexDirection:'row',top:'0rem',left:'0rem'}}>
<View style={{width:'180rem',height:'300rem',backgroundColor:'rgba(75,71,71,0.70)',marginTop:'80rem',marginRight:'20rem',alignItems:'flex-start'}}>
<TouchableHighlight onPress={()=>{this.changeTab(4);this.setState({isShow:false})}}><Text style={{marginLeft:'35rem',fontSize:'28rem',color:badgetColor1,marginTop:'35rem'}}>已发货</Text></TouchableHighlight>
<TouchableHighlight onPress={()=>{this.changeTab(5);this.setState({isShow:false})}}><Text style={{marginLeft:'35rem',fontSize:'28rem',color:badgetColor2,marginTop:'35rem'}}>已成功</Text></TouchableHighlight>
<TouchableHighlight onPress={()=>{this.changeTab(6);this.setState({isShow:false})}}><Text style={{marginLeft:'35rem',fontSize:'28rem',color:badgetColor3,marginTop:'35rem'}}>已关闭</Text></TouchableHighlight>
<TouchableHighlight onPress={()=>{this.changeTab(7);this.setState({isShow:false})}}><Text style={{marginLeft:'35rem',fontSize:'28rem',color:badgetColor4,marginTop:'35rem',marginBottom:'30rem'}}>近三个月</Text></TouchableHighlight>
</View>
</TouchableHighlight>
</View>
);
}
}
};
const styles = {
tab: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
// paddingBottom: '10rem',
},
active:{
paddingBottom: '6rem',
borderBottomColor: 'navy',
borderBottomWidth: '4rem',
borderBottomStyle: 'solid',
},
tabs: {
height: '80rem',
flexDirection: 'row',
justifyContent: 'space-around',
borderBottomWidth: '1px',
borderBottomStyle: 'solid',
borderBottomColor: '#ccc',
},
};
CustomTabbar.propTypes = {
goToPage: PropTypes.func,
activeTab: PropTypes.number,
tabs: PropTypes.array,
};
export default CustomTabbar;
<file_sep>/BadInterceptNegativePage.jsx
/*差评拦截
*@author drl
*/
import { Dialog,Modal,Button,Icon,View, Text,TouchableHighlight,Switch,ScrollView,TextInput,Util,Env} from 'nuke';
import {createElement, Component,render} from 'rax';
import QN from 'QAP-SDK';
import badStyles from './rxscss/BadIntercept.rxscss';
import {PUBLIC} from './rxscss/public-style.jsx';
import {Network} from './Component/Common/Network.jsx';
import {GoToView} from './Biz/View/GoToView.jsx';
import {QNInvoke} from 'Biz/Common.jsx';
import {UserVip} from './Biz/User/UserVip.jsx';
import ListBlock from 'Component/Common/ListBlock.jsx';
import {getAllUserInfos} from './Biz/User/GetAllUserInfos.jsx';
import {DoBeacon,getQueryString} from 'Biz/Common.jsx';
import NegativeLooseTab from './Component/Negative/NegativeLooseTab.jsx';
import NegativeLooseContentTab from './Component/Negative/NegativeLooseContentTab.jsx';
const Location = Util.Location;
const { appInfo } = Env;
class BadInterceptNegativePage extends Component {
/*初始化页面*/
constructor() {
super();
this.userNick = '';
this.vipFlag = 0;
this.subUserNick = '';
this.closeWaytit = ['未及时付款','买家不想买了','买家信息填写错误,重新拍','恶意买家/同行捣乱','缺货','买家拍错了','同城见面交易'];
this.interceptortit = ['宽松拦截模式','严格拦截模式','自定义拦截模式'];
this.modalchangMoreTit = '', //弹窗复用标题
this.modalchangMoreTits = ['当买家的收到好评率低于以下数字时拦截:',
'当订单金额(含运费)大于以下数字时拦截该订单:',
'当订单金额(含运费)小于以下数字时拦截该订单:',
'当一个订单的购买件数(含购物车)大于以下数字时拦截该订单:',
'当一个订单中同一个宝贝的购买件数大于以下数字时拦截该订单:',
'当订单的买家信用分数低于以下数字时拦截该订单:',
'当订单的注册天数低于以下数字时拦截该订单:',
], //弹窗复用标题
this.modalMorechangValue = '', //弹窗复用内容
this.modalMorechangValues = ['90','1000','1000','10','15','10','10'], //弹窗复用内容
this.modalMorechangAbout = '', //弹窗复用要求
this.modalMorechangAbouts = ['请输入0-100内有效好评率',
'请输入0-999999内有效金额',
'请输入0-999999内有效金额',
'请输入1-999999内有效件数',
'请输入1-999999内有效件数',
'请输入1-999999内有效分数',
'请输入1-999999内有效天数'
], //弹窗复用要求
this.index = '', //判断不同的弹出窗口
this.state = {
disabledSWhost:false, // 主开关
firstBut:false, //用户第一次进入判断
choose:0,
disabledSW:false,
denfenon:false, //主开关
loosepattern:0, // 模式
interceptStyle:'', //拦截模式
neutralon:false, //中评
neutralonNum:'',
badon:false, //差评
badonNum:'',
keywordStatus:false, //关键字
keywordStatusNum:'',
keyword:'',
keywordWindow:'', //关键字弹窗内容
closeword:0, //关闭理由
addbiewzhu:false, //关闭理由添加到备注
publicon:false, // 云黑名单拦截
handon:false, // 黑名单拦截
goodStatus:false, //好评率
goodTit:'',
windowText:'', //弹窗内容
bigmoneyStatus:false,
bigmoneyTit:'', // MAX订单金额
smallmoneyStatus:false,
smallmoneyTit:'', //MIN订单金额
maxcarnumStatus:false, // MAX订单购买件数
maxcarnumTit:'',
maxbabynumStatus:false, // MAX订单宝贝件数
maxbabynumTit:'',
creditStatus:false, //买家信用
creditTit:'',
regdaysStatus:false, //注册天数
regdaysTit:'',
cononStatus:false, //收件人拦截
areaonStatus:false, //区域拦截
wwonStatus:false, //旺旺白名单
babyonStatus:false, //宝贝白名单
whiteonStatus:false, //黑名单中依旧拦截
noalipayStatus:false, //支付宝
looseIndex:'', // 控制取消时的开关状态
checkeds:false,
}
}
componentWillMount(){
QN.showLoading({
query:{
text:'加载中 ~~'
}
})
this.userNick = getQueryString(Location.search,'userNick');
this.vipFlag = getQueryString(Location.search,'vipFlag');
this.subUserNick = getQueryString(Location.search, 'subUserNick');
if (this.subUserNick != '') {
this.state.disabledSWhost=true;
}
if (this.vipFlag ==0) {
this.state.gotoVip = this.getMoney();
}
this.getalldefen();
if (appInfo.platform == "iOS") { /*差评拦截页面埋点*/
if (this.vipFlag == 0) {
DoBeacon('TD20170114090141','chapinglanjieyemiosfree',this.userNick)
} else {
DoBeacon('TD20170114090141','chapinglanjieyemiosvip',this.userNick)
}
}else{
if (this.vipFlag == 0) {
DoBeacon('TD20170114090141','chapinglanjieyemanzfree',this.userNick)
} else {
DoBeacon('TD20170114090141','chapinglanjieyemanzvip',this.userNick)
}
}
QN.hideLoading();
}
// 升级到VIP
getMoney(){
if (this.vipFlag == '0') {
return(
<View style={{width:'750rem',height:'80rem',justifyContent:'center',backgroundColor:'#fff0e7',flexDirection:'row'}}>
<Icon style={{fontSize:'32rem',color:'#f95b1c',alignSelf:'center',textAlign:'center'}} name='warning' />
<Text style={{fontSize:'28rem',color:'#f95b1c',alignSelf:'center',textAlign:'center'}}> 亲,差评拦截是高级版功能,您需要</Text>
<TouchableHighlight style={{fontSize:'28rem',color:'#f95b1c',alignSelf:'center',textAlign:'center'}} onPress={this.GoToView.bind(this,'bad_banner')}>
<Text style={{fontSize:'28rem',color:'#0066FF ',alignSelf:'center',textAlign:'center',textDecoration:'underline'}}>升级</Text></TouchableHighlight>
<Text style={{fontSize:'28rem',color:'#f95b1c',alignSelf:'center',textAlign:'center'}}>才能使用</Text>
</View>
)
}
}
/*跳转Vip页面*/
GoToView(value){
let yyJson = [
{title:'拦截80%差评买家', advantage:'根据设置拦截疑似差评买家,80%差评买家都会被拦截'},
{title:'11种拦截条件,独家百万云黑名单',advantage:'11中拦截条件全方位拦截,爱用独家云黑名单不放过任何一个差评师'},
{title:'白名单不拦截',advantage:'不是差评师,设置白名单以后不拦截'}
]; /*运营文本json,格式的话···往上翻就能看到*/
let name = '差评拦截';/*来自哪一页,传入中文字符串*/
let feature = value;/*传入埋点值,不是项目编号哈!*/
let query = {xfrom:name, feature: feature} /*来自哪一页,传入中文字符串*/
QN.localstore.set({ /*将运营文本json存入localstorage*/
query: {
advertisment: yyJson
},
success(result) {
},
error(error) {
}
}).then(result => {
GoToView({status:'VipAd',query:query}); /*跳转页面*/
}, error => {
Modal.toast(error);
});
}
/**
* 子账号判断是否能进行操作
*/
twofun(){
if (this.vipFlag == 0) {
this.GoToView('bad_start');
return true;
}
if (this.subUserNick != '') {
Modal.toast("子账号不支持修改差评拦截!");
return true;
}
}
// 差评拦截所有开关状态
getalldefen(){
if (appInfo.platform == "iOS") {
DoBeacon('TD20170114090141','kaiqicpljzikgios',this.userNick);/*子开关埋点*/
}else {
DoBeacon('TD20170114090141','kaiqicpljzikganz',this.userNick);/*子开关埋点*/
}
let self=this;
Network.Post('/jy2/getdefenserate',{},(data)=>{
if (data.total ==1) { //开关设置过
let rse = data.res;
let denfenon = rse.denfenon == 'on' ? true : false; //差评拦截开关
let neutralon = rse.neutralon == 'on' ? true : false; //中评开关
let badon = rse.badon == 'on' ? true : false; //差评开关
let conditions = rse.conditions; //关键字
let keywordStatus = ''; //关键字开关
let keyword = ''; //关键字内容
if(RegExp('|Y|').test(conditions)){
let conditionss=conditions.split("|Y|")
keywordStatus = conditionss[0]== "on"?true:false; // 关键字开关
keyword = conditionss[1]; // 关键字
}
let closeword = '';
if(/^\d+$/.test(rse.sellernote)){
let seller=Number(rse.sellernote);
closeword=seller; // 关闭理由
}
let addbiewzhu = rse.addbiew == 'on' ? true : false; //关闭理由添加到备注开关
let publicon = rse.publicon == 'on' ? true : false; //云黑名单开关
let handon = rse.handon == 'on' ? true : false; //黑名单开关
let goodStatus = '';
let goodTit = '';
let goodrate = rse.goodrate; //好评率 开关 与 数据
if (RegExp(';').test(goodrate)) {
let goodrates = goodrate.split(';');
goodStatus = goodrates[0] == 'on' ? true : false;
goodTit = goodrates[1];
}
let bigmoneyStatus = '';
let bigmoneyTit = '';
let bigmoney = rse.bigmoney; //订单金额大于
if (RegExp(';').test(bigmoney)) {
let bigmoneys = bigmoney.split(';');
bigmoneyStatus = bigmoneys[0] == 'on' ? true : false ;
bigmoneyTit = bigmoneys[1];
}
let smallmoneyStatus = '';
let smallmoneyTit = '';
let smallmoney = rse.smallmoney; //订单金额小于
if (RegExp(';').test(smallmoney)) {
let smallmoneys = smallmoney.split(';');
smallmoneyStatus = smallmoneys[0] == 'on' ? true : false ;
smallmoneyTit = smallmoneys[1];
}
let maxcarnumStatus = '';
let maxcarnumTit = '';
let maxcarnum = rse.carnum; //订单购买件数 大于
if (RegExp(';').test(maxcarnum)) {
let maxcarnums = maxcarnum.split(';');
maxcarnumStatus = maxcarnums[0] == 'on' ? true : false;
maxcarnumTit = maxcarnums[1];
}
let maxbabynumStatus = '';
let maxbabynumTit = '';
let maxbabynum = rse.babynum; //订单宝贝 大于
if (RegExp(';').test(maxbabynum)) {
let maxbabynums = maxbabynum.split(';');
maxbabynumStatus = maxbabynums[0] == 'on' ? true : false;
maxbabynumTit = maxbabynums[1];
}
let creditStatus = '';
let creditTit = '';
let credit = rse.credit; //买家信用分
if (RegExp(';').test(credit)) {
let credits = credit.split(';');
creditStatus = credits[0] == 'on' ? true : false;
creditTit = credits[1];
}
let regdaysStatus = '';
let regdaysTit = '';
let regdays = rse.regdays; //注册天数
if (RegExp(';').test(regdays)) {
let regdays_s = regdays.split(';');
regdaysStatus = regdays_s[0] == 'on' ? true : false;
regdaysTit = regdays_s[1];
}
let noalipayStatus = rse.noalipay == 'on' ? true : false ; //支付宝
let cononStatus = rse.conon == 'on' ? true : false ; //收件人
let areaonStatus = rse.areaon == 'on' ? true : false; //区域拦截
let wwonStatus = rse.wwon == 'on' ? true : false; //旺旺白名单
let babyonStatus = rse.babyon == 'on' ? true : false; //宝贝白名单
let whiteonStatus = rse.whiteon == 'on' ? true : false; //区域拦截
// 判断拦截模式
let interceptStyle = '';
let choose = '';
if (!publicon && !handon && !goodStatus && !creditStatus && !regdaysStatus && !bigmoneyStatus && !noalipayStatus && !smallmoneyStatus && !maxcarnumStatus && !maxbabynumStatus && !cononStatus && !areaonStatus && !wwonStatus && !babyonStatus && !whiteonStatus) {
interceptStyle = '宽松拦截模式';
choose = 0;
}else if (neutralon && badon && goodStatus && creditStatus && regdaysStatus && keywordStatus && publicon && handon && bigmoneyStatus && noalipayStatus && smallmoneyStatus && maxcarnumStatus && maxbabynumStatus && cononStatus && areaonStatus && wwonStatus && babyonStatus && whiteonStatus) {
interceptStyle = '严格拦截模式';
choose = 1
} else {
interceptStyle = '自定义拦截模式';
choose = 2
}
this.setState({
choose:choose,
denfenon:denfenon,
neutralon:neutralon,
badon:badon,
keywordStatus:keywordStatus,
keyword:keyword == '' ? '联系Q Q,活刷,皇冠,不降权,不扣分,不封店,爆款,刷钻,刷粉刷店铺,宝贝收藏,天猫关注,开团提醒,u站喜欢,企业QQ,动态评分,微淘关注,教程' : keyword,
closeword:closeword,
interceptStyle:interceptStyle,
addbiewzhu:addbiewzhu,
publicon:publicon,
handon:handon,
goodStatus:goodStatus,
goodTit:goodTit == '' ? 90 : goodTit,
bigmoneyStatus:bigmoneyStatus,
bigmoneyTit:bigmoneyTit == '' ? 1000 : bigmoneyTit,
smallmoneyStatus:smallmoneyStatus,
smallmoneyTit:smallmoneyTit == '' ? 1000 : smallmoneyTit,
maxcarnumStatus:maxcarnumStatus,
maxcarnumTit:maxcarnumTit == '' ? 10 : maxcarnumTit,
maxbabynumStatus:maxbabynumStatus,
maxbabynumTit:maxbabynumTit == '' ? 15 : maxbabynumTit,
creditStatus:creditStatus,
creditTit:creditTit == '' ? 10 : creditTit,
regdaysStatus:regdaysStatus,
regdaysTit:regdaysTit == '' ? 10 : regdaysTit,
noalipayStatus:noalipayStatus,
cononStatus:cononStatus,
areaonStatus:areaonStatus,
wwonStatus:wwonStatus,
babyonStatus:babyonStatus,
whiteonStatus:whiteonStatus,
firstBut:false, //用户第一次进入
})
}else{
this.state.firstBut=true;
}
},{mode: 'jsonp'},(error_callback)=>{
Modal.toast(JSON.stringify(error_callback));
});
QN.hideLoading();
}
/*开启关闭差评拦截总开关*/
Changebut(value,e){
if (this.subUserNick != '') {
Modal.alert("子账号不支持修改差评拦截!",[{
onPress:()=>{},
text:'确定'
}]);
return;
}
if(this.vipFlag ==0){
this.setState({disabledSWhost:true})
this.GoToView();
return true;
}
if (appInfo.platform == "iOS") { /*iOS总开关埋点*/
{this.vipFlag == 1 ? DoBeacon('TD20170114090141','kaiqicpljzongkgclickiosvip',this.userNick) : null}
{this.vipFlag == 0 ? DoBeacon('TD20170114090141','kaiqicpljzongkgclickiosfree',this.userNick) : null}
}else { /*android总开关埋点*/
{this.vipFlag == 1 ? DoBeacon('TD20170114090141','kaiqicpljzongkgclickanzvip',this.userNick) : null}
{this.vipFlag == 0 ? DoBeacon('TD20170114090141','kaiqicpljzongkgclickanzfree',this.userNick) : null}
}
let self=this;
if(value){/*开启差评拦截*/
Network.Post("/jy2/defenserateoff",{types:'on'},(rsp)=>{
this.setState({denfenon:true})
Modal.toast("差评拦截开关开启成功!");
},{mode: 'jsonp'},(error_callback)=>{
Modal.toast(JSON.stringify(error_callback));
});
if (this.state.firstBut) { //第一次进入
this.ksState();
this.saveBadInt();
}
}else{/*关闭差评拦截*/
this.setState({denfenon:false})
Modal.confirm('您确定关闭差评拦截功能吗?关闭差评拦截功能后,将不再拦截订单',[
{
onPress:()=>{
this.setState({denfenon:true})
},
text:"取消"
},
{
onPress:()=>{
Network.Post("/jy2/defenserateoff",{types:'off'},(rsp)=>{
Modal.toast("关闭差评拦截开关成功!");
},{mode: 'jsonp'},(error_callback)=>{
Modal.alert("关闭差评拦截开关失败:"+JSON.stringify(error_callback),[{
onPress:()=>{},
text:'确定'
}]);
});
this.setState({
denfenon:false,
})
},
text:"确定",
}
]);
}
}
/*保存数据*/
saveBadInt(event){
let self = this;
/*开始保存数据*/
let info=new Object();
info.Tzhongpingoff = event == 'neutralon' ? !this.state.neutralon ? "on" : "off" : this.state.neutralon ? "on" : "off";/*给过我中评*/
info.Tchapingoff = event == 'badon' ? !this.state.badon ? "on" : "off" : this.state.badon ? "on" : "off" ;/*给过我差评*/
info.condikey = (event == 'keywordStatus' ? !this.state.keywordStatus ? "on|Y|" : "off|Y|" : this.state.keywordStatus ? "on|Y|" : "off|Y|" )+this.state.keyword; /*关键字*/
info.addbiew = this.state.addbiewzhu ? "on" : "off";/*关闭原因添加到关闭备注*/
info.Tclosetent = this.state.closeword; /*关闭理由*/
info.Tgoodvalues=(event == 'goodStatus' ? !this.state.goodStatus ? "on;" : "off;" : this.state.goodStatus ? "on;" : "off;") + this.state.goodTit; /*好评率*/
info.Tbigmoney=(event == 'bigmoneyStatus' ? !this.state.bigmoneyStatus ? "on;" : "off;" : this.state.bigmoneyStatus ? "on;" : "off;") + this.state.bigmoneyTit; /*MAX金额*/
info.Tsmallmoney=(event == 'smallmoneyStatus' ? !this.state.smallmoneyStatus ? "on;" : "off;" : this.state.smallmoneyStatus ? "on;" : "off;") + this.state.smallmoneyTit; /*MIN金额*/
info.car=(event == 'maxcarnumStatus' ? !this.state.maxcarnumStatus ? "on;" : "off;" : this.state.maxcarnumStatus ? "on;" : "off;") + this.state.maxcarnumTit; /*MAX购买件数*/
info.babysum=(event == 'maxbabynumStatus' ? !this.state.maxbabynumStatus ? "on;" : "off;" : this.state.maxbabynumStatus ? "on;" : "off;") + this.state.maxbabynumTit; /*MAX购买件数*/
info.crevalues=(event == 'creditStatus' ? !this.state.creditStatus ? "on;" : "off;" : this.state.creditStatus ? "on;" : "off;") + this.state.creditTit; /*信用分数*/
info.Tregdayvalues=(event == 'regdaysStatus' ? !this.state.regdaysStatus ? "on;" : "off;" : this.state.regdaysStatus ? "on;" : "off;") + this.state.regdaysTit; /*注册天数*/
info.Talipay=event == 'noalipayStatus' ? !this.state.noalipayStatus ? "on" : "off" : this.state.noalipayStatus ? "on" : "off"; /*支付宝*/
info.conon=event == 'cononStatus' ? !this.state.cononStatus ? "on" : "off" : this.state.cononStatus ? "on" : "off"; /*收件人*/
info.areaon=event == 'areaonStatus' ? !this.state.areaonStatus ? "on" : "off" : this.state.areaonStatus ? "on" : "off"; /*区域*/
info.wwon=event == 'wwonStatus' ? !this.state.wwonStatus ? "on" : "off" : this.state.wwonStatus ? "on" : "off"; /*旺旺白名单*/
info.babyon=event == 'babyonStatus' ? !this.state.babyonStatus ? "on" : "off" : this.state.babyonStatus ? "on" : "off"; /*宝贝白名单*/
info.whiteon=this.state.whiteonStatus ? "on" : "off"; /*黑名单依旧拦截*/
info.publicon= event == 'publicon' ? !this.state.publicon ? "on" : "off" : this.state.publicon ? "on" : "off"; /*云黑名单*/
info.handon=event == 'handon' ? !this.state.handon ? "on" : "off" : this.state.handon ? "on" : "off"; /*黑名单*/
Network.Post("/jy2/savedefenseratecbl",info,(rsp)=>{
if(!this.state.neutralon && !this.state.badon && !this.state.keywordStatus && this.state.choose == 0){
this.state.neutralon=true;
this.state.badon=true;
this.state.keywordStatus=true;
}
self.setState({
neutralon:event == 'neutralon' ? !this.state.neutralon : this.state.neutralon,
badon:event == 'badon' ? !this.state.badon : this.state.badon,
keywordStatus: event == 'keywordStatus' ? !this.state.keywordStatus : this.state.keywordStatus,
closeword:this.state.closeword,
interceptStyle:this.state.interceptStyle,
addbiewzhu:this.state.addbiewzhu,
goodStatus:event == 'goodStatus' ? !this.state.goodStatus : this.state.goodStatus,
goodTit:this.state.goodTit,
bigmoneyStatus:event == 'bigmoneyStatus' ? !this.state.bigmoneyStatus : this.state.bigmoneyStatus,
bigmoneyTit:this.state.bigmoneyTit,
smallmoneyStatus:event == 'smallmoneyStatus' ? !this.state.smallmoneyStatus : this.state.smallmoneyStatus,
smallmoneyTit:this.state.smallmoneyTit,
maxcarnumStatus:event == 'maxcarnumStatus' ? !this.state.maxcarnumStatus : this.state.maxcarnumStatus,
maxcarnumTit:this.state.maxcarnumTit,
maxbabynumStatus:event == 'maxbabynumStatus' ? !this.state.maxbabynumStatus : this.state.maxbabynumStatus,
maxbabynumTit:this.state.maxbabynumTit,
creditStatus:event == 'creditStatus' ? !this.state.creditStatus : this.state.creditStatus,
creditTit:this.state.creditTit,
regdaysStatus:event == 'regdaysStatus' ? !this.state.regdaysStatus : this.state.regdaysStatus,
regdaysTit:this.state.regdaysTit,
noalipayStatus:event == 'noalipayStatus' ? !this.state.noalipayStatus : this.state.noalipayStatus,
cononStatus:event == 'cononStatus' ? !this.state.cononStatus : this.state.cononStatus,
areaonStatus:event == 'areaonStatus' ? !this.state.areaonStatus : this.state.areaonStatus,
wwonStatus:event == 'wwonStatus' ? !this.state.wwonStatus : this.state.wwonStatus,
babyonStatus:event == 'babyonStatus' ? !this.state.babyonStatus : this.state.babyonStatus,
whiteonStatus:this.state.whiteonStatus,
handon:event == 'handon' ? !this.state.handon : this.state.handon,
publicon:event == 'publicon' ? !this.state.publicon : this.state.publicon,
});
},{mode: 'jsonp'},(error_callback)=>{
Modal.toast("差评拦截设置保存失败!");
});
}
// 拦截模式选择
ksState(){ //宽松
this.state.choose=0;
this.state.interceptStyle='宽松拦截模式';
this.state.neutralon=true; //中评
this.state.badon=true; //差评
this.state.keywordStatus=true; //关键字
this.state.goodStatus=false; // 好评率
this.state.goodTit=this.state.goodTit == "" ? this.modalMorechangValues[0] : this.state.goodTit;
this.state.bigmoneyStatus=false; // MAX订单金额
this.state.bigmoneyTit=this.state.bigmoneyTit == "" ? this.modalMorechangValues[1] : this.state.bigmoneyTit;
this.state.smallmoneyStatus=false; // MIN订单金额
this.state.smallmoneyTit=this.state.smallmoneyTit == "" ? this.modalMorechangValues[2] : this.state.smallmoneyTit;
this.state.maxcarnumStatus=false; //订单购买件数大于
this.state.maxcarnumTit=this.state.maxcarnumTit == "" ? this.modalMorechangValues[3] : this.state.maxcarnumTit;
this.state.maxbabynumStatus=false; //宝贝购买件数大于
this.state.maxbabynumTit=this.state.maxbabynumTit == "" ? this.modalMorechangValues[4] : this.state.maxbabynumTit;
this.state.creditStatus=false; //买家信用分
this.state.creditTit=this.state.creditTit == "" ? this.modalMorechangValues[5] : this.state.creditTit;
this.state.regdaysStatus=false; //注册天数
this.state.regdaysTit=this.state.regdaysTit == "" ? this.modalMorechangValues[6] : this.state.regdaysTit;
this.state.noalipayStatus=false; //支付宝
this.state.cononStatus=false; //收件人
this.state.areaonStatus=false; //区域
this.state.wwonStatus=false; //旺旺白名单
this.state.babyonStatus=false; //宝贝白名单
this.state.whiteonStatus=false; //黑名单依旧拦截
this.state.handon=false;
this.state.publicon=false;
}
ygState(){ //严格
this.handon = false;
this.state.choose=1;
this.state.interceptStyle='严格拦截模式';
this.state.neutralon=true; //中评
this.state.badon=true; //差评
this.state.keywordStatus=true; //关键字
this.state.goodStatus=true; // 好评率
this.state.goodTit=this.state.goodTit == "" ? this.modalMorechangValues[0] : this.state.goodTit;
this.state.bigmoneyStatus=true; // MAX订单金额
this.state.bigmoneyTit=this.state.bigmoneyTit == "" ? this.modalMorechangValues[1] : this.state.bigmoneyTit;
this.state.smallmoneyStatus=true; // MIN订单金额
this.state.smallmoneyTit=this.state.smallmoneyTit == "" ? this.modalMorechangValues[2] : this.state.smallmoneyTit;
this.state.maxcarnumStatus=true; //订单购买件数大于
this.state.maxcarnumTit=this.state.maxcarnumTit == "" ? this.modalMorechangValues[3] : this.state.maxcarnumTit;
this.state.maxbabynumStatus=true; //宝贝购买件数大于
this.state.maxbabynumTit=this.state.maxbabynumTit == "" ? this.modalMorechangValues[4] : this.state.maxbabynumTit;
this.state.creditStatus=true; //买家信用分
this.state.creditTit=this.state.creditTit == "" ? this.modalMorechangValues[5] : this.state.creditTit;
this.state.regdaysStatus=true; //注册天数
this.state.regdaysTit=this.state.regdaysTit == "" ? this.modalMorechangValues[6] : this.state.regdaysTit;
this.state.noalipayStatus=true; //支付宝
this.state.cononStatus=true; //收件人
this.state.areaonStatus=true; //区域
this.state.wwonStatus=true; //旺旺白名单
this.state.babyonStatus=true; //宝贝白名单
this.state.whiteonStatus=true; //黑名单依旧拦截
this.state.handon=true;
this.state.publicon=true;
}
zdyState(){ //自定义
this.state.choose=2;
this.state.interceptStyle='自定义拦截模式';
this.state.neutralon=false; //中评
this.state.badon=false; //差评
this.state.keywordStatus=false; //关键字
this.state.goodStatus=false; // 好评率
this.state.goodTit=this.state.goodTit == "" ? this.modalMorechangValues[0] : this.state.goodTit;
this.state.bigmoneyStatus=false; // MAX订单金额
this.state.bigmoneyTit=this.state.bigmoneyTit == "" ? this.modalMorechangValues[1] : this.state.bigmoneyTit;
this.state.smallmoneyStatus=false; // MIN订单金额
this.state.smallmoneyTit=this.state.smallmoneyTit == "" ? this.modalMorechangValues[2] : this.state.smallmoneyTit;
this.state.maxcarnumStatus=false; //订单购买件数大于
this.state.maxcarnumTit=this.state.maxcarnumTit == "" ? this.modalMorechangValues[3] : this.state.maxcarnumTit;
this.state.maxbabynumStatus=false; //宝贝购买件数大于
this.state.maxbabynumTit=this.state.maxbabynumTit == "" ? this.modalMorechangValues[4] : this.state.maxbabynumTit;
this.state.creditStatus=false; //买家信用分
this.state.creditTit=this.state.creditTit == "" ? this.modalMorechangValues[5] : this.state.creditTit;
this.state.regdaysStatus=false; //注册天数
this.state.regdaysTit=this.state.regdaysTit == "" ? this.modalMorechangValues[6] : this.state.regdaysTit;
this.state.noalipayStatus=false; //支付宝
this.state.cononStatus=false; //收件人
this.state.areaonStatus=false; //区域
this.state.wwonStatus=false; //旺旺白名单
this.state.babyonStatus=false; //宝贝白名单
this.state.whiteonStatus=false; //黑名单依旧拦截
this.state.handon=false;
this.state.publicon=false;
}
textbutter(index){ // 拦截模式选择
this.setState({loosepattern:index})
let tex='';
switch (index) {
case 0:
tex='宽松拦截模式';
this.ksState();
this.saveBadInt();
break;
case 1:
tex='严格拦截模式';
this.ygState();
this.saveBadInt();
break;
case 2:
tex='自定义拦截模式';
this.zdyState();
this.saveBadInt();
break;
default:
}
this.hideModal(); //隐藏弹窗
// 更新数据
this.setState({
interceptStyle:tex
})
}
// 拦截模式模块
interceptor(){
let interceptordata=[];
let interceptortit=this.interceptortit;
for (var i = 0; i < interceptortit.length; i++) {
interceptordata.push(
<TouchableHighlight onPress={this.textbutter.bind(this,i)} style={{marginRight:'24rem',width:'600rem',borderBottomWidth:'1rem',borderBottomStyle:'solid',borderBottomColor:'#e2e3e8'}}>
<Text style={{marginLeft:'24rem',textAlign:'center',fontSize:'28rem',borderWidth:'0rem',color:'#333333',marginTop:'24rem',marginBottom:'24rem'}}>{interceptortit[i]}</Text>
</TouchableHighlight>
)
}
return interceptordata;
}
// 选择关闭理由
closeWhydata(){
let Waydata = [];
let closeWaytit=this.closeWaytit;
for (var i = 0; i < closeWaytit.length; i++) {
Waydata.push(
<TouchableHighlight onPress={this.cloTextbutter.bind(this,i)} style={{marginRight:'24rem',width:'600rem',borderBottomWidth:'1rem',borderBottomStyle:'solid',borderBottomColor:'#e2e3e8'}}>
<Text style={{marginLeft:'24rem',textAlign:'center',fontSize:'28rem',borderWidth:'0rem',color:'#333333',marginTop:'24rem',marginBottom:'24rem'}}>{closeWaytit[i]}</Text>
</TouchableHighlight>
)
}
return Waydata;
}
// 宽松模式判断子开关是不是最后一个
toSaveint(event){
// 宽松模式
let looseDate = ['neutralon','badon','keywordStatus'];
for (var i = 0; i < looseDate.length; i++) {
if (event == looseDate[i]) {
this.state.looseIndex=i;
}
}
let denfenon = this.state.denfenon;
if (denfenon && this.state.neutralon && !this.state.badon && !this.state.keywordStatus && this.state.looseIndex == 0 && this.state.choose == '0' ||
denfenon && !this.state.neutralon && this.state.badon && !this.state.keywordStatus && this.state.looseIndex == 1 && this.state.choose == '0' ||
denfenon && !this.state.neutralon && !this.state.badon && this.state.keywordStatus && this.state.looseIndex == 2 && this.state.choose == '0' ) {
Modal.confirm('您确定关闭差评拦截功能吗?关闭差评拦截功能后,将不再拦截订单',[
{
onPress:()=>{
this.setState({
neutralon:this.state.looseIndex == 0 ? false : this.state.neutralon,
badon: this.state.looseIndex == 1 ? false : this.state.badon,
keywordStatus:this.state.looseIndex == 2 ? false : this.state.keywordStatus,
})
this.setState({
neutralon:this.state.looseIndex == 0 ? true : this.state.neutralon,
badon: this.state.looseIndex == 1 ? true : this.state.badon,
keywordStatus:this.state.looseIndex == 2 ? true : this.state.keywordStatus,
denfenon:true,
firstBut:false,
choose:0,
})
},
text:"取消"
},
{
onPress:()=>{
Network.Post("/jy2/defenserateoff",{types:'off'},(rsp)=>{
Modal.toast("关闭差评拦截开关成功!");
this.setState({
denfenon:false,
firstBut:true,
choose:0,
interceptStyle:'宽松拦截模式',
neutralon:true,
badon:true,
keywordStatus:true,
keyword:'联系Q Q,活刷,皇冠,不降权,不扣分,不封店,爆款,刷钻,刷粉刷店铺,宝贝收藏,天猫关注,开团提醒,u站喜欢,企业QQ,动态评分,微淘关注,教程',
})
this.saveBadInt();
// QN.hideLoading();
},{mode: 'jsonp'},(error_callback)=>{
Modal.toast("关闭差评拦截开关失败:"+JSON.stringify(error_callback));
});
},
text:"确定",
}
]);
}else {
this.saveBadInt(event)
}
// QN.hideLoading();
}
// 自定义模式判断子开关是不是最后一个
toSaveintCustom(event,value){
// 自定义模式
let looseDate = ['neutralon','badon','handon','keywordStatus','publicon','goodStatus','creditStatus','regdaysStatus','bigmoneyStatus','smallmoneyStatus','maxcarnumStatus','maxbabynumStatus','noalipayStatus','cononStatus','areaonStatus','wwonStatus','babyonStatus'];
for (var i = 0; i < looseDate.length; i++) {
if (event == looseDate[i]) {
this.state.looseIndex=i;
}
}
{event=='neutralon' ? this.state.neutralon=value : null}
{event=='badon' ? this.state.badon=value : null}
{event=='handon' ? this.state.handon=value : null}
{event=='keywordStatus' ? this.state.keywordStatus=value : null}
{event=='publicon' ? this.state.publicon=value : null}
{event=='goodStatus' ? this.state.goodStatus=value : null}
{event=='bigmoneyStatus' ? this.state.bigmoneyStatus=value : null}
{event=='smallmoneyStatus' ? this.state.smallmoneyStatus=value : null}
{event=='maxcarnumStatus' ? this.state.maxcarnumStatus=value : null}
{event=='maxbabynumStatus' ? this.state.maxbabynumStatus=value : null}
{event=='creditStatus' ? this.state.creditStatus=value : null}
{event=='regdaysStatus' ? this.state.regdaysStatus=value : null}
{event=='noalipayStatus' ? this.state.noalipayStatus=value : null}
{event=='cononStatus' ? this.state.cononStatus=value : null}
{event=='areaonStatus' ? this.state.areaonStatus=value : null}
{event=='wwonStatus' ? this.state.wwonStatus=value : null}
{event=='babyonStatus' ? this.state.babyonStatus=value : null}
if (this.state.denfenon && !this.state.neutralon && !this.state.badon && !this.state.handon && !this.state.keywordStatus && !this.state.bigmoneyStatus && !this.state.smallmoneyStatus
&& !this.state.maxcarnumStatus && !this.state.maxbabynumStatus && !this.state.noalipayStatus && !this.state.cononStatus && !this.state.areaonStatus && !this.state.wwonStatus && !this.state.babyonStatus
&& !this.state.publicon && !this.state.goodStatus && !this.state.creditStatus && !this.state.regdaysStatus) {
Modal.confirm('您确定关闭差评拦截功能吗?关闭差评拦截功能后,将不再拦截订单',[
{
onPress:()=>{
this.setState({
neutralon:this.state.looseIndex == 0 ? false : this.state.neutralon,
badon: this.state.looseIndex == 1 ? false : this.state.badon,
handon: this.state.looseIndex == 2 ? false : this.state.handon,
keywordStatus:this.state.looseIndex == 3 ? false : this.state.keywordStatus,
publicon:this.state.looseIndex == 4 ? false : this.state.publicon,
goodStatus:this.state.looseIndex == 5 ? false : this.state.goodStatus,
creditStatus:this.state.looseIndex == 6 ? false : this.state.creditStatus,
regdaysStatus:this.state.looseIndex == 7 ? false : this.state.regdaysStatus,
bigmoneyStatus:this.state.looseIndex == 8 ? false : this.state.bigmoneyStatus,
smallmoneyStatus:this.state.looseIndex == 9 ? false : this.state.smallmoneyStatus,
maxcarnumStatus:this.state.looseIndex == 10 ? false : this.state.maxcarnumStatus,
maxbabynumStatus:this.state.looseIndex == 11 ? false : this.state.maxbabynumStatus,
noalipayStatus:this.state.looseIndex == 12 ? false : this.state.noalipayStatus,
cononStatus:this.state.looseIndex == 13 ? false : this.state.cononStatus,
areaonStatus:this.state.looseIndex == 14 ? false : this.state.areaonStatus,
wwonStatus:this.state.looseIndex == 15 ? false : this.state.wwonStatus,
babyonStatus:this.state.looseIndex == 16 ? false : this.state.babyonStatus,
})
this.setState({
neutralon:this.state.looseIndex == 0 ? true : this.state.neutralon,
badon: this.state.looseIndex == 1 ? true : this.state.badon,
handon: this.state.looseIndex == 2 ? true : this.state.handon,
keywordStatus:this.state.looseIndex == 3 ? true : this.state.keywordStatus,
publicon:this.state.looseIndex == 4 ? true : this.state.publicon,
goodStatus:this.state.looseIndex == 5 ? true : this.state.goodStatus,
creditStatus:this.state.looseIndex == 6 ? true : this.state.creditStatus,
regdaysStatus:this.state.looseIndex == 7 ? true : this.state.regdaysStatus,
bigmoneyStatus:this.state.looseIndex == 8 ? true : this.state.bigmoneyStatus,
smallmoneyStatus:this.state.looseIndex == 9 ? true : this.state.smallmoneyStatus,
maxcarnumStatus:this.state.looseIndex == 10 ? true : this.state.maxcarnumStatus,
maxbabynumStatus:this.state.looseIndex == 11 ? true : this.state.maxbabynumStatus,
noalipayStatus:this.state.looseIndex == 12 ? true : this.state.noalipayStatus,
cononStatus:this.state.looseIndex == 13 ? true : this.state.cononStatus,
areaonStatus:this.state.looseIndex == 14 ? true : this.state.areaonStatus,
wwonStatus:this.state.looseIndex == 15 ? true : this.state.wwonStatus,
babyonStatus:this.state.looseIndex == 16 ? true : this.state.babyonStatus,
denfenon:true,
firstBut:false,
})
},
text:"取消"
},
{
onPress:()=>{
Network.Post("/jy2/defenserateoff",{types:'off'},(rsp)=>{
Modal.toast("关闭差评拦截开关成功!");
this.setState({
denfenon:false,
})
this.saveBadInt();
},{mode: 'jsonp'},(error_callback)=>{
Modal.alert("关闭差评拦截开关失败:"+JSON.stringify(error_callback),[{
onPress:()=>{},
text:'确定'
}]);
});
},
text:"确定",
}
]);
}else {
this.saveBadInt()
}
// QN.hideLoading();
}
// 跳到拦截记录
goToNewPage(){
if (this.state.denfenon) {
GoToView({
title:"拦截记录",
status:'Badrecord',
query:{
userNick:encodeURI(this.userNick),
vipFlag:this.vipFlag,
subUserNick:encodeURI(this.subUserNick)
}
});
}
}
// 普通按钮Tab回调函数
onChildChanged(newState,butTit) {
let self = this;
let buttit = butTit;
if (self.NegativeLooseTab.state.choose == '0') {
if (buttit == 'keywordStatus' && newState) {
self.NegativeLooseTab.refs.modalchang.show()
}
self.NegativeLooseTab.toSaveint(butTit);
}else if (self.NegativeLooseTab.state.choose == '1' || self.NegativeLooseTab.state.choose == '2') {
if (buttit == 'keywordStatus' && newState) {
self.NegativeLooseTab.refs.modalchang.show()
}
self.NegativeLooseTab.toSaveintCustom(butTit,newState)
}
}
// 含有输入内容的Tab
onChildChangedContent(butNum,value){ //点击开关
this.changeStyleMoreBut(butNum,value);
}
callbackParentContent(contNum){ //点击内容
this.changeStyleMore(contNum);
}
/*不同的模式
*/
patterndata(){
let patterndata=[];
let changColor = this.state.denfenon ? {color:'#333333'} : {color:'#cccccc'};
let changColorZhu = this.state.denfenon ? {color:'#F23C3C'} : {color:'#cccccc'};
let changColorTit = this.state.denfenon ? {color:'#999999'} : {color:'#cccccc'};
let changColorBord = this.state.denfenon ? {borderColor:'#333333'} : {borderColor:'#cccccc'};
let changBut = this.state.denfenon ? this.state.disabledSW : true;
if (this.state.choose == '0') { //宽松模式
patterndata.push(
<View style={{marginTop:'20rem'}}>
<NegativeLooseTab text={'给过我中评的买家'} butTit={'neutralon'} onValueChange={this.state.neutralon} callbackParent={this.onChildChanged} NegativeLooseTab={this} changBut={this.state.denfenon ? this.state.disabledSW : true} changColor={this.state.denfenon ? {color:'#333333'} : {color:'#cccccc'}}></NegativeLooseTab>
<NegativeLooseTab text={'给过我差评的买家'} butTit={'badon'} onValueChange={this.state.badon} callbackParent={this.onChildChanged} NegativeLooseTab={this} changBut={this.state.denfenon ? this.state.disabledSW : true} changColor={this.state.denfenon ? {color:'#333333'} : {color:'#cccccc'}}></NegativeLooseTab>
<NegativeLooseTab text={'地址或留言包含以下关键字:'} butTit={'keywordStatus'} onValueChange={this.state.keywordStatus} callbackParent={this.onChildChanged} NegativeLooseTab={this} changBut={this.state.denfenon ? this.state.disabledSW : true} changColor={this.state.denfenon ? {color:'#333333'} : {color:'#cccccc'}}></NegativeLooseTab>
<View style={{flexDirection:'column',backgroundColor:'#FFFFFF',borderBottomWidth:'1rem',borderStyle:'solid',borderColor:'#e2e3e8',marginTop:'-1rem'}}>
<TouchableHighlight onPress={this.state.denfenon ? this.keywordButton.bind(this) : null }
style={{marginLeft:'20rem',textAlign:'left',borderWidth:'0rem',width:'702rem',color:'#999999',height:'150rem',marginRight:'24rem'}}>
<Text style={[{fontSize:'28rem'},changColorTit]}>{this.state.keyword}</Text>
</TouchableHighlight>
</View>
</View>
)
}else
if (this.state.choose == '1' || this.state.choose == '2' ) { //严格模式//自定义模式
patterndata.push(
<View style={{marginTop:'0rem'}}>
<Text style={[{fontSize:'28rem',marginLeft:'24rem',marginTop:'20rem',marginBottom:'20rem'},changColorTit]}>中差评拦截:</Text>
<NegativeLooseTab text={'给过我中评的买家'} butTit={'neutralon'} onValueChange={this.state.neutralon} callbackParent={this.onChildChanged} NegativeLooseTab={this} changBut={this.state.denfenon ? this.state.disabledSW : true} changColor={this.state.denfenon ? {color:'#333333'} : {color:'#cccccc'}}></NegativeLooseTab>
<NegativeLooseTab text={'给过我差评的买家'} butTit={'badon'} onValueChange={this.state.badon} callbackParent={this.onChildChanged} NegativeLooseTab={this} changBut={this.state.denfenon ? this.state.disabledSW : true} changColor={this.state.denfenon ? {color:'#333333'} : {color:'#cccccc'}}></NegativeLooseTab>
<NegativeLooseTab text={'云黑名单拦截'} butTit={'publicon'} onValueChange={this.state.publicon} callbackParent={this.onChildChanged} NegativeLooseTab={this} changBut={this.state.denfenon ? this.state.disabledSW : true} changColor={this.state.denfenon ? {color:'#333333'} : {color:'#cccccc'}}></NegativeLooseTab>
<NegativeLooseContentTab text={'买家收到好评率低于'} textCont={'%的买家'} butTit={'goodStatus'} onValueChange={this.state.goodStatus}
callbackParent={this.onChildChangedContent.bind(this)} callbackParentContent={this.callbackParentContent.bind(this)} maxcarnumTit={this.state.goodTit}
NegativeLooseContentTab={this} changBut={this.state.denfenon ? this.state.disabledSW : true} changColor={this.state.denfenon ? {color:'#333333'} : {color:'#cccccc'}} changColorBord={this.state.denfenon ? {borderColor:'#333333'} : {borderColor:'#cccccc'}} NegativeLooseContentTab={this}>
</NegativeLooseContentTab>
<View style={{flexDirection:'column',backgroundColor:'#FFFFFF',backgroundColor:'#ffffff',borderBottomWidth:"1rem",borderBottomStyle:"solid",borderBottomColor:"#e2e3e8",marginTop:'-1rem'}}>
<Text style={[{fontSize:'26rem',marginTop:'10rem',marginBottom:'20rem',marginLeft:'24rem',marginRight:'24rem'},changColorZhu]}>该好评率是卖家给买家发出的好评率</Text>
</View>
<NegativeLooseTab text={'黑名单拦截'} butTit={'handon'} onValueChange={this.state.handon} callbackParent={this.onChildChanged} NegativeLooseTab={this} changBut={this.state.denfenon ? this.state.disabledSW : true} changColor={this.state.denfenon ? {color:'#333333'} : {color:'#cccccc'}}></NegativeLooseTab>
<TouchableHighlight onPress={()=>{
if (this.state.denfenon) {
if (this.vipFlag == 0) {
this.GoToView.bind(this,'bad_start');
return true;
}
if (!this.state.handon) {
Modal.alert("请先开启黑名单拦截,再添加旺旺黑名单拦截!",[{
onPress:()=>{},
text:'确定'
}]);
return ;
}
GoToView({title:"旺旺黑名单",status:'BadInterceptBlackLists',query:{userNick:encodeURI(this.userNick), vipFlag:this.vipFlag, subUserNick:encodeURI(this.subUserNick)}});
}
}} style={[badintStyles.Touchbutt,{marginTop:'0rem'}]}>
<Text style={[{fontSize:'28rem'},changColor]}>旺旺黑名单</Text>
<Icon style={[{marginRight:'10rem',fontSize:'30rem'},changColorTit]} name="arrowRight"></Icon>
</TouchableHighlight>
<Text style={[{fontSize:'28rem',marginLeft:'24rem',marginTop:'20rem',marginBottom:'20rem'},changColorTit]}>订单信息拦截:</Text>
<NegativeLooseContentTab text={'订单金额大于(含运费):'} textCont={'元'} butTit={'bigmoneyStatus'} onValueChange={this.state.bigmoneyStatus}
callbackParent={this.onChildChangedContent.bind(this)} callbackParentContent={this.callbackParentContent.bind(this)} maxcarnumTit={this.state.bigmoneyTit}
NegativeLooseContentTab={this} changBut={this.state.denfenon ? this.state.disabledSW : true} changColor={this.state.denfenon ? {color:'#333333'} : {color:'#cccccc'}} changColorBord={this.state.denfenon ? {borderColor:'#333333'} : {borderColor:'#cccccc'}} NegativeLooseContentTab={this}>
</NegativeLooseContentTab>
<NegativeLooseContentTab text={'订单金额小于(含运费):'} textCont={'元'} butTit={'smallmoneyStatus'} onValueChange={this.state.smallmoneyStatus}
callbackParent={this.onChildChangedContent.bind(this)} callbackParentContent={this.callbackParentContent.bind(this)} maxcarnumTit={this.state.smallmoneyTit}
NegativeLooseContentTab={this} changBut={this.state.denfenon ? this.state.disabledSW : true} changColor={this.state.denfenon ? {color:'#333333'} : {color:'#cccccc'}} changColorBord={this.state.denfenon ? {borderColor:'#333333'} : {borderColor:'#cccccc'}} NegativeLooseContentTab={this}>
</NegativeLooseContentTab>
<NegativeLooseContentTab text={'一个订单购买件数(含购物车)大于'} textCont={'件'} butTit={'maxcarnumStatus'} onValueChange={this.state.maxcarnumStatus}
callbackParent={this.onChildChangedContent.bind(this)} callbackParentContent={this.callbackParentContent.bind(this)} maxcarnumTit={this.state.maxcarnumTit}
NegativeLooseContentTab={this} changBut={this.state.denfenon ? this.state.disabledSW : true} changColor={this.state.denfenon ? {color:'#333333'} : {color:'#cccccc'}} changColorBord={this.state.denfenon ? {borderColor:'#333333'} : {borderColor:'#cccccc'}} NegativeLooseContentTab={this}>
</NegativeLooseContentTab>
<NegativeLooseContentTab text={'一个订单中同一个宝贝购买数大于'} textCont={'件'} butTit={'maxbabynumStatus'} onValueChange={this.state.maxbabynumStatus}
callbackParent={this.onChildChangedContent.bind(this)} callbackParentContent={this.callbackParentContent.bind(this)} maxcarnumTit={this.state.maxbabynumTit}
NegativeLooseContentTab={this} changBut={this.state.denfenon ? this.state.disabledSW : true} changColor={this.state.denfenon ? {color:'#333333'} : {color:'#cccccc'}} changColorBord={this.state.denfenon ? {borderColor:'#333333'} : {borderColor:'#cccccc'}} NegativeLooseContentTab={this}>
</NegativeLooseContentTab>
<Text style={[{fontSize:'28rem',marginLeft:'24rem',marginTop:'20rem',marginBottom:'20rem'},changColorTit]}>买家信息拦截:</Text>
<NegativeLooseContentTab text={'买家信用分数低于'} textCont={'分的买家'} butTit={'creditStatus'} onValueChange={this.state.creditStatus}
callbackParent={this.onChildChangedContent.bind(this)} callbackParentContent={this.callbackParentContent.bind(this)} maxcarnumTit={this.state.creditTit}
NegativeLooseContentTab={this} changBut={this.state.denfenon ? this.state.disabledSW : true} changColor={this.state.denfenon ? {color:'#333333'} : {color:'#cccccc'}} changColorBord={this.state.denfenon ? {borderColor:'#333333'} : {borderColor:'#cccccc'}} NegativeLooseContentTab={this}>
</NegativeLooseContentTab>
<NegativeLooseContentTab text={'注册天数低于'} textCont={'天的买家'} butTit={'regdaysStatus'} onValueChange={this.state.regdaysStatus}
callbackParent={this.onChildChangedContent.bind(this)} callbackParentContent={this.callbackParentContent.bind(this)} maxcarnumTit={this.state.regdaysTit}
NegativeLooseContentTab={this} changBut={this.state.denfenon ? this.state.disabledSW : true} changColor={this.state.denfenon ? {color:'#333333'} : {color:'#cccccc'}} changColorBord={this.state.denfenon ? {borderColor:'#333333'} : {borderColor:'#cccccc'}} NegativeLooseContentTab={this}>
</NegativeLooseContentTab>
<NegativeLooseTab text={'没有绑定支付宝账户的买家'} butTit={'noalipayStatus'} onValueChange={this.state.noalipayStatus} callbackParent={this.onChildChanged} NegativeLooseTab={this} changBut={this.state.denfenon ? this.state.disabledSW : true} changColor={this.state.denfenon ? {color:'#333333'} : {color:'#cccccc'}}></NegativeLooseTab>
<NegativeLooseTab text={'地址或留言包含以下关键字:'} butTit={'keywordStatus'} onValueChange={this.state.keywordStatus} callbackParent={this.onChildChanged} NegativeLooseTab={this} changBut={this.state.denfenon ? this.state.disabledSW : true} changColor={this.state.denfenon ? {color:'#333333'} : {color:'#cccccc'}}></NegativeLooseTab>
<View style={{flexDirection:'column',backgroundColor:'#FFFFFF',borderBottomWidth:'1rem',borderStyle:'solid',borderColor:'#e2e3e8',marginTop:'-1rem'}}>
<TouchableHighlight onPress={this.state.denfenon ? this.keywordButton.bind(this) : null }
style={{marginLeft:'20rem',textAlign:'left',borderWidth:'0rem',width:'702rem',color:'#999999',height:'150rem',marginRight:'24rem'}}>
<Text style={[{fontSize:'28rem'},changColorTit]}>{this.state.keyword}</Text>
</TouchableHighlight>
</View>
<NegativeLooseTab text={'收件人拦截'} butTit={'cononStatus'} onValueChange={this.state.cononStatus} callbackParent={this.onChildChanged} NegativeLooseTab={this} changBut={this.state.denfenon ? this.state.disabledSW : true} changColor={this.state.denfenon ? {color:'#333333'} : {color:'#cccccc'}}></NegativeLooseTab>
<TouchableHighlight onPress={()=>{
if (this.state.denfenon) {
if (this.vipFlag == 0) {
this.GoToView.bind(this,'bad_start');
return true;
}
if (!this.state.cononStatus) {
Modal.alert("请先开启收件人拦截,再添加收件人拦截!",[{
onPress:()=>{},
text:'确定'
}]);
return ;
}
GoToView({title:"收件人拦截",status:'BadInterceptRecipeList',query:{userNick:encodeURI(this.userNick), vipFlag:this.vipFlag, subUserNick:encodeURI(this.subUserNick)}});
}
}} style={[badintStyles.Touchbutt,{marginTop:'0rem'}]}>
<Text style={[{fontSize:'28rem'},changColor]}>添加收件人拦截</Text>
<Icon style={[{marginRight:'10rem',fontSize:'30rem'},changColorTit]} name="arrowRight"></Icon>
</TouchableHighlight>
<NegativeLooseTab text={'区域拦截'} butTit={'areaonStatus'} onValueChange={this.state.areaonStatus} callbackParent={this.onChildChanged} NegativeLooseTab={this} changBut={this.state.denfenon ? this.state.disabledSW : true} changColor={this.state.denfenon ? {color:'#333333'} : {color:'#cccccc'}}></NegativeLooseTab>
<TouchableHighlight onPress={()=>{
if (this.state.denfenon) {
if (this.vipFlag == 0) {
this.GoToView.bind(this,'bad_start');
return true;
}
if (!this.state.areaonStatus) {
Modal.alert("请先开启区域拦截,再添加区域拦截!",[{
onPress:()=>{},
text:'确定'
}]);
return ;
}
GoToView({title:"区域拦截",status:'BadInterceptAreaList',query:{userNick:encodeURI(this.userNick), vipFlag:this.vipFlag, subUserNick:encodeURI(this.subUserNick)}});
}
}} style={[badintStyles.Touchbutt,{marginTop:'0rem'}]}>
<Text style={[{fontSize:'28rem'},changColor]}>添加区域拦截</Text>
<Icon style={[{marginRight:'10rem',fontSize:'30rem'},changColorTit]} name="arrowRight"></Icon>
</TouchableHighlight>
<Text style={[{fontSize:'28rem',marginLeft:'24rem',marginTop:'20rem',marginBottom:'20rem'},changColorTit]}>放行旺旺和宝贝:</Text>
<NegativeLooseTab text={'旺旺白名单'} butTit={'wwonStatus'} onValueChange={this.state.wwonStatus} callbackParent={this.onChildChanged} NegativeLooseTab={this} changBut={this.state.denfenon ? this.state.disabledSW : true} changColor={this.state.denfenon ? {color:'#333333'} : {color:'#cccccc'}}></NegativeLooseTab>
<TouchableHighlight onPress={()=>{
if (this.state.denfenon) {
if (!this.state.wwonStatus) {
Modal.alert("请先开启旺旺白名单,再添加旺旺白名单!",[{
onPress:()=>{},
text:'确定'
}]);
return ;
}
GoToView({title:"旺旺白名单",status:'BadInterceptWhiteLists',query:{userNick:encodeURI(this.userNick), vipFlag:this.vipFlag, subUserNick:encodeURI(this.subUserNick)}});
}
}} style={[badintStyles.Touchbutt,{marginTop:'0rem'}]}>
<Text style={[{fontSize:'28rem'},changColor]}>添加旺旺白名单</Text>
<Icon style={[{marginRight:'10rem',fontSize:'30rem'},changColorTit]} name="arrowRight"></Icon>
</TouchableHighlight>
<NegativeLooseTab text={'宝贝白名单'} butTit={'babyonStatus'} onValueChange={this.state.babyonStatus} callbackParent={this.onChildChanged} NegativeLooseTab={this} changBut={this.state.denfenon ? this.state.disabledSW : true} changColor={this.state.denfenon ? {color:'#333333'} : {color:'#cccccc'}}></NegativeLooseTab>
{
this.state.babyonStatus ?
<View style={{flexDirection:'row',justifyContent:'space-between',alignItems:'center',backgroundColor:'#FFFFFF',backgroundColor:'#ffffff',borderBottomWidth:"1rem",borderBottomStyle:"solid",borderBottomColor:"#e2e3e8"}}>
<Text style={[{fontSize:'28rem',marginLeft:'24rem',marginTop:'20rem',marginBottom:'20rem'},changColor]}>黑名单中买家依旧拦截</Text>
<Switch key={`whiteonStatus`}
ref='state'
style={{marginRight:'24rem'}}
disabled={changBut}
onValueChange={
(value,event)=>{this.setState({whiteonStatus:value})
this.saveBadInt();
}}
checked={this.state.whiteonStatus}
/>
</View> : <View></View>
}
<TouchableHighlight onPress={()=>{
if (this.state.denfenon) {
if (this.vipFlag == 0) {
this.GoToView.bind(this,'bad_start');
return true;
}
if (!this.state.babyonStatus){
Modal.alert("请先开启宝贝白名单拦截,再添加宝贝白名单!",[{
onPress:()=>{},
text:'确定'
}]);
return;
}
GoToView({title:"宝贝白名单",status:'BadInterceptBabyLists',query:{userNick:encodeURI(this.userNick), vipFlag:this.vipFlag, subUserNick:encodeURI(this.subUserNick)}});
}
}} style={[badintStyles.Touchbutt,{marginTop:'0rem'}]}>
<Text style={[{fontSize:'28rem'},changColor]}>添加宝贝白名单</Text>
<Icon style={[{marginRight:'10rem',fontSize:'30rem'},changColorTit]} name="arrowRight"></Icon>
</TouchableHighlight>
</View>
)
QN.hideLoading();
}
return patterndata;
}
// 用户第一次进入底部显示内容
firstList(){
let firstList = [];
if (this.state.firstBut) {
firstList.push(
<View>
<TouchableHighlight style={badintStyles.Touchbutt}>
<Text style={{fontSize:'28rem',color:'#999999'}}>快速设置拦截方式:</Text>
<Text style={{fontSize:'28rem',color:'#999999'}}>宽松拦截模式</Text>
<Icon style={{marginRight:'10rem',color:'#999999',fontSize:'30rem'}} name="arrowRight"></Icon>
</TouchableHighlight>
<View style={{marginTop:'20rem'}}>
<View style={{flexDirection:'row',justifyContent:'space-between',alignItems:'center',backgroundColor:'#FFFFFF',backgroundColor:'#ffffff',borderBottomWidth:"1rem",borderBottomStyle:"solid",borderBottomColor:"#e2e3e8"}}>
<Text style={{fontSize:'28rem',color:'#999999',marginLeft:'24rem',marginTop:'20rem',marginBottom:'20rem'}}>给过我中评的买家</Text>
<Switch key={`denfenon`} style={{marginRight:'24rem'}} disabled={true}/>
</View>
<View style={{flexDirection:'row',justifyContent:'space-between',alignItems:'center',backgroundColor:'#FFFFFF',backgroundColor:'#ffffff',borderBottomWidth:"1rem",borderBottomStyle:"solid",borderBottomColor:"#e2e3e8"}}>
<Text style={{fontSize:'28rem',color:'#999999',marginLeft:'24rem',marginTop:'20rem',marginBottom:'20rem'}}>给过我差评的买家</Text>
<Switch key={`denfenon`} style={{marginRight:'24rem'}} disabled={true}/>
</View>
<View style={{flexDirection:'column',backgroundColor:'#FFFFFF',borderBottomWidth:'1rem',borderStyle:'solid',borderColor:'#e2e3e8'}}>
<View style={{flexDirection:'row',alignItems:'center',justifyContent:'center',flex:1}}>
<View style={{flexDirection:'row',alignItems:'center',justifyContent:'flex-start',flex:1}}>
<Text style={{marginLeft:'24rem',fontSize:'28rem',color:'#999999',marginTop:'20rem',marginBottom:'20rem',marginRight:'5rem'}}>地址或留言包含以下关键字:</Text>
</View>
<Switch key={`denfenon`} style={{marginRight:'24rem'}} disabled={true}/>
</View>
<TouchableHighlight style={{marginLeft:'20rem',textAlign:'left',borderWidth:'0rem',width:'702rem',height:'150rem',marginRight:'24rem'}}>
<Text style={{fontSize:'28rem',color:'#999999'}}>联系Q Q,活刷,皇冠,不降权,不扣分,不封店,爆款,刷钻,刷粉刷店铺,宝贝收藏,天猫关注,开团提醒,u站喜欢,企业QQ,动态评分,微淘关注,教程</Text>
</TouchableHighlight>
</View>
</View>
<View>
<Text style={{fontSize:'28rem',color:'#999999',marginLeft:'24rem',marginTop:'20rem',marginBottom:'20rem'}}>设置交易关闭理由</Text>
<TouchableHighlight style={[badintStyles.Touchbutt,{marginTop:'0rem'}]}>
<Text style={{fontSize:'28rem',color:'#999999'}}>关闭理由</Text>
<Text style={{fontSize:'28rem',color:'#999999'}}>缺货</Text>
<Icon style={{marginRight:'10rem',color:'#999999',fontSize:'30rem'}} name="arrowRight"></Icon>
</TouchableHighlight>
<Text style={{fontSize:'26rem',color:'#999999',marginTop:'20rem',marginBottom:'0rem',marginLeft:'24rem',marginRight:'24rem'}}>注:由于淘宝限制买家在提交订单10秒内付款完成,系统无法进行拦截;</Text>
</View>
<View>
<Text style={{fontSize:'28rem',color:'#999999',marginLeft:'24rem',marginTop:'20rem',marginBottom:'0rem'}}>交易关闭理由添加到订单备注</Text>
<View style={{flexDirection:'row',justifyContent:'space-between',alignItems:'center',backgroundColor:'#FFFFFF',marginTop:'20rem'}}>
<Text style={{fontSize:'28rem',color:'#999999',marginLeft:'24rem',marginTop:'20rem',marginBottom:'20rem'}}>将真实关闭理由添加到订单备注(对买家隐藏)</Text>
<Switch key={`denfenon`} style={{marginRight:'24rem'}} disabled={true}/>
</View>
</View>
<View>
<Text style={{fontSize:'28rem',color:'#999999',marginLeft:'24rem',marginTop:'20rem',marginBottom:'20rem'}}>拦截记录</Text>
<TouchableHighlight style={[badintStyles.Touchbutt,{marginTop:'0rem'}]}>
<Text style={{fontSize:'28rem',color:'#999999'}}>拦截记录</Text>
<Icon style={{marginRight:'10rem',color:'#999999',fontSize:'30rem'}} name="arrowRight"></Icon>
</TouchableHighlight>
</View>
</View>
)
}else{
<View></View>
}
return firstList;
}
/*复用弹出窗口*/
// 点击内容弹出弹框
changeStyleMore(index){
this.index=index;
if (index == 0 && this.state.goodStatus) {
this.setState({
modalchangMoreTit:this.modalchangMoreTit=this.modalchangMoreTits[0],
modalMorechangValue:this.modalMorechangValue=this.state.goodTit == "" ? this.modalMorechangValues[0] : this.state.goodTit,
modalMorechangAbout:this.modalMorechangAbout=this.modalMorechangAbouts[0],
})
this.state.windowText=this.modalMorechangValue;
this.refs.modalchangMore.show();
}
if (index == 1 && this.state.bigmoneyStatus) {
this.setState({
modalchangMoreTit:this.modalchangMoreTit=this.modalchangMoreTits[1],
modalMorechangValue:this.modalMorechangValue=this.state.bigmoneyTit == "" ? this.modalMorechangValues[1] : this.state.bigmoneyTit,
modalMorechangAbout:this.modalMorechangAbout=this.modalMorechangAbouts[1],
})
this.state.windowText=this.modalMorechangValue;
this.refs.modalchangMore.show();
}
if (index == 2 && this.state.smallmoneyStatus) {
this.setState({
modalchangMoreTit:this.modalchangMoreTit=this.modalchangMoreTits[2],
modalMorechangValue:this.modalMorechangValue=this.state.smallmoneyTit == "" ? this.modalMorechangValues[2] : this.state.smallmoneyTit,
modalMorechangAbout:this.modalMorechangAbout=this.modalMorechangAbouts[2],
})
this.state.windowText=this.modalMorechangValue;
this.refs.modalchangMore.show();
}
if (index == 3 && this.state.maxcarnumStatus) {
this.setState({
modalchangMoreTit:this.modalchangMoreTit=this.modalchangMoreTits[3],
modalMorechangValue:this.modalMorechangValue=this.state.maxcarnumTit == "" ? this.modalMorechangValues[3] : this.state.maxcarnumTit,
modalMorechangAbout:this.modalMorechangAbout=this.modalMorechangAbouts[3],
})
this.state.windowText=this.modalMorechangValue;
this.refs.modalchangMore.show();
}
if (index == 4 && this.state.maxbabynumStatus) {
this.setState({
modalchangMoreTit:this.modalchangMoreTit=this.modalchangMoreTits[4],
modalMorechangValue:this.modalMorechangValue=this.state.maxbabynumTit == "" ? this.modalMorechangValues[4] : this.state.maxbabynumTit,
modalMorechangAbout:this.modalMorechangAbout=this.modalMorechangAbouts[4],
})
this.state.windowText=this.modalMorechangValue;
this.refs.modalchangMore.show();
}
if (index == 5 && this.state.creditStatus) {
this.setState({
modalchangMoreTit:this.modalchangMoreTit=this.modalchangMoreTits[5],
modalMorechangValue:this.modalMorechangValue=this.state.creditTit == "" ? this.modalMorechangValues[5] : this.state.creditTit,
modalMorechangAbout:this.modalMorechangAbout=this.modalMorechangAbouts[5],
})
this.state.windowText=this.modalMorechangValue;
this.refs.modalchangMore.show();
}
if (index == 6 && this.state.regdaysStatus) {
this.setState({
modalchangMoreTit:this.modalchangMoreTit=this.modalchangMoreTits[6],
modalMorechangValue:this.modalMorechangValue=this.state.regdaysTit == "" ? this.modalMorechangValues[6] : this.state.regdaysTit,
modalMorechangAbout:this.modalMorechangAbout=this.modalMorechangAbouts[6],
})
this.state.windowText=this.modalMorechangValue;
this.refs.modalchangMore.show();
}
}
// 点击开关弹出弹框
changeStyleMoreBut(int,value){
this.index=int;
if (int == 0) {
this.toSaveintCustom('goodStatus',value);
}
if (int == 1) {
this.toSaveintCustom('bigmoneyStatus',value);
}
if (int == 2) {
this.toSaveintCustom('smallmoneyStatus',value);
}
if (int == 3) {
this.toSaveintCustom('maxcarnumStatus',value)
}
if (int == 4) {
this.toSaveintCustom('maxbabynumStatus',value)
}
if (int == 5) {
this.toSaveintCustom('creditStatus',value)
}
if (int == 6) {
this.toSaveintCustom('regdaysStatus',value)
}
if (value && int == 0) {this.showChooseDigo(int);}
if (value && int == 1) {this.showChooseDigo(int);}
if (value && int == 2) {this.showChooseDigo(int);}
if (value && int == 3) {this.showChooseDigo(int);}
if (value && int == 4) {this.showChooseDigo(int);}
if (value && int == 5) {this.showChooseDigo(int);}
if (value && int == 6) {this.showChooseDigo(int);}
}
showChooseDigo(int){ //显示弹窗
this.changeStyleMore(int);
this.refs.modalchangMore.show();
}
// 点击输入框
modalMorechang(event){
this.setState({
windowText:event.value,
})
}
// 点击确定之后
modalMoreSurbut(){
let windowText = this.state.windowText;
if (this.index == 0 ) {
let shuLength = '';
{windowText.split('.')[1] == undefined ? shuLength=0 : shuLength=windowText.split('.')[1].length}
if (windowText.split('.')[0].length > 2 || !/^[0-9]*$/.test(windowText.split('.')[0]) || windowText.split('.')[0].length < 0 ) {
Modal.toast("请输入有效范围内的数值!");
return;
}if (shuLength > 2) {
Modal.toast("请输入2位小数有效数值!");
return;
}
}
if (this.index == 1 || this.index == 2) {
let shuLength = '';
{windowText.split('.')[1] == undefined ? shuLength=0 : shuLength=windowText.split('.')[1].length}
if (windowText.split('.')[0].length > 6 || !/^[0-9]*$/.test(windowText.split('.')[0]) || windowText.split('.')[0].length < 0 ) {
Modal.toast("请输入有效范围内的数值!");
return;
}if (shuLength > 2) {
Modal.toast("请输入2位小数有效数值!");
return;
}
}
if (this.index == 3 || this.index == 4 || this.index == 5 || this.index == 6 ) {
if (windowText.length > 6 || windowText=='' || !/^[0-9]*$/.test(windowText)) {
Modal.toast("请输入有效数值!");
return;
}
}
if (this.index == 0) {
this.state.goodTit = this.state.goodTit == '' ? this.modalMorechangValue : this.state.windowText;
}
if (this.index == 1) {
this.state.bigmoneyTit = this.state.bigmoneyTit == '' ? this.modalMorechangValue : this.state.windowText;
}
if (this.index == 2) {
this.state.smallmoneyTit = this.state.smallmoneyTit == '' ? this.modalMorechangValue : this.state.windowText;
}
if (this.index == 3) {
this.state.maxcarnumTit = this.state.maxcarnumTit == '' ? this.modalMorechangValue : this.state.windowText;
}
if (this.index == 4) {
this.state.maxbabynumTit = this.state.maxbabynumTit == '' ? this.modalMorechangValue : this.state.windowText;
}
if (this.index == 5) {
this.state.creditTit = this.state.creditTit == '' ? this.modalMorechangValue : this.state.windowText;
}
if (this.index == 6) {
this.state.regdaysTit = this.state.regdaysTit == '' ? this.modalMorechangValue : this.state.windowText;
}
this.saveBadInt();
this.refs.modalchangMore.hide();
}
//选择具体每一条关闭理由
cloTextbutter(ints){
if (this.vipFlag == 0) {
this.GoToView.bind(this,'bad_start');
return true;
}
this.setState({
closeword:ints
})
this.saveBadInt();
this.refs.modalclose.hide();
}
// 关键字输入框确定之后
surbut(){
this.state.keyword == '' ? '联系Q Q,活刷,皇冠,不降权,不扣分,不封店,爆款,刷钻,刷粉刷店铺,宝贝收藏,天猫关注,开团提醒,u站喜欢,企业QQ,动态评分,微淘关注,教程' : this.state.keywordWindow,
this.refs.modalchang.hide();
this.saveBadInt();
}
// 关键字开关弹出
keywordButton(){
if (this.state.keywordStatus) {
this.refs.modalchang.show()
}
}
// 弹出弹框提供选择
hideModal = () => {
this.refs.modalchang.hide();
this.refs.modal.hide();
this.refs.modalclose.hide();
this.refs.modalchangMore.hide();
}
// 点击灰度弹框消失
onMaskPress = (param) => {
this.refs.modalchang.hide();
this.refs.modal.hide();
this.refs.modalclose.hide();
this.refs.modalchangMore.hide();
}
/*填充数据到指定内容*/
render(){
let closeWay = this.closeWaytit[this.state.closeword];
let changColor = this.state.denfenon ? {color:'#333333'} : {color:'#cccccc'};
let changColorZhu = this.state.denfenon ? {color:'#F23C3C'} : {color:'#cccccc'};
let changColorTit = this.state.denfenon ? {color:'#999999'} : {color:'#cccccc'};
let changBut = this.state.denfenon ? this.state.disabledSW : true;
return(
<ScrollView style={{justifyContent:'flex-start',flex:1,backgroundColor:'#E6E7EB'}}>
{
this.getMoney()
}
<View style={{flexDirection:'row',justifyContent:'space-between',alignItems:'center',backgroundColor:'#FFFFFF',marginTop:'20rem'}}>
<Text style={{fontSize:'28rem',marginLeft:'24rem',marginTop:'20rem',marginBottom:'20rem',color:'#333333'}}>差评师拦截开关</Text>
<Switch key={`denfenon`} ref='state' style={{marginRight:'24rem'}} disabled={this.state.disabledSWhost} onValueChange={this.Changebut.bind(this)} checked={this.state.denfenon}/>
</View>
{this.state.firstBut && !this.state.denfenon ?
<View>
{this.firstList()}
</View>
:
<View>
<TouchableHighlight onPress={()=>{this.state.denfenon ? this.refs.modal.show() : null}} style={badintStyles.Touchbutt}>
<Text style={[{fontSize:'28rem'},changColor]}>快速设置拦截方式:</Text>
<Text style={[{fontSize:'28rem'},changColor]}>{this.state.interceptStyle}</Text>
<Icon style={[{marginRight:'10rem',fontSize:'30rem'},changColorTit]} name="arrowRight"></Icon>
</TouchableHighlight>
<View>
{
this.patterndata()
}
</View>
<View>
<Text style={[{fontSize:'28rem',marginLeft:'24rem',marginTop:'20rem',marginBottom:'20rem'},changColorTit]}>设置交易关闭理由</Text>
<TouchableHighlight onPress={()=>{this.state.denfenon ? this.refs.modalclose.show() : null }} style={[badintStyles.Touchbutt,{marginTop:'0rem'}]}>
<Text style={[{fontSize:'28rem'},changColor]}>关闭理由</Text>
<Text style={[{fontSize:'28rem'},changColor]}>{closeWay}</Text>
<Icon style={[{marginRight:'10rem',fontSize:'30rem'},changColorTit]} name="arrowRight"></Icon>
</TouchableHighlight>
<Text style={[{fontSize:'26rem',marginTop:'20rem',marginBottom:'0rem',marginLeft:'24rem',marginRight:'24rem'},changColorZhu]}>注:由于淘宝限制买家在提交订单10秒内付款完成,系统无法进行拦截;</Text>
</View>
<View>
<Text style={[{fontSize:'28rem',marginLeft:'24rem',marginTop:'20rem',marginBottom:'0rem'},changColorTit]}>交易关闭理由添加到订单备注</Text>
<View style={{flexDirection:'row',justifyContent:'space-between',alignItems:'center',backgroundColor:'#FFFFFF',marginTop:'20rem'}}>
<Text style={[{fontSize:'28rem',marginLeft:'24rem',marginTop:'20rem',marginBottom:'20rem'},changColor]}>将真实关闭理由添加到订单备注(对买家隐藏)</Text>
<Switch key={`addbiewzhu`}
style={{marginRight:'24rem'}}
disabled={changBut}
onValueChange={
(value,event)=>{this.setState({addbiewzhu:value})
this.saveBadInt();
}}
checked={this.state.addbiewzhu}
/>
</View>
</View>
<View>
<Text style={[{fontSize:'28rem',marginLeft:'24rem',marginTop:'20rem',marginBottom:'20rem'},changColorTit]}>拦截记录</Text>
<TouchableHighlight onPress={()=>{
GoToView({title:"拦截记录",status:'Badrecord',query:{userNick:encodeURI(this.userNick), vipFlag:this.vipFlag, subUserNick:encodeURI(this.subUserNick)}});
// this.goToNewPage();
}} style={[badintStyles.Touchbutt,{marginTop:'0rem'}]}>
<Text style={[{fontSize:'28rem'},changColor]}>拦截记录</Text>
<Icon style={[{marginRight:'10rem',fontSize:'30rem'},changColorTit]} name="arrowRight"></Icon>
</TouchableHighlight>
</View>
</View>
}
<Dialog ref="modal" onShow={this.onShow} onHide={this.onHide} onMaskPress={this.onMaskPress} duration={1000} contentStyle={{width:'600rem',backgroundColor:'#ffffff',borderRadius:'10rem'}}>
{
this.interceptor()
}
<View style={{flex:1,alignItems:'center',flexDirection:'row',justifyContent:'center',width:'600rem'}}>
<Button style={{borderWidth:'0rem',fontSize:'28rem',color:'#4990E2',paddingTop:'40rem',paddingBottom:'40rem'}} type="normal" onPress={this.hideModal}>取消</Button>
</View>
</Dialog>
<Dialog ref="modalclose" onShow={this.onShow} onHide={this.onHide} onMaskPress={this.onMaskPress} duration={1000} contentStyle={{width:'600rem',backgroundColor:'#ffffff',borderRadius:'10rem'}}>
{
this.closeWhydata()
}
<View style={{flex:1,alignItems:'center',flexDirection:'row',justifyContent:'center',width:'600rem'}}>
<Button style={{borderWidth:'0rem',fontSize:'28rem',color:'#4990E2',paddingTop:'40rem',paddingBottom:'40rem'}} type="normal" onPress={this.hideModal}>取消</Button>
</View>
</Dialog>
<Dialog ref="modalchang" onShow={this.onShow} onHide={this.onHide} onMaskPress={this.onMaskPress} duration={1000} contentStyle={{width:'600rem',backgroundColor:'#ffffff',borderRadius:'10rem'}} >
<View style={{marginTop:'40rem',paddingLeft:'24rem',paddingRight:'24rem',marginBottom:'10rem'}}>
<Text style={{fontSize:'28rem'}}>地址或留言包含以下关键字时拦截:</Text>
</View>
<View style={{marginRight:'24rem'}}>
<TextInput ref='custom_company'
value={this.state.keyword} maxNumberOfLines='4' multiple={true}
onInput={(value,e)=>{this.state.keyword = value.value
if (this.state.keywordStatus && this.state.keyword == '') {
Modal.alert("关键字不能为空",[{
onPress:()=>{},
text:'确定'
}]);
return;
}
this.setState({
keywordWindow:value.value,
})
}}
style={{marginLeft:'24rem',textAlign:'left',fontSize:'28rem',borderWidth:'0rem',width:'546rem',height:'200rem',color:'#4990E2',marginRight:'24rem',borderWidth:'1rem',borderStyle:'solid',borderColor:'#e2e3e8'}} />
</View>
<View style={{marginTop:'20rem',paddingLeft:'24rem',paddingRight:'24rem',marginBottom:'20rem'}}>
<Text style={{fontSize:'28rem'}}>关键字之间请用逗号分开</Text>
</View>
<View style={{flex:1,alignItems:'center',flexDirection:'row',justifyContent:'center',width:'600rem',borderWidth:'1rem',borderStyle:'solid',borderColor:'#e2e3e8'}}>
<View style={{borderRightWidth:'1rem',borderRightStyle:'solid',borderRightColor:'#e2e3e8',justifyContent:'center'}}>
<Button type="normal" onPress={this.hideModal} style={{borderWidth:'0rem',fontSize:'28rem',color:'#4990E2',paddingRight:'110rem',paddingTop:'40rem',paddingBottom:'40rem'}} >取消</Button>
</View>
<View style={{justifyContent:'center'}}>
<Button type="normal" onPress={this.surbut.bind(this)} style={{borderWidth:'0rem',fontSize:'28rem',color:'#4990E2',paddingLeft:'110rem',paddingTop:'40rem',paddingBottom:'40rem'}} >确定</Button>
</View>
</View>
</Dialog>
<Dialog ref="modalchangMore" onMaskPress={this.onMaskPress} duration={1000} contentStyle={{width:'600rem',backgroundColor:'#ffffff',borderRadius:'10rem'}} >
<View style={{marginTop:'40rem',paddingLeft:'24rem',paddingRight:'24rem',marginBottom:'10rem'}}>
<Text style={{fontSize:'28rem'}}>{this.modalchangMoreTit}</Text>
</View>
<View style={{marginRight:'24rem'}}>
<TextInput ref='custom_company'
value={this.modalMorechangValue} maxNumberOfLines='1' multiple={true}
onInput={this.modalMorechang.bind(this)}
style={{marginLeft:'24rem',textAlign:'left',fontSize:'28rem',paddingTop:'5rem',borderWidth:'0rem',width:'546rem',height:'50rem',color:'#4990E2',marginRight:'24rem',borderWidth:'1rem',borderStyle:'solid',borderColor:'#e2e3e8'}} />
</View>
<View style={{marginTop:'20rem',paddingLeft:'24rem',paddingRight:'24rem',marginBottom:'20rem'}}>
<Text style={{fontSize:'28rem'}}>{this.modalMorechangAbout}</Text>
</View>
<View style={{flex:1,alignItems:'center',flexDirection:'row',justifyContent:'center',width:'600rem',borderWidth:'0rem',borderStyle:'solid',borderColor:'#e2e3e8'}}>
<View style={{borderRightWidth:'1rem',borderRightStyle:'solid',borderRightColor:'#e2e3e8',justifyContent:'center'}}>
<Button type="normal" onPress={this.hideModal} style={{borderWidth:'0rem',fontSize:'28rem',color:'#4990E2',paddingRight:'110rem',paddingTop:'40rem',paddingBottom:'40rem'}} >取消</Button>
</View>
<View style={{justifyContent:'center'}}>
<Button type="normal" onPress={this.modalMoreSurbut.bind(this)} style={{borderWidth:'0rem',fontSize:'28rem',color:'#4990E2',paddingLeft:'110rem',paddingTop:'40rem',paddingBottom:'40rem'}} >确定</Button>
</View>
</View>
</Dialog>
</ScrollView>
)
}
}
const badintStyles = {
Touchbutt:{
marginTop:'20rem',
paddingLeft:'24rem',
paddingRight:'24rem',
paddingTop:'20rem',
paddingBottom:'20rem',
flexDirection:'row',
alignItems:'center',
justifyContent:'space-between',
flex:'1',
backgroundColor:'#ffffff',
borderBottomWidth:"1rem",
borderBottomStyle:"solid",
borderBottomColor:"#e2e3e8"
}
}
render(<BadInterceptNegativePage/>);
<file_sep>/Env/Domain.jsx
export const Domain = "//mtrade.aiyongbao.com";
export const ArticleCode= 'FW_GOODS-1827490';
export const VipCode='FW_GOODS-1827490-v2';
export const PriceType=['20元/月','48元/季度','88元/半年','148元/年'];
export const Product='trade';
<file_sep>/BatchDeliver.jsx
'use strict';
import {createElement, Component,render} from 'rax';
import {View, Text, Modal,Button,ListView,Checkbox,Icon,RefreshControl,Image,TouchableHighlight,Util} from 'nuke';
import QN from 'QAP-SDK';
import SendCard from './Component/SendCard/SendCard.jsx'
import {GetTradeList,OrderSort} from './Biz/Order/GetTrade.jsx';
import {GoToView} from 'Biz/View/GoToView.jsx';
import {GetUserInfo} from 'Biz/User/GetUserInfo.jsx';
import VipButton from './Component/Common/VipButton.jsx';
import {DoBeacon, getQueryString} from './Biz/Common.jsx';
import MyButton from './Component/Common/MyButton.jsx';
const Location = Util.Location;
var yyJson = [
{title:'发货时间节省50%', advantage:'一键选择所有待发货订单,扫码发货'},
{title:'发货效率提升30%',advantage:'减少手动发货带来的错发漏发,效率提升30%'},
{title:'随时随地发货',advantage:'拿着手机就可以随时随地一键发货,省时/省力/省心'}
]; /*运营文本json,格式的话···往上翻就能看到*/
class BatchSend extends Component {
constructor(props) {
// console.log("进入页面");
super(props);
this.state = {tradeList:[],value:true,qx:'全选',Tid:[],eachState:[],PAGE_NO:1,total:'',
stop: false,
isRefreshing: false,
showLoading:this.loading,
refreshText: '↓ 下拉刷新',
isNoOrder:false,
vipFlag:''
}
this.userNick;
// this.vipFlag = "";
this.PAGE_NO = 1;
this.loading = true
}
addTid(a){
this.setState({
Tid:this.state.Tid.concat(a)
});
}
addEachState(a){
this.setState({
eachState:this.state.eachState.concat(a)
})
}
getTradeMsg(page_no){
// console.log(page_no);
GetTradeList({
pageNo:page_no,
status:'WAIT_SELLER_SEND_GOODS',
callback: (result)=>{
// console.log(result);
if(result.trades_sold_get_response.trades){
this.setState({total:result.trades_sold_get_response.total_results});
var trades = result.trades_sold_get_response.trades;
let tradelist=this.state.tradeList;
for(var i in trades.trade){
trades.trade[i]['checkbox'] = 'false';
// trades.trade[i].tid = trades.trade[i].tid_str?trades.trade[i].tid_str:trades.trade[i].tid;
// this.addTrade(trades.trade[i]);
trades.trade[i].orders.order = OrderSort(trades.trade[i].orders.order);
tradelist.push(trades.trade[i]);
this.addTid(trades.trade[i].tid)
}
this.setState({tradeList:tradelist});
}else if(result.trades_sold_get_response.total_results!=0){
this.setState({total:result.trades_sold_get_response.total_results,showLoading: false});
}else{
this.setState({total:0,showLoading: false});
this.noOrder();
}
},
error_callback:(error)=>{
// console.error(error);
Modal.toast(error);
}
});
}
addTrade(trade) {
this.setState({tradeList: this.state.tradeList.concat(trade)});
}
componentWillMount(){
this.userNick = getQueryString(Location.search, 'userNick');
this.vipFlag = getQueryString(Location.search, 'vipFlag');
DoBeacon('TD20170114090141','ysshouhuo',this.userNick);
// GetUserInfo({callback:(result=>{
// // console.error(result);
// this.userNick=result.userNick;
// this.setState({vipFlag:result.vipFlag});
//
// })});
// console.log("进入页面");
this.getTradeMsg(1);
}
/**
* 获取用户vip信息
*/
getUserVip(){
QN.localstore.get({
query: {
key: 'vipFlag_'+this.userNick
}
}).then(result => {
this.setState({vipFlag:result});
// this.vipFlag = result;
}, error => {
Modal.toast(JSON.stringify(error));
// console.error(error);
});
}
/**
* 加载到底部时触发的事件
*/
handleLoadMore() {
var self = this;
// 这里进行异步操作
if (!this.loading) {//如果是最后一页数据。
self.setState({showLoading:false,isRefreshing: false});
return;
}else{
this.PAGE_NO = this.PAGE_NO + 1;
this.getTradeMsg(this.PAGE_NO);
self.setState({isRefreshing: false});
}
}
/**
* 下拉刷新时触发的事件
*/
handleRefresh = (e) => {
// console.log("@@@@@@@@@@");
// console.debug("HAND REF");
this.initTrade();
this.getTradeMsg(1);
this.setState({
isRefreshing: true,
refreshText: '加载中',
});
};
/**
* 当没有订单时处理事件
*/
noOrder(){
this.setState({showLoading: false,isNoOrder: true});
}
initTrade(){
this.PAGE_NO = 1;
this.setState({tradeList:[],value:true,qx:'全选',Tid:[],eachState:[],PAGE_NO:1,total:'',
stop: false,
isRefreshing: false,
showLoading:this.loading,
refreshText: '↓ 下拉刷新',
isNoOrder:false});
}
onChangeCheckbox(tid){
for(let i in tradeList){
if(tradeList[i].tid == tid){
if(tradeList[i].checkbox == 'false'){
tradeList[i].checkbox == 'true';
}else{
tradeList[i].checkbox == 'false';
}
}
}
}
onChange(value){
// console.log(value);
let count = 0;
for(let i in this.state.tradeList){
if(this.state.tradeList[i].tid == value){
if(this.state.tradeList[i].checkbox == 'false'){
this.state.tradeList[i].checkbox = 'true';
}else{
this.state.tradeList[i].checkbox = 'false';
}
}
}
for(let i in this.state.tradeList){
if(this.state.tradeList[i].checkbox == 'false'){
count++;
}
}
// console.log(count);
if(count == 0){
this.setState({
qx:'取消全选'
})
}else{
this.setState({
qx:'全选'
})
}
this.setState({
tradeList:this.state.tradeList
})
}
allSel(){
// console.log(this.state.qx);
// console.log(this.state.tradeList)
if(this.state.qx == '全选'){
for(let i in this.state.tradeList){
this.state.tradeList[i].checkbox = 'true';
}
this.setState({
tradeList:this.state.tradeList
})
this.setState({
qx:'取消全选'
})
}else{
for(let i in this.state.tradeList){
this.state.tradeList[i].checkbox = 'false';
}
this.setState({
tradeList:this.state.tradeList
})
this.setState({
qx:'全选'
})
}
}
ad(){
Modal.alert("续订广告");
}
send(){
let arr=[];
for(let i in this.state.tradeList){
if(this.state.tradeList[i].checkbox == 'true'){
arr.push(this.state.tradeList[i]);
}
}
// console.log(arr);
if(arr.length==0){
Modal.alert('请选择需要发送的订单');
return;
}
//准备正式进入批量发送页面
let self=this;
QN.localstore.set({
query: {
batch_deliver_trade_data: arr
},
success(result) {
// console.log(result);
GoToView({
title:'批量发货',
status:'BatchDeliverGoodsPage',
callback:(result)=>{
// console.log(result);
//注册全局时间
QN.on('app.batchDeliverTrade',(data)=>{
//首先关闭这个事件的注册
// console.log('事件传回的信息');
// console.log(data);
QN.off('app.batchDeliverTrade');
//不用管那么多,直接刷新就好了
//如何主动驱动刷新?
if(data.refresh){
self.initTrade();
self.getTradeMsg(1);
}
});
}
});
},
error(error) {
// console.error(error);
}
}).then(result => {
// console.log(result);
// console.log('难道是这里?')
}, error => {
// console.log(error);
// console.log('或者这里?')
});
//Modal.alert(arr);
DoBeacon('TD20170114090141','piliangfahuock',this.userNick);
}
/*听说这是张凝同学的坑*/
GoToView(value){
let name = '批量发货';/*来自哪一页,传入中文字符串*/
let feature = value;/*传入埋点值,不是项目编号哈!*/
let query = {xfrom:name, feature: feature} /*来自哪一页,传入中文字符串*/
QN.localstore.set({ /*将运营文本json存入localstorage*/
query: {
advertisment: yyJson
},
success(result) {
},
error(error) {
}
}).then(result => {
GoToView({status:'VipAd',query:query}); /*跳转页面*/
}, error => {
});
}
renderHead=()=>{
// console.log("111111111111");
// console.log(this.state.refreshText);
return <RefreshControl style={style.refresh} refreshing={this.state.isRefreshing} onRefresh={this.handleRefresh}><Text style={style.loadingText}>{this.state.refreshText}</Text></RefreshControl>;
}
renderFoot=()=>{
// console.debug('Footer');
if(this.state.showLoading){
return <View style={[style.loading]}><Text style={style.loadingText}>加载中...</Text></View>
}else{
if (this.state.isNoOrder) {
return (<View style={{flex:1,justifyContent:'center',alignItems:'center',marginTop:'100rem'}}>
<Image source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/ddgl.png'}} style={{width:'240rem',height:'240rem'}}/>
<Text style={[{marginLeft:'8rem',color:'#666666'}]}>暂无订单数据</Text>
</View>
)
}else{
return null;
}
}
}
render() {
let self=this;
let Vip1Button =
(<View style={{height:'100rem',flexDirection:'row',backgroundColor:'#ffffff',width:'750rem',borderTopWidth:'2rem',borderColor:'#eff0f4'}}>
<View style={{flexDirection:'row',flex:1,justifyContent:'flex-start',alignItems:'center',marginLeft:'-6rem'}}>
<Checkbox checked={this.state.qx=='全选'?false:true} size="small" onChange={this.allSel.bind(this)}></Checkbox>
<Text style={{color:'#333333',fontSize:'28rem'}}>全选</Text>
</View>
<View style={{flex:1,justifyContent:'center',alignItems:'flex-end'}}>
{/* <Button onPress={this.send.bind(this)} style={{alignSelf:'flex-end',marginRight:'24rem'}} type="secondary">批量发货</Button> */}
<MyButton style={{borderColor:'#3089dc',marginRight:'24rem'}} textStyle={{color:'#3089dc'}} size='medium' onPress={this.send.bind(this)} type="secondary" text='批量发货'></MyButton>
</View>
</View>);
let Vip0Button =
(<View style={{height:'100rem',flexDirection:'row',backgroundColor:'#ffffff',width:'750rem',borderTopWidth:'2rem',borderColor:'#eff0f4'}}>
<View style={{flexDirection:'row',flex:1,justifyContent:'flex-start',alignItems:'center',marginLeft:'-6rem'}}>
<Checkbox checked={this.state.qx=='全选'?false:true} size="small" onChange={this.allSel.bind(this)}></Checkbox>
<Text style={{color:'#333333',fontSize:'28rem'}}>全选</Text>
</View>
<View style={{flex:1,justifyContent:'center',alignItems:'flex-end'}}>
<VipButton data={{name:'批量发货',isVip:false,content:yyJson,bid:'20170109ShowSend',feature:'batch_send'}}></VipButton>
</View>
</View>);
if(this.state.total==undefined) return;
if(this.state.total!=0){
if(this.vipFlag == 0){
return (
<View style={{justifyContent:'space-between',height:'1200rem',backgroundColor:'#EFF0F4'}}>
<TouchableHighlight onPress={this.GoToView.bind(this,'batch_send_banner')} style={{width:'750rem',height:'80rem',justifyContent:'center',backgroundColor:'#fff0e7',flexDirection:'row'}}>
<Icon style={{fontSize:'32rem',color:'#f95b1c',alignSelf:'center',textAlign:'center'}} name='warning' />
<Text style={{fontSize:'28rem',color:'#f95b1c',alignSelf:'center',textAlign:'center'}}> 亲,批量发货是高级版功能,您需要</Text>
<TouchableHighlight style={{fontSize:'28rem',color:'#f95b1c',alignSelf:'center',textAlign:'center'}}>
<Text style={{fontSize:'28rem',color:'#0066FF ',alignSelf:'center',textAlign:'center',textDecoration:'underline'}}>升级</Text></TouchableHighlight>
<Text style={{fontSize:'28rem',color:'#f95b1c',alignSelf:'center',textAlign:'center'}}>才能使用</Text>
</TouchableHighlight>
<ListView
renderHeader={this.renderHead}
renderFooter={this.renderFoot}
renderRow={this.renderItem.bind(this)}
dataSource={this.state.tradeList}
onEndReached={this.handleLoadMore.bind(this)}
/>
{Vip0Button}
</View>
);
}else{
return(
<View style={{justifyContent:'space-between',flex:1,backgroundColor:'#EFF0F4'}}>
<ListView
renderHeader={this.renderHead}
renderFooter={this.renderFoot}
renderRow={this.renderItem.bind(this)}
dataSource={this.state.tradeList}
onEndReached={this.handleLoadMore.bind(this)}
style={{flex:1}}
/>
{Vip1Button}
</View>
)
}
}else{
if(this.vipFlag == 0){
return (
<View style={{flex:1,backgroundColor:'#EFF0F4'}}>
<TouchableHighlight onPress={this.GoToView.bind(this,'batch_send_banner')} style={{width:'750rem',height:'80rem',justifyContent:'center',backgroundColor:'#fff0e7',flexDirection:'row'}}>
<Icon style={{fontSize:'32rem',color:'#f95b1c',alignSelf:'center',textAlign:'center'}} name='warning' />
<Text style={{fontSize:'28rem',color:'#f95b1c',alignSelf:'center',textAlign:'center'}}> 亲,批量发货是高级版功能,您需要</Text>
<TouchableHighlight style={{fontSize:'28rem',color:'#f95b1c',alignSelf:'center',textAlign:'center'}}>
<Text style={{fontSize:'28rem',color:'#0066FF ',alignSelf:'center',textAlign:'center',textDecoration:'underline'}}>升级</Text></TouchableHighlight>
<Text style={{fontSize:'28rem',color:'#f95b1c',alignSelf:'center',textAlign:'center'}}>才能使用</Text>
</TouchableHighlight>
<View style={{flex:1,justifyContent:'center',alignItems:'center',marginTop:'100rem'}}>
<Image source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/ddgl.png'}} style={{width:'240rem',height:'240rem'}}/>
<Text style={[{marginLeft:'8rem',color:'#666666'}]}>暂无订单数据</Text>
</View>
</View>
)
}else{
return (<View style={{flex:1,justifyContent:'center',alignItems:'center',marginTop:'100rem'}}>
<Image source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/ddgl.png'}} style={{width:'240rem',height:'240rem'}}/>
<Text style={[{marginLeft:'8rem',color:'#666666'}]}>暂无订单数据</Text>
</View>
)
}
}
}
renderItem (item, index){
return (
<SendCard dataSource={item} index={index} card={this}></SendCard>
);
}
}
const style = {
container: {
justifyContent: 'flex-start',
alignItems: 'flex-start',
backgroundColor: '#F5FCFF'
},
loadingText:{
height:"80rem",
color:"#666666"
},
loading:{
height:"80rem",
display:"flex",
flexDirection:"row",
backgroundColor:"#cccccc",
alignItems:"center",
justifyContent:"center"
},
refresh:{
height:"80rem",
width:"750rem",
display:"flex",
flex:"1",
flexDirection:"row",
justifyContent:"center",
alignItems:"center"
},
};
render(<BatchSend />);
// export default Demo;
<file_sep>/BadInterceptSellLists.jsx
/* 出售中宝贝
*@author drl
*/
import {createElement, Component,render} from 'rax';
import { Env,Modal,Button,View, Text,Util,ListView,Image} from 'nuke';
import {Network} from 'Component/Common/Network.jsx';
import QN from 'QAP-SDK';
import ListBlock from 'Component/Common/ListBlock.jsx';
import {getAllUserInfos} from './Biz/User/GetAllUserInfos.jsx';
import {QNInvoke} from 'Biz/Common.jsx';
import {DoBeacon,getQueryString} from 'Biz/Common.jsx';
const { appInfo } = Env;
const Location = Util.Location;
class BadInterceptSellLists extends Component {
constructor() {
super();
this.state = {
getSelldata:[], //出售中的宝贝
total_results:'',
babyData:[],
showLoading:true,
flag:false
}
this.userNick = '';
this.vipFlag=0;
this.resdata=[];
this.page=1;
this.allpage=1;
}
componentWillMount(){
QN.showLoading({
query: {
text: '加载中 ~~'
}
});
this.userNick = getQueryString(Location.search, 'userNick');
this.vipFlag = getQueryString(Location.search, 'vipFlag');
this.subUserNick = getQueryString(Location.search, 'subUserNick');
// this.ratebalckname(1);
this.getSellBabyList(1);
}
/*查看出售中的宝贝*/
getSellBabyList(page){
let query={
method: 'taobao.items.onsale.get' , /*出售里的宝贝*/
fields: 'num_iid,title,nick,pic_url'
}
let self = this;
QNInvoke(query,(result)=>{
let total_results=result.items_onsale_get_response.total_results;
let arr = result.items_onsale_get_response.items.item;
let allPage = Math.ceil(total_results/10);
let pageNum=10;
let start=0;
let end=pageNum * page + start;
let pageData = arr.splice(start,end);
self.setState({
page:this.page=page,
allpage:this.allpage=allPage,
flag:true,
total_results:total_results,
getSelldata:pageData
})
QN.hideLoading();
},(error_callback)=>{
QN.hideLoading();
Modal.toast(JSON.stringify(error_callback));
})
QN.hideLoading();
}
/**
* 加载到底部时触发的事件
*/
handleLoadMore() {
let self = this;
let page=this.page+1;
let allpage=this.allpage;
if (this.page==allpage) {//最后一页数据
return;
}else{
this.getSellBabyList(page);
}
}
/**
* 无限滚动输出
*/
renderFoot=()=>{
if(this.page < this.allpage){
return <View style={badBlackStyle.loading}><Text style={badBlackStyle.loadingText}>正在加载中...</Text></View>
}else{
// return <View style={badBlackStyle.loading}><Text style={badBlackStyle.loadingText}>数据加载完毕</Text></View>
}
}
/**
* 单行渲染
*/
renderData (e,index){
let imageurl = e.pic_url;
return(
<View style={{flexDirection:'row',alignItems:'center',justifyContent:'space-between',backgroundColor:'#FFFFFF',borderBottomWidth:'1rem',borderStyle:'solid',borderColor:'#c4c6cf'}}>
<View style={{marginLeft:'24rem',flexDirection:'row',justifyContent:'flex-start',alignItems:'center',width:'580rem',marginLeft:'24rem'}}>
<View style={{width:'120rem',height:'120rem',marginTop:'20rem',marginBottom:'20rem'}}>
<Image source={{uri: imageurl}} style={{width:'120rem',height:'120rem',quality:"original"}}/>
</View>
<Text style={{width:'420rem',marginLeft:'24rem',fontSize:'28rem',color:'#333333',marginRight:'24rem'}}>{e.title}</Text>
</View>
<View style={{marginRight:'24rem'}}>
<Button style={{marginTop:'20rem',marginBottom:'20rem'}} onPress={this.addBaby.bind(this,e)} size='small'>添加</Button>
</View>
</View>
)
}
/*添加出售中宝贝*/
addBaby(event){
let self = this;
QN.showLoading({
query: {
text: '正在添加中~'
}
});
if (appInfo.platform == "iOS") {
DoBeacon('TD20170114090141','tianjiacpljiosbaobbmd',this.userNick);/*添加宝贝白名单埋点*/
}else {
DoBeacon('TD20170114090141','tianjiacpljanzbaobbmd',this.userNick);/*添加宝贝白名单埋点*/
}
Network.Post("/jy2/addBabylist",{title:event.title,imgurl:event.pic_url,num_id:event.num_iid},(data)=>{
if (data==0) {
Modal.alert("此宝贝已在宝贝白名单中,请重新选择其他未添加的宝贝",[{
onPress:()=>{},
text:'确定'
}]);
return;
}
Modal.toast("添加出售中宝贝成功");
QN.hideLoading();
// 仅仅触发返回事件
QN.emit('app.gotoSellList',{});
QN.navigator.back();
},{mode: 'jsonp'},(error_callback)=>{
QN.hideLoading();
Modal.alert("添加失败:"+JSON.stringify(error_callback),[{
onPress:()=>{},
text:'确定'
}]);
});
QN.hideLoading();
}
render() {
let self=this;
// if (!self.state.flag) {
// return;
// }
if (this.state.getSelldata.length == 0) {
return (
<View style={badBlackStyle.loading}>
<Text style={{conor: '#666666',fontSize: '26rem'}}>没有出售中的宝贝</Text>
</View>
)
}else{
return (
<View style={{backgroundColor:'#eff0f4',flex:1}}>
<ListView
showScrollbar={true}
dataSource={this.state.getSelldata}
renderRow={this.renderData.bind(this)}
onEndReached={this.handleLoadMore.bind(this)}
renderFooter={this.renderFoot}
style={{backgroundColor:'#eff0f4'}}
/>
</View>
)
}
}
}
const badBlackStyle={
loading:{
height:"80rem",
display:"flex",
flexDirection:"row",
backgroundColor:"#cccccc",
alignItems:"center",
justifyContent:"center",
fontSize:'28rem',
},
loadingText:{
color:"#666666",
fontSize:'28rem',
},
}
render(<BadInterceptSellLists/>);
<file_sep>/Biz/User/GetUserType.jsx
/**
* @author shitou
*/
import QN from 'QAP-SDK';
let default_userseller_query={
method: "taobao.user.seller.get",
};
/**
* 获取c店还是B店
* @author Jiang
*/
var GetUserType = function({query=default_userseller_query,callback,error_callback=undefined}){
query.fields = 'type,nick';
QN.top.invoke({
query: query
}).then((result) => {
callback(result.data);
}, (error) => {
if(error_callback){
// let msg_error = error.error_response.msg;
error_callback(error);
}
});
}
export {GetUserType};
<file_sep>/TradeIndex.jsx
/**
* 首页
* @author Shitou
*/
import {Modal,View, Text, TouchableHighlight,ScrollView,Image,Icon,Link,Env} from 'nuke';
import {createElement, Component,render} from 'rax';
import QN from 'QAP-SDK';
import {GoToView} from './Biz/View/GoToView.jsx';
import styles from './rxscss/tradeindex.rxscss';
import {StorageOper} from './Biz/View/StorageOper.jsx';
import IndexIcon from './Component/Trade/IndexIcon.jsx';
import PayFlag from './Component/Common/PayFlag.jsx';
import {Network} from 'Component/Common/Network.jsx';
import {QNInvoke} from 'Biz/Common.jsx';
import {getAllUserInfos} from 'Biz/User/GetAllUserInfos.jsx';
import {UserContact} from 'Biz/User/UserContact.jsx';
import ModalAD from 'Public/Biz/OpenAD/ModalAD.jsx';
import BannerAD from 'Public/Biz/OpenAD/BannerAD.jsx';
import {IsEmpty} from 'Public/Common/Utils/IsEmpty.jsx';
import {DoBeacon} from 'Biz/Common.jsx';
const { isWeex, isWeb, isQNWeb , isQNWeex , appInfo } = Env;
const appInfo_JSON = QN.uri.parseQueryString(appInfo);
class TradeIndex extends Component {
constructor() {
super();
this.state = {
todayNum: 0,
waitPayNum: 0,
waitSendNum: 0,
SendToNum: 0,
waitEvaNum: 0,
refundNum:0,
successNum:0,
closeNum:0,
flag:true,
renderAD:false,
}
this.userNick = '';
this.vipFlag = '';
this.vipTime = '';
this.avatar = '';
}
/**
* 会在render函数前被执行
*/
componentWillMount(){
this.userNick = this.props.index.userNick;
this.subUserNick = this.props.index.sub_user_nick;
this.vipFlag = this.props.index.vipFlag;
this.vipTime = this.props.index.vipTime;
this.avatar = this.props.index.avatar;
this.title = this.props.index.title;
this.userInfo = this.props.index.userInfo;
// this.syncUserInfo();
this.getStatusNum();
let key="usertype,vipflag,imei,home,subusernick";
StorageOper.localGet({key:key,callback:(result)=>{
if(IsEmpty(result)){
return;
}
this.homeIndex=result['home'];
this.ad_info=result;
this.setState({
renderAD:true
});
if(this.ad_info){
let nick=this.ad_info.subusernick;
if(nick.indexOf(":")>0){
//说明有子账号
nick=nick.split(':')[0];
}
if(appInfo_JSON.platform=='android'){
if(this.ad_info.vipflag==1)
DoBeacon('TD20170114090141','indexanvip',nick);
else {
DoBeacon('TD20170114090141','indexanfree',nick);
}
DoBeacon('TD20170114090141','indexan',nick);
}else{
//说明是ios
if(this.ad_info.vipflag==1)
DoBeacon('TD20170114090141','indexiosvip',nick);
else {
DoBeacon('TD20170114090141','indexiosfree',nick);
}
DoBeacon('TD20170114090141','indexios',nick);
}
}
}});
}
GoToQA(){
let url = 'tbsellerplatform://?session_event=event_back_platform&module=module_setting&sub_module=submodule_setting_feedback&service_id=issueSource%3D21085840';
QN.navigator.push({
url: url
});
}
/**
* 测试,联系客服接口
*/
contactKf(value){
let infoStr = "";
let appInfo_JSON = QN.uri.parseQueryString(appInfo);
infoStr += "来自设备:" + appInfo_JSON.deviceModel + " \r\n系统:" + appInfo_JSON.platform + " \r\n千牛版本:" + appInfo_JSON.appVersion + " \r\n";
if (this.vipFlag == 1) {
infoStr += "高级版:"+this.vipTime;
}else{
infoStr += "初级版:"+this.vipTime;
}
if (value) {
infoStr = infoStr + " \r\n" + value;
}
UserContact({
value:infoStr,
});
}
format(datatime,pattern) {
/*初始化返回值字符串*/
var returnValue = pattern;
/*正则式pattern类型对象定义*/
var format = {
"y+": datatime.getFullYear(),
"M+": datatime.getMonth()+1,
"d+": datatime.getDate(),
"H+": datatime.getHours(),
"m+": datatime.getMinutes(),
"s+": datatime.getSeconds(),
"S": datatime.getMilliseconds(),
"h+": (datatime.getHours()%12),
"a": (datatime.getHours()/12) <= 1? "AM":"PM"
};
/*遍历正则式pattern类型对象构建returnValue对象*/
for(var key in format) {
var regExp = new RegExp("("+key+")");
if(regExp.test(returnValue)) {
var zero = "";
for(var i = 0; i < RegExp.$1.length; i++) { zero += "0"; }
var replacement = RegExp.$1.length == 1? format[key]:(zero+format[key]).substring(((""+format[key]).length));
returnValue = returnValue.replace(RegExp.$1, replacement);
}
}
return returnValue;
};
/**
* 获取各个状态的订单数量
*/
getStatusNum(){
let start_time = this.format(new Date(), 'yyyy-MM-dd 00:00:00');
let end_time = this.format(new Date(), 'yyyy-MM-dd 23:59:59');
let query = {
method: 'taobao.trades.sold.get',
fields:'timeout_action_time,end_time,pay_time,consign_time,rate_status,seller_nick,shipping_type,cod_status,orders.oid,orders.oid_str,orders.outer_iid,orders.outer_sku_id,orders.consign_time,tid,tid_str,status,end_time,buyer_nick,trade_from,credit_card_fee,buyer_rate,seller_rate,created,num,payment,pic_path,has_buyer_message,receiver_country,receiver_state,receiver_city,receiver_district,receiver_town,receiver_address,receiver_zip,receiver_name,receiver_mobile,receiver_phone,orders.timeout_action_time,orders.end_time,orders.title,orders.status,orders.price,orders.payment,orders.sku_properties_name,orders.num_iid,orders.refund_id,orders.pic_path,orders.refund_status,orders.num,orders.logistics_company,orders.invoice_no,seller_flag,type,post_fee,is_daixiao,has_yfx,yfx_fee,buyer_message,buyer_flag,buyer_memo,seller_memo',
type: 'tmall_i18n,fixed,auction,guarantee_trade,step,independent_simple_trade,independent_shop_trade,auto_delivery,ec,cod,game_equipment,shopex_trade,netcn_trade,external_trade,instant_trade,b2c_cod,hotel_trade,super_market_trade,super_market_cod_trade,taohua,waimai,nopaid,step,eticket',
};
let queryArr = [{
method:query.method,
fields:query.fields,
type:query.type,
status:'WAIT_BUYER_PAY'
}, {
method:query.method,
fields:query.fields,
type:query.type,
status:'WAIT_SELLER_SEND_GOODS'
}, {
method:query.method,
fields:query.fields,
type:query.type,
status:'WAIT_BUYER_CONFIRM_GOODS'
}, {
fields:query.fields,
method:query.method,
page_no:1,
page_size:100,
rate_status:"RATE_UNSELLER",
status:"TRADE_FINISHED",
type:query.type
}, {
method:"taobao.refunds.receive.get",
fields:"refund_id,status,tid",
pageSize:100
}, {
method:query.method,
fields:query.fields,
type:query.type,
status:'TRADE_FINISHED'
}, {
method:query.method,
fields:query.fields,
type:query.type,
status:'ALL_CLOSED'
}, {
method:query.method,
fields:query.fields,
type:query.type,
start_created: start_time,
end_created: end_time
}];
if (this.vipFlag == '') {
queryArr[queryArr.length] = {
method: "taobao.vas.subscribe.get",
article_code: "FW_GOODS-1827490",
nick: this.userNick
};
}
// console.log(queryArr);
QN.top.batch({
query: queryArr,
}).then(result => {
// console.error(result);
if (result.data[result.data.length]) {
let subscribes = result.data[result.length].vas_subscribe_get_response;
var vipFlag = subscribes.article_user_subscribes.article_user_subscribe[0].item_code;
if (vipFlag == 'FW_GOODS-1827490-v2') {
vipFlag = 1;
}else{
vipFlag = 0;
}
this.vipFlag = vipFlag;
}
QN.hideLoading();
if (result.data[0].error_response) {
if (result.data[0].error_response.sub_msg.indexOf('无此操作权限') > 0) {
Modal.alert("订单笔数获取失败!子账号无查看订单权限!");
}else{
Modal.alert(result.data[0].error_response.sub_msg);
}
return;
}
var waitPayNum = result.data[0].trades_sold_get_response.total_results;
var waitSendNum = result.data[1].trades_sold_get_response.total_results;
var SendToNum = result.data[2].trades_sold_get_response.total_results;
var waitEvaNum=0; //result.data[3].trades_sold_get_response.total_results;
if (result.data[3].trades_sold_get_response.trades != undefined) {
for(var i in result.data[3].trades_sold_get_response.trades.trade){
let trade=result.data[3].trades_sold_get_response.trades.trade[i];
//这里待评价叫做特殊处理
var order=trade;
let end_time_str=order.end_time;
end_time_str = end_time_str.replace(/-/g,"/");
var endTime = new Date(end_time_str);
var now=new Date;
var date3=now.getTime()-endTime.getTime();
//计算出相差天数
var days=Math.floor(date3/(24*3600*1000));
if(days>=15){
// console.log('时间大于15了 '+days);
continue;
}
waitEvaNum++;
}
} else {
waitEvaNum=0;
}
var refundNum =0; // result[4].refunds_receive_get_response.total_results;
let refundTids=[];
if (result.data[4].refunds_receive_get_response.refunds != undefined) {
for(var i in result.data[4].refunds_receive_get_response.refunds.refund){
let trade=result.data[4].refunds_receive_get_response.refunds.refund[i];
if(trade.status=='SUCCESS' || trade.status=='CLOSED'){
continue;
}
if(refundTids.indexOf(trade.tid)<0){
refundTids.push(trade.tid);
refundNum++;
}
}
} else {
refundNum =0;
refundTids=[];
}
var successNum = result.data[5].trades_sold_get_response.total_results;
var closeNum = result.data[6].trades_sold_get_response.total_results;
var todayNum = result.data[7].trades_sold_get_response.total_results;
if (todayNum > 99) {
todayNum = '99+';
}
this.setState({
waitPayNum: waitPayNum,
waitSendNum: waitSendNum,
SendToNum: SendToNum,
waitEvaNum: waitEvaNum,
refundNum:refundNum,
successNum:successNum,
closeNum:closeNum,
todayNum: todayNum,
});
}, error => {
// console.error(error);
});
}
GoToView(value){
GoToView({
status:value,
query:{userNick:encodeURI(this.userNick), vipFlag:this.vipFlag, subUserNick:encodeURI(this.subUserNick)}
});
}
goToList(status){
let change_index = this.props.index;
change_index.goToList(status);
}
goToMy(status){
let change_index = this.props.index;
change_index.goToMy(status);
}
/*
**点击高级功能跳转至高级功能页面
*@author ryq
*/
superOrder(){
this.props.dataFlag=false;
this.setState({
flag:false
})
}
/**
* 重新授权
* by wp
*/
webauth(){
getAllUserInfos({
callback: (result)=>{
if(result.sub_user_nick){
Modal.alert("子账号不支持授权!",[
{
onPress:()=>{},
text:"确定"
}
])
}else{
let url = "https://oauth.taobao.com/authorize?response_type=code&client_id=" + "21085840" + "&redirect_uri=" + "http://mtrade.aiyongbao.com/" + "/tc/trades2?scope=item&view=wap&state=" + "jy" + ",qapmobile&code=trade"
QN.navigator.push({
url: url,
title: '爱用交易',
success(result) {
},
error(error) {
// console.error(error);
}
});
// QN.sso({
// success(result) {
// },
// error(error) {
// // console.log(error);
// }
// }).then(result => {
// Network.Post('/Jy2/webauth', {content:result.data}, (res) => {
// Modal.alert("授权成功请重新打开插件!",[
// {
// onPress:()=>{QN.navigator.close();},
// text:"确定"
// }
// ])
// });
// }, error => {
// // console.log(error);
// });
}
},
error_callback:(error)=>{
}
});
}
/**
* 清除缓存
*/
ClearStorage(){
QN.localstore.clear({
success(result) {
},
error(error) {
// console.log(error);
}
}).then(result => {
Modal.alert("初始化交易缓存成功,请关闭插件后重进",[
{
onPress:(e)=>{QN.navigator.close()},
text:"确定"
}
])
}, error => {
// console.log(error);
});
}
renderTools(){
let text = '';
let appInfo_JSON = QN.uri.parseQueryString(appInfo);
if (appInfo_JSON.platform == 'android') {
text = '付费';
}else{
text = '高级';
}
if (this.props.vipuser == '1' || this.vipFlag == '1') {
return(
<View style={styles.vipCard}>
<View style={styles.ordermgtTitle}><Text style={styles.ordermgtTitleStyle}>必备工具</Text></View>
<View style={styles.ordermgt}>
<TouchableHighlight style={{flex:1}} onPress={this.GoToView.bind(this,'SmsCare')}>
<IndexIcon status="mgt" title="短信关怀" pic_url="//q.aiyongbao.com/trade/web/images/qap_img/mobile/dxgh_new.png"></IndexIcon>
</TouchableHighlight>
<TouchableHighlight style={{flex:1}} onPress={this.GoToView.bind(this,'EvaluateMgt')}>
<IndexIcon status="mgt" title="评价管理" pic_url="//q.aiyongbao.com/trade/web/images/qap_img/mobile/pjgl_new.png"></IndexIcon>
</TouchableHighlight>
<TouchableHighlight style={{flex:1}} onPress={this.GoToView.bind(this,'LogisticMgt')}>
<IndexIcon status="mgt" title="物流管理" pic_url="//q.aiyongbao.com/trade/web/images/qap_img/mobile/wlgl_new.png"></IndexIcon>
</TouchableHighlight>
<TouchableHighlight style={{flex:1}} onPress={this.GoToView.bind(this,'OrderBlank')}>
<IndexIcon status="mgt" title="拣货单" pic_url="//q.aiyongbao.com/trade/web/images/qap_img/mobile/jhd_new.png"></IndexIcon>
</TouchableHighlight>
</View>
<View style={styles.ordermgt}>
<TouchableHighlight style={{flex:1}} onPress={this.GoToView.bind(this,"autoeva")}>
<IndexIcon status="mgt" title="自动评价" pic_url="//q.aiyongbao.com/trade/web/images/qap_img/mobile/zdpj_new.png"></IndexIcon>
</TouchableHighlight>
<TouchableHighlight style={{flex:1}} onPress={this.GoToView.bind(this,'BadInterceptNegativePage')}>
<IndexIcon status="mgt" title="差评拦截" pic_url="//q.aiyongbao.com/trade/web/images/qap_img/mobile/cplj_new.png"></IndexIcon>
</TouchableHighlight>
<TouchableHighlight style={{flex:1}} onPress={this.GoToView.bind(this,'BatchDeliver')}>
<IndexIcon status="mgt" title="批量发货" pic_url="//q.aiyongbao.com/trade/web/images/qap_img/mobile/plfh_new.png"></IndexIcon>
</TouchableHighlight>
<TouchableHighlight style={{flex:1}} onPress={this.GoToView.bind(this,'BatchRate')}>
<IndexIcon status="mgt" title="批量评价" pic_url="//q.aiyongbao.com/trade/web/images/qap_img/mobile/plpj_new.png"></IndexIcon>
</TouchableHighlight>
</View>
<View style={styles.ordermgt}>
<TouchableHighlight style={{flex:1}} onPress={this.GoToView.bind(this,'WwFastPayPage')}>
<IndexIcon status="mgt" title="旺旺催付" pic_url="//q.aiyongbao.com/trade/web/images/qap_img/mobile/wwcf_new.png"></IndexIcon>
</TouchableHighlight>
<TouchableHighlight style={{flex:1}} onPress={this.GoToView.bind(this,'CheckAddrPage')}>
<IndexIcon status="mgt" title="核对地址" pic_url="//q.aiyongbao.com/trade/web/images/qap_img/mobile/hddz_new.png"></IndexIcon>
</TouchableHighlight>
<View style={{flex:1}}>
<View style={styles.ordermgtLabelNull}>
</View>
</View>
<View style={{flex:1}}>
<View style={styles.ordermgtLabelNull}>
</View>
</View>
</View>
</View>
);
} else {
return(
<View>
<View style={styles.vipCard}>
<View style={styles.ordermgtTitle}><Text style={styles.ordermgtTitleStyle}>基础工具</Text></View>
<View style={styles.ordermgt}>
<TouchableHighlight style={{flex:1}} onPress={this.GoToView.bind(this,'SmsCare')}>
<IndexIcon status="mgt" title="短信关怀" pic_url="//q.aiyongbao.com/trade/web/images/qap_img/mobile/dxgh_new.png"></IndexIcon>
</TouchableHighlight>
<TouchableHighlight style={{flex:1}} onPress={this.GoToView.bind(this,'EvaluateMgt')}>
<IndexIcon status="mgt" title="评价管理" pic_url="//q.aiyongbao.com/trade/web/images/qap_img/mobile/pjgl_new.png"></IndexIcon>
</TouchableHighlight>
<TouchableHighlight style={{flex:1}} onPress={this.GoToView.bind(this,'LogisticMgt')}>
<IndexIcon status="mgt" title="物流管理" pic_url="//q.aiyongbao.com/trade/web/images/qap_img/mobile/wlgl_new.png"></IndexIcon>
</TouchableHighlight>
<TouchableHighlight style={{flex:1}} onPress={this.GoToView.bind(this,'OrderBlank')}>
<IndexIcon status="mgt" title="拣货单" pic_url="//q.aiyongbao.com/trade/web/images/qap_img/mobile/jhd_new.png"></IndexIcon>
</TouchableHighlight>
</View>
</View>
<View style={styles.vipCard}>
<View style={[styles.ordermgtTitle,{flexDirection:'row',alignItems:'center'}]}>
<Text style={styles.ordermgtTitleStyle}>必备工具</Text>
{/* <Image source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/gjc_new.png'}} style={{width:'60rem',height:'30rem',marginLeft:'24rem',marginRight:'24rem'}} /> */}
<View style={{width:'40rem',height:'20rem',marginLeft:'5rem',marginRight:'24rem',borderRadius:'5rem',backgroundColor:'#fc9825',justifyContent:'center',alignItems:'center'}}><Text style={{fontSize:'15rem',color:'#ffffff'}}>{text}</Text></View>
</View>
<View style={styles.ordermgt}>
<TouchableHighlight style={{flex:1}} onPress={this.GoToView.bind(this,"autoeva")}>
<IndexIcon status="mgt" title="自动评价" pic_url="//q.aiyongbao.com/trade/web/images/qap_img/mobile/zdpj_new.png"></IndexIcon>
</TouchableHighlight>
<TouchableHighlight style={{flex:1}} onPress={this.GoToView.bind(this,'BadInterceptNegativePage')}>
<IndexIcon status="mgt" title="差评拦截" pic_url="//q.aiyongbao.com/trade/web/images/qap_img/mobile/cplj_new.png"></IndexIcon>
</TouchableHighlight>
<TouchableHighlight style={{flex:1}} onPress={this.GoToView.bind(this,'BatchDeliver')}>
<IndexIcon status="mgt" title="批量发货" pic_url="//q.aiyongbao.com/trade/web/images/qap_img/mobile/plfh_new.png"></IndexIcon>
</TouchableHighlight>
<TouchableHighlight style={{flex:1}} onPress={this.GoToView.bind(this,'BatchRate')}>
<IndexIcon status="mgt" title="批量评价" pic_url="//q.aiyongbao.com/trade/web/images/qap_img/mobile/plpj_new.png"></IndexIcon>
</TouchableHighlight>
</View>
<View style={styles.ordermgt}>
<TouchableHighlight style={{flex:1}} onPress={this.GoToView.bind(this,'WwFastPayPage')}>
<IndexIcon status="mgt" title="旺旺催付" pic_url="//q.aiyongbao.com/trade/web/images/qap_img/mobile/wwcf_new.png"></IndexIcon>
</TouchableHighlight>
<TouchableHighlight style={{flex:1}} onPress={this.GoToView.bind(this,'CheckAddrPage')}>
<IndexIcon status="mgt" title="核对地址" pic_url="//q.aiyongbao.com/trade/web/images/qap_img/mobile/hddz_new.png"></IndexIcon>
</TouchableHighlight>
<View style={{flex:1}}>
<View style={styles.ordermgtLabelNull}>
</View>
</View>
<View style={{flex:1}}>
<View style={styles.ordermgtLabelNull}>
</View>
</View>
</View>
</View>
</View>
)
}
}
//openad的广告位
renderModalAD(){
//只有入口页面才弹窗
if(this.state.renderAD && this.homeIndex=='index'){
//能拿到这个值说明都拿到了才对
return(
<ModalAD pid="441" did="913181696" imei={this.ad_info.imei} usertype={this.ad_info.usertype} vipflag={this.ad_info.vipflag} nick={this.ad_info.subusernick} width="600rem" height="660rem"></ModalAD>
)
}
}
//openad的banner位置
renderBannerAD(){
if(this.state.renderAD){
return(
<BannerAD style={{marginTop:'20rem'}} pid="440" did="913181696" imei={this.ad_info.imei} usertype={this.ad_info.usertype} vipflag={this.ad_info.vipflag} nick={this.ad_info.subusernick} width="750rem" height="120rem"></BannerAD>
)
}
}
render(){
if (this.avatar) {
if (this.avatar.indexOf('TB1PcePLVXXXXaDXpXXXXXXXXXX-100-100') >= 0 || this.avatar == "") {
this.avatar = '//q.aiyongbao.com/trade/web/images/qap_img/mobile/mrtx.jpg'
}
} else {
this.avatar = '//q.aiyongbao.com/trade/web/images/qap_img/mobile/mrtx.jpg'
}
let flag=this.props.dataFlag;
this.state.flag=flag;
let text = '';
if (this.vipFlag == '1') {
text = '高级版';
}else {
text = '初级版';
}
return (
<ScrollView style={styles.index}>
<View style={{flexDirection:'row',height:'160rem',backgroundColor:'#F57745',alignItems:'center'}}>
<View style={{flex:1,flexDirection:'row',alignItems:'center'}}>
<View>
<Image source={{uri:this.avatar}} style={{width:'80rem',height:'80rem',borderRadius:'60rem',marginLeft:'24rem'}} />
</View>
<View style={{flex:'1'}}>
<View style={{marginLeft:'24rem'}}>
<Text style={{flex:'6.5',fontSize:'28rem',color:'#ffffff',marginBottom:'10rem'}} >{this.title}</Text>
<Text style={{color:'#ffffff',fontSize:'28rem'}}>{text}到期时间:{this.vipTime}</Text>
</View>
</View>
</View>
<TouchableHighlight style={{borderBottomLeftRadius:'60rem',borderTopLeftRadius:'60rem',backgroundColor:'#FFA003',flexDirection:'row',alignItems:'center'}} onPress={this.contactKf.bind(this,'')}>
<Image source={{uri:'https://q.aiyongbao.com/trade/web/images/qap_img/mobile/ww_white.png'}} style={{width:'30rem',height:'30rem',marginRight:'10rem',marginLeft:'30rem',marginTop:'10rem',marginBottom:'10rem'}} />
<Text style={{color:'#ffffff',fontSize:'26rem',marginRight:'24rem'}}>联系客服</Text>
</TouchableHighlight>
</View>
<View style={styles.orderCard}>
<View style={[styles.ordermgtTitle,{flexDirection:'row',flex:1,alignItems:'center',borderBottomColor:'#CCCCCC',borderBottomWidth:'1rem'}]}>
<Text style={[styles.ordermgtTitleStyle,{flex:1}]}>我的订单</Text>
<TouchableHighlight style={{flexDirection:'row',alignItems:'center'}} onPress={this.goToList.bind(this,'all')}>
<Text style={{fontSize:'24rem',color:'#666666',marginRight:'5rem'}}>查看全部订单</Text>
<Icon style={{alignItems:'center',color:'#C7C7C7'}} name="arrowRight"/>
</TouchableHighlight>
</View>
{/* <TouchableHighlight style={{borderStyle:'solid',borderWidth:'2rem',borderColor:'#F5F5F5',marginLeft:'24rem',marginRight:'24rem',marginTop:'15rem',flexDirection:'row',alignItems:'center'}} onPress={()=>{GoToView({title:'订单搜索',status:'TradeListSearchPage'});}}>
<Image source={{uri:'//q.aiyongbao.com/trade/web/images/qap_img/mobile/ss.png'}} style={{width:'40rem',height:'40rem',marginRight:'10rem',marginLeft:'10rem',marginTop:'10rem',marginBottom:'10rem'}} />
<Text style={{color:'#999999',fontSize:'26rem'}}>搜索你要的订单</Text>
</TouchableHighlight> */}
<View style={styles.ordermgt}>
<TouchableHighlight style={{flex:1}} onPress={this.goToList.bind(this,'dfk')}>
<IndexIcon title="待付款" num={this.state.waitPayNum} pic_url="//q.aiyongbao.com/trade/web/images/qap_img/mobile/daifk.png"></IndexIcon>
</TouchableHighlight>
<TouchableHighlight style={{flex:1}} onPress={this.goToList.bind(this,'dfh')}>
<IndexIcon title="待发货" num={this.state.waitSendNum} pic_url="//q.aiyongbao.com/trade/web/images/qap_img/mobile/daifh.png"></IndexIcon>
</TouchableHighlight>
<TouchableHighlight style={{flex:1}} onPress={this.goToList.bind(this,'yfh')}>
<IndexIcon title="已发货" num={this.state.SendToNum} pic_url="//q.aiyongbao.com/trade/web/images/qap_img/mobile/yifh.png"></IndexIcon>
</TouchableHighlight>
<TouchableHighlight style={{flex:1}} onPress={this.goToList.bind(this,'tkz')}>
<IndexIcon title="退款中" num={this.state.refundNum} pic_url="//q.aiyongbao.com/trade/web/images/qap_img/mobile/daitk.png"></IndexIcon>
</TouchableHighlight>
<TouchableHighlight style={{flex:1}} onPress={this.goToList.bind(this,'dpj')}>
<IndexIcon title="待评价" num={this.state.waitEvaNum} pic_url="//q.aiyongbao.com/trade/web/images/qap_img/mobile/daipj.png"></IndexIcon>
</TouchableHighlight>
</View>
</View>
{this.renderBannerAD()}
{this.renderModalAD()}
{
this.renderTools()
}
<View style={[styles.vipCard,{marginBottom:'20rem'}]}>
<View style={styles.ordermgtTitle}><Text style={styles.ordermgtTitleStyle}>常用设置</Text></View>
<View style={styles.ordermgt}>
<TouchableHighlight style={{flex:1}} onPress={this.goToMy.bind(this,'my')}>
<IndexIcon status="mgt" title="默认物流" pic_url="//q.aiyongbao.com/trade/web/images/qap_img/mobile/mrwl.png"></IndexIcon>
</TouchableHighlight>
<TouchableHighlight style={{flex:1}} onPress={this.GoToView.bind(this,'DefaultAddressPage')}>
<IndexIcon status="mgt" title="地址库" pic_url="//q.aiyongbao.com/trade/web/images/qap_img/mobile/dzk.png"></IndexIcon>
</TouchableHighlight>
<TouchableHighlight style={{flex:1}} onPress={this.goToMy.bind(this,'my')}>
<IndexIcon status="mgt" title="常用短语" pic_url="//q.aiyongbao.com/trade/web/images/qap_img/mobile/cydy.png"></IndexIcon>
</TouchableHighlight>
<TouchableHighlight style={{flex:1}} onPress={this.webauth.bind(this)}>
<IndexIcon status="mgt" title="重新授权" pic_url="//q.aiyongbao.com/trade/web/images/qap_img/mobile/cxsq.png"></IndexIcon>
</TouchableHighlight>
</View>
{/* <View style={styles.ordermgt}>
<TouchableHighlight style={{flex:1}} onPress={this.ClearStorage.bind(this)}>
<IndexIcon status="mgt" title="清除缓存" pic_url="//q.aiyongbao.com/trade/web/images/qap_img/mobile/qchc.png"></IndexIcon>
</TouchableHighlight>
<TouchableHighlight style={{flex:1}} onPress={this.GoToView.bind(this,'OrderBlank')}>
<IndexIcon status="mgt" title="电台提醒" pic_url="//q.aiyongbao.com/trade/web/images/qap_img/mobile/jhd.png"></IndexIcon>
</TouchableHighlight>
<TouchableHighlight style={{flex:1}}>
<Link href="tbsellerplatform://?session_event=event_back_platform&module=module_setting&sub_module=submodule_setting_feedback&service_id=issueSource%3D21085840">
<IndexIcon status="mgt" title="意见反馈" pic_url="//q.aiyongbao.com/trade/web/images/qap_img/mobile/yjfk.png"></IndexIcon>
</Link>
</TouchableHighlight>
<TouchableHighlight style={{flex:1}} onPress={this.contactKf.bind(this,'')}>
<IndexIcon status="mgt" title="联系客服" pic_url="//q.aiyongbao.com/trade/web/images/qap_img/mobile/lxkf.png"></IndexIcon>
</TouchableHighlight>
<View style={{flex:1}}>
<View style={styles.ordermgtLabelNull}>
</View>
</View>
</View> */}
</View>
</ScrollView>
);
}
}
export default TradeIndex;
<file_sep>/Biz/User/UserSubscribe.jsx
/**
* @author shitou
*/
import QN from 'QAP-SDK';
//获取用户订购关系
let default_query={
method: "taobao.vas.subscribe.get",
article_code: "FW_GOODS-1827490"
};
var UserSubscribe= function({query=default_query,usernick=undefined,callback,error_callback=undefined}){
if (usernick == undefined) {
QN.user.getInfo({
success(result) {
query.nick = result.data.user_nick;
QN.top.invoke({
query: query
}).then((result) => {
//取得回调
// console.log(callback);
callback(result.data);
}, (error) => {
if(error_callback){
error_callback(error);
}
});
},
error(error) {
// console.error(error);
}
});
}else{
query.nick = usernick;
QN.top.invoke({
query: query
}).then((result) => {
//取得回调
// console.log(callback);
callback(result.data);
}, (error) => {
if(error_callback){
error_callback(error);
}
});
}
}
export {UserSubscribe};
<file_sep>/MyFamily.jsx
/**
* @author wp
*/
import { Modal,Link,Button,Text, View,Image,TouchableHighlight,Tabbar, Icon, Iconfont,ScrollView} from 'nuke';
import {createElement, Component,render} from 'rax';
import QN from 'QAP-SDK';
import Messagecard from 'Component/Common/Messagecard.jsx';
class MyFamily extends Component{
constructor() {
super();
}
render(){
let vip1 = '高级版';
let vip2 = '高级版';
let card1;
let card2;
let time = this.props.data[1];
let tabContent={
height:'9600rem',
flex:1
}
if(this.props.vipFlag1 == 0){
vip1 = '初级版'
}
if(this.props.vipFlag2 == 0){
vip2 = '初级版';
time = '0';
}
if(this.props.vipFlag1 == 0&& this.props.vipFlag2 == 0){
card1=(<Messagecard count={true} type={1} img_source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/ayjy.png'}} img_source2={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/aysp.png'}} price = {40}
></Messagecard>);
tabContent={
height:'10000rem',
flex:1
}
}
if(this.props.vipFlag1 == 0&& this.props.vipFlag2 == 0 && this.props.data[2] == 0){
card2=(<Messagecard count={true} type={2} img_source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/ayjy.png'}} img_source2={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/aysp.png'}} img_source3={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/cx.png'}} price = {50}
></Messagecard>);
tabContent={
height:'10400rem',
flex:1
}
}
return (
<ScrollView style={tabContent}>
<Messagecard num="21085840" img_source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/ayjy.png'}} mainTitle="爱用交易——轻松管理订单"
middleTitle={vip1} time={this.props.data[0]} subTitle="功能介绍:自动评价、差评师防御、打印发货(pc)" style={{borderBottomWidth:'0rem'}} index={true} url="https://fuwu.taobao.com/ser/detail.htm?service_code=FW_GOODS-1827490&tracelog=other_serv"></Messagecard>
<Messagecard num="21085832" img_source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/aysp.png'}} mainTitle="爱用商品——卖家引流必备"
middleTitle={vip2} time={this.props.data[1]} subTitle="功能介绍:生成手机详情、自动上下架、标题优化" style={{borderBottomWidth:'0rem'}} url="https://fuwu.taobao.com/ser/detail.htm?service_code=FW_GOODS-1828810&tracelog=other_serv"></Messagecard>
{card1}
<Messagecard num="21341952" img_source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/aycx.png'}} mainTitle="爱用促销——专注打折"
middleTitle={"高级版"} time={this.props.data[2]} subTitle="功能介绍:新品上市、节日促销、会员营销" style={{borderBottomWidth:'0rem'}} url="https://fuwu.taobao.com/ser/detail.htm?service_code=FW_GOODS-1834215&tracelog=other_serv"></Messagecard>
{card2}
<Messagecard num="21454779" img_source={{uri: '//q.aiyongbao.com/trade/web/images/qap_img/mobile/aygx.png'}} mainTitle="爱用供销——1688提供好货源"
middleTitle={"高级版"} time={this.props.data[4]} subTitle="功能介绍:智能推荐好货源、管理采购单" style={{borderBottomWidth:'0rem'}} url="https://fuwu.taobao.com/ser/detail.htm?service_code=FW_GOODS-1856541&tracelog=other_serv"></Messagecard>
<Messagecard num="21596755" img_source={{uri: 'https://q.aiyongbao.com/trade/web/images/qap_img/mobile/aysj.png'}} mainTitle="爱用数据——您的流量管家"
middleTitle={"高级版"} time={this.props.data[3]} subTitle="功能介绍:实时掌握店铺数据动态" style={{borderBottomWidth:'0rem'}} url="https://fuwu.taobao.com/ser/detail.htm?service_code=FW_GOODS-1887064&tracelog=other_serv" ></Messagecard>
</ScrollView>
)
}
}
export default MyFamily;
<file_sep>/Component/OrderCard/LogisticsBlock.jsx
/**
* @author moorwu
*/
import {createElement, Component,render} from 'rax';
import { View, Text} from 'nuke';
import {QueryLogisticsTrace,GetLogistics} from 'Biz/Order/logistics.jsx';
class LogisticsBlock extends Component{
constructor(){
super();
this.state={
logistics:undefined,
tid:-1
};
}
renderTrace(status,time){
let jsx=[];
jsx.push( <Text style={{fontSize:'28rem',color:'#25ae5f',lineHeight:'34rem',lines:'2',width:'650rem'}}>{status}</Text>);
if(time!='')
jsx.push(<Text style={{fontSize:'28rem',color:'#25ae5f',lineHeight:'34rem'}}>{time}</Text>)
return jsx;
}
renderLogisticsCompany(){
// console.log(this.state.tid);
// console.error(this.state.logistics);
if(this.state.logistics.tid==0){
if(this.props.card && this.props.card.refs.bb)
this.props.card.refs.bb.setState({isShow:false});
return '无需物流'
}else{
if (this.state.logistics.company_name != undefined) {
return this.state.logistics.company_name+' '+this.state.logistics.out_sid
} else {
return '其他 '+this.state.logistics.out_sid
}
}
}
render(){
const order=this.props.dataSource;
const self=this;
if(this.state.logistics==undefined){
//调用物流接口来
let tid=order.tid;
if(tid=='15529502116020200'){
console.log('kaka');
}
let seller_nick=order.seller_nick;
GetLogistics({tid:tid,callback:(result)=>{
// console.log('GetLogistics');
// console.log(result);
if(!result.shippings.shipping||result.shippings.shipping.tid==0){
let logistics={};
this.setState({tid:0,logistics:logistics});
return;
}
let oids=[];
this.company='其他';
for(var index in result.shippings.shipping){
oids.push(result.shippings.shipping[index].sub_tids.number[0]);
if(index==0){
this.company=result.shippings.shipping[index].company_name;
}
}
//这里开始调用追踪信息
let oid=undefined;
if(oids.length>1){
oid=oids[oids.length-1];
}
QueryLogisticsTrace({
tid:tid,
seller_nick:seller_nick,
oid:oid,
callback:(result)=>{
// console.log(result);
result.company_name=this.company;
self.setState({logistics:result});
},
error_callback:(error)=>{
console.error(tid+' '+oid);
console.error(error);
}
});
}
});
return;
}
let status=undefined;
let time=undefined;
if(this.state.logistics.trace_list==undefined){
status='暂无物流信息';
time='';
}else{
let index=this.state.logistics.trace_list.transit_step_info.length-1;
// console.log(index)
// console.log(this.state.logistics.trace_list.transit_step_info[index].status_desc)
//
// console.log(this.state.logistics.trace_list.transit_step_info[index].status_time)
if(this.state.logistics.trace_list.transit_step_info[index].status_desc==undefined || this.state.logistics.trace_list.transit_step_info[index].status_desc==''){
this.state.logistics.trace_list.transit_step_info[index].status_desc='暂无物流信息';
this.state.logistics.trace_list.transit_step_info[index].status_time='';
}
status=this.state.logistics.trace_list.transit_step_info[index].status_desc;
time=this.state.logistics.trace_list.transit_step_info[index].status_time;
}
return (
<View style={[orderStyles.AddressContainer]}>
<View>
<Text style={{fontSize:'28rem',color:'#3d4145',lineHeight:'34rem'}}>{this.renderLogisticsCompany()}</Text>
</View>
<View style={{flexDirection:'row'}}>
<View style={{width:'30rem',justifyContent:'flex-start'}}>
<Text style={{color:'#25ae5f'}}>●</Text>
</View>
<View style={{flex:1,marginLeft:'10rem',marginRight:'24rem'}}>
{this.renderTrace(status,time)}
</View>
</View>
</View>
);
}
}
const orderStyles={
AddressContainer:{
flexDirection:'column',
borderColor:'#dfdfe5',
justifyContent: 'flex-start',
alignItems:'flex-start',
marginTop:'20rem',
marginLeft:'24rem',
marginRight:'24rem',
paddingBottom:'20rem',
flexWrap:'wrap',
flex:1
},
order_address_block:{
fontSize:'28rem',
lines:'2',
lineHeight:'34rem',
color:'#3D4145'
},
mobile_color:{
color:'#1d8cff'
}
}
export default LogisticsBlock;
<file_sep>/Component/Common/VipButton.jsx
/**
* 付费按钮组件
* @author viper
*/
import QN from 'QAP-SDK';
import {Button,View, Image,Env} from 'nuke';
import {createElement, Component,render} from 'rax';
import { Network } from 'Component/Common/Network.jsx';
import MyButton from 'Component/Common/MyButton.jsx';
import { GoToView } from '../../Biz/View/GoToView.jsx';
const { isWeex, isWeb, isQNWeb , isQNWeex , appInfo } = Env;
class VipButton extends Component{
constructor(){
super();
this.state={
status:''
}
}
GoToView(value){
let yyJson = this.props.data.content;
let name = this.props.data.name;
// let bid = this.props.data.bid;
let feature=this.props.data.feature;
console.log("this is feature:",feature);
let query = {xfrom:name,feature:feature};
QN.localstore.set({
query: {
advertisment: yyJson
},
success(result) {
},
error(error) {
// console.log(error);
}
}).then(result => {
GoToView({status:'VipAd',query:query});
}, error => {
// console.log(error);
});
}
render(){
let customStyle=this.props.style?this.props.style:{};
let name = this.props.data.name;
let vip = this.props.data.isVip;
/*let status = this.props.data.status;*/
let appInfo_JSON = QN.uri.parseQueryString(appInfo);
if(vip == '1'){
return(
<View style={{marginTop:'20rem',marginBottom:'20rem'}}>
<MyButton style={customStyle} size='medium' onPress={this.props.onPress} text={name}></MyButton>
</View>
);
}
else {
let gaoji_flag="//q.aiyongbao.com/trade/web/images/qap_img/mobile/payflag.png";
if(appInfo_JSON.platform != 'android') {
gaoji_flag="//q.aiyongbao.com/trade/web/images/qap_img/mobile/gjc.png";
}
return(
<View style={{height:'100rem',alignItems:'center',justifyContent:'center',marginTop:'10rem',marginBottom:'10rem'}}>
<MyButton style={customStyle} size='medium' onPress={this.GoToView.bind(this,'VipAd')} text={name}></MyButton>
<View style={{right:'-15rem',top:'5rem',position:'absolute'}}>
<Image source={{uri: gaoji_flag}} style={{width:'60rem',height:'30rem',marginLeft:'24rem',marginRight:'24rem'}} />
</View>
</View>
);
}
// <View style={{marginRight:'-5rem',alignSelf:'center'},customStyle}>
// <MyButton style={customStyle} size='medium' onPress={this.GoToView.bind(this,'VipAd')} style={{color:'red',margin:'20rem'}} text={name}></MyButton>
// <View style={[styles.container,{right:'-15rem',top:'10rem',position:'absolute'}]}>
// <Image source={{uri: gaoji_flag}} style={{width:'60rem',height:'30rem',marginLeft:'24rem',marginRight:'24rem'}} />
// </View>
// </View>
}
}
const styles={
container:{
alignItems:'center',
justifyContent: 'center'
}
}
export default VipButton;
<file_sep>/index.jsx
/** @jsx createElement */
import { Tabbar ,Modal,Icon,View, Text,Util,richtext,TouchableHighlight,Env} from 'nuke';
import {createElement, Component,render} from 'rax';
import QN from 'QAP-SDK';
import TradeListView from './TradeListView.jsx';
import TradeData from './TradeData.jsx';
import TradeIndex from './TradeIndex.jsx';
import MyTrade from './MyTrade.jsx';
import {UserSubscribe} from './Biz/User/UserSubscribe.jsx';
import {GetUserType} from './Biz/User/GetUserType.jsx';
import {Network} from 'Component/Common/Network.jsx';
import {StorageOper} from './Biz/View/StorageOper.jsx';
import {IsEmpty} from './Biz/View/IsEmpty.jsx';
import {PUBLIC} from './rxscss/public-style.jsx';
import {DoBeacon} from 'Biz/Common.jsx';
import {GoToView} from './Biz/View/GoToView.jsx';
const Location = Util.Location;
const { isWeex, isWeb, isQNWeb , isQNWeex , appInfo } = Env;
const appInfo_JSON = QN.uri.parseQueryString(appInfo);
class TradeTop extends Component {
constructor(props) {
super(props);
this.state = {
selectedTab: 'indexTab',
notifCount: 3,
presses: 0,
key: {key: 'loading'},
tabKey:'dfh',
flag:true,
notifCount: 0,
index:2,
active:0,
isRender: false
};
this.userNick = "";
this.vipFlag = "";
this.vipTime = "";
this.avatar = "";
this.sub_user_nick = "";
this.userType = "";
this.title = "";
this.flag = false;
this.isGoToList = false;
this.pressBack = undefined;
//作为入口页面的存储
this.homeIndex='index';
}
componentWillMount(){
let self = this;
QN.navigator.setSwipeBack({
query: {enable: false},
success(result) {
},
error(error) {
}
}).then(result => {
}, error => {
});
QN.navigator.setTitle({
query: {
title: '爱用交易'
}
}).then(result => {
self.removeMenu();
StorageOper.sessionRemove({
key:'user_nick,avatar,user_id,sub_user_nick,sub_user_id'
});
self.syncUserInfo();
}, error => {
// console.error(error);
});
QN.on('page.isShowSlider', (data) => {
// console.log(data);
self.isShowSlider = data.isShow;
});
QN.on('page.back', function(data) {
// 进行一些处理
if (self.state.key.key != 'index') {
if(self.state.key.key == 'order'){
if (self.isShowSlider) {
} else {
self.changeTabStatus('index','');
self.removeMenu();
self.addMenu('pay');
}
}else{
self.changeTabStatus('index','');
self.removeMenu();
self.addMenu('pay');
}
} else {
QN.navigator.pop();
// if (self.pressBack != undefined) {
// if (new Date()-self.pressBack > 2000) {
// self.pressBack = new Date();
// Modal.toast('再按一次退出爱用交易');
// } else {
// self.pressBack = undefined;
// QN.navigator.pop();
// }
// } else {
// self.pressBack = new Date();
// Modal.toast('再按一次退出爱用交易');
// }
}
});
//添加搜索弹框
QN.on('page.search',(reuslt)=>{
//打开搜索页面
GoToView({title:'订单搜索',status:'TradeListSearchPage'});
});
QN.on('page.paymoney',(reuslt)=>{
/*if(this.vipFlag == 1){
DoBeacon('0614shengjiandroidivp','index',this.userNick);
}*/
if(appInfo_JSON.platform=="iOS"){
if(this.vipFlag == 1){
DoBeacon('0614shengjiiosivp','renew',this.userNick);
}else{
DoBeacon('0614shengjiaiosf','update',this.userNick);
}
}else{
if(this.vipFlag == 1){
DoBeacon('0614shengjiandroidivp','renew',this.userNick);
}else{
DoBeacon('0614shengjiandroidf','update',this.userNick);
}
}
GoToView({title:'爱用交易',status:'UpdatePage',query:{userNick:encodeURI(this.userNick), vipFlag:this.vipFlag}});
});
}
/**
* 同步用户
*/
syncUserInfo(){
var self = this;
QN.user.getInfo({
success(result) {
self.userNick = result.data.user_nick;
self.avatar = result.data.avatar;
self.user_id = result.data.user_id+"";
self.sub_user_nick = result.data.sub_user_nick;
if (self.sub_user_nick == undefined) {
self.sub_user_nick = "";
}
self.sub_user_id = result.data.sub_user_id+"";
let query = {
'user_nick' : self.userNick,
'avatar' : result.data.avatar,
'user_id' : result.data.user_id+"",
'sub_user_nick' : result.data.sub_user_nick,
'sub_user_id' : result.data.sub_user_id+""
};
// //设置session
// Network.Post('/trade/syncsso',{user_nick: self.userNick},(data)=>{
// });
StorageOper.sessionSet({
query:query,
callback:(result)=>{
// console.log(result);
}
});
let ccc = {};
Network.Post("/jy2/ccc",{user_nick: self.userNick},(data)=>{
ccc['ipCheck_'+self.userNick] = data;
self.ipCheck = data;
StorageOper.localSet({
query:ccc,
callback:(result)=>{
// console.log(result);
}
});
StorageOper.localGet({
key:'user_info_time'+self.userNick+',vipFlag_'+self.userNick+',vipTime_'+self.userNick+',userType_'+self.userNick+',title_'+self.userNick,
callback:(result)=>{
// console.log(result);
var date = new Date().toLocaleDateString();
var user_info_time = result['user_info_time'+self.userNick];
let query = {};
query['user_info_time'+self.userNick] = date;
if (user_info_time) {
let vip=result['vipFlag_'+self.userNick];
if (date != user_info_time || vip==undefined || vip=='' || vip=='0' || vip==0) {
StorageOper.localSet({query:query});
self.saveUserInfo();
}else{ // 当天用户重复登录 titleButton显示
self.vipFlag = result['vipFlag_'+self.userNick];
console.log(self.vipFlag);
self.vipTime = result['vipTime_'+self.userNick];
self.userType = result['userType_'+self.userNick];
self.title = result['title_'+self.userNick];
self.userInfo = {
'user_nick' : self.userNick,
'avatar' : self.avatar,
'user_id' :self.user_id,
'sub_user_nick' :self.sub_user_nick,
'sub_user_id' :self.sub_user_id,
'vipFlag' : self.vipFlag,
'vipTime' : self.vipTime,
'userType' : self.userType,
'title' : self.title,
};
if (!self.flag) {
self.addMenu('pay');
}else{
self.addMenu('search');
}
//设置session
self.syncsso();
}
}else{
StorageOper.localSet({query:query});
self.saveUserInfo();
}
},
errCallback:(result)=>{ //取不到缓存会走error
// console.log(result);
var date = new Date().toLocaleDateString();
var user_info_time = result;
let query = {};
query['user_info_time'+self.userNick] = date;
StorageOper.localSet({query:query});
self.saveUserInfo();
}
});
},{mode: 'jsonp'},()=>{
ccc['ipCheck_'+self.userNick] = 2;
self.ipCheck = data;
StorageOper.localSet({
query:ccc,
callback:(result)=>{
// console.log(result);
}
});
StorageOper.localGet({
key:'user_info_time'+self.userNick+',vipFlag_'+self.userNick+',vipTime_'+self.userNick+',userType_'+self.userNick,
callback:(result)=>{
// console.log(result);
var date = new Date().toLocaleDateString();
var user_info_time = result['user_info_time'+self.userNick];
let query = {};
query['user_info_time'+self.userNick] = date;
if (user_info_time) {
if (date != user_info_time) {
StorageOper.localSet({query:query});
self.saveUserInfo();
}else{ // 当天用户重复登录 titleButton显示
self.vipFlag = result['vipFlag_'+self.userNick];
self.vipTime = result['vipTime_'+self.userNick];
self.userType = result['userType_'+self.userNick];
self.userInfo = {
'user_nick' : self.userNick,
'avatar' : self.avatar,
'user_id' :self.user_id,
'sub_user_nick' :self.sub_user_nick,
'sub_user_id' :self.sub_user_id,
'vipFlag' : self.vipFlag,
'vipTime' : self.vipTime,
'userType' : self.userType
};
if (!self.flag) {
self.addMenu('pay');
}else{
self.addMenu('search');
}
//设置session
self.syncsso();
}
}else{
StorageOper.localSet({query:query});
self.saveUserInfo();
}
},
errCallback:(result)=>{ //取不到缓存会走error
// console.log(result);
var date = new Date().toLocaleDateString();
var user_info_time = result;
let query = {};
query['user_info_time'+self.userNick] = date;
StorageOper.localSet({query:query});
self.saveUserInfo();
}
});
});
DoBeacon('TD20170114090141','index',self.userNick);
},
error(error) {
// console.error(error);
}
});
}
saveUserInfo(){
var self = this;
Network.Post('/jy/getArea',{},(data)=>{
// console.log(data);
if(IsEmpty(data)) {return;}
let ccc = {};
ccc['areas'] = JSON.stringify(data);
StorageOper.localSet({
query:ccc,
callback:(result)=>{
// console.log(result);
}
});
},{mode: 'json'});
UserSubscribe({
usernick:self.userNick,
callback: (result)=>{
var subscribes = result.vas_subscribe_get_response;
if (subscribes && subscribes.article_user_subscribes && subscribes.article_user_subscribes.article_user_subscribe) {
var vipTime = subscribes.article_user_subscribes.article_user_subscribe[0].deadline;
var vipFlag = subscribes.article_user_subscribes.article_user_subscribe[0].item_code;
if (vipFlag == 'FW_GOODS-1827490-v2') {
vipFlag = 1;
}else{
vipFlag = 0;
}
self.vipFlag = vipFlag;
self.vipTime = /\d{4}-\d{1,2}-\d{1,2}/g.exec(vipTime)[0];
}else{
self.vipFlag = 0;
self.vipTime = 0;
}
GetUserType({
callback:(result)=>{
self.userType=result.user_seller_get_response.user.type;
if(self.sub_user_id == 'undefined'){
let member_query = {
method:'alibaba.open.convertmemberidsbyloginids',
login_ids:self.userNick
};
// 查询 memberid
QN.top.invoke({
query: member_query
}).then((result) => {
let member_id = JSON.parse(result.data.alibaba_open_convertmemberidsbyloginids_response.member_id_map)[self.userNick];
QN.top.invoke({
query: {
method: "taobao.shop.get",
nick: self.userNick,
fields:"title"
}
}).then((rsp) => {
self.title = rsp.data.shop_get_response.shop.title
self.userInfo = {
'user_nick' : self.userNick,
'avatar' : self.avatar,
'user_id' :self.user_id,
'sub_user_nick' :self.sub_user_nick,
'sub_user_id' :self.sub_user_id,
'vipFlag' : self.vipFlag,
'vipTime' : self.vipTime,
'userType' : self.userType,
'title' : self.title,
'member_id' : member_id
};
let userAppInfo = QN.uri.toQueryString(appInfo);
let query = {};
query['vipFlag_'+self.userNick] = self.vipFlag+"";
query['vipTime_'+self.userNick] = self.vipTime+"";
query['userType_'+self.userNick] = self.userType+"";
query['appInfo_'+self.userNick] = userAppInfo;
query['title_'+self.userNick] = self.title+'';
StorageOper.localSet({
query:query,
callback:(result)=>{
// console.log(result);
}
});
self.addMenu('pay');
//设置session
self.syncsso();
}, (error) => {
self.title = self.userNick;
self.userInfo = {
'user_nick' : self.userNick,
'avatar' : self.avatar,
'user_id' :self.user_id,
'sub_user_nick' :self.sub_user_nick,
'sub_user_id' :self.sub_user_id,
'vipFlag' : self.vipFlag,
'vipTime' : self.vipTime,
'userType' : self.userType,
'title' : self.title,
'member_id' : member_id
};
let userAppInfo = QN.uri.toQueryString(appInfo);
let query = {};
query['vipFlag_'+self.userNick] = self.vipFlag+"";
query['vipTime_'+self.userNick] = self.vipTime+"";
query['userType_'+self.userNick] = self.userType+"";
query['appInfo_'+self.userNick] = userAppInfo;
query['title_'+self.userNick] = self.title+'';
StorageOper.localSet({
query:query,
callback:(result)=>{
// console.log(result);
}
});
self.addMenu('pay');
//设置session
self.syncsso();
});
},(error) =>{
//console.log(error);
})
}else {
QN.top.invoke({
query: {
method: "taobao.shop.get",
nick: self.userNick,
fields:"title"
}
}).then((rsp) => {
self.title = rsp.data.shop_get_response.shop.title
self.userInfo = {
'user_nick' : self.userNick,
'avatar' : self.avatar,
'user_id' :self.user_id,
'sub_user_nick' :self.sub_user_nick,
'sub_user_id' :self.sub_user_id,
'vipFlag' : self.vipFlag,
'vipTime' : self.vipTime,
'userType' : self.userType,
'title' : self.title,
'member_id' : 'none'
};
let userAppInfo = QN.uri.toQueryString(appInfo);
let query = {};
query['vipFlag_'+self.userNick] = self.vipFlag+"";
query['vipTime_'+self.userNick] = self.vipTime+"";
query['userType_'+self.userNick] = self.userType+"";
query['appInfo_'+self.userNick] = userAppInfo;
query['title_'+self.userNick] = self.title+'';
StorageOper.localSet({
query:query,
callback:(result)=>{
// console.log(result);
}
});
self.addMenu('pay');
//设置session
self.syncsso();
}, (error) => {
self.title = self.userNick;
self.userInfo = {
'user_nick' : self.userNick,
'avatar' : self.avatar,
'user_id' :self.user_id,
'sub_user_nick' :self.sub_user_nick,
'sub_user_id' :self.sub_user_id,
'vipFlag' : self.vipFlag,
'vipTime' : self.vipTime,
'userType' : self.userType,
'title' : self.title,
'member_id' : 'none'
};
let userAppInfo = QN.uri.toQueryString(appInfo);
let query = {};
query['vipFlag_'+self.userNick] = self.vipFlag+"";
query['vipTime_'+self.userNick] = self.vipTime+"";
query['userType_'+self.userNick] = self.userType+"";
query['appInfo_'+self.userNick] = userAppInfo;
query['title_'+self.userNick] = self.title+'';
StorageOper.localSet({
query:query,
callback:(result)=>{
// console.log(result);
}
});
self.addMenu('pay');
//设置session
self.syncsso();
});
}
},
error_callback:(error)=>{
self.userType = 'C';
QN.top.invoke({
query: {
method: "taobao.shop.get",
nick: self.userNick,
fields:"title"
}
}).then((rsp) => {
self.title = rsp.data.shop_get_response.shop.title
self.userInfo = {
'user_nick' : self.userNick,
'avatar' : self.avatar,
'user_id' :self.user_id,
'sub_user_nick' :self.sub_user_nick,
'sub_user_id' :self.sub_user_id,
'vipFlag' : self.vipFlag,
'vipTime' : self.vipTime,
'userType' : self.userType,
'title' : self.title
};
let userAppInfo = QN.uri.toQueryString(appInfo);
let query = {};
query['vipFlag_'+self.userNick] = self.vipFlag+"";
query['vipTime_'+self.userNick] = self.vipTime+"";
query['userType_'+self.userNick] = self.userType+"";
query['appInfo_'+self.userNick] = userAppInfo;
query['title_'+self.userNick] = self.title+'';
StorageOper.localSet({
query:query,
callback:(result)=>{
// console.log(result);
}
});
self.addMenu('pay');
//设置session
self.syncsso();
},(error) => {
self.title = self.userNick;
self.userInfo = {
'user_nick' : self.userNick,
'avatar' : self.avatar,
'user_id' :self.user_id,
'sub_user_nick' :self.sub_user_nick,
'sub_user_id' :self.sub_user_id,
'vipFlag' : self.vipFlag,
'vipTime' : self.vipTime,
'userType' : self.userType,
'title' : self.title
};
let userAppInfo = QN.uri.toQueryString(appInfo);
let query = {};
query['vipFlag_'+self.userNick] = self.vipFlag+"";
query['vipTime_'+self.userNick] = self.vipTime+"";
query['userType_'+self.userNick] = self.userType+"";
query['appInfo_'+self.userNick] = userAppInfo;
query['title_'+self.userNick] = self.title+'';
StorageOper.localSet({
query:query,
callback:(result)=>{
// console.log(result);
}
});
self.addMenu('pay');
//设置session
self.syncsso();
});
}
});
},
error_callback:(error)=>{
self.vipFlag = 0;
self.vipTime = 0;
GetUserType({
callback:(result)=>{
self.userType=result.user_seller_get_response.user.type;
QN.top.invoke({
query: {
method: "taobao.shop.get",
nick: self.userNick,
fields:"title"
}
}).then((rsp) => {
self.title = rsp.data.shop_get_response.shop.title
self.userInfo = {
'user_nick' : self.userNick,
'avatar' : self.avatar,
'user_id' :self.user_id,
'sub_user_nick' :self.sub_user_nick,
'sub_user_id' :self.sub_user_id,
'vipFlag' : self.vipFlag,
'vipTime' : self.vipTime,
'userType' : self.userType,
'title' : self.title
};
let userAppInfo = QN.uri.toQueryString(appInfo);
let query = {};
query['vipFlag_'+self.userNick] = self.vipFlag+"";
query['vipTime_'+self.userNick] = self.vipTime+"";
query['userType_'+self.userNick] = self.userType+"";
query['appInfo_'+self.userNick] = userAppInfo;
query['title_'+self.userNick] = self.title+'';
StorageOper.localSet({
query:query,
callback:(result)=>{
// console.log(result);
}
});
self.addMenu('pay');
//设置session
self.syncsso();
}, (error) => {
self.title = self.userNick;
self.userInfo = {
'user_nick' : self.userNick,
'avatar' : self.avatar,
'user_id' :self.user_id,
'sub_user_nick' :self.sub_user_nick,
'sub_user_id' :self.sub_user_id,
'vipFlag' : self.vipFlag,
'vipTime' : self.vipTime,
'userType' : self.userType,
'title' : self.title
};
let userAppInfo = QN.uri.toQueryString(appInfo);
let query = {};
query['vipFlag_'+self.userNick] = self.vipFlag+"";
query['vipTime_'+self.userNick] = self.vipTime+"";
query['userType_'+self.userNick] = self.userType+"";
query['appInfo_'+self.userNick] = userAppInfo;
query['title_'+self.userNick] = self.title+'';
StorageOper.localSet({
query:query,
callback:(result)=>{
// console.log(result);
}
});
self.addMenu('pay');
//设置session
self.syncsso();
});
},
error_callback:(error)=>{
self.userType = 'C';
QN.top.invoke({
query: {
method: "taobao.shop.get",
nick: self.userNick,
fields:"title"
}
}).then((rsp) => {
self.title = rsp.data.shop_get_response.shop.title
self.userInfo = {
'user_nick' : self.userNick,
'avatar' : self.avatar,
'user_id' :self.user_id,
'sub_user_nick' :self.sub_user_nick,
'sub_user_id' :self.sub_user_id,
'vipFlag' : self.vipFlag,
'vipTime' : self.vipTime,
'userType' : self.userType,
'title' : self.title
};
let userAppInfo = QN.uri.toQueryString(appInfo);
let query = {};
query['vipFlag_'+self.userNick] = self.vipFlag+"";
query['vipTime_'+self.userNick] = self.vipTime+"";
query['userType_'+self.userNick] = self.userType+"";
query['appInfo_'+self.userNick] = userAppInfo;
query['title_'+self.userNick] = self.title+'';
StorageOper.localSet({
query:query,
callback:(result)=>{
// console.log(result);
}
});
self.addMenu('pay');
//设置session
self.syncsso();
}, (error) => {
self.title = self.userNick;
self.userInfo = {
'user_nick' : self.userNick,
'avatar' : self.avatar,
'user_id' :self.user_id,
'sub_user_nick' :self.sub_user_nick,
'sub_user_id' :self.sub_user_id,
'vipFlag' : self.vipFlag,
'vipTime' : self.vipTime,
'userType' : self.userType,
'title' : self.title
};
let userAppInfo = QN.uri.toQueryString(appInfo);
let query = {};
query['vipFlag_'+self.userNick] = self.vipFlag+"";
query['vipTime_'+self.userNick] = self.vipTime+"";
query['userType_'+self.userNick] = self.userType+"";
query['appInfo_'+self.userNick] = userAppInfo;
query['title_'+self.userNick] = self.title+'';
StorageOper.localSet({
query:query,
callback:(result)=>{
// console.log(result);
}
});
self.addMenu('pay');
//设置session
self.syncsso();
});
}
});
}
});
}
/**
* syncsso
*/
syncsso(){
let self = this;
Network.Post('/trade/syncsso',{user_nick: self.userNick,vip:self.vipFlag,device:appInfo_JSON.platform,h:self.ipCheck},(data)=>{
let now=new Date();
// data = self.analyseJson(data);
// ccc['ads_'+self.userNick] = JSON.stringify(data) ;
let datas = {};
datas.usertype=self.ipCheck;
datas.vipflag=self.vipFlag;
datas.imei=self.user_id;
datas['home']=self.homeIndex;
datas.subusernick=self.sub_user_nick?self.sub_user_nick:self.userNick;
StorageOper.localSet({ // 存入缓存 显示banner
query:datas,
callback:(result)=>{
self.setState({
isRender: true
})
}
});
});
}
/**
* 解析广告的json数据
* author cbl
*/
analyseJson(json){
if(!json){
return;
}
if (json.neeed_refresh) {
if (this.sub_user_nick) {
Modal.alert("您的授权已经失效,请联系主账号登录爱用交易重新授权。",[
{
onPress:()=>{return;},
text:"确定"
}
])
return;
}
let url = "https://oauth.taobao.com/authorize?response_type=code&client_id=" + "21085840" + "&redirect_uri=" + "http://mtrade.aiyongbao.com" + "/tc/trades2?scope=item&view=wap&state=" + "jy" + ",qapmobile&code=trade"
QN.navigator.push({
url: url,
title: '爱用交易',
success(result) {
},
error(error) {
// console.error(error);
}
});
}
}
/**
* 切换tab状态
*/
changeTabStatus(key,tabKey){
this.setState({key: {key: key},tabKey:tabKey,});
}
/**
* 点击下方首页图标从高级功能跳到首页
*/
back(){
this.setState({
flag:true
})
}
/**
* 为列表准备的搜索框,放在这里可以比较轻松的切换状态
*/
onInput(value,e){
this.search_value=value;
}
onSearch(){
if(this.search_value==undefined || this.search_value.replace(/(^\s*)|(\s*$)/g,"")==''){
Modal.alert('请输入查询的内容',[
{
onPress:()=>{},
text:'确定'
}
])
return;
}
this.refs['tradelist'].renewSearchKey(this.search_value);
this.goToList('search');
}
/**
* 移除titlebutton
*/
removeMenu(){
try{
QN.navigator.removeButton({
query: {
tapEvent: 'page.search', // 或 `share`
}}).then(result => {
// console.log(result);
}, error => {
// console.log(error);
});;
}catch(e){
}
try{
QN.navigator.removeButton({
query: {
tapEvent: 'page.paymoney', // 或 `share`
}}).then(result => {
// console.log(result);
}, error => {
// console.log(error);
});
}catch(e){
}
}
/**
* 添加titlebutton
*/
addMenu(type){
if(type=='search'){
QN.navigator.addButton({
query: {
text: '搜索',
iconName: 'search',
// iconImg:'//q.aiyongbao.com/trade/web/images/qap_img/mobile/ss.png',
tapEvent: 'page.search', // 或 `share`
}}).then(result => {
// console.log(result);
}, error => {
// console.log(error);
});
}
else{
if (this.vipFlag == 1) {
QN.navigator.addButton({
query: {
text: '续订',
tapEvent: 'page.paymoney', // 或 `share`
}}).then(result => {
// console.log(result);
}, error => {
// console.log(error);
});
}else if(this.vipFlag == 0){
QN.navigator.addButton({
query: {
text: '升级',
tapEvent: 'page.paymoney', // 或 `share`
}}).then(result => {
// console.log(result);
}, error => {
// console.log(error);
});
}
}
}
/**
* @author Shitou
* 切换tab,根据状态显示内容
*/
renderContent(status) {
switch(status){
case 'index':{
return <TradeIndex ref='tradeIndex' hasHeader={true} index={this} dataFlag={this.state.flag}></TradeIndex>;
}
case 'order':{
return <TradeListView ref='tradelist' index={this} tabKey={this.state.tabKey} onInput={this.onInput.bind(this)} onSearch={this.onSearch.bind(this)}></TradeListView>
}
case 'data':{
return <TradeData index={this} ref='tradeData' tabKey={this.state.tabKey} onInput={this.onInput.bind(this)}></TradeData>
}
case 'my':{
return <MyTrade ref='myTrade' userInfo={this.userInfo} index={this}></MyTrade>;
}
case 'loading':{
return <View style={{flex:1,alignItems:'center',justifyContent:'center'}}><Text style={{fontSize:'28rem',color:'#666666'}}>加载中..</Text></View>;
}
}
}
renderIndexTabBar(status,title,selected_image,common_image){
let jsx=[];
if(status){
jsx.push(<View style={{flex:1,paddingTop:'5rem'}}><Icon src={selected_image} size='large'/><Text style={{color:'#f57745',fontSize:'28rem',marginTop:'5rem',textAlign:'center'}}>{title}</Text></View>);
}else{
jsx.push(<View style={{flex:1,paddingTop:'5rem'}}><Icon src={common_image} size='large'/><Text style={{color:'#333333',fontSize:'28rem',marginTop:'5rem',textAlign:'center'}}>{title}</Text></View>);
}
return jsx;
}
renderTab(status,tabkey){
switch(tabkey){
case 'index':
return this.renderIndexTabBar(status,'首页','//q.aiyongbao.com/trade/web/images/qap_img/mobile/sy_2.png','//q.aiyongbao.com/trade/web/images/qap_img/mobile/sy.png');
case 'order':
return this.renderIndexTabBar(status,'订单','//q.aiyongbao.com/trade/web/images/qap_img/mobile/dd_2.png','//q.aiyongbao.com/trade/web/images/qap_img/mobile/dd.png');
case 'data':
return this.renderIndexTabBar(status,'数据','//q.aiyongbao.com/trade/web/images/qap_img/mobile/sj2.png','//q.aiyongbao.com/trade/web/images/qap_img/mobile/sj1.png');
case 'my':
return this.renderIndexTabBar(status,'我的','//q.aiyongbao.com/trade/web/images/qap_img/mobile/wd_2.png','//q.aiyongbao.com/trade/web/images/qap_img/mobile/wd.png');
}
}
onTabChange(index){
if(index.next=='order'){
this.removeMenu();
this.addMenu('search');
}else{
this.removeMenu();
this.addMenu('pay');
}
//this.setState({active:index});
}
changeTab(index){
// console.log(this);
// console.log(this.refs);
this.refs.TabSlider.slideTo(index);
this.setState({active:index});
}
// render(){
// return(
// <View>
// <Text>66666</Text>
// <TouchableHighlight style={{width:'150rem',height:'100rem',backgroundColor:'#999999'}} onPress={()=>{ GoToView({title:'爱用交易',status:'UpdatePage',query:{userNick:'weiye021', vipFlag:1}}) }}></TouchableHighlight>
// </View>
// )
// }
render() {
let dataContent=this.props.dataContent;
if (!this.state.isRender) {
return;
}
return (
<Tabbar
// iconBar={true} 慎用 会强制限制高度 bug 优先级高
activeKey={this.state.key}
asFramework={true}
itemStyle={{borderTopStyle:'solid',borderTopWidth:"1rem",borderTopColor:PUBLIC.BORDER_COLOR,height:'100rem'}}
onChange={this.onTabChange.bind(this)}
>
<Tabbar.Item
title="首页"
tabKey="index"
onPress={this.back.bind(this)}
//icon={{src:'//q.aiyongbao.com/trade/web/images/qap_img/mobile/sy.png',selected:'//q.aiyongbao.com/trade/web/images/qap_img/mobile/sy_1.png'}}
render={this.renderTab.bind(this)}
>
{this.renderContent('index')}
</Tabbar.Item>
<Tabbar.Item
title="订单"
tabKey="order"
//icon={{src:'//q.aiyongbao.com/trade/web/images/qap_img/mobile/dd.png',selected:'//q.aiyongbao.com/trade/web/images/qap_img/mobile/dd_1.png'}}
render={this.renderTab.bind(this)}
>
{this.renderContent('order')}
</Tabbar.Item>
{/* <Tabbar.Item
title="数据"
tabKey="data"
//icon={{src:'//q.aiyongbao.com/trade/web/images/qap_img/mobile/dd.png',selected:'//q.aiyongbao.com/trade/web/images/qap_img/mobile/dd_1.png'}}
render={this.renderTab.bind(this)}
>
{this.renderContent('data')}
</Tabbar.Item> */}
<Tabbar.Item
title="我的"
tabKey="my"
//icon={{src:'//q.aiyongbao.com/trade/web/images/qap_img/mobile/wd.png',selected:'//q.aiyongbao.com/trade/web/images/qap_img/mobile/wd_1.png'}}
render={this.renderTab.bind(this)}
>
{this.renderContent('my')}
</Tabbar.Item>
</Tabbar>
);
}
componentDidUpdate(prevProps, prevState) {
if (this.isGoToList) {
this.isGoToList = false;
switch(this.tradeStatus){
case 'WAIT_BUYER_PAY':
this.goToList('dfk');
break;
case 'WAIT_SELLER_SEND_GOODS':
this.goToList('dfh');
break;
case 'WAIT_BUYER_CONFIRM_GOODS':
this.goToList('yfh');
break;
case 'TRADE_FINISHED':
this.goToList('success');
break;
case 'TRADE_CLOSED':
this.goToList('close');
break;
case 'TRADE_REFUND':
this.goToList('tkz');
break;
case 'WAIT_BUYER_APPRAISE':
this.goToList('dpj');
break;
default:
this.goToList('all');
break;
}
}
}
componentDidMount() {
//这里开始判断是否是协议注入
let url=document.URL;
let queryStr=url.split('?');
// console.error(queryStr);
// console.error(queryStr instanceof Array);
if((queryStr instanceof Array) && queryStr.length>1){
queryStr=queryStr[1];
let query=QN.uri.parseQueryString(queryStr);
// console.error(query);
let event=query['event'];
if(event=='tradeList'){
this.homeIndex="list";
let tradeStatus=query['tradeStatus'];
// if(tradeStatus=='' || tradeStatus==undefined){
// return;
// }
//
this.flag = true;
this.isGoToList = true;
this.tradeStatus = tradeStatus;
}else if(event=='refundDetail'){
this.homeIndex="detail";
let refundId=query['refundId'];
QN.app.invoke({
api: 'newRefundDetail',
query: {
page:'detail',
refundId: ''+refundId
}
}).then(result => {
}, error => {
// console.log(error);
});
}else if(event=='tradeDetail'||event=='event_tradeDetail'){
this.homeIndex="detail";
let tid=query['tid'];
QN.navigator.push({
url: 'qap:///TradeDetailsPage.js',
query: { tid: tid },
settings: {
animate: true,
request: true,
},
success(result) {
},
error(error) {
}
}).then(result => {
}, error => {});
}else{
this.changeTabStatus('index','');
}
}
}
goToList(status){
this.changeTabStatus('order',status);
this.refs.tradelist.slideTo(status);
this.removeMenu();
this.addMenu('search');
}
goToMy(status){
this.changeTabStatus('my',status);
}
}
const styles = {
tabContent: {
flex: 1,
alignItems: 'center',
},
tabText: {
color: 'white',
margin: 50,
},
container: {
justifyContent: 'flex-start',
alignItems: 'flex-start',
backgroundColor: '#000000'
},
};
render(<TradeTop/>);
| 0be33f4841611a1db57d8ace500bfdaf0add2012 | [
"JavaScript"
] | 30 | JavaScript | SherryPing/qapmasrc | 900b0c51dd1a702e8355b1316f8e1b6f93c2374d | 53afcc1992e98f207b02230313606a3f820a936b |
refs/heads/master | <file_sep>namespace InstaHub.Web.Pages
{
using Nancy;
using Nancy.Security;
public class User : NancyModule
{
public User()
: base("/user")
{
this.RequiresAuthentication();
Get["/"] = Home;
}
private dynamic Home(dynamic parameters)
{
return View["home"];
}
}
}<file_sep>namespace InstaHub.Core.Services
{
using InstaHub.Model.Entities;
using InstaHub.Model.Providers;
using InstaHub.Model.Services;
public class InstragramClientService : BaseService, IInstagramClientService
{
private readonly IInstagramClientProvider _instagramClientProvider;
public InstragramClientService(IInstagramClientProvider instagramClientProvider)
{
_instagramClientProvider = instagramClientProvider;
}
public InstagramClient GetDefault()
{
return _instagramClientProvider.GetDefault();
}
}
}
<file_sep>namespace InstaHub.Core.Services
{
using InstaHub.Model.Entities;
using InstaHub.Model.Providers;
using InstaHub.Model.Services;
using System;
public class AccountService : BaseService, IAccountService
{
private readonly IAccountProvider _accountProvider;
public AccountService(IAccountProvider accountProvider)
{
_accountProvider = accountProvider;
}
public Account GetByExternalId(string id)
{
return _accountProvider.GetByExternalId(id);
}
public void Create(Account account)
{
_accountProvider.Create(account);
}
public void Update(Account account)
{
_accountProvider.Update(account);
}
}
}
<file_sep>namespace InstaHub.Web
{
using Nancy.Security;
using System.Collections.Generic;
internal class UserIdentity : IUserIdentity
{
private readonly string _userName;
private readonly List<string> _claims;
public UserIdentity(string userName)
{
_userName = userName;
_claims = new List<string>();
}
public string UserName
{
get
{
return _userName;
}
}
public IEnumerable<string> Claims
{
get
{
return _claims;
}
}
}
}<file_sep>namespace InstaHub.Core.Services
{
public abstract class BaseService
{
}
}
<file_sep>namespace InstaHub.Web.Pages
{
using InstaHub.Model.Entities;
using InstaHub.Model.Services;
using Nancy;
using Nancy.Security;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net.Http;
public class Auth : NancyModule
{
private readonly IInstagramClientService _instagramClientService;
private readonly IAccountService _accountService;
private static readonly string _authTokenName = "<PASSWORD>";
public Auth(IInstagramClientService instagramClientService, IAccountService accountService)
: base("/auth")
{
_instagramClientService = instagramClientService;
_accountService = accountService;
Get["/callback"] = Callback;
Get["/redirect"] = Redirect;
}
private dynamic Callback(dynamic parameters)
{
var code = (string)Request.Query["code"];
if (code == null)
{
return Response.AsRedirect("/");
}
var instagramClient = _instagramClientService.GetDefault();
var accessTokenResponse = RequestAccessToken(instagramClient, code);
var account = _accountService.GetByExternalId((string)accessTokenResponse.user.id);
var response = Response.AsRedirect("redirect");
if (account == null)
{
Guid userId;
if (Context.CurrentUser.IsAuthenticated())
{
userId = Guid.Parse(Context.CurrentUser.UserName);
}
else
{
userId = Guid.NewGuid();
SignIn(Guid.NewGuid(), response);
}
account = new Account()
{
Id = Guid.NewGuid(),
UserId = userId
};
UpdateAccountFromAccessTokenResponse(account, accessTokenResponse);
_accountService.Create(account);
}
else
{
if (Context.CurrentUser.IsAuthenticated())
{
var userId = Guid.Parse(Context.CurrentUser.UserName);
account.UserId = userId;
}
else
{
SignIn(account.UserId, response);
}
UpdateAccountFromAccessTokenResponse(account, accessTokenResponse);
_accountService.Update(account);
}
return response;
}
private dynamic Redirect(dynamic parameters)
{
var location = "/";
if (Context.CurrentUser.IsAuthenticated())
{
location = "/user";
}
return Response.AsRedirect(location);
}
private static void SignIn(Guid userId, Response response)
{
response.WithCookie(_authTokenName, userId.ToString());
}
private static void SignOff(Response response)
{
}
private static dynamic RequestAccessToken(InstagramClient instagramClient, string code)
{
using (var client = new HttpClient())
{
var values = new Dictionary<string, string>()
{
{ "client_id", instagramClient.Id },
{ "client_secret", instagramClient.Secret },
{ "redirect_uri", instagramClient.RedirectUrl },
{ "code", code },
{ "grant_type", "authorization_code" }
};
var content = new FormUrlEncodedContent(values);
var response = client.PostAsync("https://api.instagram.com/oauth/access_token", content).Result;
response.EnsureSuccessStatusCode();
var json = response.Content.ReadAsStringAsync().Result;
return JObject.Parse(json);
}
}
private static void UpdateAccountFromAccessTokenResponse(Account account, dynamic response)
{
account.AccessToken = response.access_token;
account.ExternalId = response.user.id;
account.UserName = response.user.username;
account.FullName = response.user.full_name;
account.Picture = response.user.profile_picture;
}
}
}<file_sep>@Master['master']
@Section['title']
Home
@EndSection
@Section['body']
<div class="panel panel-default">
<div class="panel-heading">Feed</div>
<div class="panel-body">Feed</div>
</div>
@EndSection<file_sep>namespace InstaHub.Core.Providers
{
using InstaHub.Model.Entities;
using InstaHub.Model.Providers;
using System.Linq;
public class AccountProvider : BaseProvider, IAccountProvider
{
public Account GetByExternalId(string id)
{
return Query<Account>("Account_GetByExternalId", new { Id = id }).SingleOrDefault();
}
public void Create(Account account)
{
Execute("Account_Create", account);
}
public void Update(Account account)
{
Execute("Account_Update", account);
}
}
}
<file_sep>namespace InstaHub.Model.Providers
{
using InstaHub.Model.Entities;
public interface IInstagramClientProvider
{
InstagramClient GetDefault();
}
}
<file_sep>namespace InstaHub.Core.Providers
{
using InstaHub.Model.Entities;
using InstaHub.Model.Providers;
using System.Configuration;
public class InstagramClientProvider : BaseProvider, IInstagramClientProvider
{
private static readonly InstagramClient _cache;
static InstagramClientProvider()
{
var id = ConfigurationManager.AppSettings["instagram.client.id"];
var secret = ConfigurationManager.AppSettings["instagram.client.secret"];
var redirect = ConfigurationManager.AppSettings["instagram.client.redirect"];
_cache = new InstagramClient()
{
Id = id,
Secret = secret,
RedirectUrl = redirect
};
}
public InstagramClient GetDefault()
{
return _cache;
}
}
}
<file_sep>namespace InstaHub.Web
{
using Nancy;
using Nancy.Authentication.Stateless;
using Nancy.Bootstrapper;
using Nancy.Conventions;
using Nancy.TinyIoc;
using System;
public class Application : DefaultNancyBootstrapper
{
protected override void ConfigureApplicationContainer(TinyIoCContainer container)
{
base.ConfigureApplicationContainer(container);
}
protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
{
var configuration = new StatelessAuthenticationConfiguration(c =>
{
string token;
if (c.Request.Cookies.TryGetValue("auth-token", out token))
{
token = Uri.UnescapeDataString(token);
return new UserIdentity(token);
}
return null;
});
StatelessAuthentication.Enable(pipelines, configuration);
}
protected override void ConfigureConventions(Nancy.Conventions.NancyConventions nancyConventions)
{
base.ConfigureConventions(nancyConventions);
Conventions.ViewLocationConventions.Clear();
Conventions.StaticContentsConventions.Clear();
Conventions.ViewLocationConventions.Add((view, model, context) => string.Format("client/{0}/{1}/views/index.html", context.ModuleName, view));
Conventions.ViewLocationConventions.Add((view, model, context) => string.Format("client/{0}/!common/views/{1}", context.ModuleName, view));
Conventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("client", "client", "js", "css", "png"));
}
}
}<file_sep>namespace InstaHub.Core.Providers
{
using Dapper;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
public abstract class BaseProvider
{
protected readonly string _connectionString;
public BaseProvider()
: this("InstaHub")
{
}
public BaseProvider(string connectionStringName)
{
_connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
}
protected IDbConnection CreateConnection()
{
var connection = new SqlConnection(_connectionString);
connection.Open();
return connection;
}
protected IEnumerable<dynamic> Query(string sql, dynamic param)
{
using (var connection = CreateConnection())
{
return SqlMapper.Query(connection, sql, param, commandType: CommandType.StoredProcedure);
}
}
protected IEnumerable<T> Query<T>(string sql, dynamic param)
{
using (var connection = CreateConnection())
{
return SqlMapper.Query<T>(connection, sql, param, commandType: CommandType.StoredProcedure);
}
}
protected int Execute(string sql, dynamic param = null)
{
using (var connection = CreateConnection())
{
return SqlMapper.Execute(connection, sql, param, commandType: CommandType.StoredProcedure);
}
}
}
}
<file_sep>namespace InstaHub.Model.Providers
{
using InstaHub.Model.Entities;
public interface IAccountProvider
{
Account GetByExternalId(string id);
void Create(Account account);
void Update(Account account);
}
}
<file_sep>namespace InstaHub.Model.Services
{
using InstaHub.Model.Entities;
using System;
public interface IInstagramClientService
{
InstagramClient GetDefault();
}
}
<file_sep>namespace InstaHub.Web.Pages
{
using InstaHub.Model.Services;
using Nancy;
public class Info : NancyModule
{
private readonly IInstagramClientService _instagramClientService;
public Info(IInstagramClientService instagramClientService)
: base()
{
_instagramClientService = instagramClientService;
Get["/"] = Home;
Get["/home"] = Home;
Get["/features"] = Home;
Get["/terms"] = Home;
Get["/contacts"] = Home;
Get["/feedback"] = Home;
}
private dynamic Home(dynamic parameters)
{
var instagramClient = _instagramClientService.GetDefault();
return View["home", instagramClient];
}
}
}<file_sep>namespace InstaHub.Model.Entities
{
using System;
public class Account : IIdentity
{
public Guid Id { get; set; }
public Guid UserId { get; set; }
public string ExternalId { get; set; }
public string UserName { get; set; }
public string FullName { get; set; }
public string Picture { get; set; }
public string AccessToken { get; set; }
}
}
<file_sep>namespace InstaHub.Model.Services
{
using InstaHub.Model.Entities;
public interface IAccountService
{
Account GetByExternalId(string id);
void Create(Account account);
void Update(Account account);
}
}
| 5e4a9a39e051a4fe157da8d002a4030a77f19613 | [
"C#",
"HTML"
] | 17 | C# | ababik/InstaHub | d1d00753fbb6ddf0a450ad5e7629ac68c7ecba44 | 6a5ddcbcb30b57d55bc44844be79cdc42ed5b723 |
refs/heads/master | <repo_name>yiHahoi/yiHa-N-gine<file_sep>/README.md
yiHa'N'gine-2D
2D Game Engine (C+SDL)<file_sep>/ColliTest.h
#include "yiHaNgine/yiHaNgine.h"
void camPan1(GAME_STATE* state){
/*float t = 0.1;
float camMaxForceX = 10;
float error = 0.00001;
float delta;
// state->CAM.accel.x = 0;
if(state->OBJ[0].vel.x > state->CAM.vel.x)
state->CAM.accel.x = camMaxForceX;
if(state->OBJ[0].vel.x < state->CAM.vel.x)
state->CAM.accel.x = -camMaxForceX;
state->CAM.vel.x += t*state->CAM.accel.x;
delta = state->OBJ[0].vel.x - state->CAM.vel.x;
if(delta <= error || delta >= -error){
state->CAM.accel.x = 0;
state->CAM.vel.x = state->OBJ[0].vel.x;
}
state->CAM.pos.x += t*state->CAM.vel.x;
printf("%f %f\n", state->OBJ[0].accel.x,state->CAM.accel.x);*/
state->CAM.pos.x = state->OBJ[0].pos.x - 650;
state->CAM.pos.y = state->OBJ[0].pos.y - 250;
}
/* Funcion para controlar la camara */
void camPan2(GAME_STATE* state){
if(state->MSE.lButton){ // Control de camara.
state->CAM.pos.x += state->CAM.pan.x - state->MSE.x;
state->CAM.pos.y += state->CAM.pan.y - state->MSE.y;
state->CAM.pan.x = state->MSE.x;
state->CAM.pan.y = state->MSE.y;
}
if(!state->MSE.lButton){
state->CAM.pan.x = state->MSE.x;
state->CAM.pan.y = state->MSE.y;
}
}
<file_sep>/yiHaNgine/main.c
#include "yiHaNgine.h"
/* MAIN */
int main(int argc, char* argv[]){
/* Iniciar SDL y en caso de fallar terminar el programa */
if(SDL_Init(SDL_INIT_EVERYTHING)<0)
return 1;
/* Iniciar estructura de Estado del Juego (definido en yiHaNgine.h) */
GAME_STATE state; // state es la estructura principal del juego.
if(init(&state)) // Le damos valores de inicio al programa.
return 1;
/* Inicio de las variables del juego */
if(gameInit(&state))
return 1;
/* Inicio del Loop de juego */
while(state.WIN.Quit!=1){ // Mientras no se cierre la ventana.
if(input(&state)) // Control de entrada.
return 1;
if(logic(&state)) // Control de estado de juego.
return 1;
if(render(&state)) // Control de renderizado.
return 1;
}
if(clean(&state)) // Liberamos la memoria.
return 1;
SDL_Quit(); // Cerramos SDL.
return 0; // Terminamos el programa.
}
<file_sep>/yiHaNgine/input.c
#include "yiHaNgine.h"
/* Funcion para recibir entradas al estado de juego */
int input(GAME_STATE* state){
while(SDL_PollEvent(&(state->WIN.event))){
switch(state->WIN.event.type){
case SDL_MOUSEMOTION:
state->MSE.x = (state->CAM.width/state->WIN.WIDTH)*state->WIN.event.motion.x;
state->MSE.y = (state->CAM.height/state->WIN.HEIGHT)*(state->WIN.HEIGHT - state->WIN.event.motion.y); // Restamos por coord. invertida de SDL.
break;
case SDL_MOUSEBUTTONDOWN:
if(state->WIN.event.button.button == SDL_BUTTON_RIGHT)
state->MSE.rButton = 1;
if(state->WIN.event.button.button == SDL_BUTTON_LEFT)
state->MSE.lButton = 1;
break;
case SDL_MOUSEBUTTONUP:
if(state->WIN.event.button.button == SDL_BUTTON_RIGHT)
state->MSE.rButton = 0;
if(state->WIN.event.button.button == SDL_BUTTON_LEFT)
state->MSE.lButton = 0;
break;
case SDL_KEYDOWN:
switch(state->WIN.event.key.keysym.sym){
case SDLK_UP: state->KEY.up = 1; break;
case SDLK_DOWN: state->KEY.down = 1; break;
case SDLK_LEFT: state->KEY.left = 1; break;
case SDLK_RIGHT: state->KEY.right = 1; break;
case SDLK_q: state->KEY.q = 1; break;
case SDLK_w: state->KEY.w = 1; break;
case SDLK_e: state->KEY.e = 1; break;
case SDLK_r: state->KEY.r = 1; break;
case SDLK_a: state->KEY.a = 1; break;
case SDLK_s: state->KEY.s = 1; break;
case SDLK_d: state->KEY.d = 1; break;
case SDLK_f: state->KEY.f = 1; break;
case SDLK_z: state->KEY.z = 1; break;
case SDLK_x: state->KEY.x = 1; break;
case SDLK_c: state->KEY.c = 1; break;
case SDLK_v: state->KEY.v = 1; break;
case SDLK_p:
if(SDL_GetTicks()-state->WIN.stateSubTicks > state->WIN.minPauseTime){
state->WIN.PAUSE = !state->WIN.PAUSE;
state->WIN.stateSubTicks = SDL_GetTicks();
}
break;
case SDLK_SPACE: state->KEY.space = 1; break;
case SDLK_LCTRL: state->KEY.ctrl = 1; break;
case SDLK_LALT: state->KEY.alt = 1; break;
case SDLK_LSHIFT: state->KEY.shift = 1; break;
case SDLK_TAB: state->KEY.tab = 1; break;
case SDLK_ESCAPE: state->KEY.esc = 1; break;
}
break;
case SDL_KEYUP:
switch(state->WIN.event.key.keysym.sym){
case SDLK_UP: state->KEY.up = 0; break;
case SDLK_DOWN: state->KEY.down = 0; break;
case SDLK_LEFT: state->KEY.left = 0; break;
case SDLK_RIGHT: state->KEY.right = 0; break;
case SDLK_q: state->KEY.q = 0; break;
case SDLK_w: state->KEY.w = 0; break;
case SDLK_e: state->KEY.e = 0; break;
case SDLK_r: state->KEY.r = 0; break;
case SDLK_a: state->KEY.a = 0; break;
case SDLK_s: state->KEY.s = 0; break;
case SDLK_d: state->KEY.d = 0; break;
case SDLK_f: state->KEY.f = 0; break;
case SDLK_z: state->KEY.z = 0; break;
case SDLK_x: state->KEY.x = 0; break;
case SDLK_c: state->KEY.c = 0; break;
case SDLK_v: state->KEY.v = 0; break;
case SDLK_SPACE: state->KEY.space = 0; break;
case SDLK_LCTRL: state->KEY.ctrl = 0; break;
case SDLK_LALT: state->KEY.alt = 0; break;
case SDLK_LSHIFT: state->KEY.shift = 0; break;
case SDLK_TAB: state->KEY.tab = 0; break;
case SDLK_ESCAPE: state->KEY.esc = 0; break;
}
break;
case SDL_QUIT:
state->WIN.Quit=1;
break;
}
}
return 0;
}
/* Funcion que se encarga de cargar los datos a un objeto */
int loadObj(GAME_STATE* state, char* dataFile, int objPosition, int objTotal){
FILE* datos;
char imgFile[state->WIN.fileCharLimit];
char line[state->WIN.fileCharLimit];
int objNumber = objPosition;
Uint8 alphaColor[3];
int ctrl1, ctrl2, ctrl3, ctrl4, temp;
while(objNumber < objPosition + objTotal){
datos = NULL;
datos = fopen(dataFile, "r");
if(datos == NULL)
return 1;
if(objNumber == objPosition)
state->OBJ[objNumber].objCopy = 0;
else
state->OBJ[objNumber].objCopy = 1;
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%d", &state->OBJ[objNumber].animTotal);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%d", &state->OBJ[objNumber].animCurrent);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%d", &state->OBJ[objNumber].camRelative);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%f", &state->OBJ[objNumber].scale);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%f", &state->OBJ[objNumber].rotation);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%f", &state->OBJ[objNumber].transparency);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%d", &state->OBJ[objNumber].xMirror);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%d", &state->OBJ[objNumber].yMirror);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%f", &state->OBJ[objNumber].pos.x);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%f", &state->OBJ[objNumber].pos.y);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%d", &state->OBJ[objNumber].zPos);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%f", &state->OBJ[objNumber].vel.x);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%f", &state->OBJ[objNumber].vel.y);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%f", &state->OBJ[objNumber].accel.x);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%f", &state->OBJ[objNumber].accel.y);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%d", &state->OBJ[objNumber].ghost);
state->OBJ[objNumber].anim = malloc(state->OBJ[objNumber].animTotal * sizeof(ANIMATION));
if(state->OBJ[objNumber].anim == NULL)
return 1;
for(ctrl1=0; ctrl1 < state->OBJ[objNumber].animTotal; ctrl1++){
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%d", &state->OBJ[objNumber].anim[ctrl1].subFrameTotal);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%d", &state->OBJ[objNumber].anim[ctrl1].subFrameCurrent);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%d", &state->OBJ[objNumber].anim[ctrl1].subFramePixelWidth);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%d", &state->OBJ[objNumber].anim[ctrl1].subFramePixelHeight);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%d", &state->OBJ[objNumber].anim[ctrl1].loop);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%d", &state->OBJ[objNumber].anim[ctrl1].fps);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%u", &state->OBJ[objNumber].anim[ctrl1].lastClock);
if(!state->OBJ[objNumber].objCopy){
temp = state->OBJ[objNumber].anim[ctrl1].subFrameTotal;
state->OBJ[objNumber].anim[ctrl1].subFrame = malloc( temp * sizeof(QUAD));
if(state->OBJ[objNumber].anim[ctrl1].subFrame == NULL)
return 1;
}
else{
state->OBJ[objNumber].anim[ctrl1].subFrame = state->OBJ[objPosition].anim[ctrl1].subFrame;
}
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%s", imgFile);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%u", &alphaColor[0]);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%u", &alphaColor[1]);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%u", &alphaColor[2]);
if(!state->OBJ[objNumber].objCopy){
loadImage(imgFile, alphaColor, &state->OBJ[objNumber].anim[ctrl1].frame);
state->OBJ[objNumber].anim[ctrl1].coll = malloc(state->OBJ[objNumber].anim[ctrl1].subFrameTotal * sizeof(COLLISION));
if(state->OBJ[objNumber].anim[ctrl1].coll == NULL)
return 1;
}
else{
state->OBJ[objNumber].anim[ctrl1].frame = state->OBJ[objPosition].anim[ctrl1].frame;
state->OBJ[objNumber].anim[ctrl1].coll = state->OBJ[objPosition].anim[ctrl1].coll;
}
for(ctrl2=0; ctrl2 < state->OBJ[objNumber].anim[ctrl1].subFrameTotal; ctrl2++){
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%f", &state->OBJ[objNumber].anim[ctrl1].subFrame[ctrl2].x);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%f", &state->OBJ[objNumber].anim[ctrl1].subFrame[ctrl2].y);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%f", &state->OBJ[objNumber].anim[ctrl1].subFrame[ctrl2].w);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%f", &state->OBJ[objNumber].anim[ctrl1].subFrame[ctrl2].h);
}
for(ctrl2=0; ctrl2 < state->OBJ[objNumber].anim[ctrl1].subFrameTotal; ctrl2++){
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%d", &state->OBJ[objNumber].anim[ctrl1].coll[ctrl2].polyTotal);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%f", &state->OBJ[objNumber].anim[ctrl1].coll[ctrl2].pos.x);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%f", &state->OBJ[objNumber].anim[ctrl1].coll[ctrl2].pos.y);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%f", &state->OBJ[objNumber].anim[ctrl1].coll[ctrl2].radius);
if(!state->OBJ[objNumber].objCopy){
state->OBJ[objNumber].anim[ctrl1].coll[ctrl2].poly = malloc(state->OBJ[objNumber].anim[ctrl1].coll[ctrl2].polyTotal * sizeof(POLY));
if(state->OBJ[objNumber].anim[ctrl1].coll[ctrl2].poly == NULL)
return 1;
}
else{
state->OBJ[objNumber].anim[ctrl1].coll[ctrl2].poly = state->OBJ[objPosition].anim[ctrl1].coll[ctrl2].poly;
}
for(ctrl3=0; ctrl3 < state->OBJ[objNumber].anim[ctrl1].coll[ctrl2].polyTotal; ctrl3++){
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%d", &state->OBJ[objNumber].anim[ctrl1].coll[ctrl2].poly[ctrl3].pointTotal);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%f", &state->OBJ[objNumber].anim[ctrl1].coll[ctrl2].poly[ctrl3].pos.x);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%f", &state->OBJ[objNumber].anim[ctrl1].coll[ctrl2].poly[ctrl3].pos.y);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%f", &state->OBJ[objNumber].anim[ctrl1].coll[ctrl2].poly[ctrl3].radius);
if(!state->OBJ[objNumber].objCopy){
state->OBJ[objNumber].anim[ctrl1].coll[ctrl2].poly[ctrl3].point = malloc(state->OBJ[objNumber].anim[ctrl1].coll[ctrl2].poly[ctrl3].pointTotal * sizeof(VECT));
if(state->OBJ[objNumber].anim[ctrl1].coll[ctrl2].poly[ctrl3].point == NULL)
return 1;
}
else{
state->OBJ[objNumber].anim[ctrl1].coll[ctrl2].poly[ctrl3].point = state->OBJ[objPosition].anim[ctrl1].coll[ctrl2].poly[ctrl3].point;
}
for(ctrl4=0; ctrl4 < state->OBJ[objNumber].anim[ctrl1].coll[ctrl2].poly[ctrl3].pointTotal; ctrl4++){
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%f", &state->OBJ[objNumber].anim[ctrl1].coll[ctrl2].poly[ctrl3].point[ctrl4].x);
fgets(line, state->WIN.fileCharLimit+1, datos);
sscanf(line,"%f", &state->OBJ[objNumber].anim[ctrl1].coll[ctrl2].poly[ctrl3].point[ctrl4].y);
}
}
}
}
fclose(datos);
objNumber++;
}
return 0;
}
/* Rellenamos los datos en un archivo de texto con los siguientes datos:
animTotal
animCurrent
camRelative
scale
rotation
transparency
xMirror
yMirror
pos.x
pos.y
zPos
vel.x
vel.y
accel.x
accel.y
ghost
for(animTotal)
subFrameTotal
subFrameCurrent
subFramePixelWidth
subFramePixelHeight
loop
fps
lastClock
imgFile
alphaColor[0]
alphaColor[1]
alphaColor[2]
for(subFrameTotal)
subFrame.x
subFrame.y
subFrame.w
subFrame.h
for(subFrameTotal)
polyTotal
pos.x
pos.y
radius
for(polyTotal)
pointTotal
pos.x
pos.y
radius
for(pointTotal)
x
y
*/
<file_sep>/yiHaNgine/logic.c
#include "yiHaNgine.h"
/* Funcion para calcular la logica del estado de juego */
int logic(GAME_STATE* state){
GetTicks(state);
if(!state->WIN.PAUSE){
if(game(state))
return 1;
}
if(state->KEY.esc==1)
state->WIN.Quit=1;
return 0;
}
/* Producto punto entre dos vectores */
float dot(VECT* A, VECT* B){
return A->x * B->x + A->y * B->y;
}
/* Normaliza un vector */
void normalize(VECT* vct){
float temp = 1/sqrt(vct->x*vct->x+vct->y*vct->y);
vct->x *= temp;
vct->y *= temp;
}
/* Escala un poligono en "factor" unidades */
void polyScale(POLY* polygon, VECT* center, float factor){
int ctrl1;
polygon->pos.x -= center->x;
polygon->pos.y -= center->y;
polygon->pos.x *= factor;
polygon->pos.y *= factor;
polygon->pos.x += factor*center->x;
polygon->pos.y += factor*center->y;
polygon->radius *= factor;
for(ctrl1=0; ctrl1<polygon->pointTotal; ctrl1++){
polygon->point[ctrl1].x -= center->x;
polygon->point[ctrl1].y -= center->y;
polygon->point[ctrl1].x *= factor;
polygon->point[ctrl1].y *= factor;
polygon->point[ctrl1].x += factor*center->x;
polygon->point[ctrl1].y += factor*center->y;
}
}
/* Rota un poligono en "angle" grados */
void polyRotate(POLY* polygon, VECT* center, float angle){
int ctrl1;
float temp, pi = 3.14159265;
float COS=cos(2*0.002777*pi*angle), SEN=sin(2*0.002777*pi*angle);
polygon->pos.x -= center->x;
polygon->pos.y -= center->y;
temp = polygon->pos.x*COS-polygon->pos.y*SEN;
polygon->pos.y = polygon->pos.x*SEN+polygon->pos.y*COS;
polygon->pos.x = temp;
polygon->pos.x += center->x;
polygon->pos.y += center->y;
for(ctrl1=0; ctrl1<polygon->pointTotal; ctrl1++){
polygon->point[ctrl1].x -= center->x;
polygon->point[ctrl1].y -= center->y;
temp = polygon->point[ctrl1].x*COS-polygon->point[ctrl1].y*SEN;
polygon->point[ctrl1].y = polygon->point[ctrl1].x*SEN+polygon->point[ctrl1].y*COS;
polygon->point[ctrl1].x = temp;
polygon->point[ctrl1].x += center->x;
polygon->point[ctrl1].y += center->y;
}
}
/* Traslada un poligono desde el origen a "pos" */
void polyTranslate(POLY* polygon, VECT* pos){
int ctrl1;
polygon->pos.x += pos->x;
polygon->pos.y += pos->y;
for(ctrl1=0; ctrl1<polygon->pointTotal; ctrl1++){
polygon->point[ctrl1].x += pos->x;
polygon->point[ctrl1].y += pos->y;
}
}
/* Deteccion de colision circular */
int cirCollision(VECT* A, float aRadius, VECT* B, float bRadius){
if((A->x-B->x)*(A->x-B->x)+(A->y-B->y)*(A->y-B->y) < (aRadius+bRadius)*(aRadius+bRadius))
return 1;
return 0;
}
/* Deteccion de colision entre poligonos */
int polyCollision(POLY* A, POLY* B, RESPONSE* collResp1, RESPONSE* collResp2){
int i, j, k;
float aMin, aMax, bMin, bMax, respMag;
VECT axis, respAxis, pA, pB;
for(i=0; i < A->pointTotal; i++){
if(i==A->pointTotal-1){
pA.x = A->point[0].x;
pA.y = A->point[0].y;
}
else{
pA.x = A->point[i+1].x;
pA.y = A->point[i+1].y;
}
pB.x = A->point[i].x;
pB.y = A->point[i].y;
axis.x = pA.y - pB.y;
axis.y = pB.x - pA.x;
aMin = dot(&pA, &axis);
aMax = dot(&pA, &axis);
for(k=0; k < A->pointTotal; k++){
pA.x = A->point[k].x;
pA.y = A->point[k].y;
if(dot(&pA, &axis) < aMin)
aMin = dot(&pA, &axis);
if(dot(&pA, &axis) > aMax)
aMax = dot(&pA, &axis);
}
for(j=0; j < B->pointTotal; j++){
pB.x = B->point[j].x;
pB.y = B->point[j].y;
bMin = dot(&pB, &axis);
bMax = dot(&pB, &axis);
for(k=0; k < B->pointTotal; k++){
pB.x = B->point[k].x;
pB.y = B->point[k].y;
if(dot(&pB, &axis) < bMin)
bMin = dot(&pB, &axis);
if(dot(&pB, &axis) > bMax)
bMax = dot(&pB, &axis);
}
if(aMin < bMin){
if(aMax < bMin)
return 0;
if(!i && !j){
respMag = aMax-bMin;
respAxis.x = -axis.x;
respAxis.y = -axis.y;
}
if(aMax-bMin<respMag){
respMag = aMax-bMin;
respAxis.x = -axis.x;
respAxis.y = -axis.y;
}
}
if(bMin < aMin){
if(bMax < aMin)
return 0;
if(!i && !j){
respMag = bMax-aMin;
respAxis.x = axis.x;
respAxis.y = axis.y;
}
if(bMax-aMin<respMag){
respMag = bMax-aMin;
respAxis.x = axis.x;
respAxis.y = axis.y;
}
}
}
}
// Segunda pasada. Cambio de poligono.
for(i=0; i < B->pointTotal; i++){
if(i==B->pointTotal-1){
pB.x = B->point[0].x;
pB.y = B->point[0].y;
}
else{
pB.x = B->point[i+1].x;
pB.y = B->point[i+1].y;
}
pA.x = B->point[i].x;
pA.y = B->point[i].y;
axis.x = pB.y - pA.y;
axis.y = pA.x - pB.x;
bMin = dot(&pB, &axis);
bMax = dot(&pB, &axis);
for(k=0; k < B->pointTotal; k++){
pB.x = B->point[k].x;
pB.y = B->point[k].y;
if(dot(&pB, &axis) < bMin)
bMin = dot(&pB, &axis);
if(dot(&pB, &axis) > bMax)
bMax = dot(&pB, &axis);
}
for(j=0; j < A->pointTotal; j++){
pA.x = A->point[j].x;
pA.y = A->point[j].y;
aMin = dot(&pA, &axis);
aMax = dot(&pA, &axis);
for(k=0; k < A->pointTotal; k++){
pA.x = A->point[k].x;
pA.y = A->point[k].y;
if(dot(&pA, &axis) < aMin)
aMin = dot(&pA, &axis);
if(dot(&pA, &axis) > aMax)
aMax = dot(&pA, &axis);
}
if(aMin < bMin){
if(aMax < bMin)
return 0;
if(aMax-bMin<respMag){
respMag = aMax-bMin;
respAxis.x = -axis.x;
respAxis.y = -axis.y;
}
}
if(bMin < aMin){
if(bMax < aMin)
return 0;
if(bMax-aMin<respMag){
respMag = bMax-aMin;
respAxis.x = axis.x;
respAxis.y = axis.y;
}
}
}
}
collResp1->axis.x = respAxis.x;
collResp1->axis.y = respAxis.y;
collResp1->mag = respMag;
collResp2->axis.x = -respAxis.x;
collResp2->axis.y = -respAxis.y;
collResp2->mag = respMag;
return 1;
}
int collision(OBJECT* obj1, OBJECT* obj2, GAME_STATE* state){
if(obj1->ghost || obj2->ghost){
obj1->collResp.cirCollided = 0;
obj1->collResp.objCollided = 0;
obj1->collResp.axis.x = 0.0;
obj1->collResp.axis.y = 0.0;
obj1->collResp.mag = 0.0;
obj2->collResp.cirCollided = 0;
obj2->collResp.objCollided = 0;
obj2->collResp.axis.x = 0.0;
obj2->collResp.axis.y = 0.0;
obj2->collResp.mag = 0.0;
return 0;
}
int animCurr1, animCurr2, subFrameCurr1, subFrameCurr2;
int polyTot1, polyTot2, ctrl1, ctrl2, ctrl3;
int pixelWidth1, pixelHeight1, pixelWidth2, pixelHeight2;
float r1, r2;
VECT pos1, pos2, pointA[state->WIN.polyMaxPoints], pointB[state->WIN.polyMaxPoints];
POLY A, B;
A.point = pointA;
B.point = pointB;
animCurr1 = obj1->animCurrent;
subFrameCurr1 = obj1->anim[animCurr1].subFrameCurrent;
pos1.x = obj1->anim[animCurr1].coll[subFrameCurr1].pos.x * obj1->scale + obj1->pos.x;
pos1.y = obj1->anim[animCurr1].coll[subFrameCurr1].pos.y * obj1->scale + obj1->pos.y;
r1 = obj1->scale * obj1->anim[animCurr1].coll[subFrameCurr1].radius;
animCurr2 = obj2->animCurrent;
subFrameCurr2 = obj2->anim[animCurr2].subFrameCurrent;
pos2.x = obj2->anim[animCurr2].coll[subFrameCurr2].pos.x * obj2->scale + obj2->pos.x;
pos2.y = obj2->anim[animCurr2].coll[subFrameCurr2].pos.y * obj2->scale + obj2->pos.y;
r2 = obj2->scale * obj2->anim[animCurr2].coll[subFrameCurr2].radius;
if(obj1->camRelative){
pos1.x -= state->CAM.pos.x;
pos1.y -= state->CAM.pos.y;
}
if(obj2->camRelative){
pos2.x -= state->CAM.pos.x;
pos2.y -= state->CAM.pos.y;
}
obj1->collResp.cirCollided = cirCollision(&pos1, r1, &pos2, r2);
obj2->collResp.cirCollided = obj1->collResp.cirCollided;
if(obj1->collResp.cirCollided){
polyTot1 = obj1->anim[animCurr1].coll[subFrameCurr1].polyTotal;
polyTot2 = obj2->anim[animCurr2].coll[subFrameCurr2].polyTotal;
for(ctrl1=0; ctrl1<polyTot1; ctrl1++){
pixelWidth1 = obj1->anim[animCurr1].subFramePixelWidth;
pixelHeight1 = obj1->anim[animCurr1].subFramePixelHeight;
A.pointTotal = obj1->anim[animCurr1].coll[subFrameCurr1].poly[ctrl1].pointTotal;
for(ctrl3=0; ctrl3<A.pointTotal; ctrl3++){
A.point[ctrl3].x = obj1->anim[animCurr1].coll[subFrameCurr1].poly[ctrl1].point[ctrl3].x;
A.point[ctrl3].y = obj1->anim[animCurr1].coll[subFrameCurr1].poly[ctrl1].point[ctrl3].y;
}
A.pos.x = obj1->anim[animCurr1].coll[subFrameCurr1].poly[ctrl1].pos.x;
A.pos.y = obj1->anim[animCurr1].coll[subFrameCurr1].poly[ctrl1].pos.y;
A.radius = obj1->anim[animCurr1].coll[subFrameCurr1].poly[ctrl1].radius;
pos1.x = 0.5*pixelWidth1;
pos1.y = 0.5*pixelHeight1;
polyScale(&A, &pos1, obj1->scale);
pos1.x *= obj1->scale;
pos1.y *= obj1->scale;
polyRotate(&A, &pos1, obj1->rotation);
pos1.x = obj1->pos.x;
pos1.y = obj1->pos.y;
if(obj1->camRelative){
pos1.x -= state->CAM.pos.x;
pos1.y -= state->CAM.pos.y;
}
polyTranslate(&A, &pos1);
for(ctrl2=0; ctrl2<polyTot2; ctrl2++){
pixelWidth2 = obj2->anim[animCurr2].subFramePixelWidth;
pixelHeight2 = obj2->anim[animCurr2].subFramePixelHeight;
B.pointTotal = obj2->anim[animCurr2].coll[subFrameCurr2].poly[ctrl2].pointTotal;
for(ctrl3=0; ctrl3<A.pointTotal; ctrl3++){
B.point[ctrl3].x = obj2->anim[animCurr2].coll[subFrameCurr2].poly[ctrl2].point[ctrl3].x;
B.point[ctrl3].y = obj2->anim[animCurr2].coll[subFrameCurr2].poly[ctrl2].point[ctrl3].y;
}
B.pos.x = obj2->anim[animCurr2].coll[subFrameCurr2].poly[ctrl2].pos.x;
B.pos.y = obj2->anim[animCurr2].coll[subFrameCurr2].poly[ctrl2].pos.y;
B.radius = obj2->anim[animCurr2].coll[subFrameCurr2].poly[ctrl2].radius;
pos2.x = 0.5*pixelWidth2;
pos2.y = 0.5*pixelHeight2;
polyScale(&B, &pos2, obj2->scale);
pos2.x *= obj2->scale;
pos2.y *= obj2->scale;
polyRotate(&B, &pos2, obj2->rotation);
pos2.x = obj2->pos.x;
pos2.y = obj2->pos.y;
if(obj2->camRelative){
pos2.x -= state->CAM.pos.x;
pos2.y -= state->CAM.pos.y;
}
polyTranslate(&B, &pos2);
if(cirCollision(&A.pos, A.radius, &B.pos, B.radius)){
if(polyCollision(&A, &B, &obj1->collResp, &obj2->collResp)){
obj1->collResp.objCollided = 1;
obj2->collResp.objCollided = 1;
normalize(&obj1->collResp.axis);
normalize(&obj2->collResp.axis);
return 1;
}
}
}
}
}
obj1->collResp.objCollided = 0;
obj1->collResp.axis.x = 0.0;
obj1->collResp.axis.y = 0.0;
obj1->collResp.mag = 0.0;
obj2->collResp.objCollided = 0;
obj2->collResp.axis.x = 0.0;
obj2->collResp.axis.y = 0.0;
obj2->collResp.mag = 0.0;
return 0;
}
<file_sep>/yiHaNgine/render.c
#include "yiHaNgine.h"
/* Funcion para inicializar el estado de juego */
int init(GAME_STATE* state){
state->WIN.NAME = "yiHa'N'gine";
state->WIN.ICON = "yiHaNgine/yiHaPig.ico";
state->WIN.WIDTH = 640;
state->WIN.HEIGHT = 480;
state->WIN.BPP = 32;
state->WIN.FPS = 60; // Limite de FPS del programa.
state->WIN.zPosMax = 3; // Limite de profundidad.
state->WIN.polyMaxPoints = 128; // Limite de puntos por poligono.
state->WIN.console_Enable = 1; // Mostrar datos en Consola.
state->WIN.SURFACE = NULL;
state->WIN.Quit = 0;
state->WIN.PAUSE = 0;
state->WIN.lastClock = 0;
state->WIN.console_FpsUpdate = 1000;
state->WIN.console_Frames = 0;
state->WIN.console_Clocks = 0;
state->WIN.fileCharLimit = 128;
state->TICKS = 0;
state->WIN.totalPauseTime = 0;
state->WIN.stateSubTicks = 0;
state->WIN.minPauseTime = 200;
if(state->WIN.FPS != 0)
state->WIN.mSeg = 1000/state->WIN.FPS;
if(state->WIN.console_Enable){ // Datos a consola.
freopen("CON", "w", stdout); // Redirige stdout.
freopen("CON", "w", stderr); // Redirige stderr.
}
/* Iniciar ventana del juego */
SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); // Buffer doble.
SDL_Surface* ICON = NULL;
ICON = SDL_LoadBMP(state->WIN.ICON);
SDL_WM_SetIcon(ICON, NULL);
printf("%s",ICON);
state->WIN.SURFACE = SDL_SetVideoMode(state->WIN.WIDTH,state->WIN.HEIGHT,state->WIN.BPP,SDL_OPENGL);
if(state->WIN.SURFACE==NULL)
return 1;
SDL_WM_SetCaption( state->WIN.NAME, NULL); // Nombre de la ventana.
state->MSE.x = 0;
state->MSE.y = 0;
state->MSE.rButton = 0;
state->MSE.lButton = 0;
state->KEY.up = 0;
state->KEY.down = 0;
state->KEY.left = 0;
state->KEY.right = 0;
state->KEY.q = 0;
state->KEY.w = 0;
state->KEY.e = 0;
state->KEY.r = 0;
state->KEY.a = 0;
state->KEY.s = 0;
state->KEY.d = 0;
state->KEY.f = 0;
state->KEY.z = 0;
state->KEY.x = 0;
state->KEY.c = 0;
state->KEY.v = 0;
state->KEY.p = 0;
state->KEY.space = 0;
state->KEY.ctrl = 0;
state->KEY.alt = 0;
state->KEY.shift = 0;
state->KEY.tab = 0;
state->KEY.esc = 0;
state->CAM.pos.x = 0;
state->CAM.pos.y = 0;
state->CAM.pan.x = 0;
state->CAM.pan.y = 0;
state->CAM.width = 1600;
state->CAM.height = 1200;
glClearColor( 1, 1, 1, 0 );
glDisable(GL_DEPTH_TEST);
glEnable( GL_TEXTURE_2D );
glEnable(GL_ALPHA_TEST);
glEnable(GL_BLEND);
glAlphaFunc(GL_GREATER,0.1);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
glOrtho( 0, state->CAM.width, 0, state->CAM.height, -1, 1 );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
return 0;
}
/* Funcion para renderizar en pantalla el estado de juego */
int render(GAME_STATE* state){
int ctrl1, ctrl2;
for(ctrl1=0; ctrl1 < state->objTotal; ctrl1++){ // actualizamos la animacion de cada obj.
if(state->OBJ[ctrl1].anim[state->OBJ[ctrl1].animCurrent].subFrameTotal > 1)
animUpdate(&state->OBJ[ctrl1].anim[state->OBJ[ctrl1].animCurrent], state);
}
// Clear the screen before drawing
glClear( GL_COLOR_BUFFER_BIT );
// Dibujamos en orden de profundidad.
for(ctrl2=0; ctrl2 <= state->WIN.zPosMax; ctrl2++){
for(ctrl1=0; ctrl1 < state->objTotal; ctrl1++){
if(ctrl2==state->OBJ[ctrl1].zPos)
if(drawObj(&state->OBJ[ctrl1], &state->CAM))
return 1;
}
}
// Actualizamos la pantalla.
SDL_GL_SwapBuffers();
// Calculamos FPS y limitamos si corresponde.
fps(state);
return 0;
}
/* Funcion para limpiar memoria */
int clean(GAME_STATE* state){
int ctrl1, ctrl2, ctrl3, ctrl4;
for(ctrl1=0; ctrl1<state->objTotal; ctrl1++){
for(ctrl2=0; ctrl2<state->OBJ[ctrl1].animTotal; ctrl2++){
for(ctrl3=0; ctrl3<state->OBJ[ctrl1].anim[ctrl2].subFrameTotal; ctrl3++){
for(ctrl4=0; ctrl4 < state->OBJ[ctrl1].anim[ctrl2].coll[ctrl3].poly[ctrl4].pointTotal; ctrl4++){
if(!state->OBJ[ctrl1].objCopy){
free(state->OBJ[ctrl1].anim[ctrl2].coll[ctrl3].poly[ctrl4].point);
}
}
if(!state->OBJ[ctrl1].objCopy){
free(state->OBJ[ctrl1].anim[ctrl2].coll[ctrl3].poly);
state->OBJ[ctrl1].anim[ctrl2].coll[ctrl3].poly = NULL;
}
}
if(!state->OBJ[ctrl1].objCopy){
glDeleteTextures(1, &state->OBJ[ctrl1].anim[ctrl2].frame);
free(state->OBJ[ctrl1].anim[ctrl2].subFrame);
free(state->OBJ[ctrl1].anim[ctrl2].coll);
}
}
free(state->OBJ[ctrl1].anim);
}
free(state->OBJ);
return 0;
}
/* Funcion para controlar los FPS */
void fps(GAME_STATE* state){
Uint32 clocks, newTime = SDL_GetTicks();
if(state->WIN.console_Enable){
state->WIN.console_Frames += 1;
clocks = newTime - state->WIN.console_Clocks;
if(clocks > state->WIN.console_FpsUpdate){
printf("FPS: %0.2f\n", 1000*state->WIN.console_Frames/(float)clocks);
state->WIN.console_Clocks = newTime;
state->WIN.console_Frames = 0;
}
}
if(state->WIN.FPS){
clocks = newTime - state->WIN.lastClock;
if(clocks < state->WIN.mSeg)
SDL_Delay(state->WIN.mSeg - clocks);
state->WIN.lastClock = SDL_GetTicks();
}
}
/* Funcion para cargar imagenes con mismo formato de pantalla */
void loadImage(char* file, Uint8* RGB, GLuint* texture){
SDL_Surface* img = NULL;
SDL_Surface* optImg = NULL;
SDL_Surface* optImg2 = NULL;
GLenum texture_format;
GLint nofcolors;
img = IMG_Load(file);
if(img != NULL){
optImg = SDL_DisplayFormat(img);
SDL_FreeSurface(img);
if(optImg!=NULL){
Uint32 alpha = SDL_MapRGB( optImg->format, RGB[0], RGB[1], RGB[2] );
SDL_SetColorKey( optImg, SDL_SRCCOLORKEY, alpha );
optImg2 = SDL_DisplayFormatAlpha(optImg);
SDL_FreeSurface(optImg);
}
}
if(optImg2 != NULL){
//get number of channels in the SDL surface
nofcolors=optImg2->format->BytesPerPixel;
//contains an alpha channel
if(nofcolors==4){
if(optImg2->format->Rmask==0x000000ff)
texture_format=GL_RGBA;
else
texture_format=GL_BGRA;
}
else{
if(nofcolors==3){ //no alpha channel
if(optImg2->format->Rmask==0x000000ff)
texture_format=GL_RGB;
else
texture_format=GL_BGR;
}
else
printf("warning: the image is not truecolor...this will break ");
}
// Have OpenGL generate a texture object handle for us
glGenTextures( 1, texture );
// Bind the texture object
glBindTexture( GL_TEXTURE_2D, *texture );
// Set the texture's stretching properties
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
glTexImage2D( GL_TEXTURE_2D, 0, nofcolors, optImg2->w, optImg2->h, 0,
texture_format, GL_UNSIGNED_BYTE, optImg2->pixels );
SDL_FreeSurface(optImg2);
}
}
/* Funcion para actualizar animaciones */
int animUpdate(ANIMATION* anim, GAME_STATE* state){
if((!anim->loop) && (anim->subFrameCurrent==anim->subFrameTotal-1))
return 0;
Uint32 mSec = 1000/anim->fps;
Uint32 mSecTotal = mSec*anim->subFrameTotal;
Uint32 clocks = state->TICKS - anim->lastClock;
if(clocks >= mSecTotal){
while(clocks >= mSecTotal){
clocks -= mSecTotal;
}
anim->lastClock = state->TICKS - clocks;
}
anim->subFrameCurrent = clocks/mSec;
return 0;
}
int drawObj(OBJECT* obj, CAMERA* cam){
int animCurr = obj->animCurrent;
int subFrameCurr = obj->anim[animCurr].subFrameCurrent;
QUAD rect2, rect1 = obj->anim[animCurr].subFrame[subFrameCurr];
rect2.x = obj->pos.x;
rect2.y = obj->pos.y;
rect2.w = obj->anim[animCurr].subFramePixelWidth;
rect2.h = obj->anim[animCurr].subFramePixelHeight;
// Bind the texture to which subsequent calls refer to
glBindTexture( GL_TEXTURE_2D, obj->anim[animCurr].frame );
glColor4f( 1, 1, 1, obj->transparency );
glLoadIdentity();
// Camara
if(obj->camRelative)
glTranslatef(-cam->pos.x, -cam->pos.y, 0);
glTranslatef(obj->pos.x + obj->scale*rect2.w*0.5, obj->pos.y + obj->scale*rect2.h*0.5, 0);
glRotatef(obj->rotation, 0, 0, 1);
glTranslatef(-obj->scale*rect2.w*0.5, -obj->scale*rect2.h*0.5, 0);
glScalef(obj->scale , obj->scale, 1.0);
glTranslatef(-obj->pos.x, -obj->pos.y, 0);
if(!obj->xMirror && !obj->yMirror){
glBegin( GL_QUADS );
// Top-left vertex (corner)
glTexCoord2f( rect1.x, rect1.y );
glVertex3f( rect2.x, rect2.y + rect2.h, 0 );
// Top-right vertex (corner)
glTexCoord2f( rect1.x + rect1.w, rect1.y );
glVertex3f( rect2.x + rect2.w, rect2.y + rect2.h, 0 );
// Bottom-right vertex (corner)
glTexCoord2f( rect1.x + rect1.w, rect1.y + rect1.h);
glVertex3f( rect2.x + rect2.w, rect2.y, 0 );
// Bottom-left vertex (corner)
glTexCoord2f( rect1.x, rect1.y + rect1.h);
glVertex3f( rect2.x, rect2.y, 0 );
glEnd();
}
else if(obj->xMirror && !obj->yMirror){
glBegin( GL_QUADS );
// Top-left vertex (corner)
glTexCoord2f( rect1.x + rect1.w, rect1.y );
glVertex3f( rect2.x, rect2.y + rect2.h, 0 );
// Top-right vertex (corner)
glTexCoord2f( rect1.x, rect1.y );
glVertex3f( rect2.x + rect2.w, rect2.y + rect2.h, 0 );
// Bottom-right vertex (corner)
glTexCoord2f( rect1.x, rect1.y + rect1.h);
glVertex3f( rect2.x + rect2.w, rect2.y, 0 );
// Bottom-left vertex (corner)
glTexCoord2f( rect1.x + rect1.w, rect1.y + rect1.h);
glVertex3f( rect2.x, rect2.y, 0 );
glEnd();
}
else if(!obj->xMirror && obj->yMirror){
glBegin( GL_QUADS );
// Top-left vertex (corner)
glTexCoord2f( rect1.x, rect1.y + rect1.h );
glVertex3f( rect2.x, rect2.y + rect2.h, 0 );
// Top-right vertex (corner)
glTexCoord2f( rect1.x + rect1.w, rect1.y + rect1.h );
glVertex3f( rect2.x + rect2.w, rect2.y + rect2.h, 0 );
// Bottom-right vertex (corner)
glTexCoord2f( rect1.x + rect1.w, rect1.y);
glVertex3f( rect2.x + rect2.w, rect2.y, 0 );
// Bottom-left vertex (corner)
glTexCoord2f( rect1.x, rect1.y);
glVertex3f( rect2.x, rect2.y, 0 );
glEnd();
}
else{
glBegin( GL_QUADS );
// Top-left vertex (corner)
glTexCoord2f( rect1.x + rect1.w, rect1.y + rect1.h );
glVertex3f( rect2.x, rect2.y + rect2.h, 0 );
// Top-right vertex (corner)
glTexCoord2f( rect1.x, rect1.y + rect1.h );
glVertex3f( rect2.x + rect2.w, rect2.y + rect2.h, 0 );
// Bottom-right vertex (corner)
glTexCoord2f( rect1.x, rect1.y);
glVertex3f( rect2.x + rect2.w, rect2.y, 0 );
// Bottom-left vertex (corner)
glTexCoord2f( rect1.x + rect1.w, rect1.y);
glVertex3f( rect2.x, rect2.y, 0 );
glEnd();
}
glLoadIdentity();
return 0;
}
Uint32 GetTicks(GAME_STATE* state){
if(state->WIN.PAUSE)
state->WIN.totalPauseTime = SDL_GetTicks() - state->TICKS;
else
state->TICKS = SDL_GetTicks() - state->WIN.totalPauseTime;
return state->TICKS;
}
<file_sep>/ColliTest.c
#include "ColliTest.h"
/* Funcion para iniciar variables del juego */
int gameInit(GAME_STATE* state){
/*----PRUEBA----*/
state->objTotal = 4;
state->OBJ = malloc(state->objTotal * sizeof(OBJECT));
if(state->OBJ == NULL)
return 1;
if(loadObj(state, "data/A.txt", 0, 1))
return 1;
if(loadObj(state, "data/B.txt", 1, 1))
return 1;
if(loadObj(state, "data/C.txt", 2, 1))
return 1;
if(loadObj(state, "data/D.txt", 3, 1))
return 1;
/*----PRUEBA----*/
return 0;
}
/* Funcion del Juego */
int game(GAME_STATE* state){
/*----PRUEBA----*/
state->OBJ[0].pos.x = state->MSE.x;
state->OBJ[0].pos.y = state->MSE.y;
state->OBJ[1].pos.x = state->MSE.x;
state->OBJ[1].pos.y = state->MSE.y;
state->OBJ[2].pos.x = state->MSE.x;
state->OBJ[2].pos.y = state->MSE.y;
if(state->KEY.right)
state->OBJ[3].pos.x += 5;
if(state->KEY.left)
state->OBJ[3].pos.x -= 5;
if(state->KEY.up)
state->OBJ[3].pos.y += 5;
if(state->KEY.down)
state->OBJ[3].pos.y -= 5;
if(state->KEY.s){
state->OBJ[0].scale +=0.1;
state->OBJ[1].scale +=0.1;
state->OBJ[2].scale +=0.1;
}
if(state->KEY.d){
state->OBJ[0].scale -=0.1;
state->OBJ[1].scale -=0.1;
state->OBJ[2].scale -=0.1;
}
if(state->MSE.lButton){
state->OBJ[0].rotation +=1.5;
state->OBJ[1].rotation +=1.5;
state->OBJ[2].rotation +=1.5;
}
if(state->MSE.rButton){
state->OBJ[0].rotation -=1.5;
state->OBJ[1].rotation -=1.5;
state->OBJ[2].rotation -=1.5;
}
if(collision(&state->OBJ[0], &state->OBJ[3], state)){
state->OBJ[3].pos.x += state->OBJ[3].collResp.mag*state->OBJ[3].collResp.axis.x*0.005;
state->OBJ[3].pos.y += state->OBJ[3].collResp.mag*state->OBJ[3].collResp.axis.y*0.005;
state->OBJ[0].transparency = 0.0;
state->OBJ[1].transparency = 0.0;
state->OBJ[2].transparency = 1.0;
}
else{
state->OBJ[2].transparency = 0.0;
if(!state->OBJ[3].collResp.cirCollided){
state->OBJ[0].transparency = 1.0;
state->OBJ[1].transparency = 0.0;
}
else{
state->OBJ[0].transparency = 0.0;
state->OBJ[1].transparency = 1.0;
}
}
/*----PRUEBA----*/
return 0;
}
<file_sep>/yiHaNgine/yiHaNgine.h
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
#include "SDL/SDL_opengl.h"
/*---------
Vector 2D
---------*/
typedef struct{ // Estructura que define un vector en 2 dimensiones.
float x,y; // Componentes x e y del vector.
}VECT;
/*--------
Poligono
--------*/
typedef struct{ // Estructura que define un poligono en dos dimensiones.
VECT* point; // Vector de puntos que forman el poligono.
int pointTotal; // Total de puntos que conforman el poligono.
VECT pos; // Ubicacion del centro del poligono (para deteccion de colision circular).
float radius; // Radio del poligono (para deteccion de colision circular).
}POLY;
/*---------
Float Rect
---------*/
typedef struct{ // Estructura tipo SDL_Rect pero compuesta de floats.
float x; // Coordenada x.
float y; // Coordenada y.
float w; // Ancho.
float h; // Altura.
}QUAD;
/*---------
Colisiones
---------*/
typedef struct{ // Estructura que guarda los poligonos de colision.
POLY* poly; // Poligonos de colision para un subFrame de una animacion.
int polyTotal; // Total de poligonos de colision de un subFrame.
VECT pos; // Centro del objeto.
float radius; // Radio del objeto;
}COLLISION;
/*--------------------
Respuesta de Colision
---------------------*/
typedef struct{
int cirCollided; // Sirve como flag para indicar que los objetos han colisionado radialmente.
int objCollided; // Sirve como flag para indicar que los objetos han colisionado poligonalmente.
VECT axis; // Direccion en la que existe la menor penetracion entre objetos.
float mag; // Magnitud de la penetracion entre objetos.
}RESPONSE;
/*----------
Animaciones
----------*/
typedef struct{ // Estructura que almacena todos los datos de una animacion.
GLuint frame; // Textura en opengl que contiene la animación.
QUAD* subFrame; // Sub-imagenes de la animación (vector almacenado en memoria dinamica).
int subFrameTotal; // Total de imagenes que componen la animacion.
int subFrameCurrent; // Imagen en la que se encuentra la animacion.
int subFramePixelWidth; // Ancho de sub-imagen en pixeles.
int subFramePixelHeight; // Alto de sub-imagen en pixeles.
int loop; // La animacion se repite si loop=1.
Uint32 lastClock; // Reloj actual de animacion.
int fps; // Sub-imagenes por segundo de la animación (velocidad).
COLLISION* coll; // Bordes de colision. Si coll=NULL se hace un solo test con ancho de subframe.
}ANIMATION;
/*-------
Objetos
-------*/
typedef struct{ // Estructura que almacena los datos de cada objeto o personaje en el juego.
VECT pos; // Vector de posicion del objeto.
VECT vel; // Vector de velocidad del objeto.
VECT accel; // Vector de aceleracion del objeto.
int zPos; // Profundidad en la que se encuentra el objeto.
float mass; // Masa del objeto.
float scale; // Ampliado de imagen.
float rotation; // Rotacion de imagen.
RESPONSE collResp; // Contiene flags que indican si el objeto se encuentra colisionando.
int ghost; // Objetos con ghost=1 no colisionan.
int objCopy; // Es una copia del objeto original (objCopy=1 es copia, objCopy=0 es original).
ANIMATION* anim; // Animaciones del objeto (vector almacenado en memoria dinamica).
int animTotal; // Total de animaciones del objeto.
int animCurrent; // Animacion actual del objeto.
int camRelative; // Posicion en el renderizado del objeto es afectado por posicion de camara.
float transparency; // Transparencia del objeto, 0.0=transparente, 1.0=visible.
int xMirror; // Inversion horizontal.
int yMirror; // Inversion vertical.
}OBJECT;
/*-------
Ventana
-------*/
typedef struct{ // Estructura que almacena las propiedades de la ventana de juego.
char* NAME; // Titulo de la ventana.
char* ICON; // Icono del Motor.
SDL_Surface* SURFACE; // Puntero a superficie que contiene la ventana.
int WIDTH; // Ancho de la ventana.
int HEIGHT; // Altura de la ventana.
int BPP; // Bits por pixel a utilizar en la ventana.
int FPS; // Tasa de refresco limite del programa (FPS=0 ilimitada).
int zPosMax; // Maximo nivel de profundidad para objetos.
int polyMaxPoints; // Maximo numero de puntos para definir un poligono.
Uint32 mSeg; // Milisegundos por cada frame (solo si FPS distinto de cero).
Uint32 lastClock; // Ultimo tiempo almacenado por funcion fps();
int Quit; // Variable que controla el cierre de la ventana.
SDL_Event event; // Evento que se encarga de controlar las opciones de ventana.
int console_Enable; // Variable que controla la salida de datos por consola.
Uint32 console_FpsUpdate; // Variable que controla cada cuantos milisegundos se actualizan los fps.
Uint32 console_Clocks; // Variable que ayuda a controlar console_FpsUpdate.
int console_Frames; // Contador de Frames de juego para calcular FPS.
int fileCharLimit; // Largo maximo de caracteres en nombre de archivos de datos.
int PAUSE; // Variable que identifica si el juego se encuentra en pausa (detiene variables de tiempo).
Uint32 minPauseTime; // Tiempo minimo para que cambie el valor de la variable PAUSA al apretar la tecla p.
Uint32 totalPauseTime; // Variable que aloja el tiempo total que se ha encontrado el estado de juego en pausa.
Uint32 stateSubTicks; // Variable temporal para alojar un periodo de tiempo.
}WINDOW;
/*-----
Mouse
-----*/
typedef struct{ // Estructura con el estado del mouse.
int x; // Posicion en el eje x del mouse dentro de la ventana.
int y; // Posicion en el eje y del mouse dentro de la ventana.
int rButton; // Estado del boton derecho del mouse.
int lButton; // Estado del boton izquierdo del mouse.
}MOUSE;
/*------
Teclado
------*/
typedef struct{ // Estructura con el estado del teclado.
int up; // Estado de la tecla arriba.
int down; // Estado de la tecla abajo.
int left; // Estado de la tecla izquierda.
int right; // Estado de la tecla derecha.
int q; // Estado de la tecla q.
int w; // Estado de la tecla w.
int e; // Estado de la tecla e.
int r; // Estado de la tecla r.
int a; // Estado de la tecla a.
int s; // Estado de la tecla s.
int d; // Estado de la tecla d.
int f; // Estado de la tecla f.
int z; // Estado de la tecla z.
int x; // Estado de la tecla x.
int c; // Estado de la tecla c.
int v; // Estado de la tecla v.
int p; // Estado de la tecla p.
int space; // Estado de la tecla espacio.
int ctrl; // Estado de la tecla control izquierdo.
int alt; // Estado de la tecla alt izquierdo.
int shift; // Estado de la tecla shift izquierdo.
int tab; // Estado de la tecla tab.
int esc; // Estado de la tecla Esc.
}KEYBOARD;
/*------
Camara
-----*/
typedef struct{
VECT pos; // Vector de posicion de camara.
VECT vel; // Vector de velocidad de camara.
VECT accel; // Vector de aceleracion de camara.
VECT pan; // Vector de paneo de camara.
int width; // Ancho de camara a mostrar en pantalla.
int height; // Alto de camara a mostrar en pantalla.
}CAMERA;
/*-----------------------------
Estructura principal del juego
-----------------------------*/
typedef struct{ // Estructura principal del juego que contiene el estado actual.
WINDOW WIN; // Ventana del juego.
OBJECT* OBJ; // Vector que contiene todos los objetos del juego (almacenado en memoria dinamica).
int objTotal; // Total de objetos en el juego.
//GAME game; // Variables de juego que queremos mantener separadas del motor.
MOUSE MSE; // Variables de mouse.
KEYBOARD KEY; // Variables de teclado.
CAMERA CAM; // Camara del juego.
Uint32 TICKS; // Tiempo del estado de juego en ms (no del programa, se detiene al pausar).
Uint32 DELTA; // Delta de tiempo para frame (para calcular posicion).
}GAME_STATE;
/*------------------------
Declaracion de funciones
------------------------*/
int init(GAME_STATE*); // Valor inicial a variables de estructuras y crea ventana.
int input(GAME_STATE*); // Respuesta al teclado y mouse.
int logic(GAME_STATE*); // Deteccion de colisiones, fisica del juego, etc.
int render(GAME_STATE*); // Muestra el estado actual de juego en pantalla.
int gameInit(GAME_STATE*); // Valor inicial a variables de estructuras de objetos del juego.
int game(GAME_STATE*); // Funcion que controla toda la logica del juego.
int clean(GAME_STATE*); // Libera todas las variables almacenadas en memoria dinamica (malloc).
void fps(GAME_STATE*); // Limita los frames por segundo del programa (FPS=0 ilimitado).
Uint32 GetTicks(GAME_STATE*); // Entrega los ticks del estado de juego (NO del PROGRAMA como SDL_GetTicks).
int collision(OBJECT*, OBJECT*, GAME_STATE*); // Deteccion de colisiones entre objetos.
int polyCollision(POLY*, POLY*, RESPONSE*, RESPONSE*); // Deteccion de colisiones entre poligonos.
int cirCollision(VECT*, float, VECT*, float); // Deteccion de colisiones entre circulos mediante radios.
void polyScale(POLY*, VECT*, float); // Escala un poligono en una cantidad dada por factor y con respecto al vector center.
void polyRotate(POLY*, VECT*, float); // Rota un poligono en angle grados con respecto al punto dado por center.
void polyTranslate(POLY*, VECT*); // Traslada un poligono al vector pos.
float dot(VECT*, VECT*); // Producto punto entre dos vectores.
void normalize(VECT*); // Normaliza un vector (le da modulo unitario a un vector).
int loadObj(GAME_STATE*, char*, int, int); // Carga los datos de un archivo de texto a un objeto.
void loadImage(char*, Uint8*, GLuint*); // Carga una imagen en una textura de opengl.
int animUpdate(ANIMATION*, GAME_STATE*); // Actualiza la sub-imagen de la animacion actual de cada objeto.
int drawObj(OBJECT*, CAMERA*); // Dibuja el objeto en la pantalla usando opengl.
| 9a98230633610ea2002a0f8bb44d157df8e92a06 | [
"Markdown",
"C"
] | 8 | Markdown | yiHahoi/yiHa-N-gine | 6486e144c0cdc28413c23dba4a846448ef3d9494 | 398835ff5730a4e902f3411fea61ce37b0fcdad6 |
refs/heads/master | <repo_name>h23571113/mwdnode<file_sep>/controllers/default.js
exports.install = function () {
F.route('/', view_index);
F.route('/Register', view_Register);
F.route('/Login', view_Login);
F.route('/Registered', view_Registered, ['post']);
F.route('/Loggedin', view_Loggedin, ['post']);
F.route('/Loggedin', view_Loggedinget, ['get']);
F.route('/Edited', view_Edited, ['post']);
F.route('/Edit', view_Edit, ['post']);
F.route('/Exit', view_Exit);
// or
// F.route('/');
};
var MongoClient = require('mongodb').MongoClient,
assert = require('assert'),
ObjectID = require('mongodb').ObjectID;
var url = "mongodb://mwdgroup:235711@ds051831.mongolab.com:51831/mwd";
function view_index() {
var self = this;
self.view('index');
}
function view_Register() {
var self = this;
self.view('Register');
}
function view_Login() {
var self = this;
if (self.req.cookie('mwdcookie')) {
self.redirect("/Loggedin");
}
else
self.view('Login', self.req.cookie('mwdcookie'));
}
function view_Loggedinget() {
var self = this;
MongoClient.connect(url, function (err, db) {
assert.equal(null, err);
var collection = db.collection('login');
var objid = ObjectID.createFromHexString(self.req.cookie('mwdcookie'));
collection.findOne({ _id: objid }, {}, function (err, docs) {
if (docs == null) {
self.view('Register', "رمز عبور و یاایمیل معتبر نیست ");
}
else {
self.view('Show', docs);
}
db.close();
});
});
//var connection = new sql.Connection(config, function (err) {
// var request = connection.request();
// request.query("select * from RegisterTBL where ID ='" + self.req.cookie('mwdcookie') + "'", function (err, editreturn) {
// if (err)
// self.view('Register', err.toString());
// else {
// var selfreturns = editreturn[0];
// self.view("Show", selfreturns);
// }
// });
//});
}
function view_Registered() {
var self = this;
var model = self.post;
MongoClient.connect(url, function (err, db) {
assert.equal(null, err);
var collection = db.collection('login');
var id = 0;
var doc;
//collection.find().sort({ _id: -1 }, function (err, cursor) {
// if (err)
// self.view('Register', err.toString());
// else {
// console.log("------------------------2------------------------");
// cursor.toArray(function (error, items) {
// id = (parseInt(items[0].id) + 1).toString();
// console.log("------------------------" + id + "------------------------");
// db.close();
// });
// }
//});
collection.findOne({ 'email': model.email }, function (err, docs) {
if (docs == null) {
doc = { 'email': model.email, 'name': model.name, 'family': model.family, 'password': model.pass };
collection.insert(doc, function (err, result) {
self.view('Register', "اطلاعات با موفقیت ثبت گردید");
});
}
else {
self.view('Register', "این ایمیل قبلا ثبت شده");
}
db.close();
});
});
}
function view_Loggedin() {
var self = this;
var model = self.post;
MongoClient.connect(url, function (err, db) {
assert.equal(null, err);
var collection = db.collection('login');
collection.findOne({ 'email': model.email, 'password': model.pass }, {}, function (err, docs) {
if (docs == null) {
self.view('Login', "رمز عبور و یاایمیل معتبر نیست ");
}
else {
if (model.check == "checked") {
self.res.cookie('mwdcookie', docs._id, new Date().add('day', 1));
}
self.view('Show',docs);
}
db.close();
});
});
}
function view_Edit() {
var self = this;
var model = self.post;
MongoClient.connect(url, function (err, db) {
assert.equal(null, err);
var collection = db.collection('login');
var objid = ObjectID.createFromHexString(model.id);
collection.findOne({ _id: objid }, {}, function (err, docs) {
if (docs == null) {
self.view('Login', "رمز عبور و یاایمیل معتبر نیست ");
}
else {
self.view('Edit', docs);
}
db.close();
});
});
}
function view_Edited() {
var self = this;
var model = self.post;
MongoClient.connect(url, function (err, db) {
assert.equal(null, err);
var collection = db.collection('login');
var objid = ObjectID.createFromHexString(model.id);
collection.update({ _id: objid }, { 'email': model.email, 'name': model.name, 'family': model.family, 'password': <PASSWORD> }, function (err , docs) {
if (err)
self.view('Login', err.toString());
else {
self.view('Login', "اطلاعات با موفقیت تغییر یافت");
}
db.close();
});
});
}
function view_Exit() {
var self = this;
self.res.cookie('mwdcookie', "Deleted", new Date().add('day', -1));
self.redirect("/");
}
//getting query listh using mongodb
//var collection = db.collection('login');
//var cursor = collection.find({ 'id': '2' });
//var rows = 0;
//cursor.count(function (err, count) {
// rows = count;
//});
//var result = cursor.toArray(function (err, items) {
// for (var i = 0 ; i < rows; i++)
// console.log(items[i].email);
//}); | 950389f7412b625c5de6286bea131f2cf11a456c | [
"JavaScript"
] | 1 | JavaScript | h23571113/mwdnode | 1628adbbb97aed310d12a683b02e5fcdfd97df5e | 5e91dc4182223097226ac234c35b83d0b941e16b |
refs/heads/master | <repo_name>lework/Docker-php-fpm<file_sep>/README.md
## Docker-php-fpm


基于php-alpine基础镜像的php环境,包含常用的php扩展包
## Versioning
| Docker Tag | Git Release | Nginx Version | PHP Version | Alpine Version |
|-----|-------|-----|--------|--------|
| latest/7.3.33-fpm-alpine3.13 | Master Branch | 1.18.0 | 7.3.33 | 3.13 |
| 7.3.33-fpm-alpine3.13 | 7.3.33-fpm-alpine3.13 | 1.18.0 | 7.3.33 | 3.13 |
| 7.1.30-nginx-alpine3.9 | 7.1.30-nginx-alpine3.9 |1.14.2 | 7.1.30 | 3.9 |
| 7.1.24-fpm-alpine3.8 | 7.1.24-fpm-alpine3.8 | | 7.1.30 | 3.8 |
## Quick Start
```
docker run -tid -v ./php/src:/src -p 80:80 --cap-add sys_ptrace lework/php-fpm:latest
```
<file_sep>/Dockerfile
FROM php:7.3.33-fpm-alpine3.13
MAINTAINER Lework <<EMAIL>>
ARG WORKSPACE=/src
ENV WORKSPACE=${WORKSPACE} \
TIMEZONE=Asia/Shanghai
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories \
&& apk --update -t --no-cache add tzdata \
&& ln -snf /usr/share/zoneinfo/${TIMEZONE} /etc/localtime \
&& echo "${TIMEZONE}" > /etc/timezone \
\
&& apk add --no-cache --virtual .build-deps \
build-base \
gcc \
make \
autoconf \
musl-dev \
\
&& apk add --no-cache \
libpq \
libtool \
libcurl \
freetds \
libzip-dev \
libffi-dev \
libpng-dev \
libxml2-dev \
libxslt-dev \
libressl-dev \
libmemcached \
linux-headers \
libmcrypt-dev \
libmemcached-dev \
libjpeg-turbo-dev \
gmp-dev \
bzip2-dev \
sqlite-dev \
augeas-dev \
gettext-dev \
freetds-dev \
freetype-dev \
postgresql-dev \
imagemagick \
imagemagick-dev \
\
&& pecl install xdebug \
&& pecl install apcu \
&& pecl install igbinary \
&& pecl install memcached \
&& pecl install mongodb \
&& pecl install redis \
&& pecl install mcrypt \
&& pecl install imagick \
&& pecl install msgpack \
\
&& docker-php-ext-configure gd \
--with-gd \
--with-freetype-dir=/usr/include/ \
--with-png-dir=/usr/include/ \
--with-jpeg-dir=/usr/include/ \
&& docker-php-ext-install pdo_mysql mysqli gd bcmath exif intl xsl soap zip opcache pcntl \
pdo_dblib gettext calendar shmop sockets wddx pdo_pgsql gmp bz2 xmlrpc \
&& docker-php-ext-enable apcu redis xdebug mongodb memcached imagick mcrypt \
\
&& docker-php-source delete \
&& apk del --no-network .build-deps \
&& rm -rf /tmp/* /var/cache/apk/* ~/.pearrc \
\
&& mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini" \
&& mkdir -p /usr/local/log/ \
&& sed -i 's#;date.timezone =#date.timezone = Asia/Shanghai#g' "$PHP_INI_DIR/php.ini" \
&& sed -i 's#; max_input_vars = 1000#max_input_vars = 2000#g' "$PHP_INI_DIR/php.ini" \
&& sed -i 's#post_max_size = 8M#post_max_size = 200M#g' "$PHP_INI_DIR/php.ini" \
&& sed -i 's#upload_max_filesize = 2M#upload_max_filesize = 200M#g' "$PHP_INI_DIR/php.ini" \
&& sed -i 's#;error_log = php_errors.log#error_log = php_errors.log#g' "$PHP_INI_DIR/php.ini" \
&& sed -i 's#;pid = run/php-fpm.pid#pid = run/php-fpm.pid#g' /usr/local/etc/php-fpm.conf \
&& sed -i 's#;error_log = log/php-fpm.log#error_log = log/php-fpm.log#g' /usr/local/etc/php-fpm.conf \
&& sed -i 's#;ping.path = /ping#ping.path = /fpm-ping#g' /usr/local/etc/php-fpm.d/www.conf \
&& sed -i 's#;pm.status_path = /status#pm.status_path = /fpm-status#g' /usr/local/etc/php-fpm.d/www.conf \
&& sed -i 's#;catch_workers_output = yes#catch_workers_output = yes#g' /usr/local/etc/php-fpm.d/www.conf \
&& sed -i 's#;access.log = log/$pool.access.log#access.log = log/$pool.access.log#g' /usr/local/etc/php-fpm.d/www.conf \
&& sed -i 's#;slowlog = log/$pool.log.slow#slowlog = log/$pool.log.slow#g' /usr/local/etc/php-fpm.d/www.conf \
&& sed -i 's#;request_slowlog_timeout = 0#request_slowlog_timeout = 2#g' /usr/local/etc/php-fpm.d/www.conf \
\
&& mkdir -p ${WORKSPACE}
RUn apk add nginx curl \
&& ln -sf /dev/stdout /var/log/nginx/access.log \
&& ln -sf /dev/stderr /var/log/nginx/error.log \
&& echo '<?php phpinfo(); ?>' > ${WORKSPACE}/index.php
COPY nginx.conf /etc/nginx/nginx.conf
COPY docker-run.sh /docker-run.sh
RUN chmod +x /docker-run.sh
EXPOSE 80
VOLUME ${WORKSPACE}
WORKDIR ${WORKSPACE}
ENTRYPOINT ["/docker-run.sh"]
<file_sep>/docker-run.sh
#!/bin/sh
trap _term INT TERM QUIT
_term() {
echo "Caught SIGTERM signal!"
kill -INT `cat /usr/local/var/run/php-fpm.pid`
kill -TERM `cat /var/run/nginx.pid`
exit
}
if [ -n "$WORKSPACE" ]; then
sed -i "s#root /src;#root $WORKSPACE;#g" /etc/nginx/nginx.conf
chown www-data.www-data -R $WORKSPACE /var/lib/nginx/tmp/
fi
php-fpm --force-stderr --daemonize
status=$?
if [ $status -ne 0 ]; then
echo "Failed to start php-fpm: $status"
exit $status
fi
nginx -g "daemon on;"
status=$?
if [ $status -ne 0 ]; then
echo "Failed to start nginx: $status"
exit $status
fi
while sleep 5; do
ps aux |grep php-fpm |grep -q -v grep
FPM_STATUS=$?
ps aux |grep nginx |grep -q -v grep
NGINX_STATUS=$?
if [ $FPM_STATUS -ne 0 -o $NGINX_STATUS -ne 0 ]; then
echo "[Process]One of the processes has already exited."
exit 1
fi
done
| d5d39a6a0f5a302133021e9248ead67d0b466fb7 | [
"Markdown",
"Dockerfile",
"Shell"
] | 3 | Markdown | lework/Docker-php-fpm | 22e9c9bc0d5830f1bfa2a2d823a61f2d37a9b040 | 2cdbafba74bac6078d0b14367fc5732207fc884f |
refs/heads/master | <file_sep>package com.mode.noble.objects;
import com.mode.noble.framework.GameObject;
import com.mode.noble.framework.ObjectId;
import com.mode.noble.framework.Texture;
import com.mode.noble.window.Game;
import com.mode.noble.window.Handler;
import java.awt.*;
import java.util.LinkedList;
public class Player extends GameObject
{
//Player Dimension
private float width = 32;
private float height = 64;
//Gravity
private float gravity = 0.5f;
private final float MAX_SPEED = 10;
private Handler handler;
Texture tex = Game.getInstance();
public Player(float x , float y, Handler handler, ObjectId id)
{
super(x,x,id);
this.handler = handler;
}
public void tick(LinkedList<GameObject> object)
{
x += velX;
y += velY;
if(falling || jumping)
{
velY += gravity;
if(velY > MAX_SPEED)
{
velY = MAX_SPEED;
}
}
Collision(object);
}
private void Collision(LinkedList<GameObject> object)
{
for(int i = 0; i < handler.object.size(); i++)
{
GameObject tempObject = handler.object.get(i);
if(tempObject.getId() == ObjectId.Block)
{
if(getBoundsTop().intersects(tempObject.getBounds()))
y = tempObject.getY() + 32;
if(getBounds().intersects(tempObject.getBounds())) {
y = tempObject.getY() - height;
velY = 0;
falling = false;
jumping = false;
}
else
falling = true;
if(getBoundsRight().intersects(tempObject.getBounds()))
x = tempObject.getX() - width;
if(getBoundsLeft().intersects(tempObject.getBounds()))
x = tempObject.getX() + 35;
}
}
}
//Draws the player
public void render(Graphics g)
{
g.drawImage(tex.player[0],(int)x,(int)y,32,64,null);
}
//Bounds around the player
public Rectangle getBounds()
{
return new Rectangle((int) ((int)x+(width/2)-((width/2)/2)), (int) ((int)y+(height/2)),(int)width/2,(int)height/2);
}
public Rectangle getBoundsTop()
{
return new Rectangle((int) ((int)x+(width/2)-((width/2)/2)),(int)y,(int)width/2,(int)height/2);
}
public Rectangle getBoundsRight()
{
return new Rectangle((int) ((int)x+(width-5)), ((int)y+5),(int)5,(int)height-10);
}
public Rectangle getBoundsLeft()
{
return new Rectangle((int)x, ((int)y+5),(int)5,(int)height-10);
}
/* public Rectangle getBoundsBottum()
{
return new Rectangle((int)x,(int)y,(int)width,(int)height);
}*/
}
<file_sep>package com.mode.noble.framework;
import com.mode.noble.window.BufferedImageLoader;
import java.awt.image.BufferedImage;
public class Texture
{
SpriteSheet bs, ps;
private BufferedImage block_sheet = null;
private BufferedImage player_sheet = null;
public BufferedImage[] block = new BufferedImage[2];
public BufferedImage[] player = new BufferedImage[1];
public Texture()
{
BufferedImageLoader loader = new BufferedImageLoader();
try{
block_sheet = loader.loadImage("/testtiles.png");
player_sheet = loader.loadImage("/testsprites.png");
}catch (Exception e){
e.printStackTrace();
}
bs = new SpriteSheet(block_sheet);
ps = new SpriteSheet(player_sheet);
getTextures();
}
private void getTextures()
{
block[0] = bs.grabImage(1,1,32,32);
player[0] = ps.grabImage(1,1,32,64);//idle for player
// block[1] = bs.grabImage(10,8,32,32);
}
}
<file_sep>Noble
I wanted to implement a chess-themed game. I wanted it to be a side scroller so I could have my desired pixel effect.
The purpose of the game is to more up the nobility ranking until you are King. As of right now, the game is VERY rough, but the functionality is there.
<file_sep>package com.mode.noble.window;
import com.mode.noble.framework.GameObject;
import com.mode.noble.framework.ObjectId;
import com.mode.noble.objects.Block;
import java.awt.*;
import java.util.LinkedList;
import java.util.Random;
public class Handler
{
public LinkedList<GameObject> object = new LinkedList<GameObject>();
private GameObject tempObject;
Random rand = new Random();
public void tick()
{
for(int i = 0; i < object.size(); i++)
{
tempObject = object.get(i);
tempObject.tick(object);
}
}
public void render(Graphics g)
{
for(int i = 0; i < object.size(); i++)
{
tempObject = object.get(i);
tempObject.render(g);
}
}
public void addObject(GameObject object)
{
this.object.add(object);
}
public void removeObject(GameObject object)
{
this.object.remove(object);
}
/*public void createLevel()
{
//Left Side
for(int j = 0; j < Game.HEIGHT + 32; j += 32)
{
addObject(new Block(0,j, ObjectId.Block));
}
//Right Side
for(int j = 0; j < Game.HEIGHT + 32; j += 32)
{
addObject(new Block(Game.WIDTH - 32,j, ObjectId.Block));
}
//Floor
for(int k = 0; k < Game.WIDTH * 2; k += 32)
{
addObject(new Block(k,Game.HEIGHT - 32, ObjectId.Block));
}
//Middle
for(int l = 200; l < 600 ; l += 32)
{
addObject(new Block(l ,400, ObjectId.Block));
}
}*/
}
| eb6bd8381905cbdce928bc2bd113339e8c176abb | [
"Markdown",
"Java"
] | 4 | Java | AkiliLewis/Noble | 45d77cc7d39289d3a1596d0499d791fbf39e654f | 4076fd3372dea915996004deb7e22847fafebf73 |
refs/heads/master | <repo_name>MIEE-ACS/data-binding-example<file_sep>/WpfApp6/MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApp6
{
public class AirFlight : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public int number { get; set; }
public string destination { get; set; }
public int ticketsLeft { get; set; }
public void reserveTicket()
{
if(ticketsLeft > 0)
{
ticketsLeft--;
OnPropertyChanged("ticketsLeft");
OnPropertyChanged("description");
}
}
public override string ToString()
{
return $"{number} - {destination} - {ticketsLeft}";
}
public string description
{
get { return ToString(); }
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public ObservableCollection<AirFlight> flights { get; set; }
public MainWindow()
{
InitializeComponent();
flights = new ObservableCollection<AirFlight>();
DataContext = this;
}
private void pbAdd_Click(object sender, RoutedEventArgs e)
{
var r = new Random();
flights.Add(new AirFlight { number = r.Next(100, 999), destination = tbDestination.Text, ticketsLeft = 10 });
}
private void pbReserve_Click(object sender, RoutedEventArgs e)
{
var flight = (AirFlight) cbFlight.SelectedItem;
flight.reserveTicket();
}
}
}
| 35d5cb93b60c63911632e37638ed722355d3e838 | [
"C#"
] | 1 | C# | MIEE-ACS/data-binding-example | b7c9027387e08e1fbad57057a87a48080b048382 | 68bee0f70e0e62143d9e65fcdd3dd12b1dd38b93 |
refs/heads/master | <repo_name>cheeplusplus/simplestaticsitegen<file_sep>/docker/build.py
import os
import sssg
input_dir = "./"
if 'INPUT_SOURCE' in os.environ and len(os.environ['INPUT_SOURCE']):
input_dir = os.environ['INPUT_SOURCE']
target_dir = os.path.join(input_dir, "build")
if 'INPUT_TARGET' in os.environ and len(os.environ['INPUT_TARGET']):
target_dir = os.environ['INPUT_TARGET']
files_as_dirs = False
if 'INPUT_FILESASDIRS' in os.environ and os.environ['INPUT_FILESASDIRS'] == 'true':
files_as_dirs = True
ignore_paths = None
if 'INPUT_IGNORE' in os.environ and len(os.environ['INPUT_IGNORE']) > 0:
ignore_paths = os.environ['INPUT_IGNORE'].split(',')
debug = False
if 'SSSG_DEBUG' in os.environ and os.environ['SSSG_DEBUG'] == 'true':
print("Starting SSSG action.")
print("Current directory:", os.getcwd())
print("Input:", input_dir)
print("Target:", target_dir)
print("Files as dirs?", files_as_dirs)
print("Ignore paths:", ignore_paths)
print("Processing data...")
sssg.process_directory(input_dir, target_dir, files_as_dirs=files_as_dirs, ignore_paths=ignore_paths, debug=debug)
print("Done.")
<file_sep>/README.md
Simple Static Site Generator
===
Takes an input directory with Markdown, plain HTML, or Jinja templates and turns them into a nice static HTML website.
Recommended Python 3.6 or later.
Customization
---
In your input directory, create `.templates/
Running
---
CLI:
```
sssg [--delete] [--files-as-dirs] [--ignore *.ignore,paths/] source destination
```
Code example
```
import sssg
sssg.process_directory("input", "output")
```
Examples
---
[Creator's blog site using SSSG](https://github.com/cheeplusplus/ncn-blog)
<file_sep>/Dockerfile
FROM python:3.10-alpine
LABEL maintainer="Kauko <<EMAIL>>" \
org.label-schema.name="Simple Static Site Generator" \
org.label-schema.vendor="Kauko" \
org.label-schema.schema-version="1.0"
# Install SSSG
RUN mkdir -p /build/staging
COPY . /build/staging/
RUN pip install /build/staging
RUN rm -rf /build/staging
# Handle buildscript
RUN mkdir -p /build/run
COPY docker/build.py /build/run/
ENTRYPOINT ["python", "/build/run/build.py"]
<file_sep>/setup.py
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="sssg",
version="0.1.0",
author="Kauko",
author_email="<EMAIL>",
description="Simple static site generator with Jinja",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/cheeplusplus/simplestaticsitegen",
packages=setuptools.find_packages(),
include_package_data=True,
classifiers=(
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
),
install_requires=[
"jinja2",
"markdown",
"pymdown-extensions",
"python-frontmatter",
"pathmatch"
],
entry_points={
"console_scripts": ["sssg = sssg.__main__:main"]
}
)
<file_sep>/sssg/__init__.py
import os
import shutil
from pathlib import Path
from pathmatch import gitmatch
import inspect
import json
from jinja2 import Environment, FileSystemLoader
from markdown import Markdown
from markupsafe import Markup
import frontmatter
import urllib.request
class BuildError(Exception):
def __init__(self, message):
Exception.__init__(self, message)
class Templater(object):
'''Build templates.'''
def __init__(self, source_dir):
self.md = Markdown(extensions=[
'markdown.extensions.nl2br',
'markdown.extensions.tables',
'pymdownx.magiclink',
'pymdownx.betterem',
'pymdownx.tilde',
'pymdownx.emoji',
'pymdownx.tasklist',
'pymdownx.superfences'
])
# Don't use the built-in link as we want to be able to rewrite them
self.md.inlinePatterns.deregister("link")
template_paths = []
template_dir = os.path.join(source_dir, ".templates")
if os.path.exists(template_dir):
template_paths.append(template_dir)
cur_lib_dir = os.path.dirname(inspect.getabsfile(Templater))
default_template_dir = os.path.join(cur_lib_dir, "default_templates")
template_paths.append(default_template_dir)
self.jinja = Environment(loader=FileSystemLoader(template_paths))
self.jinja.filters["markdown"] = lambda text: Markup(self.md.convert(text))
def read_metadata(self, content):
'''Attempt to read metadata from a file.'''
post = frontmatter.loads(content)
return (post.content, post.metadata)
def render_redirect(self, meta):
template = self.jinja.get_template("redirect.html")
return template.render(**meta)
def generate_string(self, content, source_filename, **kwargs):
'''Generate output given a template string and content.'''
(con, meta) = self.read_metadata(content)
# Handle load_json
extra_data = {}
if "load_json" in meta:
p = os.path.join(os.path.dirname(source_filename), meta["load_json"])
with open(p, "r", encoding="utf-8") as f:
extra_data = json.load(f)
template = self.jinja.from_string(con)
template.filename = source_filename
return (template.render(**kwargs, **meta, **extra_data), meta)
def generate_html(self, content, source_filename, **kwargs):
'''Generate output given template HTML content.'''
(con, meta) = self.generate_string(content, source_filename, **kwargs)
if "redirect_url" in meta:
return self.render_redirect(meta)
return con
def generate_markdown(self, content, source_filename, **kwargs):
'''Generate output given template Markdown content.'''
# Convert Markdown to HTML
(con, meta) = self.generate_string(content, source_filename, **kwargs)
if "redirect_url" in meta:
return self.render_redirect(meta)
# Metadata processing
# Handle template_name
template_name = "markdown.html"
if "template_name" in meta:
template_name = "{}.html".format(meta["template_name"])
# Output template as final HTML
template = self.jinja.get_template(template_name)
return template.render(md_content=con, **kwargs, **meta)
def process_template(tmpl, source_filename, dest_filename, **kwargs):
'''Read a source file and save the template output.'''
with open(source_filename, "r", encoding="utf-8") as f:
content = f.read()
output = tmpl.generate_html(content, source_filename, **kwargs)
with open(dest_filename, "w", encoding="utf-8") as f:
f.write(output)
def process_md_template(tmpl, source_filename, dest_filename, **kwargs):
'''Read a Markdown file and save the template output.'''
with open(source_filename, "r", encoding="utf-8") as f:
content = f.read()
output = tmpl.generate_markdown(content, source_filename, **kwargs)
with open(dest_filename, "w", encoding="utf-8") as f:
f.write(output)
def process_copy_operation(source_filename, dest_filename):
'''Parse a SSSG-COPY file and save the target to the destination.'''
with open(source_filename, "r", encoding="utf-8") as f:
target_url = f.read()
if not target_url:
return
(scheme, _, _, _, _, _) = urllib.parse.urlparse(target_url)
if not scheme:
# Probably a local path, relative or otherwise
abs_target = Path(target_url)
if (not abs_target.is_absolute()):
abs_target = (Path(source_filename).parent / target_url).resolve()
if abs_target.exists():
shutil.copy2(abs_target, dest_filename)
else:
raise BuildError(f"Unable to find source file {target_url}")
else:
# Save the URL to a file
urllib.request.urlretrieve(target_url, dest_filename)
def restructure_file_as_dir(files_as_dirs, current_path, current_height=0, new_filename="index.html"):
'''Restructure "file.md" as "file/index.html", imitating Jekyll'''
basedir = current_path.parent
filename = current_path.stem
if files_as_dirs and filename != "index":
# Only increment height if not an index file
current_height = current_height + 1
ptr = ""
if current_height > 1:
ptr = "".join(map(lambda x: "../", range(current_height - 1)))
if not files_as_dirs or filename == "index":
# Don't continue
return (current_path, ptr)
target_dir = basedir / filename
if not target_dir.exists():
target_dir.mkdir()
return (target_dir / new_filename, ptr)
def find_files(dir, ignore_paths=None, relative_path=""):
'''Find files in the source directory.'''
ignore_these = []
if ignore_paths and len(ignore_paths) > 0:
if not isinstance(ignore_paths, list):
# Coerce to list
ignore_paths = list(ignore_paths)
# Construct matchers
ignore_these = [(lambda fn: gitmatch.match(p, fn)) for p in ignore_paths]
with os.scandir(dir) as it:
for entry in it:
relative_file = relative_path + "/" + entry.name
if entry.is_file():
# Handle ignore paths
if any(i(relative_file) for i in ignore_these):
# Skip this entry
continue
yield os.path.join(entry.path)
if entry.is_dir() and entry.name != "." and entry.name != ".." and entry.name != ".templates":
yield from find_files(entry.path, ignore_paths=ignore_paths, relative_path=relative_file)
def process_directory(source_dir, dest_dir, files_as_dirs=False, wipe_first=False, ignore_paths=None, debug=False):
'''Process a source directory and save results to destination.'''
# Validate source directory
source_dir = os.path.abspath(source_dir)
source_path = Path(source_dir)
if not source_path.exists():
raise FileNotFoundError("Source directory does not exist.")
# Find all files in source
contents = find_files(source_dir, ignore_paths)
# Handle destination directory
dest_dir = os.path.abspath(dest_dir)
if wipe_first and os.path.exists(dest_dir):
shutil.rmtree(dest_dir)
# Prepare templater
templater = Templater(source_dir)
file_transform = {}
# Copy to output directory
for src_path in contents:
# Get the target path
p = Path(src_path)
pp = p.parts[len(source_path.parts):]
dest_path = Path(dest_dir, *pp)
# Make sure it exists
dest_dir_path = os.path.dirname(dest_path)
if not os.path.exists(dest_dir_path):
os.makedirs(dest_dir_path)
if debug:
print(f" > {src_path}")
if src_path.endswith(".j2") or src_path.endswith(".md"):
# Run anything ending in .j2 as a template
# Assume .md files are templates so they get turned into HTML
dest_path_pure = dest_path.with_suffix("")
ptr_height = len(pp)
if src_path.endswith(".md.j2") or src_path.endswith(".md"):
# Process Markdown template
dest_path_pure = dest_path_pure.with_suffix(".html")
(dest_path_pure, ptr) = restructure_file_as_dir(files_as_dirs, dest_path_pure, ptr_height)
try:
process_md_template(templater, src_path, dest_path_pure, path_to_root=ptr)
except Exception as err:
raise BuildError(f"Failed processing markdown file: /{'/'.join(pp)}, got error: {err}") from err
else:
# Process default template
(dest_path_pure, ptr) = restructure_file_as_dir(files_as_dirs, dest_path_pure, ptr_height)
try:
process_template(templater, src_path, dest_path_pure, path_to_root=ptr)
except Exception as err:
raise BuildError(f"Failed processing template file: /{'/'.join(pp)}, got error: {err}") from err
elif src_path.endswith(".sssg-copy"):
# Copy softlinks
dest_path_pure = dest_path.with_suffix("")
try:
process_copy_operation(src_path, dest_path_pure)
except Exception as err:
raise BuildError(f"Failed file copy: /{'/'.join(pp)}, got error: {err}") from err
else:
# Copy everything else
shutil.copy2(src_path, dest_path)
<file_sep>/sssg/__main__.py
import argparse
from . import process_directory
def main():
parser = argparse.ArgumentParser()
parser.add_argument("source", help="Source directory")
parser.add_argument("destination", help="Destination directory")
parser.add_argument("-d", "--delete", action="store_true", help="Delete contents of destination directory before copying")
parser.add_argument("--files-as-dirs", action="store_true", help="Turn templated files into directories (Jekyll style)")
parser.add_argument("-i", "--ignore", action="store", help="Ignore glob (gitignore style, comma seperated)")
args = parser.parse_args()
ignore_paths = []
if args.ignore:
ignore_paths = args.ignore.split(",")
print("Processing.")
process_directory(args.source, args.destination, files_as_dirs=args.files_as_dirs, wipe_first=args.delete, ignore_paths=ignore_paths)
print("Done.")
if __name__ == "__main__":
main()
<file_sep>/Pipfile
[[source]]
url = "https://pypi.python.org/simple"
verify_ssl = true
name = "pypi"
[packages]
"jinja2" = "*"
markdown = "*"
python-frontmatter = "*"
pathmatch = "*"
pymdown-extensions = "*"
[dev-packages]
"flake8" = "*"
| fbb83ace1ca0f62cc50718bb101139d48cbfbeba | [
"Markdown",
"TOML",
"Python",
"Dockerfile"
] | 7 | Python | cheeplusplus/simplestaticsitegen | e5766e249e5aa27182914dec3687f6c474e97b1f | 12ef69885fa64c53cfa0fb91813ee6fae87d788e |
refs/heads/main | <repo_name>shrey2506/NodeJs-Crud-Operations<file_sep>/backend/Controllers/peopleControllers.js
const BlogModel =require('../Models/people')
const slugify = require('slugify')
const fs=require('fs')
const formidable=require('formidable')
exports.time=(req,res)=>{
res.json({time: Date().toString()})
}
exports.createBlog=(req,res)=>{
BlogModel.findOne({userId: req.body.blogId}).exec((err, user)=>{
if(user){
return res.status(400).json({
error: 'Blog already exists'
})
}
const {blogId,blogTitle,content, Date,}=req.body
let newBlog=new BlogModel({blogId,blogTitle,content,Date})
newBlog.slug=slugify(blogId)
newBlog.save((err, success)=>{
if(err){
return res.status(400).json({
error: err
})
}
res.json({
user: success
})
})
})
}
exports.getBlogs=(req,res)=>{
BlogModel.find({})
.exec((err,data)=>{
if(err){
return res.json({
error: 'No data of the blogs found'
})
}
res.json(data);
})
}
exports.getSingleBlog=(req,res)=>{
const slug=req.params.slug
BlogModel.findOne({slug})
.exec((err,user)=>{
if(err){
return res.json({
error: 'Blog not found'
})
}
res.json(user);
})
}
exports.deleteBlog=(req,res)=>{
const slug=req.params.slug
BlogModel.findOneAndRemove({slug})
.exec((err,data)=>{
if(err){
return res.json({
error: 'Deletion Failed'
})
}
res.json({
message: 'Blog Deleted Successfully'
})
})
}
exports.updateBlog=(req,res)=>{
const slug=req.params.slug
BlogModel.findOne({slug})
.exec((err,data)=>{
if(err){
return res.json({
error: 'Updation Failed'
})
}
// res.json(data)
const {blogTitle,content}=req.body
data.blogTitle=blogTitle,
data.content=content,
data.save((err,success)=>{
if(err){
return res.status(400).json({
error: err
})
}
res.json({
blog: success
})
})
})
}<file_sep>/backend/Routes/people.js
const express = require('express')
const router=express.Router()
const {time, createBlog,deleteBlog,getBlogs,getSingleBlog,updateBlog} =require('../Controllers/peopleControllers')
//validators
const {runValidation} =require('../Validators/')
const {userValidator} =require('../Validators/peopleValidator')
router.get('/',time)
router.post('/create-blog',userValidator ,runValidation , createBlog)
router.get('/blogs', getBlogs)
router.get('/blog/:slug', getSingleBlog)
router.delete('/remove/:slug', deleteBlog)
router.put('/blog/:slug', updateBlog)
module.exports = router<file_sep>/backend/Models/people.js
const mongoose = require('mongoose')
const crypto=require('crypto')
const blogSchema=new mongoose.Schema({
blogTitle:{
type: String,
trim: true,
required:true,
index: true
},
blogId:{
type: String,
maxLength: 3,
required:true,
index: true
},
content: {
type: String,
required: true,
unique: true,
maxlength: 100
},
Date: {
type: String,
required: true
},
mediaFile: {
data: Buffer,
contentType: String
},
slug: {
type: String,
unique: true,
index: true
},
}, {timestamp: true})
module.exports=mongoose.model('Blogs',blogSchema)<file_sep>/backend/Validators/peopleValidator.js
const {check}=require('express-validator');
exports.userValidator=[
check('blogId').not()
.isEmpty()
.withMessage('BlogId is Required')
.isLength({max: 3})
.withMessage('BlogId should not be more than 3 characters long'),
check('blogTitle').not()
.isEmpty()
.withMessage('Name is Required')
.isLength({max: 10})
.withMessage('Name should not be more than 10 characters long'),
check('Date').not()
.isEmpty()
.withMessage('Date is Required'),
check('content').not()
.isEmpty()
.withMessage('Content is Required')
.isLength({min: 10})
.withMessage('Content should be more than 10 characters long')
] | a36b9aaf5642535b2ab2aef9f4a7e0a814e88935 | [
"JavaScript"
] | 4 | JavaScript | shrey2506/NodeJs-Crud-Operations | b18562c4928eda7d4ae8b7d7cc9d303364bbc94b | 7611eebb6295e616fddacfe6b7bcf6b4ea8f0d5c |
refs/heads/main | <file_sep># @reactflow/core
## 11.7.4
### Patch Changes
- [#3166](https://github.com/wbkd/react-flow/pull/3166) [`1941c561`](https://github.com/wbkd/react-flow/commit/1941c561c9eab937c0a01747c6d188ec8c6a1bf8) - fix(nodeExtent): include node width and height
- [#3164](https://github.com/wbkd/react-flow/pull/3164) [`c8b607dc`](https://github.com/wbkd/react-flow/commit/c8b607dcddeaf80912b756b0ce8045f7974e4657) - fix(handles): always check handles below mouse while connecting
## 11.7.3
### Patch Changes
- [#3152](https://github.com/wbkd/react-flow/pull/3152) [`52dbac5a`](https://github.com/wbkd/react-flow/commit/52dbac5a56c092504256f947df7a959eb07385c6) Thanks [@bcakmakoglu](https://github.com/bcakmakoglu)! - Use all valid handles in proximity to determine the closest handle that can be snapped to
- [#3154](https://github.com/wbkd/react-flow/pull/3154) [`3a277cb1`](https://github.com/wbkd/react-flow/commit/3a277cb123a886af093cee694c289c7e139c79ef) - elevateEdgesOnSelect: adjust behaviour like elevateNodesOnSelect
## 11.7.2
### Patch Changes
- [#3060](https://github.com/wbkd/react-flow/pull/3060) [`70ec97f7`](https://github.com/wbkd/react-flow/commit/70ec97f7daec6d5401215cae3edac04aea88a3ba) - fix useNodes and useEdges bug with infinite re-renderings
- [#3064](https://github.com/wbkd/react-flow/pull/3064) [`d2d1aebc`](https://github.com/wbkd/react-flow/commit/d2d1aebc0f7fea4183406e7d1915b7fcd6995f48) - refactor(useUpdateNodeInternals): only call updateNodeDimensions once
- [#3059](https://github.com/wbkd/react-flow/pull/3059) [`4374459e`](https://github.com/wbkd/react-flow/commit/4374459ef9fec797bbc0407231f09a1acacd245b) - fix useUpdateNodeInternals type
## 11.7.1
### Patch Changes
- [#3043](https://github.com/wbkd/react-flow/pull/3043) [`cf7a7d3d`](https://github.com/wbkd/react-flow/commit/cf7a7d3dad1e73215a72a5dc72e21fd50208cdbb) - handles: handles on top of each other, reduce re-renderings
- [#3046](https://github.com/wbkd/react-flow/pull/3046) [`07b975bb`](https://github.com/wbkd/react-flow/commit/07b975bbee3580249e36a19582213b250f78093c) - base-edge: pass id to base edge path
- [#3007](https://github.com/wbkd/react-flow/pull/3007) [`c80d269b`](https://github.com/wbkd/react-flow/commit/c80d269b85a0054221f4639c328fc36a3befbe70) Thanks [@bcakmakoglu](https://github.com/bcakmakoglu)! - allow array of ids as updateNodeInternals arg
- [#3029](https://github.com/wbkd/react-flow/pull/3029) [`a3fa164c`](https://github.com/wbkd/react-flow/commit/a3fa164c34cc820c79bb031c9fd97b72a3546614) Thanks [@bcakmakoglu](https://github.com/bcakmakoglu)! - autopan: only update nodes when transform change happen
## 11.7.0
Most notable updates:
- Handles: `isConnectableStart` and `isConnectableEnd` props to configure if you can start or end a connection at a certain handle
- Edges: `updatable` option to enable updates for specific edges
- useNodesInitialized: options to configure if hidden nodes should be included (false by default)
### Minor Changes
- [#2960](https://github.com/wbkd/react-flow/pull/2960) Thanks [@bcakmakoglu](https://github.com/bcakmakoglu)! - edges: add `updatable` option
- [#2958](https://github.com/wbkd/react-flow/pull/2958) [`4d97a0ed`](https://github.com/wbkd/react-flow/commit/4d97a0ed168ce643fc0c99fa6b47cf1296d66065) - handles: add `isConnectableStart` and `isConnectableEnd` props
- [#2956](https://github.com/wbkd/react-flow/pull/2956) [`923a54c4`](https://github.com/wbkd/react-flow/commit/923a54c481b90954806202817ba844cfa7203a38) - add options for `useNodesInitialized`, ignore hidden nodes by default
### Patch Changes
- [#2926](https://github.com/wbkd/react-flow/pull/2926) Thanks [@Elringus](https://github.com/Elringus)! - fix non-passive wheel event listener violation
- [#2933](https://github.com/wbkd/react-flow/pull/2933) [`fe8cac0a`](https://github.com/wbkd/react-flow/commit/fe8cac0adb359109e0e9eafe8b9261ba354076bb) - prefix error keys with "error"
- [#2939](https://github.com/wbkd/react-flow/pull/2939) [`4a4ca171`](https://github.com/wbkd/react-flow/commit/4a4ca171955f5c8d58b23e3ad48406f1a21dc402) - add connection result to store
## 11.6.1
### Patch Changes
- Always create new edge object (fixes an issue with Redux toolkit and other immutable helper libs)
## 11.6.0
### Minor Changes
- [#2877](https://github.com/wbkd/react-flow/pull/2877) [`b8886514`](https://github.com/wbkd/react-flow/commit/b88865140c72fa7e92a883498768000cb2cc96a7) - add `isValidConnection` prop for ReactFlow component
- [#2847](https://github.com/wbkd/react-flow/pull/2847) [`16bf89f2`](https://github.com/wbkd/react-flow/commit/16bf89f2b7bbf8449c00d0e2c07c19c3ff6d2533) Thanks [@bcakmakoglu](https://github.com/bcakmakoglu)! - Add option to enable/disable replacing edge id when using `updateEdge`
### Patch Changes
- [#2895](https://github.com/wbkd/react-flow/pull/2895) [`3d5764ca`](https://github.com/wbkd/react-flow/commit/3d5764cac6548984a30cbf85899024e62fd69425) - add data-testid for controls, minimap and background
- [#2894](https://github.com/wbkd/react-flow/pull/2894) [`83fc4675`](https://github.com/wbkd/react-flow/commit/83fc467545527729633e817dbccfe59d0040da4b) - fix(nodes): blur when node gets unselected
- [#2892](https://github.com/wbkd/react-flow/pull/2892) [`5fabd272`](https://github.com/wbkd/react-flow/commit/5fabd2720f6367f75f79a45822d8f675a3b8e1cf) Thanks [@danielgek](https://github.com/danielgek) - track modifier keys on useKeypress
- [#2893](https://github.com/wbkd/react-flow/pull/2893) [`8f080bd5`](https://github.com/wbkd/react-flow/commit/8f080bd5e0e7e6c71f51eee9c9f2bc4b25182861) - fix: check if handle is connectable
## 11.5.5
### Patch Changes
- [#2834](https://github.com/wbkd/react-flow/pull/2834) [`23424ea6`](https://github.com/wbkd/react-flow/commit/23424ea6750f092210f83df17a00c89adb910d96) Thanks [@bcakmakoglu](https://github.com/bcakmakoglu)! - Add `nodes` to fit view options to allow fitting view only around specified set of nodes
- [#2836](https://github.com/wbkd/react-flow/pull/2836) [`959b1114`](https://github.com/wbkd/react-flow/commit/959b111448bba4686040473e46988be9e7befbe6) - Fix: connections for handles with bigger handles than connection radius
- [#2819](https://github.com/wbkd/react-flow/pull/2819) [`0d259b02`](https://github.com/wbkd/react-flow/commit/0d259b028558aab650546f3371a85f3bce45252f) Thanks [@bcakmakoglu](https://github.com/bcakmakoglu)! - Avoid triggering edge update if not using left mouse button
- [#2832](https://github.com/wbkd/react-flow/pull/2832) [`f3de9335`](https://github.com/wbkd/react-flow/commit/f3de9335af6cd96cd77dc77f24a944eef85384e5) - fitView: return type boolean
- [#2838](https://github.com/wbkd/react-flow/pull/2838) [`021f5a92`](https://github.com/wbkd/react-flow/commit/021f5a9210f47a968e50446cd2f9dae1f97880a4) - refactor: use key press handle modifier keys + input
- [#2839](https://github.com/wbkd/react-flow/pull/2839) [`72216ff6`](https://github.com/wbkd/react-flow/commit/72216ff62014acd2d73999053c72bd7aeed351f6) - fix PropsWithChildren: pass default generic for v17 types
## 11.5.4
### Patch Changes
- [`383a074a`](https://github.com/wbkd/react-flow/commit/383a074aeae6dbec8437fa08c7c8d8240838a84e) Thanks [@bcakmakoglu](https://github.com/bcakmakoglu)! - Check if prevClosestHandle exists in onPointerUp. Fixes connections getting stuck on last handle and connecting, even when out of connectionRadius
## 11.5.3
This release fixes some issues with the newly introduced connection radius feature. We are now not only checking the radius but the handle itself too (like in the old version). That means that you can connect to a handle that is bigger than the connection radius. We are also not snapping connections anymore when they are not valid and pass a status class to the connection line that says if the current connection is valid or not. More over we fixed a connection issue with iOS.
### Patch Changes
- [#2800](https://github.com/wbkd/react-flow/pull/2800) [`be8097ac`](https://github.com/wbkd/react-flow/commit/be8097acadca3054c3b236ce4296fc516010ef8c) - When node is not draggable, you can't move it with a selection either
- [#2803](https://github.com/wbkd/react-flow/pull/2803) [`1527795d`](https://github.com/wbkd/react-flow/commit/1527795d18c3af38c8ec7059436ea0fbf6c27bbd) - connection: add status class (valid or invalid) while in connection radius
- [#2801](https://github.com/wbkd/react-flow/pull/2801) [`3b6348a8`](https://github.com/wbkd/react-flow/commit/3b6348a8d1573afb39576327318bc172e33393c2) - fix(ios): connection error + dont snap invalid connection lines, check handle and connection radius
## 11.5.2
### Patch Changes
- [#2792](https://github.com/wbkd/react-flow/pull/2792) [`d8c679b4`](https://github.com/wbkd/react-flow/commit/d8c679b4c90c5b57d4b51e4aaa988243d6eaff5a) - Accept React 17 types as dev dependency
## 11.5.1
### Patch Changes
- [#2783](https://github.com/wbkd/react-flow/pull/2783) [`71153534`](https://github.com/wbkd/react-flow/commit/7115353418ebc7f7c81ab0e861200972bbf7dbd5) - connections: check handle below mouse before using connection radius
## 11.5.0
Lot's of improvements are coming with this release!
- **Connecting radius**: No need to drop a connection line on top of handle anymore. You only need to be close to the handle. That radius can be configured with the `connectionRadius` prop.
- **Auto pan**: When you drag a node, a selection or the connection line to the border of the pane, it will pan into that direction. That makes it easier to connect far away nodes for example. If you don't like it you can set `autoPnaOnNodeDrag` and `autoPanOnConnect` to false.
- **Touch devices**: It's finally possibleto connect nodes with the connection line on touch devices. In combination with the new auto pan and connection radius the overall UX is way better.
- **Errors**: We added an `onError` prop to get notified when an error like "couldn't find source handle" happens. This is useful if you want to log errors for example.
- **Node type**: We added a second param to the generic `Node` type. You can not only pass `NodeData` but also the type as a second param:
```ts
type MyCustomNode = Node<MyCustomNodeData, 'custom-node-type'>;
```
This makes it easier to work with different custom nodes and data types.
### Minor Changes
- [#2754](https://github.com/wbkd/react-flow/pull/2754) [`e96309b6`](https://github.com/wbkd/react-flow/commit/e96309b6a57b1071faeebf7b0547fef7fd418694) - Add auto pan for connecting and node dragging and `connectionRadius`
- [#2773](https://github.com/wbkd/react-flow/pull/2773) - Add `onError` prop to get notified when an error happens
### Patch Changes
- [#2763](https://github.com/wbkd/react-flow/pull/2763) [`85003b01`](https://github.com/wbkd/react-flow/commit/85003b01add71ea852bd5b0d2f1e7496050a6b52) - Connecting nodes: Enable connections on touch devices
- [#2620](https://github.com/wbkd/react-flow/pull/2620) - Thanks [RichSchulz](https://github.com/RichSchulz)! - Types: improve typing for node type
## 11.4.2
### Patch Changes
- [#2741](https://github.com/wbkd/react-flow/pull/2741) [`e2aff6c1`](https://github.com/wbkd/react-flow/commit/e2aff6c1e4ce54b57b724b2624367ee5fefd1c39) - chore(dependencies): update and cleanup
## 11.4.1
### Patch Changes
- [#2738](https://github.com/wbkd/react-flow/pull/2738) [`82988485`](https://github.com/wbkd/react-flow/commit/82988485b730a9e32acbdae1ddcc81b33ddccaba) - fix: fitView for subflows, context menu on right mouse pan
- [#2740](https://github.com/wbkd/react-flow/pull/2740) [`d91e619a`](https://github.com/wbkd/react-flow/commit/d91e619a70a95db99a621ede59bc05b5a7766086) Thanks [@michaelspiss](https://github.com/michaelspiss)! - EdgeRenderer: check all handles for connection mode loose
## 11.4.0
## New Features
New props for the ReactFlow component to customize the controls of the viewport and the selection box better:
1. `selectionOnDrag` prop: Selection box without extra button press (need to set `panOnDrag={false}` or `panOnDrag={[1, 2]}`)
2. `panOnDrag={[0, 1, 2]}` option to configure specific mouse buttons for panning
3. `panActivationKeyCode="Space"` key code for activating dragging (useful when using `selectionOnDrag`)
4. `selectionMode={SelectionMode.Full}`: you can chose if the selection box needs to contain a node fully (`SelectionMode.Full`) or partially (`SelectionMode.Partial`) to select it
5. `onSelectionStart` and `onSelectionEnd` events
6. `elevateNodesOnSelect`: Defines if z-index should be increased when node is selected
7. New store function `getNodes`. You can now do `store.getState().getNodes()` instead of `Array.from(store.getNodes().nodeInternals.values())`.
Thanks to @jackfishwick who helped a lot with the new panning and selection options.
### Minor Changes
- [#2678](https://github.com/wbkd/react-flow/pull/2678) [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493)
- Add new props to configure viewport controls (`selectionOnDrag`, `panActivationKeyCode`, ..)
- [#2661](https://github.com/wbkd/react-flow/pull/2661) [`7ef29108`](https://github.com/wbkd/react-flow/commit/7ef2910808aaaee029894363d52efc0c378a7654)
- panOnDrag: Use numbers for prop ([1,2] = drag via middle or right mouse button)
- selection: do not include hidden nodes
- minimap: fix onNodeClick for nodes outside the viewport
- keys: allow multi select when input is focused
### Patch Changes
- [#2695](https://github.com/wbkd/react-flow/pull/2695) [`ab2ff374`](https://github.com/wbkd/react-flow/commit/ab2ff3740618da48bd4350597e816c397f3d78ff) - Add elevateNodesOnSelect prop
- [#2660](https://github.com/wbkd/react-flow/pull/2660) [`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0) - Add `getNodes` function to the store so that you don't need to do `Array.from(store.getState().nodeInternals.values())` anymore.
- [#2659](https://github.com/wbkd/react-flow/pull/2659) [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9) - Use translateExtent correctly
- [#2657](https://github.com/wbkd/react-flow/pull/2657) [`23afb3ab`](https://github.com/wbkd/react-flow/commit/23afb3abebdb42fad284f68bec164afac609563c) - Only trigger drag event when change happened
## 11.4.0-next.1
### Minor Changes
- panOnDrag: Use numbers for prop ([1,2] = drag via middle or right mouse button)
- selection: do not include hidden nodes
- minimap: fix onNodeClick for nodes outside the viewport
- keys: allow multi select when input is focused
## 11.4.0-next.0
### Minor Changes
- [#2678](https://github.com/wbkd/react-flow/pull/2678) [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493) Thanks [@moklick](https://github.com/moklick)! - ## New Features
New props for the ReactFlow component to customize the controls of the viewport and the selection box better:
1. `selectionOnDrag` prop: Selection box without extra button press (need to set `panOnDrag={false} or `panOnDrag="RightClick"`)
2. `panOnDrag="RightClick"` option
3. `panActivationKeyCode="Space"` key code for activating dragging (useful when using `selectionOnDrag`)
4. `selectionMode={SelectionMode.Full}`: you can chose if the selection box needs to contain a node fully (`SelectionMode.Full`) or partially (`SelectionMode.Partial`) to select it
5. `onSelectionStart` and `onSelectionEnd` events
### Patch Changes
- [#2660](https://github.com/wbkd/react-flow/pull/2660) [`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0) Thanks [@moklick](https://github.com/moklick)! - Add `getNodes` function to the store so that you don't need to do `Array.from(store.getState().nodeInternals.values())` anymore.
- [#2659](https://github.com/wbkd/react-flow/pull/2659) [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9) Thanks [@moklick](https://github.com/moklick)! - Use translateExtent correctly
- [#2657](https://github.com/wbkd/react-flow/pull/2657) [`23afb3ab`](https://github.com/wbkd/react-flow/commit/23afb3abebdb42fad284f68bec164afac609563c) Thanks [@moklick](https://github.com/moklick)! - Only trigger drag event when change happened
## 11.3.2
In this update we did some changes so that we could implement the new [`<NodeResizer />`](https://reactflow.dev/docs/api/nodes/node-resizer/) component more smoothly.
### Patch Changes
- [#2646](https://github.com/wbkd/react-flow/pull/2646) [`e6b5d90f`](https://github.com/wbkd/react-flow/commit/e6b5d90f61c8ee60e817bba232a162cae2ab3e2a) - Fix getRectOfNodes
- [#2648](https://github.com/wbkd/react-flow/pull/2648) [`6ee44e07`](https://github.com/wbkd/react-flow/commit/6ee44e076eaa6908d07578a757a5187642b732ae) - Allow middle mouse pan over edges
- [#2647](https://github.com/wbkd/react-flow/pull/2647) [`aa69c207`](https://github.com/wbkd/react-flow/commit/aa69c20765e6978f4f9c8cc63ed7110dbf6d9d9d) Thanks [@neo](https://github.com/neo)! - Invalidate node trying to connect itself with the same handle
- [#2626](https://github.com/wbkd/react-flow/pull/2626) [`d29c401d`](https://github.com/wbkd/react-flow/commit/d29c401d598dbf2dcd5609b7adb8d029906a6f18) - Export the useNodeId hook, refactor how changes are applied and create a helper function
- [#2642](https://github.com/wbkd/react-flow/pull/2642) [`0df02f35`](https://github.com/wbkd/react-flow/commit/0df02f35f8d6c54dae36af18278feadc77acb2d6) - Ignore key events for nodes when input is focused
## 11.3.1
### Patch Changes
- [#2595](https://github.com/wbkd/react-flow/pull/2595) [`c828bfda`](https://github.com/wbkd/react-flow/commit/c828bfda0a8c4774bc43588640c7cca0cfdcb3f4) Thanks [@chrtze](https://github.com/chrtze)! - Fix and improve the behaviour when using nodeOrigin in combination with subflows
- [#2602](https://github.com/wbkd/react-flow/pull/2602) [`b0302ce4`](https://github.com/wbkd/react-flow/commit/b0302ce4261a992bee841bae84af347d03be690f) Thanks [@sdegueldre](https://github.com/sdegueldre)! - Don't use try catch in wrapper for checking if provider is available
- [#2601](https://github.com/wbkd/react-flow/pull/2601) [`b2c72813`](https://github.com/wbkd/react-flow/commit/b2c728137d1b53e38883f044fa447585c377a6af) Thanks [@hoondeveloper](https://github.com/hoondeveloper)! - fix isRectObject function
## 11.3.0
### Minor Changes
- [#2563](https://github.com/wbkd/react-flow/pull/2563) [`98116d43`](https://github.com/wbkd/react-flow/commit/98116d431f9fcdcc9b23a5b606a94ec0740b64cd) Thanks [@chrtze](https://github.com/chrtze)! - Export a new component "NodeToolbar" that renders a fixed element attached to a node
### Patch Changes
- [#2561](https://github.com/wbkd/react-flow/pull/2561) [`92cf497e`](https://github.com/wbkd/react-flow/commit/92cf497eb72f21af592a53f5af9770c9f1e6d940) Thanks [@moklick](https://github.com/moklick)! - Fix multi selection and fitView when nodeOrigin is used
- [#2560](https://github.com/wbkd/react-flow/pull/2560) [`a39224b3`](https://github.com/wbkd/react-flow/commit/a39224b3a80afbdb83fc4490dd5f4f2be23cd4dd) Thanks [@neo](https://github.com/neo)! - Always elevate zIndex when node is selected
- [#2573](https://github.com/wbkd/react-flow/pull/2573) [`5e8b67dd`](https://github.com/wbkd/react-flow/commit/5e8b67dd41f9bb60dcd7f5d14cc34b42c970e967) Thanks [@moklick](https://github.com/moklick)! - Fix disappearing connection line for loose flows
- [#2558](https://github.com/wbkd/react-flow/pull/2558) [`2a1c7db6`](https://github.com/wbkd/react-flow/commit/2a1c7db6b27ac0f4f81dcef2d593f4753c4321c7) Thanks [@moklick](https://github.com/moklick)! - EdgeLabelRenderer: handle multiple instances on a page
## 11.2.0
### Minor Changes
- [#2535](https://github.com/wbkd/react-flow/pull/2535) [`7902a3ce`](https://github.com/wbkd/react-flow/commit/7902a3ce3188426d5cd07cf0943a68f679e67948) Thanks [@moklick](https://github.com/moklick)! - Feat: Add edge label renderer
- [#2536](https://github.com/wbkd/react-flow/pull/2536) [`b25d499e`](https://github.com/wbkd/react-flow/commit/b25d499ec05b5c6f21ac552d03650eb37433552e) Thanks [@pengfu](https://github.com/pengfu)! - Feat: add deleteElements helper function
- [#2539](https://github.com/wbkd/react-flow/pull/2539) [`4fc1253e`](https://github.com/wbkd/react-flow/commit/4fc1253eadf9b7dd392d8dc2348f44fa8d08f931) Thanks [@moklick](https://github.com/moklick)! - Feat: add intersection helpers
- [#2530](https://github.com/wbkd/react-flow/pull/2530) [`8ba4dd5d`](https://github.com/wbkd/react-flow/commit/8ba4dd5d1d4b2e6f107c148de62aec0b688d8b21) Thanks [@moklick](https://github.com/moklick)! - Feat: Add pan and zoom to mini map
### Patch Changes
- [#2538](https://github.com/wbkd/react-flow/pull/2538) [`740659c0`](https://github.com/wbkd/react-flow/commit/740659c0e788c7572d4a1e64e1d33d60712233fc) Thanks [@neo](https://github.com/neo)! - Refactor: put React Flow in isolated stacking context
## 11.1.2
### Patch Changes
- make pro options acc type optional
- cleanup types
- fix rf id handling
- always render nodes when dragging=true
- don't apply animations to helper edge
## 11.1.1
### Patch Changes
- [`c44413d`](https://github.com/wbkd/react-flow/commit/c44413d816604ae2d6ad81ed227c3dfde1a7bd8a) Thanks [@moklick](https://github.com/moklick)! - chore(panel): dont break user selection above panel
- [`48c402c`](https://github.com/wbkd/react-flow/commit/48c402c4d3bd9e16dc91cd4c549324e57b6d5c57) Thanks [@moklick](https://github.com/moklick)! - refactor(aria-descriptions): render when disableKeyboardA11y is true
- [`3a1a365`](https://github.com/wbkd/react-flow/commit/3a1a365a63fc4564d9a8d96309908986fcc86f95) Thanks [@moklick](https://github.com/moklick)! - fix(useOnSelectionChange): repair hook closes #2484
- [`5d35094`](https://github.com/wbkd/react-flow/commit/5d350942d33ded626b3387206f0b0dee368efdfb) Thanks [@neo](https://github.com/neo)! - Add css files as sideEffects
## 11.1.0
### Minor Changes
- [`def11008`](https://github.com/wbkd/react-flow/commit/def11008d88749fec40e6fcba8bc41eea2511bab) Thanks [@moklick](https://github.com/moklick)! - New props: nodesFocusable and edgesFocusable
### Patch Changes
- [`d00faa6b`](https://github.com/wbkd/react-flow/commit/d00faa6b3e77388bfd655d4c02e9a5375bc515e4) Thanks [@moklick](https://github.com/moklick)! - Make nopan class name overwritable with class name option
## 11.0.0
### Major Changes
- **Better [Accessibility](/docs/guides/accessibility)**
- Nodes and edges are focusable, selectable, moveable and deleteable with the keyboard.
- `aria-` default attributes for all elements and controllable via `ariaLabel` options
- Keyboard controls can be disabled with the new `disableKeyboardA11y` prop
- **Better selectable edges** via new edge option: `interactionWidth` - renders invisible edge that makes it easier to interact
- **Better routing for smoothstep and step edges**: https://twitter.com/reactflowdev/status/1567535405284614145
- **Nicer edge updating behaviour**: https://twitter.com/reactflowdev/status/1564966917517021184
- **Node origin**: The new `nodeOrigin` prop lets you control the origin of a node. Useful for layouting.
- **New background pattern**: `BackgroundVariant.Cross` variant
- **[`useOnViewportChange`](/docs/api/hooks/use-on-viewport-change) hook** - handle viewport changes within a component
- **[`useOnSelectionChange`](/docs/api/hooks/use-on-selection-change) hook** - handle selection changes within a component
- **[`useNodesInitialized`](/docs/api/hooks/use-nodes-initialized) hook** - returns true if all nodes are initialized and if there is more than one node
- **Deletable option** for Nodes and edges
- **New Event handlers**: `onPaneMouseEnter`, `onPaneMouseMove` and `onPaneMouseLeave`
- **Edge `pathOptions`** for `smoothstep` and `default` edges
- **Nicer cursor defaults**: Cursor is grabbing, while dragging a node or panning
- **Pane moveable** with middle mouse button
- **Pan over nodes** when they are not draggable (`draggable=false` or `nodesDraggable` false)
- **[`<BaseEdge />`](/docs/api/edges/base-edge) component** that makes it easier to build custom edges
- **[Separately installable packages](/docs/overview/packages/)**
- @reactflow/core
- @reactflow/background
- @reactflow/controls
- @reactflow/minimap
<file_sep>import type { RefObject } from 'react';
import { clampPosition, isNumeric } from '../../utils';
import type { CoordinateExtent, Node, NodeDragItem, NodeInternals, NodeOrigin, OnError, XYPosition } from '../../types';
import { getNodePositionWithOrigin } from '../../utils/graph';
import { errorMessages } from '../../contants';
export function isParentSelected(node: Node, nodeInternals: NodeInternals): boolean {
if (!node.parentNode) {
return false;
}
const parentNode = nodeInternals.get(node.parentNode);
if (!parentNode) {
return false;
}
if (parentNode.selected) {
return true;
}
return isParentSelected(parentNode, nodeInternals);
}
export function hasSelector(target: Element, selector: string, nodeRef: RefObject<Element>): boolean {
let current = target;
do {
if (current?.matches(selector)) return true;
if (current === nodeRef.current) return false;
current = current.parentElement as Element;
} while (current);
return false;
}
// looks for all selected nodes and created a NodeDragItem for each of them
export function getDragItems(
nodeInternals: NodeInternals,
nodesDraggable: boolean,
mousePos: XYPosition,
nodeId?: string
): NodeDragItem[] {
return Array.from(nodeInternals.values())
.filter(
(n) =>
(n.selected || n.id === nodeId) &&
(!n.parentNode || !isParentSelected(n, nodeInternals)) &&
(n.draggable || (nodesDraggable && typeof n.draggable === 'undefined'))
)
.map((n) => ({
id: n.id,
position: n.position || { x: 0, y: 0 },
positionAbsolute: n.positionAbsolute || { x: 0, y: 0 },
distance: {
x: mousePos.x - (n.positionAbsolute?.x ?? 0),
y: mousePos.y - (n.positionAbsolute?.y ?? 0),
},
delta: {
x: 0,
y: 0,
},
extent: n.extent,
parentNode: n.parentNode,
width: n.width,
height: n.height,
}));
}
function clampNodeExtent(node: NodeDragItem | Node, extent?: CoordinateExtent | 'parent') {
if (!extent || extent === 'parent') {
return extent;
}
return [extent[0], [extent[1][0] - (node.width || 0), extent[1][1] - (node.height || 0)]];
}
export function calcNextPosition(
node: NodeDragItem | Node,
nextPosition: XYPosition,
nodeInternals: NodeInternals,
nodeExtent?: CoordinateExtent,
nodeOrigin: NodeOrigin = [0, 0],
onError?: OnError
): { position: XYPosition; positionAbsolute: XYPosition } {
const clampedNodeExtent = clampNodeExtent(node, node.extent || nodeExtent);
let currentExtent = clampedNodeExtent;
if (node.extent === 'parent') {
if (node.parentNode && node.width && node.height) {
const parent = nodeInternals.get(node.parentNode);
const { x: parentX, y: parentY } = getNodePositionWithOrigin(parent, nodeOrigin).positionAbsolute;
currentExtent =
parent && isNumeric(parentX) && isNumeric(parentY) && isNumeric(parent.width) && isNumeric(parent.height)
? [
[parentX + node.width * nodeOrigin[0], parentY + node.height * nodeOrigin[1]],
[
parentX + parent.width - node.width + node.width * nodeOrigin[0],
parentY + parent.height - node.height + node.height * nodeOrigin[1],
],
]
: currentExtent;
} else {
onError?.('005', errorMessages['error005']());
currentExtent = clampedNodeExtent;
}
} else if (node.extent && node.parentNode) {
const parent = nodeInternals.get(node.parentNode);
const { x: parentX, y: parentY } = getNodePositionWithOrigin(parent, nodeOrigin).positionAbsolute;
currentExtent = [
[node.extent[0][0] + parentX, node.extent[0][1] + parentY],
[node.extent[1][0] + parentX, node.extent[1][1] + parentY],
];
}
let parentPosition = { x: 0, y: 0 };
if (node.parentNode) {
const parentNode = nodeInternals.get(node.parentNode);
parentPosition = getNodePositionWithOrigin(parentNode, nodeOrigin).positionAbsolute;
}
const positionAbsolute = currentExtent
? clampPosition(nextPosition, currentExtent as CoordinateExtent)
: nextPosition;
return {
position: {
x: positionAbsolute.x - parentPosition.x,
y: positionAbsolute.y - parentPosition.y,
},
positionAbsolute,
};
}
// returns two params:
// 1. the dragged node (or the first of the list, if we are dragging a node selection)
// 2. array of selected nodes (for multi selections)
export function getEventHandlerParams({
nodeId,
dragItems,
nodeInternals,
}: {
nodeId?: string;
dragItems: NodeDragItem[];
nodeInternals: NodeInternals;
}): [Node, Node[]] {
const extentedDragItems: Node[] = dragItems.map((n) => {
const node = nodeInternals.get(n.id)!;
return {
...node,
position: n.position,
positionAbsolute: n.positionAbsolute,
};
});
return [nodeId ? extentedDragItems.find((n) => n.id === nodeId)! : extentedDragItems[0], extentedDragItems];
}
<file_sep>import { useEffect } from 'react';
import { useStoreApi } from './useStore';
import type { OnSelectionChangeFunc } from '../types';
export type UseOnSelectionChangeOptions = {
onChange?: OnSelectionChangeFunc;
};
function useOnSelectionChange({ onChange }: UseOnSelectionChangeOptions) {
const store = useStoreApi();
useEffect(() => {
store.setState({ onSelectionChange: onChange });
}, [onChange]);
}
export default useOnSelectionChange;
<file_sep># @reactflow/core
Core components and util functions of React Flow.
## Installation
```sh
npm install @reactflow/core
```
<file_sep>describe('Interaction Flow Rendering', () => {
before(() => {
cy.visit('/Interaction');
});
it('renders initial flow', () => {
cy.get('.react-flow__renderer');
cy.get('.react-flow__node').should('have.length', 4);
cy.get('.react-flow__edge').should('have.length', 2);
cy.get('.react-flow__node').children('.react-flow__handle');
});
it('tries to select a node by click', () => {
const pointerEvents = Cypress.$('.react-flow__node:first').css('pointer-events');
expect(pointerEvents).to.equal('none');
});
it('tries to select an edge by click', () => {
const pointerEvents = Cypress.$('.react-flow__edge:first').css('pointer-events');
expect(pointerEvents).to.equal('none');
});
it('toggles on capture element click', () => {
cy.get('.react-flow__captureelementclick').click();
});
it('allows node clicks when enabled', () => {
const pointerEvents = Cypress.$('.react-flow__node:first').css('pointer-events');
expect(pointerEvents).to.equal('all');
});
it('allows edge clicks when enabled', () => {
const pointerEvents = Cypress.$('.react-flow__edge:first').css('pointer-events');
expect(pointerEvents.toLowerCase()).to.equal('visiblestroke');
});
it('tries to do a selection', () => {
cy.get('body')
.type('{shift}', { release: false })
.wait(50)
.get('.react-flow__pane')
.trigger('mousedown', 1000, 50, { button: 0, force: true })
.trigger('mousemove', 1, 400, { button: 0 })
.wait(50)
.get('.react-flow__selection')
.should('not.exist');
cy.get('.react-flow__pane').trigger('mouseup', 1, 200, { force: true });
cy.get('body').type('{shift}', { release: true });
});
it('tries to connect to nodes', () => {
cy.get('.react-flow__node')
.contains('Node 3')
.find('.react-flow__handle.source')
.then(($el) => {
const pointerEvents = $el.css('pointer-events');
expect(pointerEvents).to.equal('none');
});
});
it('tries to zoom by double click', () => {
const styleBeforeZoom = Cypress.$('.react-flow__nodes').css('transform');
cy.get('.react-flow__renderer')
.dblclick()
.then(() => {
const styleAfterZoom = Cypress.$('.react-flow__nodes').css('transform');
expect(styleBeforeZoom).to.equal(styleAfterZoom);
});
});
it('tries to zoom by scroll', () => {
const styleBeforeZoom = Cypress.$('.react-flow__nodes').css('transform');
cy.get('.react-flow__renderer')
.trigger('wheel', 'topLeft', { deltaY: -200 })
.then(() => {
const styleAfterZoom = Cypress.$('.react-flow__nodes').css('transform');
expect(styleBeforeZoom).to.equal(styleAfterZoom);
});
});
it('toggles draggable mode', () => {
cy.get('.react-flow__draggable').click();
});
it('drags a node', () => {
const styleBeforeDrag = Cypress.$('.react-flow__node:first').css('transform');
cy.drag('.react-flow__node:first', { x: 325, y: 100 }).then(($el) => {
const styleAfterDrag = $el.css('transform');
expect(styleBeforeDrag).to.not.equal(styleAfterDrag);
});
});
it('toggles selectable mode', () => {
cy.get('.react-flow__selectable').click();
});
it('selects a node by click', () => {
cy.get('.react-flow__node:first').click().should('have.class', 'selected');
});
it('selects an edge by click', () => {
cy.get('.react-flow__edge:first').click({ force: true });
cy.get('.react-flow__edge:first').should('have.class', 'selected');
});
it('toggles connectable mode', () => {
cy.get('.react-flow__connectable').click();
});
it('connects two nodes', () => {
cy.get('.react-flow__node')
.contains('Node 3')
.find('.react-flow__handle.source')
.trigger('mousedown', { button: 0 });
cy.get('.react-flow__node')
.contains('Node 4')
.find('.react-flow__handle.target')
.trigger('mousemove')
.trigger('mouseup', { force: true });
cy.get('.react-flow__edge').should('have.length', 3);
});
it('toggles zoom on scroll', () => {
cy.get('.react-flow__zoomonscroll').click();
});
it('zooms by scroll', () => {
const styleBeforeZoom = Cypress.$('.react-flow__viewport').css('transform');
cy.get('.react-flow__pane')
.trigger('wheel', 'topLeft', { deltaY: 200 })
.wait(50)
.then(() => {
const styleAfterZoom = Cypress.$('.react-flow__viewport').css('transform');
expect(styleBeforeZoom).not.to.equal(styleAfterZoom);
});
});
it('toggles zoom on double click', () => {
cy.get('.react-flow__zoomondbl').click();
});
it('zooms by double click', () => {
cy.get('.react-flow__controls-zoomout').click();
const styleBeforeZoom = Cypress.$('.react-flow__viewport').css('transform');
cy.get('.react-flow__pane')
.dblclick()
.wait(50)
.then(() => {
const styleAfterZoom = Cypress.$('.react-flow__viewport').css('transform');
expect(styleBeforeZoom).not.to.equal(styleAfterZoom);
});
});
});
export {};
<file_sep>import { useCallback } from 'react';
import { useStoreApi } from '../hooks/useStore';
import type { NodeDimensionUpdate, UpdateNodeInternals } from '../types';
function useUpdateNodeInternals(): UpdateNodeInternals {
const store = useStoreApi();
return useCallback<UpdateNodeInternals>((id: string | string[]) => {
const { domNode, updateNodeDimensions } = store.getState();
const updateIds = Array.isArray(id) ? id : [id];
const updates = updateIds.reduce<NodeDimensionUpdate[]>((res, updateId) => {
const nodeElement = domNode?.querySelector(`.react-flow__node[data-id="${updateId}"]`) as HTMLDivElement;
if (nodeElement) {
res.push({ id: updateId, nodeElement, forceUpdate: true });
}
return res;
}, []);
requestAnimationFrame(() => updateNodeDimensions(updates));
}, []);
}
export default useUpdateNodeInternals;
<file_sep>import { useCallback, useMemo } from 'react';
import useViewportHelper from './useViewportHelper';
import { useStoreApi } from '../hooks/useStore';
import type {
ReactFlowInstance,
Instance,
NodeAddChange,
EdgeAddChange,
NodeResetChange,
EdgeResetChange,
NodeRemoveChange,
EdgeRemoveChange,
NodeChange,
Node,
Rect,
} from '../types';
import { getConnectedEdges } from '../utils/graph';
import { getOverlappingArea, isRectObject, nodeToRect } from '../utils';
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
export default function useReactFlow<NodeData = any, EdgeData = any>(): ReactFlowInstance<NodeData, EdgeData> {
const viewportHelper = useViewportHelper();
const store = useStoreApi();
const getNodes = useCallback<Instance.GetNodes<NodeData>>(() => {
return store
.getState()
.getNodes()
.map((n) => ({ ...n }));
}, []);
const getNode = useCallback<Instance.GetNode<NodeData>>((id) => {
return store.getState().nodeInternals.get(id);
}, []);
const getEdges = useCallback<Instance.GetEdges<EdgeData>>(() => {
const { edges = [] } = store.getState();
return edges.map((e) => ({ ...e }));
}, []);
const getEdge = useCallback<Instance.GetEdge<EdgeData>>((id) => {
const { edges = [] } = store.getState();
return edges.find((e) => e.id === id);
}, []);
const setNodes = useCallback<Instance.SetNodes<NodeData>>((payload) => {
const { getNodes, setNodes, hasDefaultNodes, onNodesChange } = store.getState();
const nodes = getNodes();
const nextNodes = typeof payload === 'function' ? payload(nodes) : payload;
if (hasDefaultNodes) {
setNodes(nextNodes);
} else if (onNodesChange) {
const changes =
nextNodes.length === 0
? nodes.map((node) => ({ type: 'remove', id: node.id } as NodeRemoveChange))
: nextNodes.map((node) => ({ item: node, type: 'reset' } as NodeResetChange<NodeData>));
onNodesChange(changes);
}
}, []);
const setEdges = useCallback<Instance.SetEdges<EdgeData>>((payload) => {
const { edges = [], setEdges, hasDefaultEdges, onEdgesChange } = store.getState();
const nextEdges = typeof payload === 'function' ? payload(edges) : payload;
if (hasDefaultEdges) {
setEdges(nextEdges);
} else if (onEdgesChange) {
const changes =
nextEdges.length === 0
? edges.map((edge) => ({ type: 'remove', id: edge.id } as EdgeRemoveChange))
: nextEdges.map((edge) => ({ item: edge, type: 'reset' } as EdgeResetChange<EdgeData>));
onEdgesChange(changes);
}
}, []);
const addNodes = useCallback<Instance.AddNodes<NodeData>>((payload) => {
const nodes = Array.isArray(payload) ? payload : [payload];
const { getNodes, setNodes, hasDefaultNodes, onNodesChange } = store.getState();
if (hasDefaultNodes) {
const currentNodes = getNodes();
const nextNodes = [...currentNodes, ...nodes];
setNodes(nextNodes);
} else if (onNodesChange) {
const changes = nodes.map((node) => ({ item: node, type: 'add' } as NodeAddChange<NodeData>));
onNodesChange(changes);
}
}, []);
const addEdges = useCallback<Instance.AddEdges<EdgeData>>((payload) => {
const nextEdges = Array.isArray(payload) ? payload : [payload];
const { edges = [], setEdges, hasDefaultEdges, onEdgesChange } = store.getState();
if (hasDefaultEdges) {
setEdges([...edges, ...nextEdges]);
} else if (onEdgesChange) {
const changes = nextEdges.map((edge) => ({ item: edge, type: 'add' } as EdgeAddChange<EdgeData>));
onEdgesChange(changes);
}
}, []);
const toObject = useCallback<Instance.ToObject<NodeData, EdgeData>>(() => {
const { getNodes, edges = [], transform } = store.getState();
const [x, y, zoom] = transform;
return {
nodes: getNodes().map((n) => ({ ...n })),
edges: edges.map((e) => ({ ...e })),
viewport: {
x,
y,
zoom,
},
};
}, []);
const deleteElements = useCallback<Instance.DeleteElements>(({ nodes: nodesDeleted, edges: edgesDeleted }) => {
const {
nodeInternals,
getNodes,
edges,
hasDefaultNodes,
hasDefaultEdges,
onNodesDelete,
onEdgesDelete,
onNodesChange,
onEdgesChange,
} = store.getState();
const nodeIds = (nodesDeleted || []).map((node) => node.id);
const edgeIds = (edgesDeleted || []).map((edge) => edge.id);
const nodesToRemove = getNodes().reduce<Node[]>((res, node) => {
const parentHit = !nodeIds.includes(node.id) && node.parentNode && res.find((n) => n.id === node.parentNode);
const deletable = typeof node.deletable === 'boolean' ? node.deletable : true;
if (deletable && (nodeIds.includes(node.id) || parentHit)) {
res.push(node);
}
return res;
}, []);
const deletableEdges = edges.filter((e) => (typeof e.deletable === 'boolean' ? e.deletable : true));
const initialHitEdges = deletableEdges.filter((e) => edgeIds.includes(e.id));
if (nodesToRemove || initialHitEdges) {
const connectedEdges = getConnectedEdges(nodesToRemove, deletableEdges);
const edgesToRemove = [...initialHitEdges, ...connectedEdges];
const edgeIdsToRemove = edgesToRemove.reduce<string[]>((res, edge) => {
if (!res.includes(edge.id)) {
res.push(edge.id);
}
return res;
}, []);
if (hasDefaultEdges || hasDefaultNodes) {
if (hasDefaultEdges) {
store.setState({
edges: edges.filter((e) => !edgeIdsToRemove.includes(e.id)),
});
}
if (hasDefaultNodes) {
nodesToRemove.forEach((node) => {
nodeInternals.delete(node.id);
});
store.setState({
nodeInternals: new Map(nodeInternals),
});
}
}
if (edgeIdsToRemove.length > 0) {
onEdgesDelete?.(edgesToRemove);
if (onEdgesChange) {
onEdgesChange(
edgeIdsToRemove.map((id) => ({
id,
type: 'remove',
}))
);
}
}
if (nodesToRemove.length > 0) {
onNodesDelete?.(nodesToRemove);
if (onNodesChange) {
const nodeChanges: NodeChange[] = nodesToRemove.map((n) => ({ id: n.id, type: 'remove' }));
onNodesChange(nodeChanges);
}
}
}
}, []);
const getNodeRect = useCallback(
(
nodeOrRect: (Partial<Node<NodeData>> & { id: Node['id'] }) | Rect
): [Rect | null, Node<NodeData> | null | undefined, boolean] => {
const isRect = isRectObject(nodeOrRect);
const node = isRect ? null : store.getState().nodeInternals.get(nodeOrRect.id);
if (!isRect && !node) {
[null, null, isRect];
}
const nodeRect = isRect ? nodeOrRect : nodeToRect(node!);
return [nodeRect, node, isRect];
},
[]
);
const getIntersectingNodes = useCallback<Instance.GetIntersectingNodes<NodeData>>(
(nodeOrRect, partially = true, nodes) => {
const [nodeRect, node, isRect] = getNodeRect(nodeOrRect);
if (!nodeRect) {
return [];
}
return (nodes || store.getState().getNodes()).filter((n) => {
if (!isRect && (n.id === node!.id || !n.positionAbsolute)) {
return false;
}
const currNodeRect = nodeToRect(n);
const overlappingArea = getOverlappingArea(currNodeRect, nodeRect);
const partiallyVisible = partially && overlappingArea > 0;
return partiallyVisible || overlappingArea >= nodeOrRect.width! * nodeOrRect.height!;
});
},
[]
);
const isNodeIntersecting = useCallback<Instance.IsNodeIntersecting<NodeData>>(
(nodeOrRect, area, partially = true) => {
const [nodeRect] = getNodeRect(nodeOrRect);
if (!nodeRect) {
return false;
}
const overlappingArea = getOverlappingArea(nodeRect, area);
const partiallyVisible = partially && overlappingArea > 0;
return partiallyVisible || overlappingArea >= nodeOrRect.width! * nodeOrRect.height!;
},
[]
);
return useMemo(() => {
return {
...viewportHelper,
getNodes,
getNode,
getEdges,
getEdge,
setNodes,
setEdges,
addNodes,
addEdges,
toObject,
deleteElements,
getIntersectingNodes,
isNodeIntersecting,
};
}, [
viewportHelper,
getNodes,
getNode,
getEdges,
getEdge,
setNodes,
setEdges,
addNodes,
addEdges,
toObject,
deleteElements,
getIntersectingNodes,
isNodeIntersecting,
]);
}
<file_sep>import { useCallback } from 'react';
import { useStoreApi } from '../hooks/useStore';
import { calcNextPosition } from './useDrag/utils';
function useUpdateNodePositions() {
const store = useStoreApi();
const updatePositions = useCallback((params: { x: number; y: number; isShiftPressed: boolean }) => {
const { nodeInternals, nodeExtent, updateNodePositions, getNodes, snapToGrid, snapGrid, onError, nodesDraggable } =
store.getState();
const selectedNodes = getNodes().filter(
(n) => n.selected && (n.draggable || (nodesDraggable && typeof n.draggable === 'undefined'))
);
// by default a node moves 5px on each key press, or 20px if shift is pressed
// if snap grid is enabled, we use that for the velocity.
const xVelo = snapToGrid ? snapGrid[0] : 5;
const yVelo = snapToGrid ? snapGrid[1] : 5;
const factor = params.isShiftPressed ? 4 : 1;
const positionDiffX = params.x * xVelo * factor;
const positionDiffY = params.y * yVelo * factor;
const nodeUpdates = selectedNodes.map((n) => {
if (n.positionAbsolute) {
const nextPosition = { x: n.positionAbsolute.x + positionDiffX, y: n.positionAbsolute.y + positionDiffY };
if (snapToGrid) {
nextPosition.x = snapGrid[0] * Math.round(nextPosition.x / snapGrid[0]);
nextPosition.y = snapGrid[1] * Math.round(nextPosition.y / snapGrid[1]);
}
const { positionAbsolute, position } = calcNextPosition(
n,
nextPosition,
nodeInternals,
nodeExtent,
undefined,
onError
);
n.position = position;
n.positionAbsolute = positionAbsolute;
}
return n;
});
updateNodePositions(nodeUpdates, true, false);
}, []);
return updatePositions;
}
export default useUpdateNodePositions;
<file_sep>import { Node, Edge } from 'reactflow';
export const nodes: Node[] = [
{
id: '1',
data: { label: 'Node 1' },
position: { x: 0, y: 0 },
},
{
id: '2',
data: { label: 'Node 2' },
position: { x: 200, y: 200 },
},
];
export const edges: Edge[] = [
{
id: 'e1',
source: '1',
target: '2',
},
];
<file_sep>export { default as ReactFlow } from './container/ReactFlow';
export { default as Handle } from './components/Handle';
export { default as EdgeText } from './components/Edges/EdgeText';
export { default as StraightEdge, getStraightPath } from './components/Edges/StraightEdge';
export { default as StepEdge } from './components/Edges/StepEdge';
export { default as BezierEdge, getBezierPath } from './components/Edges/BezierEdge';
export { default as SimpleBezierEdge, getSimpleBezierPath } from './components/Edges/SimpleBezierEdge';
export { default as SmoothStepEdge, getSmoothStepPath } from './components/Edges/SmoothStepEdge';
export { default as BaseEdge } from './components/Edges/BaseEdge';
export { internalsSymbol, rectToBox, boxToRect, getBoundsOfRects, clamp } from './utils';
export {
isNode,
isEdge,
addEdge,
getOutgoers,
getIncomers,
getConnectedEdges,
updateEdge,
getTransformForBounds,
getRectOfNodes,
getNodePositionWithOrigin,
} from './utils/graph';
export { applyNodeChanges, applyEdgeChanges } from './utils/changes';
export { getMarkerEnd } from './components/Edges/utils';
export { default as ReactFlowProvider } from './components/ReactFlowProvider';
export { default as Panel } from './components/Panel';
export { default as EdgeLabelRenderer } from './components/EdgeLabelRenderer';
export { default as useReactFlow } from './hooks/useReactFlow';
export { default as useUpdateNodeInternals } from './hooks/useUpdateNodeInternals';
export { default as useNodes } from './hooks/useNodes';
export { default as useEdges } from './hooks/useEdges';
export { default as useViewport } from './hooks/useViewport';
export { default as useKeyPress } from './hooks/useKeyPress';
export * from './hooks/useNodesEdgesState';
export { useStore, useStoreApi } from './hooks/useStore';
export { default as useOnViewportChange, type UseOnViewportChangeOptions } from './hooks/useOnViewportChange';
export { default as useOnSelectionChange, type UseOnSelectionChangeOptions } from './hooks/useOnSelectionChange';
export { default as useNodesInitialized, type UseNodesInitializedOptions } from './hooks/useNodesInitialized';
export { default as useGetPointerPosition } from './hooks/useGetPointerPosition';
export { useNodeId } from './contexts/NodeIdContext';
export * from './types';
<file_sep>
<div align="center">




A highly customizable React component for building interactive graphs and node-based editors.
[🚀 Getting Started](https://reactflow.dev/docs/getting-started/installation) | [📖 Documentation](https://reactflow.dev/docs/api/react-flow-props) | [📺 Examples](https://reactflow.dev/docs/examples/overview) | [☎️ Discord](https://discord.gg/RVmnytFmGW) | [💎 React Flow Pro](https://pro.reactflow.dev/pricing)
</div>
---
## 🚨 Upcoming Changes
The main branch (v11) is now in a feature freeze. The next version is being developed in the [xyflow branch](https://github.com/wbkd/react-flow/tree/xyflow).
Find out more about the those changes [here](https://wbkd.notion.site/Upcoming-Changes-at-React-Flow-1a443641891a4069927c0a115e915251).
## Key Features
- **Easy to use:** Seamless zooming and panning, single- and multi selection of graph elements and keyboard shortcuts are supported out of the box
- **Customizable:** Different [node](https://reactflow.dev/docs/api/nodes/node-types) and [edge types](https://reactflow.dev/docs/api/edges/edge-types) and support for custom nodes with multiple handles and custom edges
- **Fast rendering:** Only nodes that have changed are re-rendered and only those in the viewport are displayed
- **Hooks and Utils:** [Hooks](https://reactflow.dev/docs/api/hooks/use-react-flow) for handling nodes, edges and the viewport and graph [helper functions](https://reactflow.dev/docs/api/graph-util-functions)
- **Plugin Components:** [Background](https://reactflow.dev/docs/api/plugin-components/background), [MiniMap](https://reactflow.dev/docs/api/plugin-components/minimap) and [Controls](https://reactflow.dev/docs/api/plugin-components/controls)
- **Reliable**: Written in [Typescript](https://www.typescriptlang.org/) and tested with [cypress](https://www.cypress.io/)
## Commercial Usage
**Are you using React Flow for a personal project?** Great! No sponsorship needed, you can support us by reporting any bugs you find, sending us screenshots of your projects, and starring us on Github 🌟
**Are you using React Flow at your organization and making money from it?** Awesome! We rely on your support to keep React Flow developed and maintained under an MIT License, just how we like it. You can do that on the [React Flow Pro website](https://pro.reactflow.dev) or through [Github Sponsors](https://github.com/sponsors/wbkd).
You can find more information in our [React Flow Pro FAQs](https://pro.reactflow.dev/info).
## Installation
The easiest way to get the latest version of React Flow is to install it via npm, yarn or pnpm:
```bash
npm install reactflow
```
## Quick Start
This is only a very basic usage example of React Flow. To see everything that is possible with the library, please refer to the [website](https://reactflow.dev) for [guides](https://reactflow.dev/docs/guides/custom-nodes), [examples](https://reactflow.dev/docs/examples/overview) and [API reference](https://reactflow.dev/docs/api/react-flow-props).
```jsx
import { useCallback } from 'react';
import ReactFlow, {
MiniMap,
Controls,
Background,
useNodesState,
useEdgesState,
addEdge,
} from 'reactflow';
import 'reactflow/dist/style.css';
const initialNodes = [
{ id: '1', position: { x: 0, y: 0 }, data: { label: '1' } },
{ id: '2', position: { x: 0, y: 100 }, data: { label: '2' } },
];
const initialEdges = [{ id: 'e1-2', source: '1', target: '2' }];
function Flow() {
const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes);
const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges);
const onConnect = useCallback((params) => setEdges((eds) => addEdge(params, eds)), [setEdges]);
return (
<ReactFlow
nodes={nodes}
edges={edges}
onNodesChange={onNodesChange}
onEdgesChange={onEdgesChange}
onConnect={onConnect}
>
<MiniMap />
<Controls />
<Background />
</ReactFlow>
);
}
```
## Development
Before you can start developing please make sure that you have [pnpm](https://pnpm.io/) installed (`npm i -g pnpm`). Then install the dependencies using pnpm: `pnpm install`.
For local development, you can use `pnpm dev`.
## Testing
Testing is done with cypress. You can find the tests in the [`examples/cypress`](/examples/cypress/) folder. In order to run the tests do:
```sh
pnpm test
```
## Maintainers
React Flow is developed and maintained by [webkid](https://webkid.io), a web development agency with focus on data driven applications from Berlin. If you need help or want to talk to us about a collaboration, feel free to contact us:
- <NAME> • [Twitter](https://twitter.com/moklick) • [Github](https://github.com/moklick)
- <NAME> • [Twitter](https://twitter.com/chrtze) • [Github](https://github.com/chrtze)
You can also use our [contact form](https://pro.reactflow.dev/contact) or join the [React Flow Discord Server](https://discord.gg/Bqt6xrs).
## Community Packages
- [useUndoable](https://github.com/Infinium8/useUndoable) - Hook for undo/redo functionality with an explicit React Flow example
- [react-flow-smart-edge](https://github.com/tisoap/react-flow-smart-edge) - Custom edge that doesn't intersect with nodes
- [Feliz.ReactFlow](https://github.com/tforkmann/Feliz.ReactFlow) - Feliz React Bindings for React Flow
## Credits
React Flow was initially developed for [datablocks](https://datablocks.pro), a graph-based editor for transforming, analyzing and visualizing data in the browser. Under the hood, React Flow depends on these great libraries:
- [d3-zoom](https://github.com/d3/d3-zoom) - used for zoom, pan and drag interactions with the graph canvas
- [d3-drag](https://github.com/d3/d3-drag) - used for making the nodes draggable
- [zustand](https://github.com/pmndrs/zustand) - internal state management
## License
React Flow is [MIT licensed](https://github.com/wbkd/react-flow/blob/main/LICENSE).
<file_sep>import { MouseEvent as ReactMouseEvent, TouchEvent as ReactTouchEvent } from 'react';
import { ConnectingHandle, ConnectionMode, ConnectionStatus } from '../../types';
import { getEventPosition, internalsSymbol } from '../../utils';
import type { Connection, HandleType, XYPosition, Node, NodeHandleBounds } from '../../types';
export type ConnectionHandle = {
id: string | null;
type: HandleType | null;
nodeId: string;
x: number;
y: number;
};
export type ValidConnectionFunc = (connection: Connection) => boolean;
// this functions collects all handles and adds an absolute position
// so that we can later find the closest handle to the mouse position
export function getHandles(
node: Node,
handleBounds: NodeHandleBounds,
type: HandleType,
currentHandle: string
): ConnectionHandle[] {
return (handleBounds[type] || []).reduce<ConnectionHandle[]>((res, h) => {
if (`${node.id}-${h.id}-${type}` !== currentHandle) {
res.push({
id: h.id || null,
type,
nodeId: node.id,
x: (node.positionAbsolute?.x ?? 0) + h.x + h.width / 2,
y: (node.positionAbsolute?.y ?? 0) + h.y + h.height / 2,
});
}
return res;
}, []);
}
export function getClosestHandle(
event: MouseEvent | TouchEvent | ReactMouseEvent | ReactTouchEvent,
doc: Document | ShadowRoot,
pos: XYPosition,
connectionRadius: number,
handles: ConnectionHandle[],
validator: (handle: Pick<ConnectionHandle, 'nodeId' | 'id' | 'type'>) => Result
) {
// we always want to prioritize the handle below the mouse cursor over the closest distance handle,
// because it could be that the center of another handle is closer to the mouse pointer than the handle below the cursor
const { x, y } = getEventPosition(event);
const domNodes = doc.elementsFromPoint(x, y);
const handleBelow = domNodes.find((el) => el.classList.contains('react-flow__handle'));
if (handleBelow) {
const handleNodeId = handleBelow.getAttribute('data-nodeid');
if (handleNodeId) {
const handleType = getHandleType(undefined, handleBelow);
const handleId = handleBelow.getAttribute('data-handleid');
const validHandleResult = validator({ nodeId: handleNodeId, id: handleId, type: handleType });
if (validHandleResult) {
return {
handle: {
id: handleId,
type: handleType,
nodeId: handleNodeId,
x: pos.x,
y: pos.y,
},
validHandleResult,
};
}
}
}
// if we couldn't find a handle below the mouse cursor we look for the closest distance based on the connectionRadius
let closestHandles: { handle: ConnectionHandle; validHandleResult: Result }[] = [];
let minDistance = Infinity;
handles.forEach((handle) => {
const distance = Math.sqrt((handle.x - pos.x) ** 2 + (handle.y - pos.y) ** 2);
if (distance <= connectionRadius) {
const validHandleResult = validator(handle);
if (distance <= minDistance) {
if (distance < minDistance) {
closestHandles = [{ handle, validHandleResult }];
} else if (distance === minDistance) {
// when multiple handles are on the same distance we collect all of them
closestHandles.push({
handle,
validHandleResult,
});
}
minDistance = distance;
}
}
});
if (!closestHandles.length) {
return { handle: null, validHandleResult: defaultResult() };
}
if (closestHandles.length === 1) {
return closestHandles[0];
}
const hasValidHandle = closestHandles.some(({ validHandleResult }) => validHandleResult.isValid);
const hasTargetHandle = closestHandles.some(({ handle }) => handle.type === 'target');
// if multiple handles are layouted on top of each other we prefer the one with type = target and the one that is valid
return (
closestHandles.find(({ handle, validHandleResult }) =>
hasTargetHandle ? handle.type === 'target' : true && (hasValidHandle ? validHandleResult.isValid : true)
) || closestHandles[0]
);
}
type Result = {
handleDomNode: Element | null;
isValid: boolean;
connection: Connection;
endHandle: ConnectingHandle | null;
};
const nullConnection: Connection = { source: null, target: null, sourceHandle: null, targetHandle: null };
const defaultResult = (): Result => ({
handleDomNode: null,
isValid: false,
connection: nullConnection,
endHandle: null,
});
// checks if and returns connection in fom of an object { source: 123, target: 312 }
export function isValidHandle(
handle: Pick<ConnectionHandle, 'nodeId' | 'id' | 'type'>,
connectionMode: ConnectionMode,
fromNodeId: string,
fromHandleId: string | null,
fromType: HandleType,
isValidConnection: ValidConnectionFunc,
doc: Document | ShadowRoot
) {
const isTarget = fromType === 'target';
const handleToCheck = doc.querySelector(
`.react-flow__handle[data-id="${handle?.nodeId}-${handle?.id}-${handle?.type}"]`
);
const result = {
...defaultResult(),
handleDomNode: handleToCheck,
};
if (handleToCheck) {
const handleType = getHandleType(undefined, handleToCheck);
const handleNodeId = handleToCheck.getAttribute('data-nodeid');
const handleId = handleToCheck.getAttribute('data-handleid');
const connectable = handleToCheck.classList.contains('connectable');
const connectableEnd = handleToCheck.classList.contains('connectableend');
const connection: Connection = {
source: isTarget ? handleNodeId : fromNodeId,
sourceHandle: isTarget ? handleId : fromHandleId,
target: isTarget ? fromNodeId : handleNodeId,
targetHandle: isTarget ? fromHandleId : handleId,
};
result.connection = connection;
const isConnectable = connectable && connectableEnd;
// in strict mode we don't allow target to target or source to source connections
const isValid =
isConnectable &&
(connectionMode === ConnectionMode.Strict
? (isTarget && handleType === 'source') || (!isTarget && handleType === 'target')
: handleNodeId !== fromNodeId || handleId !== fromHandleId);
if (isValid) {
result.endHandle = {
nodeId: handleNodeId as string,
handleId,
type: handleType as HandleType,
};
result.isValid = isValidConnection(connection);
}
}
return result;
}
type GetHandleLookupParams = {
nodes: Node[];
nodeId: string;
handleId: string | null;
handleType: string;
};
export function getHandleLookup({ nodes, nodeId, handleId, handleType }: GetHandleLookupParams) {
return nodes.reduce<ConnectionHandle[]>((res, node) => {
if (node[internalsSymbol]) {
const { handleBounds } = node[internalsSymbol];
let sourceHandles: ConnectionHandle[] = [];
let targetHandles: ConnectionHandle[] = [];
if (handleBounds) {
sourceHandles = getHandles(node, handleBounds, 'source', `${nodeId}-${handleId}-${handleType}`);
targetHandles = getHandles(node, handleBounds, 'target', `${nodeId}-${handleId}-${handleType}`);
}
res.push(...sourceHandles, ...targetHandles);
}
return res;
}, []);
}
export function getHandleType(
edgeUpdaterType: HandleType | undefined,
handleDomNode: Element | null
): HandleType | null {
if (edgeUpdaterType) {
return edgeUpdaterType;
} else if (handleDomNode?.classList.contains('target')) {
return 'target';
} else if (handleDomNode?.classList.contains('source')) {
return 'source';
}
return null;
}
export function resetRecentHandle(handleDomNode: Element): void {
handleDomNode?.classList.remove('valid', 'connecting', 'react-flow__handle-valid', 'react-flow__handle-connecting');
}
export function getConnectionStatus(isInsideConnectionRadius: boolean, isHandleValid: boolean) {
let connectionStatus = null;
if (isHandleValid) {
connectionStatus = 'valid';
} else if (isInsideConnectionRadius && !isHandleValid) {
connectionStatus = 'invalid';
}
return connectionStatus as ConnectionStatus;
}
<file_sep>describe('Empty Flow Rendering', () => {
before(() => {
cy.visit('/Empty');
});
it('renders an empty flow', () => {
cy.get('.react-flow__renderer');
cy.get('.react-flow__node').should('not.exist');
cy.get('.react-flow__edge').should('not.exist');
});
it('renders empty selection', () => {
cy.get('.react-flow__renderer').click();
cy.get('body')
.type('{shift}', { release: false })
.wait(50)
.get('.react-flow__pane')
.trigger('mousedown', 400, 50, { button: 0, force: true })
.trigger('mousemove', 200, 200, { button: 0 })
.wait(50)
.trigger('mouseup', 200, 200, { force: true });
cy.get('body').type('{shift}', { release: true });
});
it('adds two nodes', () => {
cy.contains('add node').click();
cy.contains('add node').click();
});
it('connects nodes', () => {
cy.get('.react-flow__node').first().find('.react-flow__handle.source').trigger('mousedown', { button: 0 });
cy.get('.react-flow__node')
.last()
.find('.react-flow__handle.target')
.trigger('mousemove')
.trigger('mouseup', { force: true });
cy.get('.react-flow__edge').should('have.length', 1);
});
});
export {};
<file_sep># @reactflow/node-resizer
## 2.1.1
### Patch Changes
- [#3150](https://github.com/wbkd/react-flow/pull/3150) [`880a5932`](https://github.com/wbkd/react-flow/commit/880a593292ce5fdff30b656c2a1290cf98771818) Thanks [@goliney](https://github.com/goliney)! - add onResize/onResizeStart/onResizeEnd to useEffect deps
- Updated dependencies [[`52dbac5a`](https://github.com/wbkd/react-flow/commit/52dbac5a56c092504256f947df7a959eb07385c6), [`3a277cb1`](https://github.com/wbkd/react-flow/commit/3a277cb123a886af093cee694c289c7e139c79ef)]:
- @reactflow/core@11.7.3
## 2.1.0
### Minor Changes
- [#2900](https://github.com/wbkd/react-flow/pull/2900) [`b1190837`](https://github.com/wbkd/react-flow/commit/b11908370bc438ca8d4179497cd4eb1f8c656798) Thanks [@stffabi](https://github.com/stffabi)! - add `maxWidth` and `maxHeight` props
- [#2900](https://github.com/wbkd/react-flow/pull/2900) [`b1190837`](https://github.com/wbkd/react-flow/commit/b11908370bc438ca8d4179497cd4eb1f8c656798) - add `keepAspectRatio` prop
### Patch Changes
- Updated dependencies [[`3d5764ca`](https://github.com/wbkd/react-flow/commit/3d5764cac6548984a30cbf85899024e62fd69425), [`83fc4675`](https://github.com/wbkd/react-flow/commit/83fc467545527729633e817dbccfe59d0040da4b), [`b1190837`](https://github.com/wbkd/react-flow/commit/b11908370bc438ca8d4179497cd4eb1f8c656798), [`5fabd272`](https://github.com/wbkd/react-flow/commit/5fabd2720f6367f75f79a45822d8f675a3b8e1cf), [`8f080bd5`](https://github.com/wbkd/react-flow/commit/8f080bd5e0e7e6c71f51eee9c9f2bc4b25182861), [`b8886514`](https://github.com/wbkd/react-flow/commit/b88865140c72fa7e92a883498768000cb2cc96a7), [`16bf89f2`](https://github.com/wbkd/react-flow/commit/16bf89f2b7bbf8449c00d0e2c07c19c3ff6d2533)]:
- @reactflow/core@11.6.0
## 2.0.1
### Patch Changes
- [#2792](https://github.com/wbkd/react-flow/pull/2792) [`d8c679b4`](https://github.com/wbkd/react-flow/commit/d8c679b4c90c5b57d4b51e4aaa988243d6eaff5a) - Accept React 17 types as dev dependency
- Updated dependencies [[`d8c679b4`](https://github.com/wbkd/react-flow/commit/d8c679b4c90c5b57d4b51e4aaa988243d6eaff5a)]:
- @reactflow/core@11.5.2
## 2.0.0
After this update it should be easier to update the node resizer (no need to update the reactflow package anymore).
New props:
- `shouldResize`: user can pass a function that determines if resize should be executed
- `direction`: gets passed as an attribute on resize
### Major Changes
- [#2749](https://github.com/wbkd/react-flow/pull/2749) [`e347dd82`](https://github.com/wbkd/react-flow/commit/e347dd82d342bf9c4884ca667afaa5cf639283e5) - Add `shouldResize`, rename and cleanup types - `ResizeEventParams` is now `ResizeParams`
### Patch Changes
- Updated dependencies [[`e96309b6`](https://github.com/wbkd/react-flow/commit/e96309b6a57b1071faeebf7b0547fef7fd418694), [`85003b01`](https://github.com/wbkd/react-flow/commit/85003b01add71ea852bd5b0d2f1e7496050a6b52), [`4c516882`](https://github.com/wbkd/react-flow/commit/4c516882d2bbf426c1832a53ad40763cc1abef92)]:
- @reactflow/core@11.5.0
## 1.2.2
### Patch Changes
- [#2741](https://github.com/wbkd/react-flow/pull/2741) [`e2aff6c1`](https://github.com/wbkd/react-flow/commit/e2aff6c1e4ce54b57b724b2624367ee5fefd1c39) - chore(dependencies): update and cleanup
- Updated dependencies [[`e34a3072`](https://github.com/wbkd/react-flow/commit/e34a30726dc55184f59adc4f16ca5215a7c42805), [`e2aff6c1`](https://github.com/wbkd/react-flow/commit/e2aff6c1e4ce54b57b724b2624367ee5fefd1c39)]:
- @reactflow/core@11.4.2
## 1.2.1
### Patch Changes
- Updated dependencies [[`82988485`](https://github.com/wbkd/react-flow/commit/82988485b730a9e32acbdae1ddcc81b33ddccaba), [`d91e619a`](https://github.com/wbkd/react-flow/commit/d91e619a70a95db99a621ede59bc05b5a7766086)]:
- @reactflow/core@11.4.1
## 1.2.0
### Patch Changes
- Updated dependencies [[`ab2ff374`](https://github.com/wbkd/react-flow/commit/ab2ff3740618da48bd4350597e816c397f3d78ff), [`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0), [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493), [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9), [`7ef29108`](https://github.com/wbkd/react-flow/commit/7ef2910808aaaee029894363d52efc0c378a7654), [`23afb3ab`](https://github.com/wbkd/react-flow/commit/23afb3abebdb42fad284f68bec164afac609563c)]:
- @reactflow/core@11.4.0
## 1.2.0-next.1
### Minor Changes
- panOnDrag: Use numbers for prop ([1,2] = drag via middle or right mouse button)
- selection: do not include hidden nodes
- minimap: fix onNodeClick for nodes outside the viewport
- keys: allow multi select when input is focused
### Patch Changes
- Updated dependencies []:
- @reactflow/core@11.4.0-next.1
## 1.1.1-next.0
### Patch Changes
- Updated dependencies [[`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0), [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493), [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9), [`23afb3ab`](https://github.com/wbkd/react-flow/commit/23afb3abebdb42fad284f68bec164afac609563c)]:
- @reactflow/core@11.4.0-next.0
## 1.1.0
### Minor Changes
- Add `onResizeStart`, `onResize`, `onResizeEnd` handlers
- Fix resizing flag
- Cleanup types
## 1.0.3
### Patch Changes
- cleanup
## 1.0.2
### Patch Changes
- fix `minWidth` and `minHeight` so that it can be used dynamically
## 1.0.1
### Patch Changes
- pass `minWidth` and `minHeight` from `NodeResizer` component to `NodeResizeControl`
## 1.0.0
This is a new package that exports components to build a UI for resizing a node 🎉 It exports a [`<NodeResizer />`](https://reactflow.dev/docs/api/nodes/node-resizer/) component and a [`<NodeResizeControl />`](https://reactflow.dev/docs/api/nodes/node-resizer/#noderesizecontrol--component) component.
### Major Changes
- [#2626](https://github.com/wbkd/react-flow/pull/2626) [`d29c401d`](https://github.com/wbkd/react-flow/commit/d29c401d598dbf2dcd5609b7adb8d029906a6f18) - Add a node resizer component that can be used to resize a custom node
### Patch Changes
- Updated dependencies [[`e6b5d90f`](https://github.com/wbkd/react-flow/commit/e6b5d90f61c8ee60e817bba232a162cae2ab3e2a), [`6ee44e07`](https://github.com/wbkd/react-flow/commit/6ee44e076eaa6908d07578a757a5187642b732ae), [`aa69c207`](https://github.com/wbkd/react-flow/commit/aa69c20765e6978f4f9c8cc63ed7110dbf6d9d9d), [`d29c401d`](https://github.com/wbkd/react-flow/commit/d29c401d598dbf2dcd5609b7adb8d029906a6f18), [`0df02f35`](https://github.com/wbkd/react-flow/commit/0df02f35f8d6c54dae36af18278feadc77acb2d6)]:
- @reactflow/core@11.3.2
<file_sep># @reactflow/minimap
## 11.5.4
### Patch Changes
- Updated dependencies [[`1941c561`](https://github.com/wbkd/react-flow/commit/1941c561c9eab937c0a01747c6d188ec8c6a1bf8), [`c8b607dc`](https://github.com/wbkd/react-flow/commit/c8b607dcddeaf80912b756b0ce8045f7974e4657)]:
- @reactflow/core@11.7.4
## 11.5.3
### Patch Changes
- [#3153](https://github.com/wbkd/react-flow/pull/3153) [`fbbee046`](https://github.com/wbkd/react-flow/commit/fbbee046282d466612089d31a2eff5a010733283) - Improve performance for flows with lots of nodes that use the MiniMap component
- Updated dependencies [[`52dbac5a`](https://github.com/wbkd/react-flow/commit/52dbac5a56c092504256f947df7a959eb07385c6), [`3a277cb1`](https://github.com/wbkd/react-flow/commit/3a277cb123a886af093cee694c289c7e139c79ef)]:
- @reactflow/core@11.7.3
## 11.5.2
### Patch Changes
- Updated dependencies [[`70ec97f7`](https://github.com/wbkd/react-flow/commit/70ec97f7daec6d5401215cae3edac04aea88a3ba), [`d2d1aebc`](https://github.com/wbkd/react-flow/commit/d2d1aebc0f7fea4183406e7d1915b7fcd6995f48), [`4374459e`](https://github.com/wbkd/react-flow/commit/4374459ef9fec797bbc0407231f09a1acacd245b)]:
- @reactflow/core@11.7.2
## 11.5.1
### Patch Changes
- Updated dependencies [[`cf7a7d3d`](https://github.com/wbkd/react-flow/commit/cf7a7d3dad1e73215a72a5dc72e21fd50208cdbb), [`07b975bb`](https://github.com/wbkd/react-flow/commit/07b975bbee3580249e36a19582213b250f78093c), [`c80d269b`](https://github.com/wbkd/react-flow/commit/c80d269b85a0054221f4639c328fc36a3befbe70), [`a3fa164c`](https://github.com/wbkd/react-flow/commit/a3fa164c34cc820c79bb031c9fd97b72a3546614)]:
- @reactflow/core@11.7.1
## 11.5.0
### Minor Changes
- [#2944](https://github.com/wbkd/react-flow/pull/2944) Thanks [@Elringus](https://github.com/Elringus)! - add `inversePan` and `zoomStep` props
### Patch Changes
- Updated dependencies [[`098eee3d`](https://github.com/wbkd/react-flow/commit/098eee3d41dabc870777b081796401ff13b5a776), [`fe8cac0a`](https://github.com/wbkd/react-flow/commit/fe8cac0adb359109e0e9eafe8b9261ba354076bb), [`4a4ca171`](https://github.com/wbkd/react-flow/commit/4a4ca171955f5c8d58b23e3ad48406f1a21dc402), [`923a54c4`](https://github.com/wbkd/react-flow/commit/923a54c481b90954806202817ba844cfa7203a38), [`4d97a0ed`](https://github.com/wbkd/react-flow/commit/4d97a0ed168ce643fc0c99fa6b47cf1296d66065), [`c22e1c28`](https://github.com/wbkd/react-flow/commit/c22e1c28c5555a638c2a8e82c3bfc986b3965d36)]:
- @reactflow/core@11.7.0
## 11.4.1
### Patch Changes
- Updated dependencies
## 11.4.0
### Minor Changes
- [#2906](https://github.com/wbkd/react-flow/pull/2906) [`4a30185a`](https://github.com/wbkd/react-flow/commit/4a30185a12899691ff61259f0db84bc5494cb573) Thanks [@hayleigh-dot-dev](https://github.com/hayleigh-dot-dev)! - Add `nodeComponent` prop for passing custom component for the nodes
### Patch Changes
- [#2895](https://github.com/wbkd/react-flow/pull/2895) [`3d5764ca`](https://github.com/wbkd/react-flow/commit/3d5764cac6548984a30cbf85899024e62fd69425) - add data-testid for controls, minimap and background
- Updated dependencies [[`3d5764ca`](https://github.com/wbkd/react-flow/commit/3d5764cac6548984a30cbf85899024e62fd69425), [`83fc4675`](https://github.com/wbkd/react-flow/commit/83fc467545527729633e817dbccfe59d0040da4b), [`b1190837`](https://github.com/wbkd/react-flow/commit/b11908370bc438ca8d4179497cd4eb1f8c656798), [`5fabd272`](https://github.com/wbkd/react-flow/commit/5fabd2720f6367f75f79a45822d8f675a3b8e1cf), [`8f080bd5`](https://github.com/wbkd/react-flow/commit/8f080bd5e0e7e6c71f51eee9c9f2bc4b25182861), [`b8886514`](https://github.com/wbkd/react-flow/commit/b88865140c72fa7e92a883498768000cb2cc96a7), [`16bf89f2`](https://github.com/wbkd/react-flow/commit/16bf89f2b7bbf8449c00d0e2c07c19c3ff6d2533)]:
- @reactflow/core@11.6.0
## 11.3.8
### Patch Changes
- Updated dependencies [[`72216ff6`](https://github.com/wbkd/react-flow/commit/72216ff62014acd2d73999053c72bd7aeed351f6), [`959b1114`](https://github.com/wbkd/react-flow/commit/959b111448bba4686040473e46988be9e7befbe6), [`0d259b02`](https://github.com/wbkd/react-flow/commit/0d259b028558aab650546f3371a85f3bce45252f), [`f3de9335`](https://github.com/wbkd/react-flow/commit/f3de9335af6cd96cd77dc77f24a944eef85384e5), [`23424ea6`](https://github.com/wbkd/react-flow/commit/23424ea6750f092210f83df17a00c89adb910d96), [`021f5a92`](https://github.com/wbkd/react-flow/commit/021f5a9210f47a968e50446cd2f9dae1f97880a4)]:
- @reactflow/core@11.5.5
## 11.3.7
### Patch Changes
- Updated dependencies [[`383a074a`](https://github.com/wbkd/react-flow/commit/383a074aeae6dbec8437fa08c7c8d8240838a84e)]:
- @reactflow/core@11.5.4
## 11.3.6
### Patch Changes
- Updated dependencies [[`be8097ac`](https://github.com/wbkd/react-flow/commit/be8097acadca3054c3b236ce4296fc516010ef8c), [`1527795d`](https://github.com/wbkd/react-flow/commit/1527795d18c3af38c8ec7059436ea0fbf6c27bbd), [`3b6348a8`](https://github.com/wbkd/react-flow/commit/3b6348a8d1573afb39576327318bc172e33393c2)]:
- @reactflow/core@11.5.3
## 11.3.5
### Patch Changes
- [#2792](https://github.com/wbkd/react-flow/pull/2792) [`d8c679b4`](https://github.com/wbkd/react-flow/commit/d8c679b4c90c5b57d4b51e4aaa988243d6eaff5a) - Accept React 17 types as dev dependency
- Updated dependencies [[`d8c679b4`](https://github.com/wbkd/react-flow/commit/d8c679b4c90c5b57d4b51e4aaa988243d6eaff5a)]:
- @reactflow/core@11.5.2
## 11.3.4
### Patch Changes
- Updated dependencies [[`71153534`](https://github.com/wbkd/react-flow/commit/7115353418ebc7f7c81ab0e861200972bbf7dbd5)]:
- @reactflow/core@11.5.1
## 11.3.3
### Patch Changes
- Updated dependencies [[`e96309b6`](https://github.com/wbkd/react-flow/commit/e96309b6a57b1071faeebf7b0547fef7fd418694), [`85003b01`](https://github.com/wbkd/react-flow/commit/85003b01add71ea852bd5b0d2f1e7496050a6b52), [`4c516882`](https://github.com/wbkd/react-flow/commit/4c516882d2bbf426c1832a53ad40763cc1abef92)]:
- @reactflow/core@11.5.0
## 11.3.2
### Patch Changes
- [#2741](https://github.com/wbkd/react-flow/pull/2741) [`e2aff6c1`](https://github.com/wbkd/react-flow/commit/e2aff6c1e4ce54b57b724b2624367ee5fefd1c39) - chore(dependencies): update and cleanup
- Updated dependencies [[`e34a3072`](https://github.com/wbkd/react-flow/commit/e34a30726dc55184f59adc4f16ca5215a7c42805), [`e2aff6c1`](https://github.com/wbkd/react-flow/commit/e2aff6c1e4ce54b57b724b2624367ee5fefd1c39)]:
- @reactflow/core@11.4.2
## 11.3.1
### Patch Changes
- Updated dependencies [[`82988485`](https://github.com/wbkd/react-flow/commit/82988485b730a9e32acbdae1ddcc81b33ddccaba), [`d91e619a`](https://github.com/wbkd/react-flow/commit/d91e619a70a95db99a621ede59bc05b5a7766086)]:
- @reactflow/core@11.4.1
## 11.3.0
### Patch Changes
- [#2660](https://github.com/wbkd/react-flow/pull/2660) [`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0) - Add `getNodes` function to the store so that you don't need to do `Array.from(store.getState().nodeInternals.values())` anymore.
- [#2659](https://github.com/wbkd/react-flow/pull/2659) [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9) - Use translateExtent correctly
- Updated dependencies [[`ab2ff374`](https://github.com/wbkd/react-flow/commit/ab2ff3740618da48bd4350597e816c397f3d78ff), [`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0), [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493), [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9), [`7ef29108`](https://github.com/wbkd/react-flow/commit/7ef2910808aaaee029894363d52efc0c378a7654), [`23afb3ab`](https://github.com/wbkd/react-flow/commit/23afb3abebdb42fad284f68bec164afac609563c)]:
- @reactflow/core@11.4.0
## 11.3.0-next.1
### Minor Changes
- panOnDrag: Use numbers for prop ([1,2] = drag via middle or right mouse button)
- selection: do not include hidden nodes
- minimap: fix onNodeClick for nodes outside the viewport
- keys: allow multi select when input is focused
### Patch Changes
- Updated dependencies []:
- @reactflow/core@11.4.0-next.1
## 11.3.0-next.0
### Minor Changes
- [#2678](https://github.com/wbkd/react-flow/pull/2678) [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493) Thanks [@moklick](https://github.com/moklick)! - ## New Features
New props for the ReactFlow component to customize the controls of the viewport and the selection box better:
1. `selectionOnDrag` prop: Selection box without extra button press (need to set `panOnDrag={false} or `panOnDrag="RightClick"`)
2. `panOnDrag="RightClick"` option
3. `panActivationKeyCode="Space"` key code for activating dragging (useful when using `selectionOnDrag`)
4. `selectionMode={SelectionMode.Full}`: you can chose if the selection box needs to contain a node fully (`SelectionMode.Full`) or partially (`SelectionMode.Partial`) to select it
5. `onSelectionStart` and `onSelectionEnd` events
### Patch Changes
- [#2660](https://github.com/wbkd/react-flow/pull/2660) [`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0) Thanks [@moklick](https://github.com/moklick)! - Add `getNodes` function to the store so that you don't need to do `Array.from(store.getState().nodeInternals.values())` anymore.
- [#2659](https://github.com/wbkd/react-flow/pull/2659) [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9) Thanks [@moklick](https://github.com/moklick)! - Use translateExtent correctly
- Updated dependencies [[`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0), [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493), [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9), [`23afb3ab`](https://github.com/wbkd/react-flow/commit/23afb3abebdb42fad284f68bec164afac609563c)]:
- @reactflow/core@11.4.0-next.0
## 11.2.3
### Patch Changes
- [#2646](https://github.com/wbkd/react-flow/pull/2646) [`e6b5d90f`](https://github.com/wbkd/react-flow/commit/e6b5d90f61c8ee60e817bba232a162cae2ab3e2a) - Cleanup get node position with origin usage
- Updated dependencies [[`e6b5d90f`](https://github.com/wbkd/react-flow/commit/e6b5d90f61c8ee60e817bba232a162cae2ab3e2a), [`6ee44e07`](https://github.com/wbkd/react-flow/commit/6ee44e076eaa6908d07578a757a5187642b732ae), [`aa69c207`](https://github.com/wbkd/react-flow/commit/aa69c20765e6978f4f9c8cc63ed7110dbf6d9d9d), [`d29c401d`](https://github.com/wbkd/react-flow/commit/d29c401d598dbf2dcd5609b7adb8d029906a6f18), [`0df02f35`](https://github.com/wbkd/react-flow/commit/0df02f35f8d6c54dae36af18278feadc77acb2d6)]:
- @reactflow/core@11.3.2
## 11.2.2
### Patch Changes
- [`7ece618d`](https://github.com/wbkd/react-flow/commit/7ece618d94b76183c1ecd45b16f6ab168168351b) Thanks [@lounsbrough](https://github.com/lounsbrough)! - Fix minimap node position
## 11.2.1
### Patch Changes
- [#2595](https://github.com/wbkd/react-flow/pull/2595) [`c828bfda`](https://github.com/wbkd/react-flow/commit/c828bfda0a8c4774bc43588640c7cca0cfdcb3f4) Thanks [@chrtze](https://github.com/chrtze)! - Fix and improve the behaviour when using nodeOrigin in combination with subflows
- Updated dependencies [[`c828bfda`](https://github.com/wbkd/react-flow/commit/c828bfda0a8c4774bc43588640c7cca0cfdcb3f4), [`b0302ce4`](https://github.com/wbkd/react-flow/commit/b0302ce4261a992bee841bae84af347d03be690f), [`b2c72813`](https://github.com/wbkd/react-flow/commit/b2c728137d1b53e38883f044fa447585c377a6af)]:
- @reactflow/core@11.3.1
## 11.2.0
### Minor Changes
- [#2562](https://github.com/wbkd/react-flow/pull/2562) [`d745aa33`](https://github.com/wbkd/react-flow/commit/d745aa33fcd1333e12929c862f9a3d6de53f7179) Thanks [@moklick](https://github.com/moklick)! - Add maskStrokeColor and maskStrokeWidth props
- [#2545](https://github.com/wbkd/react-flow/pull/2545) [`8f63f751`](https://github.com/wbkd/react-flow/commit/8f63f751e302d3c935865760d2134350c31ab93f) Thanks [@chrtze](https://github.com/chrtze)! - add a new property "ariaLabel" to configure or remove the aria-label of the minimap component
### Patch Changes
- Updated dependencies [[`92cf497e`](https://github.com/wbkd/react-flow/commit/92cf497eb72f21af592a53f5af9770c9f1e6d940), [`98116d43`](https://github.com/wbkd/react-flow/commit/98116d431f9fcdcc9b23a5b606a94ec0740b64cd), [`a39224b3`](https://github.com/wbkd/react-flow/commit/a39224b3a80afbdb83fc4490dd5f4f2be23cd4dd), [`5e8b67dd`](https://github.com/wbkd/react-flow/commit/5e8b67dd41f9bb60dcd7f5d14cc34b42c970e967), [`2a1c7db6`](https://github.com/wbkd/react-flow/commit/2a1c7db6b27ac0f4f81dcef2d593f4753c4321c7)]:
- @reactflow/core@11.3.0
## 11.1.0
### Minor Changes
- [#2530](https://github.com/wbkd/react-flow/pull/2530) [`8ba4dd5d`](https://github.com/wbkd/react-flow/commit/8ba4dd5d1d4b2e6f107c148de62aec0b688d8b21) Thanks [@moklick](https://github.com/moklick)! - Feat: Add pan and zoom to mini map
### Patch Changes
- Updated dependencies [[`740659c0`](https://github.com/wbkd/react-flow/commit/740659c0e788c7572d4a1e64e1d33d60712233fc), [`7902a3ce`](https://github.com/wbkd/react-flow/commit/7902a3ce3188426d5cd07cf0943a68f679e67948), [`b25d499e`](https://github.com/wbkd/react-flow/commit/b25d499ec05b5c6f21ac552d03650eb37433552e), [`4fc1253e`](https://github.com/wbkd/react-flow/commit/4fc1253eadf9b7dd392d8dc2348f44fa8d08f931), [`8ba4dd5d`](https://github.com/wbkd/react-flow/commit/8ba4dd5d1d4b2e6f107c148de62aec0b688d8b21)]:
- @reactflow/core@11.2.0
## 11.0.3
### Patch Changes
- cleanup types
- Updated dependencies:
- @reactflow/core@11.1.2
## 11.0.2
### Patch Changes
- Updated dependencies:
- @reactflow/core@11.1.1
## 11.0.1
### Patch Changes
- Updated dependencies [[`def11008`](https://github.com/wbkd/react-flow/commit/def11008d88749fec40e6fcba8bc41eea2511bab), [`d00faa6b`](https://github.com/wbkd/react-flow/commit/d00faa6b3e77388bfd655d4c02e9a5375bc515e4)]:
- @reactflow/core@11.1.0
## 11.0.0
### Major Changes
- **Better [Accessibility](/docs/guides/accessibility)**
- Nodes and edges are focusable, selectable, moveable and deleteable with the keyboard.
- `aria-` default attributes for all elements and controllable via `ariaLabel` options
- Keyboard controls can be disabled with the new `disableKeyboardA11y` prop
- **Better selectable edges** via new edge option: `interactionWidth` - renders invisible edge that makes it easier to interact
- **Better routing for smoothstep and step edges**: https://twitter.com/reactflowdev/status/1567535405284614145
- **Nicer edge updating behaviour**: https://twitter.com/reactflowdev/status/1564966917517021184
- **Node origin**: The new `nodeOrigin` prop lets you control the origin of a node. Useful for layouting.
- **New background pattern**: `BackgroundVariant.Cross` variant
- **[`useOnViewportChange`](/docs/api/hooks/use-on-viewport-change) hook** - handle viewport changes within a component
- **[`useOnSelectionChange`](/docs/api/hooks/use-on-selection-change) hook** - handle selection changes within a component
- **[`useNodesInitialized`](/docs/api/hooks/use-nodes-initialized) hook** - returns true if all nodes are initialized and if there is more than one node
- **Deletable option** for Nodes and edges
- **New Event handlers**: `onPaneMouseEnter`, `onPaneMouseMove` and `onPaneMouseLeave`
- **Edge `pathOptions`** for `smoothstep` and `default` edges
- **Nicer cursor defaults**: Cursor is grabbing, while dragging a node or panning
- **Pane moveable** with middle mouse button
- **Pan over nodes** when they are not draggable (`draggable=false` or `nodesDraggable` false)
- **[`<BaseEdge />`](/docs/api/edges/base-edge) component** that makes it easier to build custom edges
- **[Separately installable packages](/docs/overview/packages/)**
- @reactflow/core
- @reactflow/background
- @reactflow/controls
- @reactflow/minimap
### Patch Changes
- Updated dependencies:
- @reactflow/core@11.0.0
<file_sep># Contributing to React Flow
Hello there! So glad you want to help out with React Flow 🤗 You’re the best. Here’s a guide for how you can contribute to the project.
# Our Contributing Philosophy
The direction of React Flow and which new features are added, and which are left out, is decided by the core team (sometimes referred to as a “cathedral” style of development). The core team is paid to do this work ([see how here](https://reactflow.dev/blog/asking-for-money-for-open-source/)). With this model we ensure that the people doing the most work on the library are paid for their time and effort, and that we prevent the library from bloating.
That being said, React Flow is only interesting because of the people who make things with it, share their work, and discuss it. Some of the most important and undervalued work in open source is from non-code contributions, and that is where we can use the most help from you.
# How can I help?
The things we need the most help for the library and its community are:
**🐛 Bug reports:** We simply can’t catch them all. Check [existing issues](https://github.com/wbkd/react-flow/issues/new/choose) and discussion first, then [create a new issue](https://github.com/wbkd/react-flow/issues/new/choose) to tell us what’s up.
**💬 Answering questions** in our [Discord Server](https://discord.gg/Bqt6xrs) and [Github discussions](https://github.com/wbkd/react-flow/discussions).
🎬 **Create tutorials** for React Flow. Send them to us and we’ll happily share them!
**✏️ Edit our [Docs](https://reactflow.dev/docs/introduction/)**: Make changes in the [react-flow-docs repo](https://github.com/wbkd/react-flow-docs), or click the "edit this page” button that lives on every doc site.
All interactions should be done with care following our [Code of Conduct](https://github.com/wbkd/react-flow/blob/main/CODE_OF_CONDUCT.md).
## Enhancements
If you have an idea or suggestion for an enhancement to the React Flow library, please use the [New Features](https://github.com/wbkd/react-flow/discussions/categories/new-features) discussion section. If you want to build it yourself, **please reach out to us before you dive into a new pull request.** The direction of React Flow and which new features are added are discussed in our Discord Server and in [this Github discussions section](https://github.com/wbkd/react-flow/discussions/categories/new-features), and in the end they are decided by the core team.
Talking to us first about the enhancement you want to build will be the most likely way to get your pull request into the library (see Our Contributing Philosophy above). We would hate to see you write code you’re proud of, just to learn that we’ve already been working on the same thing, or that we feel doesn’t fit into the core library.
### Contact us
To ask about a possible enhancement, email us at <EMAIL>
### 💫 Pull Requests
If you want to contribute improvements or new features we are happy to review your PR :)
Please use a meaningful commit message and add a little description of your changes.
1. Install dependencies `pnpm install`
2. Start dev server `pnpm dev`
3. Test your changes with the existing examples or add a new one if it's needed for your changes
4. Run tests `pnpm test` and add new new tests if you are introducing a new feature
<file_sep>describe('Controls Testing', () => {
before(() => {
cy.visit('/');
});
it('renders the control panel', () => {
cy.get('.react-flow__controls');
});
it('zooms in', () => {
const styleBeforeZoom = Cypress.$('.react-flow__viewport').css('transform');
cy.get('.react-flow__controls-zoomin')
.click()
.then(() => {
const styleAfterZoom = Cypress.$('.react-flow__viewport').css('transform');
expect(styleBeforeZoom).to.not.equal(styleAfterZoom);
});
});
it('zooms out', () => {
const styleBeforeZoom = Cypress.$('.react-flow__viewport').css('transform');
cy.get('.react-flow__controls-zoomout')
.click()
.then(() => {
const styleAfterZoom = Cypress.$('.react-flow__viewport').css('transform');
expect(styleBeforeZoom).to.not.equal(styleAfterZoom);
});
});
// view is already fitted so we drag the pane to un-fit it
it('drags the pane', () => {
const styleBeforeDrag = Cypress.$('.react-flow__viewport').css('transform');
// for d3 we have to pass the window to the event
// https://github.com/cypress-io/cypress/issues/3441
cy.window().then((win) => {
cy.get('.react-flow__renderer')
.trigger('mousedown', 'topLeft', { button: 0, view: win })
.trigger('mousemove', 10, 400)
.wait(50)
.trigger('mouseup', 10, 400, { force: true, view: win })
.then(() => {
const styleAfterDrag = Cypress.$('.react-flow__viewport').css('transform');
expect(styleBeforeDrag).to.not.equal(styleAfterDrag);
});
});
});
it('fits view', () => {
const styleBeforeZoom = Cypress.$('.react-flow__viewport').css('transform');
cy.get('.react-flow__controls-fitview')
.click()
.then(() => {
const styleAfterZoom = Cypress.$('.react-flow__viewport').css('transform');
expect(styleBeforeZoom).to.not.equal(styleAfterZoom);
});
});
it('uses interactive control - not interactive', () => {
cy.get('.react-flow__node:first').click().should('have.class', 'selected');
cy.get('.react-flow__pane').click('topLeft');
cy.get('.react-flow__node:first').should('not.have.class', 'selected');
cy.get('.react-flow__controls-interactive')
.click()
.then(() => {
cy.get('.react-flow__node:first').should('not.have.class', 'selected');
});
});
it('uses interactive control - interactive', () => {
cy.get('.react-flow__controls-interactive')
.click()
.then(() => {
cy.get('.react-flow__node:first').click({ force: true }).should('have.class', 'selected');
});
});
});
export {};
<file_sep>/* eslint-disable @typescript-eslint/no-explicit-any */
import type {
MouseEvent as ReactMouseEvent,
TouchEvent as ReactTouchEvent,
ComponentType,
MemoExoticComponent,
} from 'react';
import type { D3DragEvent, Selection as D3Selection, SubjectPosition, ZoomBehavior } from 'd3';
import type { XYPosition, Rect, Transform, CoordinateExtent } from './utils';
import type { NodeChange, EdgeChange } from './changes';
import type {
Node,
NodeInternals,
NodeDimensionUpdate,
NodeProps,
WrapNodeProps,
NodeDragItem,
NodeDragHandler,
SelectionDragHandler,
NodeOrigin,
} from './nodes';
import type { Edge, EdgeProps, WrapEdgeProps } from './edges';
import type { HandleType, ConnectingHandle } from './handles';
import type { DefaultEdgeOptions } from '.';
import type { ReactFlowInstance } from './instance';
export type NodeTypes = { [key: string]: ComponentType<NodeProps> };
export type NodeTypesWrapped = { [key: string]: MemoExoticComponent<ComponentType<WrapNodeProps>> };
export type EdgeTypes = { [key: string]: ComponentType<EdgeProps> };
export type EdgeTypesWrapped = { [key: string]: MemoExoticComponent<ComponentType<WrapEdgeProps>> };
export type FitView = (fitViewOptions?: FitViewOptions) => boolean;
export type Project = (position: XYPosition) => XYPosition;
export type OnNodesChange = (changes: NodeChange[]) => void;
export type OnEdgesChange = (changes: EdgeChange[]) => void;
export type OnNodesDelete = (nodes: Node[]) => void;
export type OnEdgesDelete = (edges: Edge[]) => void;
export type OnMove = (event: MouseEvent | TouchEvent, viewport: Viewport) => void;
export type OnMoveStart = OnMove;
export type OnMoveEnd = OnMove;
export type ZoomInOut = (options?: ViewportHelperFunctionOptions) => void;
export type ZoomTo = (zoomLevel: number, options?: ViewportHelperFunctionOptions) => void;
export type GetZoom = () => number;
export type GetViewport = () => Viewport;
export type SetViewport = (viewport: Viewport, options?: ViewportHelperFunctionOptions) => void;
export type SetCenter = (x: number, y: number, options?: SetCenterOptions) => void;
export type FitBounds = (bounds: Rect, options?: FitBoundsOptions) => void;
export type OnInit<NodeData = any, EdgeData = any> = (reactFlowInstance: ReactFlowInstance<NodeData, EdgeData>) => void;
export interface Connection {
source: string | null;
target: string | null;
sourceHandle: string | null;
targetHandle: string | null;
}
export type IsValidConnection = (edge: Edge | Connection) => boolean;
export type ConnectionStatus = 'valid' | 'invalid';
export enum ConnectionMode {
Strict = 'strict',
Loose = 'loose',
}
export type OnConnect = (connection: Connection) => void;
export type FitViewOptions = {
padding?: number;
includeHiddenNodes?: boolean;
minZoom?: number;
maxZoom?: number;
duration?: number;
nodes?: (Partial<Node> & { id: Node['id'] })[];
};
export type OnConnectStartParams = {
nodeId: string | null;
handleId: string | null;
handleType: HandleType | null;
};
export type OnConnectStart = (event: ReactMouseEvent | ReactTouchEvent, params: OnConnectStartParams) => void;
export type OnConnectEnd = (event: MouseEvent | TouchEvent) => void;
export type Viewport = {
x: number;
y: number;
zoom: number;
};
export type KeyCode = string | Array<string>;
export type SnapGrid = [number, number];
export enum PanOnScrollMode {
Free = 'free',
Vertical = 'vertical',
Horizontal = 'horizontal',
}
export type ViewportHelperFunctionOptions = {
duration?: number;
};
export type SetCenterOptions = ViewportHelperFunctionOptions & {
zoom?: number;
};
export type FitBoundsOptions = ViewportHelperFunctionOptions & {
padding?: number;
};
export type UnselectNodesAndEdgesParams = {
nodes?: Node[];
edges?: Edge[];
};
export type OnViewportChange = (viewport: Viewport) => void;
export type ViewportHelperFunctions = {
zoomIn: ZoomInOut;
zoomOut: ZoomInOut;
zoomTo: ZoomTo;
getZoom: GetZoom;
setViewport: SetViewport;
getViewport: GetViewport;
fitView: FitView;
setCenter: SetCenter;
fitBounds: FitBounds;
project: Project;
viewportInitialized: boolean;
};
export type ReactFlowStore = {
rfId: string;
width: number;
height: number;
transform: Transform;
nodeInternals: NodeInternals;
edges: Edge[];
onNodesChange: OnNodesChange | null;
onEdgesChange: OnEdgesChange | null;
hasDefaultNodes: boolean;
hasDefaultEdges: boolean;
domNode: HTMLDivElement | null;
paneDragging: boolean;
noPanClassName: string;
d3Zoom: ZoomBehavior<Element, unknown> | null;
d3Selection: D3Selection<Element, unknown, null, undefined> | null;
d3ZoomHandler: ((this: Element, event: any, d: unknown) => void) | undefined;
minZoom: number;
maxZoom: number;
translateExtent: CoordinateExtent;
nodeExtent: CoordinateExtent;
nodeOrigin: NodeOrigin;
nodesSelectionActive: boolean;
userSelectionActive: boolean;
userSelectionRect: SelectionRect | null;
// @todo remove this in next major version in favor of connectionStartHandle
connectionNodeId: string | null;
connectionHandleId: string | null;
connectionHandleType: HandleType | null;
connectionPosition: XYPosition;
connectionStatus: ConnectionStatus | null;
connectionMode: ConnectionMode;
snapToGrid: boolean;
snapGrid: SnapGrid;
nodesDraggable: boolean;
nodesConnectable: boolean;
nodesFocusable: boolean;
edgesFocusable: boolean;
edgesUpdatable: boolean;
elementsSelectable: boolean;
elevateNodesOnSelect: boolean;
multiSelectionActive: boolean;
connectionStartHandle: ConnectingHandle | null;
connectionEndHandle: ConnectingHandle | null;
// @todo this is only used for the click connection - we might remove this in the next major version
connectionClickStartHandle: ConnectingHandle | null;
onNodeDragStart?: NodeDragHandler;
onNodeDrag?: NodeDragHandler;
onNodeDragStop?: NodeDragHandler;
onSelectionDragStart?: SelectionDragHandler;
onSelectionDrag?: SelectionDragHandler;
onSelectionDragStop?: SelectionDragHandler;
onConnect?: OnConnect;
onConnectStart?: OnConnectStart;
onConnectEnd?: OnConnectEnd;
onClickConnectStart?: OnConnectStart;
onClickConnectEnd?: OnConnectEnd;
connectOnClick: boolean;
defaultEdgeOptions?: DefaultEdgeOptions;
fitViewOnInit: boolean;
fitViewOnInitDone: boolean;
fitViewOnInitOptions: FitViewOptions | undefined;
onNodesDelete?: OnNodesDelete;
onEdgesDelete?: OnEdgesDelete;
onError?: OnError;
// event handlers
onViewportChangeStart?: OnViewportChange;
onViewportChange?: OnViewportChange;
onViewportChangeEnd?: OnViewportChange;
onSelectionChange?: OnSelectionChangeFunc;
ariaLiveMessage: string;
autoPanOnConnect: boolean;
autoPanOnNodeDrag: boolean;
connectionRadius: number;
isValidConnection?: IsValidConnection;
};
export type ReactFlowActions = {
setNodes: (nodes: Node[]) => void;
getNodes: () => Node[];
setEdges: (edges: Edge[]) => void;
setDefaultNodesAndEdges: (nodes?: Node[], edges?: Edge[]) => void;
updateNodeDimensions: (updates: NodeDimensionUpdate[]) => void;
updateNodePositions: (nodeDragItems: NodeDragItem[] | Node[], positionChanged: boolean, dragging: boolean) => void;
resetSelectedElements: () => void;
unselectNodesAndEdges: (params?: UnselectNodesAndEdgesParams) => void;
addSelectedNodes: (nodeIds: string[]) => void;
addSelectedEdges: (edgeIds: string[]) => void;
setMinZoom: (minZoom: number) => void;
setMaxZoom: (maxZoom: number) => void;
setTranslateExtent: (translateExtent: CoordinateExtent) => void;
setNodeExtent: (nodeExtent: CoordinateExtent) => void;
cancelConnection: () => void;
reset: () => void;
triggerNodeChanges: (changes: NodeChange[]) => void;
panBy: (delta: XYPosition) => boolean;
};
export type ReactFlowState = ReactFlowStore & ReactFlowActions;
export type UpdateNodeInternals = (nodeId: string | string[]) => void;
export type OnSelectionChangeParams = {
nodes: Node[];
edges: Edge[];
};
export type OnSelectionChangeFunc = (params: OnSelectionChangeParams) => void;
export type PanelPosition = 'top-left' | 'top-center' | 'top-right' | 'bottom-left' | 'bottom-center' | 'bottom-right';
export type ProOptions = {
account?: string;
hideAttribution: boolean;
};
export type UseDragEvent = D3DragEvent<HTMLDivElement, null, SubjectPosition>;
export enum SelectionMode {
Partial = 'partial',
Full = 'full',
}
export type SelectionRect = Rect & {
startX: number;
startY: number;
};
export type OnError = (id: string, message: string) => void;
export interface UpdateEdgeOptions {
shouldReplaceId?: boolean;
}
<file_sep>///<reference types="cypress" />
///<reference types="@cypress/skip-test" />
///<reference types="cypress-real-events" />
import './commands';
import 'cypress-real-events/support';
import { mount } from 'cypress/react18';
import { XYPosition } from 'reactflow';
import 'reactflow/dist/style.css';
declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace Cypress {
interface Chainable {
mount: typeof mount;
drag: (selector: string, toPosition: XYPosition) => Cypress.Chainable<JQuery<HTMLElement>>;
dragPane: ({ from, to }: { from: XYPosition; to: XYPosition }) => Cypress.Chainable<JQuery<HTMLElement>>;
zoomPane: (wheelDelta: number) => Cypress.Chainable<JQuery<HTMLElement>>;
isWithinViewport: () => Cypress.Chainable<JQuery<HTMLElement>>;
isOutsideViewport: () => Cypress.Chainable<JQuery<HTMLElement>>;
}
}
}
Cypress.Commands.add('mount', mount);
<file_sep>import { useEffect } from 'react';
import { useStoreApi } from './useStore';
import type { OnViewportChange } from '../types';
export type UseOnViewportChangeOptions = {
onStart?: OnViewportChange;
onChange?: OnViewportChange;
onEnd?: OnViewportChange;
};
function useOnViewportChange({ onStart, onChange, onEnd }: UseOnViewportChangeOptions) {
const store = useStoreApi();
useEffect(() => {
store.setState({ onViewportChangeStart: onStart });
}, [onStart]);
useEffect(() => {
store.setState({ onViewportChange: onChange });
}, [onChange]);
useEffect(() => {
store.setState({ onViewportChangeEnd: onEnd });
}, [onEnd]);
}
export default useOnViewportChange;
<file_sep>module.exports = {
plugins: [
require('postcss-import'),
require('postcss-nested'),
require('postcss-combine-duplicated-selectors'),
require('autoprefixer'),
],
};
<file_sep>/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-namespace */
import { ViewportHelperFunctions, Viewport, Node, Edge, Rect } from '.';
export type ReactFlowJsonObject<NodeData = any, EdgeData = any> = {
nodes: Node<NodeData>[];
edges: Edge<EdgeData>[];
viewport: Viewport;
};
export type DeleteElementsOptions = {
nodes?: (Partial<Node> & { id: Node['id'] })[];
edges?: (Partial<Edge> & { id: Edge['id'] })[];
};
export namespace Instance {
export type GetNodes<NodeData> = () => Node<NodeData>[];
export type SetNodes<NodeData> = (
payload: Node<NodeData>[] | ((nodes: Node<NodeData>[]) => Node<NodeData>[])
) => void;
export type AddNodes<NodeData> = (payload: Node<NodeData>[] | Node<NodeData>) => void;
export type GetNode<NodeData> = (id: string) => Node<NodeData> | undefined;
export type GetEdges<EdgeData> = () => Edge<EdgeData>[];
export type SetEdges<EdgeData> = (
payload: Edge<EdgeData>[] | ((edges: Edge<EdgeData>[]) => Edge<EdgeData>[])
) => void;
export type GetEdge<EdgeData> = (id: string) => Edge<EdgeData> | undefined;
export type AddEdges<EdgeData> = (payload: Edge<EdgeData>[] | Edge<EdgeData>) => void;
export type ToObject<NodeData = any, EdgeData = any> = () => ReactFlowJsonObject<NodeData, EdgeData>;
export type DeleteElements = ({ nodes, edges }: DeleteElementsOptions) => void;
export type GetIntersectingNodes<NodeData> = (
node: (Partial<Node<NodeData>> & { id: Node['id'] }) | Rect,
partially?: boolean,
nodes?: Node<NodeData>[]
) => Node<NodeData>[];
export type IsNodeIntersecting<NodeData> = (
node: (Partial<Node<NodeData>> & { id: Node['id'] }) | Rect,
area: Rect,
partially?: boolean
) => boolean;
}
export type ReactFlowInstance<NodeData = any, EdgeData = any> = {
getNodes: Instance.GetNodes<NodeData>;
setNodes: Instance.SetNodes<NodeData>;
addNodes: Instance.AddNodes<NodeData>;
getNode: Instance.GetNode<NodeData>;
getEdges: Instance.GetEdges<EdgeData>;
setEdges: Instance.SetEdges<EdgeData>;
addEdges: Instance.AddEdges<EdgeData>;
getEdge: Instance.GetEdge<EdgeData>;
toObject: Instance.ToObject<NodeData, EdgeData>;
deleteElements: Instance.DeleteElements;
getIntersectingNodes: Instance.GetIntersectingNodes<NodeData>;
isNodeIntersecting: Instance.IsNodeIntersecting<NodeData>;
viewportInitialized: boolean;
} & Omit<ViewportHelperFunctions, 'initialized'>;
<file_sep>/* eslint-disable @typescript-eslint/no-explicit-any */
import type { CSSProperties, MouseEvent as ReactMouseEvent } from 'react';
import { internalsSymbol } from '../utils';
import type { XYPosition, Position, CoordinateExtent, HandleElement } from '.';
// interface for the user node items
export type Node<T = any, U extends string | undefined = string | undefined> = {
id: string;
position: XYPosition;
data: T;
type?: U;
style?: CSSProperties;
className?: string;
sourcePosition?: Position;
targetPosition?: Position;
hidden?: boolean;
selected?: boolean;
dragging?: boolean;
draggable?: boolean;
selectable?: boolean;
connectable?: boolean;
deletable?: boolean;
dragHandle?: string;
width?: number | null;
height?: number | null;
parentNode?: string;
zIndex?: number;
extent?: 'parent' | CoordinateExtent;
expandParent?: boolean;
positionAbsolute?: XYPosition;
ariaLabel?: string;
focusable?: boolean;
resizing?: boolean;
// only used internally
[internalsSymbol]?: {
z?: number;
handleBounds?: NodeHandleBounds;
isParent?: boolean;
};
};
export type NodeMouseHandler = (event: ReactMouseEvent, node: Node) => void;
export type NodeDragHandler = (event: ReactMouseEvent, node: Node, nodes: Node[]) => void;
export type SelectionDragHandler = (event: ReactMouseEvent, nodes: Node[]) => void;
export type WrapNodeProps<T = any> = Pick<
Node<T>,
'id' | 'data' | 'style' | 'className' | 'dragHandle' | 'sourcePosition' | 'targetPosition' | 'hidden' | 'ariaLabel'
> &
Required<Pick<Node<T>, 'selected' | 'type' | 'zIndex'>> & {
isConnectable: boolean;
xPos: number;
yPos: number;
xPosOrigin: number;
yPosOrigin: number;
initialized: boolean;
isSelectable: boolean;
isDraggable: boolean;
isFocusable: boolean;
selectNodesOnDrag: boolean;
onClick?: NodeMouseHandler;
onDoubleClick?: NodeMouseHandler;
onMouseEnter?: NodeMouseHandler;
onMouseMove?: NodeMouseHandler;
onMouseLeave?: NodeMouseHandler;
onContextMenu?: NodeMouseHandler;
resizeObserver: ResizeObserver | null;
isParent: boolean;
noDragClassName: string;
noPanClassName: string;
rfId: string;
disableKeyboardA11y: boolean;
};
// props that get passed to a custom node
export type NodeProps<T = any> = Pick<
WrapNodeProps<T>,
'id' | 'data' | 'dragHandle' | 'type' | 'selected' | 'isConnectable' | 'xPos' | 'yPos' | 'zIndex'
> & {
dragging: boolean;
targetPosition?: Position;
sourcePosition?: Position;
};
export type NodeHandleBounds = {
source: HandleElement[] | null;
target: HandleElement[] | null;
};
export type NodeDimensionUpdate = {
id: string;
nodeElement: HTMLDivElement;
forceUpdate?: boolean;
};
export type NodeInternals = Map<string, Node>;
export type NodeBounds = XYPosition & {
width: number | null;
height: number | null;
};
export type NodeDragItem = {
id: string;
position: XYPosition;
positionAbsolute: XYPosition;
// distance from the mouse cursor to the node when start dragging
distance: XYPosition;
width?: number | null;
height?: number | null;
extent?: 'parent' | CoordinateExtent;
parentNode?: string;
dragging?: boolean;
};
export type NodeOrigin = [number, number];
<file_sep>import { useEffect, useRef } from 'react';
import useReactFlow from './useReactFlow';
import type { OnInit } from '../types';
function useOnInitHandler(onInit: OnInit | undefined) {
const rfInstance = useReactFlow();
const isInitialized = useRef<boolean>(false);
useEffect(() => {
if (!isInitialized.current && rfInstance.viewportInitialized && onInit) {
setTimeout(() => onInit(rfInstance), 1);
isInitialized.current = true;
}
}, [onInit, rfInstance.viewportInitialized]);
}
export default useOnInitHandler;
<file_sep>import { devWarn } from '../utils';
import { ConnectionMode } from '../types';
import type { CoordinateExtent, ReactFlowStore } from '../types';
export const infiniteExtent: CoordinateExtent = [
[Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY],
[Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY],
];
const initialState: ReactFlowStore = {
rfId: '1',
width: 0,
height: 0,
transform: [0, 0, 1],
nodeInternals: new Map(),
edges: [],
onNodesChange: null,
onEdgesChange: null,
hasDefaultNodes: false,
hasDefaultEdges: false,
d3Zoom: null,
d3Selection: null,
d3ZoomHandler: undefined,
minZoom: 0.5,
maxZoom: 2,
translateExtent: infiniteExtent,
nodeExtent: infiniteExtent,
nodesSelectionActive: false,
userSelectionActive: false,
userSelectionRect: null,
connectionNodeId: null,
connectionHandleId: null,
connectionHandleType: 'source',
connectionPosition: { x: 0, y: 0 },
connectionStatus: null,
connectionMode: ConnectionMode.Strict,
domNode: null,
paneDragging: false,
noPanClassName: 'nopan',
nodeOrigin: [0, 0],
snapGrid: [15, 15],
snapToGrid: false,
nodesDraggable: true,
nodesConnectable: true,
nodesFocusable: true,
edgesFocusable: true,
edgesUpdatable: true,
elementsSelectable: true,
elevateNodesOnSelect: true,
fitViewOnInit: false,
fitViewOnInitDone: false,
fitViewOnInitOptions: undefined,
multiSelectionActive: false,
connectionStartHandle: null,
connectionEndHandle: null,
connectionClickStartHandle: null,
connectOnClick: true,
ariaLiveMessage: '',
autoPanOnConnect: true,
autoPanOnNodeDrag: true,
connectionRadius: 20,
onError: devWarn,
isValidConnection: undefined,
};
export default initialState;
<file_sep>import { useCallback } from 'react';
import { useStoreApi } from './useStore';
import type { UseDragEvent } from '../types';
function useGetPointerPosition() {
const store = useStoreApi();
// returns the pointer position projected to the RF coordinate system
const getPointerPosition = useCallback(({ sourceEvent }: UseDragEvent) => {
const { transform, snapGrid, snapToGrid } = store.getState();
const x = sourceEvent.touches ? sourceEvent.touches[0].clientX : sourceEvent.clientX;
const y = sourceEvent.touches ? sourceEvent.touches[0].clientY : sourceEvent.clientY;
const pointerPos = {
x: (x - transform[0]) / transform[2],
y: (y - transform[1]) / transform[2],
};
// we need the snapped position in order to be able to skip unnecessary drag events
return {
xSnapped: snapToGrid ? snapGrid[0] * Math.round(pointerPos.x / snapGrid[0]) : pointerPos.x,
ySnapped: snapToGrid ? snapGrid[1] * Math.round(pointerPos.y / snapGrid[1]) : pointerPos.y,
...pointerPos,
};
}, []);
return getPointerPosition;
}
export default useGetPointerPosition;
<file_sep>/* eslint-disable @typescript-eslint/no-explicit-any */
import { useState, useCallback } from 'react';
import type { SetStateAction, Dispatch } from 'react';
import { applyNodeChanges, applyEdgeChanges } from '../utils/changes';
import type { Node, NodeChange, Edge, EdgeChange } from '../types';
type ApplyChanges<ItemType, ChangesType> = (changes: ChangesType[], items: ItemType[]) => ItemType[];
type OnChange<ChangesType> = (changes: ChangesType[]) => void;
// returns a hook that can be used liked this:
// const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes);
function createUseItemsState(
applyChanges: ApplyChanges<Node, NodeChange>
): <NodeData = any>(
initialItems: Node<NodeData>[]
) => [Node<NodeData>[], Dispatch<SetStateAction<Node<NodeData>[]>>, OnChange<NodeChange>];
function createUseItemsState(
applyChanges: ApplyChanges<Edge, EdgeChange>
): <EdgeData = any>(
initialItems: Edge<EdgeData>[]
) => [Edge<EdgeData>[], Dispatch<SetStateAction<Edge<EdgeData>[]>>, OnChange<EdgeChange>];
function createUseItemsState(
applyChanges: ApplyChanges<any, any>
): (initialItems: any[]) => [any[], Dispatch<SetStateAction<any[]>>, OnChange<any>] {
return (initialItems: any[]) => {
const [items, setItems] = useState(initialItems);
const onItemsChange = useCallback((changes: any[]) => setItems((items: any) => applyChanges(changes, items)), []);
return [items, setItems, onItemsChange];
};
}
export const useNodesState = createUseItemsState(applyNodeChanges);
export const useEdgesState = createUseItemsState(applyEdgeChanges);
<file_sep>type GetDirectionParams = {
width: number;
prevWidth: number;
height: number;
prevHeight: number;
invertX: boolean;
invertY: boolean;
};
// returns an array of two numbers (0, 1 or -1) representing the direction of the resize
// 0 = no change, 1 = increase, -1 = decrease
export function getDirection({ width, prevWidth, height, prevHeight, invertX, invertY }: GetDirectionParams) {
const deltaWidth = width - prevWidth;
const deltaHeight = height - prevHeight;
const direction = [deltaWidth > 0 ? 1 : deltaWidth < 0 ? -1 : 0, deltaHeight > 0 ? 1 : deltaHeight < 0 ? -1 : 0];
if (deltaWidth && invertX) {
direction[0] = direction[0] * -1;
}
if (deltaHeight && invertY) {
direction[1] = direction[1] * -1;
}
return direction;
}
<file_sep>import type {
KeyboardEvent as ReactKeyboardEvent,
MouseEvent as ReactMouseEvent,
TouchEvent as ReactTouchEvent,
} from 'react';
import type { Dimensions, Node, XYPosition, CoordinateExtent, Box, Rect } from '../types';
export const getDimensions = (node: HTMLDivElement): Dimensions => ({
width: node.offsetWidth,
height: node.offsetHeight,
});
export const clamp = (val: number, min = 0, max = 1): number => Math.min(Math.max(val, min), max);
export const clampPosition = (position: XYPosition = { x: 0, y: 0 }, extent: CoordinateExtent) => ({
x: clamp(position.x, extent[0][0], extent[1][0]),
y: clamp(position.y, extent[0][1], extent[1][1]),
});
// returns a number between 0 and 1 that represents the velocity of the movement
// when the mouse is close to the edge of the canvas
const calcAutoPanVelocity = (value: number, min: number, max: number): number => {
if (value < min) {
return clamp(Math.abs(value - min), 1, 50) / 50;
} else if (value > max) {
return -clamp(Math.abs(value - max), 1, 50) / 50;
}
return 0;
};
export const calcAutoPan = (pos: XYPosition, bounds: Dimensions): number[] => {
const xMovement = calcAutoPanVelocity(pos.x, 35, bounds.width - 35) * 20;
const yMovement = calcAutoPanVelocity(pos.y, 35, bounds.height - 35) * 20;
return [xMovement, yMovement];
};
export const getHostForElement = (element: HTMLElement): Document | ShadowRoot =>
(element.getRootNode?.() as Document | ShadowRoot) || window?.document;
export const getBoundsOfBoxes = (box1: Box, box2: Box): Box => ({
x: Math.min(box1.x, box2.x),
y: Math.min(box1.y, box2.y),
x2: Math.max(box1.x2, box2.x2),
y2: Math.max(box1.y2, box2.y2),
});
export const rectToBox = ({ x, y, width, height }: Rect): Box => ({
x,
y,
x2: x + width,
y2: y + height,
});
export const boxToRect = ({ x, y, x2, y2 }: Box): Rect => ({
x,
y,
width: x2 - x,
height: y2 - y,
});
export const nodeToRect = (node: Node): Rect => ({
...(node.positionAbsolute || { x: 0, y: 0 }),
width: node.width || 0,
height: node.height || 0,
});
export const getBoundsOfRects = (rect1: Rect, rect2: Rect): Rect =>
boxToRect(getBoundsOfBoxes(rectToBox(rect1), rectToBox(rect2)));
export const getOverlappingArea = (rectA: Rect, rectB: Rect): number => {
const xOverlap = Math.max(0, Math.min(rectA.x + rectA.width, rectB.x + rectB.width) - Math.max(rectA.x, rectB.x));
const yOverlap = Math.max(0, Math.min(rectA.y + rectA.height, rectB.y + rectB.height) - Math.max(rectA.y, rectB.y));
return Math.ceil(xOverlap * yOverlap);
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const isRectObject = (obj: any): obj is Rect =>
isNumeric(obj.width) && isNumeric(obj.height) && isNumeric(obj.x) && isNumeric(obj.y);
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
export const isNumeric = (n: any): n is number => !isNaN(n) && isFinite(n);
export const internalsSymbol = Symbol.for('internals');
// used for a11y key board controls for nodes and edges
export const elementSelectionKeys = ['Enter', ' ', 'Escape'];
export const devWarn = (id: string, message: string) => {
if (process.env.NODE_ENV === 'development') {
console.warn(`[React Flow]: ${message} Help: https://reactflow.dev/error#${id}`);
}
};
const isReactKeyboardEvent = (event: KeyboardEvent | ReactKeyboardEvent): event is ReactKeyboardEvent =>
'nativeEvent' in event;
export function isInputDOMNode(event: KeyboardEvent | ReactKeyboardEvent): boolean {
const kbEvent = isReactKeyboardEvent(event) ? event.nativeEvent : event;
// using composed path for handling shadow dom
const target = (kbEvent.composedPath?.()?.[0] || event.target) as HTMLElement;
const isInput = ['INPUT', 'SELECT', 'TEXTAREA'].includes(target?.nodeName) || target?.hasAttribute('contenteditable');
// when an input field is focused we don't want to trigger deletion or movement of nodes
return isInput || !!target?.closest('.nokey');
}
export const isMouseEvent = (
event: MouseEvent | ReactMouseEvent | TouchEvent | ReactTouchEvent
): event is MouseEvent | ReactMouseEvent => 'clientX' in event;
export const getEventPosition = (
event: MouseEvent | ReactMouseEvent | TouchEvent | ReactTouchEvent,
bounds?: DOMRect
) => {
const isMouseTriggered = isMouseEvent(event);
const evtX = isMouseTriggered ? event.clientX : event.touches?.[0].clientX;
const evtY = isMouseTriggered ? event.clientY : event.touches?.[0].clientY;
return {
x: evtX - (bounds?.left ?? 0),
y: evtY - (bounds?.top ?? 0),
};
};
<file_sep>/* eslint-disable @typescript-eslint/no-explicit-any */
import type { XYPosition, Dimensions } from './utils';
import type { Node } from './nodes';
import type { Edge } from './edges';
export type NodeDimensionChange = {
id: string;
type: 'dimensions';
dimensions?: Dimensions;
updateStyle?: boolean;
resizing?: boolean;
};
export type NodePositionChange = {
id: string;
type: 'position';
position?: XYPosition;
positionAbsolute?: XYPosition;
dragging?: boolean;
};
export type NodeSelectionChange = {
id: string;
type: 'select';
selected: boolean;
};
export type NodeRemoveChange = {
id: string;
type: 'remove';
};
export type NodeAddChange<NodeData = any> = {
item: Node<NodeData>;
type: 'add';
};
export type NodeResetChange<NodeData = any> = {
item: Node<NodeData>;
type: 'reset';
};
export type NodeChange =
| NodeDimensionChange
| NodePositionChange
| NodeSelectionChange
| NodeRemoveChange
| NodeAddChange
| NodeResetChange;
export type EdgeSelectionChange = NodeSelectionChange;
export type EdgeRemoveChange = NodeRemoveChange;
export type EdgeAddChange<EdgeData = any> = {
item: Edge<EdgeData>;
type: 'add';
};
export type EdgeResetChange<EdgeData = any> = {
item: Edge<EdgeData>;
type: 'reset';
};
export type EdgeChange = EdgeSelectionChange | EdgeRemoveChange | EdgeAddChange | EdgeResetChange;
<file_sep>import { MouseEvent as ReactMouseEvent } from 'react';
import { StoreApi } from 'zustand';
import type { Edge, MarkerType, ReactFlowState } from '../../types';
export const getMarkerEnd = (markerType?: MarkerType, markerEndId?: string): string => {
if (typeof markerEndId !== 'undefined' && markerEndId) {
return `url(#${markerEndId})`;
}
return typeof markerType !== 'undefined' ? `url(#react-flow__${markerType})` : 'none';
};
export function getMouseHandler(
id: string,
getState: StoreApi<ReactFlowState>['getState'],
handler?: (event: ReactMouseEvent<SVGGElement, MouseEvent>, edge: Edge) => void
) {
return handler === undefined
? handler
: (event: ReactMouseEvent<SVGGElement, MouseEvent>) => {
const edge = getState().edges.find((e) => e.id === id);
if (edge) {
handler(event, { ...edge });
}
};
}
// this is used for straight edges and simple smoothstep edges (LTR, RTL, BTT, TTB)
export function getEdgeCenter({
sourceX,
sourceY,
targetX,
targetY,
}: {
sourceX: number;
sourceY: number;
targetX: number;
targetY: number;
}): [number, number, number, number] {
const xOffset = Math.abs(targetX - sourceX) / 2;
const centerX = targetX < sourceX ? targetX + xOffset : targetX - xOffset;
const yOffset = Math.abs(targetY - sourceY) / 2;
const centerY = targetY < sourceY ? targetY + yOffset : targetY - yOffset;
return [centerX, centerY, xOffset, yOffset];
}
export function getBezierEdgeCenter({
sourceX,
sourceY,
targetX,
targetY,
sourceControlX,
sourceControlY,
targetControlX,
targetControlY,
}: {
sourceX: number;
sourceY: number;
targetX: number;
targetY: number;
sourceControlX: number;
sourceControlY: number;
targetControlX: number;
targetControlY: number;
}): [number, number, number, number] {
// cubic bezier t=0.5 mid point, not the actual mid point, but easy to calculate
// https://stackoverflow.com/questions/67516101/how-to-find-distance-mid-point-of-bezier-curve
const centerX = sourceX * 0.125 + sourceControlX * 0.375 + targetControlX * 0.375 + targetX * 0.125;
const centerY = sourceY * 0.125 + sourceControlY * 0.375 + targetControlY * 0.375 + targetY * 0.125;
const offsetX = Math.abs(centerX - sourceX);
const offsetY = Math.abs(centerY - sourceY);
return [centerX, centerY, offsetX, offsetY];
}
<file_sep>import { zoomIdentity } from 'd3-zoom';
import type { StoreApi } from 'zustand';
import { internalsSymbol, isNumeric } from '../utils';
import { getD3Transition, getRectOfNodes, getTransformForBounds, getNodePositionWithOrigin } from '../utils/graph';
import type {
Edge,
EdgeSelectionChange,
Node,
NodeInternals,
NodeSelectionChange,
ReactFlowState,
XYZPosition,
FitViewOptions,
NodeOrigin,
} from '../types';
type ParentNodes = Record<string, boolean>;
function calculateXYZPosition(
node: Node,
nodeInternals: NodeInternals,
result: XYZPosition,
nodeOrigin: NodeOrigin
): XYZPosition {
if (!node.parentNode) {
return result;
}
const parentNode = nodeInternals.get(node.parentNode)!;
const parentNodePosition = getNodePositionWithOrigin(parentNode, nodeOrigin);
return calculateXYZPosition(
parentNode,
nodeInternals,
{
x: (result.x ?? 0) + parentNodePosition.x,
y: (result.y ?? 0) + parentNodePosition.y,
z: (parentNode[internalsSymbol]?.z ?? 0) > (result.z ?? 0) ? parentNode[internalsSymbol]?.z ?? 0 : result.z ?? 0,
},
nodeOrigin
);
}
export function updateAbsoluteNodePositions(
nodeInternals: NodeInternals,
nodeOrigin: NodeOrigin,
parentNodes?: ParentNodes
) {
nodeInternals.forEach((node) => {
if (node.parentNode && !nodeInternals.has(node.parentNode)) {
throw new Error(`Parent node ${node.parentNode} not found`);
}
if (node.parentNode || parentNodes?.[node.id]) {
const { x, y, z } = calculateXYZPosition(
node,
nodeInternals,
{
...node.position,
z: node[internalsSymbol]?.z ?? 0,
},
nodeOrigin
);
node.positionAbsolute = {
x,
y,
};
node[internalsSymbol]!.z = z;
if (parentNodes?.[node.id]) {
node[internalsSymbol]!.isParent = true;
}
}
});
}
export function createNodeInternals(
nodes: Node[],
nodeInternals: NodeInternals,
nodeOrigin: NodeOrigin,
elevateNodesOnSelect: boolean
): NodeInternals {
const nextNodeInternals = new Map<string, Node>();
const parentNodes: ParentNodes = {};
const selectedNodeZ: number = elevateNodesOnSelect ? 1000 : 0;
nodes.forEach((node) => {
const z = (isNumeric(node.zIndex) ? node.zIndex : 0) + (node.selected ? selectedNodeZ : 0);
const currInternals = nodeInternals.get(node.id);
const internals: Node = {
width: currInternals?.width,
height: currInternals?.height,
...node,
positionAbsolute: {
x: node.position.x,
y: node.position.y,
},
};
if (node.parentNode) {
internals.parentNode = node.parentNode;
parentNodes[node.parentNode] = true;
}
Object.defineProperty(internals, internalsSymbol, {
enumerable: false,
value: {
handleBounds: currInternals?.[internalsSymbol]?.handleBounds,
z,
},
});
nextNodeInternals.set(node.id, internals);
});
updateAbsoluteNodePositions(nextNodeInternals, nodeOrigin, parentNodes);
return nextNodeInternals;
}
type InternalFitViewOptions = {
initial?: boolean;
} & FitViewOptions;
export function fitView(get: StoreApi<ReactFlowState>['getState'], options: InternalFitViewOptions = {}) {
const {
getNodes,
width,
height,
minZoom,
maxZoom,
d3Zoom,
d3Selection,
fitViewOnInitDone,
fitViewOnInit,
nodeOrigin,
} = get();
const isInitialFitView = options.initial && !fitViewOnInitDone && fitViewOnInit;
const d3initialized = d3Zoom && d3Selection;
if (d3initialized && (isInitialFitView || !options.initial)) {
const nodes = getNodes().filter((n) => {
const isVisible = options.includeHiddenNodes ? n.width && n.height : !n.hidden;
if (options.nodes?.length) {
return isVisible && options.nodes.some((optionNode) => optionNode.id === n.id);
}
return isVisible;
});
const nodesInitialized = nodes.every((n) => n.width && n.height);
if (nodes.length > 0 && nodesInitialized) {
const bounds = getRectOfNodes(nodes, nodeOrigin);
const [x, y, zoom] = getTransformForBounds(
bounds,
width,
height,
options.minZoom ?? minZoom,
options.maxZoom ?? maxZoom,
options.padding ?? 0.1
);
const nextTransform = zoomIdentity.translate(x, y).scale(zoom);
if (typeof options.duration === 'number' && options.duration > 0) {
d3Zoom.transform(getD3Transition(d3Selection, options.duration), nextTransform);
} else {
d3Zoom.transform(d3Selection, nextTransform);
}
return true;
}
}
return false;
}
export function handleControlledNodeSelectionChange(nodeChanges: NodeSelectionChange[], nodeInternals: NodeInternals) {
nodeChanges.forEach((change) => {
const node = nodeInternals.get(change.id);
if (node) {
nodeInternals.set(node.id, {
...node,
[internalsSymbol]: node[internalsSymbol],
selected: change.selected,
});
}
});
return new Map(nodeInternals);
}
export function handleControlledEdgeSelectionChange(edgeChanges: EdgeSelectionChange[], edges: Edge[]) {
return edges.map((e) => {
const change = edgeChanges.find((change) => change.id === e.id);
if (change) {
e.selected = change.selected;
}
return e;
});
}
type UpdateNodesAndEdgesParams = {
changedNodes: NodeSelectionChange[] | null;
changedEdges: EdgeSelectionChange[] | null;
get: StoreApi<ReactFlowState>['getState'];
set: StoreApi<ReactFlowState>['setState'];
};
export function updateNodesAndEdgesSelections({ changedNodes, changedEdges, get, set }: UpdateNodesAndEdgesParams) {
const { nodeInternals, edges, onNodesChange, onEdgesChange, hasDefaultNodes, hasDefaultEdges } = get();
if (changedNodes?.length) {
if (hasDefaultNodes) {
set({ nodeInternals: handleControlledNodeSelectionChange(changedNodes, nodeInternals) });
}
onNodesChange?.(changedNodes);
}
if (changedEdges?.length) {
if (hasDefaultEdges) {
set({ edges: handleControlledEdgeSelectionChange(changedEdges, edges) });
}
onEdgesChange?.(changedEdges);
}
}
<file_sep>/* eslint-disable @typescript-eslint/no-explicit-any */
import type { CSSProperties, ComponentType, HTMLAttributes, ReactNode, MouseEvent as ReactMouseEvent } from 'react';
import { ConnectionStatus, Position } from '.';
import type { Connection, HandleElement, HandleType, Node } from '.';
type EdgeLabelOptions = {
label?: string | ReactNode;
labelStyle?: CSSProperties;
labelShowBg?: boolean;
labelBgStyle?: CSSProperties;
labelBgPadding?: [number, number];
labelBgBorderRadius?: number;
};
// interface for the user edge items
type DefaultEdge<T = any> = {
id: string;
type?: string;
source: string;
target: string;
sourceHandle?: string | null;
targetHandle?: string | null;
style?: CSSProperties;
animated?: boolean;
hidden?: boolean;
deletable?: boolean;
data?: T;
className?: string;
sourceNode?: Node;
targetNode?: Node;
selected?: boolean;
markerStart?: EdgeMarkerType;
markerEnd?: EdgeMarkerType;
zIndex?: number;
ariaLabel?: string;
interactionWidth?: number;
focusable?: boolean;
updatable?: EdgeUpdatable;
} & EdgeLabelOptions;
export type EdgeUpdatable = boolean | HandleType;
export type SmoothStepPathOptions = {
offset?: number;
borderRadius?: number;
};
type SmoothStepEdgeType<T> = DefaultEdge<T> & {
type: 'smoothstep';
pathOptions?: SmoothStepPathOptions;
};
export type BezierPathOptions = {
curvature?: number;
};
type BezierEdgeType<T> = DefaultEdge<T> & {
type: 'default';
pathOptions?: BezierPathOptions;
};
export type Edge<T = any> = DefaultEdge<T> | SmoothStepEdgeType<T> | BezierEdgeType<T>;
export type DefaultEdgeOptions = Omit<
Edge,
'id' | 'source' | 'target' | 'sourceHandle' | 'targetHandle' | 'sourceNode' | 'targetNode'
>;
export type EdgeMouseHandler = (event: ReactMouseEvent, edge: Edge) => void;
export type WrapEdgeProps<T = any> = Omit<Edge<T>, 'sourceHandle' | 'targetHandle'> & {
onClick?: EdgeMouseHandler;
onEdgeDoubleClick?: EdgeMouseHandler;
sourceHandleId?: string | null;
targetHandleId?: string | null;
sourceX: number;
sourceY: number;
targetX: number;
targetY: number;
sourcePosition: Position;
targetPosition: Position;
elementsSelectable?: boolean;
onEdgeUpdate?: OnEdgeUpdateFunc;
onContextMenu?: EdgeMouseHandler;
onMouseEnter?: EdgeMouseHandler;
onMouseMove?: EdgeMouseHandler;
onMouseLeave?: EdgeMouseHandler;
edgeUpdaterRadius?: number;
onEdgeUpdateStart?: (event: ReactMouseEvent, edge: Edge, handleType: HandleType) => void;
onEdgeUpdateEnd?: (event: MouseEvent | TouchEvent, edge: Edge, handleType: HandleType) => void;
rfId?: string;
isFocusable: boolean;
isUpdatable: EdgeUpdatable;
pathOptions?: BezierPathOptions | SmoothStepPathOptions;
};
// props that get passed to a custom edge
export type EdgeProps<T = any> = Pick<
Edge<T>,
'id' | 'animated' | 'data' | 'style' | 'selected' | 'source' | 'target'
> &
Pick<
WrapEdgeProps,
| 'sourceX'
| 'sourceY'
| 'targetX'
| 'targetY'
| 'sourcePosition'
| 'targetPosition'
| 'sourceHandleId'
| 'targetHandleId'
| 'interactionWidth'
> &
EdgeLabelOptions & {
markerStart?: string;
markerEnd?: string;
// @TODO: how can we get better types for pathOptions?
pathOptions?: any;
};
export type BaseEdgeProps = Pick<EdgeProps, 'style' | 'markerStart' | 'markerEnd' | 'interactionWidth'> &
EdgeLabelOptions & {
id?: string;
labelX?: number;
labelY?: number;
path: string;
};
export type SmoothStepEdgeProps<T = any> = EdgeProps<T> & {
pathOptions?: SmoothStepPathOptions;
};
export type BezierEdgeProps<T = any> = EdgeProps<T> & {
pathOptions?: BezierPathOptions;
};
export type EdgeTextProps = HTMLAttributes<SVGElement> &
EdgeLabelOptions & {
x: number;
y: number;
};
export enum ConnectionLineType {
Bezier = 'default',
Straight = 'straight',
Step = 'step',
SmoothStep = 'smoothstep',
SimpleBezier = 'simplebezier',
}
export type ConnectionLineComponentProps = {
connectionLineStyle?: CSSProperties;
connectionLineType: ConnectionLineType;
fromNode?: Node;
fromHandle?: HandleElement;
fromX: number;
fromY: number;
toX: number;
toY: number;
fromPosition: Position;
toPosition: Position;
connectionStatus: ConnectionStatus | null;
};
export type ConnectionLineComponent = ComponentType<ConnectionLineComponentProps>;
export type OnEdgeUpdateFunc<T = any> = (oldEdge: Edge<T>, newConnection: Connection) => void;
export type EdgeMarker = {
type: MarkerType;
color?: string;
width?: number;
height?: number;
markerUnits?: string;
orient?: string;
strokeWidth?: number;
};
export type EdgeMarkerType = string | EdgeMarker;
export enum MarkerType {
Arrow = 'arrow',
ArrowClosed = 'arrowclosed',
}
<file_sep>import { useEffect } from 'react';
import type { MutableRefObject } from 'react';
import { useStoreApi } from '../hooks/useStore';
import { getDimensions } from '../utils';
import { errorMessages } from '../contants';
function useResizeHandler(rendererNode: MutableRefObject<HTMLDivElement | null>): void {
const store = useStoreApi();
useEffect(() => {
let resizeObserver: ResizeObserver;
const updateDimensions = () => {
if (!rendererNode.current) {
return;
}
const size = getDimensions(rendererNode.current);
if (size.height === 0 || size.width === 0) {
store.getState().onError?.('004', errorMessages['error004']());
}
store.setState({ width: size.width || 500, height: size.height || 500 });
};
updateDimensions();
window.addEventListener('resize', updateDimensions);
if (rendererNode.current) {
resizeObserver = new ResizeObserver(() => updateDimensions());
resizeObserver.observe(rendererNode.current);
}
return () => {
window.removeEventListener('resize', updateDimensions);
if (resizeObserver && rendererNode.current) {
resizeObserver.unobserve(rendererNode.current!);
}
};
}, []);
}
export default useResizeHandler;
<file_sep>import { useEffect } from 'react';
import { useStoreApi } from '../hooks/useStore';
import useKeyPress from './useKeyPress';
import type { KeyCode } from '../types';
import useReactFlow from './useReactFlow';
interface HookParams {
deleteKeyCode: KeyCode | null;
multiSelectionKeyCode: KeyCode | null;
}
export default ({ deleteKeyCode, multiSelectionKeyCode }: HookParams): void => {
const store = useStoreApi();
const { deleteElements } = useReactFlow();
const deleteKeyPressed = useKeyPress(deleteKeyCode);
const multiSelectionKeyPressed = useKeyPress(multiSelectionKeyCode);
useEffect(() => {
if (deleteKeyPressed) {
const { edges, getNodes } = store.getState();
const selectedNodes = getNodes().filter((node) => node.selected);
const selectedEdges = edges.filter((edge) => edge.selected);
deleteElements({ nodes: selectedNodes, edges: selectedEdges });
store.setState({ nodesSelectionActive: false });
}
}, [deleteKeyPressed]);
useEffect(() => {
store.setState({ multiSelectionActive: multiSelectionKeyPressed });
}, [multiSelectionKeyPressed]);
};
<file_sep>Cypress.Commands.add('drag', (selector, { x, y }) =>
cy.window().then((window) => {
const elementToDrag = cy.get(selector as string);
return elementToDrag.then(($el) => {
const { left, top, width, height } = $el[0].getBoundingClientRect();
const centerX = left + width / 2;
const centerY = top + height / 2;
const nextX: number = centerX + x;
const nextY: number = centerY + y;
return elementToDrag
.trigger('mousedown', { view: window })
.trigger('mousemove', nextX, nextY, { force: true })
.wait(50)
.trigger('mouseup', { view: window, force: true });
});
})
);
Cypress.Commands.add('dragPane', ({ from, to }) =>
cy
.window()
.then((window) =>
cy
.get('.react-flow__pane')
.trigger('mousedown', from.x, from.y, { view: window })
.trigger('mousemove', to.x, to.y)
.trigger('mouseup', { force: true, view: window })
)
);
Cypress.Commands.add('zoomPane', (wheelDelta: number) =>
cy.get('.react-flow__pane').trigger('wheel', 'center', { deltaY: wheelDelta }).wait(250)
);
Cypress.Commands.add('isWithinViewport', { prevSubject: true }, (subject) => {
const rect = subject[0].getBoundingClientRect();
return cy.window().then((window) => {
expect(rect.top).to.be.within(0, window.innerHeight);
expect(rect.right).to.be.within(0, window.innerWidth);
expect(rect.bottom).to.be.within(0, window.innerHeight);
expect(rect.left).to.be.within(0, window.innerWidth);
return subject;
});
});
Cypress.Commands.add('isOutsideViewport', { prevSubject: true }, (subject) => {
const rect = subject[0].getBoundingClientRect();
return cy.window().then((window) => {
expect(window.innerHeight < rect.top || rect.bottom < 0 || window.innerWidth < rect.left || rect.right < 0).to.be
.true;
return subject;
});
});
export {};
<file_sep>describe('Hidden Flow Rendering', () => {
before(() => {
cy.visit('/Hidden');
});
it('renders empty flow', () => {
cy.get('.react-flow__node').should('not.exist');
cy.get('.react-flow__edge').should('not.exist');
cy.get('.react-flow__minimap-node').should('not.exist');
});
it('toggles isHidden mode', () => {
cy.get('.react-flow__ishidden').click();
});
it('renders initial flow', () => {
cy.get('.react-flow__renderer');
cy.get('.react-flow__node').should('have.length', 4);
cy.get('.react-flow__edge').should('have.length', 3);
cy.get('.react-flow__minimap-node').should('have.length', 4);
});
it('toggles isHidden mode again', () => {
cy.get('.react-flow__ishidden').click();
});
it('renders empty flow', () => {
cy.get('.react-flow__node').should('not.exist');
cy.get('.react-flow__edge').should('not.exist');
cy.get('.react-flow__minimap-node').should('not.exist');
});
});
export {};
<file_sep>import { Node, Edge, isNode, isEdge, getOutgoers, getIncomers, addEdge } from 'reactflow';
const nodes: Node[] = [
{
id: '1',
type: 'input',
data: { label: 'Node 1' },
position: { x: 250, y: 5 },
},
{ id: '2', data: { label: 'Node 2' }, position: { x: 100, y: 100 } },
{ id: '3', data: { label: 'Node 3' }, position: { x: 400, y: 100 } },
{ id: '4', data: { label: 'Node 4' }, position: { x: 400, y: 200 } },
];
const edges: Edge[] = [
{ id: 'e1-2', source: '1', target: '2', animated: true },
{ id: 'e1-3', source: '1', target: '3' },
{ id: 'e2-3', source: '2', target: '3' },
];
describe('Graph Utils Testing', () => {
it('tests isNode function', () => {
expect(isNode(nodes[0])).to.be.true;
expect(isNode(edges[0])).to.be.false;
});
it('tests isEdge function', () => {
expect(isEdge(edges[0])).to.be.true;
expect(isEdge(nodes[0])).to.be.false;
});
it('tests getOutgoers function', () => {
const outgoers = getOutgoers(nodes[0], nodes, edges);
expect(outgoers.length).to.be.equal(2);
const noOutgoers = getOutgoers(nodes[2], nodes, edges);
expect(noOutgoers.length).to.be.equal(0);
});
it('tests getIncomers function', () => {
const incomers = getIncomers(nodes[2], nodes, edges);
expect(incomers.length).to.be.equal(2);
const noIncomers = getIncomers(nodes[0], nodes, edges);
expect(noIncomers.length).to.be.equal(0);
});
describe('tests addEdge function', () => {
it('adds edge', () => {
const newEdge: Edge = { source: '1', target: '4', id: 'new-edge-1-4' };
const nextEdges = addEdge(newEdge, edges);
expect(nextEdges.length).to.be.equal(edges.length + 1);
});
it('tries to add existing edge', () => {
const newEdge: Edge = { source: '2', target: '3', id: 'new-edge-2-3' };
const nextEdges = addEdge(newEdge, edges);
expect(nextEdges.length).to.be.equal(edges.length);
});
it('tries to add invalid edge', () => {
// @ts-ignore
const newEdge: Edge = { nosource: '1', notarget: '3' };
try {
addEdge(newEdge, edges);
} catch (e: any) {
console.log(e.message);
expect(e.message).to.be.equal("Can't create edge. An edge needs a source and a target.");
}
});
});
});
export {};
<file_sep>import type { ComponentType } from 'react';
import { BezierEdge, SmoothStepEdge, StepEdge, StraightEdge, SimpleBezierEdge } from '../../components/Edges';
import wrapEdge from '../../components/Edges/wrapEdge';
import { internalsSymbol, rectToBox } from '../../utils';
import { Position } from '../../types';
import type {
EdgeProps,
EdgeTypes,
EdgeTypesWrapped,
HandleElement,
NodeHandleBounds,
Node,
Rect,
Transform,
XYPosition,
} from '../../types';
export type CreateEdgeTypes = (edgeTypes: EdgeTypes) => EdgeTypesWrapped;
export function createEdgeTypes(edgeTypes: EdgeTypes): EdgeTypesWrapped {
const standardTypes: EdgeTypesWrapped = {
default: wrapEdge((edgeTypes.default || BezierEdge) as ComponentType<EdgeProps>),
straight: wrapEdge((edgeTypes.bezier || StraightEdge) as ComponentType<EdgeProps>),
step: wrapEdge((edgeTypes.step || StepEdge) as ComponentType<EdgeProps>),
smoothstep: wrapEdge((edgeTypes.step || SmoothStepEdge) as ComponentType<EdgeProps>),
simplebezier: wrapEdge((edgeTypes.simplebezier || SimpleBezierEdge) as ComponentType<EdgeProps>),
};
const wrappedTypes = {} as EdgeTypesWrapped;
const specialTypes: EdgeTypesWrapped = Object.keys(edgeTypes)
.filter((k) => !['default', 'bezier'].includes(k))
.reduce((res, key) => {
res[key] = wrapEdge((edgeTypes[key] || BezierEdge) as ComponentType<EdgeProps>);
return res;
}, wrappedTypes);
return {
...standardTypes,
...specialTypes,
};
}
export function getHandlePosition(position: Position, nodeRect: Rect, handle: HandleElement | null = null): XYPosition {
const x = (handle?.x || 0) + nodeRect.x;
const y = (handle?.y || 0) + nodeRect.y;
const width = handle?.width || nodeRect.width;
const height = handle?.height || nodeRect.height;
switch (position) {
case Position.Top:
return {
x: x + width / 2,
y,
};
case Position.Right:
return {
x: x + width,
y: y + height / 2,
};
case Position.Bottom:
return {
x: x + width / 2,
y: y + height,
};
case Position.Left:
return {
x,
y: y + height / 2,
};
}
}
export function getHandle(bounds: HandleElement[], handleId?: string | null): HandleElement | null {
if (!bounds) {
return null;
}
if (bounds.length === 1 || !handleId) {
return bounds[0];
} else if (handleId) {
return bounds.find((d) => d.id === handleId) || null;
}
return null;
}
interface EdgePositions {
sourceX: number;
sourceY: number;
targetX: number;
targetY: number;
}
export const getEdgePositions = (
sourceNodeRect: Rect,
sourceHandle: HandleElement,
sourcePosition: Position,
targetNodeRect: Rect,
targetHandle: HandleElement,
targetPosition: Position
): EdgePositions => {
const sourceHandlePos = getHandlePosition(sourcePosition, sourceNodeRect, sourceHandle);
const targetHandlePos = getHandlePosition(targetPosition, targetNodeRect, targetHandle);
return {
sourceX: sourceHandlePos.x,
sourceY: sourceHandlePos.y,
targetX: targetHandlePos.x,
targetY: targetHandlePos.y,
};
};
interface IsEdgeVisibleParams {
sourcePos: XYPosition;
targetPos: XYPosition;
sourceWidth: number;
sourceHeight: number;
targetWidth: number;
targetHeight: number;
width: number;
height: number;
transform: Transform;
}
export function isEdgeVisible({
sourcePos,
targetPos,
sourceWidth,
sourceHeight,
targetWidth,
targetHeight,
width,
height,
transform,
}: IsEdgeVisibleParams): boolean {
const edgeBox = {
x: Math.min(sourcePos.x, targetPos.x),
y: Math.min(sourcePos.y, targetPos.y),
x2: Math.max(sourcePos.x + sourceWidth, targetPos.x + targetWidth),
y2: Math.max(sourcePos.y + sourceHeight, targetPos.y + targetHeight),
};
if (edgeBox.x === edgeBox.x2) {
edgeBox.x2 += 1;
}
if (edgeBox.y === edgeBox.y2) {
edgeBox.y2 += 1;
}
const viewBox = rectToBox({
x: (0 - transform[0]) / transform[2],
y: (0 - transform[1]) / transform[2],
width: width / transform[2],
height: height / transform[2],
});
const xOverlap = Math.max(0, Math.min(viewBox.x2, edgeBox.x2) - Math.max(viewBox.x, edgeBox.x));
const yOverlap = Math.max(0, Math.min(viewBox.y2, edgeBox.y2) - Math.max(viewBox.y, edgeBox.y));
const overlappingArea = Math.ceil(xOverlap * yOverlap);
return overlappingArea > 0;
}
export function getNodeData(node?: Node): [Rect, NodeHandleBounds | null, boolean] {
const handleBounds = node?.[internalsSymbol]?.handleBounds || null;
const isValid =
handleBounds &&
node?.width &&
node?.height &&
typeof node?.positionAbsolute?.x !== 'undefined' &&
typeof node?.positionAbsolute?.y !== 'undefined';
return [
{
x: node?.positionAbsolute?.x || 0,
y: node?.positionAbsolute?.y || 0,
width: node?.width || 0,
height: node?.height || 0,
},
handleBounds,
!!isValid,
];
}
<file_sep>import { shallow } from 'zustand/shallow';
import { useStore } from '../hooks/useStore';
import type { Edge, ReactFlowState } from '../types';
const edgesSelector = (state: ReactFlowState) => state.edges;
function useEdges<EdgeData>(): Edge<EdgeData>[] {
const edges = useStore(edgesSelector, shallow);
return edges;
}
export default useEdges;
<file_sep># @reactflow/controls
## 11.1.15
### Patch Changes
- Updated dependencies [[`1941c561`](https://github.com/wbkd/react-flow/commit/1941c561c9eab937c0a01747c6d188ec8c6a1bf8), [`c8b607dc`](https://github.com/wbkd/react-flow/commit/c8b607dcddeaf80912b756b0ce8045f7974e4657)]:
- @reactflow/core@11.7.4
## 11.1.14
### Patch Changes
- Updated dependencies [[`52dbac5a`](https://github.com/wbkd/react-flow/commit/52dbac5a56c092504256f947df7a959eb07385c6), [`3a277cb1`](https://github.com/wbkd/react-flow/commit/3a277cb123a886af093cee694c289c7e139c79ef)]:
- @reactflow/core@11.7.3
## 11.1.13
### Patch Changes
- [#3063](https://github.com/wbkd/react-flow/pull/3063) [`33915b88`](https://github.com/wbkd/react-flow/commit/33915b88c2ae701847870346b381f9cfa86c6459) - disable zoom buttons when min/max is reached
- Updated dependencies [[`70ec97f7`](https://github.com/wbkd/react-flow/commit/70ec97f7daec6d5401215cae3edac04aea88a3ba), [`d2d1aebc`](https://github.com/wbkd/react-flow/commit/d2d1aebc0f7fea4183406e7d1915b7fcd6995f48), [`4374459e`](https://github.com/wbkd/react-flow/commit/4374459ef9fec797bbc0407231f09a1acacd245b)]:
- @reactflow/core@11.7.2
## 11.1.12
### Patch Changes
- [#3054](https://github.com/wbkd/react-flow/pull/3054) [`46526b4e`](https://github.com/wbkd/react-flow/commit/46526b4e02b83d74726701e3ba73d0be8cf80787) - fix(icons): show correct lock icon
- Updated dependencies [[`cf7a7d3d`](https://github.com/wbkd/react-flow/commit/cf7a7d3dad1e73215a72a5dc72e21fd50208cdbb), [`07b975bb`](https://github.com/wbkd/react-flow/commit/07b975bbee3580249e36a19582213b250f78093c), [`c80d269b`](https://github.com/wbkd/react-flow/commit/c80d269b85a0054221f4639c328fc36a3befbe70), [`a3fa164c`](https://github.com/wbkd/react-flow/commit/a3fa164c34cc820c79bb031c9fd97b72a3546614)]:
- @reactflow/core@11.7.1
## 11.1.11
### Patch Changes
- Updated dependencies [[`098eee3d`](https://github.com/wbkd/react-flow/commit/098eee3d41dabc870777b081796401ff13b5a776), [`fe8cac0a`](https://github.com/wbkd/react-flow/commit/fe8cac0adb359109e0e9eafe8b9261ba354076bb), [`4a4ca171`](https://github.com/wbkd/react-flow/commit/4a4ca171955f5c8d58b23e3ad48406f1a21dc402), [`923a54c4`](https://github.com/wbkd/react-flow/commit/923a54c481b90954806202817ba844cfa7203a38), [`4d97a0ed`](https://github.com/wbkd/react-flow/commit/4d97a0ed168ce643fc0c99fa6b47cf1296d66065), [`c22e1c28`](https://github.com/wbkd/react-flow/commit/c22e1c28c5555a638c2a8e82c3bfc986b3965d36)]:
- @reactflow/core@11.7.0
## 11.1.10
### Patch Changes
- Updated dependencies
## 11.1.9
### Patch Changes
- [#2895](https://github.com/wbkd/react-flow/pull/2895) [`3d5764ca`](https://github.com/wbkd/react-flow/commit/3d5764cac6548984a30cbf85899024e62fd69425) Thanks [@moklick](https://github.com/moklick)! - add data-testid for controls, minimap and background
- Updated dependencies [[`3d5764ca`](https://github.com/wbkd/react-flow/commit/3d5764cac6548984a30cbf85899024e62fd69425), [`83fc4675`](https://github.com/wbkd/react-flow/commit/83fc467545527729633e817dbccfe59d0040da4b), [`b1190837`](https://github.com/wbkd/react-flow/commit/b11908370bc438ca8d4179497cd4eb1f8c656798), [`5fabd272`](https://github.com/wbkd/react-flow/commit/5fabd2720f6367f75f79a45822d8f675a3b8e1cf), [`8f080bd5`](https://github.com/wbkd/react-flow/commit/8f080bd5e0e7e6c71f51eee9c9f2bc4b25182861), [`b8886514`](https://github.com/wbkd/react-flow/commit/b88865140c72fa7e92a883498768000cb2cc96a7), [`16bf89f2`](https://github.com/wbkd/react-flow/commit/16bf89f2b7bbf8449c00d0e2c07c19c3ff6d2533)]:
- @reactflow/core@11.6.0
## 11.1.8
### Patch Changes
- Updated dependencies [[`72216ff6`](https://github.com/wbkd/react-flow/commit/72216ff62014acd2d73999053c72bd7aeed351f6), [`959b1114`](https://github.com/wbkd/react-flow/commit/959b111448bba4686040473e46988be9e7befbe6), [`0d259b02`](https://github.com/wbkd/react-flow/commit/0d259b028558aab650546f3371a85f3bce45252f), [`f3de9335`](https://github.com/wbkd/react-flow/commit/f3de9335af6cd96cd77dc77f24a944eef85384e5), [`23424ea6`](https://github.com/wbkd/react-flow/commit/23424ea6750f092210f83df17a00c89adb910d96), [`021f5a92`](https://github.com/wbkd/react-flow/commit/021f5a9210f47a968e50446cd2f9dae1f97880a4)]:
- @reactflow/core@11.5.5
## 11.1.7
### Patch Changes
- Updated dependencies [[`383a074a`](https://github.com/wbkd/react-flow/commit/383a074aeae6dbec8437fa08c7c8d8240838a84e)]:
- @reactflow/core@11.5.4
## 11.1.6
### Patch Changes
- Updated dependencies [[`be8097ac`](https://github.com/wbkd/react-flow/commit/be8097acadca3054c3b236ce4296fc516010ef8c), [`1527795d`](https://github.com/wbkd/react-flow/commit/1527795d18c3af38c8ec7059436ea0fbf6c27bbd), [`3b6348a8`](https://github.com/wbkd/react-flow/commit/3b6348a8d1573afb39576327318bc172e33393c2)]:
- @reactflow/core@11.5.3
## 11.1.5
### Patch Changes
- [#2792](https://github.com/wbkd/react-flow/pull/2792) [`d8c679b4`](https://github.com/wbkd/react-flow/commit/d8c679b4c90c5b57d4b51e4aaa988243d6eaff5a) - Accept React 17 types as dev dependency
- Updated dependencies [[`d8c679b4`](https://github.com/wbkd/react-flow/commit/d8c679b4c90c5b57d4b51e4aaa988243d6eaff5a)]:
- @reactflow/core@11.5.2
## 11.1.4
### Patch Changes
- Updated dependencies [[`71153534`](https://github.com/wbkd/react-flow/commit/7115353418ebc7f7c81ab0e861200972bbf7dbd5)]:
- @reactflow/core@11.5.1
## 11.1.3
### Patch Changes
- Updated dependencies [[`e96309b6`](https://github.com/wbkd/react-flow/commit/e96309b6a57b1071faeebf7b0547fef7fd418694), [`85003b01`](https://github.com/wbkd/react-flow/commit/85003b01add71ea852bd5b0d2f1e7496050a6b52), [`4c516882`](https://github.com/wbkd/react-flow/commit/4c516882d2bbf426c1832a53ad40763cc1abef92)]:
- @reactflow/core@11.5.0
## 11.1.2
### Patch Changes
- [#2741](https://github.com/wbkd/react-flow/pull/2741) [`e2aff6c1`](https://github.com/wbkd/react-flow/commit/e2aff6c1e4ce54b57b724b2624367ee5fefd1c39) - chore(dependencies): update and cleanup
- Updated dependencies [[`e34a3072`](https://github.com/wbkd/react-flow/commit/e34a30726dc55184f59adc4f16ca5215a7c42805), [`e2aff6c1`](https://github.com/wbkd/react-flow/commit/e2aff6c1e4ce54b57b724b2624367ee5fefd1c39)]:
- @reactflow/core@11.4.2
## 11.1.1
### Patch Changes
- Updated dependencies [[`82988485`](https://github.com/wbkd/react-flow/commit/82988485b730a9e32acbdae1ddcc81b33ddccaba), [`d91e619a`](https://github.com/wbkd/react-flow/commit/d91e619a70a95db99a621ede59bc05b5a7766086)]:
- @reactflow/core@11.4.1
## 11.1.0
### Patch Changes
- Updated dependencies [[`ab2ff374`](https://github.com/wbkd/react-flow/commit/ab2ff3740618da48bd4350597e816c397f3d78ff), [`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0), [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493), [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9), [`7ef29108`](https://github.com/wbkd/react-flow/commit/7ef2910808aaaee029894363d52efc0c378a7654), [`23afb3ab`](https://github.com/wbkd/react-flow/commit/23afb3abebdb42fad284f68bec164afac609563c)]:
- @reactflow/core@11.4.0
## 11.1.0-next.1
### Minor Changes
- panOnDrag: Use numbers for prop ([1,2] = drag via middle or right mouse button)
- selection: do not include hidden nodes
- minimap: fix onNodeClick for nodes outside the viewport
- keys: allow multi select when input is focused
### Patch Changes
- Updated dependencies []:
- @reactflow/core@11.4.0-next.1
## 11.0.8-next.0
### Patch Changes
- Updated dependencies [[`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0), [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493), [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9), [`23afb3ab`](https://github.com/wbkd/react-flow/commit/23afb3abebdb42fad284f68bec164afac609563c)]:
- @reactflow/core@11.4.0-next.0
## 11.0.7
### Patch Changes
- Updated dependencies [[`e6b5d90f`](https://github.com/wbkd/react-flow/commit/e6b5d90f61c8ee60e817bba232a162cae2ab3e2a), [`6ee44e07`](https://github.com/wbkd/react-flow/commit/6ee44e076eaa6908d07578a757a5187642b732ae), [`aa69c207`](https://github.com/wbkd/react-flow/commit/aa69c20765e6978f4f9c8cc63ed7110dbf6d9d9d), [`d29c401d`](https://github.com/wbkd/react-flow/commit/d29c401d598dbf2dcd5609b7adb8d029906a6f18), [`0df02f35`](https://github.com/wbkd/react-flow/commit/0df02f35f8d6c54dae36af18278feadc77acb2d6)]:
- @reactflow/core@11.3.2
## 11.0.6
### Patch Changes
- Updated dependencies [[`c828bfda`](https://github.com/wbkd/react-flow/commit/c828bfda0a8c4774bc43588640c7cca0cfdcb3f4), [`b0302ce4`](https://github.com/wbkd/react-flow/commit/b0302ce4261a992bee841bae84af347d03be690f), [`b2c72813`](https://github.com/wbkd/react-flow/commit/b2c728137d1b53e38883f044fa447585c377a6af)]:
- @reactflow/core@11.3.1
## 11.0.5
### Patch Changes
- Updated dependencies [[`92cf497e`](https://github.com/wbkd/react-flow/commit/92cf497eb72f21af592a53f5af9770c9f1e6d940), [`98116d43`](https://github.com/wbkd/react-flow/commit/98116d431f9fcdcc9b23a5b606a94ec0740b64cd), [`a39224b3`](https://github.com/wbkd/react-flow/commit/a39224b3a80afbdb83fc4490dd5f4f2be23cd4dd), [`5e8b67dd`](https://github.com/wbkd/react-flow/commit/5e8b67dd41f9bb60dcd7f5d14cc34b42c970e967), [`2a1c7db6`](https://github.com/wbkd/react-flow/commit/2a1c7db6b27ac0f4f81dcef2d593f4753c4321c7)]:
- @reactflow/core@11.3.0
## 11.0.4
### Patch Changes
- Updated dependencies [[`740659c0`](https://github.com/wbkd/react-flow/commit/740659c0e788c7572d4a1e64e1d33d60712233fc), [`7902a3ce`](https://github.com/wbkd/react-flow/commit/7902a3ce3188426d5cd07cf0943a68f679e67948), [`b25d499e`](https://github.com/wbkd/react-flow/commit/b25d499ec05b5c6f21ac552d03650eb37433552e), [`4fc1253e`](https://github.com/wbkd/react-flow/commit/4fc1253eadf9b7dd392d8dc2348f44fa8d08f931), [`8ba4dd5d`](https://github.com/wbkd/react-flow/commit/8ba4dd5d1d4b2e6f107c148de62aec0b688d8b21)]:
- @reactflow/core@11.2.0
## 11.0.3
### Patch Changes
- cleanup types
- Updated dependencies:
- @reactflow/core@11.1.2
## 11.0.2
### Patch Changes
- Updated dependencies:
- @reactflow/core@11.1.1
## 11.0.1
### Patch Changes
- Updated dependencies [[`def11008`](https://github.com/wbkd/react-flow/commit/def11008d88749fec40e6fcba8bc41eea2511bab), [`d00faa6b`](https://github.com/wbkd/react-flow/commit/d00faa6b3e77388bfd655d4c02e9a5375bc515e4)]:
- @reactflow/core@11.1.0
## 11.0.0
### Major Changes
- **Better [Accessibility](/docs/guides/accessibility)**
- Nodes and edges are focusable, selectable, moveable and deleteable with the keyboard.
- `aria-` default attributes for all elements and controllable via `ariaLabel` options
- Keyboard controls can be disabled with the new `disableKeyboardA11y` prop
- **Better selectable edges** via new edge option: `interactionWidth` - renders invisible edge that makes it easier to interact
- **Better routing for smoothstep and step edges**: https://twitter.com/reactflowdev/status/1567535405284614145
- **Nicer edge updating behaviour**: https://twitter.com/reactflowdev/status/1564966917517021184
- **Node origin**: The new `nodeOrigin` prop lets you control the origin of a node. Useful for layouting.
- **New background pattern**: `BackgroundVariant.Cross` variant
- **[`useOnViewportChange`](/docs/api/hooks/use-on-viewport-change) hook** - handle viewport changes within a component
- **[`useOnSelectionChange`](/docs/api/hooks/use-on-selection-change) hook** - handle selection changes within a component
- **[`useNodesInitialized`](/docs/api/hooks/use-nodes-initialized) hook** - returns true if all nodes are initialized and if there is more than one node
- **Deletable option** for Nodes and edges
- **New Event handlers**: `onPaneMouseEnter`, `onPaneMouseMove` and `onPaneMouseLeave`
- **Edge `pathOptions`** for `smoothstep` and `default` edges
- **Nicer cursor defaults**: Cursor is grabbing, while dragging a node or panning
- **Pane moveable** with middle mouse button
- **Pan over nodes** when they are not draggable (`draggable=false` or `nodesDraggable` false)
- **[`<BaseEdge />`](/docs/api/edges/base-edge) component** that makes it easier to build custom edges
- **[Separately installable packages](/docs/overview/packages/)**
- @reactflow/core
- @reactflow/background
- @reactflow/controls
- @reactflow/minimap
### Patch Changes
- Updated dependencies:
- @reactflow/core@11.0.0
<file_sep>import { useCallback } from 'react';
import { useStore } from '../hooks/useStore';
import { isEdgeVisible } from '../container/EdgeRenderer/utils';
import { internalsSymbol, isNumeric } from '../utils';
import type { ReactFlowState, NodeInternals, Edge } from '../types';
const defaultEdgeTree = [{ level: 0, isMaxLevel: true, edges: [] }];
function groupEdgesByZLevel(edges: Edge[], nodeInternals: NodeInternals, elevateEdgesOnSelect = false) {
let maxLevel = -1;
const levelLookup = edges.reduce<Record<string, Edge[]>>((tree, edge) => {
const hasZIndex = isNumeric(edge.zIndex);
let z = hasZIndex ? edge.zIndex! : 0;
if (elevateEdgesOnSelect) {
const targetNode = nodeInternals.get(edge.target);
const sourceNode = nodeInternals.get(edge.source);
const edgeOrConnectedNodeSelected = edge.selected || targetNode?.selected || sourceNode?.selected;
const selectedZIndex = Math.max(
sourceNode?.[internalsSymbol]?.z || 0,
targetNode?.[internalsSymbol]?.z || 0,
1000
);
z = (hasZIndex ? edge.zIndex! : 0) + (edgeOrConnectedNodeSelected ? selectedZIndex : 0);
}
if (tree[z]) {
tree[z].push(edge);
} else {
tree[z] = [edge];
}
maxLevel = z > maxLevel ? z : maxLevel;
return tree;
}, {});
const edgeTree = Object.entries(levelLookup).map(([key, edges]) => {
const level = +key;
return {
edges,
level,
isMaxLevel: level === maxLevel,
};
});
if (edgeTree.length === 0) {
return defaultEdgeTree;
}
return edgeTree;
}
function useVisibleEdges(onlyRenderVisible: boolean, nodeInternals: NodeInternals, elevateEdgesOnSelect: boolean) {
const edges = useStore(
useCallback(
(s: ReactFlowState) => {
if (!onlyRenderVisible) {
return s.edges;
}
return s.edges.filter((e) => {
const sourceNode = nodeInternals.get(e.source);
const targetNode = nodeInternals.get(e.target);
return (
sourceNode?.width &&
sourceNode?.height &&
targetNode?.width &&
targetNode?.height &&
isEdgeVisible({
sourcePos: sourceNode.positionAbsolute || { x: 0, y: 0 },
targetPos: targetNode.positionAbsolute || { x: 0, y: 0 },
sourceWidth: sourceNode.width,
sourceHeight: sourceNode.height,
targetWidth: targetNode.width,
targetHeight: targetNode.height,
width: s.width,
height: s.height,
transform: s.transform,
})
);
});
},
[onlyRenderVisible, nodeInternals]
)
);
return groupEdgesByZLevel(edges, nodeInternals, elevateEdgesOnSelect);
}
export default useVisibleEdges;
<file_sep>import { shallow } from 'zustand/shallow';
import { useStore } from '../hooks/useStore';
import type { Viewport, ReactFlowState } from '../types';
const viewportSelector = (state: ReactFlowState) => ({
x: state.transform[0],
y: state.transform[1],
zoom: state.transform[2],
});
function useViewport(): Viewport {
const viewport = useStore(viewportSelector, shallow);
return viewport;
}
export default useViewport;
<file_sep>export * from './general';
export * from './nodes';
export * from './edges';
export * from './handles';
export * from './changes';
export * from './utils';
export * from './instance';
export * from './component-props';
<file_sep>import { createContext, useContext } from 'react';
export const NodeIdContext = createContext<string | null>(null);
export const Provider = NodeIdContext.Provider;
export const Consumer = NodeIdContext.Consumer;
export const useNodeId = (): string | null => {
const nodeId = useContext(NodeIdContext);
return nodeId;
};
export default NodeIdContext;
<file_sep>import { useMemo } from 'react';
import { zoomIdentity } from 'd3-zoom';
import { shallow } from 'zustand/shallow';
import { useStoreApi, useStore } from '../hooks/useStore';
import { pointToRendererPoint, getTransformForBounds, getD3Transition } from '../utils/graph';
import { fitView } from '../store/utils';
import type { ViewportHelperFunctions, ReactFlowState, XYPosition } from '../types';
// eslint-disable-next-line @typescript-eslint/no-empty-function
const noop = () => {};
const initialViewportHelper: ViewportHelperFunctions = {
zoomIn: noop,
zoomOut: noop,
zoomTo: noop,
getZoom: () => 1,
setViewport: noop,
getViewport: () => ({ x: 0, y: 0, zoom: 1 }),
fitView: () => false,
setCenter: noop,
fitBounds: noop,
project: (position: XYPosition) => position,
viewportInitialized: false,
};
const selector = (s: ReactFlowState) => ({
d3Zoom: s.d3Zoom,
d3Selection: s.d3Selection,
});
const useViewportHelper = (): ViewportHelperFunctions => {
const store = useStoreApi();
const { d3Zoom, d3Selection } = useStore(selector, shallow);
const viewportHelperFunctions = useMemo<ViewportHelperFunctions>(() => {
if (d3Selection && d3Zoom) {
return {
zoomIn: (options) => d3Zoom.scaleBy(getD3Transition(d3Selection, options?.duration), 1.2),
zoomOut: (options) => d3Zoom.scaleBy(getD3Transition(d3Selection, options?.duration), 1 / 1.2),
zoomTo: (zoomLevel, options) => d3Zoom.scaleTo(getD3Transition(d3Selection, options?.duration), zoomLevel),
getZoom: () => store.getState().transform[2],
setViewport: (transform, options) => {
const [x, y, zoom] = store.getState().transform;
const nextTransform = zoomIdentity
.translate(transform.x ?? x, transform.y ?? y)
.scale(transform.zoom ?? zoom);
d3Zoom.transform(getD3Transition(d3Selection, options?.duration), nextTransform);
},
getViewport: () => {
const [x, y, zoom] = store.getState().transform;
return { x, y, zoom };
},
fitView: (options) => fitView(store.getState, options),
setCenter: (x, y, options) => {
const { width, height, maxZoom } = store.getState();
const nextZoom = typeof options?.zoom !== 'undefined' ? options.zoom : maxZoom;
const centerX = width / 2 - x * nextZoom;
const centerY = height / 2 - y * nextZoom;
const transform = zoomIdentity.translate(centerX, centerY).scale(nextZoom);
d3Zoom.transform(getD3Transition(d3Selection, options?.duration), transform);
},
fitBounds: (bounds, options) => {
const { width, height, minZoom, maxZoom } = store.getState();
const [x, y, zoom] = getTransformForBounds(bounds, width, height, minZoom, maxZoom, options?.padding ?? 0.1);
const transform = zoomIdentity.translate(x, y).scale(zoom);
d3Zoom.transform(getD3Transition(d3Selection, options?.duration), transform);
},
project: (position: XYPosition) => {
const { transform, snapToGrid, snapGrid } = store.getState();
return pointToRendererPoint(position, transform, snapToGrid, snapGrid);
},
viewportInitialized: true,
};
}
return initialViewportHelper;
}, [d3Zoom, d3Selection]);
return viewportHelperFunctions;
};
export default useViewportHelper;
<file_sep>import { shallow } from 'zustand/shallow';
import { useStore } from '../hooks/useStore';
import type { Node, ReactFlowState } from '../types';
const nodesSelector = (state: ReactFlowState) => state.getNodes();
function useNodes<NodeData>(): Node<NodeData>[] {
const nodes = useStore(nodesSelector, shallow);
return nodes;
}
export default useNodes;
<file_sep>import type { ComponentType } from 'react';
import DefaultNode from '../../components/Nodes/DefaultNode';
import InputNode from '../../components/Nodes/InputNode';
import OutputNode from '../../components/Nodes/OutputNode';
import GroupNode from '../../components/Nodes/GroupNode';
import wrapNode from '../../components/Nodes/wrapNode';
import type { NodeTypes, NodeProps, NodeTypesWrapped, NodeOrigin, XYPosition } from '../../types';
export type CreateNodeTypes = (nodeTypes: NodeTypes) => NodeTypesWrapped;
export function createNodeTypes(nodeTypes: NodeTypes): NodeTypesWrapped {
const standardTypes: NodeTypesWrapped = {
input: wrapNode((nodeTypes.input || InputNode) as ComponentType<NodeProps>),
default: wrapNode((nodeTypes.default || DefaultNode) as ComponentType<NodeProps>),
output: wrapNode((nodeTypes.output || OutputNode) as ComponentType<NodeProps>),
group: wrapNode((nodeTypes.group || GroupNode) as ComponentType<NodeProps>),
};
const wrappedTypes = {} as NodeTypesWrapped;
const specialTypes: NodeTypesWrapped = Object.keys(nodeTypes)
.filter((k) => !['input', 'default', 'output', 'group'].includes(k))
.reduce((res, key) => {
res[key] = wrapNode((nodeTypes[key] || DefaultNode) as ComponentType<NodeProps>);
return res;
}, wrappedTypes);
return {
...standardTypes,
...specialTypes,
};
}
export const getPositionWithOrigin = ({
x,
y,
width,
height,
origin,
}: {
x: number;
y: number;
width: number;
height: number;
origin: NodeOrigin;
}): XYPosition => {
if (!width || !height) {
return { x, y };
}
if (origin[0] < 0 || origin[1] < 0 || origin[0] > 1 || origin[1] > 1) {
return { x, y };
}
return {
x: x - width * origin[0],
y: y - height * origin[1],
};
};
<file_sep>import type { MouseEvent as ReactMouseEvent, TouchEvent as ReactTouchEvent } from 'react';
import { StoreApi } from 'zustand';
import { getHostForElement, calcAutoPan, getEventPosition } from '../../utils';
import type { OnConnect, HandleType, ReactFlowState, Connection } from '../../types';
import { pointToRendererPoint, rendererPointToPoint } from '../../utils/graph';
import {
ConnectionHandle,
getClosestHandle,
getConnectionStatus,
getHandleLookup,
getHandleType,
isValidHandle,
resetRecentHandle,
ValidConnectionFunc,
} from './utils';
export function handlePointerDown({
event,
handleId,
nodeId,
onConnect,
isTarget,
getState,
setState,
isValidConnection,
edgeUpdaterType,
onEdgeUpdateEnd,
}: {
event: ReactMouseEvent | ReactTouchEvent;
handleId: string | null;
nodeId: string;
onConnect: OnConnect;
isTarget: boolean;
getState: StoreApi<ReactFlowState>['getState'];
setState: StoreApi<ReactFlowState>['setState'];
isValidConnection: ValidConnectionFunc;
edgeUpdaterType?: HandleType;
onEdgeUpdateEnd?: (evt: MouseEvent | TouchEvent) => void;
}): void {
// when react-flow is used inside a shadow root we can't use document
const doc = getHostForElement(event.target as HTMLElement);
const {
connectionMode,
domNode,
autoPanOnConnect,
connectionRadius,
onConnectStart,
panBy,
getNodes,
cancelConnection,
} = getState();
let autoPanId = 0;
let closestHandle: ConnectionHandle | null;
const { x, y } = getEventPosition(event);
const clickedHandle = doc?.elementFromPoint(x, y);
const handleType = getHandleType(edgeUpdaterType, clickedHandle);
const containerBounds = domNode?.getBoundingClientRect();
if (!containerBounds || !handleType) {
return;
}
let prevActiveHandle: Element;
let connectionPosition = getEventPosition(event, containerBounds);
let autoPanStarted = false;
let connection: Connection | null = null;
let isValid = false;
let handleDomNode: Element | null = null;
const handleLookup = getHandleLookup({
nodes: getNodes(),
nodeId,
handleId,
handleType,
});
// when the user is moving the mouse close to the edge of the canvas while connecting we move the canvas
const autoPan = (): void => {
if (!autoPanOnConnect) {
return;
}
const [xMovement, yMovement] = calcAutoPan(connectionPosition, containerBounds);
panBy({ x: xMovement, y: yMovement });
autoPanId = requestAnimationFrame(autoPan);
};
setState({
connectionPosition,
connectionStatus: null,
// connectionNodeId etc will be removed in the next major in favor of connectionStartHandle
connectionNodeId: nodeId,
connectionHandleId: handleId,
connectionHandleType: handleType,
connectionStartHandle: {
nodeId,
handleId,
type: handleType,
},
connectionEndHandle: null,
});
onConnectStart?.(event, { nodeId, handleId, handleType });
function onPointerMove(event: MouseEvent | TouchEvent) {
const { transform } = getState();
connectionPosition = getEventPosition(event, containerBounds);
const { handle, validHandleResult } = getClosestHandle(
event,
doc,
pointToRendererPoint(connectionPosition, transform, false, [1, 1]),
connectionRadius,
handleLookup,
(handle) =>
isValidHandle(handle, connectionMode, nodeId, handleId, isTarget ? 'target' : 'source', isValidConnection, doc)
);
closestHandle = handle;
if (!autoPanStarted) {
autoPan();
autoPanStarted = true;
}
handleDomNode = validHandleResult.handleDomNode;
connection = validHandleResult.connection;
isValid = validHandleResult.isValid;
setState({
connectionPosition:
closestHandle && isValid
? rendererPointToPoint(
{
x: closestHandle.x,
y: closestHandle.y,
},
transform
)
: connectionPosition,
connectionStatus: getConnectionStatus(!!closestHandle, isValid),
connectionEndHandle: validHandleResult.endHandle,
});
if (!closestHandle && !isValid && !handleDomNode) {
return resetRecentHandle(prevActiveHandle);
}
if (connection.source !== connection.target && handleDomNode) {
resetRecentHandle(prevActiveHandle);
prevActiveHandle = handleDomNode;
// @todo: remove the old class names "react-flow__handle-" in the next major version
handleDomNode.classList.add('connecting', 'react-flow__handle-connecting');
handleDomNode.classList.toggle('valid', isValid);
handleDomNode.classList.toggle('react-flow__handle-valid', isValid);
}
}
function onPointerUp(event: MouseEvent | TouchEvent) {
if ((closestHandle || handleDomNode) && connection && isValid) {
onConnect?.(connection);
}
// it's important to get a fresh reference from the store here
// in order to get the latest state of onConnectEnd
getState().onConnectEnd?.(event);
if (edgeUpdaterType) {
onEdgeUpdateEnd?.(event);
}
resetRecentHandle(prevActiveHandle);
cancelConnection();
cancelAnimationFrame(autoPanId);
autoPanStarted = false;
isValid = false;
connection = null;
handleDomNode = null;
doc.removeEventListener('mousemove', onPointerMove as EventListener);
doc.removeEventListener('mouseup', onPointerUp as EventListener);
doc.removeEventListener('touchmove', onPointerMove as EventListener);
doc.removeEventListener('touchend', onPointerUp as EventListener);
}
doc.addEventListener('mousemove', onPointerMove as EventListener);
doc.addEventListener('mouseup', onPointerUp as EventListener);
doc.addEventListener('touchmove', onPointerMove as EventListener);
doc.addEventListener('touchend', onPointerUp as EventListener);
}
<file_sep>/* eslint-disable @typescript-eslint/no-explicit-any */
import type { ComponentType, CSSProperties, HTMLAttributes, MouseEvent } from 'react';
import type { Node, PanelPosition, XYPosition } from '@reactflow/core';
export type GetMiniMapNodeAttribute<NodeData = any> = (node: Node<NodeData>) => string;
export type MiniMapProps<NodeData = any> = Omit<HTMLAttributes<SVGSVGElement>, 'onClick'> & {
nodeColor?: string | GetMiniMapNodeAttribute<NodeData>;
nodeStrokeColor?: string | GetMiniMapNodeAttribute<NodeData>;
nodeClassName?: string | GetMiniMapNodeAttribute<NodeData>;
nodeBorderRadius?: number;
nodeStrokeWidth?: number;
nodeComponent?: ComponentType<MiniMapNodeProps>;
maskColor?: string;
maskStrokeColor?: string;
maskStrokeWidth?: number;
position?: PanelPosition;
onClick?: (event: MouseEvent, position: XYPosition) => void;
onNodeClick?: (event: MouseEvent, node: Node<NodeData>) => void;
pannable?: boolean;
zoomable?: boolean;
ariaLabel?: string | null;
inversePan?: boolean;
zoomStep?: number;
};
export type MiniMapNodes = Pick<
MiniMapProps,
'nodeColor' | 'nodeStrokeColor' | 'nodeClassName' | 'nodeBorderRadius' | 'nodeStrokeWidth' | 'nodeComponent'
> & {
onClick?: (event: MouseEvent, nodeId: string) => void;
};
export type MiniMapNodeProps = {
id: string;
x: number;
y: number;
width: number;
height: number;
borderRadius: number;
className: string;
color: string;
shapeRendering: string;
strokeColor: string;
strokeWidth: number;
style?: CSSProperties;
onClick?: (event: MouseEvent, id: string) => void;
};
<file_sep># @reactflow/node-toolbar
A toolbar component for React Flow that can be attached to a node.
## Installation
```sh
npm install @reactflow/node-toolbar
```
<file_sep># @reactflow/node-resizer
A resizer component for React Flow that can be attached to a node.
## Installation
```sh
npm install @reactflow/node-resizer
```
<file_sep>describe('Minimap Testing', () => {
before(() => {
cy.visit('/');
});
it('renders the mini map', () => {
cy.get('.react-flow__minimap');
cy.get('.react-flow__minimap-mask');
});
it('has same number of nodes as the pane', () => {
cy.get('.react-flow__minimap-node').then(() => {
const paneNodes = Cypress.$('.react-flow__node').length;
const minimapNodes = Cypress.$('.react-flow__minimap-node').length;
expect(paneNodes).equal(minimapNodes);
});
});
it('changes zoom level', () => {
const viewBoxBeforeZoom = Cypress.$('.react-flow__minimap svg').attr('viewBox');
const maskPathBeforeZoom = Cypress.$('.react-flow__minimap-mask').attr('d');
cy.get('.react-flow__pane')
.trigger('wheel', 'topLeft', { deltaY: -200 })
.wait(50)
.then(() => {
const viewBoxAfterZoom = Cypress.$('.react-flow__minimap svg').attr('viewBox');
const maskPathAfterZoom = Cypress.$('.react-flow__minimap-mask').attr('d');
expect(viewBoxBeforeZoom).to.not.equal(viewBoxAfterZoom);
expect(maskPathBeforeZoom).to.not.equal(maskPathAfterZoom);
});
});
it('changes node position', () => {
const minimapNode = Cypress.$('.react-flow__minimap-node:first');
const xPosBeforeDrag = Number(minimapNode.attr('x'));
const yPosBeforeDrag = Number(minimapNode.attr('y'));
cy.drag('.react-flow__node:first', { x: 500, y: 25 })
.wait(100)
.then(() => {
const xPosAfterDrag = Number(minimapNode.attr('x'));
const yPosAfterDrag = Number(minimapNode.attr('y'));
expect(xPosAfterDrag).not.to.equal(xPosBeforeDrag);
expect(yPosAfterDrag).not.to.equal(yPosBeforeDrag);
expect(xPosAfterDrag - xPosBeforeDrag).to.be.greaterThan(yPosAfterDrag - yPosBeforeDrag);
});
});
it('changes node positions via pane drag', () => {
const viewBoxBeforeDrag = Cypress.$('.react-flow__minimap svg').attr('viewBox');
const maskPathBeforeDrag = Cypress.$('.react-flow__minimap-mask').attr('d');
// for d3 we have to pass the window to the event
// https://github.com/cypress-io/cypress/issues/3441
cy.window().then((win) => {
cy.get('.react-flow__pane')
.trigger('mousedown', 'topLeft', { button: 0, view: win })
.trigger('mousemove', 'bottomLeft')
.wait(50)
.trigger('mouseup', { force: true, view: win })
.then(() => {
const viewBoxAfterDrag = Cypress.$('.react-flow__minimap svg').attr('viewBox');
const maskPathAfterDrag = Cypress.$('.react-flow__minimap-mask').attr('d');
expect(viewBoxBeforeDrag).to.not.equal(viewBoxAfterDrag);
expect(maskPathBeforeDrag).to.not.equal(maskPathAfterDrag);
});
});
});
});
export {};
<file_sep>import type { XYPosition, Position, Dimensions, OnConnect, Connection } from '.';
export type HandleType = 'source' | 'target';
export type HandleElement = XYPosition &
Dimensions & {
id?: string | null;
position: Position;
};
export type ConnectingHandle = {
nodeId: string;
type: HandleType;
handleId?: string | null;
};
export type HandleProps = {
type: HandleType;
position: Position;
isConnectable?: boolean;
isConnectableStart?: boolean;
isConnectableEnd?: boolean;
onConnect?: OnConnect;
isValidConnection?: (connection: Connection) => boolean;
id?: string;
};
<file_sep>import { Position } from '@reactflow/core';
import type { HTMLAttributes } from 'react';
export type NodeToolbarProps = HTMLAttributes<HTMLDivElement> & {
nodeId?: string | string[];
isVisible?: boolean;
position?: Position;
offset?: number;
align?: Align;
};
export type Align = 'center' | 'start' | 'end';
<file_sep>import type { CSSProperties, HTMLAttributes, MouseEvent as ReactMouseEvent, WheelEvent } from 'react';
import type {
OnSelectionChangeFunc,
NodeTypes,
EdgeTypes,
Node,
Edge,
ConnectionMode,
ConnectionLineType,
ConnectionLineComponent,
OnConnectStart,
OnConnectEnd,
OnConnect,
CoordinateExtent,
KeyCode,
PanOnScrollMode,
OnEdgeUpdateFunc,
OnInit,
ProOptions,
PanelPosition,
DefaultEdgeOptions,
FitViewOptions,
OnNodesDelete,
OnEdgesDelete,
OnNodesChange,
OnEdgesChange,
OnMove,
OnMoveStart,
OnMoveEnd,
NodeDragHandler,
NodeMouseHandler,
SelectionDragHandler,
Viewport,
NodeOrigin,
EdgeMouseHandler,
HandleType,
SelectionMode,
OnError,
} from '.';
import { ValidConnectionFunc } from '../components/Handle/utils';
export type ReactFlowProps = HTMLAttributes<HTMLDivElement> & {
nodes?: Node[];
edges?: Edge[];
defaultNodes?: Node[];
defaultEdges?: Edge[];
defaultEdgeOptions?: DefaultEdgeOptions;
onNodeClick?: NodeMouseHandler;
onNodeDoubleClick?: NodeMouseHandler;
onNodeMouseEnter?: NodeMouseHandler;
onNodeMouseMove?: NodeMouseHandler;
onNodeMouseLeave?: NodeMouseHandler;
onNodeContextMenu?: NodeMouseHandler;
onNodeDragStart?: NodeDragHandler;
onNodeDrag?: NodeDragHandler;
onNodeDragStop?: NodeDragHandler;
onEdgeClick?: (event: ReactMouseEvent, node: Edge) => void;
onEdgeUpdate?: OnEdgeUpdateFunc;
onEdgeContextMenu?: EdgeMouseHandler;
onEdgeMouseEnter?: EdgeMouseHandler;
onEdgeMouseMove?: EdgeMouseHandler;
onEdgeMouseLeave?: EdgeMouseHandler;
onEdgeDoubleClick?: EdgeMouseHandler;
onEdgeUpdateStart?: (event: ReactMouseEvent, edge: Edge, handleType: HandleType) => void;
onEdgeUpdateEnd?: (event: MouseEvent | TouchEvent, edge: Edge, handleType: HandleType) => void;
onNodesChange?: OnNodesChange;
onEdgesChange?: OnEdgesChange;
onNodesDelete?: OnNodesDelete;
onEdgesDelete?: OnEdgesDelete;
onSelectionDragStart?: SelectionDragHandler;
onSelectionDrag?: SelectionDragHandler;
onSelectionDragStop?: SelectionDragHandler;
onSelectionStart?: (event: ReactMouseEvent) => void;
onSelectionEnd?: (event: ReactMouseEvent) => void;
onSelectionContextMenu?: (event: ReactMouseEvent, nodes: Node[]) => void;
onConnect?: OnConnect;
onConnectStart?: OnConnectStart;
onConnectEnd?: OnConnectEnd;
onClickConnectStart?: OnConnectStart;
onClickConnectEnd?: OnConnectEnd;
onInit?: OnInit;
onMove?: OnMove;
onMoveStart?: OnMoveStart;
onMoveEnd?: OnMoveEnd;
onSelectionChange?: OnSelectionChangeFunc;
onPaneScroll?: (event?: WheelEvent) => void;
onPaneClick?: (event: ReactMouseEvent) => void;
onPaneContextMenu?: (event: ReactMouseEvent) => void;
onPaneMouseEnter?: (event: ReactMouseEvent) => void;
onPaneMouseMove?: (event: ReactMouseEvent) => void;
onPaneMouseLeave?: (event: ReactMouseEvent) => void;
nodeTypes?: NodeTypes;
edgeTypes?: EdgeTypes;
connectionLineType?: ConnectionLineType;
connectionLineStyle?: CSSProperties;
connectionLineComponent?: ConnectionLineComponent;
connectionLineContainerStyle?: CSSProperties;
connectionMode?: ConnectionMode;
deleteKeyCode?: KeyCode | null;
selectionKeyCode?: KeyCode | null;
selectionOnDrag?: boolean;
selectionMode?: SelectionMode;
panActivationKeyCode?: KeyCode | null;
multiSelectionKeyCode?: KeyCode | null;
zoomActivationKeyCode?: KeyCode | null;
snapToGrid?: boolean;
snapGrid?: [number, number];
onlyRenderVisibleElements?: boolean;
nodesDraggable?: boolean;
nodesConnectable?: boolean;
nodesFocusable?: boolean;
nodeOrigin?: NodeOrigin;
edgesFocusable?: boolean;
edgesUpdatable?: boolean;
initNodeOrigin?: NodeOrigin;
elementsSelectable?: boolean;
selectNodesOnDrag?: boolean;
panOnDrag?: boolean | number[];
minZoom?: number;
maxZoom?: number;
defaultViewport?: Viewport;
translateExtent?: CoordinateExtent;
preventScrolling?: boolean;
nodeExtent?: CoordinateExtent;
defaultMarkerColor?: string;
zoomOnScroll?: boolean;
zoomOnPinch?: boolean;
panOnScroll?: boolean;
panOnScrollSpeed?: number;
panOnScrollMode?: PanOnScrollMode;
zoomOnDoubleClick?: boolean;
edgeUpdaterRadius?: number;
noDragClassName?: string;
noWheelClassName?: string;
noPanClassName?: string;
fitView?: boolean;
fitViewOptions?: FitViewOptions;
connectOnClick?: boolean;
attributionPosition?: PanelPosition;
proOptions?: ProOptions;
elevateNodesOnSelect?: boolean;
elevateEdgesOnSelect?: boolean;
disableKeyboardA11y?: boolean;
autoPanOnNodeDrag?: boolean;
autoPanOnConnect?: boolean;
connectionRadius?: number;
onError?: OnError;
isValidConnection?: ValidConnectionFunc;
};
export type ReactFlowRefType = HTMLDivElement;
<file_sep>export enum Position {
Left = 'left',
Top = 'top',
Right = 'right',
Bottom = 'bottom',
}
export interface XYPosition {
x: number;
y: number;
}
export type XYZPosition = XYPosition & { z: number };
export interface Dimensions {
width: number;
height: number;
}
export interface Rect extends Dimensions, XYPosition {}
export interface Box extends XYPosition {
x2: number;
y2: number;
}
export type Transform = [number, number, number];
export type CoordinateExtent = [[number, number], [number, number]];
<file_sep>import { internalsSymbol } from '../utils';
import { useStore } from './useStore';
import type { ReactFlowState } from '../types';
export type UseNodesInitializedOptions = {
includeHiddenNodes?: boolean;
};
const selector = (options: UseNodesInitializedOptions) => (s: ReactFlowState) => {
if (s.nodeInternals.size === 0) {
return false;
}
return s
.getNodes()
.filter((n) => (options.includeHiddenNodes ? true : !n.hidden))
.every((n) => n[internalsSymbol]?.handleBounds !== undefined);
};
const defaultOptions = {
includeHiddenNodes: false,
};
function useNodesInitialized(options: UseNodesInitializedOptions = defaultOptions): boolean {
const initialized = useStore(selector(options));
return initialized;
}
export default useNodesInitialized;
<file_sep># reactflow
## 11.7.4
### Patch Changes
- [#3166](https://github.com/wbkd/react-flow/pull/3166) [`1941c561`](https://github.com/wbkd/react-flow/commit/1941c561c9eab937c0a01747c6d188ec8c6a1bf8) - fix(nodeExtent): include node width and height
- [#3164](https://github.com/wbkd/react-flow/pull/3164) [`c8b607dc`](https://github.com/wbkd/react-flow/commit/c8b607dcddeaf80912b756b0ce8045f7974e4657) - fix(handles): always check handles below mouse while connecting
- Updated dependencies [[`1941c561`](https://github.com/wbkd/react-flow/commit/1941c561c9eab937c0a01747c6d188ec8c6a1bf8), [`c8b607dc`](https://github.com/wbkd/react-flow/commit/c8b607dcddeaf80912b756b0ce8045f7974e4657)]:
- @reactflow/core@11.7.4
- @reactflow/background@11.2.4
- @reactflow/controls@11.1.15
- @reactflow/minimap@11.5.4
- @reactflow/node-toolbar@1.2.3
## 11.7.3
### Patch Changes
- [#3154](https://github.com/wbkd/react-flow/pull/3154) [`3a277cb1`](https://github.com/wbkd/react-flow/commit/3a277cb123a886af093cee694c289c7e139c79ef) - ElevateEdgesOnSelect: adjust behaviour so that it works like elevateNodesOnSelect
- [#3152](https://github.com/wbkd/react-flow/pull/3152) [`52dbac5a`](https://github.com/wbkd/react-flow/commit/52dbac5a56c092504256f947df7a959eb07385c6) Thanks [@bcakmakoglu](https://github.com/bcakmakoglu)! - Use all valid handles in proximity to determine the closest handle that can be snapped to. Fixes invalid handles connection radius blocking snap to valid handles inside the same radius
- [#3150](https://github.com/wbkd/react-flow/pull/3150) [`880a5932`](https://github.com/wbkd/react-flow/commit/880a593292ce5fdff30b656c2a1290cf98771818) Thanks [@goliney](https://github.com/goliney)! - Node-Resizer: add onResize/onResizeStart/onResizeEnd to useEffect deps
- [#3153](https://github.com/wbkd/react-flow/pull/3153) [`fbbee046`](https://github.com/wbkd/react-flow/commit/fbbee046282d466612089d31a2eff5a010733283) - Minimap: Improve performance for flows with lots of nodes that use the MiniMap component
- Updated dependencies [[`fbbee046`](https://github.com/wbkd/react-flow/commit/fbbee046282d466612089d31a2eff5a010733283), [`52dbac5a`](https://github.com/wbkd/react-flow/commit/52dbac5a56c092504256f947df7a959eb07385c6), [`3a277cb1`](https://github.com/wbkd/react-flow/commit/3a277cb123a886af093cee694c289c7e139c79ef), [`880a5932`](https://github.com/wbkd/react-flow/commit/880a593292ce5fdff30b656c2a1290cf98771818)]:
- @reactflow/minimap@11.5.3
- @reactflow/core@11.7.3
- @reactflow/node-resizer@2.1.1
- @reactflow/background@11.2.3
- @reactflow/controls@11.1.14
- @reactflow/node-toolbar@1.2.2
## 11.7.2
### Patch Changes
- [#3063](https://github.com/wbkd/react-flow/pull/3063) [`33915b88`](https://github.com/wbkd/react-flow/commit/33915b88c2ae701847870346b381f9cfa86c6459) - controls: disable zoom buttons when min/max is reached
- [#3060](https://github.com/wbkd/react-flow/pull/3060) [`70ec97f7`](https://github.com/wbkd/react-flow/commit/70ec97f7daec6d5401215cae3edac04aea88a3ba) - fix useNodes and useEdges bug with infinite re-renderings
- [#3064](https://github.com/wbkd/react-flow/pull/3064) [`d2d1aebc`](https://github.com/wbkd/react-flow/commit/d2d1aebc0f7fea4183406e7d1915b7fcd6995f48) - refactor useUpdateNodeInternals: only call updateNodeDimensions once
- [#3059](https://github.com/wbkd/react-flow/pull/3059) [`4374459e`](https://github.com/wbkd/react-flow/commit/4374459ef9fec797bbc0407231f09a1acacd245b) - fix useUpdateNodeInternals: update type
- Updated dependencies [[`70ec97f7`](https://github.com/wbkd/react-flow/commit/70ec97f7daec6d5401215cae3edac04aea88a3ba), [`33915b88`](https://github.com/wbkd/react-flow/commit/33915b88c2ae701847870346b381f9cfa86c6459), [`d2d1aebc`](https://github.com/wbkd/react-flow/commit/d2d1aebc0f7fea4183406e7d1915b7fcd6995f48), [`4374459e`](https://github.com/wbkd/react-flow/commit/4374459ef9fec797bbc0407231f09a1acacd245b)]:
- @reactflow/core@11.7.2
- @reactflow/controls@11.1.13
- @reactflow/background@11.2.2
- @reactflow/minimap@11.5.2
- @reactflow/node-toolbar@1.2.1
## 11.7.1
### Patch Changes
- [#3043](https://github.com/wbkd/react-flow/pull/3043) [`cf7a7d3d`](https://github.com/wbkd/react-flow/commit/cf7a7d3dad1e73215a72a5dc72e21fd50208cdbb) - handles: handles on top of each other, reduce re-renderings
- [#3046](https://github.com/wbkd/react-flow/pull/3046) [`07b975bb`](https://github.com/wbkd/react-flow/commit/07b975bbee3580249e36a19582213b250f78093c) - base-edge: pass id to base edge path
- [#3007](https://github.com/wbkd/react-flow/pull/3007) [`c80d269b`](https://github.com/wbkd/react-flow/commit/c80d269b85a0054221f4639c328fc36a3befbe70) Thanks [@bcakmakoglu](https://github.com/bcakmakoglu)! - allow array of ids as updateNodeInternals arg
- [#3029](https://github.com/wbkd/react-flow/pull/3029) [`a3fa164c`](https://github.com/wbkd/react-flow/commit/a3fa164c34cc820c79bb031c9fd97b72a3546614) Thanks [@bcakmakoglu](https://github.com/bcakmakoglu)! - autopan: only update nodes when transform change happen
- [#3052](https://github.com/wbkd/react-flow/pull/3052) [`55e05cf7`](https://github.com/wbkd/react-flow/commit/55e05cf76ae21863691153e76dbd51d1eecd2c60) Thanks [@Noam3kCH](https://github.com/Noam3kCH)! - node-toolbar: add prop to align bar at start, center or end
- Updated dependencies [[`cf7a7d3d`](https://github.com/wbkd/react-flow/commit/cf7a7d3dad1e73215a72a5dc72e21fd50208cdbb), [`07b975bb`](https://github.com/wbkd/react-flow/commit/07b975bbee3580249e36a19582213b250f78093c), [`55e05cf7`](https://github.com/wbkd/react-flow/commit/55e05cf76ae21863691153e76dbd51d1eecd2c60), [`c80d269b`](https://github.com/wbkd/react-flow/commit/c80d269b85a0054221f4639c328fc36a3befbe70), [`46526b4e`](https://github.com/wbkd/react-flow/commit/46526b4e02b83d74726701e3ba73d0be8cf80787), [`a3fa164c`](https://github.com/wbkd/react-flow/commit/a3fa164c34cc820c79bb031c9fd97b72a3546614)]:
- @reactflow/core@11.7.1
- @reactflow/node-toolbar@1.2.0
- @reactflow/controls@11.1.12
- @reactflow/background@11.2.1
- @reactflow/minimap@11.5.1
## 11.7.0
Most notable updates:
- `@reactflow/node-resizer` is now part of this package. No need to install it separately anymore.
- Handles: `isConnectableStart` and `isConnectableEnd` props to configure if you can start or end a connection at a certain handle
- Edges: `updatable` option to enable updates for specific edges
- MiniMap: `inversePan` and `zoomStep` props
- Background: `id` and `offset` props - this enables you to combine different patterns (useful if you want a graph paper like background for example)
- useNodesInitialized: options to configure if hidden nodes should be included (false by default)
Big thanks to [@Elringus](https://github.com/Elringus) and [@bcakmakoglu](https://github.com/bcakmakoglu)!
### Minor Changes
- [#2964](https://github.com/wbkd/react-flow/pull/2964) [`2fb4c2c8`](https://github.com/wbkd/react-flow/commit/2fb4c2c82343751ff536da262de74bd9080321b4) - add @reactflow/node-resizer package
- [#2960](https://github.com/wbkd/react-flow/pull/2960) Thanks [@bcakmakoglu](https://github.com/bcakmakoglu)! - edges: add `updatable` option
- [#2958](https://github.com/wbkd/react-flow/pull/2958) [`4d97a0ed`](https://github.com/wbkd/react-flow/commit/4d97a0ed168ce643fc0c99fa6b47cf1296d66065) - handles: add `isConnectableStart` and `isConnectableEnd` props
- [#2956](https://github.com/wbkd/react-flow/pull/2956) [`923a54c4`](https://github.com/wbkd/react-flow/commit/923a54c481b90954806202817ba844cfa7203a38) - add options for `useNodesInitialized`, ignore hidden nodes by default
- [#2944](https://github.com/wbkd/react-flow/pull/2944) Thanks [@Elringus](https://github.com/Elringus)! - add `inversePan` and `zoomStep` props
- [#2941](https://github.com/wbkd/react-flow/pull/2941) Thanks [@Elringus](https://github.com/Elringus)! - background: add `id` and `offset` props
### Patch Changes
- [#2926](https://github.com/wbkd/react-flow/pull/2926) Thanks [@Elringus](https://github.com/Elringus)! - fix non-passive wheel event listener violation
- [#2933](https://github.com/wbkd/react-flow/pull/2933) [`fe8cac0a`](https://github.com/wbkd/react-flow/commit/fe8cac0adb359109e0e9eafe8b9261ba354076bb) - prefix error keys with "error"
- [#2939](https://github.com/wbkd/react-flow/pull/2939) [`4a4ca171`](https://github.com/wbkd/react-flow/commit/4a4ca171955f5c8d58b23e3ad48406f1a21dc402) - add connection result to store
### Patch Changes
- Updated dependencies [[`098eee3d`](https://github.com/wbkd/react-flow/commit/098eee3d41dabc870777b081796401ff13b5a776), [`fe8cac0a`](https://github.com/wbkd/react-flow/commit/fe8cac0adb359109e0e9eafe8b9261ba354076bb), [`4a4ca171`](https://github.com/wbkd/react-flow/commit/4a4ca171955f5c8d58b23e3ad48406f1a21dc402), [`c1448c2f`](https://github.com/wbkd/react-flow/commit/c1448c2f7415dd3b4b2c54e05404c5ab24e8978d), [`923a54c4`](https://github.com/wbkd/react-flow/commit/923a54c481b90954806202817ba844cfa7203a38), [`4d97a0ed`](https://github.com/wbkd/react-flow/commit/4d97a0ed168ce643fc0c99fa6b47cf1296d66065), [`771c7a5d`](https://github.com/wbkd/react-flow/commit/771c7a5d133ce96e9f7471394c15189e0657ce01), [`c22e1c28`](https://github.com/wbkd/react-flow/commit/c22e1c28c5555a638c2a8e82c3bfc986b3965d36)]:
- @reactflow/core@11.7.0
- @reactflow/minimap@11.5.0
- @reactflow/background@11.2.0
- @reactflow/controls@11.1.11
- @reactflow/node-toolbar@1.1.11
## 11.6.1
### Patch Changes
- Always create new edge object (fixes an issue with Redux toolkit and other immutable helper libs)
## 11.6.0
This release introduces a new `isValidConnection` prop for the ReactFlow component. You no longer need to pass it to all your Handle components but can pass it once. We also added a new option for the `updateEdge` function that allows you to specify if you want to replace an id when updating it. More over the `MiniMap` got a new `nodeComponent` prop to pass a custom component for the mini map nodes.
### Minor Changes
- [#2877](https://github.com/wbkd/react-flow/pull/2877) [`b8886514`](https://github.com/wbkd/react-flow/commit/b88865140c72fa7e92a883498768000cb2cc96a7) - add `isValidConnection` prop for ReactFlow component
- [#2847](https://github.com/wbkd/react-flow/pull/2847) [`16bf89f2`](https://github.com/wbkd/react-flow/commit/16bf89f2b7bbf8449c00d0e2c07c19c3ff6d2533) Thanks [@bcakmakoglu](https://github.com/bcakmakoglu)! - Add option to enable/disable replacing edge id when using `updateEdge`
- [#2906](https://github.com/wbkd/react-flow/pull/2906) [`4a30185a`](https://github.com/wbkd/react-flow/commit/4a30185a12899691ff61259f0db84bc5494cb573) Thanks [@hayleigh-dot-dev](https://github.com/hayleigh-dot-dev)! - Minimap: add nodeComponent prop for passing custom component
### Patch Changes
- [#2895](https://github.com/wbkd/react-flow/pull/2895) [`3d5764ca`](https://github.com/wbkd/react-flow/commit/3d5764cac6548984a30cbf85899024e62fd69425) - add data-testid for controls, minimap and background
- [#2894](https://github.com/wbkd/react-flow/pull/2894) [`83fc4675`](https://github.com/wbkd/react-flow/commit/83fc467545527729633e817dbccfe59d0040da4b) - fix(nodes): blur when node gets unselected
- [#2892](https://github.com/wbkd/react-flow/pull/2892) [`5fabd272`](https://github.com/wbkd/react-flow/commit/5fabd2720f6367f75f79a45822d8f675a3b8e1cf) Thanks [@danielgek](https://github.com/danielgek) - track modifier keys on useKeypress
- [#2893](https://github.com/wbkd/react-flow/pull/2893) [`8f080bd5`](https://github.com/wbkd/react-flow/commit/8f080bd5e0e7e6c71f51eee9c9f2bc4b25182861) - fix: check if handle is connectable
- Updated dependencies [[`3d5764ca`](https://github.com/wbkd/react-flow/commit/3d5764cac6548984a30cbf85899024e62fd69425), [`4a30185a`](https://github.com/wbkd/react-flow/commit/4a30185a12899691ff61259f0db84bc5494cb573), [`83fc4675`](https://github.com/wbkd/react-flow/commit/83fc467545527729633e817dbccfe59d0040da4b), [`b1190837`](https://github.com/wbkd/react-flow/commit/b11908370bc438ca8d4179497cd4eb1f8c656798), [`5fabd272`](https://github.com/wbkd/react-flow/commit/5fabd2720f6367f75f79a45822d8f675a3b8e1cf), [`8f080bd5`](https://github.com/wbkd/react-flow/commit/8f080bd5e0e7e6c71f51eee9c9f2bc4b25182861), [`b8886514`](https://github.com/wbkd/react-flow/commit/b88865140c72fa7e92a883498768000cb2cc96a7), [`16bf89f2`](https://github.com/wbkd/react-flow/commit/16bf89f2b7bbf8449c00d0e2c07c19c3ff6d2533)]:
- @reactflow/background@11.1.9
- @reactflow/controls@11.1.9
- @reactflow/core@11.6.0
- @reactflow/minimap@11.4.0
- @reactflow/node-toolbar@1.1.9
## 11.5.6
### Patch Changes
- [#2834](https://github.com/wbkd/react-flow/pull/2834) [`23424ea6`](https://github.com/wbkd/react-flow/commit/23424ea6750f092210f83df17a00c89adb910d96) Thanks [@bcakmakoglu](https://github.com/bcakmakoglu)! - Add `nodes` to fit view options to allow fitting view only around specified set of nodes
- [#2836](https://github.com/wbkd/react-flow/pull/2836) [`959b1114`](https://github.com/wbkd/react-flow/commit/959b111448bba4686040473e46988be9e7befbe6) - Fix: connections for handles with bigger handles than connection radius
- [#2819](https://github.com/wbkd/react-flow/pull/2819) [`0d259b02`](https://github.com/wbkd/react-flow/commit/0d259b028558aab650546f3371a85f3bce45252f) Thanks [@bcakmakoglu](https://github.com/bcakmakoglu)! - Avoid triggering edge update if not using left mouse button
- [#2832](https://github.com/wbkd/react-flow/pull/2832) [`f3de9335`](https://github.com/wbkd/react-flow/commit/f3de9335af6cd96cd77dc77f24a944eef85384e5) - fitView: return type boolean
- [#2838](https://github.com/wbkd/react-flow/pull/2838) [`021f5a92`](https://github.com/wbkd/react-flow/commit/021f5a9210f47a968e50446cd2f9dae1f97880a4) - refactor: use key press handle modifier keys + input
- [#2839](https://github.com/wbkd/react-flow/pull/2839) [`72216ff6`](https://github.com/wbkd/react-flow/commit/72216ff62014acd2d73999053c72bd7aeed351f6) - fix PropsWithChildren: pass default generic for v17 types
- Updated dependencies [[`72216ff6`](https://github.com/wbkd/react-flow/commit/72216ff62014acd2d73999053c72bd7aeed351f6), [`959b1114`](https://github.com/wbkd/react-flow/commit/959b111448bba4686040473e46988be9e7befbe6), [`0d259b02`](https://github.com/wbkd/react-flow/commit/0d259b028558aab650546f3371a85f3bce45252f), [`f3de9335`](https://github.com/wbkd/react-flow/commit/f3de9335af6cd96cd77dc77f24a944eef85384e5), [`23424ea6`](https://github.com/wbkd/react-flow/commit/23424ea6750f092210f83df17a00c89adb910d96), [`021f5a92`](https://github.com/wbkd/react-flow/commit/021f5a9210f47a968e50446cd2f9dae1f97880a4)]:
- @reactflow/core@11.5.5
- @reactflow/background@11.1.8
- @reactflow/controls@11.1.8
- @reactflow/minimap@11.3.8
- @reactflow/node-toolbar@1.1.8
## 11.5.5
### Patch Changes
- [`383a074a`](https://github.com/wbkd/react-flow/commit/383a074aeae6dbec8437fa08c7c8d8240838a84e) Thanks [@bcakmakoglu](https://github.com/bcakmakoglu)! - Check if prevClosestHandle exists in onPointerUp. Fixes connections getting stuck on last handle and connecting, even when out of connectionRadius
- Updated dependencies [[`383a074a`](https://github.com/wbkd/react-flow/commit/383a074aeae6dbec8437fa08c7c8d8240838a84e)]:
- @reactflow/core@11.5.4
- @reactflow/background@11.1.7
- @reactflow/controls@11.1.7
- @reactflow/minimap@11.3.7
- @reactflow/node-toolbar@1.1.7
## 11.5.4
This release fixes some issues with the newly introduced connection radius feature. We are now not only checking the radius but the handle itself too (like in the old version). That means that you can connect to a handle that is bigger than the connection radius. We are also not snapping connections anymore when they are not valid and pass a status class to the connection line that says if the current connection is valid or not. More over we fixed a connection issue with iOS.
### Patch Changes
- [#2800](https://github.com/wbkd/react-flow/pull/2800) [`be8097ac`](https://github.com/wbkd/react-flow/commit/be8097acadca3054c3b236ce4296fc516010ef8c) - When node is not draggable, you can't move it with a selection either
- [#2803](https://github.com/wbkd/react-flow/pull/2803) [`1527795d`](https://github.com/wbkd/react-flow/commit/1527795d18c3af38c8ec7059436ea0fbf6c27bbd) - connection: add status class (valid or invalid) while in connection radius
- [#2801](https://github.com/wbkd/react-flow/pull/2801) [`3b6348a8`](https://github.com/wbkd/react-flow/commit/3b6348a8d1573afb39576327318bc172e33393c2) - fix(ios): connection error + dont snap invalid connection lines, check handle and connection radius
- Updated dependencies [[`be8097ac`](https://github.com/wbkd/react-flow/commit/be8097acadca3054c3b236ce4296fc516010ef8c), [`1527795d`](https://github.com/wbkd/react-flow/commit/1527795d18c3af38c8ec7059436ea0fbf6c27bbd), [`3b6348a8`](https://github.com/wbkd/react-flow/commit/3b6348a8d1573afb39576327318bc172e33393c2)]:
- @reactflow/core@11.5.3
- @reactflow/background@11.1.6
- @reactflow/controls@11.1.6
- @reactflow/minimap@11.3.6
- @reactflow/node-toolbar@1.1.6
## 11.5.3
### Patch Changes
- [#2792](https://github.com/wbkd/react-flow/pull/2792) [`d8c679b4`](https://github.com/wbkd/react-flow/commit/d8c679b4c90c5b57d4b51e4aaa988243d6eaff5a) - Accept React 17 types as dev dependency
- Updated dependencies [[`d8c679b4`](https://github.com/wbkd/react-flow/commit/d8c679b4c90c5b57d4b51e4aaa988243d6eaff5a)]:
- @reactflow/background@11.1.5
- @reactflow/controls@11.1.5
- @reactflow/core@11.5.2
- @reactflow/minimap@11.3.5
- @reactflow/node-toolbar@1.1.5
## 11.5.2
### Patch Changes
- [#2783](https://github.com/wbkd/react-flow/pull/2783) [`71153534`](https://github.com/wbkd/react-flow/commit/7115353418ebc7f7c81ab0e861200972bbf7dbd5) - connections: check handle below mouse before using connection radius
- Updated dependencies [[`71153534`](https://github.com/wbkd/react-flow/commit/7115353418ebc7f7c81ab0e861200972bbf7dbd5)]:
- @reactflow/core@11.5.1
- @reactflow/background@11.1.4
- @reactflow/controls@11.1.4
- @reactflow/minimap@11.3.4
- @reactflow/node-toolbar@1.1.4
## 11.5.1
### Minor Changes
- use latest node-toolbar package to prevent dependency issues
## 11.5.0
Lot's of improvements are coming with this release!
- **Connecting radius**: No need to drop a connection line on top of handle anymore. You only need to be close to the handle. That radius can be configured with the `connectionRadius` prop.
- **Auto pan**: When you drag a node, a selection or the connection line to the border of the pane, it will pan into that direction. That makes it easier to connect far away nodes for example. If you don't like it you can set `autoPnaOnNodeDrag` and `autoPanOnConnect` to false.
- **Touch devices**: It's finally possibleto connect nodes with the connection line on touch devices. In combination with the new auto pan and connection radius the overall UX is way better.
- **Errors**: We added an `onError` prop to get notified when an error like "couldn't find source handle" happens. This is useful if you want to log errors for example.
- **Node type**: We added a second param to the generic `Node` type. You can not only pass `NodeData` but also the type as a second param:
```ts
type MyCustomNode = Node<MyCustomNodeData, 'custom-node-type'>;
```
This makes it easier to work with different custom nodes and data types.
### Minor Changes
- [#2754](https://github.com/wbkd/react-flow/pull/2754) [`e96309b6`](https://github.com/wbkd/react-flow/commit/e96309b6a57b1071faeebf7b0547fef7fd418694) - Add auto pan for connecting and node dragging and `connectionRadius`
- [#2773](https://github.com/wbkd/react-flow/pull/2773) - Add `onError` prop to get notified when an error happens
### Patch Changes
- [#2763](https://github.com/wbkd/react-flow/pull/2763) [`85003b01`](https://github.com/wbkd/react-flow/commit/85003b01add71ea852bd5b0d2f1e7496050a6b52) - Connecting nodes: Enable connections on touch devices
- [#2620](https://github.com/wbkd/react-flow/pull/2620) - Thanks [RichSchulz](https://github.com/RichSchulz)! - Types: improve typing for node type
- Updated dependencies [[`e96309b6`](https://github.com/wbkd/react-flow/commit/e96309b6a57b1071faeebf7b0547fef7fd418694), [`85003b01`](https://github.com/wbkd/react-flow/commit/85003b01add71ea852bd5b0d2f1e7496050a6b52), [`4c516882`](https://github.com/wbkd/react-flow/commit/4c516882d2bbf426c1832a53ad40763cc1abef92)]:
- @reactflow/core@11.5.0
- @reactflow/background@11.1.3
- @reactflow/controls@11.1.3
- @reactflow/minimap@11.3.3
## 11.4.2
### Patch Changes
- [#2741](https://github.com/wbkd/react-flow/pull/2741) [`e2aff6c1`](https://github.com/wbkd/react-flow/commit/e2aff6c1e4ce54b57b724b2624367ee5fefd1c39) - chore(dependencies): update and cleanup
- Updated dependencies [[`e34a3072`](https://github.com/wbkd/react-flow/commit/e34a30726dc55184f59adc4f16ca5215a7c42805), [`e2aff6c1`](https://github.com/wbkd/react-flow/commit/e2aff6c1e4ce54b57b724b2624367ee5fefd1c39)]:
- @reactflow/background@11.1.2
- @reactflow/core@11.4.2
- @reactflow/minimap@11.3.2
- @reactflow/node-toolbar@1.1.2
- @reactflow/controls@11.1.2
## 11.4.1
### Patch Changes
- [#2738](https://github.com/wbkd/react-flow/pull/2738) [`82988485`](https://github.com/wbkd/react-flow/commit/82988485b730a9e32acbdae1ddcc81b33ddccaba) - fix: fitView for subflows, context menu on right mouse pan
- [#2740](https://github.com/wbkd/react-flow/pull/2740) [`d91e619a`](https://github.com/wbkd/react-flow/commit/d91e619a70a95db99a621ede59bc05b5a7766086) Thanks [@michaelspiss](https://github.com/michaelspiss)! - EdgeRenderer: check all handles for connection mode loose
- Updated dependencies [[`82988485`](https://github.com/wbkd/react-flow/commit/82988485b730a9e32acbdae1ddcc81b33ddccaba), [`d91e619a`](https://github.com/wbkd/react-flow/commit/d91e619a70a95db99a621ede59bc05b5a7766086)]:
- @reactflow/core@11.4.1
- @reactflow/background@11.1.1
- @reactflow/controls@11.1.1
- @reactflow/minimap@11.3.1
- @reactflow/node-toolbar@1.1.1
## 11.4.0
## 11.4.0
## New Features
New props for the ReactFlow component to customize the controls of the viewport and the selection box better:
1. `selectionOnDrag` prop: Selection box without extra button press (need to set `panOnDrag={false}` or `panOnDrag={[1, 2]}`)
2. `panOnDrag={[0, 1, 2]}` option to configure specific mouse buttons for panning
3. `panActivationKeyCode="Space"` key code for activating dragging (useful when using `selectionOnDrag`)
4. `selectionMode={SelectionMode.Full}`: you can chose if the selection box needs to contain a node fully (`SelectionMode.Full`) or partially (`SelectionMode.Partial`) to select it
5. `onSelectionStart` and `onSelectionEnd` events
6. `elevateNodesOnSelect`: Defines if z-index should be increased when node is selected
7. New store function `getNodes`. You can now do `store.getState().getNodes()` instead of `Array.from(store.getNodes().nodeInternals.values())`.
Thanks to @jackfishwick who helped a lot with the new panning and selection options.
### Minor Changes
- [#2678](https://github.com/wbkd/react-flow/pull/2678) [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493)
- Add new props to configure viewport controls (`selectionOnDrag`, `panActivationKeyCode`, ..)
- [#2661](https://github.com/wbkd/react-flow/pull/2661) [`7ef29108`](https://github.com/wbkd/react-flow/commit/7ef2910808aaaee029894363d52efc0c378a7654)
- panOnDrag: Use numbers for prop ([1,2] = drag via middle or right mouse button)
- selection: do not include hidden nodes
- minimap: fix onNodeClick for nodes outside the viewport
- keys: allow multi select when input is focused
### Patch Changes
- [#2695](https://github.com/wbkd/react-flow/pull/2695) [`ab2ff374`](https://github.com/wbkd/react-flow/commit/ab2ff3740618da48bd4350597e816c397f3d78ff) - Add elevateNodesOnSelect prop
- [#2660](https://github.com/wbkd/react-flow/pull/2660) [`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0) - Add `getNodes` function to the store so that you don't need to do `Array.from(store.getState().nodeInternals.values())` anymore.
- [#2659](https://github.com/wbkd/react-flow/pull/2659) [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9) - Use translateExtent correctly
- [#2657](https://github.com/wbkd/react-flow/pull/2657) [`23afb3ab`](https://github.com/wbkd/react-flow/commit/23afb3abebdb42fad284f68bec164afac609563c) - Only trigger drag event when change happened
- Updated dependencies [[`ab2ff374`](https://github.com/wbkd/react-flow/commit/ab2ff3740618da48bd4350597e816c397f3d78ff), [`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0), [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493), [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9), [`7ef29108`](https://github.com/wbkd/react-flow/commit/7ef2910808aaaee029894363d52efc0c378a7654), [`23afb3ab`](https://github.com/wbkd/react-flow/commit/23afb3abebdb42fad284f68bec164afac609563c)]:
- @reactflow/core@11.4.0
- @reactflow/minimap@11.3.0
- @reactflow/node-toolbar@1.1.0
- @reactflow/background@11.1.0
- @reactflow/controls@11.1.0
## 11.4.0-next.1
### Minor Changes
- panOnDrag: Use numbers for prop ([1,2] = drag via middle or right mouse button)
selection: do not include hidden nodes
minimap: fix onNodeClick for nodes outside the viewport
keys: allow multi select when input is focused
### Patch Changes
- Updated dependencies []:
- @reactflow/background@11.1.0-next.1
- @reactflow/controls@11.1.0-next.1
- @reactflow/core@11.4.0-next.1
- @reactflow/minimap@11.3.0-next.1
- @reactflow/node-toolbar@1.1.0-next.1
## 11.4.0-next.0
### Minor Changes
- [#2678](https://github.com/wbkd/react-flow/pull/2678) [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493) Thanks [@moklick](https://github.com/moklick)! - ## New Features
New props for the ReactFlow component to customize the controls of the viewport and the selection box better:
1. `selectionOnDrag` prop: Selection box without extra button press (need to set `panOnDrag={false} or `panOnDrag="RightClick"`)
2. `panOnDrag="RightClick"` option
3. `panActivationKeyCode="Space"` key code for activating dragging (useful when using `selectionOnDrag`)
4. `selectionMode={SelectionMode.Full}`: you can chose if the selection box needs to contain a node fully (`SelectionMode.Full`) or partially (`SelectionMode.Partial`) to select it
5. `onSelectionStart` and `onSelectionEnd` events
### Patch Changes
- [#2660](https://github.com/wbkd/react-flow/pull/2660) [`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0) Thanks [@moklick](https://github.com/moklick)! - Add `getNodes` function to the store so that you don't need to do `Array.from(store.getState().nodeInternals.values())` anymore.
- [#2659](https://github.com/wbkd/react-flow/pull/2659) [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9) Thanks [@moklick](https://github.com/moklick)! - Use translateExtent correctly
- [#2657](https://github.com/wbkd/react-flow/pull/2657) [`23afb3ab`](https://github.com/wbkd/react-flow/commit/23afb3abebdb42fad284f68bec164afac609563c) Thanks [@moklick](https://github.com/moklick)! - Only trigger drag event when change happened
- Updated dependencies [[`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0), [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493), [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9), [`23afb3ab`](https://github.com/wbkd/react-flow/commit/23afb3abebdb42fad284f68bec164afac609563c)]:
- @reactflow/core@11.4.0-next.0
- @reactflow/minimap@11.3.0-next.0
- @reactflow/node-toolbar@1.1.0-next.0
- @reactflow/background@11.0.8-next.0
- @reactflow/controls@11.0.8-next.0
## 11.3.3
In this update we did some changes so that we could implement the new [`<NodeResizer />`](https://reactflow.dev/docs/api/nodes/node-resizer/) component (not part of the `reactflow` package!) more smoothly.
### Patch Changes
- Updated dependencies [[`e6b5d90f`](https://github.com/wbkd/react-flow/commit/e6b5d90f61c8ee60e817bba232a162cae2ab3e2a), [`6ee44e07`](https://github.com/wbkd/react-flow/commit/6ee44e076eaa6908d07578a757a5187642b732ae), [`d29c401d`](https://github.com/wbkd/react-flow/commit/d29c401d598dbf2dcd5609b7adb8d029906a6f18), [`aa69c207`](https://github.com/wbkd/react-flow/commit/aa69c20765e6978f4f9c8cc63ed7110dbf6d9d9d), [`d29c401d`](https://github.com/wbkd/react-flow/commit/d29c401d598dbf2dcd5609b7adb8d029906a6f18), [`0df02f35`](https://github.com/wbkd/react-flow/commit/0df02f35f8d6c54dae36af18278feadc77acb2d6)]:
- @reactflow/core@11.3.2
- @reactflow/minimap@11.2.3
- @reactflow/node-toolbar@1.0.2
- @reactflow/background@11.0.7
- @reactflow/controls@11.0.7
## 11.3.2
### Patch Changes
- [`7ece618d`](https://github.com/wbkd/react-flow/commit/7ece618d94b76183c1ecd45b16f6ab168168351b) Thanks [@lounsbrough](https://github.com/lounsbrough)! - Fix minimap node position
- Updated dependencies [[`7ece618d`](https://github.com/wbkd/react-flow/commit/7ece618d94b76183c1ecd45b16f6ab168168351b)]:
- @reactflow/minimap@11.2.2
## 11.3.1
### Patch Changes
- [#2595](https://github.com/wbkd/react-flow/pull/2595) [`c828bfda`](https://github.com/wbkd/react-flow/commit/c828bfda0a8c4774bc43588640c7cca0cfdcb3f4) Thanks [@chrtze](https://github.com/chrtze)! - Fix and improve the behaviour when using nodeOrigin in combination with subflows
- [#2602](https://github.com/wbkd/react-flow/pull/2602) [`b0302ce4`](https://github.com/wbkd/react-flow/commit/b0302ce4261a992bee841bae84af347d03be690f) Thanks [@sdegueldre](https://github.com/sdegueldre)! - Don't use try catch in wrapper for checking if provider is available
- [#2601](https://github.com/wbkd/react-flow/pull/2601) [`b2c72813`](https://github.com/wbkd/react-flow/commit/b2c728137d1b53e38883f044fa447585c377a6af) Thanks [@hoondeveloper](https://github.com/hoondeveloper)! - fix isRectObject function
- [#2594](https://github.com/wbkd/react-flow/pull/2594) [`ec94d9ec`](https://github.com/wbkd/react-flow/commit/ec94d9ecdc964d6d66c04e9242f195614bbfdbbe) Thanks [@chrtze](https://github.com/chrtze)! - Allow multiple node ids to be passed for enabling multi selection toolbars
- Updated dependencies [[`c828bfda`](https://github.com/wbkd/react-flow/commit/c828bfda0a8c4774bc43588640c7cca0cfdcb3f4), [`b0302ce4`](https://github.com/wbkd/react-flow/commit/b0302ce4261a992bee841bae84af347d03be690f), [`b2c72813`](https://github.com/wbkd/react-flow/commit/b2c728137d1b53e38883f044fa447585c377a6af), [`ec94d9ec`](https://github.com/wbkd/react-flow/commit/ec94d9ecdc964d6d66c04e9242f195614bbfdbbe)]:
- @reactflow/core@11.3.1
- @reactflow/minimap@11.2.1
- @reactflow/node-toolbar@1.0.1
- @reactflow/background@11.0.6
- @reactflow/controls@11.0.6
## 11.3.0
### Minor Changes
- [#2562](https://github.com/wbkd/react-flow/pull/2562) [`d745aa33`](https://github.com/wbkd/react-flow/commit/d745aa33fcd1333e12929c862f9a3d6de53f7179) Thanks [@moklick](https://github.com/moklick)! - Minimap: Add `maskStrokeColor` and `maskStrokeWidth` props
- [#2563](https://github.com/wbkd/react-flow/pull/2563) [`98116d43`](https://github.com/wbkd/react-flow/commit/98116d431f9fcdcc9b23a5b606a94ec0740b64cd) Thanks [@chrtze](https://github.com/chrtze)! - Core: Add `<NodeToolbar />` component that renders a fixed element attached to a node
- [#2545](https://github.com/wbkd/react-flow/pull/2545) [`8f63f751`](https://github.com/wbkd/react-flow/commit/8f63f751e302d3c935865760d2134350c31ab93f) Thanks [@chrtze](https://github.com/chrtze)! - Minimap: Add `ariaLabel` prop to configure or remove the aria-label
### Patch Changes
- [#2561](https://github.com/wbkd/react-flow/pull/2561) [`92cf497e`](https://github.com/wbkd/react-flow/commit/92cf497eb72f21af592a53f5af9770c9f1e6d940) Thanks [@moklick](https://github.com/moklick)! - Core: Fix multi selection and fitView when nodeOrigin is used
- [#2560](https://github.com/wbkd/react-flow/pull/2560) [`a39224b3`](https://github.com/wbkd/react-flow/commit/a39224b3a80afbdb83fc4490dd5f4f2be23cd4dd) Thanks [@neo](https://github.com/neo)! - Core: Always elevate zIndex when node is selected
- [#2573](https://github.com/wbkd/react-flow/pull/2573) [`5e8b67dd`](https://github.com/wbkd/react-flow/commit/5e8b67dd41f9bb60dcd7f5d14cc34b42c970e967) Thanks [@moklick](https://github.com/moklick)! - Core: Fix disappearing connection line for loose flows
- [#2558](https://github.com/wbkd/react-flow/pull/2558) [`2a1c7db6`](https://github.com/wbkd/react-flow/commit/2a1c7db6b27ac0f4f81dcef2d593f4753c4321c7) Thanks [@moklick](https://github.com/moklick)! - Core: Handle multiple instances on a page for EdgeLabelRenderer
- Updated dependencies [[`d745aa33`](https://github.com/wbkd/react-flow/commit/d745aa33fcd1333e12929c862f9a3d6de53f7179), [`92cf497e`](https://github.com/wbkd/react-flow/commit/92cf497eb72f21af592a53f5af9770c9f1e6d940), [`98116d43`](https://github.com/wbkd/react-flow/commit/98116d431f9fcdcc9b23a5b606a94ec0740b64cd), [`8f63f751`](https://github.com/wbkd/react-flow/commit/8f63f751e302d3c935865760d2134350c31ab93f), [`a39224b3`](https://github.com/wbkd/react-flow/commit/a39224b3a80afbdb83fc4490dd5f4f2be23cd4dd), [`5e8b67dd`](https://github.com/wbkd/react-flow/commit/5e8b67dd41f9bb60dcd7f5d14cc34b42c970e967), [`2a1c7db6`](https://github.com/wbkd/react-flow/commit/2a1c7db6b27ac0f4f81dcef2d593f4753c4321c7), [`c793433c`](https://github.com/wbkd/react-flow/commit/c793433cafc214281ae97c9a32f5ac2fe453c34f)]:
- @reactflow/minimap@11.2.0
- @reactflow/core@11.3.0
- @reactflow/node-toolbar@1.0.0
- @reactflow/background@11.0.5
- @reactflow/controls@11.0.5
## 11.2.0
### Minor Changes
- [#2535](https://github.com/wbkd/react-flow/pull/2535) [`7902a3ce`](https://github.com/wbkd/react-flow/commit/7902a3ce3188426d5cd07cf0943a68f679e67948) Thanks [@moklick](https://github.com/moklick)! - Feat: Add edge label renderer
- [#2536](https://github.com/wbkd/react-flow/pull/2536) [`b25d499e`](https://github.com/wbkd/react-flow/commit/b25d499ec05b5c6f21ac552d03650eb37433552e) Thanks [@pengfu](https://github.com/pengfu)! - Feat: add deleteElements helper function
- [#2539](https://github.com/wbkd/react-flow/pull/2539) [`4fc1253e`](https://github.com/wbkd/react-flow/commit/4fc1253eadf9b7dd392d8dc2348f44fa8d08f931) Thanks [@moklick](https://github.com/moklick)! - Feat: add intersection helpers
- [#2530](https://github.com/wbkd/react-flow/pull/2530) [`8ba4dd5d`](https://github.com/wbkd/react-flow/commit/8ba4dd5d1d4b2e6f107c148de62aec0b688d8b21) Thanks [@moklick](https://github.com/moklick)! - Feat: Add pan and zoom to mini map
### Patch Changes
- [#2538](https://github.com/wbkd/react-flow/pull/2538) [`740659c0`](https://github.com/wbkd/react-flow/commit/740659c0e788c7572d4a1e64e1d33d60712233fc) Thanks [@neo](https://github.com/neo)! - Refactor: put React Flow in isolated stacking context
- Updated dependencies [[`740659c0`](https://github.com/wbkd/react-flow/commit/740659c0e788c7572d4a1e64e1d33d60712233fc), [`7902a3ce`](https://github.com/wbkd/react-flow/commit/7902a3ce3188426d5cd07cf0943a68f679e67948), [`b25d499e`](https://github.com/wbkd/react-flow/commit/b25d499ec05b5c6f21ac552d03650eb37433552e), [`4fc1253e`](https://github.com/wbkd/react-flow/commit/4fc1253eadf9b7dd392d8dc2348f44fa8d08f931), [`8ba4dd5d`](https://github.com/wbkd/react-flow/commit/8ba4dd5d1d4b2e6f107c148de62aec0b688d8b21)]:
- @reactflow/core@11.2.0
- @reactflow/minimap@11.1.0
- @reactflow/background@11.0.4
- @reactflow/controls@11.0.4
## 11.1.2
Housekeeping release with some fixes and some cleanups for the types.
### Patch Changes
- make pro options acc type optional
- cleanup types
- fix rf id handling
- always render nodes when dragging=true
- don't apply animations to helper edge
- Updated dependencies:
- @reactflow/core@11.1.2
- @reactflow/background@11.0.3
- @reactflow/controls@11.0.3
- @reactflow/minimap@11.0.3
## 11.1.1
### Patch Changes
- [`c44413d`](https://github.com/wbkd/react-flow/commit/c44413d816604ae2d6ad81ed227c3dfde1a7bd8a) Thanks [@moklick](https://github.com/moklick)! - chore(panel): dont break user selection above panel
- [`48c402c`](https://github.com/wbkd/react-flow/commit/48c402c4d3bd9e16dc91cd4c549324e57b6d5c57) Thanks [@moklick](https://github.com/moklick)! - refactor(aria-descriptions): render when disableKeyboardA11y is true
- [`3a1a365`](https://github.com/wbkd/react-flow/commit/3a1a365a63fc4564d9a8d96309908986fcc86f95) Thanks [@moklick](https://github.com/moklick)! - fix(useOnSelectionChange): repair hook closes #2484
- [`5d35094`](https://github.com/wbkd/react-flow/commit/5d350942d33ded626b3387206f0b0dee368efdfb) Thanks [@neo](https://github.com/neo)! - Add css files as sideEffects
- Updated dependencies:
- @reactflow/background@11.0.2
- @reactflow/core@11.1.1
- @reactflow/controls@11.0.2
- @reactflow/minimap@11.0.2
## 11.1.0
### Minor Changes
- [`def11008`](https://github.com/wbkd/react-flow/commit/def11008d88749fec40e6fcba8bc41eea2511bab) Thanks [@moklick](https://github.com/moklick)! - New props: nodesFocusable and edgesFocusable
### Patch Changes
- [`d00faa6b`](https://github.com/wbkd/react-flow/commit/d00faa6b3e77388bfd655d4c02e9a5375bc515e4) Thanks [@moklick](https://github.com/moklick)! - Make nopan class name overwritable with class name option
- Updated dependencies [[`def11008`](https://github.com/wbkd/react-flow/commit/def11008d88749fec40e6fcba8bc41eea2511bab), [`def11008`](https://github.com/wbkd/react-flow/commit/def11008d88749fec40e6fcba8bc41eea2511bab), [`d00faa6b`](https://github.com/wbkd/react-flow/commit/d00faa6b3e77388bfd655d4c02e9a5375bc515e4)]:
- @reactflow/background@11.0.1
- @reactflow/core@11.1.0
- @reactflow/controls@11.0.1
- @reactflow/minimap@11.0.1
## 11.0.0
Finally it's here! A new version that comes with lots of improvements and the new package name `reactflow`.
From now on you can install it via `npm install reactflow`.
## Major Changes
- Importing CSS via `reactflow/dist/style.css` is mandatory
- **Better [Accessibility](/docs/guides/accessibility)**
- Nodes and edges are focusable, selectable, moveable and deleteable with the keyboard.
- `aria-` default attributes for all elements and controllable via `ariaLabel` options
- Keyboard controls can be disabled with the new `disableKeyboardA11y` prop
- **Better selectable edges** via new edge option: `interactionWidth` - renders invisible edge that makes it easier to interact
- **Better routing for smoothstep and step edges**: https://twitter.com/reactflowdev/status/1567535405284614145
- **Nicer edge updating behaviour**: https://twitter.com/reactflowdev/status/1564966917517021184
- **Node origin**: The new `nodeOrigin` prop lets you control the origin of a node. Useful for layouting.
- **New background pattern**: `BackgroundVariant.Cross` variant
- **[`useOnViewportChange`](/docs/api/hooks/use-on-viewport-change) hook** - handle viewport changes within a component
- **[`useOnSelectionChange`](/docs/api/hooks/use-on-selection-change) hook** - handle selection changes within a component
- **[`useNodesInitialized`](/docs/api/hooks/use-nodes-initialized) hook** - returns true if all nodes are initialized and if there is more than one node
- **Deletable option** for Nodes and edges
- **New Event handlers**: `onPaneMouseEnter`, `onPaneMouseMove` and `onPaneMouseLeave`
- **Edge `pathOptions`** for `smoothstep` and `default` edges
- **Nicer cursor defaults**: Cursor is grabbing, while dragging a node or panning
- **Pane moveable** with middle mouse button
- **Pan over nodes** when they are not draggable (`draggable=false` or `nodesDraggable` false)
- **[`<BaseEdge />`](/docs/api/edges/base-edge) component** that makes it easier to build custom edges
- **[Separately installable packages](/docs/overview/packages/)**
- @reactflow/core
- @reactflow/background
- @reactflow/controls
- @reactflow/minimap
### Patch Changes
- Updated dependencies:
- @reactflow/background@11.0.0
- @reactflow/controls@11.0.0
- @reactflow/core@11.0.0
- @reactflow/minimap@11.0.0
<file_sep>{
"extends": "@reactflow/tsconfig/react.json",
"display": "@reactflow/minimap",
"include": ["**/*.ts", "**/*.tsx"],
"exclude": ["node_modules", "dist"]
}
<file_sep>import type { CSSProperties, ReactNode } from 'react';
import type { D3DragEvent, SubjectPosition } from 'd3-drag';
export type ResizeParams = {
x: number;
y: number;
width: number;
height: number;
};
export type ResizeParamsWithDirection = ResizeParams & {
direction: number[];
};
type OnResizeHandler<Params = ResizeParams, Result = void> = (event: ResizeDragEvent, params: Params) => Result;
export type ShouldResize = OnResizeHandler<ResizeParamsWithDirection, boolean>;
export type OnResizeStart = OnResizeHandler;
export type OnResize = OnResizeHandler<ResizeParamsWithDirection>;
export type OnResizeEnd = OnResizeHandler;
export type NodeResizerProps = {
nodeId?: string;
color?: string;
handleClassName?: string;
handleStyle?: CSSProperties;
lineClassName?: string;
lineStyle?: CSSProperties;
isVisible?: boolean;
minWidth?: number;
minHeight?: number;
maxWidth?: number;
maxHeight?: number;
keepAspectRatio?: boolean;
shouldResize?: ShouldResize;
onResizeStart?: OnResizeStart;
onResize?: OnResize;
onResizeEnd?: OnResizeEnd;
};
export type ControlLinePosition = 'top' | 'bottom' | 'left' | 'right';
export type ControlPosition = ControlLinePosition | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';
export enum ResizeControlVariant {
Line = 'line',
Handle = 'handle',
}
export type ResizeControlProps = Pick<
NodeResizerProps,
| 'nodeId'
| 'color'
| 'minWidth'
| 'minHeight'
| 'maxWidth'
| 'maxHeight'
| 'keepAspectRatio'
| 'shouldResize'
| 'onResizeStart'
| 'onResize'
| 'onResizeEnd'
> & {
position?: ControlPosition;
variant?: ResizeControlVariant;
className?: string;
style?: CSSProperties;
children?: ReactNode;
};
export type ResizeControlLineProps = ResizeControlProps & {
position?: ControlLinePosition;
};
export type ResizeDragEvent = D3DragEvent<HTMLDivElement, null, SubjectPosition>;
<file_sep>describe('Basic Flow Rendering', () => {
before(() => {
cy.visit('/');
});
it('renders a flow with three nodes', () => {
cy.get('.react-flow__renderer');
cy.get('.react-flow-basic-example'); // check if className prop works
cy.get('.react-flow__node').should('have.length', 4);
cy.get('.react-flow__edge').should('have.length', 2);
cy.get('.react-flow__node').children('.react-flow__handle');
});
it('renders a grid', () => {
cy.get('.react-flow__background');
});
it('selects two nodes by clicks', () => {
cy.get('body').type('{cmd}', { release: false });
cy.get('.react-flow__node:first')
.click()
.should('have.class', 'selected')
.get('.react-flow__node:last')
.click()
.should('have.class', 'selected')
.get('.react-flow__node:first')
.should('have.class', 'selected');
cy.get('body').type('{cmd}', { release: true });
});
it('selects a node by click', () => {
cy.get('.react-flow__node:first').click({ force: true }).should('have.class', 'selected');
});
it('deselects node', () => {
cy.get('.react-flow__renderer').click('bottomLeft');
cy.get('.react-flow__node:first').should('not.have.class', 'selected');
});
it('selects an edge by click', () => {
cy.get('.react-flow__edge:first').click({ force: true }).should('have.class', 'selected');
});
it('deselects edge', () => {
cy.get('.react-flow__renderer').click('bottomLeft');
cy.get('.react-flow__edge:first').should('not.have.class', 'selected');
});
it('selects one node with a selection', () => {
cy.get('body')
.type('{shift}', { release: false })
.wait(50)
.get('.react-flow__pane')
.trigger('mousedown', 1, 10, { button: 0, force: true })
.trigger('mousemove', 1000, 450, { button: 0 })
.wait(50)
.trigger('mouseup', 1000, 450, { button: 0, force: true });
cy.wait(200);
cy.get('.react-flow__node').eq(1).should('have.class', 'selected');
cy.get('.react-flow__node').eq(3).should('have.not.class', 'selected');
cy.get('.react-flow__nodesselection-rect');
cy.get('body').type('{shift}', { release: true, force: true });
});
it('selects all nodes', () => {
cy.get('body')
.type('{shift}', { release: false })
.get('.react-flow__pane')
.trigger('mousedown', 'topRight', { button: 0, force: true })
.trigger('mousemove', 'bottomLeft', { button: 0 })
.wait(50)
.trigger('mouseup', 'bottomLeft', { button: 0, force: true })
.wait(400)
.get('.react-flow__node')
.should('have.class', 'selected');
cy.wait(200);
cy.get('.react-flow__nodesselection-rect');
cy.get('body').type('{shift}', { release: true });
});
it('removes selection', () => {
cy.get('.react-flow__renderer').click('bottomLeft');
cy.get('.react-flow__nodesselection-rect').should('not.exist');
});
it('selects an edge', () => {
cy.get('.react-flow__edge:first').click({ force: true }).should('have.class', 'selected');
});
it('drags a node', () => {
const styleBeforeDrag = Cypress.$('.react-flow__node:first').css('transform');
cy.drag('.react-flow__node:first', { x: 500, y: 25 }).then(($el: any) => {
const styleAfterDrag = $el.css('transform');
expect(styleBeforeDrag).to.not.equal(styleAfterDrag);
});
});
// @TODO: why does this fail since react18?
// it('removes a node', () => {
// cy.get('.react-flow__node').contains('Node 1').click().should('have.class', 'selected');
// cy.get('html').type('{backspace}').wait(100);
// cy.get('.react-flow__node').should('have.length', 3);
// cy.get('.react-flow__edge').should('have.length', 1);
// });
it('connects nodes', () => {
cy.get('.react-flow__node')
.contains('Node 3')
.find('.react-flow__handle.source')
.trigger('mousedown', { force: true, button: 0 });
cy.get('.react-flow__node')
.contains('Node 4')
.find('.react-flow__handle.target')
.trigger('mousemove', { force: true, button: 0 })
.wait(200)
.trigger('mouseup', { force: true, button: 0 });
cy.get('.react-flow__edge').should('have.length', 3);
});
// @TODO: why does this fail since react18?
// it('removes an edge', () => {
// cy.get('.react-flow__edge:first').click();
// cy.get('body').type('{backspace}');
// cy.get('.react-flow__edge').should('have.length', 1);
// });
it('drags the pane', () => {
const styleBeforeDrag = Cypress.$('.react-flow__viewport').css('transform');
// for d3 we have to pass the window to the event
// https://github.com/cypress-io/cypress/issues/3441
cy.window().then((win) => {
cy.get('.react-flow__pane')
.trigger('mousedown', 'topLeft', { button: 0, view: win })
.trigger('mousemove', 'bottomLeft')
.wait(50)
.trigger('mouseup', { force: true, view: win })
.then(() => {
const styleAfterDrag = Cypress.$('.react-flow__viewport').css('transform');
expect(styleBeforeDrag).to.not.equal(styleAfterDrag);
});
});
});
it('zooms the pane', () => {
const styleBeforeZoom = Cypress.$('.react-flow__viewport').css('transform');
cy.get('.react-flow__pane')
.trigger('wheel', 'topLeft', { deltaY: -200 })
.wait(50)
.then(() => {
const styleAfterZoom = Cypress.$('.react-flow__viewport').css('transform');
expect(styleBeforeZoom).to.not.equal(styleAfterZoom);
});
});
});
export {};
<file_sep>import { MouseEvent, RefObject } from 'react';
import { StoreApi } from 'zustand';
import { getDimensions } from '../../utils';
import { Position } from '../../types';
import type { HandleElement, Node, NodeOrigin, ReactFlowState } from '../../types';
export const getHandleBounds = (
selector: string,
nodeElement: HTMLDivElement,
zoom: number,
nodeOrigin: NodeOrigin
): HandleElement[] | null => {
const handles = nodeElement.querySelectorAll(selector);
if (!handles || !handles.length) {
return null;
}
const handlesArray = Array.from(handles) as HTMLDivElement[];
const nodeBounds = nodeElement.getBoundingClientRect();
const nodeOffset = {
x: nodeBounds.width * nodeOrigin[0],
y: nodeBounds.height * nodeOrigin[1],
};
return handlesArray.map((handle): HandleElement => {
const handleBounds = handle.getBoundingClientRect();
return {
id: handle.getAttribute('data-handleid'),
position: handle.getAttribute('data-handlepos') as unknown as Position,
x: (handleBounds.left - nodeBounds.left - nodeOffset.x) / zoom,
y: (handleBounds.top - nodeBounds.top - nodeOffset.y) / zoom,
...getDimensions(handle),
};
});
};
export function getMouseHandler(
id: string,
getState: StoreApi<ReactFlowState>['getState'],
handler?: (event: MouseEvent, node: Node) => void
) {
return handler === undefined
? handler
: (event: MouseEvent) => {
const node = getState().nodeInternals.get(id)!;
handler(event, { ...node });
};
}
// this handler is called by
// 1. the click handler when node is not draggable or selectNodesOnDrag = false
// or
// 2. the on drag start handler when node is draggable and selectNodesOnDrag = true
export function handleNodeClick({
id,
store,
unselect = false,
nodeRef,
}: {
id: string;
store: {
getState: StoreApi<ReactFlowState>['getState'];
setState: StoreApi<ReactFlowState>['setState'];
};
unselect?: boolean;
nodeRef?: RefObject<HTMLDivElement>;
}) {
const { addSelectedNodes, unselectNodesAndEdges, multiSelectionActive, nodeInternals } = store.getState();
const node = nodeInternals.get(id)!;
store.setState({ nodesSelectionActive: false });
if (!node.selected) {
addSelectedNodes([id]);
} else if (unselect || (node.selected && multiSelectionActive)) {
unselectNodesAndEdges({ nodes: [node] });
requestAnimationFrame(() => nodeRef?.current?.blur());
}
}
<file_sep>import { Node, Edge, XYPosition, MarkerType } from 'reactflow';
const position: XYPosition = { x: 0, y: 0 };
const nodes: Node[] = [
{
id: '1',
type: 'input',
data: { label: 'input' },
position,
},
{
id: '2',
data: { label: 'node 2' },
position,
},
{
id: '2a',
data: { label: 'node 2a' },
position,
},
{
id: '2b',
data: { label: 'node 2b' },
position,
},
{
id: '2c',
data: { label: 'node 2c' },
position,
},
{
id: '2d',
data: { label: 'node 2d' },
position,
},
{
id: '3',
data: { label: 'node 3' },
position,
},
{
id: '4',
data: { label: 'node 4' },
position,
},
{
id: '5',
data: { label: 'node 5' },
position,
},
{
id: '6',
type: 'output',
data: { label: 'output' },
position,
},
{
id: '7',
type: 'output',
data: { label: 'output' },
position: { x: 400, y: 450 },
},
];
const edges: Edge[] = [
{
id: 'e12',
source: '1',
target: '2',
type: 'smoothstep',
markerEnd: { type: MarkerType.Arrow },
},
{
id: 'e13',
source: '1',
target: '3',
type: 'smoothstep',
markerEnd: { type: MarkerType.Arrow },
},
{
id: 'e22a',
source: '2',
target: '2a',
type: 'smoothstep',
markerEnd: { type: MarkerType.Arrow },
},
{
id: 'e22b',
source: '2',
target: '2b',
type: 'smoothstep',
markerEnd: { type: MarkerType.Arrow },
},
{
id: 'e22c',
source: '2',
target: '2c',
type: 'smoothstep',
markerEnd: { type: MarkerType.Arrow },
},
{
id: 'e2c2d',
source: '2c',
target: '2d',
type: 'smoothstep',
markerEnd: { type: MarkerType.Arrow },
},
{
id: 'e45',
source: '4',
target: '5',
type: 'smoothstep',
markerEnd: { type: MarkerType.Arrow },
},
{
id: 'e56',
source: '5',
target: '6',
type: 'smoothstep',
markerEnd: { type: MarkerType.Arrow },
},
{
id: 'e57',
source: '5',
target: '7',
type: 'smoothstep',
markerEnd: { type: MarkerType.Arrow },
},
];
const nodesAndEdges = { nodes, edges };
export default nodesAndEdges;
<file_sep>/* eslint-disable @typescript-eslint/no-explicit-any */
import type { Node, Edge, EdgeChange, NodeChange } from '../types';
function handleParentExpand(res: any[], updateItem: any) {
const parent = res.find((e) => e.id === updateItem.parentNode);
if (parent) {
const extendWidth = updateItem.position.x + updateItem.width - parent.width;
const extendHeight = updateItem.position.y + updateItem.height - parent.height;
if (extendWidth > 0 || extendHeight > 0 || updateItem.position.x < 0 || updateItem.position.y < 0) {
parent.style = { ...parent.style } || {};
parent.style.width = parent.style.width ?? parent.width;
parent.style.height = parent.style.height ?? parent.height;
if (extendWidth > 0) {
parent.style.width += extendWidth;
}
if (extendHeight > 0) {
parent.style.height += extendHeight;
}
if (updateItem.position.x < 0) {
const xDiff = Math.abs(updateItem.position.x);
parent.position.x = parent.position.x - xDiff;
parent.style.width += xDiff;
updateItem.position.x = 0;
}
if (updateItem.position.y < 0) {
const yDiff = Math.abs(updateItem.position.y);
parent.position.y = parent.position.y - yDiff;
parent.style.height += yDiff;
updateItem.position.y = 0;
}
parent.width = parent.style.width;
parent.height = parent.style.height;
}
}
}
function applyChanges(changes: any[], elements: any[]): any[] {
// we need this hack to handle the setNodes and setEdges function of the useReactFlow hook for controlled flows
if (changes.some((c) => c.type === 'reset')) {
return changes.filter((c) => c.type === 'reset').map((c) => c.item);
}
const initElements: any[] = changes.filter((c) => c.type === 'add').map((c) => c.item);
return elements.reduce((res: any[], item: any) => {
const currentChanges = changes.filter((c) => c.id === item.id);
if (currentChanges.length === 0) {
res.push(item);
return res;
}
const updateItem = { ...item };
for (const currentChange of currentChanges) {
if (currentChange) {
switch (currentChange.type) {
case 'select': {
updateItem.selected = currentChange.selected;
break;
}
case 'position': {
if (typeof currentChange.position !== 'undefined') {
updateItem.position = currentChange.position;
}
if (typeof currentChange.positionAbsolute !== 'undefined') {
updateItem.positionAbsolute = currentChange.positionAbsolute;
}
if (typeof currentChange.dragging !== 'undefined') {
updateItem.dragging = currentChange.dragging;
}
if (updateItem.expandParent) {
handleParentExpand(res, updateItem);
}
break;
}
case 'dimensions': {
if (typeof currentChange.dimensions !== 'undefined') {
updateItem.width = currentChange.dimensions.width;
updateItem.height = currentChange.dimensions.height;
}
if (typeof currentChange.updateStyle !== 'undefined') {
updateItem.style = { ...(updateItem.style || {}), ...currentChange.dimensions };
}
if (typeof currentChange.resizing === 'boolean') {
updateItem.resizing = currentChange.resizing;
}
if (updateItem.expandParent) {
handleParentExpand(res, updateItem);
}
break;
}
case 'remove': {
return res;
}
}
}
}
res.push(updateItem);
return res;
}, initElements);
}
export function applyNodeChanges<NodeData = any>(changes: NodeChange[], nodes: Node<NodeData>[]): Node<NodeData>[] {
return applyChanges(changes, nodes) as Node<NodeData>[];
}
export function applyEdgeChanges<EdgeData = any>(changes: EdgeChange[], edges: Edge<EdgeData>[]): Edge<EdgeData>[] {
return applyChanges(changes, edges) as Edge<EdgeData>[];
}
export const createSelectionChange = (id: string, selected: boolean) => ({
id,
type: 'select',
selected,
});
export function getSelectionChanges(items: any[], selectedIds: string[]) {
return items.reduce((res, item) => {
const willBeSelected = selectedIds.includes(item.id);
if (!item.selected && willBeSelected) {
item.selected = true;
res.push(createSelectionChange(item.id, true));
} else if (item.selected && !willBeSelected) {
item.selected = false;
res.push(createSelectionChange(item.id, false));
}
return res;
}, []);
}
<file_sep>import { Edge, Node } from 'reactflow';
export const initialNodes: Node[] = [
{
id: '1',
type: 'input',
data: { label: 'Node 1' },
position: { x: 250, y: 5 },
className: 'light',
},
{
id: '2',
data: { label: 'Node 2' },
position: { x: 100, y: 100 },
className: 'light',
},
{
id: '3',
data: { label: 'Node 3' },
position: { x: 400, y: 100 },
className: 'light',
},
{
id: '4',
data: { label: 'Node 4' },
position: { x: 400, y: 200 },
className: 'light',
},
];
export const initialEdges: Edge[] = [
{ id: 'e1-2', source: '1', target: '2', animated: true },
{ id: 'e1-3', source: '1', target: '3' },
];
<file_sep>import { Node, Edge } from 'reactflow';
type ElementsCollection = {
nodes: Node[];
edges: Edge[];
};
export function getNodesAndEdges(xElements = 10, yElements = 10): ElementsCollection {
const initialNodes = [];
const initialEdges: Edge[] = [];
let nodeId = 1;
let recentNodeId = null;
for (let y = 0; y < yElements; y++) {
for (let x = 0; x < xElements; x++) {
const position = { x: x * 100, y: y * 50 };
const data = { label: `Node ${nodeId}` };
const node = {
id: nodeId.toString(),
style: { width: 50, fontSize: 11 },
data,
position,
};
initialNodes.push(node);
if (recentNodeId && nodeId <= xElements * yElements) {
initialEdges.push({
id: `${x}-${y}`,
source: recentNodeId.toString(),
target: nodeId.toString(),
});
}
recentNodeId = nodeId;
nodeId++;
}
}
return {
nodes: initialNodes,
edges: initialEdges,
};
}
<file_sep>import { useContext, useMemo } from 'react';
import { useStore as useZustandStore } from 'zustand';
import type { StoreApi } from 'zustand';
import StoreContext from '../contexts/RFStoreContext';
import { errorMessages } from '../contants';
import type { ReactFlowState } from '../types';
const zustandErrorMessage = errorMessages['error001']();
type ExtractState = StoreApi<ReactFlowState> extends { getState: () => infer T } ? T : never;
function useStore<StateSlice = ExtractState>(
selector: (state: ReactFlowState) => StateSlice,
equalityFn?: (a: StateSlice, b: StateSlice) => boolean
) {
const store = useContext(StoreContext);
if (store === null) {
throw new Error(zustandErrorMessage);
}
return useZustandStore(store, selector, equalityFn);
}
const useStoreApi = () => {
const store = useContext(StoreContext);
if (store === null) {
throw new Error(zustandErrorMessage);
}
return useMemo(
() => ({
getState: store.getState,
setState: store.setState,
subscribe: store.subscribe,
destroy: store.destroy,
}),
[store]
);
};
export { useStore, useStoreApi };
<file_sep>export { default as SimpleBezierEdge } from './SimpleBezierEdge';
export { default as SmoothStepEdge } from './SmoothStepEdge';
export { default as StepEdge } from './StepEdge';
export { default as StraightEdge } from './StraightEdge';
export { default as BezierEdge } from './BezierEdge';
<file_sep>export * from '@reactflow/core';
export * from '@reactflow/minimap';
export * from '@reactflow/controls';
export * from '@reactflow/background';
export * from '@reactflow/node-toolbar';
export * from '@reactflow/node-resizer';
export { ReactFlow as default } from '@reactflow/core';
<file_sep>describe('DragHandle Flow Rendering', () => {
before(() => {
cy.visit('/DragHandle');
});
it('renders a flow with a node', () => {
cy.get('.react-flow__renderer');
cy.get('.react-flow__node').should('have.length', 1);
});
it('tries to drag a node', () => {
const $nodeElement = Cypress.$('.react-flow__node:first');
const styleBeforeDrag = $nodeElement.css('transform');
cy.drag('.react-flow__node:first', { x: 500, y: 500 }).then(() => {
const styleAfterDrag = $nodeElement.css('transform');
expect(styleBeforeDrag).to.be.equal(styleAfterDrag);
});
});
it('drags a node', () => {
const $nodeElement = Cypress.$('.react-flow__node:first');
const styleBeforeDrag = $nodeElement.css('transform');
cy.drag('.custom-drag-handle:first', { x: 500, y: 500 }).then(() => {
const styleAfterDrag = $nodeElement.css('transform');
expect(styleBeforeDrag).to.not.equal(styleAfterDrag);
});
});
});
export {};
<file_sep># @reactflow/controls
Controls component for React Flow.
## Installation
```sh
npm install @reactflow/controls
```
<file_sep>import type { ButtonHTMLAttributes, HTMLAttributes } from 'react';
import type { FitViewOptions, PanelPosition } from '@reactflow/core';
export type ControlProps = HTMLAttributes<HTMLDivElement> & {
showZoom?: boolean;
showFitView?: boolean;
showInteractive?: boolean;
fitViewOptions?: FitViewOptions;
onZoomIn?: () => void;
onZoomOut?: () => void;
onFitView?: () => void;
onInteractiveChange?: (interactiveStatus: boolean) => void;
position?: PanelPosition;
};
export type ControlButtonProps = ButtonHTMLAttributes<HTMLButtonElement>;
<file_sep># @reactflow/node-toolbar
## 1.2.3
### Patch Changes
- Updated dependencies [[`1941c561`](https://github.com/wbkd/react-flow/commit/1941c561c9eab937c0a01747c6d188ec8c6a1bf8), [`c8b607dc`](https://github.com/wbkd/react-flow/commit/c8b607dcddeaf80912b756b0ce8045f7974e4657)]:
- @reactflow/core@11.7.4
## 1.2.2
### Patch Changes
- Updated dependencies [[`52dbac5a`](https://github.com/wbkd/react-flow/commit/52dbac5a56c092504256f947df7a959eb07385c6), [`3a277cb1`](https://github.com/wbkd/react-flow/commit/3a277cb123a886af093cee694c289c7e139c79ef)]:
- @reactflow/core@11.7.3
## 1.2.1
### Patch Changes
- Updated dependencies [[`70ec97f7`](https://github.com/wbkd/react-flow/commit/70ec97f7daec6d5401215cae3edac04aea88a3ba), [`d2d1aebc`](https://github.com/wbkd/react-flow/commit/d2d1aebc0f7fea4183406e7d1915b7fcd6995f48), [`4374459e`](https://github.com/wbkd/react-flow/commit/4374459ef9fec797bbc0407231f09a1acacd245b)]:
- @reactflow/core@11.7.2
## 1.2.0
### Minor Changes
- [#3052](https://github.com/wbkd/react-flow/pull/3052) [`55e05cf7`](https://github.com/wbkd/react-flow/commit/55e05cf76ae21863691153e76dbd51d1eecd2c60) Thanks [@Noam3kCH](https://github.com/Noam3kCH)! - feat(align): add prop to align bar at start, center or end
### Patch Changes
- Updated dependencies [[`cf7a7d3d`](https://github.com/wbkd/react-flow/commit/cf7a7d3dad1e73215a72a5dc72e21fd50208cdbb), [`07b975bb`](https://github.com/wbkd/react-flow/commit/07b975bbee3580249e36a19582213b250f78093c), [`c80d269b`](https://github.com/wbkd/react-flow/commit/c80d269b85a0054221f4639c328fc36a3befbe70), [`a3fa164c`](https://github.com/wbkd/react-flow/commit/a3fa164c34cc820c79bb031c9fd97b72a3546614)]:
- @reactflow/core@11.7.1
## 1.1.11
### Patch Changes
- Updated dependencies [[`098eee3d`](https://github.com/wbkd/react-flow/commit/098eee3d41dabc870777b081796401ff13b5a776), [`fe8cac0a`](https://github.com/wbkd/react-flow/commit/fe8cac0adb359109e0e9eafe8b9261ba354076bb), [`4a4ca171`](https://github.com/wbkd/react-flow/commit/4a4ca171955f5c8d58b23e3ad48406f1a21dc402), [`923a54c4`](https://github.com/wbkd/react-flow/commit/923a54c481b90954806202817ba844cfa7203a38), [`4d97a0ed`](https://github.com/wbkd/react-flow/commit/4d97a0ed168ce643fc0c99fa6b47cf1296d66065), [`c22e1c28`](https://github.com/wbkd/react-flow/commit/c22e1c28c5555a638c2a8e82c3bfc986b3965d36)]:
- @reactflow/core@11.7.0
## 1.1.10
### Patch Changes
- Updated dependencies
## 1.1.9
### Patch Changes
- Updated dependencies [[`3d5764ca`](https://github.com/wbkd/react-flow/commit/3d5764cac6548984a30cbf85899024e62fd69425), [`83fc4675`](https://github.com/wbkd/react-flow/commit/83fc467545527729633e817dbccfe59d0040da4b), [`b1190837`](https://github.com/wbkd/react-flow/commit/b11908370bc438ca8d4179497cd4eb1f8c656798), [`5fabd272`](https://github.com/wbkd/react-flow/commit/5fabd2720f6367f75f79a45822d8f675a3b8e1cf), [`8f080bd5`](https://github.com/wbkd/react-flow/commit/8f080bd5e0e7e6c71f51eee9c9f2bc4b25182861), [`b8886514`](https://github.com/wbkd/react-flow/commit/b88865140c72fa7e92a883498768000cb2cc96a7), [`16bf89f2`](https://github.com/wbkd/react-flow/commit/16bf89f2b7bbf8449c00d0e2c07c19c3ff6d2533)]:
- @reactflow/core@11.6.0
## 1.1.8
### Patch Changes
- Updated dependencies [[`72216ff6`](https://github.com/wbkd/react-flow/commit/72216ff62014acd2d73999053c72bd7aeed351f6), [`959b1114`](https://github.com/wbkd/react-flow/commit/959b111448bba4686040473e46988be9e7befbe6), [`0d259b02`](https://github.com/wbkd/react-flow/commit/0d259b028558aab650546f3371a85f3bce45252f), [`f3de9335`](https://github.com/wbkd/react-flow/commit/f3de9335af6cd96cd77dc77f24a944eef85384e5), [`23424ea6`](https://github.com/wbkd/react-flow/commit/23424ea6750f092210f83df17a00c89adb910d96), [`021f5a92`](https://github.com/wbkd/react-flow/commit/021f5a9210f47a968e50446cd2f9dae1f97880a4)]:
- @reactflow/core@11.5.5
## 1.1.7
### Patch Changes
- Updated dependencies [[`383a074a`](https://github.com/wbkd/react-flow/commit/383a074aeae6dbec8437fa08c7c8d8240838a84e)]:
- @reactflow/core@11.5.4
## 1.1.6
### Patch Changes
- Updated dependencies [[`be8097ac`](https://github.com/wbkd/react-flow/commit/be8097acadca3054c3b236ce4296fc516010ef8c), [`1527795d`](https://github.com/wbkd/react-flow/commit/1527795d18c3af38c8ec7059436ea0fbf6c27bbd), [`3b6348a8`](https://github.com/wbkd/react-flow/commit/3b6348a8d1573afb39576327318bc172e33393c2)]:
- @reactflow/core@11.5.3
## 1.1.5
### Patch Changes
- [#2792](https://github.com/wbkd/react-flow/pull/2792) [`d8c679b4`](https://github.com/wbkd/react-flow/commit/d8c679b4c90c5b57d4b51e4aaa988243d6eaff5a) - Accept React 17 types as dev dependency
- Updated dependencies [[`d8c679b4`](https://github.com/wbkd/react-flow/commit/d8c679b4c90c5b57d4b51e4aaa988243d6eaff5a)]:
- @reactflow/core@11.5.2
## 1.1.4
### Patch Changes
- Updated dependencies [[`71153534`](https://github.com/wbkd/react-flow/commit/7115353418ebc7f7c81ab0e861200972bbf7dbd5)]:
- @reactflow/core@11.5.1
## 1.1.3
### Patch Changes
- Updated dependencies [[`e96309b6`](https://github.com/wbkd/react-flow/commit/e96309b6a57b1071faeebf7b0547fef7fd418694), [`85003b01`](https://github.com/wbkd/react-flow/commit/85003b01add71ea852bd5b0d2f1e7496050a6b52), [`4c516882`](https://github.com/wbkd/react-flow/commit/4c516882d2bbf426c1832a53ad40763cc1abef92)]:
- @reactflow/core@11.5.0
## 1.1.2
### Patch Changes
- [#2741](https://github.com/wbkd/react-flow/pull/2741) [`e2aff6c1`](https://github.com/wbkd/react-flow/commit/e2aff6c1e4ce54b57b724b2624367ee5fefd1c39) - chore(dependencies): update and cleanup
- Updated dependencies [[`e34a3072`](https://github.com/wbkd/react-flow/commit/e34a30726dc55184f59adc4f16ca5215a7c42805), [`e2aff6c1`](https://github.com/wbkd/react-flow/commit/e2aff6c1e4ce54b57b724b2624367ee5fefd1c39)]:
- @reactflow/core@11.4.2
## 1.1.1
### Patch Changes
- Updated dependencies [[`82988485`](https://github.com/wbkd/react-flow/commit/82988485b730a9e32acbdae1ddcc81b33ddccaba), [`d91e619a`](https://github.com/wbkd/react-flow/commit/d91e619a70a95db99a621ede59bc05b5a7766086)]:
- @reactflow/core@11.4.1
## 1.1.0
### Patch Changes
- [#2660](https://github.com/wbkd/react-flow/pull/2660) [`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0) - Add `getNodes` function to the store so that you don't need to do `Array.from(store.getState().nodeInternals.values())` anymore.
- Updated dependencies [[`ab2ff374`](https://github.com/wbkd/react-flow/commit/ab2ff3740618da48bd4350597e816c397f3d78ff), [`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0), [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493), [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9), [`7ef29108`](https://github.com/wbkd/react-flow/commit/7ef2910808aaaee029894363d52efc0c378a7654), [`23afb3ab`](https://github.com/wbkd/react-flow/commit/23afb3abebdb42fad284f68bec164afac609563c)]:
- @reactflow/core@11.4.0
## 1.1.0-next.1
### Minor Changes
- panOnDrag: Use numbers for prop ([1,2] = drag via middle or right mouse button)
selection: do not include hidden nodes
minimap: fix onNodeClick for nodes outside the viewport
keys: allow multi select when input is focused
### Patch Changes
- Updated dependencies []:
- @reactflow/core@11.4.0-next.1
## 1.1.0-next.0
### Minor Changes
- [#2678](https://github.com/wbkd/react-flow/pull/2678) [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493) Thanks [@moklick](https://github.com/moklick)! - ## New Features
New props for the ReactFlow component to customize the controls of the viewport and the selection box better:
1. `selectionOnDrag` prop: Selection box without extra button press (need to set `panOnDrag={false} or `panOnDrag="RightClick"`)
2. `panOnDrag="RightClick"` option
3. `panActivationKeyCode="Space"` key code for activating dragging (useful when using `selectionOnDrag`)
4. `selectionMode={SelectionMode.Full}`: you can chose if the selection box needs to contain a node fully (`SelectionMode.Full`) or partially (`SelectionMode.Partial`) to select it
5. `onSelectionStart` and `onSelectionEnd` events
### Patch Changes
- [#2660](https://github.com/wbkd/react-flow/pull/2660) [`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0) Thanks [@moklick](https://github.com/moklick)! - Add `getNodes` function to the store so that you don't need to do `Array.from(store.getState().nodeInternals.values())` anymore.
- Updated dependencies [[`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0), [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493), [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9), [`23afb3ab`](https://github.com/wbkd/react-flow/commit/23afb3abebdb42fad284f68bec164afac609563c)]:
- @reactflow/core@11.4.0-next.0
## 1.0.2
### Patch Changes
- [#2626](https://github.com/wbkd/react-flow/pull/2626) [`d29c401d`](https://github.com/wbkd/react-flow/commit/d29c401d598dbf2dcd5609b7adb8d029906a6f18) - Get nodeId from React Flow context if it is not passed explicitly as prop
- Updated dependencies [[`e6b5d90f`](https://github.com/wbkd/react-flow/commit/e6b5d90f61c8ee60e817bba232a162cae2ab3e2a), [`6ee44e07`](https://github.com/wbkd/react-flow/commit/6ee44e076eaa6908d07578a757a5187642b732ae), [`aa69c207`](https://github.com/wbkd/react-flow/commit/aa69c20765e6978f4f9c8cc63ed7110dbf6d9d9d), [`d29c401d`](https://github.com/wbkd/react-flow/commit/d29c401d598dbf2dcd5609b7adb8d029906a6f18), [`0df02f35`](https://github.com/wbkd/react-flow/commit/0df02f35f8d6c54dae36af18278feadc77acb2d6)]:
- @reactflow/core@11.3.2
## 1.0.1
### Patch Changes
- [#2594](https://github.com/wbkd/react-flow/pull/2594) [`ec94d9ec`](https://github.com/wbkd/react-flow/commit/ec94d9ecdc964d6d66c04e9242f195614bbfdbbe) Thanks [@chrtze](https://github.com/chrtze)! - Allow multiple node ids to be passed for enabling multi selection toolbars
- Updated dependencies [[`c828bfda`](https://github.com/wbkd/react-flow/commit/c828bfda0a8c4774bc43588640c7cca0cfdcb3f4), [`b0302ce4`](https://github.com/wbkd/react-flow/commit/b0302ce4261a992bee841bae84af347d03be690f), [`b2c72813`](https://github.com/wbkd/react-flow/commit/b2c728137d1b53e38883f044fa447585c377a6af)]:
- @reactflow/core@11.3.1
## 1.0.0
### Major Changes
- [#2563](https://github.com/wbkd/react-flow/pull/2563) [`98116d43`](https://github.com/wbkd/react-flow/commit/98116d431f9fcdcc9b23a5b606a94ec0740b64cd) Thanks [@chrtze](https://github.com/chrtze)! - Export a new component "NodeToolbar" that renders a fixed element attached to a node
<file_sep>import { defineConfig } from 'cypress';
export default defineConfig({
e2e: {
baseUrl: 'http://localhost:3000',
viewportWidth: 1280,
viewportHeight: 720,
video: false,
screenshotOnRunFailure: false,
},
component: {
devServer: {
framework: 'react',
bundler: 'vite',
},
screenshotOnRunFailure: false,
video: false,
},
});
<file_sep>/* eslint-disable @typescript-eslint/no-explicit-any */
import type { Selection as D3Selection } from 'd3';
import { boxToRect, clamp, devWarn, getBoundsOfBoxes, getOverlappingArea, rectToBox } from '../utils';
import {
Node,
Edge,
Connection,
EdgeMarkerType,
Transform,
XYPosition,
Rect,
NodeInternals,
NodeOrigin,
UpdateEdgeOptions,
} from '../types';
import { errorMessages } from '../contants';
export const isEdge = (element: Node | Connection | Edge): element is Edge =>
'id' in element && 'source' in element && 'target' in element;
export const isNode = (element: Node | Connection | Edge): element is Node =>
'id' in element && !('source' in element) && !('target' in element);
export const getOutgoers = <T = any, U extends T = T>(node: Node<U>, nodes: Node<T>[], edges: Edge[]): Node<T>[] => {
if (!isNode(node)) {
return [];
}
const outgoerIds = edges.filter((e) => e.source === node.id).map((e) => e.target);
return nodes.filter((n) => outgoerIds.includes(n.id));
};
export const getIncomers = <T = any, U extends T = T>(node: Node<U>, nodes: Node<T>[], edges: Edge[]): Node<T>[] => {
if (!isNode(node)) {
return [];
}
const incomersIds = edges.filter((e) => e.target === node.id).map((e) => e.source);
return nodes.filter((n) => incomersIds.includes(n.id));
};
const getEdgeId = ({ source, sourceHandle, target, targetHandle }: Connection): string =>
`reactflow__edge-${source}${sourceHandle || ''}-${target}${targetHandle || ''}`;
export const getMarkerId = (marker: EdgeMarkerType | undefined, rfId?: string): string => {
if (typeof marker === 'undefined') {
return '';
}
if (typeof marker === 'string') {
return marker;
}
const idPrefix = rfId ? `${rfId}__` : '';
return `${idPrefix}${Object.keys(marker)
.sort()
.map((key: string) => `${key}=${(marker as any)[key]}`)
.join('&')}`;
};
const connectionExists = (edge: Edge, edges: Edge[]) => {
return edges.some(
(el) =>
el.source === edge.source &&
el.target === edge.target &&
(el.sourceHandle === edge.sourceHandle || (!el.sourceHandle && !edge.sourceHandle)) &&
(el.targetHandle === edge.targetHandle || (!el.targetHandle && !edge.targetHandle))
);
};
export const addEdge = (edgeParams: Edge | Connection, edges: Edge[]): Edge[] => {
if (!edgeParams.source || !edgeParams.target) {
devWarn('006', errorMessages['error006']());
return edges;
}
let edge: Edge;
if (isEdge(edgeParams)) {
edge = { ...edgeParams };
} else {
edge = {
...edgeParams,
id: getEdgeId(edgeParams),
} as Edge;
}
if (connectionExists(edge, edges)) {
return edges;
}
return edges.concat(edge);
};
export const updateEdge = (
oldEdge: Edge,
newConnection: Connection,
edges: Edge[],
options: UpdateEdgeOptions = { shouldReplaceId: true }
): Edge[] => {
const { id: oldEdgeId, ...rest } = oldEdge;
if (!newConnection.source || !newConnection.target) {
devWarn('006', errorMessages['error006']());
return edges;
}
const foundEdge = edges.find((e) => e.id === oldEdgeId) as Edge;
if (!foundEdge) {
devWarn('007', errorMessages['error007'](oldEdgeId));
return edges;
}
// Remove old edge and create the new edge with parameters of old edge.
const edge = {
...rest,
id: options.shouldReplaceId ? getEdgeId(newConnection) : oldEdgeId,
source: newConnection.source,
target: newConnection.target,
sourceHandle: newConnection.sourceHandle,
targetHandle: newConnection.targetHandle,
} as Edge;
return edges.filter((e) => e.id !== oldEdgeId).concat(edge);
};
export const pointToRendererPoint = (
{ x, y }: XYPosition,
[tx, ty, tScale]: Transform,
snapToGrid: boolean,
[snapX, snapY]: [number, number]
): XYPosition => {
const position: XYPosition = {
x: (x - tx) / tScale,
y: (y - ty) / tScale,
};
if (snapToGrid) {
return {
x: snapX * Math.round(position.x / snapX),
y: snapY * Math.round(position.y / snapY),
};
}
return position;
};
export const rendererPointToPoint = ({ x, y }: XYPosition, [tx, ty, tScale]: Transform): XYPosition => {
return {
x: x * tScale + tx,
y: y * tScale + ty,
};
};
export const getNodePositionWithOrigin = (
node: Node | undefined,
nodeOrigin: NodeOrigin = [0, 0]
): XYPosition & { positionAbsolute: XYPosition } => {
if (!node) {
return {
x: 0,
y: 0,
positionAbsolute: {
x: 0,
y: 0,
},
};
}
const offsetX = (node.width ?? 0) * nodeOrigin[0];
const offsetY = (node.height ?? 0) * nodeOrigin[1];
const position: XYPosition = {
x: node.position.x - offsetX,
y: node.position.y - offsetY,
};
return {
...position,
positionAbsolute: node.positionAbsolute
? {
x: node.positionAbsolute.x - offsetX,
y: node.positionAbsolute.y - offsetY,
}
: position,
};
};
export const getRectOfNodes = (nodes: Node[], nodeOrigin: NodeOrigin = [0, 0]): Rect => {
if (nodes.length === 0) {
return { x: 0, y: 0, width: 0, height: 0 };
}
const box = nodes.reduce(
(currBox, node) => {
const { x, y } = getNodePositionWithOrigin(node, nodeOrigin).positionAbsolute;
return getBoundsOfBoxes(
currBox,
rectToBox({
x,
y,
width: node.width || 0,
height: node.height || 0,
})
);
},
{ x: Infinity, y: Infinity, x2: -Infinity, y2: -Infinity }
);
return boxToRect(box);
};
export const getNodesInside = (
nodeInternals: NodeInternals,
rect: Rect,
[tx, ty, tScale]: Transform = [0, 0, 1],
partially = false,
// set excludeNonSelectableNodes if you want to pay attention to the nodes "selectable" attribute
excludeNonSelectableNodes = false,
nodeOrigin: NodeOrigin = [0, 0]
): Node[] => {
const paneRect = {
x: (rect.x - tx) / tScale,
y: (rect.y - ty) / tScale,
width: rect.width / tScale,
height: rect.height / tScale,
};
const visibleNodes: Node[] = [];
nodeInternals.forEach((node) => {
const { width, height, selectable = true, hidden = false } = node;
if ((excludeNonSelectableNodes && !selectable) || hidden) {
return false;
}
const { positionAbsolute } = getNodePositionWithOrigin(node, nodeOrigin);
const nodeRect = {
x: positionAbsolute.x,
y: positionAbsolute.y,
width: width || 0,
height: height || 0,
};
const overlappingArea = getOverlappingArea(paneRect, nodeRect);
const notInitialized =
typeof width === 'undefined' || typeof height === 'undefined' || width === null || height === null;
const partiallyVisible = partially && overlappingArea > 0;
const area = (width || 0) * (height || 0);
const isVisible = notInitialized || partiallyVisible || overlappingArea >= area;
if (isVisible || node.dragging) {
visibleNodes.push(node);
}
});
return visibleNodes;
};
export const getConnectedEdges = (nodes: Node[], edges: Edge[]): Edge[] => {
const nodeIds = nodes.map((node) => node.id);
return edges.filter((edge) => nodeIds.includes(edge.source) || nodeIds.includes(edge.target));
};
export const getTransformForBounds = (
bounds: Rect,
width: number,
height: number,
minZoom: number,
maxZoom: number,
padding = 0.1
): Transform => {
const xZoom = width / (bounds.width * (1 + padding));
const yZoom = height / (bounds.height * (1 + padding));
const zoom = Math.min(xZoom, yZoom);
const clampedZoom = clamp(zoom, minZoom, maxZoom);
const boundsCenterX = bounds.x + bounds.width / 2;
const boundsCenterY = bounds.y + bounds.height / 2;
const x = width / 2 - boundsCenterX * clampedZoom;
const y = height / 2 - boundsCenterY * clampedZoom;
return [x, y, clampedZoom];
};
export const getD3Transition = (selection: D3Selection<Element, unknown, null, undefined>, duration = 0) => {
return selection.transition().duration(duration);
};
<file_sep>import { useCallback } from 'react';
import { useStore } from '../hooks/useStore';
import { getNodesInside } from '../utils/graph';
import type { ReactFlowState } from '../types';
function useVisibleNodes(onlyRenderVisible: boolean) {
const nodes = useStore(
useCallback(
(s: ReactFlowState) =>
onlyRenderVisible
? getNodesInside(s.nodeInternals, { x: 0, y: 0, width: s.width, height: s.height }, s.transform, true)
: s.getNodes(),
[onlyRenderVisible]
)
);
return nodes;
}
export default useVisibleNodes;
<file_sep>import { useEffect, useRef, useState } from 'react';
import type { RefObject, MouseEvent } from 'react';
import { drag } from 'd3-drag';
import { select } from 'd3-selection';
import { useStoreApi } from '../../hooks/useStore';
import { getDragItems, getEventHandlerParams, hasSelector, calcNextPosition } from './utils';
import { handleNodeClick } from '../../components/Nodes/utils';
import useGetPointerPosition from '../useGetPointerPosition';
import { calcAutoPan, getEventPosition } from '../../utils';
import type { NodeDragItem, Node, SelectionDragHandler, UseDragEvent, XYPosition } from '../../types';
export type UseDragData = { dx: number; dy: number };
type UseDragParams = {
nodeRef: RefObject<Element>;
disabled?: boolean;
noDragClassName?: string;
handleSelector?: string;
nodeId?: string;
isSelectable?: boolean;
selectNodesOnDrag?: boolean;
};
function wrapSelectionDragFunc(selectionFunc?: SelectionDragHandler) {
return (event: MouseEvent, _: Node, nodes: Node[]) => selectionFunc?.(event, nodes);
}
function useDrag({
nodeRef,
disabled = false,
noDragClassName,
handleSelector,
nodeId,
isSelectable,
selectNodesOnDrag,
}: UseDragParams) {
const store = useStoreApi();
const [dragging, setDragging] = useState<boolean>(false);
const dragItems = useRef<NodeDragItem[]>([]);
const lastPos = useRef<{ x: number | null; y: number | null }>({ x: null, y: null });
const autoPanId = useRef(0);
const containerBounds = useRef<DOMRect | null>(null);
const mousePosition = useRef<{ x: number; y: number }>({ x: 0, y: 0 });
const dragEvent = useRef<MouseEvent | null>(null);
const autoPanStarted = useRef(false);
const getPointerPosition = useGetPointerPosition();
useEffect(() => {
if (nodeRef?.current) {
const selection = select(nodeRef.current);
const updateNodes = ({ x, y }: XYPosition) => {
const {
nodeInternals,
onNodeDrag,
onSelectionDrag,
updateNodePositions,
nodeExtent,
snapGrid,
snapToGrid,
nodeOrigin,
onError,
} = store.getState();
lastPos.current = { x, y };
let hasChange = false;
dragItems.current = dragItems.current.map((n) => {
const nextPosition = { x: x - n.distance.x, y: y - n.distance.y };
if (snapToGrid) {
nextPosition.x = snapGrid[0] * Math.round(nextPosition.x / snapGrid[0]);
nextPosition.y = snapGrid[1] * Math.round(nextPosition.y / snapGrid[1]);
}
const updatedPos = calcNextPosition(n, nextPosition, nodeInternals, nodeExtent, nodeOrigin, onError);
// we want to make sure that we only fire a change event when there is a changes
hasChange = hasChange || n.position.x !== updatedPos.position.x || n.position.y !== updatedPos.position.y;
n.position = updatedPos.position;
n.positionAbsolute = updatedPos.positionAbsolute;
return n;
});
if (!hasChange) {
return;
}
updateNodePositions(dragItems.current, true, true);
setDragging(true);
const onDrag = nodeId ? onNodeDrag : wrapSelectionDragFunc(onSelectionDrag);
if (onDrag && dragEvent.current) {
const [currentNode, nodes] = getEventHandlerParams({
nodeId,
dragItems: dragItems.current,
nodeInternals,
});
onDrag(dragEvent.current as MouseEvent, currentNode, nodes);
}
};
const autoPan = (): void => {
if (!containerBounds.current) {
return;
}
const [xMovement, yMovement] = calcAutoPan(mousePosition.current, containerBounds.current);
if (xMovement !== 0 || yMovement !== 0) {
const { transform, panBy } = store.getState();
lastPos.current.x = (lastPos.current.x ?? 0) - xMovement / transform[2];
lastPos.current.y = (lastPos.current.y ?? 0) - yMovement / transform[2];
if (panBy({ x: xMovement, y: yMovement })) {
updateNodes(lastPos.current as XYPosition);
}
}
autoPanId.current = requestAnimationFrame(autoPan);
};
if (disabled) {
selection.on('.drag', null);
} else {
const dragHandler = drag()
.on('start', (event: UseDragEvent) => {
const {
nodeInternals,
multiSelectionActive,
domNode,
nodesDraggable,
unselectNodesAndEdges,
onNodeDragStart,
onSelectionDragStart,
} = store.getState();
const onStart = nodeId ? onNodeDragStart : wrapSelectionDragFunc(onSelectionDragStart);
if (!selectNodesOnDrag && !multiSelectionActive && nodeId) {
if (!nodeInternals.get(nodeId)?.selected) {
// we need to reset selected nodes when selectNodesOnDrag=false
unselectNodesAndEdges();
}
}
if (nodeId && isSelectable && selectNodesOnDrag) {
handleNodeClick({
id: nodeId,
store,
nodeRef: nodeRef as RefObject<HTMLDivElement>,
});
}
const pointerPos = getPointerPosition(event);
lastPos.current = pointerPos;
dragItems.current = getDragItems(nodeInternals, nodesDraggable, pointerPos, nodeId);
if (onStart && dragItems.current) {
const [currentNode, nodes] = getEventHandlerParams({
nodeId,
dragItems: dragItems.current,
nodeInternals,
});
onStart(event.sourceEvent as MouseEvent, currentNode, nodes);
}
containerBounds.current = domNode?.getBoundingClientRect() || null;
mousePosition.current = getEventPosition(event.sourceEvent, containerBounds.current!);
})
.on('drag', (event: UseDragEvent) => {
const pointerPos = getPointerPosition(event);
const { autoPanOnNodeDrag } = store.getState();
if (!autoPanStarted.current && autoPanOnNodeDrag) {
autoPanStarted.current = true;
autoPan();
}
// skip events without movement
if (
(lastPos.current.x !== pointerPos.xSnapped || lastPos.current.y !== pointerPos.ySnapped) &&
dragItems.current
) {
dragEvent.current = event.sourceEvent as MouseEvent;
mousePosition.current = getEventPosition(event.sourceEvent, containerBounds.current!);
updateNodes(pointerPos);
}
})
.on('end', (event: UseDragEvent) => {
setDragging(false);
autoPanStarted.current = false;
cancelAnimationFrame(autoPanId.current);
if (dragItems.current) {
const { updateNodePositions, nodeInternals, onNodeDragStop, onSelectionDragStop } = store.getState();
const onStop = nodeId ? onNodeDragStop : wrapSelectionDragFunc(onSelectionDragStop);
updateNodePositions(dragItems.current, false, false);
if (onStop) {
const [currentNode, nodes] = getEventHandlerParams({
nodeId,
dragItems: dragItems.current,
nodeInternals,
});
onStop(event.sourceEvent as MouseEvent, currentNode, nodes);
}
}
})
.filter((event: MouseEvent) => {
const target = event.target as HTMLDivElement;
const isDraggable =
!event.button &&
(!noDragClassName || !hasSelector(target, `.${noDragClassName}`, nodeRef)) &&
(!handleSelector || hasSelector(target, handleSelector, nodeRef));
return isDraggable;
});
selection.call(dragHandler);
return () => {
selection.on('.drag', null);
};
}
}
}, [
nodeRef,
disabled,
noDragClassName,
handleSelector,
isSelectable,
store,
nodeId,
selectNodesOnDrag,
getPointerPosition,
]);
return dragging;
}
export default useDrag;
<file_sep>import type { CSSProperties } from 'react';
export const containerStyle: CSSProperties = {
position: 'absolute',
width: '100%',
height: '100%',
top: 0,
left: 0,
};
<file_sep>## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
- The use of sexualized language or imagery and unwelcome sexual attention or advances
- Trolling, insulting/derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or electronic address, without explicit permission
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behaviour and are expected to take appropriate and fair corrective and/or restorative action in response to any instances of unacceptable behaviour.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
Where it is appropriate and parties consent, project maintainers will endeavour to facilitate restorative justice over punitive action.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
Additionally, we ask that all community members uphold the standards laid out in this Code of Conduct to create a safe and welcome space for all.
## Attribution
This Code of Conduct is a direct decendant of the [Gleam Code of Conduct](https://github.com/gleam-lang/gleam/blob/f793b5d28a3102276a8b861c7e16a19c5231426e/CODE_OF_CONDUCT.md), which is itself a decendant of the [Contributor Covenant (v1.4)](https://www.contributor-covenant.org/version/1/4/code-of-conduct.html).
<file_sep>import { readFileSync } from 'fs';
import { resolve } from 'path';
import { cwd } from 'process';
import { defineConfig } from 'rollup';
import resolvePlugin from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import replace from '@rollup/plugin-replace';
import terser from '@rollup/plugin-terser';
import peerDepsExternal from 'rollup-plugin-peer-deps-external';
import typescript from '@rollup/plugin-typescript';
const pkg = JSON.parse(readFileSync(resolve(cwd(), './package.json')));
const isProd = process.env.NODE_ENV === 'production';
const defaultPlugins = [
resolvePlugin(),
commonjs({
include: /node_modules/,
}),
];
const onwarn = (warning, rollupWarn) => {
if (warning.code !== 'CIRCULAR_DEPENDENCY') {
rollupWarn(warning);
}
};
export const esmConfig = defineConfig({
input: pkg.source,
output: {
file: pkg.module,
format: 'esm',
},
onwarn,
plugins: [
peerDepsExternal({
includeDependencies: true,
}),
...defaultPlugins,
typescript(),
],
});
const globals = {
react: 'React',
'react-dom': 'ReactDOM',
'react/jsx-runtime': 'jsxRuntime',
...(pkg.rollup?.globals || {}),
};
export const umdConfig = defineConfig({
input: pkg.source,
output: {
file: pkg.main,
format: 'umd',
exports: 'named',
name: pkg.rollup?.name || 'ReactFlow',
globals,
},
onwarn,
plugins: [
peerDepsExternal(),
...defaultPlugins,
typescript(),
replace({
preventAssignment: true,
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
}),
terser(),
],
});
export default isProd ? [esmConfig, umdConfig] : esmConfig;
<file_sep>import { createContext } from 'react';
import { createRFStore } from '../store';
const StoreContext = createContext<ReturnType<typeof createRFStore> | null>(null);
export const Provider = StoreContext.Provider;
export default StoreContext;
<file_sep>import { createStore } from 'zustand';
import { zoomIdentity } from 'd3-zoom';
import { clampPosition, getDimensions, internalsSymbol } from '../utils';
import { applyNodeChanges, createSelectionChange, getSelectionChanges } from '../utils/changes';
import { getHandleBounds } from '../components/Nodes/utils';
import { createNodeInternals, fitView, updateAbsoluteNodePositions, updateNodesAndEdgesSelections } from './utils';
import initialState from './initialState';
import type {
ReactFlowState,
Node,
Edge,
NodeDimensionUpdate,
CoordinateExtent,
NodeDimensionChange,
EdgeSelectionChange,
NodeSelectionChange,
NodePositionChange,
NodeDragItem,
UnselectNodesAndEdgesParams,
NodeChange,
XYPosition,
} from '../types';
const createRFStore = () =>
createStore<ReactFlowState>((set, get) => ({
...initialState,
setNodes: (nodes: Node[]) => {
const { nodeInternals, nodeOrigin, elevateNodesOnSelect } = get();
set({ nodeInternals: createNodeInternals(nodes, nodeInternals, nodeOrigin, elevateNodesOnSelect) });
},
getNodes: () => {
return Array.from(get().nodeInternals.values());
},
setEdges: (edges: Edge[]) => {
const { defaultEdgeOptions = {} } = get();
set({ edges: edges.map((e) => ({ ...defaultEdgeOptions, ...e })) });
},
setDefaultNodesAndEdges: (nodes?: Node[], edges?: Edge[]) => {
const hasDefaultNodes = typeof nodes !== 'undefined';
const hasDefaultEdges = typeof edges !== 'undefined';
const nodeInternals = hasDefaultNodes
? createNodeInternals(nodes, new Map(), get().nodeOrigin, get().elevateNodesOnSelect)
: new Map();
const nextEdges = hasDefaultEdges ? edges : [];
set({ nodeInternals, edges: nextEdges, hasDefaultNodes, hasDefaultEdges });
},
updateNodeDimensions: (updates: NodeDimensionUpdate[]) => {
const {
onNodesChange,
nodeInternals,
fitViewOnInit,
fitViewOnInitDone,
fitViewOnInitOptions,
domNode,
nodeOrigin,
} = get();
const viewportNode = domNode?.querySelector('.react-flow__viewport');
if (!viewportNode) {
return;
}
const style = window.getComputedStyle(viewportNode);
const { m22: zoom } = new window.DOMMatrixReadOnly(style.transform);
const changes: NodeDimensionChange[] = updates.reduce<NodeDimensionChange[]>((res, update) => {
const node = nodeInternals.get(update.id);
if (node) {
const dimensions = getDimensions(update.nodeElement);
const doUpdate = !!(
dimensions.width &&
dimensions.height &&
(node.width !== dimensions.width || node.height !== dimensions.height || update.forceUpdate)
);
if (doUpdate) {
nodeInternals.set(node.id, {
...node,
[internalsSymbol]: {
...node[internalsSymbol],
handleBounds: {
source: getHandleBounds('.source', update.nodeElement, zoom, nodeOrigin),
target: getHandleBounds('.target', update.nodeElement, zoom, nodeOrigin),
},
},
...dimensions,
});
res.push({
id: node.id,
type: 'dimensions',
dimensions,
});
}
}
return res;
}, []);
updateAbsoluteNodePositions(nodeInternals, nodeOrigin);
const nextFitViewOnInitDone =
fitViewOnInitDone ||
(fitViewOnInit && !fitViewOnInitDone && fitView(get, { initial: true, ...fitViewOnInitOptions }));
set({ nodeInternals: new Map(nodeInternals), fitViewOnInitDone: nextFitViewOnInitDone });
if (changes?.length > 0) {
onNodesChange?.(changes);
}
},
updateNodePositions: (nodeDragItems: NodeDragItem[] | Node[], positionChanged = true, dragging = false) => {
const { triggerNodeChanges } = get();
const changes = nodeDragItems.map((node) => {
const change: NodePositionChange = {
id: node.id,
type: 'position',
dragging,
};
if (positionChanged) {
change.positionAbsolute = node.positionAbsolute;
change.position = node.position;
}
return change;
});
triggerNodeChanges(changes);
},
triggerNodeChanges: (changes: NodeChange[]) => {
const { onNodesChange, nodeInternals, hasDefaultNodes, nodeOrigin, getNodes, elevateNodesOnSelect } = get();
if (changes?.length) {
if (hasDefaultNodes) {
const nodes = applyNodeChanges(changes, getNodes());
const nextNodeInternals = createNodeInternals(nodes, nodeInternals, nodeOrigin, elevateNodesOnSelect);
set({ nodeInternals: nextNodeInternals });
}
onNodesChange?.(changes);
}
},
addSelectedNodes: (selectedNodeIds: string[]) => {
const { multiSelectionActive, edges, getNodes } = get();
let changedNodes: NodeSelectionChange[];
let changedEdges: EdgeSelectionChange[] | null = null;
if (multiSelectionActive) {
changedNodes = selectedNodeIds.map((nodeId) => createSelectionChange(nodeId, true)) as NodeSelectionChange[];
} else {
changedNodes = getSelectionChanges(getNodes(), selectedNodeIds);
changedEdges = getSelectionChanges(edges, []);
}
updateNodesAndEdgesSelections({
changedNodes,
changedEdges,
get,
set,
});
},
addSelectedEdges: (selectedEdgeIds: string[]) => {
const { multiSelectionActive, edges, getNodes } = get();
let changedEdges: EdgeSelectionChange[];
let changedNodes: NodeSelectionChange[] | null = null;
if (multiSelectionActive) {
changedEdges = selectedEdgeIds.map((edgeId) => createSelectionChange(edgeId, true)) as EdgeSelectionChange[];
} else {
changedEdges = getSelectionChanges(edges, selectedEdgeIds);
changedNodes = getSelectionChanges(getNodes(), []);
}
updateNodesAndEdgesSelections({
changedNodes,
changedEdges,
get,
set,
});
},
unselectNodesAndEdges: ({ nodes, edges }: UnselectNodesAndEdgesParams = {}) => {
const { edges: storeEdges, getNodes } = get();
const nodesToUnselect = nodes ? nodes : getNodes();
const edgesToUnselect = edges ? edges : storeEdges;
const changedNodes = nodesToUnselect.map((n) => {
n.selected = false;
return createSelectionChange(n.id, false);
}) as NodeSelectionChange[];
const changedEdges = edgesToUnselect.map((edge) =>
createSelectionChange(edge.id, false)
) as EdgeSelectionChange[];
updateNodesAndEdgesSelections({
changedNodes,
changedEdges,
get,
set,
});
},
setMinZoom: (minZoom: number) => {
const { d3Zoom, maxZoom } = get();
d3Zoom?.scaleExtent([minZoom, maxZoom]);
set({ minZoom });
},
setMaxZoom: (maxZoom: number) => {
const { d3Zoom, minZoom } = get();
d3Zoom?.scaleExtent([minZoom, maxZoom]);
set({ maxZoom });
},
setTranslateExtent: (translateExtent: CoordinateExtent) => {
get().d3Zoom?.translateExtent(translateExtent);
set({ translateExtent });
},
resetSelectedElements: () => {
const { edges, getNodes } = get();
const nodes = getNodes();
const nodesToUnselect = nodes
.filter((e) => e.selected)
.map((n) => createSelectionChange(n.id, false)) as NodeSelectionChange[];
const edgesToUnselect = edges
.filter((e) => e.selected)
.map((e) => createSelectionChange(e.id, false)) as EdgeSelectionChange[];
updateNodesAndEdgesSelections({
changedNodes: nodesToUnselect,
changedEdges: edgesToUnselect,
get,
set,
});
},
setNodeExtent: (nodeExtent: CoordinateExtent) => {
const { nodeInternals } = get();
nodeInternals.forEach((node) => {
node.positionAbsolute = clampPosition(node.position, nodeExtent);
});
set({
nodeExtent,
nodeInternals: new Map(nodeInternals),
});
},
panBy: (delta: XYPosition): boolean => {
const { transform, width, height, d3Zoom, d3Selection, translateExtent } = get();
if (!d3Zoom || !d3Selection || (!delta.x && !delta.y)) {
return false;
}
const nextTransform = zoomIdentity.translate(transform[0] + delta.x, transform[1] + delta.y).scale(transform[2]);
const extent: CoordinateExtent = [
[0, 0],
[width, height],
];
const constrainedTransform = d3Zoom?.constrain()(nextTransform, extent, translateExtent);
d3Zoom.transform(d3Selection, constrainedTransform);
const transformChanged =
transform[0] !== constrainedTransform.x ||
transform[1] !== constrainedTransform.y ||
transform[2] !== constrainedTransform.k;
return transformChanged;
},
cancelConnection: () =>
set({
connectionNodeId: initialState.connectionNodeId,
connectionHandleId: initialState.connectionHandleId,
connectionHandleType: initialState.connectionHandleType,
connectionStatus: initialState.connectionStatus,
connectionStartHandle: initialState.connectionStartHandle,
connectionEndHandle: initialState.connectionEndHandle,
}),
reset: () => set({ ...initialState }),
}));
export { createRFStore };
<file_sep>import { useRef, useState } from 'react';
const useCountdown = (callback: () => void) => {
const interval = useRef<NodeJS.Timer>();
const [remaining, setRemaining] = useState(0);
const start = (duration: number) => {
setRemaining(duration);
interval.current = setInterval(() => {
setRemaining((prev) => {
if (prev === 1) {
clearInterval(interval.current);
callback();
}
return prev - 1;
});
}, 1000);
};
const stop = () => {
clearInterval(interval.current);
setRemaining(0);
};
return {
start,
remaining,
stop,
counting: remaining > 0,
};
};
export default useCountdown;
<file_sep># @reactflow/minimap
Mini map component for React Flow.
## Installation
```sh
npm install @reactflow/minimap
```
<file_sep>import { useState, useEffect, useRef, useMemo } from 'react';
import { isInputDOMNode } from '../utils';
import type { KeyCode } from '../types';
type Keys = Array<string>;
type PressedKeys = Set<string>;
type KeyOrCode = 'key' | 'code';
export interface UseKeyPressOptions {
target: Window | Document | HTMLElement | ShadowRoot | null;
}
const doc = typeof document !== 'undefined' ? document : null;
// the keycode can be a string 'a' or an array of strings ['a', 'a+d']
// a string means a single key 'a' or a combination when '+' is used 'a+d'
// an array means different possibilites. Explainer: ['a', 'd+s'] here the
// user can use the single key 'a' or the combination 'd' + 's'
export default (keyCode: KeyCode | null = null, options: UseKeyPressOptions = { target: doc }): boolean => {
const [keyPressed, setKeyPressed] = useState(false);
// we need to remember if a modifier key is pressed in order to track it
const modifierPressed = useRef(false);
// we need to remember the pressed keys in order to support combinations
const pressedKeys = useRef<PressedKeys>(new Set([]));
// keyCodes = array with single keys [['a']] or key combinations [['a', 's']]
// keysToWatch = array with all keys flattened ['a', 'd', 'ShiftLeft']
// used to check if we store event.code or event.key. When the code is in the list of keysToWatch
// we use the code otherwise the key. Explainer: When you press the left "command" key, the code is "MetaLeft"
// and the key is "Meta". We want users to be able to pass keys and codes so we assume that the key is meant when
// we can't find it in the list of keysToWatch.
const [keyCodes, keysToWatch] = useMemo<[Array<Keys>, Keys]>(() => {
if (keyCode !== null) {
const keyCodeArr = Array.isArray(keyCode) ? keyCode : [keyCode];
const keys = keyCodeArr.filter((kc) => typeof kc === 'string').map((kc) => kc.split('+'));
const keysFlat = keys.reduce((res: Keys, item) => res.concat(...item), []);
return [keys, keysFlat];
}
return [[], []];
}, [keyCode]);
useEffect(() => {
if (keyCode !== null) {
const downHandler = (event: KeyboardEvent) => {
modifierPressed.current = event.ctrlKey || event.metaKey || event.shiftKey;
if (!modifierPressed.current && isInputDOMNode(event)) {
return false;
}
const keyOrCode = useKeyOrCode(event.code, keysToWatch);
pressedKeys.current.add(event[keyOrCode]);
if (isMatchingKey(keyCodes, pressedKeys.current, false)) {
event.preventDefault();
setKeyPressed(true);
}
};
const upHandler = (event: KeyboardEvent) => {
if (!modifierPressed.current && isInputDOMNode(event)) {
return false;
}
const keyOrCode = useKeyOrCode(event.code, keysToWatch);
if (isMatchingKey(keyCodes, pressedKeys.current, true)) {
setKeyPressed(false);
pressedKeys.current.clear();
} else {
pressedKeys.current.delete(event[keyOrCode]);
}
modifierPressed.current = false;
};
const resetHandler = () => {
pressedKeys.current.clear();
setKeyPressed(false);
};
options?.target?.addEventListener('keydown', downHandler as EventListenerOrEventListenerObject);
options?.target?.addEventListener('keyup', upHandler as EventListenerOrEventListenerObject);
window.addEventListener('blur', resetHandler);
return () => {
options?.target?.removeEventListener('keydown', downHandler as EventListenerOrEventListenerObject);
options?.target?.removeEventListener('keyup', upHandler as EventListenerOrEventListenerObject);
window.removeEventListener('blur', resetHandler);
};
}
}, [keyCode, setKeyPressed]);
return keyPressed;
};
// utils
function isMatchingKey(keyCodes: Array<Keys>, pressedKeys: PressedKeys, isUp: boolean): boolean {
return (
keyCodes
// we only want to compare same sizes of keyCode definitions
// and pressed keys. When the user specified 'Meta' as a key somewhere
// this would also be truthy without this filter when user presses 'Meta' + 'r'
.filter((keys) => isUp || keys.length === pressedKeys.size)
// since we want to support multiple possibilities only one of the
// combinations need to be part of the pressed keys
.some((keys) => keys.every((k) => pressedKeys.has(k)))
);
}
function useKeyOrCode(eventCode: string, keysToWatch: KeyCode): KeyOrCode {
return keysToWatch.includes(eventCode) ? 'code' : 'key';
}
<file_sep>import { Edge, HandleElement } from './types';
export const errorMessages = {
error001: () =>
'[React Flow]: Seems like you have not used zustand provider as an ancestor. Help: https://reactflow.dev/error#001',
error002: () =>
"It looks like you've created a new nodeTypes or edgeTypes object. If this wasn't on purpose please define the nodeTypes/edgeTypes outside of the component or memoize them.",
error003: (nodeType: string) => `Node type "${nodeType}" not found. Using fallback type "default".`,
error004: () => 'The React Flow parent container needs a width and a height to render the graph.',
error005: () => 'Only child nodes can use a parent extent.',
error006: () => "Can't create edge. An edge needs a source and a target.",
error007: (id: string) => `The old edge with id=${id} does not exist.`,
error009: (type: string) => `Marker type "${type}" doesn't exist.`,
error008: (sourceHandle: HandleElement | null, edge: Edge) =>
`Couldn't create edge for ${!sourceHandle ? 'source' : 'target'} handle id: "${
!sourceHandle ? edge.sourceHandle : edge.targetHandle
}", edge id: ${edge.id}.`,
error010: () => 'Handle: No node id found. Make sure to only use a Handle inside a custom Node.',
error011: (edgeType: string) => `Edge type "${edgeType}" not found. Using fallback type "default".`,
};
<file_sep>import { useMemo, useRef } from 'react';
import { shallow } from 'zustand/shallow';
import { devWarn } from '../../utils';
import { CreateEdgeTypes } from '../EdgeRenderer/utils';
import { CreateNodeTypes } from '../NodeRenderer/utils';
import type { EdgeTypes, EdgeTypesWrapped, NodeTypes, NodeTypesWrapped } from '../../types';
import { errorMessages } from '../../contants';
export function useNodeOrEdgeTypes(nodeOrEdgeTypes: NodeTypes, createTypes: CreateNodeTypes): NodeTypesWrapped;
export function useNodeOrEdgeTypes(nodeOrEdgeTypes: EdgeTypes, createTypes: CreateEdgeTypes): EdgeTypesWrapped;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function useNodeOrEdgeTypes(nodeOrEdgeTypes: any, createTypes: any): any {
const typesKeysRef = useRef<string[] | null>(null);
const typesParsed = useMemo(() => {
if (process.env.NODE_ENV === 'development') {
const typeKeys = Object.keys(nodeOrEdgeTypes);
if (shallow(typesKeysRef.current, typeKeys)) {
devWarn('002', errorMessages['error002']());
}
typesKeysRef.current = typeKeys;
}
return createTypes(nodeOrEdgeTypes);
}, [nodeOrEdgeTypes]);
return typesParsed;
}
<file_sep>import { CSSProperties } from 'react';
export enum BackgroundVariant {
Lines = 'lines',
Dots = 'dots',
Cross = 'cross',
}
export type BackgroundProps = {
id?: string
color?: string;
className?: string;
gap?: number | [number, number];
size?: number;
offset?: number;
lineWidth?: number;
variant?: BackgroundVariant;
style?: CSSProperties;
};
<file_sep>describe('Figma Flow UI', () => {
before(() => {
cy.visit('/figma');
});
it('renders a flow with three nodes', () => {
cy.get('.react-flow__renderer');
cy.get('.react-flow__node').should('have.length', 4);
cy.get('.react-flow__edge').should('have.length', 2);
cy.get('.react-flow__node').children('.react-flow__handle');
});
it('renders a grid', () => {
cy.get('.react-flow__background');
});
it('selects all nodes by drag', () => {
cy.window().then((win) => {
cy.get('.react-flow__pane')
.trigger('mousedown', 'topLeft', { button: 0, view: win })
.trigger('mousemove', 'bottomRight', { force: true })
.wait(50)
.trigger('mouseup', { force: true, view: win })
.then(() => {
cy.get('.react-flow__node').should('have.class', 'selected');
});
});
});
it('removes selection', () => {
cy.get('.react-flow__pane').click('topLeft');
cy.get('.react-flow__node').should('not.have.class', 'selected');
});
it('drags using right click', () => {
cy.window().then((win) => {
cy.get('.react-flow__node:last').isWithinViewport();
cy.get('.react-flow__pane')
.trigger('mousedown', 'center', { button: 2, view: win })
.trigger('mousemove', 'bottom', { force: true })
.wait(50)
.trigger('mouseup', { force: true, view: win })
.then(() => {
cy.get('.react-flow__node').should('not.have.class', 'selected');
cy.get('.react-flow__node:last').isOutsideViewport();
});
});
});
});
export {};
<file_sep># @reactflow/background
Background component for React Flow.
## Installation
```sh
npm install @reactflow/background
```
| 448c2049be0f51beb4a68c4368cc13b889139714 | [
"Markdown",
"TypeScript",
"JavaScript",
"JSON with Comments"
] | 91 | Markdown | mfkiwl/react-flow | 993a778b80cc1e80a47983ed75407b579313a73c | 920cc0b74e20c03b45900bd1ec27fc212151cbcf |
refs/heads/master | <file_sep># 🦜 Mockingjay
## Unsupervised Speech Representation Learning with Deep Bidirectional Transformer Encoders
### PyTorch Official Implementation
[](https://en.wikipedia.org/wiki/MIT_License)
[](CONTRIBUTING.md)
[](https://github.com/andi611/Mockingjay-Speech-Representation/issues)
* This is an open source project for Mockingjay, an unsupervised algorithm for learning speech representations introduced and described in the paper ["Mockingjay: Unsupervised Speech Representation Learning with Deep Bidirectional Transformer Encoders"](https://arxiv.org/abs/1910.12638), which is accepted as a Lecture in [ICASSP 2020](https://2020.ieeeicassp.org/).
* We compare our speech representations with the [APC](https://arxiv.org/abs/1904.03240) and [CPC](https://arxiv.org/abs/1807.03748) approach, evaluating on 3 downstream tasks including: phone classification, speaker recognition, and sentiment classification on spoken content.
* Feel free to use or modify them, any bug report or improvement suggestion will be appreciated. If you have any questions, please contact <EMAIL>. If you find this project helpful for your research, please do consider to cite [this paper](#Citation), thanks!
* Below we illustrate the proposed Masked Acoustic Model pre-training task, where 15% of input the frames are masked to zero at random during training. Which is reminiscent of the Masked Language Model task of [BERT](https://arxiv.org/abs/1810.04805)-style pre-training from the NLP ccommunity.
<img src="https://github.com/andi611/Mockingjay-Speech-Representation/blob/master/paper/training.png">
# Results
* We provide furthur frame-wise phone classification results, which is not included in our previous paper, comparing with the *"Contrastive Predictive Coding, CPC"* method, using identical [phone
labels and train/test split](https://drive.google.com/drive/folders/1BhJ2umKH3whguxMwifaKtSra0TgAbtfb) as provided in the [CPC paper](https://arxiv.org/pdf/1807.03748.pdf).
* We pre-train Mockingjay on the 100hr subset of LibriSpeech, same as CPC.
* There are 41 possible classes, phone classification results on LibriSpeech:
| Features | Pre-train | Linear Classifier | 1 Hidden Classifier |
|-------------|:---------:|:-----------------:|:-------------------:|
| MFCC | None | 39.7 | |
| CPC | 100 hr | 64.6 | 72.5 |
| BASE (Ours) | 100 hr | 64.3 | 76.8 |
| BASE (Ours) | 360 hr | 66.4 | 77.0 |
| BASE (Ours) | 960 hr | **67.0** | **79.1** |
# Highlight
## Pre-trained Models
You can find pre-trained models here:
**[http://bit.ly/result_mockingjay](http://bit.ly/result_mockingjay)**
Their usage are explained bellow and furthur in [Step 3 of the Instruction Section](#Instructions).
## Extract features or fine-tuning with your own downstream models (RECOMMEND)
With this repo and the trained models, you can fine-tune the pre-trained Mockingjay model on your own dataset and tasks (*important: the input acoustic features must use the same preprocessing settings!!!*).
To do so, use the wrapper class in [nn_mockingjay.py](mockingjay/nn_mockingjay.py), and take a look at the following example python code ([example_extract_finetune.py](example_extract_finetune.py)):
```python
import torch
from mockingjay.nn_mockingjay import MOCKINGJAY
from downstream.model import example_classifier
from downstream.solver import get_mockingjay_optimizer
# setup the mockingjay model
options = {
'ckpt_file' : 'result/result_mockingjay/mockingjay_libri_sd1337_MelBase/mockingjay-500000.ckpt',
'load_pretrain' : 'True',
'no_grad' : 'False',
'dropout' : 'default'
}
model = MOCKINGJAY(options=options, inp_dim=160)
# setup your downstream class model
classifier = example_classifier(input_dim=768, hidden_dim=128, class_num=2).cuda()
# construct the Mockingjay optimizer
params = list(model.named_parameters()) + list(classifier.named_parameters())
optimizer = get_mockingjay_optimizer(params=params, lr=4e-3, warmup_proportion=0.7, training_steps=50000)
# forward
example_inputs = torch.zeros(1200, 3, 160) # A batch of spectrograms: (time_step, batch_size, dimension)
reps = model(example_inputs) # returns: (time_step, batch_size, hidden_size)
reps = reps.permute(1, 0, 2) # change to: (batch_size, time_step, feature_size)
labels = torch.LongTensor([0, 1, 0]).cuda()
loss = classifier(reps, labels)
# update
loss.backward()
optimizer.step()
# save
PATH_TO_SAVE_YOUR_MODEL = 'example.ckpt'
states = {'Classifier': classifier.state_dict(), 'Mockingjay': model.state_dict()}
torch.save(states, PATH_TO_SAVE_YOUR_MODEL)
```
## Extracting Speech Representations with Solver
With this repo and the trained models, you can use it to extract speech representations from your target dataset (*important: the input acoustic features must use the same preprocessing settings!!!*). To do so, feed-forward the trained model on the target dataset and retrieve the extracted features by running the following example python code ([example_solver.py](example_solver.py)):
```python
import torch
from runner_mockingjay import get_mockingjay_model
example_path = 'result/result_mockingjay/mockingjay_libri_sd1337_LinearLarge/mockingjay-500000.ckpt'
mockingjay = get_mockingjay_model(from_path=example_path)
# A batch of spectrograms: (batch_size, seq_len, hidden_size)
spec = torch.zeros(3, 800, 160)
# reps.shape: (batch_size, num_hiddem_layers, seq_len, hidden_size)
reps = mockingjay.forward(spec=spec, all_layers=True, tile=True)
# reps.shape: (batch_size, num_hiddem_layers, seq_len // downsample_rate, hidden_size)
reps = mockingjay.forward(spec=spec, all_layers=True, tile=False)
# reps.shape: (batch_size, seq_len, hidden_size)
reps = mockingjay.forward(spec=spec, all_layers=False, tile=True)
# reps.shape: (batch_size, seq_len // downsample_rate, hidden_size)
reps = mockingjay.forward(spec=spec, all_layers=False, tile=False)
```
`spec` is the input spectrogram of the mockingjay model where:
- `spec` needs to be a PyTorch tensor with shape of `(seq_len, mel_dim)` or `(batch_size, seq_len, mel_dim)`.
- `mel_dim` is the spectrogram feature dimension which by default is `mel_dim == 160`, see [utility/audio.py](utility/audio.py) for more preprocessing details.
`reps` is a PyTorch tensor of various possible shapes where:
- `batch_size` is the inference batch size.
- `num_hiddem_layers` is the transformer encoder depth of the mockingjay model.
- `seq_len` is the maximum sequence length in the batch.
- `downsample_rate` is the dimensionality of the transformer encoder layers.
- `hidden_size` is the number of stacked consecutive features vectors to reduce the length of input sequences.
The output shape of `reps` is determined by the two arguments:
- `all_layers` is a boolean which controls whether to output all the Encoder layers, if `False` returns the hidden of the last Encoder layer.
- `tile` is a boolean which controls whether to tile representations to match the input `seq_len` of `spec`.
As you can see, `reps` is essentially the Transformer Encoder hidden representations in the mockingjay model. You can think of Mockingjay as a speech version of [BERT](https://arxiv.org/abs/1810.04805) if you are familiar with it.
There are many ways to incorporate `reps` into your downtream task. One of the easiest way is to take only the outputs of the last Encoder layer (i.e., `all_layers=False`) as the input features to your downstream model, feel free to explore other mechanisms.
# Requirements
- Python 3
- Pytorch 1.3.0 or above
- Computing power (high-end GPU) and memory space (both RAM/GPU's RAM) is **extremely important** if you'd like to train your own model.
- Required packages and their use are listed below, and also in [requirements.txt](requirements.txt):
```
editdistance # error rate calculation
joblib # parallel feature extraction & decoding
librosa # feature extraction (for feature extraction only)
pydub # audio segmentation (for MOSEI dataset preprocessing only)
pandas # data management
tensorboardX # logger & monitor
torch # model & learning
tqdm # verbosity
yaml # config parser
matplotlib # visualization
ipdb # optional debugger
numpy # array computation
scipy # for feature extraction
```
The above packages can be installed by the command:
```bash
pip3 install -r requirements.txt
```
Below we list packages that need special attention, and we recommand you to install them manually:
```
apex # non-essential, faster optimization (only needed if enabled in config)
sentencepiece # sub-word unit encoding (for feature extraction only, see https://github.com/google/sentencepiece#build-and-install-sentencepiece for install instruction)
```
# Instructions
***Before you start, make sure all the packages required listed above are installed correctly***
### Step 0. Preprocessing - Acoustic Feature Extraction & Text Encoding
See the instructions on the [Preprocess wiki page](https://github.com/andi611/Mockingjay-Speech-Representation/wiki/Mockingjay-Preprocessing-Instructions) for preprocessing instructions.
### Step 1. Configuring - Model Design & Hyperparameter Setup
All the parameters related to training/decoding will be stored in a yaml file. Hyperparameter tuning and massive experiment and can be managed easily this way. See [config files](config/) for the exact format and examples.
### Step 2. Training the Mockingjay Model for Speech Representation Learning
Once the config file is ready, run the following command to train unsupervised end-to-end Mockingjay:
```bash
python3 runner_mockingjay.py --train
```
All settings will be parsed from the config file automatically to start training, the log file can be accessed through TensorBoard.
### Step 3. Using Pre-trained Models on Downstream Tasks
Once a Mockingjay model was trained, we can use the generated representations on downstream tasks.
See the [Experiment section](#Experiments) for reproducing downstream task results mentioned in our paper, and see the [Highlight section](#Highlight) for incorporating the extracted representations with your own downstream task.
Pre-trained models and their configs can be download from [HERE](http://bit.ly/result_mockingjay).
To load with default path, models should be placed under the directory path: `--ckpdir=./result_mockingjay/` and name the model file manually with `--ckpt=`.
### Step 4. Loading Pre-trained Models and Visualize
Run the following command to visualize the model generated samples:
```bash
# visualize hidden representations
python3 runner_mockingjay.py --plot
# visualize spectrogram
python3 runner_mockingjay.py --plot --with_head
```
Note that the arguments ```--ckpdir=XXX --ckpt=XXX``` needs to be set correctly for the above command to run properly.
### Step 5. Monitor Training Log
```bash
# open TensorBoard to see log
tensorboard --logdir=log/log_mockingjay/mockingjay_libri_sd1337/
# or
python3 -m tensorboard.main --logdir=log/log_mockingjay/mockingjay_libri_sd1337/
```
## Experiments
### Application on downstream tasks
See the instructions on the [Downstream wiki page](https://github.com/andi611/Mockingjay-Speech-Representation/wiki/Downstream-Task-Instructions) to reproduce our experiments.
### Comparing with APC
See the instructions on the [APC wiki page](https://github.com/andi611/Mockingjay-Speech-Representation/wiki/Reproducing-APC-to-compare-with-Mockingjay) to reproduce our experiments. Comparison results are in our [paper](https://arxiv.org/abs/1910.12638).
### Comparing with CPC
See the instructions on the [Downstream wiki page](https://github.com/andi611/Mockingjay-Speech-Representation/wiki/Downstream-Task-Instructions) to reproduce our experiments. Comparison results are in the first [section](#Results).
# Reference
1. [Montreal Forced Aligner](https://montreal-forced-aligner.readthedocs.io/en/latest/), McAuliffe et. al.
2. [CMU MultimodalSDK](https://github.com/A2Zadeh/CMU-MultimodalSDK/blob/master/README.md), <NAME>.
3. [PyTorch Transformers](https://github.com/huggingface/pytorch-transformers), Hugging Face.
4. [Autoregressive Predictive Coding](https://arxiv.org/abs/1904.03240), <NAME>.
5. [Contrastive Predictive Coding](https://arxiv.org/abs/1807.03748), <NAME>.
5. [End-to-end ASR Pytorch](https://github.com/Alexander-H-Liu/End-to-end-ASR-Pytorch), Alexander-H-Liu.
6. [Tacotron Preprocessing](https://github.com/r9y9/tacotron_pytorch), <NAME> (r9y9)
## Citation
```
@article{Liu_2020,
title={Mockingjay: Unsupervised Speech Representation Learning with Deep Bidirectional Transformer Encoders},
ISBN={9781509066315},
url={http://dx.doi.org/10.1109/ICASSP40776.2020.9054458},
DOI={10.1109/icassp40776.2020.9054458},
journal={ICASSP 2020 - 2020 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP)},
publisher={IEEE},
author={<NAME>. and <NAME> and <NAME> and <NAME> and <NAME>},
year={2020},
month={May}
}
```
<file_sep>import os
import sys
import torch
"""
Usage:
This .py helps fix the old checkpoint name issue.
1) First create a dummy directory called "utils/"
2) Copy utility/timer.py as utils/timer.py
3) Run this script to fix the old checkpoint files that store a 'utils.timer' that is no longer used
"""
input_dir = sys.argv[1]
input_ckpt = os.path.join(input_dir, 'mockingjay-500000.ckpt')
all_states = torch.load(input_ckpt, map_location='cpu')
config = all_states['Settings']['Config']
for cluster in all_states['Settings']['Config']:
if 'timer' in all_states['Settings']['Config']:
del all_states['Settings']['Config']['timer']
break
torch.save(all_states, input_ckpt)
print('Done fixing ckpt: ', input_ckpt)
| 5d0c81c128791a8e7d81e31f5e395351c325539e | [
"Markdown",
"Python"
] | 2 | Markdown | aviasd/Mockingjay-Speech-Representation | c01aef3f98bbb3fd4b0fc1b61e77fb5d02a0e453 | eecd2f361b2ee682643ebcd0d2860773cc21c3a8 |
refs/heads/master | <repo_name>BhackNL/Meetup.TheGame<file_sep>/voorbeeld.ino
#include <I2C.h>
#include <II2C.h>
#include <MPU6050.h>
#include <MultiFuncShield.h>
#define LED_MIN 10
#define LED_MAX 13
#define UP true
#define DOWN false
int ledPin = LED_MIN;
bool direction = UP;
int delayMs = 750;
int score = 0;
void setup() {
Timer1.initialize();
MFS.initialize(&Timer1);
Serial.begin(9600);
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
pinMode(12, OUTPUT);
pinMode(13, OUTPUT);
digitalWrite(10, HIGH);
digitalWrite(11, HIGH);
digitalWrite(12, HIGH);
digitalWrite(13, HIGH);
Serial.println(score);
}
void gameOver() {
score = 0;
delayMs = 750;
direction = UP;
ledPin = LED_MIN;
Serial.println("GAME OVER!");
digitalWrite(10, LOW);
digitalWrite(11, LOW);
digitalWrite(12, LOW);
digitalWrite(13, LOW);
delay(2000);
digitalWrite(10, HIGH);
digitalWrite(11, HIGH);
digitalWrite(12, HIGH);
digitalWrite(13, HIGH);
}
bool handleUp() {
if (ledPin == LED_MAX) {
if (analogRead(3) < 100) {
score++;
Serial.println(score);
if (delayMs > 150)
delayMs -= 30;
} else {
gameOver();
return true;
}
direction = DOWN;
ledPin--;
} else {
ledPin++;
}
return false;
}
bool handleDown() {
if (ledPin == LED_MIN) {
if (analogRead(1) < 100) {
score++;
Serial.println(score);
if (delayMs > 150)
delayMs -= 30;
} else {
gameOver();
return true;
}
direction = UP;
ledPin++;
} else {
ledPin--;
}
return false;
}
void loop() {
digitalWrite(ledPin, HIGH);
if (direction == UP) {
if (handleUp())
return;
} else if (direction == DOWN) {
if (handleDown())
return;
}
digitalWrite(ledPin, LOW);
MFS.write(score);
delay(delayMs);
}
| bb271f4eadce98ee398227e60633b40d35c08a5b | [
"C++"
] | 1 | C++ | BhackNL/Meetup.TheGame | 0cb1137dbdc861c7c3134871a589efd150a8b61c | 634286978be75777b0938a6c5a8d263c888fd354 |
refs/heads/main | <file_sep># not edited yet
| 19e8c51df407ca2b2f8ccf927ef9e03df0045a33 | [
"Python"
] | 1 | Python | Harris-Kousiavelos/roza-teliki-ergasia | 6b2043405d74e691a20a99930de485d0d697aa51 | 7f38b33c69346056041bf2db4f3011fc572842f3 |
refs/heads/master | <repo_name>hare001/Mystery_UI_V5<file_sep>/Interface/AddOns/MysteryUI/MysteryUI.lua
--MysteryUI核心设置
local addonName, L = ...;
local function defaultFunc(L, key)
return key;
end
setmetatable(L, {__index=defaultFunc});
local _G = _G --解决头像在换类似天赋,符文的时候出现暴雪禁用插件的情况。
--[[ 选项 ]]
local SellGreyCrap = true -- 是否自动出售灰色物品.
local HideHotKeys = false -- 是否隐藏快捷键和宏在技能栏里的文本
local HideClock = false -- 是否隐藏暴雪时钟
--local checkthrown = true -- 是否检毒药
local MoveWatchFrame = true -- 是否移动任务追踪框体
--头像布局切换设置:[PVP布局:/My pvp],[PVE布局:/My pve] 注意命令后面的大小写必须一致!
local function slashCommand(str)
if (str == 'pvp') then
MyUnitframesDB.PVE_Style = false
MyUnitframesDB.PVP_Style = true
StaticPopup_Show("RELOAD")
elseif(str == 'pve') then
MyUnitframesDB.PVE_Style = true
MyUnitframesDB.PVP_Style = false
StaticPopup_Show("RELOAD")
elseif(str == 'bz') then
MyUnitframesDB = {}
StaticPopup_Show("RELOAD")
end
end
local eventframe = CreateFrame'Frame'
eventframe:RegisterEvent('ADDON_LOADED')
eventframe:SetScript('OnEvent', function(self, event, name)
if(name ~= "MysteryUI") then return end
self:UnregisterEvent('ADDON_LOADED')
SLASH_MysteryUI1 = '/My'
SlashCmdList["MysteryUI"] = function(str) slashCommand(str) end
end)
StaticPopupDialogs["RELOAD"] = {
text = L["切换布局你需要重新加载插件。"],
OnAccept = function()
ReloadUI()
end,
OnCancel = function() end ,
button1 = ACCEPT,
button2 = CANCEL,
timeout = 0,
whileDead = 1,
}
--[[ 添加命令 ]]
SlashCmdList["FRAME"] = function() print(GetMouseFocus():GetName()) end
SLASH_FRAME1 = "/frame"--输入此命令检查鼠标位置框体的名称
SlashCmdList["GETPARENT"] = function() print(GetMouseFocus():GetParent():GetName()) end
SLASH_GETPARENT1 = "/gp"
SLASH_GETPARENT2 = "/parent"--输入次命令用来检查鼠标位置框体的父框的名称
SlashCmdList["RELOADUI"] = function() ReloadUI() end
SLASH_RELOADUI1 = "/rl"--重载命令
SlashCmdList["RCSLASH"] = function() DoReadyCheck() end
SLASH_RCSLASH1 = "/rc"--就位确认
SlashCmdList["TICKET"] = function() ToggleHelpFrame() end
SLASH_TICKET1 = "/gm"--找GM的命令
--加载配置
local SetupUI = function()
SetCVar("chatStyle", "classic")
SetCVar("chatMouseScroll", 1)
SetCVar("nameplateShowFriends", 0)
SetCVar("nameplateShowEnemyTotems", 1)
SetCVar("ShowClassColorInNameplate", 1)
SetCVar("autoSelfCast", 1)
SetCVar("rotateMinimap", 0)
SetCVar("UnitNameOwn", 1)
SetCVar("UnitNameNPC", 1)
SetCVar("UnitNameNonCombatCreatureName", 0)
SetCVar("UnitNamePlayerPVPTitle", 1)
SetCVar("UnitNameFriendlyPlayerName", 1)
SetCVar("UnitNameFriendlyPetName", 1)
SetCVar("UnitNameFriendlyGuardianName", 0)
SetCVar("UnitNameFriendlyTotemName", 1)
SetCVar("UnitNameEnemyPlayerName", 1)
SetCVar("UnitNameEnemyPetName", 1)
SetCVar("UnitNameEnemyGuardianName", 1)
SetCVar("UnitNameEnemyTotemName", 1)
SetCVar("cameraDistanceMax", 50)
SetCVar("cameraDistanceMaxFactor", 3.4)
SetCVar("screenshotQuality", 8)
SetCVar("lootUnderMouse", 1)
SetCVar("UberTooltips", 1)
SetCVar("showArenaEnemyFrames", 0)
SetCVar("alwaysShowActionBars", 1)
SetCVar("consolidateBuffs",0)
SetCVar("buffDurations",1)
-- SetCVar("useUiScale", 1)
-- SetCVar("uiScale", min(2, max(.9, 768/string.match(({GetScreenResolutions()})[GetCurrentResolution()], "%d+x(%d+)"))))
ToggleChatColorNamesByClassGroup(true, "SAY")
ToggleChatColorNamesByClassGroup(true, "EMOTE")
ToggleChatColorNamesByClassGroup(true, "YELL")
ToggleChatColorNamesByClassGroup(true, "GUILD")
ToggleChatColorNamesByClassGroup(true, "GUILD_OFFICER")
ToggleChatColorNamesByClassGroup(true, "OFFICER")
ToggleChatColorNamesByClassGroup(true, "GUILD_ACHIEVEMENT")
ToggleChatColorNamesByClassGroup(true, "ACHIEVEMENT")
ToggleChatColorNamesByClassGroup(true, "WHISPER")
ToggleChatColorNamesByClassGroup(true, "PARTY")
ToggleChatColorNamesByClassGroup(true, "PARTY_LEADER")
ToggleChatColorNamesByClassGroup(true, "RAID")
ToggleChatColorNamesByClassGroup(true, "RAID_LEADER")
ToggleChatColorNamesByClassGroup(true, "RAID_WARNING")
ToggleChatColorNamesByClassGroup(true, "BATTLEGROUND")
ToggleChatColorNamesByClassGroup(true, "BATTLEGROUND_LEADER")
ToggleChatColorNamesByClassGroup(true, "CHANNEL1")
ToggleChatColorNamesByClassGroup(true, "CHANNEL2")
ToggleChatColorNamesByClassGroup(true, "CHANNEL3")
ToggleChatColorNamesByClassGroup(true, "CHANNEL4")
ToggleChatColorNamesByClassGroup(true, "CHANNEL5")
setupUI = true
ReloadUI()
end
StaticPopupDialogs["SETUP_UI"] = {
text = L["第一次使用MysteryUI_V5你需要重新加载插件。"],
button1 = ACCEPT,
button2 = CANCEL,
OnAccept = SetupUI,
timeout = 0,
whileDead = 1,
hideOnEscape = 1,
}
local frame = CreateFrame("Frame")
frame:RegisterEvent("PLAYER_ENTERING_WORLD")
frame:SetScript("OnEvent", function(self, event, addon)
self:UnregisterEvent(event)
if not setupUI then
StaticPopup_Show("SETUP_UI")
end
end)
-- ---DBM等插件美化的背景材质设定--
-- CreateBG = function(parent, noparent)
-- local bg = CreateFrame('Frame', nil, noparent and UIParent or parent)
-- bg:SetPoint('TOPLEFT', parent, 'TOPLEFT', -2, 2)
-- bg:SetPoint('BOTTOMRIGHT', parent, 'BOTTOMRIGHT', 2, -2)
-- bg:SetFrameLevel(parent:GetFrameLevel()-1 > 0 and parent:GetFrameLevel()-1 or 0)
-- bg:SetBackdrop({
-- bgFile = [=[Interface\ChatFrame\ChatFrameBackground]=],
-- edgeFile = [=[Interface\ChatFrame\ChatFrameBackground]=],
-- edgeSize = 1,
-- insets = { left = 1, right = 1, top = 1, bottom = 1}
-- })
-- bg:SetBackdropColor(0, 0, 0, .65)
-- bg:SetBackdropBorderColor(.35, .3, .3, 1)
-- bg.border = CreateFrame("Frame", nil, bg)
-- bg.border:SetPoint("TOPLEFT", 1, -1)
-- bg.border:SetPoint("BOTTOMRIGHT", -1, 1)
-- bg.border:SetFrameLevel(bg:GetFrameLevel())
-- bg.border:SetBackdrop({
-- edgeFile = [=[Interface\ChatFrame\ChatFrameBackground]=],
-- edgeSize = 1,
-- insets = { left = 1, right = 1, top = 1, bottom = 1}
-- })
-- bg.border:SetBackdropBorderColor(0, 0, 0, 1)
-- bg.border2 = CreateFrame("Frame", nil, bg)
-- bg.border2:SetPoint("TOPLEFT", -1, 1)
-- bg.border2:SetPoint("BOTTOMRIGHT", 1, -1)
-- bg.border2:SetFrameLevel(bg:GetFrameLevel())
-- bg.border2:SetBackdrop({
-- edgeFile = [=[Interface\ChatFrame\ChatFrameBackground]=],
-- edgeSize = 1,
-- insets = { left = 1, right = 1, top = 1, bottom = 1}
-- })
-- bg.border2:SetBackdropBorderColor(0, 0, 0, 0.9)
-- return bg
-- end
--[[ 隐藏快捷键和宏在技能栏里的文本 ]]
if (HideHotKeys == true) then
local format = string.format;
local match = string.match;
local upper = strupper;
local _G = getfenv(0);
local f = {"ActionButton%d", "MultiBarBottomLeftButton%d", "MultiBarBottomRightButton%d", "MultiBarRightButton%d",
"MultiBarLeftButton%d"}
do
for k, v in pairs(f) do
for i = 1, 12 do
local str = format(v, i);
_G[str.."HotKey"].Show = function() end;
_G[str.."Name"].Show = function() end;
_G[str.."Name"]:Hide();
end
end
end
end
--隐藏错误提示(我没有目标等等)
local event = CreateFrame"Frame"
local dummy = function() end
UIErrorsFrame:UnregisterEvent"UI_ERROR_MESSAGE"
event.UI_ERROR_MESSAGE = function(self, event, error)
if(not stuff[error]) then
UIErrorsFrame:AddMessage(error, 1, .1, .1)
end
end
event:RegisterEvent"UI_ERROR_MESSAGE"
--[[ 自动出售垃圾 ]]
local function OnEvent()
for bag=0,4 do
for slot=0,GetContainerNumSlots(bag) do
local link = GetContainerItemLink(bag, slot)
if link and select(3, GetItemInfo(link)) == 0 then
ShowMerchantSellCursor(1)
UseContainerItem(bag, slot)
end
end
end
end
local f = CreateFrame("Frame")
f:RegisterEvent("MERCHANT_SHOW")
f:SetScript("OnEvent", OnEvent)
if MerchantFrame:IsVisible() then OnEvent() end
--[[ 修理 - 变量是可以改变的,只要你想 ]]--
local iRepair_Chatter = true
local iRepair_GRF = true
local iRepair_ROGR = false
--[[ AUTO REPAIR SERVICES ]]--
local iRepair = CreateFrame("Frame", "iRepair")
iRepair:RegisterEvent("MERCHANT_SHOW")
iRepair:SetScript("OnEvent", function()
local cost = GetRepairAllCost()
local function iRepair_Guild()
if iRepair_Chatter then
print(L[" 公会银行自动修理费用: "].. GetCoinTextureString(cost) )
end
RepairAllItems(1)
end
local function iRepair_Self()
if iRepair_Chatter then
print(L[" 你支付的修理费用: "].. GetCoinTextureString(cost) )
end
RepairAllItems()
end
if IsModifierKeyDown() then
return
elseif CanMerchantRepair() and cost ~= 0 then
if iRepair_GRF and CanGuildBankRepair() and cost <= GetGuildBankMoney() and (cost <= GetGuildBankWithdrawMoney() or GetGuildBankWithdrawMoney() == -1) then
if iRepair_ROGR and GetNumRaidMembers() ~= 0 then
iRepair_Guild()
elseif not iRepair_ROGR then
iRepair_Guild()
elseif cost <= GetMoney() then
iRepair_Self()
else
print(L[" 公会没有足够的资金修理,请尝试手动。"])
end
elseif cost <= GetMoney() then
iRepair_Self()
else
print(L[" 你没有足够的资金修理。你需要 "]..GetCoinTextureString(cost)..L[" 的修理费。"])
end
end
end)
--[[ 隐藏暴雪时钟]]
if (HideClock == true) then
local name, addon = ...
local event1, event2 = "ADDON_LOADED", "PLAYER_ENTERING_WORLD"
local frame = CreateFrame("Frame")
frame:RegisterEvent(event1)
frame:RegisterEvent(event2)
frame:SetScript("OnEvent", function(self, event, arg1)
if((event == event2 and name == arg1) or (event==event1)) then
self:UnregisterEvent(event)
LoadAddOn("Blizzard_TimeManager")
TimeManagerClockButton:SetScript("OnUpdate", nil)
TimeManagerClockButton:SetScript("OnEvent", nil)
TimeManagerClockButton:SetScript("OnShow", function(self)
self:Hide()
end)
TimeManagerClockButton:Hide()
if(event == event1) then
self:RegisterEvent(event)
end
end
end)
end
---------------------------
--[[移动任务追踪框体]]
---------------------------
if (MoveWatchFrame == true) then
local pos = { a1 = "RIGHT", a2 = "RIGHT", af = "UIParent", x = -100, y = -70 }
local watchframeheight = 450
--提示图标功能
local function QWFM_Tooltip(self)
GameTooltip:SetOwner(self, "ANCHOR_TOP")
GameTooltip:AddLine(L["拖动!"], 0, 1, 0.5, 1, 1, 1)
GameTooltip:Show()
end
--让任务追踪框体可以移动
local wf = WatchFrame
wf:SetClampedToScreen(true)
wf:SetMovable(true)
wf:SetUserPlaced(true)
wf:ClearAllPoints()
wf.ClearAllPoints = function() end
wf:SetPoint(pos.a1,pos.af,pos.a2,pos.x,pos.y)
wf.SetPoint = function() end
wf:SetHeight(watchframeheight)
local wfh = WatchFrameHeader
wfh:EnableMouse(true)
wfh:RegisterForDrag("LeftButton")
wfh:SetHitRectInsets(-15, -15, -5, -5)
wfh:SetScript("OnDragStart", function(s)
local f = s:GetParent()
f:StartMoving()
end)
wfh:SetScript("OnDragStop", function(s)
local f = s:GetParent()
f:StopMovingOrSizing()
end)
wfh:SetScript("OnEnter", function(s)
QWFM_Tooltip(s)
end)
wfh:SetScript("OnLeave", function(s)
GameTooltip:Hide()
end)
end
--[[ 盗贼毒药检查 ]]
-- if(select(2,UnitClass("player")) ~= "ROGUE" or UnitLevel("player") < 20) then return end
-- local f = CreateFrame("Frame")
-- f:RegisterEvent("PLAYER_ENTERING_WORLD")
-- f:RegisterEvent("UPDATE_STEALTH")
-- f:RegisterEvent("PLAYER_LEAVE_COMBAT")
-- f:SetScript("OnEvent", function()
-- local main, _, _, off, _, _, thrown = GetWeaponEnchantInfo()
-- if not UnitInVehicle("player") and(not main or not off or(not thrown and checkthrown == true)) then
-- --DEFAULT_CHAT_FRAME:AddMessage(L["##### 没毒药了 #####"], 1.0,0.96,0.41) --聊天框提示.
-- UIErrorsFrame:AddMessage(L["##### 没毒药了 #####"], 1.0, 0.96, 0.41, 1.0); --屏幕醒目提示.
-- end
-- end)
-------------
local f = CreateFrame("Frame")
f:SetScript("OnEvent", function()
SetCVar("cameraDistanceMax", 50)
SetCVar("CameraDistanceMaxFactor", 3.4)
end)
f:RegisterEvent("PLAYER_ENTERING_WORLD")
--离开战斗回收插件内存
local eventcount = 0
local cf = CreateFrame("Frame")
cf:RegisterAllEvents()
cf:SetScript("OnEvent", function(self, event)
eventcount = eventcount + 1
if InCombatLockdown() then return end
if eventcount > 6000 or event == "PLAYER_ENTERING_WORLD" or event == "PLAYER_REGEN_ENABLED" then
collectgarbage("collect")
eventcount = 0
end
end)
| 470af6aafd0fd317c75049ce8e8324d2ea01370c | [
"Lua"
] | 1 | Lua | hare001/Mystery_UI_V5 | c38fc1844342a6b7325b35521dfed50863f7e477 | 05ce7e142faa58048a68f9259a630bb6a8f8b7d4 |
refs/heads/master | <repo_name>arnerak/pvgnaloader<file_sep>/pvgnaloader.py
import requests
import subprocess
import os
import string
import json
import math
settings = json.load(open('pvgnaloader.ini'))
res = settings['resolution']
links = settings['links']
PVGNALOGIN = 'https://pvgna.com/login'
FINDTOKENL = 'name="authenticity_token" value="'
FINDTOKENR = '"'
FINDVLINKL = ';'
FINDVLINKR = res + '.m3u8'
FINDVNAMEL = '<h1 class="ui header">'
FINDVNAMER = '</h1>'
FINDCHPTRL = '<a class="link step" href="'
FINDCHPTRR = '"'
def find_between(s, left, right):
start = s.find(left) + len(left)
end = s.find(right, start)
return s[start:end]
def find_between_r(s, right, left):
end = s.rindex(right)
start = s.rindex(left, 0, end) + len(left)
return s[start:end]
def sanitize_filename(s):
valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
return ''.join(c for c in s if c in valid_chars)
def print_progressbar(iteration, total, prefix = '', suffix = '', decimals = 1, length = 50):
blocks = ["", "▌"]
percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
filledLength = int(length * iteration // total)
blockindex = math.floor(((length * iteration / total) - filledLength) * len(blocks))
bar = '█' * filledLength + blocks[blockindex] + '-' * (length - filledLength - len(blocks[blockindex]))
print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = '\r')
if iteration == total:
print()
print("Loading pvgna...")
s = requests.Session()
adapter = requests.adapters.HTTPAdapter(max_retries=10)
s.mount('https://', adapter)
s.mount('http://', adapter)
r = s.get(PVGNALOGIN)
token = find_between(r.text, FINDTOKENL, FINDTOKENR)
payload = {
'utf8': '✓',
'authenticity_token': token,
'user[email]': settings['email'],
'user[password]': settings['password'],
'commit': 'Log In'
}
print("Logging in...")
r = s.post(PVGNALOGIN, data=payload)
if r.text.find('Invalid email or password.') != -1:
print('Login incorrect')
exit()
vlinks = []
vnames = []
chapterlinks = links[:]
if settings['crawlchapters']:
for idx,link in enumerate(links):
print('\rFetching chapters... [%s]' % (str(idx+1)+'/'+str(len(links))), end='\r')
r = s.get(link)
restsrc = r.text
while restsrc.find(FINDCHPTRL) != -1:
chapterlink = 'https://pvgna.com' + find_between(restsrc, FINDCHPTRL, FINDCHPTRR)
restsrc = restsrc[restsrc.find(FINDCHPTRL) + len(FINDCHPTRL):]
if chapterlink not in chapterlinks:
chapterlinks.append(chapterlink)
print()
links = chapterlinks
for idx,link in enumerate(links):
print('\rFetching video links... [%s]' % (str(idx+1)+'/'+str(len(links))), end='\r')
r = s.get(link)
vlink = find_between_r(r.text, FINDVLINKR, FINDVLINKL)
vname = find_between(r.text, FINDVNAMEL, FINDVNAMER)
vname = sanitize_filename(vname)
vlinks.append(vlink)
vnames.append(vname)
print()
idx = 0
while(idx < len(vnames)):
mp4_name = 'videos/' + vnames[idx] + '.mp4'
if os.path.isfile(mp4_name):
print('"' + vnames[idx] + '" already exists.')
del vlinks[idx]
del vnames[idx]
else:
idx = idx + 1
if len(vnames) == 0:
print('Nothing to download.')
exit()
print('Downloading videos...')
for idx,link in enumerate(vlinks):
r = s.get(link + res + '.m3u8')
lines = r.text.splitlines()
ts_name = 'videos/' + vnames[idx] + '.ts'
with open(ts_name, 'wb') as outfile:
for idx2,ts_link in enumerate(lines):
if (ts_link.endswith('.ts')):
r = s.get(link + ts_link, stream=True)
for chunk in r:
outfile.write(chunk)
print_progressbar(idx*100+100/len(lines)*(idx2), len(vlinks)*100, str(idx+1)+'/'+str(len(vlinks)))
print_progressbar(100, 100, str(len(vlinks))+'/'+str(len(vlinks)))
for idx,vname in enumerate(vnames):
print('\rConverting videos... [%s]' % (str(idx+1)+'/'+str(len(vnames))), end='\r')
ts_name = 'videos/' + vname + '.ts'
mp4_name = 'videos/' + vname + '.mp4'
with open(os.devnull, 'w') as f:
subprocess.call('ffmpeg -y -i "' + ts_name + '" -acodec copy -vcodec copy "' + mp4_name + '"', shell=True, stdout=f, stderr=subprocess.STDOUT)
os.remove(ts_name)
print()
print("Done.")<file_sep>/README.md
# pvgnaloader
Clone this repository and install dependencies as shown.
`git clone https://github.com/arnibold/pvgnaloader`
Fill in your [pvgna](http://pvgna.com) credentials in pvgnaloader.ini and run with
`python pvgnaloader.py`
### pvgnaloader.ini
* email: your pvgna registered email address.
* password: <PASSWORD>.
* resolution: choose from 1080p, 720p, 480p, 360p.
* crawlchapters: set to true if you want pvgnaloader to automatically download all chapters from a single link.
* links: list of desired videos. If crawlchapters is true, only enter a single link of each guide.
## Dependencies
### Python Requests
Clone repository:
`git clone git://github.com/requests/requests.git`
Install:
`cd requests`
`pip install .`
[Installation guide](http://docs.python-requests.org/en/master/user/install/)
### ffmpeg
Download [here](https://ffmpeg.zeranoe.com/builds/) and place ffmpeg.exe in pvgnaloader folder.<file_sep>/pvgnaloader.ini
{
"email": "",
"password": "",
"resolution": "720p",
"crawlchapters": false,
"links": [
"https://pvgna.com/dota2/welcome-to-dota-2-introduction",
"https://pvgna.com/dota2/how-to-raise-mmr-with-pudge-introduction-basic-concepts",
"https://pvgna.com/dota2/axe-guide-introduction-basic-mechanics"
]
} | 3f0d500e42c431c82d0ee5c281bb8cb006f44ef5 | [
"Markdown",
"Python",
"INI"
] | 3 | Python | arnerak/pvgnaloader | 2546003b3b70611abf4d59c750c53d3598a7d219 | 204329593915d4421be4e5de218c7d77c13038ff |
refs/heads/master | <repo_name>vladislav-i/reverseWords<file_sep>/java.js
//javascript
$(document).ready(function(){
$("button").click(function(){
var str=$("#words").val();
var stack = new Stack();
str= str.split("");
for (var i in str) {
stack.push(str[i]);
}
for(str=""; !stack.isEmpty(); str+=stack.pop());
//add to div tag
$("div").append(str+" ");
});
});
function Stack () {
var head = null; //set to null to know that it is empty
//push takes one parameter and returns one parameter
this.push = function(obj) {
//brings in an object, create an object locally called node
var node = {}; //pointed to data storage
node.data = obj; // obj is a data of node
node.next = head;
head = node; //inserted node onto my stack
};
this.pop = function() {
var temp = head; //holds value of previous head (nodes)
head = temp.next;
return temp.data;
};
this.isEmpty = function () {
return head === null; //if head is null means its empty (return true)
};
}
| f14c9eb847ed073e751065fd3e1fbdbe9a2783cb | [
"JavaScript"
] | 1 | JavaScript | vladislav-i/reverseWords | 014199198ccd666e1c9cbc713aa4a58a94bfa2c4 | 257d3dcddda364b5b5e849d2b2032de33d40198a |
refs/heads/master | <repo_name>murtazasamiwala/heart_predict<file_sep>/Heart/models.py
#%%
#import statements
import pandas as pd
import numpy as np
from utils import Explore
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import log_loss
from sklearn.linear_model import LogisticRegression
#%%
filepath_train="C:\\Users\\user\\Desktop\\Python work\\Home stuff\\Heart\\Heart\\data\\train_values.csv"
filepath_labels="C:\\Users\\user\\Desktop\\Python work\\Home stuff\\Heart\\Heart\\data\\train_labels.csv"
filepath_test="C:\\Users\\user\\Desktop\\Python work\\Home stuff\\Heart\\Heart\\data\\test_values.csv"
#%%
df1=pd.read_csv(filepath_train)
df1.head()
#%%
df2=pd.read_csv(filepath_labels)
df=df1.merge(df2)
df.head()
#%%
continous=['resting_blood_pressure','serum_cholesterol_mg_per_dl','oldpeak_eq_st_depression','age','max_heart_rate_achieved']
categorical=['slope_of_peak_exercise_st_segment','thal','chest_pain_type','num_major_vessels','fasting_blood_sugar_gt_120_mg_per_dl','resting_ekg_results','sex','exercise_induced_angina']
#%%
df.drop(columns=['patient_id'],inplace=True)
#%%
X=df.iloc[:,:13]
y=df['heart_disease_present']
#%%
X_d=pd.get_dummies(X,drop_first=True)
#%%
rfc=RandomForestClassifier()
dtc=DecisionTreeClassifier()
#%%
X_test=pd.read_csv(filepath_test)
#%%
X_test_d=pd.get_dummies(X_test.drop(columns=['patient_id']),drop_first=True)
#%%
rfc.fit(X_d,y)
#%%
rfc_results=pd.DataFrame(X_test['patient_id'])
#%%
rfc_results['heart_disease_present']=rfc.predict_proba(X_test_d)[:,1]
#%%
rfc_results.to_csv(r'C:\Users\user\Desktop\Python work\Home stuff\Heart\Heart\results\rfc_results.csv',index=False)
#%%
dtc.fit(X_d,y)
#%%
dtc_results=pd.DataFrame(X_test['patient_id'])
#%%
dtc_results['heart_disease_present']=dtc.predict_proba(X_test_d)[:,1]
#%%
dtc_results.to_csv(r'C:\Users\user\Desktop\Python work\Home stuff\Heart\Heart\results\dtc_results.csv',index=False)
#%%
lr=LogisticRegression()
lr.fit(X_d,y)
#%%
lr_results=pd.DataFrame(X_test['patient_id'])
lr_results['heart_disease_present']=lr.predict_proba(X_test_d)[:,1]
#%%
lr_results.to_csv(r'C:\Users\user\Desktop\Python work\Home stuff\Heart\Heart\results\lr_results.csv',index=False)<file_sep>/Heart/utils.py
import os
import pandas as pd
def make_submission(model, train, labels, test, fname, result_path = '..\\Heart\\results', test_values = pd.read_csv("..\\Heart\\data\\test_values.csv")):
"Function to make submission given model and datasets."
csv_file = fname + '.csv'
if csv_file in os.listdir(result_path):
print('{} already exists'.format(csv_file))
return
else:
model.fit(train,labels)
temp_df = pd.DataFrame(test_values['patient_id'])
if model.classes_[1]==1:
temp_df['heart_disease_present'] = model.predict_proba(test)[:, 1]
else:
temp_df['heart_disease_present'] = model.predict_proba(test)[:, 0]
temp_df.to_csv(result_path + '\\' + csv_file, index=False)
print('{} created'.format(csv_file))
return | d0c1851af1693948b0db1c81b882d9e90dc0604b | [
"Python"
] | 2 | Python | murtazasamiwala/heart_predict | 6509b746429bb17168f37c5c259f5c422eeb40e2 | 28961b8232fdfcbaf14bdf77233ef73291cf29a4 |
refs/heads/master | <file_sep># functionanalyser
[](https://github.com/Plagiatus/functionanalyser/releases/latest)


Lists the number of lines you have in your functions with a detailed breakdown on which commands you've used.
[Latest Release](https://github.com/Plagiatus/functionanalyser/releases/latest)
You can either run it without any arguments (e.g. through a doubleclick) to search through the folder (and its subfolders) the analyser located in or by giving the path as an argument when running it from the console.
Example: `.\FunctionAnalyser.exe C:\Users\<username>\AppData\Roaming\.minecraft\saves\world\datapacks`
<file_sep>using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
namespace FunctionAnalyser
{
class Program
{
static void Main(string[] args)
{
int linesTotal = 0;
int commandsTotal = 0;
int commentsTotal = 0;
int emptyTotal = 0;
int filesTotal = 0;
int entitySelectorsTotal = 0;
int nbtAccessTotal = 0;
string path = "./";
Dictionary<string, int> commandsUsed = new Dictionary<string, int>();
Dictionary<string, int> commandsUsedAfterExecute = new Dictionary<string, int>();
if (args.Length > 0)
{
path = args[0];
}
Console.WriteLine("Analysing all function files in path " + path + " ...\n\n");
string[] files = Directory.GetFiles(path, "*", SearchOption.AllDirectories);
foreach (string file in files)
{
if (file.EndsWith(".mcfunction"))
{
filesTotal++;
string[] lines = File.ReadAllLines(file);
linesTotal += lines.Length;
foreach (string line in lines)
{
if (line.Length == 0)
{
emptyTotal++;
}
else
{
if (Char.IsWhiteSpace(line, 0))
{
emptyTotal++;
}
else if (line[0] == '#')
{
commentsTotal++;
}
else
{
commandsTotal++;
string command = line.Split(' ')[0];
if (command == "execute")
{
string[] tmp = line.Split(new string[] {"run "}, StringSplitOptions.RemoveEmptyEntries);
if (tmp.Length > 1)
{
command = tmp[1].Split(' ')[0];
if (commandsUsedAfterExecute.ContainsKey(command))
{
commandsUsedAfterExecute[command]++;
}
else
{
commandsUsedAfterExecute.Add(command, 1);
}
}
}
if (commandsUsed.ContainsKey(command))
{
commandsUsed[command]++;
}
else
{
commandsUsed.Add(command, 1);
}
if (line.Contains("@e"))
{
entitySelectorsTotal++;
}
if (line.Contains("{") && (command != "tellraw" && command != "title") || command == "data" || line.StartsWith("execute store result entity"))
{
nbtAccessTotal++;
}
}
}
}
}
}
string result = String.Format("Found {0} mcfunction files that include a total amount of {1} lines. Of these lines\n"
+ "+ {2} are commands ({5}%)\n"
+ "+ {3} are comments ({6}%)\n"
+ "+ {4} are empty ({7}%)\n\n",
new object[] { filesTotal, linesTotal, commandsTotal, commentsTotal, emptyTotal,
Math.Round((float)commandsTotal * 100 / linesTotal,2), Math.Round((float)commentsTotal * 100 / linesTotal,2), Math.Round((float)emptyTotal * 100 / linesTotal,2) });
result += "-------------------------------\n\nUsed Commands\n";
List<KeyValuePair<string, int>> commandsList = commandsUsed.ToList();
commandsList.Sort((pair1, pair2) => pair2.Value.CompareTo(pair1.Value));
// List<KeyValuePair<string, int>> executeList = commandsUsedAfterExecute.ToList();
// executeList.Sort((pair1, pair2) => pair2.Value.CompareTo(pair1.Value));
foreach (KeyValuePair<string, int> commandPair in commandsList)
{
result += "+ " + commandPair.Key + ": " + commandPair.Value + " (" + Math.Round((float)commandPair.Value * 100 / commandsTotal, 2) + "%)";
if(commandsUsedAfterExecute.ContainsKey(commandPair.Key)){
result += " (" + commandsUsedAfterExecute[commandPair.Key] + " behind execute)";
}
result += "\n";
}
result += "\n-------------------------------\n\nPerformance Information\n";
float averageEntitySelector = (float)Math.Round((float)entitySelectorsTotal / filesTotal, 2);
float averageNBTAccess = (float)Math.Round((float)nbtAccessTotal / filesTotal, 2);
result += "Usage of @e selectors: " + entitySelectorsTotal + ", that's an average of " + averageEntitySelector + " per file.\n";
result += "Amount of NBT access: " + nbtAccessTotal + ", that's an average of " + averageNBTAccess + " per file.\n";
Console.WriteLine(result);
Console.WriteLine("Press any key to close");
Console.ReadKey();
}
}
}
| 062bda46ac97e8f2052a94894ada6751ed9a2798 | [
"Markdown",
"C#"
] | 2 | Markdown | Plagiatus/functionanalyser | 342327acd7b307bfc8f4d90b6db2971ae38f9301 | 122e0c3acd9c2aae7da739a9b47ae519ffb73500 |
refs/heads/master | <file_sep># react-native-project-template
This is react native project template, it have structured files and some of the basic libraries
<file_sep>import React, { Component } from "react";
import {
Container,
Header,
Title,
Content,
Button,
Icon,
Left,
Right,
View,
Body,
Text,
ListItem,
List
} from "native-base";
import styles from "./styles";
class Page extends Component {
constructor(props) {
super(props);
this.state = {
};
}
componentDidMount(){
}
render() {
return (
<Container style={styles.container}>
<Header>
<Left>
<Button
transparent
onPress={() => this.props.navigation.navigate("Home")}
>
<Icon name="arrow-back" />
</Button>
</Left>
<Body><Title>Page name</Title></Body>
<Right />
</Header>
<Content padder>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Vero culpa veniam debitis velit dicta corporis est reiciendis fugit! Quod reiciendis ea neque illum reprehenderit aspernatur. Ab quas aspernatur unde voluptatem, totam recusandae molestias placeat porro aliquam dolor aut architecto maxime, eligendi saepe labore natus hic voluptates deleniti dolorum ut? Adipisci.
</Content>
</Container>
);
}
}
export default Page;
<file_sep>/**
*
* Firebase file is created to init firebase to use it on whole app
*
*/
import Firebase from 'firebase'
import firebaseConfig from '../config/firebase_config'
Firebase.initializeApp(firebaseConfig)
export default Firebase
<file_sep>/**
*
* Database file is created to create, read, update, display data from/to database in firebase
*
*/
import Firebase from './Firebase'
import { getTimeFromDate } from '../helpers'
let db = Firebase.database();
export default db;
export function getDevices () {
return db.ref('devices');
}
export function getDevicesByIds (ids) {
return new Promise(resolve => {
var promises = ids.filter(id => !! id).map(key => db.ref("devices").child(key).once("value"));
Promise.all(promises).then(snapshots => {
resolve(
snapshots
.filter(snapshot => !! snapshot.val())
.map(snapshot => snapshot.val())
)
});
})
}
export function changeDeviceStatus (deviceId, isOn) {
return db.ref('devices').child(deviceId).child('status').set(isOn ? 'on' : 'off');
}
export function changeDeviceActiveFrom (deviceId, time) {
return db.ref('devices').child(deviceId).child('fromTime').set(time);
}
export function changeDeviceActiveTo (deviceId, time) {
return db.ref('devices').child(deviceId).child('toTime').set(time);
}
export function saveDevice (device) {
return db.ref('devices').child(device.id).set(device);
}
export function getDevice(deviceId) {
return db.ref('devices').child(deviceId);
}
export function saveDeviceData(device) {
if (! device.id) {
var newPostRef = db.ref('devices').push();
device.id = newPostRef.key;
}
return new Promise(resolve => {
db.ref('devices').child(device.id).set(device).then(() => resolve(device))
})
}
export function getPages () {
return db.ref('pages');
}
export function getPage(pageId) {
return db.ref('pages').child(pageId);
}
<file_sep>export default {
container: {
backgroundColor: "#FFF"
},
mainTitle: {
flex: 1,
fontSize: 26,
fontWeight: '600',
marginTop: 10,
marginBottom: 10,
color: '#c52b36',
textAlign: 'center'
},
mainContent: {
fontSize: 18,
color: '#323232',
marginBottom: 10,
},
mb10: {
marginBottom: 10
}
};
<file_sep>import React from "react";
import { Root } from "native-base";
import { StackNavigator, DrawerNavigator } from "react-navigation";
import Home from "./screens/home/";
import Settings from "./screens/settings/";
import Page from "./screens/page/";
import SideBar from "./screens/sidebar";
const Drawer = DrawerNavigator(
{
Home: { screen: Home },
Settings: { screen: Settings },
Page: { screen: Page },
},
{
initialRouteName: "Home",
contentOptions: {
activeTintColor: "#e91e63"
},
contentComponent: props => <SideBar {...props} />
}
);
const AppNavigator = StackNavigator(
{
Drawer: { screen: Drawer }
},
{
initialRouteName: "Drawer",
headerMode: "none"
}
);
export default () =>
<Root>
<AppNavigator />
</Root>;
<file_sep>import React, { Component } from "react";
import {
Container,
Header,
Title,
Content,
Button,
Icon,
Left,
Right,
Body,
Text,
ListItem,
List
} from "native-base";
import styles from "./styles";
class Settings extends Component {
constructor(props) {
super(props);
this.state = {
pages: []
};
}
componentDidMount(){
}
render() {
return (
<Container style={styles.container}>
<Header>
<Left>
<Button
transparent
onPress={() => this.props.navigation.navigate("DrawerOpen")}
>
<Icon name="menu" />
</Button>
</Left>
<Body>
<Title>Settings</Title>
</Body>
<Right />
</Header>
<Content>
<List>
return (
<ListItem
button
onPress={() => }
>
<Left>
<Text>
Page Name
</Text>
</Left>
<Right>
<Icon name="arrow-forward" style={{ color: "#999" }} />
</Right>
</ListItem>
)
</List>
</Content>
</Container>
);
}
}
export default Settings;
| e55fd874836edacb2aec58f78f88e93dc5f9a36a | [
"Markdown",
"JavaScript"
] | 7 | Markdown | shyqerigashi/react-native-project-template | 3bc10cfa67d79f5dcdc345575a0c150ae2a98244 | d31ca8119abfc99689f90cc79bb1a4c0592e6ef5 |
refs/heads/main | <file_sep>print("This is my first ever Git commit")
| 372f5c7fb8c8c66366207f6476f743ae6bf4e30a | [
"Python"
] | 1 | Python | justmedave254/Test | 4d43dc9ae81201e5ea67029bb012509ae807f086 | 8c854b3a0f5ceaaf73c2e9074f998b7efddeb9da |
refs/heads/master | <repo_name>xiaohaozi1212/MyFirstRepo<file_sep>/b2.java
package ca.myseneca.model;
public class b {
public static void main(String[] args) throws Exception {
System.out.println("input 2st number is : ");
}
}
| bce69f6f5761eacc85387eb5e488ca2b054a4a3e | [
"Java"
] | 1 | Java | xiaohaozi1212/MyFirstRepo | 6ecf7123e28d78ca6d1817daba846c584d6c78cc | 3416bc185177c2c9d8db41610ad52b6af8b64bac |
refs/heads/master | <repo_name>futureLix/CustomProgressMaster<file_sep>/customprogressmaster/src/main/java/example/com/customprogressmaster/CustomProgress.java
package example.com.customprogressmaster;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.view.View;
/**
* 自定义进度
* Created by Lix on 2017-10-18.
*
* @author Lix
*/
@SuppressLint("DrawAllocation")
public class CustomProgress extends View {
/**
* 画笔对象的引用
*/
private Paint paint;
/**
* 中间进度百分比的字符串
*/
private int textRoundWidth;
/**
* 中间进度百分比的字符串的颜色
*/
private int textColor;
/**
* 中间进度百分比的字符串的字体
*/
private float textSize;
/**
* 圆环的宽度
*/
private float roundWidth;
/**
* 最大进度 默认100
*/
private int max;
/**
* 当前进度
*/
private int mProgress;
/**
* 是否显示中间的进度
*/
private boolean textIsDisplayable;
/**
* 背景颜色
*/
private int foreground;
/**
* 进度条颜色
*/
private int backgroundColor;
/**
* 获取圆中心
*/
// private int center;
/**
* 圆环的半径
*/
private int radius;
/**
* 文字
*/
private String text;
/**
* 获取自定义View的宽和高
*/
private float halfWidth;
private float halfHeight;
/**
* 显示进度数值
*/
private int mShowProgress;
/**
* 设置动态时间
*/
private int mShowProgressTime;
public CustomProgress(Context context) {
this(context, null);
}
public CustomProgress(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomProgress(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomProgress);
backgroundColor = typedArray.getInteger(R.styleable.CustomProgress_mBackGround, ContextCompat.getColor(context, R.color.progress_bg1));
foreground = typedArray.getInteger(R.styleable.CustomProgress_mForeGround, ContextCompat.getColor(context, R.color.progress_bg2));
max = typedArray.getInteger(R.styleable.CustomProgress_max, 100);
mProgress = typedArray.getInteger(R.styleable.CustomProgress_progress, 0);
text = typedArray.getString(R.styleable.CustomProgress_mText);
textColor = typedArray.getInteger(R.styleable.CustomProgress_mTextColor, ContextCompat.getColor(context, R.color.progress_bg3));
textSize = typedArray.getDimension(R.styleable.CustomProgress_mTextSize, 22);
mShowProgressTime = typedArray.getInteger(R.styleable.CustomProgress_mTime, 30);
roundWidth = typedArray.getFloat(R.styleable.CustomProgress_mRoundWidth, 10);
textRoundWidth = typedArray.getInteger(R.styleable.CustomProgress_mTextRoundWidth, 0);
textIsDisplayable = typedArray.getBoolean(R.styleable.CustomProgress_mTextIsDisplayable, true);
typedArray.recycle();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint = new Paint();
halfWidth = getMeasuredWidth() / 2;
halfHeight = getMeasuredHeight() / 2;
radius = (int) (halfWidth - roundWidth / 2);
drawBackground(canvas);
drawText(canvas);
drawProgress(canvas);
}
/**
* 画最外层的大圆环
*
* @param canvas
*/
private void drawBackground(Canvas canvas) {
paint.setColor(foreground);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(roundWidth);
paint.setAntiAlias(true);
canvas.drawCircle(halfWidth, halfWidth, radius, paint);
}
/***
* 绘制进度值
* @param canvas
*/
private void drawProgress(Canvas canvas) {
/**
* 画圆弧 ,画圆环的进度
*/
paint.setStrokeWidth(roundWidth);
paint.setColor(backgroundColor);
RectF oval = new RectF(halfWidth - radius, halfWidth - radius, halfWidth + radius, halfWidth + radius);
paint.setStyle(Paint.Style.STROKE);
canvas.drawArc(oval, -90, 360 * mProgress / max, false, paint);
}
/***
* 绘制文本
* @param canvas
*/
private void drawText(Canvas canvas) {
paint.setColor(textColor);
paint.setTextSize(textSize);
paint.setStrokeWidth(textRoundWidth);
paint.setTypeface(Typeface.DEFAULT);
int percent = (int) ((mProgress / (float) max) * 100);
if (textIsDisplayable && percent > -1) {
canvas.drawText(percent + "%", halfWidth - paint.measureText(percent + "%") / 2, halfHeight - (paint.ascent() + paint.descent()) / 2, paint);
} else {
if (null != text) {
canvas.drawText(text, halfWidth - paint.measureText(text) / 2, halfHeight - (paint.ascent() + paint.descent()) / 2, paint);
}
}
}
/**
* 设置字体大小
*
* @param textSize
*/
public void setTextSize(float textSize) {
this.textSize = textSize;
}
/**
* 设置宽度
*
* @param roundWidth
*/
public void setRoundWidth(float roundWidth) {
this.roundWidth = roundWidth;
}
/**
* 设置圆角
*
* @param radius
*/
public void setRadius(int radius) {
this.radius = radius;
}
/**
* 设置最大值
*
* @param max
*/
public void setMax(int max) {
this.max = max;
}
/**
* 设置文本提示信息
*
* @param text
*/
public void setText(String text) {
this.text = text;
}
/**
* 设置进度条的颜色值
*
* @param color
*/
public void setForeground(int color) {
this.foreground = color;
}
/**
* 设置进度条的背景色
*/
@Override
public void setBackgroundColor(int color) {
this.backgroundColor = color;
}
/***
* 设置文本的大小
*/
public void setTextSize(int size) {
this.textSize = size;
}
/**
* 设置文本的颜色值
*
* @param color
*/
public void setTextColor(int color) {
this.textColor = color;
}
/**
* 设置进度值
*
* @param progress
*/
public void setProgress(int progress) {
if (progress > 100) {
progress = 100;
}
if (progress < 0) {
progress = 0;
}
mProgress = progress;
postInvalidate();
}
public int getMax() {
return max;
}
public int getProgress() {
return mProgress;
}
/**
* 是否显示中间的进度字体
*
* @return
*/
public boolean isTextIsDisplayable() {
return textIsDisplayable;
}
/**
* 获取是否显示中间的进度字体
*
* @param textIsDisplayable
*/
public void setTextIsDisplayable(boolean textIsDisplayable) {
this.textIsDisplayable = textIsDisplayable;
}
/**
* 动画时长
*
* @param showProgressTime
*/
public void setShowProgressTime(int showProgressTime) {
mShowProgressTime = showProgressTime;
}
/**
* 实际展示总进度
*
* @param progress
*/
public void setmShowProgress(int progress) {
mShowProgress = progress;
new Thread(runnable).start();//实现进度增长的动画效果
}
/**
* 动画增长
*/
Runnable runnable = new Runnable() {
@Override
public void run() {
Message message = handler.obtainMessage();
try {
for (int i = 1; i <= mShowProgress; i++) {
message.what = i;
handler.sendEmptyMessage(message.what);
Thread.sleep(mShowProgressTime);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int p = msg.what;
setProgress(p);
}
};
}<file_sep>/README.md
# CustomProgressMaster
Simple custom progress bar.
### CustomProgressMaster sample
<img src="pic/ezgif.com-video-to-gif.gif" width="400"> </img>
<img src="pic/device-2018-12-02-171734.png" width="400"></img>
## Build
Add the following to your app's build.gradle:
```groovy
dependencies {
implementation 'com.github.futureLix:CustomProgressMaster:v1.0'
}
```
## How to use
#### Add the following XML:
```xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ExampleActivity">
<example.com.customprogressmaster.CustomProgress
android:id="@+id/mProgressZero"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="center_horizontal"
android:layout_margin="30dp"
app:mBackGround="@color/progress_bg1"
app:mForeGround="@color/progress_bg2"
app:mTextSize="@dimen/text_size"/>
<example.com.customprogressmaster.CustomProgress
android:id="@+id/mProgressOne"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="center_horizontal"
android:layout_margin="30dp"
app:mBackGround="@color/progress_bg4"
app:mForeGround="@color/progress_bg5"
app:mTextColor="@color/progress_bg4"
app:mTextSize="@dimen/text_size"/>
<example.com.customprogressmaster.CustomProgress
android:id="@+id/mProgressTwo"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="center_horizontal"
android:layout_margin="30dp"/>
</LinearLayout>
```
#### Create :
```java
public class ExampleActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_example);
bindView();
}
private void bindView() {
CustomProgress myProgressZ = findViewById(R.id.mProgressZero);
myProgressZ.setmShowProgress(80);
myProgressZ.setShowProgressTime(100);
CustomProgress myProgressO = findViewById(R.id.mProgressOne);
myProgressO.setmShowProgress(80);
CustomProgress myProgressT = findViewById(R.id.mProgressTwo);
myProgressT.setmShowProgress(100);
myProgressT.setBackgroundColor(ContextCompat.getColor(this, R.color.progress_bg6));
myProgressT.setForeground(ContextCompat.getColor(this, R.color.progress_bg7));
myProgressT.setText("完成");
myProgressT.setTextColor(ContextCompat.getColor(this, R.color.progress_bg6));
myProgressT.setTextIsDisplayable(false);
}
}
```
| 5785224c83a0689dbd71ee920c0af7ef8aa69e1d | [
"Markdown",
"Java"
] | 2 | Java | futureLix/CustomProgressMaster | d6e952a238adc3186ced7864b2562f7bad0ed913 | 09f6ab7b24b81c0d3c4c3e579b0ae3b0587a971b |
refs/heads/master | <repo_name>bugbug2022/gscheduler<file_sep>/cmd/master/runner/MasterExecGoroutine.go
package runner
import (
"github.com/maybaby/gscheduler/models"
"github.com/maybaby/gscheduler/pkg/logging"
)
type MasterExecGoroutine struct {
*models.Command
}
func (meg *MasterExecGoroutine) Run() {
go func() {
logging.Info("getting... ", meg.CommandType)
}()
}
<file_sep>/models/Flag.go
package models
type Flag int32
const (
YES Flag = iota
NO
)
<file_sep>/go.mod
module github.com/maybaby/gscheduler
go 1.15
require (
github.com/360EntSecGroup-Skylar/excelize v1.4.1
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751
github.com/astaxie/beego v1.12.3
github.com/boombuler/barcode v1.0.1
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/gin-gonic/gin v1.6.3
github.com/go-ini/ini v1.62.0
github.com/go-openapi/spec v0.20.3 // indirect
github.com/go-sql-driver/mysql v1.5.0
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0
github.com/gomodule/redigo v2.0.0+incompatible
github.com/jinzhu/gorm v1.9.16
github.com/mailru/easyjson v0.7.7 // indirect
github.com/sanketplus/go-mysql-lock v0.0.5
github.com/swaggo/gin-swagger v1.3.0
github.com/swaggo/swag v1.7.0
github.com/tealeg/xlsx v1.0.5
github.com/unknwon/com v1.0.1
golang.org/x/image v0.0.0-20210220032944-ac19c3e999fb // indirect
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110 // indirect
golang.org/x/sys v0.0.0-20210228012217-479acdf4ea46 // indirect
golang.org/x/tools v0.1.0 // indirect
gopkg.in/ini.v1 v1.62.0 // indirect
)
<file_sep>/services/process_service/processInstance.go
package process_service
import "time"
type ProcessInstance struct {
Name string
CreateTime time.Time
UpdateTime time.Time
ProcessData *ProcessData
GroupId string
Description string
}
<file_sep>/cmd/worker/worker.go
package main
import (
gsrpc "github.com/maybaby/gscheduler"
"github.com/maybaby/gscheduler/libs/worker"
"github.com/maybaby/gscheduler/models"
"github.com/maybaby/gscheduler/pkg/gredis"
"github.com/maybaby/gscheduler/pkg/logging"
"github.com/maybaby/gscheduler/pkg/setting"
"github.com/maybaby/gscheduler/pkg/util"
"github.com/maybaby/gscheduler/services/registry_service"
"net"
"sync"
)
func startWorkerServer(registryAddr string, wg *sync.WaitGroup) {
var tp worker.TaskExecuteProcessor
l, _ := net.Listen("tcp", ":0")
server := gsrpc.NewServer()
_ = server.Register(&tp)
registry_service.Heartbeat(registryAddr, "tcp@"+l.Addr().String(), 0)
wg.Done()
server.Accept(l)
}
func init() {
setting.Setup()
models.Setup()
logging.Setup()
gredis.Setup()
util.Setup()
}
func main() {
var wg sync.WaitGroup
registryAddr := "http://localhost:9999/_gsrpc_/registry"
wg.Add(2)
go startWorkerServer(registryAddr, &wg)
wg.Wait()
}
<file_sep>/services/lock_service/distribute_lock.go
package lock_service
import (
_ "context"
"database/sql"
"errors"
"fmt"
"github.com/maybaby/gscheduler/pkg/setting"
"os"
"time"
_ "github.com/go-sql-driver/mysql"
"github.com/sanketplus/go-mysql-lock"
)
type Locker interface {
InitLocker()
GetLock(name string) *gomysqllock.Lock
ReleaseLock(*gomysqllock.Lock) error
}
type MysqlLocker struct {
db *sql.DB
locker *gomysqllock.MysqlLocker
}
func (m *MysqlLocker) InitLocker() {
url := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local",
setting.DatabaseSetting.User,
setting.DatabaseSetting.Password,
setting.DatabaseSetting.Host,
setting.DatabaseSetting.Port,
setting.DatabaseSetting.Name)
fmt.Println("初始化Locker中", url)
db, _ := sql.Open(setting.DatabaseSetting.Type, url)
locker := gomysqllock.NewMysqlLocker(db)
m.db = db
m.locker = locker
}
func (m *MysqlLocker) GetLock(name string) *gomysqllock.Lock {
lock, _ := m.locker.Obtain(name)
return lock
}
func (m *MysqlLocker) ReleaseLock(l *gomysqllock.Lock) error {
if l == nil {
return errors.New("Null")
}
l.Release()
return nil
}
func GetAndInitLocker() Locker {
var l Locker
switch setting.DSlockerSetting.Type {
case "mysql":
l = &MysqlLocker{}
l.InitLocker()
default:
l = &MysqlLocker{}
l.InitLocker()
}
return l
}
func main() {
url := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local",
setting.DatabaseSetting.User,
setting.DatabaseSetting.Password,
setting.DatabaseSetting.Host,
setting.DatabaseSetting.Name)
fmt.Println(url)
db, _ := sql.Open(setting.DatabaseSetting.Type, url)
locker := gomysqllock.NewMysqlLocker(db)
lock, _ := locker.Obtain("foo")
fmt.Println("我拿到了锁", os.Args[0])
time.Sleep(10 * time.Second)
lock.Release()
fmt.Println("我释放了锁", os.Args[0])
}
<file_sep>/cmd/master/master.go
package main
import (
"fmt"
geerpc "github.com/maybaby/gscheduler"
"github.com/maybaby/gscheduler/cmd/master/runner"
"github.com/maybaby/gscheduler/services/registry_service"
"log"
"net"
"net/http"
"sync"
"time"
"github.com/gin-gonic/gin"
"github.com/maybaby/gscheduler/models"
"github.com/maybaby/gscheduler/pkg/gredis"
"github.com/maybaby/gscheduler/pkg/logging"
"github.com/maybaby/gscheduler/pkg/setting"
"github.com/maybaby/gscheduler/pkg/util"
"github.com/maybaby/gscheduler/routers"
)
type Foo int
type Args struct{ Num1, Num2 int }
func (f Foo) Sum(args Args, reply *int) error {
*reply = args.Num1 + args.Num2
return nil
}
func (f Foo) Sleep(args Args, reply *int) error {
time.Sleep(time.Second * time.Duration(args.Num1))
*reply = args.Num1 + args.Num2
return nil
}
func startRegistry(wg *sync.WaitGroup) {
l, _ := net.Listen("tcp", ":9999")
registry_service.HandleHTTP()
wg.Done()
_ = http.Serve(l, nil)
}
func startServer(registryAddr string, wg *sync.WaitGroup) {
var foo Foo
l, _ := net.Listen("tcp", ":0")
server := geerpc.NewServer()
_ = server.Register(&foo)
registry_service.Heartbeat(registryAddr, "tcp@"+l.Addr().String(), 0)
wg.Done()
server.Accept(l)
}
func init() {
setting.Setup()
models.Setup()
logging.Setup()
gredis.Setup()
util.Setup()
}
// @title Golang Gin API
// @version 1.0
// @description An example of gin
// @termsOfService https://github.com/maybaby/gscheduler
// @license.name MIT
// @license.url https://github.com/maybaby/gscheduler/blob/master/LICENSE
func main() {
var wg sync.WaitGroup
wg.Add(1)
go startRegistry(&wg)
wg.Wait()
gin.SetMode(setting.ServerSetting.RunMode)
//registryAddr := "http://localhost:9999/_gsrpc_/registry"
//time.Sleep(time.Second*16)
//call(registryAddr)
routersInit := routers.InitRouter()
readTimeout := setting.ServerSetting.ReadTimeout
writeTimeout := setting.ServerSetting.WriteTimeout
endPoint := fmt.Sprintf(":%d", setting.ServerSetting.HttpPort)
maxHeaderBytes := 1 << 20
server := &http.Server{
Addr: endPoint,
Handler: routersInit,
ReadTimeout: readTimeout,
WriteTimeout: writeTimeout,
MaxHeaderBytes: maxHeaderBytes,
}
logging.Info("Starting master scheudler")
ms := &runner.MasterSchedulerService{}
ms.Run()
log.Printf("[info] start http server listening %s", endPoint)
server.ListenAndServe()
// If you want Graceful Restart, you need a Unix system and download github.com/fvbock/endless
//endless.DefaultReadTimeOut = readTimeout
//endless.DefaultWriteTimeOut = writeTimeout
//endless.DefaultMaxHeaderBytes = maxHeaderBytes
//server := endless.NewServer(endPoint, routersInit)
//server.BeforeBegin = func(add string) {
// log.Printf("Actual pid is %d", syscall.Getpid())
//}
//
//err := server.ListenAndServe()
//if err != nil {
// log.Printf("Server err: %v", err)
//}
}
<file_sep>/services/executor_service/executor.go
package executor_service
type Executor struct {
ID int
Name string
State int
PageNum int
PageSize int
}
<file_sep>/models/ExecutionStatus.go
package models
type ExecutionStatus int32
const (
SUBMITTED_SUCCESS ExecutionStatus = iota
RUNNING_EXEUTION
READY_PAUSE
EPAUSE
READY_STOP
ESTOP
FAILURE
SUCCESS
NEED_FAULT_TOLERANCE
KILL
WAITTING_THREAD
WAITTING_DEPEND
)
<file_sep>/cmd/master/runner/mastershedulerservice.go
package runner
import (
"github.com/maybaby/gscheduler/pkg/logging"
"github.com/maybaby/gscheduler/pkg/util"
"github.com/maybaby/gscheduler/services/lock_service"
"github.com/maybaby/gscheduler/services/process_service"
"time"
)
type MasterSchedulerService struct {
}
func (m *MasterSchedulerService) Run() error {
locker := lock_service.GetAndInitLocker()
logging.Info("Master scheudler start.")
//c := make(chan os.Signal)
// 监听信号
//signal.Notify(c, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
go func() {
for {
//for s := range c {
// switch s {
// case syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM:
// logging.Info("退出:", s)
// os.Exit(-1)
// default:
// logging.Debug("Master scheduler Service ")
// }
//}
lock := locker.GetLock("master")
cmd, err := process_service.FindOneCommand()
if cmd != nil && err == nil {
processInstance, err := process_service.HandleCommand(cmd, util.GetLocalAddress())
if processInstance != nil && err == nil {
// TODO support Dag split here
logging.Info("开始分解ProcessInstance, 切割为Task ...")
meg := &MasterExecGoroutine{
cmd,
}
meg.Run()
}
} else {
time.Sleep(1 * time.Second)
}
lock.Release()
}
}()
return nil
}
<file_sep>/libs/worker/worker.go
package worker
import (
"fmt"
"github.com/maybaby/gscheduler/models"
"github.com/maybaby/gscheduler/services/lock_service"
"time"
)
type TaskExecuteProcessor struct {
}
func (tp TaskExecuteProcessor) Process(cmd *models.Command, reply *int) error {
locker := lock_service.GetAndInitLocker()
for i := 0; i < 5; i++ {
fmt.Println("获取到Command", cmd.CommandType)
lock := locker.GetLock("worker")
fmt.Println("等待10s", cmd.CommandType)
time.Sleep(10 * time.Second)
locker.ReleaseLock(lock)
}
return nil
}
<file_sep>/pkg/util/JsonUtil.go
package util
import (
"encoding/json"
"github.com/maybaby/gscheduler/pkg/logging"
)
func ToMap(jsonString string) map[string]interface{} {
if jsonString == "" {
logging.Info("Empty String Found, Return \"\"")
return nil
}
jsonMap := make(map[string]interface{})
err := json.Unmarshal([]byte(jsonString), &jsonMap)
if err != nil {
logging.Error(err)
return nil
}
return jsonMap
}
<file_sep>/models/ProcessDefinition.go
package models
import (
"github.com/jinzhu/gorm"
"time"
)
type ProcessDefinition struct {
ID int `json:"id"`
Name string `json:"name"`
Version string `json:"version"`
GroupId string `json:"group_id"`
UserId string `json:"user_id"`
ProcessDefinitionJson string `json:"process_definition_json"`
Description string `json:"description"`
Flag string `json:"flag"`
CreateTime time.Time `json:"create_time"`
Timeout string `json:"timeout"`
UpdateTime time.Time `json:"update_time"`
}
// TableName 会将 User 的表名重写为 `process_definition`
// 参加gorm约定
func (ProcessDefinition) TableName() string {
return "process_definition"
}
// 校验pd 合法性
func (p *ProcessDefinition) CheckProcessDefinitionValid() error {
return nil
}
// CheckAuth checks if authentication information exists
func SaveDefinition(sd *ProcessDefinition) error {
if err := db.Create(&sd).Error; err != nil {
return err
}
return nil
}
// GetProcessDefinition Get a single ProcessDefinition based on ID
func GetProcessDefinition(id int) (*ProcessDefinition, error) {
var pd ProcessDefinition
err := db.Table("t_gs_process_definition").First(&pd, id).Error
if err != nil || err == gorm.ErrRecordNotFound {
return nil, err
}
return &pd, nil
}
<file_sep>/docs/sql_demo/scheduler.sql
CREATE TABLE `t_gs_process_definition` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'key',
`name` varchar(255) DEFAULT NULL COMMENT 'process definition name',
`version` int(11) DEFAULT NULL COMMENT 'process definition version',
`release_state` tinyint(4) DEFAULT NULL COMMENT 'process definition release state:0:offline,1:online',
`group_id` int(11) DEFAULT NULL COMMENT 'group_id分组id',
`user_id` int(11) DEFAULT NULL COMMENT 'process definition creator id',
`process_definition_json` longtext COMMENT 'process definition json content',
`description` text,
`global_params` text COMMENT 'global parameters',
`flag` tinyint(4) DEFAULT NULL COMMENT '0 not available, 1 available',
`locations` text COMMENT 'Node location information',
`connects` text COMMENT 'Node connection information',
`receivers` text COMMENT 'receivers',
`receivers_cc` text COMMENT 'cc',
`create_time` datetime DEFAULT NULL COMMENT 'create time',
`timeout` int(11) DEFAULT '0' COMMENT 'time out',
`tenant_id` int(11) NOT NULL DEFAULT '-1' COMMENT 'tenant id',
`update_time` datetime DEFAULT NULL COMMENT 'update time',
`modify_by` varchar(36) DEFAULT '' COMMENT 'modify user',
`resource_ids` varchar(255) DEFAULT NULL COMMENT 'resource ids',
PRIMARY KEY (`id`),
UNIQUE KEY `process_definition_unique` (`name`,`group_id`),
KEY `process_definition_index` (`group_id`,`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
CREATE TABLE `t_gs_process_definition_version` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'key',
`process_definition_id` int(11) NOT NULL COMMENT 'process definition id',
`version` int(11) DEFAULT NULL COMMENT 'process definition version',
`process_definition_json` longtext COMMENT 'process definition json content',
`description` text,
`global_params` text COMMENT 'global parameters',
`locations` text COMMENT 'Node location information',
`connects` text COMMENT 'Node connection information',
`receivers` text COMMENT 'receivers',
`receivers_cc` text COMMENT 'cc',
`create_time` datetime DEFAULT NULL COMMENT 'create time',
`timeout` int(11) DEFAULT '0' COMMENT 'time out',
`resource_ids` varchar(255) DEFAULT NULL COMMENT 'resource ids',
PRIMARY KEY (`id`),
UNIQUE KEY `process_definition_id_and_version` (`process_definition_id`,`version`) USING BTREE,
KEY `process_definition_index` (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
CREATE TABLE `t_gs_process_instance` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'key',
`name` varchar(255) DEFAULT NULL COMMENT 'process instance name',
`process_definition_id` int(11) DEFAULT NULL COMMENT 'process definition id',
`state` tinyint(4) DEFAULT NULL COMMENT 'process instance Status: 0 commit succeeded, 1 running, 2 prepare to pause, 3 pause, 4 prepare to stop, 5 stop, 6 fail, 7 succeed, 8 need fault tolerance, 9 kill, 10 wait for thread, 11 wait for dependency to complete',
`recovery` tinyint(4) DEFAULT NULL COMMENT 'process instance failover flag:0:normal,1:failover instance',
`start_time` datetime DEFAULT NULL COMMENT 'process instance start time',
`end_time` datetime DEFAULT NULL COMMENT 'process instance end time',
`run_times` int(11) DEFAULT NULL COMMENT 'process instance run times',
`host` varchar(45) DEFAULT NULL COMMENT 'process instance host',
`command_type` tinyint(4) DEFAULT NULL COMMENT 'command type',
`command_param` text COMMENT 'json command parameters',
`task_depend_type` tinyint(4) DEFAULT NULL COMMENT 'task depend type. 0: only current node,1:before the node,2:later nodes',
`max_try_times` tinyint(4) DEFAULT '0' COMMENT 'max try times',
`failure_strategy` tinyint(4) DEFAULT '0' COMMENT 'failure strategy. 0:end the process when node failed,1:continue running the other nodes when node failed',
`warning_type` tinyint(4) DEFAULT '0' COMMENT 'warning type. 0:no warning,1:warning if process success,2:warning if process failed,3:warning if success',
`warning_group_id` int(11) DEFAULT NULL COMMENT 'warning group id',
`schedule_time` datetime DEFAULT NULL COMMENT 'schedule time',
`command_start_time` datetime DEFAULT NULL COMMENT 'command start time',
`global_params` text COMMENT 'global parameters',
`process_instance_json` longtext COMMENT 'process instance json(copy的process definition 的json)',
`flag` tinyint(4) DEFAULT '1' COMMENT 'flag',
`update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`is_sub_process` int(11) DEFAULT '0' COMMENT 'flag, whether the process is sub process',
`executor_id` int(11) NOT NULL COMMENT 'executor id',
`locations` text COMMENT 'Node location information',
`connects` text COMMENT 'Node connection information',
`history_cmd` text COMMENT 'history commands of process instance operation',
`dependence_schedule_times` text COMMENT 'depend schedule fire time',
`process_instance_priority` int(11) DEFAULT NULL COMMENT 'process instance priority. 0 Highest,1 High,2 Medium,3 Low,4 Lowest',
`worker_group` varchar(64) DEFAULT '' COMMENT 'worker group',
`timeout` int(11) DEFAULT '0' COMMENT 'time out',
`tenant_id` int(11) NOT NULL DEFAULT '-1' COMMENT 'tenant id',
`var_pool` longtext,
PRIMARY KEY (`id`),
KEY `process_instance_index` (`process_definition_id`,`id`) USING BTREE,
KEY `start_time_index` (`start_time`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
CREATE TABLE `t_gs_group` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'key',
`name` varchar(100) DEFAULT NULL COMMENT 'group name',
`description` varchar(200) DEFAULT NULL,
`user_id` int(11) DEFAULT NULL COMMENT 'creator id',
`flag` tinyint(4) DEFAULT '1' COMMENT '0 not available, 1 available',
`create_time` datetime DEFAULT NULL COMMENT 'create time',
`update_time` datetime DEFAULT NULL COMMENT 'update time',
PRIMARY KEY (`id`),
KEY `user_id_index` (`user_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
CREATE TABLE `t_gs_command` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'key',
`command_type` tinyint(4) DEFAULT NULL COMMENT 'Command type: 0 start workflow, 1 start execution from current node, 2 resume fault-tolerant workflow, 3 resume pause process, 4 start execution from failed node, 5 complement, 6 schedule, 7 rerun, 8 pause, 9 stop, 10 resume waiting thread',
`process_definition_id` int(11) DEFAULT NULL COMMENT 'process definition id',
`command_param` text COMMENT 'json command parameters',
`task_depend_type` tinyint(4) DEFAULT NULL COMMENT 'Node dependency type: 0 current node, 1 forward, 2 backward',
`failure_strategy` tinyint(4) DEFAULT '0' COMMENT 'Failed policy: 0 end, 1 continue',
`warning_type` tinyint(4) DEFAULT '0' COMMENT 'Alarm type: 0 is not sent, 1 process is sent successfully, 2 process is sent failed, 3 process is sent successfully and all failures are sent',
`warning_group_id` int(11) DEFAULT NULL COMMENT 'warning group',
`schedule_time` datetime DEFAULT NULL COMMENT 'schedule time',
`start_time` datetime DEFAULT NULL COMMENT 'start time',
`executor_id` int(11) DEFAULT NULL COMMENT 'executor id',
`dependence` varchar(255) DEFAULT NULL COMMENT 'dependence',
`update_time` datetime DEFAULT NULL COMMENT 'update time',
`process_instance_priority` int(11) DEFAULT NULL COMMENT 'process instance priority: 0 Highest,1 High,2 Medium,3 Low,4 Lowest',
`worker_group` varchar(64) DEFAULT '' COMMENT 'worker group',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=37 DEFAULT CHARSET=utf8;
<file_sep>/pkg/util/Osutil.go
package util
import (
"fmt"
"github.com/maybaby/gscheduler/pkg/setting"
"net"
)
//获取本机ip
func GetLocalIp() string {
addrs, err := net.InterfaceAddrs()
if err != nil {
fmt.Println("get local ip failed")
}
for _, address := range addrs {
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
return ipnet.IP.String()
}
}
}
return ""
}
func GetLocalAddress() string {
return fmt.Sprintf("%s:%d", GetLocalIp(), setting.ServerSetting.HttpPort)
}
<file_sep>/controllers/api/v1/test.go
package v1
import (
"context"
"github.com/gin-gonic/gin"
"github.com/maybaby/gscheduler/models"
"github.com/maybaby/gscheduler/services/client_service"
"log"
"net/http"
"sync"
"github.com/maybaby/gscheduler/pkg/app"
"github.com/maybaby/gscheduler/pkg/e"
)
func foo(xc *client_service.XClient, ctx context.Context, typ, serviceMethod string, command *models.Command) {
var reply int
var err error
switch typ {
case "call":
err = xc.Call(ctx, serviceMethod, command, &reply)
case "broadcast":
err = xc.Broadcast(ctx, serviceMethod, command, &reply)
}
if err != nil {
log.Printf("%s %s error: %v", typ, serviceMethod, err)
} else {
log.Printf("%s %s success: %d + %d = %d", typ, serviceMethod, command.CommandType, command.CommandParam, reply)
}
}
func call(registry string) {
d := client_service.NewGsRegistryDiscovery(registry, 0)
xc := client_service.NewXClient(d, client_service.RandomSelect, nil)
defer func() { _ = xc.Close() }()
// send request & receive response
var wg sync.WaitGroup
wg.Add(1)
go func(i int) {
defer wg.Done()
foo(xc, context.Background(), "call", "TaskExecuteProcessor.Process", &models.Command{CommandType: 1})
}(1)
wg.Wait()
}
// @Summary Call a rpc procedure
// @Produce json
// @Success 200 {object} app.Response
// @Failure 500 {object} app.Response
// @Router /api/v1/call [get]
func CallRpc(c *gin.Context) {
appG := app.Gin{C: c}
registryAddr := "http://localhost:9999/_gsrpc_/registry"
//time.Sleep(time.Second*16)
call(registryAddr)
appG.Response(http.StatusOK, e.SUCCESS, "haha")
}
<file_sep>/controllers/api/v1/process.go
package v1
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/maybaby/gscheduler/models"
"github.com/maybaby/gscheduler/pkg/app"
"github.com/maybaby/gscheduler/pkg/e"
"github.com/maybaby/gscheduler/services/process_service"
"github.com/maybaby/gscheduler/services/task_service"
"net/http"
"time"
)
/**
* 流程controller
* pd := process_service.ProcessData{}
td := &task_service.TaskNode{
Id: "11111",
Name: "firstNode",
Params: task_service.TaskParams{
ResourceList: []string{"1111","2222"},
LocalParams: []string{"ccccccddd"},
RawScript: "print(\"pythonNode1\")",
},
RunFlag: "1",
Type: "PYTHON",
}
pd.Tasks = []*task_service.TaskNode{td}
pd.Timeout = 123
s, _:= pd.MarshalJSON()
fmt.Println(string(s))
*/
// @Summary 测试任务定义接口 a rpc procedure
// @Produce json
// @Success 200 {object} app.Response
// @Failure 500 {object} app.Response
// @Router /api/v1/process/test [get]
func TestCreateProcessDefinition(c *gin.Context) {
var (
//appG = app.Gin{C: c}
json_ AddProcessDefineJson
)
c.BindJSON(&json_)
//appG.Response(httpCode, errCode, nil)
processService := process_service.ProcessDefinition{}
_ = processService.Save()
pd := process_service.ProcessData{}
td := &task_service.TaskNode{
Id: "11111",
Name: "firstNode",
Params: task_service.TaskParams{
ResourceList: []string{"1111", "2222"},
LocalParams: []string{"ccccccddd"},
RawScript: "print(\"pythonNode1\")",
},
RunFlag: "1",
Type: "PYTHON",
}
pd.Tasks = []*task_service.TaskNode{td}
pd.Timeout = 123
s, _ := pd.MarshalJSON()
fmt.Println(string(s))
return
//registryAddr := "http://localhost:9999/_gsrpc_/registry"
////time.Sleep(time.Second*16)
//call(registryAddr)
}
// @Summary 保存任务定义接口
// @Produce json
// @Success 200 {object} app.Response
// @Failure 500 {object} app.Response
// @Router /api/v1/process/save [post]
func CreateProcessDefinition(c *gin.Context) {
var (
appG = app.Gin{C: c}
json_ AddProcessDefineJson
)
c.BindJSON(&json_)
processService := process_service.ProcessDefinition{
Name: json_.Name,
Description: json_.Desc,
GroupId: json_.GroupId,
ProcessData: json_.ProcessData,
CreateTime: time.Now(),
UpdateTime: time.Now(),
}
err := processService.Save()
if err != nil {
appG.Response(http.StatusForbidden, e.ERROR, nil)
return
}
appG.Response(http.StatusOK, e.SUCCESS, json_.Name)
//registryAddr := "http://localhost:9999/_gsrpc_/registry"
////time.Sleep(time.Second*16)
//call(registryAddr)
}
type AddProcessDefineJson struct {
Name string `form:"name" json:"name"`
GroupId string `form:"groupId" json:"groupId"`
ProcessData *process_service.ProcessData `form:"processData" json:"processData"`
Desc string `form:"desc" json:"desc"`
//TODO 定义 dag的连接 暂时不支持dag
}
// @Summary 执行一个任务定义接口 启动一个任务定义,并创建一个任务实例
// @Produce json
// @Success 200 {object} app.Response
// @Failure 500 {object} app.Response
// @Router /api/v1/process/start [post]
func CreateAndStartProcessInstance(c *gin.Context) {
var (
appG = app.Gin{C: c}
json_ StartProcessDefineJson
)
c.BindJSON(&json_)
err := process_service.ExecProcessInstance(
models.START_PROCESS,
json_.GroupId,
json_.ProcessDefinitionId,
json_.WorkerGroup,
json_.Timeout,
process_service.Serial)
if err != nil {
appG.Response(http.StatusForbidden, e.ERROR, err)
return
}
appG.Response(http.StatusOK, e.SUCCESS, nil)
}
type StartProcessDefineJson struct {
GroupId string `form:"groupId" json:"groupId"`
ProcessDefinitionId int `form:"processDefinitionId" json:"processDefinitionId"`
FailureStrategy string `form:"failureStrategy" json:"failureStrategy"` //失败策略
WorkerGroup string `form:"workerGroup" json:"workerGroup"` //worker组别
Timeout int `form:"timeout" json:"timeout"`
//TODO 定义 dag的连接 暂时不支持dag
}
<file_sep>/models/scheduleParam.go
package models
type ScheduleParam struct {
Model
StartTime int `json:"startTime"`
EndTime int `json:"endTime"`
Crontab string `json:"crontab"`
}
<file_sep>/models/ProcessInstance.go
package models
import (
"github.com/jinzhu/gorm"
"time"
)
type Priority int32
const (
HIGHEST Priority = iota
HIGH
MEDIUM
LOW
LOWEST
)
type ProcessInstance struct {
ID string `json:"id"`
ProcessDefinitionId int `json:"processDefinitionId"`
State ExecutionStatus `json:"state"`
Flag Flag `json:"flag"`
StartTime time.Time `json:"startTime"`
EndTime time.Time `json:"endTime"`
RunTimes int `json:"runTimes"`
Name string `json:"name"`
Host string `json:"host"`
CommandType CommandType `json:"commandType"`
CommandParam string `json:"commandParam"`
MaxTryTimes int `json:"maxTryTimes"`
ScheduleTime time.Time `json:"scheduleTime"`
ProcessInstanceJson string `json:"processInstanceJson"`
WorkerGroup string `json:"workerGroup"`
Timeout int `json:"timeout"`
ProcessInstancePriority Priority `json:"process_instance_priority"`
}
// TableName 会将 User 的表名重写为 `process_definition`
// 参加gorm约定
func (ProcessInstance) TableName() string {
return "process_instance"
}
// CheckAuth checks if authentication information exists
func SaveProcessInstance(pi *ProcessInstance) error {
if err := db.Create(&pi).Error; err != nil {
return err
}
return nil
}
func GetProcessInstance(id string) (*ProcessInstance, error) {
var pd ProcessInstance
err := db.Where("id = ? ", id).Table("t_gs_process_instance").First(&pd).Error
if err != nil && err != gorm.ErrRecordNotFound {
return nil, err
}
return &pd, nil
}
<file_sep>/models/CommandType.go
package models
type CommandType int32
const (
START_PROCESS CommandType = iota
START_CURRENT_TASK_PROCESS
RECOVER_TOLERANCE_FAULT_PROCESS
RECOVER_SUSPENDED_PROCESS
START_FAILURE_TASK_PROCESS
COMPLEMENT_DATA
SCHEDULER
REPEAT_RUNNING
PAUSE
STOP
RECOVER_WAITTING_THREAD
)
<file_sep>/services/process_service/processDefinition.go
package process_service
import (
"encoding/json"
"errors"
"github.com/maybaby/gscheduler/models"
"github.com/maybaby/gscheduler/pkg/e"
"github.com/maybaby/gscheduler/pkg/logging"
"github.com/maybaby/gscheduler/pkg/setting"
"github.com/maybaby/gscheduler/pkg/util"
"github.com/maybaby/gscheduler/services/task_service"
"time"
)
type RunMode int32
const (
Serial RunMode = iota
Parallel
)
type ProcessData struct {
Tasks []*task_service.TaskNode
GlobalParams []*task_service.Property
Timeout int
}
type ProcessDefinition struct {
Name string
CreateTime time.Time
UpdateTime time.Time
ProcessData *ProcessData
GroupId string
Description string
}
func (p *ProcessDefinition) Save() error {
pr := &models.ProcessDefinition{
Name: p.Name,
Version: "1", // Save 第一次默认为1
Description: p.Description,
GroupId: p.GroupId,
CreateTime: p.CreateTime,
UpdateTime: p.UpdateTime,
ProcessDefinitionJson: p.ProcessData.ToJson(),
}
if err := models.SaveDefinition(pr); err != nil {
return err
}
return nil
}
func (p *ProcessData) ToJson() string {
b, err := p.MarshalJSON()
if err != nil {
return "{}"
}
return string(b)
}
func (p *ProcessData) MarshalJSON() ([]byte, error) {
return json.Marshal(&struct {
Tasks []*task_service.TaskNode `json:"tasks"`
GlobalParams []*task_service.Property `json:"globalParams"`
Timeout int `json:"timeout"`
}{
Tasks: p.Tasks,
GlobalParams: p.GlobalParams,
Timeout: p.Timeout,
})
}
/*
* 反序列化
*/
func (p *ProcessData) UnmarshalJSON(data []byte) error {
aux := &struct {
Tasks []*task_service.TaskNode `json:"tasks"`
GlobalParams []*task_service.Property `json:"globalParams"`
Timeout int `json:"timeout"`
}{
Tasks: p.Tasks,
GlobalParams: p.GlobalParams,
Timeout: p.Timeout,
}
if err := json.Unmarshal(data, &aux); err != nil {
return err
}
p.Timeout = aux.Timeout
p.Tasks = aux.Tasks
p.GlobalParams = aux.GlobalParams
return nil
}
/*
启动1个 Process实例, 分解 processDefintion 为多个Command Task
*/
func ExecProcessInstance(cmdType models.CommandType, groupId string, processDefinitionId int, workerGroup string, timeout int, runMode RunMode) error {
if timeout <= 0 || timeout > setting.MAX_TASK_TIMEOUT {
return errors.New(string(e.ERROR_PROCESS_TIMEOUT))
}
pd, err := models.GetProcessDefinition(processDefinitionId)
if err != nil {
return errors.New(string(e.ERROR_PROCESS_NOTFOUND))
}
if pd == nil {
return errors.New(string(e.ERROR_PROCESS_NOTFOUND))
}
// 简单校验
err = pd.CheckProcessDefinitionValid()
processData := &ProcessData{}
processData.UnmarshalJSON([]byte(pd.ProcessDefinitionJson))
/**
* create command
*/
cmd := &models.Command{
CommandType: cmdType,
ProcessDefinitionId: pd.ID,
ExecutorId: "",
WorkerGroup: workerGroup,
}
err = models.SaveCommand(cmd)
if err != nil {
return err
}
return nil
}
func FindOneCommand() (*models.Command, error) {
cmd, err := models.GetOneCommandToRun()
return cmd, err
}
func HandleCommand(command *models.Command, host string) (*models.ProcessInstance, error) {
logging.Info("Find one Command To Run...")
processInstance := constructProcessInstance(command, host)
if processInstance == nil {
logging.Error("scan command, command parameter is error: {}", command)
moveToErrorCommand(command, "process instance is null")
return nil, nil
}
processInstance.CommandType = command.CommandType
//TODO add history cmd
//processInstance.addHistoryCmd(command.getCommandType());
models.SaveProcessInstance(processInstance)
models.DeleteCommand(command)
return processInstance, nil
}
func moveToErrorCommand(command *models.Command, msg string) {
//TODOs
logging.Info("Not implement.. TODO..")
}
func constructProcessInstance(command *models.Command, host string) *models.ProcessInstance {
cmdType := command.CommandType
cmdParam := util.ToMap(command.CommandParam)
var processInstance *models.ProcessInstance = nil
var processDefinition *models.ProcessDefinition = nil
var err error
if command.ProcessDefinitionId != 0 {
processDefinition, err = models.GetProcessDefinition(command.ProcessDefinitionId)
if err != nil || processDefinition == nil {
logging.Error("Not found Definition...")
return nil
}
}
if cmdParam != nil {
processInstance = &models.ProcessInstance{}
logging.Info(cmdType)
return processInstance
} else {
// generate one new process instance
processInstance = generateNewProcessInstance(processDefinition, command, command.CommandParam)
}
processInstance.Host = host
var runStatus models.ExecutionStatus = models.RUNNING_EXEUTION
//runTimes := processInstance.Runtimes
switch command.CommandType {
case models.START_PROCESS:
break
case models.START_FAILURE_TASK_PROCESS:
// find failed tasks and init these tasks
break
//TODO
case models.START_CURRENT_TASK_PROCESS:
break
case models.RECOVER_WAITTING_THREAD:
break
case models.RECOVER_SUSPENDED_PROCESS:
break
case models.RECOVER_TOLERANCE_FAULT_PROCESS:
break
case models.COMPLEMENT_DATA:
break
case models.REPEAT_RUNNING:
case models.SCHEDULER:
break
default:
break
}
processInstance.State = runStatus
return processInstance
}
func generateNewProcessInstance(definition *models.ProcessDefinition,
command *models.Command,
cmdParam string) *models.ProcessInstance {
processInstance := &models.ProcessInstance{}
processInstance.ProcessDefinitionId = command.ProcessDefinitionId
processInstance.State = models.RUNNING_EXEUTION
processInstance.StartTime = time.Now()
processInstance.RunTimes = 1
processInstance.MaxTryTimes = 0
processInstance.CommandParam = cmdParam
processInstance.CommandType = command.CommandType
if command.WorkerGroup == "" {
command.WorkerGroup = setting.DEFAULT_WORKER_GROUP
} else {
command.WorkerGroup = command.WorkerGroup
}
processInstance.Timeout = processInstance.Timeout
//copy process define json to process instance
processInstance.ProcessInstanceJson = definition.ProcessDefinitionJson
// set process instance priority
processInstance.ProcessInstancePriority = command.ProcessInstancePriority
return processInstance
}
<file_sep>/pkg/setting/consts.go
package setting
const (
MAX_TASK_TIMEOUT int = 24 * 3600
DEFAULT_WORKER_GROUP string = "default"
)
<file_sep>/models/Command.go
package models
import (
"time"
)
type Command struct {
Id string `json:"id"`
CommandType CommandType `json:"command_type"`
ProcessDefinitionId int `json:"process_definition_id"`
ExecutorId string `json:"executor_id"`
CommandParam string `json:"command_param"`
TaskDependType TaskDependType `json:"task_depend_type"`
WarningType WarningType `json:"warning_type"`
FailureStrategy FailureStrategy `json:"failure_strategy"`
WarningGroupId string `json:"warning_type"`
StartTime time.Time `json:"start_time"`
UpdateTime time.Time `json:"update_time"`
ScheduleTime time.Time `json:"schedule_time"`
WorkerGroup string `json:"worker_group"`
ProcessInstancePriority Priority `json:"process_instance_priority"`
}
// TableName 会将 User 的表名重写为 `process_definition`
// 参考gorm约定
func (Command) TableName() string {
return "command"
}
// CheckAuth checks if authentication information exists
func SaveCommand(c *Command) error {
if err := db.Create(&c).Error; err != nil {
return err
}
return nil
}
func GetOneCommandToRun() (*Command, error) {
var cmd Command
err := db.Table("t_gs_command").First(&cmd).Error
return &cmd, err
}
func DeleteCommand(command *Command) error {
err := db.Table("t_gs_command").Delete(command).Error
return err
}
type TaskDependType int64
type WarningType int64
type FailureStrategy int64
<file_sep>/README.md
# Gsheduler 架构
<file_sep>/services/task_service/task.go
package task_service
type TaskNode struct {
Id string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Type string `json:"type"`
RunFlag string `json:"runFlag"`
Loc string `json:"loc"`
MaxRetryTimes int `json:"maxRetryTimes"`
RetryInterval int `json:"retryInterval"`
Params TaskParams `json:"params"`
PreTasks string `json:"preTasks"`
DepList []string `json:"depList"`
Dependence string `json:"dependence"`
ConditionResult string `json:"conditionResult"`
WorkerGroup string `json:"workerGroup"`
WorkerGroupId int `json:"workerGroupId"`
Timeout string `json:"timeout"`
}
type TaskParams struct {
// 资源文件列表
ResourceList []string `json:"resourceList"`
// Task 本地保留参数
LocalParams []string `json:"localParams"`
RawScript string `json:"rawScript"`
}
type Property struct {
}
| ecbe2b9c07d11458be5ab30217bc3275f0b0a4f4 | [
"Markdown",
"SQL",
"Go Module",
"Go"
] | 25 | Go | bugbug2022/gscheduler | 49b18a2e7858a9360a1628347fe7fe91ede27521 | 21dd7f00a14c54a2414e065407b3c55a486f44a2 |
refs/heads/master | <file_sep>#!/usr/bin/env python
# coding: utf-8
# ## Tic-Tac-Toe game
# In[1]:
def printBoard(board):
for i in range(len(board)):
for j in range(len(board)):
if board[i,j] == 0:
sys.stdout.write("_ ")
elif board[i,j] == 1:
sys.stdout.write("X ")
elif board[i,j] == 2:
sys.stdout.write("O ")
print()
# In[2]:
def checkzeros(board):
count = 0
for zero in np.nditer(board):
if zero == 0:
count+=1
return count
# In[3]:
def checkResult(board):
winner = None
# Horizontal winner
for i in range(len(board)):
if board[i,0] ==board[i,1] and board[i,1]==board[i,2] and board[i,0] != 0:
winner = board[i,0]
#vertical winner
for i in range(len(board)):
if board[0,i] ==board[1,i] and board[1,i]==board[2,i] and board[0,i] != 0:
winner = board[0,i]
# diagonal winner
if board[0,0] ==board[1,1] and board[1,1]==board[2,2] and board[0,0] != 0:
winner = board[0,0]
elif board[2,0] ==board[1,1] and board[1,1]==board[0,2] and board[2,0] != 0:
winner = board[2,0]
if checkzeros(board) == 0 and winner is None:
return 0
else:
if winner == 2:
return 10
elif winner == 1:
return -10
else:
return None
# In[4]:
def minimax(state,depth,isMaximizing):
returnstate = np.copy(state)
score = checkResult(returnstate)
if score is not None:
return score,returnstate
if isMaximizing:
bestscore = neg_inf
for i in range(3):
for j in range(3):
if state[i,j] == 0:
state[i,j] = 2
nextstate = np.copy(state)
scor,nullstate = minimax(nextstate,depth+1,False)
state[i,j] = 0
if scor> bestscore:
bestscore = scor
returnstate = np.copy(nextstate)
return bestscore,returnstate
else:
bestscore = inf
for i in range(3):
for j in range(3):
if state[i,j] == 0:
state[i,j] = 1
nextstate = np.copy(state)
# print(nextstate)
scor,nullstate = minimax(nextstate,depth+1,True)
# print(nullstate)
state[i,j] = 0
if scor < bestscore:
bestscore = scor
returnstate = np.copy(nextstate)
return bestscore,returnstate
# In[5]:
import numpy as np
import sys
neg_inf = -9999999999
inf = 9999999999
board = np.zeros((3,3),dtype = int)
print("Initial configuration of board is:-\n")
printBoard(board)
def main():
k = 0
global board
turn =int(input("enter your turn(1st or 2nd)"))
for i in range(9):
if (turn+i)&1: #its human turn as "X"
a,b = [int(x) for x in input("enter the row and column: ").split()]
board[a-1,b-1] = 1
printBoard(board)
if checkResult(board) == -10:
print("Hurrah! you won the game")
return
else:
temp_state = np.copy(board)
value,nextstate = minimax(temp_state,0,True )
board= np.copy(nextstate)
printBoard(board)
if checkResult(board)== 10:
print("pc won! you lost the game")
return
print("---------------------------------------------------------------------------------------------------------------------------------")
print("it's a tie")
# In[ ]:
# %debug
main()
# In[ ]:
<file_sep>import numpy as np
neg_inf = -9999999
inf = 9999999
# Returns neighbouring index
def getNeighbour(key):
arr = np.array([(1,3,8),(0,2,4),(1,5,13),(0,4,6,9),(1,3,5),(2,4,7,12),(3,7,10),(5,6,11),(0,9,20),(3,8,10,17),(6,9,14),(7,12,16),(5,11,13,19),(2,12,22),(10,15,17),
(14,16,18),(11,15,19),(9,14,18,20),( 15,17,19,21),(12,16,18,22),(8,17,21),(18,20,22),(13,19,21 )])
return arr[key]
#check whether a closed mill is formed or not.It returns a boolean value
def closed_mill(state,pos):
k0 = (state[0] == state[1] and state[1] == state[2] and state[2]) or (state[0] == state[3] and state[3] == state[6] and state[6]) or (state[0] == state[8] and state[8] == state[20] and state[20])
k1 = (state[0] == state[1] and state[1] == state[2] and state[2])
k2 = (state[2] == state[13] and state[13] == state[22] and state[22]) or (state[0] == state[1] and state[1] == state[2] and state[2]) or (state[2]==state[5] and state[5]==state[7] and state[7])
k3 = (state[0] == state[3] and state[3] == state[6] and state[6]) or (state[3] == state[4] and state[4] == state[5] and state[5]) or (state[3]==state[9] and state[9] == state[17] and state[17])
k4 = (state[3] == state[4] and state[4] == state[5] and state[5])
k5 = (state[2] == state[5] and state[5] == state[7] and state[7]) or (state[3] == state[4] and state[4] == state[5] and state[5]) or (state[5]==state[12] and state[12] == state[19] and state[19])
k6 = (state[0] == state[3] and state[3] == state[6] and state[6]) or (state[6] == state[10] and state[10] == state[14] and state[14])
k7 = (state[2] == state[5] and state[5] == state[7] and state[7]) or (state[7] == state[11] and state[11] == state[16] and state[16])
k8 = (state[0] == state[8] and state[8] == state[20] and state[20]) or (state[8] == state[9] and state[9] == state[10] and state[10])
k9 = (state[3] == state[9] and state[9] == state[17] and state[17]) or (state[8] == state[9] and state[9] == state[10] and state[10])
k10 =(state[6] == state[10] and state[10] == state[14] and state[14])
k11 = (state[7] == state[11] and state[11] == state[16] and state[16] )
k12 = (state[5] == state[12] and state[12] == state[19] and state[19]) or (state[11] == state[12] and state[12] == state[13] and state[13])
k13 = (state[11] == state[12] and state[12] == state[13] and state[13]) or (state[2] == state[13] and state[13] == state[22] and state[22])
k14 = (state[14] == state[15] and state[15] == state[16] and state[16]) or (state[14] == state[17] and state[17] == state[20] and state[20]) or (state[6] == state[10] and state[10] == state[14] and state[14])
k15 = (state[14] == state[15] and state[15] == state[16] and state[16]) or (state[15] == state[18] and state[18] == state[21] and state[21])
k16 = (state[14] == state[15] and state[15] == state[16] and state[16]) or (state[16] == state[19] and state[19] == state[22] and state[22])
k17 =(state[14] == state[17] and state[17] == state[20] and state[20]) or (state[17] == state[18] and state[18] == state[19] and state[19]) or (state[3] == state[9] and state[9] == state[17] and state[17])
k18 = (state[17] == state[18] and state[18] == state[19] and state[19]) or (state[15] == state[18] and state[18] == state[21] and state[21])
k19 = (state[16] == state[19] and state[19] == state[22] and state[22]) or (state[17] == state[18] and state[18] == state[19] and state[19]) or (state[5] == state[12] and state[12] == state[19] and state[19])
k20 = (state[14] == state[17] and state[17] == state[20] and state[20]) or (state[20] == state[21] and state[21] == state[22] and state[22]) or (state[0] == state[8] and state[8] == state[20] and state[20])
k21 = (state[15] == state[18] and state[18] == state[21] and state[21]) or (state[20] == state[21] and state[21] == state[22] and state[22])
k22 = (state[2] == state[13] and state[13] == state[22] and state[22]) or (state[20] == state[21] and state[21] == state[22] and state[22]) or (state[16] == state[19] and state[19] == state[22] and state[22])
res = [k0,k1,k2,k3,k4,k5,k6,k7,k8,k9,k10,k11,k12,k13,k14,k15,k16,k17,k18,k19,k20,k21,k22]
return res[pos]
class evaluate_utility():
def __init__(self):
self.evaluate = 0
self.board = []
# common minimax for all three phases of Nine Men's morris game
def minimax(state,depth,isMax,alpha,beta,isstage1,Heuristic):
return_utility = evaluate_utility()
if depth != 0:
current_utility = evaluate_utility()
if isMax:
if isstage1:
possible_conf = generateAIboardList(movesOfStage1(InvertedBoard(state)))
else:
possible_conf = generateAIboardList(possiblestage20r3(InvertedBoard(state)))
for board_state in possible_conf:
nextstate = np.copy(board_state)
current_utility = minimax(nextstate,depth-1,False,alpha,beta,isstage1,Heuristic)
if current_utility.evaluate > alpha:
alpha = current_utility.evaluate
return_utility.board = nextstate
if alpha >= beta:
break
return_utility.evaluate = alpha
else:
if isstage1:
possible_conf = movesOfStage1(state)
else:
possible_conf = movesOfStage3(state)
for board_state in possible_conf:
nextstate = np.copy(board_state)
current_utility = minimax(nextstate,depth-1,True,alpha,beta,isstage1,Heuristic)
if current_utility.evaluate < beta:
beta = current_utility.evaluate
return_utility.board = board_state
if alpha >= beta:
break
return_utility.evaluate = beta
else:
if isMax:
return_utility.evaluate = Heuristic(InvertedBoard(state),isstage1)
else:
return_utility = Heuristic(state,isstage1)
return return_utility
def possiblestage20r3(state,player = 1):
cont = 0
for i in range(len(state)):
if state[i] == player:
cont+=1
if cont == 3:
return movesOfStage3(state, player)
else:
return movesOfStage2(state, player)
# function to invert the board to train the AI
def InvertedBoard(state):
Inv_board = []
for i in state:
if i == 1:
Inv_board.append(2)
elif i == 2:
Inv_board.append(1)
else:
Inv_board.append(0)
return Inv_board
# generate the list of possible board configuration
def generateAIboardList(board_list):
result = []
for i in board_list:
result.append(InvertedBoard(i))
return result
def movesOfStage1(state):
board_list = []
for i in range(len(state)):
if state[i] == 0:
temp = np.copy(state)
temp[i] = 1
if closed_mill(temp,i):
board_list = removeMethod(temp,board_list,1)
else:
board_list.append(temp)
return board_list
# generates the possible board configuaration after all the coins are placed on the board
def movesOfStage2(state,player):
return_list = []
for i in range(len(state)):
if state[i] == player: # palyer == 1
adj_list = getNeighbour(i)
for j in adj_list:
if state[j] == 0:
temp = np.copy(state)
temp[j],temp[i]= player,0
if closed_mill(temp,j):
return_list = removeMethod(temp,return_list,player)
else:
return_list.append(temp)
return return_list
# generates all possible configuartion of the board when any of the player's coin is reduced to to three
def movesOfStage3(state):
return_list = []
for i in range(len(state)):
if state[i] == 1:
for j in len(state):
if state[j] == 0:
temp = np.copy(state)
temp[j] = 1
temp[i] = 0
if closed_mill(temp,j):
return_list = removeMethod(temp,return_list,1)
else:
return_list.append(temp)
return return_list
# removes a coin if opponent forms a mill of three coins
def removeMethod(state,board_list,player):
if player == 1:
opponent = 2
else:
opponent = 1
for i in range(len(state)):
if state[i] == opponent:
if closed_mill(state,i) == False:
temp = np.copy(state)
temp[i] = 0
board_list.append(temp)
else:
board_list.append(state)
return board_list
# return the total number of mill count at a givem configuration of board
def getMillCount(state,player):
count = 0
for i in range(len(state)):
if (state[i] == 0):
if closed_mill(state, i):
count += 1
return count
# check whether given coin can form a mill or not
def possibleMillFormation(position, state, player):
adjacent_list = getNeighbour(position)
for i in adjacent_list:
if (state[i] == player) and (not closed_mill(state,position)):
return True
return False
# returns the total number of possible mill formation
def countOfPossibleMill(state,player):
cnt = 0
for i in range(len(state)):
if (state[i] == player):
adjacent_list = getNeighbour(i)
for pos in adjacent_list:
if (player == 1):
if (state[pos] == 2):
state[i] = 2
if closed_mill(state, i):
cnt += 1
state[i] = player
else:
if (state[pos] == 1 and possibleMillFormation(pos, state, 1)):
cnt += 1
return cnt
# heuristic function
def HeuristicEvaluationFunction(state,isstage1):
score = 0
millPlayer1 = getMillCount(state, 1)
if not isstage1:
movable = len(possiblestage20r3(state))
MillsPlayer2 = countOfPossibleMill(state, 2)
if not isstage1:
if np.count_nonzero(state==2) <= 2 or movable == 0: # wining configuration
score = inf
elif np.count_nonzero(state==1) <= 2:
score = neg_inf
else:
if (np.count_nonzero(state==1) < 4):
score += 1 * millPlayer1
score += 2 * MillsPlayer2
else:
score += 2 * millPlayer1
score += 1 * MillsPlayer2
else:
if np.count_nonzero(state==2) < 4:
score += 1 * millPlayer1
score += 2 * MillsPlayer2
else:
score += 2 * millPlayer1
score += 1 * MillsPlayer2
return score
def printBoard(state):
board = np.copy(state)
################################################################################# board orientation
print(" pos(20)[{}]--------------------------[{}]--------------------pos(22)[{}]".format(board[20],board[21],board[22]))
print(" | \ pos(21) / |")
print(" | \ | / |")
print(" | \ | / |")
print(" | \ | / |")
print(" | 17[{}]____________pos(18)[{}]__________________19[{}] |".format(board[17],board[18],board[19]))
print(" | pos(17) | pos(19) |")
print(" | | \ | / | |")
print(" | | \ | / | |")
print(" | | \ pos(15) / | |")
print(" | | [{}]------------[{}]-------------[{}] | |".format(board[14],board[15],board[16]))
print(" | | pos(14) pos(16) | |")
print(" | | | | | |")
print(" | | | | | |")
print(" | | | | | |")
print(" pos(8)[{}]----[{}]----[{}]pos(10) pos(11)[{}]----[{}]---[{}]pos(13)".format(board[8],board[9],board[10],board[11],board[12],board[13]))
print(" | pos(9) | | pos(12) |")
print(" | | | | | |")
print(" | | | | | |")
print(" | | | | | |")
print(" | |pos(6)[{}]----------------------pos(7)[{}] | |".format(board[6],board[7]))
print(" | | / \ | |")
print(" | | / \ | |")
print(" | | / \ | |")
print(" | | / \ | |")
print(" |pos(3)[{}]_____________pos(4)[{}]______________pos(5)[{}] |".format(board[3],board[4],board[5]))
print(" | / | \ |")
print(" | / | \ |")
print(" | / | \ |")
print(" | / | \ |")
print(" pos(0)[{}]---------------------pos(1)[{}]-------------------pos(2)[{}]".format(board[0],board[1],board[2]))
#####################################################################################
def main(Heuristic):
depth = 2
board = np.zeros(23,dtype = int)
print("Initial configuration of Board is= ")
printBoard(board)
# print(closed_mill(board))
print("\n STAGE -> 1\n")
score = evaluate_utility()
for i in range(9):
print("its your turn \nEnter an input( 'as an array say,1,2,3,4.....')")
src = int(input("source position ="))
if board[src] == 0:
board[src] = 1
# printBoard(board)
if closed_mill(board,src):
print("Please enter only valid input")
rm = int(input("Enter the position to remove an item of opponent\n"))
# print(np.count_nonzero(board == 1))
if (board[rm] == 2 and closed_mill(board,rm) == False) or (closed_mill(board,rm) and np.count_nonzero(board == 1) == 3) :
board[rm] = 0
print("\nNew configuartion of the board after you entered is =\n")
printBoard(board)
utility = minimax(board,depth,True,neg_inf,inf,True,Heuristic )
# print(utility.board)
print("\nNew configuartion of the board after AI entered is =\n")
printBoard(utility.board)
board = np.copy(utility.board)
if utility.evaluate == neg_inf:
print("you lost")
print("\nPHASE ->2\n")
print("Now you are out of coins, SInce you have entered in phase-2 \n Configuration of the board is")
while True:
printBoard(board)
print("Enter the position of your coin which you want to move(only valid positions are allowed):")
src = int(input("source index"))
dest = int(input("Destination index"))
board[src],board[dest] = board[dest],board[src]
if closed_mill(board,dest):
print("Now yur coins have formed mill ,so please enter below the index of opposition coin to remove it from the board")
pos = int(input("Position of opposition's coin="))
if board[pos] == 2 :
if (not closed_mill(board,pos) or (closed_mill(board,pos) and np.count_nonzero(board == 1) == 3)):
board[pos] == 0
print("You have successfully removed the opponent")
printBoard(board)
utility = minimax(board,depth,True,neg_inf,inf,True,Heuristic )
if utility.evaluate == neg_inf:
print("You lost the game")
exit(0)
else:
board = utility.board
if __name__ == "__main__":
print("Welcome to Nine Men's Morris Game\n")
main(HeuristicEvaluationFunction)
<file_sep>"""
Python API client wrapper for the LocationIQ Geocoding service
LocationIQ provides 10,000 requests/day for free. You can signup here to get the API Key : https://locationiq.org/
API documentation is available on https://locationiq.org/docs
"""
import requests
import json
from requests.exceptions import RequestException
class LocationIq(object):
"""LocationIQ API client wrapper."""
def __init__(self, key=None, format="json", addressdetails=1, limit=10, params={}, timeout=None, test_mode=False):
"""Initialize the API Client wrapper
:param key: LocationIQ API key. You can signup here to get the api key: https://locationiq.org
:param format: Output response format. json, xml are available formats. (Defaults to json)
:param addressdetails: Include a breakdown of the address into elements. Accepted values are 0 or 1.
:param limit: Limit the number of returned results. Default is 10. Max is 50.
:param params: Set extra params to return desired results. This includes viewbox, zoom, postalcode etc.
:param timeout: Connect and read timeout in seconds. Specify a tuple (connect, read) to specify each timeout individually.
:param test_mode: Set to True to enable test mode. Defaults to False.
"""
self.key = key
self.timeout = timeout
self.test_mode = test_mode
self.params = {
"format": format,
"addressdetails": addressdetails,
"limit": limit,
"accept-language": "en"
}
# Content headers
self.headers = {'content-type': 'application/json'}
extra_params = {
"viewbox": [],
"bounded": 0,
"zoom": 18,
"street": None,
"city": None,
"county": None,
"state": None,
"country": None,
"postalcode": None
}
# If user includes any extra params, the update the self.params object
for param, value in params:
if param in extra_params:
self.params.update({param: value})
def geocode(self, query=None):
"""Search the given string or address from LocationIQ Geocoder
:param query: String to search for
:returns result: A list of addresses matching the given search string
"""
url = "https://locationiq.org/v1/search.php"
data = {
"key": self.key,
"q": query
}
data.update(self.params)
r = LocationIqRequest(url)
r.get(data, self.headers)
return r.response
def reverse_geocode(self, lat, lon):
"""Get the address for the given latitude, longitude from LocationIQ reverse geocoder.
:param lat: Latitude
:param lon: Longitude
:returns result: dict
"""
url = "https://locationiq.org/v1/reverse.php"
data = {
"key": self.key,
"lat": lat,
"lon": lon
}
data.update(self.params)
r = LocationIqRequest(url)
r.get(data, self.headers)
return r.response
class LocationIqRequest(object):
"""
Helper class for making requests.
:param url: Base url or endpoint url to send the requests
"""
def __init__(self, url=None):
"""Initialize request object."""
self.url = url
self.data = None
self.code = None
self.response = None
def request(self, method='GET', params={}, headers={}):
"""
Make a request.
If the request was successful (i.e no exceptions), you can find the
HTTP response code in self.code and the response body in self.value.
:param method: Request method (Only GET supported)
:param params: Request parameters
:param headers: Request headers
"""
self.data = None
self.code = None
kwargs = dict(
params=params,
headers=headers,
)
request_func = getattr(requests, method.lower())
try:
res = request_func(self.url, **kwargs)
self.data = res.json()
self.code = res.status_code
res.raise_for_status()
return self.data
except requests.exceptions.RequestException as err:
# Concatenate the error code and the error message
raise LocationIqError.factory(res.status_code)
except requests.exceptions.HTTPError as errh:
raise LocationIqError.factory(res.status_code, errh)
except requests.exceptions.ConnectionError as errc:
raise LocationIqError.factory(500, errc)
except requests.exceptions.Timeout as errt:
raise LocationIqError.factory(500, errt)
def get(self, params: object = {}, headers: object = {}):
"""
Make a GET request
:param params: Request parameters to send in the url
:param headers: Request Headers
:return response: Response
"""
self.response = self.request("GET", params=params, headers=headers)
class LocationIqError(Exception):
"""Exception raised when the server returns a known HTTP error code.
Known HTTP error codes include:
* 404 Unable to geocode
* 401 Invalid key or key not active
* 400 Invalid request
* 429 Request Ratelimited error
* 500 Error on server's side
"""
@staticmethod
def factory(err_code, *wargs):
"""Create exceptions through a Factory based on the HTTP error code."""
if err_code == 404:
# No location or places were found for the given input
return LocationIqNoPlacesFound(err_code, *wargs)
elif err_code == 401:
# An invalid API key was provided
return LocationIqInvalidKey(err_code, *wargs)
elif err_code == 400:
# Required parameters are missing, or invalid.
return LocationIqInvalidRequest(err_code, *wargs)
elif err_code == 429:
# Request exceeded the per-second / minute / day rate-limits set on your account
return LocationIqRequestLimitExeceeded(err_code, *wargs)
else:
return LocationIqServerError(err_code, *wargs)
class LocationIqNoPlacesFound(LocationIqError):
# No location or places were found for the given input
pass
class LocationIqInvalidKey(LocationIqError):
# An invalid API key was provided or API key is not active
pass
class LocationIqInvalidRequest(LocationIqError):
# Required parameters are missing, or invalid.
pass
class LocationIqRequestLimitExeceeded(LocationIqError):
# Request exceeded the per-second / minute / day rate-limits set on your account
pass
class LocationIqServerError(LocationIqError):
# This is an error on the server's side, we monitor this 24x7 and you should try again.
pass
| ebfa20593c1d404326a12ae0b583f2dc36f23b91 | [
"Python"
] | 3 | Python | chandan5362/Artificial-Intelligence-spring2020 | 98aa6a3452eac46c9ae5f339daec873cbfdb736d | 0c6c948925726e1b34ce98ed860a20181aeb8221 |
refs/heads/master | <file_sep># parseFIO
This python script parses through the output of a fio run
<file_sep># <NAME>
# May 7 2017
# Parsing raw data files from FIO benchmark file
# Pre-condition:
# fio_raw_disk_perf_blksize1K_datasize10240MB.csv
# fio_raw_disk_perf_blksize4K_datasize10240MB.csv
#
# This script compares the write IOPS of synchronous (sync) and asynchronous (async) I/O
import csv
import pprint
import re
import matplotlib.pyplot as plt
s=""
asynclst = []
synclst = []
asynclst1 = []
synclst1 = []
with open("fio_raw_disk_perf_blksize1K_datasize10240MB.csv", 'r', encoding='utf-8') as csvfile:
# find the format
fileDialect = csv.Sniffer().sniff(csvfile.read(1024))
csvfile.seek(0)
# read the CSV file into a dictionary
dictReader = csv.DictReader(csvfile, dialect=fileDialect)
for row in dictReader:
s = row['jobname']
if (bool(re.match("async-",s))):
asynclst.append(row['WRITE_IOPS'])
if (bool(re.match("sync-",s))):
synclst.append(row['WRITE_IOPS'])
with open("fio_raw_disk_perf_blksize4K_datasize10240MB.csv", 'r', encoding='utf-8') as csvfile:
# find the format
fileDialect = csv.Sniffer().sniff(csvfile.read(1024))
csvfile.seek(0)
# read the CSV file into a dictionary
dictReader = csv.DictReader(csvfile, dialect=fileDialect)
for row in dictReader:
s = row['jobname']
if (bool(re.match("async-",s))):
asynclst1.append(row['WRITE_IOPS'])
if (bool(re.match("sync-",s))):
synclst1.append(row['WRITE_IOPS'])
fig = plt.figure()
fig.subplots_adjust(bottom=0.2)
ax1 = fig.add_subplot(111)
line1 = ax1.plot(asynclst,'bo-',label='async WriteIOPS 1K_blks')
line2 = ax1.plot(synclst,'go-',label='sync WriteIOPS 1Kblks')
line3 = ax1.plot(asynclst1,'ro-',label='async WriteIOPS 4K_blks')
line4 = ax1.plot(synclst1,'yo-',label='sync WriteIOPS 4K_blks')
ax1.set_ylim(0,300000)
plt.xlabel("x-axis")
plt.ylabel("write IOPS")
plt.title("Sync and Async Write IOPS")
plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.07),ncol=2)
plt.grid()
plt.show() | 57e43c1070201897646b2d3ba8e51840530d1893 | [
"Markdown",
"Python"
] | 2 | Markdown | ciscofran/parseFIO | cf044a3b8e1ea23b2f81f9e8d2c7b4a35b1fe498 | a76f7acd3ca4eeb015da75de1aeb1ce72e12d8bf |
refs/heads/master | <file_sep>import { AppExtensionSDK, FieldExtensionSDK } from 'contentful-ui-extensions-sdk'
export interface AppConfigParams {
sdk: AppExtensionSDK
}
export interface SavedParams {
clientId: string
}
export interface FieldExtensionProps {
sdk: FieldExtensionSDK
}
| aaa7d36092807822aa659caf9dee1a278434f88a | [
"TypeScript"
] | 1 | TypeScript | rkparsons/contentful-app-soundcloud | 608e242f3565f4cd44172bf5457094385b51ca75 | 8ee801beaddde498a3a9cf6149da5e916e9c4005 |
refs/heads/master | <repo_name>Serg-Pogrebnyak/ZoomSDK<file_sep>/ZoomSDK/ZoomSDK/ViewController.swift
//
// ViewController.swift
// ZoomSDK
//
// Created by <NAME> on 4/5/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
import ZoomAuthenticationHybrid
class ViewController: UIViewController, ZoomVerificationDelegate, URLSessionDelegate {
@IBOutlet fileprivate weak var addUserButton: UIButton!
let zoomServerBaseURL = "https://api.zoomauth.com/api/v1/biometrics";
let licenseKey = "<KEY>"
let publicKey =
"-----BEGIN PUBLIC KEY-----\n" +
"<KEY>" +
"<KEY>" +
"<KEY>" +
"<KEY>f<KEY>j<KEY>f\n" +
"<KEY>j3ahfYxioBH7F7HQxzmWkwDyn3bqU54eaiB7f0ftsPpWM\n" +
"ceUaqkL2DZUvg<KEY>5y1/Gk<KEY>9XG/SwXJ30BbVUehTbVcD70+ZF\n" +
"8QIDAQAB\n" +
"-----END PUBLIC KEY-----"
let userIdentifier = "gvyuh78yiu1"
override func viewDidLoad() {
super.viewDidLoad()
Zoom.sdk.setFacemapEncryptionKey(publicKey: publicKey)
Zoom.sdk.initialize(
appToken: licenseKey,
completion: { initializationSuccessful in
self.addUserButton.isEnabled = initializationSuccessful
print("ZoOm initialize success: \(initializationSuccessful)")
if initializationSuccessful {
self.isUserEnrolled(callback: { (hasUser) in
if hasUser {
self.deleteUserEnrollment(callback: { (successDeleating) in
if successDeleating {
self.startScaninng()
} else {
print("Errror deleating!!!!")
}
})
} else {
self.startScaninng()
}
})
}
}
)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
DispatchQueue.main.async {
Zoom.sdk.preload()
}
}
fileprivate func startScaninng() {
let customization: ZoomCustomization = ZoomCustomization()
customization.showPreEnrollmentScreen = false
Zoom.sdk.setCustomization(customization)
let zoomVerificationVC = Zoom.sdk.createVerificationVC(delegate: self)
zoomVerificationVC.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
zoomVerificationVC.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
self.present(zoomVerificationVC, animated: true, completion: nil)
}
@IBAction func didTapScanButton(_ sender: Any) {
startScaninng()
}
// MARK: - Zoom verification deleagte function
func onBeforeZoomDismiss(status: ZoomVerificationStatus, retryReason reason: ZoomRetryReason) -> Bool {
return false
}
func onZoomVerificationResult(result: ZoomVerificationResult) {
print("get result")
guard result.status.rawValue == 0 else {
print("error scanning")
return
}
registerNewUser(result: result)
}
// MARK: - register new user
fileprivate func registerNewUser(result: ZoomVerificationResult) {
let zoomFacemapStr: String = (result.faceMetrics?.zoomFacemap)!.base64EncodedString(options: [])
let endpoint = "/enrollment"
var parameters: [String : Any] = [String: Any]()
parameters["sessionId"] = result.sessionId
parameters["enrollmentIdentifier"] = userIdentifier
parameters["facemap"] = zoomFacemapStr
makeApiCall(method: .post, endpoint: endpoint, parameters: parameters) { (isJson) in
guard let json = isJson else {
print("error register user")
return
}
if (json["data"] as? [String : Any])?["livenessResult"] as? String == "passed" {
print("User create")
self.sendImageOnServer()
} else {
print("User NO Created some error!")
}
}
}
// MARK: - delete user
fileprivate func deleteUserEnrollment(callback: @escaping (Bool) -> Void ) {
let endpoint: String = "/enrollment/\(userIdentifier)"
var parameters: [String : Any] = [:]
parameters["enrollmentIdentifier"] = userIdentifier
makeApiCall(method: .delete, endpoint: endpoint, parameters: parameters) { (isJson) in
guard let json = isJson else {
print("error deleating user")
return
}
callback(((json["meta"] as? [String : Any])?["ok"] as? Bool)!)
print("user is deleate - \(((json["meta"] as? [String : Any])?["ok"] as? Bool)!)")
}
}
// MARK: - authentication user
fileprivate func authenticationUser(imageInBase64: String) {
let endpoint = "/authenticate"
var parameters: [String : Any] = [String: Any]()
parameters["sessionId"] = generateUniqueSessionId()
parameters["source"] = ["enrollmentIdentifier": userIdentifier]
parameters["targets"] = [["facemap": imageInBase64]]
makeApiCall(method: .post, endpoint: endpoint, parameters: parameters) { (isJson) in
guard let json = isJson else {
print("error authentication user")
return
}
if ((json["data"] as? [String : Any])?["results"] as? [[String : AnyObject]])?[0]["authenticated"] as? Int == 1 {
print("User was authorization")
} else {
print("User not enrolled or invalid enrollmentIdentifier")
}
}
}
// MARK: - create facemap user from image
fileprivate func sendImageOnServer() {
let endpoint: String = "/facemap"
var parameters: [String : Any] = [:]
let imageData: Data = UIImage.init(named: "sergFace")!.jpegData(compressionQuality: 1.0)!
parameters["images"] = [imageData.base64EncodedString()]
parameters["sessionId"] = generateUniqueSessionId()
makeApiCall(method: .post, endpoint: endpoint, parameters: parameters) { (isJson) in
guard let json = isJson else {
print("error create face-map user")
return
}
if json["data"] != nil {
self.authenticationUser(imageInBase64: json["data"] as! String) //todo - add validation on is string
print("Successfull create face map")
} else {
print("erro creating face map")
}
}
}
// MARK: - check user id
func isUserEnrolled(callback: @escaping (Bool) -> Void) {
let endpoint: String = "/enrollment/\(userIdentifier)"
var parameters: [String : Any] = [:]
parameters["enrollmentIdentifier"] = userIdentifier
parameters["sessionId"] = generateUniqueSessionId()
makeApiCall(method: .get, endpoint: endpoint, parameters: parameters) { (isJson) in
guard let json = isJson else {
print("error cehck user")
return
}
print("enrolled: \(((json["meta"] as? [String : Any])?["ok"] as? Bool)!)")
callback(((json["meta"] as? [String : Any])?["ok"] as? Bool)!)
}
}
// MARK: - generate session id
func generateUniqueSessionId() -> String {
let length = 14
let symbols : NSString = "0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"
var randomString = ""
for _ in 0 ..< length {
let rand = arc4random_uniform(UInt32(symbols.length))
var nextChar = symbols.character(at: Int(rand))
randomString += NSString(characters: &nextChar, length: 1) as String
}
return randomString
}
// MARK: Create and make api call
fileprivate func makeApiCall(method: ApiMethod, endpoint: String, parameters: [String: Any], callback: @escaping ([String: AnyObject]?) -> Void) {
let request = buildHTTPRequest(method: method, endpoint: endpoint, parameters: parameters)
let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request as URLRequest, completionHandler: { responseData, response, error in
guard let responseData = responseData , error == nil else {
callback(nil)
return
}
do {
let json = try JSONSerialization.jsonObject(with: responseData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String: AnyObject]
callback(json)
}
catch {
callback(nil)
}
})
task.resume()
}
fileprivate func buildHTTPRequest(method: ApiMethod, endpoint: String, parameters: [String : Any]) -> NSMutableURLRequest {
let request = NSMutableURLRequest(url: NSURL(string: zoomServerBaseURL + endpoint)! as URL)
request.httpMethod = method.rawValue
// Only send data if there are parameters and this is not a GET request
if parameters.count > 0 && method != ApiMethod.get {
request.httpBody = try! JSONSerialization.data(withJSONObject: parameters as Any, options: JSONSerialization.WritingOptions(rawValue: 0))
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue(licenseKey, forHTTPHeaderField: "X-App-Token")
let sessionId: String = parameters["sessionId"] as? String ?? "nil"
request.addValue("facetec|zoomsdk|ios|\(Bundle.main.bundleIdentifier!)|\(licenseKey)|\(UIDevice.current.zoomDeviceIdentifierForVendor)|\(UIDevice.current.modelName)|\(Zoom.sdk.version)|\(Locale.current.identifier)|\(Bundle.main.preferredLocalizations.first ?? "Unknown")|\(sessionId)",
forHTTPHeaderField: "User-Agent")
return request
}
enum ApiMethod: String {
case post = "POST"
case get = "GET"
case delete = "DELETE"
}
}
private let deviceIdentifierSingleton: String = UIDevice.current.identifierForVendor?.uuidString ?? ""
extension UIDevice {
var zoomDeviceIdentifierForVendor: String {
return deviceIdentifierSingleton
}
var modelName: String {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
let identifier = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8 , value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
switch identifier {
case "iPod5,1": return "iPod Touch 5"
case "iPod7,1": return "iPod Touch 6"
case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4"
case "iPhone4,1": return "iPhone 4s"
case "iPhone5,1", "iPhone5,2": return "iPhone 5"
case "iPhone5,3", "iPhone5,4": return "iPhone 5c"
case "iPhone6,1", "iPhone6,2": return "iPhone 5s"
case "iPhone7,2": return "iPhone 6"
case "iPhone7,1": return "iPhone 6 Plus"
case "iPhone8,1": return "iPhone 6s"
case "iPhone8,2": return "iPhone 6s Plus"
case "iPhone9,1", "iPhone9,3": return "iPhone 7"
case "iPhone9,2", "iPhone9,4": return "iPhone 7 Plus"
case "iPhone8,4": return "iPhone SE"
case "iPhone10,1", "iPhone10,4": return "iPhone 8"
case "iPhone10,2", "iPhone10,5": return "iPhone 8 Plus"
case "iPhone10,3", "iPhone10,6": return "iPhone X"
case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2"
case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3"
case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4"
case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air"
case "iPad5,3", "iPad5,4": return "iPad Air 2"
case "iPad6,11", "iPad6,12": return "iPad 5"
case "iPad7,5", "iPad7,6": return "iPad 6"
case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini"
case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2"
case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3"
case "iPad5,1", "iPad5,2": return "iPad Mini 4"
case "iPad6,3", "iPad6,4": return "iPad Pro 9.7 Inch"
case "iPad6,7", "iPad6,8": return "iPad Pro 12.9 Inch"
case "iPad7,1", "iPad7,2": return "iPad Pro 12.9 Inch 2. Generation"
case "iPad7,3", "iPad7,4": return "iPad Pro 10.5 Inch"
case "AppleTV5,3": return "Apple TV"
case "AppleTV6,2": return "Apple TV 4K"
case "AudioAccessory1,1": return "HomePod"
default: return identifier
}
}
}
| b5be38c4eaee4a90e236cd52d6fefc5d0503c75d | [
"Swift"
] | 1 | Swift | Serg-Pogrebnyak/ZoomSDK | 96a8ca432ea2ed30d6d23cbb27579e08beb7c747 | 6d462d54448247e87333246080adaffb8435c7a6 |
refs/heads/master | <file_sep>require 'active_record'
require 'twitter'
ActiveRecord::Base.establish_connection(ENV["DATABASE_URL"] || "sqlite3:db/development.db")
class LatestFavsTweets < ActiveRecord::Base
end
def twitter_client
@client ||= Twitter::REST::Client.new do |config|
config.consumer_key = ENV['TWITTER_CONSUMER_KEY']
config.consumer_secret = ENV['TWITTER_CONSUMER_SECRET']
config.access_token = ENV['TWITTER_ACCESS_TOKEN']
config.access_token_secret = ENV['TWITTER_ACCESS_TOKEN_SECRET']
end
end
def latest_fav
@latest_fav ||= (LatestFavsTweets.order(:created_at).all.first || LatestFavsTweets.new)
end
favs = twitter_client.favorites(ENV['USER_SCREEN_NAME'], count: 1)
latest_fav.status_id = favs.first.id
latest_fav.save!
<file_sep># frozen_string_literal: true
# A sample Gemfile
source "https://rubygems.org"
# gem "rails"
gem 'activerecord'
gem 'hatenablog'
gem 'pry'
gem 'sinatra'
gem 'sinatra-activerecord'
gem 'twitter'
group :development, :test do
gem 'foreman'
gem 'sqlite3'
end
group :production do
gem 'pg'
end
<file_sep>require 'bundler'
Bundler.require
require './app'
use ActiveRecord::ConnectionAdapters::ConnectionManagement
run Sinatra::Application
<file_sep>class ChangeStatusIdType < ActiveRecord::Migration[4.2]
def change
change_column :latest_favs_tweets, :status_id, :string
end
end
<file_sep># favs2blogposts
## About
Twitter での「いいね」(fav)を自動で「はてなブログ」に投稿する heroku app です。
## Setup
### 1. 準備するもの
以下のもの・準備が必要です。
* はてなアカウント
* 投稿先となるはてなブログ
* はてなの[アプリケーション登録](https://www.hatena.ne.jp/oauth/develop)
* Twitter アカウント
* [Twitter app の登録](https://apps.twitter.com/)
* [heroku](https://www.heroku.com/) のアカウント
* Ruby が実行可能な PC
* Mac なら最初から入っているもので大丈夫(多分)
### 2. はてなアプリケーションの認証情報の取得
[はてなブログ API 用の gem を書いた - blog.kymmt.com](http://blog.kymmt.com/entry/hatenablog_gem) に書いて頂いている手順で認証情報を取得します。(Ruby が必要です。)
```ruby
$ gem install hatenablog
$ get_access_token <コンシューマキー> <コンシューマシークレット>
Visit this website and get the PIN: https://www.hatena.com/oauth/authorize?oauth_token=XXXXXXXXXXXXXXXXXXXX
Enter the PIN: <ここに PIN を入力する> [Enter]
Access token: <アクセストークン>
Access token secret: <アクセストークンシークレット>
```
favs2blogposts の動作には以下の4つの情報が必要です。
* コンシューマーキー
* コンシューマーシークレット
* アクセストークン
* アクセストークンシークレット
### 3. heroku へのデプロイを行う
[](https://heroku.com/deploy)
↑のボタンを押すと、以下の様なデプロイ設定画面が開きます。

開いた画面で、以下の情報を入力してください。
* App Name
* `ここで指定した文字列.herokuapp.com` というドメイン名になります。
* 指定しない場合、ランダムな文字列が割り当てられます。
* Runtime Selection
* 通常は初期設定( `United States` )のままで問題ないはずです。
* Config Variables
* TWITTER_CONSUMER_KEY
* 登録した Twitter app の管理画面から取得できる consumer key を入力します
* TWITTER_CONSUMER_SECRET
* 登録した Twitter app の管理画面から取得できる consumer secret を入力します
* TWITTER_ACCESS_TOKEN
* 登録した Twitter app の管理画面から取得できる access token を入力します
* TWITTER_ACCESS_TOKEN_SECRET
* 登録した Twitter app の管理画面から取得できる access token secret を入力します
* HATENA_CONSUMER_KEY
* 登録した はてなアプリケーション の管理画面から取得できる consumer key を入力します
* HATENA_CONSUMER_SECRET
* 登録した はてなアプリケーション の管理画面から取得できる consumer secret を入力します
* HATENA_ACCESS_TOKEN
* 登録した はてなアプリケーション の管理画面から取得できる access token を入力します
* HATENA_ACCESS_TOKEN_SECRET
* 登録した はてなアプリケーション の管理画面から取得できる access token secret を入力します
* HATENA_USER_ID
* はてなブログへ投稿するユーザーのはてなIDを入力します。(id:xxxxx の xxxxx の部分)
* HATENA_BLOG_ID
* 登録するはてなブログの初期ドメインを入力します。 `example.hatenablog.com` などです。
* カスタムドメインを設定している場合でも、初期ドメインを入力してください。
* USER_SCREEN_NAME
* 取得対象の Twitter ID を入力します。( `@a-know` の `a-know` の部分)
* BLOG_TIMEZONE
* タイムゾーンを指定します。
* 通常は初期値( `Asia/Tokyo` )のままで問題ないはずです。
* このタイムゾーンを基準として投稿タイトル( `yy-mm-dd の favs` )が決められます。
これらの情報の入力が完了したら、 `Deploy for Free` ボタンを押し、しばらくすると以下の様な表示が出て、デプロイが完了します。

### 4. 定期実行の設定
毎日決められた時間に favs の収集・ブログへの投稿を行うよう、スケジュール設定を行う必要があります。
heroku app の管理画面 `https://dashboard.heroku.com/apps/{3. で指定した App Name}` を開き、 `Heroku Scheduler` リンクを押します。

するとスケジュール設定画面になりますので、以下の画像を参考に設定をし保存してください。

注意事項としては、実行時間の指定は UTC での指定になる点です。
おすすめの指定は `15:30` です。これは日本時間でいうと 0:30 になり、そのタイミングで前日の favs を収集し投稿することになります。
## 注意事項
* 収集・投稿できるものは「その日favしたツイート」ではなく、「前回はてなブログに自動投稿されてから今回の自動実行の間までにつぶやかれたツイートのうち、favされたもの」となります。
* 例えば、昔のツイートをその日にfavしても収集・投稿されません。
* 実行するたびに、「ここまでのツイートをブログに登録した」という情報をアプリケーションが記録しています。
* 初回はデプロイしたタイミングで記録されますので、最初の投稿はそのタイミング以降のfavが投稿されることになります。
* (適当な作りなので、)1回で100を超えるfavは登録できません。
* 先頭100件を登録します
<file_sep>require 'sinatra'
require 'active_record'
require 'twitter'
require 'hatenablog'
ActiveRecord::Base.establish_connection(ENV["DATABASE_URL"] || "sqlite3:db/development.db")
class LatestFavsTweets < ActiveRecord::Base
end
def twitter_client
@client ||= Twitter::REST::Client.new do |config|
config.consumer_key = ENV['TWITTER_CONSUMER_KEY']
config.consumer_secret = ENV['TWITTER_CONSUMER_SECRET']
config.access_token = ENV['TWITTER_ACCESS_TOKEN']
config.access_token_secret = ENV['TWITTER_ACCESS_TOKEN_SECRET']
end
end
def latest_fav
@latest_fav ||= (LatestFavsTweets.order(:created_at).all.first || LatestFavsTweets.new)
end
def register_latest_fav
favs = twitter_client.favorites(ENV['USER_SCREEN_NAME'], count: 1)
latest_fav.status_id = favs.first.id
latest_fav.save!
end
def yesterday
old = ENV['TZ']
utc = Time.now.dup.utc - 86400
ENV['TZ'] = ENV['BLOG_TIMEZONE']
output = utc.localtime
ENV['TZ'] = old
output
end
if latest_fav.nil? || latest_fav.status_id.nil?
register_latest_fav
else
favs = twitter_client.favorites(ENV['USER_SCREEN_NAME'], since_id: latest_fav.status_id, count: 100)
unless favs.empty?
latest_fav.status_id = favs.first.id
latest_fav.save!
end
end
content = favs.empty? ? "この日の fav はありませんでした。" : ""
favs.each do |fav|
content += "[https://twitter.com/#{fav.user.screen_name}/status/#{fav.id}:embed]\n"
end
Hatenablog::Client.create do |blog|
blog.post_entry(yesterday.strftime("%Y-%m-%d のfavs"), content, ['今日の favs'])
end
| 6d4353064cbbe08964c8ac855dceea3e623da535 | [
"Markdown",
"Ruby"
] | 6 | Ruby | a-know/favs2blogposts | 1c5f204a345f6ae15e2aee1e138d7e504096ad9c | c1c7b3c9bc302c20714974013178795087b91ecd |
refs/heads/master | <file_sep><?php
namespace App\Listeners;
use App\Events\OrderCreated;
use Exception;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log;
class SendOrderToWebhookNotification
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param OrderCreated $event
* @return void
*/
public function handle(OrderCreated $event)
{
try {
$data = [
'customer_id' => $event->customer->id,
'order_id' => $event->order->id,
'amount' => $event->order->total_price,
'description' => $event->order->description,
];
$client = new \GuzzleHttp\Client();
$request = $client->post(env('WEBHOOK_URL'), [
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json'
],
'body' => json_encode($data)
]);
$response = $request->getBody();
$content = json_decode($response->getContents());
if ($content->status !== 'OK') {
throw new Exception('Error when sending data to Webhook. Response status is not OK', 500);
}
} catch (Exception $e) {
Log::error($e->getMessage());
}
}
}
<file_sep># Order Service
## How To Setup
```bash
git clone https://github.com/taylanunutmaz/order-service.git
cd order-service
# do not forget to arrange .env file
cp .env.example .env
composer install
php artisan migrate
```
## The webhook.site Address
Site :[https://webhook.site/#!/<PASSWORD>-31a0-4495-<PASSWORD>/f5e8aede-655f-4fb7-b2b7-92d0d0fe7062/1](https://webhook.site/#!/1<PASSWORD>c-3<PASSWORD>/f5e8aede-655f-4fb7-b2b7-92d0d0fe7062/1)
<file_sep><?php
namespace App\Notifications;
use App\Models\Order;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class SendEmailWhenOrderCreatedNotification extends Notification implements ShouldQueue
{
use Queueable;
/**
* The order instance.
*
* @var \App\Models\Order
*/
public $order;
/**
* Create a new notification instance.
*
* @return void
*/
public function __construct(Order $order)
{
$this->order = $order;
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->greeting("Hello {$notifiable->title}")
->line('An order created!')
->line("Name: {$this->order->name}")
->line("Description: {$this->order->description}")
->line("Price: {$this->order->total_price}");
}
}
<file_sep><?php
namespace App\Http\Controllers\Api\Customer;
use App\Events\OrderCreated;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\Customer\StoreOrderRequest;
use App\Http\Resources\Customer as CustomerResource;
use App\Http\Resources\CustomerOrders;
use App\Http\Resources\Order as OrderResource;
use App\Models\Customer;
use App\Notifications\SendEmailWhenOrderCreatedNotification;
use Illuminate\Http\Request;
class OrderController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Customer $customer)
{
return new CustomerOrders($customer);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(StoreOrderRequest $request, Customer $customer)
{
$order = $customer->orders()->create($request->only(
'total_price',
'name',
'description'
));
$customer->notify(new SendEmailWhenOrderCreatedNotification($order));
event(new OrderCreated($order, $customer));
return new OrderResource($order);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
| ad2ced3f2b25cfced4b39a44606b5cd917cce7d2 | [
"Markdown",
"PHP"
] | 4 | PHP | taylanunutmaz/order-service | f623a0a6084ddc41f5811a2ff1f40e6055036bdd | c6ba04de8cc5a765d2ae9521deb3b69b14ce86c1 |
refs/heads/master | <repo_name>YomariCodeCamp2015/pocketnurse<file_sep>/app/src/main/java/com/anishparajuli/pn/pocketnurse/news.java
package com.anishparajuli.pn.pocketnurse;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class news extends ActionBarActivity {
WebView news;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
news=(WebView)findViewById(R.id.newsview);
news.setWebViewClient(new WebViewClient());
news.getSettings().setJavaScriptEnabled(true);
news.loadUrl("http://www.cnn.com/health");
news.requestFocus();
}
public void cnn(View v){
news.loadUrl("http://www.cnn.com/health");
}
public void bbc(View v){
news.loadUrl("http://www.bbc.co.uk/health");
}
public void yahoo(View v){
news.loadUrl("http://www.yahoo.com/health");
}
public void wmd(View v){
news.loadUrl("http://www.webmd.com");
}
}
| 0ec22e30489e82b9e71f9068e7ebeaf54a968687 | [
"Java"
] | 1 | Java | YomariCodeCamp2015/pocketnurse | a34f60be71070f1667e2449876a53f939acc6302 | 9bef0fc9e3d4e0d9a51c97840195c2fe78cadd30 |
refs/heads/master | <repo_name>Subuday77/IPcheck<file_sep>/src/main/java/com/defineIp/IPcheck/rest/IPcheckController.java
package com.defineIp.IPcheck.rest;
import java.util.StringTokenizer;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.defineIp.IPcheck.beans.Result;
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/request")
public class IPcheckController {
@Autowired
HttpServletRequest servletRequest;
@Autowired
Result result;
@RequestMapping("/send")
public ResponseEntity<?> getPost(HttpServletRequest request) {
result.setProtocol(request.getProtocol());
result.setRequestType(request.getMethod());
result.setRemoteAddress(getClientIpAddress(request));
System.out.println(result.getProtocol() + " " + result.getRequestType() + " request:\n" + request
+ "\nCame from IP:\n" + result.getRemoteAddress());
return new ResponseEntity<Result>(result, HttpStatus.OK);
}
public String getClientIpAddress(HttpServletRequest request) {
String xForwardedForHeader = servletRequest.getHeader("X-Forwarded-For");
if (xForwardedForHeader == null) {
return request.getRemoteAddr();
} else {
return new StringTokenizer(xForwardedForHeader, ",").nextToken().trim();
}
}
@GetMapping("/getresult")
public ResponseEntity<?> getResult() {
return new ResponseEntity<>("Permanently moved to https://request-checker2000.herokuapp.com",
HttpStatus.MOVED_PERMANENTLY);
}
}
| ffdaa014317021f5efa25412a04bab831b44d0f1 | [
"Java"
] | 1 | Java | Subuday77/IPcheck | 8869d9f6361fcec6f551c8b41823cdff812974a7 | e72c000270ebddca723d2f63c9d2c6f62984d3d0 |
refs/heads/master | <file_sep>/**
* lxd.go - LXD API discovery implementation
*
* @author <NAME> <<EMAIL>>
*/
package discovery
import (
"fmt"
"strings"
"time"
"../config"
"../core"
"../logging"
"../utils"
"github.com/jtopjian/lxdhelpers"
"github.com/lxc/lxd"
"github.com/lxc/lxd/shared"
)
const (
lxdRetryWaitDuration = 2 * time.Second
lxdTimeout = 5 * time.Second
)
/**
* Create new Discovery with LXD fetch func
*/
func NewLXDDiscovery(cfg config.DiscoveryConfig) interface{} {
d := Discovery{
opts: DiscoveryOpts{lxdRetryWaitDuration},
fetch: lxdFetch,
cfg: cfg,
}
return &d
}
/**
* Fetch backends from LXD API
*/
func lxdFetch(cfg config.DiscoveryConfig) (*[]core.Backend, error) {
log := logging.For("lxdFetch")
/* Get an LXD client */
client, err := lxdBuildClient(cfg)
if err != nil {
return nil, err
}
/* Set the timeout for the client */
client.Http.Timeout = utils.ParseDurationOrDefault(cfg.Timeout, lxdTimeout)
log.Debug("Fetching containers from ", client.Config.Remotes[cfg.LXDServerRemoteName].Addr)
/* Create backends from response */
backends := []core.Backend{}
/* Fetch containers */
containers, err := client.ListContainers()
if err != nil {
return nil, err
}
for _, container := range containers {
/* Ignore containers that aren't running */
if container.Status != "Running" {
continue
}
/* Ignore continers if not match label key and value */
if cfg.LXDContainerLabelKey != "" {
actualLabelValue, ok := container.Config[cfg.LXDContainerLabelKey]
if !ok {
continue
}
if cfg.LXDContainerLabelValue != "" && actualLabelValue != cfg.LXDContainerLabelValue {
continue
}
}
/* Try get container port either from label, or from discovery config */
port := fmt.Sprintf("%v", cfg.LXDContainerPort)
if cfg.LXDContainerPortKey != "" {
if p, ok := container.Config[cfg.LXDContainerPortKey]; ok {
port = p
}
}
if port == "" {
log.Warn(fmt.Sprintf("Port is not found in neither in lxd_container_port config not in %s label for %s. Skipping",
cfg.LXDContainerPortKey, container.Name))
continue
}
/* iface is the container interface to get an IP address. */
/* This isn't exposed by the LXD API, and containers can have multiple interfaces, */
iface := cfg.LXDContainerInterface
if v, ok := container.Config[cfg.LXDContainerInterfaceKey]; ok {
iface = v
}
ip := ""
if ip, err = lxdDetermineContainerIP(client, container.Name, iface, cfg.LXDContainerAddressType); err != nil {
log.Error(fmt.Sprintf("Can't determine %s container ip address: %s. Skipping", container.Name, err))
continue
}
sni := ""
if v, ok := container.Config[cfg.LXDContainerSNIKey]; ok {
sni = v
}
backends = append(backends, core.Backend{
Target: core.Target{
Host: ip,
Port: port,
},
Priority: 1,
Weight: 1,
Stats: core.BackendStats{
Live: true,
},
Sni: sni,
})
}
return &backends, nil
}
/**
* Create new LXD Client
*/
func lxdBuildClient(cfg config.DiscoveryConfig) (*lxd.Client, error) {
log := logging.For("lxdBuildClient")
/* Make a client to pass around */
var client *lxd.Client
/* Build a configuration with the requested options */
lxdConfig, err := lxdBuildConfig(cfg)
if err != nil {
return client, err
}
if strings.HasPrefix(cfg.LXDServerAddress, "https:") {
/* Validate or generate certificates on the client side (gobetween) */
if err := lxdhelpers.ValidateClientCertificates(lxdConfig, cfg.LXDGenerateClientCerts); err != nil {
return nil, err
}
/* Validate or accept certificates on the server side (LXD) */
serverCertf := lxdConfig.ServerCertPath(cfg.LXDServerRemoteName)
if !shared.PathExists(serverCertf) {
/* If the server certificate was not found, either gobetween and the LXD server are set
* up for PKI, or gobetween must authenticate with the LXD server and accept its server
* certificate.
*
* First, create a simple LXD client
*/
client, err = lxd.NewClient(&lxdConfig, cfg.LXDServerRemoteName)
if err != nil {
return nil, err
}
/* Next, check if the client is able to communicate with the LXD server. If it can,
* this means that gobetween and the LXD server are configured with PKI certificates
* from a private CA.
*
* But if there's an error, then gobetween will try to download the server's cert.
*/
if _, err := client.GetServerConfig(); err != nil {
if cfg.LXDAcceptServerCert {
var err error
client, err = lxdhelpers.GetRemoteCertificate(client, cfg.LXDServerRemoteName)
if err != nil {
return nil, fmt.Errorf("Could not add the LXD server: %s", err)
}
} else {
err := fmt.Errorf("Unable to communicate with LXD server. Either set " +
"lxd_accept_server_cert to true or add the LXD server out of " +
"band of gobetween and try again.")
return nil, err
}
}
/*
* Finally, check and see if gobetween needs to authenticate with the LXD server.
* Authentication happens only once. After that, gobetween will be a trusted client
* as long as the exchanged certificates to not change.
*
* Authentication must happen even if PKI is in use.
*/
log.Info("Attempting to authenticate")
err = lxdhelpers.ValidateRemoteConnection(client, cfg.LXDServerRemoteName, cfg.LXDServerRemotePassword)
if err != nil {
log.Info("Authentication unsuccessful")
return nil, err
}
log.Info("Authentication successful")
}
}
/* Build a new client */
client, err = lxd.NewClient(&lxdConfig, cfg.LXDServerRemoteName)
if err != nil {
return nil, err
}
/* Validate the client config and connectivity */
if _, err := client.GetServerConfig(); err != nil {
return nil, err
}
return client, nil
}
/**
* Create LXD Client Config
*/
func lxdBuildConfig(cfg config.DiscoveryConfig) (lxd.Config, error) {
log := logging.For("lxdBuildConfig")
log.Debug("Using API: ", cfg.LXDServerAddress)
/* Build an LXD configuration that will connect to the requested LXD server */
config := lxd.Config{
ConfigDir: cfg.LXDConfigDirectory,
Remotes: make(map[string]lxd.RemoteConfig),
}
config.Remotes[cfg.LXDServerRemoteName] = lxd.RemoteConfig{Addr: cfg.LXDServerAddress}
return config, nil
}
/**
* Get container IP address depending on network interface and address type
*/
func lxdDetermineContainerIP(client *lxd.Client, container, iface, addrType string) (string, error) {
var containerIP string
/* Convert addrType to inet */
var inet string
switch addrType {
case "IPv4":
inet = "inet"
case "IPv6":
inet = "inet6"
}
cstate, err := client.ContainerState(container)
if err != nil {
return "", err
}
for i, network := range cstate.Network {
if i != iface {
continue
}
for _, ip := range network.Addresses {
if ip.Family == inet {
containerIP = ip.Address
break
}
}
}
/* If IPv6, format correctly */
if inet == "inet6" {
containerIP = fmt.Sprintf("[%s]", containerIP)
}
if containerIP == "" {
return "", fmt.Errorf("Unable to determine IP address for LXD container %s", container)
}
return containerIP, nil
}
| ba037e6769c5331c777ae94a4450ba78ebb15067 | [
"Go"
] | 1 | Go | lstiebel/gobetween | 5c51b0c3a3e63b9d8cfdb58e72bea312904c7771 | be5b3091dbd9d3140bfdf74b234ddd7c35497c04 |
refs/heads/master | <file_sep>import React, { Component } from 'react';
import '../App.css';
import axios from 'axios';
class Login extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: ""
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({
...this.state,
[event.target.name]: event.target.value
})
}
handleSubmit(event) {
event.preventDefault();
axios.post('http://localhost:4000/api/login', {
email: this.state.email,
password: <PASSWORD>
}).then(res => {
console.log(res.data);
}).catch(err => {
// setErr(err.response.data);
})
}
render() {
return (
<div className="Login">
<div className="container">
<div className="banner"></div>
<div className="login-box">
<div className="login-box-title">
<p>Instagram</p>
</div>
<div className="login-box-input">
<form onSubmit={this.handleSubmit}>
<input type="text" placeholder="Số điện thoại, tên người dùng hoặc email" name="email" onChange={this.handleChange}></input>
<input type="text" placeholder="<NAME>" name="password" onChange={this.handleChange}></input>
<button>Login</button>
</form>
</div>
</div>
</div>
</div>
);
}
}
export default Login;
| 81039c71916bb1c1c309c2f44c83bfc3ff3d8f61 | [
"JavaScript"
] | 1 | JavaScript | dbaonam99/instagram | 751f2641a826f294022f5b01b8c1b2e8583132ce | 08e0b0ae69c6f88305beb39ffd155b61e8b90822 |
refs/heads/master | <repo_name>samuelololol/prplgate<file_sep>/src/glibcompat.h
/**
* @file glibcompat.h Compatibility for many glib versions.
* @ingroup core
*/
/* purple
*
* Purple is the legal property of its developers, whose names are too numerous
* to list here. Please refer to the COPYRIGHT file distributed with this
* source distribution.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA
*/
#ifndef PURPLE_GLIBCOMPAT_H
#define PURPLE_GLIBCOMPAT_H
#include <glib.h>
#if !GLIB_CHECK_VERSION(2,32,0)
# define G_GNUC_BEGIN_IGNORE_DEPRECATIONS
# define G_GNUC_END_IGNORE_DEPRECATIONS
void g_queue_free_full(GQueue *queue, GDestroyNotify free_func);
gboolean g_hash_table_contains (GHashTable *hash_table, gconstpointer key);
#endif /* !GLIB_CHECK_VERSION(2,32,0) */
#ifdef __clang__
#undef G_GNUC_BEGIN_IGNORE_DEPRECATIONS
#define G_GNUC_BEGIN_IGNORE_DEPRECATIONS \
_Pragma ("clang diagnostic push") \
_Pragma ("clang diagnostic ignored \"-Wdeprecated-declarations\"")
#undef G_GNUC_END_IGNORE_DEPRECATIONS
#define G_GNUC_END_IGNORE_DEPRECATIONS \
_Pragma ("clang diagnostic pop")
#endif /* __clang__ */
#endif /* PURPLE_GLIBCOMPAT_H */
<file_sep>/Dockerfile
FROM ubuntu:18.04
RUN useradd -m user && yes password | passwd user
EXPOSE 22
RUN apt-get update &&\
apt-get install -y \
openssh-server \
rsync build-essential cmake g++ gdb \
pidgin-dev libpurple-dev zlib1g-dev libxml2-dev &&\
apt-get clean &&\
rm -rf /var/lib/apt/lists/*
RUN mkdir /var/run/sshd
CMD ["/usr/sbin/sshd", "-D"]
<file_sep>/README.md
# prplgate
## TODO
- [x] Add nullprpl file as init sample
- [x] Build docker images as build environemnt
- [ ] Transform `prplgate.c` file to `prplgate.cpp` cpp file
- [ ] Split `prplgate.cpp` into multiple small cpp files
- [ ] Prepare curl modules
<file_sep>/src/CMakeLists.txt
add_library(${PROJECT_NAME} SHARED
prplgate.c
)
target_include_directories(${PROJECT_NAME} PRIVATE
${PURPLE_INCLUDE_DIRS}
${GLIB_PKG_INCLUDE_DIRS}
internal.h
)
target_link_libraries(${PROJECT_NAME} PRIVATE
${LibXml2_LIBRARIES}
${ZLIB_LIBRARIES}
${GLIB_PKG_LIBRARIES}
${PURPLE_LIBRARIES}
)<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
project(prplgate)
set(CMAKE_CXX_STANDARD 14)
include(FindPkgConfig)
pkg_check_modules(PURPLE REQUIRED purple)
pkg_check_modules(GLIB_PKG REQUIRED glib-2.0)
find_package(ZLIB REQUIRED)
find_package(LibXml2 REQUIRED)
add_subdirectory(src)
| a646a57ceb77878f75bcba1fb29d8bb735de16e4 | [
"Markdown",
"C",
"CMake",
"Dockerfile"
] | 5 | C | samuelololol/prplgate | 7a1ecd6cfa5736c06765ed1f728a7bb8441cbaf9 | 9e9647f82ab3dc454718c68928119b42b633088c |
refs/heads/master | <file_sep>rootProject.name = "Vooly Simple App"
include ':app'
<file_sep>package com.example.voolysimpleapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.voolysimpleapp.javaClass.MySingleton;
public class MainActivity extends AppCompatActivity {
TextView textView;
String url ="https://www.google.com";
public static final String TAG = "MyTag";
RequestQueue requestQueue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
// Intantiate request Queue
requestQueue = Volley.newRequestQueue(this);
// request a String response from the provided URL
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
textView.setText("Response is: " + response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
textView.setText("That didn't work!");
}
});
stringRequest.setTag(TAG);
requestQueue.add(stringRequest);
}
@Override
protected void onStop() {
super.onStop();
if (requestQueue != null){
requestQueue.cancelAll(TAG);
}
}
public void nextScreen(View view) {
MySingleton.getInstance(MainActivity.this).startNewActivity(MainActivity.this,SingletonClassActivity.class);
}
} | 87e772ef2930bdb18f7009e99eedd77d6e58c16e | [
"Java",
"Gradle"
] | 2 | Gradle | aBridgeTo/Vooly_Simple_App | c2610c8a76d2a927440469deab3a0b7c078a9ec6 | 2477c7551340bb384657158a698c163a8071167c |
refs/heads/master | <file_sep>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Created by Dino on 19.7.2016.
*/
public class ServerThred implements Runnable {
ServerSocket server;
Socket socket;
String port;
ServerThred(String port){
this.port=port;
}
public void run(){
try {
server = new ServerSocket(Integer.parseInt(port));
socket=server.accept();
BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String clientData = "";
clientData = reader.readLine();
System.out.println(clientData);
//socket.close();
server.close();
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
| c687c73bfb5838786d2d5e9af955f378bf8ffe46 | [
"Java"
] | 1 | Java | dizda13/chat-socket | 14311b5c2511192366eb96416a281603ebcfae57 | aca460ba9878ee4522bdface626a091a52d735ef |
refs/heads/master | <file_sep>import { Component, OnInit, Inject } from '@angular/core';
import PlaceResult = google.maps.places.PlaceResult;
import { Location, Appearance, GermanAddress } from '@angular-material-extensions/google-maps-autocomplete';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
@Component({
selector: 'app-autocomplete',
templateUrl: './autocomplete.component.html',
styleUrls: ['./autocomplete.component.scss']
})
export class AutocompleteComponent implements OnInit {
public appearance = Appearance;
public zoom: number;
public latitude: number;
public longitude: number;
public selectedAddress: PlaceResult;
placesName: string;
addressChosen = false;
constructor(private dialogRef: MatDialogRef<AutocompleteComponent>,
@Inject(MAT_DIALOG_DATA) public data: any) { }
ngOnInit() {
this.zoom = 1000;
setTimeout(() => {
if (this.data) {
this.latitude = this.data.latitude;
this.longitude = this.data.longitude;
this.placesName = this.data.adress ? this.data.adress : this.data.workLocation;
}
}, 2000);
this.setCurrentPosition();
}
private setCurrentPosition() {
if ('geolocation' in navigator) {
navigator.geolocation.getCurrentPosition((position) => {
this.latitude = position.coords.latitude;
this.longitude = position.coords.longitude;
this.zoom = 12;
});
}
}
onAutocompleteSelected(result: PlaceResult) {
this.placesName = result.formatted_address;
this.addressChosen = true;
}
onLocationSelected(location: Location) {
this.latitude = location.latitude;
this.longitude = location.longitude;
this.addressChosen = true;
}
onGermanAddressMapped($event: GermanAddress) {
}
onKey($event) {
}
ngAfterContentInit(): void {
// Called after ngOnInit when the component's or directive's content has been initialized.
// Add 'implements AfterContentInit' to the class.
}
onConfirm() {
const mapData = {
latitude: this.latitude,
longitude: this.longitude,
name: this.placesName
};
this.dialogRef.close(mapData);
}
}
<file_sep>import { ApiserviceService } from './../../apiservice.service';
import { Component, OnInit, Input } from '@angular/core';
import { ChartDataSets, ChartOptions } from 'chart.js';
import { Label, Color } from 'ng2-charts';
declare const Chart;
@Component({
selector: 'app-charts',
templateUrl: './charts.component.html',
styleUrls: ['./charts.component.scss']
})
export class ChartsComponent implements OnInit {
govs = {
Tataouine: 'تطاوين',
Kebili: 'قبلي',
Medenine: 'مدنين',
Kasserine: 'القصرين',
Gafsa: 'قفصة',
Sfax: 'صفاقس',
'Sidi Bouzid': 'سيدي بوزيد',
'Gabès': 'قابس',
Kairouan: 'القيروان',
Tozeur: 'توزر',
Kef: 'الكاف',
Siliana: 'سليانة',
Bizerte: 'بنزرت',
Beja: 'باجة',
Jendouba: 'جندوبة',
Mahdia: 'المهدية',
Nabeul: 'نابل',
Zaghouan: 'زغوان',
Sousse: 'سوسة',
Mannouba: 'منوبة',
Monastir: 'المنستير',
'Ben Arous': 'بن عروس',
Ariana: 'أريانة',
Tunis: 'تونس'
};
// nationalities
nationalities = {
Afghan: 'أفغاني',
Albanian: 'ألباني',
Algerian: 'جزائري',
American: 'أمريكي',
Andorran: 'أندوري',
Angolan: 'أنغولي',
Antiguans: 'انتيغوا',
Argentinean: 'أرجنتيني',
Armenian: 'أرميني',
Australian: 'أسترالي',
Austrian: 'نمساوي',
Azerbaijani: 'أذربيجاني',
Bahamian: 'باهامى',
Bahraini: 'بحريني',
Bangladeshi: 'بنجلاديشي',
Barbadian: 'باربادوسي',
Barbudans: 'بربودا',
Batswana: 'بوتسواني',
Belarusian: 'بيلاروسي',
Belgian: 'بلجيكي',
Belizean: 'بليزي',
Beninese: 'بنيني',
Bhutanese: 'بوتاني',
Bolivian: 'بوليفي',
Bosnian: 'بوسني',
Brazilian: 'برازيلي',
British: 'بريطاني',
Bruneian: 'بروناى',
Bulgarian: 'بلغاري',
Burkinabe: 'بوركيني',
Burmese: 'بورمي',
Burundian: 'بوروندي',
Cambodian: 'كمبودي',
Cameroonian: 'كاميروني',
Canadian: 'كندي',
'Cape Verdean': 'االرأس الأخضر',
'Central African': 'وسط أفريقيا',
Chadian: 'تشادي',
Chilean: 'شيلي',
Chinese: 'صينى',
Colombian: 'كولومبي',
Comoran: 'جزر القمر',
Congolese: 'كونغولي',
'Costa Rican': 'كوستاريكي',
Croatian: 'كرواتية',
Cuban: 'كوبي',
Cypriot: 'قبرصي',
Czech: 'تشيكي',
Danish: 'دانماركي',
Djibouti: 'جيبوتي',
Dominican: 'دومينيكاني',
Dutch: 'هولندي',
'East Timorese': 'تيموري شرقي',
Ecuadorean: 'اكوادوري',
Egyptian: 'مصري',
Emirian: 'إماراتي',
'Equatorial Guinean': 'غيني استوائي',
Eritrean: 'إريتري',
Estonian: 'إستوني',
Ethiopian: 'حبشي',
Fijian: 'فيجي',
Filipino: 'فلبيني',
Finnish: 'فنلندي',
French: 'فرنسي',
Gabonese: 'جابوني',
Gambian: 'غامبيي',
Georgian: 'جورجي',
German: 'ألماني',
Ghanaian: 'غاني',
Greek: 'إغريقي',
Grenadian: 'جرينادي',
Guatemalan: 'غواتيمالي',
'Guinea-Bissauan': 'غيني بيساوي',
Guinean: 'غيني',
Guyanese: 'جوياني',
Haitian: 'هايتي',
Herzegovinian: 'هرسكي',
Honduran: 'هندوراسي',
Hungarian: 'هنغاري',
Icelander: 'إيسلندي',
Indian: 'هندي',
Indonesian: 'إندونيسي',
Iranian: 'إيراني',
Iraqi: 'عراقي',
Irish: 'إيرلندي',
Italian: 'إيطالي',
Ivorian: 'إفواري',
Jamaican: 'جامايكي',
Japanese: 'ياباني',
Jordanian: 'أردني',
Kazakhstani: 'كازاخستاني',
Kenyan: 'كيني',
'Kittian and Nevisian': 'كيتياني ونيفيسياني',
Kuwaiti: 'كويتي',
Kyrgyz: 'قيرغيزستان',
Laotian: 'لاوسي',
Latvian: 'لاتفي',
Lebanese: 'لبناني',
Liberian: 'ليبيري',
Libyan: 'ليبي',
Liechtensteiner: 'ليختنشتايني',
Lithuanian: 'لتواني',
Luxembourger: 'لكسمبرغي',
Macedonian: 'مقدوني',
Malagasy: 'مدغشقري',
Malawian: 'مالاوى',
Malaysian: 'ماليزي',
Maldivan: 'مالديفي',
Malian: 'مالي',
Maltese: 'مالطي',
Marshallese: 'مارشالي',
Mauritanian: 'موريتاني',
Mauritian: 'موريشيوسي',
Mexican: 'مكسيكي',
Micronesian: 'ميكرونيزي',
Moldovan: 'مولدوفي',
Monacan: 'موناكو',
Mongolian: 'منغولي',
Moroccan: 'مغربي',
Mosotho: 'ليسوتو',
Motswana: 'لتسواني',
Mozambican: 'موزمبيقي',
Namibian: 'ناميبي',
Nauruan: 'ناورو',
Nepalese: 'نيبالي',
'New Zealander': 'نيوزيلندي',
'Ni-Vanuatu': 'ني فانواتي',
Nicaraguan: 'نيكاراغوا',
Nigerien: 'نيجري',
'North Korean': 'كوري شمالي',
'Northern Irish': 'إيرلندي شمالي',
Norwegian: 'نرويجي',
Omani: 'عماني',
Pakistani: 'باكستاني',
Palauan: 'بالاوي',
Palestinian: 'فلسطيني',
Panamanian: 'بنمي',
'Papua New Guinean': 'بابوا غينيا الجديدة',
Paraguayan: 'باراغواياني',
Peruvian: 'بيروفي',
Polish: 'بولندي',
Portuguese: 'برتغالي',
Qatari: 'قطري',
Romanian: 'روماني',
Russian: 'روسي',
Rwandan: 'رواندي',
'Saint Lucian': 'لوسياني',
Salvadoran: 'سلفادوري',
Samoan: 'ساموايان',
'San Marinese': 'سان مارينيز',
'Sao Tomean': 'ساو توميان',
Saudi: 'سعودي',
Scottish: 'سكتلندي',
Senegalese: 'سنغالي',
Serbian: 'صربي',
Seychellois: 'سيشلي',
'Sierra Leonean': 'سيرا ليوني',
Singaporean: 'سنغافوري',
Slovakian: 'سلوفاكي',
Slovenian: 'سلوفيني',
'Solomon Islander': 'جزر سليمان',
Somali: 'صومالي',
'South African': 'جنوب افريقيي',
'South Korean': 'كوري جنوبي',
Spanish: 'إسباني',
'Sri Lankan': 'سري لانكي',
Sudanese: 'سوداني',
Surinamer: 'سورينامي',
Swazi: 'سوازي',
Swedish: 'سويدي',
Swiss: 'سويسري',
Syrian: 'سوري',
Taiwanese: 'تايواني',
Tajik: 'طاجيكي',
Tanzanian: 'تنزاني',
Thai: 'التايلاندي',
Togolese: 'توغواني',
Tongan: 'تونجاني',
'Trinidadian or Tobagonian': 'ترينيدادي أو توباغوني',
Tunisian: 'تونسي',
Turkish: 'تركي',
Tuvaluan: 'توفالي',
Ugandan: 'أوغندي',
Ukrainian: 'أوكراني',
Uruguayan: 'أوروجواي',
Uzbekistani: 'أوزبكستاني',
Venezuelan: 'فنزويلي',
Vietnamese: 'فيتنامي',
Welsh: 'ويلزي',
Yemenite: 'يمني',
Zambian: 'زامبي',
Zimbabwean: 'زيمبابوي'
};
countries = {
Egypt: 'مصر',
France: 'فرنسا',
Italy: 'ايطاليا',
China: 'الصين',
Morroco: 'المغرب',
Spain: 'اسبانيا',
Algeria: 'الجزائر',
Libya: 'ليبيا'
};
loading = true;
@Input() chartType: string;
pieData: any;
@Input() dataSource: string;
@Input() legend: boolean;
@Input() chartLabel: string;
@Input() language: string;
options: any;
public lineChartData: any = [
{ data: [65, 59, 80, 81, 56, 55, 40], label: 'Cas confirmés' },
{ data: [28, 2, 10, 5, 6, 8, 10], label: 'Débraillé' },
{ data: [180, 480, 770, 90, 1000, 270, 400], label: 'Symptômes signalés' }
];
dataPie: any;
public lineChartLabels: Label[] = ['January', 'February', 'March', 'April', 'May', 'June', 'July'];
public lineChartLegend = true;
public lineChartOptions = {
legend: {
display: false
},
responsive: true,
maintainAspectRatio: false,
elements: {
line: {
tension: 0.4,
fill: false,
spanGaps: true,
bezierCurve: true
}
},
tooltips: {
intersect: false,
mode: 'x',
axis: 'x'
},
scales: {
xAxes: [
{
// stacked: true,
// interval: 1,
gridLines: {
display: false
},
offset: true,
ticks: {
maxRotation: 0,
autoSkip: true,
maxTicksLimit: 4,
},
type: 'category',
unit: 'day',
time: {
displayFormats: {
month: 'MMM',
day: 'DD/MM',
hour: 'DD/MM'
}
}
}
],
yAxes: [
{
gridLines: {
display: true
},
type: 'linear',
ticks: {
autoSkip: true,
maxTicksLimit: 5,
}
}
]
}
};
public barChartOptions = {
legend: {
display: false
},
responsive: true,
// We use these empty structures as placeholders for dynamic theming.
scales: {
xAxes: [{
gridLines: {
display: false
}
}],
yAxes: [{
ticks: {
beginAtZero: true,
// maxTicksLimit: 6,
stepSize: 1
},
gridLines: {
display: true
}
}]
},
plugins: {
datalabels: {
anchor: 'end',
align: 'end',
}
},
maintainAspectRatio: false,
};
public pieChartOptions = {
responsive: true,
legend: {
display: false
},
elements: {
line: {
tension: 0,
fill: false, // disables bezier curves
spanGaps: true
}
},
maintainAspectRatio: false,
};
colors: any;
public lineColors: Color[] = [
{
backgroundColor: '#6342D2',
borderColor: '#6342D2',
pointBackgroundColor: '#6342D2',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(148,159,177,0.8)'
},
{
backgroundColor: '#59D5FD',
borderColor: '#59D5FD',
pointBackgroundColor: '#59D5FD',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: '#59D5FD'
},
{
backgroundColor: '#FB6B80',
borderColor: '#FB6B80',
pointBackgroundColor: '#FB6B80',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: '#FB6B80'
},
{
backgroundColor: '#3BA756',
borderColor: '#3BA756',
pointBackgroundColor: '#3BA756',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: '#3BA756'
}
];
public pieChartColors = [
{
backgroundColor: ['#6342D2', '#59D5FD', '#FB6B80', '#FF9578', '#3BA756', '#6563FF', '#FCBE2C'],
},
];
public barChartData: ChartDataSets[] = [
{ data: [65, 59, 80, 81, 56, 55, 40], label: 'Masculin' },
{ data: [28, 48, 40, 19, 86, 27, 90], label: 'Féminin' }
];
// legends margin bottom
public pieChartPlugins = [{
beforeInit: (chart, options) => {
chart.legend.afterFit = function () {
this.height += 20; // must use `function` and not => because of `this`
};
}
}];
constructor(private apiService: ApiserviceService) { }
ngOnInit() {
// getting data for the chart
if (this.dataSource) {
this.apiService.get(this.dataSource).subscribe(
(data: any) => {
switch (this.chartLabel) {
case 'genderPie':
if (this.language === 'ar') {
this.lineChartLabels = ['ذكر', 'أنثى'];
}
this.pieData = [data.men, data.women];
break;
case 'sourcePie':
this.lineChartLabels = ['Importé', 'Local'];
if (this.language === 'ar') {
this.lineChartLabels = ['مستوردة', 'محلية'];
}
this.pieData = [data.imported, data.local];
break;
case 'countriesPie':
let countrieslabels = [];
if (this.language === 'ar') {
Object.keys(data).map(key => {
if (this.countries[key]) {
countrieslabels.push(this.countries[key]);
} else {
countrieslabels.push(key);
}
});
} else {
countrieslabels = Object.keys(data);
}
this.lineChartLabels = countrieslabels;
this.pieData = Object.values(data);
break;
case 'ageGenderRepartition':
let barData = [];
const dataWomen = [];
const dataMan = [];
Object.keys(data).map(key => {
dataWomen.push(data[key].women ? data[key].women : 0);
dataMan.push(data[key].men ? data[key].men : 0);
});
barData = [{ data: dataMan, label: 'Male' }, { data: dataWomen, label: 'Female' }];
this.lineChartLabels = Object.keys(data);
this.lineChartData = barData;
break;
case 'casePerDay':
this.options.scales.xAxes[0].stacked = true;
this.options.scales.yAxes[0].ticks.beginAtZero = true;
let allLabels = [];
Object.keys(data).map((key: any) => {
allLabels = [...Object.keys(data[key])];
});
// remove duplicate labels
const cleanLabels = allLabels.filter((elem, index, self) => {
return index === self.indexOf(elem);
});
// sorting labels
const sortedLabels = cleanLabels.sort((a: any, b: any) => b.date - a.date);
this.lineChartLabels = sortedLabels;
const dataStacked = [];
if (data.Confirmed) {
dataStacked.push({ data: Object.values(data.Confirmed), label: 'Cas Confirmés' });
}
if (data.Discharged) {
dataStacked.push({ data: Object.values(data.Discharged), label: 'Cas Déchargés' });
}
if (data.Recovred) {
dataStacked.push({ data: Object.values(data.Recovred), label: 'Cas récovrés' });
}
if (data.Dead) {
dataStacked.push({ data: Object.values(data.Confirmed), label: 'Cas mortes' });
}
this.lineChartData = dataStacked;
break;
case 'nationalityPie':
let labels = [];
if (this.language === 'ar') {
Object.keys(data).map(key => {
if (this.nationalities[key]) {
labels.push(this.nationalities[key]);
} else {
labels.push(key);
}
});
} else {
labels = Object.keys(data);
}
this.lineChartLabels = labels;
this.pieData = Object.values(data);
break;
case 'govsPie':
const templabels = [];
const dataGovs = [];
Object.keys(data).map(key => {
if (key.includes('Tunisia')) {
const formattedKey = key.split(',')[0];
if (this.language === 'ar') {
if (this.govs[formattedKey]) {
templabels.push(this.govs[formattedKey]);
} else {
templabels.push(formattedKey);
}
} else {
templabels.push(formattedKey);
}
dataGovs.push(data[key]);
}
});
this.pieData = dataGovs;
this.lineChartLabels = templabels;
break;
default:
break;
}
this.loading = false;
});
}
switch (this.chartType) {
case 'line':
this.options = this.lineChartOptions;
this.colors = this.lineColors;
break;
case 'bar':
this.options = this.barChartOptions;
this.colors = this.lineColors;
this.lineChartData = this.barChartData;
break;
case 'pie':
this.options = this.pieChartOptions;
this.colors = this.pieChartColors;
this.lineChartLabels = ['Masculin', 'Féminin'];
this.pieData = [300, 500];
break;
default:
break;
}
if (this.legend) {
this.options.legend = {
display: true,
position: 'bottom',
labels: {
usePointStyle: true,
generateLabels(chart) {
const data = chart.data;
if (data.labels.length && data.datasets.length) {
return data.labels.map(function (label, i) {
const meta = chart.getDatasetMeta(0);
const ds = data.datasets[0];
const arc = meta.data[i];
const custom = arc && arc.custom || {};
const getValueAtIndexOrDefault = Chart.helpers.getValueAtIndexOrDefault;
const arcOpts = chart.options.elements.arc;
const fill =
custom.backgroundColor ? custom.backgroundColor : getValueAtIndexOrDefault(ds.backgroundColor, i, arcOpts.backgroundColor);
const stroke = custom.borderColor ? custom.borderColor : getValueAtIndexOrDefault(ds.borderColor, i, arcOpts.borderColor);
const bw = custom.borderWidth ? custom.borderWidth : getValueAtIndexOrDefault(ds.borderWidth, i, arcOpts.borderWidth);
const value = chart.config.data.datasets[arc._datasetIndex].data[arc._index];
return {
text: label + ' : ' + value,
fillStyle: fill,
strokeStyle: stroke,
lineWidth: bw,
hidden: isNaN(ds.data[i]) || meta.data[i].hidden,
index: i
};
});
} else {
return [];
}
}
},
};
}
}
}
<file_sep>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {AutoQuestionsComponent} from './auto-questions/auto-questions.component';
import {FormComponent} from './diagnostic/forms.component';
import {ListingComponent} from './listing/listing.component';
const routes: Routes = [
{path: 'diagnostic', component: FormComponent},
{path: 'declaration', component: AutoQuestionsComponent},
{path: 'listing', component: ListingComponent},
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class FormsRoutingModule { }
<file_sep>import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {FormsRoutingModule} from './forms-routing.module';
import {ListingComponent} from './listing/listing.component';
import {FormComponent} from './diagnostic/forms.component';
import {AutoQuestionsComponent} from './auto-questions/auto-questions.component';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {MatRadioModule} from '@angular/material/radio';
import {MatFormFieldModule} from '@angular/material/form-field';
import {MatInputModule} from '@angular/material/input';
import {MatButtonModule} from '@angular/material/button';
import {MatCheckboxModule} from '@angular/material/checkbox';
import {MatIconModule} from '@angular/material/icon';
import {DetailListDialogComponent} from './detail-list-dialog/detail-list-dialog.component';
import {MatPaginatorModule} from '@angular/material/paginator';
@NgModule({
declarations: [ListingComponent, FormComponent, AutoQuestionsComponent, DetailListDialogComponent],
imports: [
CommonModule,
FormsRoutingModule,
ReactiveFormsModule,
MatRadioModule,
MatFormFieldModule,
MatInputModule,
MatButtonModule,
MatCheckboxModule,
FormsModule,
MatIconModule,
MatPaginatorModule
],
entryComponents: [DetailListDialogComponent]
})
export class DiagModule {
}
<file_sep>import {NgModule} from '@angular/core';
import {Routes, RouterModule} from '@angular/router';
const routes: Routes = [
{path: '', redirectTo: 'dashboard', pathMatch: 'full'},
{path: 'formulaire', loadChildren: () => import('./home/home.module').then(m => m.HomeModule)},
{path: 'dashboard', loadChildren: () => import('./dashboard/dashboard.module').then(m => m.DashboardModule)},
{path: 'preprod', loadChildren: () => import('./dashboard-preprod/dashboard.module').then(m => m.DashboardModule)},
{path: 'questions', loadChildren: () => import('./home/forms/forms.module').then(m => m.DiagModule)},
{path: 'list', loadChildren: () => import('./list/list.module').then(m => m.ListModule)},
{ path: 'back-office', loadChildren: () => import('./back-office/back-office.module').then(m => m.BackOfficeModule) },
{ path: 'front', loadChildren: () => import('./front/dashboard.module').then(m => m.DashboardModule) }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}
<file_sep>import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import * as echarts from 'echarts';
import { latlong } from './map-config/latlong';
@Component({
selector: 'app-map',
templateUrl: './map.component.html',
styleUrls: ['./map.component.scss']
})
export class MapComponent implements OnInit {
// if laoding data
isLoading = true;
mapData: any[] = [];
mapOptions: any;
// latlong
latlong: any;
echartMax = -Infinity;
echartMin = Infinity;
constructor(private http: HttpClient) { }
ngOnInit() {
this.http.get('../../../assets/map/world.json').subscribe((geoJson) => {
// register map
echarts.registerMap('world', geoJson);
this.latlong = latlong;
// update map options
this.mapOptions = {
title: {
text: 'Distribution des cas',
// subtext: '人口密度数据来自Wikipedia',
// sublink: 'http://zh.wikipedia.org/wiki/%E9%A6%99%E6%B8%AF%E8%A1%8C%E6%94%BF%E5%8D%80%E5%8A%83#cite_note-12'
},
tooltip: {
trigger: 'item',
formatter: params => {
return `${params.name}: ${params.value[2]}`;
}
},
geo: {
map: 'world',
label: {
emphasis: {
show: false
}
},
// colors and shit
itemStyle: {
normal: {
areaColor: 'rgba(100, 60, 214, 0.7)',
borderColor: 'white'
},
emphasis: {
areaColor: 'rgba(100, 60, 214, 1)'
}
}
},
// colors and shit
visualMap: {
min: 0,
max: this.echartMax,
splitNumber: 5,
precision: null,
color: ['#F9677E', '#f9f967'],
textStyle: {
color: '#212121'
}
},
// real shit for data to display
series: [
{
type: 'scatter',
coordinateSystem: 'geo',
data: this.mapData.map(itemOpt => {
return {
name: itemOpt.name,
value: [
itemOpt.longitude,
itemOpt.latitude,
itemOpt.value
]
};
}),
itemStyle: {
emphasis: {
areaColor: '#A5DABB',
borderColor: '#fff',
borderWidth: 2
}
}
}
],
zoom: 1.2
};
});
}
}
<file_sep>import { ApiserviceService } from './../../apiservice.service';
import { Component, OnInit, AfterViewInit, Input } from '@angular/core';
declare var google: any;
@Component({
selector: 'app-google-map',
templateUrl: './google-map.component.html',
styleUrls: ['./google-map.component.scss']
})
export class GoogleMapComponent implements OnInit {
markers ;
@Input() dataSource: string;
// google maps zoom level
zoom = 6;
// initial center position for the map
lat = 33.8869;
lng = 9.5375;
constructor(private apiService: ApiserviceService) { }
ngOnInit() {
this.apiService.get(this.dataSource).subscribe((data: any) => {
const tempMarkers = [];
for (let marker of data) {
tempMarkers.push({lat: marker.lat, lng: marker.long});
}
this.markers = tempMarkers;
});
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { ApiserviceService } from '../apiservice.service';
@Component({
selector: 'app-back-office',
templateUrl: './back-office.component.html',
styleUrls: ['./back-office.component.scss']
})
export class BackOfficeComponent implements OnInit {
constructor(
private fb: FormBuilder,
private apiService: ApiserviceService,
) { }
updateForm = this.fb.group({
Confirmed: [''],
hospitalized: [''],
Discharged: [''],
date: [''],
quarantaine_achevee: [''],
quarantaine: [''],
depistage: [''],
Recovered: ['']
});
ngOnInit(): void {
}
onSubmit() {
// TODO: Use EventEmitter with form value
console.warn(this.updateForm.value);
// /api/?f=stats
this.apiService.updateback(this.updateForm.value).subscribe(value => {
});
}
}
<file_sep>import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {MedicalExtension, SymptomForm, Testing} from '../symptom-form';
import {ApiserviceService} from '../../../apiservice.service';
import {MatSnackBar} from '@angular/material/snack-bar';
@Component({
selector: 'app-auto-questions',
templateUrl: './auto-questions.component.html',
styleUrls: ['./auto-questions.component.scss']
})
export class AutoQuestionsComponent implements OnInit {
symptomForm: FormGroup;
medicalForm: FormGroup;
testingForm: FormGroup;
symptomValues = SymptomForm;
medicalExtension = MedicalExtension;
testingDiag = Testing;
symptomsIndex = 0;
medicalIndex = 0;
testingIndex = 0;
toDisplay = 0;
done = false;
index = 0;
length = 0;
constructor(private fb: FormBuilder, private api: ApiserviceService, private snackBar: MatSnackBar) {
}
ngOnInit() {
// symptom form
const symptom = {};
this.symptomValues.forEach(input => {
symptom[input.value] = input.value === 'other' ? new FormControl('') :
new FormControl('', [Validators.required]);
});
this.symptomForm = new FormGroup(symptom);
// medical form
const medical = {};
this.medicalExtension.forEach(input => {
if (input.type === 'group') {
medical[input.value] = this.specifyGroup();
} else {
medical[input.value] = input.value === 'other' ? new FormControl('') :
new FormControl('', [Validators.required]);
}
});
this.medicalForm = this.fb.group(medical);
// testing Form
const testing = {};
this.testingDiag.forEach(input => {
if (input.type === 'group') {
if (input.value === 'other') {
testing[input.value] = this.fb.group({
firstValue: [''],
secondValue: ['']
});
} else {
testing[input.value] = this.fb.group({
firstValue: ['', Validators.required],
secondValue: ['', Validators.required]
});
}
} else if (input.type === 'number' || input.type === 'string') {
testing[input.value] = input.value === 'other' ? new FormControl('') :
new FormControl('', [Validators.required]);
}
});
this.testingForm = this.fb.group(testing);
this.length = this.symptomValues.length;
}
openSnackBar() {
this.snackBar.open('veuillez remplir tous les champs', 'Close', {duration: 5000});
}
next() {
let index;
let hasError = false;
if (this.toDisplay === 1) {
index = 'symptomsIndex';
this.length = this.symptomValues.length;
hasError = this.symptomForm.controls[this.symptomValues[this[index]].value].valid;
} else if (this.toDisplay === 2) {
index = 'medicalIndex';
hasError = this.medicalForm.controls[this.medicalExtension[this[index]].value].valid;
this.length = this.medicalExtension.length;
} else if (this.toDisplay === 3) {
index = 'testingIndex';
hasError = this.testingForm.controls[this.testingDiag[this[index]].value].valid;
this.length = this.testingDiag.length;
}
if (!hasError) {
this.openSnackBar();
}
setTimeout(() => {
console.log(index + ':', this[index], 'To Display :', this.toDisplay);
console.log('hasError :', hasError);
if ((this[index] < this.length - 1) && hasError === true) {
this[index]++;
this.index = this[index];
} else {
if (this.toDisplay !== 3 && hasError === true) {
this.toDisplay++;
this.index = 0;
}
}
if (this.toDisplay && this.testingIndex === this.length - 1) {
this.done = true;
}
}, 200);
}
previous() {
let index = 'symptomsIndex';
if (this.toDisplay === 1) {
index = 'symptomsIndex';
} else if (this.toDisplay === 2) {
index = 'medicalIndex';
} else if (this.toDisplay === 3) {
index = 'testingIndex';
}
console.log(index + ':', this[index], 'To Display :', this.toDisplay);
if (this[index] > 0) {
this[index]--;
this.index = this[index];
} else {
if (this.toDisplay !== 0) {
this.toDisplay--;
this.index = 0;
}
}
}
save() {
const data = {
symptom: this.symptomForm.value,
medical: this.medicalForm.value,
testing: this.testingForm.value,
};
const validate = this.symptomForm.valid && this.medicalForm.valid && this.testingForm.valid;
if (validate) {
this.api.sendDataForm(data).subscribe(res => {
console.log(res);
this.snackBar.open('Merci pour vos réponse, formulaire ajouté avec succès', '', {duration: 5000, panelClass : 'successSnack'});
});
} else {
this.snackBar.open('veuillez remplir tous les champs', 'Close', {duration: 5000});
}
}
specifyGroup(): FormGroup {
return this.fb.group({radio: ['', Validators.required], specify: ['']});
}
gotToTest() {
this.toDisplay++;
}
}
<file_sep>import {Component, OnInit} from '@angular/core';
import {ApiserviceService} from '../../../apiservice.service';
import {MatDialog} from '@angular/material/dialog';
import {DetailListDialogComponent} from '../detail-list-dialog/detail-list-dialog.component';
@Component({
selector: 'app-listing',
templateUrl: './listing.component.html',
styleUrls: ['./listing.component.scss']
})
export class ListingComponent implements OnInit {
declarationsList: any[] = [];
totalTests = 0;
page = 0;
pageIndex = 0;
constructor(private api: ApiserviceService, private matDialog: MatDialog) {
}
ngOnInit(): void {
// this.getListData(this.page);
this.getServerData({pageIndex : 0});
}
getListData(page) {
this.api.getDeclarationList(page).subscribe(data => {
console.log('declarations :', data);
this.declarationsList = data.data;
this.totalTests = data.total_tests;
this.page = data.pagination;
});
}
convertValue(value) {
return +value === 0 ? 'Oui' : value === 1 ? 'Non' : value === 2 ? 'Inconnu' : '-';
}
getServerData($event) {
console.log($event);
this.page = $event.pageIndex + 1;
this.getListData(this.page);
}
openDetailDialog(data) {
this.matDialog.open(DetailListDialogComponent, {
data,
panelClass: 'detailDeclarationDialog'
});
}
}
<file_sep>import { ApiserviceService } from './../apiservice.service';
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { PageEvent } from '@angular/material/paginator';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements OnInit {
// endpoints
genderPieEndpoint = '?f=api&endpoint=genderPie';
casesTable = '?f=api&endpoint=cases';
numbersEndpoint = '?f=api&endpoint=numbers';
nationalitiesEndpoint = '?f=api&endpoint=nationalities';
clusterEndpoint = '?f=api&endpoint=clusters';
gendreAgeEndpoint = '?f=api&endpoint=genderAge';
sourceEndpoint = '?f=api&endpoint=sources';
exportersEndpoint = '?f=api&endpoint=exporters';
stackedEndpoint = '?f=api&endpoint=stacked';
casesEndpoint = '?f=api&endpoint=cases';
govsEndpoint = '?f=api&endpoint=governates';
statsEndpoint = '?f=api&endpoint=statistics';
// numbers
confirmed: number;
hospitalized: number;
discharged: number;
restablished: number;
last_update: number;
dead;
// table charts
cases: any[];
casesPaginator: any[];
averageAge: number;
language: string;
pageEvent: PageEvent;
pageIndex = 0;
length = 100;
pageSize = 10;
quarantaine: number;
depistage: number;
ratio: number;
quarantaine_achevee: number;
dateStatistics: string;
constructor(
private apiService: ApiserviceService,
private router: Router,
private translate: TranslateService,
private route: ActivatedRoute
) {
this.route.queryParams.subscribe(params => {
if (params.lang) {
this.language = params.lang;
} else {
this.language = 'fr';
}
});
translate.setDefaultLang(this.language);
}
ngOnInit(): void {
// getting numbers
this.apiService.get(this.numbersEndpoint).subscribe((data: any) => {
this.confirmed = data.Confirmed;
this.hospitalized = data.hospitalized;
this.discharged = data.Discharged;
this.restablished = data.Recovered;
this.last_update = data.last_update;
this.dead = data.Dead;
});
this.apiService.get(this.statsEndpoint).subscribe((data: any) => {
this.quarantaine = data.quarantaine;
this.depistage = data.depistage;
this.ratio = data.ratio.toFixed(2);
this.quarantaine_achevee = data.quarantaine_achevee;
this.dateStatistics = data.date;
});
this.getCases();
}
public getCases() {
// getting table data
this.apiService.get(this.casesEndpoint).subscribe((data: any) => {
this.cases = data.cases.reverse();
this.getServerData();
this.averageAge = data.average;
this.length = data.cases.length;
});
}
getServerData(event?) {
if (event) {
this.pageSize = event.pageSize;
this.pageIndex = event.pageIndex;
}
this.casesPaginator = [];
this.cases.forEach((item, index) => {
if (
index < this.pageSize + this.pageSize * this.pageIndex &&
index >= this.pageIndex * this.pageSize
) {
this.casesPaginator.push(item);
}
});
}
goTo(route) {
this.router.navigate([route]);
}
changeLaneguage(event) {
this.translate.use(event.value);
}
}
<file_sep>export const SymptomForm = [
{
label: 'Age / عمر',
value: 'age',
type: 'string'
},
{
label: 'Taille / حجم',
value: 'size',
type: 'string'
},
{
label: 'Poids / الوزن',
value: 'weight',
type: 'string'
},
{
label: 'Fièvre / حمى (>38°C)',
value: 'fever',
type: 'number'
},
{
label: 'Fièvre subjective / حمى ذاتية',
value: 'subjectiveFever',
type: 'number'
},
{
label: 'Frissons / قشعريرة',
value: 'chills',
type: 'number'
},
{
label: 'Douleur musculaire / آلام على مستوى العضلات',
value: 'muscleAches',
type: 'number'
},
{
label: 'écoulement nasale / سيلان الأنف',
value: 'runnyNose',
type: 'number'
},
{
label: 'Maux de gorge / إلتهاب في الحلق',
value: 'soreThroat',
type: 'number'
},
{
label: 'Toux / سعال',
value: 'cough',
type: 'number'
},
{
label: 'Essoufflement / ضيق في التنفس',
value: 'shortnessBreath',
type: 'number'
},
{
label: 'Nausées ou vomissements / غثيان أو تقيء',
value: 'nauseaVomiting',
type: 'number'
},
{
label: 'Maux de tête / صداع ',
value: 'headache',
type: 'number'
},
{
label: 'Douleur abdominale / وجع على مستوى البطن',
value: 'abdominalPain',
type: 'number'
},
{
label: 'Diarrhée / إسهال',
value: 'diarrhea',
type: 'number'
},
{
label: 'Autres symptômes, précisez / أعراض أخرى ، حدد',
value: 'other',
type: 'string'
}
];
export const MedicalExtension = [
{
label: 'Maladie pulmonaire chronique / مرض رئوي مزمن',
value: 'chronicLungDisease',
type: 'number'
},
{
label: 'Diabète / داء السكري',
value: 'diabeteMellitus',
type: 'number'
},
{
label: 'Maladie cardiovasculaire / أمراض القلب والأوعية الدموية',
value: 'cardiavascularDisease',
type: 'number'
},
{
label: 'Maladie rénale cardiovasculaire / أمراض الكلى والأوعية الدموية',
value: 'cardiavascularRenalDisease',
type: 'number'
},
{
label: 'Maladie hépatique cardiovasculaire / أمراض الكبد القلبية الوعائية',
value: 'cardiavascularLiverDisease',
type: 'number'
},
{
label: 'immunodépression / حالة نقص المناعة',
value: 'immunocompromised',
type: 'number'
},
{
label: 'Déficience neurologique ou intellectuelle / ضعف عصبي / فكري ',
value: 'neurologic',
valueRadioBox: 'radio',
valueInput: 'specify',
type: 'group'
},
{
label: 'Autre maladie chronique / مرض مزمن آخر',
value: 'otherChronicDiseases',
valueRadioBox: 'radio',
valueInput: 'specify',
type: 'group'
},
{
label: 'Si c\'est une femme , actuellement enceinte / إذا كانت الأنثى حامل حاليا',
value: 'pregnant',
type: 'number'
},
{
label: 'Fumeur actuel / مدخن حالي',
value: 'currentSmoker',
type: 'number'
},
{
label: 'Ancien fumeur / مدخن سابق',
value: 'formerSmoker',
type: 'number'
}
];
export const Testing = [
{
label: 'Grippe rapid Ag',
value: 'influenzaRapid',
valueType: 'type',
type: 'group'
},
{
label: 'Grippe PCR',
value: 'influenzaPCR',
valueType: 'type',
type: 'group'
},
{
label: 'RSV',
value: 'rsv',
type: 'number'
},
{
label: 'H.métapneumovirus',
value: 'metapneumovirus',
type: 'number'
},
{
label: 'Para-influenza',
value: 'paraInfluenza',
type: 'number'
},
{
label: 'Adénovirus',
value: 'adenovirus',
type: 'number'
},
{
label: 'Rhinovirus/enterovirus',
value: 'RhinoEntervirus',
type: 'number'
},
{
label: 'Coronavirus (OC43, 229E, HKU1, NL63)',
value: 'coronavirusType',
type: 'number'
},
{
label: 'Mycoplasma pneumoniae',
value: 'mPneumoniae',
type: 'number'
},
{
label: 'Chlamydophila pneumoniae',
value: 'cPneumoniae',
type: 'number'
},
{
label: 'autres tests, précisez',
value: 'other',
type: 'group',
valueType: 'string'
},
{
label: 'Email / البريد الإلكتروني',
value: 'email',
type: 'string'
},
];
export const Specimens = [
{
label: 'Échantillon nasale / عينة من الأنف',
value: 'NPSwab',
type: 'object'
},
{
label: 'Échantillon oral / عينة من الفم',
value: 'OPSwab',
type: 'object'
},
{
label: 'salive / لعاب',
value: 'Sputum',
type: 'object'
},
{
label: 'autres, précisez / أخرى ، حدد:',
value: 'other',
type: 'string'
},
];
export const SymptomsList = [
{
label: 'Fièvre / حمى (>38°C)',
value: 'fever',
type: 'number'
},
{
label: 'Fièvre subjective / حمى ذاتية',
value: 'subjectiveFever',
type: 'number'
},
{
label: 'Frissons / قشعريرة',
value: 'chills',
type: 'number'
},
{
label: 'Douleur musculaire / آلام على مستوى العضلات',
value: 'muscleAches',
type: 'number'
},
{
label: 'écoulement nasale / سيلان الأنف',
value: 'runnyNose',
type: 'number'
},
{
label: 'Maux de gorge / إلتهاب في الحلق',
value: 'soreThroat',
type: 'number'
},
{
label: 'Toux / سعال',
value: 'cough',
type: 'number'
},
{
label: 'Essoufflement / ضيق في التنفس',
value: 'shortnessBreath',
type: 'number'
},
{
label: 'Nausées ou vomissements / غثيان أو تقيء',
value: 'nauseaVomiting',
type: 'number'
},
{
label: 'Maux de tête / صداع ',
value: 'headache',
type: 'number'
},
{
label: 'Douleur abdominale / وجع على مستوى البطن',
value: 'abdominalPain',
type: 'number'
},
{
label: 'Diarrhée / إسهال',
value: 'diarrhea',
type: 'number'
},
{
label: 'Autres symptômes, précisez / أعراض أخرى ، حدد',
value: 'other',
type: 'string'
}
];
<file_sep>import { AutocompleteComponent } from './autocomplete/autocomplete.component';
import { Component, OnInit, ViewChild, ElementRef, NgZone } from '@angular/core';
import { nationality } from '../data';
import { FormArray, FormBuilder, Validators, FormGroup } from '@angular/forms';
import { Location, Appearance, GermanAddress } from '@angular-material-extensions/google-maps-autocomplete';
import PlaceResult = google.maps.places.PlaceResult;
import { MapsAPILoader } from '@agm/core';
import { MatDialog } from '@angular/material/dialog';
import { ApiserviceService } from '../apiservice.service';
import { DialogsucessComponent } from './dialogsucess/dialogsucess.component';
import { ActivatedRoute, Params, ParamMap } from '@angular/router';
import { Observable, Subscription } from 'rxjs';
import { switchMap } from 'rxjs/operators';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
phoneNumber = '^((\\+91-?)|0)?[0-9]{10}$';
nationality: { num_code: string; alpha_2_code: string; alpha_3_code: string; en_short_name: string; nationality: string; }[];
status: any = [
{ name: 'En cours de diagnostic', value: 'Under Investigation' },
{ name: 'Déchargé', value: 'Discharged' },
{ name: 'Confirmé', value: 'Confirmed' },
{ name: 'Rétabli', value: 'Recovered' },
{ name: 'Mort', value: 'Dead' }
];
public appearance = Appearance;
public zoom: number;
public latitude: number;
public longitude: number;
public selectedAddress: PlaceResult;
hiden = false;
case: number;
private routeSub: Subscription;
constructor(
private fb: FormBuilder,
public dialog: MatDialog,
private apiService: ApiserviceService,
private route: ActivatedRoute,
) { }
profileForm = this.fb.group({
case: [''],
age: ['', Validators.required],
gender: ['', Validators.required],
nationality: ['', Validators.required],
// adress: ['', Validators.required],
adress: this.fb.group({
adress: ['', Validators.required],
latitude: [''],
longitude: ['']
}),
workLocation: this.fb.group({
workLocation: ['', Validators.required],
latitude: [''],
longitude: ['']
}),
phone: ['', Validators.required],
supportPhone: ['', Validators.required],
infectedFamily: this.fb.array([
this.newInfectedFamily()
]),
location: this.fb.array([
this.newLocation()
]),
travelEtat: ['', Validators.required],
travel: this.fb.array([
this.newTravel()
]),
caseEtat: ['', Validators.required],
caseId: this.fb.array([
this.newCase(),
]),
symptoms: this.fb.group({
etat: ['', Validators.required],
date: [''],
}),
diagnosis: ['', Validators.required],
status: this.fb.group({
case: ['', Validators.required],
date: [''],
}),
hospitalized: this.fb.group({
etat: ['', Validators.required],
adress: [''],
date: [''],
latitude: [''],
longitude: ['']
}),
commentaire: ['']
});
newCase(): FormGroup {
return this.fb.group({
id: ['']
});
}
newInfectedFamily(): FormGroup {
return this.fb.group({
name: '',
infection: '',
});
}
newTravel(): FormGroup {
return this.fb.group({
date: [''],
from: [''],
to: ['']
});
}
newLocation(): FormGroup {
return this.fb.group({
place: [''],
date: [''],
latitude: [''],
longitude: ['']
});
}
get caseId() {
return this.profileForm.get('caseId') as FormArray;
}
get infectedFamily() {
return this.profileForm.get('infectedFamily') as FormArray;
}
get travel() {
return this.profileForm.get('travel') as FormArray;
}
get location() {
return this.profileForm.get('location') as FormArray;
}
addCase() {
this.caseId.push(this.newCase());
}
removeCase(i) {
this.caseId.removeAt(i);
}
addTravel() {
this.travel.push(this.newTravel());
}
removeTravel(i) {
this.travel.removeAt(i);
}
addAlias() {
this.infectedFamily.push(this.newInfectedFamily());
}
removeAlias(i) {
this.infectedFamily.removeAt(i);
}
addLocation() {
this.location.push(this.newLocation());
}
removeLocation(i) {
this.location.removeAt(i);
}
ngOnInit(): void {
this.nationality = nationality;
this.profileForm.get('location').valueChanges.subscribe(value => {
});
this.routeSub = this.route.params.subscribe(params => {
this.case = +params['id'];
if (this.case) {
this.getData(params['id']);
}
});
// GET DATA CASE
// this.getData(2);
}
focusFunction(id: string, i?) {
let data: any;
switch (id) {
case 'address_input':
data = this.profileForm.controls.adress.value;
break;
case 'work_location':
data = this.profileForm.controls.workLocation.value;
break;
case 'recent_location':
data = this.profileForm.controls.location[i].place.value;
break;
case 'hospital_place':
data = this.profileForm.get('hospitalized').get('adress').value;
break;
default:
break;
}
const dialogRef = this.dialog.open(AutocompleteComponent, {
width: '600px',
data
});
dialogRef.afterClosed().subscribe(result => {
if (result && result.name) {
(document.getElementById(id) as HTMLInputElement).value = result.name;
switch (id) {
case 'address_input':
this.profileForm.patchValue({
adress: {
adress: result.name,
latitude: result.latitude,
longitude: result.longitude
}
});
break;
case 'work_location':
this.profileForm.patchValue({
workLocation: {
workLocation: result.name,
latitude: result.latitude,
longitude: result.longitude
}
});
break;
case 'recent_location':
this.profileForm.controls.location[i].patchValue({
place: result.name,
latitude: result.latitude,
longitude: result.longitude
});
break;
case 'hospital_place':
this.profileForm.patchValue({
hospitalized: {
adress: result.name,
latitude: result.latitude,
longitude: result.longitude
}
});
break;
default:
break;
}
}
});
}
onSubmit() {
// TODO: Use EventEmitter with form value
if (this.case) {
this.profileForm.patchValue({
case: this.case
});
}
this.apiService.Send(this.profileForm.value).subscribe(value => {
const dialogRef = this.dialog.open(DialogsucessComponent, {
panelClass: 'confirmed'
});
dialogRef.afterClosed().subscribe(result => {
this.profileForm.reset();
});
});
}
getData(value) {
this.apiService.getData(value).subscribe(value => {
this.patchValue(value);
});
}
patchValue(value) {
this.profileForm.patchValue(value);
}
}
<file_sep>import { ChartsComponent } from './charts/charts.component';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DashboardRoutingModule } from './dashboard-routing.module';
import { DashboardComponent } from './dashboard.component';
import { ChartsModule } from 'ng2-charts';
import { MapComponent } from './map/map.component';
import { NgxEchartsModule } from 'ngx-echarts';
import { GoogleMapComponent } from './google-map/google-map.component';
import { AgmCoreModule } from '@agm/core';
import { MatButtonModule } from '@angular/material/button';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { MatSelectModule } from '@angular/material/select';
import { LeafletMapComponent } from './leaflet-map/leaflet-map.component';
import {MatPaginatorModule} from '@angular/material/paginator';
import {MatIconModule} from '@angular/material/icon';
import { HelpComponent } from './help/help.component';
import {MatTooltipModule} from '@angular/material/tooltip';
@NgModule({
declarations: [DashboardComponent, ChartsComponent, MapComponent, GoogleMapComponent, LeafletMapComponent, HelpComponent],
imports: [
CommonModule,
DashboardRoutingModule,
ChartsModule,
NgxEchartsModule,
AgmCoreModule.forRoot({
apiKey: '<KEY>',
libraries: ['places']
}),
MatButtonModule,
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
}),
MatSelectModule,
MatPaginatorModule,
MatIconModule,
MatTooltipModule
],
entryComponents: [HelpComponent]
})
export class DashboardModule { }
// required for AOT compilation
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http);
}
<file_sep>import {Component, Inject, OnInit} from '@angular/core';
import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material/dialog';
import {MedicalExtension, SymptomForm, Testing} from '../symptom-form';
@Component({
selector: 'app-detail-list-dialog',
templateUrl: './detail-list-dialog.component.html',
styleUrls: ['./detail-list-dialog.component.scss']
})
export class DetailListDialogComponent implements OnInit {
symptomsList = SymptomForm;
medicalList = MedicalExtension;
testinList = Testing;
constructor(
public dialogRef: MatDialogRef<DetailListDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: any) {
console.log('declaration :', data);
}
ngOnInit(): void {
}
onNoClick(): void {
this.dialogRef.close();
}
convertSymptom(value) {
return +value === 0 ? 'Oui' : value === 1 ? 'Non' : value === 2 ? 'Inconnu' : value;
}
convertSanguin(value) {
return +value === 0 ? 'A' : value === 1 ? 'B' : value;
}
convertTesting(value) {
return +value === 0 ? 'Positive' : value === 1 ? 'Negative' : value === 2 ? 'En attente' : value === 3 ? 'Pas fini' : value ;
}
colors(value) {
return value === 0 ? 'red' : value === 1 ? 'green' : value === 2 ? 'gray' : value === 3 ? '#ff9c08' : 'black';
}
}
<file_sep>import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {HomeRoutingModule} from './home-routing.module';
import {HomeComponent} from './home.component';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {DemoMaterialModule} from '../material-module';
import {AgmCoreModule} from '@agm/core';
import {AutocompleteComponent} from './autocomplete/autocomplete.component';
import {MatGoogleMapsAutocompleteModule} from '@angular-material-extensions/google-maps-autocomplete';
import {FlexLayoutModule} from '@angular/flex-layout';
import {DialogsucessComponent} from './dialogsucess/dialogsucess.component';
@NgModule({
declarations: [HomeComponent, AutocompleteComponent, DialogsucessComponent],
imports: [
CommonModule,
HomeRoutingModule,
FormsModule,
ReactiveFormsModule,
DemoMaterialModule,
FlexLayoutModule,
AgmCoreModule.forRoot({
// please get your own API key here:
// https://developers.google.com/maps/documentation/javascript/get-api-key?hl=en
apiKey: '<KEY>',
libraries: ['places']
}),
MatGoogleMapsAutocompleteModule
],
exports: [AutocompleteComponent, DialogsucessComponent],
entryComponents: [AutocompleteComponent, DialogsucessComponent]
})
export class HomeModule {
}
<file_sep><div>
<div *ngIf="toDisplay == 0">
<div class="container informations" >
<p class="prem-title">Préaumbule</p>
<p class="prem-paragraph">
« L’application est fournie à titre gratuit, en l’état, uniquement à des fins d’information pour contribuer à fluidifier la prise en charge des personnes par les services d’urgences pendant l’épidémie de Coronavirus COVID-19. L’exhaustivité, l’exactitude, le caractère à jour des informations et contenus mis à disposition dans cette application, ou leur adéquation à des finalités particulières, ne sont pas garantis.
<br>
<br>
L’utilisateur reconnaît que l’application y compris le test et les autres informations qu’elle contient, ne constituent en aucun cas un avis, une recommandation, un examen, un diagnostic, une prescription, ou tout autre acte de nature médicale notamment établi ou réalisé par un médecin ou un pharmacien. L’utilisation de l’application et de son contenu ne remplace en aucun cas le conseil nécessaire donné par votre médecin ou votre pharmacien ou tout autre professionnel de santé compétent dans chaque cas particulier. Tout examen ou décision de l’utilisateur doit être réalisé ou prise de manière autonome sur la base de l’information scientifique et clinique pertinente, de la notice officielle du produit concerné le cas échéant et en cas de doute, en consultant un médecin compétent.
<br>
<br>
Les informations mises à disposition dans le cadre de l’application servent uniquement d’informations de premier niveau. L’absence d’avertissement au sujet d’un risque ne signifie pas qu’il n’existe pas. »
</p>
</div>
<button class="btn-prem" mat-flat-button (click)="gotToTest()">Démarrer le test <mat-icon>arrow_forward</mat-icon></button>
</div>
<div class="questionary" *ngIf="toDisplay !== 0">
<!--Question-->
<div class="form-container">
<!--SYMPTOMS-->
<div class="question"><p class="title">Questionnaire {{toDisplay}}</p></div>
<p class="quest-previous d-flex align-items-center" (click)="previous()">
<mat-icon>keyboard_arrow_left</mat-icon> {{' Question '+ (index + 1) + '/' + length}}</p>
<form [formGroup]="symptomForm" *ngIf="toDisplay == 1">
<div class="question-response">
<div *ngFor="let item of symptomValues; let i = index">
<div class="" *ngIf="i == symptomsIndex">
<div class="div-title"><p class="label slide-in-left">{{item.label}}</p></div>
<div class="div-questions">
<div [ngSwitch]="item.type" class="slide-in-left">
<div *ngSwitchCase="'number'">
<mat-radio-group formControlName="{{item.value}}" (change)="next()" class="align-column">
<mat-radio-button [value]=0>Oui / نعم</mat-radio-button>
<mat-radio-button [value]=1>Non / لا</mat-radio-button>
<mat-radio-button [value]=2><span> Je ne sais pas / لا أعرف</span></mat-radio-button>
</mat-radio-group>
</div>
<div *ngSwitchCase="'string'">
<mat-form-field class="w-100">
<input matInput [placeholder]="item.label + item.value == 'age' ? 'ans' : item.value == 'size' ?
'Cm' : item.value == 'weight' ? 'Kg' : ''" [type]="item.value == 'other' ? 'text' : 'number'" min="0"
formControlName="{{item.value}}"
>
</mat-form-field>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<!--FIN SYMPTOMS-->
<!--MEDICAL -->
<form [formGroup]="medicalForm" *ngIf="toDisplay == 2">
<div class="question-response">
<div *ngFor="let item of medicalExtension; let i = index">
<div *ngIf="medicalIndex == i">
<div class="div-title"><p class="label slide-in-left slide-in-left">{{item.label}}</p></div>
<div class="d-flex div-questions slide-in-left">
<div [ngSwitch]="item.type">
<div *ngSwitchCase="'group'">
<div [formGroupName]="item.value">
<mat-radio-group [formControlName]="item.valueRadioBox" class="align-column">
<mat-radio-button [value]=0>Oui / نعم</mat-radio-button>
<mat-radio-button [value]=1>Non / لا</mat-radio-button>
<mat-radio-button [value]=2>Je ne sais pas / لا أعرف</mat-radio-button>
</mat-radio-group>
</div>
</div>
<div *ngSwitchCase="'number'">
<mat-radio-group [formControlName]="item.value" (change)="next()" class="align-column">
<mat-radio-button [value]=0>Oui / نعم</mat-radio-button>
<mat-radio-button [value]=1>Non / لا</mat-radio-button>
<mat-radio-button [value]=2 class="smallSize">Je ne sais pas / لا أعرف</mat-radio-button>
</mat-radio-group>
</div>
</div>
<div [formGroupName]="item.value" class="input-other"
*ngIf="item.type === 'group' && medicalForm.get(item.value).get(item.valueRadioBox).value === 0">
<mat-form-field class="w-100">
<input matInput placeholder="Spécifiez" formControlName="{{item.valueInput}}"
>
</mat-form-field>
</div>
</div>
</div>
</div>
</div>
</form>
<!--FIN MEDICAL -->
<!--TESTING -->
<form [formGroup]="testingForm" *ngIf="toDisplay == 3">
<div class="question-response">
<div *ngFor="let item of testingDiag; let i = index">
<div *ngIf="testingIndex == i">
<div class="div-title">
<p class="label slide-in-left">{{item.label}}</p>
<div [ngSwitch]="item.valueType" class="ml-3 slide-in-left">
<div [formGroupName]="item.value">
<div *ngSwitchCase="'type'">
<mat-radio-group formControlName="firstValue" class="align" (change)="next()">
<mat-radio-button [value]=0>A</mat-radio-button>
<mat-radio-button [value]=1>B</mat-radio-button>
</mat-radio-group>
</div>
<div *ngSwitchCase="'string'">
<mat-form-field class="w-100">
<input matInput placeholder="Other" formControlName="firstValue" >
</mat-form-field>
</div>
</div>
</div>
</div>
<div class="div-questions slide-in-left">
<div [ngSwitch]="item.type">
<div *ngSwitchCase="'string'">
<mat-form-field class="w-100">
<input matInput placeholder="Other" [formControlName]="item.value" >
</mat-form-field>
</div>
<div *ngSwitchCase="'number'">
<mat-radio-group [formControlName]="item.value" (change)="next()" class="align-column">
<mat-radio-button [value]=0>Pos</mat-radio-button>
<mat-radio-button [value]=1>Neg</mat-radio-button>
<mat-radio-button [value]=2>Pend.</mat-radio-button>
<mat-radio-button [value]=3>Not done</mat-radio-button>
</mat-radio-group>
</div>
<div *ngSwitchCase="'group'">
<div formGroupName="{{item.value}}">
<mat-radio-group required formControlName="secondValue" (change)="next()" class="align-column">
<mat-radio-button [value]=0>Pos</mat-radio-button>
<mat-radio-button [value]=1>Neg</mat-radio-button>
<mat-radio-button [value]=2>Pend.</mat-radio-button>
<mat-radio-button [value]=3>Not done</mat-radio-button>
</mat-radio-group>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<!--FIN TESTING -->
</div>
<div class="buttons">
<!-- <button mat-stroked-button class="mr-2" (click)="previous()">Précédent</button>-->
<button mat-stroked-button (click)="done ? save() : next()"
[ngStyle]="{'background' : done ? '#0069cc' : '', 'color' : done ? 'white' : ''}"
class="next-button">{{ done ? 'Confirmer' : 'Suivant'}}</button>
<!-- <button mat-stroked-button (click)="save()" color="primary" *ngIf="done">Confirmer</button>-->
</div>
</div>
</div>
<file_sep>import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {MedicalExtension, SymptomForm, Testing, Specimens, SymptomsList} from '../symptom-form';
import {ApiserviceService} from '../../../apiservice.service';
@Component({
selector: 'app-forms',
templateUrl: './forms.component.html',
styleUrls: ['./forms.component.scss']
})
export class FormComponent implements OnInit {
symptomForm: FormGroup;
medicalForm: FormGroup;
testingForm: FormGroup;
specimensForm: FormGroup;
symptomValues = SymptomsList;
medicalExtension = MedicalExtension;
testingDiag = Testing;
preExisting: number;
specimen = Specimens;
show = false;
language: string;
constructor(private fb: FormBuilder, private api: ApiserviceService) {
}
ngOnInit() {
// symptom form
const symptom = {};
this.symptomValues.forEach(input => {
symptom[input.value] = input.value === 'other' ? new FormControl('') :
new FormControl('', [Validators.required]);
});
this.symptomForm = new FormGroup(symptom);
// medical form
const medical = {};
this.medicalExtension.forEach(input => {
if (input.type === 'group') {
medical[input.value] = this.specifyGroup();
} else {
medical[input.value] = input.value === 'other' ? new FormControl('') :
new FormControl('', [Validators.required]);
}
});
this.medicalForm = this.fb.group(medical);
// testing Form
const testing = {};
this.testingDiag.forEach(input => {
if (input.value !== 'email') {
if (input.type === 'group') {
testing[input.value] = this.fb.group({
firstValue: ['', Validators.required],
secondValue: ['', Validators.required]
});
} else if (input.type === 'number') {
testing[input.value] = input.value === 'other' ? new FormControl('') :
new FormControl('', [Validators.required]);
}
}
});
this.testingForm = this.fb.group(testing);
// Specimens Form
const specimen = {};
this.specimen.forEach(input => {
if (input.type === 'object') {
specimen[input.value] = this.specimensGroup();
} else {
specimen[input.value] = input.value === 'other' ? new FormControl('') :
new FormControl('', [Validators.required]);
}
});
this.specimensForm = this.fb.group(specimen);
}
save() {
const data = {
symptom: this.symptomForm.value,
medical: this.medicalForm.value,
testing: this.testingForm.value,
specimens: this.specimensForm.value
};
this.api.sendDataForm(data).subscribe(res => {
});
}
specifyGroup(): FormGroup {
return this.fb.group({radio: ['', Validators.required], specify: ['', Validators.required]});
}
specimensGroup(): FormGroup {
return this.fb.group({
specimenID: ['', Validators.required],
DateCollected: ['', Validators.required],
labTested: false,
labResult: ['', Validators.required],
sentCDC: false,
CDCResult: ['', Validators.required],
});
}
}
<file_sep>import {ApiserviceService} from '../apiservice.service';
import {Component, OnInit} from '@angular/core';
import {Router, ActivatedRoute} from '@angular/router';
import {TranslateService} from '@ngx-translate/core';
import {PageEvent} from '@angular/material/paginator';
import {HelpComponent} from './help/help.component';
import {MatDialog} from '@angular/material/dialog';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements OnInit {
// endpoints
genderPieEndpoint = '?f=api&endpoint=genderPie&preprod';
stackedEndpoint = '?f=api&endpoint=stacked&preprod';
nationalitiesEndpoint = '?f=api&endpoint=nationalities&preprod';
gendreAgeEndpoint = '?f=api&endpoint=genderAge&preprod';
sourceEndpoint = '?f=api&endpoint=sources&preprod';
govsEndpoint = '?f=api&endpoint=governates&preprod';
exportersEndpoint = '?f=api&endpoint=exporters&preprod';
casesEndpoint = '?f=api&endpoint=cases&preprod';
numbersEndpoint = '?f=api&endpoint=numbers';
statsEndpoint = '?f=api&endpoint=statistics';
// numbers
confirmed: number;
hospitalized: number;
discharged: number;
restablished: number;
dead: number;
last_update: number;
// table charts
cases: any[];
casesPaginator: any[];
averageAge: number;
language: string;
lastUpdateCases: string;
pageEvent: PageEvent;
pageIndex = 0;
length = 100;
pageSize = 10;
quarantaine: number;
depistage: number;
ratio: number;
quarantaine_achevee: number;
dateStatistics: string;
lastUpdates: any = {};
govs = {
Tataouine: 'تطاوين',
Kebili: 'قبلي',
Medenine: 'مدنين',
Kasserine: 'القصرين',
Gafsa: 'قفصة',
Sfax: 'صفاقس',
'Sidi Bouzid': 'سيدي بوزيد',
'Gabès': 'قابس',
Kairouan: 'القيروان',
Tozeur: 'توزر',
Kef: 'الكاف',
Siliana: 'سليانة',
Bizerte: 'بنزرت',
Beja: 'باجة',
Jendouba: 'جندوبة',
Mahdia: 'المهدية',
Nabeul: 'نابل',
Zaghouan: 'زغوان',
Sousse: 'سوسة',
Mannouba: 'منوبة',
Monastir: 'المنستير',
'<NAME>': 'بن عروس',
Ariana: 'أريانة',
Tunis: 'تونس',
unknown: 'غير معروف'
};
constructor(
private matDialog: MatDialog,
private apiService: ApiserviceService,
private router: Router,
private translate: TranslateService,
private route: ActivatedRoute) {
this.route.queryParams.subscribe(params => {
if (params.lang) {
this.language = params.lang;
} else {
this.language = 'fr';
}
});
translate.setDefaultLang(this.language);
}
ngOnInit(): void {
// getting numbers
this.apiService.get(this.numbersEndpoint).subscribe(
(data: any) => {
this.confirmed = data.Confirmed;
this.hospitalized = data.hospitalized;
this.discharged = data.Discharged;
this.restablished = data.Recovered;
this.dead = data.Dead;
this.last_update = data.last_update;
});
this.apiService.get(this.statsEndpoint).subscribe(
(data: any) => {
this.quarantaine = data.quarantaine;
this.depistage = data.depistage;
this.ratio = data.ratio.toFixed(2);
this.quarantaine_achevee = data.quarantaine_achevee;
this.dateStatistics = data.date;
});
this.getCases();
}
public getCases() {
// getting table data
this.apiService.get(this.casesEndpoint).subscribe(
(data: any) => {
this.cases = data.chartData.cases;
this.getServerData();
this.averageAge = data.chartData.average;
this.lastUpdateCases = data.last_update;
this.length = data.chartData.cases.length;
});
}
getServerData(event?) {
if (event) {
this.pageSize = event.pageSize;
this.pageIndex = event.pageIndex;
}
this.casesPaginator = [];
this.cases.forEach((item, index) => {
if (index < this.pageSize + (this.pageSize * this.pageIndex) && index >= this.pageIndex * this.pageSize) {
this.casesPaginator.push(item);
}
});
}
goTo(route) {
this.router.navigate([route]);
}
changeLaneguage(event) {
this.translate.use(event.value);
}
openHelpPopup(help) {
this.matDialog.open(HelpComponent, {
data: {
help,
lang: this.language
}
});
}
arGourenorate(gov) {
const governorate = Object.keys(this.govs).find(value => gov.includes(value));
return this.govs[governorate];
}
resultLastUpdate(event, label) {
this.lastUpdates[label] = event;
}
mapDisplay() {
this.cases.map(c => c.display = false);
}
}
| 1f9cdb64599f9ea21e7b4942abf5cb5f7ef4baeb | [
"TypeScript",
"HTML"
] | 19 | TypeScript | tebib91/formulaire_corona | 7f2c955ac67ca36dbc52a36ac1744b747f0b95ae | b884c1ceb1ae73cc481493c404db8ea11eadda76 |
refs/heads/main | <repo_name>ChrisAlonsoA/React<file_sep>/counter-app/src/tests/base/05-funciones.test.js
import { getUser, getUsuarioActivo } from "../../base/05-funciones";
describe('Pruebas de 05-funciones.js', () => {
//
test('getUser -> {objeto}', () => {
const resultado = {
uid: 'ABC123',
username: 'El_Papi1502'
}
const getUserTest = getUser();
expect(getUserTest).toEqual(resultado);
});
//
test('getusuarioActivo -> {objeto} con argumento', () => {
const nombre = 'Christian';
const getusuarioActivoTests = getUsuarioActivo(nombre);
const resultado = {
uid: 'ABC567',
username: nombre
}
expect(getusuarioActivoTests).toEqual(resultado);
});
});<file_sep>/gif-expert-app/src/tests/componentes/AddCategory.test.js
import React from 'react';
import '@testing-library/jest-dom';
import { AddCategory } from "../../componentes/AddCategory";
import {shallow} from 'enzyme';
describe('Probando AddCategory', () => {
const setCategories = jest.fn();
let wrapper = shallow(<AddCategory setCategories={setCategories}/>);
beforeEach(() => {
jest.clearAllMocks();
wrapper = shallow(<AddCategory setCategories={setCategories}/>);
});
//Requiere la funcion SetCategories como prop
test('Snapshot de <AddCategory/>', () => {
expect(wrapper).toMatchSnapshot();
});
//Simular cambios en input
test('Evaluar cambias en input', () => {
const input = wrapper.find('input');
const value = 'hola';
input.simulate('change', {
target: {value}
});
expect(wrapper.find('p').text().trim()).toBe(value);
});
//Simular submit, reinicia test, no se llama funcion
test('Prevent default', () => {
wrapper.find('form').simulate('submit', {
preventDefault(){}
});
expect(setCategories).not.toHaveBeenCalled();
});
//Se limpia el input
test('Llamar setCategories y limpiarla ', () => {
//console.log('limpiar');
//Change
const input = wrapper.find('input');
const value = 'hola';
input.simulate('change', {
target: {value}
});
//Submit
wrapper.find('form').simulate('submit', {
preventDefault(){},
});
expect(setCategories).toHaveBeenCalled();
expect(setCategories).toHaveBeenCalledTimes(1);
expect(setCategories).toHaveBeenCalledWith(expect.any(Function));
expect(wrapper.find('input').prop('value')).toBe('');
});
});<file_sep>/gif-expert-app/src/componentes/GifExpertApp.js
import React, {useState} from 'react'
import { AddCategory } from './AddCategory';
import { GifGrid } from './GifGrid';
export const GifExpertApp = ({defaultCategories=[]}) => {
//const categories = ['Inuyasha', 'Naruto', 'Samurai X'];
const [categories, setCategories] = useState(defaultCategories);
/*
const handleAdd = () => {
//setCategories([...categories, 'DeathNote']);
setCategories( cate => [...cate, 'DeathNote']);
}*/
//Para pasar datos en el <AddCategory/> agregamos que vamos a utilizar
return (
<>
<h2>GifExpertApp</h2>
<AddCategory setCategories={setCategories}/>
<hr/>
<ol>
{
categories.map(category =>
<GifGrid
key={category}
category={category}
/>
//<li key={category}>{category}</li>
) //El key no debe ser el indice, casi siempre es el id de la BD
}
</ol>
</>
)
}
<file_sep>/intro-js/src/bases/desestructuracion.js
//Destructuracion de objetos o Asignacion desestructurtante
//https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
//Expresiones que nos permiten desempacar valores de arreglos o objetos
const vengador = {
nombre: 'Tony',
apellido: 'Stark',
edad: 45,
clave: 'IronMan'
}
console.log(vengador.clave);
const retornaVengador = (usuario) => {
console.log(usuario);
}
retornaVengador(vengador);
//Se declaran variables const con valores especificos de las propiedades del objeto
const {nombre:nombreVengador, edad:edadVengador} = vengador;
console.log(nombreVengador);
console.log(edadVengador);
//Obtener ciertos valores
const valoresVengador = ({clave, rango = 'Lider'}) => {
console.log(clave, rango);
}
valoresVengador(vengador);
const masValores = ({clave, edad}) => {
return {
nombreClave: clave,
anios: edad,
latLng:{
lat:14.1234,
lng: -12.2345
}
}
}
const {nombreClave, anios, latLng: {lat, lng}} = masValores(vengador);
console.log(nombreClave, anios);
console.log(lat);
console.log(lng);
//Desestructuracion de Arreglos
const personajes = ['Goku', 'Vegeta', 'Picoro', 'Trunks'];
console.log(personajes);
console.log(personajes[3]);
const [p1] = personajes;
const [,p2] = personajes;
const [,,p3] = personajes;
console.log(p1);
console.log(p2);
console.log(p3);
const retornaArreglo = () => {
return ['ABCD', 1234];
}
const arr = retornaArreglo();
console.log(arr);
const [letras, numero] = retornaArreglo();
console.log(letras);
console.log(numero);
const userState = (valor) => {
return [valor, ()=> {console.log('Hola mundo')}];
}
//const arrUseState = useState('Goku');
//console.log(arrUseState);
const[nombrearr, setNombrearr] = userState('Krilin');
console.log(nombrearr);
setNombrearr();<file_sep>/intro-js/src/bases/asyncAwait.js
//Async
const getImagenPromesa = () => new Promise(resolve => resolve('https.google1.com'));
getImagenPromesa().then(console.log);
//Al poner asycn deja de ser una funcion y se convierte en promesa
const getImagen = async() => {
return 'https.google2.com'
}
getImagen().then(console.log);
//Async y Await
//Await nos ayuda a trabajar como si todo fuera sincrono
//Me espero a que termine await para continuar con la siguiente linea
const getDatos = async() => {
try {
const apiKey = '<KEY>';
const respuesta = await fetch(`http://api.giphy.com/v1/gifs/random?api_key=${apiKey}`);
const data = await respuesta.json();
console.log(data);
const url = data.data.images.original.url;
const img = document.createElement('img');
img.src = url;
document.body.append(img);
} catch (error) {
console.log('Error: ' + error)
}
}
getDatos();
<file_sep>/calendar-app/.env.development
REACT_APP_API_URL=http://localhost:1234/api
<file_sep>/heroes/src/tests/components/heroes/HeroeScreen.test.js
import React from 'react';
import { mount } from 'enzyme';
import { HeroeScreen } from '../../../components/heroes/HeroeScreen';
import { MemoryRouter, Route } from 'react-router-dom';
describe('Probando HeroeScreen', () => {
const history = {
length: 10,
goBack: jest.fn(),
push: jest.fn()
}
test('Debe de mostrar el componente redirect ', () => {
const wrapper = mount(
<MemoryRouter initialEntries={['/hero']}>
<HeroeScreen history={history}/>
</MemoryRouter>
);
expect(wrapper).toMatchSnapshot();
expect(wrapper.find('Redirect').exists()).toBe(true);
});
test('Debe de mostrar un heroe si el parametro existe', () => {
const wrapper = mount(
<MemoryRouter initialEntries={['/heroe/marvel-hulk']}>
<Route path="/heroe/:heroeId" component={HeroeScreen}/>
</MemoryRouter>
);
expect(wrapper.find('.row').exists()).toBe(true);
});
test('Debe regresar a la pantalla anterior con PUSH', () => {
const history = {
length: 1,
goBack: jest.fn(),
push: jest.fn()
}
const wrapper = mount(
<MemoryRouter initialEntries={['/heroe/marvel-hulk']}>
<Route
path="/heroe/:heroeId"
component={() => <HeroeScreen history={history}/>}
/>
</MemoryRouter>
);
wrapper.find('button').prop('onClick')();
expect(history.push).toHaveBeenCalledWith('/');
expect(history.goBack).not.toHaveBeenCalled();
});
test('Debe regresar a la pantalla anterior con goBack', () => {
const history = {
length: 3,
goBack: jest.fn(),
push: jest.fn()
}
const wrapper = mount(
<MemoryRouter initialEntries={['/heroe/marvel-hulk']}>
<Route
path="/heroe/:heroeId"
component={() => <HeroeScreen history={history}/>}
/>
</MemoryRouter>
);
wrapper.find('button').prop('onClick')();
expect(history.goBack).toHaveBeenCalledWith();
expect(history.push).not.toHaveBeenCalled();
});
test('Debe de llamar el Redirect', () => {
const wrapper = mount(
<MemoryRouter initialEntries={['/heroe/marvel-huwdefek']}>
<Route
path="/heroe/:heroeId"
component={() => <HeroeScreen history={history}/>}
/>
</MemoryRouter>
);
console.log(wrapper.html());
expect(wrapper.find('Redirect').exists()).toBe(false);
});
});<file_sep>/heroes/src/tests/auth/authReducer.test.js
import { authReducer } from "../../auth/authReducer";
import { types } from "../../types/types";
describe('Probando authReducer', () => {
test('Debe de retornar el estado por defecto ', () => {
const state = authReducer({logged: false}, {});
expect(state).toEqual({logged: false});
});
test('Debe pasar el nombre, autentificar', () => {
const action = {
type: types.login,
payload: {
name: 'Christian'
}
};
const state = authReducer({logged: false}, action);
expect(state).toEqual({
logged: true,
name: 'Christian'
});
});
test('Debe de borrar el name del user y logged en false', () => {
const action = {
type: types.logout,
payload: {}
};
const state = authReducer({logged: false, name: 'Chris'}, action);
expect(state).toEqual({
logged: false,
});
});
});<file_sep>/calendar-backend/index.js
//Configuracion basica de express, como hacer un import
const express = require('express');
require('dotenv').config();
const { dbConnection } = require('./database/config');
const cors = require('cors');
//Crear el servidor de express
const app = express();
//Llamar mi DB
dbConnection();
//CORS
app.use(cors());
//Directorio publico
app.use(express.static('public'));
//Lectura y parseo del body (Enviamor informacion)
app.use(express.json());
//Rutas o Endpoints
app.use('/api/auth', require('./routes/auth')); // --> Auth: crear, login, token
app.use('/api/events', require('./routes/events')); // --> Crud: Eventos
//Escuchar peticiones
app.listen(process.env.PORT, () => {
console.log(`Corriendo servidor ${process.env.PORT}`);
});<file_sep>/counter-app/src/PrimeraApp.js
//Un componente usa upperCamelCase
//Clases o functionalComponets FC
//Clases ya no se usan, se usan funciones
import {Fragment} from 'react'
import React from 'react';
import PropTypes from 'prop-types'
/*
const PrimeraApp = ({saludo, despedida, subtitulo} ) => {
const saludos = 'H<NAME> String';
const numero = 123.12;
const arreglo = [1,2,3,4,5,6];
const persona = {
nombre: 'Chris',
edad: 25
};
/*
return (
<Fragment>
<h1>{saludo}</h1>
<p>{subtitulo}</p>
</Fragment>
);**
return (
<>
<h1>Primer componente</h1>
<p>{saludos}</p>
<p>{numero}</p>
<p>{arreglo}</p>
<p>{JSON.stringify(persona, null, 3)}</p>
<p>{saludo}</p>
<p>{despedida}</p>
<p>{subtitulo}</p>
</>
);
}*/
//Para mis pruebas
const PrimeraApp = ({saludo, subtitulo} ) => {
return (
<Fragment>
<h1>{saludo}</h1>
<p>{subtitulo}</p>
</Fragment>
);
}
PrimeraApp.propTypes = {
saludo: PropTypes.string.isRequired,
}
PrimeraApp.defaultProps = {
subtitulo: 'Soy un subtitulo'
}
export default PrimeraApp;
<file_sep>/hook-app/src/tests/hooks/useCounter.test.js
import {renderHook, act} from '@testing-library/react-hooks';
import { useCounter } from '../../hooks/useCounter';
describe('Probando useCounter', () => {
test('Debe de retornar valores por defecto ', () => {
const {result} = renderHook(() => useCounter());
//console.log(result.current);
expect(result.current.counter).toBe(0);
expect( typeof result.current.decrement).toBe('function');
expect( typeof result.current.increment).toBe('function');
expect( typeof result.current.reset).toBe('function');
});
test('Debe de retornar valores que proporciono ', () => {
const {result} = renderHook(() => useCounter(100));
//console.log(result.current);
expect(result.current.counter).toBe(100);
});
test('Debe incrementar el counter', () => {
const {result} = renderHook(() => useCounter(100));
const {increment} = result.current;
act(() => {
increment();
});
const {counter} = result.current;
expect(counter).toBe(101);
});
test('Debe decrementar el counter', () => {
const {result} = renderHook(() => useCounter(100));
const {decrement} = result.current;
act(() => {
decrement();
});
const {counter} = result.current;
expect(counter).toBe(99);
});
test('Debe resetear el counter', () => {
const {result} = renderHook(() => useCounter());
const {increment} = result.current;
const {reset} = result.current;
act(() => {
increment();
reset();
});
const {counter} = result.current;
expect(counter).toBe(0);
});
});<file_sep>/gif-expert-app/src/tests/helpers/getGifs.test.js
import { getGifs } from "../../helpers/getGifs";
describe('Probando Helper getGifs Fetch', () => {
test('Debe traer a 10 elementos', async() => {
const gifs = await getGifs('Inuyasha');
expect(gifs.length).toBe(10);
});
test('No tiene category', async() => {
const gifs = await getGifs('');
//console.log(gifs);
expect(gifs.length).toBe(0);
});
});<file_sep>/heroes/src/tests/HeroesApp.test.js
import { HeroesApp } from "../HeroesApp";
import React from 'react';
import {shallow} from 'enzyme';
describe('Probando HeroesApp', () => {
test('Se muestra bien', () => {
const wrapper = shallow(<HeroesApp/>);
expect(wrapper).toMatchSnapshot();
});
});<file_sep>/hook-app/src/tests/components/03-examples/TodoListItem.test.js
import {shallow} from 'enzyme';
import React from 'react';
import { TodoListItem } from '../../../components/08-useReducer/TodoListItem';
import {demotoDo } from '../../fixtures/demotoDo';
describe('Probando ToDoListItem', () => {
const handleDelete = jest.fn();
const handleToggle = jest.fn();
const wrapper = shallow(
<TodoListItem
toDo={demotoDo[0]}
i={0}
handleDelete={handleDelete}
handleToggle={handleToggle}
/>);
test('Debe de mostrarse correctamente ', () => {
expect(wrapper).toMatchSnapshot();
});
test('Debe de llamar la función borrar', () => {
wrapper.find('button').simulate('click');
expect(handleDelete).toHaveBeenCalledWith(demotoDo[0].id)
});
test('Debe de llamar la funcioon toggle', () => {
wrapper.find('p').simulate('click');
expect(handleToggle).toHaveBeenCalledWith(demotoDo[0].id)
});
test('Debe mostrar p correctamente', () => {
const p = wrapper.find('p');
expect(p.text().trim()).toBe(`1.- ${demotoDo[0].descripcion}`)
});
test('Debe tener la clase complete', () => {
const toDo = demotoDo[0];
toDo.done = true;
const wrapper = shallow(
<TodoListItem
toDo={demotoDo[0]}
/>);
expect(wrapper.find('p').hasClass('complete')).toBe(true);
});
});<file_sep>/intro-js/src/data/gatos.js
const gatos = [
{
gato: 'panzas',
edad: 10
},
{
gato: 'Shikis',
edad: 5
}
]
export default gatos;<file_sep>/counter-app/src/base/08-imp-exp.js
import heroes from '../data/heroes'
//Find
export const getHeroeByID = (id) => {
return heroes.find((heroe) => {
return heroe.id === id;
});
}
//Filter
export const getHeroesByOwner = (owner) => heroes.filter((heroe) => heroe.owner === owner)
<file_sep>/hook-app/src/tests/components/03-examples/ToDoList.test.js
import {shallow} from 'enzyme';
import React from 'react';
import {demotoDo } from '../../fixtures/demotoDo';
import { ToDoList } from '../../../components/08-useReducer/ToDoList';
describe('Probando toDoList', () => {
const handleDelete = jest.fn();
const handleToggle = jest.fn();
const wrapper = shallow(
<ToDoList
toDos={demotoDo}
handleDelete={handleDelete}
handleToggle={handleToggle}
/>);
test('Mostrar correctamente', () => {
expect(wrapper).toMatchSnapshot();
});
test('Debe de tener dos elementos', () => {
expect(wrapper.find('TodoListItem').length).toBe(demotoDo.length);
expect(wrapper.find('TodoListItem').at(0).prop('handleDelete')).toEqual(expect.any(Function));
});
});<file_sep>/gif-expert-app/src/componentes/GifGrid.js
import React from "react";
import { useFetchGifs } from "../hooks/useFetchGifs";
import { GifGridItem } from "./GifGridItem";
import PropTypes from 'prop-types';
//import { getGifs } from "../helpers/getGifs";
export const GifGrid = ({ category }) => {
//Al ejecutar una funcion dentro de una api, se vuelve un ciclo infinito
//UseEffect hace que no hagamos ciclo infinito
//Ejecuta cierto codigo de manera condicional
//El arreglo vacio, indica que solo se ejecuta una vez
//const [images, setImages] = useState([]);
//Usamos helpers
const {data:images, loading} = useFetchGifs(category);
//console.log(data, loading);
/*
useEffect(() => {
getGifs(category)
.then(imgs =>{
setImages(imgs);
})
}, [category]);//Si la category cambia, se vuelve a ejecutar
*/
return (
<>
<h3 className="animate_animated animate_fadeIn">{category}</h3>
{loading && <p className="animate_animated animate_flash">Loading...</p>}
<div className="card-grid">
{images.map(img => (
<GifGridItem key={img.id} {...img} />
))}
</div>
</>
);
};
GifGrid.propTypes = {
category: PropTypes.string.isRequired
}
<file_sep>/hook-app/src/components/01-useState/CounterWithCustomHook.js
import React from 'react';
import './counter.css'
//Importamos el hooks que acabamos de hacer
import { useCounter } from '../hooks/useCounter';
export const CounterWithCustomHook = () => {
const {state:counter, increment, decrement, reset} = useCounter(0);
return (
<>
<h1>CounterWithCustomHook: {counter}</h1>
<hr/>
<button
className="btn btn-primary"
onClick={increment}
>
+1
</button>
<button
className="btn btn-primary"
onClick={reset}
>
Reset
</button>
<button
className="btn btn-secondary"
onClick={() => decrement(2)}
>
-1
</button>
</>
)
}
<file_sep>/counter-app/src/tests/CounterApp.test.js
import '@testing-library/jest-dom';
import {shallow} from 'enzyme';
import CounterApp from '../CounterApp';
import React from 'react';
describe('Pruebas en CounterApp', () => {
//Obtener todo el wrapper para las pruebas
let wrapper = shallow(<CounterApp/>);
//Inicializar antes de cada prueba
beforeEach(()=>{
//console.log('Empieza prueba reiniciada...');
wrapper = shallow(<CounterApp/>);
});
test('Mostrar <CounterApp/> correctamente', () => {
//const wrapper = shallow(<CounterApp/>);
expect(wrapper).toMatchSnapshot();
});
test('Mostrar valor por defecto de 100', () => {
const value = 100;
const respuesta = `Valor de inicio: ${value}`;
const wrapper = shallow(
<CounterApp value={value}/>
)
const valorIniciar = wrapper.find('h2').text();
//console.log(valorIniciar);
expect(valorIniciar).toBe(respuesta);
});
//Click
test('Debe incrementar con el boton +1', () => {
//const wrapper = shallow(<CounterApp/>);
const btn1 = wrapper.find('button').at(0);
btn1.simulate('click');
const counter = wrapper.find('h4').text();
expect(counter).toBe('1');
});
test('Debe decrementar con el boton -1', () => {
//const wrapper = shallow(<CounterApp/>);
const btn3 = wrapper.find('button').at(2);
btn3.simulate('click');
const counter = wrapper.find('h4').text();
expect(counter).toBe('-1');
});
test('Debe resetear al valor inicial', () => {
const wrapper = shallow(<CounterApp value={105}/>) ;
wrapper.find('button').at(0).simulate('click');
wrapper.find('button').at(1).simulate('click');
const counter = wrapper.find('h4').text();
expect(counter).toBe('105');
});
});
<file_sep>/counter-app/src/tests/base/09-promesas.test.js
import { getHeroeByIdAsync } from "../../base/09-promesas";
import { heroes } from "../../data/heroes";
import '@testing-library/jest-dom';
import '@testing-library/jest-dom/extend-expect';
describe('Pruebas en 09-promesas.js', () => {
test('should ', () => {
});
/*
test('getHeroeByIdAsync -> Heroe Async ', (done) => {
const id = 1;
getHeroeByIdAsync(id)
.then(heroe => {
expect(heroe).toBe(heroes[0]);
done();
})
});
test('getHeroeByIdAsync -> No existe heroe', (done) => {
const id = 10;
getHeroeByIdAsync(id)
.catch(error => {
expect(error).toBe('No se pudo encontrar el héroe');
done();
})
});*/
});<file_sep>/intro-js/src/bases/basico.js
//Variables y constantes
//No usar var
const nombre = 'Christian';
let apellido = 'Alonso';
let valorDado = 5;
valorDado = 4;
console.log(nombre, apellido, valorDado);
if(true){//Scope
const nombre = 'Fernando';
let valorDado = 6;
console.log(nombre, valorDado);
}
console.log(nombre, apellido, valorDado);
//Template string ``
console.log(`Mi nombre es ${nombre} y mi apellido es ${apellido}`);
function getSaludo(){
return 'Soy una funcion';
}
console.log(`Llamando a la funcion: ${getSaludo()}`);
//Objetos literal
const persona = {
nombre: 'Tony',
apellido: 'Stark',
edad: 45,
direccion: {
ciudad: 'New York',
zip: 12345,
lat: 14.2,
lng: 12.2
}
};
console.log(persona);
console.log({persona});//Crea un objeto del objeto
console.table(persona);
const persona2 = {...persona};//Crea una copia del objeto
console.log(persona2);
//Paso por referencia -> Se pasa un copia
//Paso por valor -> Se pasa el original
//Arreglos
//Coleccion de informacion
//const arreglo = new Array(5);//Solo usarlo cuando se tiene el tamaño especifico, no pone candado, mejor []
//Documentacion map -> https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Array/map
/*Map crea un nuevo array con los resultados de la llamada a la funcion indicada
var numbers = [1, 5, 10, 15];
var doubles = numbers.map(function(x) {
return x * 2;
});
// doubles is now [2, 10, 20, 30]
// numbers is still [1, 5, 10, 15]*/
const arreglo = [1,2,3,4];
arreglo.push(1);
arreglo.push(2);
let arreglo2 = [...arreglo, 5];
const arreglo3 = arreglo2.map(function(numero){
return numero * 2;
});
console.log(arreglo);
console.log(arreglo2);
console.log(arreglo3);
//Funciones
function saludar(nombre){
return `Hola, ${nombre}`;
}
console.log(saludar('Goku'));
//Mejor forma
const saludo = function(name){
return `Hola, ${name}`;
}
console.log(saludo('Vegeta'));
//Flecha
const saludar2 = (nombre2) => {
return `Hola ${nombre2}`;
}
console.log(saludar2);
console.log(saludar2('Pikoro'));
const getUser = () =>{
return {
uid: 'ABC123',
username: 'Krozz18'
}
}
const getInfo = () => ({
id: '123',
name: 'ABC'
});
console.log(getUser());
console.log(getInfo());
function getUsuarioActivo(nombre){
return{
uid: '1234567',
username: nombre
}
};
const usuarioActivo = getUsuarioActivo('Fernando');
console.log(usuarioActivo);
const userActivate = (name) => ({
uid: '87654321',
username: name
});
const userActi = userActivate('Chris');
console.log(userActi);
<file_sep>/journal-app/src/firebase/firebase-config.js
import firebase from 'firebase/app';
import 'firebase/firestore';
import 'firebase/auth';
const firebaseConfig = {
apiKey: "<KEY>",
authDomain: "react-journal-app-5cd8b.firebaseapp.com",
projectId: "react-journal-app-5cd8b",
storageBucket: "react-journal-app-5cd8b.appspot.com",
messagingSenderId: "565481088440",
appId: "1:565481088440:web:64535374943e37d4f3db4d"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
//Mi base de datos - referencia
const db = firebase.firestore();
//Authenticacion
const googleAuthProvider = new firebase.auth.GoogleAuthProvider();
export{
db,
googleAuthProvider,
firebase
}<file_sep>/counter-app/src/tests/base/07-deses-arr.test.js
import { retornaArreglo } from "../../base/07-deses-arr";
describe('Pruebas en 07-deses-arr', () => {
test('retornaArreglo() -> [arreglo]', () => {
const retornaArregloTests = retornaArreglo();
//console.log(retornaArregloTests);
const [letras, numero] = retornaArreglo();
const resultado = ['ABC', 123];
expect(retornaArregloTests).toEqual(resultado);
expect(letras).toBe('ABC');
expect(typeof letras).toBe('string');
expect(numero).toBe(123)
expect(typeof numero).toBe('number');
});
});<file_sep>/counter-app/src/tests/base/02-template-string.test.js
//Completar jest
import '@testing-library/jest-dom';
//Importamos la funcion a probar
import { getSaludo } from "../../base/02-template-string";
describe('Pruebas 02 template-string', () => {
test('getSaludo() -> Hola + nombre', () => {
const nombre = 'Christian';
const saludo = getSaludo(nombre);
//console.log(saludo);
expect(saludo).toBe('Hola ' + nombre);
});
//getSaludo debe retornar <NAME>, si no hay argumento
test('getSaludo() -> Sin argumento <NAME>', () => {
const resultado = '<NAME>';
const saludo = getSaludo();
expect(saludo).toBe(resultado);
//console.log(saludo);
});
});<file_sep>/intro-js/src/index.js
//Documentacion JS: https://developer.mozilla.org/es/
<file_sep>/hook-app/src/components/08-useReducer/ToDoApp.js
import React, {useReducer, useEffect} from 'react';
import { toDoReducer } from './toDoReducer';
import {useForm} from '../hooks/useForm'
import './style.css';
import { ToDoList } from './ToDoList';
//Funcion init
const init = () => {
/*
return [{
id: new Date().getTime(),
descripcion: 'Aprender React',
done: false
}];*/
return JSON.parse(localStorage.getItem('todos')) || [];
}
export const ToDoApp = () => {
//Usamos useReducer
const [toDos, dispatch] = useReducer(toDoReducer, [], init);
//Hooks de forms para extraer los datos
const [{descripcion}, handleInputChange, reset] = useForm({
descripcion: '',
})
//useEffect para guardar en localStorage cada que toDos cambia
useEffect(() => {
localStorage.setItem('todos', JSON.stringify(toDos));
}, [toDos]);
//Click en agregar
const handleSubmit = (e) => {
e.preventDefault();
//console.log('Agregar');
if(descripcion.trim().length <= 1){
return;
}
const newToDo = {
id: new Date().getTime(),
descripcion: descripcion,
done: false
};
const action = {
type: 'add',
payload: newToDo
}
dispatch(action);
reset();
}
//Click en eliminar
const handleDelete = (id) => {
//console.log(id);
const action = {
type: 'delete',
payload: id
}
dispatch(action);
}
const handleToggle = (id) => {
//console.log('Toogle');
const action = {
type: 'toggle',
payload: id
}
dispatch(action);
}
return (
<div>
<h1>ToDoApp ({toDos.length})</h1>
<hr/>
<div className="row">
<div className="col-7">
<ToDoList
toDos={toDos}
handleDelete={handleDelete}
handleToggle={handleToggle}
/>
</div>
<div className="col-5">
<h4>Agregar ToDo</h4>
<hr/>
<form onSubmit={handleSubmit}>
<input
type="text"
name="descripcion"
placeholder="Aprender ..."
autoComplete="off"
className="form-control"
value={descripcion}
onChange={handleInputChange}
/>
<button
type="submit"
className="btn btn-outline-primary btn-block mt-1"
>Agregar</button>
</form>
</div>
</div>
</div>
)
}
<file_sep>/hook-app/src/tests/components/03-examples/MultipleCustomHooks.test.js
import { MultipleCustomHooks } from "../../../components/03-examples/MultipleCustomHooks";
import React from 'react';
import { shallow} from 'enzyme';
import { useFetch } from "../../../hooks/useFetch";
//import { useFetch } from "../../../hooks/useFetch";
jest.mock('../../../hooks/useFetch');
describe('Probando MultipleCustomHook', () => {
test('Debe de mostrrase correctamente ', () => {
useFetch.mockReturnValue({
data: null,
loding: true,
error: null
})
const wrapper = shallow(<MultipleCustomHooks/>);
expect(wrapper).toMatchSnapshot();
});
test('Debe de mostrar la informacion ', () => {
useFetch.mockReturnValue({
data: [{
data: [{
author: 'Chris',
quote: 'Hola mundo'
}],
loding: false,
error: null
}],
loding: true,
error: null
});
const wrapper = shallow(<MultipleCustomHooks/>);
expect(wrapper.find('.alert').exists()).toBe(false);
//expect(wrapper.find('.mb-2').text().trim()).toBe('Hola mundo');
//expect(wrapper.find('footer').text().trim()).toBe('Chris');
//console.log(wrapper.html());
});
});<file_sep>/gif-expert-app/src/tests/componentes/GifGridItem.test.js
import {shallow} from 'enzyme';
import React from 'react'
import {GifGridItem} from '../../componentes/GifGridItem';
describe('Probando GifGridItem', () => {
const title = 'titulo';
const url = 'https://localhost/algo.jpg'
const wrapper = shallow(<GifGridItem title={title} url={url}/>);
test('Debe mostra <GifGridItem/>', () => {
//const wrapper = shallow(<GifGridItem title={title} url={url}/>);
expect(wrapper).toMatchSnapshot();
});
test('Debe de tener un p -> con el texto', () => {
const p = wrapper.find('p');
expect(p.text().trim()).toBe(title);
});
test('Imagen debe tener imagen == url y props', () => {
const img = wrapper.find('img');
//console.log(img.prop('src'));
expect(img.prop('src')).toBe(url);
expect(img.prop('alt')).toBe(title)
});
test('Debe tener la clase Css', () => {
const div = wrapper.find('div');
const className = div.prop('className');
//console.log(div.hasClass());
expect(className.includes('animate__animated')).toBe(true);
});
});
<file_sep>/counter-app/src/tests/PrimeraApp.test.js
import PrimeraApp from "../PrimeraApp";
import React from 'react';
//import {render} from '@testing-library/react';
//import '@testing-library/jest-dom/extend-expect';
import '@testing-library/jest-dom';
import {shallow} from 'enzyme';
/*
describe('Pruebas en PrimeraAPP', () => {
test('Demostrar Hola soy Goku ', () => {
const saludo = '<NAME>';
//Wrapper = Producto renderizado de mi componente React
const {getByText} = render(<PrimeraApp saludo={saludo}/>);
expect(getByText(saludo)).toBeInTheDocument();
});
});*/
import Enzyme from 'enzyme';
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
describe('Pruebas en PrimeraAPP', () => {
test('Debe mostrar <PrimeraApp/> correctamente', () => {
const saludo = '<NAME>';
const wrapper = shallow(<PrimeraApp saludo={saludo}/>);
expect(wrapper).toMatchSnapshot();
});
//Subtitulo
test('Debe de mostrar subtitulo, enviado por props', () => {
const subtitulo = 'Soy un subtitulo';
const saludo = '<NAME>';
const wrapper = shallow(
<PrimeraApp
saludo={saludo}
subtitulo={subtitulo}
/>
);
const textoParrafo = wrapper.find('p').text();
//console.log(textoParrafo);
expect(textoParrafo).toBe(subtitulo);
});
});<file_sep>/intro-js/src/bases/ternarios.js
const activo = true;
let mensaje = '';
/*
if(activo){
mensaje = 'Activo';
}else{
mensaje = 'Inactivo';
}
mensaje = (activo)? 'Activo':'Inactivo';*/
mensaje = activo && 'Activo';//Si no cumple regresa False
console.log(mensaje);
activo===true?console.log('true'):console.log('false');<file_sep>/hook-app/src/tests/HookApp.test.js
import {shallow} from 'enzyme';
import React from 'react';
import { HookApp } from '../HookApp';
describe('Probando HookApp', () => {
test('SnapShot correcto', () => {
const wrapper = shallow(<HookApp/>);
expect(wrapper).toMatchSnapshot();
});
});<file_sep>/heroes/src/components/heroes/HeroeScreen.js
import React, { useMemo } from 'react';
import {useParams, Redirect} from 'react-router-dom';
import { getHeroesById } from '../../selectors/getHeroesById';
export const HeroeScreen = ({history}) => {
const {heroeId} = useParams();
const hero = useMemo(() => getHeroesById(heroeId), [heroeId]);
//const hero = getHeroesById(heroeId);
//console.log(hero);
if(!hero){
return <Redirect to="/"/>
}
const {
superhero,
publisher,
alter_ego,
first_appearance,
characters
} = hero;
const handleReturn = () =>{
if(history.length <=2){
history.push('/');
}else{
history.goBack();
}
}
return (
<div className="row mt-5 animate__fadeInTopLeft">
<div className="col-4">
<img
className="img-thumbnail animate__fadeInDownBig"
alt={superhero}
src={`../assets/heroes/${heroeId}.jpg`}
/>
</div>
<div className="col-8">
<h3 className="text-success">{superhero}</h3>
<ul className="list-group list-group-flush">
<li className="list-group-item"><b>Alter ego:</b> {alter_ego}</li>
<li className="list-group-item"><b>Publisher:</b> {publisher}</li>
<li className="list-group-item"><b>First appearance:</b> {first_appearance}</li>
</ul>
<h5 className="mt-3"> Character:</h5>
<p>{characters}</p>
<button
className="btn btn-outline-info mt-2"
onClick={handleReturn}
>Return</button>
</div>
</div>
)
}
| 62acea94d9b00ec36f6abe094cf2e53c2ec2883b | [
"JavaScript",
"Shell"
] | 33 | JavaScript | ChrisAlonsoA/React | 0c9e1ec9f133901e8755bc8098c129973e4c304d | f3900b2b8bb1175c2d4d934779d9aee9cc23dbb8 |
refs/heads/master | <repo_name>lakshansameera/OOPGROUPPROJECT<file_sep>/oopProject2020/src/main/java/oopProject2020/Models/Operator.java
package oopProject2020.Models;
public class Operator extends user {
public Operator(String name, String email, String address, String contactNumber, String regNo, int userType) {
super(name, email, address, contactNumber, regNo, userType);
// TODO Auto-generated constructor stub
}
public Operator()
{
super();
}
}
<file_sep>/oopProject2020/src/main/java/oopProject2020/Models/interfaces/Student.java
package oopProject2020.Models.interfaces;
public interface Student {
}
<file_sep>/oopProject2020/src/main/java/oopProject2020/Controls/AddVehicle.java
package oopProject2020.Controls;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import oopProject2020.Models.Vehicle;
/**
* Servlet implementation class AddVehicle
*/
public class AddVehicle extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AddVehicle() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
String VehicleType= request.getParameter("vehicleType");
int numOfPassengers = Integer.parseInt(request.getParameter("noOfPessengers"));
String RejNo = request.getParameter("rejNo");
String VehicleStatus = request.getParameter("VehicleStatus");
int status;
if(VehicleStatus.equals("Available")){
status =0;
}
else
{
status =1;
}
Vehicle vehicle = new Vehicle(RejNo, VehicleType,numOfPassengers, status);
vehicle.insertVehicle();
}
}
| 6ed8ba8d6b17926410cbf556c9d20766681d596e | [
"Java"
] | 3 | Java | lakshansameera/OOPGROUPPROJECT | 04afdde062ed6308778add373f9724a7d5d0443c | e69e8acd260921ad988a054519ea106c3024948c |
refs/heads/master | <repo_name>paoloiaretti/demomis_coll<file_sep>/README.md
# demomis
# missviluppo: percorso per db "OracleXE"->schema "missviluppo"
# miscollaudo: percorso per db "OracleXE"->schema "miscollaudo"<file_sep>/src/demomis_tic1111.sql
--liquibase formatted sql
--changeset iaretti:v.tic1111.1
--comment Aggiunta PIVA tabella ANAGRAFICA
ALTER TABLE ANAGRAFICA
ADD (PIVA VARCHAR2(21) );
--changeset iaretti:v.tic1111.2
--comment Aggiunta CF tabella ANAGRAFICA
ALTER TABLE ANAGRAFICA
ADD (CF VARCHAR2(16) );
| e1ac96b5d3db4f150abb83ca91ce379aedacdf42 | [
"Markdown",
"SQL"
] | 2 | Markdown | paoloiaretti/demomis_coll | e3d0366fa049c7956b6e33bb474183097396f294 | 20958d88c67bb058956163c6954082e320be379f |
refs/heads/master | <repo_name>Moraxno/testGame<file_sep>/src/com/github/moraxno/sprites/SpriteAtlas.java
package com.github.moraxno.sprites;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.awt.image.ImageProducer;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import com.github.moraxno.registry.Time.Updatable;
import javax.imageio.ImageIO;
public class SpriteAtlas implements Updatable
{
private ArrayList<Image> _sprites = new ArrayList<Image>();
private int _current;
private int MILLISECONDS_PER_FRAME = 100;
private int _tickedMS = MILLISECONDS_PER_FRAME;
private static String[] EXTENSIONS = new String[]
{
"jpg", "png", "bmp"
};
static FilenameFilter IMAGE_FILTER = new FilenameFilter() {
@Override
public boolean accept(final File dir, final String name) {
for (String ext : EXTENSIONS) {
if (name.endsWith("." + ext)) {
return (true);
}
}
return (false);
}
};
public SpriteAtlas(File path, int frameTime)
{
_sprites = readFolder(path);
MILLISECONDS_PER_FRAME = frameTime;
}
public Image currentSprite()
{
return _sprites.get(_current);
}
public void update()
{
_current = (_current >= _sprites.size() - 1) ? 0 : _current + 1;
}
private ArrayList<Image> readFolder(File path)
{
ArrayList<Image> images = new ArrayList<Image>();
if (path.isDirectory()) { // make sure it's a directory
for (final File f : path.listFiles(IMAGE_FILTER)) {
BufferedImage img = null;
try {
img = ImageIO.read(f);
images.add(img);
} catch (IOException e) {
}
}
}
return images;
}
@Override
public void decTick(int millisecondsElapsed)
{
_tickedMS -= millisecondsElapsed;
}
@Override
public boolean isReady()
{
return (_tickedMS <= 0);
}
@Override
public void resetTimer()
{
_tickedMS += MILLISECONDS_PER_FRAME;
}
}
<file_sep>/src/com/github/moraxno/math/Vector2D.java
package com.github.moraxno.math;
/**
* A crude model of a mathematical Vector
*
* @author Moraxno
*/
public class Vector2D
{
private double _x;
private double _y;
/**
* simple Constructor
* @param x the X Component
* @param y the Y Component
*/
public Vector2D(double x, double y)
{
setX(x);
setY(y);
}
/**
* @return X Component
*/
public double getX()
{
return _x;
}
/**
* @param x the X Component
*/
public void setX(double x)
{
_x = x;
}
/**
* @return Y Component
*/
public double getY()
{
return _y;
}
/**
* @param y the Y Component
*/
public void setY(double y)
{
this._y = y;
}
/**
* @return a new Vector2D with the same components
*/
public Vector2D clone()
{
Vector2D n = new Vector2D(0,0);
n.setX(getX());
n.setY(getY());
return n;
}
/**
* @return a Vector2D(0,0)
*/
public static Vector2D zero()
{
return new Vector2D(0,0);
}
/**
*
* @param d the factor to multi
*/
public Vector2D scale(double d)
{
this.setX(getX() * d);
this.setY(getY() * d);
return this;
}
/**
* @return the length of the Vector2D
*/
public double length()
{
return Math.sqrt(MMath.square(getX())
+ MMath.square(getY()));
}
public Vector2D add(Vector2D v)
{
setX(getX() + v.getX());
setY(getY() + v.getY());
return this;
}
public String toString()
{
return getX() + "/" + getY();
}
}
<file_sep>/src/com/github/moraxno/Objects/SpriteObject.java
package com.github.moraxno.Objects;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import com.github.moraxno.config.PlayerConfig;
import com.github.moraxno.registry.MainHandler;
import com.github.moraxno.sprites.MyImageObserver;
import com.github.moraxno.sprites.SpriteAtlas;
public class SpriteObject
{
private int _height;
private int _width;
private double _x;
private double _y;
private SpriteAtlas[] _atlas;
private int _atlasIndex = PlayerConfig.DEFAULT_ANIMATION_INDEX;
protected Rectangle test = new Rectangle(0,0,0,0);
public SpriteObject(int h, int w, int x, int y, SpriteAtlas[] a)
{
setHeight(h);
setWidth(w);
setX(x);
setY(y);
setAtlas(a);
for(SpriteAtlas sA : _atlas)
{
MainHandler.registerUpdatable(sA);
}
}
public void paintMe(Graphics g)
{
g.drawImage(_atlas[_atlasIndex].currentSprite(), (int)getX(), (int)getY(), getWidth(), getHeight(), new MyImageObserver());
Rectangle r = getBounds();
g.setColor(Color.BLACK);
g.drawRect(r.x, r.y, r.width, r.height);
g.setColor(Color.RED);
g.drawRect(test.x, test.y, test.width, test.height);
}
/**
* @return the _height
*/
public int getHeight()
{
return _height;
}
/**
* @param _height the _height to set
*/
public void setHeight(int _height)
{
this._height = _height;
}
/**
* @return the _width
*/
public int getWidth()
{
return _width;
}
/**
* @param _width the _width to set
*/
public void setWidth(int _width)
{
this._width = _width;
}
/**
* @return the _x
*/
public double getX()
{
return _x;
}
/**
* @param d the _x to set
*/
public void setX(double d)
{
this._x = d;
}
/**
* @return the _y
*/
public double getY()
{
return _y;
}
/**
* @param _y the _y to set
*/
public void setY(double y)
{
this._y = y;
}
public Rectangle getBounds()
{
return new Rectangle((int)getX(), (int)getY(),
getWidth(), getHeight());
}
public int getAtlasIndex()
{
return _atlasIndex;
}
public void setAtlasIndex(int i)
{
_atlasIndex = i;
}
public SpriteAtlas[] getAtlas()
{
return _atlas;
}
public void setAtlas(SpriteAtlas[] _atlas)
{
this._atlas = _atlas;
}
}
<file_sep>/src/com/github/moraxno/config/PhysicsConfig.java
package com.github.moraxno.config;
import com.github.moraxno.math.Vector2D;
/**
* Important constants for all physical translations and movements.
*
* @author Moraxno
*/
public class PhysicsConfig {
@Deprecated
public static final int GrROUND_HEIGHT = 500;
public static final float GRAVITATIONAL_ACCELERATION = 0.06F;
public static final Vector2D GRAVITY_VECTOR2D = new Vector2D(0, GRAVITATIONAL_ACCELERATION);
}
<file_sep>/src/com/github/moraxno/registry/Listener.java
package com.github.moraxno.registry;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Listener implements KeyListener
{
public enum Keymode {UP, DOWN};
@Override
public void keyPressed(KeyEvent e)
{
setKey(e, Keymode.DOWN);
}
@Override
public void keyReleased(KeyEvent e)
{
setKey(e, Keymode.UP);
}
@Override
public void keyTyped(KeyEvent e)
{
// TODO Auto-generated method stub
}
private void setKey(KeyEvent e, Keymode k)
{
boolean down = (k==Keymode.DOWN);
switch (e.getKeyCode())
{
case 87:
InputHandler.setW(down);
break;
case 65:
InputHandler.setA(down);
break;
case 83:
InputHandler.setS(down);
break;
case 68:
InputHandler.setD(down);
break;
default:
break;
}
}
}
<file_sep>/src/com/github/moraxno/math/MMath.java
package com.github.moraxno.math;
public class MMath {
public static double square(double a)
{
return a * a;
}
public static int square(int a)
{
return a * a;
}
}
<file_sep>/src/com/github/moraxno/Main.java
package com.github.moraxno;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
import com.github.moraxno.Objects.ControlableObject;
import com.github.moraxno.config.GameConfig;
import com.github.moraxno.config.PhysicsConfig;
import com.github.moraxno.frame.MPane;
import com.github.moraxno.math.Vector2D;
import com.github.moraxno.registry.HitBoxHandler;
import com.github.moraxno.registry.Listener;
import com.github.moraxno.registry.MainHandler;
import com.github.moraxno.registry.Log.LogHandler;
import com.github.moraxno.sprites.SpriteAtlas;
public class Main
{
public static void main(String[] args) throws InterruptedException
{
JFrame frm = new JFrame("hi");
frm.setBounds(100,100,500,800);
MPane pane = new MPane();
frm.setContentPane(pane);
frm.addKeyListener(new Listener());
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
MainHandler.setMainFrame(pane);
Initialize.createPlayer();
HitBoxHandler.registerHitBox(new Rectangle(300, 300, 200, 200));
frm.setVisible(true);
MainHandler.startGame();
}
}
<file_sep>/src/com/github/moraxno/registry/MainHandler.java
package com.github.moraxno.registry;
import java.util.ArrayList;
import com.github.moraxno.Objects.ControlableObject;
import com.github.moraxno.Objects.MovableObject;
import com.github.moraxno.config.GameConfig;
import com.github.moraxno.frame.MPane;
import com.github.moraxno.math.Clamp;
import com.github.moraxno.registry.Time.Updatable;
/**
* Central Handler and Registry for <b><i>ALL</i></b> actions and events happening in the game.
* @author Robert
*
*/
public class MainHandler
{
private static MPane _mainFrame = null;
private static ArrayList<Updatable> _toUpdate = new ArrayList<Updatable>();
public static void setMainFrame(MPane f)
{
_mainFrame = f;
}
public static MPane getMainFrame()
{
return _mainFrame;
}
public static void registerPlayer(ControlableObject p)
{
ControlHandler.registerPlayer(p);
registerMovable(p);
}
public static void registerMovable(MovableObject m)
{
PhysicsHandler.registerMovObject(m);
DrawHandler.registerMovObject(m);
}
public static void registerUpdatable(Updatable u)
{
_toUpdate.add(u);
}
public static void startGame() throws InterruptedException
{
while(true)
{
PhysicsHandler.updateAll();
ControlHandler.updateAll();
for(Updatable u : _toUpdate)
{
u.decTick(GameConfig.MILLISECONDS_PER_TICK);
if(u.isReady())
{
u.update();
u.resetTimer();
}
}
Thread.sleep(GameConfig.MILLISECONDS_PER_TICK);
_mainFrame.repaint();
_mainFrame.revalidate();
}
}
}
<file_sep>/src/com/github/moraxno/Objects/ControlableObject.java
package com.github.moraxno.Objects;
import com.github.moraxno.config.PlayerConfig;
import com.github.moraxno.math.Vector2D;
import com.github.moraxno.registry.InputHandler;
import com.github.moraxno.registry.Time.Updatable;
import com.github.moraxno.sprites.SpriteAtlas;
public class ControlableObject extends MovableObject
{
private int WALKING_SPEED = 1;
private int SPRINTING_SPEED = 2;
private int JUMP_FORCE = 5;
public ControlableObject(int h, int w, int x, int y, SpriteAtlas[] a)
{
super(h,w,x,y,a);
}
}
<file_sep>/src/com/github/moraxno/Objects/IGravityPullableObject.java
package com.github.moraxno.Objects;
public interface IGravityPullableObject
{
public void addGravity();
}
| d8b5d8a44a61c7863f87416a5b9ab2f262f2cd1e | [
"Java"
] | 10 | Java | Moraxno/testGame | 7687d4b73437c42ab1106adcfd6ba64c2dceb072 | 44516dc50699f66d78ee19ce5e5983e3deeff3e1 |
refs/heads/master | <file_sep>namespace CoreEscuela.Entidades
{
public class AlumnoPromedio
{
public float alumnopromedio { get; set; }
public string alumnoId { get; set; }
public string alumnoNombre { get; set; }
public override string ToString()
{
return $"{alumnoNombre},{alumnopromedio}";
}
}
}<file_sep>using CoreEscuela.Entidades;
using platzi_curso_csharp.Entidades;
using System;
using System.Collections.Generic;
using System.Linq;
namespace CoreEscuela.App
{
public sealed class EscuelaEngine
{
public Escuela Escuela { get; set; }
public EscuelaEngine()
{
}
public void Inicializar()
{
Escuela = new Escuela("Platzi Academay", 2012, TiposEscuela.Primaria,
ciudad: "Bogotá", pais: "Colombia"
);
CargarCursos();
CargarAsignaturas();
CargarEvaluaciones();
}
#region Cargar
private void CargarEvaluaciones()
{
var rnd = new Random();
foreach (var curso in Escuela.Cursos)
{
foreach (var asignatura in curso.Asignaturas)
{
foreach (var alumno in curso.Alumnos)
{
for (int i = 0; i < 5; i++)
{
var ev = new Evaluación
{
Asignatura = asignatura,
Nombre = $"{asignatura.Nombre} Ev#{i + 1}",
Nota = (float)Math.Round((5 * rnd.NextDouble()), 2),
Alumno = alumno
};
alumno.Evaluaciones.Add(ev);
}
}
}
}
}
private void CargarAsignaturas()
{
foreach (var curso in Escuela.Cursos)
{
var listaAsignaturas = new List<Asignatura>(){
new Asignatura{Nombre="Matemáticas"} ,
new Asignatura{Nombre="Educación Física"},
new Asignatura{Nombre="Castellano"},
new Asignatura{Nombre="Ciencias Naturales"}
};
curso.Asignaturas = listaAsignaturas;
}
}
private void CargarCursos()
{
Escuela.Cursos = new List<Curso>(){
new Curso(){ Nombre = "101", Jornada = TiposJornada.Mañana },
new Curso() {Nombre = "201", Jornada = TiposJornada.Mañana},
new Curso{Nombre = "301", Jornada = TiposJornada.Mañana},
new Curso(){ Nombre = "401", Jornada = TiposJornada.Tarde },
new Curso() {Nombre = "501", Jornada = TiposJornada.Tarde},
};
Random rnd = new Random();
foreach (var c in Escuela.Cursos)
{
int cantRandom = rnd.Next(5, 20);
c.Alumnos = GenerarAlumnosAlAzar(cantRandom);
}
}
#endregion Cargar
public IReadOnlyList<ObjetoEscuelaBase> GetObjetosEscuela(
out int Conteo_Evaluaciones,
out int Conteo_Alumnos,
out int Conteo_Asignaturas,
out int Conteo_Cursos,
bool Trae_Evaluciacones = true,
bool Trae_Alumnos = true,
bool Trae_Asignaturas = true,
bool Trae_Curos = true)
{
var listaObj = new List<ObjetoEscuelaBase>();
Conteo_Evaluaciones = 0;
Conteo_Asignaturas = 0;
Conteo_Alumnos = 0;
listaObj.Add(Escuela);
if (Trae_Curos)
listaObj.AddRange(Escuela.Cursos);
Conteo_Cursos = Escuela.Cursos.Count;
foreach (var curso in Escuela.Cursos)
{
Conteo_Asignaturas += curso.Asignaturas.Count;
Conteo_Alumnos += curso.Alumnos.Count;
if (Trae_Asignaturas)
listaObj.AddRange(curso.Asignaturas);
if (Trae_Alumnos)
listaObj.AddRange(curso.Alumnos);
if (Trae_Evaluciacones == true)
{
foreach (var alumno in curso.Alumnos)
{
listaObj.AddRange(alumno.Evaluaciones);
Conteo_Evaluaciones++;
}
}
}
return listaObj.AsReadOnly();
}
//Sobrecarga de metodos
public IReadOnlyList<ObjetoEscuelaBase> GetObjetosEscuela(bool Trae_Evaluciacones = true,
bool Trae_Alumnos = true,
bool Trae_Asignaturas = true,
bool Trae_Curos = true)
{
return GetObjetosEscuela(out int dummy, out dummy, out dummy, out dummy);
}
private List<Alumno> GenerarAlumnosAlAzar(int cantidad)
{
string[] nombre1 = { "Alba", "Felipa", "Eusebio", "Farid", "Donald", "Alvaro", "Nicolás" };
string[] apellido1 = { "Ruiz", "Sarmiento", "Uribe", "Maduro", "Trump", "Toledo", "Herrera" };
string[] nombre2 = { "Freddy", "Anabel", "Rick", "Murty", "Silvana", "Diomedes", "Nicomedes", "Teodoro" };
var listaAlumnos = from n1 in nombre1
from n2 in nombre2
from a1 in apellido1
select new Alumno { Nombre = $"{n1} {n2} {a1}" };
return listaAlumnos.OrderBy((al) => al.UniqueId).Take(cantidad).ToList();
}
public Dictionary<Llaves_Diccionario, IEnumerable<ObjetoEscuelaBase>> GetDiccionarioObjetos()
{
var Diccionario = new Dictionary<Llaves_Diccionario, IEnumerable<ObjetoEscuelaBase>>();
Diccionario.Add(Llaves_Diccionario.Escuela, new[] { Escuela });
Diccionario.Add(Llaves_Diccionario.Cursos, Escuela.Cursos);
var Alumnos_Totales = new List<Alumno>();
var Asignaturas_Totales = new List<Asignatura>();
var Evaluaciones_Totales = new List<Evaluación>();
foreach (var Listai in Escuela.Cursos)
{
foreach (var Alumnoi in Listai.Alumnos)
{
Alumnos_Totales.Add(Alumnoi);
Evaluaciones_Totales.AddRange(Alumnoi.Evaluaciones);
}
Asignaturas_Totales.AddRange(Listai.Asignaturas);
}
Diccionario.Add(Llaves_Diccionario.Alumnos, Alumnos_Totales);
Diccionario.Add(Llaves_Diccionario.Asignaturas, Asignaturas_Totales);
Diccionario.Add(Llaves_Diccionario.Evaluaciones, Evaluaciones_Totales);
return Diccionario;
}
public void ImprimirDiccionario(Dictionary<Llaves_Diccionario, IEnumerable<ObjetoEscuelaBase>> Dic, bool imprimirEval = false)
{
foreach (var llave in Dic)
{
Console.WriteLine(llave.Key.ToString());
foreach (var val in llave.Value)
{
switch (llave.Key)
{
case Llaves_Diccionario.Evaluaciones:
if (imprimirEval)
{
Console.WriteLine(val);
}
break;
case Llaves_Diccionario.Escuela:
Console.WriteLine("Escuela: " + val);
break;
case Llaves_Diccionario.Alumnos:
Console.WriteLine("Alumno: " + val.Nombre);
break;
case Llaves_Diccionario.Cursos:
var CursoTemp = val as Curso;
if (CursoTemp != null)
Console.WriteLine("Curos: " + CursoTemp.Nombre + " Cantidad Alumnos: " + CursoTemp.Alumnos.Count);
break;
default:
Console.WriteLine(val);
break;
}
}
}
}
}
}<file_sep>using CoreEscuela.App;
using CoreEscuela.Entidades;
using CoreEscuela.Util;
using System;
using static System.Console;
namespace CoreEscuela
{
internal class Program
{
private static void Main(string[] args)
{
AppDomain.CurrentDomain.ProcessExit += AccionDelEvento;
//AppDomain.CurrentDomain.ProcessExit += (o, s) => Printer.Beep(1000, 1000, 1);
//AppDomain.CurrentDomain.ProcessExit -= AccionDelEvento;
var engine = new EscuelaEngine();
engine.Inicializar();
Printer.WriteTitle("BIENVENIDOS A LA ESCUELA");
var reporteador = new Reporteador(engine.GetDiccionarioObjetos());
var EvalList = reporteador.GetListaEvaluaciones();
var AsignaturaList = reporteador.GetListAsignaturas();
var DicEval = reporteador.GetDicEvaluacionesPorAsignatura();
var ListaPromXAsignatura = reporteador.GetPromedioAlumnosPorAsignatura();
Printer.WriteTitle("Captura evaluación por consola");
string Nombre, notaString;
var newEval = new Evaluación();
WriteLine("Ingrese el nombre de la evaluación:");
Printer.PresioneENTER();
Nombre = Console.ReadLine();
if (string.IsNullOrWhiteSpace(Nombre))
{
Printer.WriteTitle("El valor del nombre no puede ser vacio");
WriteLine("Saliendo del programa");
}
else
{
newEval.Nombre = Nombre.ToLower();
WriteLine("El nombre de la evaluación ha sido ingresado correctamente.");
}
WriteLine("Ingrese la nota de la evaluación:");
Printer.PresioneENTER();
notaString = Console.ReadLine();
if (string.IsNullOrWhiteSpace(notaString))
{
Printer.WriteTitle("El valor de la nota no puede ser vacio");
WriteLine("Saliendo del programa");
}
else
{
try
{
newEval.Nota = float.Parse(notaString);
if (newEval.Nota < 0 | newEval.Nota > 5)
{
throw new ArgumentOutOfRangeException("La nota debe de estar entre 0 y 5");
}
WriteLine("la nota de la evaluación ha sido ingresado correctamente.");
return;
}
catch (ArgumentOutOfRangeException arge)
{
Printer.WriteTitle(arge.Message);
WriteLine("Saliendo del programa");
}
catch (Exception)
{
Printer.WriteTitle("El valor de la nota no es un número valido");
WriteLine("Saliendo del programa");
}
finally
{
Printer.WriteTitle("FINALLY");
Printer.Beep(2500, 500, 3);
}
}
// foreach (var item in ListaPromXAsignatura)
// {
// foreach (var alumn in item.Value)
// {
// var temp = alumn as Alumno;
// }
// }
//Printer.Beep(10000, cantidad: 10);
// ImpimirCursosEscuela(engine.Escuela);
// var ListaObjetos = engine.GetObjetosEscuela(out int Conteo_Evaluaciones,
// out int Conteo_Alumnos,
// out int Conteo_Asignaturas,
// out int Conteo_Cursos);
// var DicTemp = engine.GetDiccionarioObjetos();
// engine.ImprimirDiccionario(DicTemp, true);
// Dictionary<int, string> Diccionario = new Dictionary<int, string>();
// Diccionario.Add(10, "Juan");
// Diccionario.Add(23, "Lorem impsum");
// foreach (var llaveValor in Diccionario)
// {
// WriteLine(llaveValor.Value);
// WriteLine(llaveValor.Key);
// }
// Printer.WriteTitle("Acceso a diccionario");
// WriteLine(Diccionario[10]);
// Printer.DrawLine(20);
// Printer.DrawLine(20);
// Printer.DrawLine(20);
// Printer.WriteTitle("Pruebas de poliformismo");
// var Alumno_Test = new Alumno { Nombre = "<NAME>" };
// ObjetoEscuelaBase objeto = Alumno_Test;
// Printer.WriteTitle("Alumno_or");
// WriteLine($"Alumno: {Alumno_Test.Nombre}");
// WriteLine($"Alumno: {Alumno_Test.UniqueId}");
// WriteLine($"Alumno: {Alumno_Test.GetType()}");
// Printer.WriteTitle("Alumno_pol");
// WriteLine($"Alumno: {objeto.Nombre}");
// WriteLine($"Alumno: {objeto.UniqueId}");
// WriteLine($"Alumno: {objeto.GetType()}");
// var listaObjetos = engine.GetObjetosEscuela();
}
private static void AccionDelEvento(object sender, EventArgs e)
{
Printer.WriteTitle("Saliendo");
//Printer.Beep(3000, 1000, 3);
Printer.WriteTitle("SALIO");
}
private static void ImpimirCursosEscuela(Escuela escuela)
{
Printer.WriteTitle("Cursos de la Escuela");
if (escuela?.Cursos != null)
{
foreach (var curso in escuela.Cursos)
{
WriteLine($"Nombre {curso.Nombre }, Id {curso.UniqueId}");
}
}
}
}
}<file_sep>using System.Collections.Generic;
using CoreEscuela.Entidades;
using platzi_curso_csharp.Entidades;
using System;
using System.Linq;
namespace CoreEscuela.App
{
//Clase para extraer informacion de nuestra base de datos
public class Reporteador
{
Dictionary<Llaves_Diccionario, IEnumerable<ObjetoEscuelaBase>> _diccionario;
public Reporteador(Dictionary<Llaves_Diccionario, IEnumerable<ObjetoEscuelaBase>> DicObjetoEscuela)
{
if (DicObjetoEscuela == null)
{
throw new ArgumentNullException(nameof(DicObjetoEscuela));
}
else
{
_diccionario = DicObjetoEscuela;
}
}
public IEnumerable<Evaluación> GetListaEvaluaciones()
{
if (_diccionario.TryGetValue(Llaves_Diccionario.Evaluaciones, out IEnumerable<ObjetoEscuelaBase> listatemp))
{
return listatemp.Cast<Evaluación>();
}
else
{
return new List<Evaluación>();
}
}
public IEnumerable<string> GetListAsignaturas()
{
return GetListAsignaturas(0, out var dummy);
}
public IEnumerable<string> GetListAsignaturas(float NotaMin, out IEnumerable<Evaluación> ListaEvaluaciones)
{
ListaEvaluaciones = GetListaEvaluaciones();
return (from Evaluación ev in ListaEvaluaciones
where ev.Nota >= NotaMin
select ev.Asignatura.Nombre).Distinct();
}
public IEnumerable<Escuela> GetListaEscuela()
{
if (_diccionario.TryGetValue(Llaves_Diccionario.Escuela, out IEnumerable<ObjetoEscuelaBase> listatemp))
{
return listatemp.Cast<Escuela>();
}
else
{
return new List<Escuela>();
}
}
public Dictionary<string, IEnumerable<Evaluación>> GetDicEvaluacionesPorAsignatura()
{
Dictionary<string, IEnumerable<Evaluación>> DicRta = new Dictionary<string, IEnumerable<Evaluación>>();
var ListaAsignaturas = GetListAsignaturas(0f, out var ListaEvaluaciones);
foreach (var asig in ListaAsignaturas)
{
var evalsAsig = from eval in ListaEvaluaciones
where eval.Asignatura.Nombre == asig
select eval;
DicRta.Add(asig, evalsAsig);
}
return DicRta;
}
public Dictionary<string, IEnumerable<AlumnoPromedio>> GetPromedioAlumnosPorAsignatura()
{
var Rta = new Dictionary<string, IEnumerable<AlumnoPromedio>>();
var DicEvaluacionesAsignaturas = GetDicEvaluacionesPorAsignatura();
foreach (var AsigConEvaluaciones in DicEvaluacionesAsignaturas)
{
var PromAlumn = from eval in AsigConEvaluaciones.Value
group eval by new
{
eval.Alumno.UniqueId,
eval.Alumno.Nombre
}
into grupoEvalAlumno
select new AlumnoPromedio
{
alumnoId = grupoEvalAlumno.Key.UniqueId,
alumnoNombre = grupoEvalAlumno.Key.Nombre,
alumnopromedio = grupoEvalAlumno.Average(x => x.Nota)
};
Rta.Add(AsigConEvaluaciones.Key, PromAlumn);
}
return Rta;
}
}
}<file_sep>using System;
namespace CoreEscuela.Entidades
{
public class Asignatura : ObjetoEscuelaBase
{
public override bool Equals(object obj)
{
if (obj is Asignatura)
{
Asignatura temp = (Asignatura)obj;
if (Nombre == temp.Nombre) return true;
}
return false;
}
}
} | c0ed9523ba822ab8e35f6c92f85b3737de75fde6 | [
"C#"
] | 5 | C# | santiagovasquez1/platzi-curso-csharp | e7ead83678a8ce0d878fe9b010b93ade04c8e6b9 | 2c56aeefb660b553c951bffa5b2ab74b8d1fd9cc |
refs/heads/master | <file_sep><?php
declare(strict_types=1);
namespace muqsit\vanillagenerator\generator\overworld\decorator\types;
use pocketmine\block\DoublePlant;
final class DoublePlantDecoration{
/** @var DoublePlant */
private $block;
/** @var int */
private $weight;
public function __construct(DoublePlant $block, int $weight){
$this->block = $block;
$this->weight = $weight;
}
public function getBlock() : DoublePlant{
return $this->block;
}
public function getWeight() : int{
return $this->weight;
}
}<file_sep><?php
declare(strict_types=1);
namespace muqsit\vanillagenerator\generator\overworld\decorator;
use muqsit\vanillagenerator\generator\Decorator;
use pocketmine\block\Block;
use pocketmine\block\BlockLegacyIds;
use pocketmine\block\BlockLegacyMetadata;
use pocketmine\utils\Random;
use pocketmine\world\ChunkManager;
use pocketmine\world\format\Chunk;
class MushroomDecorator extends Decorator{
/** @var Block */
private $type;
/** @var bool */
private $fixedHeightRange = false;
/** @var float */
private $density = 0.0;
/**
* Creates a mushroom decorator for the overworld.
*
* @param Block $type {@link Material#BROWN_MUSHROOM} or {@link Material#RED_MUSHROOM}
*/
public function __construct(Block $type){
$this->type = $type;
}
public function setUseFixedHeightRange() : MushroomDecorator{
$this->fixedHeightRange = true;
return $this;
}
public function setDensity(float $density) : MushroomDecorator{
$this->density = $density;
return $this;
}
public function decorate(ChunkManager $world, Random $random, Chunk $chunk) : void{
if($random->nextFloat() < $this->density){
$sourceX = ($chunk->getX() << 4) + $random->nextBoundedInt(16);
$sourceZ = ($chunk->getZ() << 4) + $random->nextBoundedInt(16);
$sourceY = $chunk->getHighestBlockAt($sourceX & 0x0f, $sourceZ & 0x0f);
$sourceY = $this->fixedHeightRange ? $sourceY : $random->nextBoundedInt($sourceY << 1);
$height = $world->getWorldHeight();
for($i = 0; $i < 64; ++$i){
$x = $sourceX + $random->nextBoundedInt(8) - $random->nextBoundedInt(8);
$z = $sourceZ + $random->nextBoundedInt(8) - $random->nextBoundedInt(8);
$y = $sourceY + $random->nextBoundedInt(4) - $random->nextBoundedInt(4);
$block = $world->getBlockAt($x, $y, $z);
$blockBelow = $world->getBlockAt($x, $y - 1, $z);
if($y < $height && $block->getId() === BlockLegacyIds::AIR){
switch($blockBelow->getId()){
case BlockLegacyIds::MYCELIUM:
case BlockLegacyIds::PODZOL:
$canPlaceShroom = true;
break;
case BlockLegacyIds::GRASS:
$canPlaceShroom = ($block->getLightLevel() < 13);
break;
case BlockLegacyIds::DIRT:
if($blockBelow->getMeta() === BlockLegacyMetadata::DIRT_NORMAL){
$canPlaceShroom = $block->getLightLevel() < 13;
}else{
$canPlaceShroom = false;
}
break;
default:
$canPlaceShroom = false;
}
if($canPlaceShroom){
$world->setBlockAt($x, $y, $z, $this->type);
}
}
}
}
}
}<file_sep><?php
declare(strict_types=1);
namespace muqsit\vanillagenerator\generator\overworld\decorator;
use muqsit\vanillagenerator\generator\Decorator;
use pocketmine\block\BlockLegacyIds;
use pocketmine\block\VanillaBlocks;
use pocketmine\utils\Random;
use pocketmine\world\ChunkManager;
use pocketmine\world\format\Chunk;
use pocketmine\world\World;
class WaterLilyDecorator extends Decorator{
public function decorate(ChunkManager $world, Random $random, Chunk $chunk) : void{
$sourceX = ($chunk->getX() << 4) + $random->nextBoundedInt(16);
$sourceZ = ($chunk->getZ() << 4) + $random->nextBoundedInt(16);
$sourceY = $random->nextBoundedInt($chunk->getHighestBlockAt($sourceX & 0x0f, $sourceZ & 0x0f) << 1);
while($world->getBlockAt($sourceX, $sourceY - 1, $sourceZ)->getId() === BlockLegacyIds::AIR && $sourceY > 0){
--$sourceY;
}
for($j = 0; $j < 10; ++$j){
$x = $sourceX + $random->nextBoundedInt(8) - $random->nextBoundedInt(8);
$z = $sourceZ + $random->nextBoundedInt(8) - $random->nextBoundedInt(8);
$y = $sourceY + $random->nextBoundedInt(4) - $random->nextBoundedInt(4);
if(
$y >= 0 && $y < World::Y_MAX && $world->getBlockAt($x, $y, $z)->getId() === BlockLegacyIds::AIR &&
$world->getBlockAt($x, $y - 1, $z)->getId() === BlockLegacyIds::STILL_WATER
){
$world->setBlockAt($x, $y, $z, VanillaBlocks::LILY_PAD());
}
}
}
}<file_sep><?php
declare(strict_types=1);
namespace muqsit\vanillagenerator\generator\object;
use pocketmine\block\BlockLegacyIds;
use pocketmine\block\VanillaBlocks;
use pocketmine\math\Facing;
use pocketmine\math\Vector3;
use pocketmine\utils\Random;
use pocketmine\world\ChunkManager;
class Cactus extends TerrainObject{
private const FACES = [Facing::NORTH, Facing::EAST, Facing::SOUTH, Facing::WEST];
/**
* Generates or extends a cactus, if there is space.
*
* @param ChunkManager $world
* @param Random $random
* @param int $x
* @param int $y
* @param int $z
* @return bool
*/
public function generate(ChunkManager $world, Random $random, int $x, int $y, int $z) : bool{
if($world->getBlockAt($x, $y, $z)->getId() === BlockLegacyIds::AIR){
$height = $random->nextBoundedInt($random->nextBoundedInt(3) + 1) + 1;
for($n = $y; $n < $y + $height; ++$n){
$vec = new Vector3($x, $n, $z);
$typeBelow = $world->getBlockAt($x, $n - 1, $z)->getId();
if(($typeBelow === BlockLegacyIds::SAND || $typeBelow === BlockLegacyIds::CACTUS) && $world->getBlockAt($x, $n + 1, $z)->getId() === BlockLegacyIds::AIR){
foreach(self::FACES as $face){
$face = $vec->getSide($face);
if($world->getBlockAt($face->x, $face->y, $face->z)->isSolid()){
return $n > $y;
}
}
$world->setBlockAt($x, $n, $z, VanillaBlocks::CACTUS());
}
}
}
return true;
}
}<file_sep><?php
declare(strict_types=1);
namespace muqsit\vanillagenerator\generator\overworld\decorator;
use muqsit\vanillagenerator\generator\Decorator;
use muqsit\vanillagenerator\generator\object\TallGrass;
use pocketmine\block\BlockFactory;
use pocketmine\block\BlockLegacyIds;
use pocketmine\block\BlockLegacyMetadata;
use pocketmine\utils\Random;
use pocketmine\world\ChunkManager;
use pocketmine\world\format\Chunk;
class TallGrassDecorator extends Decorator{
/** @var float */
private $fernDensity = 0.0;
final public function setFernDensity(float $fernDensity) : void{
$this->fernDensity = $fernDensity;
}
public function decorate(ChunkManager $world, Random $random, Chunk $chunk) : void{
$x = $random->nextBoundedInt(16);
$z = $random->nextBoundedInt(16);
$topBlock = $chunk->getHighestBlockAt($x, $z);
if($topBlock <= 0){
// Nothing to do if this column is empty
return;
}
$sourceY = $random->nextBoundedInt(abs($topBlock << 1));
// the grass species can change on each decoration pass
$species = BlockLegacyMetadata::TALLGRASS_NORMAL;
if($this->fernDensity > 0 && $random->nextFloat() < $this->fernDensity){
$species = BlockLegacyMetadata::TALLGRASS_FERN;
}
(new TallGrass(BlockFactory::getInstance()->get(BlockLegacyIds::TALL_GRASS, $species)))->generate($world, $random, ($chunk->getX() << 4) + $x, $sourceY, ($chunk->getZ() << 4) + $z);
}
}<file_sep><?php
declare(strict_types=1);
namespace muqsit\vanillagenerator\generator\overworld\decorator;
use muqsit\vanillagenerator\generator\Decorator;
use pocketmine\block\BlockLegacyIds;
use pocketmine\block\VanillaBlocks;
use pocketmine\utils\Random;
use pocketmine\world\ChunkManager;
use pocketmine\world\format\Chunk;
class DeadBushDecorator extends Decorator{
private const SOIL_TYPES = [BlockLegacyIds::SAND, BlockLegacyIds::DIRT, BlockLegacyIds::HARDENED_CLAY, BlockLegacyIds::STAINED_CLAY];
public function decorate(ChunkManager $world, Random $random, Chunk $chunk) : void{
$sourceX = ($chunk->getX() << 4) + $random->nextBoundedInt(16);
$sourceZ = ($chunk->getZ() << 4) + $random->nextBoundedInt(16);
$sourceY = $random->nextBoundedInt($chunk->getHighestBlockAt($sourceX & 0x0f, $sourceZ & 0x0f) << 1);
while($sourceY > 0
&& ($world->getBlockAt($sourceX, $sourceY, $sourceZ)->getId() === BlockLegacyIds::AIR
|| $world->getBlockAt($sourceX, $sourceY, $sourceZ)->getId() === BlockLegacyIds::LEAVES)){
--$sourceY;
}
for($i = 0; $i < 4; ++$i){
$x = $sourceX + $random->nextBoundedInt(8) - $random->nextBoundedInt(8);
$z = $sourceZ + $random->nextBoundedInt(8) - $random->nextBoundedInt(8);
$y = $sourceY + $random->nextBoundedInt(4) - $random->nextBoundedInt(4);
if($world->getBlockAt($x, $y, $z)->getId() === BlockLegacyIds::AIR){
$blockBelow = $world->getBlockAt($x, $y - 1, $z)->getId();
foreach(self::SOIL_TYPES as $soil){
if($soil === $blockBelow){
$world->setBlockAt($x, $y, $z, VanillaBlocks::DEAD_BUSH());
break;
}
}
}
}
}
}<file_sep><?php
declare(strict_types=1);
namespace muqsit\vanillagenerator\generator\overworld\populator\biome;
use muqsit\vanillagenerator\generator\overworld\biome\BiomeIds;
use muqsit\vanillagenerator\generator\overworld\decorator\IceDecorator;
use pocketmine\utils\Random;
use pocketmine\world\ChunkManager;
use pocketmine\world\format\Chunk;
class IcePlainsSpikesPopulator extends IcePlainsPopulator{
/** @var IceDecorator */
protected $iceDecorator;
public function __construct(){
parent::__construct();
$this->tallGrassDecorator->setAmount(0);
$this->iceDecorator = new IceDecorator();
}
protected function populateOnGround(ChunkManager $world, Random $random, Chunk $chunk) : void{
$this->iceDecorator->populate($world, $random, $chunk);
parent::populateOnGround($world, $random, $chunk);
}
public function getBiomes() : ?array{
return [BiomeIds::MUTATED_ICE_FLATS];
}
}<file_sep><?php
declare(strict_types=1);
namespace muqsit\vanillagenerator\generator\overworld\populator\biome;
use muqsit\vanillagenerator\generator\object\tree\BigOakTree;
use muqsit\vanillagenerator\generator\object\tree\CocoaTree;
use muqsit\vanillagenerator\generator\object\tree\JungleBush;
use muqsit\vanillagenerator\generator\object\tree\MegaJungleTree;
use muqsit\vanillagenerator\generator\overworld\biome\BiomeIds;
use muqsit\vanillagenerator\generator\overworld\decorator\MelonDecorator;
use muqsit\vanillagenerator\generator\overworld\decorator\types\TreeDecoration;
use pocketmine\utils\Random;
use pocketmine\world\BlockTransaction;
use pocketmine\world\ChunkManager;
use pocketmine\world\format\Chunk;
class JunglePopulator extends BiomePopulator{
/** @var TreeDecoration[] */
protected static $TREES;
protected static function initTrees() : void{
self::$TREES = [
new TreeDecoration(BigOakTree::class, 10),
new TreeDecoration(JungleBush::class, 50),
new TreeDecoration(MegaJungleTree::class, 15),
new TreeDecoration(CocoaTree::class, 30)
];
}
/** @var MelonDecorator */
protected $melonDecorator;
public function __construct(){
$this->melonDecorator = new MelonDecorator();
parent::__construct();
}
protected function initPopulators() : void{
$this->treeDecorator->setAmount(65);
$this->treeDecorator->setTrees(...self::$TREES);
$this->flowerDecorator->setAmount(4);
$this->flowerDecorator->setFlowers(...self::$FLOWERS);
$this->tallGrassDecorator->setAmount(25);
$this->tallGrassDecorator->setFernDensity(0.25);
}
public function getBiomes() : ?array{
return [BiomeIds::JUNGLE, BiomeIds::JUNGLE_HILLS, BiomeIds::MUTATED_JUNGLE];
}
protected function populateOnGround(ChunkManager $world, Random $random, Chunk $chunk) : void{
$sourceX = $chunk->getX() << 4;
$sourceZ = $chunk->getZ() << 4;
for($i = 0; $i < 7; ++$i){
$x = $random->nextBoundedInt(16);
$z = $random->nextBoundedInt(16);
$y = $chunk->getHighestBlockAt($x, $z);
$delegate = new BlockTransaction($world);
$bush = new JungleBush($random, $delegate);
if($bush->generate($world, $random, $sourceX + $x, $y, $sourceZ + $z)){
$delegate->apply();
}
}
parent::populateOnGround($world, $random, $chunk);
$this->melonDecorator->populate($world, $random, $chunk);
}
}
JunglePopulator::init();<file_sep><?php
declare(strict_types=1);
namespace muqsit\vanillagenerator\generator\overworld\populator\biome;
use muqsit\vanillagenerator\generator\object\tree\RedwoodTree;
use muqsit\vanillagenerator\generator\object\tree\TallRedwoodTree;
use muqsit\vanillagenerator\generator\overworld\biome\BiomeIds;
use muqsit\vanillagenerator\generator\overworld\decorator\MushroomDecorator;
use muqsit\vanillagenerator\generator\overworld\decorator\types\DoublePlantDecoration;
use muqsit\vanillagenerator\generator\overworld\decorator\types\TreeDecoration;
use pocketmine\block\VanillaBlocks;
use pocketmine\utils\Random;
use pocketmine\world\ChunkManager;
use pocketmine\world\format\Chunk;
class TaigaPopulator extends BiomePopulator{
/** @var DoublePlantDecoration[] */
protected static $DOUBLE_PLANTS;
/** @var TreeDecoration[] */
protected static $TREES;
public static function init() : void{
parent::init();
self::$DOUBLE_PLANTS = [
new DoublePlantDecoration(VanillaBlocks::LARGE_FERN(), 1)
];
}
protected static function initTrees() : void{
self::$TREES = [
new TreeDecoration(RedwoodTree::class, 2),
new TreeDecoration(TallRedwoodTree::class, 1)
];
}
/** @var MushroomDecorator */
protected $taigaBrownMushroomDecorator;
/** @var MushroomDecorator */
protected $taigaRedMushroomDecorator;
public function __construct(){
$this->taigaBrownMushroomDecorator = new MushroomDecorator(VanillaBlocks::BROWN_MUSHROOM());
$this->taigaRedMushroomDecorator = new MushroomDecorator(VanillaBlocks::RED_MUSHROOM());
parent::__construct();
}
protected function initPopulators() : void{
$this->doublePlantDecorator->setAmount(7);
$this->doublePlantDecorator->setDoublePlants(...self::$DOUBLE_PLANTS);
$this->treeDecorator->setAmount(10);
$this->treeDecorator->setTrees(...self::$TREES);
$this->tallGrassDecorator->setFernDensity(0.8);
$this->deadBushDecorator->setAmount(1);
$this->taigaBrownMushroomDecorator->setAmount(1);
$this->taigaBrownMushroomDecorator->setUseFixedHeightRange();
$this->taigaBrownMushroomDecorator->setDensity(0.25);
$this->taigaRedMushroomDecorator->setAmount(1);
$this->taigaRedMushroomDecorator->setDensity(0.125);
}
public function getBiomes() : ?array{
return [BiomeIds::TAIGA, BiomeIds::TAIGA_HILLS, BiomeIds::MUTATED_TAIGA, BiomeIds::TAIGA_COLD, BiomeIds::TAIGA_COLD_HILLS, BiomeIds::MUTATED_TAIGA_COLD];
}
protected function populateOnGround(ChunkManager $world, Random $random, Chunk $chunk) : void{
parent::populateOnGround($world, $random, $chunk);
$this->taigaBrownMushroomDecorator->populate($world, $random, $chunk);
$this->taigaRedMushroomDecorator->populate($world, $random, $chunk);
}
}
TaigaPopulator::init();<file_sep><?php
declare(strict_types=1);
namespace muqsit\vanillagenerator\generator\biomegrid\utils;
use Ds\Set;
final class BiomeEdgeEntry{
/** @var array<int, int> */
public $key;
/** @var Set<int>|null */
public $value;
/**
* @param array<int, int> $mapping
* @param int[] $value
*/
public function __construct(array $mapping, ?array $value = null){
$this->key = $mapping;
$this->value = $value !== null ? new Set($value) : null;
}
}<file_sep><?php
declare(strict_types=1);
namespace muqsit\vanillagenerator\generator\utils;
use muqsit\vanillagenerator\generator\noise\bukkit\OctaveGenerator;
class WorldOctaves{
/** @var OctaveGenerator */
public $height;
/** @var OctaveGenerator */
public $roughness;
/** @var OctaveGenerator */
public $roughness2;
/** @var OctaveGenerator */
public $detail;
/** @var OctaveGenerator */
public $surface;
public function __construct(
OctaveGenerator $height,
OctaveGenerator $roughness,
OctaveGenerator $roughness2,
OctaveGenerator $detail,
OctaveGenerator $surface
){
$this->height = $height;
$this->roughness = $roughness;
$this->roughness2 = $roughness2;
$this->detail = $detail;
$this->surface = $surface;
}
}<file_sep><?php
declare(strict_types=1);
namespace muqsit\vanillagenerator\generator\object;
use pocketmine\block\BlockLegacyIds;
use pocketmine\block\BlockLegacyMetadata;
use pocketmine\block\VanillaBlocks;
use pocketmine\math\Facing;
use pocketmine\math\Vector3;
use pocketmine\utils\Random;
use pocketmine\world\ChunkManager;
class SugarCane extends TerrainObject{
private const FACES = [Facing::NORTH, Facing::EAST, Facing::SOUTH, Facing::WEST];
public function generate(ChunkManager $world, Random $random, int $x, int $y, int $z) : bool{
if($world->getBlockAt($x, $y, $z)->getId() !== BlockLegacyIds::AIR){
return false;
}
$vec = new Vector3($x, $y - 1, $z);
$adjacentWater = false;
foreach(self::FACES as $face){
// needs a directly adjacent water block
$blockTypeV = $vec->getSide($face);
$blockType = $world->getBlockAt($blockTypeV->x, $blockTypeV->y, $blockTypeV->z)->getId();
if($blockType === BlockLegacyIds::STILL_WATER || $blockType === BlockLegacyIds::WATER){
$adjacentWater = true;
break;
}
}
if(!$adjacentWater){
return false;
}
for($n = 0; $n <= $random->nextBoundedInt($random->nextBoundedInt(3) + 1) + 1; ++$n){
$block = $world->getBlockAt($x, $y + $n - 1, $z);
$blockId = $block->getId();
if($blockId === BlocKLegacyIds::SUGARCANE_BLOCK
|| $blockId === BlocKLegacyIds::GRASS
|| $blockId === BlocKLegacyIds::SAND
|| ($blockId === BlocKLegacyIds::DIRT && $block->getMeta() === BlockLegacyMetadata::DIRT_NORMAL)
){
$caneBlock = $world->getBlockAt($x, $y + $n, $z);
if($caneBlock->getId() !== BlockLegacyIds::AIR && $world->getBlockAt($x, $y + $n + 1, $z)->getId() !== BlockLegacyIds::AIR){
return $n > 0;
}
$world->setBlockAt($x, $y + $n, $z, VanillaBlocks::SUGARCANE());
}
}
return true;
}
}<file_sep><?php
declare(strict_types=1);
namespace muqsit\vanillagenerator\generator\overworld\populator\biome;
use muqsit\vanillagenerator\generator\object\tree\SwampTree;
use muqsit\vanillagenerator\generator\overworld\biome\BiomeIds;
use muqsit\vanillagenerator\generator\overworld\decorator\MushroomDecorator;
use muqsit\vanillagenerator\generator\overworld\decorator\types\FlowerDecoration;
use muqsit\vanillagenerator\generator\overworld\decorator\types\TreeDecoration;
use muqsit\vanillagenerator\generator\overworld\decorator\WaterLilyDecorator;
use pocketmine\block\VanillaBlocks;
use pocketmine\utils\Random;
use pocketmine\world\ChunkManager;
use pocketmine\world\format\Chunk;
class SwamplandPopulator extends BiomePopulator{
/** @var TreeDecoration[] */
protected static $TREES;
/** @var FlowerDecoration[] */
protected static $FLOWERS;
protected static function initTrees() : void{
self::$TREES = [
new TreeDecoration(SwampTree::class, 1)
];
}
protected static function initFlowers() : void{
self::$FLOWERS = [
new FlowerDecoration(VanillaBlocks::BLUE_ORCHID(), 1)
];
}
/** @var MushroomDecorator */
private $swamplandBrownMushroomDecorator;
/** @var MushroomDecorator */
private $swamplandRedMushroomDecorator;
/** @var WaterLilyDecorator */
private $waterlilyDecorator;
public function __construct(){
$this->swamplandBrownMushroomDecorator = new MushroomDecorator(VanillaBlocks::BROWN_MUSHROOM());
$this->swamplandRedMushroomDecorator = new MushroomDecorator(VanillaBlocks::RED_MUSHROOM());
$this->waterlilyDecorator = new WaterLilyDecorator();
parent::__construct();
}
protected function initPopulators() : void{
$this->sandPatchDecorator->setAmount(0);
$this->gravelPatchDecorator->setAmount(0);
$this->treeDecorator->setAmount(2);
$this->treeDecorator->setTrees(...self::$TREES);
$this->flowerDecorator->setAmount(1);
$this->flowerDecorator->setFlowers(...self::$FLOWERS);
$this->tallGrassDecorator->setAmount(5);
$this->deadBushDecorator->setAmount(1);
$this->sugarCaneDecorator->setAmount(20);
$this->swamplandBrownMushroomDecorator->setAmount(8);
$this->swamplandRedMushroomDecorator->setAmount(8);
$this->waterlilyDecorator->setAmount(4);
}
public function getBiomes() : ?array{
return [BiomeIds::SWAMPLAND, BiomeIds::MUTATED_SWAMPLAND];
}
protected function populateOnGround(ChunkManager $world, Random $random, Chunk $chunk) : void{
parent::populateOnGround($world, $random, $chunk);
$this->swamplandBrownMushroomDecorator->populate($world, $random, $chunk);
$this->swamplandRedMushroomDecorator->populate($world, $random, $chunk);
$this->waterlilyDecorator->populate($world, $random, $chunk);
}
}
SwamplandPopulator::init();<file_sep><?php
declare(strict_types=1);
namespace muqsit\vanillagenerator\generator\object;
use Ds\Set;
use pocketmine\block\BlockLegacyIds;
use pocketmine\block\BlockLegacyMetadata;
use pocketmine\block\Flowable;
use pocketmine\block\VanillaBlocks;
use pocketmine\utils\Random;
use pocketmine\world\ChunkManager;
use pocketmine\world\World;
abstract class TerrainObject{
/** @var Set<int> */
private static $PLANT_TYPES;
public static function init() : void{
self::$PLANT_TYPES = new Set([
BlockLegacyIds::TALL_GRASS,
BlockLegacyIds::YELLOW_FLOWER,
BlockLegacyIds::RED_FLOWER,
BlockLegacyIds::DOUBLE_PLANT,
BlockLegacyIds::BROWN_MUSHROOM,
BlockLegacyIds::RED_MUSHROOM
]);
}
/**
* Removes weak blocks like grass, shrub, flower or mushroom directly above the given block, if present.
* Does not drop an item.
*
* @param ChunkManager $world
* @param int $x
* @param int $y
* @param int $z
* @return bool whether a block was removed; false if none was present
*/
public static function killWeakBlocksAbove(ChunkManager $world, int $x, int $y, int $z) : bool{
$cur_y = $y + 1;
$changed = false;
while($cur_y < World::Y_MAX){
$block = $world->getBlockAt($x, $cur_y, $z);
if(!($block instanceof Flowable)){
break;
}
$world->setBlockAt($x, $cur_y, $z, VanillaBlocks::AIR());
$changed = true;
++$cur_y;
}
return $changed;
}
/**
* Generates this feature.
*
* @param ChunkManager $world the world to generate in
* @param Random $random the PRNG that will choose the size and a few details of the shape
* @param int $sourceX the base X coordinate
* @param int $sourceY the base Y coordinate
* @param int $sourceZ the base Z coordinate
* @return bool if successfully generated
*/
abstract public function generate(ChunkManager $world, Random $random, int $sourceX, int $sourceY, int $sourceZ) : bool;
}
TerrainObject::init();<file_sep><?php
declare(strict_types=1);
namespace muqsit\vanillagenerator\generator;
use pocketmine\utils\Random;
use pocketmine\world\ChunkManager;
use pocketmine\world\format\Chunk;
abstract class Decorator implements Populator{
/** @var int */
protected $amount = -PHP_INT_MAX;
final public function setAmount(int $amount) : void{
$this->amount = $amount;
}
abstract public function decorate(ChunkManager $world, Random $random, Chunk $chunk) : void;
public function populate(ChunkManager $world, Random $random, Chunk $chunk) : void{
for($i = 0; $i < $this->amount; ++$i){
$this->decorate($world, $random, $chunk);
}
}
}<file_sep><?php
declare(strict_types=1);
namespace muqsit\vanillagenerator\generator\nether\populator;
use muqsit\vanillagenerator\generator\nether\decorator\FireDecorator;
use muqsit\vanillagenerator\generator\nether\decorator\GlowstoneDecorator;
use muqsit\vanillagenerator\generator\nether\decorator\MushroomDecorator;
use muqsit\vanillagenerator\generator\Populator;
use pocketmine\block\VanillaBlocks;
use pocketmine\utils\Random;
use pocketmine\world\ChunkManager;
use pocketmine\world\format\Chunk;
use pocketmine\world\World;
class NetherPopulator implements Populator{
/** @var Populator[] */
private $inGroundPopulators = [];
/** @var Populator[] */
private $onGroundPopulators = [];
/** @var OrePopulator */
private $orePopulator;
/** @var FireDecorator */
private $fireDecorator;
/** @var GlowstoneDecorator */
private $glowstoneDecorator1;
/** @var GlowstoneDecorator */
private $glowstoneDecorator2;
/** @var MushroomDecorator */
private $brownMushroomDecorator;
/** @var MushroomDecorator */
private $redMushroomDecorator;
public function __construct(int $worldHeight = World::Y_MAX){
$this->orePopulator = new OrePopulator($worldHeight);
$this->inGroundPopulators[] = $this->orePopulator;
$this->fireDecorator = new FireDecorator();
$this->glowstoneDecorator1 = new GlowstoneDecorator(true);
$this->glowstoneDecorator2 = new GlowstoneDecorator();
$this->brownMushroomDecorator = new MushroomDecorator(VanillaBlocks::BROWN_MUSHROOM());
$this->redMushroomDecorator = new MushroomDecorator(VanillaBlocks::RED_MUSHROOM());
array_push($this->onGroundPopulators,
$this->fireDecorator,
$this->glowstoneDecorator1,
$this->glowstoneDecorator2,
$this->fireDecorator,
$this->brownMushroomDecorator,
$this->redMushroomDecorator
);
$this->fireDecorator->setAmount(1);
$this->glowstoneDecorator1->setAmount(1);
$this->glowstoneDecorator2->setAmount(1);
$this->brownMushroomDecorator->setAmount(1);
$this->redMushroomDecorator->setAmount(1);
}
public function populate(ChunkManager $world, Random $random, Chunk $chunk) : void{
$this->populateInGround($world, $random, $chunk);
$this->populateOnGround($world, $random, $chunk);
}
private function populateInGround(ChunkManager $world, Random $random, Chunk $chunk) : void{
foreach($this->inGroundPopulators as $populator){
$populator->populate($world, $random, $chunk);
}
}
private function populateOnGround(ChunkManager $world, Random $random, Chunk $chunk) : void{
foreach($this->onGroundPopulators as $populator){
$populator->populate($world, $random, $chunk);
}
}
}<file_sep><?php
declare(strict_types=1);
namespace muqsit\vanillagenerator\generator\utils;
use muqsit\vanillagenerator\generator\noise\bukkit\OctaveGenerator;
class NetherWorldOctaves extends WorldOctaves{
/** @var OctaveGenerator */
public $soul_sand;
/** @var OctaveGenerator */
public $gravel;
public function __construct(
OctaveGenerator $height,
OctaveGenerator $roughness,
OctaveGenerator $roughness2,
OctaveGenerator $detail,
OctaveGenerator $surface,
OctaveGenerator $soul_sand,
OctaveGenerator $gravel
){
parent::__construct($height, $roughness, $roughness2, $detail, $surface);
$this->soul_sand = $soul_sand;
$this->gravel = $gravel;
}
}<file_sep><?php
declare(strict_types=1);
namespace muqsit\vanillagenerator\generator\utils;
use pocketmine\block\Block;
use pocketmine\block\BlockFactory;
use pocketmine\block\BlockLegacyIds;
use pocketmine\block\BlockLegacyMetadata;
use pocketmine\block\utils\BlockDataSerializer;
use pocketmine\math\Facing;
final class BlockUtils{
public static function VINE(int $face) : Block{
static $meta = [
Facing::NORTH => BlockLegacyMetadata::VINE_FLAG_NORTH,
Facing::SOUTH => BlockLegacyMetadata::VINE_FLAG_SOUTH,
Facing::EAST => BlockLegacyMetadata::VINE_FLAG_EAST,
Facing::WEST => BlockLegacyMetadata::VINE_FLAG_WEST
];
return BlockFactory::getInstance()->get(BlockLegacyIds::VINE, $meta[$face]);
}
public static function COCOA(int $face, int $age = 0) : Block{
return BlockFactory::getInstance()->get(BlockLegacyIds::COCOA, BlockDataSerializer::writeLegacyHorizontalFacing(Facing::opposite($face)) | ($age << 2));
}
} | 6d517b3bea6ea2302cae936dbb0ee0149dc87622 | [
"PHP"
] | 18 | PHP | Altamash347/VanillaGenerator | 0dcdf18566e543c487f578cef382dae7f04c3bce | e7e0907d8b0a1bfff26ca65b4ab6c9ddde698f58 |
refs/heads/master | <repo_name>Komodo/Mark-Text-Macro<file_sep>/Mark-Text.js
/**
* @fileoverview Mark/unmark selected text (and persist marked text)
* @author <NAME>
* @version 1.0
*/
if (typeof(extensions) === 'undefined')
extensions = {};
if ( ! extensions.MarkSelection) {
extensions.MarkSelection = {};
}
else
{
var editor_pane = ko.views.manager.topView;
editor_pane.removeEventListener('keypress', extensions.MarkSelection.onKeyPress, true);
}
(function() {
var log = ko.logging.getLogger("ext_markselect");
var editor = ko.views.manager.currentView.scimoz;
var self = this;
//log.setLevel(10);
this.init = function()
{
if ( ! this.prepare()) return;
var indicators = this.getFileIndicators();
for (let i in indicators)
{
this.addIndicator(indicators[i]);
}
var editor_pane = ko.views.manager.topView;
editor_pane.addEventListener('keypress', this.onKeyPress, true);
}
this.prepare = function()
{
if ( ! editor) return false;
var hexToLong = ("require" in window) ? require("ko/color").RGBToBGR : xtk.color.hexToLong;
var color = ko.prefs.getLong('ext_marksel_color', hexToLong("#FF0000"));
editor.indicSetStyle(30, editor.INDIC_STRAIGHTBOX);
editor.indicSetFore(30, color);
editor.indicSetAlpha(30, 100);
editor.indicSetUnder(30, false);
editor.indicatorCurrent = 30;
editor.indicatorValue = 1;
return true;
}
this.onKeyPress = function(e)
{
if (e.charCode != 109 || ! e.altKey || ! self.prepare()) return;
var start = editor.anchor;
var end = editor.currentPos;
if (editor.anchor > editor.currentPos)
{
start = editor.currentPos;
end = editor.anchor;
}
var range = {start: start, length: end - start, stop: end};
if (editor.indicatorValueAt(30, range.start) == 1)
{
self.removeIndicator(range);
}
else
{
self.addIndicator(range);
}
};
this.getFileIndicators = function()
{
var pref = ko.views.manager.currentView.prefs;
return pref.hasPrefHere('ext_marksel_indicators') ?
JSON.parse(pref.getString('ext_marksel_indicators')) :
[];
}
this.saveFileIndicators = function(indicators)
{
var pref = ko.views.manager.currentView.prefs;
pref.setString('ext_marksel_indicators', JSON.stringify(indicators));
}
this.addIndicator = function(range)
{
var indicators = self.getFileIndicators();
indicators.push(range)
self.saveFileIndicators(indicators);
editor.indicatorFillRange(range.start, range.length);
}
this.removeIndicator = function(range)
{
var cleared = false;
var newIndicators = [];
var indicators = this.getFileIndicators();
for (let i in indicators)
{
let _range = indicators[i];
if (range.start >= _range.start && range.start < _range.stop)
{
editor.indicatorClearRange(_range.start, _range.length);
}
else
{
newIndicators.push(_range);
}
}
self.saveFileIndicators(newIndicators);
editor.indicatorClearRange(range.start, range.length);
}
this.init();
}).apply(extensions.MarkSelection);
<file_sep>/README.md
Mark-Text-Macro
===============
Allows marking text in files by pressing alt+M, persists across file close/reopen
You can change the color of the highlight by settings the pref via a macro (just delete it afterwards):
```js
var hexColor = "#FF0000";
ko.prefs.setLong('ext_marksel_color', ("require" in window) ?
require("ko/color").RGBToBGR(hexColor) :
xtk.color.hexToLong(hexColor));
```
| 892c53e5274bc24c1db74b226064ee16513827f0 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | Komodo/Mark-Text-Macro | 9c0db1ae87f15088e98973e913d41853765e0b2e | a82f6009aed12cfbfb6b380bb12492c0bd5952b6 |
refs/heads/main | <repo_name>dong-zhan/calculus<file_sep>/convolution/README.md
# convolution
f(x) is rectangular puse, g(x) is triangle, the convolution f(x)*g(x) is in red <br>
 <br>
<file_sep>/README.md
# calculus
step function/rectangular pulse, Fourier transform, and FFT <br>
 <br>
<file_sep>/convolution/triangle pulse.py
def u(x):
if x<0 :
return 0
return 1
def pulse(x):
cnt = len(t)
y = np.zeros(cnt)
for i,v in np.ndenumerate(t):
if v < 0:
y[i] = 0
elif v > 2:
y[i] = 0
else:
y[i] = 2
return y
def negx(t):
cnt = len(t)
y = np.zeros(cnt)
for i,v in np.ndenumerate(t):
if v < 0:
y[i] = 0
elif v > 2:
y[i] = 0
else:
y[i] = 2-v
return y
def conv_negx_const(t):
cnt = len(t)
y = np.zeros(cnt)
for i,v in np.ndenumerate(t):
if v < 0:
y[i] = 0
elif v <= 2:
y[i] = 4*v - v*v
elif v <= 4:
y[i] = 16 - 8*v + v*v
else:
y[i] = 0
return y
def pf(df, xstart, xstop, xnum = 50, color = 'green', show = True, linewidth=1.0):
global plt, t, s, xstep
xstep = (xstop-xstart)/(xnum)
t = np.arange(xstart, xstop+xstep, xstep) #use xstop+xstep to include the endpoint.
s = df(t)
line, = plt.plot(t, s, color = color, linewidth = linewidth)
if show:
plt.show()
def test_negx_pulse():
pf(negx, -1, 5, 50, 'green', False)
pf(pulse, -1, 5, 50, 'blue', False)
pf(conv_negx_const, -1, 5, 250, 'red', True)
<file_sep>/Laplace/laplace.py
def func(s): # L{e^(-at)}
global a
return 1/(s+a)
def func(s):
global a
return 1/(1+s*s)
def TransferFunction(s):
global a, b, z
return (s*z+1) / ((s+a+np.complex(0,1)*b) * (s+a-np.complex(0,1)*b))
def plot_laplace(func, xstart, xstop, xstep, ystart, ystop, ystep, zmin, zmax) :
global X,Y
fig = plt.figure()
ax = fig.gca(projection='3d')
#Z = np.zeros((2,2),dtype=np.complex_)
X = np.arange(xstart, xstop, xstep)
Y = np.arange(ystart, ystop, ystep)
X, Y = np.meshgrid(X, Y)
Z = np.vectorize(complex)(X, Y)
Z = func(Z)
# Plot the surface.
surf = ax.plot_surface(X, Y, np.abs(Z), cmap=cm.coolwarm,
linewidth=0, antialiased=False)
# Customize the z axis.
ax.set_zlim(zmin, zmax)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
# Add a color bar which maps values to colors.
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
a = np.complex(1.5,1.5)
b = np.complex(0.5,0.5)
z = np.complex(1,1)
a = -1
b = 1
z = 0
plot_laplace(TransferFunction, -2, 2, 0.01, -2, 2, 0.01, 0, 22)
a = 12
plot_laplace(func, -1, 1, 0.01, -1, 1, 0.01, 0, 0.2)
plot_laplace(func, -10, 10, 0.1, -10, 10, 0.1, 0, 6)
<file_sep>/spherical_harmonics/README.md
Y33, plotted with sh.py <br>
 <br>
sine function projected and reconstructed in spherical harmonics <br>
 <br>
<file_sep>/Laplace/README.md
Laplace transform with 2 poles and 1 zero.
 <br>
<file_sep>/spherical_harmonics/sh.py
def pf(df, xstart, xstop, xnum = 50, show = True, linewidth=1.0):
global plt, t, s, xstep
xstep = (xstop-xstart)/(xnum)
t = np.arange(xstart, xstop+xstep, xstep) #use xstop+xstep to include the endpoint.
s = df(t)
line, = plt.plot(t, s, linewidth = linewidth)
if show:
plt.show()
#########################################################
# https://en.wikipedia.org/wiki/Table_of_spherical_harmonics#Spherical_harmonics_with_l_.3D_4
def func_Y(): # real
global Y0, Y1_1, Y1, Y11, Y2_2, Y2_1, Y2, Y21, Y22, Y3_3, Y3_2, Y3_1, Y3, Y31, Y32, Y33, computeCoefficents, CEs, computeY, getY, Y0Table, Y1Table, Y2Table, Y3Table, YTable, computeCoefficentsY3, computeCoefficentsY2, computeCoefficentsY1, computeCoefficentsY0, computeY3, computeY2, computeY1, computeY0
def consts(): # real
global r, C_r_squared, C_r_cubed, CY0, CY1_1, CY1, CY11, CY2_2, CY2_1, CY2, CY21, CY22, CY3_3, CY3_2, CY3_1, CY3, CY31, CY32, CY33
r = 1
C_r_cubed = r * r * r
C_r_squared = r * r
CY0 = 1./2. * np.sqrt(1./ (1. * np.pi))
CY1_1 = 1./1. * np.sqrt(3./ (4. * np.pi)) #l,m
CY1 = 1./1. * np.sqrt(3./ (4. * np.pi))
CY11 = 1./1. * np.sqrt(3./ (4. * np.pi))
CY2_2 = 1./2. * np.sqrt(15./ (1. * np.pi))
CY2_1 = 1./2. * np.sqrt(15./ (1. * np.pi))
CY2 = 1./4. * np.sqrt(5./ (1. * np.pi))
CY21 = 1./2. * np.sqrt(15./ (1. * np.pi))
CY22 = 1./4. * np.sqrt(15./ (1. * np.pi))
CY3_3 = 1./4. * np.sqrt( 35./ (2. * np.pi))
CY3_2 = 1./2. * np.sqrt( 105./ (1. * np.pi))
CY3_1 = 1./4. * np.sqrt( 21./ (2. * np.pi))
CY3 = 1./4. * np.sqrt( 7./ (1. * np.pi))
CY31 = 1./4. * np.sqrt( 21./ (2. * np.pi))
CY32 = 1./4. * np.sqrt( 105./ (1. * np.pi))
CY33 = 1./4. * np.sqrt( 35./ (2. * np.pi))
consts()
################ Y0 ################
def Y0(x, y, z):
return np.full(x.shape, CY0)
################ Y1 ################
def Y1_1(x, y, z):
return CY0 * y / r
def Y1(x, y, z):
return CY0 * z / r
def Y11(x, y, z):
return CY0 * x / r
################ Y2 ################
def Y2_2(x, y, z):
return CY2_2 * (x*y) / C_r_squared
def Y2_1(x, y, z):
return CY2_1 * (y*z) / C_r_squared
def Y2(x, y, z):
return CY2 * (-x*x - y*y + 2*z*z) / C_r_squared
def Y21(x, y, z):
return CY21 * (z * x) / C_r_squared
def Y22(x, y, z):
return CY22 * (x*x - y*y) / C_r_squared
################ Y3 ################
def Y3_3(x, y, z):
return CY3_3 * (3*x*x - y*y) * y / C_r_cubed
def Y3_2(x, y, z):
return CY3_2 * (x*y*z) / C_r_cubed
def Y3_1(x, y, z):
return CY3_1 * (4*z*z - x*x - y*y) * y / C_r_cubed
def Y3(x, y, z):
return CY3 * (2*z*z - 3*x*x - 3*y*y) * z / C_r_cubed
def Y31(x, y, z):
return CY31 * (4*z*z - x*x - y*y) * x / C_r_cubed
def Y32(x, y, z):
return CY32 * (x*x - y*y) * z / C_r_cubed
def Y33(x, y, z):
return CY33 * (x*x - 3*y*y) * x / C_r_cubed
def computeCoefficentsY3(x, y, z):
return np.array([Y3_3(x, y, z), Y3_2(x, y, z), Y3_1(x, y, z), Y3(x, y, z), Y31(x, y, z), Y32(x, y, z), Y33(x, y, z)])
def computeY3(CEs, x, y, z):
return Y3_3(x, y, z)*CEs[0] + Y3_2(x, y, z)*CEs[1] + Y3_1(x, y, z)*CEs[2] + Y3(x, y, z)*CEs[3] +Y31(x, y, z)*CEs[4] + Y32(x, y, z)*CEs[5] + Y33(x, y, z)*CEs[6]
def computeCoefficentsY2(x, y, z):
return np.array([Y2_2(x, y, z), Y2_1(x, y, z), Y2(x, y, z), Y21(x, y, z), Y22(x, y, z)])
def computeY2(CEs, x, y, z):
return Y2_2(x, y, z)*CEs[0] + Y2_1(x, y, z)*CEs[1] + Y2(x, y, z)*CEs[2] +Y21(x, y, z)*CEs[3] + Y22(x, y, z)*CEs[4]
def computeCoefficentsY1(x, y, z):
return np.array([Y1_1(x, y, z), Y1(x, y, z), Y11(x, y, z)])
def computeY1(CEs, x, y, z):
return Y1_1(x, y, z)*CEs[0] + Y1(x, y, z)*CEs[1] +Y11(x, y, z)*CEs[2]
def computeCoefficentsY0(x, y, z):
return np.array([Y0(x, y, z)])
def computeY0(CEs, x, y, z):
return Y0(x, y, z)*CEs[0]
Y0Table = [Y0]
Y1Table = [Y1_1, Y1, Y11]
Y2Table = [Y2_2, Y2_1, Y2, Y21, Y22]
Y3Table = [Y3_3, Y3_2, Y3_1, Y3, Y31, Y32, Y33]
YTable = [Y0Table, Y1Table, Y2Table, Y3Table]
def getY(l, m):
return YTable[l][m+l]
def vsh(l = 3, m = -3): #Visualizing the spherical harmonics (real)
import matplotlib.pyplot as plt
from matplotlib import cm, colors
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from scipy.special import sph_harm
global x, y, z, sh, phi, theta, fcolors, fmin, fmax
phi = np.linspace(0, np.pi, 100)
theta = np.linspace(0, 2*np.pi, 100)
phi, theta = np.meshgrid(phi, theta)
x = np.sin(phi) * np.cos(theta)
y = np.sin(phi) * np.sin(theta)
z = np.cos(phi)
sh = getY(l, m)(x, y, z)
#sh = Y0(x, y, z)
#sh = Y1(x, y, z)
sh = np.sqrt(2) * (-1)**m * sh.real
fmax, fmin = sh.max(), sh.min()
fcolors = sh.real
if fmax == fmin :
pass
else:
fcolors = (fcolors - fmin)/(fmax - fmin)
mag = np.abs(sh)
z = z * mag
x = x * mag
y = y * mag
fig = plt.figure(figsize=plt.figaspect(1.))
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(x, y, z, rstride=1, cstride=1, facecolors=cm.seismic(fcolors))
#ax.set_axis_off()
plt.show()
def project():
## https://www.chebfun.org/examples/sphere/SphericalHarmonics.html#:~:text=A%20spherical%20harmonic%20projection%20gives,periodic%20function%20in%20one%20dimension.
def cshc_band3(): #compute spherical harmonics coefficients
global x, y, CEsn
r = np.pi*1
x = np.arange(-r, r, 0.1)
fy = np.sin(x)
#fy = x*x
x = x / r #normalize x
y = 1. - x*x
plt.plot(x, fy)
#return
i = 0
CEs3 = np.zeros(7)
for v in x:
CEs3 = CEs3 + fy[i] * computeCoefficentsY3(v, y[i], 0)
i = i+1
CEs3 = CEs3 / len(x)
i = 0
CEs2 = np.zeros(5)
for v in x:
CEs2 = CEs2 + fy[i] * computeCoefficentsY2(v, y[i], 0)
i = i+1
CEs2 = CEs2 / len(x)
i = 0
CEs1 = np.zeros(3)
for v in x:
CEs1 = CEs1 + fy[i] * computeCoefficentsY1(v, y[i], 0)
i = i+1
CEs1 = CEs1 / len(x)
i = 0
CEs0 = np.zeros(1)
for v in x:
CEs0 = CEs0 + fy[i] * computeCoefficentsY0(v, y[i], 0)
i = i+1
CEs0 = CEs0 / len(x)
#x = x / r
i = 0
for v in x:
y[i] = computeY3(CEs3, v, y[i], 0)
i = i + 1
i = 0
for v in x:
y[i] = y[i] + computeY2(CEs2, v, y[i], 0)
i = i + 1
i = 0
for v in x:
y[i] = y[i] + computeY1(CEs1, v, y[i], 0)
i = i + 1
i = 0
for v in x:
y[i] = y[i] + computeY0(CEs0, v, y[i], 0)
i = i + 1
y = y * 10
plt.plot(x, y)
plt.show()
<file_sep>/Fourier/rectangular pulse.py
def unit_step_fn(x):
global T
cnt = len(x)
y = np.zeros(cnt)
for i,v in np.ndenumerate(x):
if v>= -1 and v<=1:
y[i] = 1
else:
y[i] = 0
return y
def rectangular_pulse(inT, interval = np.pi/30):
global x, T, y
T = inT
ext = T*0.2
x = np.arange(-T-ext, T+ext+ext*0.1, interval)
y = unit_step_fn(x)
plt.plot(x, y)
plt.show()
def test_fft(ndArr, spacing):
global X, Y
samples = int(len(ndArr))
Y = scipy.fftpack.fft(ndArr)
X = np.linspace(0.0, 1.0/(2.0*spacing), int(samples/2))
plt.plot(X, 2.0/samples * np.abs(Y[:int(samples//2)]))
plt.show()
def fourier_unit_step_fn(x):
global T
return 2*np.sin(x*T)/x
def fourier_rectangular_pulse(inT, interval = np.pi/30):
global x, T, y
T = inT
ext = T*0.2
x = np.arange(-T-ext, T+ext+ext*0.1, interval)
y = fourier_unit_step_fn(x)
plt.plot(x, y)
plt.show()
rectangular_pulse(10)
test_fft(y, 0.1)
fourier_rectangular_pulse(10)
| 0fffa9802b8e52f98db5413fbcb37e5fc5a99b87 | [
"Markdown",
"Python"
] | 8 | Markdown | dong-zhan/calculus | f889e2ddcc78a175172094517512513f6550ab10 | 28587c75357bb93306afaa64757a139da421e880 |
refs/heads/master | <repo_name>redditvfs/redditvfs<file_sep>/README.md
redditVFS
========
Description
-----------
**reddivfs** is a FUSE-based filesystem that allows the user to read, post, and explore the content aggregation site reddit by maniplulating files and directories. The goal is to provide feature-complete access to the website via your file browser of choice.
Setup
-----
redditvfs runs off Python 2.3+. Once Python 2.3+ has been installed and all paths are set, redditvfs can then be run without any setup. However, if the user wishes to log in, a config file must be set up.
If a config file is used, but is empty or noncomplete, then redditvfs will prompt the user to input any missing information from the config.
Usage
-----
Default usage is
`./redditvfs.py [options] <mount-point>`
Once redditvfs is running, one can navigate from the mount point like a regular file system.
File System
-----------
The top-level mountpoint holds several directories and any config files in the following configuration.
user1.conf
r/
u/
m/
`r/` holds different subreddits. Subreddits can be subscribed or unsubscribed by `rmdir <subreddit>` the subreddit directory to unsubscribe, and `mkdir <subreddit name>` to subscribe.
Inside each subreddit directory, each post is another directory which contains a file with the post contents and all comments.
`u/` holds user information. `ls <username>` returns the files
overview/
comments/
submitted/
gilded/
Each directory holds the relevant comments or submissions as a symlink to the relevant post or comment in r/
`m/` holds the messages of the user in two directories, should one be logged in. One directory, `sent/` holds all sent messages from the user. The other, `inbox/` holds all messages received. To compose a message, a new text file is created in the directory `m/`, with the username of the recipient as the name of the file, and the contents of the file being the contents of the message.
The `r/` Directory
------------------
The first level of the `r/` directory holds all subreddits currently subscribed to. To subscribe to a subreddit, you `mkdir <subreddit-name>`. To unsubscribe, you `rmdir <subreddit-name>`
Each directory is named after the subreddit it contains.
Each subreddit directory contains multiple 'post directories.' Each post directory is named from the post it represents and a unique ID. Inside the directory there is
content -holds the contents of the post, be it a self-post or a link.
raw_content -holds the raw contents of the post or comment
link_content -appears when a url is provided to reddit. Typically this can be used to view files.
reply -a special file that when written to will reply to the current parent.
thumbnail -a special file that appears when a thumbnail is generated by reddit.
votes -when read gives the number of upvotes and downvotes the post has.
You can write a positive interger (upvote), 0 (no vote) or negative integer (downvote) to the file to vote.
flat -Holds the contents of the post and all children comments.
<username> -symlink to the user profile of the user who made the post.
The directory also contains several 'comment directories.'
Each comment directory corrosponds to the child comments. A comment directory has the same layout as a post directory, and can also contain comment directories of its own. The file `contents` instead contains the comment.
To make a post, you can write to the file `post` in the subreddit directory, with the first line being the title and the rest of the file being the contents.
To post a comment, inside any comment directory (or a post directory to make a top-level comment) you can write to `reply`. The contents are the comment itself.
To delete your post or comment, delete the `raw_content` file in the directory of the post or comment. If you have the correct permissions, the post or comment will be deleted.
To edit a post or comment, edit the `raw_content` file.
Options
-------
`-c -config [optional-config-file]` Designates a config files that may be empty, noncomplete, or filled out. If no config file is given, `.redditvfs.conf` is used.
`-f -foreground` Forces redditvfs to run in the foreground instead of in daemon mode. Useful for debugging.
<file_sep>/redditvfs.py
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
This is a reddit virtual filesystem. Provide a filepath where to mount this
filesystem as an argument and, optionally, an "-f" flag to keep it from
daemonizing.
"""
import errno
import fuse
import stat
import time
import praw
import getpass
import ConfigParser
import sys
import urllib2
import format
import json
fuse.fuse_python_api = (0, 2)
content_stuff = ['thumbnail', 'flat', 'votes', 'content', 'reply',
'raw_content', 'link_content']
class redditvfs(fuse.Fuse):
"""
The filesystem calls which could be utilized in redditvfs are implemented
here.
"""
def __init__(self, reddit=None, username=None, *args, **kw):
fuse.Fuse.__init__(self, *args, **kw)
if reddit is None:
raise Exception('reddit must be set')
def rmdir(self, path):
"""
One can run "rmdir" on r/<subreddit>.sub" to unsubscribe from the
directory.
"""
if len(path.split('/')) == 3 and reddit.is_logged_in:
reddit.unsubscribe(path.split('/')[-1:][0])
return
else:
return -errno.ENOSYS
def mkdir(self, path, mode):
"""
One can run "mmkdir" on r/<subreddit>.sub" to subscribe to the
directory.
"""
if len(path.split('/')) == 3 \
and path.split('/')[-1:][0][-4:] == '.sub' \
and reddit.is_logged_in:
reddit.subscribe(path.split('/')[-1:][0][:-4])
return
else:
return -errno.ENOSYS
def getattr(self, path):
"""
Returns stat info for file, such as permissions and access times.
"""
# default nlink and time info
st = fuse.Stat()
st.st_nlink = 2
st.st_atime = int(time.time())
st.st_mtime = st.st_atime
st.st_ctime = st.st_atime
# everything defaults to being a normal file unless explicitly set
# otherwise
st.st_mode = stat.S_IFREG | 0444
# useful information
path_split = path.split('/')
path_len = len(path_split)
# "." and ".."
if path_split[-1] == '.' or path_split[-1] == '..':
# . and ..
st.st_mode = stat.S_IFDIR | 0555
return st
# top-level directories
if path in ['/', '/u', '/r']:
st.st_mode = stat.S_IFDIR | 0555
return st
# r/*/ - subreddits
if path_split[1] == 'r' and path_len == 3:
# check for .sub directories for subscribing
if reddit.is_logged_in():
if path.split('/')[-1:][0][-4:] == '.sub':
my_subs = [sub.display_name.lower() for sub in
reddit.get_my_subreddits()]
if (path.split('/')[-1:][0][:-4]).lower() not in my_subs:
st = -2
else:
st.st_mode = stat.S_IFDIR | 0555
else:
st.st_mode = stat.S_IFDIR | 0555
else:
# normal subreddit
st.st_mode = stat.S_IFDIR | 0555
return st
# r/*/* - submissions
if path_split[1] == 'r' and path_len == 4:
if path_split[-1] == 'post':
# file to post a submission
st.st_mode = stat.S_IFREG | 0666
else:
# submission
st.st_mode = stat.S_IFDIR | 0555
return st
# r/*/*/[vote, etc] - content stuff in submission
if (path_split[1] == 'r' and path_len == 5 and path_split[-1] in
content_stuff):
st.st_mode = stat.S_IFREG | 0444
post_id = path_split[3].split(' ')[-1]
post = reddit.get_submission(submission_id=post_id)
formatted = ''
if path_split[-1] == 'content':
formatted = format.format_sub_content(post)
formatted = formatted.encode('ascii', 'ignore')
elif path_split[-1] == 'votes':
formatted = str(post.score) + '\n'
elif path_split[-1] == 'flat':
formatted = format.format_submission(post)
formatted = formatted.encode('ascii', 'ignore')
elif (path_split[-1] == 'thumbnail' and 'thumbnail' in dir(post)
and post.thumbnail != '' and post.thumbnail != 'self'
and post.thumbnail != 'default'):
f = urllib2.urlopen(post.thumbnail)
if f.getcode() == 200:
formatted = f.read()
elif path_split[-1] == 'reply':
st.st_mode = stat.S_IFREG | 0666
elif path_split[-1] == 'raw_content' and post.selftext:
st.st_mode = stat.S_IFREG | 0666
formatted = post.selftext.encode('ascii', 'ignore')
elif path_split[-1] == 'raw_content' and post.url:
st.st_mode = stat.S_IFREG | 0666
formatted = post.url.encode('ascii', 'ignore')
elif path_split[-1] == 'link_content' and post.url:
f = urllib2.urlopen(post.url)
if f.getcode() == 200:
formatted = f.read()
st.st_size = len(formatted)
return st
# r/*/*/** - comment post
if (path_split[1] == 'r' and path_len > 4 and path_split[-1] not in
content_stuff and path.split('/')[-1:][0][-1:] != '_'):
st.st_mode = stat.S_IFDIR | 0555
return st
# user link
if (path_split[1] == 'r' and path_len > 4 and path_split[-1] not in
content_stuff and path.split('/')[-1:][0][-1:] == '_'):
st.st_mode = stat.S_IFLNK | 0777
return st
# r/*/*/** - comment directory
if (path_split[1] == 'r' and path_len > 5 and path_split[-1] not in
content_stuff):
st.st_mode = stat.S_IFDIR | 0555
return st
# r/*/*/** - comment stuff
if (path_split[1] == 'r' and path_len > 5 and path_split[-1] in
content_stuff):
st.st_mode = stat.S_IFREG | 0444
post = get_comment_obj(path)
formatted = ''
if path_split[-1] == 'content':
formatted = format.format_comment(post, recursive=False)
formatted = formatted.encode('ascii', 'ignore')
elif path_split[-1] == 'votes':
formatted = str(post.score) + '\n'
elif path_split[-1] == 'flat':
formatted = format.format_comment(post, recursive=True)
formatted = formatted.encode('ascii', 'ignore')
elif path_split[-1] == 'reply':
st.st_mode = stat.S_IFREG | 0666
elif path_split[-1] == 'raw_content':
st.st_mode = stat.S_IFREG | 0666
formatted = post.body.encode('ascii', 'ignore')
st.st_size = len(formatted)
return st
# u/* - user
if path_split[1] == 'u' and path_len == 3:
st.st_mode = stat.S_IFDIR | 0555
return st
# u/*/* - user stuff (comments, submitted, etc)
if path_split[1] == 'u' and path_len == 4:
st.st_mode = stat.S_IFDIR | 0555
return st
# u/*/*/* - links (comment, submitted, etc)
elif (path_split[1] == 'u' and path_len == 5):
st.st_mode = stat.S_IFLNK | 0777
return st
def readlink(self, path):
"""
Symlinks are used to redirect some references to one thing to a single
implementation. The logic to dereference symlinks is here.
"""
numdots = len(path.split('/'))
dots = ''
if path.split('/')[-1:][0][-1:] == '_' and len(path.split('/')) >= 5:
#if this is a userlink
numdots -= 2
while (numdots > 0):
dots += '../'
numdots -= 1
return dots + 'u/' + path.split('/')[-1:][0][11:-1]
if path.split('/')[1] == 'u' and len(path.split('/')) == 5:
numdots -= 2
while (numdots > 0):
dots += '../'
numdots -= 1
comment_id = path.split(' ')[-1]
sub = str('http://www.reddit.com/comments/'+comment_id)
sub = reddit.get_submission(sub)
subname = str(sub.subreddit)
subid = str(sub.id)
return str(dots + 'r/' + subname + '/' + subid)
def readdir(self, path, offset):
"""
Returns a list of directories in requested path
"""
# Every directory has '.' and '..'
yield fuse.Direntry('.')
yield fuse.Direntry('..')
# cut-off length on items with id to make things usable for end-user
pathmax = 50
path_split = path.split('/')
path_len = len(path_split)
if path == '/':
# top-level directory
yield fuse.Direntry('u')
yield fuse.Direntry('r')
elif path_split[1] == 'r':
if path_len == 2:
# if user is logged in, populate with get_my_subreddits
# otherwise, default to frontpage
if reddit.is_logged_in():
for subreddit in reddit.get_my_subreddits():
url_part = subreddit.url.split('/')[2]
dirname = sanitize_filepath(url_part)
yield fuse.Direntry(dirname)
else:
for subreddit in reddit.get_popular_subreddits():
url_part = subreddit.url.split('/')[2]
dirname = sanitize_filepath(url_part)
yield fuse.Direntry(dirname)
elif path_len == 3:
# posts in subreddits
subreddit = path_split[2]
for post in reddit.get_subreddit(subreddit).get_hot(limit=20):
filename = sanitize_filepath(post.title[0:pathmax]
+ ' ' + post.id)
yield fuse.Direntry(filename)
# write to this to create a new post
yield fuse.Direntry('post')
elif path_len == 4:
# a submission in a subreddit
post_id = path_split[3].split(' ')[-1]
post = reddit.get_submission(submission_id=post_id)
# vote, content, etc
for file in content_stuff:
if file != 'thumbnail' and file != 'link_content':
yield fuse.Direntry(file)
yield fuse.Direntry("_Posted_by_" + str(post.author) + "_")
if post.thumbnail != "" and post.thumbnail != 'self':
# there is link content, maybe a thumbnail
if post.thumbnail != 'default':
yield fuse.Direntry('thumbnail')
yield fuse.Direntry('link_content')
for comment in post.comments:
if 'body' in dir(comment):
yield fuse.Direntry(
sanitize_filepath(comment.body[0:pathmax]
+ ' ' + comment.id))
elif len(path.split('/')) > 4:
# a comment or a user
# Can't find a good way to get a comment from an id, but there
# is a good way to get a submission from the id and to walk
# down the tree, so doing that as a work-around.
comment = get_comment_obj(path)
for file in content_stuff:
if file != 'thumbnail' and file != 'link_content':
yield fuse.Direntry(file)
yield fuse.Direntry('_Posted_by_' + str(comment.author)+'_')
for reply in comment.replies:
if 'body' in dir(reply):
yield fuse.Direntry(
sanitize_filepath(reply.body[0:pathmax]
+ ' ' + reply.id))
elif path_split[1] == 'u':
if path_len == 2:
# if user is logged in, show the user. Otherwise, this empty
# doesn't have any values listed.
if reddit.is_logged_in():
yield fuse.Direntry(username)
if path_len == 3:
yield fuse.Direntry('Overview')
yield fuse.Direntry('Submitted')
yield fuse.Direntry('Comments')
if path_len == 4:
user = reddit.get_redditor(path_split[2])
if path_split[3] == 'Overview':
for c in enumerate(user.get_overview(limit=10)):
if type(c[1]) == praw.objects.Submission:
c_part = c[1].title[0:pathmax] + ' ' + c[1].id
yield fuse.Direntry(sanitize_filepath(c_part))
if type(c[1]) == praw.objects.Comment:
c_part = c[1].body[0:pathmax] + ' ' +\
c[1].submission.id
yield fuse.Direntry(sanitize_filepath(c_part))
elif path_split[3] == 'Submitted':
for c in enumerate(user.get_submitted(limit=10)):
c_part = c[1].title[0:pathmax] + ' ' + c[1].id
yield fuse.Direntry(sanitize_filepath(c_part))
elif path_split[3] == 'Comments':
for c in enumerate(user.get_comments(limit=10)):
c_part = c[1].body[0:pathmax] + ' ' +\
c[1].submission.id
yield fuse.Direntry(sanitize_filepath(c_part))
def read(self, path, size, offset, fh=None):
"""
Is used to get contents of posts, comments, etc from reddit to the end
user.
"""
path_split = path.split('/')
path_len = len(path_split)
if path_split[1] == 'r' and path_len == 5:
# Get the post
post_id = path_split[3].split(' ')[-1]
post = reddit.get_submission(submission_id=post_id)
formatted = ''
if path_split[-1] == 'content':
formatted = format.format_sub_content(post)
formatted = formatted.encode('ascii', 'ignore')
elif path_split[-1] == 'votes':
formatted = str(post.score) + '\n'
elif path_split[-1] == 'flat':
formatted = format.format_submission(post)
formatted = formatted.encode('ascii', 'ignore')
elif (path_split[-1] == 'thumbnail' and post.thumbnail != '' and
post.thumbnail != 'self' and post.thumbnail != 'default'):
f = urllib2.urlopen(post.thumbnail)
if f.getcode() == 200:
formatted = f.read()
elif path_split[-1] == 'raw_content' and post.selftext:
formatted = post.selftext.encode('ascii', 'ignore')
elif path_split[-1] == 'raw_content' and post.url:
formatted = post.url.encode('ascii', 'ignore')
elif path_split[-1] == 'link_content' and post.url:
f = urllib2.urlopen(post.url)
if f.getcode() == 200:
formatted = f.read()
return formatted[offset:offset+size]
elif path_split[1] == 'r' and path_len > 5:
# Get the comment
post = get_comment_obj(path)
if path_split[-1] == 'content':
formatted = format.format_comment(post, recursive=False)
formatted = formatted.encode('ascii', 'ignore')
elif path_split[-1] == 'votes':
formatted = str(post.score) + '\n'
elif path_split[-1] == 'flat':
formatted = format.format_comment(post, recursive=True)
formatted = formatted.encode('ascii', 'ignore')
elif path_split[-1] == 'raw_content':
formatted = post.body.encode('ascii', 'ignore')
return formatted[offset:offset+size]
return -errno.ENOSYS
def truncate(self, path, len):
"""
there is no situation where this will actually be used
"""
pass
def write(self, path, buf, offset, fh=None):
"""
Handles voting, content creation, and management. Requires login
"""
if not reddit.is_logged_in():
return errno.EACCES
path_split = path.split('/')
path_len = len(path_split)
# Voting
if path_split[1] == 'r' and path_len >= 5 and\
path_split[-1] == 'votes':
# Get the post or comment
if path_len > 5:
post = get_comment_obj(path)
else:
post_id = path_split[-2].split(' ')[-1]
post = reddit.get_submission(submission_id=post_id)
# Determine what type of vote and place the vote
vote = int(buf)
if vote == 0:
post.clear_vote()
elif vote > 0:
post.upvote()
elif vote < 0:
post.downvote()
return len(buf)
# Reply to submission
if path_split[1] == 'r' and path_len == 5 and\
path_split[-1] == 'reply':
post_id = path_split[-2].split(' ')[-1]
post = reddit.get_submission(submission_id=post_id)
post.add_comment(buf)
return len(buf)
# Reply to comments
if path_split[1] == 'r' and path_len > 5 and\
path_split[-1] == 'reply':
post = get_comment_obj(path)
post.reply(buf)
return len(buf)
# Write a new post
if path_split[1] == 'r' and path_len == 4 and\
path_split[-1] == 'post':
buf_split = buf.split('\n')
title = buf_split[0]
if len(buf_split) > 2:
# Self-post
text = '\n'.join(buf_split[1:])
reddit.submit(subreddit=path_split[2], title=title, text=text)
else:
# Link
reddit.submit(subreddit=path_split[2], title=title,
url=buf_split[1])
return len(buf)
# Edit a post or comment
if path_split[1] == 'r' and path_len >= 5 and\
path_split[-1] == 'raw_content':
# Get the post or comment
if path_len > 5:
post = get_comment_obj(path)
else:
post_id = path_split[-2].split(' ')[-1]
post = reddit.get_submission(submission_id=post_id)
post.edit(buf)
return len(buf)
# fake success for editor's backup files
return len(buf)
def create(self, path, flags, mode):
"""
No part of the redditvfs API actually utilizes create() - it is always
an error.
"""
return errno.EPERM
def unlink(self, path):
"""
Handle deleting posts and comments
"""
if not reddit.is_logged_in():
return errno.EACCES
path_split = path.split('/')
path_len = len(path_split)
if path_split[1] == 'r' and path_len >= 5 and\
path_split[-1] == 'raw_content':
if path_len > 5:
post = get_comment_obj(path)
else:
post_id = path_split[-2].split(' ')[-1]
post = reddit.get_submission(submission_id=post_id)
post.delete()
return 0
return errno.EPERM
def sanitize_filepath(path):
"""
Converts provided path to legal UNIX filepaths.
"""
# remove illegal and confusing characters
for char in ['/', '\n', '\0']:
path = path.replace(char, '_')
# Direntry() doesn't seem to like non-ascii
path = path.encode('ascii', 'ignore')
return path
def get_comment_obj(path):
"""
given a filesystem path, returns a praw comment object
"""
# Can't find a good way to get a comment from an id, but there
# is a good way to get a submission from the id and to walk
# down the tree, so doing that as a work-around.
path_split = path.split('/')
path_len = len(path_split)
post_id = path_split[3].split(' ')[-1]
post = reddit.get_submission(submission_id=post_id)
# quick error check
if len(post.comments) == 0:
return -errno.ENOENT
for comment in post.comments:
if comment.id == path_split[4].split(' ')[-1]:
break
level = 4
if path_split[-1] in content_stuff:
adjust = 2
else:
adjust = 1
while level < path_len - adjust:
level += 1
for comment in comment.replies:
if comment.id == path_split[level].split(' ')[-1]:
break
return comment
def login_get_username(config):
"""
returns the username of the user to login
"""
try:
username = config.get('login', 'username')
except Exception, e:
# Prompt for username
username = raw_input("Username: ")
pass
return username
def login_get_password(config):
"""
returns the password of the user to login
"""
try:
password = config.get('login', 'password')
except Exception, e:
# Prompt for password
password = <PASSWORD>()
pass
return password
if __name__ == '__main__':
# Create a reddit object from praw
reddit = praw.Reddit(user_agent='redditvfs')
# Login only if a configuration file is present
if '-c' in sys.argv:
# Remove '-c' from sys.argv
sys.argv.remove('-c')
# User wants to use the config file, create the parser
config = ConfigParser.RawConfigParser(allow_no_value=True)
# Check for default login
try:
config.read('~/.redditvfs.conf')
except Exception, e:
pass
finally:
username = login_get_username(config=config)
password = login_get_password(config=config)
try:
reddit.login(username=username, password=<PASSWORD>)
print 'Logged in as: ' + username
except Exception, e:
print e
print 'Failed to login'
else:
username = None
fs = redditvfs(reddit=reddit, username=username, dash_s_do='setsingle')
fs.parse(errex=1)
fs.main()
<file_sep>/format.py
import praw
import textwrap
import time
import codecs
def format_sub_content(submission):
"""return formatted submission without comments as a String"""
text = []
indent = 3
wrap = textwrap.TextWrapper(initial_indent=indent*' '+'|', subsequent_indent=indent*' '+'|')
br = indent * ' ' + '-' * (79-indent) + '\n'
text.append(br)
text += wrap.wrap(submission.title)
text.append(br)
if submission.selftext:
text += wrap.wrap('\n' + submission.selftext + '\n')
text.append(br)
if submission.url:
text += wrap.wrap('\n' + submission.url + '\n')
text.append(br)
d = get_info_dict(submission)
formatted = "%(author)s %(time)s ago\n"\
+"%(score)d points (%(ups)d|%(downs)d) id:%(id)s"
text += wrap.wrap(formatted % d)
text.append(br)
return '\n'.join(text)+'\n'
def format_submission(submission):
"""return formatted submission and all comments as [String]"""
text = [format_sub_content(submission)] +\
[format_comment(c) for c in submission.comments]
return '\n'.join(text)+'\n'
def get_info_dict(comsub):
"""get dictionary of attributes for formatting"""
d = {}
d['author'] = comsub.author if comsub.author else "DELETED"
d['time'] = time.ctime(comsub.created)
d['score'] = comsub.score
d['ups'] = comsub.ups
d['downs'] = comsub.downs
d['id'] = comsub.id
return d
def format_comment(comment, depth=0, cutoff=-1, recursive=True, top=-1):
"""returns formatted comment + children as a [String]"""
indent = 2
base_ind=4
indent += depth * base_ind
if depth==cutoff:
return ' '*indent + '...\n'
if isinstance(comment, praw.objects.MoreComments):
return ' '*indent + 'More...\n'
text = get_comment_header(comment, indent)
text += get_comment_body(comment,indent)
if recursive:
for i, child in enumerate(comment.replies):
text += format_comment(child, depth+1)
return text
def get_comment_header(comment, indent):
"""return formatted header of post"""
wrap = indent * ' ' + (78- indent) * '-'
formatted = indent * '-'+ "|%(author)s %(time)s ago\n"\
+ indent * ' ' + "|%(score)d points (%(ups)d|%(downs)d) id:%(id)s"
d = get_info_dict(comment)
return '\n'.join([wrap, formatted % d, wrap]) + '\n'
def get_comment_body(comment, indent):
"""returns formatted body of comment as [String]"""
wrap = indent * ' ' + (78- indent) * '-' + '\n'
indent = indent* ' '
wrapper = textwrap.TextWrapper(initial_indent=indent + '|',
subsequent_indent=indent + '|',width=79)
return '\n'.join(wrapper.wrap(comment.body)+[wrap])
def get_top_10(subreddit):
"""utility testing function"""
r = praw.Reddit('test!')
sub = r.get_subreddit(subreddit)
return [post for post in sub.get_top(limit=10)]
#testing code
if __name__=='__main__':
r = praw.Reddit('test!')
sub = r.get_subreddit('iama')
posts = [post for post in sub.get_top(limit=1)]
with codecs.open('out.txt', mode='w',encoding='utf-8') as f:
for post in posts:
lines = format_submission(post)
print lines
| 73706f015024e31b2299c51108a92612f964cd56 | [
"Markdown",
"Python"
] | 3 | Markdown | redditvfs/redditvfs | a29ae54e3afc6b2e64fa960d90a8f8b2115c0acf | 13de17df0ee0afa3bac4921c5dec112f76215bff |
refs/heads/master | <file_sep><?php
/**
* Created by PhpStorm.
* User: test
* Date: 3/2/17
* Time: 12:03 AM
*/
class SquareShape extends ShapeAbstractClass
{
public $sideLength;
public $defaultColor = self::COLOR_RED;
public function draw(DrawTypeInterface $drawMethod)
{
// do some actions with params to make pointsArray
$drawParams = [
'pointsArray' => [[4,5], [3,3]],
'comment' => 'draw square with params: sideLength = '. $this->sideLength .', lineWidth = '. $this->lineWidth .', colorId = '. $this->color
];
$drawMethod->draw($drawParams);
}
public function setParams(array $paramsList)
{
$this->lineWidth = $paramsList['lineWidth'];
$this->sideLength = $paramsList['sideLength'];
$this->color = $this->checkCorrectColor($paramsList['color']) ? $paramsList['color'] : $this->defaultColor;
}
}<file_sep><?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once 'ShapeFactory.php';
require_once 'DrawTypeEcho.php';
if (isset($_GET['shapesJson'])) {
$shapes = json_decode($_GET['shapesJson'], true);
} else {
$shapes = [
['type' => 'circle', 'params' => ['color' => 1, 'lineWidth' => 1, 'radius' => 5]],
['type' => 'circle', 'params' => ['color' => 5, 'lineWidth' => 1, 'radius' => 5]],
['type' => 'square', 'params' => ['color' => 1, 'lineWidth' => 3, 'sideLength' => 5]],
['type' => 'square', 'params' => ['color' => 5, 'lineWidth' => 3, 'sideLength' => 5]]
];
}
foreach ($shapes as $shape) {
$shapeName = $shape['type'];
$shapeParams = $shape['params'];
$drawMethodClass = new DrawTypeEcho();
$shapeModel = ShapeFactory::getShape($shapeName);
$shapeModel->setParams($shapeParams);
$shapeModel->draw($drawMethodClass);
}
<file_sep># yell-test repo
Задание 1
------------
Сделал без фанатизма, по хорошему нужно разнести по папкам, добавить проверки всех параметров и тп. Файлы собственно в корне репозитория.
Задание 2
------------
```
Book table
+----+--------+
| id | name |
+----+--------+
| 1 | Book1 |
+----+--------+
| 2 | Book2 |
+----+--------+
Author table
+----+--------+
| id | name |
+----+--------+
| 1 | Ptrov |
+----+--------+
| 2 | Semnv |
+----+--------+
Author_book table
+----+-------------+---------------+
| id | author_id | book_id |
+----+--------+------------+-------+
| 1 | 1 | 1 |
+----+--------+--------------------+
| 2 | 2 | 1 |
+----+--------+--------------------+
```
Задание 3
------------
```
SELECT type,value FROM "data" as t1 WHERE date = (SELECT MAX(date) from "data" as t2 WHERE t2.type = t1.type)
```<file_sep><?php
/**
* Created by PhpStorm.
* User: test
* Date: 3/2/17
* Time: 1:03 AM
*/
require_once 'DrawTypeInterface.php';
class DrawTypeEcho implements DrawTypeInterface
{
public function draw(array $params)
{
echo '<p>'.$params['comment'].'</p><br/>';
echo '<pre>';
var_dump($params['pointsArray']);
echo '</pre><br/>';
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: test
* Date: 3/1/17
* Time: 11:55 PM
*/
abstract class ShapeAbstractClass
{
const COLOR_BLACK = 1;
const COLOR_RED = 2;
public $lineWidth = 1;
public $color = self::COLOR_BLACK;
public abstract function draw(DrawTypeInterface $drawMethod);
/**
* @param array $paramsList
* @return bool
*/
public abstract function setParams(array $paramsList);
protected function checkCorrectColor($colorId) {
return in_array($colorId, [self::COLOR_BLACK, self::COLOR_RED]);
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: test
* Date: 3/2/17
* Time: 12:03 AM
*/
require_once 'CircleShape.php';
require_once 'SquareShape.php';
class ShapeFactory
{
public static function getShape($shapeName) {
switch ($shapeName) {
case 'circle':
return new CircleShape();
case 'square':
return new SquareShape();
}
}
}<file_sep><?php
require_once 'ShapeAbstractClass.php';
/**
* Created by PhpStorm.
* User: test
* Date: 3/2/17
* Time: 12:03 AM
*/
class CircleShape extends ShapeAbstractClass
{
public $radius;
public $defaultColor = self::COLOR_RED;
public function draw(DrawTypeInterface $drawMethod)
{
// do some actions with params to make pointsArray
$drawParams = [
'pointsArray' => [[1,2], [2,3]],
'comment' => 'draw circle with params: radius = '. $this->radius .', lineWidth = '. $this->lineWidth .', colorId = '. $this->color
];
$drawMethod->draw($drawParams);
}
public function setParams(array $paramsList)
{
$this->lineWidth = $paramsList['lineWidth'];
$this->radius = $paramsList['radius'];
$this->color = $this->checkCorrectColor($paramsList['color']) ? $paramsList['color'] : $this->defaultColor;
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: test
* Date: 3/2/17
* Time: 1:01 AM
*/
interface DrawTypeInterface
{
public function draw(array $params);
} | c0c1c30cb4aed6d763ed8fff8df917f43fabfe05 | [
"Markdown",
"PHP"
] | 8 | PHP | hrom252/yell-test | dfcb8dcd4c043ebd26da96b630e94ac724c3a074 | a86f2e5af660095c6fed051c39016605972ced1c |
refs/heads/master | <repo_name>mcdir/zabbix-cloudwatch<file_sep>/README.md
# zabbix-cloudwatch
Amazon CloudWatch is a monitoring service for AWS cloud resources and the applications you run on AWS, which can be accessed from AWS console. We have now integrated CloudWatch monitoring data into Zabbix monitoring system.
AmazonCloudWatch Developer Guide - http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/supported_services.html
AWS SDK in Python Boto - https://github.com/boto/boto
# Installation
Install boto on zabbix server via pip.
```
virtualenv -p python3 .venv
. .venv/bin/activate
pip3 install -r requirements.txt
virtualenv -p python2 .venv
. .venv/bin/activate
pip install -r requirements2.txt
```
Clone this repo to /opt/zabbix-extention
```
git clone https://github.com/omni-lchen/zabbix-cloudwatch.git cloudwatch
```
Customize `conf.d/crontab` to your settings where:
1. `<*_Name>` : The name in AWS
2. `<zabbix_host>` : The name of the host being monitored by Zabbix (not the Zabbix host)
3. `<zabbix_server or zabbix_proxy>` : Tho host running the Zabbix Server backend
4. `<aws_account>` : AWS Account number
5. `<aws_region>` : i.e. `us-east-1`
Customize `conf/awscreds` where:
1. `[aws_account_1]` : AWS Account number, i.e. `[<aws_account>]`
2. `aws_access_key_id` : Get it from the AWS website
3. `aws_secret_access_key` : Get it from the AWS website
Customize the metrics you want to capture in `conf/aws_services_metrics.conf`. Find the metrics from [AmazonCloudWatch Developer Guide](http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/supported_services.html).
Test that the cron script you are running works:
```
./cron.RDS.sh "cool-server" "mydb.abs343jddvzu.us-east-1.rds.amazonaws.com" "localhost" "12345678901" "us-east-1"
```
In the `cron.d` folder, run `crontab crontab` - ** WARNING this will clear your personal crontab! **
Make sure the cron job is being run with no errors in `syslog`.
Import `template\*` into Zabbix via the website. (It's as simple as it sounds)
Finally, associate an imported template with a host, which must match the name `<zabbix_host>`
### Advanced Help
Example AWS Metric Zabbix Trapper Item Key Format without Discovery.
```
Key: \<aws_service\>.\<metric\>.\<statistics\>
```
Example AWS Metric Zabbix Trapper Item Key Format with Discovery.
```
Key: \<aws_service\>.\<metric\>.\<statistics\>["\<aws_account\>","\<aws_region\>","\<discovery_item_value\>"]
```
DynamoDB Item Key Format is different from the standard setup, due to combinations of different dimensions and metrics.
```
operations_all = ['GetItem', 'PutItem', 'Query', 'Scan', 'UpdateItem', 'DeleteItem', 'BatchGetItem', 'BatchWriteItem']
operations_metrics = ['SuccessfulRequestLatency', 'SystemErrors', 'ThrottledRequests]
```
DynamoDB Item Key1: `DynamoDB.\<operations_all\>.\<operations_metrics\>.\<statistics\>["\<aws_account\>","\<aws_region\>","\<table_name\>"]`
```
operations_returned_item = ['Query', 'Scan']
```
DynamoDB Item Key2: `DynamoDB.\<operations_returned_item\>.ReturnedItemCount.\<statistics\>["\<aws_account\>","\<aws_region\>","\<table_name\>"]`
DynamoDB Other Keys: `DynamoDB.\<metric\>.\<statistics\>["\<aws_account\>","\<aws_region\>","\<table_name\>"]`
<file_sep>/requirements2.txt
boto==2.49.0
boto3==1.14.7
botocore==1.17.7
configparser==4.0.2
python-dateutil==2.8.1
<file_sep>/cron.d/cron.RDS-test.sh
#!/bin/bash
# Date: 08/08/2015
# Author: <NAME>
# Description: A script to bulk send RDS cloudwatch data to zabbix server
# /cron.RDS-test.sh "test-database" "test-profile" "eu-west-1"
LIB_PATH=$(cd ../ && pwd)
PATH=$PATH:/opt/zabbix-extention/cloudwatch:${LIB_PATH}
export PATH
if [ -f /opt/zabbix-extention/cloudwatch/.venv/bin/activate ]; then
source "/opt/zabbix-extention/cloudwatch/.venv/bin/activate"
fi
# DB instance indentifier
DB_INSTANCE=$1
# AWS Account
ACCOUNT=$2
# AWS Region
REGION=$3
# Collecting 5-minute data from cloudwatch
PERIOD="300"
# Set start time and end time for collecting cloudwatch data
# Adding lag, as CloudWatch doesn't send all data if requested too early.
ENDTIME=$(date -u "+%F %H:%M:00" -d "5 minutes ago")
STARTTIME=$(date -u "+%F %H:%M:00" -d "10 minutes ago")
# Send cloudwatch data of a table to Zabbix Server
${LIB_PATH}/zabbixCloudWatch.py --test True -a "$ACCOUNT" -r "$REGION" -s "RDS" -d "DBInstanceIdentifier=$DB_INSTANCE" -p "$PERIOD" -f "$STARTTIME" -t "$ENDTIME"
<file_sep>/cron.d/cron.ELB-test.sh
#!/bin/bash
# Date: 08/08/2015
# Author: <NAME>
# Description: A script to bulk send ELB cloudwatch data to zabbix server
LIB_PATH=$(cd ../ && pwd)
PATH=$PATH:/opt/zabbix-extention/cloudwatch:${LIB_PATH}
export PATH
if [ -f /opt/zabbix-extention/cloudwatch/.venv/bin/activate ]; then
source "/opt/zabbix-extention/cloudwatch/.venv/bin/activate"
fi
# Load Balancer Name
LOAD_BALANCER=$1
# AWS Account
ACCOUNT=$2
# AWS Region
REGION=$3
# Collecting 5-minute data from cloudwatch
PERIOD="300"
# Set start time and end time for collecting cloudwatch data
# Adding lag, as CloudWatch doesn't send all data if requested too early.
ENDTIME=$(date -u "+%F %H:%M:00" -d "5 minutes ago")
STARTTIME=$(date -u "+%F %H:%M:00" -d "10 minutes ago")
# Send cloudwatch data of a table to Zabbix Server
echo "zabbixCloudWatch.py --test True -a \"$ACCOUNT\" -r \"$REGION\" -s ELB -d LoadBalancerName=\"$LOAD_BALANCER\" -p \"$PERIOD\" -f \"$STARTTIME\" -t \"$ENDTIME\""
${LIB_PATH}/zabbixCloudWatch.py --test True -a "$ACCOUNT" -r "$REGION" -s "ELB" -d "LoadBalancerName=$LOAD_BALANCER" -p "$PERIOD" -f "$STARTTIME" -t "$ENDTIME"
<file_sep>/examples/py-zabbix-example-psk.py
import functools
import ssl
import sslpsk
from pyzabbix import ZabbixMetric, ZabbixSender
class PyZabbixPSKSocketWrapper:
"""Implements ssl.wrap_socket with PSK instead of certificates.
Proxies calls to a `socket` instance.
"""
def __init__(self, sock, *, identity, psk):
self.__sock = sock
self.__identity = identity
self.__psk = psk
def connect(self, *args, **kwargs):
# `sslpsk.wrap_socket` must be called *after* socket.connect,
# while the `ssl.wrap_socket` must be called *before* socket.connect.
self.__sock.connect(*args, **kwargs)
# `sslv3 alert bad record mac` exception means incorrect PSK
self.__sock = sslpsk.wrap_socket(
self.__sock,
# https://github.com/zabbix/zabbix/blob/f0a1ad397e5653238638cd1a65a25ff78c6809bb/src/libs/zbxcrypto/tls.c#L3231
ssl_version=ssl.PROTOCOL_TLSv1_2,
# https://github.com/zabbix/zabbix/blob/f0a1ad397e5653238638cd1a65a25ff78c6809bb/src/libs/zbxcrypto/tls.c#L3179
ciphers="PSK-AES128-CBC-SHA",
psk=(self.__psk, self.__identity),
)
def __getattr__(self, name):
return getattr(self.__sock, name)
sender = ZabbixSender(
zabbix_server="127.0.0.1",
socket_wrapper=functools.partial(
PyZabbixPSKSocketWrapper,
identity="TEST-PSK", # your PSK identity
psk=bytes.fromhex(
"fa4ca8cc95bb4740864bbbd9d931688ec90fff9363af6ce5a0cd725b1058f25f" # your PSK
),
),
)
# Send metrics to zabbix trapper
packet = [
ZabbixMetric('test-zabbix-host', 'RDS.BinLogDiskUsage.Average', 3),
]
result = sender.send(packet)
print(result)<file_sep>/examples/pyZabbixSenderTest.py
from pyZabbixSender import pyZabbixSender
test_host="zabbix agent"
# Creating a sender object
z = pyZabbixSender(server="zabbix-server", port=10051)
# Adding data (without timestamp)
z.addData(host=test_host, key="RDS.BinLogDiskUsage.Average", value="777")
# Ready to send your data?
results = z.sendData()
# Check if everything was sent as expected
if results[0][0] != z.RC_OK:
print("oops!")
print(results)
<file_sep>/requirements.txt
boto==2.49.0
boto3==1.14.7
botocore==1.17.7
configparser==5.0.0
docutils==0.15.2
install==1.3.4
jmespath==0.10.0
py-zabbix @ git+https://github.com/mcdir/py-zabbix.git@psk
python-dateutil==2.8.1
s3transfer==0.3.4
six==1.15.0
sslpsk==1.0.0
urllib3==1.25.11
<file_sep>/examples/py-zabbix-example.py
from pyzabbix import ZabbixMetric, ZabbixSender
from pyzabbix import ZabbixSender
import ssl
# Send metrics to zabbix trapper
packet = [
ZabbixMetric('test-zabbix-host', 'RDS.BinLogDiskUsage.Average', 3),
]
result = ZabbixSender(use_config=True,socket_wrapper=lambda sock: ssl.wrap_socket(sock).send(packet)
print(result) | acf377f63f865bd4dc489efe8309e65714dc3de0 | [
"Markdown",
"Python",
"Text",
"Shell"
] | 8 | Markdown | mcdir/zabbix-cloudwatch | 1897e441967634f23c89e260256371655b411d49 | e25534ce75b4535695980b62af6f1aa1fb129068 |
refs/heads/master | <file_sep>/*
Program: Translate from English to PigLatin (Lab6)
Due Date: 9/26/2017 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lab6
{
class Program
{
static void Main(string[] args)
{
bool run = true;
while (run == true)
{
Console.WriteLine("Welcome to PIGLATIN Translator!");
Console.WriteLine("Enter a line to be translated");
var inputLine = Console.ReadLine().ToLower();// Converts user sentence to lower case
bool validationStatus = UserInputValidatinon(inputLine);
if (validationStatus == true)
{
string[] words = Split(inputLine);
Console.WriteLine("Pig Latin Translation is...");
MakePigLatin(words);
}
run = Continue();
}
}
public static bool UserInputValidatinon(string input)
{
try
{
if (string.IsNullOrWhiteSpace(input) || string.IsNullOrWhiteSpace(input))
{
Console.WriteLine("Please enter valid sentence to be translated.");
return false;
}
else
{
return true;
}
}
catch (Exception ex)
{
Console.WriteLine($"{ex.GetType() } means {ex.Message}");
return false;
}
}
public static string[] Split(string input)
{
//Takes input of string and splits them into separate words.
String[] Words = input.Split(' ');
return Words;
}
public static void MakePigLatin(string[] input)
{
string Addway = "way";
string Adday = "ay";
int wordLength = input.Length;
for (int i = 0; i < input.Length; i++)
{
try
{
int vowelPosition = VowelPosition(input[i]);
int numPosition = NumPosition(input[i]);
int puncPosition = PunctPosition(input[i]);
int specCharPosition = SpecialCharPosition(input[i]);
//Checks to see if first letter of a sentence starts with a vowel and translates to PigLatin.
if (vowelPosition == 0)
{
Console.Write(input[i] + Addway + " ");
}
//Checks if user entered sentence does not have a vowel and its length is one
else if (vowelPosition == -1 && wordLength == 1)
{
Console.Write(input[i] + " ");
}
// Checks if the sentnece has only consonants
else if (vowelPosition == -1 )
{
Console.Write(input[i] + " ");
}
//Does not translate sentence with numbers
else if( numPosition != -1)
{
Console.Write(input[i] + " ");
}
//Does not translate sentence with special characters
else if(specCharPosition!= -1)
{
Console.Write(input[i] + " ");
}
//Allows Punctuation
else if (puncPosition != -1)
{
Console.Write(input[i] + " ");
}
else
{
//Else the first word starts with a consonant.
var part1 = input[i].Substring(vowelPosition);// Takes remaining string after a vowel
var part2 = input[i].Substring(0, vowelPosition);// Takes string part until vowel
Console.Write(part1 + part2 + Adday + " "); // Joins them along with "ay" at the end
}
}
catch (Exception ex)
{
Console.WriteLine($"{ex.GetType().Name} means {ex.Message}");
}
}
}
public static int VowelPosition(string input)
{
char[] vowels = { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' };
int vowelPosition = input.IndexOfAny(vowels);
return vowelPosition;// Returns the current positon of vowel in a sentence
}
public static int NumPosition(string input)
{
char[] numbers = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
int numPosition = input.IndexOfAny(numbers);
return numPosition; // Returns the current positon of numbers in a sentence
}
public static int PunctPosition(string input)
{
char[] punctuation = new char[] { ',', ':', ';', '?', '!', '.' };
int puncPosition = input.IndexOfAny(punctuation);
return puncPosition; // Returns the current positon of punctuation in a sentence
}
public static int SpecialCharPosition(string input)
{
char[] specChar = new char[] { '@', '#', '$', '%', '^', '&', '*', '(', ')', '/', '[', ']' };
int specialCharPosition = input.IndexOfAny(specChar);
return specialCharPosition; // Returns the current positon of special characters in a sentence
}
public static bool IsVowel(string input)
{
char[] vowels = { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' };
for (int i = 0; i < input.Length; i++)
{
bool isVowel = vowels.Contains(input[i]);
return true;
}
return false;
}
public static bool Continue()
{
Console.WriteLine("Do you want to translate another line?(y/n)");
string input = Console.ReadLine();
input = input.ToLower();
bool goAhead;
if (input == "y")
{
goAhead = true;
}
else if (input == "n")
{
goAhead = false;
}
else
{
Console.WriteLine("I don't understand that, please try again");
goAhead = Continue();
}
return goAhead;
}
}
}
| 80602759fcb1e663d1f87813ed12097cb3cb7249 | [
"C#"
] | 1 | C# | tanvisathe/PigLatinTranslator | 58ba9c61a458a5da9f9b31015b88bb668c718d2a | 4812610da2bcab61ba82ef75aad80f63275acc59 |
refs/heads/master | <file_sep>#pragma once
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include <vector>
using namespace std;
using namespace cv;
namespace fld
{
class CLineDetect
{
public:
CLineDetect();
virtual ~CLineDetect();
public:
int Process(const Mat &img_gray, vector<Vec4f> &lines);
};
}
<file_sep>#include "stdafx.h"
#include <algorithm>
#include "FrameLineSelect.h"
#include "LineTools.h"
using namespace fld;
using namespace std;
int g_nWPt2Line = 1, g_nWPt2Pt = 5, g_nWAngle = 1;
const int MAX_OFFSET_ANGLE = 5;
const int MIN_LINE_LEN = 100;
CFrameLineSelect::CFrameLineSelect()
{
}
CFrameLineSelect::~CFrameLineSelect()
{
}
int CFrameLineSelect::Process(const Mat &img_gray, vector<Vec4f> &lines, FrameLineNode &frameLine, const int &nWidth, const int &nHeight, const int Param)
{
int nRet = 0;
m_nImgWidth = nWidth;
m_nImgHeight = nHeight;
vector<LineNode> linesHor, linesVer;
ClassifyAndMarkLines(lines, linesHor, linesVer);
sort(linesHor.begin(), linesHor.end(), CmpLine_Hor);
sort(linesVer.begin(), linesVer.end(), CmpLine_Ver);
LinkLineHor(linesHor);
LinkLineVer(linesVer);
MergeLineHor(linesHor);
MergeLineVer(linesVer);
sort(linesHor.begin(), linesHor.end(), CmpLine_Hor);
sort(linesVer.begin(), linesVer.end(), CmpLine_Ver);
#ifdef _DEBUG
Scalar arrScalar[3] = { Scalar(255, 0, 0) , Scalar(0, 255, 0) , Scalar(0, 0, 255) };
imwrite("../log_img/img_gray_forfld.jpg", img_gray);
Mat img_forTest(img_gray);
cvtColor(img_forTest, img_forTest, CV_GRAY2BGR);
vector<LineNode> linesForDebug;
linesForDebug.insert(linesForDebug.end(), linesHor.begin(), linesHor.end());
linesForDebug.insert(linesForDebug.end(), linesVer.begin(), linesVer.end());
for (int i =0; i <linesForDebug.size(); i++)
{
line(img_forTest, linesForDebug[i].start, linesForDebug[i].end, arrScalar[i%3]);
}
imshow("link the lines", img_forTest);
waitKey(500);
imwrite("../log_img/linesLink_lsd.jpg", img_forTest);
#endif
frameLine.m_vecLinesHor = linesHor;
frameLine.m_vecLinesVer = linesVer;
if (!SelectOptimalLine(img_gray, frameLine))
{
return 1;
}
if (Param == DOC_TYPE_BussinessLicense)
{
AdjustFrameLine(frameLine);
}
return nRet;
}
//************************************
// Method: AdjustFrameLine
// Description: 由于存在多个框线 所以需要挑选框线
// Access: private
// Returns: void
// Qualifier:
// Parameter: FrameLineNode & frameLine
//************************************
void CFrameLineSelect::AdjustFrameLine(FrameLineNode &frameLine)
{
const int nThDstX_AdjustLine = 100;
const int nThDstY_AdjustLine = 150;
const int nThAngle_AdjustLine = 6;
const int nThLenRatioLimit = 2;
vector<LineNode> &vecLinesHor = frameLine.m_vecLinesHor;
vector<LineNode> &vecLinesVer = frameLine.m_vecLinesVer;
int &nIdLeft = frameLine.nIdLeft;
int &nIdTop = frameLine.nIdTop;
int &nIdRight = frameLine.nIdRight;
int &nIdBottom = frameLine.nIdBottom;
// ver
for (int i =nIdLeft+1; i<vecLinesVer.size(); i++)
{
if (vecLinesVer[i].nLength * nThLenRatioLimit > vecLinesVer[nIdLeft].nLength &&
vecLinesVer[i].center.x < m_nImgWidth/2 - 10 &&
abs(vecLinesVer[nIdLeft].center.x - vecLinesVer[i].center.x) < nThDstX_AdjustLine &&
(abs(vecLinesVer[nIdLeft].angle % 180 - vecLinesVer[i].angle % 180) < nThAngle_AdjustLine ||
abs(vecLinesVer[nIdLeft].angle % 180 - vecLinesVer[i].angle % 180) > 180 - nThAngle_AdjustLine))
{
nIdLeft = i;
}
}
for (int i = nIdRight - 1; i > 0; i--)
{
if (vecLinesVer[i].nLength * nThLenRatioLimit > vecLinesVer[nIdRight].nLength &&
vecLinesVer[i].center.x > m_nImgWidth / 2 + 10 &&
abs(vecLinesVer[nIdRight].center.x - vecLinesVer[i].center.x) < nThDstX_AdjustLine &&
(abs(vecLinesVer[nIdRight].angle % 180 - vecLinesVer[i].angle % 180) < nThAngle_AdjustLine ||
abs(vecLinesVer[nIdRight].angle % 180 - vecLinesVer[i].angle % 180) > 180 - nThAngle_AdjustLine))
{
nIdRight = i;
}
}
// hor
for (int i = nIdTop + 1; i < vecLinesHor.size(); i++)
{
if (vecLinesHor[i].nLength * nThLenRatioLimit > vecLinesHor[nIdTop].nLength &&
vecLinesHor[i].center.y < m_nImgHeight / 2 - 10 &&
abs(vecLinesHor[nIdTop].center.y - vecLinesHor[i].center.y) < nThDstY_AdjustLine &&
(abs(vecLinesHor[nIdTop].angle % 180 - vecLinesHor[i].angle % 180) < nThAngle_AdjustLine ||
abs(vecLinesHor[nIdTop].angle % 180 - vecLinesHor[i].angle % 180) > 180 - nThAngle_AdjustLine))
{
nIdTop = i;
}
}
for (int i = nIdBottom - 1; i > 0; i--)
{
if (vecLinesHor[i].nLength * nThLenRatioLimit > vecLinesHor[nIdBottom].nLength &&
vecLinesHor[i].center.y > m_nImgHeight / 2 + 10 &&
abs(vecLinesHor[nIdBottom].center.y - vecLinesHor[i].center.y) < nThDstY_AdjustLine &&
(abs(vecLinesHor[nIdBottom].angle % 180 - vecLinesHor[i].angle % 180) < nThAngle_AdjustLine ||
abs(vecLinesHor[nIdBottom].angle % 180 - vecLinesHor[i].angle % 180) > 180 - nThAngle_AdjustLine))
{
nIdBottom= i;
}
}
}
void CFrameLineSelect::LinkLineHor(vector<LineNode> &lines)
{
int nSize = lines.size();
int *pFlag = new int[nSize];
const int MAX_LINE_GAP = 20;
const int MAX_OFFSETY = 5;
vector<LineNode> vecLines;
memset(pFlag, 0, sizeof(int)* nSize);
for (int i = 0; i < lines.size(); i++)
{
if (pFlag[i] == 1) continue;
pFlag[i] = 1;
bool bFlagMerged = true;
int nCurrDirect = lines[i].nDirect;
// 沿着结束点方向查找 扩展直线结束方向
Point2f pt_end = lines[i].end;
while (bFlagMerged)
{
bFlagMerged = false;
int min_hor_dist = 65535;
int min_index = -1;
for (int j = 0; j < lines.size(); j++)
{
if (pFlag[j] == 1) continue;
LineNode line = lines[j];
Point2f next_start = lines[j].start;
int line2lineAngleDis = abs(lines[j].angle % 180 - lines[i].angle % 180) % 180;
if (fabs(next_start.y - pt_end.y) < MAX_OFFSETY &&
(line2lineAngleDis <= MAX_OFFSET_ANGLE || line2lineAngleDis >= 180 - MAX_OFFSET_ANGLE))
{
int hor_dist = next_start.x - pt_end.x;
if (hor_dist >= -5 && hor_dist < min_hor_dist)
{
min_hor_dist = hor_dist;
min_index = j;
}
}
}
if (min_index != -1 && min_hor_dist < MAX_LINE_GAP)
{
pt_end = lines[min_index].end;
pFlag[min_index] = 1;
bFlagMerged = true;
}
}
// 沿着开始点方向查找 扩展直线开始方向
bFlagMerged = true;
Point2f pt_start = lines[i].start;
while (bFlagMerged)
{
bFlagMerged = false;
int min_hor_dist = 65535;
int min_index = -1;
for (int j = 0; j < lines.size(); j++)
{
if (pFlag[j] == 1) continue;
LineNode line = lines[j];
Point2f pre_end = lines[j].end;
int line2lineAngleDis = abs(lines[j].angle % 180 - lines[i].angle % 180) % 180;
if (fabs(pre_end.y - pt_start.y) < MAX_OFFSETY &&
(line2lineAngleDis <= MAX_OFFSET_ANGLE || line2lineAngleDis >= 180 - MAX_OFFSET_ANGLE))
{
int hor_dist = abs(pt_start.x - pre_end.x);
if (hor_dist <=5 && hor_dist < min_hor_dist)
{
min_hor_dist = hor_dist;
min_index = j;
}
}
}
if (min_index != -1 && min_hor_dist < MAX_LINE_GAP)
{
pt_start = lines[min_index].start;
pFlag[min_index] = 1;
bFlagMerged = true;
}
}
LineNode merged_line;
merged_line.angle = lines[i].angle;
merged_line.start = pt_start;
merged_line.end = pt_end;
merged_line.center.x = (merged_line.start.x + merged_line.end.x) / 2;
merged_line.center.y = (merged_line.start.y + merged_line.end.y) / 2;
int tx = fabs(merged_line.start.x - merged_line.end.x);
int ty = fabs(merged_line.start.y - merged_line.end.y);
long tLength = tx*tx + ty*ty;
merged_line.nLength = tLength;
merged_line.nDirect = nCurrDirect;
if (CLineTools::GetDistance(pt_start, pt_end) > MIN_LINE_LEN)
vecLines.push_back(merged_line);
}
lines.clear();
lines = vecLines;
delete[] pFlag; pFlag = NULL;
}
void CFrameLineSelect::LinkLineVer(vector<LineNode> &lines)
{
int nSize = lines.size();
int *pFlag = new int[nSize];
const int MAX_LINE_GAP = 20;
const int MAX_OFFSETY = 5;
vector<LineNode> vecLines;
memset(pFlag, 0, sizeof(int)* nSize);
for (int i = 0; i < lines.size(); i++)
{
if (pFlag[i] == 1) continue;
pFlag[i] = 1;
bool bFlagMerged = true;
int nCurrDirect = lines[i].nDirect;
// 沿着结束点方向查找 扩展直线结束方向
Point2f pt_end = lines[i].end;
while (bFlagMerged)
{
bFlagMerged = false;
int min_hor_dist = 65535;
int min_index = -1;
for (int j = 0; j < lines.size(); j++)
{
if (pFlag[j] == 1) continue;
LineNode line = lines[j];
Point2f next_start = lines[j].start;
int line2lineAngleDis = abs(lines[j].angle % 180 - lines[i].angle % 180) % 180;
if (fabs(next_start.x - pt_end.x) < MAX_OFFSETY &&
(line2lineAngleDis <= MAX_OFFSET_ANGLE || line2lineAngleDis >= 180 - MAX_OFFSET_ANGLE))
{
int hor_dist = next_start.y - pt_end.y;
if (hor_dist >= -5 && hor_dist < min_hor_dist)
{
min_hor_dist = hor_dist;
min_index = j;
}
}
}
if (min_index != -1 && min_hor_dist < MAX_LINE_GAP)
{
pt_end = lines[min_index].end;
pFlag[min_index] = 1;
bFlagMerged = true;
}
}
// 沿着开始点方向查找 扩展直线开始方向
bFlagMerged = true;
Point2f pt_start = lines[i].start;
while (bFlagMerged)
{
bFlagMerged = false;
int min_hor_dist = 65535;
int min_index = -1;
for (int j = 0; j < lines.size(); j++)
{
if (pFlag[j] == 1) continue;
LineNode line = lines[j];
Point2f pre_end = lines[j].end;
int line2lineAngleDis = abs(lines[j].angle % 180 - lines[i].angle % 180) % 180;
if (fabs(pre_end.x - pt_start.x) < MAX_OFFSETY &&
(line2lineAngleDis <= MAX_OFFSET_ANGLE || line2lineAngleDis >= 180 - MAX_OFFSET_ANGLE))
{
int hor_dist = pt_start.y - pre_end.y;
if (hor_dist >= -5 && hor_dist < min_hor_dist)
{
min_hor_dist = hor_dist;
min_index = j;
}
}
}
if (min_index != -1 && min_hor_dist < MAX_LINE_GAP)
{
pt_start = lines[min_index].start;
pFlag[min_index] = 1;
bFlagMerged = true;
}
}
LineNode merged_line;
merged_line.angle = lines[i].angle;
merged_line.start = pt_start;
merged_line.end = pt_end;
merged_line.center.x = (merged_line.start.x + merged_line.end.x) / 2;
merged_line.center.y = (merged_line.start.y + merged_line.end.y) / 2;
int tx = fabs(merged_line.start.x - merged_line.end.x);
int ty = fabs(merged_line.start.y - merged_line.end.y);
long tLength = tx*tx + ty*ty;
merged_line.nLength = tLength;
merged_line.nDirect = nCurrDirect;
if (CLineTools::GetDistance(pt_start, pt_end) > MIN_LINE_LEN)
vecLines.push_back(merged_line);
}
lines.clear();
lines = vecLines;
delete[] pFlag; pFlag = NULL;
}
void CFrameLineSelect::MergeLineHor(vector<LineNode> &lines)
{
int nSize = lines.size();
if (nSize < 3)
{
return;
}
const int MAX_LINE_GAP = 6;
bool bFlagMerged = true;
while (bFlagMerged)
{
bFlagMerged = false;
for (int i = 0; i < nSize; i++)
{
for (int j = 0; j < nSize; j++)
{
if (i == j) continue;
int line2lineAngleDis = abs(lines[j].angle % 180 - lines[i].angle % 180) % 180;
int line2lineLenDis = CLineTools::GetDistance(lines[i].center, lines[j]);
if ( (line2lineAngleDis <= MAX_OFFSET_ANGLE || line2lineAngleDis >= 180 - MAX_OFFSET_ANGLE) &&
line2lineLenDis < MAX_LINE_GAP)
{
// merge line
bFlagMerged = true;
lines[i].start = lines[i].start.x > lines[j].start.x ? lines[j].start : lines[i].start;
lines[i].end = lines[i].end.x > lines[j].end.x ? lines[i].end : lines[j].end;
lines[i].center.x = (lines[i].start.x + lines[i].end.x) / 2;
lines[i].center.y = (lines[i].start.y + lines[i].end.y) / 2;
int tx = fabs(lines[i].start.x - lines[i].end.x);
int ty = fabs(lines[i].start.y - lines[i].end.y);
long tLength = tx*tx + ty*ty;
lines[i].nLength = tLength;
lines[j] = lines[nSize - 1];
nSize--;
}
}
}
}
lines.erase(lines.begin() + nSize, lines.end());
}
void CFrameLineSelect::MergeLineVer(vector<LineNode> &lines)
{
int nSize = lines.size();
if (nSize < 3)
{
return;
}
const int MAX_LINE_GAP = 6;
bool bFlagMerged = true;
while (bFlagMerged)
{
bFlagMerged = false;
for (int i = 0; i < nSize; i++)
{
for (int j = 0; j < nSize; j++)
{
if (i == j) continue;
int line2lineAngleDis = abs(lines[j].angle % 180 - lines[i].angle % 180) % 180;
int line2lineLenDis = CLineTools::GetDistance(lines[i].center, lines[j]);
if ((line2lineAngleDis <= MAX_OFFSET_ANGLE || line2lineAngleDis >= 180 - MAX_OFFSET_ANGLE) &&
line2lineLenDis < MAX_LINE_GAP)
{
// merge line
bFlagMerged = true;
lines[i].start = lines[i].start.y > lines[j].start.y ? lines[j].start : lines[i].start;
lines[i].end = lines[i].end.y > lines[j].end.y ? lines[i].end : lines[j].end;
lines[i].center.x = (lines[i].start.x + lines[i].end.x) / 2;
lines[i].center.y = (lines[i].start.y + lines[i].end.y) / 2;
int tx = fabs(lines[i].start.x - lines[i].end.x);
int ty = fabs(lines[i].start.y - lines[i].end.y);
long tLength = tx*tx + ty*ty;
lines[i].nLength = tLength;
lines[j] = lines[nSize - 1];
nSize--;
}
}
}
}
lines.erase(lines.begin() + nSize, lines.end());
}
//************************************
// Method: SelectOptimalLine
// Description: 寻找每一条直线的最优邻居
// Access: private
// Returns: void
// Qualifier:
// Parameter: FrameLineNode & frameLine
//************************************
bool CFrameLineSelect::SelectOptimalLine(const Mat &img_gray, FrameLineNode &frameLine)
{
bool bRet =true;
vector<LineNode> &vecLinesHor = frameLine.m_vecLinesHor;
vector<LineNode> &vecLinesVer = frameLine.m_vecLinesVer;
FindLinesNeighbor(vecLinesHor, vecLinesVer);
bRet = CreateFrameLineByNeighbor(img_gray, frameLine);
return bRet;
}
void CFrameLineSelect::FindLinesNeighbor(vector<LineNode> &vecLinesHor, vector<LineNode> &vecLinesVer)
{
for (int i =0; i<vecLinesHor.size(); i++)
{
FindLineNeighbor(vecLinesHor[i], vecLinesVer);
}
for (int i =0; i<vecLinesVer.size(); i++)
{
FindLineNeighbor(vecLinesVer[i], vecLinesHor);
}
}
void CFrameLineSelect::FindLineNeighbor(LineNode &line, vector<LineNode> &vecLines)
{
// line开始点
int nMaxScore = -1;
int nMaxId = -1;
for (int i = 0; i < vecLines.size(); i++)
{
if (IsValidLine(line, 1, vecLines[i]));
{
int nScore = CalcLine2LineScore(line, 1, vecLines[i]);
if (nScore > nMaxScore)
{
nMaxScore = nScore;
nMaxId = i;
}
}
}
line.neighbor.nStartId = nMaxId;
line.neighbor.nStartScore = nMaxScore;
// line结束点
nMaxScore = -1;
nMaxId = -1;
for (int i = 0; i < vecLines.size(); i++)
{
if (IsValidLine(line, 0, vecLines[i]));
{
int nScore = CalcLine2LineScore(line, 0, vecLines[i]);
if (nScore > nMaxScore)
{
nMaxScore = nScore;
nMaxId = i;
}
}
}
line.neighbor.nEndId = nMaxId;
line.neighbor.nEndScore = nMaxScore;
}
bool CFrameLineSelect::CreateFrameLineByNeighbor(const Mat &img_gray, FrameLineNode &frameLine)
{
vector<LineNode> &vecLinesHor = frameLine.m_vecLinesHor;
vector<LineNode> &vecLinesVer = frameLine.m_vecLinesVer;
for (int i =0; i<vecLinesHor.size();i++)
{
LineNode line = vecLinesHor[i];
FrameLineQuadrangle tQuad;
if (line.nDirect == 1)
{
if (line.neighbor.nEndId !=-1 && line.neighbor.nStartId != -1 &&
i == vecLinesVer[line.neighbor.nEndId].neighbor.nStartId &&
i == vecLinesVer[line.neighbor.nStartId].neighbor.nStartId)
{
tQuad.nIdTop = i;
tQuad.nIdLeft = line.neighbor.nStartId;
tQuad.nIdRight = line.neighbor.nEndId;
LineNode lineLeftVer = vecLinesVer[line.neighbor.nStartId];
LineNode lineRightVer = vecLinesVer[line.neighbor.nEndId];
if (lineLeftVer.neighbor.nEndId !=-1 && lineRightVer.neighbor.nEndId !=-1)
{
tQuad.nIdBottom = lineLeftVer.neighbor.nEndScore > lineRightVer.neighbor.nEndScore ? lineLeftVer.neighbor.nEndId : lineRightVer.neighbor.nEndId;
m_vecQuad.push_back(tQuad);
}
else if (lineLeftVer.neighbor.nEndId != -1 || lineRightVer.neighbor.nEndId != -1)
{
tQuad.nIdBottom = lineLeftVer.neighbor.nEndId != -1 ? lineLeftVer.neighbor.nEndId : lineRightVer.neighbor.nEndId;
m_vecQuad.push_back(tQuad);
}
}
}
else if (line.nDirect == 3)
{
if (line.neighbor.nEndId != -1 && line.neighbor.nStartId != -1 &&
i == vecLinesVer[line.neighbor.nEndId].neighbor.nEndId &&
i == vecLinesVer[line.neighbor.nStartId].neighbor.nEndId)
{
tQuad.nIdBottom = i;
tQuad.nIdLeft = line.neighbor.nStartId;
tQuad.nIdRight = line.neighbor.nEndId;
LineNode lineLeftVer = vecLinesVer[line.neighbor.nStartId];
LineNode lineRightVer = vecLinesVer[line.neighbor.nEndId];
if (lineLeftVer.neighbor.nStartId != -1 && lineRightVer.neighbor.nStartId != -1)
{
tQuad.nIdTop = lineLeftVer.neighbor.nStartScore > lineRightVer.neighbor.nStartScore ? lineLeftVer.neighbor.nStartId : lineRightVer.neighbor.nStartId;
m_vecQuad.push_back(tQuad);
}
else if (lineLeftVer.neighbor.nStartId != -1 || lineRightVer.neighbor.nStartId != -1)
{
tQuad.nIdTop = lineLeftVer.neighbor.nStartId != -1 ? lineLeftVer.neighbor.nStartId : lineRightVer.neighbor.nStartId;
m_vecQuad.push_back(tQuad);
}
}
}
}
for (int i = 0; i < vecLinesVer.size();i++)
{
LineNode line = vecLinesVer[i];
FrameLineQuadrangle tQuad;
if (line.nDirect == 0)
{
if (line.neighbor.nEndId != -1 && line.neighbor.nStartId != -1 &&
i == vecLinesHor[line.neighbor.nEndId].neighbor.nStartId &&
i == vecLinesHor[line.neighbor.nStartId].neighbor.nStartId)
{
tQuad.nIdLeft = i;
tQuad.nIdTop = line.neighbor.nStartId;
tQuad.nIdBottom = line.neighbor.nEndId;
LineNode lineTopHor = vecLinesHor[line.neighbor.nStartId];
LineNode lineBottomHor = vecLinesHor[line.neighbor.nEndId];
if (lineTopHor.neighbor.nEndId != -1 && lineBottomHor.neighbor.nEndId != -1)
{
tQuad.nIdRight = lineTopHor.neighbor.nEndScore > lineBottomHor.neighbor.nEndScore ? lineTopHor.neighbor.nEndId : lineBottomHor.neighbor.nEndId;
m_vecQuad.push_back(tQuad);
}
else if (lineTopHor.neighbor.nEndId != -1 || lineBottomHor.neighbor.nEndId != -1)
{
tQuad.nIdRight = lineTopHor.neighbor.nEndId != -1 ? lineTopHor.neighbor.nEndId : lineBottomHor.neighbor.nEndId;
m_vecQuad.push_back(tQuad);
}
}
}
else if (line.nDirect == 2)
{
if (line.neighbor.nEndId != -1 && line.neighbor.nStartId != -1 &&
i == vecLinesHor[line.neighbor.nEndId].neighbor.nEndId &&
i == vecLinesHor[line.neighbor.nStartId].neighbor.nEndId)
{
tQuad.nIdRight = i;
tQuad.nIdTop = line.neighbor.nStartId;
tQuad.nIdBottom = line.neighbor.nEndId;
LineNode lineTopHor = vecLinesHor[line.neighbor.nStartId];
LineNode lineBottomHor = vecLinesHor[line.neighbor.nEndId];
if (lineTopHor.neighbor.nStartId != -1 && lineBottomHor.neighbor.nStartId != -1)
{
tQuad.nIdLeft = lineTopHor.neighbor.nStartScore > lineBottomHor.neighbor.nStartScore ? lineTopHor.neighbor.nStartId : lineBottomHor.neighbor.nStartId;
m_vecQuad.push_back(tQuad);
}
else if (lineTopHor.neighbor.nStartId != -1 || lineBottomHor.neighbor.nStartId != -1)
{
tQuad.nIdLeft = lineTopHor.neighbor.nStartId != -1 ? lineTopHor.neighbor.nStartId : lineBottomHor.neighbor.nStartId;
m_vecQuad.push_back(tQuad);
}
}
}
}
#ifdef _DEBUG
Mat img_forTest(img_gray);
cvtColor(img_forTest, img_forTest, COLOR_GRAY2BGR);
Scalar arrScalar[3] = { Scalar(255, 0, 0) , Scalar(0, 255, 0) , Scalar(0, 0, 255) };
for (int i = 0; i < m_vecQuad.size(); i++)
{
Point2f lt, tr, rb, bl;
lt = CLineTools::GetCrossPoint(frameLine.m_vecLinesVer[m_vecQuad[i].nIdLeft], frameLine.m_vecLinesHor[m_vecQuad[i].nIdTop]);
tr = CLineTools::GetCrossPoint(frameLine.m_vecLinesHor[m_vecQuad[i].nIdTop], frameLine.m_vecLinesVer[m_vecQuad[i].nIdRight]);
rb = CLineTools::GetCrossPoint(frameLine.m_vecLinesVer[m_vecQuad[i].nIdRight], frameLine.m_vecLinesHor[m_vecQuad[i].nIdBottom]);
bl = CLineTools::GetCrossPoint(frameLine.m_vecLinesHor[m_vecQuad[i].nIdBottom], frameLine.m_vecLinesVer[m_vecQuad[i].nIdLeft]);
line(img_forTest, lt, tr, arrScalar[i % 3]);
line(img_forTest, tr, rb, arrScalar[i % 3]);
line(img_forTest, rb, bl, arrScalar[i % 3]);
line(img_forTest, bl, lt, arrScalar[i % 3]);
}
imshow("link the lines", img_forTest);
waitKey(500);
imwrite("../log_img/framelinesets.jpg", img_forTest);
#endif
int nId = SelectFrameLineFromQuadSet(frameLine, m_vecQuad);
if (nId >=0)
{
frameLine.nIdLeft = m_vecQuad[nId].nIdLeft;
frameLine.nIdTop = m_vecQuad[nId].nIdTop;
frameLine.nIdRight = m_vecQuad[nId].nIdRight;
frameLine.nIdBottom = m_vecQuad[nId].nIdBottom;
return true;
}
else
{
frameLine.nIdLeft = -1;
frameLine.nIdTop = -1;
frameLine.nIdRight = -1;
frameLine.nIdBottom = -1;
return false;
}
return false;
}
int CFrameLineSelect::SelectFrameLineFromQuadSet(FrameLineNode &frameLine, const vector<FrameLineQuadrangle> &vecQuad)
{
vector<LineNode> &vecLinesHor = frameLine.m_vecLinesHor;
vector<LineNode> &vecLinesVer = frameLine.m_vecLinesVer;
const int nThArea = m_nImgHeight*m_nImgWidth >> 2;
int nMaxArea = -1;
int nMaxAreaId = -1;
for (int i =0; i<vecQuad.size(); i++)
{
if (IsValidQuadrangle(frameLine, vecQuad[i]))
{
Point2f lt, tr, rb, bl;
lt = CLineTools::GetCrossPoint(vecLinesVer[vecQuad[i].nIdLeft], vecLinesHor[vecQuad[i].nIdTop]);
tr = CLineTools::GetCrossPoint(vecLinesHor[vecQuad[i].nIdTop], vecLinesVer[vecQuad[i].nIdRight]);
rb = CLineTools::GetCrossPoint(vecLinesVer[vecQuad[i].nIdRight], vecLinesHor[vecQuad[i].nIdBottom]);
bl = CLineTools::GetCrossPoint(vecLinesHor[vecQuad[i].nIdBottom], vecLinesVer[vecQuad[i].nIdLeft]);
int nArea = CalcQuadrangleArea(lt, tr, rb, bl);
if (nArea >nThArea &&
nArea > nMaxArea)
{
nMaxArea = nArea;
nMaxAreaId = i;
}
}
}
return nMaxAreaId;
}
bool CFrameLineSelect::IsValidQuadrangle(const FrameLineNode &frameLine, const FrameLineQuadrangle &flQuad)
{
LineNode leftLine, topLine, rightLine, bottomLine;
leftLine = frameLine.m_vecLinesVer[flQuad.nIdLeft];
topLine = frameLine.m_vecLinesHor[flQuad.nIdTop];
rightLine = frameLine.m_vecLinesVer[flQuad.nIdRight];
bottomLine = frameLine.m_vecLinesHor[flQuad.nIdBottom];
const int nOverlop = 50;
if (leftLine.center.x - nOverlop <m_nImgWidth/2 &&
rightLine.center.x + nOverlop >m_nImgWidth/2 &&
topLine.center.y - nOverlop <m_nImgHeight/2 &&
bottomLine.center.y + nOverlop >m_nImgHeight/2)
{
return true;
}
return false;
}
//************************************
// Method: IsValidLine
// Description: 判断直线lina_a 的开始点或者结束点与直线Line_b的位置关系是否有效
// Access: private
// Returns: bool
// Qualifier:
// Parameter: const LineNode & line_a
// Parameter: bool IsBeginPoint
// Parameter: const LineNode & line_b
//************************************
bool CFrameLineSelect::IsValidLine(const LineNode &line_a, bool IsBeginPoint, const LineNode &line_b)
{
const int nOverlop = 5;
if (IsBeginPoint)
{
Point2f pt = line_a.start;
if (line_a.nDirect == 0)
{
if (pt.x - nOverlop < line_b.start.x &&
pt.y + nOverlop > line_b.start.y)
{
return true;
}
}
else if (line_a.nDirect == 1)
{
if (pt.x + nOverlop > line_b.start.x &&
pt.y - nOverlop < line_b.start.y)
{
return true;
}
}
else if (line_a.nDirect == 2)
{
if (pt.x + nOverlop > line_b.end.x &&
pt.y + nOverlop > line_b.end.y)
{
return true;
}
}
else if (line_a.nDirect == 3)
{
if (pt.x + nOverlop > line_b.end.x &&
pt.y + nOverlop > line_b.end.y)
{
return true;
}
}
}
else
{
Point2f pt = line_a.end;
if (line_a.nDirect == 0)
{
if (pt.x - nOverlop < line_b.start.x &&
pt.y - nOverlop < line_b.start.y)
{
return true;
}
}
else if (line_a.nDirect == 1)
{
if (pt.x - nOverlop < line_b.start.x &&
pt.y - nOverlop < line_b.start.y)
{
return true;
}
}
else if (line_a.nDirect == 2)
{
if (pt.x + nOverlop > line_b.end.x &&
pt.y - nOverlop < line_b.end.y)
{
return true;
}
}
else if (line_a.nDirect == 3)
{
if (pt.x - nOverlop < line_b.end.x &&
pt.y + nOverlop > line_b.end.y)
{
return true;
}
}
}
return false;
}
//************************************
// Method: CalcLine2LineScore
// Description: 计算直线 a 与 b 的得分,依据特征: 距离,角度
// Access: private
// Returns: int
// Qualifier:
// Parameter: const LineNode & line_a
// Parameter: bool IsBeginPoint
// Parameter: const LineNode & line_b
//************************************
int CFrameLineSelect::CalcLine2LineScore(const LineNode &line_a, bool IsBeginPoint, const LineNode &line_b)
{
int nScore =0;
int nDstPt2Line = 65535;
int nDstPt2Pt = 65535;
int nDisAngle = 360;
int nScorePt2Line = 0;
int nScorePt2Pt = 0;
int nScoreAngle = 0;
if (IsBeginPoint)
{
if (line_a.nDirect == 0 || line_a.nDirect == 1)
{
nDstPt2Pt = CLineTools::GetDistance(line_a.start, line_b.start);
}
else if (line_a.nDirect == 2 || line_a.nDirect == 3)
{
nDstPt2Pt = CLineTools::GetDistance(line_a.start, line_b.end);
}
nDstPt2Line = CLineTools::GetDistance(line_a.start, line_b);
}
else
{
if (line_a.nDirect == 0 || line_a.nDirect == 1)
{
nDstPt2Pt = CLineTools::GetDistance(line_a.end, line_b.start);
}
else if (line_a.nDirect == 2 || line_a.nDirect == 3)
{
nDstPt2Pt = CLineTools::GetDistance(line_a.end, line_b.end);
}
nDstPt2Line = CLineTools::GetDistance(line_a.end, line_b);
}
nDisAngle = abs(line_a.angle % 90 - line_b.angle % 90);
nScorePt2Line = nDstPt2Line==0 ? 100 : -nDstPt2Pt / 2 + 100;
nScorePt2Pt = nDstPt2Pt <=5 ? 100 : -nDstPt2Pt/2 +100;
nScoreAngle = nDisAngle == 0 ? 100 : (100 - nDisAngle);
nScorePt2Line = 0;
nScoreAngle = 0;
nScore = g_nWPt2Line*nScorePt2Line + g_nWPt2Pt*nScorePt2Pt + g_nWAngle*nScoreAngle;
return nScore;
}
void CFrameLineSelect::ClassifyAndMarkLines(vector<Vec4f> &lines, vector<LineNode> &linesHor, vector<LineNode> &linesVer)
{
const int nLop_Angle = 5;
for (int i = 0; i < lines.size(); i++)
{
LineNode line = LineNode(lines[i]);
CLineTools::CalcAngle(line);
int x1 = line.start.x;
int y1 = line.start.y;
int x2 = line.end.x;
int y2 = line.end.y;
int angle360 = line.angle;
if ((angle360 > 315 + nLop_Angle || angle360 < 45 - nLop_Angle) ||
(angle360 > 135 + nLop_Angle && angle360 < 225 - nLop_Angle))
{
if (x1 > x2)
{
line.start.x = x2;
line.start.y = y2;
line.end.x = x1;
line.end.y = y1;
}
line.center.y < m_nImgHeight / 2 ? line.nDirect = 1 : line.nDirect = 3;
linesHor.push_back(line);
}
if ((angle360 > 45 + nLop_Angle && angle360 < 135 - nLop_Angle) ||
(angle360 > 225 + nLop_Angle && angle360 < 315 - nLop_Angle))
{
if (y1 > y2)
{
line.start.x = x2;
line.start.y = y2;
line.end.x = x1;
line.end.y = y1;
}
line.center.x < m_nImgWidth / 2 ? line.nDirect = 0 : line.nDirect = 2;
linesVer.push_back(line);
}
}
}
bool CFrameLineSelect::CmpLine_Hor(const LineNode &line_a, const LineNode &line_b)
{
return line_a.center.y < line_b.center.y;
}
bool CFrameLineSelect::CmpLine_Ver(const LineNode &line_a, const LineNode &line_b)
{
return line_a.center.x < line_b.center.x;
}
int CFrameLineSelect::CalcQuadrangleArea(Point2f lt, Point2f tr, Point2f rb, Point2f bl)
{
int nArea = 0;
Point2f ptLT, ptRB;
ptLT.x = min(lt.x, bl.x);
ptLT.y = min(lt.y, tr.y);
ptRB.x = max(rb.x, tr.x);
ptRB.y = max(rb.y, bl.y);
nArea = abs(ptRB.x - ptLT.x)*abs(ptRB.y - ptLT.y);
return nArea;
}
<file_sep>#pragma once
#include <vector>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
enum DOC_TYPE {
DOC_TYPE_BussinessLicense = 0,
DOC_TYPE_ForeignersWorkPermit = 1,
DOC_TYPE_EmploymentPermit = 2,
DOC_TYPE_ExpertCertificate = 3,
DOC_TYPE_HouseholdRegister = 4,
DOC_TYPE_BussinessCard = 5,
};
// 直线邻居结构
struct LineNeighbor {
LineNeighbor() {
nStartId = -1;
nEndId = -1;
}
int nStartId;
int nStartScore;
int nEndId;
int nEndScore;
};
// 水平线 start 在左侧
// 垂直线 start 在上部
struct LineNode
{
LineNode() {
start = Point2f(0.0,0.0);
end = Point2f(0.0, 0.0);;
}
LineNode(Vec4f cvLine){
start = Point2f(cvLine[0], cvLine[1]);
end = Point2f(cvLine[2], cvLine[3]);
center.x = fabs(start.x + end.x) / 2;
center.y = fabs(start.y + end.y) / 2;
}
Point2f start;
Point2f end;
Point2f center;
int angle;
int nDirect; // 0,1,2,3, 左上右下
int nLength;
LineNeighbor neighbor;
};
// 框线信息
struct FrameLineNode
{
FrameLineNode()
{
nIdLeft = -1;
nIdTop = -1;
nIdRight = -1;
nIdBottom = -1;
};
vector<LineNode> m_vecLines;
vector<LineNode> m_vecLinesHor;
vector<LineNode> m_vecLinesVer;
// 框线在 m_vecLinesHor/ m_vecLinesVer 的id
int nIdLeft;
int nIdTop;
int nIdRight;
int nIdBottom;
};
// 框线四边在FrameLineNode:: m_vecLinesHor/m_vecLinesVer 的 Id
struct FrameLineQuadrangle
{
// 框线id
int nIdLeft;
int nIdTop;
int nIdRight;
int nIdBottom;
};
<file_sep>#include "stdafx.h"
#include "LineDetect.h"
#include "CommonDefines.h"
using namespace fld;
CLineDetect::CLineDetect()
{
}
CLineDetect::~CLineDetect()
{
}
int CLineDetect::Process(const Mat &img_gray, vector<Vec4f> &lines)
{
if (img_gray.empty())
{
return -1;
}
#if 1
Ptr<LineSegmentDetector> lsd = createLineSegmentDetector(LSD_REFINE_STD);
#else
Ptr<LineSegmentDetector> lsd = createLineSegmentDetector(LSD_REFINE_NONE);
#endif
lsd->detect(img_gray, lines);
#ifdef _DEBUG
// For Debug Show found lines
Mat drawnLines(img_gray);
lsd->drawSegments(drawnLines, lines);
imshow("Standard refinement", drawnLines);
waitKey(500);
imwrite("../log_img/lines_lsd.jpg", drawnLines);
#endif
return 0;
}
<file_sep>#pragma once
#include <opencv2/opencv.hpp>
#include "CommonDefines.h"
#include "Error_FLD.h"
using namespace cv;
namespace fld
{
class CFrameLineDetect
{
public:
CFrameLineDetect();
~CFrameLineDetect();
ERROR_FLD Process(const Mat &img, Mat &img_res, const int Param=0);
ERROR_FLD Process(const Mat &img, Point2f &ptLeftUp, Point2f &ptRightUp, Point2f &ptRightDown, Point2f &ptLeftDown, const int Param = 0);
private:
// 框线检测
int FrameLineDetect(const Mat &img_gray, FrameLineNode &frameLineNode, const int Param = 0);
// 图像矫正
void TransformImage(const Mat &img_src, Point2f srcImg_lt, Point2f srcImg_tr, Point2f srcImg_rb, Point2f srcImg_bl, Mat &img_res);
// 根据四个点估计原图像信息
void EstimateImageInfo(const Point2f &srcImg_lt, const Point2f &srcImg_tr, const Point2f & rcImg_rb, const Point2f &srcImg_bl,
int &dstImg_width, int &dstImg_height);
// 微调框线四个点
void AdjustCornerPoint(Point2f &Img_lt, Point2f &Img_tr, Point2f &Img_rb, Point2f &Img_bl);
// tools
//
void ConvertPtCoordinate(Point2f &pt, float scale_x, float scale_y) {
pt.x = pt.x * scale_x;
pt.y = pt.y * scale_y;
}
private:
const float m_fWHRatio_BussinessLicense;
// 框线检测时应用的图像信息
int m_nWidthForFLD;
int m_nHeightForFLD;
// 原图信息
int m_nSrcImgWidth;
int m_nSrcImgHeight;
};
}
<file_sep>#pragma once
#include "CommonDefines.h"
#include <opencv2/opencv.hpp>
using namespace cv;
namespace fld
{
class CLineTools
{
public:
CLineTools();
~CLineTools();
// ½Ç¶È
static void CalcAngle(LineNode &line);
// ¾àÀë
static int GetDistance(const Point2f &ptStart, const Point2f &ptEnd);
static int GetDistance(const Point2f &pt, const LineNode &line);
// ½»µã
static Point2f GetCrossPoint(LineNode line_a, LineNode line_b);
static Point2f GetCrossPoint(Point2f StPt1, Point2f EdPt1, Point2f StPt2, Point2f EdPt2);
};
}<file_sep>// Test.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include <gflags/gflags.h>
#include "../FrameLineDetect/FrameLineDetect.h"
using namespace cv;
using namespace std;
using namespace fld;
DEFINE_int32(doc_type, 0, "the input image type");
DEFINE_string(input_img, "", "the input image path");
DEFINE_string(output_img, "", "the output image path");
int main(int argc, char **argv)
{
int nRet = 0;
google::ParseCommandLineFlags(&argc, &argv, true);
//std::cout << "the input image path:" << FLAGS_input_img << std::endl;
//std::cout << "the output image path:" << FLAGS_output_img << std::endl;
// string in = "D:/datasets/bussinesscard/24.jpg";
Mat img_input = imread(FLAGS_input_img, IMREAD_COLOR);
if (img_input.empty())
{
nRet = -1;
}
else
{
Mat img_res;
CFrameLineDetect frameLineDetect;
nRet = frameLineDetect.Process(img_input, img_res, FLAGS_doc_type);
//Point2f ptLeftUp, ptRightUp, ptRightDown, ptLeftDown;
//nRet = frameLineDetect.Process(img_input, ptLeftUp, ptRightUp, ptRightDown, ptLeftDown, FLAGS_doc_type);
if (nRet == 0)
{
// 建立路径中不存在得文件夹
imwrite(FLAGS_output_img, img_res);
}
}
google::ShutDownCommandLineFlags();
return nRet;
}
<file_sep># -*- coding: utf-8 -*-
"""
Created on Wed May 10 11:19:46 2017
@author: jtcstc
"""
import os
root_path = os.getcwd()
exePath = root_path + "/"+ "./x86/Test.exe"
# -1: all, 0:营业执照, 1:外国人工作许可证, 2:就业证, 3:户口本, 4:身份证
doc_type = -1
img_dir_list = ["../sample/bussinesscard", "../sample/外国人工作许可证", "../sample/就业证", "../sample/户口本""]
img_res_dir_list = ["../result/bussinesscard", "../result/外国人工作许可证", "../result/就业证", "../result/户口本"]
def image_rectifying(img_dir, img_res_dir):
for dir, dirs, files in os.walk(img_dir):
for file in files:
fileInfo = os.path.splitext(file)
filename = fileInfo[0]
fileExt = fileInfo[1]
#print (filename)
#print (fileExt)
img_path = root_path + "/" + dir + "/" + file
img_res_path = root_path + "/" + img_res_dir + "/" + filename + "_res" + fileExt
#print (img_res_path)
cmdInfo = "%s --doc_type=%d --input_img=%s --output_img=%s" % (exePath, doc_type, img_path, img_res_path)
print (cmdInfo)
os.system(cmdInfo)
def image_rectifying_allclass(img_dir_list, img_res_dir_list):
for doc_type in range(len(img_dir_list)):
image_rectifying(img_dir_list[doc_type], img_res_dir_list[doc_type])
if __name__ == "__main__":
if doc_type == -1: # create all class
image_rectifying_allclass(img_dir_list, img_res_dir_list)
else: # create single class
image_rectifying(img_dir_list[doc_type], img_res_dir_list[doc_type])
<file_sep>#include "stdafx.h"
#include "LineTools.h"
using namespace fld;
CLineTools::CLineTools()
{
}
CLineTools::~CLineTools()
{
}
void CLineTools::CalcAngle(LineNode &line)
{
int x1 = line.start.x;
int y1 = line.start.y;
int x2 = line.end.x;
int y2 = line.end.y;
int angle360 = 0;
if (x1 == x2)
angle360 = y1 < y2 ? 270 : 90;
else
{
if (y1 == y2)
angle360 = x1 < x2 ? 0 : 180;
else
{
float dy = y2 - y1;
float dx = x2 - x1;
float absangle = atan(fabs(dy) / fabs(dx)) / 3.1415926 * 180;
if (y2 > y1 && x2 > x1)
angle360 = 360 - absangle;
if (y2 < y1 && x2 > x1)
angle360 = absangle;
if (y2 > y1 && x2 < x1)
angle360 = 180 + absangle;
if (y2 < y1 && x2 < x1)
angle360 = 180 - absangle;
}
}
line.angle = angle360;
}
int CLineTools::GetDistance(const Point2f &ptStart, const Point2f &ptEnd)
{
return sqrtf((ptEnd.x - ptStart.x)*(ptEnd.x - ptStart.x) +
(ptEnd.y - ptStart.y)*(ptEnd.y - ptStart.y));
}
int CLineTools::GetDistance(const Point2f &pt, const LineNode &line)
{
Point2f ptStart = line.start;
Point2f ptEnd = line.end;
int dx = ptEnd.x - ptStart.x;
int dy = ptEnd.y - ptStart.y;
if (dx == 0)
return abs(pt.x - ptStart.x);
if (dy == 0)
return abs(pt.y - ptStart.y);
int distance = abs(pt.y*dx - dy*pt.x + dy*ptStart.x - ptStart.y*dx)*1.0 / (sqrtf(dx*dx + dy*dy));
return distance;
}
Point2f CLineTools::GetCrossPoint(LineNode line_a, LineNode line_b)
{
return GetCrossPoint(line_a.start, line_a.end, line_b.start, line_b.end);
}
Point2f CLineTools::GetCrossPoint(Point2f StPt1, Point2f EdPt1, Point2f StPt2, Point2f EdPt2)
{
Point2f CrossPnt;
CrossPnt.x = -1;
CrossPnt.y = -1;
double dx, _dx, dy, _dy, x, y;
dx = EdPt1.x - StPt1.x;
dy = EdPt1.y - StPt1.y;
_dx = EdPt2.x - StPt2.x;
_dy = EdPt2.y - StPt2.y;
if (_dx*dy == dx*_dy && _dx*dy != 0) return CrossPnt;
if (dx == 0)
{
x = StPt1.x;
y = StPt2.y + (StPt1.x - StPt2.x)*_dy / _dx;
}
else
{
x = (dx*_dx*(StPt2.y - StPt1.y) - dx*_dy*StPt2.x + _dx*dy*StPt1.x) / (_dx*dy - dx*_dy);
y = (dy*(x - StPt1.x) + StPt1.y*dx) / dx;
}
CrossPnt.x = (x); CrossPnt.y = (y);
return CrossPnt;
}<file_sep>#pragma once
enum ERROR_FLD
{
ERROR_NO =0,
ERROR_NO_FRAMELINE =1,
ERROR_IMAGE_INPUT =2,
ERROR_PARAM_INPUT =3,
}; <file_sep>#pragma once
#include "CommonDefines.h"
#include <vector>
using namespace std;
namespace fld
{
class CFrameLineSelect
{
public:
CFrameLineSelect();
virtual ~CFrameLineSelect();
public:
int Process(const Mat &img_gray, vector<Vec4f> &lines, FrameLineNode &frameLine, const int &nWidth, const int &nHeight, const int Param = 0);
private:
bool SelectOptimalLine(const Mat &img_gray, FrameLineNode &frameLine);
// 找线段集合的邻居
void FindLinesNeighbor(vector<LineNode> &vecLinesHor, vector<LineNode> &vecLinesVer);
void FindLineNeighbor(LineNode &line, vector<LineNode> &vecLines);
// 根据每条线段与他的邻居生成框线
bool CreateFrameLineByNeighbor(const Mat &img_gray, FrameLineNode &frameLine);
// 根据规则从框线集合vecQuad中挑选最优框线
int SelectFrameLineFromQuadSet(FrameLineNode &frameLine, const vector<FrameLineQuadrangle> &vecQuad);
// 判断四边形是否有效
bool IsValidQuadrangle(const FrameLineNode &frameLine, const FrameLineQuadrangle &flQuad);
// 判断line_b相对line_a的开始或者结束点是否有效
bool IsValidLine(const LineNode &line_a, bool IsBeginPoint, const LineNode &line_b);
// 计算两条直线得分
int CalcLine2LineScore(const LineNode &line_a, bool IsBeginPoint, const LineNode &line_b);
// 对检测出的框线进行微调以使用不同类型图像
void AdjustFrameLine(FrameLineNode &frameLine);
// 连接与合并直线
void LinkLineHor(vector<LineNode> &lines);
void LinkLineVer(vector<LineNode> &lines);
void MergeLineHor(vector<LineNode> &lines);
void MergeLineVer(vector<LineNode> &lines);
// 标记直线信息
void ClassifyAndMarkLines(vector<Vec4f> &lines, vector<LineNode> &linesHor, vector<LineNode> &linesVer);
static bool CmpLine_Hor(const LineNode &line_a, const LineNode &line_b);
static bool CmpLine_Ver(const LineNode &line_a, const LineNode &line_b);
//tools
// 计算四个点的外接矩形面积
int CalcQuadrangleArea(Point2f lt, Point2f tr, Point2f rb, Point2f bl);
private:
int m_nImgWidth;
int m_nImgHeight;
vector<FrameLineQuadrangle> m_vecQuad;
};
}<file_sep>========================================================================
静态库:FrameLineDetect 项目概述
========================================================================
应用程序向导已为您创建了此 FrameLineDetect 库项目。
本文件概要介绍组成 FrameLineDetect 应用程序的每个文件的内容。
FrameLineDetect.vcxproj
这是使用应用程序向导生成的 VC++ 项目的主项目文件,其中包含生成该文件的 Visual C++ 的版本信息,以及有关使用应用程序向导选择的平台、配置和项目功能的信息。
FrameLineDetect.vcxproj.filters
这是使用“应用程序向导”生成的 VC++ 项目筛选器文件。它包含有关项目文件与筛选器之间的关联信息。在 IDE 中,通过这种关联,在特定节点下以分组形式显示具有相似扩展名的文件。例如,“.cpp”文件与“源文件”筛选器关联。
/////////////////////////////////////////////////////////////////////////////
StdAfx.h, StdAfx.cpp
这些文件用于生成名为 FrameLineDetect.pch 的预编译头 (PCH) 文件和名为 StdAfx.obj 的预编译类型文件。
/////////////////////////////////////////////////////////////////////////////
其他注释:
应用程序向导使用“TODO:”注释来指示应添加或自定义的源代码部分。
/////////////////////////////////////////////////////////////////////////////
| 7e3c3fe115a16929fde3824c56408b08eb214424 | [
"C",
"Python",
"Text",
"C++"
] | 12 | C++ | jtcjump/framelinedetect | c36eee260cfae4e6d53ca7b33cd0835d80ea6ca4 | 9ae82853adf9a7c50313c64c7789bec9ec336c15 |
refs/heads/master | <repo_name>papico328/calendar<file_sep>/test.js
// html用の変数
var $window = $(window),
$year = $('#js-year'),
$month = $('#js-month'),
$day = $('#js-day'),
$tbody = $('#js-calendar-body'),
$thead = $('#js-calendar-head');
// 今日の年月日と曜日を取得する
var today = new Date()
date = today.getDate(),
// console.log(today);
// console.log(date);
currentYear = today.getFullYear(),
currentMonth = today.getMonth(),
dayOfWeekStrJP = [ "日", "月", "火", "水", "木", "金", "土" ] ,
currentDay = dayOfWeekStrJP[today.getDay()];
// 今年、今月のカレンダーを表示する
$window.on('load',function(){
calendarTitle(currentYear, currentMonth);
calendarHeading();
calendarBody(currentYear, currentMonth);
});
// 二つの引数を変えるとその月日のカレンダーが取得できる
// (例:currentYear = 1991,currentMonth =3)
// カレンダーの年と月
function calendarTitle(year, month){
$year.text(year);
// console.log($year.text(year));
$month.text(month + 1);
}
// 前月のカレンダー
document.getElementById("minus").onclick = function countDown(){
if(currentMonth == 0){
currentYear = currentYear - 1;
currentMonth += 11;
// 月は0から始まるので1月は0,12月は11
calendarTitle(currentYear, currentMonth);
calendarBody(currentYear,currentMonth);
}
else{
currentMonth = currentMonth - 1;
calendarTitle(currentYear, currentMonth);
calendarBody(currentYear,currentMonth);
}
console.log(currentMonth);
};
// 翌月のカレンダー
document.getElementById("plus").onclick = function countUp(){
console.log(currentMonth);
if(currentMonth == 11){
currentYear = currentYear + 1;
currentMonth -= 11;
calendarTitle(currentYear, currentMonth);
calendarBody(currentYear,currentMonth);
}
else{
currentMonth = currentMonth + 1;
calendarTitle(currentYear, currentMonth);
calendarBody(currentYear,currentMonth);
}
console.log(currentMonth);
// ここに#buttonをクリックしたら発生させる処理を記述する
};
// カレンダーの曜日
function calendarHeading() {
var th = '';
var dayOfWeekStrJP = [ '<span style="color:red">日</span>', "月", "火", "水", "木", "金", '<span style="color:blue;">土</span>' ] ;
for(var col = 0; col < 7 ; col++) {
var day = dayOfWeekStrJP[col]
// console.log(`"${dayOfWeekStrJP[col]}"`);
th += `<th>${day}</th>`;
console.log(th);
}
$thead.html(`<tr>${th}</tr>`);
}
// function calendarHeading() {
// var dayOfWeekStrJP = [ "日", "月", "火", "水", "木", "金", "土" ] ;
// var th = []; 配列を生成
// for(var col = 0; col < 7 ; col++) {
// var day = dayOfWeekStrJP[col];
// th.push(`<th>${day}</th>`); 配列に代入
// console.log(th);
// }
// console.log(th);
// console.log(th.join(''));
// $thead.html(`<tr>${th.join('')}</tr>`); 配列を文字列にする
// }
// ぴよちゃん
// 今日を赤くする関数
function getToday(year,month,textTd){
var todayYMFlag = ((today.getFullYear() === year) && (today.getMonth() === month)) ? true : false; // 本日の年と月が表示されるカレンダーと同じか判定
var addClass = '';
if (todayYMFlag && (textTd === today.getDate())) {
addClass = 'is-today';
}
return addClass;
}
var day = new Date("2020/6/25")
console.log(day.getDay());
// 土日を赤と青にする関数
function getDay(currentYear,currentMonth,textTd){
var calendarDay = new Date(`${currentYear}/${currentMonth + 1}/${textTd}`);
console.log(calendarDay);
var sundayFlag = (calendarDay.getDay() === 0) ? true : false;
var suturdayFlag = (calendarDay.getDay() === 6) ? true : false;
var suturdayFlag
var addClass='';
if (sundayFlag) {
addClass = 'is-sunday';
}
else if(suturdayFlag) {
addClass = 'is-suturday';
}
return addClass;
}
// 当月の日にちを生成する関数
function calendarBody(year, month){
var startDate = new Date(year, month, 1); // その月の最初の日の情報
var endDate = new Date(year, month + 1 , 0); // その月の最後の日の情報
var startDay = startDate.getDay();// その月の最初の日の曜日を取得
var endDay = endDate.getDate();// その月の最後の日の曜日を取得
var textSkip = true; // 日にちを埋める用のフラグ
var textDate = 1; // 日付(これがカウントアップされます)
var tableBody =''; // テーブルのHTMLを格納する変数
for (var row = 0; row < 6; row++){
var tr = '<tr>';
for (var col = 0; col < 7; col++) {
if (row === 0 && startDay === col){
textSkip = false;
}
if (textDate > endDay) {
textSkip = true;
}
// var addClass = (todayYMFlag && (textDate === today.getDate())) ? 'is-today' : '';
var textTd = textSkip ? ' ' : textDate++;
var todayClass = getToday(year,month,textTd);
var dayClass = getDay(currentYear,currentMonth,textTd);
var td = '<td class="'+todayClass+' '+dayClass+'"><span class="text">'+textTd+'</span></td>';
// `<td class="${addClass}">${textTd}</td>`;
tr += td;
}
tr += '</tr>';
tableBody += tr;
}
$tbody.html(tableBody);
}
// 前月の日にちを生成する関数
| 41bbc2a466cdbc5a733544c181aa7d6fbe4103b4 | [
"JavaScript"
] | 1 | JavaScript | papico328/calendar | 7320b814a97ddf7914115248f08aa9fb01f5b2fa | e530c992d0597cf627f6b1a01828ddbcb42f3d9a |
refs/heads/master | <file_sep><?php
/**
*
*/
class My_model extends CI_Model
{
function __construct()
{
parent::__construct();
$this->load->database();
}
public function cek_user($uname, $pass)
{
$qry = $this->db->query("select * from t_user where username='$uname' and password='$<PASSWORD>'");
return $qry;
}
public function input_data($data, $table)
{
$this->db->insert($table,$data);
}
public function tampil_data($table)
{
$where = array('level' => 3);
return $this->db->get_where($table, $where);
}
public function tampil_user($table, $where)
{
return $this->db->get_where($table, $where);
}
public function tampil_adm_user()
{
$qry = $this->db->query("select * from t_user where id=".$_SESSION['id']);
return $qry;
}
public function get_by_id($table, $where)
{
$this->db->from($table);
$this->db->where($where);
$query = $this->db->get();
return $query->row();
}
public function barang_update($where, $data, $table)
{
$this->db->update($table, $data, $where);
return $this->db->affected_rows();
}
public function delete_by_id($where, $table)
{
$this->db->where($where);
$this->db->delete($table);
}
} | f9c21186cd028841a923c5994be74f60927cf963 | [
"PHP"
] | 1 | PHP | alwialwow/flight_booking | 3bd8bd8f1e144294d2eff559e356ad40df43a065 | df6c9f915f0a0934a9d1e8aa63839e6982b17d7a |
refs/heads/main | <repo_name>eueuG/HiSwift<file_sep>/HiSwift/HiSwiftApp.swift
//
// HiSwiftApp.swift
// HiSwift
//
// Created by 野田凜太郎 on 2021/03/30.
//
import SwiftUI
@main
struct HiSwiftApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
| bb5c7d838c8ccea620edd2f347e9c24d162753d0 | [
"Swift"
] | 1 | Swift | eueuG/HiSwift | c8364e44b457c68583aaf918dcbe03586762eaf9 | 7529426f8ea41e174ed79140559d1279735cbe14 |
refs/heads/master | <file_sep>import smtplib
import traceback
from email.message import Message
def send_email(subject, content):
try:
real_sender, passwd, server = "real_user_name", "password", "smtp.abc.cn"
fake_sender = "<EMAIL>"
real_recipients = ["<EMAIL>", "<EMAIL>", "<EMAIL>"]
fake_recipients = ["<EMAIL>", "<EMAIL>"]
message = Message()
message["Subject"] = subject
message["From"] = fake_sender
message["To"] = ";".join(fake_recipients)
#Copy to
#message["CC"] is only for display, to send the email we must specify it in the method "SMTP.sendmail".
#message["CC"] = "<EMAIL>,<EMAIL>"
message.set_payload(content)
message.set_charset("utf-8")
msg = message.as_string()
sm = smtplib.SMTP(server)
sm.set_debuglevel(0) #sm.set_debuglevel(1)
sm.ehlo()
sm.starttls()
sm.ehlo()
sm.login(real_sender, passwd)
sm.sendmail(fake_sender, real_recipients, msg) # 注意: 这里必须是fake_sender,否则会出现"由XXX代发"的问题。
sm.quit()
return 0
except Exception as e:
traceback.print_exc()
return 1
def main():
subject = "明天上午会议取消"
content = "伪造收件人、发件人、抄送人、邮件主题、邮件内容..."
if send_email(subject, content) == 0:
print("邮件发送成功")
else:
print("邮件发送失败")
if __name__ == '__main__':
main()
<file_sep>#!/usr/bin/python2.7
#coding:utf-8
#如果想有中文注释就必须得有上面的语句
#File: myUtils.py
#Author: lxw
import smtplib
from email.message import Message
from Server import getServerEmail
def getRCB():
recipient = raw_input("收件人: ")
return recipient
def filterList(aList):
length = len(aList)
i = 0
while i < len(aList):
if aList[i] == "":
del aList[i]
else:
i += 1
return aList
def splitStr(string, sep):
aList = string.split(sep)
length = len(aList)
for i in xrange(length):
string = aList[i]
string = string.strip()
aList[i] = string
return aList
def sendEmail(subject, content):
"""
Send Email.
"""
try:
email, passwd, server = getServerEmail.getServerEmail()
smtpServer = server
userName = email
password = <PASSWORD>
recipient = getRCB()
rList = splitStr(recipient, ",")
rList = filterList(rList)
fromAddr = email
toAddrs = rList #["<EMAIL>", "<EMAIL>"]
message = Message()
message["Subject"] = subject
message["From"] = fromAddr
message["To"] = ";".join(toAddrs)
#Copy to
#message["CC"] is only for display, to send the email we must specify it in the method "SMTP.sendmail".
#message["CC"] = "<EMAIL>,<EMAIL>,<EMAIL>"
message["CC"] = "<EMAIL>,<EMAIL>"
message.set_payload(content)
message.set_charset("utf-8")
msg = message.as_string()
sm = smtplib.SMTP(smtpServer)
sm.set_debuglevel(0) #sm.set_debuglevel(1)
sm.ehlo()
sm.starttls()
sm.ehlo()
sm.login(userName, password)
sm.sendmail(fromAddr, toAddrs, msg)
sm.quit()
except Exception, e:
print "lxw Exception: ", e
def main():
subject = raw_input("主题: ")
content = raw_input("邮件内容: ")
sendEmail(subject, content)
print "邮件发送成功"
if __name__ == '__main__':
main()
"""
14:30开会通知
下午跟我去怀柔雁栖湖校区开会,记得带上电脑和门禁卡!
"""
| 8b5f9b42a357ca59e57408e7183914b5f3b6610d | [
"Python"
] | 2 | Python | lxw0109/PhishingDemo | c72a0d02b1e733379367daad94aaf7b9ebe3e823 | 21c544205446e26c398be29b1910635405a6fc6e |
refs/heads/master | <file_sep>import {bootstrap, FORM_PROVIDERS, ELEMENT_PROBE_PROVIDERS} from 'angular2/angular2';
import {ROUTER_PROVIDERS} from 'angular2/router';
import {HTTP_PROVIDERS} from 'angular2/http';
import {MyApp} from './components/app/app';
bootstrap(MyApp, [
FORM_PROVIDERS,
ROUTER_PROVIDERS,
HTTP_PROVIDERS,
ELEMENT_PROBE_PROVIDERS
]);
<file_sep>import {Component} from 'angular2/angular2';
@Component({
selector: 'my-app',
templateUrl: './components/app/app.html'
})
export class MyApp {
constructor() {
}
ngOnInit() {
console.log('NG INIT');
}
}
| df6e912b9cc877cd9458b761f733031f128a70b0 | [
"TypeScript"
] | 2 | TypeScript | TheLarkInn/angular2-electron-playground | bcb165b94be1623aea61bd4ee380633b5e8f7fde | 9cbe9059775970866c5843d3eba136f1934fc46d |
refs/heads/master | <file_sep>import register from './components/Register.vue'
export default {
mode: 'history',
routes: [
{
path:'/register',
component: {
register
}
}
]
};<file_sep>export default {
state: {
user: {
userId: '',
username: '',
password: '',
email: '',
message: ''
},
roomId: '',
currentUser: null,
users: null,
initialMessages: []
},
mutations: {
//USER
SET_USERID ({user}, payload) {
user.userId = payload.userId;
},
SET_USERNAME ({user}, payload) {
user.username = payload.username;
},
SET_PASSWORD ({user}, payload) {
user.password = <PASSWORD>;
},
SET_EMAIL ({user}, payload) {
user.email = payload.email;
},
SET_MESSAGE ({user}, payload) {
user.message = payload.message;
}
},
getters: {
//USER
GET_USERID ({user}) {
return user.userId;
},
GET_USERNAME ({user}) {
return user.username;
},
GET_PASSWORD ({user}) {
return user.<PASSWORD>;
},
GET_EMAIL ({user}) {
return user.email;
},
GET_MESSAGE ({user}) {
return user.message;
}
},
actions: {
//USER
SET_USERID({commit}, id) {
}
}
};<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Console\Presets\React;
use Illuminate\Http\Request;
class ChatController extends Controller
{
private $chat;
private $roomId;
public function __construct()
{
$this->chat = app('Chat');
$this->roomId = env('CHATKIT_GENERAL_ROOM_ID');
}
/*Returns welcome page if a user ID doesn't exist in the current session.
else it redirects to the chat page.*/
public function index(Request $request)
{
$userid = $request->session()->get('chatkit_id')[0];
if (!is_null($userid))
{
return redirect(route('chat'));
}
return view('app');
}
/*Creates a new user and adds the user to the chat.
Saves the users ID in the current session beofre redirecting the user to the chat page. */
public function join(Request $request)
{
$chatkit_id = strtolower(str_random(5));
$this->chat->createUser([
'id' => $chatkit_id,
'user-ids' => [$chatkit_id],
]);
$this->chat->addUsersToRoom([
'room_id' => $this->roomId,
'user_ids' => [$chatkit_id],
]);
$request->session()->push('chatkit_id', $chatkit_id);
return redirect(route('chat'));
}
/*Handles chat page on browser load.
Gets the current user ID from the session, if ID is not found, redirect user to the welcome page. */
public function chat(Request $request)
{
$roomId = $this->roomId;
$userId = $request->session()->get('chatkit_id')[0];
if (is_null($userId)) {
$request->session()->flash('status', 'Join to access chat room!');
return redirect(url('/'));
}
$fetchMessages = $this->chat->getRoomMessages([
'room_id' => $roomId,
'direction' => 'newer',
'limit' => 100
]);
$messages = collect($fetchMessages['body'])->map(function ($message) {
return [
'id' => $message['id'],
'senderId' => $message['user_id'],
'text' => $message['text'],
'timestamp' => $message['created_at']
];
});
return view('chat')->with(compact('messages','roomId','userId'));
}
/*Token provider server that recieves the client's request and returns a valid JWT (JSON Web Token) to chat client.*/
public function authenticate(Request $request)
{
$response = $this->chat->authenticate([
'user_id' => $request->user_id,
]);
return response()
->json(
$response['body'],
$response['status']
);
}
/*Use SDK's method to send message to chat room. */
public function sendMessage(Request $request)
{
$message = $this->chat->sendSimpleMessage([
'sender_id' => $request->user,
'room_id' => $this->roomId,
'text' => $request->message
]);
return response($message);
}
/*Returns all users created on chat instance. */
public function getUsers()
{
$users = $this->chat->getUsers();
return response($users);
}
/*Flushes current session and redirects to the welcome page*/
public function logout(Request $request)
{
$request->session()->flush();
return redirect(url('/'));
}
}
| c5db408c1e7cde237340ef572ab3639464842352 | [
"JavaScript",
"PHP"
] | 3 | JavaScript | KarelVendla/Hub | 2e22e28d6f1833132166673a34ca0864607ea487 | 5236d615c420b41c8c354a7cbac506630c5bdc90 |
refs/heads/master | <file_sep>class BlogsController < ApplicationController
def destroy
blog = Blog.find(params[:id])
blog.destroy
redirect_to blogs_path
end
def edit
@blog = Blog.find(params[:id])
end
def updeate
blog = Blog.find(params[:id])
blog.update(blog_params)
redirect_to blog_path(blog)
end
def show
@blog = Blog.find(params[:id])
end
def index
@blogs=Blog.all
end
def new
@blog = Blog.new
end
def create
blog = Blog.new(blog_params)
blog.save
redirect_to blogs_path
end
private
def blog_params
params.require(:blog).permit(:title, :category, :body)
end
end
<file_sep>echo "# CARAVAN" >> README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/shizukaota/CARAVAN.git
git push -u origin master | 3c0d97367ecb06c452085eea4ff629f3f55e0017 | [
"Markdown",
"Ruby"
] | 2 | Ruby | shizukaota/CARAVAN | b4e0510562e9f526ba59e90ea17a705c957c74c4 | 277ee3e4005e640bf7173c2a3a41145ed08f7f5c |
refs/heads/master | <repo_name>AdithyaBhat17/vignesh-kannan-portfolio<file_sep>/README.md
https://vignesh.now.sh<file_sep>/src/components/Footer.js
import React from "react";
import { Link } from "react-router-dom";
import { HashLink } from "react-router-hash-link";
export default function Footer({ hmm }) {
return (
<div className="container bottom">
<div className="row">
<div className="col-md-3 col-sm-6">
<h3 className="bottom-h3 Vignesh"><NAME></h3>
<br />
<p className="bottom-icons">
<a
href="mailto:<EMAIL>"
target="_blank"
rel="noopener noreferrer"
title="mail"
>
<i className="far fa-envelope fa-2x"></i>
</a>
<a
href="https://instagram.com/vigneshk54"
target="_blank"
rel="noopener noreferrer"
title="instagram"
>
<i className="fab fa-instagram fa-2x"></i>
</a>
<a
href="https://dribbble.com/vigneshk54"
target="_blank"
rel="noopener noreferrer"
title="dribbble"
>
<i className="fab fa-dribbble fa-2x"></i>
</a>
</p>
</div>
<div className="col-md-3 col-sm-6">
<h3 className="bottom-h3">
<HashLink to={hmm ? `../../#work` : `./#work`}>Work</HashLink>
</h3>
{/* <p className="bottom-a"><Link to="/ui-ux-design">UI/UX Design</Link></p> */}
<p className="bottom-a">
<Link to="/graphic-design">Graphic Design</Link>
</p>
<p className="bottom-a">
<Link to="/illustrations">Illustrations</Link>
</p>
<p className="bottom-a">
<Link to="/motion-graphics">Motion Graphics</Link>
</p>
<p className="bottom-a">
<Link to="/photography">Photography</Link>
</p>
<p className="bottom-a">
<Link to="/videography">Videography</Link>
</p>
<h3 className="bottom-h3">
<HashLink to={hmm ? `../../#testimonial` : `./#testimonial`}>
Testimonials
</HashLink>
</h3>
<h3 className="bottom-h3">
<a href="mailto:<EMAIL>" to="/">
Contact
</a>
</h3>
<h3 className="bottom-h3">
<Link to="/credits" to="/credits">
Credits
</Link>
</h3>
</div>
</div>
</div>
);
}
<file_sep>/src/components/Hero.js
import React, { Component } from "react";
import resume from "../assets/Vignesh_Kannan-Resume.pdf";
import { HashLink } from "react-router-hash-link";
import heroimg from "../assets/HPImage.png";
class Hero extends Component {
render() {
return (
<div className="container">
<div className="row">
<div className="col-md-6 col-md-push-6">
<img src={heroimg} alt="<NAME>" className="hero-img" />
</div>
<div className="col-md-6 col-md-pull-6">
<h1 className="hero-tag">
Hi, I am <br /> <strong><NAME>.</strong>
</h1>
<p className="about-tag">
A Mechanical Engineer, I am currently pursuing a Master's in
Human-Computer Interaction Design at Indiana University,
Bloomington.
</p>
<p className="buttons">
<HashLink
to="#work"
scroll={el =>
el.scrollIntoView({ behavior: "smooth", block: "start" })
}
title="view work"
>
view work
</HashLink>
<a
target="_blank"
rel="noopener noreferrer"
href={resume}
title="view resume"
>
view resume
</a>
</p>
<p className="socials">
<a
target="_blank"
rel="noopener noreferrer"
title="mail"
href="mailto:<EMAIL>"
>
<i className="far fa-2x fa-envelope"></i>
</a>
<a
target="_blank"
rel="noopener noreferrer"
title="instagram"
href="https://instagram.com/vigneshk54"
>
<i className="fab fa-2x fa-instagram"></i>
</a>
<a
target="_blank"
rel="noopener noreferrer"
title="dribbble"
href="https://www.dribbble.com/vigneshk54"
>
<i className="fab fa-2x fa-dribbble"></i>
</a>
</p>
</div>
</div>
</div>
);
}
}
export default Hero;
| 3f61e2a9f951d6cfe8bd7b636608c6fda704ec74 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | AdithyaBhat17/vignesh-kannan-portfolio | 9309aabdd6e93f201216b033a8abbf442ee2943c | f541a7951e5a9b5d8eb560eefb87e1629a8a85a3 |
refs/heads/master | <file_sep># MovieHub
MovieHub gives you the overview of Movies TV shows & Actors from the largest community network The Movie Database (TMDb), like IMDB. You can discover movies and TV series, or browse through many categories to get the right information.
In this project, I have used Android with Retrofit, Pagination, RoomDataBase, ,Coordinater Layout & Android JetPack.
# Demo of Movie Hub App
<img width="200px" src="https://github.com/mayankkasera/Movie-Stack/blob/master/media/moviestack.gif"></br>
App Features:
* Discover trending Movies, TV shows & Persons.
* Discover Popular Movies, TV shows & Persons.
* Discover Top rated Movies, TV shows & Persons.
* Search your desired Movies, TV shows & Persons.
* Make your desired Movies, TV shows List.
* Make a bookmark of Movies & TV shows and many more.
## Contributing
Please fork this repository and contribute back using
[pull requests](https://github.com/Amirkhan5949/MoviesHub/pulls).
Any contributions, large or small, major features, bug fixes, are welcomed and appreciated
but will be thoroughly reviewed .
### Contact - Let's become friend
- [Github](https://github.com/Amirkhan5949)
- [Linkedin](https://www.linkedin.com/in/aamir-khan-710185197/)
<file_sep>package com.example.moviehub.adapter;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.moviehub.model.Result;
import com.example.moviehub.ui.activities.ProfileActivity;
import com.example.moviehub.network.NetworkConstraint;
import com.example.moviehub.R;
import com.example.moviehub.model.TrendingPersonDetail;
import com.squareup.picasso.Picasso;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import de.hdodenhof.circleimageview.CircleImageView;
public class TrendingPersonListAdapter extends RecyclerView.Adapter<TrendingPersonListAdapter.TrendingRecyclerview>{
Context context;
List<Result> list;
public TrendingPersonListAdapter(Context context, List<Result> list) {
this.context=context;
this.list=list;
}
@NonNull
@Override
public TrendingRecyclerview onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.cast, parent, false);
return new TrendingRecyclerview(view);
}
@Override
public void onBindViewHolder(@NonNull TrendingRecyclerview holder, int position) {
Picasso.get().load(NetworkConstraint.IMAGE_BASE_URL + list.get(position).getProfile_path()).into(holder.circleimg);
holder.name.setText(list.get(position).getName());
if (list.get(position).getKnownForDepartment()!=null){
holder.nickname.setText(list.get(position).getKnownForDepartment());
}else holder.nickname.setVisibility(View.GONE);
holder.linear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.i("dnsdf", "onClick: " + list.get(position).getId());
Intent intent = new Intent(context, ProfileActivity.class);
intent.putExtra("id", list.get(position).getId() + "");
intent.putExtra("name",list.get(position).getName()+"");
intent.putExtra("photo",list.get(position).getProfile_path()+"");
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return list.size();
}
public class TrendingRecyclerview extends RecyclerView.ViewHolder {
CircleImageView circleimg;
TextView name, nickname;
LinearLayout linear;
public TrendingRecyclerview(@NonNull View itemView) {
super(itemView);
circleimg = itemView.findViewById(R.id.circleimg);
name = itemView.findViewById(R.id.name);
nickname = itemView.findViewById(R.id.nickname);
linear = itemView.findViewById(R.id.linear);
}
}
public void addAllResult(List<Result> list){
this.list.addAll(list);
notifyItemRangeInserted(this.list.size() - list.size(),this.list.size());
Log.i("ashbdha","saxghvashvx "+(this.list.size() - list.size())+" "+this.list.size() );
}
}
<file_sep>package com.example.moviehub.adapter;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.moviehub.network.NetworkConstraint;
import com.example.moviehub.ui.activities.ProfileActivity;
import com.example.moviehub.R;
import com.example.moviehub.model.Credit;
import com.example.moviehub.utils.Type;
import com.squareup.picasso.Picasso;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import de.hdodenhof.circleimageview.CircleImageView;
public class CastAdapter extends RecyclerView.Adapter<CastAdapter.CastRecyclerView> {
Context context;
Credit credit;
Type.Credit creditType;
List<Credit.Cast> cast;
List<Credit.Crew> crew;
Type.MovieOrTvshow type;
public CastAdapter(Context context, Credit credit, Type.MovieOrTvshow type, Type.Credit creditType) {
this.context = context;
this.credit = credit;
this.type = type;
this.creditType = creditType;
cast = credit.getCast();
crew = credit.getCrew();
}
@NonNull
@Override
public CastRecyclerView onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.cast, parent, false);
return new CastRecyclerView(view);
}
@Override
public void onBindViewHolder(@NonNull CastRecyclerView holder, int position) {
if (creditType==Type.Credit.CAST){
Picasso.get().load(NetworkConstraint.IMAGE_BASE_URL + cast.get(position).getProfilePath()).into(holder.circleimg);
holder.name.setText(cast.get(position).getName());
holder.nickname.setText(cast.get(position).getCharacter());
holder.linear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.i("dnsdf", "onClick: " + cast.get(position).getId());
Intent intent = new Intent(context, ProfileActivity.class);
intent.putExtra("id", cast.get(position).getId() + "");
intent.putExtra("name",cast.get(position).getName()+"");
intent.putExtra("photo",cast.get(position).getProfilePath()+"");
intent.putExtra("type", type);
context.startActivity(intent);
}
});
}
else {
Picasso.get().load(NetworkConstraint.IMAGE_BASE_URL + crew.get(position).getProfilePath()).into(holder.circleimg);
holder.name.setText(crew.get(position).getName());
// holder.nickname.setText(crew.get(position).getCharacter());
holder.nickname.setVisibility(View.GONE);
holder.linear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.i("ffsff", "onClick: " + crew.get(position).getId());
Intent intent = new Intent(context, ProfileActivity.class);
intent.putExtra("id", crew.get(position).getId() + "");
intent.putExtra("type", type);
intent.putExtra("name",crew.get(position).getName()+"");
intent.putExtra("photo",crew.get(position).getProfilePath()+"");
context.startActivity(intent);
}
});
}
}
@Override
public int getItemCount() {
if (creditType == Type.Credit.CAST)
return credit.getCast().size();
else
return credit.getCrew().size();
}
public class CastRecyclerView extends RecyclerView.ViewHolder {
CircleImageView circleimg;
TextView name, nickname;
LinearLayout linear;
public CastRecyclerView(@NonNull View itemView) {
super(itemView);
circleimg = itemView.findViewById(R.id.circleimg);
name = itemView.findViewById(R.id.name);
nickname = itemView.findViewById(R.id.nickname);
linear = itemView.findViewById(R.id.linear);
}
}
}
<file_sep>package com.example.moviehub.ui.activities;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import com.example.moviehub.R;
public class AppinfoActivity extends AppCompatActivity {
LinearLayout github,linkdin,fbook,instagram;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_appinfo);
github = findViewById(R.id.github);
linkdin = findViewById(R.id.linkdin);
fbook = findViewById(R.id.fbook);
instagram = findViewById(R.id.instagram);
fbook.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent facebookAppIntent;
try {
facebookAppIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/aamir.mansuri.7315?ref=bookmarks"));
startActivity(facebookAppIntent);
} catch (ActivityNotFoundException e) {
facebookAppIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/aamir.mansuri.7315?ref=bookmarks"));
startActivity(facebookAppIntent);
}
}
});
linkdin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String profile_url = "https://www.linkedin.com/in/aamir-khan-710185197/";
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.linkedin.com/in/aamir-khan-710185197/"));
intent.setPackage("com.linkedin.android");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} catch (Exception e) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(profile_url)));
}
}
});
github.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String profile_url = "https://github.com/Amirkhan5949";
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/Amirkhan5949"));
intent.setPackage("com.linkedin.android");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} catch (Exception e) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(profile_url)));
}
}
});
instagram.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("fgdvd", "onClick: "+24233);
{
String profile_url = "https://www.instagram.com/aamir1576/";
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.instagram.com/aamir1576/"));
intent.setPackage("com.linkedin.android");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} catch (Exception e) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(profile_url)));
}
}
}
});
}
}
<file_sep>package com.example.moviehub.ui.fragments;
import android.content.Intent;
import android.os.Bundle;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.moviehub.ui.activities.ForMoreActivity;
import com.example.moviehub.ui.activities.MoreActivity;
import com.example.moviehub.ui.activities.SearchActivity;
import com.example.moviehub.R;
import com.example.moviehub.utils.Type;
/**
* A simple {@link Fragment} subclass.
*/
public class SearchFragment extends Fragment {
View view;
CardView rmovies,rtvshows,rpersons,searchkey;
public SearchFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view=inflater.inflate(R.layout.fragment_search, container, false);
rmovies=view.findViewById(R.id.rmovies);
rtvshows=view.findViewById(R.id.rtvshow);
rpersons=view.findViewById(R.id.rperson);
searchkey=view.findViewById(R.id.searchkey);
searchkey.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(getContext(), SearchActivity.class);
startActivity(intent);
}
});
rmovies.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(getContext(), ForMoreActivity.class);
intent.putExtra("type", Type.MoreButton.TRENDINGMOVIES);
startActivity(intent);
}
});
rtvshows.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(getContext(), ForMoreActivity.class);
intent.putExtra("type", Type.MoreButton.TRENDINGTVSHOW);
startActivity(intent);
}
});
rpersons.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(getContext(), MoreActivity.class);
intent.putExtra("type", Type.MoreButton.TRENDINGPERSON);
startActivity(intent);
}
});
return view;
}
}
<file_sep>package com.example.moviehub.model;
import androidx.room.Entity;
import androidx.room.ForeignKey;
import androidx.room.PrimaryKey;
import androidx.room.TypeConverters;
import com.example.moviehub.room.typeconverter.MTvConverter;
import com.example.moviehub.utils.Type;
@TypeConverters({MTvConverter.class
})
@Entity
(foreignKeys = {
@ForeignKey(entity = MyList.class,
parentColumns="id",
childColumns = "mlid"),
@ForeignKey(entity = MovieInfo.class,
parentColumns="id",
childColumns = "minfoid"),
})
public class MyListDetail {
@PrimaryKey(autoGenerate = true)
long id;
long mlid;
long minfoid;
Type.MovieOrTvshow type;
public MyListDetail(long mlid,long minfoid,Type.MovieOrTvshow type){
this.mlid=mlid;
this.minfoid=minfoid;
this.type=type;
}
public long getMlid() {
return mlid;
}
public void setMlid(long mlid) {
this.mlid = mlid;
}
public long getMinfoid() {
return minfoid;
}
public void setMinfoid(long minfoid) {
this.minfoid = minfoid;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
@TypeConverters({MTvConverter.class})
public Type.MovieOrTvshow getType() {
return type;
}
public void setType(Type.MovieOrTvshow type) {
this.type = type;
}
}
<file_sep>package com.example.moviehub.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.moviehub.R;
import com.example.moviehub.model.Reviews;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class ReviewAdapter extends RecyclerView.Adapter<ReviewAdapter.ReviewRecylerView>{
Context context;
List<Reviews.Result>list;
public ReviewAdapter(Context context,List<Reviews.Result>list){
this.context=context;
this.list=list;
}
@NonNull
@Override
public ReviewRecylerView onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater=LayoutInflater.from(parent.getContext());
View view=inflater.inflate(R.layout.review,parent,false);
return new ReviewRecylerView(view);
}
@Override
public void onBindViewHolder(@NonNull ReviewRecylerView holder, int position) {
holder.name.setText(list.get(position).getAuthor());
holder.moviereview.setText(list.get(position).getContent());
}
@Override
public int getItemCount() {
return list.size();
}
public class ReviewRecylerView extends RecyclerView.ViewHolder {
TextView name,moviereview;
public ReviewRecylerView(@NonNull View itemView) {
super(itemView);
name=itemView.findViewById(R.id.name);
moviereview=itemView.findViewById(R.id.moviereview);
}
}
}
<file_sep>package com.example.moviehub.adapter;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.example.moviehub.R;
import com.example.moviehub.model.YoutubeConnect;
import com.squareup.picasso.Picasso;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class TrailorAdapter extends RecyclerView.Adapter<TrailorAdapter.TrailorViewHolder>{
Context context;
List<YoutubeConnect.Result>list;
public TrailorAdapter(Context context, List<YoutubeConnect.Result>list){
this.context=context;
this.list=list;
}
@NonNull
@Override
public TrailorViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater=LayoutInflater.from(parent.getContext());
View view=layoutInflater.inflate(R.layout.trailor,parent,false);
return new TrailorViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull TrailorViewHolder holder, int position) {
Picasso.get().load("https://i.ytimg.com/vi/"+list.get(position).getKey()+"/hqdefault.jpg").into(holder.image);
holder.name.setText(list.get(position).getName());
holder.relative.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String a= list.get(position).getKey();
String videoId = a;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:"+videoId));
intent.putExtra("VIDEO_ID", videoId);
context.startActivity(intent);
Log.i("sdscssd", "onClick: "+videoId);
}
});
}
@Override
public int getItemCount() {
return list.size();
}
public class TrailorViewHolder extends RecyclerView.ViewHolder {
ImageView image;
TextView name;
RelativeLayout relative;
public TrailorViewHolder(@NonNull View itemView)
{
super(itemView);
image=itemView.findViewById(R.id.image);
name=itemView.findViewById(R.id.name);
relative=itemView.findViewById(R.id.relative);
}
}
}
<file_sep>package com.example.moviehub.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class MovieImages {
@SerializedName("id")
@Expose
private Long id;
public String getBackdropPath() {
return backdropPath;
}
public void setBackdropPath(String backdropPath) {
this.backdropPath = backdropPath;
}
public List<ImageData> getData() {
return data;
}
public void setData(List<ImageData> data) {
this.data = data;
}
@SerializedName("backdrop_path")
@Expose
private String backdropPath;
@SerializedName("backdrops")
@Expose
private List<ImageData> backdrops = null;
@SerializedName("posters")
@Expose
private List<ImageData> data = null;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public List<ImageData> getBackdrops() {
return backdrops;
}
public void setBackdrops(List<ImageData> backdrops) {
this.backdrops = backdrops;
}
public List<ImageData> getImageData() {
return data;
}
public void setImageData(List<ImageData> data) {
this.data = data;
}
}
<file_sep>package com.example.moviehub.network;
public class NetworkConstraint {
public static final String BASE_URL="https://api.themoviedb.org/3/";
public static final String IMAGE_BASE_URL="https://image.tmdb.org/t/p/w185";
public static final String Image_URL="https://image.tmdb.org/t/p/w500";
public static final String Image_Org="https://image.tmdb.org/t/p/original";
public static final String key="bc19b07e368dad62f3388351b5145758";
}
<file_sep>package com.example.moviehub.ui.fragments;
import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.moviehub.model.ImageData;
import com.example.moviehub.model.MovieImages;
import com.example.moviehub.network.NetworkConstraint;
import com.example.moviehub.network.PersonRequest;
import com.example.moviehub.network.RetrofitClient;
import com.example.moviehub.R;
import com.example.moviehub.adapter.ImagesAdapter;
import com.example.moviehub.model.PersonDetail;
import com.example.moviehub.model.PersonImages;
import com.example.moviehub.ui.activities.MoviePosterActivity;
import java.util.ArrayList;
/**
* A simple {@link Fragment} subclass.
*/
public class ProfileFragment extends Fragment {
TextView birth,sincefrom,knownas,bio;
RecyclerView images;
View view;
String personid;
public static ProfileFragment newInstance(String personid) {
ProfileFragment f = new ProfileFragment();
Bundle args = new Bundle();
args.putString("personid",personid);
f.setArguments(args);
return f;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view=inflater.inflate(R.layout.fragment_profile, container, false);
birth=view.findViewById(R.id.birth);
sincefrom=view.findViewById(R.id.sincefrom);
knownas=view.findViewById(R.id.knownas);
bio=view.findViewById(R.id.bio);
images=view.findViewById(R.id.images);
Bundle args = getArguments();
if (args!=null){
personid=args.getString("personid") ;
}
images.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
RetrofitClient.getClient(NetworkConstraint.BASE_URL)
.create(PersonRequest.class)
.getPersondetail(personid,NetworkConstraint.key)
.enqueue(new Callback<PersonDetail>() {
@Override
public void onResponse(Call<PersonDetail> call, Response<PersonDetail> response) {
birth.setText(response.body().getBirthday());
sincefrom.setText(response.body().getPlaceOfBirth());
knownas.setText(response.body().getAlsoKnownAs().toString());
bio.setText(response.body().getBiography());
}
@Override
public void onFailure(Call<PersonDetail> call, Throwable t) {
}
});
Log.i("sfseee", "onCreateView: "+personid);
RetrofitClient.getClient(NetworkConstraint.BASE_URL)
.create(PersonRequest.class)
.getPersonImgRequest(personid,NetworkConstraint.key)
.enqueue(new Callback<PersonImages>() {
@Override
public void onResponse(Call<PersonImages> call, Response<PersonImages> response) {
ImagesAdapter adapter=new ImagesAdapter(getContext(),response.body().getImageDatas());
images.setAdapter(adapter);
Log.i("sscscscfe", "onResponse: "+response.body().toString());
}
@Override
public void onFailure(Call<PersonImages> call, Throwable t) {
Log.i("sscscscfe", "onResponse: "+t.toString());
}
});
return view;
}
}
<file_sep>package com.example.moviehub.adapter;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.moviehub.R;
import com.example.moviehub.model.Credit;
import com.example.moviehub.model.Credit;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class CrewAdapter extends RecyclerView.Adapter<CrewAdapter.CrewRecyclerView>{
Context context;
List<Credit.Crew>list;
public CrewAdapter(Context context, List<Credit.Crew>list){
this.context=context;
this.list=list;
Log.i("nscssknssks", "CrewAdapter: "+list.toString());
}
@NonNull
@Override
public CrewRecyclerView onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater=LayoutInflater.from(parent.getContext());
View view=layoutInflater.inflate(R.layout.crew,parent,false);
return new CrewRecyclerView(view);
}
@Override
public void onBindViewHolder(@NonNull CrewRecyclerView holder, int position) {
holder.name.setText(list.get(position).getName());
Log.i("sfsfssf", "onBindViewHolder: "+list.get(position).getName());
holder.Profession.setText(list.get(position).getDepartment());
Log.i("sfsfssf", "onBindViewHolder: "+list.get(position).getDepartment());
}
@Override
public int getItemCount() {
if(list.size()>6){
return 6;
}
else {
return list.size();
}
}
public class CrewRecyclerView extends RecyclerView.ViewHolder {
TextView name,Profession;
public CrewRecyclerView(@NonNull View itemView) {
super(itemView);
name=itemView.findViewById(R.id.name);
Profession=itemView.findViewById(R.id.profession);
}
}
}
<file_sep>package com.example.moviehub.ui.fragments;
import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toolbar;
import com.example.moviehub.R;
import com.example.moviehub.adapter.MovieDetailAdapter;
import com.example.moviehub.ui.activities.SearchActivity;
import com.example.moviehub.utils.Type;
import com.google.android.material.tabs.TabLayout;
/**
* A simple {@link Fragment} subclass.
*/
public class MyListFragment extends Fragment {
TabLayout tablayoumtv;
FrameLayout framelistmtv;
ImageView msearch;
View view;
private FragmentManager supportFragmentManager;
public MyListFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view= inflater.inflate(R.layout.fragment_my_list, container, false);
tablayoumtv=view.findViewById(R.id.tablayoutmtv);
framelistmtv=view.findViewById(R.id.framelistmtv);
msearch = view.findViewById(R.id.msearchicon);
tablayoumtv.addTab(tablayoumtv.newTab().setText("Movie"));
tablayoumtv.addTab(tablayoumtv.newTab().setText("Tv Show"));
setFragment(new MovieFragment(Type.MovieOrTvshow.MOVIE));
tablayoumtv.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition()){
case 0 : setFragment(new MovieFragment(Type.MovieOrTvshow.MOVIE));
break;
case 1 : setFragment(new MovieFragment(Type.MovieOrTvshow.TVSHOW));
break;
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
msearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(getContext(), SearchActivity.class);
startActivity(intent);
}
});
return view;
}
protected void setFragment(Fragment fragment) {
FragmentTransaction t = getChildFragmentManager().beginTransaction();
t.replace(R.id.framelistmtv, fragment);
t.commit();
}
}
<file_sep>package com.example.moviehub.adapter;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.moviehub.ui.activities.ProfileActivity;
import com.example.moviehub.network.NetworkConstraint;
import com.example.moviehub.R;
import com.example.moviehub.model.Result;
import com.squareup.picasso.Picasso;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import de.hdodenhof.circleimageview.CircleImageView;
public class TrendingPersonAdapter extends RecyclerView.Adapter<TrendingPersonAdapter.Personview> {
Context context;
List<Result> list;
public TrendingPersonAdapter(Context context, List<Result> list ){
this.context=context;
this.list=list;
}
@NonNull
@Override
public Personview onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater=LayoutInflater.from(parent.getContext());
View view=inflater.inflate(R.layout.circle,parent,false);
return new Personview(view);
}
@Override
public void onBindViewHolder(@NonNull Personview holder, int position) {
holder.trendingname.setText(list.get(position).getName());
Log.i("sffdfdfd", "onBindViewHolder: "+list.get(position).getId());
Picasso.get().load(NetworkConstraint.Image_URL+list.get(position).getProfile_path()).into(holder.circleImageView);
holder.llayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
{
Intent intent = new Intent(context, ProfileActivity.class);
intent.putExtra("id", list.get(position).getId()+"");
intent.putExtra("name",list.get(position).getName()+"");
intent.putExtra("photo",list.get(position).getProfile_path()+"");
context.startActivity(intent);
}
}
});
}
@Override
public int getItemCount() {
return list.size();
}
class Personview extends RecyclerView.ViewHolder {
CircleImageView circleImageView;
TextView trendingname;
LinearLayout llayout;
public Personview(@NonNull View itemView) {
super(itemView);
circleImageView=itemView.findViewById(R.id.circleimage);
trendingname=itemView.findViewById(R.id.trendingname);
llayout=itemView.findViewById(R.id.llayout);
}
}
}
<file_sep>package com.example.moviehub.model;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
import androidx.room.TypeConverters;
import com.example.moviehub.room.typeconverter.MTvConverter;
import com.example.moviehub.utils.Type;
@Entity
@TypeConverters({MTvConverter.class
})
public class MyList {
@PrimaryKey(autoGenerate = true)
Long id;
String name;
int size;
Type.MovieOrTvshow type;
public MyList(String name, int size, Type.MovieOrTvshow type) {
this.name = name;
this.size = size;
this.type = type;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
@TypeConverters({MTvConverter.class})
public Type.MovieOrTvshow getType() {
return type;
}
public void setType(Type.MovieOrTvshow type) {
this.type = type;
}
}
<file_sep>package com.example.moviehub.network;
import com.example.moviehub.model.Credit;
import com.example.moviehub.model.MovieInfo;
import com.example.moviehub.model.Reviews;
import com.example.moviehub.model.SimilarMovie;
import com.example.moviehub.model.Trending;
import com.example.moviehub.model.YoutubeConnect;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
public interface MoviesRequest {
@GET("movie/upcoming")
Call<Trending>getUpcoming(@Query("api_key") String key);
@GET("movie/upcoming")
Call<Trending>getUpcomingMore(@Query("page") String page,@Query("api_key") String key);
@GET("movie/popular")
Call<Trending>getPopular(@Query("api_key")String key);
@GET("movie/popular")
Call<Trending>getPopularMore(@Query("page") String page,@Query("api_key")String key);
@GET("movie/top_rated")
Call<Trending>getTopRated(@Query("api_key")String key);
@GET("movie/top_rated")
Call<Trending>getTopRatedMore(@Query("page") String page,@Query("api_key")String key);
@GET("movie/{id}")
Call<MovieInfo> getmovierequest(@Path("id") String id, @Query("api_key") String key);
@GET("movie/{id}/reviews")
Call<Reviews>getreviews(@Path ("id")String id, @Query("api_key") String key);
@GET("movie/{id}/similar")
Call<SimilarMovie>getsimilarmovie(@Path ("id")String id, @Query("api_key") String key);
@GET("movie/{id}/videos")
Call<YoutubeConnect>getYoutubeRequest(@Path ("id")String id, @Query("api_key") String key);
@GET("movie/{id}/credits")
Call<Credit>getCrewRequest(@Path ("id") String id, @Query("api_key") String key);
}
<file_sep>package com.example.moviehub.ui.activities;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Build;
import android.os.Bundle;
import com.example.moviehub.R;
//import com.example.moviehub.adapter.MainSliderAdapter;
public class MainActivity extends AppCompatActivity {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//
// class PicassoImageLoadingService implements ImageLoadingService {
// public Context context;
//
// public PicassoImageLoadingService(Context context) {
// this.context = context;
// }
//
// @Override
// public void loadImage(String url, ImageView imageView) {
// Picasso.get().load(url).into(imageView);
// }
//
// @Override
// public void loadImage(int resource, ImageView imageView) {
// Picasso.get().load(resource).into(imageView);
// }
//
// @Override
// public void loadImage(String url, int placeHolder, int errorDrawable, ImageView imageView) {
// Picasso.get().load(url).placeholder(placeHolder).error(errorDrawable).into(imageView);
// }
// }
//
// Slider.init((ImageLoadingService) PicassoImageLoadingService);
// banner_slider1.setAdapter(new TrendingPersonAdapter(MainActivity.this,));
}
}
<file_sep>package com.example.moviehub.ui.fragments;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.moviehub.R;
import com.example.moviehub.adapter.FrontPageAdapter;
import com.example.moviehub.adapter.MainSliderAdapter;
import com.example.moviehub.adapter.TrendingPersonAdapter;
import com.example.moviehub.model.Trending;
import com.example.moviehub.network.MoviesRequest;
import com.example.moviehub.network.NetworkConstraint;
import com.example.moviehub.network.RetrofitClient;
import com.example.moviehub.network.TrendingRequest;
import com.example.moviehub.ui.activities.AllDetatilActivity;
import com.example.moviehub.ui.activities.ForMoreActivity;
import com.example.moviehub.ui.activities.MoreActivity;
import com.example.moviehub.ui.activities.SearchActivity;
import com.example.moviehub.utils.PicassoImageLoadingService;
import com.example.moviehub.utils.Type;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import ss.com.bannerslider.Slider;
import ss.com.bannerslider.event.OnSlideClickListener;
/**
* A simple {@link Fragment} subclass.
*/
public class HomeFragment extends Fragment {
private RecyclerView recycler, resque, upcoming, popular, toprated,trendingpersonrecycler;
TextView trending, tvshow, upcomingmovie, popularmovie, topratedmovie,trendingperson;
Slider banner_slider1;
ImageView msearch;
View view;
public HomeFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view=inflater.inflate(R.layout.fragment_home, container, false);
// Inflate the layout for getContext() fragment
recycler = view.findViewById(R.id.recycler);
resque =view.findViewById(R.id.resque);
trendingpersonrecycler = view.findViewById(R.id.trendingpersonrecycler);
upcoming = view.findViewById(R.id.upcoming);
popular = view.findViewById(R.id.popular);
toprated = view.findViewById(R.id.toprated);
msearch = view.findViewById(R.id.msearchicon);
trending = view.findViewById(R.id.trending);
tvshow = view.findViewById(R.id.tvshow);
upcomingmovie = view.findViewById(R.id.upcomingmovie);
popularmovie = view.findViewById(R.id.popularmovie);
topratedmovie = view.findViewById(R.id.topratedmovie);
trendingperson = view.findViewById(R.id.trendingperson);
banner_slider1=view.findViewById(R.id.banner_slider1);
recycler.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
resque.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
trendingpersonrecycler.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
upcoming.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
popular.setLayoutManager(new LinearLayoutManager(getContext()));
popular.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, true));
toprated.setLayoutManager(new LinearLayoutManager(getContext()));
toprated.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, true));
Slider.init(new PicassoImageLoadingService(getContext()));
// banner_slider1.setSelectedSlide(2);
apitrendingperson();
apiTrendingMovies();
apiTrendingTvShow();
apiUpcoming();
apiPopulaar();
apiTopRated();
msearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(getContext(), SearchActivity.class);
startActivity(intent);
}
});
trendingperson.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(getContext(), MoreActivity.class);
intent.putExtra("type", Type.MoreButton.TRENDINGPERSON);
startActivity(intent);
}
});
trending.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(getContext(),ForMoreActivity.class);
intent.putExtra("type", Type.MoreButton.TRENDINGMOVIES);
startActivity(intent);
}
});
tvshow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(getContext(),ForMoreActivity.class);
intent.putExtra("type", Type.MoreButton.TRENDINGTVSHOW);
startActivity(intent);
}
});
popularmovie.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(getContext(), ForMoreActivity.class);
intent.putExtra("type", Type.MoreButton.POPULARMOVIES);
startActivity(intent);
}
});
topratedmovie.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(getContext(),ForMoreActivity.class);
intent.putExtra("type", Type.MoreButton.TOPRAYEDMOVIES);
startActivity(intent);
}
});
upcomingmovie.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(getContext(),ForMoreActivity.class);
intent.putExtra("type", Type.MoreButton.UPCOMINGMOVIES);
startActivity(intent);
}
});
return view;
}
private void apiTopRated() {
RetrofitClient.getClient(NetworkConstraint.BASE_URL)
.create(MoviesRequest.class)
.getTopRated(NetworkConstraint.key)
.enqueue(new Callback<Trending>() {
@Override
public void onResponse(Call<Trending> call, Response<Trending> response) {
Log.i("fxczc", "onResponse: " + response.toString());
Log.i("fxczc", "onResponse: " + response.body());
toprated.setAdapter(new FrontPageAdapter(getContext(), response.body().getResults(), Type.MovieOrTvshow.MOVIE));
}
@Override
public void onFailure(Call<Trending> call, Throwable t) {
Log.i("fxczc", "onFailure: " + t.getMessage());
}
});
}
private void apiPopulaar() {
RetrofitClient.getClient(NetworkConstraint.BASE_URL)
.create(MoviesRequest.class)
.getPopular(NetworkConstraint.key)
.enqueue(new Callback<Trending>() {
@Override
public void onResponse(Call<Trending> call, Response<Trending> response) {
Log.i("dscsc", "onResponse: " + response.body());
Log.i("dscsc", "onResponse: " + response.toString());
popular.setAdapter(new FrontPageAdapter(getContext(), response.body().getResults(), Type.MovieOrTvshow.MOVIE));
}
@Override
public void onFailure(Call<Trending> call, Throwable t) {
Log.i("dscsc", "onFailure: " + t.getMessage());
}
});
}
private void apiUpcoming() {
RetrofitClient.getClient(NetworkConstraint.BASE_URL)
.create(MoviesRequest.class)
.getUpcoming(NetworkConstraint.key)
.enqueue(new Callback<Trending>() {
@Override
public void onResponse(Call<Trending> call, Response<Trending> response) {
Log.i("adadczc", "onResponse: " + response.toString());
Log.i("adadczc", "onResponse: " + response.body());
upcoming.setAdapter(new FrontPageAdapter(getContext(), response.body().getResults(), Type.MovieOrTvshow.MOVIE));
banner_slider1.setAdapter(new MainSliderAdapter(response.body().getResults(),Type.UpcomingOrPersonImage.UPCOMINGMOVIE));
banner_slider1.setOnSlideClickListener(new OnSlideClickListener() {
@Override
public void onSlideClick(int position) {
//Do what you want
Intent intent=new Intent(getContext(), AllDetatilActivity.class);
intent.putExtra("id",response.body().getResults().get(position).getId()+"");
intent.putExtra("type",Type.MovieOrTvshow.MOVIE);
Log.i("sfsfss", "onSlideClick: "+response.body().getResults().get(position).getId());
startActivity(intent);
}
});
}
@Override
public void onFailure(Call<Trending> call, Throwable t) {
Log.i("adadczc", "onFailure: " + t.getMessage());
}
});
}
private void apiTrendingTvShow() {
RetrofitClient.getClient(NetworkConstraint.BASE_URL)
.create(TrendingRequest.class)
.getTrendingTvShow(NetworkConstraint.key)
.enqueue(new Callback<Trending>() {
@Override
public void onResponse(Call<Trending> call, Response<Trending> response) {
Log.i("adadczc", "onResponse: " + response.toString());
Log.i("adadczc", "onResponse: " + response.body());
resque.setAdapter(new FrontPageAdapter(getContext(), response.body().getResults(), Type.MovieOrTvshow.TVSHOW));
}
@Override
public void onFailure(Call<Trending> call, Throwable t) {
Log.i("adadczc", "onFailure: " + t.getMessage());
}
});
}
private void apiTrendingMovies() {
RetrofitClient.getClient(NetworkConstraint.BASE_URL)
.create(TrendingRequest.class)
.getTrending(NetworkConstraint.key)
.enqueue(new Callback<Trending>() {
@Override
public void onResponse(Call<Trending> call, Response<Trending> response) {
Log.i("dadacc", "onResponse: " + response.body().getResults());
Log.i("dadacc", "onResponse: " + response.toString());
recycler.setAdapter(new FrontPageAdapter(getContext(), response.body().getResults(), Type.MovieOrTvshow.MOVIE));
}
@Override
public void onFailure(Call<Trending> call, Throwable t) {
Log.i("dadacc", "onFailure: " + t.getMessage());
}
});
}
private void apitrendingperson() {
RetrofitClient.getClient(NetworkConstraint.BASE_URL)
.create(TrendingRequest.class)
.getTrendingPerson(NetworkConstraint.key)
.enqueue(new Callback<Trending>() {
@Override
public void onResponse(Call<Trending> call, Response<Trending> response) {
trendingpersonrecycler.setAdapter(new TrendingPersonAdapter(getContext(),response.body().getResults()));
}
@Override
public void onFailure(Call<Trending> call, Throwable t) {
}
});
}
}
<file_sep>package com.example.moviehub.adapter;
import com.example.moviehub.model.ImageData;
import com.example.moviehub.ui.fragments.PhotosFragment;
import com.example.moviehub.model.MovieImages;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
public class MoviePosterAdapter extends FragmentPagerAdapter {
ArrayList<ImageData> data;
public MoviePosterAdapter(@NonNull FragmentManager fm, ArrayList<ImageData> data) {
super(fm);
this.data = data;
}
@NonNull
@Override
public Fragment getItem(int position) {
return PhotosFragment.newInstance (data.get(position).getFilePath());
}
@Override
public int getCount() {
return data.size();
}
}
<file_sep>package com.example.moviehub.ui.activities;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import android.util.Log;
import com.example.moviehub.R;
import com.example.moviehub.adapter.MoviePosterAdapter;
import com.example.moviehub.model.ImageData;
import com.example.moviehub.model.MovieImages;
import java.util.ArrayList;
public class MoviePosterActivity extends AppCompatActivity {
ViewPager pager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_poster);
pager=findViewById(R.id.pager);
ArrayList<ImageData> images = (ArrayList<ImageData>) getIntent().getSerializableExtra("images");
Log.i("cghsdg", "onCreate: "+ images.toString());
pager.setAdapter(new MoviePosterAdapter( getSupportFragmentManager(),images));
Log.i("scffdf", "onCreate: "+images);
}
}
| 3ea209663a348547fe2a6e2ca1f00e1418a1fb28 | [
"Markdown",
"Java"
] | 20 | Markdown | Amirkhan5949/MoviesHub | 091cb9995048f78fc75cb0d4766a5415099d7176 | 6add72290a0aa9200df358a24b43dd76427245d6 |
refs/heads/main | <repo_name>allenoxli/language-model-playground<file_sep>/lmp/infer/_top_p.py
r"""Top ``P`` inference method."""
import argparse
from typing import ClassVar, Dict, Optional
import torch
from lmp.infer._base import BaseInfer
from lmp.model import BaseModel
from lmp.tknzr import BaseTknzr
class TopPInfer(BaseInfer):
r"""Top ``P`` inference method.
Use indice with the top ``P`` highest probability that cumulative
probability is lower than ``P`` as possible next token id, then randomly
choose ``1`` index out of ``P`` as next token id prediction.
Top-p sampling, also called nucleus sampling is similar to top-k sampling
where k changes at every step to cover ``P`` probability mass.
It is a non-greedy algorithm since the best prediction is not always
choosen, but it provide dynamic of generation result (because of
randomness, obviously).
For comment throughout this class and its subclasses, we use ``P`` to
denote the number of candidate token ids with highest probabilities that
cumulative probability is lower than ``P``.
Attributes
==========
infer_name: ClassVar[str]
Inference method name is ``top-p``.
Used for command line argument parsing.
"""
infer_name: ClassVar[str] = 'top-p'
def __init__(self, p: float, max_seq_len: int, **kwargs: Optional[Dict]):
super().__init__(max_seq_len=max_seq_len)
if not isinstance(p, float):
raise TypeError('`p` must be an instance of `float`.')
if not 0.0 < p <= 1.0:
raise ValueError('`p` must satisfy `0.0 < p <= 1.0`.')
self.p = p
@torch.no_grad()
def gen(
self,
model: BaseModel,
tknzr: BaseTknzr,
txt: str,
) -> str:
r"""Generate text conditional on text segment.
Top ``P`` inference algorithm is structured as follow:
#. Encode input text as ``1`` sample batch.
(shape: ``(1, S')``)
#. Remove ``[eos]`` token since model is not trained to predict tokens
after seeing ``[eos]``.
(shape: ``(1, S'-1)`` or ``(1, S)`` where ``S'-1 = S``)
#. Truncate text to satisfy maximum sequence constraint.
(shape: ``(1, S)`` or ``(1, max_seq_len)``)
#. Use for-loop to generate sequence of token ids.
#. Use ``model.pred()`` to get next token ids probability
distribution.
(shape: ``(1, S, V)``)
#. Get the last next token id probability distribution.
(shape: ``(1, V)``)
#. Sort the probability distribution in descending order.
(shape: ``(1, V)``)
#. Get the top ``P`` highest probability distribution with
cumulative probability lower than ``P`` and their respective
indices.
(shape: ``(1, P)``)
#. Use top ``P`` highest probability to construct multinomial
distribution.
#. Sample ``1`` index from top ``P`` indices tensor using
previously constructed multinomial distribution.
Use sampled index as next token id prediction result.
(shape: ``(1, 1)``)
#. Concate the last next token id prediction result with previous
next token id prediction result.
(shape: ``(1, S+1)``)
#. Break loop if token ids sequence length violate
``self.max_seq_len`` constraint.
#. Break loop if the last next token id prediction is ``[eos]``.
#. Otherwise go to the for-loop start and continue generation.
#. Decode generated sequence of token ids to text and return.
Parameters
==========
model: lmp.model.BaseModel
Pre-trained language model to generate text.
tknzr: lmp.tknzr.BaseTknzr
Pre-trained tokenizer for text segment encoding.
txt: str
Text segment to condition on.
Returns
=======
str
Generated text.
"""
# Encode as 1 sample batch.
batch_prev_tkids = tknzr.batch_enc(batch_txt=[txt], max_seq_len=-1)
# Convert to tensor with `dtype == torch.int64`.
# Tensor shape: `(1, S')`.
# Tensor dtype: `torch.int64`.
batch_prev_tkids = torch.LongTensor(batch_prev_tkids)
# Remove `[eos]` token id since model is not trained to predict tokens
# after seeing `[eos]`.
# Tensor shape: `(1, S'-1)` or `(1, S)`.
# Tensor dtype: `torch.int64`.
batch_prev_tkids = batch_prev_tkids[..., :-1]
# Satisty maximum sequence length constraint.
# If sequence length is longer than constraint, then truncate tensor
# to have shape `(1, self.max_seq_len)`.
# Otherwise tensor shape remain the same.
batch_prev_tkids = batch_prev_tkids[..., :self.max_seq_len]
# Get model running device.
device = next(model.parameters()).device
# Move tensors to model running device.
batch_prev_tkids = batch_prev_tkids.to(device)
# Calculate how many token can be generate at most.
# `out_seq_len` satisfy `0 <= out_seq_len <= self.max_seq_len`.
out_seq_len = self.max_seq_len - batch_prev_tkids.size(1)
# Generate tokens.
for _ in range(out_seq_len):
# Get probability distribution with current token ids.
# Input tensor : Current token ids.
# Input shape : `(1, S)`.
# Input dtype : `torch.int64`.
# Output tensor: Next token ids probability distribution.
# Output shape : `(1, S, V)`.
# Output dtype : `torch.float32`.
batch_next_tkids_probs = model.pred(
batch_prev_tkids=batch_prev_tkids
)
# Get the last token id probability distribution.
# Only need the last token since we already know every previous
# token ids.
# Input tensor : Next token ids probability distribution.
# Input shape : `(1, S, V)`.
# Input dtype : `torch.float32`.
# Output tensor: The last next token id probability distribution.
# Output shape : `(1, V)`.
# Output dtype : `torch.float32`.
batch_next_tkid_probs = batch_next_tkids_probs[:, -1]
# Sort the probability distribution in descending order.
# `batch_topp_tkid_probs` shape : `(1, V)`.
# `batch_topp_tkid_probs` dtype : `torch.float32`.
# `batch_topp_tkid` tensor : The top K next token id.
# `batch_topp_tkid` shape : `(1, V)`.
# `batch_topp_tkid` dtype : `torch.int64`.
(
batch_topp_tkid_probs,
batch_topp_tkid,
) = batch_next_tkid_probs.sort(
dim=-1,
descending=True
)
# Calculate cumulative distribution and retrieve indices with
# cumulative probability lower than `P`.
# Input tensor : The last next token id
# probability distribution.
# Input shape : `(1, V)`.
# Input dtype : `torch.float32`.
# `batch_topp_tkid_probs` tensor : The next token id probability
# distribution.
# `batch_topp_tkid_probs` shape : `(1, P)`.
# `batch_topp_tkid_probs` dtype : `torch.float32`.
# `batch_topp_tkid` tensor : The top P next token id.
# `batch_topp_tkid` shape : `(1, P)`.
# `batch_topp_tkid` dtype : `torch.int64`.
topp_length = (batch_topp_tkid_probs.cumsum(
dim=-1)[0] < self.p).sum().item()
# If `P` is higher than the highest probability, `topp_length` will
# be `0`. In the above situation, `topp_length` will be assigned
# `1`.
if topp_length == 0:
topp_length = 1
# Only retain the top `P` highest probability distribution with
# cumulative probability lower than `P` and the corresponding
# index.
batch_topp_tkid_probs = batch_topp_tkid_probs[..., :topp_length]
batch_topp_tkid = batch_topp_tkid[..., :topp_length]
# Sample index from multinomial distribution of the top `P` highest
# probabilities with cumulative probability lower than `P` as the
# last next token id prediction result.
# Input tensor : The top `P` next token id probability
# distribution.
# Input shape : `(1, P)`.
# Input dtype : `torch.float32`.
# Candidate index tensor: Sampled index of the top `P` next token
# id.
# Sampled index is not a token id but is
# an index of top `P` next token id tensor.
# Candidate index shape : `(1, 1)`.
# Candidate index dtype : `torch.int64`.
# Next token id tensor : Sampled token id from top `P`.
# Use sampled index to get sampled token
# id from top `P` next token id tensor.
# Next token id shape : `(1, 1)`.
# Next token id dtype : `torch.int64`.
batch_next_tkid_cand_idx = torch.multinomial(
batch_topp_tkid_probs,
num_samples=1,
)
batch_next_tkid = torch.gather(
batch_topp_tkid,
-1,
batch_next_tkid_cand_idx,
)
# Concate the last next token id prediction result with previous
# token ids prediction result and use to perform further
# prediction.
# `batch_prev_tkids` shape: `(1, S)`.
# `batch_prev_tkids` dtype: `torch.int64`.
# `batch_next_tkid` shape: `(1, 1)`.
# `batch_next_tkid` dtype: `torch.int64`.
# Output shape : `(1, S+1)`.
# Output dtype : `torch.int64`.
batch_prev_tkids = torch.cat(
[batch_prev_tkids, batch_next_tkid],
dim=-1
)
# If the prediction token id is `[eos]`, then stop prediction.
if batch_next_tkid[0, 0].item() == tknzr.eos_tkid:
break
# Output generated text.
return tknzr.batch_dec(
batch_tkids=batch_prev_tkids.tolist(),
rm_sp_tks=True,
)[0]
@staticmethod
def infer_parser(parser: argparse.ArgumentParser) -> None:
r"""Top ``P`` inference method CLI arguments parser.
Parameters
==========
parser: argparse.ArgumentParser
Parser for CLI arguments.
See Also
========
lmp.script.generate_text
Generate text using pre-trained language model.
Examples
========
>>> import argparse
>>> from lmp.infer import TopPInfer
>>> parser = argparse.ArgumentParser()
>>> TopPInfer.infer_parser(parser)
>>> args = parser.parse_args([
... '--ckpt', '5000',
... '--exp_name', 'my_exp',
... '--P, '.9',
... '--txt', 'Hello world',
... ])
>>> args.ckpt == 5000
True
>>> args.exp_name == 'my_exp'
True
>>> args.p == .9
True
>>> args.txt == 'Hello world'
True
>>> args.seed == 42
True
"""
# Load common arguments.
BaseInfer.infer_parser(parser=parser)
# Required arguments.
group = parser.add_argument_group('inference method arguments')
group.add_argument(
'--p',
help='Sample from token ids with top p probabilities mass.',
required=True,
type=float,
)
| 5e21963726fb6ce328327cfebc88e5ed0af9b7f6 | [
"Python"
] | 1 | Python | allenoxli/language-model-playground | c8f877d338795bb8e100865ef4d0dc4b5eb24a03 | 6ea2b87d6b06d933cf0df6708f6b673daae68e92 |
refs/heads/master | <repo_name>karikera/ruarule<file_sep>/src/server/settings.ts
import { JsonWatcher } from "../server_lib/jsonwatcher";
interface Settings
{
zoneExpireTime:number;
playerExpireTime:number;
zoneGap:number;
zoneYBellowRate:number;
zoneYAboveRate:number;
zoneNewSize:number;
trafficLimit:number;
trafficLimitPeriod:number;
warningLimit:number;
warningBan:number;
banReducingInterval:number;
welcomeMessage:string;
admins:string[];
}
const defaultSettings:Settings = {
zoneExpireTime: 96*60*60*1000,
playerExpireTime: 14*24*60*60*1000,
zoneGap: 30,
zoneYBellowRate: 0.2,
zoneYAboveRate: 1.8,
zoneNewSize: 10,
trafficLimit: 1000000,
trafficLimitPeriod: 60*5,
warningLimit: 50,
warningBan: 100,
banReducingInterval: 60000 * 20,
welcomeMessage: "welcomeMessage",
admins: [],
};
export const settings = new JsonWatcher<Settings>(process.argv[1]+"/settings.json", defaultSettings);
settings.onUpdate.on(data=>{
let modified = false;
for (const key in defaultSettings)
{
const defval = defaultSettings[key];
if (!(key in data))
{
data[key] = defval;
modified = true;
}
else if ((typeof defval) !== (typeof data[key]))
{
data[key] = defval;
modified = true;
}
}
if (modified)
{
console.log('settings updated');
settings.save();
}
});
<file_sep>/src/lib/timeschdule.ts
import { realTime, TIME_PER_SECONDS } from "@mcbe/timer/realtime";
import { tellrawAll } from "@mcbe/system_server";
import { toTimeText } from "./korean";
export function setSchedule(hours:number, min:number, name:string, useAlarm:boolean, cb:()=>void):void
{
const date = new Date;
const now = +date;
date.setHours(hours, min, 0, 0);
let next = +date;
if (next < now) next += 24 * 60 * 60 * 1000;
function alarm(remaining:number):void
{
const target = next - remaining - realTime.now;
if (target <= 0) return;
setTimeout(()=>{
tellrawAll(['§e'+toTimeText(remaining / TIME_PER_SECONDS)+' 후: '+name]);
}, target);
}
function regist():void
{
if (useAlarm)
{
alarm(10*60*1000);
alarm(5*60*1000);
alarm(3*60*1000);
alarm(2*60*1000);
alarm(60*1000);
alarm(30*1000);
alarm(10*1000);
alarm(5*1000);
alarm(4*1000);
alarm(3*1000);
alarm(2*1000);
alarm(1*1000);
}
setTimeout(()=>{
cb();
tellrawAll(['§e'+name+' 실행됨']);
next += 24 * 60 * 60 * 1000;
regist();
}, next - realTime.now);
}
regist();
}
<file_sep>/src/server/module/digcounter.ts
import { User, UserExtra } from "@bdsx/ruakr_user";
import ID from "@mcbe/identifier/id";
import { Box, Vector3 } from "krgeometry";
import { Storage } from "@mcbe/store";
import Identifier from "@mcbe/identifier";
import { Entity } from "@mcbe/entity";
import { callAtNextTick } from "@mcbe/nexttick";
import { Block } from "@bdsx/block";
import LOG from "@mcbe/ruakr_log";
import { banlist } from "@bdsx/ruakr_ban";
const VAR_DIG = '#dig';
const VAR_GOLD = '#dig_gold';
const VAR_DIAMOND = '#dig_diamond';
const VAR_EMERALD = '#dig_emerald';
const DROPMAP = new Map<Identifier, [Identifier, number]>([
[ID.diamond_ore, [ID.diamond, 4]],
[ID.quartz_ore, [ID.quartz, 4]],
[ID.emerald_ore, [ID.emerald, 4]],
[ID.lapis_ore, [ID.dye, 32]],
[ID.redstone_ore, [ID.redstone, 8]],
[ID.gravel, [ID.flint, 1]],
[ID.wheat, [ID.wheat, 4]],
[ID.beetroot, [ID.beetroot, 4]],
[ID.potatoes, [ID.potato, 10]],
[ID.nether_wart, [ID.nether_wart, 7]],
[ID.melon_block, [ID.melon, 10]],
[ID.sealantern, [ID.prismarine_crystals, 6]],
[ID.glowstone, [ID.glowstone_dust, 7]],
[ID.carrot, [ID.carrot, 7]],
]);
export function getDigCounterString():string
{
const infos:{
storage:Storage,
dig?:number,
gold?:number,
diamond?:number,
emerald?:number,
diamond_rate?:number,
gold_rate?:number,
emerald_rate?:number
}[] = [];
for (const storage of User.store.values())
{
const info = {
storage,
dig:storage.get(VAR_DIG),
gold:storage.get(VAR_GOLD),
diamond:storage.get(VAR_DIAMOND),
emerald:storage.get(VAR_EMERALD),
};
if (info.gold !== undefined || info.diamond !== undefined || info.emerald !== undefined)
{
infos.push(info);
}
}
for (const info of infos)
{
const dig = info.dig!;
info.diamond_rate = dig / (info.diamond || 0);
info.gold_rate = dig / (info.gold || 0);
info.emerald_rate = dig / (info.emerald || 0);
}
infos.sort((a,b)=>b.diamond_rate! - a.diamond_rate!);
let out = 'DPD report\n';
for (const info of infos)
{
const name = info.storage.name;
let msg = `${name}: `;
if (isFinite(info.diamond_rate!)) msg += `D${info.diamond_rate!.toFixed(1)}(${info.diamond})`;
if (isFinite(info.gold_rate!)) msg += `G${info.gold_rate!.toFixed(1)}(${info.gold})`;
if (isFinite(info.emerald!)) msg += `E${info.emerald_rate!.toFixed(1)}(${info.emerald})`;
out += `${msg} ${info.dig!}\n`;
}
return out;
}
export class DigCounter implements UserExtra
{
constructor(public readonly user:User)
{
}
onPlace(block:Block):boolean
{
if (block.pos.y >= 35) return false;
if (block.id === ID.diamond_ore)
{
this.user.storage.remove(VAR_DIAMOND, 1);
}
else if(block.id === ID.gold_ore)
{
this.user.storage.remove(VAR_GOLD, 1);
}
else if(block.id === ID.emerald_ore)
{
this.user.storage.remove(VAR_EMERALD, 1);
}
return false;
}
onDestroy(block:Block):boolean
{
const dropcheck = DROPMAP.get(block.id);
let counter = 0;
const entities:Entity[] = [];
let needToRemove = false;
if (dropcheck)
{
Entity.catchPost(new Box(block.pos.x, block.pos.y, block.pos.z, block.pos.x, block.pos.y, block.pos.z), ev=>{
const entity = ev.entity;
const [dropped, limit] = dropcheck;
if (entity.id === dropped)
{
counter++;
if (counter > limit)
{
for (const previous of entities)
{
previous.destroy();
}
entities.length = 0;
if (!needToRemove)
{
needToRemove = true;
callAtNextTick(()=>{
banlist.ban(this.user, {action:LOG.Action.OverMine, block, item2:dropped, msg: `drop count: ${dropped} ${counter} > ${limit}`});
});
}
}
if (!needToRemove)
{
entities.push(entity);
}
}
else if (entity.id === block.id)
{
}
else
{
return;
}
if (needToRemove)
{
ev.removeEntity = true;
}
});
return false;
}
if (block.pos.y >= 35) return false;
const dig = this.user.storage.add(VAR_DIG, 1);
switch (block.id)
{
case ID.diamond_ore:
const diamond = this.user.storage.add(VAR_DIAMOND, 1);
if (dig >= diamond * 50) break;
banlist.warning(this.user, 5, {action:LOG.Action.TooMany, block});
if (diamond >= 15) banlist.ban(this.user, {action:LOG.Action.TooMany, block});
needToRemove = true;
break;
case ID.gold_ore:
const gold = this.user.storage.add(VAR_GOLD, 1);
if (dig >= gold * 10) break;
banlist.warning(this.user, 3, {action:LOG.Action.TooMany, pos:block.pos});
if (gold >= 50) banlist.ban(this.user, {action:LOG.Action.TooMany, block});
needToRemove = true;
break;
case ID.emerald_ore:
const emerald = this.user.storage.add(VAR_EMERALD, 1);
break;
}
return false;
}
}<file_sep>/src/lib/particle_id.ts
export const particleIds = {
mobflame_emitter:'minecraft:mobflame_emitter',
// test_beziercurve:'minecraft:test_beziercurve',
// test_bounce:'minecraft:test_bounce',
// test_catmullromcurve:'minecraft:test_catmullromcurve',
// test_colorcurve:'minecraft:test_colorcurve',
// test_combocurve:'minecraft:test_combocurve',
// test_highrestitution:'minecraft:test_highrestitution',
// test_linearcurve:'minecraft:test_linearcurve',
// test_mule:'minecraft:test_mule',
// test_smoke_puff:'minecraft:test_smoke_puff',
// test_sphere:'minecraft:test_sphere',
// test_spiral:'minecraft:test_spiral',
// test_watertest:'minecraft:test_watertest',
// test_flipbook:'minecraft:test_flipbook',
// test_vertexrandom:'minecraft:test_vertexrandom',
balloon_gas_particle:'minecraft:balloon_gas_particle',
mobspell_emitter:'minecraft:mobspell_emitter',
basic_crit_particle:'minecraft:basic_crit_particle',
portal_directional:'minecraft:portal_directional',
bubble_column_down_particle:'minecraft:bubble_column_down_particle',
portal_east_west:'minecraft:portal_east_west',
portal_north_south:'minecraft:portal_north_south',
bubble_column_up_particle:'minecraft:bubble_column_up_particle',
crit_emitter:'minecraft:crit_emitter',
splash_spell_emitter:'minecraft:splash_spell_emitter',
end_chest:'minecraft:end_chest',
totem_particle:'minecraft:totem_particle',
evocation_fang_particle:'minecraft:evocation_fang_particle',
water_splash_particle:'minecraft:water_splash_particle',
evoker_spell:'minecraft:evoker_spell',
water_wake_particle:'minecraft:water_wake_particle',
magnesium_salts_emitter:'minecraft:magnesium_salts_emitter',
wither_boss_invulnerable:'minecraft:wither_boss_invulnerable',
mob_portal:'minecraft:mob_portal',
};
Object.freeze(particleIds);<file_sep>/src/server/module/tempblock.ts
import { User, UserExtra, blockEvent } from "@bdsx/ruakr_user";
import { CID } from "../customid";
import { Vector3 } from "krgeometry";
import { createItem } from "@mcbe/system_server";
import { execute } from "@mcbe/command";
import ID from "@mcbe/identifier/id";
import { removeBlockDrop } from "@bdsx/restoreblock";
import { particleIds } from "../../lib/particle_id";
import { Block } from "@bdsx/block";
const tempBlocks = new Map<string, TempBlock>();
export class TempBlockComponent implements UserExtra
{
private readonly lists:Vector3[] = [];
private giving:NodeJS.Timeout|null = null;
constructor(public readonly user:User)
{
}
flush():void
{
if (this.giving)
{
clearTimeout(this.giving);
this.giving = null;
}
if (this.lists.length === 0) return;
if (this.user.disposed)
{
for (const pos of this.lists)
{
createItem(CID.tempblock, pos);
}
}
else
{
this.user.giveItem(CID.tempblock, 0, this.lists.length);
}
this.lists.length = 0;
}
setReturn(pos:Vector3):void
{
this.lists.push(pos);
if (this.giving) return;
this.giving = setTimeout(()=>{
this.giving = null;
this.flush();
}, TempBlock.GIVETIME);
}
onNew():void
{
}
static onInstall():void
{
blockEvent.install({
TARGET: [CID.tempblock],
onPlace(user:User, block:Block):boolean
{
new TempBlock(user, block.pos);
user.extra(TempBlockComponent).flush();
return true;
},
onDestroy(user:User, block:Block):void
{
const postext = block.pos.x+' '+block.pos.y+' '+block.pos.z;
const blockinst = tempBlocks.get(postext);
if (blockinst) blockinst.onDestroy(user, block);
},
onPistonPush(user:User, block:Block, pistonPos:Vector3, oldPos:Vector3):boolean
{
const postext = oldPos.x+' '+oldPos.y+' '+oldPos.z;
const blockinst = tempBlocks.get(postext);
if (blockinst) blockinst.destroyAt(user, block.pos);
return true;
},
});
}
}
export class TempBlock
{
public static readonly DURATION = 3000;
public static readonly GIVETIME = 1000;
private timeout:NodeJS.Timeout|null;
private readonly postext:string;
constructor(
public readonly user:User,
public readonly pos:Vector3)
{
this.postext = pos.x+' '+pos.y+' '+pos.z;
this.timeout = setTimeout(()=>{
this.timeout = null;
this.destroyAt(this.user, this.pos);
}, TempBlock.DURATION);
tempBlocks.set(this.postext, this);
}
destroyAt(user:User, pos:Vector3):void
{
if (this.timeout)
{
clearTimeout(this.timeout);
this.timeout = null;
}
tempBlocks.delete(this.postext);
execute(user.name).replaceBlock(pos, CID.tempblock, ID.air).then(succeeded=>{
if (!succeeded) return;
user.extra(TempBlockComponent).setReturn(pos);
})
}
onDestroy(user:User, block:Block):void
{
if (!this.timeout)
{
removeBlockDrop(block);
return;
}
clearTimeout(this.timeout);
this.timeout = null;
tempBlocks.delete(this.postext);
if (this.user.disposed) return;
removeBlockDrop(block);
execute(user.name).particle(particleIds.balloon_gas_particle, this.pos.add(Vector3.HALF));
user.extra(TempBlockComponent).setReturn(this.pos);
}
}
<file_sep>/src/server/module/netherchecker.ts
import { User, UserExtra } from "@bdsx/ruakr_user";
import ID from "@mcbe/identifier/id";
import { testforblock, execute, setblock, silentCommander } from "@mcbe/command";
import { CID } from "../customid";
export enum OverworldState
{
Overworld,
NotOverworld,
Unknown,
}
export class NetherChecker implements UserExtra
{
public overworld = OverworldState.Unknown;
constructor(private readonly user:User)
{
}
onUpdateSlow():void
{
const pos = this.user.position.floor();
const bottom = {x:pos.x, y:0, z:pos.z};
silentCommander.setblock(bottom, CID.nether_checker);
execute(this.user.name).testforblock(bottom, CID.nether_checker).then(res=>{
this.overworld = res ? OverworldState.Overworld : OverworldState.NotOverworld;
});
silentCommander.setblock(bottom, ID.bedrock);
}
}
<file_sep>/src/server/module/softinventory.ts
import { ItemStack, ItemList } from "@mcbe/item";
import Identifier from "@mcbe/identifier";
import ID from "@mcbe/identifier/id";
import { execute } from "@mcbe/command";
import { callAtNextTick } from "@mcbe/nexttick";
import { AcquationMethod } from "@mcbe/ruakr_const";
import { NoComponentError } from "@mcbe/component";
import LOG from "@mcbe/ruakr_log";
import { User, UserExtra, Container } from "@bdsx/ruakr_user";
import { banlist } from "@bdsx/ruakr_ban";
import { Block } from "@bdsx/block";
export function getItemMax(item:Identifier):number
{
if (item === ID.egg) return 16;
return 64;
}
export class SoftInventory implements UserExtra
{
public readonly inventory:ItemList = new ItemList;
private invCheckRequested = false;
protected inventoryChecked = false;
private invraw:ItemStack[] = [];
public static readonly MAIN_SIZE = 9 * 3;
public static readonly HOTBAR_SIZE = 9;
public static readonly BAN_BLOCK = new Set<Identifier>([
ID.spawn_egg,
ID.mob_spawner,
ID.bedrock,
ID.end_portal_frame,
ID.end_portal,
ID.gateway,
ID.command_block,
]);
public chestplate:Identifier = ID.undefined;
constructor(public readonly user:User)
{
this.inventory.setAllRaw(this._updateItemRaw());
}
fullTest(id:Identifier):boolean
{
let haveCount = 0;
let haveSlot = 0;
let maxStack = getItemMax(id);
for (const item of this.mainPlusHotbar())
{
if (item.id === ID.undefined) return false;
if (item.id === id)
{
haveCount += item.count;
haveSlot ++;
}
}
return haveCount === haveSlot * maxStack;
}
requestCheckInventory():void
{
if (this.invCheckRequested) return;
this.invCheckRequested = true;
callAtNextTick(()=>{
this._updateInventory();
});
}
onUpdateRealEnd():void
{
this.inventoryChecked = false;
}
onUpdateSlow():void
{
this._updateInventory();
}
*main():IterableIterator<ItemStack>
{
for (let i=0;i<SoftInventory.MAIN_SIZE;i++)
{
yield this.invraw[i];
}
}
*hotbar():IterableIterator<ItemStack>
{
for (let i=SoftInventory.MAIN_SIZE;i<SoftInventory.MAIN_SIZE + SoftInventory.HOTBAR_SIZE;i++)
{
yield this.invraw[i];
}
}
*mainPlusHotbar():IterableIterator<ItemStack>
{
for (let i=0;i<SoftInventory.MAIN_SIZE + SoftInventory.HOTBAR_SIZE;i++)
{
yield this.invraw[i];
}
}
onPlaceBefore(block:Block):boolean
{
// 사용 불가능 불럭 확인
if (!this.user.isAdminMode() && (SoftInventory.BAN_BLOCK.has(block.id)))
{
execute(this.user.name).setblock(block.pos, ID.air);
callAtNextTick(()=>{
banlist.ban(this.user, {action: LOG.Action.BlockedItem, block, msg:`place`});
});
return true;
}
this.requestCheckInventory();
return false;
}
onInterectEnd(block:Block):void
{
this.invCheckRequested = false;
this._updateInventory();
}
getInventoryText():string
{
var text = `--- inventory(${this.user.name}) ---\n`;
for (const item of this.inventory.values())
{
text += `${item.id}: ${item.count}\n`;
}
const ender = Container.getEnder(this.user.name);
ender.setFlags(Container.CHEST_ENDER);
text += ender.getInventoryText();
return text;
}
onAcquireItem(method:AcquationMethod, id:Identifier, count:number, secondary_entity?:IEntity):void
{
const max = getItemMax(id);
for (const item of this.mainPlusHotbar())
{
if (item.id !== id) continue;
if (item.count >= max) continue;
const space = max - item.count;
if (space >= count)
{
item.count += count;
return;
}
else
{
count -= space;
item.count = max;
}
}
}
onDropItem(id:Identifier, count:number)
{
for (const item of this.invraw)
{
if (item.id !== id) continue;
if (item.count === 0)
{
LOG.error({user: this.user, action: LOG.Action.Assertion, msg: "zero count item: " + item.id});
item.id = ID.undefined;
continue;
}
if (item.count > count)
{
item.count -= count;
return;
}
else
{
count -= item.count;
item.count = 0;
item.id = ID.undefined;
if (count === 0) return;
}
}
}
protected _updateInventory():void
{
if (this.inventoryChecked) return;
this.inventory.setAllRaw(this._updateItemRaw());
}
private _updateItemRaw():ItemStack[]
{
this.inventoryChecked = true;
const inventory = this.user.component.InventoryContainer.data;
const hotbar = this.user.component.HotbarContainer.data;
const armors = this.user.component.ArmorContainer.data;
const hand = this.user.component.HandContainer.data;
// const helmet = armors[0];
this.chestplate = Identifier.get(armors[1].item);
// const leggings = armors[2];
// const boots = armors[3];
return this.invraw = inventory.concat(hotbar, armors, [hand[1]])
.map<ItemStack>(v=>({
id: Identifier.get(v.item),
count: v.count
}));
}
protected _getInventoryDiff(added:ItemStack[], removed:ItemStack[])
{
this.invCheckRequested = false;
try
{
const items = this._updateItemRaw();
this.inventory.update(items, added, removed);
}
catch (err)
{
if (err instanceof NoComponentError) return;
throw err;
}
}
}
<file_sep>/src/server_lib/filestore.ts
class FileStore
{
}
<file_sep>/src/lib/arraymap.ts
export class ArrayMap<Key, T> extends Map<Key, T[]>
{
push(key:Key, ...items:T[]):number
{
const arr = this.get(key);
if (arr)
{
return arr.push(...items);
}
else
{
this.set(key, items);
return items.length;
}
}
pop(key:Key):T|undefined
{
const arr = this.get(key);
if (!arr) return undefined;
const res = arr.pop();
if (arr.length === 0) this.delete(key);
return res;
}
}<file_sep>/src/server/clearold.ts
import { setHourTest } from "../lib/hourtest";
import LOG from "@mcbe/ruakr_log";
import { getLastConnection } from "./module/last_conn";
import { settings } from "./settings";
import { User } from "@bdsx/ruakr_user";
export function enableClearOld():void
{
setHourTest(()=>{
const playerExpireTime = settings.data.playerExpireTime;
const now = Date.now();
for (const storage of User.store.values())
{
const lastConn = now - getLastConnection(storage);
if (lastConn >= playerExpireTime)
{
LOG.message_np(`player ${storage.name} is expired`);
storage.dispose();
// Container.cleanEnder(storage.name);
}
}
});
}
<file_sep>/src/lib/breaking.ts
import Identifier from "@mcbe/identifier";
import { BREAKING } from "./breaking_data";
// class BlockInfo
// {
// public readonly hardness:number;
// public readonly tool:ToolType;
// constructor(line:string)
// {
// }
// }
const HARDNESS_TO_SECONDS_CAN = 1.5;
const HARDNESS_TO_SECONDS_CANNOT = 5;
const HASTE_2 = 1.4;
const EFFICIENCY_5 = 26;
function getBreakingPower(hand:Identifier, block:Identifier):void
{
const data = BREAKING.get(block);
if (!data) return;
data.diamond;
}
<file_sep>/src/server_lib/lang/en_US.ts
import { freeze } from './freeze';
import { LangId } from './langid';
const lang_data = {
id: "en_US" as LangId,
commands:{},
item:{
"element_1": [
"Town",
"Town"
],
"element_2": [
"Town and Pillar",
"Town and Pillar"
],
"element_3": [
"Add 1 Block",
"Add 1 Block"
],
"element_4": [
"Add 8 Block",
"Add 8 Block"
],
"element_5": [
"Add 64 Block",
"Add 64 Block"
],
"element_6": [
"Subtract 1 Block",
"Subtract 1 Block"
],
"element_7": [
"Subtract 8 Block",
"Subtract 8 Block"
],
"element_8": [
"Subtract 64 Block",
"Subtract 64 Block"
],
"element_9": [
"Submit Block",
"Submit Block"
],
"element_10": [
"Credit Card",
"Credit Card"
],
"element_11": [
"Question Block",
"Question Block"
],
"element_12": [
"Overworld Tester",
"Overworld Tester"
],
"element_13": [
"Credit Card Block",
"Credit Card Block"
],
"element_14": [
"Returning Block",
"Returning Block"
],
"element_15": [
"Sell All Block",
"Sell All Block"
],
"element_16": [
"Shop Portal Block",
"Shop Portal Block"
],
"element_17": [
"Reward Block",
"Reward Block"
],
"element_18": [
"Buy Block",
"Buy Block"
],
"element_19": [
"Ballot",
"Ballot"
]
}
};
freeze(lang_data);
export = lang_data;
<file_sep>/src/server/build.ts
import { Vector3 } from "krgeometry";
import { fill, fillReplace } from "@mcbe/command";
import ID from "@mcbe/identifier/id";
const DIR_TO_VECTOR = [
new Vector3(1,0,0),
new Vector3(-1,0,0),
new Vector3(0,0,1),
new Vector3(0,0,-1),
];
function bedplace(axis:VectorXYZ, width:number, height:number):void
{
fill(new Vector3(0, -10, 0).add(axis), new Vector3(width, 0, height).add(axis), ID.cobblestone);
}
export function buildTownTower(pos:Vector3):void
{
const top = new Vector3(0, 6, 0).add(pos);
pos = pos.add(Vector3.Y);
fill(pos, top, ID.cobblestone);
for (let i=0;i<4;i++)
{
const dir = DIR_TO_VECTOR[i];
fill(dir.add(pos), dir.add(top), ID.torch, i+1);
}
}
export function removeTownTower(pos:VectorXYZ):void
{
const top = new Vector3(0, 16, 0).add(pos);
for (let i=0;i<4;i++)
{
const dir = DIR_TO_VECTOR[i];
fillReplace(dir.add(pos), dir.add(top), ID.air, 0, ID.torch, i+1);
}
fillReplace(pos, top, ID.air, 0, ID.cobblestone, 0);
}
<file_sep>/src/server/module/portalblock.ts
import { CID } from "../customid";
import { SPAWN_POINT } from "../spawnpoint";
import { Store } from "@mcbe/store";
import { Vector3, Box } from "krgeometry";
import { testforblock, execute } from "@mcbe/command";
import { UserExtra, User } from "@bdsx/ruakr_user";
import { Region } from "./region";
import { Block } from "@bdsx/block";
import LOG from "@mcbe/ruakr_log";
import { BlockListener } from "@bdsx/ruakr_user/blockevent";
const store = new Store('portal');
const VAR_PORTAL_TYPE = '#type';
const portals = new Map<string, PortalBlock>();
class PortalBlock extends Region
{
private postext:string;
private pos:Vector3;
private readonly interval:NodeJS.Timeout = setInterval(()=>{
// particle(particleIds.balloon_gas_particle, this.pos.add(Vector3.Y).add(Vector3.HALF));
}, 1000);
constructor(pos:Vector3)
{
super('상점 포탈 블럭', Box.fromVector(pos, pos).moveBy(Vector3.Y));
this.pos = pos;
this.postext = `${pos.x}_${pos.y}_${pos.z}`;
portals.set(this.postext, this);
store.create(this.postext).set(VAR_PORTAL_TYPE, 1);
}
remove():boolean
{
if (!super.remove()) return false;
clearInterval(this.interval);
store.dispose(this.postext);
portals.delete(this.postext);
return true;
}
move(pos:Vector3):void
{
const oldtext = this.postext;
this.pos = pos;
this.postext = `${pos.x}_${pos.y}_${pos.z}`;
portals.delete(oldtext);
portals.set(this.postext, this);
store.create(oldtext).rename(this.postext);
super.moveBy(pos.sub(this.pos));
}
onEnter(user:User):string|null
{
user.tp(SPAWN_POINT);
return null;
}
}
export const portalBlock:BlockListener&{store:Store} = {
store,
TARGET: [CID.spawnportal],
onInstall():void
{
Store.onLoad.then(()=>{
for (const portal of store.values())
{
const [x,y,z] = portal.name.split('_');
new PortalBlock(new Vector3(+x, +y, +z));
}
});
},
onPlace(user, block)
{
testforblock(block.pos, CID.spawnportal).then(exists=>{
if (!exists)
{
block.destroy();
user.info('스폰 포탈은 오버월드에만 설치가 가능해요');
return;
}
else
{
new PortalBlock(block.pos);
}
});
return true;
},
onDestroy(user, block)
{
const postext = `${block.pos.x}_${block.pos.y}_${block.pos.z}`;
const portal = portals.get(postext);
if (!portal) LOG.error({user, action:LOG.Action.Assertion, block, msg: `spawnportal notfound (destroy, id=${postext})`});
else portal.remove();
},
onPistonPush(user, block, pispos, oldpos)
{
const postext = `${oldpos.x}_${oldpos.y}_${oldpos.z}`;
const portal = portals.get(postext);
if (!portal) LOG.error({user, action:LOG.Action.Assertion, block, msg: `spawnportal notfound (piston, id=${postext})`});
else portal.move(block.pos);
return true;
},
}<file_sep>/src/server/module/zone.ts
import { Vector3, Box } from "krgeometry";
import { Scoreboard, ObjectiveScoreboard } from "@mcbe/scoreboard";
import { DimensionId } from "bdsx/common";
import { Region } from "./region";
import { User, UserExtra, blockEvent } from "@bdsx/ruakr_user";
import { restorePistonPush, restoreBlock, restoreBlockSlow } from "@bdsx/restoreblock";
import ID from "@mcbe/identifier/id";
import { buildTownTower, removeTownTower } from "../build";
import { titleAll, setblock, testforblock, setblockWithoutError } from "@mcbe/command";
import { SPAWN_POINT, spawnLock } from "../spawnpoint";
import { tellrawAll } from "@mcbe/system_server";
import { getLastConnection } from "./last_conn";
import { setFarTicker } from "@mcbe/farticker";
import { setHourTest } from "../../lib/hourtest";
import { EntityType, Entity } from "@mcbe/entity";
import { SCORE_LIMIT } from "@mcbe/ruakr_const";
import { TradingBlock } from "../structure/tradecenter";
import { Pusher } from "./pusher";
import { pvpzone } from "../pvpzone";
import { CID } from "../customid";
import { Storage } from "@mcbe/store";
import { callAtNextTick } from "@mcbe/nexttick";
import { Block } from "@bdsx/block";
import LOG from "@mcbe/ruakr_log";
import { settings } from "../settings";
import { Position } from "@bdsx/position";
import { banlist } from "@bdsx/ruakr_ban";
const zoneById = new Map<string, Zone>();
const zoneboard = new Scoreboard('$zones');
function makeZoneCube(pos:VectorXYZ, size:number):Box
{
const ypos = pos.y + size * settings.data.zoneYAboveRate;
return new Box(
pos.x - size,
pos.y - size * settings.data.zoneYBellowRate,
pos.z - size,
pos.x + size,
ypos,
pos.z + size,
);
}
function * zoneEntires(storage:Storage):IterableIterator<[string, number]>
{
for (const [key, value] of storage.entires())
{
if (key.startsWith('#')) continue;
switch (key)
{
case 'sx': case 'sy': case'sz': continue;
default: yield [key, value];
}
}
}
enum ZoneLevel
{
None = 0,
Member = 1,
Owner = 2,
}
function coordToText(v:Vector3):string
{
v = v.round();
let text = '(';
if (v.x < 0) text += `서 ${-v.x}블럭`;
else if (v.x !== 0) text += `동 ${v.x}블럭`;
if (v.z < 0)
{
if (text) text += ', ';
text += `북 ${-v.z}블럭`;
}
else if (v.z !== 0)
{
if (text) text += ', ';
text += `남 ${v.z}블럭`;
}
if (text.length === 1) return '(이곳)';
return text + ')';
}
export class ZoneComponent implements UserExtra
{
owned:Zone|null = null;
accessable = new Set<Zone>();
constructor(public readonly user:User)
{
for (const [zoneName, level] of zoneEntires(this.user.storage))
{
const zone = Zone.get(zoneName);
if (!zone)
{
LOG.error({user, action:LOG.Action.Assertion, msg: `zone(${zoneName}) not found`});
continue;
}
switch (level)
{
case 2:
this.owned = zone;
this.accessable.add(zone);
break;
case 1:
this.accessable.add(zone);
break;
}
}
}
onInterect(block:Block):boolean
{
const zone = this.owned;
if (!zone) return false;
const other = User.getAt(block.pos.add(Vector3.Y), 2, this.user);
if (!other) return false;
switch (this.user.hand)
{
case ID.stick:
if (zone.isAccessableBy(other))
{
const error = zone.removeAccessable(other);
if (error)
{
this.user.info(error);
}
else
{
this.user.info(other.name+'님을 마을에서 추방하셨어요');
other.info(zone.name+' 마을에서 추방되셨어요!');
}
}
else
{
const error = zone.addAccessable(other);
if (error)
{
this.user.info(error);
}
else
{
this.user.info(`${other.name}님을 마을에 초대하셨어요`);
}
}
break;
case ID.arrow:
const oextra = other.extra(ZoneComponent);
if (!oextra.accessable.has(zone))
{
this.user.info(`${other.name} 주민에게만 마을을 줄 수 있어요`);
}
else
{
const error = zone.recreateAs(other.name);
this.user.info(`${other.name}님에게 마을 권한을 넘기셨어요`);
if (error) this.user.info(error);
}
break;
default:
return false;
}
return true;
}
static async onInstall():Promise<void>
{
blockEvent.onPlace.on(CID.zone_maker, (user, block)=>{
testforblock(block.pos, CID.zone_maker).then(exists=>{
if (!exists)
{
block.destroy();
user.info('오버월드에만 마을이 가능해요');
return;
}
Zone.place(user, block.pos);
});
return true;
});
blockEvent.onPlace.on(CID.zone_maker_torch, (user, block)=>{
testforblock(block.pos, CID.zone_maker_torch).then(exists=>{
if (!exists)
{
block.destroy();
user.info('오버월드에만 마을이 가능해요');
return;
}
const zone = Zone.place(user, block.pos);
if (zone)
{
setblock(block.pos, CID.zone_maker);
buildTownTower(block.pos);
user.tellraw('§7마을 설명을 보시려면 마을 블럭을 파괴해주세요');
user.tellraw('§c화살§7을 들고 파괴하면 마을이 §c없어져요§7!');
}
});
return true;
});
const zones = await zoneboard.list();
const proms:Promise<Zone|null>[] = [];
for (const name in zones)
{
proms.push(Zone.load(name));
}
await Promise.all(proms);
setHourTest(Zone.clean);
}
}
export class Zone extends Region
{
public readonly id:string;
private constructor(
private readonly board:ObjectiveScoreboard,
public readonly pos:Position,
private size:number)
{
super(board.objective + ' 마을');
this.setSize(size);
this.bottomY = this.pos.y - 3;
this.id = board.objective;
zoneById.set(this.id, this);
}
setSize(size:number):void
{
this.cube = makeZoneCube(this.pos, size);
}
getSize():number
{
return this.size;
}
remove():boolean
{
if (!super.remove()) return false;
zoneById.delete(this.id);
this.board.destroy();
User.store.cleanObjectiveWithoutSave(this.board.objective);
for (const user of User.all())
{
const extra = user.extra(ZoneComponent);
extra.accessable.delete(this);
if (extra.owned === this)
{
extra.owned = null;
}
}
return true;
}
destroy():boolean
{
if (!this.remove()) return false;
setblockWithoutError(this.pos, ID.air).then(res=>{
if (res)
{
removeTownTower(this.pos);
}
else
{
setFarTicker(this.pos, new Box(
this.pos.x - 2, this.pos.y - 2, this.pos.z - 2,
this.pos.x + 2, this.pos.y + 18, this.pos.z + 2), ()=>{
setblock(this.pos, ID.air);
removeTownTower(this.pos);
return true;
});
}
});
return true;
}
getMembers():Map<string, ZoneLevel>
{
const members = new Map<string, ZoneLevel>();
for (const storage of User.store.values())
{
const level:ZoneLevel|undefined = storage.get(this.id);
if (level === undefined) continue;
members.set(storage.name, level);
}
return members;
}
recreateAs(name:string):string|null
{
const newid = name.substr(0, SCORE_LIMIT);
const oldzone = zoneById.get(newid);
if (oldzone) return `§c이미 있는 마을: ${newid}`;
try
{
this.remove();
const res = Zone.create(name, this.pos, this.size, true);
if (res.error)
{
tellrawAll([`§c버그로 인해 ${this.id} 마을이 없어져 버렸어요`]);
return '§c'+res.error;
}
const newzone = res.zone!;
const board = res.board!;
for (const storage of User.store.values())
{
const level:ZoneLevel|undefined = storage.get(this.id);
if (level === undefined) continue;
const user = User.getByName(storage.name);
if (user)
{
newzone.addAccessableQuiet(user);
}
else
{
switch (level)
{
case ZoneLevel.None: break;
case ZoneLevel.Owner:
storage.set(board.objective, ZoneLevel.Member);
break;
default:
storage.set(board.objective, level);
break;
}
}
}
tellrawAll([`§e${this.id} 마을이 ${newzone.id} 마을이 되었어요!`]);
return null;
}
catch(err)
{
LOG.error_obj(err);
return '오류';
}
}
onEnter(user:User):string|null
{
if (!user.extra(ZoneComponent).accessable.has(this)) return this.name + ' 제한 구역';
user.info(this.name);
return null;
}
onLeave(user:User):void
{
user.info('마을 외부');
}
canWrite(user:User|null):boolean
{
if (!user) return false;
return user.extra(ZoneComponent).accessable.has(this);
}
canInterect(user:User|null):boolean
{
if (!user) return false;
return user.extra(ZoneComponent).accessable.has(this);
}
isAccessableBy(user:User):boolean
{
const accessable = user.extra(ZoneComponent).accessable;
return accessable.has(this);
}
addAccessable(user:User):string|null
{
const accessable = user.extra(ZoneComponent).accessable;
if (accessable.has(this)) return user.name + '님은 이미 초대되어있어요';
if (accessable.size !== 0)
{
return user.name + '님은 이미 '+[...accessable.values()].map(v=>v.name).join(', ')+'에 살고계세요';
}
user.info(this.name+'에 초대되셨어요!');
accessable.add(this);
user.storage.set(this.id, 1);
return null;
}
addAccessableQuiet(user:User):boolean
{
if (this.id === user.name) return false;
const accessable = user.extra(ZoneComponent).accessable;
if (accessable.has(this)) return false;
accessable.add(this);
user.storage.set(this.id, 1);
return true;
}
removeAccessable(user:User):string|null
{
const extra = user.extra(ZoneComponent);
if (extra.owned === this) return '촌장을 추방할 수 없어요';
const accessable = extra.accessable;
if (!accessable.has(this)) return user.name+'님은 마을사람이 아니에요';
accessable.delete(this);
user.storage.delete(this.id);
if (this.contains(user.position))
{
user.extra(Pusher).pushFromNow(this, this.bottomY, 1);
}
return null;
}
onPistonPush(user:User, block:Block, pistonPos:Vector3, oldPos:Vector3):boolean
{
if (block.id === CID.zone_maker)
{
return restorePistonPush(user, block, pistonPos, oldPos);
}
return false;
}
onDestroy(user:User, block:Block):void
{
if (block.id === CID.zone_maker)
{
if (!block.pos.equals(this.pos))
{
const pos = block.pos;
Entity.catchPost(
new Box(pos.x, pos.y, pos.z, pos.x+1, pos.y+1, pos.z+1),
ev=>{
if (ev.entity.type !== EntityType.Item) return;
ev.removeEntity = true;
}
);
LOG.error({user, action:LOG.Action.Assertion, block, msg:`destroy zone_maker in ${this.id}`});
return;
}
const extra = user.extra(ZoneComponent);
if (!extra.accessable.has(this) && !user.isAdminMode())
{
restoreBlock(user, block);
callAtNextTick(()=>{
banlist.ban(user, {action:LOG.Action.AggressiveDestroy, block, item2: user.hand,
msg:`destroy zone_maker in ${this.name}`});
});
return;
}
switch (user.hand)
{
case ID.arrow:
if (extra.owned === this || user.isAdminMode())
{
if (this.remove())
{
removeTownTower(this.pos);
tellrawAll([`§e${this.id} 마을이 없어졌어요!`]);
user.actionbar(`마을을 없앴어요`);
}
}
else
{
restoreBlock(user, block);
if (this.removeAccessable(user) === null)
{
user.actionbar(`${this.id} 마을에서 나가셨어요`);
}
}
break;
default:
user.tellraw('§7§l 마을 기능 설명');
user.tellraw('§7초대/추방: 막대를 들고 대상의 바닥에 상호작용');
if (extra.owned === this)
{
user.tellraw('§7권한 이전: 화살을 들고 대상의 바닥에 상호작용');
user.tellraw('§7마을 제거: 화살을 들고 마을 블럭 파괴');
}
else
{
user.tellraw('§7마을 탈퇴: 화살을 들고 마을 블럭 파괴');
}
restoreBlockSlow(user, block);
break;
}
}
}
static get(name:string):Zone|undefined
{
return zoneById.get(name);
}
private static _testCollide(pos:Vector3, size:number):string|null
{
const collide:string[] = [];
const area = makeZoneCube(pos, size);
if (area.intersect(spawnLock.cube)) collide.push(`스폰지점(${SPAWN_POINT.sub(pos).diaLength()}블럭)`);
if (TradingBlock.intersect(area)) collide.push(`상점`);
if (pvpzone.intesectAll(area)) collide.push('PvP장');
const expand = area.expand(settings.data.zoneGap);
for (const zone of zoneById.values())
{
if (zone.cube.intersect(expand))
{
collide.push(`${zone.id}(${zone.pos.sub(pos).diaLength()}블럭)`);
}
}
if (collide.length !== 0)
{
return '다른 마을과 너무 가까워요\n'+collide.join(', ');
}
return null;
}
static create(username:string, pos:Position, size:number, ignoreCollide?:boolean):{zone?:Zone, error?:string, board?:ObjectiveScoreboard}
{
const user = User.getByName(username);
const id = username.substr(0, SCORE_LIMIT);
let zone = zoneById.get(id);
if (zone) return {error: `이미 있는 마을: ${id} 마을`};
if (!ignoreCollide)
{
const error = Zone._testCollide(pos, size);
if (error) return {error};
}
const board = new ObjectiveScoreboard(id);
board.create();
User.store.create(username).set(id, 2);
board.set('x', pos.x);
board.set('y', pos.y);
board.set('z', pos.z);
if (size !== undefined) board.set('size', size);
zoneboard.set(id, 1);
zone = new Zone(board, pos, size);
if (user)
{
const extra = user.extra(ZoneComponent);
extra.owned = zone;
extra.accessable.add(zone);
}
return {zone, board};
}
static async load(id:string):Promise<Zone|null>
{
const board = new ObjectiveScoreboard(id);
const [x, y, z, size] = await Promise.all([
board.get('x'),
board.get('y'),
board.get('z'),
board.get('size'),
]);
if (x === undefined) return null;
const pos = new Position(x, y!, z!, DimensionId.Overworld);
return new Zone(board, pos, size || settings.data.zoneNewSize);
}
static clean():void
{
try
{
const zoneExpireTime = settings.data.zoneExpireTime;
const expireTime = Date.now() - zoneExpireTime;
interface ZoneMember
{
zone:Zone;
owner:UserData;
member:UserData[];
}
const zoneMemberMap:Map<string, ZoneMember> = new Map;
for (const zone of zoneById.values())
{
zoneMemberMap.set(zone.id, {
zone,
owner:null as any,
member:[],
});
}
const noOwner = new WeakSet<UserData>();
class UserData
{
public readonly expired:boolean;
public readonly lastConn:number;
public readonly zones:[ZoneMember, number][];
constructor(public readonly storage:Storage)
{
this.lastConn = getLastConnection(storage);
this.expired = Math.round((this.lastConn - expireTime) / (60*60*1000)) <= 0;
const zones:[ZoneMember, number][] = [];
for (const [zonename, level] of zoneEntires(storage))
{
const zone = zoneMemberMap.get(zonename);
if (zone) zones.push([zone, level]);
else LOG.error({action:LOG.Action.Assertion, msg:`zone not found: ${zonename}`});
}
this.zones = zones;
for (const [zone, level] of zones)
{
if (level !== 2) continue;
zone.owner = this;
return;
}
if (!this.expired)
{
for (const [zone, level] of zones)
{
zone.member.push(this);
}
noOwner.add(this);
}
}
}
for (const s of User.store.values())
{
new UserData(s);
}
const expired:ZoneMember[] = [];
const sorted = [...zoneMemberMap.values()].sort((a,b)=>b.member.length - a.member.length);
for (const list of sorted)
{
const owner = list.owner;
if (owner === null)
{
LOG.error({action:LOG.Action.Assertion, msg: 'zone without owner: '+list.zone.id});
expired.push(list);
}
else
{
if (owner.expired)
{
expired.push(list);
}
}
}
for (const list of expired)
{
let lastConn = 0;
let user:UserData|null = null;
for (const m of list.member)
{
if (!noOwner.has(m)) continue;
if (m.lastConn > lastConn)
{
lastConn = m.lastConn;
user = m;
}
}
const zone = Zone.get(list.zone.id)!;
if (user === null)
{
zone.destroy();
tellrawAll([`§e${list.zone.id} 마을에 남아있는 사람이 없어 사라졌어요!`]);
}
else
{
noOwner.delete(user);
zone.recreateAs(user.storage.name);
}
}
}
catch (err)
{
LOG.error_obj(err);
}
}
toString():string
{
return `[zone:${this.id}]`;
}
toInfoString():string
{
return `${this.name} (${this.pos.x} ${this.pos.y} ${this.pos.z}) size=${this.size}`;
}
static async list():Promise<string[]>
{
const scores = await zoneboard.list();
return Object.keys(scores);
}
static place(user:User, pos:Position):Zone|null
{
const extra = user.extra(ZoneComponent);
if (extra.accessable.size !== 0)
{
const posname:string[] = [];
for (const zone of extra.accessable.values())
{
const diff = zone.pos.sub(pos);
if (diff.x === 0 && diff.y === 0 && diff.z === 0)
{
return null;
}
posname.push(zone.name + coordToText(diff));
}
user.info('§c이미 '+posname.join(', ')+'에 살고계세요');
setblock(pos, ID.air, 0, 'destroy');
return null;
}
const {zone, error} = Zone.create(user.name, pos, settings.data.zoneNewSize, false);
if (zone)
{
titleAll('title', '§0');
tellrawAll([`§e${zone.id} 마을이 세워졌어요!`]);
return zone;
}
else if (error)
{
user.info('§c'+error);
setblock(pos, ID.air, 0, 'destroy');
}
return null;
}
}
<file_sep>/src/server/module/nethertop.ts
import { UserExtra, User } from "@bdsx/ruakr_user";
import { Vector3 } from "krgeometry";
import { DimensionId } from "bdsx/common";
export class NetherTop implements UserExtra
{
constructor(public readonly user:User)
{
}
onUpdateSlow():void
{
const pos = this.user.position;
if (pos.y >= 128 && this.user.dimension === DimensionId.Nether)
{
this.user.tp(pos.add(new Vector3(0, -5, 0)));
}
}
}
<file_sep>/README.md
# Caution
This project is abandoned.
I don't recommend using it
Upstream: [https://github.com/karikera/mcbe_modules](https://github.com/karikera/mcbe_modules)
<file_sep>/src/server/test.ts
declare function testfunc(message:string):void;
export function test():void
{
// testfunc("TEST");
}
<file_sep>/src/server_lib/chatmanager.ts
import { NativePointer, netevent, PacketId } from "bdsx";
// class User
// {
// constructor(public readonly name:LogInInfo)
// {
// }
// public startTime:number = Date.now();
// public time:number = 0;
// }
// class ChatManager extends Event<(name:string, message:string)=>void>
// {
// /**
// * -1 = unlimited
// */
// public lengthLimit:number = 200;
// public millisecondsPerCharacters:number = 1000 / 50;
// /**
// * cost = max(millisecondsPerCharacters * characterCount, minimumCost)
// * rule: (milliseconds)
// */
// public minimumCost:number = 300;
// private readonly users = new Map<string, ChatUser>();
// private _getUser(name:string):ChatUser
// {
// let user = this.users.get(name);
// if (user) return user;
// user = new ChatUser(name);
// this.users.set(name, user);
// return user;
// }
// private checkCost(user:ChatUser, cost:number):number
// {
// const now = Date.now();
// const spend = now - user.startTime;
// user.startTime = now;
// user.time = Math.min(user.time + spend, this.lengthLimit * this.millisecondsPerCharacters);
// if (user.time < cost)
// {
// cost = user.time;
// user.time = 0;
// return cost;
// }
// user.time -= cost;
// return cost;
// }
// private readonly chatlistener = (ptr:NativePointer, ni:string, packetId:PacketId)=>{
// ptr.move(0x30);
// const name = ptr.readCxxString();
// let message = ptr.readCxxString();
// let cost = (message.length + name.length) * this.millisecondsPerCharacters;
// if (cost < this.minimumCost) cost = this.minimumCost;
// this.checkCost(, cost);
// if (this.lengthLimit !== -1)
// {
// if (message.length > this.lengthLimit)
// {
// ptr.move(-0x20);
// message = message.substr(0, this.lengthLimit);
// ptr.writeCxxString(message);
// }
// }
// this.fire(name, message);
// };
// constructor()
// {
// super();
// netevent.before(PacketId.Text).on(this.chatlistener);
// }
// }
// export = new ChatManager;
<file_sep>/src/lib/averager.ts
export class Averager
{
private readonly samples:number[] = [];
private total:number = 0;
private i:number = 0;
constructor(public readonly count:number)
{
}
put(sample:number):void
{
const oldsample = this.samples[this.i];
if (oldsample) this.total -= oldsample;
this.total += sample;
this.samples[this.i] = sample;
this.i = (this.i + 1) % this.count;
}
get():number
{
return this.total / this.samples.length;
}
}
<file_sep>/src/server_lib/lang/en_GB.ts
import { freeze } from './freeze';
import { LangId } from './langid';
const lang_data = {
id: "en_GB" as LangId,
commands:{},
item:{}
};
freeze(lang_data);
export = lang_data;
<file_sep>/src/server_lib/jsonwatcher.ts
"use strict";
import Event from "krevent";
import fs = require("fs");
import path = require("path");
export class JsonWatcher<T> {
private asyncwork:Promise<void> = Promise.resolve();
private savedTime = 0;
private mtime = 0;
public readonly onUpdate = new Event();
private datastr = '';
private readonly watcher:fs.FSWatcher;
public data:T;
constructor(public readonly filepath:string, public readonly defaultData:T) {
const filename = path.basename(filepath);
this.watcher = fs.watch(path.dirname(filepath), (event, who) => {
if (who !== filename)
return;
this.load();
});
this.data = defaultData;
this.load();
}
close():void {
this.watcher.close();
}
load():void {
if (Date.now() <= this.savedTime)
return;
this.asyncwork = this.asyncwork
.then(async()=>{
try {
const stat = await fs.promises.stat(this.filepath);
if (this.mtime === stat.mtimeMs) return;
this.mtime = stat.mtimeMs;
const content = await fs.promises.readFile(this.filepath, 'utf-8');
if (this.datastr === content) return;
this.datastr = content;
try {
const newdata = JSON.parse(content);
this.onUpdate.fire(newdata, this.data);
this.data = newdata;
}
catch (err) {
console.error(err);
}
}
catch (err) {
if (err.code === 'ENOENT')
{
if (this.mtime !== 0) {
this.mtime = 0;
this.data = this.defaultData;
this.datastr = '';
this.onUpdate.fire(this.data, this.data);
}
}
this.save();
}
});
}
save():void {
this.asyncwork = this.asyncwork.then(() => {
this.savedTime = Date.now() + 500;
const content = JSON.stringify(this.data, null, 4);
return fs.promises.writeFile(this.filepath, content);
}).catch(err => console.error(err));
}
}
exports.JsonWatcher = JsonWatcher;
//# sourceMappingURL=index.js.map<file_sep>/src/server/module/region.ts
import { Box, Vector3 } from "krgeometry";
import ID from "@mcbe/identifier/id";
import { execute, tp } from "@mcbe/command";
import Identifier from "@mcbe/identifier";
import { callAtNextTick } from "@mcbe/nexttick";
import { DimensionId } from "bdsx/common";
import { TickingArea, Block } from "@bdsx/block";
import { restoreBlock } from "@bdsx/restoreblock";
import LOG from "@mcbe/ruakr_log";
import { User, UserExtra, Container } from "@bdsx/ruakr_user";
import { Pusher } from "./pusher";
import { banlist } from "@bdsx/ruakr_ban";
const regions = new Set<Region>();
let regionListTemp = new Set<Region>();
export class RegionComponent implements UserExtra
{
regions = new Set<Region>();
constructor(public readonly user:User)
{
}
onDeath():void
{
for (const old of this.regions)
{
old.onDeath(this.user);
}
}
onUpdateReal():void
{
const oldregions = this.regions;
if (this.user.dimension === DimensionId.Overworld)
{
const pos = this.user.position;
let errorFrom:Region|null = null;
let errorMsg:string|null = null;
for (const region of Region.pick(pos))
{
if (!oldregions.delete(region))
{
const error = region.onEnter(this.user);
if (error)
{
if (!this.user.isAdminMode())
{
errorFrom = region;
errorMsg = error;
}
continue;
}
}
regionListTemp.add(region);
}
for (const old of oldregions)
{
old.onLeave(this.user);
}
if (errorFrom)
{
errorFrom.pushUser(this.user, 2, errorMsg!);
}
}
else
{
for (const old of oldregions)
{
old.onLeave(this.user);
}
}
this.regions = regionListTemp;
regionListTemp = oldregions;
regionListTemp.clear();
}
onDispose():void
{
for (const old of this.regions)
{
old.onLeave(this.user);
}
this.regions.clear();
}
onDestroyStart(block:Block):void
{
if (this.user.dimension !== DimensionId.Overworld) return;
const regions = [...Region.pick(block.pos)];
if (!this.user.isAdminMode())
{
for (const region of regions)
{
if (!region.canWrite(this.user, block.pos))
{
region.pushUser(this.user, 5, `${region.name} - 블럭 파괴 금지`);
return;
}
}
}
for (const region of regions)
{
region.onDestroyStart(this.user, block);
}
}
onDestroy(block:Block):boolean
{
if (this.user.dimension !== DimensionId.Overworld) return false;
const regions = [...Region.pick(block.pos)];
if (!this.user.isAdminMode())
{
for (const region of regions)
{
if (!region.canWrite(this.user, block.pos))
{
switch (block.id)
{
case ID.seagrass:
case ID.tallgrass:
case ID.kelp:
case ID.yellow_flower:
case ID.red_flower:
case ID.double_plant:
region.pushUser(this.user, 5, `${region.name} - 블럭 파괴 금지`);
return false;
default:
const res = restoreBlock(this.user, block);
callAtNextTick(()=>{
let score:number;
if (res)
{
if (Container.getFlags(block.id) === Container.INVALID)
{
score = 8;
}
else
{
score = 15;
}
}
else
{
score = 30;
}
banlist.warning(this.user, score, {
action: LOG.Action.AggressiveDestroy,
block,
item2: this.user.hand,
msg: `in ${region.name}`
});
this.user.kill();
this.user.tellraw('§c※주의※: §r계속 반복하면 추방될 수 있어요');
});
break;
}
return false;
}
}
}
for (const region of regions)
{
region.onDestroy(this.user, block);
}
return false;
}
onPlace(block:Block, hand:Identifier):boolean
{
if (this.user.dimension !== DimensionId.Overworld) return false;
for (const region of Region.pick(block.pos))
{
if (!this.user.isAdminMode() && !region.canWrite(this.user, block.pos))
{
this.user.info(`${region.name} - 블럭 설치 금지`);
block.destroy();
return true;
}
else
{
if (region.onPlace(this.user, block, hand))
{
return true;
}
}
}
return false;
}
onInterect(block:Block):boolean
{
if (this.user.dimension !== DimensionId.Overworld) return false;
const hand = this.user.hand;
if (hand === ID.bucket || hand === ID.flint_and_steel)
{
let tickingarea:TickingArea|null = null;
const checkWater = (pos:Vector3)=>{
for (const region of Region.pick(pos))
{
if (!this.user.isAdminMode() && !region.canWrite(this.user, pos))
{
if (tickingarea === null)
{
tickingarea = this.user.getTickingArea();
}
const upblock = tickingarea.getBlock(pos);
if (!upblock) break;
switch (upblock.id)
{
case ID.flowing_lava:
case ID.flowing_water:
if (hand === ID.bucket)
{
execute(this.user.name).setblock(pos, ID.air);
this.user.info(`${region.name} - 블럭 설치 금지`);
return true;
}
break;
case ID.fire:
if (hand === ID.flint_and_steel)
{
execute(this.user.name).setblock(pos, ID.air);
this.user.info(`${region.name} - 블럭 설치 금지`);
return true;
}
break;
}
break;
}
}
return false;
};
checkWater(block.pos.add(Vector3.Y)) ||
checkWater(block.pos.sub(Vector3.Y)) ||
checkWater(block.pos.add(Vector3.Z)) ||
checkWater(block.pos.sub(Vector3.Z)) ||
checkWater(block.pos.add(Vector3.X)) ||
checkWater(block.pos.sub(Vector3.X));
}
for (const region of Region.pick(block.pos))
{
if (!this.user.isAdminMode() && !region.canInterect(this.user, block.pos))
{
const message = region.name + ' - 상호작용 금지';
switch (hand)
{
case ID.flint_and_steel:
this.user.info(message);
this.user.kill();
break;
case ID.bucket:
this.user.info(message);
this.user.kill();
break;
default:
const ctype = Container.getFlags(block.id);
if (ctype !== Container.INVALID && ctype !== Container.CHEST_ENDER)
{
banlist.warning(this.user, 10, {action: LOG.Action.AggressiveInteract, block, msg: `in ${region.name}`});
this.user.kill();
this.user.tellraw('§c※주의※: §r계속 반복하면 추방될 수 있어요');
}
else
{
region.pushUser(this.user, 5, message);
}
break;
}
return true;
}
else
{
if (region.onInterect(this.user, block))
{
return true;
}
}
}
return false;
}
}
const emptyBox = new Box(0, 0, 0, 0, 0, 0);
export abstract class Region
{
constructor(
public readonly name:string,
public cube:Box = emptyBox,
public bottomY:number = (cube.y1+cube.y2)/2)
{
regions.add(this);
}
contains(pos:VectorXYZ):boolean
{
return this.cube.contains(pos);
}
containsXZ(pos:VectorXYZ):boolean
{
return this.cube.containsXZ(pos);
}
moveBy(pos:Vector3):void
{
this.cube = this.cube.moveBy(pos);
this.bottomY += pos.y;
}
remove():boolean
{
if (!regions.delete(this)) return false;
return true;
}
onEnter(user:User):string|null
{
return null;
}
onLeave(user:User):void
{
}
canWrite(user:User|null, pos:Vector3):boolean
{
return true;
}
canInterect(user:User|null, pos:Vector3):boolean
{
return true;
}
onPlace(user:User, block:Block, hand:Identifier):boolean
{
return false;
}
onInterect(user:User, block:Block):boolean
{
return false;
}
onDestroyStart(user:User, block:Block):void
{
}
onDestroy(user:User, block:Block):void
{
}
onDeath(user:User):void
{
}
onPistonPush(user:User, block:Block, pistonPos:Vector3, oldpos:Vector3):boolean
{
return false;
}
rotate180(user:User, pos:Vector3, displayMessage:string):void
{
user.extra(Pusher).rotate180(pos, displayMessage);
}
pushUser(user:User, distance:number, displayMessage:string):void
{
user.extra(Pusher).pushFrom(this, this.bottomY, distance, displayMessage);
}
static * pick(pos:Vector3):IterableIterator<Region>
{
for (const r of regions)
{
if (r.contains(pos)) yield r;
}
}
}
export class WriteLock extends Region
{
canWrite(user:User):boolean
{
return false;
}
}
export class PlaceLock extends Region
{
onPlace(user:User, block:Block):boolean
{
user.info(`${this.name} - 블럭 설치 금지`);
block.destroy();
return true;
}
}
export class FilteredWriteLock extends Region
{
constructor(name:string, cube:Box)
{
super(name, cube);
}
canWrite(user:User):boolean
{
return user.isAdminMode();
}
}
<file_sep>/src/server/structure/tradecenter.ts
import Identifier from "@mcbe/identifier";
import ID from "@mcbe/identifier/id";
import { setblockWithoutError, fill, getItemCounts } from "@mcbe/command";
import { realTime } from "@mcbe/timer/realtime";
import { Store, Storage } from "@mcbe/store";
import { createItem } from "@mcbe/system_server";
import { SCORE_LIMIT } from "@mcbe/ruakr_const";
import { itemLang } from "@mcbe/lang";
import { Vector3, Box } from "krgeometry";
import { ItemList } from "@mcbe/item";
import { setFarBlock, setFarTicker } from "@mcbe/farticker";
import LOG from "@mcbe/ruakr_log";
import { User } from "@bdsx/ruakr_user";
import { Block } from "@bdsx/block";
import { restoreBlockSlow, restorePistonPush } from "@bdsx/restoreblock";
import { setSchedule } from "../../lib/timeschdule";
import { ArrayMap } from "../../lib/arraymap";
import { Region } from "../module/region";
// import { HardInventory } from "../module/hardinventory";
import { VAR_WALLET_MONEY, Wallet } from "../module/wallet";
import { CID } from "../customid";
import { DDBlockExtra } from "../ddblock";
import { SoftInventory } from "../module/softinventory";
export const DIAMOND_PRICE = 1000000;
const MINIMUM_MONEY = 5000000;
const TERRACOTA_DATA = [0,2,3,4,5];
const MAIN_ITEM = ID.diamond;
const SELL_ALL_FILTER = new Set<Identifier>([
ID.skull,
ID.arrow,
CID.zone_maker_torch,
CID.tempblock,
CID.spawnportal,
]);
export class TradeExtra
{
target:TradingBlock|null = null;
expireTime:number = 0;
count:number = 0;
expireTest(target:TradingBlock):void
{
if (this.target !== target)
{
this.count = 0;
}
else if (realTime.now > this.expireTime)
{
this.count = 0;
}
this.expireTime = realTime.now + 30000;
this.target = target;
}
}
export const tradestore = new Store('$trade');
let trade_main:Storage;
let trade_price:Storage;
let trade_stock:Storage;
let trade_target:Storage;
let trade_min:Storage;
let trade_max:Storage;
export function priceRound(price:number):number
{
if (price < 10) return Math.round(price);
const v = Math.pow(10, Math.floor(Math.log10(price))) / 10;
return Math.round(price / v) * v;
}
function priceToFixed(price:number, div:number):string
{
let out = ((price / div) |0).toString();
price %= div;
if (price === 0) return out;
out += '.';
for (;;)
{
div /= 1000;
const str = ((price / div) |0).toString();
out += '0'.repeat(3 - str.length);
out += str;
price %= div;
if (div === 1)
{
if (price !== 0) return out + '.' + (price * 10 | 0);
return out;
}
if (price === 0) return out;
out += ' ';
}
}
export function priceToString(price:number):string
{
price = Math.round(price * 10) / 10;
// if (price >= 1000000000) return '§4'+priceToFixed(price, 1000000000)+'kD§f';
if (price >= 1000000) return '§6'+priceToFixed(price, 1000000)+'D§f';
// if (price >= 1000) return '§e'+priceToFixed(price, 1000)+'mD§f';
if (price >= 1000) return '§e'+price+'µD§f';
if (price === 0) return '§a0µD§f';
return '§a'+price+'µD§f';
}
function makeId(id:Identifier, data:number):string
{
const out = data > 0 ? id.minified+'/'+data : id.minified;
console.assert(out.length <= SCORE_LIMIT, `${id} is too long (${out})`);;
return out;
}
const allBlocks:TradingBlock[] = [];
const sellableItems = new ArrayMap<Identifier, TradingBlock>();
function textWidth(text:string):number
{
let size = 0;
for (let i=0;i<text.length;i++)
{
const chr = text.charCodeAt(i);
size += (chr < 0x80) ? 1 : 2;
}
return size;
}
export const tradeCenter = {
getMoney():number
{
return trade_main.get('money') || 0;
},
getDiamond():number
{
return trade_stock.get(MAIN_ITEM.minified) || 0;
},
removeDiamond(gold:number):boolean
{
const count = tradeCenter.getDiamond();
if (gold > count) return false;
trade_stock.remove(MAIN_ITEM.minified, gold);
return true;
},
removeMoney(money:number):void
{
tradeCenter.addMoney(-money);
},
repackMoney(price:number):number
{
const money = tradeCenter.getMoney();
if (money === 0) return 0;
if (money - price >= MINIMUM_MONEY) return price;
function unpack(money:number):number
{
return Math.exp((money - MINIMUM_MONEY) / MINIMUM_MONEY) * MINIMUM_MONEY;
}
function pack(packed:number):number
{
return Math.log(packed / MINIMUM_MONEY) * MINIMUM_MONEY + MINIMUM_MONEY;
}
let plane = money - MINIMUM_MONEY;
let money_from = money;
if (plane < 0)
{
plane = 0;
}
else
{
price -= plane;
money_from = MINIMUM_MONEY;
}
const money_to = unpack(pack(money_from) - price);
price = Math.max(Math.floor(money_from - money_to + plane), 0);
return price;
},
addMoney(money:number):void
{
if (money === 0) return;
let total = tradeCenter.getMoney();
total += money;
trade_main.set('money', total);
if (total < 0)
{
LOG.error({action:LOG.Action.Assertion, msg:`trade center total minus: ${priceToString(money)}`});
}
if (money > 0)
{
const max = trade_main.get('money_max') || 0;
if (total > max) trade_main.set('money_max', total);
}
},
getBasePriceOf(item:Identifier, data:number = 0):number
{
const id = makeId(item, data);
const basePrice = trade_price.get(id);
if (basePrice === undefined) return -1;
return basePrice;
},
getSellings(user:User):ItemList
{
const sellings = new ItemList;
for (const item of user.extra(SoftInventory).main())
{
if (!sellableItems.has(item.id)) continue;
if (SELL_ALL_FILTER.has(item.id)) continue;
sellings.add(item.id, item.count);
}
return sellings;
},
async testSellAll(user:User, msg:string):Promise<void>
{
const sellings = tradeCenter.getSellings(user);
if (sellings.size() === 0)
{
user.infoFast(`전부 팔기 - 팔 것 없음`);
return;
}
let text = `전부 팔기 - ${msg}\n`;
let lineLen = 0;
for (const {id, count} of sellings.values())
{
const itext = `${itemLang.get(id)} ${count}개, `;
text += itext;
lineLen += textWidth(itext);
if (lineLen > 20)
{
lineLen = 0;
text += '\n';
}
}
user.infoWith(text, 0, 200, 20);
},
async sellAll(user:User):Promise<void>
{
const sellings = tradeCenter.getSellings(user);
if (sellings.size() === 0)
{
user.infoFast(`전부 팔기 - 팔 것 없음`);
return;
}
let total = 0;
for (let {id, count} of sellings.values())
{
const blocks = sellableItems.get(id);
if (!blocks) continue;
for (const block of blocks)
{
const [selledPrice, selledCount] = await block.sell(user, count);
if (selledCount === 0) continue;
user.tellraw(`§e${block.targetName} ${selledCount}개 - ${priceToString(selledPrice)}`);
count -= selledCount;
total += selledPrice;
if (count <= 0) break;
}
}
user.infoFast(`전부 팔기 완료 - 총액 ${priceToString(total)}`);
},
};
export class CardBlock extends Region
{
constructor(pos:Vector3)
{
super('카드 생성기', Box.fromVector(pos, pos), pos.y);
}
build():void
{
setFarBlock(this.cube.getPoint1(), CID.trade_card_block);
}
onPistonPush(user:User, block:Block, pistonPos:Vector3, oldPos:Vector3):boolean
{
return restorePistonPush(user, block, pistonPos, oldPos);
}
onInterect(user:User, block:Block):boolean
{
user.infoFast(`현재: ${priceToString(user.storage.get(VAR_WALLET_MONEY)||0)}`);
return true;
}
onDestroy(user:User, block:Block):void
{
restoreBlockSlow(user, block);
createItem(CID.trade_card, block.pos.add(Vector3.HALF));
}
}
export class TradingBlock extends Region
{
protected readonly shortId:string;
public readonly targetDV:number[];
public readonly centerBlock:Identifier;
public readonly centerBlockDV:number;
public readonly targetName:string;
constructor(
public readonly position:Vector3,
public readonly startPrice:number,
public readonly target:Identifier,
targetDV?:number[],
centerBlock?:Identifier,
centerBlockDV?:number)
{
super(itemLang.get(target, targetDV ? targetDV[0] : 0)+' 교환기',
new Box(position.x-1, position.y, position.z,
position.x+1, position.y+2, position.z),
position.y
);
this.targetName = this.name.substr(0, this.name.length - 4);
this.targetDV = targetDV === undefined ? [0] : targetDV;
if (centerBlock)
{
this.centerBlock = centerBlock;
this.centerBlockDV = centerBlockDV || 0;
}
else
{
this.centerBlock = target;
this.centerBlockDV = centerBlockDV !== undefined ? centerBlockDV : Math.max(this.targetDV[0], 0);
}
this.shortId = makeId(target, this.targetDV[0]);
allBlocks.push(this);
sellableItems.push(target, this);
}
updatePrice():void
{
}
async sellAll(user:User):Promise<[number, number]>
{
const sellCount = await user.takeItems(this.target, this.targetDV);
if (sellCount <= 0) return [0, 0];
const price = this.getSellPrice(sellCount);
user.infoFast(`§7${this.targetName} ${sellCount}개 - ${priceToString(price)}`);
user.extra(Wallet).add(price);
trade_stock.add(this.shortId, sellCount);
return [price, sellCount];
}
async sell(user:User, sellCount:number):Promise<[number, number]>
{
const wallet = user.extra(Wallet);
if (sellCount <= 0)
{
user.infoFast(`${this.targetName}\n판매 개수를 정해주세요`);
return [0, 0];
}
const maxCount = user.extra(SoftInventory).inventory.getCount(this.target);
if (sellCount > maxCount) sellCount = maxCount;
if (sellCount <= 0)
{
user.infoFast(`${this.targetName} 판매 실패\n하나도 없음`);
return [0, 0];
}
const count = await user.takeItems(this.target, this.targetDV, sellCount);
if (count <= 0)
{
user.infoFast(`${this.targetName} 판매 실패\n하나도 없음`);
return [0, 0];
}
const price = this.getSellPrice(count);
LOG.verbose({user, action:LOG.Action.Sell, item: this.target, count, msg: `with ${priceToString(price)}`});
if (price === 0)
{
user.infoFast(`${this.targetName} ${count}개 기부 완료`);
}
else
{
user.infoFast(`${this.targetName} ${count}개 판매 완료\n개당 ${priceToString(price/count)} / 전체 ${priceToString(price)}`);
wallet.add(price);
}
trade_stock.add(this.shortId, count);
this.onSubmit(-price);
return [price, count];
}
async buy(user:User, buyCount:number):Promise<[number, number]>
{
const extra = user.extra(TradeExtra);
extra.expireTest(this);
const wallet = user.extra(Wallet);
if (extra.count === 0)
{
user.infoFast(`${this.targetName}\n구매 개수를 정해주세요`);
return [0, 0];
}
const stock = this.getStock();
if (stock !== -1)
{
if (buyCount > stock) buyCount = stock;
if (stock <= 0)
{
user.infoFast(`${this.targetName} 구매 실패\n제고 부족`);
return [0, 0];
}
}
const price = this.getBuyPrice(buyCount);
const money = wallet.get();
if (money < price)
{
user.infoFast(`${this.targetName} 구매 실패\n금액 부족(가격: ${priceToString(price)}`);
return [0, 0];
}
wallet.set(money - price);
LOG.verbose({user, action:LOG.Action.Buy, item:this.target, count:buyCount, msg: `with ${priceToString(price)}`});
user.infoFast(`${this.targetName} ${buyCount}개 구매 완료\n개당 ${priceToString(price/buyCount)} / ${priceToString(price)}`);
user.giveItem(this.target, Math.max(this.targetDV[0], 0), buyCount);
trade_stock.remove(this.shortId, buyCount);
this.onSubmit(price);
return [price, buyCount];
}
test():void
{
}
getStock():number
{
return trade_stock.get(this.shortId) || 0;
}
getOneBuyPrice():number
{
return this.startPrice;
}
getBuyPrice(count:number):number
{
return count * this.startPrice;
}
getMaxBuyCount(money:number):number
{
return Math.floor(money / this.startPrice);
}
getSellPrice(count:number):number
{
return count * this.startPrice;
}
build():this
{
const U = this.position.add(Vector3.Y.mul(2));
const C = this.position.add(Vector3.Y);
const D = this.position;
setblockWithoutError(C, this.centerBlock, this.centerBlockDV);
setblockWithoutError(U.sub(Vector3.X), CID.trade_add1);
setblockWithoutError(U, CID.trade_add8);
setblockWithoutError(U.add(Vector3.X), CID.trade_add64);
setblockWithoutError(D.sub(Vector3.X), CID.trade_sub1);
setblockWithoutError(D, CID.trade_sub8);
setblockWithoutError(D.add(Vector3.X), CID.trade_sub64);
setblockWithoutError(C.sub(Vector3.X), CID.trade_question);
setblockWithoutError(C.add(Vector3.X), CID.trade_submit);
return this;
}
async addCount(user:User, count:number):Promise<void>
{
const extra = user.extra(TradeExtra);
extra.expireTest(this);
count = extra.count += count;
if (count === 0)
{
user.infoFast(`${this.targetName} 0개 구매/판매`);
}
else if (count < 0)
{
const count1 = await getItemCounts(user.name, this.target, this.targetDV);
const count2 = user.extra(SoftInventory).inventory.getCount(this.target);
const max = Math.min(count1, count2);
if (max === 0)
{
extra.count = 0;
user.infoFast(`${this.targetName} 0개 판매\n하나도 없음`);
}
else
{
let error:string = '';
count = -count;
if (count > max)
{
count = max;
extra.count = -max;
error = '\n소유량 전부';
}
const total = this.getSellPrice(count);
user.infoFast(`${this.targetName} ${count}개 판매\n개당 ${priceToString(total/count)} / 전체 ${total ? priceToString(total) : '0💎(기부)'}${error}`);
}
}
else
{
const wallet = user.extra(Wallet);
const money = wallet.get();
const max = this.getMaxBuyCount(money);
if (max <= 0)
{
extra.count = 0;
const buyPrice = this.getOneBuyPrice();
let error = '';
if (this.getStock() === 0)
{
error += `제고 없음`;
}
if (money < buyPrice)
{
if (error) error += ', ';
error += `금액 부족(${priceToString(buyPrice)})`;
}
user.infoFast(`${this.targetName} 구매 불가능\n${error || '원인 불명/오류'}`);
return;
}
let error:string = '';
if (count > max)
{
extra.count = count = max;
const stock = this.getStock();
if (max === stock)
{
error = '\n제고 끝';
}
else
{
error = '\n최대 금액';
}
}
const total = this.getBuyPrice(count);
user.infoFast(`${this.targetName} ${count}개 구매\n개당 ${priceToString(total/count)} / 전체 ${priceToString(total)}${error}`);
}
}
showPrice(user:User):void
{
const extra = user.extra(TradeExtra);
extra.target = null;
const price = this.getOneBuyPrice();
let buyerr = '';
let stockText = '';
if (this.target !== MAIN_ITEM)
{
const stock = this.getStock();
if (stock === 0) stockText = ', 제고 없음';
else if (stock !== -1) stockText = `, 제고 ${stock}개`;
const m = tradeCenter.getMoney();
if (m === 0) buyerr = '(기부 받음)';
else if (m < MINIMUM_MONEY) buyerr = '(재정난)';
}
user.infoFast(`${this.targetName}${stockText}\n가격 ${priceToString(price)}\n매입 ${priceToString(this.getSellPrice(1))}${buyerr}`);
}
async submit(user:User):Promise<void>
{
const extra = user.extra(TradeExtra);
extra.expireTest(this);
if (extra.count === 0)
{
user.infoFast(`${this.targetName}\n구매/판매 개수를 정해주세요`);
return;
}
if (extra.count < 0)
{
await this.sell(user, -extra.count);
}
else
{
await this.buy(user, extra.count);
}
extra.target = null;
}
onSubmit(price:number):void
{
}
activeButton(user:User, block:Block):boolean
{
switch (block.id)
{
case CID.trade_add1:
this.addCount(user, 1);
break;
case CID.trade_add8:
this.addCount(user, 8);
break;
case CID.trade_add64:
this.addCount(user, 64);
break;
case CID.trade_sub1:
this.addCount(user, -1);
break;
case CID.trade_sub8:
this.addCount(user, -8);
break;
case CID.trade_sub64:
this.addCount(user, -64);
break;
case CID.trade_submit:
this.submit(user);
break;
case CID.trade_question:
this.showPrice(user);
break;
default:
return false;
}
return true;
}
onInterect(user:User, block:Block):boolean
{
this.activeButton(user, block);
return true;
}
onDestroy(user:User, block:Block):void
{
this.activeButton(user, block);
restoreBlockSlow(user, block, 300);
}
onPistonPush(user:User, block:Block, pistonPos:Vector3, oldPos:Vector3):boolean
{
return restorePistonPush(user, block, pistonPos, oldPos);
}
static updatePriceAll():void
{
for (const block of allBlocks)
{
block.updatePrice();
}
}
static intersect(cube:Box):boolean
{
for (const block of allBlocks)
{
if (block.cube.intersect(cube)) return true;
}
return false;
}
}
class TradingBlockSelling extends TradingBlock
{
constructor(
position:Vector3,
startPrice:number,
target:Identifier,
targetDV?:number[],
centerBlock?:Identifier,
centerBlockDV?:number)
{
super(position, startPrice, target, targetDV, centerBlock, centerBlockDV);
}
getStock():number
{
return -1;
}
onSubmit(money:number):void
{
tradeCenter.addMoney(money);
}
getSellPrice(count:number):number
{
return tradeCenter.repackMoney(priceRound(this.startPrice / BUY_WEIGHT) * count);
}
}
const SAME_VALUE_MIN = 0.5;
const SAME_VALUE_MAX = 1.5;
const PRICE_MUL_MAX = 0.8; // when higher stock, maximum multiply
const PRICE_MUL_MIN = 1.2; // when lower stock, minimum multiply
const BUY_WEIGHT = 1.1;
const MAX_PRICE_WEIGHT_SELL = 3;
const MAX_PRICE_WEIGHT_SELL_TOTAL = 1/50;
function clamp(min:number, v:number, max:number):number
{
if (v <= min) return min;
if (v >= max) return max;
return v;
}
function priceMult(price:number, mult:number):number
{
const oriprice = priceRound(price);
if (mult === 1) return oriprice;
let newprice = priceRound(price*mult);
if (newprice === 0) return 0;
if (newprice === oriprice) newprice ++;
return newprice;
}
class TradingCalculate
{
public readonly basePrice:number;
public readonly target:number;
constructor(public readonly block:TradingBlockAuto)
{
this.basePrice = block.getBasePrice();
this.target = block.getTargetStock();
}
getLowerPrice(stockAt:number):number
{
const c = SAME_VALUE_MIN * PRICE_MUL_MIN;
return this.basePrice * this.target * c / Math.max(stockAt, 0.5);
}
getHigherPrice(stockAt:number):number
{
return Math.pow(0.25, stockAt/this.target - SAME_VALUE_MAX) * this.basePrice * PRICE_MUL_MAX;
}
getMiddlePrice(stockAt:number):number
{
const c = (PRICE_MUL_MAX-PRICE_MUL_MIN)/(SAME_VALUE_MAX-SAME_VALUE_MIN);
return ((stockAt - this.target*SAME_VALUE_MIN) * c*this.target + PRICE_MUL_MIN)*this.basePrice;
}
getPriceAt(stockAt:number):number
{
const sameMin = Math.round(this.target * SAME_VALUE_MIN);
const sameMax = Math.round(this.target * SAME_VALUE_MAX);
if (stockAt < sameMin) return this.getLowerPrice(stockAt);
if (stockAt < sameMax) return this.getMiddlePrice(stockAt);
return this.getHigherPrice(stockAt);
}
calc(from:number, to:number, mult:number = 1, minPrice:number=0, maxPrice:number=Infinity):number
{
const sameMin = Math.round(this.target * SAME_VALUE_MIN);
const sameMax = Math.round(this.target * SAME_VALUE_MAX);
let price = 0;
const sameFrom = Math.max(sameMin, from);
const sameTo = Math.min(sameMax, to);
if (to > sameMin && from < sameMax)
{
price += (sameTo - sameFrom) * priceMult(this.basePrice, mult);
}
const higher_from = Math.max(sameMax, from);
for (let i=higher_from;i<to;i++)
{
price += priceMult(this.getHigherPrice(i), mult);
}
const lower_to = Math.min(sameMin, to);
for (let i=from;i<lower_to;i++)
{
const oneprice = this.getLowerPrice(i);
price += Math.max(priceMult(Math.min(oneprice, maxPrice), mult), minPrice);
}
return price;
}
count(money:number, mult:number=1):number
{
const startStock = this.block.getStock();
if (startStock <= 0) return 0;
let stock = startStock;
const sameMin = Math.round(this.target * SAME_VALUE_MIN);
const sameMax = Math.round(this.target * SAME_VALUE_MAX);
while (stock > sameMax)
{
money -= priceMult(this.getHigherPrice(--stock), mult);
if (money < 0) return startStock - stock - 1;
}
if (stock >= sameMin)
{
const price = priceMult(this.basePrice, mult);
const count = money / price | 0;
const remaining = stock - sameMin;
if (count <= remaining)
{
return startStock - stock + count;
}
stock -= remaining;
money -= price * remaining;
}
if (stock === 0) return startStock;
for (;;)
{
money -= priceMult(this.getLowerPrice(--stock), mult);
if (money < 0) return startStock - stock - 1;
if (stock === 0) return startStock;
}
}
}
export class TradingBlockAuto extends TradingBlockSelling
{
constructor(
position:Vector3,
price:number,
targetStock:number,
target:Identifier,
targetDV?:number[],
centerBlock?:Identifier,
centerBlockDV?:number,
private readonly minimumStockChange:number = 0)
{
super(position, price, target, targetDV, centerBlock, centerBlockDV);
console.assert(minimumStockChange >= 0);
trade_target.setDefault(this.shortId, targetStock);
trade_price.setDefault(this.shortId, price);
}
getStock():number
{
return trade_stock.get(this.shortId) || 0;
}
updatePrice():void
{
const stock = this.getStock();
const target = Math.max(this.getTargetStock(), 3);
const min = this.getStockMin();
const max = this.getStockMax();
const basePrice = this.getBasePrice();
const calc = new TradingCalculate(this);
let newPrice = 0;
if (min === 0 && max === 0 && stock === 0)
{
newPrice = basePrice;
}
else
{
const newTarget = Math.max(clamp(Math.floor(target*0.9), (max - min)*2, Math.round(target*1.5)), 3);
this._setStockTarget(newTarget);
newPrice = (calc.getPriceAt(min) + calc.getPriceAt(max)) / 2;
newPrice = Math.max(Math.round(clamp(basePrice*0.8, newPrice, basePrice*1.2)), 1);
this._setBasePrice(newPrice);
}
this._setStockMax(stock);
this._setStockMin(stock);
// if (stock < target)
// {
// let chance = 0;
// if (stock === 0 && max === 0 && min === 0)
// {
// chance = this.minimumStockChange;
// }
// else
// {
// chance = Math.max(10000 / newPrice, this.minimumStockChange);
// }
// let count = Math.floor(chance);
// if (Math.random() < chance - count) count ++;
// trade_stock.add(this.shortId, Math.min(count, 32, target - stock));
// }
}
getStockMin():number
{
return trade_min.get(this.shortId) || 0;
}
getStockMax():number
{
return trade_max.get(this.shortId) || 0;
}
getTargetStock():number
{
return trade_target.get(this.shortId) || 0;
}
getBasePrice():number
{
return trade_price.get(this.shortId) || 0;
}
onSubmit(price:number):void
{
super.onSubmit(price);
const count = this.getStock();
if (count < this.getStockMin()) this._setStockMin(count);
else if (count > this.getStockMax()) this._setStockMax(count);
}
getOneBuyPrice():number
{
let stock = this.getStock();
if (stock > 0) stock --;
const calc = new TradingCalculate(this);
return calc.calc(stock, stock+1, BUY_WEIGHT, 1);
}
getBuyPrice(count:number):number
{
const stock = this.getStock();
const calc = new TradingCalculate(this);
return calc.calc(Math.max(stock - count, 0), stock, BUY_WEIGHT, 1);
}
getMaxBuyCount(money:number):number
{
return new TradingCalculate(this).count(money, BUY_WEIGHT);
}
getSellPrice(count:number):number
{
const stock = this.getStock();
const calc = new TradingCalculate(this);
const maxPrice = Math.min(
calc.basePrice * MAX_PRICE_WEIGHT_SELL,
tradeCenter.getMoney() * MAX_PRICE_WEIGHT_SELL_TOTAL);
const price = calc.calc(stock, stock + count, 1, 0, maxPrice);
return tradeCenter.repackMoney(price);
}
private _setStockMin(count:number):void
{
trade_min.set(this.shortId, count);
}
private _setStockMax(count:number):void
{
trade_max.set(this.shortId, count);
}
private _setStockTarget(count:number):void
{
trade_target.set(this.shortId, count);
}
private _setBasePrice(price:number):void
{
trade_price.set(this.shortId, price);
}
}
DDBlockExtra.install([CID.trade_sell_all], {
onCheck(user:User, destroy:boolean):boolean
{
tradeCenter.testSellAll(user, destroy ? '한번 더 부숴주세요!' : '블럭을 부숴주세요!');
return true;
},
onSubmit(user:User):boolean
{
tradeCenter.sellAll(user).catch(LOG.error_obj);
return false;
}
});
Store.onLoad.then(data=>{
trade_main = tradestore.create('main');
trade_price = tradestore.create('price');
trade_stock = tradestore.create('stock');
trade_target = tradestore.create('target');
trade_min = tradestore.create('min');
trade_max = tradestore.create('max');
trade_price.reminify();
trade_stock.reminify();
trade_target.reminify();
trade_min.reminify();
trade_max.reminify();
const diamond_price = trade_main.get('price') || DIAMOND_PRICE;
if (diamond_price !== DIAMOND_PRICE)
{
const mul = DIAMOND_PRICE / diamond_price;
trade_main.set('price', DIAMOND_PRICE);
let totalMoney = 0;
for (const [name, price] of trade_price.entires())
{
trade_price.set(name, Math.round(price * mul));
trade_max.set(name, Math.round(trade_max.get(name)! * mul | 0));
trade_min.set(name, Math.round(trade_min.get(name)! * mul | 0));
}
for (const player of User.store.values())
{
const value = player.get(VAR_WALLET_MONEY);
if (value === undefined) continue;
const revalue = Math.round(value * mul);
totalMoney += revalue;
player.set(VAR_WALLET_MONEY, revalue);
}
const diamondCount = totalMoney / DIAMOND_PRICE | 0;
trade_stock.set(ID.diamond.minified, diamondCount); // change total
const remainedMoney = totalMoney - diamondCount * DIAMOND_PRICE;
const newmoney = Math.round((trade_main.get('money')!|0) * mul) - remainedMoney;
trade_main.set('money', newmoney);
trade_main.set('money_max', newmoney);
trade_main.delete('money_min');
}
const SHOP_MULTIPLY = 40;
type TradingBlockParams = [number, number, number, Identifier, (number[]|number)?, Identifier?, number?, number?]|null;
const MAIN = 0;
const AUTO = 1;
const STAT = 2;
const structure:TradingBlockParams[][][] = [
[
[
// 1F - 0
[STAT, 1000, -1, CID.zone_maker_torch],
[STAT, 200000, -1, CID.tempblock],
[AUTO, 10000, 64, ID.experience_bottle, 0, CID.trade_question, 0, 10],
],
[
// 1F - 1
[MAIN, DIAMOND_PRICE/SHOP_MULTIPLY, 20,MAIN_ITEM, -1, ID.diamond_ore],
[AUTO, 50, 64, ID.coal, 0, ID.coal_ore],
[AUTO, 50, 64, ID.coal, 1, ID.coal_ore],
[AUTO, 200, 50, ID.iron_ingot, -1, ID.iron_ore],
[AUTO, 3000, 20, ID.gold_ingot, -1, ID.gold_ore],
[AUTO, 100, 50, ID.dye, 4, ID.lapis_ore],
[AUTO, 10, 50, ID.redstone, 0, ID.redstone_ore],
[AUTO, 10000, 20, ID.emerald, 0, ID.emerald_ore]
],
[
// 1F - 2
[AUTO, 50, 500, ID.netherrack],
[AUTO, 200, 100, ID.magma],
[AUTO, 200, 100, ID.soul_sand],
[AUTO, 200, 100, ID.glowstone],
[AUTO, 20, 100, ID.quartz, 0, ID.quartz_ore],
[AUTO, 300, 100, ID.nether_brick],
[AUTO, 300, 100, ID.red_nether_brick],
[AUTO, 2000, 50, ID.nether_wart, 0, CID.trade_question],
],
[
// 1F - 3
[AUTO, 2, 100, ID.cobblestone],
[AUTO, 5, 500, ID.stone, -1],
[AUTO, 2, 500, ID.dirt],
[AUTO, 10, 100, ID.sand, 0, ID.sandstone, 3],
[AUTO, 100, 100, ID.glass],
[AUTO, 10, 100, ID.gravel, 0, CID.trade_question],
[AUTO, 20, 100, ID.flint, 0, CID.trade_question],
[AUTO, 100, 50, ID.obsidian],
],
[
// 1F - 4
[AUTO, 30, 100, ID.log],
[AUTO, 100, 10, ID.log, 1],
[AUTO, 30, 100, ID.log, 2],
[AUTO, 100, 10, ID.log, 3],
[AUTO, 100, 10, ID.log2],
[AUTO, 100, 10, ID.log2, 1],
null,
],
[
// 1F - 5
[AUTO, 200, 50, ID.wheat, 0, CID.trade_question],
[AUTO, 2000, 50, ID.carrot, 0, CID.trade_question],
[AUTO, 2000, 50, ID.potato, 0, CID.trade_question],
[AUTO, 600, 100, ID.baked_potato, -1, CID.trade_question],
[AUTO, 2000, 50, ID.beetroot, 0, CID.trade_question],
[AUTO, 2000, 50, ID.pumpkin],
[AUTO, 2000, 50, ID.melon, 0, ID.melon_block],
null,
],
[
// 1F - 6
[AUTO, 600, 100, ID.bread, 0, CID.trade_question],
[AUTO, 800, 100, ID.cooked_chicken, -1, CID.trade_question],
[AUTO, 1200, 100, ID.muttoncooked, -1, CID.trade_question],
[AUTO, 1500, 100, ID.cooked_porkchop, -1, CID.trade_question],
[AUTO, 1500, 100, ID.cooked_beef, -1, CID.trade_question],
[AUTO, 1500, 100, ID.cooked_rabbit, -1, CID.trade_question],
[AUTO, 800, 100, ID.cooked_fish, -1, CID.trade_question],
[AUTO, 800, 100, ID.cooked_salmon, -1, CID.trade_question],
],
[
// 1F - 7
[AUTO, 100, 50, ID.wool, 0],
[AUTO, 1000, 50, ID.wool, 1],
[AUTO, 1000, 50, ID.wool, 2],
[AUTO, 1000, 50, ID.wool, 3],
[AUTO, 1000, 50, ID.wool, 4],
[AUTO, 1000, 50, ID.wool, 5],
[AUTO, 1000, 50, ID.wool, 6],
[AUTO, 1000, 50, ID.wool, 7],
],
[
// 1F - 8
[AUTO, 1000, 50, ID.wool, 8],
[AUTO, 1000, 50, ID.wool, 9],
[AUTO, 1000, 50, ID.wool, 10],
[AUTO, 1000, 50, ID.wool, 11],
[AUTO, 1000, 50, ID.wool, 12],
[AUTO, 1000, 50, ID.wool, 13],
[AUTO, 1000, 50, ID.wool, 14],
[AUTO, 1000, 50, ID.wool, 15],
],
[
// 1F - 9
[AUTO, 1000, 50, ID.red_flower, 0, CID.trade_question],
[AUTO, 1000, 50, ID.red_flower, 1, CID.trade_question],
[AUTO, 1000, 50, ID.red_flower, 2, CID.trade_question],
[AUTO, 1000, 50, ID.red_flower, 3, CID.trade_question],
[AUTO, 1000, 50, ID.red_flower, 4, CID.trade_question],
[AUTO, 1000, 50, ID.red_flower, 5, CID.trade_question],
[AUTO, 1000, 50, ID.red_flower, 6, CID.trade_question],
[AUTO, 1000, 50, ID.red_flower, 7, CID.trade_question],
],
[
// 1F - 10
[AUTO, 1000, 50, ID.red_flower, 8, CID.trade_question],
[AUTO, 1000, 50, ID.red_flower, 9, CID.trade_question],
[AUTO, 1000, 50, ID.red_flower, 10, CID.trade_question],
[AUTO, 1000, 50, ID.yellow_flower, 0, CID.trade_question],
[AUTO, 1000, 50, ID.double_plant, 0, CID.trade_question],
[AUTO, 1000, 50, ID.double_plant, 1, CID.trade_question],
[AUTO, 1000, 50, ID.double_plant, 4, CID.trade_question],
[AUTO, 1000, 50, ID.double_plant, 5, CID.trade_question],
],
],
[
[
// B1F - 0
],
[
// B1F - 1
[AUTO, 500000, 3, ID.skull, 1, CID.trade_question],
[AUTO, 500000, 3, ID.skull, 3, CID.trade_question, 0, 0.5],
[AUTO, 500000, 3, ID.skull, 5, CID.trade_question],
[AUTO, 500000, 3, ID.skull, 0, CID.trade_question],
[AUTO, 500000, 3, ID.skull, 2, CID.trade_question],
[AUTO, 500000, 3, ID.skull, 4, CID.trade_question],
[AUTO, 500000, 3, ID.bell, -1, CID.trade_question],
],
[
// B1F - 2
[AUTO, 500, 5, ID.waterlily, 0, CID.trade_question],
[AUTO, 500, 5, ID.pufferfish, 0, CID.trade_question],
[AUTO, 50, 64, ID.fish, 0, CID.trade_question],
[AUTO, 50, 64, ID.salmon, 0, CID.trade_question],
[AUTO, 200, 10, ID.clownfish, 0, CID.trade_question],
[AUTO, 500, 10, ID.nautilus_shell, 0, CID.trade_question],
],
[
// B1F - 3
[AUTO, 10, 100, ID.stone, 1],
[AUTO, 10, 100, ID.stone, 3],
[AUTO, 10, 100, ID.stone, 5],
[AUTO, 300, 100, ID.clay],
[AUTO, 100, 100, ID.sandstone],
[AUTO, 200, 100, ID.sand, 1, ID.red_sandstone, 3],
[AUTO, 200, 100, ID.red_sandstone],
[AUTO, 2000, 50, ID.cactus, 0, CID.trade_question],
],
[
// B1F - 4
[AUTO, 300, 50, ID.sapling, 0, CID.trade_question],
[AUTO, 1000, 50, ID.sapling, 1, CID.trade_question],
[AUTO, 300, 50, ID.sapling, 2, CID.trade_question],
[AUTO, 1000, 50, ID.sapling, 3, CID.trade_question],
[AUTO, 1000, 50, ID.sapling, 4, CID.trade_question],
[AUTO, 1000, 50, ID.sapling, 5, CID.trade_question],
],
[
// B1F - 5
[AUTO, 100, 50, ID.wheat_seeds, 0, CID.trade_question],
[AUTO, 2000, 50, ID.beetroot_seeds, 0, CID.trade_question],
[AUTO, 2000, 50, ID.pumpkin_seeds, 0, CID.trade_question],
[AUTO, 2000, 50, ID.melon_seeds, 0, CID.trade_question],
[AUTO, 2000, 50, ID.sweet_berries, 0, CID.trade_question],
[AUTO, 2000, 50, ID.dye, 3, CID.trade_question],
[AUTO, 1000, 50, ID.brown_mushroom, 0, ID.brown_mushroom_block, 14],
[AUTO, 1000, 50, ID.red_mushroom, 0, ID.red_mushroom_block, 14],
],
[
// B1F - 6
[AUTO, 100, 100, ID.egg, 0, CID.trade_question],
[AUTO, 500, 100, ID.chicken, 0, CID.trade_question],
[AUTO, 800, 100, ID.muttonraw, 0, CID.trade_question],
[AUTO, 1000, 100, ID.porkchop, 0, CID.trade_question],
[AUTO, 1000, 100, ID.beef, 0, CID.trade_question],
[AUTO, 1000, 100, ID.rabbit, 0, CID.trade_question],
[AUTO, 200, 100, ID.rabbit_hide, 0, CID.trade_question],
[AUTO, 1000, 30, ID.rabbit_foot, 0, CID.trade_question],
],
[
// B1F - 7
[AUTO, 1000, 50, ID.tallgrass, 1, CID.trade_question],
[AUTO, 1000, 50, ID.tallgrass, 2, CID.trade_question],
[AUTO, 100, 500, ID.grass],
[AUTO, 200, 100, ID.snowball, 0, ID.snow],
[AUTO, 200, 100, ID.ice],
[AUTO, 300, 100, ID.packed_ice],
[AUTO, 300, 100, ID.blue_ice],
],
[
// B1F - 8
[AUTO, 5, 400, ID.end_stone],
[AUTO, 50, 400, ID.end_bricks],
[AUTO, 500, 100, ID.purpur_block],
[AUTO, 2000, 50, ID.chorus_fruit, 0, CID.trade_question],
],
[
// B1F - 9
[AUTO, 3000, 10, ID.turtle_shell_piece],
[AUTO, 800, 100, ID.prismarine, 0],
[AUTO, 2000, 100, ID.prismarine, 1],
[AUTO, 1000, 100, ID.prismarine, 2],
[AUTO, 3000, 20, ID.sponge],
[AUTO, 100000, 3, ID.heart_of_the_sea, 0, CID.trade_question],
],
[
// B1F - 10
[AUTO, 2000, 50, ID.dye, 0, CID.trade_question],
[AUTO, 1000, 100, ID.sea_pickle, 0, CID.trade_question],
[AUTO, 500, 100, ID.kelp, 0, CID.trade_question],
[AUTO, 500, 100, ID.dried_kelp, -1, CID.trade_question],
[AUTO, 1000, 100, ID.seagrass, 0, CID.trade_question],
],
],
[
[
// B2F - 0
],
[
// 2F - 1
[AUTO, 100, 30, ID.blaze_rod, 0, CID.trade_question],
[AUTO, 1000, 20, ID.ghast_tear, 0, CID.trade_question],
[AUTO, 400, 30, ID.ender_pearl, 0, CID.trade_question],
[AUTO, 200, 100, ID.spider_eye, 0, CID.trade_question],
[AUTO, 200, 100, ID.rotten_flesh, 0, CID.trade_question],
[AUTO, 1000, 30, ID.phantom_membrane, 0, CID.trade_question],
[AUTO, 1000, 30, ID.magma_cream, 0, CID.trade_question],
[AUTO, 100000, 3, ID.totem, 0, CID.trade_question],
],
[
// 2F - 2
[AUTO, 200, 30, ID.string, 0, CID.trade_question],
[AUTO, 400, 30, ID.gunpowder, 0, CID.trade_question],
[AUTO, 50, 100, ID.bone, 0, ID.bone_block],
[AUTO, 1000, 20, ID.slime_ball, 0, ID.slime],
[AUTO, 50, 100, ID.feather, 0, CID.trade_question],
[AUTO, 200, 100, ID.arrow, 0, CID.trade_question],
[AUTO, 500, 10, ID.book, 0, CID.trade_question],
[AUTO, 1000, 10, ID.lead, 0, CID.trade_question],
],
[
// 2F - 3
[AUTO, 400, 50, ID.leather, 0, CID.trade_question],
[AUTO, 50, 100, ID.reeds, 0, CID.trade_question],
[AUTO, 50, 100, ID.sugar, 0, CID.trade_question],
[AUTO, 2000, 10, ID.bamboo, 0, CID.trade_question],
[AUTO, 500, 20, ID.apple, 0, CID.trade_question],
[AUTO, 70000, 5, ID.golden_apple, 0, CID.trade_question],
[AUTO, 100000, 5, ID.appleenchanted, 0, CID.trade_question],
null
],
[
// 2F - 4
[AUTO, 5, 400, ID.planks, 0],
[AUTO, 20, 400, ID.planks, 1],
[AUTO, 10, 400, ID.planks, 2],
[AUTO, 20, 400, ID.planks, 3],
[AUTO, 20, 400, ID.planks, 4],
[AUTO, 20, 400, ID.planks, 5],
],
[
// 2F - 5
[AUTO, 500, 50, ID.hardened_clay],
[AUTO, 1000, 100, ID.rail, 0, CID.trade_question],
[AUTO, 300, 50, ID.bowl, 0, CID.trade_question],
[AUTO, 300, 50, ID.glass_bottle, 0, CID.trade_question],
[AUTO, 500, 10, ID.saddle, 0, CID.trade_question],
[AUTO, 500, 10, ID.name_tag, 0, CID.trade_question],
],
[
// 2F - 7
[AUTO, 1000, 50, ID.stained_hardened_clay],
[AUTO, 1000, 50, ID.stained_hardened_clay, 1],
[AUTO, 1000, 50, ID.stained_hardened_clay, 2],
[AUTO, 1000, 50, ID.stained_hardened_clay, 3],
[AUTO, 1000, 50, ID.stained_hardened_clay, 4],
[AUTO, 1000, 50, ID.stained_hardened_clay, 5],
[AUTO, 1000, 50, ID.stained_hardened_clay, 6],
[AUTO, 1000, 50, ID.stained_hardened_clay, 7],
],
[
// 2F - 8
[AUTO, 1000, 50, ID.stained_hardened_clay, 8],
[AUTO, 1000, 50, ID.stained_hardened_clay, 9],
[AUTO, 1000, 50, ID.stained_hardened_clay, 10],
[AUTO, 1000, 50, ID.stained_hardened_clay, 11],
[AUTO, 1000, 50, ID.stained_hardened_clay, 12],
[AUTO, 1000, 50, ID.stained_hardened_clay, 13],
[AUTO, 1000, 50, ID.stained_hardened_clay, 14],
[AUTO, 1000, 50, ID.stained_hardened_clay, 15],
],
[
// 2F - 9
[AUTO, 2000, 50, ID.white_glazed_terracotta, TERRACOTA_DATA],
[AUTO, 2000, 50, ID.orange_glazed_terracotta, TERRACOTA_DATA],
[AUTO, 2000, 50, ID.magenta_glazed_terracotta, TERRACOTA_DATA],
[AUTO, 2000, 50, ID.light_blue_glazed_terracotta, TERRACOTA_DATA],
[AUTO, 2000, 50, ID.yellow_glazed_terracotta, TERRACOTA_DATA],
[AUTO, 2000, 50, ID.lime_glazed_terracotta, TERRACOTA_DATA],
[AUTO, 2000, 50, ID.pink_glazed_terracotta, TERRACOTA_DATA],
[AUTO, 2000, 50, ID.gray_glazed_terracotta, TERRACOTA_DATA],
],
[
// 2F - 10
[AUTO, 2000, 50, ID.silver_glazed_terracotta, TERRACOTA_DATA],
[AUTO, 2000, 50, ID.cyan_glazed_terracotta, TERRACOTA_DATA],
[AUTO, 2000, 50, ID.purple_glazed_terracotta, TERRACOTA_DATA],
[AUTO, 2000, 50, ID.blue_glazed_terracotta, TERRACOTA_DATA],
[AUTO, 2000, 50, ID.brown_glazed_terracotta, TERRACOTA_DATA],
[AUTO, 2000, 50, ID.green_glazed_terracotta, TERRACOTA_DATA],
[AUTO, 2000, 50, ID.red_glazed_terracotta, TERRACOTA_DATA],
[AUTO, 2000, 50, ID.black_glazed_terracotta, TERRACOTA_DATA],
]
]
];
// build all
{
const GAP = 4;
const start = new Vector3(-234, 63, -860);
const delta = new Vector3(GAP, 0, 0);
const deltaZ = new Vector3(0, 0, -GAP);
let xcount = 0;
let zcount = 0;
const floorsY = [0, -1, 1];
function buildLoop(cb:(pos:Vector3, params:TradingBlockParams)=>void):void
{
for (let i=0;i<structure.length;i++)
{
const floor = structure[i];
let lineBegin = start.add(new Vector3(0, floorsY[i] * GAP, 0));
if (floor.length > zcount) zcount = floor.length;
for (const lines of floor)
{
let pos = lineBegin;
if (lines.length > xcount) xcount = lines.length;
for (const params of lines)
{
cb(pos, params);
pos = pos.add(delta);
}
lineBegin = lineBegin.add(deltaZ);
}
}
}
const card = new CardBlock(start.add(new Vector3(GAP, 0, GAP)));
const sellAllPos = start.add(new Vector3(GAP*2, 0, GAP));
buildLoop((pos, params)=>{
if (params === null) return;
let targetDV = params[4];
if (typeof targetDV === 'number') targetDV = [targetDV];
const startPrice = Math.round(params[1] * SHOP_MULTIPLY);
switch (params[0])
{
case MAIN: new TradingBlock(pos, startPrice, params[3], targetDV, params[5], params[6]); break;
case AUTO: new TradingBlockAuto(pos, startPrice, params[2], params[3], targetDV, params[5], params[6], params[7]); break;
case STAT: new TradingBlockSelling(pos, startPrice, params[3], targetDV, params[5], params[6]); break;
}
});
const startY = start.y - GAP;
const ycount = 3;
const xfrom = start.x - 1;
const yfrom = startY - 1;
const zfrom = start.z;
const xto = xfrom + xcount * GAP;
const yto = yfrom + ycount * GAP;
const zto = zfrom + zcount * GAP - 3;
setFarTicker(start, new Box(xfrom, yfrom, zfrom, xto, yto, zto), ()=>{
card.build();
for (const block of allBlocks)
{
block.build();
}
buildLoop((pos, params)=>{
if (params === null)
{
fill(pos.add({x:-1, y:0, z:0}),
pos.add({x:1, y:2, z:0}),
ID.air);
}
});
return true;
});
}
// TradingBlockAuto.testAll();
setSchedule(6, 0, "트레이딩 센터 가격 변동", true, TradingBlockAuto.updatePriceAll);
}).catch(LOG.error_obj);
<file_sep>/src/server_lib/lang/ko_KR.ts
import { freeze } from './freeze';
import { LangId } from './langid';
const lang_data = {
id: "ko_KR" as LangId,
commands:{},
item:{
"element_1": [
"마을",
"마을"
],
"element_2": [
"마을과 기둥",
"마을과 기둥"
],
"element_3": [
"추가 1 블럭",
"추가 1 블럭"
],
"element_4": [
"추가 8 블럭",
"추가 8 블럭"
],
"element_5": [
"추가 64 블럭",
"추가 64 블럭"
],
"element_6": [
"감소 1 블럭",
"감소 1 블럭"
],
"element_7": [
"감소 8 블럭",
"감소 8 블럭"
],
"element_8": [
"감소 64 블럭",
"감소 64 블럭"
],
"element_9": [
"확인 블럭",
"확인 블럭"
],
"element_10": [
"신용 카드",
"신용 카드"
],
"element_11": [
"질문 블럭",
"질문 블럭"
],
"element_12": [
"오버월드 테스터",
"오버월드 테스터"
],
"element_13": [
"신용 카드 블럭",
"신용 카드 블럭"
],
"element_14": [
"회귀 블럭",
"회귀 블럭"
],
"element_15": [
"전부 판매 블럭",
"전부 판매 블럭"
],
"element_16": [
"상점 포탈 블럭",
"상점 포탈 블럭"
],
"element_17": [
"보상 블럭",
"보상 블럭"
],
"element_18": [
"구매 블럭",
"구매 블럭"
],
"element_19": [
"투표 용지",
"투표 용지"
]
}
};
freeze(lang_data);
export = lang_data;
<file_sep>/src/server/customid.ts
import ID from "@mcbe/identifier/id";
export const CID = {
zone_maker:ID.element_1,
zone_maker_torch:ID.element_2,
trade_add1:ID.element_3,
trade_add8:ID.element_4,
trade_add64:ID.element_5,
trade_sub1:ID.element_6,
trade_sub8:ID.element_7,
trade_sub64:ID.element_8,
trade_submit:ID.element_9,
trade_card:ID.element_10,
trade_question:ID.element_11,
nether_checker:ID.element_12,
trade_card_block:ID.element_13,
tempblock:ID.element_14,
trade_sell_all:ID.element_15,
spawnportal:ID.element_16,
moneyblock:ID.element_17,
buyblock:ID.element_18,
ballot:ID.element_19,
};
<file_sep>/src/server_lib/log.ts
'use strict';
import { ipfilter } from "bdsx";
import { system } from "@mcbe/system_server";
function timeoutToNextDay(now:Date, cb:()=>void):void
{
const dayms = now.getHours() * 60 * 60 * 1000
+ now.getMinutes() * 60* 1000
+ now.getSeconds() * 1000;
const remain_ms = 24 * 60 * 60 * 1000 - dayms + 1000;
if (remain_ms <= 0)
{
cb();
}
else
{
setTimeout(cb, remain_ms);
}
}
export function updateTrafficLogFileName():void
{
const now = new Date();
ipfilter.logTraffic(`${process.argv[1]}/traffic_${now.getFullYear()}_${now.getMonth()+1}_${now.getDate()}.log`);
timeoutToNextDay(now, updateTrafficLogFileName);
}
<file_sep>/src/server/realty/zonesplit.ts
import { CID } from "../customid";
import { User, UserExtra } from "@bdsx/ruakr_user";
import { IVectorXZ } from "krgeometry";
import { Store, Storage } from "@mcbe/store";
import { Wallet } from "../module/wallet";
import { DDBlockExtra } from "../ddblock";
import LOG from "@mcbe/ruakr_log";
import { priceToString } from "../structure/tradecenter";
// 땅 파는 블럭이 있고,
// 땅매매 블럭을 카드를 들고 부수면, 구매됨
// 땅매매 블럭을 배치하면, 가격 정하는 블럭세트가 생성되고, 가격을 정하고 확인하면 판매 설정되게
const CHUNK_SIZE = 8;
const AXIS_X = -224;
const AXIS_Y = -840;
const VAR_PRICE = '#price';
const areas = new Map<string, RealtyArea>();
const store = new Store('realty');
class RealtyArea
{
private readonly storage:Storage;
constructor(public readonly id:string)
{
this.storage = store.create(this.id);
}
getPrice():number|undefined
{
const price = this.storage.get(VAR_PRICE);
if (price === undefined)
{
LOG.error({action:LOG.Action.Assertion, msg:`realty ${this.id} price not found`});
}
return price;
}
buy(user:User):boolean
{
const price = this.getPrice();
if (price === undefined) return false;
const wallet = user.extra(Wallet);
if (price > wallet.get())
{
user.info(`금액이 부족해요\n가격: ${priceToString(price)}`);
wallet.showOnce();
return false;
}
user.info('구매 완료');
wallet.showOnce();
return true;
}
}
function getArea(pos:IVectorXZ):RealtyArea|null
{
const x = Math.floor(pos.x / CHUNK_SIZE);
const z = Math.floor(pos.z / CHUNK_SIZE);
const id = x + '_' +z;
const area = areas.get(id);
return area || null;
}
function createArea(pos:IVectorXZ):RealtyArea
{
const x = Math.floor(pos.x / CHUNK_SIZE);
const z = Math.floor(pos.z / CHUNK_SIZE);
const id = x + '_' +z;
let area = areas.get(id);
if (area) return area;
area = new RealtyArea(id);
areas.set(id, area);
return area;
}
class RealtyExtra implements UserExtra
{
constructor()
{
}
static onInstall():void
{
DDBlockExtra.install([CID.buyblock], {
onCheck(user, destroy, pos)
{
const area = getArea(pos);
if (!area) return false;
const price = area.getPrice();
if (price === undefined) return false;
const wallet = user.extra(Wallet);
wallet.showOnce();
if (price > wallet.get())
{
user.info(`매매가: ${priceToString(price)}\n구매 불가`);
return false;
}
user.info(`매매가: ${priceToString(price)}\n${destroy ? '한번 더 부숴주세요!' : '블럭을 부숴주세요!'}`);
return true;
},
onSubmit(user, pos)
{
const area = getArea(pos);
if (!area)
{
user.giveItem(CID.buyblock, 0, 1);
return false;
}
return area.buy(user);
}
});
}
}
<file_sep>/src/lib/damper.ts
import { realTime } from "@mcbe/timer/realtime";
export class Damper
{
private current:number = 0;
private time:number = realTime.now;
constructor(public readonly max:number)
{
}
get(delta?:number):number
{
if (this.current === 0) return 0;
const passed = realTime.now - this.time;
this.time = realTime.now;
return this.current = Math.max(this.current - passed, -(delta || 0));
}
reset():void
{
this.current = 0;
this.time = realTime.now;
}
pause():void
{
this.time = realTime.now;
}
reduce(value:number):void
{
if (this.current === 0) return;
const passed = realTime.now - this.time;
this.time = realTime.now;
this.current = Math.max(this.current - passed - value, 0);
}
use(value:number, delta?:number):boolean
{
let remaining = this.max - this.get(delta);
if (delta) remaining += delta;
if (value > remaining) return false;
this.current += value;
return true;
}
toString():string
{
return '(' + Math.round(this.get(0)) + '/' + Math.round(this.max) + ')';
}
}
<file_sep>/src/lib/arraydiff.ts
export function arraydiff<T>(oldlist:T[], newlist:T[], listener:{added:(item:T)=>void, deleted:(item:T)=>void})
{
const newset = new Set(newlist);
for (const olditem of oldlist)
{
if (!newset.delete(olditem))
{
listener.deleted(olditem);
}
}
for (const newitem of newset)
{
listener.added(newitem);
}
}
<file_sep>/src/server/index.ts
import { restorePistonPush } from "@bdsx/restoreblock";
import { BanExtra } from "@bdsx/ruakr_ban";
import "@bdsx/ruakr_db";
import "@bdsx/ruakr_logdb";
import { blockEvent, Container, User } from "@bdsx/ruakr_user";
import { LogExtra } from "@bdsx/ruakr_userlog";
import { execute, killEntities, spawnpoint } from "@mcbe/command";
import { Entity, EntityType } from "@mcbe/entity";
import events from "@mcbe/event_server";
import Identifier from "@mcbe/identifier";
import ID from "@mcbe/identifier/id";
import { itemLang, Lang } from "@mcbe/lang";
import { UseMethod } from "@mcbe/ruakr_const";
import LOG from "@mcbe/ruakr_log";
import { tellrawAll } from "@mcbe/system_server";
import { realTime } from "@mcbe/timer/realtime";
import { fs, ipfilter, NativePointer, setOnRuntimeErrorListener } from "bdsx";
import { DimensionId } from "bdsx/common";
import { Vector3 } from "krgeometry";
import { setSchedule } from "../lib/timeschdule";
import { updateTrafficLogFileName } from "../server_lib/log";
import { enableNightPvP } from "../server_lib/night_pvp";
import { enableClearOld } from "./clearold";
import { CID } from "./customid";
import { DDBlockExtra } from "./ddblock";
import { AdminComponent } from "./module/admintool";
import { DigCounter } from "./module/digcounter";
import { LastConnection } from "./module/last_conn";
import { NetherTop } from "./module/nethertop";
import { portalBlock } from "./module/portalblock";
// import { HardInventory } from "./module/hardinventory";
import { Pusher } from "./module/pusher";
import { Region, RegionComponent } from "./module/region";
import { SoftInventory } from "./module/softinventory";
import { TempBlockComponent } from "./module/tempblock";
import { Wallet } from "./module/wallet";
import { WatchComponent } from "./module/watch";
import { ZoneComponent } from "./module/zone";
import { initPvP } from "./pvpzone";
import { settings } from "./settings";
import { SpawnPointExtra, SPAWN_POINT } from "./spawnpoint";
import { TradeExtra } from "./structure/tradecenter";
import { test } from "./test";
realTime.install();
Promise.all([
Lang.onLoad,
]).then(([lang])=>{
itemLang.set('ko_KR');
}).catch(LOG.error_np);
Lang.load(require('@mcbe/lang/data/ko_KR'));
Lang.mergeLoad(require('../server_lib/lang/en_US'));
Lang.mergeLoad(require('../server_lib/lang/ko_KR'));
ipfilter.setTrafficLimit(settings.data.trafficLimit);
ipfilter.setTrafficLimitPeriod(settings.data.trafficLimitPeriod);
settings.onUpdate.on(data=>{
User.admins.clear();
for (const admin of data.admins)
{
User.admins.add(admin);
}
});
test();
initPvP();
function v(ptr:NativePointer)
{
const way1 = new NativePointer(ptr);
const way2 = ptr.clone();
}
User.install(class{
constructor(public readonly user:User){}
onMoveStart()
{
for (const msg of settings.data.welcomeMessage.split('\n'))
{
this.user.tellraw(msg);
}
}
onFirstLogin()
{
spawnpoint(this.user.name, SPAWN_POINT);
}
});
User.install(LogExtra);
User.install(SpawnPointExtra);
User.install(BanExtra);
User.install(LastConnection);
User.install(RegionComponent);
User.install(ZoneComponent);
User.install(Wallet);
// User.install(HardInventory);
User.install(SoftInventory);
User.install(WatchComponent);
User.install(Pusher);
User.install(NetherTop);
User.install(DDBlockExtra);
User.install(DigCounter);
User.install(AdminComponent);
User.install(TradeExtra);
User.install(TempBlockComponent);
blockEvent.install(portalBlock);
blockEvent.install({
TARGET: [ID.respawn_anchor],
onPlace(user, block){
if (block.pos.dimension === DimensionId.Overworld)
{
block.destroy();
return true;
}
return false;
}
});
blockEvent.setNonPlaceable(CID.ballot);
// blockEvent.setUnsupported(ID.shulker_box);
// blockEvent.setUnsupported(ID.undyed_shulker_box);
User.unacquirable.add(CID.trade_add1);
User.unacquirable.add(CID.trade_add8);
User.unacquirable.add(CID.trade_add64);
User.unacquirable.add(CID.trade_sub1);
User.unacquirable.add(CID.trade_sub8);
User.unacquirable.add(CID.trade_sub64);
User.unacquirable.add(CID.trade_card_block);
User.unacquirable.add(CID.trade_submit);
User.unacquirable.add(CID.trade_question);
enableClearOld();
enableNightPvP();
// 시간마다 엔티티 삭제
setSchedule(4, 0, '엔티티 삭제(아이템, 흔한 몬스터)', true, ()=>{
Promise.all([
killEntities({type:ID.skeleton}),
killEntities({type:ID.spider}),
killEntities({type:ID.drowned}),
killEntities({type:ID.zombie}),
killEntities({type:ID.husk}),
killEntities({type:ID.creeper}),
killEntities({type:ID.item}),
]).then(entities=>{
const count = entities.map(v=>v.length).reduce((a,b)=>a+b);
tellrawAll([count+'개의 엔티티가 삭제되었어요']);
});
});
// 여러가지
Entity.setAutoDestroy(EntityType.Item, ID.bedrock);
Entity.setAutoDestroy(EntityType.Item, ID.end_portal_frame);
Entity.onNew(EntityType.Entity, ID.fishing_hook, entity=>{
const pos = entity.component.Position.data;
// if (middleLock.containsXZ(pos) && pos.y > SPAWN_POINT.y + 5)
// {
// entity.destroy();
// }
});
Entity.onNew(EntityType.Entity, ID.arrow, entity=>{
const pos = entity.component.Position.data;
// if (middleLock.containsXZ(pos) && pos.y > SPAWN_POINT.y - 5)
// {
// callAtNextTick(()=>{
// entity.destroy();
// });
// }
});
// Entity.onNew(EntityType.Entity, ID.armor_stand, entity=>{
// const pos = entity.component.Position.data;
// entity.destroy();
// createItem(ID.armor_stand, pos);
// const {user} = User.getNearst(pos);
// if (user) user.info('미지원 아이템');
// });
events.listen.PistonMovedBlock(data=>{
const newPos = Vector3.make(data.block_position);
const pistonPos = Vector3.make(data.piston_position);
const dir = newPos.sub(pistonPos).normalize();
let oldPos:Vector3;
switch (data.piston_action)
{
case 'extended':
oldPos = newPos.sub(dir);
break;
case 'retracted':
oldPos = newPos.add(dir);
break;
default:
LOG.error({action:LOG.Action.PistonPush, upos:data.piston_position, pos:data.block_position, msg:data.piston_action});
return;
}
const {user} = User.getNearst(oldPos);
if (!user) return;
const area = user.getTickingArea();
const block = area.getBlock(newPos);
if (!block) return;
// Chest problem
let flags = Container.getFlags(block.id);
switch (flags)
{
case Container.INVALID: break;
case Container.CHEST_ENDER: break;
default:
Container.onDestroy(user, flags, oldPos);
execute(user.name).setblock(newPos, ID.air, 0, 'destroy');
return;
}
// Region check
const oldregions = new Set(Region.pick(oldPos));
const newregions = new Set(Region.pick(newPos));
for (const r of Region.pick(pistonPos))
{
oldregions.delete(r);
newregions.delete(r);
}
if (newregions.size !== 0)
{
for (const r of newregions)
{
if (!r.canWrite(null, newPos))
{
if (restorePistonPush(user, block, pistonPos, oldPos)) return;
}
}
for (const r of newregions)
{
if (r.onPistonPush(user, block, pistonPos, oldPos)) return;
}
}
if (oldregions.size !== 0)
{
for (const r of oldregions)
{
if (!r.canWrite(null, oldPos))
{
if (restorePistonPush(user, block, pistonPos, oldPos)) return;
}
}
for (const r of oldregions)
{
if (r.onPistonPush(user, block, pistonPos, oldPos)) return;
}
}
blockEvent.onPistonPush.fire(user, block, pistonPos, oldPos);
});
events.listen.EntityUseItem(data=>{
const user = User.getInstance(data.entity);
if (!user) return;
user.onUseItem(<UseMethod>data.use_method, Identifier.get(data.item_stack.item), data.item_stack.count)
});
//
// PlaySound
//
// WeatherChanged
setOnRuntimeErrorListener((stack, nativestack, lastSender)=>{
const date = new Date();
let log = '';
log += stack;
log += '\n';
log += nativestack;
log += '\n';
if (lastSender)
{
log += 'Last sender: '+lastSender;
log += '\n';
}
fs.appendFileSync(`../critical_error_${date.getFullYear()}_${date.getMonth()+1}_${date.getDate()}.log`, log);
});
updateTrafficLogFileName();<file_sep>/src/server_lib/night_pvp.ts
import { tickTime, NIGHT_BEGIN, NIGHT_END, DAY } from "@mcbe/timer/ticktime";
import { getDayTime } from "@mcbe/command";;
import { command } from "@mcbe/system_server";
export async function enableNightPvP():Promise<void>
{
let daytime = await getDayTime();
let pvp = NIGHT_BEGIN <= daytime && daytime < NIGHT_END;
command('gamerule pvp '+pvp);
for (;;)
{
if (pvp)
{
await tickTime.promise(NIGHT_END - daytime);
pvp = false;
}
else
{
if (daytime >= NIGHT_END) daytime -= DAY;
await tickTime.promise(NIGHT_BEGIN - daytime);
pvp = true;
}
command('gamerule pvp '+pvp);
daytime = await getDayTime();
}
}
<file_sep>/src/server/module/wallet.ts
import { User, UserExtra, blockEvent } from "@bdsx/ruakr_user";
import { CID } from "../customid";
import Identifier from "@mcbe/identifier";
import { priceToString } from "../structure/tradecenter";
export const VAR_WALLET_MONEY = '#money';
export class Wallet implements UserExtra
{
timer:NodeJS.Timeout|null = null;
constructor(public readonly user:User)
{
}
showOnce():void
{
this.user.actionbar(`현재: ${priceToString(this.get())}`);
}
show():void
{
if (this.timer) return;
this.showOnce();
this.timer = setInterval(()=>{
this.showOnce();
}, 1000);
}
hide():void
{
if (this.timer)
{
clearInterval(this.timer);
this.timer = null;
this.user.actionbar(`§0`);
}
}
get():number
{
return this.user.storage.get(VAR_WALLET_MONEY) || 0;
}
add(value:number):number
{
const res = this.user.storage.add(VAR_WALLET_MONEY, value) || 0;;
this.showOnce();
return res;
}
remove(value:number):number
{
const res = this.user.storage.remove(VAR_WALLET_MONEY, value) || 0;;
this.showOnce();
return res;
}
set(value:number):void
{
const res = this.user.storage.set(VAR_WALLET_MONEY, value);;
this.showOnce();
return res;
}
onItemChange(now:Identifier, prev:Identifier):void
{
if (now === CID.trade_card)
{
this.show();
}
else if (prev === CID.trade_card)
{
this.hide();
}
}
onDispose():void
{
this.hide();
}
static onInstall():void
{
blockEvent.setNonPlaceable(CID.trade_card);
}
}
<file_sep>/src/server/ddblock.ts
import { Vector3 } from "krgeometry";
import Identifier from "@mcbe/identifier";
import { realTime } from "@mcbe/timer/realtime";
import { User, blockEvent } from "@bdsx/ruakr_user";
import { restorePistonPush, restoreBlockSlow, removeBlockDrop } from "@bdsx/restoreblock";
import { Block } from "@bdsx/block";
export interface DDBlockListener
{
onCheck(user:User, destroy:boolean, pos:Vector3):boolean;
onSubmit(user:User, pos:Vector3):boolean;
}
export class DDBlockExtra
{
accessTime:number = 0;
accessTarget:Vector3 = Vector3.ZERO;
static install(target:Identifier[], listener:DDBlockListener):void
{
blockEvent.install({
TARGET: target,
onPistonPush(user:User, block:Block, pistonPos:Vector3, oldPos:Vector3):boolean
{
return restorePistonPush(user, block, pistonPos, oldPos);
},
onInterect(user:User, block:Block):boolean
{
const extra = user.extra(DDBlockExtra);
if (!listener.onCheck(user, false, block.pos)) return false;
extra.accessTime = realTime.now + 3000;
extra.accessTarget = block.pos;
return true;
},
onDestroy(user:User, block:Block):void
{
const extra = user.extra(DDBlockExtra);
if (extra.accessTime < realTime.now || !extra.accessTarget.equals(block.pos))
{
extra.accessTime = realTime.now + 5000;
extra.accessTarget = block.pos;
listener.onCheck(user, true, block.pos);
}
else
{
extra.accessTime = 0;
if (listener.onSubmit(user, block.pos))
{
removeBlockDrop(block);
return;
}
}
restoreBlockSlow(user, block);
}
});
}
}
<file_sep>/src/server/structure/autodoor.ts
import { Region } from "../module/region";
import { Vector3, Box } from "krgeometry";
import { fill } from "@mcbe/command";
import ID from "@mcbe/identifier/id";
import { User } from "@bdsx/ruakr_user";
export class AutoDoor extends Region
{
private opening = false;
private openlevel = 0;
private interval:NodeJS.Timeout|null = null;
private userCount:number = 0;
constructor(
private readonly pos:Vector3,
private readonly dir:Vector3,
private readonly size:number,
private readonly height:number)
{
super('자동문', Box.align(pos, pos.add(dir.mul(size*2))).moveBy(Vector3.HALF).expand(1.5), pos.y);
this.openlevel = size;
let p = pos;
const n = size*2;
for (let i=0;i<n;i++)
{
fill(p, p.add(new Vector3(0, height-1, 0)), ID.glass);
p = p.add(dir);
}
}
setOpen(open:boolean):void
{
if (this.opening === open) return;
this.opening = open;
if (!this.interval)
{
this.interval = setInterval(()=>this.update(), 200);
}
}
onEnter(user:User):string|null
{
if (this.userCount === 0) this.setOpen(true);
this.userCount ++;
return null;
}
onLeave(user:User):void
{
this.userCount --;
if (this.userCount === 0) this.setOpen(false);
}
update():void
{
if (this.opening)
{
if (this.openlevel === 0)
{
clearInterval(this.interval!);
this.interval = null;
return;
}
this.openlevel--;
const p1 = this.pos.add(this.dir.mul(this.openlevel));
const p2 = this.pos.add(this.dir.mul(this.size*2-this.openlevel-1));
fill(p1, p1.add(new Vector3(0, this.height-1, 0)), ID.air);
fill(p2, p2.add(new Vector3(0, this.height-1, 0)), ID.air);
}
else
{
if (this.openlevel === this.size)
{
clearInterval(this.interval!);
this.interval = null;
return;
}
const p1 = this.pos.add(this.dir.mul(this.openlevel));
const p2 = this.pos.add(this.dir.mul(this.size*2-this.openlevel-1));
fill(p1, p1.add(new Vector3(0, this.height-1, 0)), ID.glass);
fill(p2, p2.add(new Vector3(0, this.height-1, 0)), ID.glass);
this.openlevel++;
}
}
}
<file_sep>/src/server/module/admintool.ts
import { Block } from "@bdsx/block";
import { loginInfoTables } from "@bdsx/logininfo-db";
import { Position } from "@bdsx/position";
import { banlist } from "@bdsx/ruakr_ban";
import { addSlashes, db } from "@bdsx/ruakr_db";
import { AttackEvent, Container, User, UserExtra } from "@bdsx/ruakr_user";
import { commander, execute, fillx, testforblock, title } from "@mcbe/command";
import Identifier from "@mcbe/identifier";
import ID from "@mcbe/identifier/id";
import { Lang } from "@mcbe/lang";
import LOG from "@mcbe/ruakr_log";
import { Store } from "@mcbe/store";
import { tellrawAll } from "@mcbe/system_server";
import { command, ipfilter, nethook, PacketId, serverControl } from "bdsx";
import { DimensionId } from "bdsx/common";
import { Vector3 } from "krgeometry";
import { pvpstore, pvpzone } from "../pvpzone";
import { settings } from "../settings";
import { setWorldSpawn } from "../spawnpoint";
import { tradestore, TradingBlock } from "../structure/tradecenter";
import { getDigCounterString } from "./digcounter";
// import { HardInventory } from "./hardinventory";
import { portalBlock } from "./portalblock";
import { SoftInventory } from "./softinventory";
import { Zone } from "./zone";
const TAG_TO_COLOR = {
'V': '§7',
'M': '§r',
'W': '§e',
'E': '§c',
};
const LOG_QUERY = 'id,tag,time,action,user,user_x,user_y,user_z,x,y,z,msg,item,item2,count,count2';
function splitCommand(line:string):string[]
{
const out:string[] = [];
let cur = '';
let quot = false;
_loop:for (let i=0;i<line.length;)
{
let chr = line.charAt(i++);
switch (chr)
{
case '\\':
if (quot)
{
if (i >= line.length) break _loop;
chr = line.charAt(i++);
switch (chr)
{
case 'n': cur += '\n'; break;
case 'r': cur += '\r'; break;
case 'f': cur += '\f'; break;
case 'b': cur += '\b'; break;
case 'a': cur += '\a'; break;
case '0': cur += '\0'; break;
default: cur += chr; break;
}
}
else
{
cur += chr;
}
break;
case '"':
quot = !quot;
break;
case ' ':
if (quot)
{
cur += chr;
}
else
{
out.push(cur);
cur = '';
}
break;
default:
cur += chr;
break;
}
}
out.push(cur);
return out;
}
const STORES = new Map<string, Store>([
['player', User.store],
['portal', portalBlock.store],
['container', Container.store],
['pvp', pvpstore],
['trade', tradestore],
]);
abstract class Commander
{
public repeating = false;
private previousCommand = '';
protected lastLogViewIndex:number = 0;
constructor()
{
}
getUser():User|null
{
return null;
}
abstract print(message:string):void;
abstract taggedPrint(tag:LOG.Tag, message:string):void;
execute(cmd:string):number|undefined
{
this.repeating = (this.previousCommand == cmd);
this.previousCommand = cmd;
const space = cmd.indexOf(' ');
const tail = cmd.substr(space+1);
let cmds:string[];
let cmdname:string;
if (space !== -1)
{
cmds = splitCommand(tail);
cmdname = cmd.substring(1, space);
}
else
{
cmds = [];
cmdname = cmd.substr(1);
}
const cmdfn = commandMap[cmdname];
if (cmdfn)
{
cmdfn(this, cmds, tail).catch(err=>this.taggedPrint('E', err.message));
return 0;
}
}
private _printLog(res:(string|null)[]):void
{
const [id, tag, time, action, user, user_x, user_y, user_z, x, y, z, msg, item, item2, count, count2] = res;
let log = `${time}| ${action}`;
if (user !== null)
{
log += ' @';
log += user;
}
if (user_x !== null)
{
log += `(${user_x} ${user_y} ${user_z})`;
}
if (x !== null)
{
log += ` (${x} ${y} ${z})`;
}
if (item !== null)
{
log += ` ${item}`;
}
if (count !== null)
{
log += `(${count})`;
}
if (item2 !== null)
{
log += ` ${item2}`;
}
if (count2 !== null)
{
log += `(${count2})`;
}
if (msg !== null)
{
log += ': ';
log += msg;
}
this.taggedPrint(tag as LOG.Tag, log);
}
_printLogs(res:(string|null)[][]):void
{
this.print('--log--');
if (res.length === 0)
{
this.lastLogViewIndex = 0;
this.print('--empty--');
return;
}
for (const r of res)
{
this._printLog(r);
}
this.lastLogViewIndex = +res[res.length-1][0]!;
}
async printLog(name?:string):Promise<void>
{
try
{
let query = `select ${LOG_QUERY} from act where 1`;
if (this.repeating) query += ` && id <${this.lastLogViewIndex}`;
if (name) query += ` && user="${addSlashes(name)}"`;
query += ' order by id desc limit 10';
const rows = await db.execute(query);
this._printLogs(rows);
}
catch(err)
{
this.print(err.stack);
}
}
async searchItem(item:Identifier):Promise<void>
{
const res = await commander.command(`clear @a ${item} -1 0`);
const lang = await Lang.onLoad;
lang.commands.clear_testing.reset();
for (;;)
{
const matched = lang.commands.clear_testing.exec(res.statusMessage);
if (!matched) break;
const username = matched[0];
const count = matched[1];
this.print(`${username}: ${count}`);
}
}
}
class ServerCommander extends Commander
{
print(message:string)
{
console.log(message);
}
taggedPrint(tag:LOG.Tag, message:string):void
{
if (tag === 'E')
{
console.error(message);
}
else
{
console.log(message);
}
}
}
function toBoolean(v:string, original:boolean):boolean
{
if (!v) return !original;
if (v === '0') return false;
if (v === 'f') return false;
if (v === 'false') return false;
if (v === 'off') return false;
if (v === 'x') return false;
if (v === 'n') return false;
return true;
}
const commandMap:{[key:string]:(cmder:Commander, cmds:string[], fullcmd:string)=>Promise<void>} = {
async 't'(cmder, cmds, fullcmd)
{
if (cmder !== serverCmder) return;
tellrawAll([fullcmd]);
},
async 'js'(cmder, cmds, fullcmd)
{
const res = new Function(
'exports',
'require',
'module',
'__filename',
'__dirname',
fullcmd)(exports, require, module, __filename, __dirname);
if (res !== undefined) console.log(res);
},
async 'restart'()
{
serverControl.restart();
},
async 'restart-force'()
{
serverControl.restart(true);
},
async 'update-price'(cmder)
{
TradingBlock.updatePriceAll();
cmder.print('Price Updated');
},
async 'pvpgame'()
{
pvpzone.ready();
},
async 'dig'(cmder)
{
cmder.print(getDigCounterString());
},
async 'find'(cmder, cmds)
{
const id = Identifier.getFromName(cmds[0]);
cmder.print('----------------');
Container.search(id);
cmder.searchItem(id);
},
async 'test'(cmder)
{
const user = cmder.getUser();
if (!user)
{
console.log('no for console');
return;
}
const packet = nethook.createPacket(PacketId.Transfer);
nethook.sendPacket(user.ni, packet);
packet.dispose();
},
async 'log'(cmder, [name])
{
cmder.printLog(name);
},
async 'who'(cmder, [name]) {
const rows = await db.execute(`select b.username,b.ipaddr from ipinfo a,ipinfo b where a.username like '${addSlashes(name)}' && a.ipaddr=b.ipaddr`);
if (!rows || rows.length === 0)
{
cmder.print(`${name} is not found`);
return;
}
cmder.print('----------------');
const xuidmap = await loginInfoTables.getXuidFromNames(rows.map(row=>row[0]!));
for (const [name, ipaddr] of rows)
{
const xuids = xuidmap.get(name!);
let show = `${name}: ${ipaddr}`;
if (xuids)
{
for (const xuid of xuids)
{
if (banlist.hasXuid(xuid)) show += `(${xuid} banned)`;
}
}
if (banlist.hasXuid(name!)) show += `(name banned)`;
if (ipfilter.has(ipaddr!)) show += ' (ip-banned)';
cmder.print(show);
}
},
async 'whoip'(cmder, [ipaddr])
{
ipaddr = ipaddr.replace(/\*/g, '%');
const rows = await db.execute(`select username from ipinfo where ipaddr like '${addSlashes(ipaddr)}'`);
if (!rows || rows.length === 0)
{
cmder.print(`${ipaddr} is not found`);
return;
}
if (ipfilter.has(ipaddr)) cmder.print('----(ip-banned)----');
else cmder.print('----------------');
const xuidmap = await loginInfoTables.getXuidFromNames(rows.map((row=>row[0]!)));
for (const [name] of rows)
{
const xuids = xuidmap.get(name!);
let out = name!;
if (banlist.hasXuid(name!)) out += ` (banned)`;
if (xuids)
{
for (const xuid of xuids)
{
if (banlist.hasXuid(xuid)) out += `(${xuid} banned)`;
}
}
cmder.print(out);
}
},
async 'keeps'(cmder, [name])
{
// const user = User.getByName(name);
// if (user)
// {
// cmder.print(user.extra(HardInventory).getKeepingText());
// }
// else
// {
// cmder.print(`${name} is not found`);
// }
},
async 'ipban'(cmder, cmds)
{
const ip = cmds.shift()!;
LOG.error({user:':'+ip, action:LOG.Action.ManualBan, msg:cmds.join(' ')});
if (banlist.banWithIp(ip))
{
cmder.print(`${ip} ip-banned`);
}
else
{
cmder.print(`${ip} is already ip-banned`);
}
},
async 'ipunban'(cmder, [ip])
{
if (banlist.unbanWithIp(ip))
{
cmder.print(`${ip} ip-unbanned`);
}
else
{
cmder.print(`${ip} is not ip-banned`);
}
},
async 'ipbanlist'(cmder)
{
cmder.print('-------------------');
cmder.print(banlist.reportIpBan());
},
async 'ban'(cmder, cmds)
{
const name = cmds.shift()!;
const user = User.getByName(name);
if (user)
{
banlist.ban(user, {action:LOG.Action.ManualBan, msg:cmds.join(' ')});
}
else
{
const xuids = await loginInfoTables.getXuidFromName(name);
if (xuids.length === 0)
{
cmder.print(`${name} not found`);
}
LOG.error({user:name, action:LOG.Action.ManualBan, msg:cmds.join(' ')});
if (xuids.length === 1)
{
if (banlist.banByXuid(xuids[0]))
{
cmder.print(`${name} banned`);
}
else
{
cmder.print(`${name} is already banned`);
}
}
else
{
for (const xuid of xuids)
{
if (banlist.banByXuid(xuid))
{
cmder.print(`${xuid} banned`);
}
else
{
cmder.print(`${xuid} is already banned`);
}
}
}
}
},
async 'unban'(cmder, [name])
{
const xuids = await loginInfoTables.getXuidFromName(name);
if (xuids.length === 0)
{
cmder.print(`${name} not founded`);
return;
}
for (const xuid of xuids)
{
if (banlist.unbanByXuid(xuid))
{
cmder.print(`${name} unbanned`);
}
else
{
cmder.print(`${name} is not banned`);
}
}
},
async 'banlist'(cmder)
{
cmder.print('-------------------');
cmder.print(await banlist.report());
},
async 'inv'(cmder, [name])
{
const user = User.getByName(name);
if (user)
{
cmder.print(user.extra(SoftInventory).getInventoryText());
}
else
{
cmder.print('user not found: '+name);
}
},
async 'zone'(cmder, [cmd, zonename, value])
{
switch (cmd)
{
case 'list': {
const list = await Zone.list();
for (const name of list)
{
const zone = Zone.get(name)!;
cmder.print(zone.toInfoString());
}
break;
}
case 'remove': {
const zone = Zone.get(zonename);
if (!zone)
{
cmder.print(`zone not found: ${zonename}`);
return;
}
if (!zone.destroy())
{
cmder.print(`zone remove failed: ${zonename}`);
}
else
{
cmder.print(`zone removed: ${zonename}`);
}
break;
}
case 'size': {
const zone = Zone.get(zonename);
if (!zone)
{
cmder.print(`zone not found: ${zonename}`);
return;
}
if (value === undefined)
{
cmder.print(`${zonename}.size: ${zone.getSize()}`);
}
else
{
const newSize = +value;
if (isNaN(newSize))
{
cmder.print(`invalid number: ${value}`);
return;
}
cmder.print(`${zonename}.size: (${zone.getSize()} -> ${newSize})`);
zone.setSize(newSize);
}
break;
}
case 'info': {
const zone = Zone.get(zonename);
if (!zone)
{
cmder.print(`zone not found: ${zonename}`);
return;
}
cmder.print(zone.toInfoString());
for (const [name, level] of zone.getMembers())
{
cmder.print(name+': '+level);
}
break;
}
default: cmder.print('[list, size, info]');
}
},
async 'store'(cmder, cmds)
{
const storename = cmds.shift();
if (!storename)
{
for (const name of STORES.keys())
{
cmder.print(name);
}
return;
}
const s = STORES.get(storename);
if (!s)
{
cmder.print('unknown store: '+storename);
return;
}
const cmd2 = cmds.shift();
const tablename = cmds.shift();
const varname = cmds.shift();
switch (cmd2)
{
case 'list':
if (tablename)
{
const table = s.get(tablename);
if (!table)
{
cmder.print('unknown table: '+storename+'.'+tablename);
break;
}
cmder.print('----list of '+storename+'.'+tablename);
for (const [key, value] of table.entires())
{
cmder.print(`${key}: ${value}`);
}
}
else
{
cmder.print('----list of '+storename);
for (const storage of s.values())
{
cmder.print(storage.name);
}
}
break;
case 'get':
if (!tablename)
{
cmder.print('need tablename');
break;
}
if (!varname)
{
cmder.print('need varname');
break;
}
const table = s.get(tablename);
if (!table)
{
cmder.print('unknown table: '+tablename);
break;
}
cmder.print(`${storename}.${table}.${varname}: ${table.get(varname)}`);
break;
case 'set':
if (!tablename)
{
cmder.print('need tablename');
break;
}
if (!varname)
{
cmder.print('need varname');
break;
}
const valuestr = cmds.shift()!;
const value = parseInt(valuestr);
if (isNaN(value))
{
cmder.print('Invalid value: '+valuestr);
break;
}
s.create(tablename).set(varname, value);
break;
default: cmder.print(`unknown command: store ${cmd2}`); break;
}
},
async 'store-update'(cmder)
{
Store.updateAll();
cmder.print('DB Updated');
},
async 'settings'(cmder, [name, value])
{
if (!name)
{
for (const name in settings.data)
{
cmder.print(name+': '+settings.data[name]);
}
}
else if (!(name in settings.data))
{
cmder.print('unknown setting property: '+name);
}
else
{
const orival = settings.data[name];
if (!value)
{
cmder.print(`settings.${name}: ${orival}`);
}
else
{
const valtype = typeof orival;
switch (valtype)
{
case 'string':
settings.data[name] = value;
cmder.print(`settings.${name}: ${orival}->${value}`);
break;
case 'number':
const numval = +value;
if (isNaN(numval))
{
cmder.print(`settings.${name} needs number`);
cmder.print(`${value} is not number`);
}
else
{
settings.data[name] = numval;
cmder.print(`settings.${name}: ${orival}->${numval}`);
}
break;
default:
cmder.print(`unsupported type: ${valtype} (settings.${name})`);
break;
}
}
}
},
async 'mini'(cmder, [v])
{
cmder.print(Identifier.get(v).minified);
},
async 'unmini'(cmder, [v])
{
cmder.print(Identifier.getFromMinified(v).name);
},
async 'adm'(cmder, [m])
{
const user = cmder.getUser();
if (!user)
{
cmder.print('Need to use it in game');
return;
}
user.setAdminMode(toBoolean(m, user.isAdminMode()));
},
};
const serverCmder = new ServerCommander;
command.hook.on((cmd, origin)=>{
let cmder:Commander;
const user = User.getByName(origin);
if (cmd.startsWith('/w '))
{
const msg = cmd.substr(2);
if (user)
{
LOG.message({user, action:LOG.Action.Chat, msg});
}
else
{
LOG.message({user:origin, action:LOG.Action.Chat, msg});
}
}
if (origin === "Server")
{
cmder = serverCmder;
}
else if (User.admins.has(origin))
{
if (!user) return;
cmder = user.extra(AdminComponent);
}
else
{
return;
}
return cmder.execute(cmd);
});
export class AdminComponent extends Commander implements UserExtra
{
private checking = false;
private fillFrom:Vector3|null = null;
private lastLogViewPos:Position = Position.NULL;
constructor(public readonly user:User)
{
super();
}
getUser():User
{
return this.user;
}
print(message:string){
for (const line of message.split('\n'))
{
this.user.tellraw(line);
}
}
taggedPrint(tag:LOG.Tag, message:string):void
{
for (const line of message.split('\n'))
{
this.user.tellraw(TAG_TO_COLOR[tag] + line);
}
}
onUpdateSlow():void
{
if (this.checking)
{
const rot = this.user.component.Rotation;
title(this.user.name, 'actionbar', `angleY=${rot.data.y.toFixed(1)},angleX=${rot.data.x.toFixed(1)}
riding=${this.user.ridingId}
dimension=${DimensionId[this.user.dimension]}`);
}
}
onInterect(block:Block):boolean
{
if (!this.user.isAdminMode())
{
if (!this.user.isAdminAccount) return false;
if (this.user.hand === ID.stick)
{
this.user.setAdminMode(true);
return true;
}
return false;
}
switch (this.user.hand)
{
case ID.stick:
this.user.setAdminMode(false);
break;
case ID.arrow:
const target = User.getAt(block.pos, 2, this.user);
if (target) banlist.ban(target, {action:LOG.Action.ManualBan, msg: "by arrow"});
break;
case ID.diamond_sword:
if (block.pos.equals(this.lastLogViewPos))
{
db.execute(`select ${LOG_QUERY} from act where `
+`x=${block.pos.x} && y=${block.pos.y} && z=${block.pos.z} && id < ${this.lastLogViewIndex} order by id desc limit 10`)
.then(row=>this._printLogs(row));
}
else
{
db.execute(`select ${LOG_QUERY} from act where `
+`x=${block.pos.x} && y=${block.pos.y} && z=${block.pos.z} order by id desc limit 10`)
.then(row=>this._printLogs(row));
this.lastLogViewPos = block.pos;
}
break;
case ID.diamond_pickaxe:
this.user.tellraw(`${block.pos.x} ${block.pos.y} ${block.pos.z}`);
break;
case ID.bow:
this.checking = !this.checking;
if (!this.checking)
{
title(this.user.name, 'actionbar', '§0');
}
break;
case ID.crossbow:
const flags = Container.getFlags(block.id);
if (flags !== -1)
{
const c = Container.peek(this.user.name, flags, block.pos);
if (!c)
{
this.user.tellraw(`${block}${block.pos} no container information`);
}
else
{
this.user.tellraw(c.getInventoryText());
}
}
break;
case ID.golden_apple:
this.user.tellraw(`start at ${block.pos}`);
this.fillFrom = block.pos;
break;
case ID.apple:
if (!this.fillFrom)
{
this.user.tellraw(`need to set start point`);
break;
}
this.user.tellraw(`remove to ${block.pos}`);
fillx(this.fillFrom, block.pos, ID.air);
this.fillFrom = null;
break;
case ID.appleenchanted:
if (!this.fillFrom)
{
this.user.tellraw(`need to set start point`);
break;
}
this.user.tellraw(`filled to ${block.pos}`);
fillx(this.fillFrom, block.pos, block.id, block.data);
this.fillFrom = null;
break;
default: return false;
}
return true;
}
onPlace(block:Block, hand:Identifier):boolean
{
if (!this.user.isAdminMode()) return false;
switch (block.id)
{
case ID.emerald_block:
testforblock(block.pos, block.id).then(exists=>{
if (exists)
{
setWorldSpawn(block.pos);
execute(this.user.name).setblock(block.pos, ID.air);
this.user.tellraw(`스폰 지역 ${block.pos} 설정됨`);
LOG.message({user:this.user, action:LOG.Action.SetSpawn, pos:block.pos});
}
})
break;
default: return false;
}
return true;
}
onAttack(ev:AttackEvent):void
{
if (!this.user.isAdminMode()) return;
switch (this.user.hand)
{
case ID.crossbow:
if (!ev.targetUser) return;
this.user.tellraw(ev.targetUser.extra(SoftInventory).getInventoryText());
break;
}
}
onDispose():void
{
this.user.setAdminMode(false);
}
}
<file_sep>/src/lib/data.ts
export class LimitedArray<T>
{
private readonly array:T[] = [];
private offset:number = 0;
constructor(private readonly max:number)
{
}
push(value:T):void
{
if (this.array.length >= this.max)
{
this.array[this.offset++] = value;
if (this.offset >= this.max)
{
this.offset = 0;
}
}
this.array.push(value);
}
*values():IterableIterator<T>
{
for (let i=this.offset;i<this.max;i++)
{
yield this.array[i];
}
for (let i=0;i<this.offset;i++)
{
yield this.array[i];
}
}
}<file_sep>/src/server/module/watch.ts
import ID from "@mcbe/identifier/id";
import { tickTime, isNight } from "@mcbe/timer/ticktime";
import { getDayTime } from "@mcbe/command";
import { User, UserExtra } from "@bdsx/ruakr_user";
import Identifier from "@mcbe/identifier";
export class WatchComponent implements UserExtra
{
private showed = false;
constructor(public readonly user:User)
{
}
onItemChange(now:Identifier, prev:Identifier):void
{
if (now === ID.clock)
{
this.show();
}
else if (prev === ID.clock)
{
this.hide();
}
}
onDispose():void
{
this.hide();
}
show():void
{
if (this.showed) return;
this.showed = true;
(async()=>{
for (;;)
{
if (!this.showed) return;
const time = await getDayTime();
const gamemin = Math.round(time / 1000 * 60);
const min = (gamemin + 60*6) % (24*60);
const night = isNight(time);
this.user.actionbar(`${min>=12*60?'오후':'오전'} ${((min/60|0)+11)%12+1}시 ${min%60}분 (${night ? '밤' : '낮'})`);
const nexttime = Math.ceil((gamemin + 1) / 60 * 1000);
await tickTime.promise(Math.max(nexttime - time, 0));
}
})();
}
hide():void
{
if (!this.showed) return;
this.showed = false;
this.user.actionbar(`§0`);
}
}
<file_sep>/src/server/pvpzone.ts
import { tellrawAll, command } from "@mcbe/system_server";
import { tickTime, TICK_PER_SECONDS, NIGHT_BEGIN, DAY } from "@mcbe/timer/ticktime";
import { getDayTime } from "@mcbe/command";
import { Store, Storage } from "@mcbe/store";
import { TIME_PER_SECONDS, realTime } from "@mcbe/timer/realtime";
import events from "@mcbe/event_server";
import { Block } from "@bdsx/block";
import { restoreBlock } from "@bdsx/restoreblock";
import { Region, FilteredWriteLock } from "./module/region";
import { Box, Vector3 } from "krgeometry";
import { tradeCenter, priceRound, DIAMOND_PRICE, priceToString } from "./structure/tradecenter";
import { toTimeText } from "../lib/korean";
import { MoneyPrizeBlock, PrizeBlock } from "./prizeblock";
import { CID } from "./customid";
import { Averager } from "../lib/averager";
import { User } from "@bdsx/ruakr_user";
const tickTimeAvg = new Averager(TICK_PER_SECONDS);
let _now = Date.now();
events.update.on(()=>{
const now = Date.now()
tickTimeAvg.put(now - _now);
_now = now;
});
const VAR_WIN_COUNT = '#pvp_win';
const VAR_LAST_WIN = '#pvp_last_win';
export const pvpstore = new Store('pvp');
let pvp_main:Storage;
Store.onLoad.then(()=>{
pvp_main = pvpstore.create('main');
});
enum PVPZoneState
{
Closed,
Ready,
Started,
}
class FilteredNoPushWriteLock extends Region
{
constructor(name:string, cube:Box)
{
super(name, cube);
}
onPlace(user:User, block:Block):boolean
{
if (user.isAdminMode()) return false;
block.destroy();
return true;
}
onDestroy(user:User, block:Block):void
{
if (!PrizeBlock.contains(block.pos))
{
restoreBlock(user, block);
}
}
}
class SpawnRegion extends FilteredNoPushWriteLock
{
private readonly internalHoal = new Box(-240, 58, -903, -204, 62, -861);
constructor()
{
super(
'스폰 지반',
new Box(-283, 0, -906, -157, 62, -796));
}
onPlace(user:User, block:Block):boolean
{
if (this.internalHoal.contains(block.pos)) return false;
return super.onPlace(user, block);
}
onDestroy(user:User, block:Block):void
{
if (this.internalHoal.contains(block.pos)) return;
super.onDestroy(user, block);
}
onEnter(user:User):null
{
if (this.internalHoal.contains(user.position)) return null;
user.tp(new Vector3(user.position.x, this.cube.y2+1, user.position.z));
return null;
}
}
class PVPZone
{
private readonly joined:Set<User> = new Set<User>();
private state = PVPZoneState.Closed;
private prizeMoney = 0;
private prizeGold = 0;
// private prizeDiamond = 0;
private second:User|null = null;
private last:User|null = null;
private current:PVPRegion|null = null;
private pvpIndex = 0;
constructor()
{
}
infoAll(message:string):void
{
for (const user of this.joined)
{
user.infoFast(message);
}
}
start():void
{
if (this.state === PVPZoneState.Started) return;
if (this.joined.size <= 2)
{
if (this.joined.size <= 1)
{
tellrawAll([`§ePvP대회에 참가자가 없어 취소되었어요`]);
this.state = PVPZoneState.Closed;
return;
}
}
PrizeBlock.clear();
this.state = PVPZoneState.Started;
tellrawAll([`§ePvP대회가 시작되었어요!`]);
this.infoAll('시작');
}
_getLastWinner():Storage|null
{
for (const user of User.store.values())
{
if (user.get(VAR_LAST_WIN)) return user;
}
return null;
}
async ready():Promise<void>
{
if (this.state === PVPZoneState.Ready) return;
this.state = PVPZoneState.Ready;
this.current = pvpRegions[this.pvpIndex];
this.pvpIndex = (this.pvpIndex + 1) % pvpRegions.length;
const money = tradeCenter.getMoney() * 0.008;
this.prizeMoney = priceRound(money);
this.prizeGold = Math.round(money / DIAMOND_PRICE);
// this.prizeDiamond = Math.round(money / tradeCenter.getBasePriceOf(ID.diamond) / 2);
const time = await getDayTime();
let wait = NIGHT_BEGIN - time;
if (wait < 0) wait += DAY;
const endTick = tickTime.now + wait;
const message = (realTime:number)=>{
tellrawAll([`§e약 ${toTimeText(realTime)}뒤 PvP대회가 시작할 예정이에요!`]);
tellrawAll([`§ePvP장: ${this.current!.nameShort}`]);
tellrawAll([`§e위치: ${this.current!.positionName}`]);
tellrawAll([`§e상금: ${priceToString(this.prizeMoney)} + 경험치`]);
};
message(wait * tickTimeAvg.get() / TIME_PER_SECONDS);
const checkpoints:number[] = [
30*1000,
60*1000,
3*60*1000,
5*60*1000,
10*60*1000,
20*60*1000,
30*60*1000,
];
{
const _ticktimeavg = tickTimeAvg.get();
while (checkpoints.length)
{
const cp = checkpoints[checkpoints.length-1];
if ((endTick - tickTime.now) * _ticktimeavg < cp)
{
checkpoints.pop();
}
else
{
break;
}
}
}
while (checkpoints.length)
{
const cp = checkpoints[checkpoints.length-1];
const remainReal = (endTick - tickTime.now) * tickTimeAvg.get();
if (remainReal <= cp)
{
checkpoints.pop();
message(cp / TIME_PER_SECONDS);
}
await realTime.promise(1000);
}
await tickTime.promise(Math.max(endTick - tickTime.now - 5*TICK_PER_SECONDS, 0));
for (let i=5;i>=1;i--)
{
tellrawAll([`§ePvP 대회 시작: ${i}초`]);
await tickTime.promise(TICK_PER_SECONDS);
}
this.start();
}
finish():void
{
if (this.state !== PVPZoneState.Started) return;
this.state = PVPZoneState.Closed;
if (this.joined.size >= 2)
{
tellrawAll([`§ePvP 결과: 오류, ${this.joined.size}명이 남아있음`]);
this.last = this.second = null;
return;
}
const lastWinner = this._getLastWinner();
const user:User|undefined = this.joined.values().next().value;
let users:User[];
if (!user)
{
users = [this.last!, this.second!];
pvp_main.delete('stack');
tellrawAll([`§ePvP 결과: 무승부 (${this.last!.name}, ${this.second!.name})`]);
tellrawAll([`§e상금은 빨리 가져가시는 분이 임자에요`]);
if (lastWinner)
{
lastWinner.delete(VAR_LAST_WIN);
pvp_main.set('stack', 0);
}
}
else
{
users = [user];
user.info('승리하셨습니다!');
let stack:number;
if (lastWinner)
{
if (user.storage !== lastWinner)
{
lastWinner.delete(VAR_LAST_WIN);
user.storage.set(VAR_LAST_WIN, 1);
pvp_main.set('stack', 0);
stack = 0;
}
else
{
stack = pvp_main.add('stack', 1);
}
}
else
{
user.storage.set(VAR_LAST_WIN, 1);
pvp_main.set('stack', 1);
stack = 1;
}
user.storage.add(VAR_WIN_COUNT, 1);
let msg = `§ePvP 결과: ${user.name} 승리`;
if (stack > 1) msg += `(${stack} 연승)`;
tellrawAll([msg]);
const health = user.component.Health;
health.data.value = health.data.max;
user.component.Health = health;
command(`xp 1000 "${user.name}"`);
command(`effect "${user.name}" resistance 120 2`);
command(`effect "${user.name}" strength 120 2`);
users = [user];
}
const names = users.map(user=>user.name);
new MoneyPrizeBlock(names, this.current!.prizePoint, '다이아', CID.moneyblock, this.prizeMoney);
this.joined.clear();
this.last = this.second = null;
this.current = null;
}
leave(zone:PVPRegion, user:User):void
{
if (this.current !== zone) return;
if (this.joined.delete(user))
{
switch (this.state)
{
case PVPZoneState.Ready:
user.info('PvP존 이탈');
tellrawAll([`§e${user.name} 님이 PvP존에서 나가셨습니다(총 ${this.joined.size}명)`]);
break;
case PVPZoneState.Started:
user.kill();
tellrawAll([`§e${user.name}님 탈락(현재 ${this.joined.size}명)`]);
if (this.joined.size === 1)
{
this.second = user;
setTimeout(()=>{
this.finish();
}, 1000);
}
else if (this.joined.size === 0)
{
this.last = user;
}
break;
}
}
}
enter(zone:PVPRegion, user:User):string|null
{
if (this.current !== zone) return null;
switch (this.state)
{
case PVPZoneState.Started:
return this.joined.has(user) ? null : 'PvP중 입장 불가';
case PVPZoneState.Ready:
if (!this.joined.has(user))
{
this.joined.add(user);
user.info('PvP존 참가');
tellrawAll([`§e${user.name} 님이 PvP존에 참가하셨습니다(총 ${this.joined.size}명)`]);
}
break;
case PVPZoneState.Closed:
break;
}
return null;
}
intesectAll(region:Box):boolean
{
for (const r of pvpRegions)
{
for (const lock of r.locks)
{
if (lock.cube.intersect(region)) return true;
}
}
return false;
}
}
export const pvpzone = new PVPZone();
const pvpRegions:PVPRegion[] = [];
class PVPRegion extends Region
{
public readonly locks:Region[];
constructor(
public readonly nameShort:string,
public readonly positionName:string,
cube:Box,
public readonly prizePoint:Vector3,
...extraLock:Box[])
{
super(nameShort+' PvP장', cube, cube.y1+2);
pvpRegions.push(this);
this.locks = extraLock.map(v=>new FilteredWriteLock(this.name+' 사다리', v));
this.locks.push(new FilteredNoPushWriteLock(this.name,
cube.expand(2)));
}
onEnter(user:User):string|null
{
return pvpzone.enter(this, user);
}
onLeave(user:User):void
{
return pvpzone.leave(this, user);
}
onDeath(user:User):void
{
return pvpzone.leave(this, user);
}
}
const Y_OFFSET = 3;
export function initPvP():void
{
new PVPRegion(
"지하 창고",
"스폰 기준 서쪽",
new Box(
-299, 5, -854,
-283, 12, -836),
new Vector3(-287, 6, -845),
new Box(
-284, 14, -845,
-284, 65, -845).expand(1));
new PVPRegion(
"석신",
"스폰 기준 동쪽 타워",
new Box(
-159, 92 + Y_OFFSET, -878,
-116, 92 + Y_OFFSET, -835).expand(6),
new Vector3(-149, 93, -868),
new Box(
-153, 69, -871,
-153, 91, -871).expand(1));
new PVPRegion(
"<NAME>",
"스폰 기준 남서쪽",
new Box(
-352, 91 + Y_OFFSET, -818,
-294, 91 + Y_OFFSET, -762).expand(6),
new Vector3(-299, 92, -795),
new Box(
-293, 73, -791,
-293, 90, -790).expand(1));
new SpawnRegion();
}
<file_sep>/src/lib/hourtest.ts
const HOUR_TEST_DURATION = 60*60*1000;
const hourTest:(()=>void)[] = [];
export function setHourTest(fn:()=>void):void
{
hourTest.push(fn);
}
setInterval(async()=>{
for (const test of hourTest)
{
test();
}
}, HOUR_TEST_DURATION);
<file_sep>/src/server/module/pusher.ts
import { User } from "@bdsx/ruakr_user";
import { Damper } from "../../lib/damper";
import { Vector3 } from "krgeometry";
import { Region } from "./region";
import { tp } from "@mcbe/command";
import LOG from "@mcbe/ruakr_log";
import { banlist } from "@bdsx/ruakr_ban";
function vectorFromDirY(angleY:number):Vector3
{
return new Vector3(-Math.sin(angleY), 0, Math.cos(angleY));
}
function dirYFromVector(x:number, z:number):number
{
return Math.atan2(z, -x);
}
export class Pusher
{
private pushing:NodeJS.Timeout|null = null;
private readonly tooFastDamper = new Damper(5000);
constructor(public readonly user:User)
{
}
getPushPosition(region:Region, bottomY:number, distance:number)
{
class Axis
{
public readonly dist:number;
public readonly plus:boolean;
constructor(
public readonly dir:Vector3,
public readonly pos:number,
public readonly p1:number,
public readonly p2:number,
)
{
const center = (p1 + p2) / 2;
this.plus = pos > center;
this.dist = this.plus ? p2 - pos : pos - p1;
}
getPushTo():Vector3
{
let pushValue:number;
if (this.plus)
{
pushValue = Math.max(this.p2 - this.pos, 0) + distance;
}
else
{
pushValue = Math.min(this.p1 - this.pos, 0) - distance;
}
return pos.add(this.dir.mul(pushValue));
}
}
const pos = this.user.position;
const axis = [
new Axis(Vector3.X, pos.x, region.cube.x1, region.cube.x2),
new Axis(Vector3.Z, pos.z, region.cube.z1, region.cube.z2),
];
if (pos.y < bottomY)
{
axis.push(new Axis(Vector3.Y, pos.y, region.cube.y1, Infinity));
}
let min_dist = axis[0];
for (let i=1;i<axis.length;i++)
{
const dist = axis[i];
if (dist.dist < min_dist.dist)
{
min_dist = dist;
}
}
return min_dist.getPushTo();
}
pushFromNow(region:Region, bottomY:number, distance:number):void
{
if (!this.pushing)
{
this.pushing = setTimeout(()=>{
this.pushing = null;
}, 300);
}
const to = this.getPushPosition(region, bottomY, distance);
this.user.tp(to);
}
rotate180(pos:Vector3, displayMessage:string):boolean
{
if (this.pushing) return false;
if (!this.tooFastDamper.use(700, 0))
{
this.tooFastDamper.reset();
banlist.warning(this.user, 10, {action:LOG.Action.AggressiveEntering, msg:displayMessage});
this.user.kill();
this.user.tellraw('§c※주의※: §r계속 반복하면 추방될 수 있어요');
return false;
}
const from = this.user.position;
const dirY = dirYFromVector(from.x - pos.x, from.z - pos.z);
tp(this.user.name, from, dirY * 180 / Math.PI);
return true;
}
pushFrom(region:Region, bottomY:number, distance:number, displayMessage:string):boolean
{
if (this.pushing) return false;
if (!this.tooFastDamper.use(700, 0))
{
this.tooFastDamper.reset();
banlist.warning(this.user, 10, {action:LOG.Action.AggressiveEntering, msg:displayMessage});
this.user.kill();
this.user.tellraw('§c※주의※: §r계속 반복하면 추방될 수 있어요');
return false;
}
this.user.info(displayMessage);
this.pushFromNow(region, bottomY, distance);
return true;
}
}
<file_sep>/src/lib/type.ts
export interface BlockInfo
{
hardness:number;
tool:number;
hand:number;
wooden:number;
stone:number;
iron:number;
diamond:number;
golden:number;
shears:number;
sword:number;
}
export enum ToolType
{
Any,
Axe,
Pickaxe,
Shears,
Shovel,
Sword,
}
<file_sep>/src/server/module/hardinventory.ts
import Identifier from "@mcbe/identifier";
import ID from "@mcbe/identifier/id";
import { callAtNextTick, NextTick } from "@mcbe/nexttick";
import { execute, clear } from "@mcbe/command";
import { Box, Vector3 } from "krgeometry";
import { ItemList, ItemStack } from "@mcbe/item";
import { pickOutOrCraft, PASS_TOOLCHECK } from "@mcbe/recipe/make";
import { sortForCraft } from "@mcbe/recipe/sort";
import { ArrayMap } from "../../lib/arraymap";
import { Entity, EntityType } from "@mcbe/entity";
import { Block } from "@bdsx/block";
import LOG from "@mcbe/ruakr_log";
import { User, UserExtra, Container } from "@bdsx/ruakr_user";
import { banlist } from "@bdsx/ruakr_ban";
import { SoftInventory } from "./softinventory";
import { UseMethod, AcquationMethod } from "@mcbe/ruakr_const";
export class HardInventory extends SoftInventory implements UserExtra
{
public readonly inventoryRemoved:ItemList = new ItemList;
private readonly itemUsing:[Identifier, number, (failed:number)=>number][] = [];
private readonly ignoreFirstDrop = new ItemList();
private skipIgnoreFirstDrop:NextTick|null = null;
private container:Container|null = null;
private containerErrorCount = 0;
constructor(user:User)
{
super(user);
}
private _useItem(id:Identifier, count:number, callback?:(failed:number)=>number):void
{
if (!callback)
{
callback = failed=>{
if (failed !== 0)
{
callAtNextTick(()=>{
banlist.ban(this.user, {action:LOG.Action.OverItem, item:id, count, msg: `use`});
});
}
return failed;
};
}
this.itemUsing.push([id, count, callback]);
this.requestCheckInventory();
}
onTakeItem(id:Identifier, count:number):void
{
this._useItem(id, count);
}
onGiveItem(id:Identifier, count:number):void
{
this.inventory.add(id, count);
}
onUseItem(method:UseMethod, item:Identifier, count:number):void
{
if (!this.user.isAdminMode() && SoftInventory.BAN_BLOCK.has(item))
{
banlist.ban(this.user, {action:LOG.Action.BlockedItem, item, count, msg:'use: '+method});
return;
}
switch (method)
{
case UseMethod.Intract:
switch (item)
{
case ID.emptymap:
case ID.map:
this.inventory.add(ID.map, 1);
this._useItem(ID.emptymap, 1);
break;
case ID.salmon:
case ID.fish:
this._useItem(item, 1);
break;
}
break;
case UseMethod.Throw:
if (item === ID.ender_pearl)
{
// this.user.tp(null);
}
this._useItem(item, 1);
break;
case UseMethod.BlockPlace:
break;
case UseMethod.Place:
this._useItem(item, 1);
break;
case UseMethod.FillBottle:
break;
case UseMethod.Eat:
this._useItem(item, 1);
break;
case UseMethod.Consume:
if (item === ID.potion)
{
this._useItem(item, 1);
this.inventory.add(ID.glass_bottle, 1);
}
break;
}
}
onDropItem(item:Identifier, count:number)
{
if (this.ignoreFirstDrop.has(item, 1))
{
this.ignoreFirstDrop.remove(item, 1);
return;
}
super.onDropItem(item, count);
const dropRemoving = new ArrayMap<Identifier, Entity>();
const pos = this.user.component.Position.data;
Entity.catchPre(new Box(pos.x-3, pos.y-3, pos.z-3, pos.x+3, pos.y+3, pos.z+3), ev=>{
if (ev.entity.type !== EntityType.Item) return false;
dropRemoving.push(ev.entity.id, ev.entity);
return false;
});
this._useItem(item, count, failed=>{
if (failed === 0) return 0;
const entities = dropRemoving.get(item);
if (!entities)
{
LOG.error({user:this.user, action:LOG.Action.OverItem, item, count:failed, msg:`dropping`});
return failed;
}
for (const entity of entities)
{
entity.destroy();
}
banlist.warning(this.user, 20, {action:LOG.Action.OverItem, item, count:failed, msg:`dropping`});
return 0;
});
}
onAcquireItem(method:AcquationMethod, item:Identifier, count:number, secondary_entity?:IEntity):void
{
super.onAcquireItem(method, item, count, secondary_entity);
if (this.fullTest(item))
{
this.ignoreFirstDrop.add(item, 1);
if (this.skipIgnoreFirstDrop !== null)
{
this.skipIgnoreFirstDrop = callAtNextTick(()=>{
this.ignoreFirstDrop.clear();
this.skipIgnoreFirstDrop = null;
});
}
}
this.inventory.add(item, count);
switch (method)
{
case 'picked_up':
break;
case 'filled':
if (item === ID.potion)
{
this.inventory.remove(ID.glass_bottle, count);
}
else
{
}
break;
default:
break;
}
}
onInterect(block:Block):boolean
{
const flags = Container.getFlags(block.id);
if (flags === Container.INVALID)
{
this.container = null;
return false;
}
this.container = Container.peek(this.user.name, flags, block.pos);
if (!this.container)
{
Container.destroy(this.user, flags, block.pos);
}
else
{
this.containerErrorCount = 0;
}
return false;
}
onInterectEnd():void
{
this.container = null;
}
onDeath():void
{
this.inventoryRemoved.clear();
}
private async _finalInventory(failedList:ItemList):Promise<boolean>
{
if (failedList.size() === 0) return true;
// 데이터 0 지우기
const proms:Promise<void>[] = [];
for (const item of failedList.values())
{
const prom = clear(this.user.name, item.id, -1, item.count).then(removed=>{
const failed = this.inventory.use(item.id, removed);
item.count -= removed;
if (failed !== 0)
{
item.count += failed;
}
else
{
if (item.count === 0)
{
failedList.reset(item.id);
}
}
});
proms.push(prom);
}
await Promise.all(proms);
return failedList.size() === 0;
}
protected _updateInventory():void
{
if (this.inventoryChecked) return;
for (const place of this.user.placings.poll())
{
this._useItem(place.item, 1, failed=>{
if (place.placeBlock)
{
if (failed > 0)
{
execute(this.user.name).setblock(place.placeBlock.pos, ID.air);
return failed-1;
}
else
{
this.user.onPlaceBlockFinal(place.placeBlock, place.item);
}
}
return failed;
});
}
const added:ItemStack[] = [];
const removed:ItemStack[] = [];
this._getInventoryDiff(added, removed);
const interectingBlock = this.user.interectingBlock;
const container = this.container;
let oldinv:ItemList|null = null;
let inventory:ItemList|null = null;
const failedList = new ItemList;
const cleanPickCallback = new ArrayMap<Identifier, [(failed:number)=>number,number]>();
const getInventory = ()=>{
if (inventory) return inventory;
if (!container) return inventory = this.inventoryRemoved;
inventory = new ItemList;
container.getAll(inventory);
oldinv = inventory.clone();
inventory.addAll(this.inventoryRemoved);
this.inventoryRemoved.clear();
return inventory;
};
const cleanInventory = ()=>{
if (inventory)
{
inventory.clean();
if (container)
{
container.updateAll(inventory);
}
}
};
const useItem = (id:Identifier, count:number)=>{
if (SoftInventory.BAN_BLOCK.has(id) || id.name.endsWith('_spawn_egg'))
{
banlist.ban(this.user, {action:LOG.Action.BlockedItem, item:id, count});
failedList.add(id, count);
return count;
}
const inv = getInventory();
let tool = interectingBlock && interectingBlock.id;
if (tool === ID.lit_blast_furnace) tool = ID.blast_furnace;
else if (tool === ID.lit_furnace) tool = ID.furnace;
else if (tool === ID.lit_smoker) tool = ID.smoker;
/// XXX: cannot check interecting tool
const failed = pickOutOrCraft(inv, PASS_TOOLCHECK, id, count);
if (failed === 0) return 0;
if (container)
{
this.containerErrorCount++;
const flags = container.getFlags();
if (this.containerErrorCount >= 3 && flags !== Container.CHEST_ENDER)
{
this.containerErrorCount = 0;
Container.destroy(this.user, flags, interectingBlock!.pos);
}
}
let logargs:LOG.Arguments;
if (container)
{
logargs = {user:this.user, action:LOG.Action.OverItem, pos:interectingBlock!.pos, item:id, count:failed, msg: `with ${container}`};
}
else
{
logargs = {user:this.user, action:LOG.Action.OverItem, item:id, item2:tool, count:failed, msg: `without container`};
}
if (this.user.isAdminMode())
{
LOG.message(logargs);
return 0;
}
banlist.warning(this.user, 1, logargs);
failedList.add(id, failed);
return failed;
};
if (removed.length !== 0)
{
const inv = getInventory();
for (const item of removed)
{
inv.add(item.id, item.count);
}
}
sortForCraft(added);
for (const item of added)
{
useItem(item.id, item.count);
}
/// ---- remove using ----
for (const [id, count, callback] of this.itemUsing)
{
const failed = useItem(id, count);
if (failed === 0)
{
callback(0);
}
else
{
cleanPickCallback.push(id, [callback, failed]);
}
}
this.itemUsing.length = 0;
cleanInventory();
// ---- diff with old ---
if (container && oldinv)
{
const cadded:ItemStack[] = [];
const cremoved:ItemStack[] = [];
(<ItemList>oldinv).diff(inventory!, cadded, cremoved);
for (const item of cadded)
{
LOG.verbose({user:this.user, action:LOG.Action.Get, item, pos: interectingBlock?.pos, msg: container.toString()});
}
for (const item of cremoved)
{
LOG.verbose({user:this.user, action:LOG.Action.Put, item, pos: interectingBlock?.pos, msg: container.toString()});
}
}
/// ---- remove failed ----
let willBan:LOG.Arguments|null = null;
const diamond_block_count = failedList.getCount(ID.diamond_block);
const diamond_count = failedList.getCount(ID.diamond);
if (diamond_block_count >= 64) willBan = {user:this.user, item:ID.diamond_block, count:diamond_block_count, action:LOG.Action.OverItem, msg:'diamond block 64'};
else if (diamond_count >= 64) willBan = {user:this.user, item:ID.diamond, count:diamond_count, action:LOG.Action.OverItem, msg:'diamond 64'};
if (failedList.size() !== 0)
{
LOG.message({user:this.user, action:LOG.Action.OverItemKeeping, msg:this.getKeepingText()});
}
const creating:ItemStack[] = [];
for (const {id, count} of failedList.values())
{
creating.push({id, count});
}
this._finalInventory(failedList).then(succeeded=>{
if (succeeded)
{
for (const [id, cpcs] of cleanPickCallback)
{
for (const [resolve, count] of cpcs)
{
resolve(0);
}
}
}
else
{
for (const [id, cbcs] of cleanPickCallback)
{
const items = failedList.get(id);
if (!items)
{
for (const [resolve, count] of cbcs)
{
resolve(0);
}
}
else
{
for (const [resolve, count] of cbcs)
{
if (items.count === 0)
{
resolve(0);
}
else
{
const failed = Math.min(items.count, count);
items.count = resolve(failed);
}
}
if (items.count === 0)
{
failedList.reset(id);
}
}
}
if (failedList.size() === 0) return;
const item:ItemStack = failedList.values().next().value;
willBan = {user:this.user, item, action:LOG.Action.OverItem, msg:'remove failed'};
}
if(willBan) banlist.ban(this.user, willBan);
}).catch(console.error);
}
onUpdateSlow():void
{
this._updateInventory();
}
onUpdateReal():void
{
if (!this.user.placings.empty())
{
this.inventoryChecked = false;
this._updateInventory();
}
}
getKeepingText():string
{
if (this.inventoryRemoved.size() === 0)
{
return `no keep`;
}
else
{
let out = '';
for (const item of this.inventoryRemoved.values())
{
out += `keep ${item.id}(${item.count})\n`;
}
return out;
}
}
}<file_sep>/src/server/prizeblock.ts
import { Region } from "./module/region";
import Identifier from "@mcbe/identifier";
import { setFarBlock } from "@mcbe/farticker";
import { Box, Vector3 } from "krgeometry";
import { User } from "@bdsx/ruakr_user";
import { removeBlockDrop } from "@bdsx/restoreblock";
import { Wallet } from "./module/wallet";
import { tradeCenter, DIAMOND_PRICE, priceToString } from "./structure/tradecenter";
import ID from "@mcbe/identifier/id";
import { Block } from "@bdsx/block";
const all:PrizeBlock[] = [];
export class PrizeBlock extends Region
{
private done = false;
constructor(
private readonly who:string[],
private readonly pos:Vector3,
priceName:string,
priceBlock:Identifier
)
{
super(priceName+' 보상', Box.fromVector(pos, pos));
setFarBlock(pos, priceBlock);
all.push(this);
}
onPrize(user:User):void
{
}
onDestroy(user:User, block:Block):void
{
if (this.done) return;
this.done = true;
removeBlockDrop(block);
this.onPrize(user);
PrizeBlock.clear();
}
canWrite(user:User|null):boolean
{
if (!user) return false;
return this.who.indexOf(user.name) !== -1;
}
remove():boolean
{
if (!super.remove()) return false;
setFarBlock(this.pos, ID.air);
return true;
}
static contains(pos:Vector3):boolean
{
for (const block of all)
{
if (block.pos.equals(pos)) return true;
}
return false;
}
static clear():void
{
for (const prize of all)
{
prize.remove();
}
}
}
export class MoneyPrizeBlock extends PrizeBlock
{
constructor(
who:string[],
pos:Vector3,
priceName:string,
priceBlock:Identifier,
private readonly money:number)
{
super(who, pos, priceName, priceBlock);
}
onPrize(user:User)
{
const wallet = user.extra(Wallet);
wallet.add(this.money);
tradeCenter.removeMoney(this.money);
user.infoFast(priceToString(this.money)+' 증가');
}
}
/** @deprecated */
export class ItemPrizeBlock extends PrizeBlock
{
constructor(
who:string[],
pos:Vector3,
priceName:string,
private readonly priceId:Identifier,
private readonly count:number,
priceBlock:Identifier,
private readonly prizeGold:number)
{
super(who, pos, priceName, priceBlock);
}
onPrize(user:User)
{
tradeCenter.removeDiamond(this.prizeGold);
tradeCenter.removeMoney(this.prizeGold * DIAMOND_PRICE);
user.giveItem(this.priceId, 0, this.count);
}
}
<file_sep>/src/server/module/last_conn.ts
import { User, UserExtra } from "@bdsx/ruakr_user";
import { scoreboard, Scores } from "@mcbe/command";
import { timepack } from "@mcbe/ruakr_util";
import { Storage } from "@mcbe/store";
export const VAR_LAST_CONN = '#last_conn';
export function getLastConnection(storage:Storage):number
{
if (User.getByName(storage.name))
{
return timepack.unpack(timepack.now());
}
const now = storage.get(VAR_LAST_CONN);
return timepack.unpack(now || 0);
}
export class LastConnection implements UserExtra
{
constructor(public readonly user:User)
{
this.user.storage.set(VAR_LAST_CONN, timepack.now());
}
onDispose():void
{
this.user.storage.set(VAR_LAST_CONN, timepack.now());
}
static onInstall():void
{
scoreboard.objectives.add(VAR_LAST_CONN);
}
}
<file_sep>/src/lib/korean.ts
const FIRST = "가".charCodeAt(0);
const LAST = "힣".charCodeAt(0);
const INITIAL_COUNT = 19;
const MEDIAL_COUNT = 21;
const FINAL_COUNT = 28;
export function subject(text:string):string
{
const chr = text.charCodeAt(text.length-1);
const final = (chr - FIRST) % FINAL_COUNT;
return final === 0 ? '는' : '은';
}
export function topic(text:string):string
{
const chr = text.charCodeAt(text.length-1);
const final = (chr - FIRST) % FINAL_COUNT;
return final === 0 ? '가' : '이';
}
export function neun(text:string):string
{
const chr = text.charCodeAt(text.length-1);
const final = (chr - FIRST) % FINAL_COUNT;
return final === 0 ? '를' : '을';
}
export function toTimeText(remaining:number):string
{
remaining = Math.round(remaining);
if (remaining <= 60)
{
return remaining + '초';
}
if (remaining < 2*60)
{
const min = remaining / 60 | 0;
const sec = remaining % 60;
if (sec === 0) return min+'분';
return min+'분 '+sec+'초';
}
if (remaining <= 60*60)
{
const min = remaining / 60 | 0;
return min+'분';
}
if (remaining < 2*60*60)
{
remaining = remaining / 60 | 0;
const hours = remaining / 60 | 0;
const min = remaining % 60;
if (min === 0) return min+'시간';
return hours+'시간 '+min+'분';
}
if (remaining <= 24*60*60)
{
remaining = remaining / (60*60) | 0;
return remaining+'시간';
}
if (remaining < 2*24*60*60)
{
remaining = remaining / (60*60) | 0;
const day = remaining / 24 | 0;
const hours = remaining % 24;
if (hours === 0) return day+'일';
return day+'일 '+hours+'시간';
}
const day = remaining / (24*60*60) | 0;
return day+'일';
}
<file_sep>/src/server/spawnpoint.ts
import { WriteLock } from "./module/region";
import { Scoreboard } from "@mcbe/scoreboard";
import { Vector3, Box } from "krgeometry";
import { command } from "@mcbe/system_server";
import { UserExtra, User, AttackEvent } from "@bdsx/ruakr_user";
const board = new Scoreboard('$spawn');
export const SPAWN_SIZE = 50;
export let SPAWN_POINT:Vector3;
export const SPAWN_GUARD_AREA = 20;
export let spawnLock:WriteLock;
function setSpawn(pos:Vector3):void
{
SPAWN_POINT = pos;
spawnLock = new WriteLock('스폰 지점', new Box(
pos.x - SPAWN_SIZE, -Infinity, pos.z - SPAWN_SIZE,
pos.x + SPAWN_SIZE, Infinity, pos.z + SPAWN_SIZE), pos.y - 3);
}
export function setWorldSpawn(pos:Vector3):void
{
pos = pos.floor();
board.set('x', pos.x);
board.set('y', pos.y);
board.set('z', pos.z);
spawnLock.remove();
setSpawn(pos);
command(`setworldspawn ${pos.x} ${pos.y} ${pos.z}`);
}
export class SpawnPointExtra implements UserExtra
{
constructor(public readonly user:User)
{
}
onAttack(ev:AttackEvent)
{
const other = ev.targetUser;
if (other)
{
if (new Box(
SPAWN_POINT.x - SPAWN_GUARD_AREA, spawnLock.cube.y1, SPAWN_POINT.z - SPAWN_GUARD_AREA,
SPAWN_POINT.x + SPAWN_GUARD_AREA, Infinity, SPAWN_POINT.z + SPAWN_GUARD_AREA
).contains(other.position))
{
this.user.kill();
}
}
}
static onInstall():void
{
Promise.all([board.get('x'), board.get('y'), board.get('z')]).then(([x, y, z])=>{
if (x === undefined)
{
setSpawn(new Vector3(12, 64, 4));
}
else
{
setSpawn(new Vector3(x, y!, z!));
}
});
}
}
<file_sep>/src/server/pistoncheck.ts
import { Vector3 } from "krgeometry";
import ID from "@mcbe/identifier/id";
import { tellrawAll } from "@mcbe/system_server";
import { execute } from "@mcbe/command";
import { User } from "@bdsx/ruakr_user";
let pistonTime = 0;
interface PistonWeight
{
position:Vector3;
time:number;
}
const pistons:PistonWeight[] = [];
const PISTON_LIMIT = 80;
export function updatePistonCheck():void
{
if (pistonTime >= PISTON_LIMIT)
{
if (pistons.length > 0)
{
let slowestIdx = 0;
let slowest = pistons[0];
for (let i=1;i<pistons.length;i++)
{
const piston = pistons[i];
if (piston.time > slowest.time)
{
slowest = piston;
slowestIdx = i;
}
}
const last = pistons.pop();
if (last !== slowest)
{
pistons[slowestIdx] = last!;
}
const {user} = User.getNearst(slowest.position);
if (user)
{
execute(user.name).setblock(slowest.position, ID.air, 0, 'destroy');
tellrawAll([`§e부하가 너무 커 ${user.name}님 근처의 피스톤을 부쉈어요`]);
}
}
}
for (let i=0;i<pistons.length;)
{
const p = pistons[i];
p.time *= 0.95;
if (p.time < 0.1)
{
const last = pistons.pop();
if (last !== p)
{
pistons[i] = last!;
}
}
else
{
i++;
}
}
pistonTime = 0;
}
export function addPistonTime(position:Vector3, time:number):void
{
pistonTime += time;
for (const piston of pistons)
{
if (!piston.position.equals(position)) continue;
piston.time += time;
return;
}
pistons.push({
position,
time
});
}
| 8df55e346a73d6d6e03bb7e3bbc9bd2535d8ad7c | [
"Markdown",
"TypeScript"
] | 48 | TypeScript | karikera/ruarule | 678b44801dd7ae749ce1a94a701eab6b78833fd4 | 47283c33d93a853d6899be95ff6909edaa99b7e3 |
refs/heads/master | <file_sep>
function Topfixed(options){
var opts = $.extend({
id:'#topFixed',
fixedClass:'top-fixed'
},options);
var fixed = $(opts.id);//获取吸顶目标ID对象
var marginBottom = parseInt(fixed.css('marginBottom')) || 0;//吸顶目标的下边距
//var blank = document.createElement('div');//创建空div
var blank = $('<div></div>');//两种创建空DIV的方式
var height = parseInt(fixed.outerHeight()+marginBottom-2);//目标元素的高度+下边距
var scrolltop = $(window).scrollTop();//获取滚动条的滑动距离
var fixedClass = opts.fixedClass;//获取默认的类名,与$(opts.id)不同,$(opts.id)获取的是对象;opts.fixedClass获取的是名称
fixed.after(blank);//在吸顶目标外面的后面加空DIV
$(blank).css({
"height":height//空DIV的高度=目标ID元素的高度+下边距
}).hide();//将空DIV隐藏,即正常时不显示
this.init = function(){
_show();
$(window).scroll(function(){
scrolltop = $(window).scrollTop();
_show();
});
}
function _show(){
if(scrolltop>47){//滚动条滚过的长度大于吸顶元素距离top的长度。47怎么得到的?
fixed.addClass(fixedClass);//目标吸顶元素增加类:fixedClass,该类在common.less中做了定义
$(blank).show();//显示出空DIV,由于position的缘故,空div相当于占位符,放在了吸顶目标的下面。
}else{
fixed.removeClass(fixedClass);
$(blank).hide();
}
}
}<file_sep># jiayunfu.github.io<file_sep>// 顶部导航 广告
function Ad(){
this.num = 0;
this.timer = null;
this.bindDom();
this.time();
}
Ad.prototype.bindDom = function(){
this.ul=document.getElementById('Pay');
this.liArr = this.ul.children;
this.arr = [].slice.call(this.liArr);
};
Ad.prototype.show = function(){
var that = this;
animate(this.ul,{top:-54});
setTimeout(function(){
var li = that.arr.shift();
that.arr.push(li);
that.ul.innerHTML = "";
for(var i = 0; i < that.arr.length; i++){
that.ul.appendChild(that.arr[i]);
}
that.ul.style.top = 0 +"px";
},2000)
};
Ad.prototype.autoStep = function(){
this.null++;
if(this.num > this.liArr.length-1){
this.num = 0;
this.movieCon.style.top = 0 + "px";
}
this.show()
};
Ad.prototype.time = function(){
var that = this;
this.timer = setInterval(function(){
that.autoStep()
},2000);
};
new Ad();
//
function Breathe(job_nav,job_con,a,div){
this.job_nav=document.getElementById(job_nav);
this.job_con=document.getElementById(job_con);
this.aArr=this.job_nav.getElementsByTagName(a);
this.divArr=this.job_con.getElementsByTagName(div);
this.bindeDom();
this.Step();
this.dot();
}
Breathe.prototype = {
bindeDom : function(){
this.aArr[0].style.zIndex=10;
this.num=0;
},
show : function(n){
// 排他思想(其他图片都透明度为0)
// 其他小方块去"cur"
// 显示当前(第i张图片透明度为1)
// 当前小方块(第i张)加"cur"
for(var i=0; i<this.aArr.length;i++){
this.aArr[i].className="nav"+[i+1];
this.divArr[i].className="con"+[i+1];
}
this.aArr[n].className+=" role"+[n+1];
this.divArr[n].className+=" active";
},
autoStep : function (){
this.num++;
if(this.num>this.aArr.length-1){
this.num=0;
}
this.show(this.num);
},
Step : function (){
var that = this;
this.timer=setInterval(function(){
that.autoStep();
},4000)
},
dot : function(){
// 鼠标经过小方块
var that = this;
for(var m=0; m<this.aArr.length; m++){
this.aArr[m].onmouseover=function(){
for(var n=0; n<that.aArr.length; n++){
if(this==that.aArr[n]){
// 关联索引值
that.num=n;
that.show(that.num);
}
}
}
}
}
}
new Breathe("job_nav","job_con","a","div");
//碰壁反弹
function Pengbi(){
this.qr=document.getElementById('qr');
this.pbft=document.getElementById('pbft');
this.posX=10;
this.stepX=1;
this.lockX=true;
this.maxH=this.qr.clientHeight-this.pbft.offsetHeight;
this.timer=null;
this.moveStep();
}
Pengbi.prototype = {
moveStep:function(){
var that=this;
this.timer=setInterval(function(){
if(that.lockX){
if(that.posX<10){
that.lockX=false;
}
that.posX-=that.stepX;
that.pbft.style.top=that.posX+"px";
}else{
if(that.posX>that.maxH-15){
that.lockX=true;
}
that.posX+=that.stepX;
that.pbft.style.top=that.posX+"px";
}
},20);
}
}
new Pengbi();
//Tab切换
function Tab(titleName,contName,liArr,divArr,navpro){
this.tabTitle = document.getElementById(titleName);
this.tabCont = document.getElementById(contName);
this.liArr=this.tabTitle.getElementsByTagName(liArr);
this.divArr=this.tabCont.getElementsByTagName(divArr);
this.set(navpro);
}
Tab.prototype = {
set : function(navpro){
var _this = this;
for(var i=0; i<this.liArr.length; i++){
this.liArr[i].index=i;
this.liArr[i].onmouseover=function(){
_this.set1(this,navpro);
}
}
},
set1 : function(_this,navpro){
for(var j=0; j<this.liArr.length; j++){
this.liArr[j].className= navpro +[j+1];
this.divArr[j].className="";
}
this.liArr[_this.index].className+=" nav"+[_this.index+1];
this.divArr[_this.index].className="tabshow";
}
}
var tab = new Tab("tab_nav","tab_con","li","ul","li")
var tab = new Tab("left_nav","left_con","a","ul","a")
//传统轮播
function Carousel(right_top){
this.bindDom(right_top);
this.init();
}
Carousel.prototype={
bindDom:function(right_top){
this.right_top=document.getElementById(right_top);
this.ad=this.right_top.children[0];
this.ul=this.right_top.getElementsByTagName('ul')[0];
this.ol=this.right_top.getElementsByTagName('ol')[0];
this.olLiArr=this.ol.children;
this.imgWidth=this.ad.offsetWidth;
this.key=0;//控制图片
this.s=0; //控制小方块
this.timer=null;
},
init:function(){
this.autoPlay();
this.cur();
},
autoPlayStep:function (){
this.key++;
if(this.key>1){
this.key=0;
}
this.move(this.ul,-this.key*this.imgWidth);
this.s++;
if(this.s>1){
this.s=0;
}
for(var i=0; i<this.olLiArr.length; i++){
this.olLiArr[i].className="";
}
this.olLiArr[this.s].className="li";
},
autoPlay:function (){
var that = this;
clearInterval(this.timer);
this.timer=setInterval(function(){
that.autoPlayStep();
},3000)
},
cur:function(){
var that = this;
for(var i=0; i<this.olLiArr.length;i++){
this.olLiArr[i].onmouseover=function(){
for(var j=0; j<that.olLiArr.length;j++){
that.olLiArr[j].className="";
if(this==that.olLiArr[j]){
that.key=that.s=j;
that.olLiArr[j].className="li";
that.move(that.ul,-j*that.imgWidth);
}
}
}
}
},
move:function(ele,target){
// 该函数内部没有用到实例对象的任何属性和方法
// 所以不需要用到this
if(ele.timer){
clearInterval(ele.timer);
}
ele.timer=setInterval(moveStep,20)
function moveStep(){
var speed=(target-ele.offsetLeft)/20;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
ele.style.left=ele.offsetLeft+speed+"px";
var cha=target-ele.offsetLeft;
if(Math.abs(cha)<Math.abs(speed)){
clearInterval(ele.timer);
ele.style.left=target+"px";
}
}
}
}
new Carousel('right_top');
| 6116bb810880bbf6489e5648b2713f37f6ea375c | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | jiayunfu/jiayunfu.github.io | 11e9de102d6294ab5fa305afe6dc8e72d777c390 | d87dda25bda2a7b12389d46fb3af778aeeed787e |
refs/heads/master | <repo_name>crubiova/Mi-proyecto-BIT<file_sep>/controllers/UserController.js
const User = require('../models/User');
function create(req, res) {
var user = new User();
var params = req.body;
user.firstname = params.firstname;
user.lastname = parmas.lastname;
user.email = params.email;
user.age = params.age;
user.save((error, userCreated) => {
if (error) {
res.status(500).send({
statusCode: 500,
message: "Error en el servidor"
})
}else{
if(!userCreated) {
res.status(400).send({
statusCode: 400,
message: "Error al insertar el usuario"
})
}else{
res.status(200).send({
statusCode: 200,
message: "Usuario almacenado correctamente",
dataUser: userCreated
})
}
}
})
}
function update(req, res) {
var parameters = req.body;
var idUser = req.params.idUser;
User.findByIdAndUpdate( idUser, parameters, (error, userUpdate) => {
if(error) {
res.status(500).send({
statusCode:500,
message: "Error en el servidor"
})
} else {
if(!UserUdated) {
res.status(400).send({
statusCode: 400,
message: "Error al actualizar el usuario"
})
}else{
res.status(200).send({
statusCode: 200,
message: "Usuario actualizado correctamente"
})
}
}
})
}
function remove(req, res) {
var idUser = req.params.idUser;
User.findByIdAndDelete( idUser, (error, userRemoved) => {
if(error){
res.status(500).send({
statusCode: 500,
message:"Error en el servidor"
})
} else {
if(!userRemoved){
res.status(400)
}
}
})
}
module.exports = {
create
}<file_sep>/routes/userRoutes.js
const express = require('express');
const UserController = require('../controllers/UserController');
const api = express.Router();
api.get("/saludar",(req, res) => {
console.log('Llego a la ruta saludar...');
});
api.post('/', UserController.create);
api.put('/:idUser', UserController.update);
module.exports = api; | 997ce5eb6f10be615a7809395db8f38ba3461871 | [
"JavaScript"
] | 2 | JavaScript | crubiova/Mi-proyecto-BIT | 1894911ac076d030d60ddf54aed621cce92a5b35 | c76aad6765ccb605c848694a0e9c6b37ad786a32 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.