text:
<repo_name>pwnall/rails5738<file_sep>/test/models/person_test.rb
require 'test_helper'

class PersonTest < ActiveSupport::TestCase
  test 'rejects duplicate names' do
    me_too = Person.new name: 'é'
    assert_raise(ActiveRecord::RecordNotUnique) do
      me_too.save!
    end
  end

  test 'rejects invalid fields' do
    me_too = Person.new name: 'abc'
    me_too.attributes[:full_name] = 'é'
    assert_raise(ActiveRecord::StatementInvalid) do
      me_too.save!
    end
  end
end

branch_name: refs/heads/master

repo_language: Ruby


text:
<file_sep>'''
Created on 2017/2/25

@author: ych
'''
import os,sys
import StockAT
from configparser import ConfigParser

class AppUtil:

    __instance__ = None

    PROJ_ROOT = os.path.dirname(StockAT.__file__).replace('\\','/')
    SETTINGS = PROJ_ROOT + '/resource/conf/settings.conf'
    config = ConfigParser()
    config.read(SETTINGS,encoding='utf-8')

    def __new__(cls):
        if not AppUtil.__instance__:
            AppUtil.__instance__ = object.__new__(cls)
        return AppUtil.__instance__

    def getStockMIS(self):
        return(self.config['TWSE']['STOCK_MIS'])

    def getStockRealTimePrice(self):
        return(self.config['TWSE']['RT_PRICE'])

    def getStockIDs(self):
        return(self.config['STATIC']['STOCKIDs'])

    def getLineChannelSecret(self):
        return(self.config['StoMonBot']['CHANNEL_SECRET'])

    def getLineChannelAccessToken(self):
        return(self.config['StoMonBot']['CHANNEL_ACCESS_TOKEN'])
    <file_sep>'''
Created on 2017/2/25

@author: ych
'''
import os,sys

class StockAT:

    def __init__(self):
        print('Hello StockAT')

if __name__ == '__main__':
    StockAT()<file_sep>web: gunicorn Bot.LineBot.StoMonBot:app --log-file -<file_sep>beautifulsoup4==4.5.3
bs4==0.0.1
click==6.7
Flask==0.12
future==0.16.0
html5lib==0.999999999
itsdangerous==0.24
Jinja2==2.9.5
line-bot-sdk==1.1.0
lxml==3.7.3
MarkupSafe==1.0
numpy==1.12.0
pandas==0.19.2
python-dateutil==2.6.0
pytz==2016.10
requests==2.13.0
six==1.10.0
webencodings==0.5
Werkzeug==0.12
gunicorn==19.6.0
<file_sep>import sys,requests,json,time,sys,datetime
from bs4 import BeautifulSoup
import numpy as np
import pandas as pd
from flask import Flask, request, abort
from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError
)
from linebot.models import (
    MessageEvent, TextMessage, TextSendMessage,
)
from util.AppUtil import AppUtil

app = Flask(__name__)
appUtil = AppUtil()
STOCK_MIS = appUtil.getStockMIS()
RT_URL = appUtil.getStockRealTimePrice()
stockIDList = appUtil.getStockIDs().split(',')

# get channel_secret and channel_access_token from your environment variable
channel_secret = appUtil.getLineChannelSecret()
channel_access_token = appUtil.getLineChannelAccessToken()
if channel_secret is None:
    print('Specify LINE_CHANNEL_SECRET as environment variable.')
    sys.exit(1)
if channel_access_token is None:
    print('Specify LINE_CHANNEL_ACCESS_TOKEN as environment variable.')
    sys.exit(1)

line_bot_api = LineBotApi(channel_access_token)
handler = WebhookHandler(channel_secret)

@app.route("/callback", methods=['POST'])
def callback():
    print('got callback')
    # get X-Line-Signature header value
    signature = request.headers['X-Line-Signature']

    # get request body as text
    body = request.get_data(as_text=True)
    app.logger.info("Request body: " + body)

    # handle webhook body
    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
        abort(400)

    return 'OK'

@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    defRtnStr = 'Don\'t call me , I will call you.'

    reciveMsg = event.message.text

    print('YYYYYYYYYYYYYYYY')
    print(event.reply_token)
    print(event.message.text)
    print('xxxxxxxxxx')

    matching = [s for s in stockIDList if reciveMsg in s]
    if (len(matching) == 0):
       defRtnStr = 'Don\'t have this stockId.'
    else:
        with requests.session() as req:
            req.get(STOCK_MIS,
                        headers={'Accept-Language': 'zh-TW'})

            timestamp = int(time.time()*1000+1000000)
            print(RT_URL.format(timestamp,matching[0]))
            res = req.get(RT_URL.format(timestamp,matching[0]))
            jsonRtn = res.text.strip()
            d = json.loads(jsonRtn)
            datas = d['msgArray']
            df = pd.DataFrame(columns=['c','n','z','t','tv'])
            for data in datas :
                try:
                    data = dict((key,data[key]) for key in ('c','n','z','t','tv'))
                    df = df.append(data,ignore_index=True)
                except Exception as e:
                    print('something is null.')
            print(df)
            defRtnStr = str(df.loc[0,'c']) + ' ' + str(df.loc[0,'n']) + ' ' + str(df.loc[0,'z']) + ' ' + str(df.loc[0,'t']) + ' ' + str(df.loc[0,'tv'])

    line_bot_api.reply_message(
        event.reply_token,
        TextSendMessage(text=defRtnStr))

@app.route('/')
def index():
    return "
Hello StoMonBot!
"

if __name__ == '__main__':
    app.run(debug=True)

languages: Procfile Text Python

repo_language: Procfile


text:
<repo_name>joql/52-604-api<file_sep>/EasySwooleEvent.php
<?php
/**
 * Created by PhpStorm.
 * User: yf
 * Date: 2018/1/9
 * Time: 下午1:04
 */

namespace EasySwoole;

use App\Process\TimeTask;
use \EasySwoole\Core\AbstractInterface\EventInterface;
use EasySwoole\Core\Component\Logger;
use EasySwoole\Core\Swoole\Process\ProcessManager;
use \EasySwoole\Core\Swoole\ServerManager;
use \EasySwoole\Core\Swoole\EventRegister;
use \EasySwoole\Core\Http\Request;
use \EasySwoole\Core\Http\Response;
use EasySwoole\Core\Component\Pool\PoolManager;
use App\Utility\MysqlPool2;
use EasySwoole\Core\Swoole\Time\Timer;

Class EasySwooleEvent implements EventInterface {

    public static function frameInitialize(): void
    {
        // TODO: Implement frameInitialize() method.
        date_default_timezone_set('Asia/Shanghai');
    }

    public static function mainServerCreate(ServerManager $server,EventRegister $register): void
    {
        // TODO: Implement mainServerCreate() method.
        // 数据库协程连接池
        // @see https://www.easyswoole.com/Manual/2.x/Cn/_book/CoroutinePool/mysql_pool.html?h=pool
        // ------------------------------------------------------------------------------------------
//        if (version_compare(phpversion('swoole'), '2.1.0', '>=')) {
//            PoolManager::getInstance()->registerPool(MysqlPool2::class, 3, 10);
//        }
//        $register->add($register::onWorkerStart, function (\swoole_server $server, $workerId){
//            //为第一个进程添加定时器
//            if($workerId == 0){
//                Timer::loop(1000*10,function (){
//                    Logger::getInstance()->console('timer run');
//                    ProcessManager::getInstance()->writeByProcessName('timeTask', time());
//                });
//            }
//        });

        // 定时任务
        //ProcessManager::getInstance()->addProcess('timeTask', TimeTask::class);
    }

    public static function onRequest(Request $request,Response $response): void
    {
        // TODO: Implement onRequest() method.
    }

    public static function afterAction(Request $request,Response $response): void
    {
        // TODO: Implement afterAction() method.
    }
}<file_sep>/App/Model/Wb.php
<?php
/**
 * Created by PhpStorm.
 * User: Joql
 * Date: 2018/10/24
 * Time: 14:00
 */

namespace App\Model;

class Wb extends Model
{
    protected $table = 'wb';

    public function __construct($db){
        parent::__construct($db);
        $this->table = $this->_prefix.$this->table;
    }

    public function __call($name, $arguments)
    {
        // TODO: Implement __call() method
        $this->$name($this->table, ...$arguments);
    }

}<file_sep>/App/Process/TimeTask.php
<?php
/**
 * Created by PhpStorm.
 * User: Joql
 * Date: 2018/10/23
 * Time: 15:51
 */
namespace App\Process;

use App\Model\Income;
use App\Model\UserSpacePerson;
use App\Model\WechatUser;
use App\Model\WechatUserSpace;
use EasySwoole\Config;
use EasySwoole\Core\Component\Pool\PoolManager;
use EasySwoole\Core\Swoole\Process\AbstractProcess;
use Swoole\Process;

class TimeTask extends AbstractProcess
{
    protected $db_pool;  //读写库连接池
    protected $db_slave_pool;  //读库连接池
    protected $_db;
    protected $_db_use = 0;  // 0 未使用  1：读写库使用中  2： 读库使用中
    protected $redis_pool;
    protected $_redis;
    protected $_redis_use = 0;

    public function run(Process $process)
    {
        // TODO: Implement run() method.

        $this->init();
        $this->addTick(1000*10,function (){
            var_dump('this is '.$this->getProcessName().' process tick time:'.time());
        });
    }
    public function onShutDown()
    {
        // TODO: Implement onShutDown() method.

        $this->db_pool->freeObj($this->_db);
        $this->redis_pool->freeObj($this->_redis);
    }
    public function onReceive(string $str, ...$args)
    {
        // TODO: Implement onReceive() method.
        var_dump('process rec'.$str);
    }

    /**
     * use for:init
     * auth: Joql
     * date:2018-10-23 16:11
     */
    public function init(){
        $this->db_pool = PoolManager::getInstance()->getPool('App\Utility\MysqlPool2');
        $this->redis_pool = PoolManager::getInstance()->getPool('App\Utility\RedisLssPool');
        $this->_db = $this->db_pool->getObj();
        $this->_redis = $this->redis_pool->getObj();
    }

    public function updateRankList(){
        $model_usp = new UserSpacePerson($this->_db);
        foreach ($model_usp->getMore([], 'id') as $v){
            $model_i = new Income($this->_db);
            $reward_rank_list = $model_i->getRandList($v['id']);
            foreach($reward_rank_list as $key => $value){
                $reward_rank_list[$key]['reward_money_sum'] = floor($value['reward_money_sum'] * 100) / 100;
                if($key == 0){
                    $reward_rank_list[$key]['rank'] = Config::getInstance()->getConf('WEBCONFIG.source_domain').'/Public/Home/Images/Rank/gold.png';
                }elseif($key == 1){
                    $reward_rank_list[$key]['rank'] = Config::getInstance()->getConf('WEBCONFIG.source_domain').'/Public/Home/Images/Rank/silver.png';
                }elseif($key == 2){
                    $reward_rank_list[$key]['rank'] = Config::getInstance()->getConf('WEBCONFIG.source_domain').'/Public/Home/Images/Rank/bronze.png';
                }else{
                    $reward_rank_list[$key]['rank'] = $key+1;
                }

                if(mb_strlen($value['from_client_name'],'utf-8') > 5){
                    $reward_rank_list[$key]['from_client_name'] = mb_substr($value['from_client_name'],0,3,'utf-8').'…';
                }
            }
            $model_wu = new WechatUser($this->_db);
            $model_wus = new WechatUserSpace($this->_db);
            $invite_rank_list = $model_wu->getRankList($v['id']);
            foreach($invite_rank_list as $key => $value){
                if($key == 0){
                    $invite_rank_list[$key]['rank'] = Config::getInstance()->getConf('WEBCONFIG.source_domain').'/Public/Home/Images/Rank/gold.png';
                }elseif($key == 1){
                    $invite_rank_list[$key]['rank'] = Config::getInstance()->getConf('WEBCONFIG.source_domain').'/Public/Home/Images/Rank/silver.png';
                }elseif($key == 2){
                    $invite_rank_list[$key]['rank'] = Config::getInstance()->getConf('WEBCONFIG.source_domain').'/Public/Home/Images/Rank/bronze.png';
                }else{
                    $invite_rank_list[$key]['rank'] = $key+1;
                }
                $row = $model_wus->get(array(
                    'openid'=>$value['inviter_openid']
                ), 'photo,name');
                if(empty($row)){
                    continue;
                }
                $invite_rank_list[$key]['client_photo'] = $row['photo'];
                if(mb_strlen($row['name'],'utf-8') > 5){
                    $invite_rank_list[$key]['from_client_name'] = mb_substr($row['name'],0,3,'utf-8').'…';
                }else{
                    $invite_rank_list[$key]['from_client_name'] = $row['name'];
                }
                $invite_rank_list[$key]['invite_count'] = $value['count(*)'];
            }

            //存入redis
            $data = serialize([
                'reward_rank' => $reward_rank_list,
                'invite_rank' => $invite_rank_list,
            ]);
            $this->_redis->exec('hset','');
        }
    }

}<file_sep>/App/HttpController/Base.php
<?php
/**
 * Created by PhpStorm.
 * User: Joql
 * Date: 2018/10/12
 * Time: 15:35
 */
namespace App\HttpController;

use EasySwoole\Config;
use EasySwoole\Core\Component\Di;
use EasySwoole\Core\Http\AbstractInterface\Controller;
use EasySwoole\Core\Component\Pool\PoolManager;
use EasySwoole\Core\Http\Response;

class Base extends Controller
{
    protected $db_pool;  //读写库连接池
    protected $db_slave_pool;  //读库连接池
    protected $_db;
    protected $_db_use = 0;  // 0 未使用  1：读写库使用中  2： 读库使用中
    protected $redis_lss_pool; //流媒体redis池
    protected $redis_wx_pool;  //微信 redis池
    protected $_redis;
    protected $_redis_use = 0; // 0 未使用  1：流媒体使用中  2： 微信使用中

    /**
     * 首页方法
     * @author : evalor <<EMAIL>>
     */
    function index(){
        $this->response()->write('hello world');
        return true;
    }

    protected function init(){
        if($this->request()->getSwooleRequest()->server['request_method'] != 'POST'){
            $this->writeJsonSelf(['code'=>0,'message'=>'非法请求']);
            return false;
        }
        return true;
    }
    /**
     * use for:请求前
     * auth: Joql
     * @param $action
     * @return bool|null
     * date:2018-10-15 14:03
     */
    function onRequest($action): ?bool
    {
        parent::onRequest($action); // TODO: Change the autogenerated stub

        $this->db_pool = PoolManager::getInstance()->getPool('App\Utility\MysqlPool2');
        //$this->db_slave_pool = PoolManager::getInstance()->getPool('App\Utility\MysqlSlavePool');
        //$this->redis_lss_pool = PoolManager::getInstance()->getPool('App\Utility\RedisLssPool');
        //$this->redis_wx_pool = PoolManager::getInstance()->getPool('App\Utility\RedisPool');

        //$this->initDb();
        //$this->initDi();
        return true;
    }

    /**
     * use for:初始化DB连接池
     * auth: Joql
     * @return bool
     * date:2018-10-16 9:40
     */
    function initDb($type = 'master'){
        //
        if(!is_null($this->_db)){
            return $this->_db;
        }
        //使用读写库
        if($type == 'master') {
            $this->_db = $this->db_pool->getObj();
            if(is_null($this->_db)){
                $this->writeJsonSelf([
                    'code' => 0,
                    'message' => '用户太多了，请刷新重试',
                    'data' => 'mysql '.$this->_db
                ]);
                return false;
            }
            $this->_db_use = 1;
            return $this->_db;
        }

        //使用读库
        if($type == 'slave'){
            $this->_db = $this->db_slave_pool->getObj();
            if(is_null($this->_db)){
                $this->writeJsonSelf([
                    'code' => 0,
                    'message' => '用户太多了，请刷新重试',
                    'data' => 'mysql '.$this->_db
                ]);

                return false;
            }
            $this->_db_use = 2;
            return true;
        }

    }

    /**
     * use for:初始化redis连接处
     * auth: Joql
     * @return bool
     * date:2018-10-16 9:40
     */
    function initRedis($type = 'wx'){
        //微信 redis
        if($type == 'wx') {
            $this->_redis = $this->redis_wx_pool->getObj();
            if(is_null($this->_redis)){
                $this->writeJsonSelf([
                    'code' => 0,
                    'message' => '用户太多了，请刷新重试',
                    'data' => 'redis '.$this->_redis,
                ]);
                return false;
            }
            $this->_redis_use = 2;
            return $this->_redis;
        }
        //流媒体 redis
        if($type == 'lss') {
            $this->_redis = $this->redis_lss_pool->getObj();
            if(is_null($this->_redis)){
                $this->writeJsonSelf([
                    'code' => 0,
                    'message' => '用户太多了，请刷新重试',
                    'data' => 'redis '.$this->_redis,
                ]);
                return false;
            }
            $this->_redis_use = 1;
            return $this->_redis;
        }
    }

    /**
     * use for:依赖处理
     * auth: Joql
     * @param string $act
     * date:2018-11-01 15:58
     */
    function initDi($act='set'){
        //mysql模型名
        $list = [
            'Chat',
            'Consume',
            'Income',
            'Jwplayer',
            'Menu',
            'Msg',
            'Pay',
            'Recharge',
            'RechargeLimit',
            'Slide',
            'Tag',
            'Transcode',
            'Traffic',
            'User',
            'UserSpace',
            'UserSpacePerson',
            'VodFlag',
            'VodLogCount',
            'WechatUser',
            'WechatUserSpace',
        ];
        $di = Di::getInstance();
        foreach ($list as $v){
            $modal = '\App\Model\\'.$v;
            $act == 'set' ? $di->$act($v, $modal) : $di->$act($v);
        }
    }

    /**
     * use for:请求后
     * auth: Joql
     * @param $actionName
     * date:2018-10-15 14:03
     */
    function afterAction($actionName): void
    {
        parent::afterAction($actionName); // TODO: Change the autogenerated stub
        //释放读写库连接
        if($this->_db_use == 1){
            $this->db_pool->freeObj($this->_db);
        }
        //释放读库连接
        if($this->_db_use == 2){
            $this->db_slave_pool->freeObj($this->_db);
        }
        //释放流媒体redis连接
        if($this->_redis_use == 1){
            $this->redis_lss_pool->freeObj($this->_redis);
        }
        //释放微信redis连接
        if($this->_redis_use == 2){
            $this->redis_wx_pool->freeObj($this->_redis);
        }
        $this->initDi('delete');
    }

//****************************
//********** 共用方法 *********
//****************************

    /**
     * use for: old返回方式
     * auth: Joql
     * @param array $data
     * @return bool
     * date:2018-10-12 15:39
     */
    protected function writeJsonSelf($data){
        if(!$this->response()->isEndResponse()){
            $this->response()->write($data);
            $this->response()->withHeader('Content-type','application/json;charset=utf-8');
            $this->response()->withStatus(200);
            $this->response()->end();
            return true;
        }else{
            trigger_error("response has end");
            return false;
        }
    }

    /**
     * use for:格式化 hgetall 返回的单列数组
     * auth: Joql
     * @param array $arr
     * @return mixed
     * date:2018-10-12 15:40
     */
    protected function formatArray(array $arr){
        $data = [];
        foreach ($arr as $k => &$v){
            if($k % 2 == 0){
                $key = $v;
            }else{
                $data[$key] = $v;
            }
        }
        return $data;
    }

    /**
     * use for:跨域头部
     * auth: Joql
     * date:2018-10-26 9:10
     */
    protected function corsHeader(){
        if ($this->request()->getMethod() === 'OPTIONS') {
            $this->response()->withHeader('Access-Control-Allow-Origin', '*');
            $this->response()->withHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
            $this->response()->withHeader('Access-Control-Allow-Credentials', 'true');
            $this->response()->withHeader('Access-Control-Allow-Headers', 'Origin, Authorization, Accept, auth');
            $this->response()->withHeader('Access-Control-Allow-Credentials', 'true');
        }elseif ($this->request()->getMethod() === 'POST' || $this->request()->getMethod() === 'GET'  ){
            $this->response()->withHeader('Access-Control-Allow-Origin', '*');
            $this->response()->withHeader('Access-Control-Allow-Headers', 'Origin, Authorization, Accept, auth');
        }
    }

    /**
     * use for:xml转array
     * auth: Joql
     * @param $xml
     * @return mixed
     * date:2018-11-13 14:59
     */
    protected function xml2Array($xml)
    {
        $xml = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        return json_decode(json_encode((array)$xml), true);
    }

    /**
     * use for:生成随机数
     * auth: Joql
     * @param $length
     * @return string
     * date:2018-12-03 11:51
     */
    public function GetRandStr($length){
        $str='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $len=strlen($str)-1;
        $randstr='';
        for($i=0;$i<$length;$i++){
            mt_srand();
            $num=mt_rand(0,$len);
            $randstr .= $str[$num];
        }
        return $randstr;
    }
}<file_sep>/vendor/aliyun/AlidnsDomain.php
<?php
/*
 * 加密浏览地址
 * --Made by Luyao
 */

if(!defined('ALIDNS_DOMAIN_ROOT')){
    define('ALIDNS_DOMAIN_ROOT',dirname(__FILE__).'/');
    require_once(ALIDNS_DOMAIN_ROOT.'aliyun-php-sdk-core/Config.php');
}
use Alidns\Request\V20150109 as Domain;
class AlidnsDomain {
	// 添加解析记录
	public function domainParsing($access_key_id, $access_key_secret, $args){
	   $iClientProfile = DefaultProfile::getProfile("cn-hangzhou",$access_key_id,$access_key_secret);
	   $client = new DefaultAcsClient($iClientProfile);

	   $request = new Domain\AddDomainRecordRequest();
	   $request->setMethod("GET");
	   $request->setAcceptFormat("JSON");
	   $request->setDomainName($args['DomainName']);
	   $request->setRR($args['RR']);
	   $request->setType($args['Type']);
	   $request->setValue($args['Value']);

	   $response = $client->getAcsResponse($request);
	   if($response->RecordId){
	      return true;
	   }
	}
	// 列出解析记录
	public function parsingList($access_key_id, $access_key_secret, $args){
	   $iClientProfile = DefaultProfile::getProfile("cn-hangzhou",$access_key_id,$access_key_secret);
	   $client = new DefaultAcsClient($iClientProfile);

	   $request = new Domain\DescribeDomainRecordsRequest();
	   $request->setMethod("GET");
	   $request->setAcceptFormat("JSON");
	   $request->setDomainName($args['DomainName']);
	   $request->setRRKeyWord($args['RRKeyWord']);

	   $response = $client->getAcsResponse($request);
	   return $response;
	}
}<file_sep>/start.sh
#!/bin/bash

DIR=$1
changeTime=1

if [ ! -n "$DIR" ] ;then
    echo "you have not choice Application directory !"
    exit
fi

php easyswoole stop
php easyswoole start --d

fswatch -r $DIR | while read file
do
   current=`date "+%Y-%m-%d %H:%M:%S"`
   nowTimeStamp=`date -d "$current" +%s`
   val=`expr $nowTimeStamp - $changeTime`
   if [ 6 -lt $val ]; then
       changeTime=$nowTimeStamp
       echo "${file} was modify" >> ./Temp/reload.log 2>&1
       php easyswoole restart
   fi
done
<file_sep>/App/HttpController/Index.php
<?php
/**
 * Created by PhpStorm.
 * User: Joql
 * Date: 2018/10/18
 * Time: 18:01
                 */

namespace App\HttpController;

use App\Model\Data;

use App\Model\Wb;
use EasySwoole\Config;
use think\Validate;

class Index extends Base
{

    private $redis;
    function onRequest($action): ?bool
    {
        parent::onRequest($action); // TODO: Change the autogenerated stub
        $conf = Config::getInstance()->getConf('REDIS');

        $this->redis = new \Redis();
        $redis_result= $this->redis->connect($conf['host'],$conf['port'],3);
        $this->redis->auth($conf['auth']);
        $this->redis->setOption(\Redis::OPT_PREFIX,'soft_');
        if($redis_result!=true){
            $this->writeJsonSelf('cc');
            return false;
        }
        return true;
    }

    public function index(){
        \EasySwoole\Core\Component\Logger::getInstance()->log('test api '.$this->request()->getRequestParam('type').'  '.$this->request()->getRequestParam('result') , 'testapi');
        return true;
    }

    /**
     * use for:
     * param:
     * auth: Joql
     * @return bool|void
     * date:2018-10-19 14:07
     */
    public function getData(){

        $validate = Validate::make([
            'id' => 'require',
            'name' => 'require',
        ]);

        if(!$validate->check($this->request()->getRequestParam())){
            $this->writeJsonSelf('cc');
            return false;
        }
        $id = $this->request()->getRequestParam('id');
        $name = $this->request()->getRequestParam('name');
        if(!in_array($name,array(
            'nr',
            'time',
            'qq',
        ))){
            $this->writeJsonSelf('cc');
            return false;
        }
        $r = $this->redis->get('data_'.$id.'-'.$name);
        if(!empty($r)){
            $this->writeJsonSelf($r);
            return true;

        }

        //mysql池获取对象
        if(!$this->initDb()){
            $this->writeJsonSelf('cc');
            return;
        }

        $r = $this->_db->where('id',$id)->getValue('soft_data',$name);

        if(empty($r)){
            $this->writeJsonSelf('cc');
        }else{
            $this->redis->set('data_'.$id.'-'.$name,$r,5);
            $this->writeJsonSelf($r);
        }
        return;
    }

    public function getWb(){

        $validate = Validate::make([
            'id' => 'require',
            'name' => 'require',
        ]);

        if(!$validate->check($this->request()->getRequestParam())){
            $this->writeJsonSelf('cc');
            return false;
        }
        $id = $this->request()->getRequestParam('id');
        $name = $this->request()->getRequestParam('name');
        if(!in_array($name,array(
            'name',
            'pwd',
        ))){
            $this->writeJsonSelf('cc');
            return false;
        }

        $r = $this->redis->get('wb'.$id.'-'.$name);
        if(!empty($r)){
            $this->writeJsonSelf($r);
            return true;

        }
        //mysql池获取对象
        if(!$this->initDb()){
            return;
        }
        $r = $this->_db->where('id',$id)->getValue('soft_wb',$name);
        if(empty($r)){
            $this->redis->set('wb_'.$id.'-'.$name,$r,5);
            $this->writeJsonSelf('cc');
        }else{
            $this->writeJsonSelf($r);
        }
        return;
    }

    public function state(){

        $r = $this->redis->get('state');
        if(empty($r)){
            $this->writeJsonSelf(-1);
            return;
        }else{
            $this->redis->set('state', 0);
            $this->writeJsonSelf($r);
            return;
        }
    }
}<file_sep>/App/Model/Model.php
<?php
/**
 * Created by PhpStorm.
 * User: Joql
 * Date: 2018/10/12
 * Time: 17:17
 */

namespace App\Model;

use AlidnsDomain;
use EasySwoole\Core\Component\Logger;

class Model
{
    protected $_db;
    protected $_prefix = 'soft_';

    protected function __construct($db)
    {
        $this->_db = $db;
    }

    protected function insert($table, $data){
        return $this->_db
            ->insert($table, $data);
    }

    protected function get($table, $where = [], $coulums ='*', $order =[]){
        foreach ($where as $k=>$v){
            if(is_array($v) && ($key = key($v)) == "val"){
                $this->_db->where($k, $v['val'], $v['cond']);
            }else{
                $this->_db->where($k, $v);
            }
        }
        if($order){
            $this->_db->orderBy($order[0], $order[1]);
        }
        return $this->_db->getOne($table, $coulums);
    }

    protected function getMore($table, $where = [], $coulums ='*', $order =[]){
        foreach ($where as $k=>$v){
            if(is_array($v) && ($key = key($v)) == "val"){
                $this->_db->where($k, $v['val'], $v['cond']);
            }else{
                $this->_db->where($k, $v);
            }
        }
        if($order){
            $this->_db->orderBy($order[0], $order[1]);
        }
        return $this->_db->get($table, null, $coulums);
    }

    /** 获取字段值
     * use for:
     * auth: Joql
     * @param $table
     * @param array $where
     * @param string $coulums
     * @param array $order
     * @return mixed
     * date:2018-10-25 10:19
     */
    protected function getVal($table, $where = [], $coulums ='*', $order =[]){
        foreach ($where as $k=>$v){
            if(is_array($v) && ($key = key($v)) == "val"){
                $this->_db->where($k, $v['val'], $v['cond']);
            }else{
                $this->_db->where($k, $v);
            }
        }
        if($order){
            $this->_db->orderBy($order[0], $order[1]);
        }
        return $this->_db->getValue($table, $coulums);
    }

    /**
     * use for:获取一列
     * auth: Joql
     * @param $table
     * @param array $where
     * @param string $coulums
     * @param array $order
     * @return mixed
     * date:2018-10-25 10:33
     */
    protected function getColumn($table, $where = [], $coulums ='*', $order =[]){
        foreach ($where as $k=>$v){
            if(is_array($v) && ($key = key($v)) == "val"){
                $this->_db->where($k, $v['val'], $v['cond']);
            }else{
                $this->_db->where($k, $v);
            }
        }
        if($order){
            $this->_db->orderBy($order[0], $order[1]);
        }
        return $this->_db->getValue($table, $coulums, null);
    }

    /**
     * use for: 字段求和
     * auth: Joql
     * @param $table
     * @param array $where
     * @param string $coulums
     * @return mixed
     * date:2018-10-25 10:43
     */
    protected function getSum($table, $where = [], $coulums ='*'){
        foreach ($where as $k=>$v){
            if(is_array($v) && ($key = key($v)) == "val"){
                $this->_db->where($k, $v['val'], $v['cond']);
            }else{
                $this->_db->where($k, $v);
            }
        }
        return $this->_db->getValue($table, 'sum('.$coulums.')');
    }

    /**
     * use for:更新
     * auth: Joql
     * @param $table
     * @param array $where
     * @param $data
     * @return mixed
     * date:2018-10-25 17:38
     */
    protected function update($table, $where = [], $data, $limit =1){
        foreach ($where as $k=>$v){
            if(is_array($v) && ($key = key($v)) == "val"){
                $this->_db->where($k, $v['val'], $v['cond']);
            }else{
                $this->_db->where($k, $v);
            }
        }
        return $this->_db->update($table, $data, $limit);
    }

    protected function delete($table, $where = [], $num=1){
        foreach ($where as $k=>$v){
            $this->_db->where($k, $v);
        }
        return $this->_db->delete($table, $num);
    }

//****************************
//********  方法库
//****************************

    protected function parsingList($access_key_id, $access_key_secret, $args){
        //vendor("aliyun.AlidnsDomain");//引入类
        require_once __DIR__.'/../../vendor/aliyun/AlidnsDomain.php';
        $alidns_domain_obj = new AlidnsDomain();
        $result = $alidns_domain_obj->parsingList($access_key_id, $access_key_secret, $args);
        return $result;

    }

    /**
     * use for:生成随机字符串
     * auth: Joql
     * @param $number
     * @return string
     * date:2018-10-18 15:46
     */
    protected function strRandom($number){
        $char = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
        $list = explode(",",$char);
        $len = count($list)-1;
        $authnum = "";
        for($i=0;$i<$number;$i++){
            $randnum = rand(0,$len);
            $authnum .= $list[$randnum];
        }
        return $authnum;
    }
}<file_sep>/README.md
# NyApi

#### 项目介绍
诺云api

#### 软件架构
php7 + easyswoole2

#### 安装教程

1. xxxx
2. xxxx
3. xxxx

#### 使用说明

1. xxxx
2. xxxx
3. xxxx

#### 参与贡献

1. Fork 本项目
2. 新建 Feat_xxx 分支
3. 提交代码
4. 新建 Pull Request
<file_sep>/vendor/easyswoole/easyswoole/src/Core/Swoole/Coroutine/Client/Mysql.php
<?php
/**
 * Created by PhpStorm.
 * User: yf
 * Date: 2018/3/9
 * Time: 下午2:32
 */

namespace EasySwoole\Core\Swoole\Coroutine\Client;
use \Swoole\Coroutine\MySQL as CoroutineMySQL;

/*
 * 本类改编自https://github.com/joshcam/PHP-MySQLi-Database-Class
 */
class Mysql
{
    public $returnType = 'array';

    protected $host = null, $username = null, $password = null, $db = null, $port = 3306;

    protected $client = null;
    protected $reConnectTimes = 0;
    protected $autoReConnect = 0;
    protected $isSubQuery = false;
    protected $defConnectionName;
    protected $connectionsSettings = [];
    protected $count;

    private $_where = [];
    private $_tableName;
    private $_query;
    private $_queryOptions = [];
    private $_bindParams = [];
    private $_updateColumns;
    private $_lastInsertId;
    private $_forUpdate;
    private $_lockInShareMode;
    private $_lastQuery;
    private $_having = [];
    private $_mapKey;
    private $_nestJoin;
    private $_orderBy;
    private $_groupBy;
    private $_joinAnd;
    private $_join;
    private $_stmtError;
    private $_stmtErrno;
    private $_tableLockMethod = "READ";
    private $_alias = null;

    public function __construct($host = null, $username = null, $password = <PASSWORD>, $db = null, $port = 3306,int $autoReConnect = 3)
    {
        $isSubQuery = false;
        if (is_array($host)) {
            foreach ($host as $key => $val) {
                $$key = $val;
            }
        }
        $this->host = $host;
        $this->username = $username;
        $this->password = $<PASSWORD>;
        $this->db = $db;
        $this->port = $port;
        $this->autoReConnect = $autoReConnect;

        if ($isSubQuery) {
            $this->isSubQuery = true;
            $this->_alias = $host;
            return;
        }

        $this->client = new CoroutineMySQL();
        $this->connect();
    }

    function connect()
    {
        if(!$this->client->connected){
            $this->client->connect([
                'host' => $this->host,
                'port' => $this->port,
                'user' => $this->username,
                'password' => $this->password,
                'database' => $this->db,
            ]);
            if($this->client->connected){
                $this->reConnectTimes = 0;
            }else{
                $this->reConnectTimes++;
            }
        }
    }

    function disConnect()
    {
        $this->client->close();
    }

    function client():CoroutineMySQL
    {
        return $this->client;
    }

    public function where($whereProp, $whereValue = 'DBNULL', $operator = '=', $cond = 'AND'):Mysql
    {
        if (is_array($whereValue) && ($key = key($whereValue)) != "0") {
            $operator = $key;
            $whereValue = $whereValue[$key];
        }

        if (count($this->_where) == 0) {
            $cond = '';
        }

        $this->_where[] = array($cond, $whereProp, $operator, $whereValue);
        return $this;
    }

    public function having($havingProp, $havingValue = 'DBNULL', $operator = '=', $cond = 'AND')
    {
        // forkaround for an old operation api
        if (is_array($havingValue) && ($key = key($havingValue)) != "0") {
            $operator = $key;
            $havingValue = $havingValue[$key];
        }
        if (count($this->_having) == 0) {
            $cond = '';
        }
        $this->_having[] = array($cond, $havingProp, $operator, $havingValue);
        return $this;
    }

    public function orWhere($whereProp, $whereValue = 'DBNULL', $operator = '='):Mysql
    {
        return $this->where($whereProp, $whereValue, $operator, 'OR');
    }

    public function get($tableName, $numRows = null, $columns = '*')
    {
        $this->_tableName = $tableName;

        if (empty($columns)) {
            $columns = '*';
        }

        $column = is_array($columns) ? implode(', ', $columns) : $columns;

        $this->_query = 'SELECT ' . implode(' ', $this->_queryOptions) . ' ' .
            $column . " FROM " . $this->_tableName;

        $stmt = $this->_buildQuery($numRows);

        if ($this->isSubQuery) {
            return $this;
        }

        $res = $this->exec($stmt);
        $this->_stmtError = $stmt->error;
        $this->_stmtErrno = $stmt->errno;
        $this->reset();
        return $res;
    }

    public function getOne($tableName, $columns = '*')
    {
        $res = $this->get($tableName, 1, $columns);

        if ($res instanceof Mysql) {
            return $res;
        } elseif (is_array($res) && isset($res[0])) {
            return $res[0];
        } elseif ($res) {
            return $res;
        }

        return null;
    }

    public function arrayBuilder()
    {
        $this->returnType = 'array';
        return $this;
    }
    public function getValue($tableName, $column, $limit = 1)
    {
        $res = $this->ArrayBuilder()->get($tableName, $limit, "{$column} AS retval");
        if (!$res) {
            return null;
        }
        if ($limit == 1) {
            if (isset($res[0]["retval"])) {
                return $res[0]["retval"];
            }
            return null;
        }

        $newRes = Array();
        for ($i = 0; $i < count($res); $i++) {
            $newRes[] = $res[$i]['retval'];
        }
        return $newRes;
    }

    public function insert($tableName, $insertData)
    {
        return $this->_buildInsert($tableName, $insertData, 'INSERT');
    }

    public function delete($tableName, $numRows = null)
    {
        if ($this->isSubQuery) {
            return;
        }

        $table =  $tableName;

        if (count($this->_join)) {
            $this->_query = "DELETE " . preg_replace('/.* (.*)/', '$1', $table) . " FROM " . $table;
        } else {
            $this->_query = "DELETE FROM " . $table;
        }

        $stmt = $this->_buildQuery($numRows);
        $this->exec($stmt);
        $this->_stmtError = $stmt->error;
        $this->_stmtErrno = $stmt->errno;
        $this->reset();

        return ($stmt->affected_rows > -1);	//	affected_rows returns 0 if nothing matched where statement, or required updating, -1 if error
    }

    public function update($tableName, $tableData, $numRows = null)
    {
        if ($this->isSubQuery) {
            return;
        }

        $this->_query = "UPDATE " . $tableName;

        $stmt = $this->_buildQuery($numRows, $tableData);
        $status = $this->exec($stmt);
        $this->reset();
        $this->_stmtError = $stmt->error;
        $this->_stmtErrno = $stmt->errno;
        $this->count = $stmt->affected_rows;

        return $status;
    }

    public function tableExists($tables)
    {
        $tables = !is_array($tables) ? Array($tables) : $tables;
        $count = count($tables);
        if ($count == 0) {
            return false;
        }

        foreach ($tables as $i => $value)
            $tables[$i] =  $value;
        $this->where('table_schema', $this->db);
        $this->where('table_name', $tables, 'in');
        $ret = $this->get('information_schema.tables', $count);
        if(is_array($ret) && $count == count($ret)){
            return true;
        }else{
            return false;
        }
    }

    public function inc($num = 1)
    {
        if (!is_numeric($num)) {
            throw new \Exception('Argument supplied to inc must be a number');
        }
        return array("[I]" => "+" . $num);
    }

    public function dec($num = 1)
    {
        if (!is_numeric($num)) {
            throw new \Exception('Argument supplied to dec must be a number');
        }
        return array("[I]" => "-" . $num);
    }

    public function join($joinTable, $joinCondition, $joinType = '')
    {
        $allowedTypes = array('LEFT', 'RIGHT', 'OUTER', 'INNER', 'LEFT OUTER', 'RIGHT OUTER', 'NATURAL');
        $joinType = strtoupper(trim($joinType));

        if ($joinType && !in_array($joinType, $allowedTypes)) {
            throw new \Exception('Wrong JOIN type: ' . $joinType);
        }

        $this->_join[] = Array($joinType, $joinTable, $joinCondition);

        return $this;
    }

    public function rawQuery($query, array $bindParams = [])
    {
        $this->_bindParams = $bindParams;
        $this->_query = $query;
        $stmt = $this->_prepareQuery();
        $res = $this->exec($stmt);
        $this->count = $stmt->affected_rows;
        $this->_stmtError = $stmt->error;
        $this->_stmtErrno = $stmt->errno;
        $this->_lastQuery = $this->replacePlaceHolders($this->_query, $bindParams);
        $this->reset();
        return $res;
    }

    protected function _buildQuery($numRows = null, $tableData = null)
    {
        $this->_buildJoin();
        $this->_buildInsertQuery($tableData);
        $this->_buildCondition('WHERE', $this->_where);
        $this->_buildGroupBy();
        $this->_buildCondition('HAVING', $this->_having);
        $this->_buildOrderBy();
        $this->_buildLimit($numRows);
        $this->_buildOnDuplicate($tableData);

        if ($this->_forUpdate) {
            $this->_query .= ' FOR UPDATE';
        }
        if ($this->_lockInShareMode) {
            $this->_query .= ' LOCK IN SHARE MODE';
        }

        $this->_lastQuery = $this->replacePlaceHolders($this->_query, $this->_bindParams);

        if ($this->isSubQuery) {
            return;
        }

        // Prepare query
        $stmt = $this->_prepareQuery();
        return $stmt;
    }

    protected function exec($stmt)
    {
        if(!$this->client->connected && $this->reConnectTimes === 0){
            $this->connect();
            return $this->exec($stmt);
        }else if($this->client->connected){
            if (!empty($this->_bindParams)) {
                $data = $this->_bindParams;
            }else{
                $data = [];
            }
            return $stmt->execute($data);
        }else{
            return null;
        }
    }

    protected function _buildJoin () {
        if (empty ($this->_join))
            return;

        foreach ($this->_join as $data) {
            list ($joinType,  $joinTable, $joinCondition) = $data;

            if (is_object ($joinTable))
                $joinStr = $this->_buildPair ("", $joinTable);
            else
                $joinStr = $joinTable;

            $this->_query .= " " . $joinType. " JOIN " . $joinStr .
                (false !== stripos($joinCondition, 'using') ? " " : " on ")
                . $joinCondition;

            // Add join and query
            if (!empty($this->_joinAnd) && isset($this->_joinAnd[$joinStr])) {
                foreach($this->_joinAnd[$joinStr] as $join_and_cond) {
                    list ($concat, $varName, $operator, $val) = $join_and_cond;
                    $this->_query .= " " . $concat ." " . $varName;
                    $this->conditionToSql($operator, $val);
                }
            }
        }
    }

    protected function _buildPair($operator,$value)
    {
        if (!is_object($value)) {
            $this->_bindParam($value);
            return ' ' . $operator . ' ? ';
        }

        $subQuery = $value->getSubQuery();
        $this->_bindParams($subQuery['params']);

        return " " . $operator . " (" . $subQuery['query'] . ") " . $subQuery['alias'];
    }

    protected function _bindParam($value)
    {
        array_push($this->_bindParams, $value);
    }

    protected function _bindParams($values)
    {
        foreach ($values as $value) {
            $this->_bindParam($value);
        }
    }

    protected function _determineType($item)
    {
        switch (gettype($item)) {
            case 'NULL':
            case 'string':
                return 's';
                break;

            case 'boolean':
            case 'integer':
                return 'i';
                break;

            case 'blob':
                return 'b';
                break;

            case 'double':
                return 'd';
                break;
        }
        return '';
    }

    protected function conditionToSql($operator, $val) {
        switch (strtolower ($operator)) {
            case 'not in':
            case 'in':
                $comparison = ' ' . $operator. ' (';
                if (is_object ($val)) {
                    $comparison .= $this->_buildPair ("", $val);
                } else {
                    foreach ($val as $v) {
                        $comparison .= ' ?,';
                        $this->_bindParam ($v);
                    }
                }
                $this->_query .= rtrim($comparison, ',').' ) ';
                break;
            case 'not between':
            case 'between':
                $this->_query .= " $operator ? AND ? ";
                $this->_bindParams ($val);
                break;
            case 'not exists':
            case 'exists':
                $this->_query.= $operator . $this->_buildPair ("", $val);
                break;
            default:
                if (is_array ($val))
                    $this->_bindParams ($val);
                else if ($val === null)
                    $this->_query .= $operator . " NULL";
                else if ($val != 'DBNULL' || $val == '0')
                    $this->_query .= $this->_buildPair ($operator, $val);
        }
    }

    public function getSubQuery()
    {
        if (!$this->isSubQuery) {
            return null;
        }

//        array_shift($this->_bindParams);
        $val = Array('query' => $this->_query,
            'params' => $this->_bindParams,
            'alias' => $this->_alias
        );
        $this->reset();
        return $val;
    }

    public static function subQuery($subQueryAlias = "")
    {
        return new self(array('host' => $subQueryAlias, 'isSubQuery' => true));
    }

    protected function _buildInsertQuery($tableData)
    {
        if (!is_array($tableData)) {
            return;
        }

        $isInsert = preg_match('/^[INSERT|REPLACE]/', $this->_query);
        $dataColumns = array_keys($tableData);
        if ($isInsert) {
            if (isset ($dataColumns[0]))
                $this->_query .= ' (`' . implode($dataColumns, '`, `') . '`) ';
            $this->_query .= ' VALUES (';
        } else {
            $this->_query .= " SET ";
        }

        $this->_buildDataPairs($tableData, $dataColumns, $isInsert);

        if ($isInsert) {
            $this->_query .= ')';
        }
    }

    public function _buildDataPairs($tableData, $tableColumns, $isInsert)
    {
        foreach ($tableColumns as $column) {
            $value = $tableData[$column];

            if (!$isInsert) {
                if(strpos($column,'.')===false) {
                    $this->_query .= "`" . $column . "` = ";
                } else {
                    $this->_query .= str_replace('.','.`',$column) . "` = ";
                }
            }

            // Subquery value
            if ($value instanceof Mysql) {
                $this->_query .= $this->_buildPair("", $value) . ", ";
                continue;
            }

            // Simple value
            if (!is_array($value)) {
                $this->_bindParam($value);
                $this->_query .= '?, ';
                continue;
            }

            // Function value
            $key = key($value);
            $val = $value[$key];
            switch ($key) {
                case '[I]':
                    $this->_query .= $column . $val . ", ";
                    break;
                case '[F]':
                    $this->_query .= $val[0] . ", ";
                    if (!empty($val[1])) {
                        $this->_bindParams($val[1]);
                    }
                    break;
                case '[N]':
                    if ($val == null) {
                        $this->_query .= "!" . $column . ", ";
                    } else {
                        $this->_query .= "!" . $val . ", ";
                    }
                    break;
                default:
                    throw new Exception("Wrong operation");
            }
        }
        $this->_query = rtrim($this->_query, ', ');
    }
    protected function _buildCondition($operator, &$conditions)
    {
        if (empty($conditions)) {
            return;
        }

        $this->_query .= ' ' . $operator;

        foreach ($conditions as $cond) {
            list ($concat, $varName, $operator, $val) = $cond;
            $this->_query .= " " . $concat . " " . $varName;

            switch (strtolower($operator)) {
                case 'not in':
                case 'in':
                    $comparison = ' ' . $operator . ' (';
                    if (is_object($val)) {
                        $comparison .= $this->_buildPair("", $val);
                    } else {
                        foreach ($val as $v) {
                            $comparison .= ' ?,';
                            $this->_bindParam($v);
                        }
                    }
                    $this->_query .= rtrim($comparison, ',') . ' ) ';
                    break;
                case 'not between':
                case 'between':
                    $this->_query .= " $operator ? AND ? ";
                    $this->_bindParams($val);
                    break;
                case 'not exists':
                case 'exists':
                    $this->_query.= $operator . $this->_buildPair("", $val);
                    break;
                default:
                    if (is_array($val)) {
                        $this->_bindParams($val);
                    } elseif ($val === null) {
                        $this->_query .= ' ' . $operator . " NULL";
                    } elseif ($val != 'DBNULL' || $val == '0') {
                        $this->_query .= $this->_buildPair($operator, $val);
                    }
            }
        }
    }

    protected function _buildGroupBy()
    {
        if (empty($this->_groupBy)) {
            return;
        }

        $this->_query .= " GROUP BY ";

        foreach ($this->_groupBy as $key => $value) {
            $this->_query .= $value . ", ";
        }

        $this->_query = rtrim($this->_query, ', ') . " ";
    }

    protected function _buildOrderBy()
    {
        if (empty($this->_orderBy)) {
            return;
        }

        $this->_query .= " ORDER BY ";
        foreach ($this->_orderBy as $prop => $value) {
            if (strtolower(str_replace(" ", "", $prop)) == 'rand()') {
                $this->_query .= "rand(), ";
            } else {
                $this->_query .= $prop . " " . $value . ", ";
            }
        }

        $this->_query = rtrim($this->_query, ', ') . " ";
    }

    protected function _buildLimit($numRows)
    {
        if (!isset($numRows)) {
            return;
        }

        if (is_array($numRows)) {
            $this->_query .= ' LIMIT ' . (int) $numRows[0] . ', ' . (int) $numRows[1];
        } else {
            $this->_query .= ' LIMIT ' . (int) $numRows;
        }
    }

    protected function _buildOnDuplicate($tableData)
    {
        if (is_array($this->_updateColumns) && !empty($this->_updateColumns)) {
            $this->_query .= " ON DUPLICATE KEY UPDATE ";
            if ($this->_lastInsertId) {
                $this->_query .= $this->_lastInsertId . "=LAST_INSERT_ID (" . $this->_lastInsertId . "), ";
            }

            foreach ($this->_updateColumns as $key => $val) {
                // skip all params without a value
                if (is_numeric($key)) {
                    $this->_updateColumns[$val] = '';
                    unset($this->_updateColumns[$key]);
                } else {
                    $tableData[$key] = $val;
                }
            }
            $this->_buildDataPairs($tableData, array_keys($this->_updateColumns), false);
        }
    }

    protected function replacePlaceHolders($str, $vals)
    {
        $i = 0;
        $newStr = "";

        if (empty($vals)) {
            return $str;
        }

        while ($pos = strpos($str, "?")) {
            $val = $vals[$i++];
            if (is_object($val)) {
                $val = '[object]';
            }
            if ($val === null) {
                $val = 'NULL';
            }
            $newStr .= substr($str, 0, $pos) . "'" . $val . "'";
            $str = substr($str, $pos + 1);
        }
        $newStr .= $str;
        return $newStr;
    }

    protected function _prepareQuery()
    {
        if(!$this->client->connected && $this->reConnectTimes === 0){
            $this->connect();
            return $this->_prepareQuery();
        }else if($this->client->connected){
            $res =  $this->client()->prepare($this->_query);
            if($res){
                return $res;
            }
        }
        $error = $this->client()->error;
        $query = $this->_query;
        $errno = $this->client()->errno;
        $this->reset();
        throw new \Exception(sprintf('%s query: %s', $error, $query), $errno);
    }

    protected function reset()
    {
        $this->_where = array();
        $this->_having = array();
        $this->_join = array();
        $this->_joinAnd = array();
        $this->_orderBy = array();
        $this->_groupBy = array();
        $this->_bindParams = array();
        $this->_query = null;
        $this->_queryOptions = array();
        $this->_nestJoin = false;
        $this->_forUpdate = false;
        $this->_lockInShareMode = false;
        $this->_tableName = '';
        $this->_lastInsertId = null;
        $this->_updateColumns = null;
        $this->_mapKey = null;
        $this->defConnectionName = 'default';
        $this->reConnectTimes = 0;
        $this->_alias = null;
        return $this;
    }

    protected function refValues(array &$arr)
    {
        if (strnatcmp(phpversion(), '5.3') >= 0) {
            $refs = array();
            foreach ($arr as $key => $value) {
                $refs[$key] = & $arr[$key];
            }
            return $refs;
        }
        return $arr;
    }

    private function _buildInsert($tableName, $insertData, $operation)
    {
        if ($this->isSubQuery) {
            return;
        }

        $this->_query = $operation . " " . implode(' ', $this->_queryOptions) . " INTO " . $tableName;
        $stmt = $this->_buildQuery(null, $insertData);
        $status = $this->exec($stmt);
        $this->_stmtError = $stmt->error;
        $this->_stmtErrno = $stmt->errno;
        $haveOnDuplicate = !empty ($this->_updateColumns);
        $this->reset();
        $this->count = $stmt->affected_rows;

        if ($stmt->affected_rows < 1) {
            // in case of onDuplicate() usage, if no rows were inserted
            if ($status && $haveOnDuplicate) {
                return true;
            }
            return false;
        }

        if ($stmt->insert_id > 0) {
            return $stmt->insert_id;
        }

        return true;
    }

    public function getInsertId()
    {
        return $this->client()->insert_id;
    }

    public function getLastQuery()
    {
        return $this->_lastQuery;
    }

    /**
     * Method returns mysql error
     *
     * @return string
     */
    public function getLastError()
    {
        return trim($this->_stmtError . " " . $this->client->error);
    }

    public function getLastErrno () {
        return $this->_stmtErrno;
    }

    public function orderBy($orderByField, $orderbyDirection = "DESC", $customFieldsOrRegExp = null)
    {
        $allowedDirection = Array("ASC", "DESC");
        $orderbyDirection = strtoupper(trim($orderbyDirection));
        $orderByField = preg_replace("/[^ -a-z0-9\.\(\),_`\*\'\"]+/i", '', $orderByField);

        $orderByField = preg_replace('/(\`)([`a-zA-Z0-9_]*\.)/', '\1' . '\2', $orderByField);

        if (empty($orderbyDirection) || !in_array($orderbyDirection, $allowedDirection)) {
            throw new \Exception('Wrong order direction: ' . $orderbyDirection);
        }

        if (is_array($customFieldsOrRegExp)) {
            foreach ($customFieldsOrRegExp as $key => $value) {
                $customFieldsOrRegExp[$key] = preg_replace("/[^-a-z0-9\.\(\),_` ]+/i", '', $value);
            }
            $orderByField = 'FIELD (' . $orderByField . ', "' . implode('","', $customFieldsOrRegExp) . '")';
        }elseif(is_string($customFieldsOrRegExp)){
            $orderByField = $orderByField . " REGEXP '" . $customFieldsOrRegExp . "'";
        }elseif($customFieldsOrRegExp !== null){
            throw new \Exception('Wrong custom field or Regular Expression: ' . $customFieldsOrRegExp);
        }

        $this->_orderBy[$orderByField] = $orderbyDirection;
        return $this;
    }

    public function groupBy($groupByField)
    {
        $groupByField = preg_replace("/[^-a-z0-9\.\(\),_\* <>=!]+/i", '', $groupByField);

        $this->_groupBy[] = $groupByField;
        return $this;
    }
    //swoole mysql client暂时不支持锁表
//    public function lock($table)
//    {
//        // Main Query
//        $this->_query = "LOCK TABLES";
//
//        // Is the table an array?
//        if(gettype($table) == "array") {
//            // Loop trough it and attach it to the query
//            foreach($table as $key => $value) {
//                if(gettype($value) == "string") {
//                    if($key > 0) {
//                        $this->_query .= ",";
//                    }
//                    $this->_query .= " ".$value." ".$this->_tableLockMethod;
//                }
//            }
//        }
//        else{
//            // Build the query
//            $this->_query = "LOCK TABLES ".$table." ".$this->_tableLockMethod;
//        }
//
//        // Exceute the query unprepared because LOCK only works with unprepared statements.
//        $result = $this->rawQuery($this->_query);
//        $errno  = $this->client()->errno;
//
//        // Reset the query
//        $this->reset();
//
//        // Are there rows modified?
//        if($result) {
//            return true;
//        }
//        // Something went wrong
//        else {
//            throw new \Exception("Locking of table ".$table." failed", $errno);
//        }
//
//        // Return the success value
//        return false;
//    }
//
//
//    public function unlock()
//    {
//        // Build the query
//        $this->_query = "UNLOCK TABLES";
//
//        // Exceute the query unprepared because UNLOCK and LOCK only works with unprepared statements.
//        $result = $this->rawQuery($this->_query);
//        $errno  = $this->client()->errno;
//
//        // Reset the query
//        $this->reset();
//
//        // Are there rows modified?
//        if($result) {
//            // return self
//            return $this;
//        }
//        // Something went wrong
//        else {
//            throw new \Exception("Unlocking of tables failed", $errno);
//        }
//
//        return $this;
//    }

}

languages: Markdown Shell PHP

repo_language: Markdown


text:
<file_sep>//---------------------------------------  3  --------------------------------------------------------------
// Implementar una función que ordene los elementos de un arreglo: ascendente. Tamaño del arreglo 1000000.
void crear(int *arreglo){
    default_random_engine engine(static_cast<unsigned int>(time(0)));
    uniform_int_distribution<int> randomInt(1, 9);
    for(int i=0;i<tamanio;i++){
        *(arreglo+i) = randomInt(engine);
    }
}
void mostrar(int *const arreglo){
    for(int i=0;i<tamanio;i++){
        cout<<*(arreglo+i)<<" ";
    }
}
void ordenarNumeros(int *array,int nElementos){
    int aux;
    //Ordenamiento burbuja con punteros
    for(int i=0;i<nElementos;i++){
        for(int j=0;j<nElementos-1;j++){
            if(*(array+j) > *(array+j+1)){
                aux = *(array+j);
                *(array+j) = *(array+j+1);
                *(array+j+1) = aux;
            }
        }
    }
}
void ordenarNumRecursivo(int *arr, int n)
{
    if (n == 1)//Paso Base
        return;

    for (int i=0; i<n-1; i++)
        if (arr[i] > arr[i+1])
            swap(arr[i], arr[i+1]);
    ordenarNumRecursivo(arr, n - 1);
}

int main(){
    int *array = new int[tamanio];
    crear(array);
    cout<<"array sin ordenar: ";
    mostrar(array);
    cout<<endl;
    ordenarNumRecursivo(array,tamanio);
    cout<<"array  ordenado: ";
    mostrar(array);
    delete[] array;
    return 0;
}

<file_sep>//---------------------------------------------  5  -------------------------------------------------------------------------
//5. Implemente una función que reciba dos cadenas a y b; dicha función debe concatenar la cadena a a la cadena b.
//(asuma que la cadena b tiene el tamaño suﬁciente para contener los elementos de a).
void mostrar(char cadena []){
    for (int i = 0; cadena[i] != '\0';i++) {
        cout<<cadena[i]<<" ";
    }
}
int main() {
  char cadena1[100] = "Hola ", cadena2[] = "Mundo";
  int longitud = 0;

  while (cadena1[longitud] != '\0') {//hallamos longitud de cadena1
    ++longitud;
  }

  for (int i = 0; cadena2[i] != '\0'; ++i, ++longitud) { //concatenando desde posicion "longitud"
      cadena1[longitud] = cadena2[i];
  }
  cadena1[longitud] = '\0';//damos fin a la cadena1
  cout<<"Cadena Concatenada: ";
  mostrar(cadena1);
  return 0;
}<file_sep>//----------------------------------------------  4  ----------------------------------------------------------
//4. Implemente una función que reciba una cadena y retorne su tamaño. (Iterativa y recursiva)
int tamanioCadena ( const char cadena[] ) {
    int c = 0 ;
    while ( cadena[c] != '\0' )
        c ++;
    return c ;
}
int tamanioCadenaRecursivo (char* cadena ) {
    if (* cadena == '\0' ) // Condición base
        return 0 ;
    return (1 + tamanioCadenaRecursivo(++cadena) ) ;
}

int main(){
    char cadena[] = {'C','S','d','e','l','a','C','o','m','p','u','t','a','c','i','o','n'};
    cout<<"La longitud de la cadena es: "<<tamanioCadena(cadena)<<endl;

}<file_sep>//----------------------------------------  2  ------------------------------
//Implementar una función que invierta los elementos de un arreglo de enteros (Iterativa y recursiva). Tamaño del arreglo 1000000.

void crear(array<unsigned int,tamanio> &arreglo){
    default_random_engine engine(static_cast<unsigned int>(time(0)));
    uniform_int_distribution<unsigned int> randomInt(1, 9);
    for ( unsigned int& elemento : arreglo) {
        elemento = randomInt(engine);
    }
}
void mostrar(const array<unsigned int,tamanio> arreglo){
    for (unsigned int elemento : arreglo ) {
        cout<<elemento<<" ";
    }
}
void reverso(const array<unsigned int,tamanio> arreglo){
    int i=0;
    cout<<"\nEl reverso del arreglo es:"<<endl;
    for(i=(tamanio-1); i>=0; i--)
        cout<<arreglo[i]<<" ";
    cout<<endl;
}
void reversoRecursivo(array<unsigned int,tamanio> arreglo,int tam){
    if(tam ==0){return;}
    else{
        unsigned int temp;
        unsigned int i= 0;
        temp = arreglo[i];
        arreglo[i] = arreglo[tam-1];
        arreglo[tam -1] = temp;
        reversoRecursivo(arreglo, tam-1);
    }
}

int main(){
    array<unsigned int,tamanio> arreglo{};
    crear(arreglo);
    mostrar(arreglo);
    reverso(arreglo);
    return 0;
}
<file_sep>//----------------------------------------------  6  ------------------------------------------------------------------------
//6. Implemente una función que reciba un arreglo de cadenas y su tamaño y ordene lexicográﬁcamente dicho arreglo.
//Tamaño del arreglo 1000000.
#include <iostream>
using namespace std;
void ordenLexicografico(string cadena[]){
    string temp;
    for (int i = 0; i < 9; ++i) {
        for (int j = 0; j < 9 - i; ++j) {
            if (cadena[j] > cadena[j + 1]) {
                temp = cadena[j];
                cadena[j] = cadena[j + 1];
                cadena[j + 1] = temp;
            }
        }
    }
}
void mostrar(string cadena[]){
    for(int i = 0; i < 10; ++i)
    {
        cout << cadena[i]<<" ";
    }
}
int main()
{
    string cadena[10] = {"Hola","Companieros","de","2do","anio"};
    cout << "Cadena sin ordenar:          ";
    mostrar(cadena);
    cout<<endl;
    ordenLexicografico(cadena);
    cout << "En orden lexicografico: ";
    mostrar(cadena);
    return 0;
}


text:
<repo_name>AkulovGennnady/Encryption-and-decryption-text-program<file_sep>/Encryption and decryption text program C++/Unit3.cpp
//---------------------------------------------------------------------------

#pragma hdrstop
#include "Unit3.h"
#include <cstring.h>
#include <string.h>      // AnsiString
#include <SysUtils.hpp>  // AnsiString

#include <math.h>       /* ceil */
#include <time.h>

//---------------------------------------------------------------------------

#pragma package(smart_init)

//0.del_space - удаление пробелов
string del_space(string s){
  char a;
	while((a=s.find(' '))!=string::npos )
		s.erase(a,1);
  return s;
 }

//1.Цезарь
//одинаковый алгоритм для 2 операций, разница в знаке ключа!
//----------------------------------------------------------------------
string Caesar_enc_decr(string s1, int b){
     s1=del_space(s1);//удаление пробелов

	string s2;//зашифрованное сообщение
	for (int i=0;(unsigned)i<s1.length();i++){
                //англ алфавит
		if (((int)(s1[i]) >= 97) && ((int)(s1[i]) <= 122)){
			if ((int)(s1[i]) + b > 122)
				s2+=(char)((int)(s1[i])+b-26);
			else if ((int)(s1[i]) + b < 97)
				s2+=(char)((int)(s1[i])+b+26);
			else
				s2+=(char)((int)(s1[i])+b);
		}
                //кириллица
		if (((int)(s1[i]+33)>=1)&&((int)(s1[i]+33)<=32)){
			if ((int)(s1[i]+33)+b>32)
				s2+=(char)((int)(s1[i])+b-32);
			else if ((int)(s1[i]+33)+b<1)
				s2+=(char)((int)(s1[i])+b+32);
			else
				s2+=(char)((int)(s1[i])+b);
		}
         //при дешифровке
        //для буквы ё, код которой -(72)
        //заменим ее на ж, на ее месте она должна быть по алфавиту
        if ( s1[i]=='ё')
          s2+=(char)((int)('ж')+b);
	}

       return s2;
}

//2.Перестановочный
//----------------------------------------------------------------------
 string Perest_enc(string s1, string p1){
    s1=del_space(s1);//удаление пробелов
     int n=5; //5 строк
      string s2;//зашифрованное сообщение

   int i,j;
   //преобразование в массив чисел строки с ключем
     int *p = new int [n];
       for (i=0;i<n;i++)
        p[i]=StrToInt(p1[i])-1;

    //необходимое количество строк
    float t = (float) s1.length()/n;
    //даже если 1 символ остался - созд. еще одну строку
     int m = ceil(t);//строки

   char **A = new char* [m]; //  m строк в матрице
    for (int count = 0; count < m; count++)
        A[count] = new char [n]; // и пять столбцов

    srand(time(NULL));  // инициализировать генератор
     int k=0;//подсчет количества символов строки

      //преобразование в двумерный массив
      for (i=0; i<m; i++){
       for (j=0; j<n; j++){
        if ((unsigned)k>=s1.length())
        //если привышает длину строки с сообщением, забиваем мусором
           *(*(A+i)+j)= (char) ( rand() % 25 + 97 ); //латиница от 97 до 122
              else //если не превышает длину сообщения
		*(*(A+i)+j)=s1[k];
		    k++;
			 }
		   }
      //запись в 1 строку с учетом перестановки столбцов по строке
      for (i=0; i<m; i++)
	  for (int r=0; r<n; r++){
	      j=p[r];
	        s2+=*(*(A+i)+j);
                  }
   return s2;
}
//----------------------------------------------------------------------
 string Perest_decr(string s1, string p1){
   s1=del_space(s1);//удаление пробелов

  int n=5; //5 строк
   string s3;//зашифрованное сообщение

    int i,j;
   //преобразование в массив чисел строки с ключем
     int *p = new int [n];
       for (i=0;i<n;i++)
         p[i]=StrToInt(p1[i])-1;

     //необходимое количество строк
     float t = (float) s1.length()/n;
     //даже если 1 символ остался - созд. еще одну строку
       int m = ceil(t);//строки

   char **A = new char* [m]; //  m строк в матрице
    for (int count = 0; count < m; count++)
        A[count] = new char [n]; // и пять столбцов

   int k=0;//контроль кол-ва итераций, чтобы не выйти за предел строки
      for (i=0; i<m; i++){
       for (j=0; j<n; j++){
         if ((unsigned)k>=s1.length()) break;
             *(*(A+i)+j)=s1[k];
	        k++;
                 }
		  }

  //расшифровка сообщения, с учетом перестановки столбцов, цикл по строкам
   for (i=0; i<m; i++)
     for (int r=0; r<n; r++){
      for ( k=0; k<n; k++)
	if (r==p[k])
	  j=k;//столбец равен индексу
            s3+=*(*(A+i)+j);
              }
 return s3;
}

//3.MagicSqr
//----------------------------------------------------------------------
string MagicSqr_enc(string s1, string p1){
  s1=del_space(s1);//удаление пробелов

  int n=4;//столбца
  string s2;//зашифрованное сообщение

  int i,j;
  //преобразование в массив чисел строки с ключем
   int *p = new int [n];
    for (i=0;i<n;i++)
      p[i]=StrToInt(p1[i])-1;

   //создание 2-мерного массива шифр. сообщ.
    float t = (float) s1.length()/n;
    //даже если 1 символ остался - созд. еще одну строку
     int m = ceil(t);//строки

   char **A = new char* [m]; //  m строк в матрице
    for (int count = 0; count < m; count++)
        A[count] = new char [n]; // и пять столбцов

    srand(time(NULL)); //инициализировать генератор
     int k=0;
     //контроль кол-ва итераций, чтобы не выйти за предел размера строки
      for (i=0; i<m; i++){
	 for (j=0; j<n; j++){
         //если привышает длину строки с сообщением, забиваем мусором
           if ((unsigned)k>=s1.length())
             *(*(A+i)+j)= (char)( rand() % 25 + 97 ); //латинский алф от 97 до 122
                else
		 *(*(A+i)+j)=s1[k];
		    k++;
		       }
		         }
  //зашифровка сообщения, с учетом расстановки символов по квадрату
    for (i=0; i<m; i++)
      for (int r=0; r<n; r++){
        j=p[r];
	  s2+=*(*(A+i)+j);
		  }
  return s2;
}
 //----------------------------------------------------------------------
 string MagicSqr_decr(string s1, string p1){
  s1=del_space(s1);//удаление пробелов
  int n=4; //4 столбца
  string s3; //расшифрованное сообщение

   int i,j;
   //преобразование в массив чисел строки с ключем
    int *p = new int [n];
      for (i=0;i<n;i++)
       p[i]=StrToInt(p1[i])-1;

    //создание 2-мерного массива шифр. сообщ.
    float t = (float) s1.length()/n;
    //даже если 1 символ остался - созд. еще одну строку
      int m = ceil(t);//строки

   char **A = new char* [m]; //  m строк в матрице
    for (int count = 0; count < m; count++)
        A[count] = new char [n]; // и пять столбцов

   int k=0;//контроль кол-ва итераций, чтобы не выйти за предел строки
      for (i=0; i<m; i++){
         for (j=0; j<n; j++){
            if ((unsigned)k>=s1.length()) break;
                *(*(A+i)+j)=s1[k];
		    k++;
                     }
		      }
    //расшифровка сообщения, с учетом расстановки символов по квадрату
     for (i=0; i<m; i++)
       for (int r=0; r<n; r++){
	 for ( k=0; k<n; k++)
	   if (r==p[k])
	     j=k;//столбец равен индексу массива ключа
               s3+=*(*(A+i)+j);
		  }
 return s3;
}

//4. Полибия
//----------------------------------------------------------------------
string Polybius_enc(string s1, string key){
    s1=del_space(s1);//удаление пробелов
    string s2;
    //определяем алфавит по 1 символу, кириллица или латиница
    //англ алфавит
                            //c   l  o   u   d
     char dp[5][5] =    {{'a','b','c','d','e'},
		         {'f','g','h','i','k'},
			 {'l','m','n','o','p'},
			 {'q','r','s','t','u'},
			 {'v','w','x','y','z'}};

 for (int n=0; (unsigned)n<s1.length(); n++)
  for (int i=0; i<5; i++)
   for (int j=0; j<5; j++)//по ключу
    if (s1[n]==dp[i][j]){//если в строке оказывается символ из мас. dp
     s2.append(key,j,1);//добавление в сообщение найденного символа ключа по столбцу
     s2.append(key,i,1);//добавление в сообщение найденного символа ключа по строке
      			};
 return s2;
}
//----------------------------------------------------------------------
string Polybius_decr(string s2, string key){
       s2=del_space(s2);//удаление пробелов
        string s3;

   //англ алфавит
                            //c   l  o   u   d
     char dp[5][5] =    {{'a','b','c','d','e'},
		         {'f','g','h','i','k'},
			 {'l','m','n','o','p'},
			 {'q','r','s','t','u'},
			 {'v','w','x','y','z'}};

  for (int n=0; (unsigned)n<s2.length(); n+=2)
    s3+=dp[key.find(s2[n+1])][key.find(s2[n])];

 return s3;
}
//----------------------------------------------------------------------

//5.Gamma
//различие в шифровании и дешифровании в знаке
 //----------------------------------------------------------------------
string Gamma_enc_decr (string s1, string p, int sign){
   s1=del_space(s1);//удаление пробелов
   int i;
   string s2;//зашифрованное сообщение

   int k = 0;
	for (i=0; (unsigned)i<s1.length(); i++){
	   s2+= (s1[i]+sign*p[k]);
           //+при шифровании -при дешфифровании
		 if (k==4) k=-1;
		  k++;
	}
  return s2;
}
 //----------------------------------------------------------------------

<file_sep>/Encryption and decryption text program C++/Unit1.cpp
//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"
#include "Unit3.h"
#include "Unit3.cpp"
#include <cstring.h>

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "sEdit"
#pragma link "sLabel"
#pragma link "sButton"
#pragma link "acPNG"
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
Panel1->Visible = false;
}
//---------------------------------------------------------------------------

void __fastcall TForm1::N2Click(TObject *Sender)
{  //
        Panel1->Visible = true;
        Panel2->Visible = false;
        Panel3->Visible = false;
        Panel4->Visible = false;
        Panel4->Visible = false;
        Panel5->Visible = false;

        Panel1->Align = alClient;
}
//---------------------------------------------------------------------------

void __fastcall TForm1::FormCreate(TObject *Sender)
{ //запуск программы

        Panel1->Visible = false;
        Panel2->Visible = false;
        Panel3->Visible = false;
        Panel4->Visible = false;
        Panel5->Visible = false;

}
//---------------------------------------------------------------------------

void __fastcall TForm1::N3Click(TObject *Sender)
{ //меню перестановочный шифр
   Panel1->Visible = false;
   Panel2->Visible = true;
   Panel3->Visible = false;
   Panel4->Visible = false;
   Panel5->Visible = false;

   Panel2->Align = alClient;
}
//---------------------------------------------------------------------------

void __fastcall TForm1::N4Click(TObject *Sender)
{  //меню магический квадрат
   Panel1->Visible = false;
   Panel2->Visible = false;
   Panel3->Visible = true;
   Panel4->Visible = false;
   Panel5->Visible = false;

   Panel3->Align = alClient;
}
//---------------------------------------------------------------------------

void __fastcall TForm1::N5Click(TObject *Sender)
{
   Panel1->Visible = false;
   Panel2->Visible = false;
   Panel3->Visible = false;
   Panel4->Visible = true;
   Panel5->Visible = false;

   Panel4->Align = alClient;
}
//---------------------------------------------------------------------------

void __fastcall TForm1::N6Click(TObject *Sender)
{
   Panel1->Visible = false;
   Panel2->Visible = false;
   Panel3->Visible = false;
   Panel4->Visible = false;
   Panel5->Visible = true;

   Panel5->Align = alClient;
}
//---------------------------------------------------------------------------

void __fastcall TForm1::sButton1Click(TObject *Sender)
{
  string s1;
  int key;
  s1 = sEdit1->Text.c_str();
  key = StrToInt(sEdit2->Text.c_str());
  string s2 = Caesar_enc_decr(s1,key);
  sEdit3->Text=s2.c_str();
}
//---------------------------------------------------------------------------

void __fastcall TForm1::sButton2Click(TObject *Sender)
{
  string s1;
  int key;
  s1 = sEdit1->Text.c_str();
  key = StrToInt(sEdit2->Text.c_str());
  string s2 = Caesar_enc_decr(s1,-key);
  sEdit3->Text=s2.c_str();
}
//---------------------------------------------------------------------------

void __fastcall TForm1::sButton3Click(TObject *Sender)
{
  string s1, key;
  s1 = sEdit5->Text.c_str();
  key = sEdit4->Text.c_str();
  string s2 = Perest_enc(s1,key);
  sEdit6->Text=s2.c_str();
}
//---------------------------------------------------------------------------

void __fastcall TForm1::sButton4Click(TObject *Sender)
{
  string s1, key;
  s1 = sEdit5->Text.c_str();
  key = sEdit4->Text.c_str();
  string s2 = Perest_decr(s1,key);
  sEdit6->Text=s2.c_str();
}
//---------------------------------------------------------------------------

void __fastcall TForm1::sButton5Click(TObject *Sender)
{
  string s1, key;
  s1 = sEdit7->Text.c_str();
  key = sEdit8->Text.c_str();
  string s2 = MagicSqr_enc(s1,key);
  sEdit9->Text=s2.c_str();
}
//---------------------------------------------------------------------------

void __fastcall TForm1::sButton6Click(TObject *Sender)
{
  string s1, key;
  s1 = sEdit7->Text.c_str();
  key = sEdit8->Text.c_str();
  string s2 = MagicSqr_decr(s1,key);
  sEdit9->Text=s2.c_str();
}
//---------------------------------------------------------------------------

void __fastcall TForm1::sButton7Click(TObject *Sender)
{
  string s1, key;
  s1 = sEdit10->Text.c_str();
  key = sEdit11->Text.c_str();
  string s2 = Polybius_enc(s1,key);
  sEdit12->Text=s2.c_str();
}
//---------------------------------------------------------------------------

void __fastcall TForm1::sButton8Click(TObject *Sender)
{
  string s1, key;
  s1 = sEdit10->Text.c_str();
  key = sEdit11->Text.c_str();
  string s2 = Polybius_decr(s1,key);
  sEdit12->Text=s2.c_str();
}
//---------------------------------------------------------------------------

void __fastcall TForm1::sButton9Click(TObject *Sender)
{
  string s1, key;
  s1 = sEdit13->Text.c_str();
  key = sEdit14->Text.c_str();
  string s2 = Gamma_enc_decr(s1,key,1);
  sEdit15->Text=s2.c_str();
}
//---------------------------------------------------------------------------

void __fastcall TForm1::sButton10Click(TObject *Sender)
{
  string s1, key;
  s1 = sEdit13->Text.c_str();
  key = sEdit14->Text.c_str();
  string s2 = Gamma_enc_decr(s1,key,-1);
  sEdit15->Text=s2.c_str();
}
//---------------------------------------------------------------------------

void __fastcall TForm1::N7Click(TObject *Sender)
{
string msg = "Программа содержит 5 методов\n шифрования и дешифрования текста.\n Автор программы - <NAME>.";
MessageBox(Handle, msg.c_str(),
 Application->Title.c_str(), MB_OK | MB_ICONINFORMATION);
}
//---------------------------------------------------------------------------

void __fastcall TForm1::N8Click(TObject *Sender)
{
  Application->Terminate();
}
//---------------------------------------------------------------------------

<file_sep>/Encryption and decryption text program C++/Unit1.h
//---------------------------------------------------------------------------

#ifndef Unit1H
#define Unit1H
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include <Menus.hpp>
#include <ExtCtrls.hpp>
#include <jpeg.hpp>
#include "sEdit.hpp"
#include "sLabel.hpp"
#include "sButton.hpp"
#include "acPNG.hpp"
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published:	// IDE-managed Components
        TMainMenu *MainMenu1;
        TMenuItem *N1;
        TMenuItem *N2;
        TMenuItem *N3;
        TMenuItem *N4;
        TMenuItem *N5;
        TMenuItem *N6;
        TMenuItem *N7;
        TMenuItem *N8;
        TPanel *Panel1;
        TImage *Image1;
        TsEdit *sEdit1;
        TsEdit *sEdit2;
        TImage *Image2;
        TsLabel *sLabel1;
        TsLabel *sLabel2;
        TsEdit *sEdit3;
        TsButton *sButton1;
        TsButton *sButton2;
        TPanel *Panel2;
        TsEdit *sEdit5;
        TsEdit *sEdit4;
        TsLabel *sLabel3;
        TsLabel *sLabel4;
        TsButton *sButton3;
        TsButton *sButton4;
        TsEdit *sEdit6;
        TPanel *Panel3;
        TImage *Image3;
        TsLabel *sLabel5;
        TsLabel *sLabel6;
        TsEdit *sEdit7;
        TsEdit *sEdit8;
        TsButton *sButton5;
        TsButton *sButton6;
        TsEdit *sEdit9;
        TPanel *Panel4;
        TImage *Image5;
        TsLabel *sLabel7;
        TsLabel *sLabel8;
        TsEdit *sEdit10;
        TsEdit *sEdit11;
        TsButton *sButton7;
        TsButton *sButton8;
        TsEdit *sEdit12;
        TPanel *Panel5;
        TImage *Image6;
        TsLabel *sLabel9;
        TsLabel *sLabel10;
        TsEdit *sEdit13;
        TsEdit *sEdit14;
        TsButton *sButton9;
        TsButton *sButton10;
        TsEdit *sEdit15;
        TImage *Image4;
        TsLabel *sLabel11;
        TsLabel *sLabel12;
        TLabel *Label1;
        TLabel *Label2;
        TLabel *Label3;
        TLabel *Label4;
        TLabel *Label5;
        TsLabel *sLabel13;
        TsLabel *sLabel15;
        TsLabel *sLabel14;
        TsLabel *sLabel16;
        TsLabel *sLabel17;
        void __fastcall N2Click(TObject *Sender);
        void __fastcall FormCreate(TObject *Sender);
        void __fastcall N3Click(TObject *Sender);
        void __fastcall N4Click(TObject *Sender);
        void __fastcall N5Click(TObject *Sender);
        void __fastcall N6Click(TObject *Sender);
        void __fastcall sButton1Click(TObject *Sender);
        void __fastcall sButton2Click(TObject *Sender);
        void __fastcall sButton3Click(TObject *Sender);
        void __fastcall sButton4Click(TObject *Sender);
        void __fastcall sButton5Click(TObject *Sender);
        void __fastcall sButton6Click(TObject *Sender);
        void __fastcall sButton7Click(TObject *Sender);
        void __fastcall sButton8Click(TObject *Sender);
        void __fastcall sButton9Click(TObject *Sender);
        void __fastcall sButton10Click(TObject *Sender);
        void __fastcall N7Click(TObject *Sender);
        void __fastcall N8Click(TObject *Sender);
private:	// User declarations
public:		// User declarations
        __fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif


text:
<repo_name>lea-prado/PracticoEntregable<file_sep>/DataAccessLayer/DALEmployeesEF.cs
using Shared.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataAccessLayer
{
    public class DALEmployeesEF : IDALEmployees
    {
        private Model.Employee Casteo(Employee emp)
        {
            if (emp == null)
            {
                return null;
            }
            if (emp.GetType().Name == "FullTimeEmployee")
            {
                FullTimeEmployee employee = (FullTimeEmployee)emp;
                Model.FullTimeEmployee employeeBase = new Model.FullTimeEmployee()
                {
                    Name = employee.Name,
                    StartDate = employee.StartDate,
                    Salary = employee.Salary
                };
                return employeeBase;
            }
            else
            {
                PartTimeEmployee employee = (PartTimeEmployee)emp;
                Model.PartTimeEmployee employeeBase = new Model.PartTimeEmployee()
                {
                    Name = employee.Name,
                    StartDate = employee.StartDate,
                    HourlyRate = employee.HourlyRate
                };
                return employeeBase;
            }

        }

        private Employee Casteo(Model.Employee emp)
        {
            if (emp == null)
            {
                return null;
            }
            if (emp.GetType().Name == "FullTimeEmployee")
            {
                Model.FullTimeEmployee Memp = (Model.FullTimeEmployee)emp;
                FullTimeEmployee employeeBase = new FullTimeEmployee()
                {
                    Id = Memp.EmployeeId,
                    Name = Memp.Name,
                    StartDate = Memp.StartDate,
                    Salary = Memp.Salary
                };
                return employeeBase;
            }
            else
            {
                Model.PartTimeEmployee Memp = (Model.PartTimeEmployee)emp;
                PartTimeEmployee employeeBase = new PartTimeEmployee()
                {
                    Id = Memp.EmployeeId,
                    Name = Memp.Name,
                    StartDate = Memp.StartDate,
                    HourlyRate = Memp.HourlyRate
                };
                return employeeBase;
            }

        }
        public void AddEmployee(Employee emp)
        {
            if (emp == null)
            {
                return;
            }
            using (Model.PracticoNetEntities en = new Model.PracticoNetEntities())
            {
                en.Employee.Add(Casteo(emp));
                en.SaveChanges();
            }
        }

        public void DeleteEmployee(int id)
        {
            using (var context = new Model.PracticoNetEntities())
            {
                Model.Employee emp = context.Employee.FirstOrDefault(x => x.EmployeeId == id);
                if (emp != null)
                {
                    if (emp.GetType().Name == "FullTimeEmployee")
                    {
                        Model.FullTimeEmployee fte = (Model.FullTimeEmployee)emp;
                        context.Employee.Remove(fte);
                        context.SaveChanges();
                    }
                    else
                    {
                        Model.PartTimeEmployee pte = (Model.PartTimeEmployee)emp;
                        context.Employee.Remove(pte);
                        context.SaveChanges();
                    }
                }
            }
        }

        public void UpdateEmployee(Employee emp)
        {
            if (emp == null)
            {
                return;
            }
            using (Model.PracticoNetEntities en = new Model.PracticoNetEntities())
            {
                Model.Employee em = en.Employee.Find(emp.Id);
                em.Name = emp.Name;
                em.StartDate = emp.StartDate;
                if (emp.GetType().Name == "FullTimeEmployee")
                {
                    Model.FullTimeEmployee emCast = (Model.FullTimeEmployee)em;
                    emCast.Salary = ((FullTimeEmployee)emp).Salary;
                }
                else
                {
                    Model.PartTimeEmployee emCast = (Model.PartTimeEmployee)em;
                    emCast.HourlyRate = ((PartTimeEmployee)emp).HourlyRate;
                }
                en.SaveChanges();
            }
        }

        public List<Employee> GetAllEmployees()
        {
            using (Model.PracticoNetEntities en = new Model.PracticoNetEntities())
            {
                List<Employee> listaEmpleados = new List<Employee>();
                en.Employee.ToList().ForEach(x =>
                {
                    listaEmpleados.Add(Casteo(x));
                });
                return listaEmpleados;
            }
        }

        public Employee GetEmployee(int id)
        {
            using (Model.PracticoNetEntities en = new Model.PracticoNetEntities())
            {
                return Casteo(en.Employee.Find(id));
            }
        }
    }

}
<file_sep>/PresentationLayerWinForm/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PresentationLayerWinForm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: esta línea de código carga datos en la tabla 'practicoNetDataSe.Employee' Puede moverla o quitarla según sea necesario.
            this.employeeTableAdapter.Fill(this.practicoNetDataSe.Employee);

        }
        private void AddNewEmployee_Load(object sender, EventArgs e)
        {
            // TODO: esta línea de código carga datos en la tabla 'practicoEntregableDataSet5.EmployeesTPH' Puede moverla o quitarla según sea necesario.
            this.employeeTableAdapter.Fill(this.practicoNetDataSe.Employee);
            comboBox1.Items.Add("FullTimeEmployee");
            comboBox1.Items.Add("ParTimeEmployee");
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count != 0)
            {
                DataGridViewRow row = this.dataGridView1.SelectedRows[0];
                int id = (int)row.Cells[0].Value;
                Controlador c = new Controlador();
                c.DeleteEmployee(id);
            }
        }

        private void Button2_Click(object sender, EventArgs e)
        {
            DataAccessLayer.DALEmployeesEF en = new DataAccessLayer.DALEmployeesEF();
            BusinessLogicLayer.BLEmployees bus = new BusinessLogicLayer.BLEmployees(en);

            if (comboBox1.Text == "FullTimeEmployee")
            {
                Shared.Entities.FullTimeEmployee fte = new Shared.Entities.FullTimeEmployee()
                {
                    Name = textBox1.Text,
                    StartDate = dateTimePicker1.Value,
                    Salary = Int32.Parse(textBox2.Text)
                };
                bus.AddEmployee(fte);
            }
            else
            {
                Shared.Entities.PartTimeEmployee fte = new Shared.Entities.PartTimeEmployee()
                {
                    Name = textBox1.Text,
                    StartDate = dateTimePicker1.Value,
                    HourlyRate = Int32.Parse(textBox3.Text)
                };
                bus.AddEmployee(fte);
            }
            this.Close();
        }

    }
}
<file_sep>/BusinessLogicLayer/BLEmployees.cs
using DataAccessLayer;
using Shared.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BusinessLogicLayer
{
    public class BLEmployees : IBLEmployees
    {
       private IDALEmployees _dal;

        public BLEmployees(IDALEmployees dal)
        {
            _dal = dal;
        }

        public void AddEmployee(Employee emp)
        {
            _dal.AddEmployee(emp);
        }

        public void DeleteEmployee(int id)
        {
            _dal.DeleteEmployee(id);
        }

        public void UpdateEmployee(Employee emp)
        {
            _dal.UpdateEmployee(emp);
        }

        public List<Employee> GetAllEmployees()
        {
            return _dal.GetAllEmployees();
        }

        public Employee GetEmployee(int id)
        {
            DALEmployeesEF emp = new DALEmployeesEF();
            if (emp == null)
            {
                throw new Exception("El usuario no ha sido encontrado");
            }
            return emp.GetEmployee(id);
        }

        public double CalcPartTimeEmployeeSalary(int idEmployee, int hours)
        {
            DALEmployeesEF empEF = new DALEmployeesEF();

            if (empEF == null)
            {
                throw new Exception("El usuario no ha sido encontrado");
            }
            Employee mEmploy = empEF.GetEmployee(idEmployee);
            if (mEmploy.GetType().Name == "FullTimeEmployee")
            {
                throw new Exception("El usuario no esta identificado como part-time");
            }
            else
            {
                return ((PartTimeEmployee)mEmploy).HourlyRate * hours;
            }
        }
    }
}
<file_sep>/ServiceLayer/Program.cs
using BusinessLogicLayer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Text;
using System.Threading.Tasks;

namespace ServiceLayer
{
    class Program
    {
        public static IBLEmployees blHandler;

        static void Main(string[] args)
        {
            SetupDependencies();
            SetupService();
        }

        private static void SetupDependencies()
        {
            blHandler = new BLEmployees(new DataAccessLayer.DALEmployeesEF());
        }

        private static void SetupService()
        {
            ServiceHost host = new ServiceHost(typeof(ServiceEmployees), new Uri("http://localhost:8834/tsi1"));
            try
            {
                // Open the service host to accept incoming calls
                host.Open();

                // The service can now be accessed.
                Console.WriteLine("The service is ready.");
                Console.WriteLine("Press <ENTER> to terminate service.");
                Console.WriteLine();
                Console.ReadLine();

                // Close the ServiceHostBase to shutdown the service.
                host.Close();
            }
            catch (CommunicationException commProblem)
            {
                Console.WriteLine("There was a communication problem. " + commProblem.Message);
                Console.Read();
            }
        }
    }
}
<file_sep>/ServiceLayer/IServiceEmployees.cs
using Shared.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Threading.Tasks;

namespace ServiceLayer
{
    public interface IServiceEmployees
    {

        void AddEmployee(Employee emp);

        void DeleteEmployee(int id);

        void UpdateEmployee(Employee emp);

        List<Employee> GetAllEmployees();

        Employee GetEmployee(int id);

        [OperationContract]
        [WebInvoke(UriTemplate = "CalcPartTimeEmployeeSalary?idEmployee={idEmployee}&hours={hours}", BodyStyle = WebMessageBodyStyle.Bare)]
        double CalcPartTimeEmployeeSalary(int idEmployee, int hours);
    }
}
<file_sep>/PresentationLayerWinForm/Controlador.cs

using BusinessLogicLayer;
using DataAccessLayer;
using Shared.Entities;
using System.Collections.Generic;

namespace PresentationLayerWinForm
{
    public class Controlador
    {
        private IBLEmployees IB;
        public Controlador()
        {
            IDALEmployees IDALEmp = new DALEmployeesEF();
            IB = new BLEmployees(IDALEmp);
        }
        public void AddEmployee(Employee emp)
        {
            IB.AddEmployee(emp);
        }

        public void DeleteEmployee(int id)
        {
            IB.DeleteEmployee(id);
        }

        public void UpdateEmployee(Employee emp)
        {
            IB.UpdateEmployee(emp);
        }

        public List<Employee> GetAllEmployees()
        {
            return IB.GetAllEmployees();
        }

        public Employee GetEmployee(int id)
        {
            return IB.GetEmployee(id);
        }

        public double CalcPartTimeEmployeeSalary(int idEmployee, int hours)
        {
            return IB.CalcPartTimeEmployeeSalary(idEmployee, hours);
        }
    }
}

repo_language: C#

repo_name: lea-prado/PracticoEntregable