branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep># gist-getter # This repo holds a small script `get_gist.py` that retrieves the latest revision of GitHub Gists given a filename. The GitHub username is hardcoded as `joesingo` in the code. It only works for publicly accessible gists, and if a gist contains more than one file only the first is returned. ## Usage ## ``` pip3 install -r requirements.txt python3 get_gist.py <filename> ``` There is also a Flask app that wraps this script and a Dockerfile to run it in a container: ``` docker build -t gist . docker run -p 5000:5000 gist ``` I have set this image up gist.joesingo.co.uk as a shortcut for grabbing files quickly; e.g. `curl gist.joesingo.co.uk/tmux.conf > ~/.tmux.conf` is slightly quicker than opening a web browser to find the URL for the gist and pasting it somewhere... <file_sep>import requests from flask import Flask, abort, make_response from get_gist import get_raw_url app = Flask(__name__) @app.route("/<filename>", methods=["GET"]) def get_gist(filename): try: raw_url = get_raw_url(filename) except ValueError as ex: abort(404) response = make_response(requests.get(raw_url).text) response.headers["Content-Type"] = "Raw" return response if __name__ == "__main__": app.run(host="0.0.0.0") <file_sep>#!/usr/bin/env python3 """ Small script to print the latest version of a GitHub Gist given a filename. If the gist contains several files only the first one is returned. Only works for publicly-accessible gists, and the username is hardcoded at the top of the script. Requirements can be installed with pip3 install beautifulsoup4 requests and the script is run as ./get_gist.py <filename> """ import sys import requests API_URL = "https://api.github.com" USERNAME = "joesingo" def get_raw_url(filename): """ Return raw URL for a file within a gist. Raises ValueError if file is not found. """ resp = requests.get("{base}/users/{user}/gists".format( base=API_URL, user=USERNAME )).json() if "message" in resp: raise ValueError("Error listing gists. Message from API is: {}".format( resp["message"] )) for obj in resp: if filename in obj["files"]: return obj["files"][filename]["raw_url"] raise ValueError("File '{}' not found for user '{}'".format( filename, USERNAME )) if __name__ == "__main__": if len(sys.argv) < 2: sys.stderr.write("Usage: {} FILE\n".format(sys.argv[0])) sys.exit(1) try: raw_url = get_raw_url(sys.argv[1]) except ValueError as ex: sys.stderr.write("{}: {}\n".format(sys.argv[0], ex)) sys.exit(1) print(requests.get(raw_url).text)
474d1a961e92befeee29c44ea0fa982efa019fef
[ "Markdown", "Python" ]
3
Markdown
joesingo/gist-getter
fe0c8b049ea3d74c09929157d3b03ac595e6aceb
acc21035bca99df7b71bf6aa6ce8cea77c940f3b
refs/heads/master
<file_sep>import pygame, sys from pygame.locals import * pygame.init() WIDTH = 800 HEIGHT = 600 screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('POONG!') FPS = 30 # frames per second fpsClock = pygame.time.Clock() # set up colors BLACK = ( 0, 0, 0) WHITE = (255, 255, 255) BALL_SIZE = 10 ballx = 400 bally = 300 balldx = 5 balldy = 0 ai_loc = 300 while True: # main game loop for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() # clear screen # pygame.draw.rect(DISPLAYSURF, BLACK, (0, 0, 800, 600)) screen.fill(BLACK) # draw ball pygame.draw.rect(screen, WHITE, (ballx, bally, BALL_SIZE, BALL_SIZE)) # draw human paddle mouse = pygame.mouse.get_pos() pygame.draw.rect(screen, WHITE, (750, mouse[1], 10, 60)) # draw AI paddle ai_loc = bally - 30 pygame.draw.rect(screen, WHITE, (40, (ai_loc), 10, 60)) ballx += balldx bally += balldy # bouncing human paddle if (ballx >= 740 and (mouse[1] < bally < mouse[1] + 60)): if (abs(balldx) < 400): balldx = -balldx - 1 # reflect and speed up else: balldx = -balldx balldy = (bally - mouse[1] - 30) / 5 # adding 'english' # bouncing off AI paddle if (ballx < 50 and (ai_loc < bally < ai_loc + 60)): if (abs(balldx) < 400): balldx = -balldx + 1 else: balldx = -balldx # bouncing off walls if (not(0 <= bally <= 590)): balldy = -balldy if (not(0 <= ballx <= 790)): balldx = -balldx pygame.display.update() fpsClock.tick(FPS)
b2babecb7eab469742b5a3853de5568310635a1c
[ "Python" ]
1
Python
rtrigg/poong
34ad7ee9887bc90e8d19d61b9a5ff5a9702c3952
a0f2bf0f48d7425f846f5406a09284ceffba93a2
refs/heads/master
<file_sep>/* ============================================================================ Name : Passing_parameters_to_the_program_via_a_text_file.c Author : =^_^= Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <stdio.h> #include <math.h> int main(void){ float *vector_a=NULL,*vector_b=NULL;// ะžะฑัŠัะฒะปะตะธะต ัƒะบะฐะทะฐั‚ะตะปะตะน ะบ ะผะฐััะธะฒะฐะผ ั ะฒะตะบั‚ะพั€ะฐะผะธ FILE *myfile, *rezult; float n,val,sum,a,b,c; int zapros,kom,f=1; myfile = fopen ("test.txt", "r");//ะงั‚ะตะฝะธะต ั„ะฐะนะปะฐ rezult = fopen ("rezult.txt", "w");//ะ—ะฐะฟะธััŒ ะฒ ั„ะฐะนะป fscanf(myfile,"%d",&zapros); if(zapros == 0){//ัƒัะปะพะฒะธะต ะดะปั ั€ะฐะฑะพั‚ั‹ ั ะพะฑั‹ั‡ะฝั‹ะผะธ ั‡ะธัะปะฐะผะธ fscanf(myfile,"%d %f %f %f",&kom,&a,&b,&c); switch(kom){ case 1: c=a+b; break; case 2: c=a-b; break; case 3: c=a*b; break; case 4: c=a/b; break; case 5: c=pow(a,b); break; case 6: while (a>0){ f*=a; a--; } c=f; } fprintf(rezult,"%.2f", c); } if(zapros==1){//ะฃัะปะพะฒะธะต ะดะปั ั€ะฐะฑะพั‚ั‹ ั ะฒะตะบั‚ะพั€ะฐะผะธ fscanf(myfile,"%d" "%f",&kom,&n);// ะ’ั‹ะดะตะปะตะฝะธะต ะฟะฐะผัั‚ะธ ะดะปั ะฒะตะบั‚ะพั€ะฐ 1 ะธ ัั‡ะธั‚ั‹ะฒะฐะฝะธะต ั€ะตะทัƒะปัŒั‚ะฐั‚ะพะฒ vector_a = malloc(n * sizeof(float)); for (int i = 0; i < n; i++){ fscanf(myfile,"%f",&vector_a[i]); } vector_b = malloc(n * sizeof(float));// ะ’ั‹ะดะตะปะตะฝะธะต ะฟะฐะผัั‚ะธ ะดะปั ะฒะตะบั‚ะพั€ะฐ 2 ะธ ัั‡ะธั‚ั‹ะฒะฐะฝะธะต ั€ะตะทัƒะปัŒั‚ะฐั‚ะพะฒ for (int i = 0; i < n; i++){ fscanf(myfile,"%f",&vector_b[i]); } switch(kom){ case 1://ะกัƒะผะผะฐ ะฒะตะบั‚ะพั€ะพะฒ fprintf(rezult,"("); for(int i = 0; i < n; i++){//ะ’ั‹ะฒะพะด ะฒะตะบั‚ะพั€ะฐ fprintf(rezult,"%.2f ",vector_a[i]); } fprintf(rezult,")"); fprintf(rezult,"+"); fprintf(rezult,"("); for(int i = 0; i < n; i++){//ะ’ั‹ะฒะพะด ะฒะตะบั‚ะพั€ะฐ fprintf(rezult,"%.2f ",vector_b[i]); } fprintf(rezult,")"); fprintf(rezult,"="); fprintf(rezult,"("); for(int i = 0; i < n; i++){ val = vector_a[i] + vector_b[i]; fprintf(rezult,"%.2f ",val); } fprintf(rezult,")"); free(vector_a);//ะžั‡ะธัั‚ะบะฐ ะฟะฐะผัั‚ะธ free(vector_b);//ะžั‡ะธัั‚ะบะฐ ะฟะฐะผัั‚ะธ break; case 2://ะ ะฐะทะฝะพัั‚ัŒ ะฒะตะบั‚ะพั€ะพะฒ fprintf(rezult,"("); for(int i = 0; i < n; i++){//ะ’ั‹ะฒะพะด ะฒะตะบั‚ะพั€ะฐ fprintf(rezult,"%.2f ",vector_a[i]); } fprintf(rezult,")"); fprintf(rezult,"-"); fprintf(rezult,"("); for(int i = 0; i < n; i++){//ะ’ั‹ะฒะพะด ะฒะตะบั‚ะพั€ะฐ fprintf(rezult,"%.2f ",vector_b[i]); } fprintf(rezult,")"); fprintf(rezult,"="); fprintf(rezult,"("); for(int i = 0; i < n; i++){ val = vector_a[i] - vector_b[i]; fprintf(rezult,"%.2f ",val); } fprintf(rezult,")"); free(vector_a);//ะžั‡ะธัั‚ะบะฐ ะฟะฐะผัั‚ะธ free(vector_b);//ะžั‡ะธัั‚ะบะฐ ะฟะฐะผัั‚ะธ break; case 3://ะกะบะฐะปัั€ะฝะพะต ะฟั€ะพะธะทะฒะตะดะตะฝะธะต ะฒะตะบั‚ะพั€ะพะฒ fprintf(rezult,"("); for(int i = 0; i < n; i++){//ะ’ั‹ะฒะพะด ะฒะตะบั‚ะพั€ะฐ fprintf(rezult,"%.2f ",vector_a[i]); } fprintf(rezult,")"); fprintf(rezult,"*"); fprintf(rezult,"("); for(int i = 0; i < n; i++){//ะ’ั‹ะฒะพะด ะฒะตะบั‚ะพั€ะฐ fprintf(rezult,"%.2f ",vector_b[i]); } fprintf(rezult,")"); fprintf(rezult," = "); for(int i = 0; i < n; i++){ val = (vector_a[i] * vector_b[i]); sum = sum + val; } fprintf(rezult,"%.2f ",sum); free(vector_a);//ะžั‡ะธัั‚ะบะฐ ะฟะฐะผัั‚ะธ free(vector_b);//ะžั‡ะธัั‚ะบะฐ ะฟะฐะผัั‚ะธ break; } } }
7c2a47838fed3c592bb514e72e7481b0e1ba25e7
[ "C" ]
1
C
DmitryNest/Passing_parameters_to_the_program_via_a_text_file-settings
cf01b9879a6aa9f470cef56cce33c8678905ebce
6afeb7988bc6e6520e3ed243520b3d880a43ca4e
refs/heads/main
<file_sep>๏ปฟusing System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerLife : MonoBehaviour { [SerializeField] public GameObject SpawnPoint; private bool respawn = false; [SerializeField] public int PlayerLifes; [HideInInspector] public int PlayerHitpoints; // Use this for initialization void Start () { PlayerHitpoints = PlayerLifes; SpawnPoint = GameObject.Find("Spawnpoints/Spawnpoint"); } // Update is called once per frame void Update () { if (PlayerHitpoints <= 0) { respawn = true; } else { respawn = false; } if (respawn) { transform.position = SpawnPoint.transform.position; } } } <file_sep>๏ปฟusing System.Collections; using System.Collections.Generic; using UnityEngine; public class Test : MonoBehaviour { public Vector3 teleportPoint; public Rigidbody rb; void Start() { rb = GetComponent<Rigidbody>(); } void FixedUpdate() { rb.MovePosition(transform.position + transform.forward * Time.deltaTime); } // Update is called once per frame void Update () { } } <file_sep>๏ปฟusing System.Collections; using System.Collections.Generic; using UnityEngine; public class Respawn : MonoBehaviour { public GameObject Player; private int PlayerHitpoints; private void OnTriggerEnter(Collider other) { if (other.gameObject == Player) { GameObject.Find("FPSController").GetComponent<PlayerLife>().PlayerHitpoints = 0; } } private void OnTriggerExit(Collider other) { if (other.gameObject == Player) { GameObject.Find("FPSController").GetComponent<PlayerLife>().PlayerHitpoints = GameObject.Find("FPSController").GetComponent<PlayerLife>().PlayerLifes; } } // Use this for initialization void Start () { Player = GameObject.Find("FPSController"); } // Update is called once per frame void Update () { } } <file_sep>๏ปฟusing System.Collections; using System.Collections.Generic; using UnityEngine; using UnityStandardAssets.Characters.FirstPerson; public class Attach : MonoBehaviour { public GameObject Player; [SerializeField] private float SpeedBoost; private bool EndSpeedBoost; private bool Grounded; private float NormalRunspeed; // When the Player triggers the Collider this is called once per frame private void OnTriggerStay(Collider other) { if (other.gameObject == Player) { Player.transform.parent = transform; } } private void OnTriggerEnter(Collider other) { if (other.gameObject == Player) { Player.transform.parent = transform; } } private void OnTriggerExit(Collider other) { if (other.gameObject == Player) { Player.transform.parent = null; GameObject.Find("FPSController").GetComponent<FirstPersonController>().m_RunSpeed += SpeedBoost; EndSpeedBoost = true; } if (GameObject.Find("FPSController").GetComponent<FirstPersonController>().m_RunSpeed > NormalRunspeed + SpeedBoost) { GameObject.Find("FPSController").GetComponent<FirstPersonController>().m_RunSpeed = NormalRunspeed + SpeedBoost; } } // Use this for initialization void Start () { EndSpeedBoost = false; NormalRunspeed = GameObject.Find("FPSController").GetComponent<FirstPersonController>().m_RunSpeed; } // Update is called once per frame void Update () { Grounded = GameObject.Find("FPSController").GetComponent<FirstPersonController>().m_CharacterController.isGrounded; if (Grounded && EndSpeedBoost) { GameObject.Find("FPSController").GetComponent<FirstPersonController>().m_RunSpeed = NormalRunspeed; EndSpeedBoost = false; } else if (Grounded) { EndSpeedBoost = true; } /*if (GameObject.Find("FPSController").GetComponent<FirstPersonController>().m_RunSpeed > NormalRunspeed + SpeedBoost) { GameObject.Find("FPSController").GetComponent<FirstPersonController>().m_RunSpeed = NormalRunspeed + SpeedBoost; }*/ } } <file_sep># BGEMBJATWDHATBTGIA A game [@JoostdeJager](https://github.com/joostdejager) and I made when we where 16 for a school project ## The game It's a (very) short platformer game. You jump from platform to platform in between rocks and lava. ## The title You might also be wondering: What does the title of this game mean? Well it's a long name. The title stands for: **B**est **G**ame **E**ver **M**ade **B**y **J**oost **A**nd **T**hijs **W**e **D**idn't **H**ave **A** **T**itle **B**ut **T**he **G**ame **I**s **A**wesome
da665758407dcf7bc55b27f3ce29f726c2313606
[ "Markdown", "C#" ]
5
C#
dusthijsvdh/BGEMBJATWDHATBTGIA
3985676f4ecd730952980f4be16a97ffae976ddb
f33b124bcf3a30a0f312f529ff8f473867662a28
refs/heads/master
<file_sep>"use strict"; module.exports = function(app) { var todoList = require("./controller"); app.route("/").get(todoList.index); app.route("/users").get(todoList.users); app.route("/users").post(todoList.createUsers); app.route("/emails").get(todoList.emails); app.route("/mobiles").get(todoList.mobiles); }; <file_sep>This project is deployed to: [http://mitraisserver-env.tecyp2skhk.us-east-2.elasticbeanstalk.com/](http://mitraisserver-env.tecyp2skhk.us-east-2.elasticbeanstalk.com/). ## Available Scripts In the project directory, you can run: ### `yarn install` Install dependencies used in this project. ### `node index.js` Runs the app in the development mode.<br /> Open [http://localhost:8000](http://localhost:8000) to view it in the browser. The page will reload if you make edits.<br /> You will also see any lint errors in the console. ### `yarn test` Launches the test script. ## Available links List all users [http://mitraisserver-env.tecyp2skhk.us-east-2.elasticbeanstalk.com/users](http://mitraisserver-env.tecyp2skhk.us-east-2.elasticbeanstalk.com/users) to view users loaded from mysql database <file_sep>'use strict'; var response = require('./res'); var connection = require('./connection'); exports.users = function(req, res) { connection.query('SELECT * FROM mitrais.registration', function (error, rows, fields){ if(error){ console.log(error) } else{ response.ok(rows, res) } }); }; exports.createUsers = function(req, res) { var phone_number = req.body.phone_number; var first_name = req.body.first_name; var last_name = req.body.last_name; var birth_date = new Date(req.body.birth_date); var gender = req.body.gender; var email = req.body.email; connection.query('INSERT INTO mitrais.registration (phone_number, first_name, last_name, birth_date, gender, email) VALUES (?, ?, ?, ?, ?, ?)', [ phone_number ,first_name, last_name, birth_date, gender, email ], function (error, rows, fields){ if(error){ console.log(error) } else{ response.ok("success", res) } }); }; exports.emails = function(req, res) { connection.query('SELECT email FROM mitrais.registration', function (error, rows, fields){ if(error){ console.log(error) } else{ response.ok(rows, res) } }); }; exports.mobiles = function(req, res) { connection.query('SELECT phone_number FROM mitrais.registration', function (error, rows, fields){ if(error){ console.log(error) } else{ response.ok(rows, res) } }); }; exports.index = function(req, res) { response.ok("Node JS RESTful mitrais test", res) };<file_sep>const chai = require("chai"); const chaiHttp = require("chai-http"); const app = require("../index"); const should = chai.should(); chai.use(chaiHttp); describe("/GET user", () => { it("it should Get all users", done => { chai .request(app) .get("/users") .end((err, res) => { res.should.have.status(200); res.body.should.be.a("object"); done(); }); }); }); describe("/POST user", () => { it("it sould post the user info", done => { const user = { phone_number: "081321886599", first_name: "Yacob", last_name: "Madiana", birth_date: "1989-15-06", gender: "male", email: "<EMAIL>" }; chai .request(app) .post("/users") .send(user) .end((err, res) => { res.should.have.status(200); res.body.should.be.a("object"); done(); }); }); });
4f7a956a2be65f67f224929ae577d74f1f9bf897
[ "JavaScript", "Markdown" ]
4
JavaScript
yacob89/registration-server
8576c4a761472b91c51b5addf587d9db7ba7bfdb
f96e6099b98808e432c45b5bc355e206274b3c91
refs/heads/master
<file_sep>package com.krayapp.weatherapp data class DataStorage(val name: String, val color: String) { }<file_sep>package com.krayapp.weatherapp import android.os.Bundle import android.widget.Button import android.widget.TextView import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { private lateinit var button1: Button private lateinit var button2: Button private lateinit var barsikButton: Button private lateinit var textview1: TextView private lateinit var textview2: TextView private lateinit var barsikView: TextView private var barsik = DataStorage("Barsik", "Red") private var counter1: Int = 0 private var counter2: Int = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) initViews() } private fun initViews() { button1 = findViewById(R.id.button1) button2 = findViewById(R.id.button2) barsikButton = findViewById(R.id.barsik_button) textview1 = findViewById(R.id.first_text) textview2 = findViewById(R.id.second_text) barsikView = findViewById(R.id.barsik_view) clickListener() } private fun clickListener() { barsikButton.setOnClickListener { barsikView.text = ("Name " + barsik.name + " Color " + barsik.color) } button1.setOnClickListener { counter1 += 1 textview1.text = counter1.toString() } button2.setOnClickListener { counter2 += 2 textview2.text = counter2.toString() } } }
e84b594584ef1a393acfee60471c55e026bec6af
[ "Kotlin" ]
2
Kotlin
januarydayfin/WeatherApp
ac741885d789df4651997fc33d7db3b7a3866c7e
ccc5ba7e4a430b9d3332c349cb7ea4cfa30894e5
refs/heads/master
<repo_name>tarikub/RavenSignalRTest<file_sep>/RavenSignalRTest/Models/Customer.cs ๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Web; namespace RavenSignalRTest.Models { public class Customer { public string FirstName { get; set; } public string LastName { get; set; } public string Address { get; set; } public string Region { get; set; } public Customer() { } } }<file_sep>/README.md RavenSignalRTest ================ Realtime data proessing with Sharded RavenDB and SignalR in ASP.MVC Application <file_sep>/RavenSignalRTest/App_Start/StartUp.Auth.cs ๏ปฟusing System; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin; using Owin; using RavenSignalRTest.Models; namespace RavenSignalRTest { public partial class Startup { public void ConfigureAuth(IAppBuilder app) { app.MapSignalR(); } } }<file_sep>/RavenSignalRTest/Services/SignalRTestHub.cs ๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Web; using Microsoft.AspNet.SignalR; using Microsoft.AspNet.SignalR.Hubs; using RavenSignalRTest.Models; using Raven.Client; using Raven.Client.Document; using Raven.Client.Indexes; namespace RavenSignalRTest.Services { [HubName("signalRTestHub")] public class SignalRTestHub : Hub { //Singleton customers object private static List<Customer> customers = new List<Customer>(); //First method that gets called when SignalR hub starts public override System.Threading.Tasks.Task OnConnected() { getCustomers(); return base.OnConnected(); } //Method that executes when hub reconnects public override System.Threading.Tasks.Task OnReconnected() { getCustomers(); return base.OnReconnected(); } //List of all customers (All Raven Shards) public void getCustomers() { IDocumentSession RavenSession = MvcApplication.Store.OpenSession(); customers = RavenSession.Query<Customer>().ToList(); //Broadcast to clients Send(); } //Add a new customer public void addCustomer(Customer customer) { IDocumentSession RavenSession = MvcApplication.Store.OpenSession(); RavenSession.Store(customer); RavenSession.SaveChanges(); //All new customer to the singleton list and broadcast new customer to all clients customers.Add(customer); Send(customer); } //Broadcast all customers public void Send() { // Call the addNewMessageToPage method to update clients. var context = GlobalHost.ConnectionManager.GetHubContext<SignalRTestHub>(); context.Clients.All.allCustomers(customers); } //Overloaded method to send one customer public void Send(Customer customer) { var context = GlobalHost.ConnectionManager.GetHubContext<SignalRTestHub>(); var newCustomer = new List<Customer>(); newCustomer.Add(customer); context.Clients.All.allCustomers(newCustomer); } } }<file_sep>/RavenSignalRTest/Controllers/BaseController.cs ๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Raven.Client; using Raven.Client.Document; using Raven.Client.Indexes; namespace RavenSignalRTest.Controllers { //Global controller public class BaseController : Controller { } }<file_sep>/RavenSignalRTest/Global.asax.cs ๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; using System.Reflection; using Raven.Client.Embedded; using Raven.Client.Document; using Raven.Client.Indexes; using Raven.Client.Shard; using Raven.Client; using RavenSignalRTest.Models; namespace RavenSignalRTest { public class MvcApplication : System.Web.HttpApplication { public static IDocumentStore Store; protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); //File based sharding example for customer data var shards = new Dictionary<string, IDocumentStore> { {"North America", new EmbeddableDocumentStore { DataDirectory = "App_Data\\North-America" }}, {"Europe", new EmbeddableDocumentStore { DataDirectory = "App_Data\\Europe" }}, {"Asia", new EmbeddableDocumentStore { DataDirectory = "App_Data\\Asia" }}, {"Australia", new EmbeddableDocumentStore { DataDirectory = "App_Data\\Australia" }}, }; var shardStrategy = new ShardStrategy(shards) .ShardingOn<Customer>(customer => customer.Region); Store = new ShardedDocumentStore(shardStrategy).Initialize(); IndexCreation.CreateIndexes(Assembly.GetCallingAssembly(), Store); } } }
8f0c255619acb661345baff261374d1cdae2d0cd
[ "Markdown", "C#" ]
6
C#
tarikub/RavenSignalRTest
39e3bb4932a1f08b84eec6d84e7d62847a30007d
285440238bd7848961fde05cd2705a7105e10e8c
refs/heads/master
<repo_name>eriksonJAguiar/Data_Science<file_sep>/Fase_1_analise/code/House_Prices.r library(ggplot2) library(ggcorrplot) library(moments) #--------- lendo a base-------- datas <- read.csv(file="~/Desktop/Data_Science/Fase_1_analise/train.csv", header=TRUE, sep=",") #extra as variaveis simbolicas datas_num <- datas[sapply(datas, is.numeric)] #extra as variaveis simbolicas data_simb <- datas[sapply(datas, is.object)] datas_num <- datas_num[ ,-1] #------ Calculando a correlaรงรฃo ------ #calcula a correlacao de todos corl_ger <- signif(cor(datas_num, method = "pearson"), 3) #plot o heatmap da correlacao geral ggcorrplot(corl_ger, type = "lower") #atributos com maior correlacao: GrLivArea, GarageCars, GarageArea, TotalBsmtSF, X1stFlrSF -> Quantitativos import_vars <- data.frame(datas_num$OverallQual,datas_num$GrLivArea, datas_num$GarageCars, datas_num$GarageArea, datas_num$TotalBsmtSF, datas_num$X1stFlrSF, datas_num$YearBuilt, datas_num$YearRemodAdd, datas_num$FullBath, datas_num$TotRmsAbvGrd ,datas_num$SalePrice) names(import_vars) <- c("OverallQual","GrLivArea", "GarageCars", "GarageArea", "TotalBsmtSF", "XstFlrSF", "YearBuilt", "YearRemodAdd", "FullBath", "TotRmsAbvGrd", "SalePrice") correlacao <- signif(cor(import_vars),3) #plot o heatmap da correlacao ggcorrplot(correlacao, type = "lower", lab=TRUE) ggsave("~/Desktop/Data_Science/Fase_1_analise/heatmap_Quant.jpg") #Aplicando testes quantitativos---------- #metricas para OverallQual print('-----OverallQual-------') ov <- c(median(datas_num$OverallQual),mean(datas_num$OverallQual),sd(datas_num$OverallQual),max(datas_num$OverallQual),min(datas_num$OverallQual),skewness(datas_num$OverallQual),kurtosis(datas_num$OverallQual)) ggplot(datas_num, aes(x=datas_num$OverallQual)) + geom_histogram(binwidth = density(datas_num$OverallQual)$bw, color="black", fill="red") + xlab(expression(bold('OverallQual'))) + ylab(expression(bold('Frequences'))) ggsave("~/Desktop/Data_Science/Fase_1_analise/hist_OverallQual.jpg") #metricas para GrLivArea print('-----GrLivArea-------') gr <- c(median(datas_num$GrLivArea),mean(datas_num$GrLivArea),sd(datas_num$GrLivArea),max(datas_num$GrLivArea),min(datas_num$GrLivArea),skewness(datas_num$GrLivArea),kurtosis(datas_num$GrLivArea)) ggplot(datas_num, aes(x=datas_num$GarageCars)) + geom_histogram(aes(y=..density.., fill=..count..), color="black", fill="red") + geom_density(colour = 'blue')+xlab(expression(bold('GrLivArea'))) + ylab(expression(bold('Frequences'))) ggsave("~~/Desktop/Data_Science/Fase_1_analise/hist_GrLivArea.jpg") #metricas para GarageCars print('-----GarageCars-------') grc <- c(median(datas_num$GarageCars),mean(datas_num$GarageCars),sd(datas_num$GarageCars),max(datas_num$GarageCars),min(datas_num$GarageCars),skewness(datas_num$GarageCars),kurtosis(datas_num$GarageCars)) ggplot(datas_num, aes(x=datas_num$GarageCars)) + geom_histogram(aes(y=..density.., fill=..count..), color="black", fill="red") + geom_density(colour = 'blue')+xlab(expression(bold('GarageCars'))) + ylab(expression(bold('Frequences'))) ggsave("~/Desktop/Data_Science/Fase_1_analise/hist_GarageCars.jpg") #metricas para GarageArea print('-----GarageArea-------') gra <- c(median(datas_num$GarageArea),mean(datas_num$GarageArea),sd(datas_num$GarageArea),max(datas_num$GarageArea),min(datas_num$GarageArea),skewness(datas_num$GarageArea),kurtosis(datas_num$GarageArea)) ggplot(datas_num, aes(x=datas_num$GarageArea)) + geom_histogram(aes(y=..density.., fill=..count..), color="black", fill="red") + geom_density(colour = 'blue')+xlab(expression(bold('GarageArea'))) + ylab(expression(bold('Frequences'))) ggsave("~/Desktop/Data_Science/Fase_1_analise/hist_GarageCars.jpg") #metricas para TotalBsmtSF print('-----TotalBsmtSF-------') tbsf <- c(median(datas_num$TotalBsmtSF),mean(datas_num$TotalBsmtSF),max(datas_num$TotalBsmtSF),min(datas_num$TotalBsmtSF),skewness(datas_num$TotalBsmtSF),kurtosis(datas_num$TotalBsmtSF)) ggplot(datas_num, aes(x=datas_num$TotalBsmtSF)) + geom_histogram(aes(y=..density.., fill=..count..), color="black", fill="red") + geom_density(colour = 'blue')+xlab(expression(bold('TotalBsmtSF'))) + ylab(expression(bold('Frequences'))) ggsave("~/Desktop/Data_Science/Fase_1_analise/hist_TotalBsmtSF.jpg") #metricas para X1stFlrSF print('-----1stFlrSF-------') stf <- c(median(datas_num$X1stFlrSF),mean(datas_num$X1stFlrSF),sd(datas_num$X1stFlrSF),max(datas_num$X1stFlrSF),min(datas_num$X1stFlrSF),skewness(datas_num$X1stFlrSF),kurtosis(datas_num$X1stFlrSF)) ggplot(datas_num, aes(x=datas_num$X1stFlrSF)) + geom_histogram(aes(y=..density.., fill=..count..), color="black", fill="red") + geom_density(colour = 'blue')+xlab(expression(bold('X1stFlrSF'))) + ylab(expression(bold('Frequences'))) ggsave("~/Desktop/Data_Science/Fase_1_analise/hist_1stFlrSF.jpg") #metricas para YearBuilt print('-----YearBuilt-------') yb <- c(median(datas_num$YearBuilt),mean(datas_num$YearBuilt),sd(datas_num$YearBuilt),max(datas_num$YearBuilt),min(datas_num$YearBuilt),skewness(datas_num$YearBuilt),kurtosis(datas_num$YearBuilt)) ggplot(datas_num, aes(x=datas_num$YearBuilt)) + geom_histogram(binwidth = density(datas_num$YearBuilt)$bw, color="black", fill="red") + xlab(expression(bold('YearBuilt'))) + ylab(expression(bold('Frequences'))) ggsave("~/Desktop/Data_Science/Fase_1_analise/hist_YearBuilt.jpg") #metricas para YearRemodAdd print('-----YearRemodAdd-------') ya <- c(median(datas_num$YearRemodAdd),mean(datas_num$YearRemodAdd),sd(datas_num$YearRemodAdd),max(datas_num$YearRemodAdd),min(datas_num$YearRemodAdd),skewness(datas_num$YearRemodAdd),kurtosis(datas_num$YearRemodAdd)) ggplot(datas_num, aes(x=datas_num$YearRemodAdd)) + geom_histogram(binwidth = density(datas_num$YearRemodAdd)$bw, color="black", fill="red") + xlab(expression(bold('YearRemodAdd'))) + ylab(expression(bold('Frequences'))) ggsave("~/Desktop/Data_Science/Fase_1_analise/hist_YearRemodAdd.jpg") #metricas para FullBath print('-----FullBath-------') fb <- c(median(datas_num$FullBath),mean(datas_num$FullBath),sd(datas_num$FullBath),max(datas_num$FullBath),min(datas_num$FullBath),skewness(datas_num$FullBath),kurtosis(datas_num$FullBath)) ggplot(datas_num, aes(x=datas_num$FullBath)) + geom_histogram(binwidth = density(datas_num$FullBath)$bw, color="black", fill="red") + xlab(expression(bold('FullBath'))) + ylab(expression(bold('Frequences'))) ggsave("~/Desktop/Data_Science/Fase_1_analise/hist_FullBath.jpg") #metricas para TotRmsAbvGrd print('-----TotRmsAbvGrd-------') rgd <- c(median(datas_num$TotRmsAbvGrd),mean(datas_num$TotRmsAbvGrd),sd(datas_num$TotRmsAbvGrd),max(datas_num$TotRmsAbvGrd),min(datas_num$TotRmsAbvGrd),skewness(datas_num$TotRmsAbvGrd),kurtosis(datas_num$TotRmsAbvGrd)) ggplot(datas_num, aes(x=datas_num$TotRmsAbvGrd)) + geom_histogram(binwidth = density(datas_num$TotRmsAbvGrd)$bw, color="black", fill="red") + xlab(expression(bold('TotRmsAbvGrd'))) + ylab(expression(bold('Frequences'))) ggsave("~/Desktop/Data_Science/Fase_1_analise/hist_TotRmsAbvGrd.jpg") #metricas para SalePrice print('-----SalePrice-------') sale <- c(median(datas_num$SalePrice),mean(datas_num$SalePrice),sd(datas_num$SalePrice),max(datas_num$SalePrice),min(datas_num$SalePrice),skewness(datas_num$SalePrice),kurtosis(datas_num$SalePrice)) ggplot(datas_num, aes(x=datas_num$SalePrice)) + geom_histogram(aes(y=..density.., fill=..count..), color="black", fill="red") + geom_density(colour = 'blue')+xlab(expression(bold('SalePrices'))) + ylab(expression(bold('Frequences'))) ggsave("~/Desktop/Data_Science/Fase_1_analise/hist_SalePrices.jpg") #juntandos dados met <- cbind(ov,gr,grc,gra,tbsf,stf,yb,ya,fb,rgd,sale) metrics <- data.frame(met) colnames(met) <- c("OverallQua","GrLivArea", "GarageCars", "GarageArea", "TotalBsmtSF", "1stFlrSF", "YearBuilt", "YearRemodAdd", "FullBath", "TotRmsAbvGrd", "SalePrice") rownames(metrics) <- c("median","mean","standard_deviation","max","min","skewness","kurtosis") write.csv(metrics, file = "~/Desktop/Data_Science/Fase_1_analise/metrics.csv", sep=";") #gerando boxplot para cada variavel ggplot(datas_num, aes(x = 1, y = datas_num$SalePrice)) + geom_boxplot() + xlab(expression(bold("OverallQual"))) + ylab(expression(bold("SalePrices"))) ggsave("~/Desktop/Data_Science/Fase_1_analise/boxplot_SalePrices_OverallQual.jpg") #------------Qualitativas------------------- #-----------Simbolic----------------------- #Plot grรกficos de barra para representar valor qualitativos jpeg(file="~/Desktop/Data_Science/Fase_1_analise/barra_Neighborhood.jpg") plot(data_simb$Neighborhood, col='red', las=2, ylab="Frequency", ylim=c(0,max(table(data_simb$Neighborhood)+30))) dev.off() jpeg(file="~/Desktop/Data_Science/Fase_1_analise/barra_Foundation.jpg") plot(data_simb$Foundation, col='red', las=2) dev.off() jpeg(file="~/Desktop/Data_Science/Fase_1_analise/barra_GarageType.jpg") plot(data_simb$GarageType, col='red',las=2) dev.off() jpeg(file="~/Desktop/Data_Science/Fase_1_analise/barra_KitchenQual.jpg") plot(data_simb$KitchenQual, col='red',las=2) dev.off() <file_sep>/Fase_2_preprocessamento/submissions/analyse_statistics.r #teste de shapiro wilk all_p <- shapiro.test(all_filters_submission$Saleprice)$p.value corr_p <- shapiro.test(corr_filter_submission$Saleprice)$p.value kbest_p <- shapiro.test(KBest_wrapper_submission$Saleprice)$p.value nan_p <- shapiro.test(KBest_wrapper_submission$Saleprice)$p.value rfe_p <- shapiro.test(rfe_wrapper$Saleprice)$p.value unb_p<- shapiro.test(unbalanced_filter$Saleprice)$p.value shapiro_df <- data.frame('al'=all_p, 'corr'=corr_p, 'kbest'=kbest_p, 'nan'=nan_p, 'rfe'=rfe_p, 'unb'=unb_p) value <- c(all_filters_submission$Saleprice,corr_filter_submission$Saleprice,KBest_wrapper_submission$Saleprice,KBest_wrapper_submission$Saleprice,rfe_wrapper$Saleprice,unbalanced_filter$Saleprice) n <- 6 k <- length(value)/n len <- length(value) z <- gl(n,k,len,labels = c('al','corr','kbest','nan','rfe','unb')) m <- matrix(value, nrow = k, ncol=n, byrow = TRUE, dimnames = list(1 : k,c('al','corr','kbest','nan','rfe','unb'))) f <- friedman.test(m) fp <- posthoc.friedman.nemenyi.test(m) nt <- NemenyiTest(value,z, out.list = TRUE)<file_sep>/trab_crimes/pre-processing/filters.py #!/usr/bin/env python # coding: utf-8 # In[1]: import pandas as pd import numpy as np import math from sklearn import preprocessing remov = {} remov["corr_filter"] = [] remov["nan_filter"] = [] remov["desc_filter"] = [] # In[2]: ''' filter: NaN values ''' def nan_filter(data): print(data.size) data = data.dropna() print(data.size) return data def obj_filter(data): obj_data = data.select_dtypes(include=['object']).copy() col = list(obj_data.columns) for i in range(len(col)): #if(col[i] == 'Calendar' or col[i] == 'Hour'): #data[col[i]] = pd.to_numeric(obj_data[col[i]]) #else: obj_data[col[i]] = obj_data[col[i]].astype('category') data[col[i]] = obj_data[col[i]].cat.codes return data def normalization(data): x = data.values #returns a numpy array min_max_scaler = preprocessing.MinMaxScaler() x_scaled = min_max_scaler.fit_transform(x) res = pd.DataFrame(x_scaled, columns= data.columns, index=data.index) return res # In[3]: <file_sep>/trab_crimes/Analysis_crimes.py import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np import gmplot import gmaps import ipywidgets as widgets import matplotlib.patches as pc import geopandas from shapely.geometry import Point import sys import os import math from sklearn import preprocessing args = sys.argv[1:] sns.set() def remove_objects(data): x = data['Primary Type'].value_counts() freq = pd.DataFrame() freq['index'] = x.index freq['values'] = x.values freq = freq.query('values > 800') return freq def plot_hist(data): freq = data index = freq['index'].tolist() values = freq['values'].tolist() plt.rcParams['figure.figsize'] = (17,15) indx = np.arange(len(index)).tolist() b = sns.barplot(x=values, y=indx, alpha=1, orient='h') b.set_xticklabels(values, fontsize=10,rotation=90) b.set_yticklabels(indx, fontsize=8) Boxes = [item for item in b.get_children() if isinstance(item, pc.Rectangle)][:-1] legend_patches = [pc.Patch(color=C, label=L) for C, L in zip([item.get_facecolor() for item in Boxes], index )] plt.title("Frequencia de crimes") plt.ylabel('Tipo de crime', fontsize=12) plt.xlabel('Numero de crimes', fontsize=12) plt.xlim(0, 1.05 * max(values)) plt.legend(handles=legend_patches) #plt.show() plt.savefig('crimes_freq.png', dpi=200) def drop_coord_nan(data): data = data.drop(columns=['X Coordinate', 'Y Coordinate']) #data[['X Coordinate', 'Y Coordinate']] = data[['X Coordinate', 'Y Coordinate']].replace(0, np.nan) data[['Latitude', 'Longitude']] = data[['Latitude', 'Longitude']].replace(0, np.nan) #data.dropna() #data = data.drop(columns=['X Coordinate','Y Coordinate']) data_rm = data[np.isnan(data['Latitude'])] data_rm = data[np.isnan(data['Longitude'])] index = data_rm.index.values.tolist() data = data.drop(index=index) return data def draw_map(data): lat = data['Latitude'].values longi = data['Longitude'].values gmap = gmplot.GoogleMapPlotter(41.8781, -87.6298, 16,apikey='') #gmap.plot(lat, longi, 'cornflowerblue', edge_width=10) #gmap.scatter(lat, longi, '#3B0B39', marker=True) #gmap.plot(lat, longi, 'cornflowerblue') #gmap.scatter(lat, longi, 'k', marker=True) gmap.heatmap(lat, longi) #gmap.marker(lat,longi) gmap.draw("heat_map.html") def correlation(data): c = data.corr() plt.rcParams['figure.figsize'] = (20,20) sns.heatmap(c, annot=True, linewidths=0.1) plt.title("Correlacao do tipo de crime") plt.savefig('heat_map.png', dpi=170) def crimes_time(data): #data = data[data['Year'] != 2017] freq = data['Year'].value_counts() plt.rcParams['figure.figsize'] = (14,14) plt.plot(freq.index,freq.values) plt.title("Criminalidade durantes os anos") plt.ylabel('Numero de crimes', fontsize=12) plt.xlabel('Ano', fontsize=12) plt.savefig('crimes_ano2.png', dpi=200) #plt.show() ''' filter: NaN values ''' def nan_filter(data): data = data.dropna() return data def obj_filter(data): obj_data = data.select_dtypes(include=['object']).copy() col = list(obj_data.columns) for i in range(len(col)): obj_data[col[i]] = obj_data[col[i]].astype('category') data[col[i]] = obj_data[col[i]].cat.codes return data def normalization(data): x = data.values #returns a numpy array min_max_scaler = preprocessing.MinMaxScaler() x_scaled = min_max_scaler.fit_transform(x) res = pd.DataFrame(x_scaled, columns= data.columns, index=data.index) return res def clean(data): new_data = nan_filter(data) new_data = obj_filter(new_data) new_data = normalization(new_data) return new_data if __name__ == '__main__': crimes = pd.read_csv('Chicago_Crimes_2012_to_2017.csv') global df_crimes global remov remov = {} remov["corr_filter"] = [] remov["nan_filter"] = [] remov["desc_filter"] = [] print(crimes.count()) if args[0] == 'correlacao': print('Calculando Correlacao ...') df_crimes = crimes.drop(columns=['Unnamed: 0','ID']) df_crimes = clean(df_crimes) correlation(df_crimes) print('Completo!') elif args[0] == 'hist': print('Plotando o grafico de barra ...') df_crimes = drop_coord_nan(crimes) freq = remove_objects(df_crimes) plot_hist(freq) print('Completo!') elif args[0] == 'maps': df_crimes = crimes.drop(columns=['Unnamed: 0','ID']) df_crimes = drop_coord_nan(crimes) draw_map(df_crimes) elif args[0] == 'time': df_crimes = crimes.drop(columns=['Unnamed: 0','ID']) df_crimes = drop_coord_nan(crimes) crimes_time(df_crimes) else: print('Processando tudo ...') df_crimes = crimes.drop(columns=['Unnamed: 0','ID']) correlation(df_crimes) df_crimes = drop_coord_nan(crimes) freq = remove_objects(df_crimes) plot_hist(crimes) print('Completo!')<file_sep>/Fase_2_preprocessamento/main.py import pandas as pd import numpy as np import math import seaborn as sns from sklearn import preprocessing from scipy import stats from pandas.api.types import is_numeric_dtype from scipy.stats import mode from sklearn.ensemble import ExtraTreesClassifier from sklearn.feature_selection import SelectFromModel from sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestRegressor from sklearn import preprocessing from sklearn.datasets import load_digits from sklearn.feature_selection import SelectKBest, chi2 from sklearn.ensemble import GradientBoostingRegressor from sklearn.base import clone pd.set_option('display.max_rows', 500) pd.set_option('display.max_columns', 500) pd.set_option('display.width', 1000) remov = {} remov["corr_filter"] = [] remov["nan_filter"] = [] remov["desc_filter"] = [] # Filter: NaN values def nan_filter(data): global remov nan_attr = {} sum_attr = data.isnull().sum() key = 0 for i in range(sum_attr.size): if (sum_attr.iloc[i] > 0): nan_attr[key] = [sum_attr.index[i], sum_attr.iloc[i]] key = key + 1 for i in range(len(nan_attr)): if (nan_attr[i][1] >= 0.75 * data[nan_attr[i][0]].value_counts(dropna=False).sum()): data = data.drop(columns=nan_attr[i][0]) remov["nan_filter"].append(nan_attr[i][0]) elif (data[nan_attr[i][0]].dtype == 'object'): data[nan_attr[i][0]] = data[nan_attr[i][0]].fillna(data[nan_attr[i][0]].mode().iloc[0]) else: data[nan_attr[i][0]] = data[nan_attr[i][0]].fillna(data[nan_attr[i][0]].mean()) return data # Filter: minimun correlation with target def corr_filter(data, target): global remov cor = data.corr() cor_target = abs(cor[target]) irrelevant_features = cor_target[cor_target < 0.6] data = data.drop(columns=irrelevant_features.index) remov["corr_filter"].append(irrelevant_features.index) return data # Filter: unbalanced classes def unbalanced_filter(data): global remov objects = [] classes_attr = {} for i in range(len(data.columns)): if (data[data.iloc[0].index[i]].dtype == "object"): objects.append(data.iloc[0].index[i]) for i in range(len(objects)): class_size = data[objects[i]].value_counts().size classes_attr[i] = [] for j in range(class_size): classes_attr[i].append(data[objects[i]].value_counts()[j]) for i in range(len(classes_attr)): if (sum(classes_attr[i][1:]) < classes_attr[i][0] / 2.5): remov["desc_filter"].append(objects[i]) data = data.drop(columns=objects[i]) return data def wrapper_rfe(data_new): feature_names = list(data_new.columns.values) # seleรงรฃo de atributos X = data_new X = X.drop('SalePrice', axis=1) y = data_new['SalePrice'] regr = RandomForestRegressor(max_depth=2, random_state=0, n_estimators=50) sel = RFE(regr, step=1) sel = sel.fit(X, y) attr = sorted(zip(map(lambda x: round(x, 4), sel.ranking_), feature_names)) # validaรงรฃo i = 0 atrib_sel = ['SalePrice'] while attr[i][0] <= 20: atrib_sel.append(attr[i][1]) i = i + 1 data_cor = data_new[atrib_sel] print(data_cor.corr().sort_values('SalePrice', ascending=False).index) return data_cor, y def wrapper_subconj_kbest(data, k=20): X = data X = X.drop('SalePrice', axis=1) y = data['SalePrice'] selected_features = SelectKBest(chi2, k).fit(X, y).get_support() return selected_features, y def remove_redundant(data): # Eliminando valores redundantes - data.drop_duplicates(inplace=True) ausentes = data.isnull() # Verificando colunas com NaN ausentes = pd.DataFrame(ausentes) col = list(data.columns.values) data_new = data for c in col: if len(data_new[c][data_new[c].isnull()]) != 0: if is_numeric_dtype(data_new[c]): mean = data_new[c].mean() data_new[c].fillna(mean, inplace=True) else: m = data_new[c].mode()[0] data_new[c].fillna(m, inplace=True) return data_new def transform_to_numeric(data, should_remove_redundant=False): if should_remove_redundant: data = remove_redundant(data) col = list(data.columns.values) # Tranformaรงรฃo dos atributos for c in col: le = preprocessing.LabelEncoder() if not is_numeric_dtype(data[c]): vals = data[c].unique() le.fit(vals) data[c] = le.transform(data[c]) return data def apply_filters(data, nan=False, corr=False, unbalanced=False, is_training_data=True): if nan: print("Nan filter...") data = nan_filter(data) print(len(data.columns)) if corr: if is_training_data: data = corr_filter(data, "SalePrice") print(len(data.columns)) if unbalanced: data = unbalanced_filter(data) print(len(data.columns)) return data def run_model_on_filters(model, data, test, nan_filter=False, corr_filter=False, unbalanced_filter=False): data = apply_filters(data, nan=nan_filter, corr=corr_filter, unbalanced=unbalanced_filter) test = apply_filters(test, nan=nan_filter, corr=corr_filter, unbalanced=unbalanced_filter, is_training_data=False) for column in test.columns: if column not in data.columns: test = test.drop(column, axis=1) print(test.shape, data.shape) data = transform_to_numeric(data, True) # put True for corr filter, False otherwise test = transform_to_numeric(test, True) data_y = data['SalePrice'] data_x = data.drop(['SalePrice'], axis=1) model.fit(data_x, data_y) predictions = model.predict(test) return predictions def run_model_on_rfe_wrapper(model, data, test): data = remove_redundant(data) data = transform_to_numeric(data) test = remove_redundant(test) test = transform_to_numeric(test) data_x, data_y = wrapper_rfe(data) print('RFE Wrapper:') for column in test.columns: if column not in data_x.columns: test = test.drop(column, axis=1) data_x = data_x.drop(['SalePrice'], axis=1) print(data_x.shape, test.shape) model.fit(data_x, data_y) predictions = model.predict(test) return predictions def run_model_on_wrapper_subconj_kbest(model, data, test): data = remove_redundant(data) data = transform_to_numeric(data) test = remove_redundant(test) test = transform_to_numeric(test) print('KBest Wrapper:') features, data_y = wrapper_subconj_kbest(data) features = list(features) print(features) to_drop = [] for k in range(len(features)): if not features[k]: to_drop.append(k) data = data.drop(data.columns[to_drop], axis=1) data = data.drop(['SalePrice'], axis=1) print(data.shape) model.fit(data, data_y) for column in test.columns: if column not in data.columns: test = test.drop(column, axis=1) predictions = model.predict(test) return predictions def run_model_no_filter_no_wrapper(model, data, test): data = remove_redundant(data) data = transform_to_numeric(data) test = remove_redundant(test) test = transform_to_numeric(test) data_y = data['SalePrice'] data = data.drop(['SalePrice'], axis=1) model.fit(data, data_y) test = test.drop(['Id'], axis=1) print(data.shape) print(test.shape) predictions = model.predict(test) return predictions def main(): data = pd.read_csv("train.csv") test = pd.read_csv('test.csv') test_ids = test['Id'] data = data.drop(columns='Id') print('Train shape:', data.shape) # prediction model: model = GradientBoostingRegressor( n_estimators=4864, learning_rate=0.05, max_depth=4, max_features='log2', min_samples_leaf=15, min_samples_split=10, loss='huber', random_state=5) predictions = run_model_on_filters(clone(model), data, test, nan_filter=True) submission = pd.DataFrame({'Id': test_ids, 'Saleprice': predictions}) submission.to_csv('submissions/nan_filter_submission.csv', index=False) print('Nan Filter - Submission file successfully created!') # NaN Filter predictions = run_model_on_filters(clone(model), data, test, nan_filter=True) submission = pd.DataFrame({'Id': test_ids, 'Saleprice': predictions}) submission.to_csv('submissions/nan_filter_submission.csv', index=False) print('Nan Filter - Submission file successfully created!') # Correlation filter predictions = run_model_on_filters(clone(model), data, test, corr_filter=True) submission = pd.DataFrame({'Id': test_ids, 'Saleprice': predictions}) submission.to_csv('submissions/corr_filter_submission.csv', index=False) print('Correlation Filter - Submission file successfully created!') # Unbalanced filter predictions = run_model_on_filters(clone(model), data, test, unbalanced_filter=True) submission = pd.DataFrame({'Id': test_ids, 'Saleprice': predictions}) submission.to_csv('submissions/unbalanced_filter_submission.csv', index=False) print('Unbalanced Filter - Submission file successfully created!') # All Filters predictions = run_model_on_filters(clone(model), data, test, nan_filter=True, corr_filter=True, unbalanced_filter=True) submission = pd.DataFrame({'Id': test_ids, 'Saleprice': predictions}) submission.to_csv('submissions/all_filters_submission.csv', index=False) print('All Filters - Submission file successfully created!') # Wrapper rfe predictions = run_model_on_rfe_wrapper(clone(model), data, test) submission = pd.DataFrame({'Id': test_ids, 'Saleprice': predictions}) submission.to_csv('submissions/rfe_wrapper_submission.csv', index=False) print('RFE Wrapper: - Submission file successfully created!') # Wrapper KBest predictions = run_model_on_wrapper_subconj_kbest(clone(model), data, test) submission = pd.DataFrame({'Id': test_ids, 'Saleprice': predictions}) submission.to_csv('submissions/KBest_wrapper_submission.csv', index=False) print('KBest Wrapper: - Submission file successfully created!') # No filter no wrapper predictions = run_model_no_filter_no_wrapper(clone(model), data, test) submission = pd.DataFrame({'Id': test_ids, 'Saleprice': predictions}) submission.to_csv('submissions/no_filter_wrapper_submission.csv', index=False) print('No Filter no Wrapper - Submission file successfully created!') if __name__ == '__main__': main()
4f5e021b245bf7f6e982c85ba9d2b3b98026a9e2
[ "Python", "R" ]
5
R
eriksonJAguiar/Data_Science
89937e9af3e81719fadedf53cc56b15caad66ffc
5f56b41cd16be9790524a26e242096eaa3011581
refs/heads/master
<repo_name>ArmandoPrieto/savioDonation<file_sep>/src/java/savioDonation/Donation.java package savioDonation; import java.util.logging.Level; import java.util.logging.Logger; import com.mes.sdk.core.Settings; import com.mes.sdk.exception.MesRuntimeException; import com.mes.sdk.gateway.CcData; import com.mes.sdk.gateway.Gateway; import com.mes.sdk.gateway.GatewayRequest; import com.mes.sdk.gateway.GatewayResponse; import com.mes.sdk.gateway.GatewaySettings; import com.mes.sdk.gateway.GatewayRequest.TransactionType; import com.mes.sdk.rbs.Rbs; import com.mes.sdk.rbs.RbsRequest; import com.mes.sdk.rbs.RbsResponse; import com.mes.sdk.rbs.RbsSettings; import com.mes.sdk.rbs.RbsRequest.PaymentFrequency; import com.mes.sdk.rbs.RbsRequest.PaymentType; import com.mes.sdk.rbs.RbsRequest.RequestType; import com.mes.sdk.test.MesTest; public class Donation extends MesTest{ private Rbs rbs; private RbsSettings rbsSettings; private Gateway gateway; private GatewaySettings settings; private final static Logger LOG = Logger.getLogger(Donation.class.getName()); private String profileId = "9410001209560000000400"; private String profileIdRBS = "9410001209560000000500"; private String profileKey = "<KEY>"; private String user = "941000120956RBS!!"; //private String pass = "<PASSWORD>"; private String pass = "<PASSWORD>!!"; public boolean sale(String firstName, String lastName, String address, String zip, String email, String phone, String cardNumber, String expDate, String cvv, String payment, String invoiceNumber, String clientReferenceNumber) { settings = new GatewaySettings(); settings.credentials(profileId, profileKey) .hostUrl(GatewaySettings.URL_LIVE) .method(Settings.Method.POST) .timeout(10000) .verbose(true); gateway = new Gateway(settings); try { GatewayRequest sRequest = new GatewayRequest(TransactionType.SALE) .cardData( new CcData() .setCcNum(cardNumber) .setExpDate(expDate) .setCvv(cvv) ) .amount(payment) .cardholderName(firstName, lastName) .cardholderAddress(address, zip) .cardholderEmail(email) //.cardholderPhone(phone) .setParameter("invoice_number", invoiceNumber) .setParameter("client_reference_number", clientReferenceNumber); GatewayResponse sResponse = gateway.run(sRequest); LOG.log(Level.INFO, sResponse.toString()); System.out.println(sResponse.toString()+" "+sResponse.getErrorCode()+" "+sResponse.getTransactionId()); return sResponse.isApproved(); } catch (MesRuntimeException e) { e.printStackTrace(); return false; } } public boolean cardCreateRecord(String custumerId, String cardNumber, String expDate, String address, String zipCode, String amount, String startDay, String startMonth, String startYear, String paymentCount) { rbsSettings = new RbsSettings() .credentials(user, pass, profileIdRBS) .hostUrl(RbsSettings.URL_LIVE) .verbose(true); rbs = new Rbs(rbsSettings); try { RbsRequest cRequest = new RbsRequest(RequestType.CREATE); cRequest.setCustomerId(custumerId) .setPaymentType(PaymentType.CC) .setFrequency(PaymentFrequency.MONTHLY) .setCardData(cardNumber, expDate) .setCardCustomerData(address, zipCode) .setStartDate(startMonth,startDay , startYear) .setAmount(amount) .setPaymentCount(paymentCount); RbsResponse cResponse = rbs.run(cRequest); LOG.log(Level.INFO, cResponse.toString()); System.out.println( cResponse.toString()+" "+cResponse.getErrorCode() + " "+cResponse.getResponseText()); if(cResponse.requestSuccessful()) { // Store Results return true; } } catch (MesRuntimeException e) { e.printStackTrace(); } return false; } public boolean cardDeleteRecord(String custumerId) { rbsSettings = new RbsSettings() .credentials(user, pass, profileIdRBS) .hostUrl(RbsSettings.URL_LIVE) .verbose(true); rbs = new Rbs(rbsSettings); try { RbsRequest cRequest = new RbsRequest(RequestType.DELETE); cRequest.setCustomerId(custumerId); RbsResponse cResponse = rbs.run(cRequest); LOG.log(Level.INFO, cResponse.toString()); if(cResponse.requestSuccessful()) { // Store Results return true; } } catch (MesRuntimeException e) { e.printStackTrace(); } return false; } public boolean cardInquireRecord(String custumerId) { rbsSettings = new RbsSettings() .credentials(user, pass, profileIdRBS) .hostUrl(RbsSettings.URL_LIVE) .verbose(true); rbs = new Rbs(rbsSettings); try { RbsRequest cRequest = new RbsRequest(RequestType.INQUIRY); cRequest.setCustomerId(custumerId); RbsResponse cResponse = rbs.run(cRequest); LOG.log(Level.INFO, cResponse.toString()); if(cResponse.requestSuccessful()) { // Store Results return true; } } catch (MesRuntimeException e) { e.printStackTrace(); } return false; } public boolean cardUpdateRecord(String custumerId, String cardNumber, String expDate, String address, String zipCode, String amount, String startDay, String startMonth, String startYear, String paymentCount) { rbsSettings = new RbsSettings() .credentials(user, pass, profileIdRBS) .hostUrl(RbsSettings.URL_LIVE) .verbose(true); rbs = new Rbs(rbsSettings); try { RbsRequest cRequest = new RbsRequest(RequestType.UPDATE); cRequest.setCustomerId(custumerId) .setCardData(cardNumber, expDate) .setCardCustomerData(address, zipCode) .setNextDate(startMonth, startDay, startYear) .setAmount(amount) .setPaymentCount(paymentCount); RbsResponse cResponse = rbs.run(cRequest); LOG.log(Level.INFO, cResponse.toString()); System.out.println(cResponse.toString() +" "+cResponse.getErrorCode() + " "+cResponse.getResponseText()); if(cResponse.requestSuccessful()) { // Store Results return true; } } catch (MesRuntimeException e) { e.printStackTrace(); } return false; } /* public String storeCard(){ settings = new GatewaySettings(); settings.credentials(profileId, profileKey) .hostUrl(GatewaySettings.URL_LIVE) .method(Settings.Method.POST) .timeout(10000) .verbose(true); gateway = new Gateway(settings); try { GatewayRequest sRequest = new GatewayRequest(TransactionType.TOKENIZE) .cardData( new CcData() .setCcNum("4012888812348882") .setExpDate("1212") ) .setParameter("client_reference_number", "Java SDK Test"); GatewayResponse sResponse = gateway.run(sRequest); LOG.log(Level.INFO, sResponse.toString()); System.out.println(sResponse.toString()+" "+sResponse.getTransactionId()+" "+sResponse.getErrorCode()); return sResponse.getTransactionId(); } catch (MesRuntimeException e) { e.printStackTrace(); } return ""; } */ /* public void deStoreCard(String cardStoreId){ settings = new GatewaySettings(); settings.credentials(profileId, profileKey) .hostUrl(GatewaySettings.URL_LIVE) .method(Settings.Method.POST) .timeout(10000) .verbose(true); gateway = new Gateway(settings); try { GatewayRequest dRequest = new GatewayRequest(TransactionType.DETOKENIZE) .cardData( new CcData() .setToken(cardStoreId) //cardToken ) .setParameter("client_reference_number", "Java SDK Test"); GatewayResponse dResponse = gateway.run(dRequest); LOG.log(Level.INFO, dResponse.toString()); System.out.println("deStoreCard "+dResponse.toString()); } catch (MesRuntimeException e) { e.printStackTrace(); } } */ @Override public void run() { // TODO Auto-generated method stub } } <file_sep>/web-app/j-forms-advanced/documentation/index.html <!doctype html> <!--[if IE 6 ]><html lang="en-us" class="ie6"> <![endif]--> <!--[if IE 7 ]><html lang="en-us" class="ie7"> <![endif]--> <!--[if IE 8 ]><html lang="en-us" class="ie8"> <![endif]--> <!--[if (gt IE 7)|!(IE)]><!--> <html lang="en-us"><!--<![endif]--> <head> <meta charset="utf-8"> <title>Just Forms advanced - Form Framework</title> <meta name="description" content=""> <meta name="author" content="LazyCode"> <meta name="copyright" content="LazyCode"> <meta name="generator" content="Documenter v2.0 http://rxa.li/documenter"> <meta name="date" content="2014-12-10T00:00:00+01:00"> <link rel="stylesheet" href="assets/css/documenter_style.css" media="all"> <link rel="stylesheet" href="assets/js/google-code-prettify/prettify.css" media="screen"> <script src="assets/js/google-code-prettify/prettify.js"></script> <link rel="shortcut icon" type="image/x-icon" href="j-forms.ico" /> <script src="assets/js/jquery.js"></script> <script src="assets/js/jquery.scrollTo.js"></script> <script src="assets/js/jquery.easing.js"></script> <script>document.createElement('section');var duration='500',easing='swing';</script> <script src="assets/js/script.js"></script> <style> html{background-color:#EEEEEE;color:#383838;} ::-moz-selection{background:#333636;color:#00DFFC;} ::selection{background:#333636;color:#00DFFC;} #documenter_sidebar #documenter_logo{background-image:url(assets/images/image_1.png);} a{color:#008C9E;} .btn { border-radius:3px; } .btn-primary { background-image: -moz-linear-gradient(top, #008C9E, #006673); background-image: -ms-linear-gradient(top, #008C9E, #006673); background-image: -webkit-gradient(linear, 0 0, 0 008C9E%, from(#343838), to(#006673)); background-image: -webkit-linear-gradient(top, #008C9E, #006673); background-image: -o-linear-gradient(top, #008C9E, #006673); background-image: linear-gradient(top, #008C9E, #006673); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#008C9E', endColorstr='#006673', GradientType=0); border-color: #006673 #006673 #bfbfbf; color:#FFFFFF; } .btn-primary:hover, .btn-primary:active, .btn-primary.active, .btn-primary.disabled, .btn-primary[disabled] { border-color: #008C9E #008C9E #bfbfbf; background-color: #006673; } hr{border-top:1px solid #D4D4D4;border-bottom:1px solid #FFFFFF;} #documenter_sidebar, #documenter_sidebar ul a{background-color:#343838;color:#FFFFFF;} #documenter_sidebar ul a{-webkit-text-shadow:1px 1px 0px #494F4F;-moz-text-shadow:1px 1px 0px #494F4F;text-shadow:1px 1px 0px #494F4F;} #documenter_sidebar ul{border-top:1px solid #212424;} #documenter_sidebar ul a{border-top:1px solid #494F4F;border-bottom:1px solid #212424;color:#FFFFFF;} #documenter_sidebar ul a:hover{background:#333636;color:#00DFFC;border-top:1px solid #333636;} #documenter_sidebar ul a.current{background:#333636;color:#00DFFC;border-top:1px solid #333636;} #documenter_copyright{display:block !important;visibility:visible !important;} </style> </head> <body class="documenter-project-b-check-forms"> <div id="documenter_sidebar"> <a href="#documenter_cover" id="documenter_logo"></a> <ul id="documenter_nav"> <li><a class="current" href="#documenter_cover">Start</a></li> <li><a href="#intro" title="Intro">Intro</a></li> <li><a href="#quick_installation" title="Quick Installation">Quick Installation</a></li> <li><a href="#html_structure" title="HTML Structure">HTML Structure</a></li> <li><a href="#css_structure" title="CSS Structure">CSS Structure</a></li> <li><a href="#js_structure" title="JS Structure">JS Structure</a></li> <li><a href="#js_plugin" title="JS Plugins">JS Plugins</a></li> <li><a href="#js_additions" title="JS Additions">JS Additions</a></li> <li><a href="#modal_form" title="Modal Form">Modal Form</a></li> <li><a href="#multistep_form" title="Multistep Form">Multistep Form</a></li> <li><a href="#multistep_form_logic" title="Multistep Form with Logic">Multistep Form with Logic</a></li> <li><a href="#order_logic" title="Order Form with Calculations">Order Form with Calculations</a></li> <li><a href="#popup_form" title="Popup Form">Popup Form</a></li> <li><a href="#foot_head_form" title="W/o footer header Form">W/o footer header Form</a></li> <li><a href="#js_validation" title="JS Validation">JS Validation</a></li> <li><a href="#new_form" title="New Form">New Form</a></li> <li><a href="#few_forms" title="Several Forms at One Page">Several Forms at One Page</a></li> <li><a href="#extensions" title="Extensions">Extensions</a></li> <li><a href="#faq" title="FAQ">FAQ</a></li> <li><a href="#changelog" title="Changelog">Changelog</a></li> <li><a href="#credits" title="Credits">Credits</a></li> </ul> </div> <div id="documenter_content"> <section id="documenter_cover"> <h1>Just Forms</h1> <h2 style="margin-bottom:0;">advanced version</h2> <h2>v 2.0</h2> <h2>Form Framework</h2> <hr> <ul> <li>created: 0415/2015</li> <li>latest update: 08/13/2015</li> <li>by: LazyCode</li> </ul> <p>Thank you for purchasing <strong>Just Forms advanced</strong>. If you have any questions that are beyond the scope of this help file, please feel free to email me via contact form in my <a target="_blank" href="http://codecanyon.net/user/lazycode?ref=lazycode">profile page</a>.</p> </section> <section id="intro"> <div class="page-header"><h3>Intro</h3><hr class="notop"></div> <h4 id="intro_folder_organization">Folder organization:</h4> <div> <p> If you`re reading this line, this means that you already unzipped the downloaded package from CodeCanyon. Now, in the extracted package you will find a folder named &quot;<strong>source</strong>&quot;. When you open this folder you will find 3 folders:</p> <ul> <li> <strong>extensions</strong> - contains extensions and additions; </li> <li> <strong>forms</strong> - contains ready-to-use forms with client-side validation; </li> <li> <strong>templates</strong> - contains ready-to-use templates that will help you to create your forms </li> </ul> <h4 id="intro_basic_html_structure">Basic HTML structure:</h4> <p style="margin-left: 40px;"> In general, HTML structure of any form should look like below:</p> <img alt="html structure" src="assets/images/html_structure.png" style="margin-left: 40px;"> </div> <h4 id="intro_basic_css_structure">Basic CSS structure:</h4> <p style="margin-left: 40px;"> All CSS code is in files:</p> <img alt="html structure" src="assets/images/css_structure.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">In the <strong>Just Forms advanced</strong> only <strong>j-forms.css</strong> file is required. It contains all css settings including default color settings. If you want to use Font Awesome icons in your form - you have to add appropriate CSS file in the "head" section of your html page.</p> <p style="margin-left: 40px;">All forms have "indigo" color as default color. But you can select any color from available in the <strong>css</strong> folder. To change form color you have to add css file with color settings. Also, you have to add a "color" class to the form. Pay attention that "color" class has to be equal to the css file name. For instance, take a look to the picture below:</p> <img alt="html structure" src="assets/images/new_color.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">So, if you have several forms at one page - you can configure color for all forms. Just connect css files with color settings and add "color" classes to the forms.</p> <h4 id="intro_basic_js_structure">Basic JS structure:</h4> <p style="margin-left: 40px;">If you want to use some extra fields (date pickers, phone masking, etc.) - you have to add appropriate js scripts to the "head" section of your html page. More info - in the &quot;<strong>JS Plugins</strong>&quot; section.</p> <img alt="html structure" src="assets/images/js_structure.png" style="margin-left: 40px;" > </section> <section id="quick_installation"> <div class="page-header"><h3>Quick Installation</h3><hr class="notop"></div> <p><strong>Just Forms full</strong> contains a wide selection of forms and templates. You can choose any template from the folder &quot;<strong>templates/</strong>&quot;. You can choose any form from the folder &quot;<strong>forms/</strong>&quot;. All templates and forms are ready to use and you can easily add it to your website. For example, we will add &quot;<strong>booking</strong>&quot; form / template to an exemplary site.</p> <h4> <strong>Case 1: Add form/template like a new html page</strong></h4> <h5> <strong>Copy files</strong></h5> <p style="margin-left: 40px;">You have to copy <strong>j-folder</strong> and selected form / template to your website.</p> <p style="margin-left: 40px;">Template files:</p> <img alt="html structure" src="assets/images/copy_folder.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">Form files:</p> <img alt="html structure" src="assets/images/copy_folder_form1.png" style="margin-left: 40px;" > <img alt="html structure" src="assets/images/copy_folder_form2.png" style="margin-left: 40px;" > <p style="margin-left: 40px;"><strong>j-folder</strong> contains all files for proper form / template displaying. <strong>j-folder</strong> has next folder structure:</p> <ul style="margin-left: 40px;"> <li> <strong>&quot;css/&quot;</strong> - folder contains CSS files;</li> <li> <strong>&quot;fonts/&quot;</strong> - folder contains Font Awesome fonts. It is required folder for proper icons displaying;</li> <li> <strong>&quot;img/&quot;</strong> - folder contains image for site background. These image required only for demonstration purpose and should not be copied to the server;</li> <li> <strong>&quot;js/&quot;</strong> - folder contains JavaScript files and libraries. This folder is required;</li> <li> <strong>&quot;php/&quot;</strong> - required folder that contains PHP files.</li> </ul> <p style="margin-left: 40px;">Now, your form/template is ready to use.</p> <h4> <strong>Case 2: Add form/template to an existing html page</strong></h4> <h5> <strong>HTML markup</strong></h5> <p style="margin-left: 40px;">First, you have to add necessary js scripts and files in the "head" section of your html page.</p> <img alt="html structure" src="assets/images/instal_2.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">Second, you have to copy form to the html page. The form is placed in the "div" with <strong>class=&quot;wrapper wrapper-640&quot;</strong>. More about form elements in the <strong>"HTML Structure"</strong> section.</p> <img alt="html structure" src="assets/images/instal_3.png" style="margin-left: 40px;" > <h5> <strong>Copy files</strong></h5> <p style="margin-left: 40px;">You have to copy <strong>j-folder</strong> to your website.</p> <p style="margin-left: 40px;">Template files:</p> <img alt="html structure" src="assets/images/instal_4.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">Form files:</p> <img alt="html structure" src="assets/images/instal_5.png" style="margin-left: 40px;" > <img alt="html structure" src="assets/images/instal_6.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">Now, your form/template is ready to use.</p> <p>After you follow these steps form on your site will work properly and send emails to your email address. All forms from the <strong>"forms/"</strong> folder created similar. So any form can be added to your site by following these steps.</p> </section> <section id="html_structure"> <div class="page-header"><h3>HTML Structure</h3><hr class="notop"></div> <p> Let`s take a look to the HTML structure with more attention. All forms have similar structure so you don`t need to change a lot of code with other forms.</p> <h4 id="html_structure_grid_system">Grid sysโ€‹tem</h4> <p style="margin-left: 40px;"> Demo of the grid system: &quot;<strong>extensions/grid.html</strong>&quot;</p> <p style="margin-left: 40px;"> All forms have responsive design. It works well for PC, tablets, mobile.</p> <p style="margin-left: 40px;"> Grid system is used for creating form layouts through a series of rows and columns which include your form elements.&nbsp;</p> <ol style="margin-left: 40px;"> <li style="margin-left: 40px;"> Use rows <strong>class=&quot;j-row&quot;</strong> to create horizontal groups of columns <strong>class=&quot;span&quot;</strong></li> <li style="margin-left: 40px;"> Content should be placed within columns</li> <li style="margin-left: 40px;"> Column classes <strong>class=&quot;span&quot;</strong> have to immediately be followed by a column number such as 6, so the entire class will look like this <strong>class=&quot;span6&quot;</strong></li> <li style="margin-left: 40px;"> <strong>class=&quot;offset&quot;</strong>&nbsp;- class that allows you to make some offsets before or between columns</li> <li style="margin-left: 40px;"> Offset classes&nbsp;<strong>class=&quot;offset&quot;</strong>&nbsp;have to immediately be followed by an offset number such as 4, so the entire class will look like this&nbsp;<strong>class=&quot;offset4&quot;</strong></li> <li style="margin-left: 40px;"> Grid form columns are created by specifying the number of twelve available columns you wish to span.&nbsp;</li> </ol> <p style="margin-left: 40px;"> A combination of all columns in a row have to add up to 12.</p> <p style="margin-left: 40px;"> For example:</p> <ul> <li style="margin-left: 80px;"> two equal columns: span6 + span6 = 12</li> <li style="margin-left: 80px;"> one right side column: offset6 + span6 = 12</li> <li style="margin-left: 80px;"> six&nbsp;equal columns: span2 + span2 + span2 + span2 + span2 + span2 = 12</li> <li style="margin-left: 80px;"> one center column: offset3 + span6 + offset3 = 12</li> <li style="margin-left: 80px;"> three unequal columns: span3 + span4 + span5 = 12</li> </ul> <p style="margin-left: 40px;">For instance, take a look to the pictures below:</p> <img alt="html structure" src="assets/images/span2.png" style="margin-left: 40px;"> <img alt="html structure" src="assets/images/span3.png" style="margin-left: 40px;" > <img alt="html structure" src="assets/images/span1.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">If you want to create an element that will be over the entire width of the form - you don't need to use <strong>class=&quot;j-row&quot;</strong>. Just wrap your element in <strong>class=&quot;unit&quot;</strong>. More about <strong>class=&quot;unit&quot;</strong> - in the next section.</p> <img alt="html structure" src="assets/images/span4.png" style="margin-left: 40px;" > <h4 id="html_structure_elements">Elements</h4> <p style="margin-left: 40px;"> Demo of the elements: &quot;<strong>extensions/elements.html</strong>&quot;</p> <h5> <strong>Form wrapper</strong></h5> <img alt="html structure" src="assets/images/wrapper.png" style="margin-left: 40px;" > <p style="margin-left: 40px;"> <strong>class=&quot;bg-pic&quot; -</strong>&nbsp;<span style="font-size: 12px;">this class required only for demonstration purpose. It sets site background.</span></p> <p style="margin-left: 40px;"> <strong>class=&quot;wrapper&quot;</strong> - wrapper-class for all forms.</p> <p style="margin-left: 40px;"> <strong>class=&quot;wrapper-400&quot; / class=&quot;wrapper-640&quot; - </strong>this class sets the width of the form. You can toggle these classes and thereby toggle form width:</p> <ul style="margin-left: 40px;"> <li style="margin-left: 40px;"> <strong>class=&quot;wrapper-400&quot;</strong>&nbsp;- 400px</li> <li style="margin-left: 40px;"> <strong>class=&quot;wrapper-640&quot;</strong>&nbsp;- 640px</li> </ul> <h5> <strong>"Header" class</strong></h5> <p style="margin-left: 40px;">You can add a header to your form using this class.</p> <img alt="html structure" src="assets/images/header_1.png" style="margin-left: 40px;" > <p style="margin-left: 40px;"><strong>"Header"</strong> class has to be added before <strong>"content"</strong> class in the html markup.</p> <p style="margin-left: 40px;">If you want to add an icon to your header - just add a line with icon.</p> <img alt="html structure" src="assets/images/header_2.png" style="margin-left: 40px;" > <h5> <strong>"Content" class</strong></h5> <p style="margin-left: 40px;">You should to add all form elements inside this class.</p> <img alt="html structure" src="assets/images/content.png" style="margin-left: 40px;" > <h5> <strong>"Footer" class</strong></h5> <p style="margin-left: 40px;">This class is used for buttons. Add your buttons inside this class.</p> <img alt="html structure" src="assets/images/footer.png" style="margin-left: 40px;" > <h5> <strong>Horizontal divider</strong></h5> <p style="margin-left: 40px;">Two types of dividers are allowed: line divider and text divider.</p> <img alt="html structure" src="assets/images/divider.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">Also, you can set the height for the gaps for dividers. Let's take a look to the css file:</p> <img alt="html structure" src="assets/images/divider_gap.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">So, you can select or 20px height gap, or 45px height gap.</p> <h5> <strong>"j-forms" class</strong></h5> <p style="margin-left: 40px;">This class is required for all forms. You have to add this class to any form for proper form displaying.</p> <img alt="html structure" src="assets/images/j-forms.png" style="margin-left: 40px;" > <h5> <strong>"unit" class</strong></h5> <p style="margin-left: 40px;">This class is required for creating indents between rows in the form. You can add this class to any element and this element will have bottom margin equal 25 pixels. Pay attention: these indents will remain on any device: PC, tablet or mobile. That's why <strong>class=&quot;unit&quot;</strong> can be used by several ways.</p> <p style="margin-left: 40px;"><strong>Case 1 - standalone element</strong></p> <p style="margin-left: 40px;">Add <strong>class=&quot;unit&quot;</strong> to every standalone element. This element will display separately from another form elements on any devices.</p> <img alt="html structure" src="assets/images/span3_u.png" style="margin-left: 40px;" > <img alt="html structure" src="assets/images/span3_unit.png" style="margin-left: 40px;" > <img alt="html structure" src="assets/images/span3_unit_mob.png" style="margin-left: 40px;" > <p style="margin-left: 40px;"><strong>Case 2 - group of elements</strong></p> <p style="margin-left: 40px;">Add <strong>class=&quot;unit&quot;</strong> to a group of elements (radio, checkbox, etc.) and this group will display without gaps on any device (any screen width).</p> <img alt="html structure" src="assets/images/unit_u.png" style="margin-left: 40px;" > <img alt="html structure" src="assets/images/unit_unit.png" style="margin-left: 40px;" > <img alt="html structure" src="assets/images/unit_unit_mob.png" style="margin-left: 40px;" > <h5> <strong>Text input</strong></h5> <img alt="html structure" src="assets/images/text_input.png" style="margin-left: 40px;" > <h5> <strong>Text input with left icon</strong></h5> <img alt="html structure" src="assets/images/text_input_icon.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">Pay attention to the <strong>class=&quot;icon-left&quot;</strong>. This class required for the left-side icons. For the right-side icons you have to add <strong>class=&quot;icon-right&quot;</strong>.</p> <p style="margin-left: 40px;">Also take a look to the <strong>&quot;for&quot;</strong> and <strong>&quot;id&quot;</strong> attributes. These attributes have to be equal if you want to make focus on the field when icon is clicked.</p> <p style="margin-left: 40px;"> Font Awesome - free library of icons - is used for icons.</p> <h5> <strong>Text input with icons and label</strong></h5> <img alt="html structure" src="assets/images/text_input_icon_label.png" style="margin-left: 40px;" > <p style="margin-left: 40px;"> More about icons and labels: &quot;<strong>extensions/icons_labels.html</strong>&quot;</p> <div class="alert alert-info" style="margin-left: 40px;"> <strong>Tips:</strong> if you want to add one label for whole row, no matter how many columns it has - add &quot;label&quot; before first <strong>class=&quot;span&quot;</strong>&nbsp;in the row.<strong>&nbsp;</strong>But if you need &quot;label&quot; for each column - add label after each <strong>class=&quot;span&quot;.</strong></div> <div> &nbsp;</div> <div style="margin-left: 40px;"> Label for a few columns:</div> <img alt="html structure" src="assets/images/label_row.png" style="margin-left: 40px;" > <p style="margin-left: 40px;"> Label for each column:</p> <img alt="html structure" src="assets/images/label_each_column.png" style="margin-left: 40px;" > <h5> <strong>Email and URL inputs</strong></h5> <img alt="html structure" src="assets/images/email_url.png" style="margin-left: 40px;" > <h5> <strong>Search and Textarea inputs</strong></h5> <img alt="html structure" src="assets/images/search_textarea.png" style="margin-left: 40px;" > <h5> <strong>Select input</strong></h5> <img alt="html structure" src="assets/images/select.png" style="margin-left: 40px;" > <h5> <strong>Link</strong></h5> <img alt="html structure" src="assets/images/link.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">Replace &quot;#&quot; in the &quot;href&quot; attribute with path to the &quot;terms of service&quot; document.</p> <h5> <strong>Tooltips</strong></h5> <p style="margin-left: 40px;"> Two types of tooltips are allowed: text tooltip and image tooltip. You can use tooltip with any input: text, textarea, select. For image tooltips don't forget to add images to the form and set proper path to these images. More about tooltips: &quot;<strong>extensions/tooltips.html</strong>&quot;</p> <img alt="html structure" src="assets/images/tooltip.png" style="margin-left: 40px;" > <h5> <strong>Note message</strong></h5> <img alt="html structure" src="assets/images/note_message.png" style="margin-left: 40px;" > <h5> <strong>Columned Checkbox and Radio</strong></h5> <img alt="html structure" src="assets/images/columned_checkbox.png" style="margin-left: 40px;" > <h5> <strong>Inline Checkbox and Radio</strong></h5> <img alt="html structure" src="assets/images/inline_checkbox.png" style="margin-left: 40px;" > <h5> <strong>Columned Toggles</strong></h5> <img alt="html structure" src="assets/images/columned_toggle.png" style="margin-left: 40px;" > <h5> <strong>Inline Toggles</strong></h5> <img alt="html structure" src="assets/images/inline_toggle.png" style="margin-left: 40px;" > <h5> <strong>Ratings</strong></h5> <img alt="html structure" src="assets/images/ratings.png" style="margin-left: 40px;" > <h5> <strong>File Buttons</strong></h5> <p style="margin-left: 40px;"> File upload button available in four variations.</p> <p style="margin-left: 40px;"> Prepend wide button:</p> <img alt="html structure" src="assets/images/prep_big_btn.png" style="margin-left: 40px;" > <p style="margin-left: 40px;"> Append wide button:</p> <img alt="html structure" src="assets/images/app_big_btn.png" style="margin-left: 40px;" > <p style="margin-left: 40px;"> Prepend narrow button and append narrow button:</p> <img alt="html structure" src="assets/images/narrow_btn.png" style="margin-left: 40px;" > <p style="margin-left: 40px;"> For multiple file inputs you will have to adjust the markup. For example, it should look like this:</p> <p><img alt="html structure" src="assets/images/multi_upload_btn.png" style="margin-left: 40px;" ></p> <div class="alert alert-info" style="margin-left: 40px;"> <strong>Notice:</strong> The &quot;onchange&quot;, the &quot;id&quot; and the &quot;name&quot; changed to &quot;file1&quot; and &quot;file2&quot;. &nbsp;</div> <h5> <strong>Buttons</strong></h5> <p style="margin-left: 40px;">Submit and Reset button are available.</p> <img alt="html structure" src="assets/images/btn.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">For primary button you have to add <strong>class=&quot;primary-btn&quot;</strong> to the button.</p> <p style="margin-left: 40px;">For secondary button you have to add <strong>class=&quot;secondary-btn&quot;</strong> to the button.</p> <p style="margin-left: 40px;">For processing button you have to add <strong>class=&quot;processing&quot;</strong> to the button.</p> <h5> <strong>Social buttons</strong></h5> <p style="margin-left: 40px;"> Demo for social buttons: &quot;<strong>extensions/social.html</strong>&quot;</p> <img alt="html structure" src="assets/images/social.png" style="margin-left: 40px;" > <p style="margin-left: 40px;"> For better user experience you may add social buttons to your form. &nbsp;<a href="https://www.google.com.ua/webhp?sourceid=chrome-instant&amp;ion=1&amp;espv=2&amp;ie=UTF-8#q=authorization+through+social+networks">Read more</a>&nbsp;about how you can make&nbsp;authorization through social networks.</p> <h5> <strong>Widget</strong></h5> <p style="margin-left: 40px;">You can use widget addons or widget buttons in your form. Widgets can be of of different widths: 50px and 130px. Also, widgets can be left-side and right-side.</p> <strong>Widget addon</strong> <p style="margin-left: 40px;">For instance, let's take a look to the html markup of narrow left-side widget addon:</p> <img alt="html structure" src="assets/images/widget_add_pic.png" style="margin-left: 40px;" > <img alt="html structure" src="assets/images/widget_add_html.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">As you can see, widget is created using <strong>class=&quot;widget&quot;</strong>. We set left padding for input using <strong>class=&quot;left-50&quot;</strong>. Widget addon is created using <strong>class=&quot;addon&quot;</strong>. Width and placement (left side or right side) of addon are configured by <strong>class=&quot;adn-50&quot;</strong> and <strong>class=&quot;adn-left&quot;</strong> accordingly. Pay attention that padding for the input has to be the same as addon width (in this example - 50px)</p> <p style="margin-left: 40px;">Html markup for wide right-side widget addon</p> <img alt="html structure" src="assets/images/widget_add_pic_wide.png" style="margin-left: 40px;" > <img alt="html structure" src="assets/images/widget_add_html_wide.png" style="margin-left: 40px;" > <p><strong>Widget button</strong></p> <p style="margin-left: 40px;">All rules for widget addons are suitable for widget buttons. But widget button is created using <strong>class=&quot;addon-btn&quot;</strong>.</p> <p style="margin-left: 40px;">Html markup for wide left-side widget button</p> <img alt="html structure" src="assets/images/widget_btn_pic_wide.png" style="margin-left: 40px;" > <img alt="html structure" src="assets/images/widget_btn_html_wide.png" style="margin-left: 40px;" > <h5> <strong>Captcha</strong></h5> <p style="margin-left: 40px;"> This is a simple PHP session captcha which you can use to reduce spamming activity on your forms. Main idea: PHP server creates an image with a sum of the digits and outputs this image to the html page. User has to enter valid sum of the digits. jQuery Validation Plugin uses "remote" method to validate the captcha. More info about validation methods - in the <strong>&quot;JS Validation&quot;</strong> section.</p> <img alt="html structure" src="assets/images/captcha.png" style="margin-left: 40px;" > <h5> <strong>Disabled state</strong></h5> <p style="margin-left: 40px;"> Demo for disabled state: &quot;<strong>extensions/disable_state.html</strong>&quot;</p> <p style="margin-left: 40px;">You can make any form element disabled. Just add <strong>class=&quot;disabled-view&quot;</strong> and <strong>&quot;disabled&quot;</strong> attribute to the element. HTML markup for the disabled text input:</p> <img alt="html structure" src="assets/images/disabled_view.png" style="margin-left: 40px;" > <h5> <strong>Error state</strong></h5> <p style="margin-left: 40px;"> Demo for error state: &quot;<strong>extensions/error_state.html</strong>&quot;</p> <p style="margin-left: 40px;"> HTML markup for error message:&nbsp;</p> <img alt="html structure" src="assets/images/error_message.png" style="margin-left: 40px;" > <p style="margin-left: 40px;"> HTML markup for input field with error state:</p> <img alt="html structure" src="assets/images/error_view.png" style="margin-left: 40px;" > <p style="margin-left: 40px;"> The "span" with <strong>class=&quot;error-view&quot;</strong> contains error message for the some particular field.</p> <h5> <strong>Success state</strong></h5> <p style="margin-left: 40px;"> Demo for success state: &quot;<strong>extensions/success_state.html</strong>&quot;</p> <p style="margin-left: 40px;"> HTML markup for success message:&nbsp;</p> <img alt="html structure" src="assets/images/success_message.png" style="margin-left: 40px;" > <p style="margin-left: 40px;"> HTML markup for input field with success state:</p> <img alt="html structure" src="assets/images/success_view.png" style="margin-left: 40px;" > <p style="margin-left: 40px;"> The "span" with <strong>class=&quot;success-view&quot;</strong> contains success message for the some particular field.</p> <h5> <strong>Info state</strong></h5> <p style="margin-left: 40px;"> Demo for info state: &quot;<strong>extensions/info_state.html</strong>&quot;</p> <p style="margin-left: 40px;"> HTML markup for info message:&nbsp;</p> <img alt="html structure" src="assets/images/info_message.png" style="margin-left: 40px;" > <p style="margin-left: 40px;"> HTML markup for input field with info state:</p> <img alt="html structure" src="assets/images/info_view.png" style="margin-left: 40px;" > <p style="margin-left: 40px;"> The "span" with <strong>class=&quot;info-view&quot;</strong> contains info message for the some particular field.</p> <h5> <strong>Warning state</strong></h5> <p style="margin-left: 40px;"> Demo for warning state: &quot;<strong>extensions/warning_state.html</strong>&quot;</p> <p style="margin-left: 40px;"> HTML markup for warning message:&nbsp;</p> <img alt="html structure" src="assets/images/warning_message.png" style="margin-left: 40px;" > <p style="margin-left: 40px;"> HTML markup for input field with warning state:</p> <img alt="html structure" src="assets/images/warning_view.png" style="margin-left: 40px;" > <p style="margin-left: 40px;"> The "span" with <strong>class=&quot;warning-view&quot;</strong> contains warning message for the some particular field.</p> <section id="css_structure"> <div class="page-header"><h3>CSS Structure</h3><hr class="notop"></div> <p> Every form has next css files in the "head" sections:</p> <img alt="html structure" src="assets/images/css_files.png" > <ul> <li> <strong>demo.css</strong> - this file is &nbsp;required only for demonstration purpose. It sets site background. The background image is located in the folder: &quot;<strong>img/</strong>&quot;;</li> <li> <strong>font-awesome.min.css</strong> - file is required for Font Awesome icons;</li> <li> <strong>j-forms.css</strong> - main css file. Contains all css properties. All sections in this file are commented and you can do your form customization. This file is duplicated for all forms and extensions.</li> </ul> <strong>j-forms.css</strong> contains all of the specific stylings for the page. The file is separated into sections using: <pre class="prettyprint lang-css linenums"> /* Font =============================== */ ... /* Default =============================== */ ... /* Reset for -webkit / -moz browser =============================== */ ... /* Header =============================== */ ... /* Content =============================== */ ... /* Footer =============================== */ ... /* Dividers =============================== */ ... /* Gap-top / gap-bottom classes =============================== */ ... /* Labels =============================== */ ... /* Radio and checkbox =============================== */ ... /* Widget =============================== */ ... /* Inputs =============================== */ ... /* Placeholders =============================== */ ... /* Select =============================== */ ... /* Icons =============================== */ ... /* File for upload =============================== */ ... /* Buttons =============================== */ ... /* Tooltip =============================== */ ... /* Status message =============================== */ ... /* Disabled state =============================== */ ... /* Error state =============================== */ ... /* Success state =============================== */ ... /* Warning state =============================== */ ... /* Info state =============================== */ ... /* Ratings =============================== */ ... /* Social links =============================== */ ... /* Captcha =============================== */ ... /* Stepper =============================== */ ... /* Datapicker and Timepicker =============================== */ ... /* jQuery Slider =============================== */ ... /* Multistep form =============================== */ ... /* Modal form =============================== */ ... /* Pop-up form =============================== */ ... /* Grid layout =============================== */ ... /* Responsiveness =============================== */ ... /* Bootstrap compatibility =============================== */ </pre> <p>If you would like to edit a specific section of the site, simply find the appropriate label in the CSS file, and then scroll down until you find the appropriate style that needs to be edited.</p> <p> Example of the <strong>&quot;green</strong>&quot; color scheme from folder &quot;<strong>css/</strong>&quot;:</p> <pre class="prettyprint lang-css linenums"> /* ========================================= */ /* Color: green */ /* ========================================= */ /* Buttons =============================== */ ... /* Ratings =============================== */ ... /* Header + footer =============================== */ ... /* Other =============================== */ ... /* Radio and checkbox =============================== */ ... /* Toggle radio and toggle checkbox =============================== */ ... /* Tooltip =============================== */ ... /* Input =============================== */ ... </pre> <p>If you want to make any changes with one of color schemes - just change the properties in the appropriate file in the folder &quot;<strong>css/</strong>&quot;.</p> </section> <section id="js_structure"> <div class="page-header"><h3>JavaScript Structure</h3><hr class="notop"></div> <p>Every form or template has some of the next files in the head sections:</p> <img alt="html structure" src="assets/images/js_all_files.png" > <ul> <strong><li>j-forms-additions.js</strong> - additional methods for <strong>Just Forms advanced</strong> (show/hide password, hidden elements, select with conditions, etc.);</li> <strong><li>j-forms-modal.js</strong> - js code for modal forms;</li> <strong><li>j-forms-multistep.js</strong> - js code for multistep forms;</li> <strong><li>jquery.1.11.1.min.js</strong> - jQuery library;</li> <strong><li>jquery.form.min.js</strong> - jQuery Form Plugin allows you to use HTML forms with AJAX;</li> <strong><li>jquery.ui.min.js</strong> - jQuery library for Sliders and Date Pickers. This library should be added to the forms with jQuery sliders and data pikers;</li> <strong><li>jquery.maskedinput.min.js</strong> - jQuery plugin for masked inputs (date, phone, numbers, etc);</li> <strong><li>jquery.placeholder.min.js</strong> - jQuery plugin for proper placeholder displaying in the old browsers;</li> <strong><li>jquery.spectrum.min.js</strong> - jQuery plugin for color picker;</li> <strong><li>jquery.stepper.min.js</strong> - jQuery plugin for nummeric stepper;</li> <strong><li>jquery.ui.timepicker.min.js</strong> - jQuery plugin for time picker;</li> <strong><li>jquery.ui.touch-punch.min.js</strong> - jQuery plugin for proper slider work on mobile devices;</li> <strong><li>jquery.validate.min.js</strong> - jQuery plugin for client-side validation;</li> <strong><li>additional-methods.min.js</strong> - additional methods for client-side validation (file validation, etc.)</li> </ul> <p>If you want to add any extension to your form (such as date picker or color picker) - please be sure that you add appropriate js script to the "head" section on your html page.</p> </section> <section id="js_plugin"> <div class="page-header"><h3>JavaScript Plugins</h3><hr class="notop"></div> <h5> <strong>Date Picker</strong></h5> <p style="margin-left: 40px;"> Demo for date pickers: &quot;<strong>extensions/datepicker.html</strong>&quot;</p> <p style="margin-left: 40px;">In this section we will discuss how you can add and configure date picker in your forms.</p> <p style="margin-left: 40px;">First of all, you have to add <strong>jquery.ui.min.js</strong> script in the "head" section of the html page. Second, you have to configure date picker settings. </p> <p style="margin-left: 40px;"> <strong>Step 1:</strong></p> <p style="margin-left: 80px;">In this step we add html markup for the date picker. Note: you have to configure some unique "id" attributes for date picker.</p> <img alt="html structure" src="assets/images/js_plg_datepicker_1.png" style="margin-left: 80px;"> <p style="margin-left: 40px;"> <strong>Step 2:</strong></p> <p style="margin-left: 80px;">In this step we add js code for the date picker. You can add js code directly to the html page where your form is placed. Or you can add it to the "main" js file of your website.</p> <img alt="html structure" src="assets/images/js_plg_datepicker_2.png" style="margin-left: 80px;"> <p style="margin-left: 80px;">In the <strong>"forms"</strong> folder you can find some form with date picker that has some differences. For instance, let's take a look to the <strong>"booking"</strong> form.</p> <img alt="html structure" src="assets/images/js_plg_datepicker_3.png" style="margin-left: 80px;"> <p style="margin-left: 80px;">The difference lies in the fact that we create a wrapper function for every DatePicker instance. This function is required if we want to create DatePicker instance when we want, but not when html page is loaded. All forms are sent to the server without page reloading - and we need to reload the DatePicker instance manually, every time when a form is submitted successfully. This is what we do every time after successful form submitting.</p> <img alt="html structure" src="assets/images/js_plg_datepicker_4.png" style="margin-left: 80px;"> <p style="margin-left: 80px;">The line - <strong>$( this ).valid();</strong> - is required for date picker validation at once after field is lost a focus. This improvement is binded with some DatePicker plugin features.</p> <p style="margin-left: 80px;">More info about form validation - in the <strong>JS Validation</strong> section.</p> <h5> <strong>Time Picker</strong></h5> <p style="margin-left: 40px;"> Demo for time pickers: &quot;<strong>extensions/timepicker.html</strong>&quot;</p> <p style="margin-left: 40px;">First of all, you have to add js scripts in the "head" section of the html page. Second, you have to configure time picker settings.</p> <img alt="html structure" src="assets/images/js_plg_timepicker_js.png" style="margin-left: 80px;"> <p style="margin-left: 40px;"> <strong>Step 1:</strong></p> <p style="margin-left: 80px;">In this step we add html markup for the time picker. Note: you have to configure unique "id" attribute for time picker.</p> <img alt="html structure" src="assets/images/js_plg_timepicker_1.png" style="margin-left: 80px;"> <p style="margin-left: 40px;"> <strong>Step 2:</strong></p> <p style="margin-left: 80px;">In this step we add js code for the time picker. You can add js code directly to the html page where your form is placed. Or you can add it to the "main" js file of your website.</p> <img alt="html structure" src="assets/images/js_plg_timepicker_2.png" style="margin-left: 80px;"> <h5> <strong>Color Picker</strong></h5> <p style="margin-left: 40px;"> Demo for color pickers: &quot;<strong>extensions/colorpicker.html</strong>&quot;</p> <p style="margin-left: 40px;">First of all, you have to add js scripts in the "head" section of the html page. Second, you have to configure color picker settings.</p> <img alt="html structure" src="assets/images/js_plg_colorpicker_js.png" style="margin-left: 80px;"> <p style="margin-left: 40px;"> <strong>Step 1:</strong></p> <p style="margin-left: 80px;">In this step we add html markup for the color picker. Note: you have to configure unique "id" attribute for color picker.</p> <img alt="html structure" src="assets/images/js_plg_colorpicker_1.png" style="margin-left: 80px;"> <p style="margin-left: 40px;"> <strong>Step 2:</strong></p> <p style="margin-left: 80px;">In this step we add js code for the color picker. You can add js code directly to the html page where your form is placed. Or you can add it to the "main" js file of your website.</p> <img alt="html structure" src="assets/images/js_plg_colorpicker_2.png" style="margin-left: 80px;"> <h5> <strong>Nummeric Stepper</strong></h5> <p style="margin-left: 40px;"> Demo for numeric stepper: &quot;<strong>extensions/numeric_stepper.html</strong>&quot;</p> <p style="margin-left: 40px;">First of all, you have to add js scripts in the "head" section of the html page. Second, you have to configure numeric stepper settings.</p> <img alt="html structure" src="assets/images/js_plg_numeric_js.png" style="margin-left: 80px;"> <p style="margin-left: 40px;"> <strong>Step 1:</strong></p> <p style="margin-left: 80px;">In this step we add html markup for the numeric stepper. Note: you have to configure unique "id" attribute for numeric stepper.</p> <img alt="html structure" src="assets/images/js_plg_numeric_1.png" style="margin-left: 80px;"> <p style="margin-left: 40px;"> <strong>Step 2:</strong></p> <p style="margin-left: 80px;">In this step we add js code for the numeric stepper. You can add js code directly to the html page where your form is placed. Or you can add it to the "main" js file of your website.</p> <img alt="html structure" src="assets/images/js_plg_numeric_2.png" style="margin-left: 80px;"> <h5> <strong>Sliders</strong></h5> <p style="margin-left: 40px;"> Demo for sliders: &quot;<strong>extensions/sliders.html</strong>&quot;</p> <p style="margin-left: 40px;">First of all, you have to add js scripts in the "head" section of the html page. Second, you have to configure slider settings.</p> <img alt="html structure" src="assets/images/js_plg_slider_js.png" style="margin-left: 80px;"> <p style="margin-left: 40px;"> <strong>Step 1:</strong></p> <p style="margin-left: 80px;">In this step we add html markup for the slider. Note: you have to configure unique "id" attribute for slider.</p> <img alt="html structure" src="assets/images/js_plg_slider_1.png" style="margin-left: 80px;"> <p style="margin-left: 40px;"> <strong>Step 2:</strong></p> <p style="margin-left: 80px;">In this step we add js code for the slider. You can add js code directly to the html page where your form is placed. Or you can add it to the "main" js file of your website.</p> <img alt="html structure" src="assets/images/js_plg_slider_2.png" style="margin-left: 80px;"> <h5> <strong>Masking</strong></h5> <p style="margin-left: 40px;"> Demo for masking: &quot;<strong>extensions/js_masking.html</strong>&quot;</p> <p style="margin-left: 40px;">First of all, you have to add js scripts in the "head" section of the html page. Second, you have to configure masking settings.</p> <img alt="html structure" src="assets/images/js_plg_masking_js.png" style="margin-left: 80px;"> <p style="margin-left: 40px;"> <strong>Step 1:</strong></p> <p style="margin-left: 80px;">In this step we add html markup for the masking. Note: you have to configure unique "id" attribute for masking.</p> <img alt="html structure" src="assets/images/js_plg_masking_1.png" style="margin-left: 80px;"> <p style="margin-left: 40px;"> <strong>Step 2:</strong></p> <p style="margin-left: 80px;">In this step we add js code for the masking. You can add js code directly to the html page where your form is placed. Or you can add it to the "main" js file of your website.</p> <img alt="html structure" src="assets/images/js_plg_masking_2.png" style="margin-left: 80px;"> <h5> <strong>TinyMCE</strong></h5> <p style="margin-left: 40px;">You can add WYSIWYG editor TinyMCE to any form.</p> <p style="margin-left: 80px;">First, connect required scripts in the html markup. Also do not forget to copy "tinymce" folder to your server. this folder contains all required files. Example forms with TinyMCE plugin you will find in the <strong>"forms/contact_tinymce/"</strong> folder.</p> <img alt="tinymce" src="assets/images/tiny_mce_1.png" style="margin-left: 80px;"> <p style="margin-left: 80px;">Second, open "j-forms.js" file and add js code for tinymce plugin.</p> <img alt="tinymce" src="assets/images/tiny_mce.png" style="margin-left: 80px;"> <p style="margin-left: 80px;">you can configure this js code according to the TinyMCE API. Also this part of code already contains a validation function (for empty enter).</p> <h5> <strong>Cloned elements</strong></h5> <p style="margin-left: 40px;">Working form with cloned elements feature - in the <strong>"forms/party_invitation_cloned_elements/"</strong> folder.</p> <p style="margin-left: 40px;"> Demo for cloned elements: &quot;<strong>extensions/clone_elements.html</strong>&quot;</p> <p style="margin-left: 40px;"> <strong>Step 1:</strong></p> <p style="margin-left: 80px;">First of all, you have to add js scripts in the "head" section of the html page.</p> <img alt="cloned elements" src="assets/images/clone_elem_1.png" style="margin-left: 80px;"> <p style="margin-left: 40px;"> <strong>Step 2:</strong></p> <p style="margin-left: 80px;">Next, wrap a div for cloning in the div with some unique class.</p> <img alt="cloned elements" src="assets/images/clone_elem_2.png" style="margin-left: 80px;"> <p style="margin-left: 40px;"> <strong>Step 3:</strong></p> <p style="margin-left: 80px;">Add js code required for the plugin.</p> <img alt="cloned elements" src="assets/images/clone_elem_3.png" style="margin-left: 80px;"> <h5> <strong>Currency format</strong></h5> <p style="margin-left: 40px;"> Demo for currency format: &quot;<strong>extensions/currency.html</strong>&quot;</p> <p style="margin-left: 40px;">Working form with currency format feature - in the <strong>"forms/order_logic_field/"</strong> folder.</p> <p style="margin-left: 40px;"> <strong>Step 1:</strong></p> <p style="margin-left: 80px;">First of all, you have to add js scripts in the "head" section of the html page.</p> <img alt="currency" src="assets/images/currency_1.png" style="margin-left: 80px;"> <p style="margin-left: 40px;"> <strong>Step 2:</strong></p> <p style="margin-left: 80px;">Next, define a data attribute and class for every field with currency feature.</p> <img alt="currency" src="assets/images/currency_2.png" style="margin-left: 80px;"> <p style="margin-left: 40px;"> <strong>Step 3:</strong></p> <p style="margin-left: 80px;">Add js code required for the plugin.</p> <img alt="currency" src="assets/images/currency_3.png" style="margin-left: 80px;"> <h5> <strong>Autocomplete</strong></h5> <p style="margin-left: 40px;"> Demo for autocomplete: &quot;<strong>extensions/autocomplete.html</strong>&quot;</p> <p style="margin-left: 40px;"> <strong>Step 1:</strong></p> <p style="margin-left: 80px;">You have to add js library in the "head" section of the html page.</p> <img alt="autocomplete" src="assets/images/autocomplete_1.png" style="margin-left: 80px;"> <p style="margin-left: 40px;"> <strong>Step 2:</strong></p> <p style="margin-left: 80px;">Add id attribute to the input with autocomplete feature.</p> <img alt="autocomplete" src="assets/images/autocomplete_2.png" style="margin-left: 80px;"> <p style="margin-left: 40px;"> <strong>Step 3:</strong></p> <p style="margin-left: 80px;">Add js code required for the autocomplete.</p> <img alt="autocomplete" src="assets/images/autocomplete_3.png" style="margin-left: 80px;"> <h5> <strong>Google Map</strong></h5> <strong> <p style="margin-left: 40px;"> Simple Google Map</p></strong> <p style="margin-left: 40px;"> Demo for google map: &quot;<strong>extensions/form_google_map.html</strong>&quot;</p> <p style="margin-left: 40px;"> <strong>Step 1:</strong></p> <p style="margin-left: 80px;">You have to add js library in the "head" section of the html page.</p> <img alt="google map" src="assets/images/google_1.png" style="margin-left: 80px;"> <p style="margin-left: 40px;"> <strong>Step 2:</strong></p> <p style="margin-left: 80px;">Add id attribute to the div with google map feature.</p> <img alt="google map" src="assets/images/google_2.png" style="margin-left: 80px;"> <p style="margin-left: 40px;"> <strong>Step 3:</strong></p> <p style="margin-left: 80px;">Add js code required for the google map.</p> <img alt="google map" src="assets/images/google_3.png" style="margin-left: 80px;"> <strong> <p style="margin-left: 40px;"> Google Map with autocomplete as page background</p></strong> <p style="margin-left: 40px;"> Demo for google map as background: &quot;<strong>extensions/form_map_background_autocomplete.html</strong>&quot;</p> <p style="margin-left: 40px;"> <strong>Step 1:</strong></p> <p style="margin-left: 80px;">You have to add js library in the "head" section of the html page. Also add a css styles for the map. It should has height and width equal to the height and width of the screen.</p> <img alt="google map" src="assets/images/google_4.png" style="margin-left: 80px;"> <p style="margin-left: 40px;"> <strong>Step 2:</strong></p> <p style="margin-left: 80px;">Add id attribute to the div with google map feature.</p> <img alt="google map" src="assets/images/google_5.png" style="margin-left: 80px;"> <p style="margin-left: 40px;"> <strong>Step 3:</strong></p> <p style="margin-left: 80px;">Add js code required for the google map. This part of code contains a function for searching height of the screen every time when map is loaded.</p> <img alt="google map" src="assets/images/google_6.png" style="margin-left: 80px;"> <img alt="google map" src="assets/images/google_7.png" style="margin-left: 80px;"> <h5> <strong>Youtube/Vimeo</strong></h5> <p style="margin-left: 40px;"> Demo for video players: &quot;<strong>extensions/youtube_vimeo.html</strong>&quot;</p> <p style="margin-left: 80px;">You can add a video player to any form. You have to add html markup with settings for the player.</p> <img alt="video" src="assets/images/video.png" style="margin-left: 80px;"> </section> <section id="js_additions"> <div class="page-header"><h3>JS Additions</h3><hr class="notop"></div> <p> Demo for js additions: &quot;<strong>extensions/js_additions.html</strong>&quot;</p> <p>In this section we will discuss all javascript additions that are available in the <strong>Just Forms advanced</strong>. These additions will help your users during form submission process.</p> <h5> <strong>Show / Hide Password</strong></h5> <p style="margin-left: 40px;"> <strong>Step 1:</strong></p> <p style="margin-left: 40px;">You can add to your form "show/hide password" feature. Note: you have to configure unique "id" attribute for "show/hide password" feature.</p> <img alt="html structure" src="assets/images/js_add_showpass_1.png" style="margin-left: 80px;"> <p style="margin-left: 40px;"> <strong>Step 2:</strong></p> <p style="margin-left: 80px;">In this step we add js code for the "show/hide password" feature. You can add js code directly to the html page where your form is placed. Or you can add it to the "main" js file of your website.</p> <img alt="html structure" src="assets/images/js_add_showpass_2.png" style="margin-left: 80px;"> <h5> <strong>Enabled input / button</strong></h5> <p style="margin-left: 40px;"> <strong>Step 1:</strong></p> <p style="margin-left: 40px;">You can add to your form "enable/disable elements" feature. Note: you have to configure unique "id" attribute for "enable/disable elements" feature. Take a look to the <strong>class=&quot;disabled-view&quot;</strong> and attribute <strong>disabled</strong>. These class and attribute are required.</p> <img alt="html structure" src="assets/images/js_add_disabled_1.png" style="margin-left: 80px;"> <p style="margin-left: 40px;"> <strong>Step 2:</strong></p> <p style="margin-left: 80px;">In this step we add js code for the "enable/disable elements" feature. You can add js code directly to the html page where your form is placed. Or you can add it to the "main" js file of your website.</p> <img alt="html structure" src="assets/images/js_add_disabled_2.png" style="margin-left: 80px;"> <h5> <strong>Hidden elements - checkbox</strong></h5> <p style="margin-left: 40px;"> <strong>Step 1:</strong></p> <p style="margin-left: 40px;">You can add to your form "hidden elements" feature. Take a look to the <strong>class=&quot;hidden-elements&quot;</strong> and <strong>class=&quot;hidden&quot;</strong>. These classes are responsible for the next features:</p> <ul style="margin-left: 40px;"> <li><strong>class=&quot;hidden-elements&quot;</strong> - this class is required for the js code. If this class is present - js code knows that current element should be hidden;</li> <li><strong>class=&quot;hidden&quot;</strong> - this class is responsible for hiding elements. It contains css properties.</li> </ul> <img alt="html structure" src="assets/images/js_add_hidden_check_1.png" style="margin-left: 80px;"> <p style="margin-left: 40px;"> <strong>Step 2:</strong></p> <p style="margin-left: 80px;">In this step we add js code for the "hidden elements" feature. You can add js code directly to the html page where your form is placed. Or you can add it to the "main" js file of your website.</p> <img alt="html structure" src="assets/images/js_add_hidden_check_2.png" style="margin-left: 80px;"> <h5> <strong>Hidden elements - select</strong></h5> <p style="margin-left: 40px;"> <strong>Step 1:</strong></p> <p style="margin-left: 40px;">You can add to your form "hidden elements" feature. Note: you have to configure unique "id" attribute for every hidden field. <strong>class=&quot;hidden&quot;</strong> - this class is responsible for hiding elements. It contains css properties. Main idea of this feature: when user select some value - some element appears.</p> <img alt="html structure" src="assets/images/js_add_hidden_select_1.png" style="margin-left: 80px;"> <p style="margin-left: 40px;"> <strong>Step 2:</strong></p> <p style="margin-left: 80px;">In this step we add js code for the "hidden elements" feature. You can add js code directly to the html page where your form is placed. Or you can add it to the "main" js file of your website.</p> <img alt="html structure" src="assets/images/js_add_hidden_select_2.png" style="margin-left: 80px;"> <h5> <strong>Select with conditions</strong></h5> <p style="margin-left: 40px;">Main idea of this feature: when user select some value in the first select field - appropriate values appear in the second select field. If user selects default value in the any select field - values in the next select fields should disappear.</p> <p style="margin-left: 40px;">In this example we will work with cars and car models. You can add any values you want.</p> <p style="margin-left: 40px;"> <strong>Step 1:</strong></p> <p style="margin-left: 80px;">In the first step you have to add select fields to the html page. Note: you have to configure unique "id" attribute for every select field.</p> <img alt="html structure" src="assets/images/js_add_cond_select_1.png" style="margin-left: 80px;"> <p style="margin-left: 80px;">Because values in the select fields should appear dynamically - we should add values only for the first select field.</p> <p style="margin-left: 40px;"> <strong>Step 2:</strong></p> <p style="margin-left: 80px;">Let's take a look to the js code</p> <img alt="html structure" src="assets/images/js_add_cond_select_2.png" style="margin-left: 80px;"> <p style="margin-left: 80px;">First - we have to create a list with models for every car. We do it in the <strong>select โ„– 2</strong> section. For example, for the "BMW" car we added three models: M6, X5, Z3. We have created values for the select โ„– 2.</p> <p style="margin-left: 80px;">Second - for every model we have to define required colors. We do it in the <strong>select โ„– 3</strong>. For example, for the model "BMW Z3" we added next colors: 'teal', 'purple', 'cyan'. That is, we have to create arrays with values for the next select field. Every array from these arrays must match to the value from current select field.</p> <p style="margin-left: 40px;"> <strong>Step 3:</strong></p> <p style="margin-left: 80px;">In this step we have to add js code that should dynamically add values to the next select fields if current select field is changed.</p> <img alt="html structure" src="assets/images/js_add_cond_select_3.png" style="margin-left: 80px;"> <p style="margin-left: 80px;">If some value was selected in the first select field - we create list of values for the second select field and add this list to the html page.</p> <img alt="html structure" src="assets/images/js_add_cond_select_4.png" style="margin-left: 80px;"> <p style="margin-left: 80px;">If some value was selected in the second select field - we create list of values for the third select field and add this list to the html page.</p> </section> <section id="modal_form"> <div class="page-header"><h3>Modal Form</h3><hr class="notop"></div> <p> Demo for modal forms: &quot;<strong>extensions/modal_form.html</strong>&quot;</p> <p> You can easily use any form in modal window. All modal forms are responsive.</p> <p>Insert your form to the div with <strong>class=&quot;modal-form&quot;</strong>. Add <strong>"id"</strong> attribute to this div.</p> <img alt="html structure" src="assets/images/js_modal_form_1.png"> <p>Add a link with <strong>class=&quot;modal-open&quot;</strong> and reference to this <strong>"id"</strong>.</p> <img alt="html structure" src="assets/images/js_modal_form_2.png"> <p>Add a close button to your form. Modal form will be hidden when this label will be clicked.</p> <img alt="html structure" src="assets/images/js_modal_form_3.png"> <p>Add js code for a modal form. You can add js code directly to the html page where your form is placed. Or you can add it to the "main" js file of your website.</p> <img alt="html structure" src="assets/images/js_modal_form_4.png"> </section> <section id="multistep_form"> <div class="page-header"><h3>Multistep Form</h3><hr class="notop"></div> <p> Two types of multistep form are allowed: <ul> <li>multistep form with steps - demo:&quot;<strong>extensions/multistep_with_steps.html</strong>&quot;</li> <li>multistep form with out steps - demo:&quot;<strong>extensions/multistep.html</strong>&quot;</li> </ul> </p> <h5> <strong>Multistep form with steps</strong></h5> <p style="margin-left: 40px;">You can easily use any form in multistep window. All multistep forms are responsive. For example, we will work with next form: - &quot;<strong>extensions/multistep_with_steps.html</strong>&quot;</p> <p style="margin-left: 40px;"> <strong>Step 1:</strong></p> <p style="margin-left: 80px;">Add js script to the "head" section of your html page.</p> <img alt="html structure" src="assets/images/multistep_js.png" style="margin-left: 80px;"> <p style="margin-left: 40px;"> <strong>Step 2:</strong></p> <p style="margin-left: 80px;">Add <strong>class=&quot;j-multistep&quot;</strong> to your form. Due to this class, js code knows that form will be with steps.</p> <img alt="html structure" src="assets/images/multistep_1.png" style="margin-left: 80px;"> <p style="margin-left: 40px;"> <strong>Step 3:</strong></p> <p style="margin-left: 80px;">Add to the div with <strong>class=&quot;content&quot;</strong> a div with steps. You can add as many steps as you want. Pay attention to the <strong>class=&quot;step&quot;</strong> and <strong>class=&quot;steps&quot;</strong>. These classes are required for proper form work.</p> <img alt="html structure" src="assets/images/multistep_2.png" style="margin-left: 80px;"> <p style="margin-left: 40px;"> <strong>Step 4:</strong></p> <p style="margin-left: 80px;">Add several <strong>fieldset</strong> tags to your form. Evenly distribute all rows with fields between all fieldsets. The optimum number of fieldsets - 3. But you can add as many fieldsets as you want. Note: quantity of the "fieldset" tags has to be equal to the quantity of the "step" divs from previous step.</p> <img alt="html structure" src="assets/images/multistep_3.png" style="margin-left: 80px;"> <p style="margin-left: 40px;"> <strong>Step 5:</strong></p> <p style="margin-left: 80px;">Add to the <strong>footer</strong> next buttons: "Next", "Back", "Submit". Note: <strong>class=&quot;multi-submit-btn&quot;</strong>, <strong>class=&quot;multi-next-btn&quot;</strong>, <strong>class=&quot;multi-prev-btn&quot;</strong> are required classes.</p> <img alt="html structure" src="assets/images/multistep_4.png" style="margin-left: 80px;"> <p style="margin-left: 80px;">Now your multistep form is ready for work.</p><h5> <h5> <strong>Multistep form with out steps</strong></h5> <p style="margin-left: 40px;">All rules for multistep form with steps are suitable for multistep form without steps. The only difference between these forms - you may not add "steps" to the html page. JS code will work properly without <strong>class=&quot;step&quot;</strong> and <strong>class=&quot;steps&quot;</strong>. </p> <h5> <strong>Multistep JS Code</strong></h5> <p style="margin-left: 40px;">JavaScript code for multistep forms is multipurpose and doesn't depend from any "id" attribute. So, you can use it without any changes with any number of multistep forms at one page. More about how to validate multistep forms - in the <strong>New Form</strong> section.</p> <p style="margin-left: 40px;">First, multistep script try to find a form with <strong>class=&quot;j-multistep&quot;</strong> on the page. And, for each form script configure settings (such as active step, active fieldset, show/hide buttons)</p> <img alt="html structure" src="assets/images/multistep_5.png" style="margin-left: 40px;"> <p style="margin-left: 40px;">When the "next" button is clicked - current fieldset became hidden, next fieldset became active, buttons are processed.</p> <img alt="html structure" src="assets/images/multistep_6.png" style="margin-left: 40px;"> <p style="margin-left: 40px;">When the "previous" button is clicked - current fieldset became hidden, previous fieldset became active, buttons are processed.</p> <img alt="html structure" src="assets/images/multistep_7.png" style="margin-left: 40px;"> </section> <section id="multistep_form_logic"> <div class="page-header"><h3>Multistep Form with Logic</h3><hr class="notop"></div> <p>In this section we will discuss variety extensions for the multistep forms. You can add these extensions to any multistep form (new one or already existing).</p> <h5> <strong>Multistep Form with Form Details</strong></h5> <p style="margin-left: 40px;">Demo: <strong>"extensions/multistep_form_with_details.html"</strong></p> <p style="margin-left: 40px;">This extensions will help your user to check entered info. In the last step all data from the form will be shown.</p> <p style="margin-left: 40px;">Specify id attribute for the input field.</p> <img alt="multi logic" src="assets/images/multi_logic_1.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">Add html markup to the last step</p> <img alt="multi logic" src="assets/images/multi_logic_2.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">Add js function for proper form work.</p> <img alt="multi logic" src="assets/images/multi_logic_3.png" style="margin-left: 40px;" > <h5> <strong>Multistep Form with Variable Steps</strong></h5> <p style="margin-left: 40px;">Demo: <strong>"extensions/multistep_form_with_variable_steps.html"</strong></p> <p style="margin-left: 40px;">Working form: <strong>"forms/multistep_form_with_variable_steps/"</strong></p> <p style="margin-left: 40px;">In this type of extension user has the ability to choose what kind of info will be shown in the next step.</p> <img alt="multi logic" src="assets/images/multi_logic_4.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">Pay attention that by default all next steps are hidden. Only when user will click some button - appropriate div inside the fieldset became visible.</p> <p style="margin-left: 40px;">Js function to make all work properly.</p> <img alt="multi logic" src="assets/images/multi_logic_5.png" style="margin-left: 40px;" > <h5> <strong>Multistep Form with Dinamicaly Steps using Checkbox</strong></h5> <p style="margin-left: 40px;">Demo: <strong>"extensions/multistep_with_dinamic_steps_checkbox.html"</strong></p> <p style="margin-left: 40px;">Working form: <strong>"forms/multistep_with_dinamic_steps_checkbox"</strong></p> <p style="margin-left: 40px;">This type of extension allows to user add a step dynamically using checkbox. If user want enter additional info - next step will be shown.</p> <p style="margin-left: 40px;">HTML markup</p> <img alt="multi logic" src="assets/images/multi_logic_6.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">Js function</p> <img alt="multi logic" src="assets/images/multi_logic_7.png" style="margin-left: 40px;" > <h5> <strong>Multistep Form with Dinamicaly Steps using Radio Buttons</strong></h5> <p style="margin-left: 40px;">Demo: <strong>"extensions/multistep_with_dinamic_steps_radio.html"</strong></p> <p style="margin-left: 40px;">Working form: <strong>"forms/multistep_with_dinamic_steps_radio"</strong></p> <p style="margin-left: 40px;">This type of extension allows to user add a step dynamically using radio buttons. If user want enter additional info - next step will be shown.</p> <p style="margin-left: 40px;">HTML markup</p> <img alt="multi logic" src="assets/images/multi_logic_10.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">Js function</p> <img alt="multi logic" src="assets/images/multi_logic_11.png" style="margin-left: 40px;" > <h5> <strong>Multistep Form with Dinamicaly Steps using Select</strong></h5> <p style="margin-left: 40px;">Demo: <strong>"extensions/multistep_with_dinamic_steps_select.html"</strong></p> <p style="margin-left: 40px;">Working form: <strong>"forms/multistep_with_dinamic_steps_select"</strong></p> <p style="margin-left: 40px;">This type of extension allows to user add a step dynamically using dropdown field. If user want enter additional info - next step will be shown.</p> <p style="margin-left: 40px;">HTML markup</p> <img alt="multi logic" src="assets/images/multi_logic_12.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">HTML markup</p> <img alt="multi logic" src="assets/images/multi_logic_13.png" style="margin-left: 40px;" > <h5> <strong>Multistep Form with Dinamicaly Steps using Input Field</strong></h5> <p style="margin-left: 40px;">Demo: <strong>"extensions/multistep_with_dinamic_steps_input.html"</strong></p> <p style="margin-left: 40px;">Working form: <strong>"forms/multistep_with_dinamic_steps_input"</strong></p> <p style="margin-left: 40px;">This type of extension allows to user add a step dynamically using input field. If user want enter additional info - next step will be shown.</p> <p style="margin-left: 40px;">HTML markup</p> <img alt="multi logic" src="assets/images/multi_logic_14.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">HTML markup</p> <img alt="multi logic" src="assets/images/multi_logic_15.png" style="margin-left: 40px;" > <h5> <strong>Multistep Form with Dinamicaly Steps combine all types</strong></h5> <p style="margin-left: 40px;">Demo: <strong>"extensions/multistep_with_dinamic_steps_all_types.html"</strong></p> <p style="margin-left: 40px;">This type of extension combine all available types of logic (checkbox, radio, dropdown, input, select).</p> <h5> <strong>Interesting Moments with Multistep Form with Dinamicaly Steps</strong></h5> <p style="margin-left: 40px;">Some interesting moments. All rules are appropriate for all forms with dinamicaly steps:</p> <p style="margin-left: 40px;">All extensions with dinamicaly steps require to check if user enter info in the additional step. And if yes - clear all fields in the additional step if a form was subbmitted from the first step, but not from the additional step. To fulfill this condition an additional js function was added.</p> <img alt="multi logic" src="assets/images/multi_logic_8.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">Also pay attention that we manually add a logic function to execute if first step is active. If you have several logic functions in one form - you have to add to the first step exactly the same function you have in the html markup. For example: first step contains checkbox logic fucntion, second step contains dropdown logic function. So, you have to add checkbox logic fucntion to execute when first step is active step.</p> <img alt="multi logic" src="assets/images/multi_logic_9.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">Next, pay attention to the next variables</p> <img alt="multi logic" src="assets/images/multi_logic_16.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">These variables contain indexes of the fieldsets for every logic function. We will use these indexes for processing the buttons when appropriate step will be active.</p> <img alt="multi logic" src="assets/images/multi_logic_17.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">Note: when next button will be clicked only three logic functions will be executed. In this particulary example dropdown logic function (select field) is placed in the first step. So, it is not nessesary to execute it when next button is clicked.</p> <p style="margin-left: 40px;">One more thing: if you are using working form with logic function - you have to execute the logic function after a form is submitted successfully. Note that you have to execute exactly the same function you have in the first step html markup. </p> <img alt="multi logic" src="assets/images/multi_logic_18.png" style="margin-left: 40px;" > </section> <section id="order_logic"> <div class="page-header"><h3>Order Form with Calculations</h3><hr class="notop"></div> <p>In this section we will discuss order forms with calculations.</p> <p> Demo for order form with checkboxes, radios and dropdowns: &quot;<strong>forms/../order_logic_field/</strong>&quot;</p> <p> Demo for order form with input fields: &quot;<strong>forms/../order_logic_check_radio/</strong>&quot;</p> <h5> <strong>Order Form with checkboxes, radios and dropdowns</strong></h5> <p style="margin-left: 40px;">Every variable in the html markup has "data-price" attribute. This attribute is required. Values of all this attributes are summed and final price obtained.</p> <img alt="order logic" src="assets/images/order_logic_1.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">In the js file we have several function. Every time when some field is changing - appropriate function obtain new price. calculateTotalPrice() function calculate total price.</p> <img alt="order logic" src="assets/images/order_logic_2.png" style="margin-left: 40px;" > <img alt="order logic" src="assets/images/order_logic_3.png" style="margin-left: 40px;" > <h5> <strong>Order Form with input fields</strong></h5> <p style="margin-left: 40px;">This form is very simple. In the html markup some field has fixed value and some doesn't. Also unique id attributes are specified for every field.</p> <img alt="order logic" src="assets/images/order_logic_4.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">Js function grabs all values (predefined or not) and calculate a total price.</p> <img alt="order logic" src="assets/images/order_logic_5.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">Please pay attention to the next classes: <strong>"fruits-calculation"</strong> and <strong>"quantity-events"</strong>.</p> <img alt="order logic" src="assets/images/order_logic_6.png" style="margin-left: 40px;" > <p style="margin-left: 40px;"><strong>"fruits-calculation"</strong> class is required for form calculation. If user click or change fields with values - "getFruitTotal()" function will be executed.</p> <p style="margin-left: 40px;"><strong>"quantity-events"</strong> class adds events listeners for the "quantity" fields. If user press up and down buttons, scroll mousewheel - "getFruitTotal()" function will be executed.</p> <img alt="order logic" src="assets/images/order_logic_7.png" style="margin-left: 40px;" > </section> <section id="popup_form"> <div class="page-header"><h3>Popup Form</h3><hr class="notop"></div> <p> Demo for popup forms: &quot;<strong>extensions/popup_form.html</strong>&quot;</p> <p> You can easily use any form in pop up window. Two types of pop up forms are allowed: menu pop up form and bottom pop up form.</p> <h5> <strong>Popup Menu Form</strong></h5> <p style="margin-left: 40px;">Main idea of menu pop up foะณm is that you can add any form to menu item on your website. And, when user will click this item - pop up menu form will appear. If you haven't enough space on your site - pop up menu form will solve this problem. You can use existen forms from "template" folder or "forms" folder or you can create your own form from scratch.</p> <p style="margin-left: 40px;">For creating pop up menu form from scratch you have to make several steps:</p> <p style="margin-left: 40px;"> <strong>Step 1:</strong></p> <p style="margin-left: 80px;">Add <strong>class=&quot;popup-list-open&quot;</strong> to the item of your menu.</p> <img alt="html structure" src="assets/images/popup_list_open.png" style="margin-left: 80px;" > <p style="margin-left: 40px;"> <strong>Step 2:</strong></p> <p style="margin-left: 80px;">Inside menu item with <strong>class=&quot;popup-list-open&quot;</strong> you have to add div with <strong>class=&quot;popup-list-wrapper&quot;</strong>. This div will hide the form when menu item isn't active.</p> <img alt="html structure" src="assets/images/popup_list_wrapper.png" style="margin-left: 80px;" > <p style="margin-left: 40px;"> <strong>Step 3:</strong></p> <p style="margin-left: 80px;">Inside div with <strong>class=&quot;popup-list-wrapper&quot;</strong> you can add your form. You can add any kind of form. But if your form will be too big (will have too many rows and inputs) it may not please your users.</p> <img alt="html structure" src="assets/images/popup_list_form.png" style="margin-left: 80px;" > <p style="margin-left: 40px;"> <strong>Step 4:</strong></p> <p style="margin-left: 80px;">In this step you have to add javascript code that will be responsible for the appearance of the form. So, first you have to add "id" attribute to your form. Second, you have to add code that will wait for user clicks. After that, when menu item will be clicked - the form will appear. When user will click anywhere outside the form - form will disappear. You can add this js code to the botton of the html page or in the main js file of your website. This code works well for desctop, tablet and mobile devices.</p> <img alt="html structure" src="assets/images/popup_list_js.png" style="margin-left: 80px;" > <p style="margin-left: 40px;">By default, the width of div with <strong>class=&quot;popup-list-wrapper&quot;</strong> is equal to 400px. So your form will have the same width. </p> <p style="margin-left: 40px;">All elements inside pop up menu form are responsive. Pop up menu form is responsive as well. When a screen width will be equal to 620px or less - pop up menu form will have width equal to width of parent element (in this case - width of all menu). If there is no parent element, pop up menu form will have screen width.</p> <p style="margin-left: 40px;">We have discussed all required classes for pop up menu form. <strong>class=&quot;popup-menu&quot;</strong> and <strong>class=&quot;popup-list&quot;</strong> - are not required classes and were added only for demonstration purpose.</p> <h5> <strong>Popup Bottom Form</strong></h5> <p style="margin-left: 40px;">You can use existen forms from "template" folder or "forms" folder or you can create your own form from scratch. For creation pop up bottom form from scratch you have to make several steps:</p> <p style="margin-left: 40px;"> <strong>Step 1:</strong></p> <p style="margin-left: 80px;">Add div with <strong>class=&quot;popup-btm-400&quot;</strong> to your html page. There are two types of pop up bottom forms: <strong>class=&quot;popup-btm-400&quot;</strong> - 400px width, <strong>class=&quot;popup-btm-640&quot;</strong> - 640px width.</p> <img alt="html structure" src="assets/images/poup_btm_both.png" style="margin-left: 80px;" > <p style="margin-left: 80px;">You can select any width for your pop up bottom form.</p> <p style="margin-left: 80px;">Note: all forms are responsive. When your form will be opened on mobile devices all rows will be placed one under another. As pop up bottom forms have fixed position on the page - users will not be able to scroll the forms if some rows will disappear behind the top of the screen. Therefore, it is the better way do not add a lot of rows to the form. Example of this issue you can see on the screenshots below:</p> <img alt="html structure" src="assets/images/poup_btm_desc.png" style="margin-left: 80px;" > <img alt="html structure" src="assets/images/poup_btm_mob.png" style="margin-left: 80px;" > <p style="margin-left: 40px;"> <strong>Step 2:</strong></p> <p style="margin-left: 80px;">Main idea of pop up bottom form is that user clicks on label and form slips from the bottom. This goal can be achieved using <strong>&lt;input type=&quot;radio&quot;&gt;</strong>. That's why in this step you have to add <strong>&lt;input type=&quot;radio&quot;&gt;</strong> on the page.</p> <img alt="html structure" src="assets/images/poup_btm_close_open.png" style="margin-left: 80px;" > <p style="margin-left: 80px;">When input with <strong>id=&quot;popup-input-open&quot;</strong> is clicked - form slips from the bottom. When input with <strong>id=&quot;popup-input-close&quot;</strong> is clicked - form disappears. Note: by default input with <strong>id=&quot;popup-input-close&quot;</strong> has attribute <strong>checked</strong>, so the form isn't shown.</p> <p style="margin-left: 40px;"> <strong>Step 3:</strong></p> <p style="margin-left: 80px;">Now let's add a label to the page. When this label will be clicked - the form will arise.</p> <img alt="html structure" src="assets/images/poup_btm_open.png" style="margin-left: 80px;" > <p style="margin-left: 40px;"> <strong>Step 4:</strong></p> <p style="margin-left: 80px;">In this step we have to add a wrapper to a form. This wrapper will hide a form outside the screen.</p> <img alt="html structure" src="assets/images/poup_btm_wrapper.png" style="margin-left: 80px;" > <p style="margin-left: 40px;"> <strong>Step 5:</strong></p> <p style="margin-left: 80px;">In this final step the form will be added inside the wrapper from previous step. Also, we have to add a close button. Note that label with <strong>class=&quot;popup-btm-close&quot;</strong> has an attribute <strong>for=&quot;popup-input-close&quot;</strong>. Therefore, when this label (close-button) is clicked - form disappears.</p> <img alt="html structure" src="assets/images/poup_btm_close.png" style="margin-left: 80px;" > <p style="margin-left: 40px;">After you will make all previous steps done - your pop up bottom form will be ready for use.</p> </section> <section id="foot_head_form"> <div class="page-header"><h3>Form without Footer and Header</h3><hr class="notop"></div> <p> Demo for forms without footer and header: &quot;<strong>forms/booking_without_footer_header</strong>&quot;</p> <p>As you may guess, this type of form is created very easy. You have to delete <strong>"header"</strong> and <strong>"footer"</strong> class from your form. Button from <strong>"footer"</strong> you have to copy to the bottom of the <strong>"content"</strong>.</p> <img alt="html structure" src="assets/images/footer_header.png"> </section> <section id="js_validation"> <div class="page-header"><h3>JS Validation</h3><hr class="notop"></div> <p>In the <strong>Just Forms advanced</strong> for client-side validation we will use jQuery Validation Plugin. In this section we will disccus how you can add validation to any field.</p> <p>Demo for available validation methods: &quot;<strong>extensions/js_validation.html</strong>&quot;</p> <p>If you want to add client-side validation to your form you have to make some steps:</p> <p style="margin-left: 40px;"> <strong>Step 1:</strong></p> <p style="margin-left: 80px;">First, you have to connect js scripts to your html page.</p> <img alt="html structure" src="assets/images/js_validation_1.png" style="margin-left: 80px;" > <p style="margin-left: 80px;"> <ul style="margin-left: 80px;"> <li>&quot;<strong>jquery.validate.min.js</strong>&quot; - contains core validation mathods (required, length, value, etc)</li> <li>&quot;<strong>additional-methods.min.js</strong>&quot; - contains additional validation methods ("remote" method for captcha, file for upload validation, etc)</li> </ul> </p> <p style="margin-left: 40px;"> <strong>Step 2:</strong></p> <p style="margin-left: 80px;">In this step we will discuss main steps of the validation process.</p> <img alt="html structure" src="assets/images/js_validation_2.png" style="margin-left: 80px;" > <p style="margin-left: 80px;">On the picture above you can see a js script that is responsible for the form validation. We can divide this script to the next sections:</p> <ul style="margin-left: 80px;"> <li>&quot;<strong>@validation states + elements</strong>&quot; - define error class, success class, error element and other settings;</li> <li>&quot;<strong>@validation rules</strong>&quot; - define rules(min length or required field) and messages('Please enter your value') for validation process;</li> <li>&quot;<strong>Add class 'error-view'</strong>&quot; - define where error classes will be placed;</li> <li>&quot;<strong>Add class 'success-view'</strong>&quot; - define where success classes will be placed;</li> <li>&quot;<strong>Error placement</strong>&quot; - define where error messages will be placed;</li> <li>&quot;<strong>Submit the form</strong>&quot; - contains instruction for performing if form doesn't have any errors.</li> </ul> <p style="margin-left: 40px;"> <strong>Step 3:</strong></p> <p style="margin-left: 80px;">So, let's validate some field:</p> <img alt="html structure" src="assets/images/js_validation_3.png" style="margin-left: 80px;" > <p style="margin-left: 80px;">Let's assume that we want to check if a field is empty.</p> <img alt="html structure" src="assets/images/js_validation_4.png" style="margin-left: 80px;" > <p style="margin-left: 80px;">We have added a rule and a message for our field. Now if user will try to submit a form when this field is empty - error message will appear.</p> <p style="margin-left: 80px;">So, let's validate some group of elements:</p> <img alt="html structure" src="assets/images/js_validation_5.png" style="margin-left: 80px;" > <img alt="html structure" src="assets/images/js_validation_6.png" style="margin-left: 80px;" > <p style="margin-left: 80px;">Rules for group elements are the same as for fields. But pay attention to the <strong>class=&quot;check&quot;</strong>. If you want to validate group of elements - this class is required. The validation script will be looking for this class because after div with <strong>class=&quot;check&quot;</strong> error message will be placed. So, if you validate some groups of checkboxes or radios - do not forget to add this class.</p> <p style="margin-left: 40px;"> <strong>Captcha validation:</strong></p> <p style="margin-left: 80px;">Demo for captcha validation: &quot;<strong>extensions/captcha.html</strong>&quot;</p> <p style="margin-left: 80px;">For captcha validation we will use "remote" method:</p> <img alt="html structure" src="assets/images/js_validation_7.png" style="margin-left: 80px;" > <img alt="html structure" src="assets/images/js_validation_8.png" style="margin-left: 80px;" > <p style="margin-left: 80px;">Main idea of the "remote" method - script gets the captcha value from the form and (without page reloading) send this value to the server script (path to the server script is in the remote rule). If server script returns true - we have success validation. If not - we have error message. <strong>Just Forms advanced</strong> contains captcha that based on a PHP session. PHP script creates the image with a sum of the digits. And, user has to enter a valid sum to make successful captcha validation. You can add a captcha to any form. For proper captcha work do not forget to add "php/captcha" folder to your server.</p> <p style="margin-left: 40px;"> <strong>Delete validation:</strong></p> <p style="margin-left: 80px;">Sometimes you may need to validate only particular field, not all fields. In this case you can comment (or delete) rules from &quot;<strong>@validation rules</strong>&quot; section.</p> <img alt="html structure" src="assets/images/js_validation_10.png" style="margin-left: 80px;" > <p style="margin-left: 80px;">In the picture above we have canceled validation of the group of elements which has name "checkbox".</p> <p style="margin-left: 40px;"> <strong>Submit the form:</strong></p> <p style="margin-left: 80px;">After successful validation, data from the form should be sent to a server for further processing. <strong>jQuery Form Plugin</strong> send data to the server. Let's talk about <strong>Submit the form</strong> section using <strong>forms/booking1</strong> form like an example.</p> <img alt="html structure" src="assets/images/js_validation_9.png" style="margin-left: 80px;" > <p style="margin-left: 80px;"><strong>Submit the form</strong> section contains only one <strong>jQuery Form Plugin</strong> function - ajaxSubmit(). This function sends data from the form to the server without page reloading. This function contains next parts:</p> <ul style="margin-left: 80px;"> <li>&quot;<strong>target:</strong>&quot; - response from server will be appended to this div;</li> <li>&quot;<strong>error:</strong>&quot; - function that defines instruction if error will happen;</li> <li>&quot;<strong>beforeSubmit:</strong>&quot; - function that defines what will happen during form submitting process (submit button will be disabled);</li> <li>&quot;<strong>success:</strong>&quot; - function that defines what will happen if successful response from server will be received.</li> </ul> <p style="margin-left: 80px;">All js code is well commented so, any problem with understanding of the meaning of the code shouldn't arise.</p> </section> <section id="new_form"> <div class="page-header"><h3>New Form</h3><hr class="notop"></div> <p>In this section we will create a new form. Based on this example, you can create your own forms or adjust already existing forms.</p> <p>Example of this working form: &quot;<strong>forms/order_multistep_with_steps</strong>&quot;</p> <p>So, let`s start from the beginning and divide form creation to several steps:</p> <ol> <li>create folder structure</li> <li>add all required javascript files</li> <li>add all required css files</li> <li>create html document, add form elements and scripts</li> <li>create main javascript file with validation rules</li> </ol> <h5> <strong>Folder structure</strong></h5> <p style="margin-left: 40px;">We start by creating required folders.</p> <img alt="html structure" src="assets/images/new_form_1.png" style="margin-left: 40px;" > <ul style="margin-left: 40px;"> <li>css folder - contains all css files</li> <li>fonts folder - contains Font Awesome fonts</li> <li>img folder - contains background picture</li> <li>js folder - contains all js files</li> <li>php folder - contains demo php file that emulates server script</li> </ul> <p style="margin-left: 40px;">As all css files and Font Awesome fonts are the same for all forms - you can just copy these files from any form.</p> <p style="margin-left: 40px;">Let's take a look to the js folder:</p> <img alt="html structure" src="assets/images/new_form_2.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">For our new form we don't need all js files that are in js folder. But we will copy all files in case if our form will be updated in the future.</p> <p style="margin-left: 40px;">Most important js file - &quot;<strong>j-forms.js</strong>&quot;. This file contains all js code required for proper form work.</p> <h5> <strong>HTML structure</strong></h5> <p style="margin-left: 40px;">In this section we will create &quot;<strong>index.html</strong>&quot; All elements and scripts will be added to this file. As we want to create multistep form - we have to abide by the rules. More details about multistep form - in the <strong>Multistep Form</strong> section.</p> <img alt="html structure" src="assets/images/new_form_3.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">We have added all required scripts to the html page.</p> <img alt="html structure" src="assets/images/new_form_4.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">Do not forget to add <strong>class=&quot;j-multistep&quot;</strong> to our form. Pay attention to the <strong>action</strong> attribute. It contains the path to the file with server script. In our case - it is only demo file with success message form the server. Also, take a look to the <strong>method</strong> and <strong>enctype</strong> attributes. These attributes are required as we want to build form with file uploaded feature.</p> <p style="margin-left: 40px;">First fieldset.</p> <img alt="html structure" src="assets/images/new_form_5.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">Second fieldset.</p> <img alt="html structure" src="assets/images/new_form_6.png" style="margin-left: 40px;" > <img alt="html structure" src="assets/images/new_form_7.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">Third fieldset.</p> <img alt="html structure" src="assets/images/new_form_8.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">Take a look to the div with <strong>id=&quot;response&quot;</strong>. Server message will be added into this div.</p> <p style="margin-left: 40px;">Footer</p> <img alt="html structure" src="assets/images/new_form_9.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">We finished with html markup. Let's do some js magic))</p> <h5> <strong>JS structure</strong></h5> <p style="margin-left: 40px;">In this section we will create main js file that contains all js code for our form.</p> <p style="margin-left: 40px;">First, we create a function. This function will include all other function and instruction.</p> <img alt="html structure" src="assets/images/new_form_10.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">Add phone masking.</p> <img alt="html structure" src="assets/images/new_form_11.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">Add datepicker.</p> <img alt="html structure" src="assets/images/new_form_12.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">Add settings for the jQuery Validation Plugin. Note: we validate our form (form "id" attribute is equal to "id" in the "j-forms.js").</p> <img alt="html structure" src="assets/images/new_form_13.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">Add validation rules. Pay attention to the file extensions. You can add any correct file extension. More about jQuery Validation Plugin you can read on the official plugin page from the "Credits" section.</p> <img alt="html structure" src="assets/images/new_form_14.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">Add validation messages. You can change these messages as you wish.</p> <img alt="html structure" src="assets/images/new_form_15.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">Add rules for error view and error messages.</p> <img alt="html structure" src="assets/images/new_form_16.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">Next we start to work with jQuery Form Plugin. "submitHandler" section contains only one function that responsible for submitting the form without page reloading.</p> <img alt="html structure" src="assets/images/new_form_17.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">We send form data to the server. If we get response from the server - we delete "error-view" and "success-view" classes from the form, make the submit button available.</p> <p style="margin-left: 40px;">But if we get a "success message" class form the server - it means that form submitted successfully. In this case, we can reset the form, update datapickers, make all buttons disabled while success message is shown.</p> <img alt="html structure" src="assets/images/new_form_18.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">After that, we want to hide success message. And, we create a function that will contain some rules: delete success message, make all buttons available, hide all buttons except "next" button (as we work with multistep form), make first fieldset and first step active (only for multistep form)</p> <img alt="html structure" src="assets/images/new_form_19.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">Next we have to add js code for multistep form. This code is multipurpose and doesn't depend from any "id" attribute.</p> <img alt="html structure" src="assets/images/new_form_20.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">There is some interesting moment with form validation. We don't want to allow users to go to the next fieldset if current fieldset has any validation errors. So, every time when "next" button will be clicked - we will validate all fields from current fieldset. And, if any errors will occur - "next" button won't work.</p> <img alt="html structure" src="assets/images/new_form_21.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">With "previous" button - nothing won't change. "Previous" button will work no matter if any validation errors exist in the fieldset or not.</p> <img alt="html structure" src="assets/images/new_form_22.png" style="margin-left: 40px;" > <p style="margin-left: 40px;">Let's summarize: we have created multistep form with steps from scratch. We have discussed all interesting moments and functions. All other forms have the same structure and validation rules. So, this section will help you understand how to create a new form with client-side validation.</p> </section> <section id="few_forms"> <div class="page-header"><h3>Several Forms at One Page</h3><hr class="notop"></div><p> Demo for several forms at one page: &quot;<strong>forms/login_recovery_1.html</strong>&quot;</p> <p>It is very easy to use several forms at one page. You can add any quantity of forms to the one page. You can add any kind of forms to the one page: multistep forms, pop up forms or classic forms. Let us start.</p> <h5> <strong>Step 1:</strong></h5> <p style="margin-left: 40px;" >You have to add several forms at one html page</p> <img alt="html structure" src="assets/images/several_forms_1.png" style="margin-left: 40px;" > <p style="margin-left: 40px;" >Note: these forms have different <strong>"id"</strong> attributes.</p> <h5> <strong>Step 2:</strong></h5> <p style="margin-left: 40px;" >Change <strong>"id"</strong> attribute to the <strong>"class"</strong> attribute in the <strong>"response from server"</strong> divs.</p> <img alt="html structure" src="assets/images/several_forms_2.png" style="margin-left: 40px;" > <h5> <strong>Step 3:</strong></h5> <p style="margin-left: 40px;">Combine js code from both forms in the one <strong>"j-forms.js"</strong> file. Change <strong>"id"</strong> attribute for every form according with <strong>"id"</strong> attribute from the html page.</p> <img alt="html structure" src="assets/images/several_forms_5.png" style="margin-left: 40px;" > <img alt="html structure" src="assets/images/several_forms_6.png" style="margin-left: 40px;" > <h5> <strong>Step 4:</strong></h5> <p style="margin-left: 40px;" >Change <strong>"id"</strong> attribute to the <strong>"class"</strong> attribute in the <strong>"j-forms.js"</strong> for every form on the page.</p> <img alt="html structure" src="assets/images/several_forms_3.png" style="margin-left: 40px;" > <img alt="html structure" src="assets/images/several_forms_4.png" style="margin-left: 40px;" > <h5> <strong>Several multistep forms at one page</strong></h5> <p style="margin-left: 40px;">There are no special rules for several multistep forms at one page. You have to complete all steps from this section and from <strong>Multistep Form</strong> section (if you are creating multistep form from scratch). If you want to have multistep form with validation - please take a look to the <strong>New Form</strong> section. In this section we created a new multistep form with validation and discussed some interesting moments about multistep form validation.</p> <p>Let us summarize: All this may seem scary, but do not worry - this is easier than it seems. As all form from the pack have the similar folder structure, you just have to divide files for one form from files for another form. After you will move through previous steps โ€“ your forms will be ready for work independently from each other.</p> </section> <section id="extensions"> <div class="page-header"><h3>Extensions</h3><hr class="notop"></div> <p> You have already known about folder &quot;<strong>extensions/</strong>&quot;. These extensions represent the features of the <strong>Just Forms advanced</strong> framework that allows you to create and customize any forms with client-side validation.</p> </section> <section id="faq"> <div class="page-header"><h3>FAQ</h3><hr class="notop"></div> <h5> <strong>How to redirect to thanks page after submitting the form?</strong></h5> <p style="margin-left: 40px;">Redirect after success message:</p> <p style="margin-left: 40px;">Please, add next line with code to your main javascript file (j-forms.js)</p> <img src="assets/images/after_success_message.png" alt="new record" style="margin-left: 40px;"> <p style="margin-left: 40px;">Redirect without success message:</p> <p style="margin-left: 80px;">First, let's assume that your server script will add class="error-message" to every error message. So, if your html page doesn't have class="error-message" - it means your form was sent successfully. And you have to change your js code:</p> <img src="assets/images/without_success_message.png" alt="new record" style="margin-left: 80px;"> <p style="margin-left: 80px;">Second, you have to comment (or delete) success message in the <strong>"action.php"</strong>:</p> <img src="assets/images/without_success_message_1.png" alt="new record" style="margin-left: 80px;"> <h5> <strong>I want to create a button instead a link to open a modal form</strong></h5> <p style="margin-left: 40px;">It is very easy. Take a look to the screenshot. All you need to do - is to set your own css properties for the button. As this button is beyond the form wrapper and css properties won't work for this button.</p> <img src="assets/images/button_modal.png" alt="new record" style="margin-left: 40px;"> <h5> <strong>How can I change the width of my form?</strong></h5> <p style="margin-left: 40px;">All forms have two variants of width:</p> <ul style="margin-left: 40px;"> <li><strong>class="wrapper-640"</strong> - 640 px;</li> <li><strong>class="wrapper-400"</strong> - 400 px.</li> </ul> <p style="margin-left: 40px;">For example, you want multistep form will have a width 800px. Open <strong>"j-forms.css"</strong> file and make changes:</p> <img src="assets/images/new_width_1.png" alt="new record" style="margin-left: 40px;"> <p style="margin-left: 40px;">Now your form have a width - 800 px, and it will be responsive when screen width will be equal to 620px. If you want your form will be responsive earlier, for example when screen width will be 750 px, change next line of code:</p> <img src="assets/images/new_width_2.png" alt="new record" style="margin-left: 40px;"> <h5> <strong>I have submitted my form and some error arise. Why this error?</strong></h5> <h5 style="margin-left: 40px;"> <strong>Case 1:</strong></h5> <img src="assets/images/error_1.png" alt="new record" style="margin-left: 80px;"> <p style="margin-left: 80px;">If you get such type of error - most probably you have an error in the form attribute <strong>"action"</strong> in the <strong>"index.php"</strong>. Because javascript code can't find a file which is written in the <strong>"action"</strong> attribute. Be sure that this attribute contains correct path to the <strong>โ€œaction.phpโ€</strong> file.</p> <h5 style="margin-left: 40px;"> <strong>Case 2:</strong></h5> <img src="assets/images/error_2.png" alt="new record" style="margin-left: 80px;"> <p style="margin-left: 80px;">If you get such type of error - most probably you don't have a connection to the internet. Please, check your internet connection.</p> <h5 style="margin-left: 40px;"> <strong>Case 3:</strong></h5> <img src="assets/images/error_3.png" alt="new record" style="margin-left: 80px;"> <p style="margin-left: 80px;">If you get such type of error - most probably you are working on local host and you try to submit a form without localhost connection.</p> <h5 style="margin-left: 40px;"> <strong>Case 4:</strong></h5> <img src="assets/images/error_4.png" alt="new record" style="margin-left: 80px;"> <p style="margin-left: 80px;">If you can see this function when your form is placed on a real web server - for some reasons php code doesn't executing on your server. Please, check logs on your server.</p> </section> <section id="changelog"> <div class="page-header"><h3>Changelog</h3><hr class="notop"></div> <ul> <li><strong>08/13/2015 - Just Forms advanced v 2.0</strong> <p style="margin-left: 40px;"><strong>Note:</strong> if you are not a new buyer - please update main css file <strong>"j-forms.css"</strong> and css files with color settings. All changes are placed in the bottom of the file in the <strong>"Just Forms version 2.0"</strong> section. This update required <strong>only</strong> for new elements and forms. If you won't use any element from the version 2.0 - you may ignore this recommendation.</p> <p style="margin-left: 40px;">Contact form with TinyMCE editor was added. Demo: <strong>"forms/contact_tinymce"</strong></p> <p style="margin-left: 40px;">Multistep form with variable steps was added. Demo: <strong>"forms/multistep_form_with_variable_steps"</strong></p> <p style="margin-left: 40px;">Multistep form with form details was added. Demo: <strong>"extensions/multistep_form_with_details.html"</strong></p> <p style="margin-left: 40px;">Were added multistep forms with dinamically steps: <ul> <li style="margin-left: 80px;"><p>using checkbox - demo: <strong>"forms/multistep_with_dinamic_steps_checkbox"</strong></p></li> <li style="margin-left: 80px;"><p>using radio button - demo: <strong>"forms/multistep_with_dinamic_steps_radio"</strong></p></li> <li style="margin-left: 80px;"><p>using select - demo: <strong>"forms/multistep_with_dinamic_steps_select"</strong></p></li> <li style="margin-left: 80px;"><p>using input field - demo: <strong>"forms/multistep_with_dinamic_steps_input"</strong></p></li> <li style="margin-left: 80px;"><p>combine all types - demo: <strong>"extensions/multistep_with_dinamic_steps_all_types.html"</strong></p></li> </ul> </p> <p style="margin-left: 40px;">Form with google map was added. Demo: <strong>"extensions/form_google_map.html"</strong></p> <p style="margin-left: 40px;">Form with autocomplete google map as a site background was added. Demo: <strong>"extensions/form_map_background_autocomplete.html"</strong></p> <p style="margin-left: 40px;">Were added next plugins: <ul> <li style="margin-left: 80px;"><p>autocomplete feature - demo: <strong>"extensions/autocomplete.html"</strong></p></li> <li style="margin-left: 80px;"><p>cloned element fearure - demo: <strong>"extensions/clone_element.html"</strong></p></li> <li style="margin-left: 80px;"><p>currency feature - demo: <strong>"extensions/currency.html"</strong></p></li> <li style="margin-left: 80px;"><p>youtube and vimeo players - demo: <strong>"extensions/youtube_vimeo.html"</strong></p></li> </ul> </p> <p style="margin-left: 40px;">Order form with logic using checkbox and radio. Demo<strong>"forms/order_logic_check_radio/"</strong></p> <p style="margin-left: 40px;">Order form with logic using input fields. Demo<strong>"forms/order_logic_field/"</strong></p> <p style="margin-left: 40px;">Form with cloned elements was added. Demo<strong>"forms/party_invitation_cloned_elements/"</strong></p> </li> <li><strong>04/15/2015 - Just Forms advanced v 1.0</strong> <p style="margin-left: 40px;">Initial release</p> </li> </ul> </section> <section id="credits"> <div class="page-header"><h3>Credits</h3><hr class="notop"></div> <p> I`ve used the following product in my work:</p> <ul> <li> <a href="http://jquery.com/">jQuery library</a> by jQuery foundation</li> <li> <a href="http://jqueryui.com/">jQuery UI library</a> by jQuery foundation</li> <li> <a href="http://github.com/malsup/form">jQuery Form Plugin</a> by malsup</li> <li> <a href="http://matoilic.github.io/jquery.placeholder/">jQuery Placeholder Plugin</a> by <NAME></li> <li> <a href="http://fontawesome.io/">Font Awesome</a> by <NAME></li> <li> <a href="http://jqueryvalidation.org/">jQuery Validation Plugin</a> by <NAME></li> <li> <a href="http://digitalbush.com/projects/masked-input-plugin/">jQuery Masked Input Plugin</a> by <NAME></li> <li> <a href="https://github.com/bgrins/spectrum">Spectrum Colorpicker</a> by <NAME></li> <li> <a href="http://xflatlinex.github.io/Numeric-Stepper/">Numeric Stepper jQuery plugin</a> by <NAME></li> <li> <a href="http://trentrichardson.com/">jQuery Timepicker Addon</a> by <NAME></li> <li> <a href="http://touchpunch.furf.com/">jQuery UI Touch Punch</a> by <NAME></li> <li> <a href="http://www.tinymce.com/">TinyMCE</a> - Javascript HTML WYSIWYG editor</li> <li> <a href="https://github.com/yapapaya/jquery-cloneya">jQuery Cloneya</a> - jQuery class for cloning DOM elements with their children</li> <li> <a href="https://github.com/BobKnothe/autoNumeric">autoNumeric</a> - International currency formatting</li> <li> <a href="https://www.google.com/maps/">Google Maps</a></li> <li> <a href="https://www.youtube.com">Youtube Player</a></li> <li> <a href="https://vimeo.com/player">Vimeo Player</a></li> </ul> <hr> <p> Thank you for your attention and thank you for making the decision to buy this product. I hope you found it worthwhile.</p> <p>Please, don`t forget to leave nice feedback about this product and rate it <strong>5 stars</strong> :))</p> <br /> <br /> <p>Regards, Alex.</p> </section> </div> </body> </html><file_sep>/src/java/com/mes/sdk/reporting/Reporting.java package com.mes.sdk.reporting; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import com.mes.sdk.core.ApiInterface; import com.mes.sdk.core.Http; import com.mes.sdk.exception.MesRuntimeException; public class Reporting implements ApiInterface<ReportingRequest> { private final Http http; private final ReportingSettings settings; private boolean success; private final static Logger LOG = Logger.getLogger(Reporting.class.getName()); /** * The main object used to communicate. * @param settings An instance of {@link ReportingSettings}. */ public Reporting(ReportingSettings settings) { http = new Http(settings); this.settings = settings; } public ReportingResponse run(ReportingRequest request) { success = false; // Assume false http.setRequestString(parseRequest(request)); if(settings.isVerbose()) LOG.log(Level.INFO, "Sending request: "+http.getRequestString()); http.run(); ReportingResponse resp = parseResponse(); if (settings.isVerbose()) { if(wasSuccessful()) LOG.info("Response: (HTTP "+http.getHttpCode()+" - "+http.getDuration()+"ms - Request Succeeded) " + resp); else { LOG.info("Response: (HTTP "+http.getHttpCode()+" - "+http.getDuration()+"ms - Request Failed) " + resp); LOG.info(resp.getRawResponse()); } } return resp; } public String parseRequest(ReportingRequest request) { StringBuilder requestString = new StringBuilder(); requestString.append("userId=").append(settings.getUserName()); requestString.append("&userPass=").append(settings.getUserPass()); String reportId = null; switch (request.getType()) { case BATCH: reportId = "1"; break; case SETTLEMENT: reportId = "2"; break; case DEPOSIT: reportId = "3"; break; case RECONSCILE: reportId = "4"; break; case CHARGEBACKADJUSTMENTS: reportId = "5"; break; case CHARGEBACKPRENOT: reportId = "6"; break; case RETRIEVAL: reportId = "7"; break; case INTERCHANGE: reportId = "8"; break; case CUSTOM: reportId = "9"; break; case FXBATCH: reportId = "10"; break; case ITLCHARGEBACK: reportId = "11"; break; case ITLRETRIEVAL: reportId = "12"; break; case FXINTERCHANGE: reportId = "13"; break; case INTLDETAILS: reportId = "14"; break; case AUTHLOG: reportId = "15"; break; case GATEWAYREQUESTLOG: reportId = "16"; break; case ACHSETTLEMENT: reportId = "17"; break; case ACHRETURN: reportId = "18"; break; case TRIDENTBATCH: reportId = "19"; break; default: throw new MesRuntimeException("Report type unsupported: "+request.getType()); } requestString.append("&dsReportId=").append(reportId); String reportMode = null; switch (request.getMode()) { case SUMMARY: reportMode = "0"; break; case DETAIL: reportMode = "1"; break; default: throw new MesRuntimeException("Report mode unsupported: " + request.getType()); } requestString.append("&reportType=").append(reportMode); for(Map.Entry<String, String> pair : request.requestTable.entrySet()) { try { requestString = requestString.append("&").append(pair.getKey()).append("=").append(URLEncoder.encode(pair.getValue(), "UTF-8")); } catch (UnsupportedEncodingException e) { throw new MesRuntimeException("Unable to URL Encode the following value: "+pair.getValue()); } } return requestString.toString(); } public ReportingResponse parseResponse() { boolean hasError = false; String error = ""; // Validate HTTP result if(http.getHttpCode() != 200) { error = "Server responded with HTTP code "+http.getHttpCode(); hasError = true; } else { // Some conditions still may return http code 200, with an HTML formatted response. We've no other way to determine the request did not complete: resort to string parsing. String s = http.getRawResponse(); // We've got an HTML response. if(s.matches(".*<html>.*")) { if(s.matches(".*Insufficient rights.*")) error = "Insufficient Rights"; else if(s.matches(".*Invalid user/password.*")) error = "Invalid username or userpass"; else error = "Report Request Failed"; hasError = true; } } if(!hasError) { success = true; ReportingResponse resp = new ReportingResponse( http.getHttpCode(), http.getHttpText(), http.getRawResponse(), http.getDuration() ); return resp; } else { ReportingResponse resp = new ReportingResponse( http.getHttpCode(), http.getHttpText(), error, http.getDuration() ); return resp; } } public boolean wasSuccessful() { return success; } }
3d187d97d02c8e61d909137c6fe09534763b36f7
[ "Java", "HTML" ]
3
Java
ArmandoPrieto/savioDonation
2de17ea46c463456b5dfa8b2a148a761a53ae0b1
9ad5002c0ab01c730c9eadbbe59ea9ecc6856ffc
refs/heads/master
<file_sep>#Projeto iface WEB <file_sep>package br.ufal.ic.validation; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ValidationEmail { public static boolean validate(String email){ // EXPRESSAO REGULAR PATA VALIDAR EMAIL Pattern p = Pattern.compile("^[\\w-]+(\\.[\\w-]+)*@([\\w-]+\\.)+[a-zA-Z]{2,7}$"); Matcher m = p.matcher(email); if (!m.find()){ //EMAIL INVALIDO //PrintError.invalidEmailError(); return false; } else{ return true; } } }<file_sep>package br.ufal.ic.model; import javax.persistence.Embeddable; @Embeddable public class ProfessionalInformation{ private String initialDate; private String finalDate; private String companyName; private String function; public ProfessionalInformation() { this.initialDate = "-"; this.finalDate = "-"; this.companyName = "-"; this.function = "-"; } public String getInitialDate() { return initialDate; } public void setInitialDate(String initialDate) { this.initialDate = initialDate; } public String getFinalDate() { return finalDate; } public void setFinalDate(String finalDate) { this.finalDate = finalDate; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public String getFunction() { return function; } public void setFunction(String function) { this.function = function; } } <file_sep>package br.ufal.ic.validation; public class ValidationData { public static boolean validateNome(String name) { return name != ""; } public static boolean validatePassword(String password) { return password.length() >= 4; } public static boolean validateGender(String gender) { return gender.equalsIgnoreCase("M") || gender.equalsIgnoreCase("F"); } } <file_sep>package br.ufal.ic.validation; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.GregorianCalendar; public class ValidationDate { static public boolean validateDateOfBirth(String dateBirth) { boolean bool = false; Calendar currentDate = new GregorianCalendar(); Calendar dtBirth = Calendar.getInstance(); SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); dtBirth.setLenient(false); try { dtBirth.setTime(dateFormat.parse(dateBirth)); if (validateValuesDate(dateBirth)) { if (dtBirth.after(currentDate)) bool = false; else bool = true; } else { bool = false; } } catch (ParseException ex) { //PrintError.invalidDateError(); bool = false; } return bool; } static public boolean validateSimpleDate(String date) { boolean bool = false; Calendar dt = Calendar.getInstance(); SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); dt.setLenient(false); try { dt.setTime(dateFormat.parse(date)); if (validateValuesDate(date)) bool = true; else bool = false; } catch (ParseException ex) { //PrintError.invalidDateError(); bool = false; } return bool; } static public boolean validateBeginEnd(String begin, String end) { boolean bool = false; Calendar b = Calendar.getInstance(); Calendar e = Calendar.getInstance(); SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); b.setLenient(false); e.setLenient(false); try { b.setTime(dateFormat.parse(begin)); e.setTime(dateFormat.parse(end)); if (validateValuesDate(begin)) { if (b.after(e)) bool = false; else bool = true; } else bool = false; } catch (ParseException ex) { //PrintError.invalidDateError(); bool = false; } return bool; } static private boolean validateValuesDate(String date) { GregorianCalendar calendar = new GregorianCalendar(); int dia = 0, mes = 0, ano = 0; try { String diaStr = date.substring(0, 2); String mesStr = date.substring(3, 5); String anoStr = date.substring(6, 10); dia = Integer.parseInt(diaStr); mes = Integer.parseInt(mesStr); ano = Integer.parseInt(anoStr); } catch (Exception e) { return false; } if (dia < 1 || mes < 1 || ano < 1) { return false; } else if (mes == 1 || mes == 3 || mes == 5 || mes == 7 || mes == 8 || mes == 10 || mes == 12) { if (dia > 31) return false; } else if (mes == 4 || mes == 6 || mes == 9 || mes == 11) { if (dia > 30) return false; } else if (mes == 2) { if (calendar.isLeapYear(ano)) { if (dia <= 29) return false; } else if (dia > 28) return false; } else return false; return true; } } <file_sep>package br.ufal.ic.DAO; import java.util.ArrayList; import java.util.List; import javax.persistence.Query; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import br.ufal.ic.model.User; public class CRUD { static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); static final SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml") .buildSessionFactory(); private static Session session = threadLocal.get(); public static void addInstance(Object instance) { session = sessionFactory.openSession(); try { session.beginTransaction(); session.save(instance); session.getTransaction().commit(); session.close(); } catch (HibernateException e) { e.printStackTrace(); session.getTransaction().rollback(); } } @SuppressWarnings("unchecked") public static User getInstance(String email, String password) { session = sessionFactory.openSession(); List<User> user = new ArrayList<User>(); try { session.beginTransaction(); Query consulta = session.createQuery("from User where email = ? and password = ?"); consulta.setParameter(0, email); consulta.setParameter(1, password); user = consulta.getResultList(); session.getTransaction().commit(); session.close(); } catch (HibernateException e) { e.printStackTrace(); session.getTransaction().rollback(); } if(user.isEmpty()){ return null; } else { return user.get(0); } } }
2122e4ed8da90596ba38d623204d26ba2ce6a2d2
[ "Markdown", "Java" ]
6
Markdown
mrcsz/ifaceWeb
8e41686e581d012392a51e79e83753e8c6b972b5
865e291da7c166484989bd24239fa4916bb31759
refs/heads/master
<file_sep>const firebaseConfig = { apiKey: "<KEY>", authDomain: "book-challenge-app.firebaseapp.com", databaseURL: "https://book-challenge-app.firebaseio.com", projectId: "book-challenge-app", storageBucket: "book-challenge-app.appspot.com", messagingSenderId: "89474317969" }; export default firebaseConfig<file_sep>import React from 'react'; import {View, FlatList, Text, StyleSheet} from 'react-native'; import {Constants} from 'expo'; import {connect} from 'react-redux'; import syncReadHistory from '../../syncReadHistory'; const EntryCard = (props) => ( <View style={styles.card}> <Text style={styles.date}> {props.date} </Text> <Text style={styles.bookName}> {props.book} </Text> <Text style={styles.pagesRead}> {props.pagesRead} pages read </Text> </View> ) class HistoryScreen extends React.Component { componentDidMount() { syncReadHistory() } render() { return ( <View style={styles.container}> <Text style={styles.header}> Your reading history </Text> <FlatList data={this.props.userHistory} renderItem={({item}) => (<EntryCard {...item} key={item.id}/>)} keyExtractor={ ( item, index ) => `${index}` }/> </View> ) } } const mapStateToProps = (state) => ({ userHistory: state.userHistory }) export default connect(mapStateToProps)(HistoryScreen) const styles = StyleSheet.create({ container: { flex: 1, paddingTop: Constants.statusBarHeight+24, paddingLeft: 12, paddingRight: 12, backgroundColor: '#eee' }, header: { fontSize: 24, fontFamily: 'poppins-bold', }, card: { marginTop: 12, backgroundColor: 'white', borderRadius: 5, }, date: { margin: 12, marginBottom: 6, fontSize: 16, fontFamily: 'poppins-bold' }, pagesRead: { margin: 12, marginTop: 2, fontSize: 10, fontFamily: 'poppins-regular' }, bookName: { margin: 12, marginTop: 6, fontSize: 12, fontFamily: 'poppins-semibold' } })<file_sep>import * as functions from 'firebase-functions'; import * as admin from 'firebase-admin'; admin.initializeApp() // // Start writing Firebase Functions // // https://firebase.google.com/docs/functions/typescript // // export const helloWorld = functions.https.onRequest((request, response) => { // response.send("Hello from Firebase!"); // }); export const resetDailyProgress = functions.https.onRequest((request, response) => { const docRef = admin.firestore().doc('challenges/meraki-01').get() let dailyProgress const isSnapshot = docRef.then(snapshot => { dailyProgress = snapshot.data().dailyProgress Object.keys(dailyProgress).forEach(key => { dailyProgress[key] = 0 }) const forUpdateRef = admin.firestore().doc('challenges/meraki-01').update({ dailyProgress: dailyProgress }) forUpdateRef.catch(error => { response.send("Error updating firestore: " + error) }) const newDocRef = admin.firestore().doc('challenges/meraki-01').get() const ifPromiseResolved = newDocRef.then(doc => { const newDailyProgress = doc.data().dailyProgress response.send("Updated firestore data: " + newDailyProgress) }) ifPromiseResolved.catch(error => { response.send("Unable to fetch firestore data after a probable succesful update firestore data") }) }) isSnapshot.catch(error => { response.status(500).send(error) }) }) <file_sep>import SignIn from '../components/screens/SignIn'; import StartScreen from '../components/screens/StartScreen'; import Tabs from './TabNavigation' const AppRoutes = { "Tabs": Tabs, "StartScreen": StartScreen, "SignIn": SignIn, } export default AppRoutes<file_sep>import firebase from './firestore/firestore'; import * as Expo from 'expo'; import store from './redux/store'; import {updateUserUid, addDisplayName} from './redux/actions' import syncAppStateWithCloud from './syncAppStateWithCloud'; import googleLoginConfig from './googleLoginConfig'; const googleLogin = async () => { try { //attempting to authenticate a user using GoogleAuthProvider and retreiving firebase credentials to update the app state console.log("Trying to re-authenticating a user.") const loginTokens = await Expo.Google.logInAsync(googleLoginConfig) const credentials = (loginTokens.type === 'success') ? (firebase.auth.GoogleAuthProvider.credential(loginTokens.idToken, loginTokens.accessToken)) : console.error('Failed retreiving Google login tokens') console.log("Got Auth Tokens...") const firebaseCredentials = await firebase.auth().signInAndRetrieveDataWithCredential(credentials) console.log("Authenticated on firebase successfully!") const firebaseUser = firebaseCredentials.user //dispatching actions to update app state store.dispatch(addDisplayName(firebaseUser.displayName)) store.dispatch(updateUserUid(firebaseUser.uid)) console.log("Dispatched actions: ", store.getState()) //adding user to a challenge and initializing his/her score const docReference = firebase.firestore().doc('challenges/meraki-01') const doc = await docReference.get() console.log("Got document reference") let dailyProgress = doc.data().dailyProgress let totalPagesRead = doc.data().totalPagesRead let users = doc.data().users let userUid = store.getState().userUid let displayName = store.getState().displayName if(!(userUid in dailyProgress)) { const updates = await docReference.update({ dailyProgress: {...dailyProgress, [userUid]: 0}, users: [...users, { name: displayName, uid: userUid }], totalPagesRead: {...totalPagesRead, [userUid]: 0} }) console.log("firestore updated with the user's data") } } catch(error) { console.error(error) } } // const googleLogin = async () => { // try { // var db = firebase.firestore() // var myChallengeRef = db.collection("challenges").doc("meraki-01") // const result = await Expo.Google.logInAsync({ // behavior: __DEV__?'web':'system', // androidClientId: '421651532715-ko49v4dcdn57p2373f5fud57o750aok2.apps.googleusercontent.com', // iosClientId: '421651532715-r9csul8p0319gjl3ps67q2toi4gkae5j.apps.googleusercontent.com', // webClientId: '421651532715-oaqjb1jl4du2iec7lqr3ibih3eg50oc9.apps.googleusercontent.com', // scopes: ['profile','email'], // }) // if(result.type === "success") { // const credential = firebase.auth.GoogleAuthProvider.credential(result.idToken, result.accessToken); // firebase.auth() // .signInAndRetrieveDataWithCredential(credential) // .then(res => { // userUid = res.user.uid // console.log(res.user.displayName) // store.dispatch(addDisplayName(res.user.displayName)) // store.dispatch(updateUserUid(userUid)) // myChallengeRef.get().then(doc => { // let dailyProgress = doc.data().dailyProgress // let totalPagesRead = doc.data().totalPagesRead // let users = doc.data().users // console.log("Hey: " + dailyProgress) // let userUid = store.getState().userUid // let displayName = store.getState().displayName // if(!(userUid in dailyProgress)) { // myChallengeRef.update({ // dailyProgress: { // ...dailyProgress, // [userUid]: 0 // }, // users: [ // ...users, // {name: displayName, uid: userUid} // ], // totalPagesRead: { // ...totalPagesRead, // [userUid]: 0 // } // }) // } // return syncAppStateWithCloud(doc.data()) // }) // }) // } else { // console.log('cancelled') // } // } catch (err) { // console.error(err) // } // } export default googleLogin<file_sep>import React from 'react'; import { View, StyleSheet, Text, ScrollView } from 'react-native'; import { connect } from 'react-redux'; import firebase from '../../firestore/firestore'; import {syncAppStateWithCloudRealTime} from '../../syncAppStateWithCloud'; import OtherChallengers from '../OtherChallengers.js'; class Challenges extends React.Component { componentDidMount() { var db = firebase.firestore().collection("challenges").doc("meraki-01") db.onSnapshot(doc => { syncAppStateWithCloudRealTime(doc.data()) }) } render() { return( <View style={styles.container} > <Text style={styles.header} > OTHER'S PROGRESS: </Text> <View style={{paddingBottom: 16}}> {this.props.challengers.map((challenger, index) => (<OtherChallengers key={index} challenger={challenger} />))} </View> </View> ) } } const mapStateToProps = (state) => ({ dailyTarget: state.dailyTarget, challengers: state.challengers }) export default connect(mapStateToProps)(Challenges) const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#eee' }, header: { fontSize: 20, padding: 8, fontFamily: 'poppins-bold', } })<file_sep>import React from 'react'; import { TouchableOpacity, Text, View, StyleSheet, Linking } from 'react-native'; import googleSignIn from '../../GoogleSignIn'; import {connect} from 'react-redux'; class SignIn extends React.Component { static navigationOptions = { header: null, } componentDidUpdate(prevProps) { if(this.props.isSyncComplete) this.props.navigation.navigate('Progress') } render() { return ( <View style={styles.container}> <TouchableOpacity style={styles.child} onPress={() => { googleSignIn() }} > <Text style={styles.label} > LOG IN WITH BITS MAIL </Text> </TouchableOpacity> </View> ) } } const mapStateToProps = (state) => ({ isSyncComplete: state.isSyncComplete }) export default connect(mapStateToProps)(SignIn) const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'center' }, child: { backgroundColor: '#ff7043', padding: 24, borderRadius: 5, }, label: { fontSize: 16, fontWeight: 'bold', color: 'white', } })<file_sep>import firebase from './firestore/firestore'; import store from './redux/store'; import {syncUserHistory} from './redux/actions'; const syncReadHistory = () => { var userHistoryRef = firebase.firestore().collection('challenges').doc('meraki-01').collection(store.getState().userUid) console.log('Im Here!') var readingHistory = [] userHistoryRef.get().then(querySnapshot => { querySnapshot.forEach(doc => { readingHistory = [doc.data(), ...readingHistory] }) readingHistory.sort((a,b) => (a.timestamp < b.timestamp)) store.dispatch(syncUserHistory(readingHistory)) console.log(store.getState().userHistory) }) } export default syncReadHistory <file_sep>import * as firebase from 'firebase'; import 'firebase/firestore'; import firebaseConfig from './firebaseConfig'; firebase.initializeApp(firebaseConfig) firebase.firestore().settings({ timestampsInSnapshots: true }) export default firebase <file_sep>//action types... export const UPDATE_PAGES_READ_TODAY = 'UPDATE_PAGES_READ_TODAY' export const UPDATE_USER_UID = 'UPDATE_USER_UID' export const SYNC_CHALLENGERS = 'SYNC_CHALLENGERS' export const USER_DAILY_TARGET = 'USER_DAILY_TARGET' export const CHECK_SYNC = 'CHECK_SYNC' export const UPDATE_CHALLENGER_PROGRESS = 'UPDATE_CHALLENGER_PROGRESS' export const SYNC_PAGES_READ_TODAY = 'SYNC_PAGES_READ_TODAY' export const ADD_DISPLAY_NAME = "ADD_DISPLAY_NAME" export const SYNC_USER_HISTORY = "SYNC_USER_HISTORY" export const UPDATE_TOTAL_PAGES_READ = "UPDATE_TOTAL_PAGES_READ" export const SYNC_TOTAL_PAGES_READ = "SYNC_TOTAL_PAGES_READ" //action creators... export const updatePagesReadToday = newEntry => ({ type: UPDATE_PAGES_READ_TODAY, payload: newEntry }) export const updateUserUid = uid => ({ type: UPDATE_USER_UID, payload: uid }) export const syncChallengers = challengers => ({ type: SYNC_CHALLENGERS, payload: challengers }) export const syncUserDailyTarget = dailyTarget => ({ type: USER_DAILY_TARGET, payload: dailyTarget }) export const checkIsSyncComplete = syncState => ({ type: CHECK_SYNC, payload: syncState }) export const updateChallengerProgress = update => ({ type: UPDATE_CHALLENGER_PROGRESS, payload: update }) export const syncPagesReadToday = pagesReadToday => ({ type: SYNC_PAGES_READ_TODAY, payload: pagesReadToday }) export const addDisplayName = displayName => ({ type: ADD_DISPLAY_NAME, payload: displayName }) export const syncUserHistory = userHistory => ({ type: SYNC_USER_HISTORY, payload: userHistory }) export const updateTotalPagesRead = totalPagesRead => ({ type: UPDATE_TOTAL_PAGES_READ, payload: totalPagesRead }) export const synctotalPagesRead = totalPagesRead => ({ type: SYNC_TOTAL_PAGES_READ, payload: totalPagesRead })<file_sep>import React from 'react'; import {View, Text, StyleSheet} from 'react-native'; import store from '../redux/store'; class OtherChallengers extends React.Component { textStyle = () => (this.props.challenger.progress > store.getState().dailyTarget) render() { return ( <View style={styles.container}> <Text style={styles.label}> {this.props.challenger.name} </Text> <Text style={[styles.score, {color: `${this.textStyle()?'green':'red'}`}]}> read {this.props.challenger.progress} pages today </Text> </View> ) } } const styles = StyleSheet.create({ container: { backgroundColor: 'white', borderRadius: 4, marginLeft: 12, marginRight: 12, marginTop: 2, marginBottom: 2 }, label: { margin: 12, marginBottom: 6, fontSize: 16, fontFamily: 'poppins-bold' }, score: { margin: 12, marginTop: 6, fontSize: 12, fontFamily: 'poppins-regular' } }) export default OtherChallengers<file_sep>import Progress from '../components/screens/Progress'; import AddEntry from '../components/screens/AddEntry'; import {createStackNavigator} from 'react-navigation'; const AppRoutes = { "Progress": Progress, "AddEntry": AddEntry, } export default createStackNavigator(AppRoutes)<file_sep>import React from 'react'; import { Text, View, StyleSheet, TouchableOpacity, Image, ScrollView } from 'react-native'; import TodayProgress from '../TodayProgress'; import Challenges from './Challenges'; import {Constants} from 'expo'; import {connect} from 'react-redux'; class Progress extends React.Component { static navigationOptions = { header: null, } handleAddEntryPress = () => { this.props.navigation.navigate('AddEntry') } render() { return( <ScrollView style={styles.container}> <View style={{backgroundColor: 'white', paddingTop: Constants.statusBarHeight + 40,}}> <Image source={require('../../../assets/iron-man.jpg')} style={styles.imageStyling} /> <Text style={styles.nameStyling}>{this.props.displayName}</Text> <Text style={styles.profileDescription}>Novice reader</Text> <TodayProgress/> <View style={styles.addEntryView}> <TouchableOpacity style={styles.addEntryButton} onPress={() => this.handleAddEntryPress()}> <Text style={styles.addEntryButtonText} > + NEW ENTRY </Text> </TouchableOpacity> </View> </View> <Challenges /> </ScrollView> ) } } const mapStateToProps = state => ({ displayName: state.displayName }) export default connect(mapStateToProps)(Progress) const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#eee', }, imageStyling: { height: 80, width: 80, margin: 12, borderRadius: 40, borderColor: 'black', borderWidth: 1, }, nameStyling: { fontSize: 28, fontFamily: 'poppins-bold', marginLeft: 12, paddingBottom: -2, }, profileDescription: { color: '#9e9e9e', fontFamily: 'poppins-regular', fontSize: 12, marginLeft: 12, }, addEntryView: { marginRight: 12, marginLeft: 12, }, addEntryButton: { alignItems: 'center', paddingTop: 12, paddingBottom: 24, }, addEntryButtonText: { color: '#0277bd', fontSize: 12, }, });<file_sep>import React from 'react'; import {View, Text, StyleSheet} from 'react-native'; import {connect} from 'react-redux'; class Stats extends React.Component { render() { return ( <View style={styles.container}> <View> <Text style ={styles.valueStyle}> {this.props.pagesReadToday} </Text> <Text style={styles.captionStyle} > pages read today </Text> </View> <View> <Text style={styles.valueStyle} > {this.props.dailyTarget} </Text> <Text style={styles.captionStyle} > daily target </Text> </View> <View> <Text style={styles.valueStyle} > {this.props.totalPagesRead} </Text> <Text style={styles.captionStyle} > total pages read </Text> </View> </View> ) } } const styles = StyleSheet.create({ container: { flexDirection: 'row', justifyContent: 'space-between', padding: 12, }, valueStyle: { fontSize: 22, fontFamily: 'poppins-bold', }, captionStyle: { color: 'black', fontSize: 12, fontFamily: 'poppins-regular', color: '#9e9e9e' } }) const mapStateToProps = (state) => ({ pagesReadToday: state.pagesReadToday, dailyTarget: state.dailyTarget, totalPagesRead: state.totalPagesRead }) export default connect(mapStateToProps)(Stats)<file_sep>import React from 'react'; import { createAppContainer, createSwitchNavigator } from 'react-navigation'; import {Provider} from 'react-redux'; import {Font} from 'expo'; import store from './src/redux/store'; import SwitchRoutes from './src/navigations/SwitchNavigation'; const AppNavigator = createSwitchNavigator(SwitchRoutes, {initialRouteName: 'StartScreen'}) const App = createAppContainer(AppNavigator) export default class Meraki extends React.Component { async componentDidMount() { await Font.loadAsync({ 'poppins-regular': require('./assets/fonts/Poppins-Regular.ttf'), 'poppins-bold': require('./assets/fonts/Poppins-Bold.ttf'), 'poppins-semibold': require('./assets/fonts/Poppins-SemiBold.ttf') }) console.log('Font loaded!') } render() { return ( <Provider store={store} > <App /> </Provider> ) } }
3e09a1875df9a8b1b616a4d5819bb74cc0875332
[ "JavaScript", "TypeScript" ]
15
JavaScript
Miraj98/book-challenge-app
bddb9c2a5a5f5e799ddbc35abb22a9d7a94f7019
fd6c583b66d6d9345674d88e9af656dda9443611
refs/heads/master
<repo_name>raincoatrun/W4111-database<file_sep>/server.py #!/usr/bin/env python2.7 """ Columbia W4111 Intro to databases Example webserver To run locally python server.py Go to http://localhost:8111 in your browser A debugger such as "pdb" may be helpful for debugging. Read about it online. """ import os from sqlalchemy import * from sqlalchemy.pool import NullPool from flask import Flask, request, render_template, g, redirect, Response import re import time import json import md5 import pdb import random import psycopg2 import traceback tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates') app = Flask(__name__, template_folder=tmpl_dir) # # The following uses the sqlite3 database test.db -- you can use this for debugging purposes # However for the project you will need to connect to your Part 2 database in order to use the # data # # XXX: The URI should be in the format of: # # postgresql://USER:PASSWORD@w4111db.eastus.cloudapp.azure.com/username # # For example, if you had username ewu2493, password <PASSWORD>, then the following line would be: # # DATABASEURI = "postgresql://ewu2493:foobar@w4111db.eastus.cloudapp.azure.com/ewu2493" # #DATABASEURI = "sqlite:///test.db" DATABASEURI = "postgresql://hc2819:KRBJZL@w4111db.eastus.cloudapp.azure.com/hc2819" # # This line creates a database engine that knows how to connect to the URI above # engine = create_engine(DATABASEURI) # # START SQLITE SETUP CODE # # after these statements run, you should see a file test.db in your webserver/ directory # this is a sqlite database that you can query like psql typing in the shell command line: # # sqlite3 test.db # # The following sqlite3 commands may be useful: # # .tables -- will list the tables in the database # .schema <tablename> -- print CREATE TABLE statement for table # # The setup code should be deleted once you switch to using the Part 2 postgresql database # #engine.execute("""DROP TABLE IF EXISTS test;""") #engine.execute("""CREATE TABLE IF NOT EXISTS test ( # id serial, # name text #);""") #engine.execute("""INSERT INTO test(name) VALUES ('grace hopper'), ('alan turing'), ('ada lovelace');""") # # END SQLITE SETUP CODE # @app.before_request def before_request(): """ This function is run at the beginning of every web request (every time you enter an address in the web browser). We use it to setup a database connection that can be used throughout the request The variable g is globally accessible """ try: g.conn = engine.connect() except: print "uh oh, problem connecting to database" import traceback; traceback.print_exc() g.conn = None @app.teardown_request def teardown_request(exception): """ At the end of the web request, this makes sure to close the database connection. If you don't the database could run out of memory! """ try: g.conn.close() except Exception as e: pass # # @app.route is a decorator around index() that means: # run index() whenever the user tries to access the "/" path using a GET request # # If you wanted the user to go to e.g., localhost:8111/foobar/ with POST or GET then you could use # # @app.route("/foobar/", methods=["POST", "GET"]) # # PROTIP: (the trailing / in the path is important) # # see for routing: http://flask.pocoo.org/docs/0.10/quickstart/#routing # see for decorators: http://simeonfranklin.com/blog/2012/jul/1/python-decorators-in-12-steps/ # @app.route('/') def index(): """ request is a special object that Flask provides to access web request information: request.method: "GET" or "POST" request.form: if the browser submitted a form, this contains the data in the form request.args: dictionary of URL arguments e.g., {a:1, b:2} for http://localhost?a=1&b=2 See its API: http://flask.pocoo.org/docs/0.10/api/#incoming-request-data """ # DEBUG: this is debugging code to see what request looks like print request.args #cursor = g.conn.execute("select rid from restaurants;") #cursor = g.conn.execute("select rm.namemenu, rt.name,m.caloryamount, m.proteinamount, m.sodiumamount, rm.price from restaurants rt, restaurantsmenu rm, menunutrients m where rm.rid = rt.rid and rm.mid = m.mid and m.rid = rm.rid; ") # print len(cursor) #for item in cursor: #print item['rid'] #cursor.close() names = [] # # Flask uses Jinja templates, which is an extension to HTML where you can # pass data to a template and dynamically generate HTML based on the data # (you can think of it as simple PHP) # documentation: https://realpython.com/blog/python/primer-on-jinja-templating/ # # You can see an example template in templates/index.html # # context are the variables that are passed to the template. # for example, "data" key in the context variable defined below will be # accessible as a variable in index.html: # # # will print: [u'grace hopper', u'alan turing', u'ada lovelace'] # <div>{{data}}</div> # # # creates a <div> tag for each element in data # # will print: # # # # <div>grace hopper</div> # # <div>alan turing</div> # # <div>ada lovelace</div> # # # {% for n in data %} # <div>{{n}}</div> # {% endfor %} # context = dict(data = names) # # render_template looks in the templates/ folder for files. # for example, the below file reads template/index.html # return render_template("index.html", **context) # # Flask uses Jinja templates, which is an extension to HTML where you can # pass data to a template and dynamically generate HTML based on the data # (you can think of it as simple PHP) # documentation: https://realpython.com/blog/python/primer-on-jinja-templating/ # # You can see an example template in templates/index.html # # context are the variables that are passed to the template. # for example, "data" key in the context variable defined below will be # accessible as a variable in index.html: # # # will print: [u'grace hopper', u'alan turing', u'ada lovelace'] # <div>{{data}}</div> # # # creates a <div> tag for each element in data # # will print: # # # # <div>grace hopper</div> # # <div>alan turing</div> # # <div>ada lovelace</div> # # # {% for n in data %} # <div>{{n}}</div> # {% endfor %}: # #context = dict(foodname = foodname, restautrant = restaurantname, sodium = sodium, calorie = calorie, protein = protein, price = price ) # # render_template looks in the templates/ folder for files. # for example, the below file reads template/index.html # @app.route('/') def approot(): return render_template("index.html") # # This is an example of a different path. You can see it at # # localhost:8111/another # # notice that the functio name is another() rather than index() # the functions for each app.route needs to have different names # #@app.route('/another') #def another(): # return render_template("anotherfile.html") #@app.route('/basicsearch', methods=['POST']) #def basicsearch(): # name = request.form['name'] # g.conn.execute('INSERT INTO test VALUES (NULL, ?)', name) # return redirect('/') # Example of adding new data to the database @app.route('/order_page') def order_page(): return render_template("order.html") @app.route('/back', methods=['POST','GET']) def back(): return render_template("index.html") @app.route('/search', methods=['POST','GET']) def search(): restaurant = '%' category = '%' calorie_upper = 100000 calorie_lower = 0 sodium_upper = 100000 sodium_lower = 0 protein_upper = 100000 protein_lower = 0 keyword = '%' #for item in request.form: # print item # print request.form[item] temp = request.form['restaurant'] print len(temp) if temp != '': seq = ('%', temp, '%') restaurant = "".join(seq) print restaurant #restaurant = request.form['restaurant'] temp = request.form['category'] if temp != '': seq = ('%', temp, '%') category = "".join(seq) print category #category = request.form['category'] temp = request.form['calorie_upper'] if temp != '': calorie_upper = temp temp = request.form['calorie_lower'] if temp != '': calorie_lower = temp temp = request.form['sodium_upper'] if temp != '': sodium_upper = temp #temp = request.form['sodium_lower'] temp = request.form['sodium_lower'] if temp != '': sodium_lower = temp temp = request.form['protein_upper'] if temp != '': protein_upper = temp temp = request.form['protein_lower'] if temp != '': protein_lower = temp temp = request.form['keyword'] if temp != '': seq = ('%', temp, '%') keyword = "".join(seq) print keyword #keyword = request.form['keyword'] q = 'select rm.namemenu, rt.name,m.caloryamount, m.proteinamount, m.sodiumamount, rm.price from restaurants rt, restaurantsmenu rm, menunutrients m where rm.rid = rt.rid and rm.mid = m.mid and m.rid = rm.rid and rt.name like %s and lower(rm.namemenu) like %s and rm.category like %s and m.caloryamount < %s and m.caloryamount > %s and m.sodiumamount < %s and m.sodiumamount > %s and m.proteinamount < %s and m.proteinamount > %s;' #q = "select rm.namemenu, rt.name,m.caloryamount, m.proteinamount, m.sodiumamount, rm.price from restaurants rt, restaurantsmenu rm, menunutrients m where rm.rid = rt.rid and rm.mid = m.mid and m.rid = rm.rid; " print q try: cursor = g.conn.execute(q, (restaurant, keyword, category, calorie_upper, calorie_lower,sodium_upper, sodium_lower, protein_upper, protein_lower,)) #cursor = g.conn.execute(q) #cursor = g.conn.execute("select rm.namemenu, rt.name,m.caloryamount, m.proteinamount, m.sodiumamount, rm.price from restaurants rt, restaurantsmenu rm, menunutrients m where rm.rid = rt.rid and rm.mid = m.mid and m.rid = rm.rid; ") foodname = [] restaurantname = [] sodium = [] calorie = [] protein = [] price = [] error = [] # # example of a database query # for result in cursor: print result['namemenu'] foodname.append(result['namemenu'])# can also be accessed using result[0] print result['name'] restaurantname.append(result['name']) print result['sodiumamount'] sodium.append(result['sodiumamount']) print result['caloryamount'] calorie.append(result['caloryamount']) print result['proteinamount'] protein.append(result['proteinamount']) print result['price'] price.append(result['price']) cursor.close() print restaurantname #context = dict(foodname = foodname, restautrant = restaurantname, sodium = sodium, calorie = calorie, protein = protein, price = price ) #g.conn.execute('INSERT INTO test VALUES (NULL, ?)', name) return render_template("index.html", foodname = foodname, restaurant = restaurantname, sodium = sodium, calorie = calorie, protein = protein, price = price) except Exception as e: q = "Not found" print q error.append(q) return render_template("index.html", error = error) @app.route('/order', methods=['POST','GET']) def order(): restaurant = request.form['restaurant'] print restaurant foodname = request.form['foodname'] print foodname quantity = request.form['quantity'] print quantity name = request.form['name'] print name deliverytime = request.form['deliverytime'] print deliverytime address = request.form['address'] print address mid = [] rid = [] amount = [] uid = [] oid = [] price = 0 calorie = 0 sodium = 0 protein = 0 foodname_list = [] restaurant_list = [] name_list = [] address_list = [] totalprice_list = [] foodname_list.append(foodname) restaurant_list.append(restaurant) name_list.append(name) address_list.append(address) amount.append(quantity) q = 'select rm.mid, rt.rid, rm.price, m.caloryamount, m.sodiumamount, m.proteinamount from restaurants rt, restaurantsmenu rm, menunutrients m where rt.rid = rm.rid and m.mid = rm.mid and rm.namemenu = %s and rt.name = %s;' print q try: cursor1 = g.conn.execute(q, (foodname, restaurant, ) ) for result in cursor1: mid.append(result['mid']) print result['mid'] rid.append(result['rid']) print result['rid'] price = price + int(result['price']) print result['price'] calorie = calorie + int(result['caloryamount']) print result['caloryamount'] sodium = sodium + int(result['sodiumamount']) print result['sodiumamount'] protein = protein + int(result['proteinamount']) print result['proteinamount'] cursor1.close() q2 = 'select uid from usersearch;' print q2 cursor2 = g.conn.execute(q2) for result in cursor2: uid.append(result['uid']) print result['uid'] length_uid = len(uid) cursor2.close() uid_new = length_uid + 21 q3 = 'select oid from userorder;' cursor3 = g.conn.execute(q3) for result in cursor3: oid.append(result['oid']) print result['oid'] cursor3.close() length_oid = len(oid) oid_new = length_oid + 100 q4 = 'insert into usersearch (uid, name) Values(%s, %s)' print q4 g.conn.execute(q4, (uid_new, name,)) totalprice = price * int(amount[0]) print totalprice totalprice_list.append(totalprice) q5 = 'insert into userorder (uid, oid, deliveraddress, totalprice) Values(%s, %s, %s, %s)' print q5 print address print totalprice g.conn.execute(q5, (uid_new, oid_new, address, totalprice,)) print "success" print foodname_list print name_list print address_list print amount print restaurant_list print totalprice_list return render_template("final.html", foodname = foodname_list, name = name_list, deliveraddress = address_list, quantity = amount, restaurant = restaurant_list, totalprice = totalprice_list) # return redictrict('another') except Exception as e: return render_template("index.html") @app.route('/login', methods=['GET','POST']) def login(): abort(401) this_is_never_executed() if __name__ == "__main__": import click @click.command() @click.option('--debug', is_flag=True) @click.option('--threaded', is_flag=True) @click.argument('HOST', default='0.0.0.0') @click.argument('PORT', default=8111, type=int) def run(debug, threaded, host, port): """ This function handles command line parameters. Run the server using python server.py Show the help text using python server.py --help """ HOST, PORT = host, port print "running on %s:%d" % (HOST, PORT) app.run(host=HOST, port=PORT, debug=debug, threaded=threaded) run()
b06fbaef670c3e6426f9f0b04a769a4c96512946
[ "Python" ]
1
Python
raincoatrun/W4111-database
68bb72b50f2103e8e80ca8c15c444ebb93fc41f7
3a86a20b7f6cceaa39a9c8b88e032fccda91386b
refs/heads/master
<file_sep>from setuptools import setup setup(name='brightsign-MRSSMaker', version='1.0.0', description='given a directory of jpegs, generates a brightsign compatible MRSS feed', url='http://github.com/riordan/brightsign-py-mrss-maker', author='<NAME>', author_email='<EMAIL>', license='Apache-2.0', packages=['mrssMaker'], install_requires=["six"], entry_points={ 'console_scripts': [ 'mrssMaker=mrssMaker:generateMRSS', ], }, zip_safe=False) <file_sep>from __future__ import print_function import logging import hashlib import os import mimetypes from six.moves.urllib.parse import urljoin import argparse class MRImage: filePath = None link = None fileHash = None fileSize = None mimetype = None name = None displaytime = None def __init__(self, localpath, baseurl, displaytime=30): self.filePath = localpath self.fileSize = os.path.getsize(localpath) self.mimetype = mimetypes.MimeTypes().guess_type(localpath)[0] with open(localpath, 'rb') as f: self.fileHash = hashlib.sha1(f.read()).hexdigest() path, filename = os.path.split(localpath) self.name = filename pathcomponents = path.split('/') del pathcomponents[0] pathcomponents.append(filename) self.link = urljoin(baseurl, os.path.join(*pathcomponents)) self.displaytime = displaytime def __repr__(self): return "%s(%r)" % (self.__class__, self.__dict__) # parser = argparse.ArgumentParser(description='Create a BS Image') # parser.add_argument("image", help="image location") # args = parser.parse_args() # # i = MRImage(args.image, "http://sample.com/images") # print(i) <file_sep>mrss-maker =========== Generates MRSS feed for a set of images Generates MRSS for Brightsign, based on [Brightsign's Custom MRSS](http://support.brightsign.biz/hc/en-us/articles/218067267-Supported-Media-RSS-feeds). Works for: * video formats: * ts * mpg * vob * mov * mp4 * images * jpeg * bmp * png Does not work for GIFs. Which is sad. Each feed consists of: * Own Filename (output location) * MediaBaseURL: Root URL for all media (assumed to be entry level) * Title * Description * Images * Image Things * Image Times # Instructions ## Installation ``` virtualenv env #(or whichever location for virtualenvironment brightsign work) source env/bin/activate git clone <THIS REPOSITORY> cd brightsign-py-mrss-maker pip install -e . ``` ## Usage ``` mrssMaker usage: mrssMaker [-h] base_url feed_url media_folder Create a Brightsign MRSS feed from a directory of images positional arguments: base_url Default location of MRSS assets when hosted (eg http://...01/content/media/) feed_url Default location of MRSS feed assets when hosted (eg http://...01/content/feed.xml) media_folder folder of media assets optional arguments: -h, --help show this help message and exit ``` # Background This project is is derived from the [brown-brightsign-shows](https://github.com/riordan/brightsign-brown-shows) repository (defunct). <file_sep>import os import datetime import hashlib import argparse from imagemrss import MRImage from six.moves.urllib.parse import urljoin import xml.etree.ElementTree as ET from xml.dom import minidom import sys """ python mrss.py http://baseurl/maybe/the/media/folder/ http://baseurl/maybe/the/feed.xml targetfolder/ Given a Media directory URL, a final feed URL, and a target folder, generates an mrss file for that folder of images. """ def prettify(elem): """Return a pretty-printed XML string for the Element. """ rough_string = ET.tostring(elem, 'utf-8') reparsed = minidom.parseString(rough_string) return reparsed.toprettyxml(indent=" ") # Brightsign MRSS Documentation # http://support.brightsign.biz/hc/en-us/articles/218067267-Supported-Media-RSS-feeds def generateMRSS(): parser = argparse.ArgumentParser(description='Create a Brightsign MRSS feed from a directory of images') parser.add_argument("base_url", help="Default location of MRSS assets when hosted (eg http://...01/content/media/)") parser.add_argument("feed_url", help="Default location of MRSS feed assets when hosted (eg http://...01/content/feed.xml)") parser.add_argument("media_folder", help="folder of media assets") if len(sys.argv[1:])==0: print("Need help?") parser.print_help() # parser.print_usage() # for just the usage line parser.exit() args = parser.parse_args() base_directory = args.media_folder filelist = [] for root,directories, filenames, in os.walk(base_directory): for filename in filenames: if ".DS_Store" in filename: pass else: filepath = os.path.join(root, filename) filelist.append(MRImage(filepath, args.base_url)) ############### # Make MRSS # ############### rss = ET.Element('rss', attrib={'version':'2.0', 'xmlns:media':'http://search.yahoo.com/mrss/'}) channel = ET.Element('channel') rss.append(channel) channelTitle = ET.Element('title') channelTitle.text="Brightsign MRSS Feed" channel.append(channelTitle) channelLink = ET.Element('link') channelLink.text = args.feed_url channel.append(channelLink) channelDescription = ET.Element('description') channelDescription.text = "Test of a MRSS Generator" channel.append(channelDescription) channelTTL = ET.Element('ttl') channelTTL.text = '1' channel.append(channelTTL) ############# # Generate files in feed ############# # Acceptable mimetypes for MRSS mimes_img=['image/jpeg', 'image/png', 'image/bmp', 'image/jpeg'] mimes_vid=['video/ts', 'video/mpg', 'video/vob', 'video/mov', 'video/mp4'] for img in filelist: if img.mimetype in mimes_img or img.mimetype in mimes_vid: item = ET.Element('item') itemTitle = ET.Element('title') itemTitle.text = img.name item.append(itemTitle) itemLink = ET.Element('link') itemLink.text = img.link item.append(itemLink) itemCategory = ET.Element('category') itemCategory.text = "image" item.append(itemCategory) itemDescription = ET.Element('description') itemDescription.text = img.name item.append(itemDescription) itemGUID = ET.Element('guid', attrib={'isPermaLink':'false'}) itemGUID.text = img.fileHash item.append(itemGUID) mediaContentAttribs = { 'url':str(img.link), 'fileSize':str(img.fileSize), 'type':str(img.mimetype) } if img.mimetype in mimes_img: mediaContentAttribs['medium'] = 'image' mediaContentAttribs['duration'] = str(img.displaytime) elif img.mimetype in mimes_vid: mediaContentAttribs['medium'] = 'video' itemMediaContent = ET.Element('media:content', attrib = mediaContentAttribs) item.append(itemMediaContent) channel.append(item) else: pass print(prettify(rss)) <file_sep>from .mrss import generateMRSS
a661d81740fe46f40f263889fcd66460661bbda6
[ "Markdown", "Python" ]
5
Python
riordan/brightsign-py-mrss-maker
ccdb29519d36458e3badea19cb422b46abd2b94c
9bf131bdaf551c53b638e4feb045cc52569d71dc
refs/heads/master
<file_sep>package com.china.oil.application.web; import com.china.oil.application.interceptor.UserSecurityInterceptor; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * Created by yangchujie on 16/1/22. */ @Configuration @EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) { // registry.addInterceptor(new LocaleInterceptor()); // registry.addInterceptor(new ThemeInterceptor()).addPathPatterns("/**").excludePathPatterns("/admin/**"); registry.addInterceptor(new UserSecurityInterceptor()).addPathPatterns("/user/**"); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/css/**") .addResourceLocations("classpath:/static/css/"); registry.addResourceHandler("/js/**") .addResourceLocations("classpath:/static/js/"); registry.addResourceHandler("/images/**") .addResourceLocations("classpath:/static/images/"); } }<file_sep>๏ปฟ;$(function(){ getContent1.initialize({ element:$('.content_1') }); getContent2.initialize({ element:$('.content_2') }); getContent3.initialize({ element:$('.content_3') }); }); var getContent1={ initialize: function (option) { $.extend(this, option); this.init(); this.element.on('change', '#fun1_select', $.proxy(this.selectEvt, this));//ไธ‹ๆ‹‰่œๅ•ๅˆ‡ๆขไบ‹ไปถ }, init:function(){ var data=[{ name:'ๅ›ฝๅฎถ', type:'line', data:[110, 120, 150, 183, 192, 210, 310], }]; var category=['2010ๅนด','2011ๅนด','2012ๅนด','2013ๅนด','2014ๅนด','2015ๅนด']; var otherInfo={ title:'็Ÿณๆฒนๅ‹˜ๆŽข่ต„้‡‘ๆŠ•ๅ…ฅๆฏ”', dw:'ไธ‡ๅ…ƒ', legend:['ๅ›ฝๅฎถ'], boundaryGap:true }; createChart('content_chart1', data, category, otherInfo); }, selectEvt:function(){//ไธ‹ๆ‹‰ๆก†็š„ๆ”นๅ˜็š„ไบ‹ไปถ๏ผŒ้œ€่ฆๅฐ่ฃ…ๆ–ฐ็š„ๆ•ฐๆฎๆŽฅๅฃ๏ผŒๅ†่ฐƒ็”จcreateChartๆ–นๆณ• var opt = this.element.find("#fun1_select option:selected"); var index = opt[0].index; if(index==0){//ๅ…จๅ›ฝๆ•ฐๆฎ this.init(); } else if(index==1){//ๆฒนๅ…ฌๅธๆ•ฐๆฎ this.companyData(); } }, companyData:function(){ var data=[{ name:'ไธญ็Ÿณๆฒน', type:'line', data:[110, 120, 150, 240, 312, 413, 510], },{ name:'ไธญ็ŸณๅŒ–', type:'line', data:[110, 130, 250, 260, 350, 430, 470], },{ name:'ไธญๆตทๆฒน', type:'line', data:[110, 210, 350, 410, 450, 530, 510], },{ name:'ๅœฐๆ–น', type:'line', data:[120, 210, 360, 450, 550, 570, 590], }]; var category=['2010ๅนด','2011ๅนด','2012ๅนด','2013ๅนด','2014ๅนด','2015ๅนด']; var otherInfo={ title:'็Ÿณๆฒนๅ‹˜ๆŽข่ต„้‡‘ๆŠ•ๅ…ฅๆฏ”', dw:'ไธ‡ๅ…ƒ', legend:['ไธญ็Ÿณๆฒน','ไธญ็ŸณๅŒ–','ไธญๆตทๆฒน','ๅœฐๆ–น'], boundaryGap:true }; createChart('content_chart1', data, category, otherInfo); } } var getContent2={ initialize: function (option) { $.extend(this, option); this.init(); }, init:function(){ $.ajax({ url: url+"/sp01/SpecialSubject01_02", // ่Žทๅ–ไธ“้ข˜ไธ€็ฌฌไบŒ้กน็š„ๆ•ฐๆฎ, data:{year:2007}, dataType: "json", //data: { "id": "value" }, type: "post", success: function(data) { var datainfo=data.datainfo; var category=data.category; var otherInfo={ title:'ๅ„ๆฒนๅ…ฌๅธ็Ÿณๆฒนๅ‹˜ๆŽข่ต„้‡‘ๆŠ•ๅ…ฅๆฏ”', dw:'ไธ‡ๅ…ƒ' }; createPie('content_chart2', datainfo, category, otherInfo); }, error: function() { alert('่ฏทๆฑ‚ๅผ‚ๅธธ'); } }); } } var getContent3={ initialize: function (option) { $.extend(this, option); this.init(); this.element.on('change', '#fun3_select', $.proxy(this.selectEvt, this));//ไธ‹ๆ‹‰่œๅ•ๅˆ‡ๆขไบ‹ไปถ }, init:function(){ ajaxSpecialSubject0103("ๅ›ฝๅฎถ"); }, selectEvt:function(){ var opt = this.element.find("#fun3_select option:selected"); var index = opt[0].index; if(index==0){//ๅ…จๅ›ฝๆ•ฐๆฎ this.init(); } else {//ๆฒนๅ…ฌๅธๆ•ฐๆฎ var companyname=opt[0].value; alert(companyname); this.companyData(companyname); } }, companyData:function(companyname){ ajaxSpecialSubject0103(companyname); //var data=[{ // name:'ไบŒ็ปดๅœฐ้œ‡่ดน็”จ', // type:'bar', // data:[210, 310, 350, 430, 520, 630, 600], // //},{ // name:'ไธ‰็ปดๅœฐ้œ‡่ดน็”จ', // type:'bar', // data:[210, 210, 450, 530, 550, 630, 640], // //},{ // name:'ๅผ€ๅ‘ไบ•ๆŠ•่ต„่ดน็”จ', // type:'bar', // data:[210, 310, 350, 330, 450, 530, 640], // //}]; //var category=['2010ๅนด','2011ๅนด','2012ๅนด','2013ๅนด','2014ๅนด','2015ๅนด']; //var otherInfo={ // title:'ไธญ็ŸณๆฒนๆŠ•ๅ…ฅไบŒใ€ไธ‰็ปดๅœฐ้œ‡่ดน็”จ', // dw:'ไธ‡ๅ…ƒ', // legend:['ไบŒ็ปดๅœฐ้œ‡่ดน็”จ','ไธ‰็ปดๅœฐ้œ‡่ดน็”จ','ๅผ€ๅ‘ไบ•ๆŠ•่ต„่ดน็”จ'], // boundaryGap:true //}; //createChart('content_chart3', data, category, otherInfo); } }<file_sep>package com.china.oil.application.controller; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.Scan; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.data.hadoop.hbase.RowMapper; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by dell-pc on 2016/4/19. */ @Controller @EnableAutoConfiguration @RequestMapping("/data") public class Subject01Controller extends BaseController { /** * ไธ“้ข˜ไธ€็ฌฌไธ€้กน็š„ๆ•ฐๆฎ API * @return data json */ @RequestMapping(value="/SpecialSubject01_01", method= RequestMethod.GET, produces="application/json;charset=UTF-8") @ResponseBody public String SpecialSubject01_01(){ Map resultMap = new HashMap(); Scan s_dk00 = new Scan(); s_dk00.addColumn("info".getBytes(), "NF".getBytes()); s_dk00.addColumn("info".getBytes(), "KTTZ".getBytes()); /** * ่ฏป HBase ่กจ โ€˜DK00_NATIONEXPโ€™ ๆŠฝๅ–็›ธๅ…ณๆ•ฐๆฎ */ List<Map> dk00_rows = hbaseTemplate.find("DK00_NATIONEXP", s_dk00, new RowMapper<Map>() { public Map mapRow(Result result, int rowNum) throws Exception { Map map = new HashMap(); map.put("NF", new String(result.getValue("info".getBytes(), "NF".getBytes()))); map.put("KTTZ", new String(result.getValue("info".getBytes(), "KTTZ".getBytes()))); return map; } }); Scan s_dk01 = new Scan(); s_dk01.addColumn("info".getBytes(), "NF".getBytes()); s_dk01.addColumn("info".getBytes(), "DWMC".getBytes()); s_dk01.addColumn("info".getBytes(), "KTTZ".getBytes()); /** * ่ฏป HBase ่กจ โ€˜DK01_COMPEXPโ€™ ๆŠฝๅ–็›ธๅ…ณๆ•ฐๆฎ */ List<Map> dk01_rows = hbaseTemplate.find("DK01_COMPEXP", s_dk01, new RowMapper<Map>() { public Map mapRow(Result result, int rowNum) throws Exception { Map map = new HashMap(); map.put("NF", new String(result.getValue("info".getBytes(), "NF".getBytes()))); map.put("DWMC", new String(result.getValue("info".getBytes(), "DWMC".getBytes()))); map.put("KTTZ", new String(result.getValue("info".getBytes(), "KTTZ".getBytes()))); return map; } }); Scan s_dk02 = new Scan(); s_dk02.addColumn("info".getBytes(), "NF".getBytes()); s_dk02.addColumn("info".getBytes(), "YFGSMC".getBytes()); s_dk02.addColumn("info".getBytes(), "KTJFTR".getBytes()); /** * ่ฏป HBase ่กจ โ€˜DK02_SUBCOMPEXโ€™ ๆŠฝๅ–็›ธๅ…ณๆ•ฐๆฎ */ List<Map> dk02_rows = hbaseTemplate.find("DK02_SUBCOMPEX", s_dk02, new RowMapper<Map>() { public Map mapRow(Result result, int rowNum) throws Exception { Map map = new HashMap(); map.put("NF", new String(result.getValue("info".getBytes(), "NF".getBytes()))); map.put("YFGSMC", new String(result.getValue("info".getBytes(), "YFGSMC".getBytes()))); map.put("KTJFTR", new String(result.getValue("info".getBytes(), "KTJFTR".getBytes()))); return map; } }); resultMap.put("dk00", dk00_rows); resultMap.put("dk01", dk01_rows); resultMap.put("dk02", dk02_rows); return gson.toJson(resultMap); } @RequestMapping(value = "/SpecialSubject01_02", method= RequestMethod.GET, produces = "application/json;charset=UTF-8") @ResponseBody public String SpecialSubject01_02(/*@RequestParam(value = "year") int year*/) { /** * ่ฏป HBase ่กจ โ€˜DK01_COMPEXPโ€™ ๆŠฝๅ–็›ธๅ…ณๆ•ฐๆฎ */ String[] fieldList = {"NF", "DWMC", "KTTZ"}; List<Map> dk01_rows = hbaseUtil.findHBaseTable("DK01_COMPEXP", fieldList); /*List<Map> maplist = new ArrayList<>(); for (Map dk01_map : dk01_rows) { int temp = Integer.parseInt((String) dk01_map.get("NF")); if (temp == year) { Map map = new HashMap(); map.put("NF", dk01_map.get("NF")); map.put("DWMC", dk01_map.get("DWMC")); map.put("KTTZ", dk01_map.get("KTTZ")); maplist.add(map); } } return gson.toJson(jsonUtil.getDK01_COMPEXPJsonMap(maplist));*/ return gson.toJson(jsonUtil.getDK01_COMPEXPJsonMap(dk01_rows)); } /** * ไธ“้ข˜1็ฌฌไธ‰้กนๅ…ฌๅธๆ•ฐๆฎๅฑ•็คบ * @param companyname * @return */ @RequestMapping(value = "/SpecialSubject01_03", method= RequestMethod.GET, produces = "application/json;charset=UTF-8") @ResponseBody public String SpecialSubject01_03(@RequestParam(value="companyname", required=false) String companyname) { /* * ่ฏป HBase ่กจ โ€˜DK01_COMPEXPโ€™ ๆŠฝๅ–็›ธๅ…ณๆ•ฐๆฎ * NF ๅนดไปฝ EWDZFYไบŒ็ปดๅ›ฝๅฎถ่ดน็”จ SWDZFY ไธ‰็ปดๅ›ฝๅฎถ่ดน็”จ KFTZ */ if(companyname==null||companyname.trim().length()==0){ companyname = "ๅ›ฝๅฎถ"; } List<Map> dk03_rows; if (companyname.equals("ๅ›ฝๅฎถ")) { String[] fieldList = {"NF", "EWDZFY", "SWDZFY"}; dk03_rows = hbaseUtil.findHBaseTable("DK00_NATIONEXP", fieldList); return gson.toJson(dk03_rows); } else { String[] fieldList = {"NF", "DWMC", "EWDZFY", "SWDZFY"}; dk03_rows = hbaseUtil.findHBaseTable("DK01_COMPEXP", fieldList); //่ฟ‡ๆปคcompanyname /*List<Map> maplist = new ArrayList<>(); for (Map dk03map : dk03_rows) { String company = (String) dk03map.get("DWMC"); if (company.equals(companyname)) { maplist.add(dk03map); } }*/ return gson.toJson(dk03_rows); } } } <file_sep>package com.china.oil.application.controller; //import com.china.oil.application.entity.User; //import com.china.oil.application.repository.UserRepository; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.Scan; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.data.hadoop.hbase.RowMapper; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by yangchujie on 15/12/28. */ @Controller @EnableAutoConfiguration public class WebController extends BaseController{ /** * ้ฆ–้กต * @return */ @RequestMapping("/") public String introduce(){ return "introduce"; } /** * ๅœฐๅ›พ้กต้ข * @return */ @RequestMapping("/data") public String data(){ return "data"; } @RequestMapping("/index") public String index(){ return "index"; } @RequestMapping("/news") public String news(){ return "news"; } /** * ไธ“้ข˜ไธ€็ฌฌไธ€้กนๆ•ฐๆฎๅฑ•็คบdemo * @return */ @RequestMapping("/charts") public String charts(){ return "sy"; } @RequestMapping("/sy") public String sy(){ return "sy"; } @RequestMapping("/fl") public String fl(){ return "fl"; } @RequestMapping("/sysm") public String sysm(){ return "introduce"; } @RequestMapping(value = "/subpage/KTTR") public ModelAndView subpage_KTTR(HttpServletResponse httpServletResponse) throws IOException { ModelAndView modelAndView=new ModelAndView(); modelAndView.setViewName("subpage/KTTR"); //่ฟ™้‡Œๅบ”่ฏฅๆ˜ฏไปŽHbaseไธญๆŸฅๆ‰พ็Ÿณๆฒนๅ…ฌๅธๅˆ—่กจ็š„ๆ•ฐๆฎ String[] companList={"ไธญ็Ÿณๆฒน","ไธญ็ŸณๅŒ–","ไธญๆตทๆฒน","ไธญ่”ๅ…ฌๅธ","ๅœฐๆ–น"}; String[] yearList={"2007","2008","2009","2010","2011","2012","2013"}; modelAndView.addObject("yearList",yearList); modelAndView.addObject("companylist",companList); return modelAndView; } @RequestMapping("/subpage/KTCG") public String subpage_KTCG(){ return "subpage/KTCG"; } @RequestMapping("/subpage/QKTR") public String subpage_QKTR(){ return "subpage/QKTR"; } @RequestMapping("/subpage/QKCYL") public String subpage_QKCYL(){ return "subpage/QKCYL"; } @RequestMapping("/subpage/KQ") public String subpage_KQ(){ return "subpage/KQ"; } /** * ไธ“้ข˜ไธ€็ฌฌไธ€้กนๆ•ฐๆฎๅฑ•็คบdemo * @return */ @RequestMapping("/sp01") public String sp01(){ return "sp01"; } } <file_sep>/** * Created by dell-pc on 2016/4/20. */ var url="http://192.168.3.11"; function ajaxSpecialSubject0103(companyname){ $.ajax({ url: url+"/data/SpecialSubject01_03", // ่Žทๅ–ไธ“้ข˜ไธ€็ฌฌไธ‰้กน็š„ๆ•ฐๆฎ dataType: "json", data: { companyname: companyname}, type: "post", success: function(data) { var years=new Array(); var EWDZFY=new Array(); var SWDZFY=new Array(); var KFTZ=new Array(); for(var i=0;i<data.length;i++){ years.push(data[i].NF); EWDZFY.push(data[i].EWDZFY); SWDZFY.push(data[i].SWDZFY); KFTZ.push(data[i].KFTZ); } var data=[ {name:'ไบŒ็ปดๅœฐ้œ‡่ดน็”จ', type:'bar', data:EWDZFY}, {name:'ไธ‰็ปดๅœฐ้œ‡่ดน็”จ', type:'bar', data:SWDZFY}, {name:'ๅผ€ๅ‘ไบ•ๆŠ•่ต„่ดน็”จ', type:'bar', data:KFTZ }]; var category=years; var otherInfo={ title:'ๅ…จๅ›ฝๆŠ•ๅ…ฅไบŒใ€ไธ‰็ปดๅœฐ้œ‡่ดน็”จ', dw:'ไธ‡ๅ…ƒ', legend:['ไบŒ็ปดๅœฐ้œ‡่ดน็”จ','ไธ‰็ปดๅœฐ้œ‡่ดน็”จ','ๅผ€ๅ‘ไบ•ๆŠ•่ต„่ดน็”จ'], boundaryGap:true }; createChart('content_chart3', data, category, otherInfo); }, error: function() { alert('่ฏทๆฑ‚ๅผ‚ๅธธ'); } }); } <file_sep>package com.china.oil.application.controller; import com.china.oil.application.util.FreeMarkerUtil; import com.china.oil.application.util.HbaseUtil; import com.china.oil.application.util.JsonUtil; import com.google.gson.Gson; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.data.hadoop.hbase.HbaseTemplate; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import java.util.HashMap; import java.util.Map; /** * Created by dell-pc on 2016/4/19. */ @Controller @EnableAutoConfiguration @RequestMapping(value = "/",produces = "text/html;charset=UTF-8") public class BaseController { protected static final Logger log = LoggerFactory.getLogger(BaseController.class); protected Gson gson = new Gson(); // @Autowired // UserRepository userRepository; @Autowired protected HbaseTemplate hbaseTemplate; @Autowired protected HbaseUtil hbaseUtil; @Autowired protected JsonUtil jsonUtil; @Autowired FreeMarkerUtil freeMarkerUtil; protected Map PageMaps=new HashMap(); } <file_sep>package com.china.oil.application.util; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.Scan; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.hadoop.hbase.HbaseTemplate; import org.springframework.data.hadoop.hbase.RowMapper; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by dell-pc on 2016/4/19. */ @Component("hbaseUtil") public class HbaseUtil { @Autowired protected HbaseTemplate hbaseTemplate; public List<Map> findHBaseTable(String tableName, final String[] fieldList){ // Scan s_dk01 = new Scan(); // s_dk01.addColumn("info".getBytes(), "NF".getBytes()); // s_dk01.addColumn("info".getBytes(), "DWMC".getBytes()); // s_dk01.addColumn("info".getBytes(), "KTTZ".getBytes()); // /** // * ่ฏป HBase ่กจ โ€˜DK01_COMPEXPโ€™ ๆŠฝๅ–็›ธๅ…ณๆ•ฐๆฎ // */ // List<Map> dk01_rows = hbaseTemplate.find("DK01_COMPEXP", s_dk01, new RowMapper<Map>() { // public Map mapRow(Result result, int rowNum) throws Exception { // Map map = new HashMap(); // map.put("NF", new String(result.getValue("info".getBytes(), "NF".getBytes()))); // map.put("DWMC", new String(result.getValue("info".getBytes(), "DWMC".getBytes()))); // map.put("KTTZ", new String(result.getValue("info".getBytes(), "KTTZ".getBytes()))); // return map; // } // }); // return dk01_rows; Scan scan = new Scan(); for(String str:fieldList){ scan.addColumn("info".getBytes(),str.getBytes()); } List<Map> scan_rows=hbaseTemplate.find(tableName, scan, new RowMapper<Map>() { @Override public Map mapRow(Result result, int i) throws Exception { Map map = new HashMap(); for(String str:fieldList){ map.put(str,new String(result.getValue("info".getBytes(),str.getBytes()))); } return map; } }); return scan_rows; } } <file_sep>package com.china.oil.application.repository; //import com.china.oil.application.entity.User; //import org.springframework.data.jpa.repository.JpaRepository; //import org.springframework.data.jpa.repository.Query; //import org.springframework.data.repository.query.Param; //import org.springframework.transaction.annotation.Transactional; /** * Created by yangchujie on 15/12/28. */ //@Transactional //public interface UserRepository extends JpaRepository<User, Long> { // // @Query("select u from User u where u.username = :username") // User finduser(@Param("username") String username); // //}
a229bc1ba3e8b0e553b4dcdc5054e0b47f7e590e
[ "JavaScript", "Java" ]
8
Java
wiidi/Oil
d5d37311d0890e38385ce355a863649488b5bdfb
850091c8f2ed14937d20082fea984e40814caa82
refs/heads/master
<repo_name>gegeduan/cat<file_sep>/src/main/java/com/cat/service/impl/ManServiceImpl.java package com.cat.service.impl; import com.cat.dao.ManMapper; import com.cat.entity.Man; import com.cat.service.ManService; import org.apache.commons.codec.digest.DigestUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * ๅˆ˜ๆ–‡ๅš * 2018/7/17 16:04 */ @Service public class ManServiceImpl implements ManService { @Autowired private ManMapper manMapper; /** * ๆณจๅ†Œ * @param man * @return */ @Override public boolean register(Man man) { man.setPassword(DigestUtils.md5Hex(man.getPassword())); int count = manMapper.insertMan(man); return count==1?true:false; } /** * ็™ป้™† * @param username * @param password * @return */ @Override public String login(String username, String password) { // Man man =new Man(); // = manMapper.checkUsername(man); // if (resultCount == 0){ // return "็”จๆˆทๅไธๅญ˜ๅœจ"; // } // // ็™ปๅฝ• MD5ๅŠ ๅฏ† // String md5pwd = DigestUtils.md5Hex(password);// MD5 ๅŠ ๅฏ† // Man man = manMapper.selectLogin(username,md5pwd); // if (man == null) { // return "ๅฏ†็ ้”™่ฏฏ"; // } // ๅฐ†ๅฏ†็ ่ฎพ็ฝฎไธบ็ฉบ ้˜ฒๆญขๅˆซไบบๆŠ“ๅŒ… // man.setPassword(String.valueOf(StringUtils.isEmpty(password))); return "็™ปๅฝ•ๆˆๅŠŸ"; } /** * ๆฃ€ๆŸฅ็”จๆˆทๅๆ˜ฏๅฆๅญ˜ๅœจ * @param manName * @return */ @Override public boolean checkManname(String manName) { int i = manMapper.checkUsername(manName); return i==0?true:false; } @Override public boolean fixPassword(Man man) { Integer integer = manMapper.updatePassword(man); return integer==1?true:false; } @Override public boolean addManInfo(Man man) { Integer integer = manMapper.updateManInfo(man); return integer==1?true:false; } } <file_sep>/src/main/java/com/cat/entity/CatNote.java package com.cat.entity; public class CatNote { private Integer id; private Integer cat; private Integer note; public CatNote(Integer id, Integer cat, Integer note) { this.id = id; this.cat = cat; this.note = note; } public CatNote() { super(); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getCat() { return cat; } public void setCat(Integer cat) { this.cat = cat; } public Integer getNote() { return note; } public void setNote(Integer note) { this.note = note; } }<file_sep>/src/main/java/com/cat/vo/CatVo.java package com.cat.vo; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import java.util.Date; /** * @Author: LR * @Descriprition: * @Date: Created in 11:33 2018/7/18 * @Modified By: **/ @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class CatVo { private String name; private String catPic; private Integer healthyStatus; private Integer gender; private Date brith; } <file_sep>/src/main/java/com/cat/entity/Pic.java package com.cat.entity; import java.util.Date; public class Pic { private Integer id; private Integer catId; private Date editTime; private String picUrl; private Byte yn; private Byte detailShow; private Byte diaryUse; private Byte articleUse; public Pic(Integer id, Integer catId, Date editTime, String picUrl, Byte yn, Byte detailShow, Byte diaryUse, Byte articleUse) { this.id = id; this.catId = catId; this.editTime = editTime; this.picUrl = picUrl; this.yn = yn; this.detailShow = detailShow; this.diaryUse = diaryUse; this.articleUse = articleUse; } public Pic() { super(); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getCatId() { return catId; } public void setCatId(Integer catId) { this.catId = catId; } public Date getEditTime() { return editTime; } public void setEditTime(Date editTime) { this.editTime = editTime; } public String getPicUrl() { return picUrl; } public void setPicUrl(String picUrl) { this.picUrl = picUrl == null ? null : picUrl.trim(); } public Byte getYn() { return yn; } public void setYn(Byte yn) { this.yn = yn; } public Byte getDetailShow() { return detailShow; } public void setDetailShow(Byte detailShow) { this.detailShow = detailShow; } public Byte getDiaryUse() { return diaryUse; } public void setDiaryUse(Byte diaryUse) { this.diaryUse = diaryUse; } public Byte getArticleUse() { return articleUse; } public void setArticleUse(Byte articleUse) { this.articleUse = articleUse; } }<file_sep>/src/main/webapp/src/store/modules/citySelect.js export default { state: { cityArr: [] }, mutations: { changeCity (state, arr) { // ไฟฎๆ”นcityArrๅ‚จๅญ˜็š„ๆ•ฐๆฎไธบๆ–ฐ้€‰ๆ‹ฉ็š„ๅœฐๅ€ state.cityArr = arr } } } <file_sep>/src/main/java/com/cat/dao/NotePicMapper.java package com.cat.dao; import org.apache.ibatis.annotations.Param; import com.cat.entity.NotePic; public interface NotePicMapper { /** * ๅธ–ๅญๅ’Œๅ›พ็‰‡ๅ…ณ็ณป * @param note * @return */ int insertNotePic(NotePic notePic); /** * ๆ นๆฎidๅˆ ้™คๅ…ณ่” * @param note * @return */ int deleteOneById(@Param("id")Integer id); } <file_sep>/src/main/resources/dataSource.properties jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql:///cat?useUnicode=true&characterEncoding=utf-8 jdbc.username=root jdbc.password=<PASSWORD> db.initialSize = 20 db.maxActive = 50 db.maxIdle = 20 db.minIdle = 10 db.maxWait = 10 db.defaultAutoCommit = true db.minEvictableIdleTimeMillis = 3600000<file_sep>/src/main/webapp/src/store/modules/publishTab.js export default { state: { currentTab: 'find-master' }, mutations: { changeItem (state, val) { state.currentTab = val } } } <file_sep>/src/main/java/com/cat/controller/manController.java package com.cat.controller; import com.cat.entity.Man; import com.cat.service.ManService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpSession; /** * ๅˆ˜ๆ–‡ๅš * 2018/7/20 16:39 */ @Controller @RequestMapping(value = "user") public class manController { @Autowired private ManService manService; @RequestMapping(value = "/fixPersonInfo",method = RequestMethod.POST) public String fixPersonInfo(@RequestParam("logname")String logname, @RequestParam("sex")String sex, @RequestParam("borntime")String borntime, @RequestParam("phone")String phone, @RequestParam("address")String address, HttpSession session){ Man man=new Man(); man.setLogname(logname); man.setSex(sex); man.setBorntime(borntime); man.setPhone(phone); man.setAddress(address); boolean b = manService.addManInfo(man); if (b){ return "user/personal-data"; } return null; } } <file_sep>/src/main/java/com/cat/service/DiaryPicService.java package com.cat.service; import com.cat.entity.DiaryPic; public interface DiaryPicService { /** * ๆ—ฅๅฟ—ๅ’Œๅ›พ็‰‡ๅ…ณ็ณป * @param diary * @return */ boolean insertDiaryPic(DiaryPic diaryPic); /** * ๆ นๆฎidๅˆ ้™คๅ…ณ่” * @param diary * @return */ boolean deleteOneById(Integer id); } <file_sep>/src/main/webapp/src/store/index.js import Vue from 'vue' import Vuex from 'vuex' import publishTab from './modules/publishTab' import diaryTab from './modules/diaryTab' import citySelect from './modules/citySelect' Vue.use(Vuex) export default new Vuex.Store({ state: { count: 0 }, mutations: { increment (state) { state.count++ } }, modules: { publishTab: publishTab, diaryTab: diaryTab, citySelect: citySelect } }) <file_sep>/src/main/java/com/cat/entity/Note.java package com.cat.entity; import java.util.Date; public class Note { private Integer id; private Integer man; private Date time; private String title; private String introduct; private String content; public Note(Integer id, Integer man, Date time, String title, String introduct, String content) { this.id = id; this.man = man; this.time = time; this.title = title; this.introduct = introduct; this.content = content; } public Note() { super(); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getMan() { return man; } public void setMan(Integer man) { this.man = man; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title == null ? null : title.trim(); } public String getIntroduct() { return introduct; } public void setIntroduct(String introduct) { this.introduct = introduct == null ? null : introduct.trim(); } public String getContent() { return content; } public void setContent(String content) { this.content = content == null ? null : content.trim(); } }<file_sep>/src/main/java/com/cat/interceptor/MyInterceptor.java package com.cat.interceptor; import com.cat.entity.Miaoman; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * ๅˆ˜ๆ–‡ๅš * 2018/7/9 17:20 */ public class MyInterceptor implements HandlerInterceptor { //ๅ‰ๅค„็†,ๆ‹ฆๆˆช่ฏทๆฑ‚ๅˆฐ่พพๅ‰็ซฏๆŽงๅˆถๅ™จ // ๅ‰ๅค„็†ๅฏไปฅๆ ก้ชŒไธ€ไบ›ๆƒ้™. @Override public boolean preHandle(HttpServletRequest Request, HttpServletResponse Response, Object o) throws Exception { System.err.println("ๅ‰ๅค„็†.ๆ‹ฆๆˆช่ฏทๆฑ‚ๅˆฐ่พพๅ‰็ซฏๆŽงๅˆถๅ™จ"); HttpSession session = Request.getSession(); Miaoman miaoman = (Miaoman) session.getAttribute("miaoman"); System.out.println(session); if (miaoman!= null){ return true; }else { Response.sendRedirect(Request.getContextPath()+"/page/user/login"); return false; } } //ๅŽๅค„็†, ๆธฒๆŸ“่ง†ๅ›พไน‹ๅ‰. // ๅฏไปฅ็ป™modelAndViewๅ†่ฎพ็ฝฎไธ€ไบ›ๅ‚ๆ•ฐ. ้”ฆไธŠๆทป่Šฑ. @Override public void postHandle(HttpServletRequest Request, HttpServletResponse Response, Object o, ModelAndView modelAndView) throws Exception { System.err.println("ๅŽๅค„็†, ๆธฒๆŸ“่ง†ๅ›พไน‹ๅ‰"); } //ๅŽๅค„็†, ๅ“ๅบ”ๆ•ฐๆฎไน‹ๅ‰ // ่ฏทๆฑ‚่ฟ›ๆฅ,ๅˆฐๅ“ๅบ”,ๆ‰ง่กŒไบ†ๅคšไน…. @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { System.err.println("ๅŽๅค„็†, ๅ“ๅบ”ๆ•ฐๆฎไน‹ๅ‰"); } } <file_sep>/src/main/java/com/cat/common/ResponseCode.java package com.cat.common; /** * @Author: LR * @Descriprition:ๅฎšไน‰้€š็”จๅ“ๅบ”็ ็š„ๆžšไธพ็ฑป * @Date: Created in 16:29 2018/7/16 * @Modified By: **/ public enum ResponseCode { SUCCESS(0, "SUCCESS"), ERROR(1,"ERROR"), NEED_LOGIN(10,"NEED_LOGIN"), ILLEGAL_ARGUMENT(2,"ARGUMENT"); private final int code; private final String desc; ResponseCode(int code, String desc){ this.code = code; this.desc = desc; } public int getCode() { return code; } public String getDesc() { return desc; } } <file_sep>/src/main/java/com/cat/service/DiaryService.java package com.cat.service; import java.util.List; import com.cat.entity.Diary; public interface DiaryService { /** * ๆ—ฅๅฟ—ไฟกๆฏ * @param diary * @return */ boolean insertDiary(Diary diary); /** * ๆŸฅ่ฏขๆ—ฅๅฟ— * @param id * @return */ Diary findDiary(Integer id); /** * ๆ นๆฎcatIdๆŸฅ่ฏขๆ‰€ๆœ‰ๆ—ฅๅฟ— * @return */ List<Diary> findByCatId(Integer catId); /** * ๆ›ดๆ”นๆ—ฅๅฟ—ไฟกๆฏ * @param diary * @return */ boolean updateDiary(Diary diary); } <file_sep>/src/main/webapp/src/router/index.js /* eslint-disable */ import Vue from 'vue' import Router from 'vue-router' import publish from '@/components/publish/publish' import diary from '@/components/diary/diary' import slogan from '@/components/slogan/slogan' import forget from '@/components/slogan/forget.vue' import register from '@/components/slogan/register.vue' import login from '@/components/slogan/login.vue' Vue.use(Router) const routes = [ { path: '/', component: resolve => require(['../views/layout.vue'], resolve ), children: [ { path: '/publish', component: publish }, { path: '/diary', component: diary }, { path: '/my', component: resolve => require(['../views/my/my-layout.vue'], resolve), children: [ { path: '/my', name: 'personal-data', component: resolve => require(['../views/my/personal-data.vue'], resolve) }, { path: '/my/notify', name: 'notify', component: resolve => require(['../views/my/notify.vue'], resolve) }, { path: '/my/collection', name: 'collection', component: resolve => require(['../views/my/collection.vue'], resolve) }, { path: '/my/about-adopt', name: 'about-adopt', component: resolve => require(['../views/my/about-adopt.vue'], resolve) }, { path: '/my/about-me-cat', name: 'about-me-cat', component: resolve => require(['../views/my/about-me-cat.vue'], resolve) } ] } ] }, { path: '/slogan', name: 'slogan', component: slogan }, { path: '/login', name: 'login', component: login }, { path: '/register', name: 'register', component: register }, { path: '/forget', name: 'forget', component: forget } ] export default new Router({ routes: routes })
dda0294d17c8851d77917c8337906e53148d769b
[ "JavaScript", "Java", "INI" ]
16
Java
gegeduan/cat
3a5a5e2cf9a457511b6747ae0d5cb9ae6c1b63f4
763ecd1678d4adfeeef5d37f5168986da52bb2c7
refs/heads/master
<repo_name>nsandeeplearning/centos-automation<file_sep>/backup/install/install-ms-sqlclient.sh #!/bin/bash #title :install-ms-sqlclient.sh #description :This script will install msodbcsql #author :sandeep(snamin501) #date :Fri Feb 19 10:07:04 EST 2018 #version :1.0 #usage :sudo sh install-ms-sqlclient.sh if [[ $EUID -ne 0 ]]; then echo "your Not authorized to run this script." exit 1 fi msodbcsql="msodbcsql-13.1.9.2-1.x86_64.rpm" echo "Downloading $msodbcsql started..." wget https://packages.microsoft.com/rhel/7/prod/$msodbcsql echo "Downloading $msodbcsql completed..." echo "Assiginging permissions to $msodbcsql started..." chmod 777 $msodbcsql echo "Assiginging permissions to $msodbcsql completed..." echo "Installation of $msodbcsql started..." ACCEPT_EULA=Y yum localinstall $msodbcsql -y echo "Installation of $msodbcsql completed..."<file_sep>/install/install-git_wget_zip.sh #!/bin/bash #title :install-git_wget_zip.sh #description :This script will install git_wget_zip utils #author :sandeep(snamin501) #date :Fri Feb 19 10:07:04 EST 2018 #version :1.0 #usage :sudo sh install-git_wget_zip.sh if [[ $EUID -ne 0 ]]; then echo "your Not authorized to run this script." exit 1 fi #utils to install.. wget="wget" zip="zip" unzip="unzip" git="git" vim="vim" unixODBC_devel="unixODBC-devel" declare -a toolslist=($wget $zip $unzip $git $unzip $vim $unixODBC_devel) for tool in ${toolslist[@]} do echo "Installing $tool started....." yum install $tool -y echo "Installing $tool completed....." done <file_sep>/install/install-pip-and-wheels.sh #!/bin/bash #title :install-pip-and-wheels.sh #description :This script will install pip-and-wheels #author :sandeep(snamin501) #date :Fri Feb 19 10:07:04 EST 2018 #version :1.0 #usage :sudo sh install-pip-and-wheels.sh if [[ $EUID -ne 0 ]]; then echo "your Not authorized to run this script." exit 1 fi pip_and_wheels="get-pip.py" echo "Downloading $pip_and_wheels started......." wget -O $pip_and_wheels "https://bootstrap.pypa.io/$pip_and_wheels" echo "Downloading $pip_and_wheels completed......." echo "Assiginging permissions to $pip_and_wheels started....." chmod 777 $pip_and_wheels echo "Assiginging permissions to $pip_and_wheels completed....." echo "Installation of $pip_and_wheels started....." python $pip_and_wheels echo "Installation of $pip_and_wheels completed....." echo "$pip_and_wheels installed Successfully....." echo "Verifying $pip_and_wheels installation...." pip -V echo "Removing $pip_and_wheels started......" rm get-pip.py echo "Removing $pip_and_wheels completed......" echo "Installation of python -m pip install --upgrade pip setuptools wheel started....." python -m pip install --upgrade pip setuptools wheel echo "Installation of python -m pip install --upgrade pip setuptools wheel completed....." <file_sep>/install/install-jdk-8-linux-x64.sh #!/bin/bash #title :install-jdk-8-linux-x64.sh #description :This script will install java8 #author :sandeep(snamin501) #date :Fri Feb 19 10:07:04 EST 2018 #version :1.0 #usage :sudo sh install-jdk-8-linux-x64.sh if [[ $EUID -ne 0 ]]; then echo "your Not authorized to run this script." exit 1 fi jdk_8_linux_64="jdk-8-linux-x64.rpm" jdk_version=${1:-8} ext=${2:-rpm} echo "Checking for Available java-8 versions started....." readonly url="http://www.oracle.com" readonly jdk_download_url1="$url/technetwork/java/javase/downloads/index.html" readonly jdk_download_url2=$( curl -s $jdk_download_url1 | \ egrep -o "\/technetwork\/java/\javase\/downloads\/jdk${jdk_version}-downloads-.+?\.html" | \ head -1 | \ cut -d '"' -f 1 ) [[ -z "$jdk_download_url2" ]] && echo "Could not get jdk download url - $jdk_download_url1" >> /dev/stderr readonly jdk_download_url3="${url}${jdk_download_url2}" readonly jdk_download_url4=$( curl -s $jdk_download_url3 | \ egrep -o "http\:\/\/download.oracle\.com\/otn-pub\/java\/jdk\/[8-9](u[0-9]+|\+).*\/jdk-${jdk_version}.*(-|_)linux-(x64|x64_bin).$ext" | tail -1 ) echo "Checking for Avaliable java-8 versions completed....." echo "Downloading jdk-8-linux-x64.rpm started......." for dl_url in ${jdk_download_url4[@]}; do wget -O $jdk_8_linux_64 --no-cookies \ --no-check-certificate \ --header "Cookie: oraclelicense=accept-securebackup-cookie" \ -N $dl_url done echo "Downloading $jdk_8_linux_64 completed......." echo "Assiginging permissions to $jdk_8_linux_64 started....." chmod 777 $jdk_8_linux_64 echo "Assiginging permissions to $jdk_8_linux_64 completed....." echo "Installation of $jdk_8_linux_64 started....." yum localinstall $jdk_8_linux_64 -y echo "Installation of $jdk_8_linux_64 completed....." echo "$jdk_8_linux_64 installed Successfully....." echo "verifying $jdk_8_linux_64 started....." java -version echo "verifying $jdk_8_linux_64 completed....."<file_sep>/backup/install/install-pentaho.sh #!/bin/bash #title :install-pentaho.sh #description :This script will install pentaho #author :sandeep(snamin501) #date :Fri Feb 19 10:07:04 EST 2018 #version :1.0 #usage :sudo sh install-pentaho.sh if [[ $EUID -ne 0 ]]; then echo "your Not authorized to run this script." exit 1 fi pentaho="pdi-ce-6.1.0.1-196.zip" mkdir /app mkdir /app/oracle_instal echo "Downloading pentaho $pentaho started......." wget -O $pentaho https://comcast.box.com/shared/static/i4i7h6o1xvuziczt6nltfsxob2nho9hl.zip echo "Downloading pentaho $pentaho completed......." pwd echo "Assiginging permissions to pentaho $pentaho started....." chmod 777 $pentaho echo "Assiginging permissions to pentaho $pentaho completed....." pwd echo "untar of $pentaho started..." unzip $pentaho echo "untar of $pentaho completed..." mv data-integration /app/oracle_instal echo "verifying pentaho $pentaho started....." ls /app/oracle_instal echo "verifying pentaho $pentaho completed....." <file_sep>/uninstall/uninstall_pip.sh #!/bin/bash - #title :remove java.sh yum remove jdk -y<file_sep>/uninstall/uninstall_java.sh #!/bin/bash - #title :remove pip.sh python -m pip uninstall pip setuptools -y<file_sep>/install/install-pip-packages.sh #!/bin/bash #title :install-pip-packages.sh #description :This script will install pip packages #author :sandeep(snamin501) #date :Fri Feb 19 10:07:04 EST 2018 #version :1.0 #usage :sudo sh install-pip-packages.sh # 37 pip packages... if [[ $EUID -ne 0 ]]; then echo "your Not authorized to run this script." exit 1 fi #pip pkgs to install.. asn1crypto="asn1crypto" bcrypt="bcrypt" cffi="cffi" chardet="chardet" configobj="configobj" configparser="configparser" cryptography="cryptography" cx_Oracle="cx-Oracle" decorator="decorator" enum34="enum34" idna="idna" iniparse="iniparse" ipaddress="ipaddress" kitchen="kitchen" numpy="numpy" pandas="pandas" paramiko="paramiko" perf="perf" pyasn1="pyasn1" pycparser="pycparser" pycurl="pycurl" pygobject="pygobject" pygpgme="pygpgme" pyliblzma="pyliblzma" PyNaCl="PyNaCl" pyodbc="pyodbc" pyparsing="pyparsing" pysftp="pysftp" python_dateutil="python-dateutil" pytz="pytz" pyudev="pyudev" pyxattr="pyxattr" six="six" slip="slip" slip_dbus="slip.dbus" teradata="teradata" urlgrabber="urlgrabber" echo "Installing 37 pip packages..." declare -a listpippkgs=($asn1crypto $bcrypt $cffi $chardet $configobj $configparser $cryptography $cx_Oracle $decorator $enum34 $idna $iniparse $ipaddress $kitchen $numpy $pandas $paramiko $perf $pyasn1 $pycparser $pycurl $pygobject $pygpgme $pyliblzma $PyNaCl $pyodbc $pyparsing $pysftp $python_dateutil $pytz $pyudev $pyxattr $six $slip $slip_dbus $teradata $urlgrabber) for pippkgname in ${listpippkgs[@]} do echo "Installation of Pip install for $pippkgname started....." pip install $pippkgname echo "Installation of Pip install for $pippkgname completed....." done echo "Verifying pip packages installation...." pip freeze <file_sep>/css/verify/java-check.sh #!/bin/bash java -version 2>&1 >/dev/null GIT_IS_AVAILABLE=$? if [ $GIT_IS_AVAILABLE -eq 0 ]; then echo "java was installed" else echo "java was not installed" fi <file_sep>/install/install-oracle-instantclient12.2-tools-12-x64.sh #!/bin/bash #title :install-oracle-instantclient12.2-tools-12-x64.sh #description :This script will install oracle-instantclient12 #author :sandeep(snamin501) #date :Fri Feb 19 10:07:04 EST 2018 #version :1.0 #usage :sudo sh install-oracle-instantclient12.2-tools-12-x64.sh if [[ $EUID -ne 0 ]]; then echo "your Not authorized to run this script." exit 1 fi oracle_instantclient_basic_12="oracle-instantclient12.2-basic-12.2.0.1.0-1.x86_64.rpm" oracle_instantclient_tools_12="oracle-instantclient12.2-tools-12.2.0.1.0-1.x86_64.rpm" echo "Downloading $oracle_instantclient_basic_12 started..." wget -O $oracle_instantclient_basic_12 https://comcast.box.com/shared/static/0be8ndipvfogq1on0n6nzmf2utd7vmxi.rpm echo "Downloading $oracle_instantclient_basic_12 completed..." echo "Downloading $oracle_instantclient_tools_12 started..." wget -O $oracle_instantclient_tools_12 https://comcast.box.com/shared/static/7kj7tsy73vdzot5eacd8fc0x2sy2ytoo.rpm echo "Downloading $oracle_instantclient_tools_12 completed..." echo "Assiginging permissions to $oracle_instantclient_basic_12 started..." chmod 777 $oracle_instantclient_basic_12 echo "Assiginging permissions to $oracle_instantclient_basic_12 completed..." echo "Assiginging permissions to $oracle_instantclient_tools_12 started..." chmod 777 $oracle_instantclient_tools_12 echo "Assiginging permissions to $oracle_instantclient_tools_12 completed..." echo "Installation of $oracle_instantclient_basic_12 started..." yum localinstall $oracle_instantclient_basic_12 -y echo "Installation of $oracle_instantclient_basic_12 completed..." echo "Installation of $oracle_instantclient_tools_12 started..." yum localinstall $oracle_instantclient_tools_12 -y echo "Installation of $oracle_instantclient_tools_12 completed..." <file_sep>/utils/KebAthEnvAutoAgent.sh #!/bin/bash #title :KebAthEnvAutoAgent.sh #description :This script will pull scripts from github and run the functions of shells scripts #author :sandeep(snamin501) #date :Fri Feb 19 10:07:04 EST 2018 #version :1.0 #usage :sudo sh KebAthEnvAutoAgent.sh if [[ $EUID -ne 0 ]]; then echo "your Not authorized to run this script." exit 1 fi #scripts dir keb_current_dir="/home/KEB_ATHENA/" #boxURls:- install_url="https://comcast.box.com/shared/static" #softwares to download.. inst_java_8="install-jdk-8-linux-x64.sh" inst_ora_client="install-oracle-instantclient12.2-tools-12-x64.sh" inst_py_devel="python-devel-2.7.5-58.el7.x86_64.sh" inst_pip_and_wheels="install-pip-and-wheels.sh" inst_git_wget_zip="install-git_wget_zip.sh" inst_maven="install-maven.sh" inst_ms_sqlclient="install-ms-sqlclient.sh" inst_pentaho="install-pentaho.sh" inst_pip_packages="install-pip-packages.sh" inst_python3="install-python3.sh" inst_teradata_client_and_unixodbc="install-teradata-client-and-unixodbc.sh" #box softwares to download.. inst_java_8_box="o2um8tdxz3pjpp1ddosmv828yay3sg03.sh" inst_ora_client_box="jordetld393ve6k28kilkb56cfbvorzn.sh" inst_py_devel_box="4p8709cs46j19cofle4cyg5ytwh088qf.sh" inst_pip_and_wheels_box="krzbt3ia8yx5bmsdg6hg2b1e38m9cmbj.sh" inst_git_wget_zip_box="0g8q9pd78lb3n5cp9ifvtzsm5n98tp57.sh" inst_mave_box="qajneh1ygrvlhpkewbn3avq9ydv29olx.sh" inst_ms_sqlclient_box="lgte1ldoirb219zp524zx7iz1x03957i.sh" inst_pentaho_box="o797uf93o8ui11easm9a5wubdlza4ibl.sh" inst_pip_packages_box="y10kach5eprg9g4zbqewhdb8oe6331o4.sh" inst_python3_box="gotkksz2tji4o3sh1nwt7mr4w6ej8xl9.sh" inst_teradata_client_and_unixodbc_box="p2sx7mh0eq6skzcatksb2663ue9fcvnm.sh" function KebAthEnvAutoAgent_pull_scripts { declare -a softlist=($inst_java_8_box $inst_ora_client_box $inst_py_devel_box $inst_pip_and_wheels_box $inst_git_wget_zip_box $inst_maven_box $inst_ms_sqlclient_box $inst_pentaho_box $inst_pip_packages_box $inst_python3_box $inst_teradata_client_and_unixodbc_box) #getting files from github. for soft_box in ${softlist[@]} do echo "getting files for $soft started....." wget -O $soft $install_url/$soft echo "getting files for $soft completed....." done #changing the file permissions for soft in ${softlist[@]} do echo "changing the file permissions for $soft started....." chmod 777 -R $soft echo "changing the file permissions $soft completed....." done #changing the dos2unix for soft in ${softlist[@]} do echo "changing the document type for $soft started....." dos2unix $soft echo "changing the document type $soft completed....." done } #main function starts here.. function KebAthEnvAutoAgent_main { KebAthEnvAutoAgent_pull_scripts inst_git_wget_zip_func inst_java_8_func inst_maven_func inst_teradata_client_and_unixodbc_func inst_ms_sqlclient_func inst_ora_client_func inst_py_devel_func inst_pip_and_wheels_func inst_pip_packages_func inst_python3_func inst_pentaho_func } #main function ends here.. ############################################################################################## #sub-function starts here.. function inst_git_wget_zip_func { sudo sh $keb_current_dir$inst_git_wget_zip } function inst_java_8_func { sudo sh $keb_current_dir$inst_java_8 } function inst_maven_func { sudo sh $keb_current_dir$inst_maven } function inst_teradata_client_and_unixodbc_func { sudo sh $keb_current_dir$inst_teradata_client_and_unixodbc } function inst_ms_sqlclient_func { sudo sh $keb_current_dir$inst_ms_sqlclient } function inst_ora_client_func { sudo sh $keb_current_dir$inst_ora_client } function inst_py_devel_func { sudo sh $keb_current_dir$inst_py_devel } function inst_pip_and_wheels_func { sudo sh $keb_current_dir$inst_pip_and_wheels } function inst_pip_packages_func { sudo sh $keb_current_dir$inst_pip_packages } function inst_pentaho_func { sudo sh $keb_current_dir$inst_pentaho } function inst_python3_func { sudo sh $keb_current_dir$inst_python3 } #sub-function ends here.. echo "main func KebAthEnvAutoAgent_main started....." KebAthEnvAutoAgent_main echo "main func KebAthEnvAutoAgent_main completed....." <file_sep>/backup/install/install-maven.sh #!/bin/bash #title :install-maven.sh #description :This script will install maven #author :sandeep(snamin501) #date :Fri Feb 19 10:07:04 EST 2018 #version :1.0 #usage :sudo sh install-maven.sh if [[ $EUID -ne 0 ]]; then echo "your Not authorized to run this script." exit 1 fi apache_maven_3="apache-maven-3.5.2-bin.tar.gz" echo "Downloading $apache_maven_3 started......." wget http://repos.fedorapeople.org/repos/dchen/apache-maven/epel-apache-maven.repo -O /etc/yum.repos.d/epel-apache-maven.repo echo "Downloading $apache_maven_3 completed......." echo "Downloading $apache_maven_3 started......." yum install apache-maven -y echo "Downloading $apache_maven_3 completed......." echo 1 | update-alternatives --config java echo 1 | update-alternatives --config javac echo "verifying $apache_maven_3 started....." mvn -version echo "verifying $apache_maven_3 completed....." <file_sep>/css/verify/git-check.sh #!/bin/bash git --version 2>&1 >/dev/null GIT_IS_AVAILABLE=$? if [ $GIT_IS_AVAILABLE -eq 0 ]; then echo "git was installed" else echo "git was not installed" fi <file_sep>/README.MD https://www.javatips.net/api/JFTClient-master/src/main/java/org/jftclient/ssh/Connection.java https://www.digitalocean.com/community/tutorials/how-to-create-a-sudo-user-on-centos-quickstart https://docs.snowflake.net/manuals/user-guide/odbc-linux.html#unixodbc<file_sep>/other/install-oracle-instantclient12.2-tools-12-x64.sh #!/bin/bash #title :oracle-instantclient12.2-tools-12-x64h #description :This script will install oracle-instantclient12 #author :nsandeep #date :Fri Feb 9 06:07:04 EST 2018 #version :0.1 #usage :bash oracle-instantclient12.2-tools-12-x64 # You must accept the Oracle Binary Code License # http://www.oracle.com/technetwork/java/javase/terms/license/index.html # usage: get_jdk.sh <jdk_version> <ext> # jdk_version: 8(default) or 9 # ext: rpm or tar.gz if [[ $EUID -ne 0 ]]; then echo "your Not authorized to run this script." exit 1 fi echo "Downloading oracle-instantclient12.2-tools-12-x64.rpm started..." wget -O oracle-instantclient12.2-tools-12-x64.rpm --no-cookies \ --no-check-certificate \ --header "Cookie: oraclelicense=accept-securebackup-cookie" \ -N http://ftp.riken.jp/Linux/cern/centos/7/cernonly/x86_64/Packages/oracle-instantclient12.2-basic-12.2.0.1.0-1.x86_64.rpm echo "Downloading oracle-instantclient12.2-tools-12.2.0.1.0-1.x86_64.rpm completed..." echo "Assiginging permissions to oracle-instantclient12.2-tools-12-x64.rpm started..." chmod 777 oracle-instantclient12.2-tools-12-x64.rpm echo "Assiginging permissions to oracle-instantclient12.2-tools-12-x64.rpm completed..." echo "Installation of oracle-instantclient12.2-tools-12-x64.rpm started..." sudo yum localinstall oracle-instantclient12.2-tools-12-x64.rpm -y echo "Installation of oracle-instantclient12.2-tools-12-x64.rpm completed..." echo "Removing oracle-instantclient12.2-tools-12-x64.rpm started......" rm oracle-instantclient12.2-tools-12-x64.rpm echo "Removing oracle-instantclient12.2-tools-12-x64.rpm completed......" <file_sep>/test.sh #!/bin/bash - #title :pull_scripts_from_github.sh #description :This script pull_scripts_from_github.sh #author :nsandeep #date :Fri Feb 9 06:07:04 EST 2018 #version :0.1 #usage :bash pull_scripts_from_github.sh date<file_sep>/backup/install/install-python3.sh #!/bin/bash #title :install-python3.sh #description :This script will install python3 #author :sandeep(snamin501) #date :Fri Feb 19 10:07:04 EST 2018 #version :1.0 #usage :sudo sh install-python3.sh if [[ $EUID -ne 0 ]]; then echo "your Not authorized to run this script." exit 1 fi Python3="Python-3.5.0.tgz" yum install yum-utils -y sudo yum-builddep python echo "Downloading $Python3 started......." curl -O https://www.python.org/ftp/python/3.5.0/$Python3 echo "Downloading $Python3 completed......." echo "Assiginging permissions to $Python3 started....." chmod 777 $Python3 echo "Assiginging permissions to $Python3 completed....." echo "untar of $Python3 started..." tar xzf $Python3 echo "untar of $Python3 completed..." echo "Installation of $Python3 started....." cd Python-3.5.0 #having multiple copies of python running ./configure make make install echo "$Python3 installed Successfully....." echo "Installation of pip tarted....." easy_install pip echo "Assiginging permissions to pip completed....." echo "verifying pentaho $Python3 started....." python3 --version echo "verifying pentaho $Python3 completed....." <file_sep>/utils/dos2unix_check.sh #!/bin/bash dos2unix --version 2>&1 >/dev/null DOS2UNIX_IS_AVAILABLE=$? if [ $DOS2UNIX_IS_AVAILABLE -eq 0 ]; then echo "dos2unix was installed" else echo "dos2unix was not installed" echo "installing dos2unix now.." sudo yum install dos2unix -y echo "dos2unix installation completed.." fi <file_sep>/install/install-teradata-client-and-unixodbc.sh #!/bin/bash #title :install-teradata-client-and-unixodbc.sh #description :This script will install teradata-client and unixodbc #author :sandeep(snamin501) #date :Fri Feb 19 10:07:04 EST 2018 #version :1.0 #usage :sudo sh install-teradata-client-and-unixodbc.sh if [[ $EUID -ne 0 ]]; then echo "your Not authorized to run this script." exit 1 fi teradata_client="tdodbc1620__linux_indep.16.20.00.18-1.tar.gz" unixodbc="unixODBC.x86_64" tdodbc1620="tdodbc1620-16.20.00.18-1.noarch.rpm" echo "Downloading $teradata_client started..." wget -O $teradata_client https://comcast.box.com/shared/static/hun0svsaz69en0u8u4mzttfuzg03okyc.gz echo "Downloading $teradata_client completed..." echo "Assiginging permissions to $teradata_client started..." chmod 777 $teradata_client echo "Assiginging permissions to $teradata_client completed..." echo "untar $teradata_client started..." tar xzf $teradata_client echo "untar $teradata_client completed..." #prerequisite echo "Installation of $unixodbc started..." yum install $unixodbc -y echo "Installation of $unixodbc completed..." echo "change to tdodbc1620 DIR." cd tdodbc1620 pwd echo "Installing $tdodbc1620 started..." yum localinstall $tdodbc1620 -y echo "Installing of $tdodbc1620 completed..." <file_sep>/backup/install/install-python-devel-2.7.5-58.el7.x86_64.sh #!/bin/bash #title :install-python-devel-2.7.5-58.el7.x86_64.sh #description :This script will install python-devels #author :sandeep(snamin501) #date :Fri Feb 19 10:07:04 EST 2018 #version :1.0 #usage :sudo sh install-python-devel if [[ $EUID -ne 0 ]]; then echo "your Not authorized to run this script." exit 1 fi python_devel_2="python-devel-2.7.5-58.el7.x86_64.rpm" echo "Downloading $python_devel_2 started......." wget -O $python_devel_2 "http://mirror.centos.org/centos/7/os/x86_64/Packages/$python_devel_2" echo "Downloading $python_devel_2 completed......." echo "Assiginging permissions to $python_devel_2 started....." chmod 777 $python_devel_2 echo "Assiginging permissions to $python_devel_2 completed....." echo "Installation of $python_devel_2 started....." yum localinstall $python_devel_2 echo "Installation of $python_devel_2 completed....." echo "$python_devel_2 installed Successfully....." echo "$python_devel_2 started......" rm $python_devel_2 echo "Removing $python_devel_2 completed......"
48f0208d065a2bac1036bc6e92d964066ac39377
[ "Markdown", "Shell" ]
20
Shell
nsandeeplearning/centos-automation
1cd4d9fe1a82d26969700ee18cb9f922b3b24f51
aaa4256abecd9329ab42a9e63ce002e659334b0e
refs/heads/master
<repo_name>smailkaddi/brief10<file_sep>/diagramme/_gestion_d___inventaire.sql -- phpMyAdmin SQL Dump -- version 5.0.2 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Apr 24, 2020 at 03:55 PM -- Server version: 10.4.11-MariaDB -- PHP Version: 7.4.4 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: ` gestion_dโ€™inventaire` -- -- -------------------------------------------------------- -- -- Table structure for table `fournisseur` -- CREATE TABLE `fournisseur` ( `id` int(50) NOT NULL, `Nom` text NOT NULL, `Adresse` text NOT NULL, `tel` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -------------------------------------------------------- -- -- Table structure for table `produit` -- CREATE TABLE `produit` ( `id` int(11) NOT NULL, `Nom` text NOT NULL, `Quantitรฉ` int(11) NOT NULL, `Nom de fournisseur` text NOT NULL, `prix` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -------------------------------------------------------- -- -- Table structure for table `rayon` -- CREATE TABLE `rayon` ( `id` int(11) NOT NULL, `Quantitรฉ` int(11) NOT NULL, `Nom _fournisseur` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
f0b2bda9d89bd9f3b26a9891e445109551c021c5
[ "SQL" ]
1
SQL
smailkaddi/brief10
8d86291392ba0cb7552696f2e901bf21f6762aa2
4ba44ae61563eb9f105378f5d25993b0f905f0d4
refs/heads/master
<repo_name>ebostijancic/fwup<file_sep>/src/fat_cache.h #ifndef FAT_CACHE_H #define FAT_CACHE_H #include <stdlib.h> #include <stdint.h> #include <stdbool.h> #include <sys/types.h> struct fat_cache { int fd; off_t partition_offset; char *cache; size_t cache_size_blocks; // Bit field of invalid and dirty bits uint8_t *flags; // read_on_invalid is true if the SDCard should // be read when accessing an invalid block in the cache. If false, // the block is filled with zeros. bool read_on_invalid; }; int fat_cache_init(struct fat_cache *fc, int fd, off_t partition_offset, size_t cache_size); void fat_cache_format(struct fat_cache *fc); int fat_cache_read(struct fat_cache *fc, off_t block, size_t count, char *buffer); ssize_t fat_cache_write(struct fat_cache *fc, off_t block, size_t count, const char *buffer); ssize_t fat_cache_free(struct fat_cache *fc); #endif // FAT_CACHE_H <file_sep>/tests/109_includes.test #!/bin/sh # # Test that including files works # . ./common.sh cat >$CONFIG.1 <<EOF file-resource file { host-path = "${TESTFILE_150K}" } EOF cat >$CONFIG.2 <<EOF include("$CONFIG.1") EOF cat >$CONFIG.3 <<EOF task complete { on-resource file { raw_write(0) } } EOF cat >$CONFIG <<EOF include($CONFIG.2) include($CONFIG.3) EOF # Create the firmware file, then "burn it" $FWUP_CREATE -c -f $CONFIG -o $FWFILE $FWUP_APPLY -a -d $IMGFILE -i $FWFILE -t complete # The firmware file is equivalent to the following dd call # (The conv=sync makes sure that the output is a multiple of 512 bytes) dd if=$TESTFILE_150K seek=0 of=$WORK/check.bin conv=sync 2>/dev/null diff $WORK/check.bin $IMGFILE # Check that the verify logic works on this file $FWUP_APPLY -V -i $FWFILE <file_sep>/src/fat_cache.c #include "fat_cache.h" #include "util.h" #include <memory.h> #include <unistd.h> // Cache bit handling functions static inline void set_dirty(struct fat_cache *fc, int block) { // Dirty implies that the block is valid, so make sure that it's set too. uint8_t *bits = &fc->flags[block / 4]; *bits = *bits | (0x3 << (2 * (block & 0x3))); } static inline bool is_dirty(struct fat_cache *fc, int block) { return (fc->flags[block / 4] & (0x1 << (2 * (block & 0x3)))) != 0; } static inline void set_valid(struct fat_cache *fc, int block) { uint8_t *bits = &fc->flags[block / 4]; *bits = *bits | (0x2 << (2 * (block & 0x3))); } static inline bool is_valid(struct fat_cache *fc, int block) { return (fc->flags[block / 4] & (0x2 << (2 * (block & 0x3)))) != 0; } /** * @brief Simple cache for operating on FAT filesystems * * The FATFS code makes small 512 byte reads and writes to the underlying media. On systems * that don't have a cache between fwup and the disk, this can double the update time. Caching * is fairly simple due to some simple assumptions: * * 1. We only cache the first n bytes of the filesystem, since fwup isn't really intended * to handle large FAT filesystems in regular operation. Reads and writes after this * aren't cached. * 2. The FAT table at the beginning is the big abuser of small and repeated reads and * writes. * 3. Writes are mostly contiguous. This means that combining FATFS writes into larger * blocks will be a win. If the FS is heavily fragmented, this won't help much, but * the boot filesystems modified by fwup really shouldn't become heavily fragmented. * * @param fc * @param fd the target file to write to * @param cache_size the size of the cache (e.g. the size of the filesystem in bytes or some fraction) * @return 0 if ok, -1 if not */ int fat_cache_init(struct fat_cache *fc, int fd, off_t partition_offset, size_t cache_size) { fc->fd = fd; fc->partition_offset = partition_offset; fc->cache = malloc(cache_size); if (!fc->cache) ERR_RETURN("Could not allocate FAT cache of %d bytes", cache_size); fc->cache_size_blocks = cache_size / 512; fc->flags = malloc(fc->cache_size_blocks / 4); if (!fc->flags) ERR_RETURN("Could not allocate FAT cache flags"); memset(fc->flags, 0, fc->cache_size_blocks / 4); fc->read_on_invalid = true; return 0; } /** * @brief "Erase" everything in the partition * * This really just invalidates everything in the cache and sets it so * that any reads will return zero'd blocks. * * @param fc * @return */ void fat_cache_format(struct fat_cache *fc) { fc->read_on_invalid = false; memset(fc->flags, 0, fc->cache_size_blocks / 4); // Optimization: Initialize the first 128 KB or else there's a // random patchwork in the beginning that gets flushed at the end. if (fc->cache_size_blocks >= 256) { memset(fc->cache, 0, 256 * 512); memset(fc->flags, 0xff, 256 / 4); } } static ssize_t load_cache(struct fat_cache *fc, int block, int count) { size_t byte_count = count * 512; ssize_t rc = 0; if (fc->read_on_invalid) { off_t byte_offset = fc->partition_offset + block * 512; rc = pread(fc->fd, &fc->cache[block * 512], byte_count, byte_offset); if (rc < 0) ERR_RETURN("Error reading FAT filesystem"); } else { // Not sure why we're reading an uninitialized block, but set it to 0s memset(&fc->cache[block * 512], 0, byte_count); } int i; for (i = 0; i < count; i++) set_valid(fc, block + i); return rc; } /** * @brief Read from the cache * * @param fc * @param block * @param count * @param buffer * @return */ int fat_cache_read(struct fat_cache *fc, off_t block, size_t count, char *buffer) { // Fetch anything directly that's beyond what we cache if (block + count > fc->cache_size_blocks) { off_t uncached_block = (block > (off_t) fc->cache_size_blocks ? block : (off_t) fc->cache_size_blocks); off_t uncached_count = block + count - uncached_block; char *uncached_buffer = buffer + (uncached_block - block) * 512; off_t byte_offset = fc->partition_offset + uncached_block * 512; size_t byte_count = uncached_count * 512; ssize_t amount_read = pread(fc->fd, uncached_buffer, byte_count, byte_offset); if (amount_read < 0) ERR_RETURN("Can't read block %d, count=%d", uncached_block, uncached_count); // Adjust the count so that we're just left with the part in the cached area count -= uncached_count; if (count == 0) return 0; } // The common case is that the block will either be all valid or all invalid bool all_valid = true; bool all_invalid = true; size_t i; for (i = 0; i < count; i++) { bool v = is_valid(fc, block + i); all_valid = all_valid && v; all_invalid = all_invalid && !v; } if (all_invalid) { // If we have to read from Flash, see if we can read up to 128 KB (256 * 512 byte blocks) size_t precache_count = count; for (; precache_count < 256 && block + precache_count < fc->cache_size_blocks; precache_count++) { if (is_valid(fc, block + precache_count)) break; } if (load_cache(fc, block, precache_count) < 0) return -1; } else { if (!all_valid) { // Not all invalid and not all valid. Punt. Just load each block individually, since this is // a rare case. for (i = 0; i < count; i++) { if (!is_valid(fc, block + i) && load_cache(fc, block + i, 1) < 0) return -1; } } } memcpy(buffer, &fc->cache[block * 512], count * 512); return 0; } /** * @brief Write to the cache * * If the write crosses over the area that we cache, then write directly to the output * without buffering. * * @param fc * @param block the starting block * @param count how many blocks to write * @param buffer the data to write * @return the number of bytes written to disk or -1 if error. Normally this is * 0 to indicate that everything was written to cache */ ssize_t fat_cache_write(struct fat_cache *fc, off_t block, size_t count, const char *buffer) { ssize_t rc = 0; off_t last = block + count; for (; block < last && block < (off_t) fc->cache_size_blocks; block++) { memcpy(&fc->cache[512 * block], buffer, 512); set_dirty(fc, block); buffer += 512; } if (block != last) { off_t byte_offset = fc->partition_offset + block * 512; size_t byte_count = (last - block) * 512; rc = pwrite(fc->fd, buffer, byte_count, byte_offset); } return rc; } static ssize_t flush_buffer(struct fat_cache *fc, int block, int count) { off_t byte_offset = fc->partition_offset + block * 512; int cache_index = block * 512; size_t byte_count = count * 512; ssize_t amount_written = 0; while (byte_count) { // Write only 128 KB at a time, since raw writing too much // may not be handled well by the OS. size_t to_write = 128 * 1024; if (to_write > byte_count) to_write = byte_count; ssize_t rc = pwrite(fc->fd, &fc->cache[cache_index], to_write, byte_offset); if (rc < 0) ERR_RETURN("Error writing FAT filesystem"); byte_offset += to_write; cache_index += to_write; byte_count -= to_write; amount_written += rc; } return amount_written; } /** * @brief Flush the FAT cache and free memory * * @param fc * @return the number of bytes written to the device or -1 if error */ ssize_t fat_cache_free(struct fat_cache *fc) { ssize_t amount_written = 0; int starting_block = -1; off_t block; for (block = 0; block < (off_t) fc->cache_size_blocks; block++) { if (is_dirty(fc, block)) { if (starting_block < 0) starting_block = block; } else { if (starting_block >= 0) { ssize_t rc = flush_buffer(fc, starting_block, block - starting_block); if (rc < 0) return rc; amount_written += rc; starting_block = -1; } } } if (starting_block >= 0) { ssize_t rc = flush_buffer(fc, starting_block, block - starting_block); if (rc < 0) return rc; amount_written += rc; } free(fc->flags); free(fc->cache); fc->cache_size_blocks = 0; return amount_written; } <file_sep>/src/block_writer.h /* * Copyright 2014 LKC Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ALIGNED_WRITER_H #define ALIGNED_WRITER_H #include <sys/types.h> /* * The aligned_writer encapsulates the logic to write at raw disk * devices at aligned offsets and multiples of block_size whenever * possible. This significantly improves throughput on systems * that do not buffer writes. */ struct block_writer { int fd; size_t buffer_size; size_t block_size; off_t block_size_mask; char *buffer; off_t write_offset; size_t buffer_index; size_t added_bytes; }; int block_writer_init(struct block_writer *bw, int fd, int buffer_size, int log2_block_size); ssize_t block_writer_pwrite(struct block_writer *aw, const void *buf, size_t count, off_t offset); ssize_t block_writer_free(struct block_writer *aw); #endif // ALIGNED_WRITER_H <file_sep>/tests/039_upgrade.test #!/bin/sh # # Write a firmware image and then test upgrading it # . ./common.sh cat >$CONFIG <<EOF # +-----------------------------+ # | MBR | # +-----------------------------+ # | p0: Boot (Simulated) | # +-----------------------------+ # | p1*: Rootfs A (Simulated) | # +-----------------------------+ # | p1*: Rootfs B (Simulated) | # +-----------------------------+ # | p2: Data (Simulated) | # +-----------------------------+ define(BOOT_PART_OFFSET, 256) # at offset 128K define(BOOT_PART_COUNT, 256) define(ROOTFS_A_PART_OFFSET, 1024) define(ROOTFS_A_PART_COUNT, 1024) define(ROOTFS_B_PART_OFFSET, 2048) define(ROOTFS_B_PART_COUNT, 1024) define(APP_PART_OFFSET, 4096) define(APP_PART_COUNT, 1024) file-resource boot.stuff { host-path = "${TESTFILE_1K}" } file-resource data.stuff { host-path = "${TESTFILE_1K}" } file-resource rootfs.stuff { host-path = "${TESTFILE_150K}" } mbr mbr-a { partition 0 { block-offset = \${BOOT_PART_OFFSET} block-count = \${BOOT_PART_COUNT} type = 0xc # FAT32 boot = true } partition 1 { block-offset = \${ROOTFS_A_PART_OFFSET} block-count = \${ROOTFS_A_PART_COUNT} type = 0x83 # Linux } partition 2 { block-offset = \${APP_PART_OFFSET} block-count = \${APP_PART_COUNT} type = 0xc # FAT32 } # partition 3 is unused } mbr mbr-b { partition 0 { block-offset = \${BOOT_PART_OFFSET} block-count = \${BOOT_PART_COUNT} type = 0xc # FAT32 boot = true } partition 1 { block-offset = \${ROOTFS_B_PART_OFFSET} block-count = \${ROOTFS_B_PART_COUNT} type = 0x83 # Linux } partition 2 { block-offset = \${APP_PART_OFFSET} block-count = \${APP_PART_COUNT} type = 0xc # FAT32 } # partition 3 is unused } # This firmware task writes everything to the destination media task complete { on-init { mbr_write(mbr-a) } on-resource boot.stuff { raw_write(\${BOOT_PART_OFFSET}) } on-resource data.stuff { raw_write(\${APP_PART_OFFSET}) } on-resource rootfs.stuff { raw_write(\${ROOTFS_A_PART_OFFSET}) } } task upgrade.a { # This task upgrades the A partition and runs when partition B # is being used. require-partition-offset(1, \${ROOTFS_B_PART_OFFSET}) on-init { mbr_write(mbr-a) } on-resource rootfs.stuff { raw_write(\${ROOTFS_A_PART_OFFSET}) } } task upgrade.b { # This task upgrades the B partition and runs when partition B # is being used. require-partition-offset(1, \${ROOTFS_A_PART_OFFSET}) on-init { mbr_write(mbr-b) } on-resource rootfs.stuff { raw_write(\${ROOTFS_B_PART_OFFSET}) } } # This task is just needed to help support the unit test task dump_mbr_b { on-init { mbr_write(mbr-b) } } EOF # Create the firmware file, then "burn it" $FWUP_CREATE -c -f $CONFIG -o $FWFILE $FWUP_APPLY -a -d $IMGFILE -i $FWFILE -t complete # The firmware file is equivalent to the following dd calls # Assume that previous tests make sure that the MBR is correct and just # copy it over. dd if=$IMGFILE of=$WORK/check.bin count=1 2>/dev/null dd if=$TESTFILE_1K seek=256 of=$WORK/check.bin conv=sync,notrunc 2>/dev/null dd if=$TESTFILE_150K seek=1024 of=$WORK/check.bin conv=sync,notrunc 2>/dev/null dd if=$TESTFILE_1K seek=4096 of=$WORK/check.bin conv=sync,notrunc 2>/dev/null diff $WORK/check.bin $IMGFILE # Now upgrade the IMGFILE file $FWUP_APPLY -a -d $IMGFILE -i $FWFILE -t upgrade $FWUP_APPLY -a -d $WORK/mbr_b.bin -i $FWFILE -t dump_mbr_b cp $WORK/check.bin $WORK/check-upgraded.bin dd if=$WORK/mbr_b.bin of=$WORK/check-upgraded.bin conv=notrunc 2>/dev/null dd if=$TESTFILE_150K seek=2048 of=$WORK/check-upgraded.bin conv=sync,notrunc 2>/dev/null diff $WORK/check-upgraded.bin $IMGFILE # Check that the verify logic works on this file $FWUP_APPLY -V -i $FWFILE <file_sep>/scripts/third_party_versions.sh #!/bin/sh # # Version numbers for the 3rd party source dependencies # ZLIB_VERSION=1.2.11 LIBARCHIVE_VERSION=3.3.1 LIBSODIUM_VERSION=1.0.12 CONFUSE_VERSION=3.0 CHOCO_VERSION=0.10.3 <file_sep>/src/block_writer.c #include "block_writer.h" #include "util.h" #include <assert.h> #include <stdlib.h> #include <string.h> #include <unistd.h> /** * @brief Helper for buffering writes into block-sized pieces * * This is needed since the unzip process creates variable sized chunks that need * to be combined before being written. File I/O to Flash media works best in 128 KB+ * sized chunks, so cache the writes until they get to that size. Writes MUST be * monotically increasing in offset. Seeking backwards is NOT supported. * * Based on benchmarks and inspection of how Linux writes to Flash media at a low level, * the chunks don't need to be on Flash erase block boundaries or Flash erase block size. * This doesn't appear to hurt, but I found out that Linux was sending 120 KB blocks (NOT * 128 KB blocks) via a USB sniffer no matter how much larger blocks were written. Performance * was still very fast. * * This code also pads files out to block boundaries (512 bytes for all supported media now). * This appears to be needed on OSX when writing to /dev/rdiskN devices. * * @param aw * @param fd the target file to write to * @param buffer_size the size of the buffer (rounded to multiple of 2^log2_block_size) * @param log2_block_size 9 for 512 byte blocks * @return 0 if ok, -1 if not */ int block_writer_init(struct block_writer *bw, int fd, int buffer_size, int log2_block_size) { bw->fd = fd; bw->block_size = (1 << log2_block_size); bw->block_size_mask = ~((off_t) bw->block_size - 1); bw->buffer_size = (buffer_size + ~bw->block_size_mask) & bw->block_size_mask; bw->buffer = (char *) malloc(bw->buffer_size); if (bw->buffer == 0) ERR_RETURN("Cannot allocate write buffer of %d bytes.", bw->buffer_size); bw->write_offset = 0; bw->buffer_index = 0; bw->added_bytes = 0; return 0; } static ssize_t flush_buffer(struct block_writer *bw) { assert(bw->buffer_index <= bw->buffer_size); // Math failed somewhere if we're buffering more than the block_size // Make sure that we're writing a whole block or pad it with 0s just in case. // Note: this isn't necessary when writing through a cache to a device, but that's // not always the case. size_t block_boundary = (bw->buffer_index + ~bw->block_size_mask) & bw->block_size_mask; ssize_t added_bytes = bw->added_bytes; if (block_boundary != bw->buffer_index) { ssize_t padding_bytes = block_boundary - bw->buffer_index; memset(&bw->buffer[bw->buffer_index], 0, padding_bytes); added_bytes += padding_bytes; bw->buffer_index = block_boundary; } ssize_t rc = pwrite(bw->fd, bw->buffer, bw->buffer_index, bw->write_offset); if (rc != (ssize_t) bw->buffer_index) return -1; // Success. Adjust rc to not count the padding. bw->write_offset += bw->buffer_index; bw->buffer_index = 0; bw->added_bytes = 0; return rc - added_bytes; } /** * @brief Write a number of bytes to an offset like pwrite * * The offset must be monotonically increasing, but gaps are supported * when dealing with sparse files. * * @param bw * @param buf the buffer * @param count how many bytes to write * @param offset where to write in the file * @return -1 if error or the number of bytes written to Flash (if <count, then bytes were buffered) */ ssize_t block_writer_pwrite(struct block_writer *bw, const void *buf, size_t count, off_t offset) { ssize_t amount_written = 0; if (bw->buffer_index) { // If we're buffering, fill in the buffer the rest of the way off_t position = bw->write_offset + bw->buffer_index; assert(offset >= position); // Check monotonicity of offset size_t to_write = bw->buffer_size - bw->buffer_index; if (offset > position) { off_t gap_size = offset - position; if (gap_size >= (off_t) to_write) { // Big gap, so flush the buffer ssize_t rc = flush_buffer(bw); if (rc < 0) return rc; amount_written += rc; goto empty_buffer; } else { // Small gap, so fill it in with 0s and buffer more memset(&bw->buffer[bw->buffer_index], 0, gap_size); bw->added_bytes += gap_size; bw->buffer_index += gap_size; to_write -= gap_size; } } assert(offset == (off_t) (bw->write_offset + bw->buffer_index)); if (count < to_write) { // Not enough to write to disk, so buffer for next time memcpy(&bw->buffer[bw->buffer_index], buf, count); bw->buffer_index += count; return amount_written; } else { // Fill out the buffer memcpy(&bw->buffer[bw->buffer_index], buf, to_write); buf += to_write; count -= to_write; offset += to_write; bw->buffer_index += to_write; ssize_t rc = flush_buffer(bw); if (rc < 0) return rc; amount_written += rc; } } empty_buffer: assert(bw->buffer_index == 0); assert(offset >= bw->write_offset); assert(bw->added_bytes == 0); // Advance to the offset, but make sure that it's on a block boundary bw->write_offset = (offset & bw->block_size_mask); size_t padding = offset - bw->write_offset; if (padding > 0) { // NOTE: Padding both to the front and back seems like we could get into a situation // where we overlap and wipe out some previously written data. This is impossible // to do, though, since within a file, we're guaranteed to be monotonically // increasing in our write offsets. Therefore, if we flush a block, we're guaranteed // to never see that block again. Between files there could be a problem if the // user configures overlapping blocks offsets between raw_writes. I can't think of // a use case for this, but the config file format specifies everything in block // offsets anyway. memset(bw->buffer, 0, padding); bw->added_bytes += padding; if (count + padding >= bw->block_size) { // Handle the block fragment size_t to_write = bw->block_size - padding; memcpy(&bw->buffer[padding], buf, to_write); if (pwrite(bw->fd, bw->buffer, bw->block_size, bw->write_offset) < 0) return -1; bw->write_offset += bw->block_size; amount_written += bw->block_size - bw->added_bytes; bw->added_bytes = 0; buf += to_write; count -= to_write; } else { // Buffer the block fragment for next time memcpy(&bw->buffer[padding], buf, count); bw->buffer_index = count + padding; return amount_written; } } // At this point, we're aligned to a block boundary assert((bw->write_offset & ~bw->block_size_mask) == 0); // If we have more than a buffer's worth, write all filled blocks // without even trying to buffer. if (count > bw->buffer_size) { size_t to_write = (count & bw->block_size_mask); if (pwrite(bw->fd, buf, to_write, bw->write_offset) < 0) return -1; bw->write_offset += to_write; amount_written += to_write - bw->added_bytes; bw->added_bytes = 0; buf += to_write; count -= to_write; } // Buffer the left overs if (count) { memcpy(bw->buffer, buf, count); bw->buffer_index = count; } return amount_written; } /** * @brief flush and free the aligned writer data structures * @param bw * @return number of bytes written or -1 if error */ ssize_t block_writer_free(struct block_writer *bw) { // Write any data that's still in the buffer ssize_t rc = 0; if (bw->buffer_index) rc = flush_buffer(bw); // Free our buffer and clean up free(bw->buffer); bw->fd = -1; bw->buffer = 0; bw->buffer_index = 0; return rc; } <file_sep>/tests/060_framed_streaming.test #!/bin/sh # # Test streaming a firmware update through fwup with framing. # This simulates the case where there's no local storage to hold # the firmware update while it is being applied. # . ./common.sh cat >$CONFIG <<EOF file-resource TEST { host-path = "${TESTFILE_1K}" } task complete { on-resource TEST { raw_write(1) } } EOF # Create the firmware file like normal $FWUP_CREATE -c -f $CONFIG -o $FWFILE # Pipe the framed contents (in super small chunks) on the .fw file to fwup cat $FWFILE | $FRAMING_HELPER -n 50 -e \ | $FWUP_APPLY -q --framing -a -d $IMGFILE -i - -t complete # The firmware file is equivalent to the following dd call dd if=$TESTFILE_1K seek=1 of=$WORK/check.bin 2>/dev/null diff $WORK/check.bin $IMGFILE
437e59236054d3bfe8372cecf3986151e5f8939a
[ "C", "Shell" ]
8
C
ebostijancic/fwup
f339a77abb92afe778d3afe056e0079a7842380d
41cb89da6f2b9b9e6d7a0c616cf0f8f3ea6d2cb5
refs/heads/master
<file_sep>import importlib from .internal import commands __all__ = ["system"] modules = {} for m in __all__: modules[m] = importlib.import_module("modules." + m) def init(client): objects = {} on_messages = [] for m in __all__: modules[m] = importlib.reload(modules[m]) obj = modules[m].main(client) objects[m] = obj commands.objects[m] = obj try: on_messages.append(obj.on_message) except AttributeError: pass return objects, on_messages <file_sep>import sys import os import time import asyncio import importlib import discord #we cant unload discord or nacl will give an error when we try to re-load it if os.name == 'posix': #use uvloop if possible try: import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) except ImportError: print("Unable to import uvloop. Reverting to asyncio.") else: print("Uvloop is not supported on this system. Reverting to asyncio.") initial = sys.modules.copy().keys() #get initial list of modules not to remove import botCore restartMsg = None while True: print("Running bot.") restartMsg = botCore.run(restartMsg) #run the bot print("Bot finished with restart status " + str(restartMsg is not None) + ".") if restartMsg is not None: loop_old = asyncio.get_event_loop() #discard the old event loop loop_old.close() asyncio.set_event_loop(asyncio.new_event_loop()) for m in [x for x in sys.modules.keys() if x not in initial]: #re-import bluCore and modules it imports del sys.modules[m] import botCore else: print("Exiting.") sys.exit(0) <file_sep>import asyncio import os from os.path import join as pjoin import json import sys import traceback import datetime import modules from modules.internal.bot import Bot from modules.internal import commands from modules.internal import perms with open(pjoin("data","botData.json"),"r") as infile: data = json.loads(infile.read()) client = Bot(data[-1]) print("Loading modules.") objects, on_messages = modules.init(client) system = objects["system"] print("Modules loaded.") cooldown = {} @client.event async def on_ready(): print('Logged in as ' + client.user.display_name + '.') if restartMsg is not None: await client.send_message(restartMsg.channel, "Restarted successfully.") @client.event async def on_message(m): if client.was_sent(m): return if m.content.startswith(client.prefix) and not m.author.bot and m.content.strip(client.prefix) != "": if cooldown.get(m.author.id, None) is not None and not await perms.check(m.author.id, "owner"): if (datetime.datetime.now() - cooldown[m.author.id]).total_seconds() < 3: return cooldown[m.author.id] = datetime.datetime.now() if ' ' in m.content: comm, args = m.content[len(client.prefix):].split(" ", 1) else: comm = m.content[len(client.prefix):] args = None if comm.lower() in commands.commands.keys(): try: await commands.commands[comm.lower()](m, args) return except Exception as e: res = "An internal error occurred. Contact <@!207648732336881664> for help.\n```python\n" exc_type, exc_value, exc_traceback = sys.exc_info() for i, line in enumerate(traceback.format_exception(exc_type, exc_value, exc_traceback)): if i > 0 and i < len(traceback.format_exception(exc_type, exc_value, exc_traceback)) - 1 and not line.split(os.sep)[-1].startswith(" File"): res += ' File "' res += line.split(os.sep)[-1] res += "```" await client.send_message(m.channel, res) if args is None: args = "" for func in on_messages: await func(m) restartMsg = None def run(msg): global restartMsg restartMsg = msg loop = asyncio.get_event_loop() try: try: print("Logging in.") loop.run_until_complete(client.start(*data[:-1])) except RuntimeError: pass except KeyboardInterrupt: loop.run_until_complete(client.logout()) print("Logged out.") return client.isRestart <file_sep>#Legends Role-Playing Bot
d49646c282d864a65885d661436b509f0dfabfe3
[ "Markdown", "Python" ]
4
Python
BluCodeGH/LegendsRPBot
1ace62506fc7b46cef9a298a358715754cfd27fc
47718726e3389aec6a5fe60eda580487f55a1bc1
refs/heads/master
<repo_name>playdj/playdj<file_sep>/README.md playdj ====== DJ with your friends using your google music accounts! <file_sep>/site/core/auth/AuthBackend.py from django.conf import settings from django.contrib.auth.models import User from gmusicapi import Mobileclient class AuthBackend(object): """ Authenticate against the user's google account with gmusicapi If this is the User's first time logging in, create them an account. """ def authenticate(self, email=None, password=<PASSWORD>): # create the gmusicapi client and attempt to login # TODO: store the client somewhere so we can use it for music gmc = Mobileclient() valid = gmc.login(email, password) if valid: try: user = User.objects.get(username=username) except User.DoesNotExist: # Create a new user. We don't need to store the password user = User(username=username, password='<PASSWORD>') # TODO: store some basic account info user.save() return user return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None
b10f6e18367c024ecd1026014357b230628cf525
[ "Markdown", "Python" ]
2
Markdown
playdj/playdj
230fc3fe51c0365230c32fbd5c6b51a0e9b30366
60b18a72ab054941226515b43265fd250500ae16
refs/heads/master
<repo_name>Fermec28/c9ia4hfh<file_sep>/app/models/room.rb # == Schema Information # # Table name: rooms # # id :integer not null, primary key # title :string # description :text # beds :integer # guests :integer # created_at :datetime not null # updated_at :datetime not null # image_url :string # #l campo description no debe tener mรกs de 400 caracteres. #El campo beds debe ser un nรบmero (entero). #El campo guests debe ser un nรบmero (entero). class Room < ActiveRecord::Base validates :title, :description, :beds, :guests, :image_url, presence: true validates :description, length:{maximum:400} validates :beds, :guests, numericality: {only_integer: true} end
15d2706949b73a1aeeb7cffd0b7548b1d3d1ad38
[ "Ruby" ]
1
Ruby
Fermec28/c9ia4hfh
60497629bf748f4e923dcaa20bdbf25d51a4ac13
ef1beda8b8055aaf175d2d34a711d64beda227bd
refs/heads/main
<repo_name>Qb1ss/LIGHT-IS-KEY<file_sep>/Assets/Scripts/GameController.cs using UnityEngine; public class GameController : MonoBehaviour { [Header ("Camera")] [SerializeField] private Camera _camera; [Space (height: 5f)] [Header("Game Object")] [SerializeField] private SpriteRenderer _lightBulb; [Space(height: 5f)] [Header("End Game")] [SerializeField] private GameObject _menu; private void Start() { Time.timeScale = 1; _lightBulb.enabled = false; } public void Tap() { _menu.SetActive(true); _lightBulb.enabled = true; _camera.backgroundColor = new Color(0.6933962f, 1f, 0.7789167f); Time.timeScale = 0; } }<file_sep>/Assets/Assets/CustomToolbar/Editor/CustomToolbar/Scripts/ToolbarElements/ToolbarSceneSelection.cs ๏ปฟusing System; using System.Linq; using System.Collections.Generic; using System.IO; using UnityEngine; using UnityEngine.SceneManagement; using UnityEditor; using UnityEditor.SceneManagement; [Serializable] internal class ToolbarSceneSelection : BaseToolbarElement { public override string NameInList => "[Dropdown] Scene selection"; [SerializeField] bool showSceneFolder = true; SceneData[] scenesPopupDisplay; string[] scenesPath; string[] scenesBuildPath; int selectedSceneIndex; public override void Init() { RefreshScenesList(); EditorSceneManager.sceneOpened -= HandleSceneOpened; EditorSceneManager.sceneOpened += HandleSceneOpened; } protected override void OnDrawInList(Rect position) { position.width = 200.0f; showSceneFolder = EditorGUI.Toggle(position, "Group by folders", showSceneFolder); } protected override void OnDrawInToolbar() { EditorGUI.BeginDisabledGroup(EditorApplication.isPlaying); DrawSceneDropdown(); EditorGUI.EndDisabledGroup(); } private void DrawSceneDropdown() { selectedSceneIndex = EditorGUILayout.Popup(selectedSceneIndex, scenesPopupDisplay.Select(e => e.popupDisplay).ToArray(), GUILayout.Width(WidthInToolbar)); if (GUI.changed && 0 <= selectedSceneIndex && selectedSceneIndex < scenesPopupDisplay.Length) { if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo()) { foreach (var scenePath in scenesPath) { if ((scenePath) == scenesPopupDisplay[selectedSceneIndex].path) { EditorSceneManager.OpenScene(scenePath); break; } } } } } void RefreshScenesList() { List<SceneData> toDisplay = new List<SceneData>(); selectedSceneIndex = -1; scenesBuildPath = EditorBuildSettings.scenes.Select(s => s.path).ToArray(); string[] sceneGuids = AssetDatabase.FindAssets("t:scene", new string[] { "Assets" }); scenesPath = new string[sceneGuids.Length]; for (int i = 0; i < scenesPath.Length; ++i) { scenesPath[i] = AssetDatabase.GUIDToAssetPath(sceneGuids[i]); } Scene activeScene = SceneManager.GetActiveScene(); int usedIds = scenesBuildPath.Length; for (int i = 0; i < scenesBuildPath.Length; ++i) { string name = GetSceneName(scenesBuildPath[i]); if (selectedSceneIndex == -1 && GetSceneName(name) == activeScene.name) selectedSceneIndex = i; GUIContent content = new GUIContent(name, EditorGUIUtility.Load("BuildSettings.Editor.Small") as Texture, "Open scene"); toDisplay.Add(new SceneData() { path = scenesBuildPath[i], popupDisplay = content, }); } toDisplay.Add(new SceneData() { path = "\0", popupDisplay = new GUIContent("\0"), }); ++usedIds; for (int i = 0; i < scenesPath.Length; ++i) { if (scenesBuildPath.Contains(scenesPath[i])) continue; string name; if (showSceneFolder) { string folderName = Path.GetFileName(Path.GetDirectoryName(scenesPath[i])); name = $"{folderName}/{GetSceneName(scenesPath[i])}"; } else { name = GetSceneName(scenesPath[i]); } if (selectedSceneIndex == -1 && name == activeScene.name) selectedSceneIndex = usedIds; GUIContent content = new GUIContent(name, "Open scene"); toDisplay.Add(new SceneData() { path = scenesPath[i], popupDisplay = content, }); ++usedIds; } scenesPopupDisplay = toDisplay.ToArray(); } void HandleSceneOpened(Scene scene, OpenSceneMode mode) { RefreshScenesList(); } string GetSceneName(string path) { path = path.Replace(".unity", ""); return Path.GetFileName(path); } class SceneData { public string path; public GUIContent popupDisplay; } } <file_sep>/Assets/Scripts/Timer.cs ๏ปฟusing UnityEngine; using UnityEngine.UI; public class Timer : MonoBehaviour { [Header("Time")] [SerializeField] private int _timeLeft = 30; [SerializeField] private int _redTime; private float _gameTime; [Space(height: 5f)] [Header("Text")] [SerializeField] private Text _timerText; [Space(height: 5f)] [Header("Camera")] [SerializeField] private Camera _camera; [Space(height: 5f)] [Header("Game Object")] [SerializeField] private SpriteRenderer _lightBulb; [Space(height: 5f)] [Header("End Game")] [SerializeField] private GameObject _menu; private void Start() { Time.timeScale = 1; } private void Update() { GameTimer(); } private void GameTimer() { _timerText.text = _timeLeft.ToString() + " s."; _gameTime += 1 * Time.deltaTime; if (_gameTime >= 1) { _timeLeft--; _gameTime = 0; } else if (_timeLeft <= _redTime) { _timerText.color = Color.red; } if (_timeLeft <= 0) { _lightBulb.enabled = true; _camera.backgroundColor = Color.red; _menu.SetActive(true); Time.timeScale = 0; } } }<file_sep>/Assets/Assets/CustomToolbar/README.md # CustomToolbar ![Unity 2019.4+](https://img.shields.io/badge/unity-unity%202019.4%2B-blue) ![License: MIT](https://img.shields.io/badge/License-MIT-brightgreen.svg) based on this [marijnz unity-toolbar-extender](https://github.com/marijnz/unity-toolbar-extender). ![image](https://user-images.githubusercontent.com/16706911/100000419-cff31e00-2dd6-11eb-9a4b-8379e3a7cc50.jpg) ### Why you should use the CustomToolbar? This custom tool helps you to test and develop your game easily ## Installation You can also install via git url by adding this entry in your **manifest.json** ```"com.smkplus.custom-toolbar": "https://github.com/smkplus/CustomToolbar.git#master",``` ## Installation through Unity-Package-Manager (2019.2+) * MenuItem - Window - Package Manager * Add package from git url * paste https://github.com/smkplus/CustomToolbar.git#master ## Sample scenes to test You can import sample scenes from package manager. ![image](Images~/Package-Manager.png) ____________ Scene selection dropdown to open scene in editor. Scenes in build have unity icon while selected and appear above splitter in list ![image](Images~/SceneSelect.jpg) ____________ when you want to clear all playerprefs you have to follow 3 step: ![image](https://user-images.githubusercontent.com/16706911/68548191-52dd4c80-03ff-11ea-85b6-e9899ab04c34.jpg) but you can easily Clear them by clicking on this button: ![image](Images~/btnClearPrefs.jpg) ____________ another button relevant to saving is this button that prevents saving during the gameplay. because sometimes you have to Clear All playerprefs after each test so you can enable this toggle: Enable Playerprefs: ![image](Images~/btnDisablePrefs.jpg) Disable Playerprefs: ![image](Images~/btnDisablePrefsInactive.jpg) ____________ you can restart the active scene by this button: ![image](Images~/btnRestartScene.jpg) ____________ suppose you want to test your game so you should start game from scene 1(Menu): ![image](https://user-images.githubusercontent.com/16706911/68548295-8371b600-0400-11ea-8737-a9da3d555df0.png) you have to find scene 1 (Menu): ![image](https://user-images.githubusercontent.com/16706911/68548309-c2a00700-0400-11ea-9740-128368bd801a.png) then you should start the game: ![image](https://user-images.githubusercontent.com/16706911/100723264-cd945380-33d6-11eb-9611-b1fe470dbd0b.png) this button is shortcut to start the game from scene 1: ![image](Images~/btnFirstScene.jpg) ____________ I usually test my games by changing timescale. ![image](Images~/timescale.jpg) ____________ Also it usefull to test your game with different framerates, to be sure that it is framerate-independent. ![image](Images~/FPS.jpg) ____________ Button to recompile scripts. Usefull when you working on splitting code into .asmdef ![image](Images~/btnRecompile.jpg) ____________ Force reserialize selected(in project window) assets. What it does - https://docs.unity3d.com/ScriptReference/AssetDatabase.ForceReserializeAssets.html ![image](Images~/btnReserializeSelected.jpg) ____________ Force reserialize all assets. Same as previous, but for all assets and takes some time. Use this after adding new asset or updating unity version in order to not spam git history with unwanted changes. ![image](Images~/btnReserializeAll.jpg) ____________ You can customize the toolbar on Project Setting ![Images~/ProjectSetting-CustomToolbar.png](Images~/ProjectSetting-CustomToolbar.png) _____ ## How to Contribute Development directory: 1. Create a project through Unity Hub. 2. clone repository at `Package` folder at root of project. 3. edit codes with your IDE. ![image](https://user-images.githubusercontent.com/51351749/100615833-8452ee00-335b-11eb-9b29-463810651ec7.png) ![image](https://user-images.githubusercontent.com/51351749/100615844-8ae16580-335b-11eb-8a1e-4600bfe75454.png) ![image](https://user-images.githubusercontent.com/51351749/100615856-8e74ec80-335b-11eb-97c5-a6ff2fb1dd8f.png) <file_sep>/Assets/Scripts/Menu.cs using UnityEngine; using UnityEngine.SceneManagement; public class Menu : MonoBehaviour { public void Button_Start(string thisScene) { SceneManager.LoadScene(thisScene); } public void Button_Menu(string menuScene) { SceneManager.LoadScene(menuScene); } public void Button_Control(GameObject controlWindow) { controlWindow.SetActive(true); } public void ButtonExit_Control(GameObject controlWindow) { controlWindow.SetActive(false); } public void Button_Exit() { Application.Quit(); } }<file_sep>/Assets/Scripts/LightBulb.cs using UnityEngine; using UnityEngine.Events; public class LightBulb : MonoBehaviour { [Header("Positions")] [SerializeField] private float _xRange = 3f; [SerializeField] private float _yRange = 3f; private Vector2 _randomPosition; [Space(height: 5f)] [Header("Positions")] [SerializeField] private UnityEvent _onTap; private void Start() { NewPosition(); } private void NewPosition() { float xPosition = Random.Range(0 - _xRange, 0 + _xRange); float yPosition = Random.Range(0 - _yRange, 0 + _yRange); _randomPosition = new Vector2(xPosition, yPosition); transform.position = _randomPosition; } private void OnMouseDown() { _onTap.Invoke(); } }
f4d18c1f94d27927ee3a6e11094123cbe6deaaeb
[ "Markdown", "C#" ]
6
C#
Qb1ss/LIGHT-IS-KEY
fe9185d43a232688433d7e52d286bfe7f701e66b
60d495cd7210a1e5701c3937bdd89effe4b568fd
refs/heads/master
<file_sep><?php //Recebe o email. $email = $_POST['email']; if (filter_var($email, FILTER_VALIDATE_EMAIL)) { //Aqui vai conectar com o Banco de dados echo json_encode('<script> Command: toastr["success"]("Vocรช recebera novidades em breve...", "Enviado!") toastr.options = { "closeButton": false, "debug": false, "newestOnTop": false, "progressBar": false, "positionClass": "toast-top-right", "preventDuplicates": true, "onclick": null, "showDuration": "300", "hideDuration": "1000", "timeOut": "5000", "extendedTimeOut": "1000", "showEasing": "swing", "hideEasing": "linear", "showMethod": "fadeIn", "hideMethod": "fadeOut" }</script> '); } else { echo json_encode(' <script> Command: toastr["error"]("Digite um email vรกlido!", "Atenรงรฃo!") toastr.options = { "closeButton": false, "debug": true, "newestOnTop": false, "progressBar": false, "positionClass": "toast-top-right", "preventDuplicates": false, "onclick": null, "showDuration": "300", "hideDuration": "1000", "timeOut": "5000", "extendedTimeOut": "1000", "showEasing": "swing", "hideEasing": "linear", "showMethod": "fadeIn", "hideMethod": "fadeOut" } </script> '); } ?><file_sep><footer class="bg-dark mg"> <div class="bg-dark text-white"> <div class="container"> <div class="row"> <div class="p-4 col-md-3"> <h2 class="mb-4 text-secondary">Agรชncia Ribsites</h2> <p class="text-white">Sites desenvolvidos e pensados no seu cliente. Criamos sites acessรญveis a audiovisuais.</p> </div> <div class="p-4 col-md-3"> <h2 class="mb-4 text-secondary">Sitemap</h2> <ul class="list-unstyled"> <a href="index.php" class="text-white">Inicio</a> <br> <a href="sobre.php" class="text-white">Sobre</a> <br> <a href="contato.php" class="text-white">Contato</a> <br> <a href="duvidas.php" class="text-white">Perguntas frequentes</a> </ul> </div> <div class="p-4 col-md-3"> <h2 class="mb-4">Contato</h2> <p> <a href="tel:4133923426 " class="text-white"><i class="fa d-inline mr-3 text-secondary fa-phone"></i>(41)92000-8829|WhatsApp</a> </p> <p> <a href="mailto:<EMAIL>" class="text-white"><i class="fa d-inline mr-3 text-secondary fa-at"></i> <EMAIL></a> </p> <p> <a href="https://goo.gl/maps/AUq7b9W7yYJ2" class="text-white" target="_blank"><i class="fa d-inline mr-3 fa-map-marker text-secondary"></i>Batista Sabim, 600 Campo Largo/Paranรก</a> </p> </div> <div class="p-4 col-md-3"> <h2 class="mb-4 text-light">Se inscrever</h2> <?php include 'email.php';?> </div> </div> <div class="row"> <div class="col-md-12 mt-3"> <p class="text-center text-white">ยฉ Copyright 2019 <NAME> - All rights reserved. </p> </div> </div> </div> </div> </footer> </body> </html><file_sep><?php include "php/header.php" ?> <div class="fundo2 abaixa-top2"> <h1 class="alert-warning">Pagina em desenvolvimento!!!</h1> </div> <?php include "php/footer.php" ?> <file_sep><?php include "php/header.php" ?> <!--Icicio--> <div class="container-fluid fundo"> <div class="container "> <div class="vertical-center-top"> <div class="col-md-8 abaixa-top " > <p class=" text-white text-center display-4 text-justify font-weight-bold fonte-roboto">O MUNDO CONHECE <br> SUA EMPRESA?</p> <h4 class="identy fonte-chilanka bg-trasn text-white thin fonte35"> O nรบmero de pessoas que navegam na internet cresce a cada dia que passa. Um novo mundo cheio de vantagens e facilidades foi descoberto. Informaรงรฃo, interatividade, relaรงรตes pessoais, negociaรงรตes, notรญcias, compras e outras necessidades do dia-a-dia ganharam um grande espaรงo na web.</h4><br> <h6 class="text-white bg-trasn float-right fonte-chilanka">"Wikipedia.org"</h6> <br><p><a class="btn btn-lg btn-outline-warning text-right" href="login.php">Iniciar </a></p> </div> </div> </div> </div> <!-- Example row of columns --> <div class="py-5 bg-light"> <div class="container"> <p class="display-3 text-center">Nossos serviรงos</p> <div class="row"> <!-- --> <div class="py-5 col-md-6"> <div class="row"> <div class="text-center col-4"><i class="d-block mx-auto fa fa-5x fas fa-at"></i></div> <div class="col-8"> <h5 class="mb-3 text-warning"><b>Desenvolvimento Front-end</b></h5> <p class="my-1">Somos especialistas em desenvolvimento front-end รฉ o nosso cabo chefe, criamos e desenvolvemos intefaces para que seus clientes tenham experiรชncias incrรญveis.</p> </div> </div> </div> <!-- --> <div class="py-5 col-md-6"> <div class="row"> <div class="text-center col-4"><i class="d-block mx-auto fa fa-5x fas fa-folder-open"></i></div> <div class="col-8"> <h5 class="mb-3 text-warning"><b>Desenvolvimento Back-end</b></h5> <p class="my-1">Trabalhamos seu sistema da hospedagem do seu site atรฉ o feedback do seu cliente apรณs, a negociaรงรฃo.</p> </div> </div> </div> </div> <!-- --> <div class="row"> <div class="py-5 col-md-6"> <div class="row"> <div class="text-center col-4"><i class="d-block mx-auto fa fa-5x fas fa-signal"></i></div> <div class="col-8"> <h5 class="mb-3 text-warning"><b>Sites Otimizados</b></h5> <p class="my-1">Utilizamos boas praticas de desenvolvimento para que seu site sempre esteja bem localizado nas buscas orgรขnicas. Mas tambรฉm trabalhamos com links patrocinados. </p> </div> </div> </div> <!-- --> <div class="py-5 col-md-6"> <div class="row"> <div class="text-center col-4"><i class="d-block mx-auto fa fa-5x fa-file-code"></i></div> <div class="col-8"> <h5 class="mb-3 text-warning"><b>Programaรงรฃo</b></h5> <p class="my-1">Atualmente trabalhamos o back-end com as seguintes linguagens: PHP,ย MySql,ย PhpMyadmin. Estamos iniciando com Asp e C#.</p> </div> </div> </div> </div> </div> </div> <?php include "php/footer.php" ?>
8d642f843864beeb9e11fd016b3094c31a2ffff5
[ "PHP" ]
4
PHP
diego90ribeiro/ribsites.com.br-v-alpha-1.0
a558c478eee304caff882fcbf576d514e87ca0fa
023232f7c14d6ca5495201ec7c660121ab23815c
refs/heads/master
<file_sep>package com.example.demo.dao; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.UUID; import org.springframework.stereotype.Repository; import com.example.demo.model.Person; @Repository("fakeDao") public class PersonDataAccessSErvice implements PersonDao { private static List<Person> DB = new ArrayList<Person>(); @Override public int insertPerson(UUID id, Person person) { DB.add(new Person(id, person.getName())); return 1; } @Override public List<Person> selectAllPeople() { return DB; } @Override public Optional<Person> getPersonById(UUID id) { return DB.stream() .filter(Person -> Person.getId().equals(id)).findFirst(); } @Override public int updatePerson(UUID id, Person update) { return getPersonById(id) .map(person ->{ int indexOfPersonToDelete = DB.indexOf(person); if(indexOfPersonToDelete>=0) { DB.set(indexOfPersonToDelete, new Person(id, update.getName())); return 1; } return 0; }).orElse(0); } @Override public int deletePersonByID(UUID id) { Optional<Person> personOptional=getPersonById(id); if(personOptional.isEmpty()) { return 0; } DB.remove(personOptional.get()); return 1; } }
db62effdd609ea66b0c2c81e22853ede57245e03
[ "Java" ]
1
Java
karanmmodi/SpringBoot-REST-API
058345ea22570d29f17e0a1ff6f636a832c31c9d
204590b6410a05c7a24a2c634c8fdc7414065b36
refs/heads/master
<repo_name>xxxmasmayxxx/reWrite-mvc3101<file_sep>/Framework/PdoTrait.php <?php namespace Framework; trait PdoTrait { private $pdo; public function setPdo(\PDO $pdo) { $this->pdo = $pdo; return $this; } }<file_sep>/Controller/BookController.php <?php namespace Controller; use Framework\Controller; use Framework\Request; class BookController extends Controller { public function indexAction(Request $request ) { return $this->render('index.phtml', [ 'books' => [1, 2, 3], // compact($books = [1, 2, 3], $authors = 'adcsa <PASSWORD>wedqs') 'authors' => 'adcsa <PASSWORD>' ]); } public function showAction(Request $request) { return $request->get('id'); } }<file_sep>/Controller/ExeptionController.php <?php namespace Controller; use Framework\Controller; class ExeptionController extends Controller { public function errorAction(string $errorMessage = null) { $errorMessage = str_replace('Exception:','',$errorMessage); // ัƒะฑะธั€ะฐะตะผ ัะปะพะฒะพ Exception $errorMessage = explode(' in ',$errorMessage); // ะดะตะปะธะผ ั‡ั‚ะพ ะพัั‚ะฒะปะพััŒ ะฟะพ ะทะฝะฐะบัƒ in $errorMessage = $errorMessage[0]; // ะพัั‚ะฐะฒะปัะตะผ ั‚ะพะปัŒะบะพ ั‚ัƒ ั‡ะฐัั‚ัŒ ัะพะพะฑั‰ะตะฝะธั ะบะพั‚ะพั€ะฐั ะฝัƒะถะฝะฐ if (stripos($errorMessage, 'action')) { // ะตัะปะธ ะฒ ัะพะพะฑั‰ะตะฝะธะธ ะตัั‚ัŒ action return $this->render('index.phtml', [ 'type' => '400', 'message' => 'Sorry problem with request', // ะฒั‹ะดะฐะตะผ ั‚ะฐะบัƒัŽ ะพัˆะธะฑะบัƒ 'errorMessage' => $errorMessage ]); } if (stripos($errorMessage, 'controller')) { // -||- controller return $this->render('index.phtml', [ 'type' => '400', 'message' => 'Sorry problem with request', 'errorMessage' => $errorMessage ]); } if (stripos($errorMessage, 'view')) { return $this->render('index.phtml', [ 'type' => '404', 'message' => 'Sorry problem with foundation', 'errorMessage' => $errorMessage ]); } else // ะฝะฐ ะฒััะบะธะน ัะปัƒั‡ะฐะน { return $this->render('index.phtml', [ 'type' => '500', 'message' => 'Sorry unknown problem ', 'errorMessage' => $errorMessage ]); } } } <file_sep>/Controller/DefaultController.php <?php namespace Controller; use Framework\Controller; use Framework\Request; class DefaultController extends Controller { public function indexAction(Request $request) { return $this->render('index.phtml'); } public function jsonAction(Request $request) { header('content-type: application/json'); return json_encode(['a'=>1, 'b'=>2]); } }<file_sep>/Framework/Logger.php <?php namespace Framework; class Logger { private $file = ''; private $message = ''; public function __construct(string $file) { $this->file = $file; if (!file_exists($file)) { $dir = pathinfo($file,PATHINFO_DIRNAME); if (!is_dir($dir)) { mkdir($dir, 0777, true); } file_put_contents($file, '', FILE_APPEND); return $this; } } public function log(string $message = '') { $this->message = (new \DateTime())->format('Y-m-d H:i:s') . ' : ' . $message; file_put_contents($this->file, $this->message . PHP_EOL, FILE_APPEND); return $this; } }<file_sep>/Framework/Controller.php <?php namespace Framework; use Model\Repository\FeedbackRepository; class Controller { protected $router; protected $feedbackRepository; protected $session; protected $logger; use PdoTrait; public function setRouter(Router $router) { $this->router = $router; return $this; } public function setFeedbackRepository(FeedbackRepository $feedbackRepository) { $this->feedbackRepository = $feedbackRepository; return $this; } public function setSession(Session $session) { $this->session = $session; return $this; } protected function render($view, array $assoc = []) { $class = get_class($this); // ัƒะทะฝะฐะตะผ ะบะปะฐัั ั ะฝะตะนะผัะฟะตะนัะพะผ $folderClass = strtolower(str_replace(['Controller', '\\'], '', $class)); // ัƒะฑะธั€ะฐะตะผ ะฝะตะนะผัะฟะตะนั ะธ ะฟะพะฝะธะถะฐะตะผ // ะทะฐะณะปะฐะฒะฝั‹ะต ะฑัƒะบะฒั‹ $path = VIEW_DIR . DS . $folderClass . DS . $view; // ัะบะปะตะธะฒะฐะตะผ ะฟัƒั‚ัŒ if (!file_exists($path)) // ะฟั€ะพะฒะตั€ะบะฐ ะฝะฐ ััƒั‰ะตัั‚ะฒะพะฒะฐะฝะธะต ะฒัŒัŽัˆะบะธ { throw new \Exception("{$path} - Path to view file not correct"); } $vars = extract($assoc); ob_start(); // ะฑัƒั„ะตั€ะธะทะฐั†ะธั ะฑะตะท ะบะพั‚ะพั€ะพะน require ะฒั‹ะปะตะทะตั‚ ะฒ ะฒะตั€ั…ัƒ layout require $path; $content = ob_get_clean(); ob_start(); // ะตั‰ะต ะพะดะฝะฐ ะฑัƒั„ะตั€ะตะทะฒั†ะธั ะดะปั ะพะบะพะฝั‡ะฐั‚ะตะปัŒะฝะพะน ะฒัŒัŽัˆะบะธ require VIEW_DIR . DS . 'layout.phtml'; return ob_get_clean(); // ะฒะพะทะฒั€ะฐั‚ ะธ ะทะฐะบั€ั‹ั‚ะธะต ะฑัƒั„ะตั€ะฐ } }<file_sep>/config/routes.php <?php return [ 'default' => [ 'controller' => 'DefaultController', 'action' => 'indexAction', 'pattern' => '/1/' ], 'json' => [ 'controller' => 'DefaultController', 'action' => 'jsonAction', 'pattern' => '/1/json' ], 'book_list' => [ 'controller' => 'BookController', 'action' => 'indexAction', 'pattern' => '/1/books' ], 'book_page' => [ 'controller' => 'BookController', 'action' => 'showAction', 'pattern' => '/1/books/{id}', 'parameters' => [ 'id' => '[0-9]+' ] ], 'feedback' => [ 'controller' => 'FeedbackController', 'action' => 'contactAction', 'pattern' => '/1/feedback' ] ];<file_sep>/web/index.php <?php //todo: think about implementation interface // fix exceptionController use Framework\Request; use Controller\ExeptionController; use Framework\Router; use Model\Repository\FeedbackRepository; use Framework\Session; use Framework\Logger; define('DS', DIRECTORY_SEPARATOR); define('ROOT_DIR', __DIR__ . DS . '..'); define('VIEW_DIR', ROOT_DIR . DS . 'View'); define('CONFIG_DIR', ROOT_DIR . DS . 'config'); define('LOG_FILE', ROOT_DIR . DS . 'log' . DS . 'log.txt'); spl_autoload_register(function ($className) //ะฐะฒั‚ะพะปะพะฐะดะธะฝะณ ั€ะฐะฑะพั‚ะฐะตั‚ ั‚ะพะปัŒะบะพ ะตัะปะธ ะฝะฐะทะฒะฐะฝะธะต ะฟะฐะบะธ ั ั„ะฐะนะปะพะผ // ะธ ะฝะตะนะผัะฟะตะนั ัะพะฒะฟะฐะดะฐัŽั‚ { require ROOT_DIR . DS . $className . '.php'; }); $logger = new Logger(LOG_FILE); $PDOPASS = ROOT_DIR . DS . "Security" . DS ."PdoPass.php"; // ะธะผั ั„ะฐะนะปะฐ ั ะฐะปัŒั‚ะตั€ ะฝะฐัั‚ั€ะพะนะบะฐะผะธ ะฟะพะดะบะปัŽั‡ะตะฝะธั ะบ ะฑะฐะทะต ะดะฐะฝะฝั‹ั… PDO if (file_exists($PDOPASS)) // ะตัะปะธ ะตัั‚ัŒ ัั‚ะพั€ะพะฝะฝะธะน ั„ะฐะนะป ั ะฝะฐัั‚ั€ะพะนะบะฐะผะธ ะฟะพะดะบะปัŽั‡ะตะฝะธั ะบ ะฑะฐะทะต ะดะฐะฝะฝั‹ั… ั‚ะพ ะธัะฟะพะปัŒะทัƒะตั‚ัั ะพะฝ { // ะฐ ะตัะปะธ ะตะณะพ ะฝะตั‚ ั‚ะพ ะฝะฐัั‚ั€ะพะนะบะธ ัƒัั‚ะฐะฝะฐะฒะปะธะฒะฐัŽั‚ัั ะทะดะตััŒ include_once $PDOPASS; $logger->log('PDOPASS file included'); }else{ $DSN = 'mysql:host=127.0.0.1;dbname=mvc1'; $USER = 'root'; $PASSWORD = <PASSWORD>; $logger->log('PDOPASS file NOT included'); } $pdo = new \PDO($DSN, $USER, $PASSWORD); $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); $routes = require CONFIG_DIR . DS .'routes.php'; $request = new Request($_GET, $_POST, $_SERVER); // ะพั‚ัั‹ะป ััƒะฟ.ะณะปะพะฑ.ะผะฐัั. ะฒ private ัะฒ-ะฒะฐ ะธ ะพะฑั€ะฐะฑะพั‚ะบะฐ if null $router = new Router($routes); // ัะพะทะดะฐะฝะธะต ั€ะพัƒั‚ะตั€ะฐ ะดะปั ะธัะฟะพะปัŒะทะพะฒะฐะฝะธั ะฟะตั€ะตะฐะดั€ะตัะฐั†ะธะธ ะฒ ะบะปะฐััะฐั… // (request ะธ router) ะฟั€ะพะฑั€ะฐัั‹ะฒะฐัŽั‚ัั ะฒ ะบะปะฐััั‹ ั€ะฐะทะฝั‹ะผะธ ัะฟะพัะพะฑะฐะผะธ, request ั‡ะตั€ะตะท ัะฒ-ะฒะฐ // ั„ัƒะฝะบั†ะธะธ ะฐ router ั‡ะตั€ะตะท ั€ะพะดะธั‚ะตะปัŒัะบะธะน ะบะปะฐัั ะฝะพ ะฒ ั€ะพะดะธั‚ะตะปัŒัะบะธะน ะฟะพะดะฐะตั‚ัั ั‚ะพะถะต ั‡ะตั€ะตะท ัะฒ-ะฒะพ // ั„ัƒะฝะบั†ะธะธ. ะญั‚ะพ dependency injection pattern. $session = (new Session())->start(); $logger->log('Session started'); $feedbackRepository = (new FeedbackRepository())->setPdo($pdo); //PDO ะดะปั ั„ะพั€ะผั‹ ัะตั‚ะธั‚ัั ะพั‚ะดะตะปัŒะฝะพ ะพั‚ ะบะพะฝั‚ั€ะพะปะปะตั€ะพะฒ try { $router->match($request); $controller = $router->getCurrentController(); // ะฟะพะปัƒั‡ะตะฝะธะต ะบะพะฝั‚ั€ะพะปะปะตั€ะฐ ั ะฟะพะผะพั‰ัŽ ัะฒ-ั‚ะฒ ะบะปะฐััะฐ $action = $router->getCurrentAction(); // -||- ัะบัˆะตะฝะฐ ; if (!file_exists(ROOT_DIR . DS . 'Controller' . DS . $controller . '.php')) // ะฟั€ะพะฒะตั€ะบะฐ ะฝะฐ ััƒั‰ะตัั‚ะฒะพะฒะฐะฝะธะต ั„ะฐะนะปะฐ + ั€ะฐััˆะธั€ะตะฝะธะต { throw new \Exception("{$controller} - not found"); } $controller = '\\Controller\\' . $controller; $controller = (new $controller()) // ะฒัะต ะฝัƒะถะฝั‹ะต ะธะฝัั‚ั€ัƒะผะตะฝั‚ั‹ ัะตั‚ัั‚ัั ะฒ ัะบะท. ะบะปะฐััะฐ ะบะพะฝั‚ั€ะพะปะปะตั€ะฐ ->setRouter($router) ->setPDO($pdo) ->setFeedbackRepository($feedbackRepository) ->setSession($session) ; if (!method_exists($controller, $action)) // ะฟั€ะพะฒะตั€ะบะฐ ะฝะฐ ััƒั‰ะตัั‚ะฒะพะฒะฐะฝะธะต ะผะตั‚ะพะดะฐ { throw new \Exception("{$action} - not found"); } $content = $controller->$action($request); // ะฟะตั€ะตะผะตะฝะฝะฐั ะดะปั ัะฑะพั€ะฐ ะธ ะฟะตั€ะตะดะฐั‡ะธ ะบะพะฝั‚ะตะฝั‚ะฐ } catch (\Exception $e){ // ะปะพะฒะธะผ ะฒัะต ะพัˆะธะฑะบะธ $ec = new ExeptionController(); // ั‡ะตั€ะตะท ัะฒะพะน ะบะพะฝั‚ั€ะพะปะปะตั€ ะฒั‹ะฒะพะดะธะผ ะธั… $ec = (new ExeptionController())->errorAction($e); $logger->log($e); } echo $content; // ะฒั‹ะบะปะฐะดั‹ะฒะฐะตะผ ั‡ั‚ะพ ัะพะฑั€ะฐะปะพััŒ
b814d61aed96612a83d78eed43587a449564ba34
[ "PHP" ]
8
PHP
xxxmasmayxxx/reWrite-mvc3101
da41e6bd3defb2839d695b35457248ab0d8df9cd
91c22d015b926f3251af91c0c31a51f4eb4bde37
refs/heads/master
<repo_name>qrealka/external_sort<file_sep>/FileSplitter.h #ifndef EXTERNAL_SORT_FILESPLITTER_H #define EXTERNAL_SORT_FILESPLITTER_H #include "FileWrapper.h" #include "SortedFile.h" #if defined(_MSC_VER) #include <cstdint> #endif #include <list> #include <functional> namespace external_sort { class FileSplitter { public: typedef std::list<SortedFile> SplitContainer; typedef SplitContainer::iterator SplitIterator; typedef std::function<void(SplitIterator, SplitIterator)> AfterSplitCallback; explicit FileSplitter(const char* inputFileName); void SplitImpl(const size_t splitSize); void Split(const size_t splitSize, AfterSplitCallback onAfterSplit); private: FileWrapper m_file; SplitContainer m_parts; }; } // external_sort #endif //EXTERNAL_SORT_FILESPLITTER_H <file_sep>/FileWrapper.cpp #include "FileWrapper.h" #include "ThrowError.h" #include <sys/types.h> #include <sys/stat.h> #if defined(_MSC_VER) #define stat64 _stat64 #define status_t _stat64 #define fseek64 _fseeki64 #elif defined(__MINGW32__) #define stat64 _stat64 #define status_t __stat64 #define fseek64 _fseeki64 #else #include <unistd.h> #define status_t stat64 #define fseek64 fseeko #endif namespace { const int64_t MaxFileSize = MAX_INPUT_FILE_SIZE * 1024LL * 1024LL * 1024LL; } //namespace namespace external_sort { FileWrapper::FileWrapper() : m_file(nullptr) , m_size(0) { m_file = std::tmpfile(); CHECK_CONTRACT(m_file, "Cannot create temporary file"); } FileWrapper::FileWrapper(const char *fileName, bool input) : m_file(nullptr) , m_size(0) { static_assert(MAX_INPUT_FILE_SIZE > 0, "File size limit cannot be zero"); CHECK_CONTRACT(fileName && fileName[0], "File name is empty"); m_file = std::fopen(fileName, input ? "rb" : "wb"); CHECK_CONTRACT(m_file, std::string("Cannot open file ") + fileName); if (input) { struct status_t fileStat; CHECK_CONTRACT(!stat64(fileName, &fileStat), std::string("Cannot get file size ") + fileName); m_size = fileStat.st_size; CHECK_CONTRACT(m_size > 0, std::string("Empty input file ") + fileName); CHECK_CONTRACT(MaxFileSize >= m_size, std::string("Too large file ") + fileName); } } FileWrapper::FileWrapper(FileWrapper&& tmp) : m_file(tmp.m_file) , m_size(tmp.m_size) { tmp.m_file = nullptr; tmp.m_size = 0; } FileWrapper::~FileWrapper() { Close(); } size_t FileWrapper::Read(int64_t offset, char* const chunk, size_t chunkSize) const { assert(chunk && chunkSize); assert(m_file); assert(offset >= 0); if (!fseek64(m_file, offset, SEEK_SET)) { const size_t bytes = std::fread(chunk, sizeof(char), chunkSize, m_file); if (bytes) return bytes; } CHECK_CONTRACT(std::feof(m_file), "Cannot read from file"); return 0; } void FileWrapper::Write(const RangeConstChar &range) const { assert(m_file); assert(!range.empty()); CHECK_CONTRACT(range.size() == std::fwrite(range.begin(), sizeof(char), range.size(), m_file), "Cannot write to file"); std::fputc('\n', m_file); } void FileWrapper::Close() { if (m_file) fclose(m_file); m_file = nullptr; } int64_t FileWrapper::GetFileSize() const { return m_size; } void FileWrapper::Rewind() const { rewind(m_file); } void FileWrapper::WriteNumbers(size_t numbers[], size_t count) const { assert(m_file); CHECK_CONTRACT(count == std::fwrite(numbers, sizeof(size_t), count, m_file), "Cannot write numbers to file"); } bool FileWrapper::ReadNumbers(size_t numbers[], size_t count) const { assert(m_file); return count == fread(numbers, sizeof(size_t), count, m_file); } FileWrapper::FileWrapper(const external_sort::FileWrapper &wrapper) { assert(false && "FileWrapper disable copy constructor"); } void FileWrapper::operator=(const external_sort::FileWrapper &wrapper) { assert(false && "FileWrapper disable assign operator"); } bool FileWrapper::IsEOF() const { return feof(m_file) != 0; } } // namespace <file_sep>/ThrowError.h #ifndef EXTERNAL_SORT_ERROR_HANDLING_H #define EXTERNAL_SORT_ERROR_HANDLING_H #include <exception> #include <stdexcept> #define CONCAT_DETAIL(x) #x #define CONCAT_IT(x) CONCAT_DETAIL(x) #define SOURCE_LOCATION __FILE__"(" CONCAT_IT(__LINE__) ") " // check 'condition' and throw exception if false #define CHECK_CONTRACT(condition, msg) \ if (false == (condition)) throw std::runtime_error(std::string(msg) + "\nSource location: " + SOURCE_LOCATION); #endif //EXTERNAL_SORT_ERROR_HANDLING_H <file_sep>/FileSplitter.cpp #include "FileSplitter.h" #include "ThrowError.h" #include "Range.h" #include <limits> namespace { #ifdef DEBUG_MERGE const size_t MaxStringLength = 256; #else const size_t MaxStringLength = MAX_STRING_SIZE * 1024; #endif const int64_t MaxMemoryAlloc = std::numeric_limits<int>::max(); const char* GetLines(const char* begin, const char* end, external_sort::RangeLines& lines){ assert(begin && end); assert(begin <= end); auto result = begin; lines.clear(); for (auto it = begin; it < end ;) { CHECK_CONTRACT(it - begin <= MaxStringLength, "Too big string!"); // CRLF windows hell if (*it == 13 || *it == 10) { // ignore empty lines ?? if (begin != it) { #ifdef DEBUG_MERGE assert((it - begin) == DEBUG_MERGE); #endif lines.emplace_back(begin, it); } // skip many CRLFs for (; (*it == 13 || *it == 10) && it < end; ++it); begin = result = it; } else { ++it; } } return result > end ? end : result; } } // namespace namespace external_sort { FileSplitter::FileSplitter(const char* inputFileName) : m_file(inputFileName, true) { static_assert(MAX_STRING_SIZE > 0, "Limit of string length cannot be zero"); } void FileSplitter::SplitImpl(const size_t splitSize) { std::vector<char> chunk(splitSize + MaxStringLength); // maximum size (in GB) of part of input file for sorting int64_t position = 0LL; m_parts.emplace_back(m_file, position); // create split RangeLines lines; lines.reserve(chunk.size() / sizeof(RangeConstChar)); for (const auto buffer = chunk.data();;) { const auto bufferLength = m_file.Read(position, buffer, splitSize); const char* chunkEnd = buffer + bufferLength; const char* bufferEnd = GetLines(buffer, chunkEnd, lines); assert(bufferEnd > chunk.data()); position += bufferLength; // EOF ? if (bufferLength < splitSize || position >= m_file.GetFileSize()) { // put last line to result if (bufferEnd != chunkEnd) lines.emplace_back(bufferEnd, chunkEnd); m_parts.back().SaveLines(lines); break; // split done } m_parts.back().SaveLines(lines); position -= chunkEnd - bufferEnd; m_parts.emplace_back(m_file, position); // new split } } void FileSplitter::Split(const size_t splitSize, AfterSplitCallback onAfterSplit) { CHECK_CONTRACT(splitSize > MaxStringLength, "too low split size specified"); CHECK_CONTRACT(splitSize < (MaxMemoryAlloc - MaxStringLength), "too high split size specified"); m_parts.clear(); if (m_file.GetFileSize()) { SplitImpl(splitSize); if (!m_parts.empty()) onAfterSplit(m_parts.begin(), m_parts.end()); } } } // external_sort <file_sep>/SortedFile.cpp #include "SortedFile.h" #include "ThrowError.h" namespace external_sort { SortedFile::SortedFile(const FileWrapper& file, int64_t offset) : m_tempFile() , m_linesCount(0) , m_inputFile(file) , m_startChunkPosition(offset) { } void SortedFile::SaveLines(RangeLines& lines) { if (lines.empty()) return; const auto fileBegin = lines.front().begin(); std::sort(lines.begin(), lines.end()); std::for_each(lines.begin(), lines.end(), [this, fileBegin](const RangeConstChar& line) { const size_t fileOffset = line.begin() - fileBegin; #ifdef DEBUG_MERGE assert(line.size() == DEBUG_MERGE); #endif size_t pair[] = {fileOffset, line.size()}; m_tempFile.WriteNumbers(pair, sizeof(pair)/sizeof(size_t)); }); m_linesCount = lines.size(); m_first.clear(); m_tempFile.Rewind(); } const CharBuffer& SortedFile::GetFirst() const { if (!m_linesCount) { m_first.clear(); return m_first; } if (m_first.size()) { #ifdef DEBUG_MERGE assert(m_first.size() == DEBUG_MERGE); #endif return m_first; } size_t filePosition[] = {0,0}; if (!m_tempFile.ReadNumbers(filePosition, sizeof(filePosition) / sizeof(size_t))) { assert(m_linesCount); m_first.clear(); return m_first; } const uint16_t lineSize = filePosition[1]; CHECK_CONTRACT(lineSize > 0, "Found empty line in chunk"); #ifdef DEBUG_MERGE assert(lineSize == DEBUG_MERGE); #endif m_first.resize(lineSize, 0); const size_t bytes = m_inputFile.Read(m_startChunkPosition + filePosition[0], m_first.data(), filePosition[1]); #ifdef DEBUG_MERGE assert(bytes == DEBUG_MERGE); #else assert(bytes); #endif if (bytes < m_first.size()) { m_first.erase(m_first.begin() + bytes, m_first.end()); } return m_first; } bool SortedFile::Pop() { m_first.clear(); --m_linesCount; if (!m_linesCount || GetFirst().empty() || m_tempFile.IsEOF()) { m_tempFile.Close(); return false; } return true; } } // external_sort<file_sep>/Range.h #ifndef EXTERNAL_SORT_RANGE_H #define EXTERNAL_SORT_RANGE_H #include <iterator> #include <algorithm> #include <vector> #include <assert.h> namespace external_sort { template<typename T> class Range { public: typedef Range<T> type; typedef typename std::iterator_traits<T>::value_type value_type; typedef typename std::iterator_traits<T>::difference_type difference_type; typedef std::size_t size_type; typedef typename std::iterator_traits<T>::reference reference; typedef T const_iterator; typedef T iterator; public: Range() : m_begin( iterator() ), m_end( iterator() ) { } template<class Iterator> Range(Iterator begin, Iterator end) : m_begin(begin), m_end(end) {} template<class Iterator> Range(const Range<Iterator> & r): m_begin(r.begin()), m_end(r.end()) { } type& operator = (const type& r) { m_begin = r.begin(); m_end = r.end(); return *this; } template<class Iterator> type& operator = (const Range<Iterator>& r) { m_begin = r.begin(); m_end = r.end(); return *this; } iterator begin() const { return m_begin; } iterator end() const { return m_end; } size_type size() const { return m_end - m_begin; } bool empty() const { return m_begin == m_end; } bool operator < ( const Range& r ) const { return std::lexicographical_compare(m_begin, m_end, r.m_begin, r.m_end ); } reference front() const { assert(!empty()); return *m_begin; } reference back() const { assert(!empty()); iterator last(m_end); return *(--last); } reference operator[](difference_type at) const { assert((at >= 0) && (at < (m_end - m_begin))); return m_begin[at]; } private: T m_begin; T m_end; }; template<class Iterator1T, class Iterator2T > inline bool operator < (const Range<Iterator1T>& l, const Range<Iterator2T>& r) { return std::lexicographical_compare(std::begin(l), std::end(l), std::begin(r), std::end(r)); } typedef std::vector<char> CharBuffer; typedef Range<const char*> RangeConstChar; typedef std::vector<RangeConstChar> RangeLines; } #endif //EXTERNAL_SORT_RANGE_H <file_sep>/FileMerger.h #ifndef EXTERNAL_SORT_FILEMERGER_H #define EXTERNAL_SORT_FILEMERGER_H #include "FileWrapper.h" #include <set> #include <iterator> namespace external_sort { template<typename Iterator> void MergeSortedTo(Iterator begin, Iterator end, FileWrapper& outFile) { typedef typename std::iterator_traits<Iterator>::pointer SortedFilePtr; outFile.Rewind(); struct Less { bool operator()(const SortedFilePtr l, const SortedFilePtr r) { return l->GetFirst() < r->GetFirst(); } }; std::multiset<SortedFilePtr, Less> splits; for (; begin != end; ++begin) { splits.insert(&*begin); } while (!splits.empty()) { const auto minimum = *splits.cbegin(); const auto& top = minimum->GetFirst(); outFile.Write(RangeConstChar(top.data(), top.data() + top.size())); splits.erase(splits.cbegin()); if (minimum->Pop() && !top.empty()) splits.insert(minimum); } outFile.Close(); } } #endif //EXTERNAL_SORT_FILEMERGER_H <file_sep>/main.cpp #include "FileSplitter.h" #include "FileMerger.h" #include <iostream> using namespace external_sort; int main(int argc, const char* argv[]) { if (argc < 3) { std::cout << "Not enough parameters. Example usage: external_sort file_for_sort.txt sorted.txt\n"; return -1; } try { FileSplitter splitter(argv[1]); FileWrapper outFile(argv[2], false); static_assert(MAX_SORTED_SIZE > 0, "Limit size of part of file can't be zero"); static_assert(MAX_SORTED_SIZE <= 1024, "Limit size of part of file too big"); #ifdef DEBUG_MERGE const auto partSize = 300; #else const auto partSize = MAX_SORTED_SIZE * 1024L * 1024L; #endif std::cout << "Start file " << argv[1] << " splitting...\n"; splitter.Split(partSize, [&outFile, &argv](FileSplitter::SplitIterator begin, FileSplitter::SplitIterator end) { std::cout << "Start merge files to destination " << argv[2] << std::endl; MergeSortedTo(begin, end, outFile); }); std::cout << "Finished\n"; return 0; } catch(const std::exception& error) { std::cout << "Error: " << error.what() << std::flush; return -1; } }<file_sep>/README.md # External Sort Simple implementation of external sort huge text file. String delimiter is CR or CRLF symbol # Compilers: * VisualStudio 2010+ * MinGW 3.2 (gcc 4.8.1) * Linux GCC 4.8.1+ # Build instructions 1. mkdir build && cd build 2. cmake .. or cmake -G"Visual Studio <version>" .. 3. use generated files # Debug hints You can debug this algo on small files too by using define DEBUG_MERGE. For example: 1. Generate a test file with lines of 6 characters long 2. Rebuild project with define 'DEBUG_MERGE=6' (make -DDEBUG_MERGE=6) 3. Start debug <file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 2.8) project(external_sort) # MAX_SORTED_SIZE - maximum size (in MB) of part of input file fol sorting # MAX_STRING_SIZE - maximum size (in KB) of strings # MAX_INPUT_FILE_SIZE - maximum input file size in GB if (NOT MSVC) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") add_definitions(-D_LARGEFILE64_SOURCE) add_definitions(-D_FILE_OFFSET_BITS=64) endif() # specify maximum input file size in GB if (NOT DEFINED MAX_INPUT_FILE_SIZE) add_definitions(-DMAX_INPUT_FILE_SIZE=200) else() add_definitions(-DMAX_INPUT_FILE_SIZE=${MAX_INPUT_FILE_SIZE}) endif() # specify maximum size part of input file in MB if (NOT DEFINED MAX_SORTED_SIZE) add_definitions(-DMAX_SORTED_SIZE=512) else() add_definitions(-DMAX_SORTED_SIZE=${MAX_SORTED_SIZE}) endif() # limit std:string size in KB if (NOT DEFINED MAX_STRING_SIZE) add_definitions(-DMAX_STRING_SIZE=512) else() add_definitions(-DMAX_STRING_SIZE=${MAX_STRING_SIZE}) endif() set(SOURCE_FILES main.cpp FileSplitter.cpp FileSplitter.h ThrowError.h Range.h FileWrapper.cpp FileWrapper.h FileMerger.h SortedFile.cpp SortedFile.h) add_executable(external_sort ${SOURCE_FILES})<file_sep>/SortedFile.h #ifndef EXTERNAL_SORT_FILEINDEX_H #define EXTERNAL_SORT_FILEINDEX_H #include "Range.h" #include "FileWrapper.h" #if defined(_MSC_VER) #include <cstdint> #endif namespace external_sort { class FileWrapper; class SortedFile { public: SortedFile(const FileWrapper& file, int64_t offset); void SaveLines(RangeLines& lines); const CharBuffer& GetFirst() const; bool Pop(); private: SortedFile(const SortedFile&); void operator=(const SortedFile&); private: FileWrapper m_tempFile; size_t m_linesCount; const FileWrapper& m_inputFile; int64_t m_startChunkPosition; mutable CharBuffer m_first; // cache read file operation }; } // external_sort #endif //EXTERNAL_SORT_FILEINDEX_H <file_sep>/FileWrapper.h #ifndef EXTERNAL_SORT_FILEWRAPPER_H #define EXTERNAL_SORT_FILEWRAPPER_H #if defined(__MINGW32__) #define __MSVCRT_VERSION__ 0x900 #elif defined(_MSC_VER) #include <cstdint> #endif #include <stdio.h> #include "Range.h" namespace external_sort { class FileWrapper { public: FileWrapper(); // temporary file FileWrapper(const char* fileName, bool input); FileWrapper(FileWrapper&& tmp); ~FileWrapper(); size_t Read(int64_t offset, char* const chunk, size_t chunkSize) const; void Write(const RangeConstChar& range) const; void Close(); int64_t GetFileSize() const; void Rewind() const; bool IsEOF() const; void WriteNumbers(size_t numbers[], size_t count) const; bool ReadNumbers(size_t numbers[], size_t count) const; private: FileWrapper(const FileWrapper&); void operator=(const FileWrapper&); private: std::FILE* m_file; int64_t m_size; }; } #endif //EXTERNAL_SORT_FILEWRAPPER_H
262e7a4ad66a9a0b40fca7152fe26baae45c7dbe
[ "Markdown", "CMake", "C++" ]
12
C++
qrealka/external_sort
2d9ccbe8290fb39a6d1b3b3a1f730a245dd95449
cbb02398a1d834cbbc6709863394c311d9485268
refs/heads/master
<file_sep>""" Subcontroller module for Alien Invaders This module contains the subcontroller to manage a single level or wave in the Alien Invaders game. Instances of Wave represent a single wave. Whenever you move to a new level, you are expected to make a new instance of the class. The subcontroller Wave manages the ship, the aliens and any laser bolts on screen. These are model objects. Their classes are defined in models.py. Most of your work on this assignment will be in either this module or models.py. Whether a helper method belongs in this module or models.py is often a complicated issue. If you do not know, ask on Piazza and we will answer. <NAME>(jb2297), <NAME>(yh383) 12/4/2018 """ from game2d import * from consts import * from models import * import random # PRIMARY RULE: Wave can only access attributes in models.py via getters/setters # Wave is NOT allowed to access anything in app.py (Subcontrollers are not permitted # to access anything in their parent. To see why, take CS 3152) class Wave(object): """ This class controls a single level or wave of Alien Invaders. This subcontroller has a reference to the ship, aliens, and any laser bolts on screen. It animates the laser bolts, removing any aliens as necessary. It also marches the aliens back and forth across the screen until they are all destroyed or they reach the defense line (at which point the player loses). When the wave is complete, you should create a NEW instance of Wave (in Invaders) if you want to make a new wave of aliens. If you want to pause the game, tell this controller to draw, but do not update. See subcontrollers.py from Lecture 24 for an example. This class will be similar to than one in how it interacts with the main class Invaders. #UPDATE ME LATER INSTANCE ATTRIBUTES: _ship: the player ship to control [Ship] _aliens: the 2d list of aliens in the wave [rectangular 2d list of Alien or None] _bolts: the laser bolts currently on screen [list of Bolt, possibly empty] _dline: the defensive line being protected [GPath] _lives: the number of lives left [int >= 0] _time: The amount of time since the last Alien "step" [number >= 0] As you can see, all of these attributes are hidden. You may find that you want to access an attribute in class Invaders. It is okay if you do, but you MAY NOT ACCESS THE ATTRIBUTES DIRECTLY. You must use a getter and/or setter for any attribute that you need to access in Invaders. Only add the getters and setters that you need for Invaders. You can keep everything else hidden. You may change any of the attributes above as you see fit. For example, may want to keep track of the score. You also might want some label objects to display the score and number of lives. If you make changes, please list the changes with the invariants. LIST MORE ATTRIBUTES (AND THEIR INVARIANTS) HERE IF NECESSARY _alienDirection: The direction where the wave of aliens moves. [either 'left' or 'right'] _stepRandom: int, the steps that the aliens take before they fire _steps: int, how many steps the aliens have taken since the last time they fired a bolt _generate: boolean, whether or not we should call _randomFire _score: int, the score that the player gets in this game _state: the current state the game should be in _fail: boolean, True if the ship has no more life or any alien dips below the defense line, False otherwise _allkilled: boolean, True if all aliens are killed _popSound: the sound when the ship fires a bolt _alienBlastSound: the sound when a alien is destroyed _shipBlastSound: the sound when teh ship is destroyed """ # GETTERS AND SETTERS (ONLY ADD IF YOU NEED THEM) def getScore(self): """ Return the score that the player gets in this game This getter method allow the access to the attribute score """ return self._score def getState(self): """ Returns the current state of the game. This getter method allow the access to the attribute state """ return self._state def setState(self,state): """ Assigns new state of the game This setter method is to protect the attribute and allow limited access to the attribute state Parameter state: The current state of the game Precondition: States are one of STATE_PAUSED, STATE_ACTIVE, STATE_NEWWAVE, STATE_COMPLETE, STATE_INACTIVE or STATE_CONTINUE """ self._state = state def getFail(self): """ Returns the current value of the attribute _fail. This getter method allow the access to the attribute _fail """ return self._fail def getAllKilled(self): """ Returns the current value of the attribute _allkilled. This getter method allow the access to the attribute _allkilled """ return self._allkilled def getLife(self): """ Returns the current value of the hidden attribute _lives. This getter method allow the access to the hidden attribute _lives """ return self._lives # INITIALIZER (standard form) TO CREATE SHIP AND ALIENS def __init__(self,speed,live,score): """ Initializes the wave Parameter speed: The speed the aliens are marching in the current game Precondition: speed is a float greater than 0 """ self._aliens = self._createAliens() self._ship = Ship(GAME_WIDTH/2,SHIP_BOTTOM,SHIP_WIDTH,SHIP_HEIGHT, 'ship.png') self._dline = GPath(points=[0,DEFENSE_LINE,GAME_WIDTH,DEFENSE_LINE], linewidth=LINEWIDTH,linecolor='black') self._time = 0 self._alienDirection = 'right' self._bolts=[] self._steps = 0 self._generate = True self._lives = live self._score = score self._state = STATE_ACTIVE self._fail= False self._allkilled = False self._speed = speed self._popSound = Sound('pop1.wav') self._alienBlastSound = Sound('blast1.wav') self._shipBlastSound = Sound('blast2.wav') # UPDATE METHOD TO MOVE THE SHIP, ALIENS, AND LASER BOLTS def update(self,direction,dt,game): """ Method to update ship, bolt, alien Parameter direction: direction of ship Precondition: direction is either left or right Parameter dt: The time in seconds since last update Precondition: dt is a number (int or float) Parameter game: the Invader object we are working with Precondition: game is an object of Invaders """ if self._generate: self._randomFire() self._generate = False self._moveShip(direction) self._alienTime(dt) self._createBolt(game) self._moveBolts() self._alienCollison() self._shipCollison() self._alienBelowDefense() self._alienGone() # DRAW METHOD TO DRAW THE SHIP, ALIENS, DEFENSIVE LINE AND BOLTS def draw(self,view): """ Draws the game objects to the view. Every single thing you want to draw in this game is a GObject. To draw a GObject g, simply use the method g.draw(self.view). It is that easy! Many of the GObjects (such as the ships, aliens, and bolts) are attributes in Wave. In order to draw them, you either need to add getters for these attributes or you need to add a draw method to class Wave. We suggest the latter. See the example subcontroller.py from class. """ # IMPLEMENT ME for i in self._aliens: if i is not None: for j in i: if j is not None: j.draw(view) if self._ship is not None: self._ship.draw(view) self._dline.draw(view) for x in self._bolts: x.draw(view) def _createAliens(self): """ Return a 2D list of aliens Assign the x, y position and source of each aliens, creates 2D list of aliens """ li=[] for k in range(ALIENS_IN_ROW): list = [] for i in range(ALIEN_ROWS): x=0 y=0 x=(k+1)*ALIEN_H_SEP+ALIEN_WIDTH*(k+1/2) y=GAME_HEIGHT-(ALIEN_CEILING+(ALIEN_ROWS-0.5-i)*ALIEN_HEIGHT+ (ALIEN_ROWS-1-i)*ALIEN_V_SEP) if i%6==0 or i%6==1: source = 'alien1.png' elif i%6==2 or i%6==3: source = 'alien2.png' elif i%6==4 or i%6==5: source = 'alien3.png' a=Alien(x,y,ALIEN_WIDTH,ALIEN_HEIGHT,source) list.append(a) li.append(list) return li def _randomFire(self): """ Pick a random number of steps between 0 and BOLT_RATE to make aliens fire randomly. Number of steps are numbers from 0 to BOLT_RATE(inclusive) """ self._stepRandom = random.randint(1,BOLT_RATE) def _moveShip(self,direction): """ Move the ship to either leeft or right by changing x and y coordinate of the ship Parameter direction: direction where ship is moving Precondition: direction is either left or right """ if direction == left: self._ship.x=max(self._ship.x-SHIP_MOVEMENT,SHIP_WIDTH/2) elif direction == right: self._ship.x=min(self._ship.x+SHIP_MOVEMENT,GAME_WIDTH-SHIP_WIDTH/2) def _createBolt(self,game): """ Create a bolt by specifying its x and y coordinate, width, height, fillcolor, linecolor and velocity Parameter game: the Invader object we are working with Precondition: game is an object of Invaders """ if self._fireBolts(game): if self._playerNoBolt(): x = self._ship.x y = self._ship.y+1/2*SHIP_HEIGHT a = Bolt(x=x,y=y,width=BOLT_WIDTH,height=BOLT_HEIGHT, fillcolor='black',linecolor='black',velocity=BOLT_SPEED) self._popSound.play() self._bolts.append(a) def _playerNoBolt(self): """ Return True if there's no player's bolt on the screen, False otherwise Method to make sure that only one bolt on the screen belongs to the player """ state = True for x in self._bolts: if x.isPlayerBolt(): state = False return state def _fireBolts(self,game): """ Return True if up key was pressed, False otherwise Method to determine whether or not the player has decided to fire a bolt Parameter game: the Invader object we are working with Precondition: game is an object of Invaders """ return game.input.is_key_down("up") def _moveBolts(self): """ Method to move all the bolts on the screen. If a bolt goes off screen, delete it from the _bolts list """ for b in self._bolts: if b.y > GAME_HEIGHT or b.y+BOLT_HEIGHT < 0: self._bolts.remove(b) else: b.y = b.y+b.getVelocity() def _alienTime(self,dt): """ Method to march the aliends across the screen. It determines when and which direction the aliens should be moving Parameter dt: The time in seconds since last update Precondition: dt is a number (int or float) """ self._time = self._time+dt if self._time > self._speed: self._time = 0 if self._alienDirection == 'right': alien = self._bottomRightAlien() if alien.x+1/2*ALIEN_WIDTH > GAME_WIDTH-ALIEN_H_SEP: self._alienDirection = 'left' self._shiftAlienDown() else: self._shiftAlienRight() elif self._alienDirection == 'left': alien = self._bottomLeftAlien() if alien.x-1/2*ALIEN_WIDTH < ALIEN_H_SEP: self._alienDirection = 'right' self._shiftAlienDown() else: self._shiftAlienLeft() def _bottomLeftAlien(self): """ Return the bottom left alien in the 2D _aliens list """ for i in self._aliens: if i is not None: for alien in i: if alien is not None: return alien def _bottomRightAlien(self): """ Return the bottom right alien in the 2D _aliens list """ for i in reversed(self._aliens): if i is not None: for alien in i: if alien is not None: return alien def _shiftAlienRight(self): """ Move the aliens to the right by increment ALIEN_H_WALK """ self._steps = self._steps+1 self._alienFire() for i in self._aliens: if i is not None: for j in i: if j is not None: j.x = j.x+ ALIEN_H_WALK def _shiftAlienLeft(self): """ Move the aliens to the left by decrement ALIEN_H_WALK """ self._steps = self._steps+1 self._alienFire() for i in self._aliens: if i is not None: for j in i: if j is not None: j.x = j.x- ALIEN_H_WALK def _shiftAlienDown(self): """ Move the aliens down by decrement ALIEN_V_WALK """ self._steps = self._steps+1 self._alienFire() for i in self._aliens: if i is not None: for j in i: if j is not None: j.y = j.y- ALIEN_V_WALK def _alienFire(self): """ Method to determine when to fire bolts from alien Reset attribute steps to 0 everytime an alien fires """ if self._steps==self._stepRandom: self._steps = 0 self._createAlienBolt() def _createAlienBolt(self): """ Method to create a bolt fired by an alien and append it to the _bolts list Change the _generate attribute to True so now it can randomly generate the next bolt """ a = self._whichAlien() x = a.x y = a.y-1/2*ALIEN_HEIGHT b= Bolt(x=x,y=y,width=BOLT_WIDTH,height=BOLT_HEIGHT,fillcolor='black', linecolor='black',velocity=-BOLT_SPEED) self._bolts.append(b) self._generate = True def _whichAlien(self): """ Method to randomly pick an alien to fire Return the alien that's at the bottom of the column that we randomly picked Add check function so when everything's none, game's over """ empty = True while empty: c = random.randint(1,ALIENS_IN_ROW)-1 if self._aliens[c] is not None: for x in range(ALIEN_ROWS): if self._aliens[c][x] is not None: empty = False return self._aliens[c][x] def _alienCollison(self): """ Method to deal with alien-bolt collisions If an alien collides with a bolt taht's fired from the ship, change the position of that alien to None and remove the bolt after the collision """ for bolt in self._bolts: for i in range(len(self._aliens)): if self._aliens[i] is not None: for j in range(len(self._aliens[i])): if self._aliens[i][j] is not None: if self._aliens[i][j].collides(bolt): self._bolts.remove(bolt) self._alienBlastSound.play() self._aliens[i][j] = None self._score = self._score+self.score_determine(j) def score_determine(self,j): """ Return the number of points the player gets for destorying this alien Method to determine how many points this line of aliens are worth The first two lines of aliens are worth 10 points, the thrid and fourth line of aliens are worth 20......Every two lines the number of points awarded increases by 10 points Parameter j: the line that this alien is in Precondition: j is an int >= 0 """ division = j//2 score = division*10+10 return score def _shipCollison(self): """ Method to deal with ship-bolt collisions If the ship collides with a bolt that's fired from an alien, but the ship has more than 1 live, decrease the number of lives the ship has and change the state to paused, otherwise change the attribute _ship to None and set attribute _fail to True """ for bolt in self._bolts: if self._ship is not None: if self._ship.collides(bolt): self._bolts.remove(bolt) self._shipBlastSound.play() if self._lives > 1: self._lives = self._lives-1 self._state = STATE_PAUSED else: self._ship = None self._fail = True def _alienBelowDefense(self): """ Method to determine whether or not the aliens are under the defense line If alien goes below defense line, set attribute _fail to True and player loses the game """ for i in self._aliens: if i is not None: for j in i: if j is not None: if j.y-1/2*ALIEN_HEIGHT < DEFENSE_LINE: self._fail = True def _alienGone(self): """ Method to determine whether or not all the aliens are killed If all aliens are killed, set attribute _allkilled to True and player wins the game """ a = True for i in self._aliens: if i is not None: for j in i: if j is not None: a = False self._allkilled = a # HELPER METHODS FOR COLLISION DETECTION
10ec82902397ab2c6e3e491c793494a6e7fa0f55
[ "Python" ]
1
Python
yuyihe/Alien-Invader
a1e45dc780ec3b15bc89d5209ed9023a55ee1d95
9a8aa9757c7610d7f9f312bbe3fa1fca3c85d911
refs/heads/master
<repo_name>PCMACHero/glomar<file_sep>/src/components/checkout/checkout.js import React from 'react' import {Route} from 'react-router-dom' import SmartPaymentButtons, {PayPalSDKWrapper} from 'react-smart-payment-buttons'; import IconButton from '@material-ui/core/IconButton'; import RemoveIcon from '@material-ui/icons/Delete'; import TextField from '@material-ui/core/TextField'; import './checkout.css' export default class Checkout extends React.Component{ state={ items:[], orderItems:[], batDivs:[], code:"", codeEntered: null, codeApplied: null, batCount:null, codeLabel:"Enter a Promo Code", totalPrice:0, discount:0, batCount:0, grandTotal: 0, batTotal:0, message:"" } colorConvert = { "Unfinished": "unfinished", "Red Mahogany":"mahogany", "Black":"black", "Charcoal": "charcoal", "Forest Green": "forest-green", "Navy Blue":"navy-blue", "Royal Blue":"royal-blue", "White Stain":"white-stain" } makeBreakDown=(quantity,discount)=>{ let batTotal = quantity * 95 let shipping = quantity>1?0:15 let discounts = this.state.codeApplied?discount:0 let grandTotal = batTotal + shipping - discounts this.setState({ batTotal: batTotal, grandTotal: grandTotal }) } makeCart=(arr)=>{ console.log("my bat arr", arr) let divArr = [] let orderItems = [] this.props.bats.forEach((element, i)=> { console.log("this",element.model) orderItems.push( { name: `${element.color},${element.wood}, ${element.size}", "${element.engraving?element.engraving:""}"`, description: `${element.color},${element.wood}, ${element.size}", "${element.engraving?element.engraving:""}"`, sku: element.model, unit_amount: { currency_code: "USD", value: "95.00" }, quantity: element.quantity } ) divArr.push(<div className="checkout-item" key={i}> <div className="checkout-item-remove"> <IconButton aria-label="Remove" onClick={()=>{ this.props.removeItem(i) }}> <RemoveIcon style={{color:"white"}} /> </IconButton> </div> <div className={`checkout-item-color-box`}> <div className={`checkout-item-color ${this.colorConvert[element.color]}`}></div> </div> <div className="checkout-item-model">{(element.model).toUpperCase()}</div> <div className="checkout-item-size">{element.size}"</div> <div className="checkout-item-quantity">Qty {element.quantity}</div> </div>) }); this.setState({ batDivs:divArr, orderItems:orderItems }) } handleCodeChange=(e)=>{ this.setState({ code: e.target.value.toUpperCase() },()=>{ if(this.state.code==="3PACKDEAL"){ this.setState({ codeEntered:true },()=>{ this.checkIfDiscountShouldApply() }) console.log("tried") if(this.state.discount===0){ this.props.openSnack("warning","Must buy at least 3 bats for deal.",5000) }else{ this.props.openSnack("success","Code added. Saved $"+this.state.discount+ ".",5000) } } }) } checkIfDiscountShouldApply=()=>{ if(this.state.code==="3PACKDEAL" && this.props.quantity>2){ this.setState({ codeApplied:true },()=>{ this.makeBreakDown(this.props.quantity, this.state.discount) }) console.log("triples", this.props.quantity%3) }else{ this.props.openSnack("warning","Code Only Valid with 3 or More Bats",5000) } } componentDidUpdate(prev,prevS){ console.log("prevProps",prev.bats.length) console.log("props",this.props.bats.length) console.log("prevState",prevS) console.log("state",this.state) if(this.state.batCount !== this.props.bats.length){ console.log("bats changed", this.props.bats) this.makeCart(this.props.bats) let batCount = this.props.quantity let discountTimes = ~~(this.props.quantity / 3) console.log("bitwise", discountTimes) this.setState({ batCount:this.props.bats.length, totalPrice: batCount * 95, discount: discountTimes * 55 },()=>{ this.makeBreakDown(this.props.quantity, (discountTimes * 55)) }) } } componentDidMount(){ this.makeCart(this.props.bats) let batCount = 0 let discountTimes = ~~(this.props.quantity / 3) this.setState({ batCount:this.props.quantity, totalPrice: this.props.quantity * 95, discount: discountTimes * 55 },()=>{ this.makeBreakDown(this.props.quantity, this.state.discount) }) } render(){ console.log("RENDERED CHECKOUT") console.log("state bat count", this.state.batCount) console.log("discount", this.state.discount) console.log("totalBat", this.state.batTotal) console.log("discount", this.state.discount) return ( <div className="center"> <h1 className="title">CHECKOUT</h1> <div className="checkout-items"> <div style={{fontSize:'1.5em',color:"white", display:this.state.batDivs.length===0?"":"none"}}>(YOUR CART IS EMPTY)</div> {this.state.batDivs} </div> <div className={this.state.message?"blur code":"code"}> <TextField onFocus={()=>{this.setState({codeLabel:""})}} onBlur={()=>{this.setState({codeLabel:this.state.code===""?"Enter a Promo Code":""})}} disabled={this.state.codeApplied?true:false} style={{borderColor:"white"}} label={this.state.codeLabel} variant="outlined" id="mui-theme-provider-outlined-input" onChange={(e)=>{this.handleCodeChange(e)}} value={this.state.codeApplied?"Promo Code Applied!": this.state.code} inputProps={{ maxLength: 20}} color="primary" InputLabelProps={{ shrink: false, }} /> </div> <div className="breakdown-box" style={{display:this.props.quantity>0?"":"none"}}> <div className="breakdown total-price">{this.props.quantity} Bats: ${this.props.quantity * 95}</div> <div className="breakdown total-price" style={{color:this.props.quantity>1 || this.props.quantity===0?"limegreen":"", display:this.props.quantity<1?"none":""}}>{this.props.quantity>1?"Free Shipping":`Shipping: $15 (free with 2 or more)`}</div> {/* <div className="total-price margin">TOTAL ${this.state.codeApplied? this.state.totalPrice - this.state.discount: this.state.totalPrice}</div> */} <div style={{display:this.state.codeApplied?'':"none", color:"limegreen"}} className="total-price margin">{this.state.codeApplied? `Saved $${this.state.discount}`: ""}</div> <div className="total-price margin">TOTAL ${this.state.grandTotal}</div> </div> {/* <div id="paypal-button-container"></div> */} <div style={{width:"300px", display:this.props.quantity===0?"none":""}} className={this.state.message?"blur":""}> <PayPalSDKWrapper // clientId="<KEY>" // Sandbox clientId="<KEY>" // Glomar Sandbox // clientId="<KEY>" // Live Glomar // disableFunding={['card', 'sepa','credit']} > <SmartPaymentButtons createOrder={(d,a)=>{ return a.order.create({ purchase_units: [ { reference_id: "PUHF", description: "Some description", custom_id: "Something7364", soft_descriptor: "Glomar Pro Bats", amount: { currency_code: "USD", value: `${this.state.batTotal-(this.state.codeApplied?this.state.discount:0) + (this.props.quantity>1 || this.props.quantity===0?0:15)}`, breakdown: { shipping: { currency_code: "USD", value: (15), }, shipping_discount: { currency_code: "USD", value: this.props.quantity>1 || this.props.quantity===0?15:0, }, item_total: { currency_code: "USD", value: `${this.state.batTotal}`, }, discount:{ currency_code:"USD", value:this.state.codeApplied?this.state.discount:0 } } }, items: this.state.orderItems, } ] }); }} onApprove={(data, actions)=>{ return actions.order.capture().then((details)=> { // Show a success message to the buyer let status = "no status" let id = 0 let name = "Customer" let message = "" if(details.payer.name.given_name){ name = details.payer.name.given_name } if(details.id){ id = details.id } if(details.status){ status = details.status } if(status==="COMPLETED"){ message = `Thank you ${name}, the transaction is complete!` }else{ message = `Transaction status: ${status}` } this.props.emptyCart() this.setState({ message:message }) }); }} /> </PayPalSDKWrapper> </div> <div className={this.state.message?"animated fadeIn message":""} style={{display:this.state.message?"":"none"}}>{this.state.message}</div> </div> ) } }<file_sep>/src/components/inputfield.js import React from 'react'; import InputAdornment from '@material-ui/core/InputAdornment'; import TextField from '@material-ui/core/TextField'; import Fab from '@material-ui/core/Fab'; import AddIcon from '@material-ui/icons/Add'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import RemoveIcon from '@material-ui/icons/Remove'; import FloatingActionButton from './floatingbtn'; class InputField extends React.Component{ state={ } handleChange=(e)=>{ this.setState({ engraving: e.target.value }) } handleChangeQuant=(e)=>{ this.setState({ quantity: e.target.value }) } render(){ return ( <div className="input-fields"> <div className="quantity-row"> <TextField id="standard-number" value={this.props.quantity} type="number" InputProps={{ startAdornment: <InputAdornment position="start">Quantity</InputAdornment>, readOnly: true, }} style={{ // marginLeft: theme.spacing.unit, // marginRight: theme.spacing.unit, width: 100, }} margin="normal" /> <FloatingActionButton color="primary" icon={<RemoveIcon/>} label="Remove" onClick={()=>{ console.log("clicked") if(this.props.quantity<1){ return } this.props.update((this.props.quantity - 1))}} /> <FloatingActionButton onClick={()=>{ console.log("clicked") this.props.update((this.props.quantity + 1))}} color="secondary" icon={<AddIcon/>} label="Add"/> </div> </div> ); } } export default InputField;<file_sep>/src/components/footer/footer.js import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import AppBar from '@material-ui/core/AppBar'; import Toolbar from '@material-ui/core/Toolbar'; import Typography from '@material-ui/core/Typography'; import { Button, IconButton } from '@material-ui/core'; import Call from '@material-ui/icons/Call'; import Email from '@material-ui/icons/Email'; const useStyles = makeStyles(theme => ({ text: { padding: theme.spacing(2, 2, 0), }, paper: { paddingBottom: 50, }, list: { marginBottom: theme.spacing(2), }, subheader: { backgroundColor: theme.palette.background.paper, }, appBar: { top: 'auto', bottom: 0, }, grow: { flexGrow: 1, }, fabButton: { position: 'absolute', zIndex: 1, top: -30, left: 0, right: 0, margin: '0 auto', }, })); function Footer() { const classes = useStyles(); return ( <div className={classes.root}> <AppBar position="fixed" color="default" elevation={3} className={classes.appBar}> <Toolbar> <Typography variant="h6" color="initial"> Glomar Pro Bats 2019ยฉ </Typography> <IconButton> <a href="mailto:<EMAIL>"><Email color="primary"/></a> </IconButton> <IconButton> <a href="tel:1-408-555-5555"><Call color="primary"/></a> </IconButton> </Toolbar> </AppBar> </div> ); } export default Footer;<file_sep>/src/components/carousel.js import React, { Component } from 'react'; import "react-responsive-carousel/lib/styles/carousel.min.css"; import { Carousel } from 'react-responsive-carousel'; export default class MyCarousel extends Component { render() { return ( <Carousel autoPlay={true} width={"100%"} infiniteLoop={true} showStatus={false} showArrows={false} showThumbs={false} showIndicators={false}> <div> <img src={require("./images/carousel/tes1.jpg")} /> {/* <p className="legend"><NAME></p> */} </div> <div> <img src={require("./images/carousel/tes3.jpg")} /> {/* <p className="legend"><NAME></p> */} </div> <div> <img src={require("./images/carousel/tes4.jpg")} /> {/* <p className="legend">Legend 3</p> */} </div> <div> <img src={require("./images/carousel/tes5.jpg")} /> {/* <p className="legend">Legend 3</p> */} </div> <div> <img src={require("./images/carousel/tes6.jpg")} /> {/* <p className="legend"><NAME></p> */} </div> <div> <img src={require("./images/carousel/tes7.gif")} /> {/* <p className="legend">Legend 3</p> */} </div> <div> <img src={require("./images/carousel/tes8.jpg")} /> {/* <p className="legend"><NAME></p> */} </div> <div> <img src={require("./images/carousel/Tim-Salmon-Glomar-Bat.jpg")} /> {/* <p className="legend"><NAME></p> */} </div> </Carousel> ); } }<file_sep>/src/components/shopselection.js import React from 'react' import CustomizedSnackbars from './snackbar'; import { Button } from '@material-ui/core'; export default class ShopSelection extends React.Component{ state={ } render(){ return ( <div className={this.props.show?`shop-selection animated ${this.props.firstOpen?"slideInLeft":"slideInLeft"} fast`:"shop-selection animated slideOutRight fast"} // style={{display:this.props.show?"flex":"none"}} > <div className="block"> <Button variant="contained" color="primary" // className={classes.margin} onClick={()=>this.props.openSnack("info","3 bats for $230. Use code 3PACKDEAL",5000)} > Deals </Button> </div> <div className="shop-item" style={{backgroundImage:`url(${this.props.models["G243 Pro Model"].image[0]})`, backgroundSize:"cover"}} onClick={()=>{this.props.onClick("G243 Pro Model")}}> <div className="shop-item-image" ></div> <div className="shop-item-text">G243 Pro Model</div> </div> <div className="shop-item" style={{backgroundImage:`url(${this.props.models["GSoftball Pro Model"].image[0]})`, backgroundSize:"cover"}} onClick={()=>{this.props.onClick("GSoftball Pro Model")}}> <div className="shop-item-text">GSoftball Pro Model</div> </div> <div className="shop-item" style={{backgroundImage:`url(${this.props.models["G271 Pro Model"].image[0]})`, backgroundSize:"cover"}} onClick={()=>{this.props.onClick("G271 Pro Model")}}> <div className="shop-item-text">G271 Pro Model</div> </div> <div className="shop-item" style={{backgroundImage:`url(${this.props.models["G271 Pro YOUTH BAT"].image[0]})`, backgroundSize:"cover"}} onClick={()=>{this.props.onClick("G271 Pro YOUTH BAT")}}> <div className="shop-item-text">G271 Pro YOUTH BAT</div> </div> <div className="shop-item" style={{backgroundImage:`url(${this.props.models["G110 Pro Model"].image[0]})`, backgroundSize:"cover"}} onClick={()=>{this.props.onClick("G110 Pro Model")}}> <div className="shop-item-text">G110 Pro Model</div> </div> <div className="shop-item" style={{backgroundImage:`url(${this.props.models["G13 Pro Model"].image[0]})`, backgroundSize:"cover"}} onClick={()=>{this.props.onClick("G13 Pro Model")}}> <div className="shop-item-text">G13 Pro Model</div> </div> <div className="shop-item" style={{backgroundImage:`url(${this.props.models["G141 Pro Model"].image[0]})`, backgroundSize:"cover"}} onClick={()=>{this.props.onClick("G141 Pro Model")}}> <div className="shop-item-text">G141 Pro Model</div> </div> <div className="shop-item" style={{backgroundImage:`url(${this.props.models["G161 Pro Model"].image[0]})`, backgroundSize:"cover"}} onClick={()=>{this.props.onClick("G161 Pro Model")}}> <div className="shop-item-text">G161 Pro Model</div> </div> </div> ) } }<file_sep>/src/App.js import 'intersection-observer' import React from 'react'; import 'animate.css' import "../node_modules/video-react/dist/video-react.css"; import {HashRouter, Route} from 'react-router-dom' import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles'; import Button from '@material-ui/core/Button'; import AppBar from '@material-ui/core/AppBar'; import Toolbar from '@material-ui/core/Toolbar'; import Typography from '@material-ui/core/Typography'; import IconButton from '@material-ui/core/IconButton'; import MenuIcon from '@material-ui/icons/Menu'; import Nav from './components/navbar' import './App.css'; import blueGrey from '@material-ui/core/colors/blueGrey' import orange from '@material-ui/core/colors/orange'; import teal from '@material-ui/core/colors/teal'; import cyan from '@material-ui/core/colors/cyan'; import blue from '@material-ui/core/colors/blue'; import red from '@material-ui/core/colors/red'; import pink from '@material-ui/core/colors/pink'; import HomePage from './components/homepage/homepage'; import { indigo } from '@material-ui/core/colors'; import Shop from './components/shop/shop'; import './mobile.css' import Footer from './components/footer/footer'; import CustomizedSnackbars from './components/snackbar'; import Checkout from './components/checkout/checkout'; import About from './components/about/about'; class App extends React.Component{ state={ cart:{ quantity:0, bats:[] }, drawer:true, snackMessage:"thisworks", //success error info warning snackVariant:"success", snackTime:3000, snackOpen:false } closeSnack=()=>{ this.setState({ snackOpen:false }) } openSnack=(variant, message, time=2000)=>{ this.setState({ snackVariant:variant, snackMessage: message, snackOpen:true, snackTime:time }) } updateCart=(quantity,bat)=>{ if(!quantity){ return } console.log("Bat Added to cart", bat) let tempBats = this.state.cart.bats // for(let i = 0; i<quantity; i++){ tempBats.push(bat) // } let totalQuantity= null tempBats.forEach((e,i)=>{ totalQuantity += e.quantity }) this.setState({ cart:{ quantity: totalQuantity, bats: tempBats } },()=>{ localStorage.setItem("cart", JSON.stringify(this.state.cart)) }) } removeItem=(index)=>{ console.log("ran remove") let tempBats = this.state.cart.bats let totalQuantity= null tempBats.splice(index,1) tempBats.forEach((e,i)=>{ totalQuantity += e.quantity }) this.setState({ cart:{ quantity:totalQuantity, bats:tempBats } },()=>{ localStorage.setItem("cart", JSON.stringify(this.state.cart)) }) } emptyCart=()=>{ this.setState({ cart:{ quantity:0, bats:[] } },()=>{ localStorage.removeItem("cart") }) } openDrawer=()=>{ this.setState({drawer:true}) } componentDidMount(){console.log(this.state.cart.bats) if(localStorage.getItem("cart")){ let cart = localStorage.getItem("cart") this.setState({ cart:JSON.parse(cart) },()=>{ console.log("Cart quantity", this.state.cart.quantity) }) } } render(){ return ( <HashRouter basename='/'> <MuiThemeProvider theme={theme}> <div className="App"> <Nav cartAmount={this.state.cart.quantity} removeItem={this.removeItem} emptyCart={()=>this.emptyCart()} bats={this.state.cart.bats?this.state.cart.bats:""} openDrawer={()=>this.openDrawer()} drawer={true}/> <div className="nav-buffer" style={{height:"56px",width:"100%"}}></div> <CustomizedSnackbars message={this.state.snackMessage} variant={this.state.snackVariant} time={this.state.snackTime} close={this.closeSnack} open={this.openSnack} isOpen={this.state.snackOpen}/> <Route path="/" exact component={HomePage}/> <Route path="/shop" render={(props) => <Shop updateCart={this.updateCart} openSnack={this.openSnack} {...props} />}/> <Route path="/checkout" exact render={(props)=> <Checkout bats={this.state.cart.bats} removeItem={this.removeItem} updateCart={this.updateCart} openSnack={this.openSnack} quantity={this.state.cart.quantity} emptyCart={this.emptyCart} {...props}/>}/> <Route path="/about" exact component={About}/> <div className="nav-buffer" style={{height:"64px",width:"100%"}}></div> <Footer/> </div> </MuiThemeProvider> </HashRouter> ); } } export default App; const theme = createMuiTheme({ palette: { primary: indigo, secondary: pink, error: red, dark: blueGrey, // Used by `getContrastText()` to maximize the contrast between the background and // the text. contrastThreshold: 3, // Used to shift a color's luminance by approximately // two indexes within its tonal palette. // E.g., shift from Red 500 to Red 300 or Red 700. tonalOffset: 0.2, }, });
9131eec2da201c6a1b861172759f85b719af57f6
[ "JavaScript" ]
6
JavaScript
PCMACHero/glomar
937e59669f3da0ec3ddec8dc62ac2ac313cc10a7
6609cf253a26bd9d8849d6ace6b6070e4bf1105c
refs/heads/master
<repo_name>sorrowless/ansible_deploy<file_sep>/roles/dotcommon/files/battshow #!/bin/bash ret="$(acpi 2>/dev/null)" if [ -z "$ret" ]; then exit 0 fi percent="$(echo $ret | awk '{ print $4}' | awk -F',' '{ print $1 }')" tm="$(echo $ret | awk '{print $5}' | awk -F ":" '{print $1":"$2}')" if echo $ret | grep -q "Discharging" then echo "โ–พ$percent/$tm" elif echo $ret | grep -q "Full" then echo "โ–ด$percent" else echo "โ–ด$percent/$tm" fi <file_sep>/roles/zsh/files/.zshrc # Cautiously export 'vim' as an editor - it will immediately break ^R and so on # keybindings in some cases. export EDITOR="vim" # Use zgen (https://github.com/tarjoilija/zgen.git) to manage plugins for zsh. # We try to automatically download it if it doesn't exists and also will auto # apply it for current shell # # Export needed variables ZGEN_GHUB='https://github.com/tarjoilija/zgen.git' ZGEN_HOME="${HOME}/.zgen" ZGEN_FILE="${ZGEN_HOME}/zgen.zsh" RC=1 # # Check if zgen directory exists, if not - install zgen if [ ! -d "${ZGEN_HOME}" ]; then echo "zgen plugins manager directory ${ZGEN_HOME} not found, try to install zgen" type git 1>/dev/null 2>&1 RC=$? if [ "$RC" -ne 0 ]; then echo "cannot find git, skip installing zgen" else git clone ${ZGEN_GHUB} ${ZGEN_HOME} RC=$? if [ "$RC" -ne 0 ]; then echo "cannot clone zgen repository from ${ZGEN_GHUB}, skip installing zgen" fi fi else RC=0 fi if [ -f "${ZGEN_FILE}" ] && [ "$RC" -eq 0 ]; then # # Load zgen source "${HOME}/.zgen/zgen.zsh" # If the init scipt doesn't exist if ! zgen saved; then # Plugins list here zgen load marzocchi/zsh-notify zgen load zsh-users/zsh-syntax-highlighting zgen load supercrabtree/k # Generate the init script from plugins above zgen save fi # Settings for zsh-notify plugin zstyle ':notify:*' error-title Error zstyle ':notify:*' success-title Success zstyle ':notify:*' command-complete-timeout 5 # End settings for zsh-notify plugin else echo "zgen plugins manager main file ${ZGEN_FILE} doesn't exists, skip plugins initialization" fi # End zgen plugins manager initialization autoload zkbd [[ ! -d ~/.zkbd ]] && mkdir ~/.zkbd if [[ ! -f ~/.zkbd/$TERM-${${DISPLAY:t}:-$VENDOR-$OSTYPE} ]]; then zkbd else source ~/.zkbd/$TERM-${${DISPLAY:t}:-$VENDOR-$OSTYPE} #setup key accordingly [[ -n "${key[Home]}" ]] && bindkey "${key[Home]}" beginning-of-line [[ -n "${key[End]}" ]] && bindkey "${key[End]}" end-of-line [[ -n "${key[Insert]}" ]] && bindkey "${key[Insert]}" overwrite-mode [[ -n "${key[Delete]}" ]] && bindkey "${key[Delete]}" delete-char [[ -n "${key[Up]}" ]] && bindkey "${key[Up]}" up-line-or-history [[ -n "${key[Down]}" ]] && bindkey "${key[Down]}" down-line-or-history [[ -n "${key[Left]}" ]] && bindkey "${key[Left]}" backward-char [[ -n "${key[Right]}" ]] && bindkey "${key[Right]}" forward-char fi # History options export HISTSIZE=10000 export HISTFILE="$HOME/.history" export SAVEHIST=$HISTSIZE setopt inc_append_history setopt hist_ignore_dups setopt hist_ignore_space setopt noflowcontrol # if you will not set promptsubst then your prompt will be computed only one time # when it will be set first time setopt promptsubst autoload -Uz compinit compinit # Actually, I hate default zsh autoselect, so - no select zstyle ':completion:::*:default' menu no select zstyle ':completion:*' matcher-list 'm:{a-z}={A-Z}' zstyle ':completion:*' completer _expand _complete _ignored _approximate zstyle ':completion:*' select-prompt '%SScrolling active: current selection at %p%s' zstyle ':completion::complete:*' use-cache 1 zstyle ':completion:*:descriptions' format '%U%F{cyan}%d%f%u' #autoload -U promptinit #promptinit #prompt adam2 cyan blue cyan black autoload -U colors && colors function who_am_i { # this function shows who I am and where I'm sitting now # %n is $USERNAME variable. %m is The hostname up to the first โ€˜.โ€™ echo "%{$fg[magenta]%}%n%{$reset_color%} %{$fg[white]%}at%{$reset_color%} %{$fg[yellow]%}%m%{$reset_color%}" } function happy_sad { # next line is just ternary operator in zsh. It shows ^_^ if last command was true # and o_O if it was false echo "%(?.%{$fg[green]%}^_^%{$reset_color%}.%{$fg[red]%}o_O%{$reset_color%})" } function red_green { # The same as for happy_sad but for '>' prompt echo "%(?.%{$fg[green]%}>%{$reset_color%}.%{$fg[red]%}>%{$reset_color%})" } function gitbranch { # find current git branch local ret="$(git rev-parse --abbrev-ref HEAD 2>/dev/null)" # and test that it is not null. If not null - then print it. [ $ret ] && echo "%{$reset_color%}[%{$fg[red]%}$ret%{$reset_color%}]" } # it MUST be in singlequotes. Otherwise, promptsubst will not be working PROMPT=' $(who_am_i) %{$fg[white]%}in%{$reset_color%} %{$fg_no_bold[cyan]%}%d%{$reset_color%} $(gitbranch) $(red_green) ' # set right prompt side function zle-line-init zle-keymap-select { VIM_PROMPT="%{$fg_bold[yellow]%} [% NORMAL]% %{$reset_color%}" RPS1="${${KEYMAP/vicmd/$VIM_PROMPT}/(main|)/}" zle reset-prompt } zle -N zle-line-init zle -N zle-keymap-select bindkey -e bindkey 'ii' vi-cmd-mode bindkey ',,' insert-last-word bindkey '^[.' insert-last-word bindkey '^R' history-incremental-search-backward bindkey '<<' history-incremental-search-backward bindkey '^H' backward-kill-word bindkey '^b' backward-word bindkey '^f' forward-word alias cp='cp -iv' alias rcp='rsync -v --progress' alias rmv='rsync -v --progress --remove-source-files' alias mv='mv -iv' alias rm='rm -iv' alias rmdir='rmdir -v' alias ln='ln -v' alias chmod="chmod -c" alias chown="chown -c" alias du='du -hc' alias df='df -h' alias svim='sudo vim' alias scat='openssl x509 -text -noout -in' alias sctl='systemctl' alias sclu='systemctl list-units' alias ipsave='sudo iptables-save' if command -v colordiff > /dev/null 2>&1; then alias diff="colordiff -Nar" alias diffy="colordiff -Nar -y --suppress-common-lines" else alias diff="diff -Nar" alias diffy="diff -Nar -y --suppress-common-lines" fi alias grep='grep --colour=auto' alias egrep='egrep --colour=auto' alias clip='fc -e - 2>/dev/null | xsel -i -b' alias speedtest="curl -s -w 'Testing Website Response Time for: %{url_effective}\n\nLookup Time:\t\t%{time_namelookup}\nConnect Time:\t\t%{time_connect}\nPre-transfer Time:\t%{time_pretransfer}\nStart-transfer Time:\t%{time_starttransfer}\n\nTotal Time:\t\t%{time_total}\n' -o /dev/null" # Git aliases alias gst='git status' alias gco='git checkout' alias grv='git remote -v' # Translation aliases alias enru='trans en:ru -b' alias ruen='trans ru:en -b' # Docker aliases alias dps='sudo docker ps' alias dpsa='sudo docker ps --all' alias dips='sudo docker images' # Ansible aliases alias aved='ansible-vault edit' alias avdec='ansible-vault decrypt' alias avenc='ansible-vault encrypt' alias apl='ansible-playbook' # Fzf aliases fkill() { local pid pid=$(ps -ef | sed 1d | /usr/bin/fzf -m | awk '{print $2}') if [ "x$pid" != "x" ] then echo $pid | xargs kill -${1:-9} fi } alias fzf='fzf --height 70% --border --preview "head -100 {}"' alias vif='vim $(fzf)' alias open='xdg-open "$(fzf)" 2>/dev/null' PLATFORM=`uname` if [ "${PLATFORM}" != "Darwin" ]; then alias ls='ls --color=auto --human-readable --group-directories-first --classify' alias ip='ip -4 -o' else alias ls='ls -G' fi alias feh='feh -x -F -Y' alias less='less -S' # you know, that's funny ;) alias fuck='sudo $(fc -ln -1)' alias wttr='curl http://wttr.in/' # Export more specific variables for less # export LESS='-srSCmqPm--Less--(?eEND:%pb\%.)' # VirtualenvWrapper export WORKON_HOME=~/.virtualenvs if [ -f /usr/bin/virtualenvwrapper.sh ]; then source /usr/bin/virtualenvwrapper.sh else echo "virtualenvwrapper script for Python not found, skip load it" fi #unset GREP_OPTIONS # set 256 colors for terminal export TERM=screen-256color # SSH-related funcs check-ssh-agent() { if [ ! -S ~/.ssh/ssh_auth_sock ]; then echo "ssh-agent not running, run it" eval `ssh-agent` ln -sf "$SSH_AUTH_SOCK" ~/.ssh/ssh_auth_sock echo "ran ssh-agent" fi } check-ssh-add() { export SSH_AUTH_SOCK=~/.ssh/ssh_auth_sock if ! ssh-add -l >/dev/null; then ssh-add -t 8h echo "Keys were added to an agent" fi } ssh() { check-ssh-agent check-ssh-add /usr/bin/ssh $@ } # M-b and M-f (backward-word and forward-word) would jump over each word separated by a '/' export WORDCHARS='*?_[]~=&;!#$%^(){}' # use 'up' script instead of typing cd ../../../.. endlessly UPTOOL="${HOME}/.config/up/up.sh" if [ ! -f "${UPTOOL}" ]; then echo "'up' script does not exist, download it" curl --create-dirs -o "${UPTOOL}" https://raw.githubusercontent.com/sorrowless/up/master/up.sh 2>/dev/null chmod u+x "${UPTOOL}" source "${UPTOOL}" else source "${UPTOOL}" fi # I always use tmux, so put it here TPM="${HOME}/.tmux/plugins/tpm" if [ ! -d "${TPM}" ]; then echo "Tmux plugin manager does not loaded, download it" git clone https://github.com/tmux-plugins/tpm "${TPM}" fi # To avoid getting this rc file bigger, just get settings from other files for FILE in ~/.rc/* ; do source $FILE done <file_sep>/README.md ansible-deploy ============== This is a set of ansible roles to deploy a bunch of things I use from day to day. To use it, you need to have an ansible (tested on version 2.3.0.0) tooling setted up. This repo is organized next way: ``` . |-- group_vars |-- host_vars |-- inventory |-- roles `-- vars ``` *group_vars* contains variables which are common for specific group types, like ~all~ or ~docker~ *host_vars* contains variables for hosts, such as user name and hostname and IP *inventory* lists all the inventory files. As this repo is used for different projects but the same roles are used, separate inventory files are needed *roles* lists all available ansible roles *vars* contains variables for different OS types or for separate playbooks Main playbooks there are: * dotfiles.yml - sets the dotfiles I use everyday * xapps.yml - sets a configs for X apps * monitoring.yml - setup collectd to nodes To apply any of there all you need is just ``` $ ansible-playbook -i hosts <playbook_name.yml> [--vault-password-file ~/.vault_pass.txt] ```
73eab683f14ef3b245236105c0ceae7b1f068234
[ "Markdown", "Shell" ]
3
Shell
sorrowless/ansible_deploy
2aaa57ce37e47353fa4d5cecc8d4120d7c516d6a
800586655194d7ed4f571403c0b10466d197bea7
refs/heads/main
<file_sep>๏ปฟnamespace Owt.Services.Contacts { using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using AutoMapper; using Owt.Common.Contacts; using Owt.Data.Contacts; using Owt.Services.Security; public class ContactService : IContactService { private readonly IMapper mapper; private readonly IContactRepository contactRepository; private readonly IContactValidator contactValidator; private readonly ISecurityService securityService; public ContactService( IMapper mapper, IContactRepository contactRepository, IContactValidator contactValidator, ISecurityService securityService) { this.mapper = mapper ?? throw new ArgumentNullException(nameof(mapper)); this.contactRepository = contactRepository ?? throw new ArgumentNullException(nameof(contactRepository)); this.contactValidator = contactValidator ?? throw new ArgumentNullException(nameof(contactValidator)); this.securityService = securityService ?? throw new ArgumentNullException(nameof(securityService)); } public async Task<ContactExcerptDto> CreateContactAsync(NewContactDto newContact, CancellationToken cancellationToken) { this.securityService.Ensure(SecurityEntityTypes.Contact, SecurityMethods.Create); if (newContact == null) { throw new ArgumentNullException(nameof(newContact)); } this.contactValidator.ValidateContact(newContact); Contact newContactModel = this.mapper.Map<Contact>(newContact); Contact createdContact = await this.contactRepository.CreateContactAsync(newContactModel, cancellationToken); createdContact.CreatedBy = this.securityService.GetCurrentIdentityName(); await this.contactRepository.SaveChangesAsync(cancellationToken); ContactExcerptDto contactExcerpt = this.mapper.Map<ContactExcerptDto>(createdContact); return contactExcerpt; } public async Task<ContactDto> UpdateContactAsync(int id, ContactDto contactToUpdate, CancellationToken cancellationToken) { this.securityService.Ensure(SecurityEntityTypes.Contact, SecurityMethods.Update); if (contactToUpdate == null) { throw new ArgumentNullException(nameof(contactToUpdate)); } if (contactToUpdate.Id != id) { throw new ArgumentException("Id mismatch."); } this.contactValidator.ValidateContact(contactToUpdate); Contact contact = await this.GetContactModelAsync(id, cancellationToken); this.securityService.EnsureOwnership(contact); contact = this.mapper.Map(contactToUpdate, contact); await this.contactRepository.UpdateContactAsync(contact, cancellationToken); await this.contactRepository.SaveChangesAsync(cancellationToken); return await this.GetContactAsync(id, cancellationToken); } public async Task DeleteContactAsync(int id, CancellationToken cancellationToken) { this.securityService.Ensure(SecurityEntityTypes.Contact, SecurityMethods.Delete); Contact contact = await this.GetContactModelWithSkillsAsync(id, cancellationToken); this.securityService.EnsureOwnership(contact); contact.Deleted = true; foreach (ContactSkill cs in contact.ContactSkills) { cs.Deleted = true; } await this.contactRepository.UpdateContactAsync(contact, cancellationToken); await this.contactRepository.SaveChangesAsync(cancellationToken); } public async Task<ContactDto> GetContactAsync(int id, CancellationToken cancellationToken) { this.securityService.Ensure(SecurityEntityTypes.Contact, SecurityMethods.View); Contact contact = await this.GetContactModelAsync(id, cancellationToken); ContactDto contactDto = this.mapper.Map<ContactDto>(contact); return contactDto; } public async Task<ContactDetailsDto> GetContactDetailsAsync(int id, CancellationToken cancellationToken) { this.securityService.Ensure(SecurityEntityTypes.Contact, SecurityMethods.View); Contact contact = await this.GetContactModelWithSkillsAsync(id, cancellationToken); ContactDetailsDto contactDto = this.mapper.Map<ContactDetailsDto>(contact); return contactDto; } public async Task<List<ContactDto>> GetContactsAsync(int? limit, CancellationToken cancellationToken) { this.securityService.Ensure(SecurityEntityTypes.Contact, SecurityMethods.View); this.securityService.Ensure(SecurityEntityTypes.Contact, SecurityMethods.View); List<Contact> contacts = await this.contactRepository.GetContactsAsync(this.GetLimit(limit), cancellationToken); List<ContactDto> contactsDto = contacts.Select(this.mapper.Map<ContactDto>).ToList(); return contactsDto; } public async Task<List<ContactSkillDto>> GetContactSkillsAsync(int contactId, CancellationToken cancellationToken) { this.securityService.Ensure(SecurityEntityTypes.ContactSkills, SecurityMethods.View); List<ContactSkill> contactSkills = await this.contactRepository.GetContactSkillsAsync(contactId, cancellationToken); List<ContactSkillDto> contactSkillsDto = contactSkills.Select(this.mapper.Map<ContactSkillDto>).ToList(); return contactSkillsDto; } public async Task<List<ContactSkillDto>> UpdateContactSkillAsync(int contactId, int contactSkillId, ContactSkillDto skillToUpdate, CancellationToken cancellationToken) { this.securityService.Ensure(SecurityEntityTypes.ContactSkills, SecurityMethods.Update); if (skillToUpdate == null) { throw new ArgumentNullException(nameof(skillToUpdate)); } if (skillToUpdate.ContactId != contactId) { throw new ArgumentException("ContactId mismatch."); } if (skillToUpdate.Id != contactSkillId) { throw new ArgumentException("ContactSkillId mismatch."); } Contact contact = await this.GetContactModelAsync(contactId, cancellationToken); this.securityService.EnsureOwnership(contact); await this.CheckIfContactSkillExistsAsync(contactId, contactSkillId, cancellationToken); ContactSkill contactSkill = await this.GetContactSkillModelAsync(contactId, contactSkillId, true, cancellationToken); this.securityService.EnsureOwnership(contactSkill); contactSkill = this.mapper.Map(skillToUpdate, contactSkill); await this.contactRepository.UpdateContactSkillAsync(contactSkill, cancellationToken); await this.contactRepository.SaveChangesAsync(cancellationToken); return await this.GetContactSkillsAsync(contactId, cancellationToken); } public async Task<List<ContactSkillDto>> DeleteContactSkillAsync(int contactId, int contactSkillId, CancellationToken cancellationToken) { this.securityService.Ensure(SecurityEntityTypes.ContactSkills, SecurityMethods.Delete); Contact contact = await this.GetContactModelAsync(contactId, cancellationToken); this.securityService.EnsureOwnership(contact); ContactSkill contactSkill = await this.GetContactSkillModelAsync(contactId, contactSkillId, true, cancellationToken); this.securityService.EnsureOwnership(contactSkill); contactSkill.Deleted = true; await this.contactRepository.UpdateContactSkillAsync(contactSkill, cancellationToken); await this.contactRepository.SaveChangesAsync(cancellationToken); return await this.GetContactSkillsAsync(contactId, cancellationToken); } public async Task<List<ContactSkillDto>> CreateContactSkillAsync(int contactId, NewContactSkillDto newContactSkill, CancellationToken cancellationToken) { this.securityService.Ensure(SecurityEntityTypes.ContactSkills, SecurityMethods.Create); if (newContactSkill == null) { throw new ArgumentNullException(nameof(newContactSkill)); } if (newContactSkill.ContactId != contactId) { throw new ArgumentException("ContactId mismatch."); } Contact contact = await this.GetContactModelAsync(contactId, cancellationToken); this.securityService.EnsureOwnership(contact); await this.CheckIfContactSkillExistsAsync(contactId, newContactSkill.Skill.Id, cancellationToken); ContactSkill newContactSkillModel = this.mapper.Map<ContactSkill>(newContactSkill); newContactSkillModel.CreatedBy = this.securityService.GetCurrentIdentityName(); await this.contactRepository.CreateContactSkillAsync(newContactSkillModel, cancellationToken); await this.contactRepository.SaveChangesAsync(cancellationToken); return await this.GetContactSkillsAsync(contactId, cancellationToken); } private async Task CheckIfContactSkillExistsAsync(int contactId, int skillId, CancellationToken cancellationToken) { ContactSkill contactSkill = await this.GetContactSkillModelBySkillAsync(contactId, skillId, false, cancellationToken); if (contactSkill != null) { throw new ArgumentException("Skill already exists for this contact."); } } private async Task<ContactSkill> GetContactSkillModelAsync(int contactId, int contactSkillId, bool throwExceptionIfNull, CancellationToken cancellationToken) { ContactSkill contactSkill = await this.contactRepository.GetContactSkillAsync(contactId, cs => cs.Id == contactSkillId, cancellationToken); if (throwExceptionIfNull && contactSkill == null) { throw new ArgumentException($"There is no {nameof(ContactSkill)} with {nameof(ContactSkill.ContactId)} {contactId} and {nameof(ContactSkill.Id)} {contactSkillId}."); } return contactSkill; } private async Task<ContactSkill> GetContactSkillModelBySkillAsync(int contactId, int skillId, bool throwExceptionIfNull, CancellationToken cancellationToken) { ContactSkill contactSkill = await this.contactRepository.GetContactSkillAsync(contactId, cs => cs.SkillId == skillId, cancellationToken); if (throwExceptionIfNull && contactSkill == null) { throw new ArgumentException($"There is no {nameof(ContactSkill)} with {nameof(ContactSkill.ContactId)} {contactId} and {nameof(ContactSkill.SkillId)} {skillId}."); } return contactSkill; } private async Task<Contact> GetContactModelAsync(int id, CancellationToken cancellationToken) { Contact contact = await this.contactRepository.GetContactAsync(e => e.Id == id, cancellationToken); if (contact == null) { throw new ArgumentException($"Unable to find contact with id '{id}'."); } return contact; } private async Task<Contact> GetContactModelWithSkillsAsync(int id, CancellationToken cancellationToken) { Contact contact = await this.contactRepository.GetContactModelWithSkillsAsync(e => e.Id == id, cancellationToken); if (contact == null) { throw new ArgumentException($"Unable to find contact with id '{id}'."); } contact.ContactSkills = contact.ContactSkills.Where(cs => !cs.Deleted).ToList(); return contact; } private int GetLimit(int? limit) { const int MaxLimit = 50; return Math.Min(limit ?? MaxLimit, MaxLimit); } } }<file_sep>๏ปฟnamespace Owt.Data.Contacts { using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; [Table("Contacts", Schema = "op")] public class Contact : IDeletable, IOwnable { // ReSharper disable once UnusedAutoPropertyAccessor.Local [Key] public int Id { get; private set; } public string Firstname { get; set; } public string Lastname { get; set; } public string Address { get; set; } public string Email { get; set; } public string MobilePhoneNumber { get; set; } public bool Deleted { get; set; } public List<ContactSkill> ContactSkills { get; set; } public string CreatedBy { get; set; } } }<file_sep>๏ปฟnamespace Owt.Data { public interface ILookup : IDeletable { int Id { get; } string Name { get; } } }<file_sep>๏ปฟnamespace Owt.Services.Lookups { using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using AutoMapper; using Owt.Common.Lookups; using Owt.Data; using Owt.Data.Lookups; using Owt.Services.Caching; public class LookupService : ILookupService { private readonly IMapper mapper; private readonly ILookupRepository lookupRepository; private readonly ICache cache; public LookupService( IMapper mapper, ILookupRepository lookupRepository, ICache cache) { this.mapper = mapper ?? throw new ArgumentNullException(nameof(mapper)); this.lookupRepository = lookupRepository ?? throw new ArgumentNullException(nameof(lookupRepository)); this.cache = cache ?? throw new ArgumentNullException(nameof(cache)); } public async Task<List<LookupDto>> GetSkillsAsync(CancellationToken cancellationToken) { return await this.GetLookupDtosAsync<Skill>(cancellationToken); } public async Task<LookupDto> GetSkillAsync(int id, CancellationToken cancellationToken) { return await this.GetLookupDtoAsync<Skill>(id, cancellationToken); } public async Task<List<LookupDto>> GetExpertiseLevelsAsync(CancellationToken cancellationToken) { return await this.GetLookupDtosAsync<ExpertiseLevel>(cancellationToken); } public async Task<LookupDto> GetExpertiseLevelAsync(int id, CancellationToken cancellationToken) { return await this.GetLookupDtoAsync<ExpertiseLevel>(id, cancellationToken); } private async Task<LookupDto> GetLookupDtoAsync<TLookup>(int id, CancellationToken cancellationToken) where TLookup : class, ILookup, new() { LookupDto lookupDto = (await this.GetLookupDtosAsync<TLookup>(cancellationToken)).FirstOrDefault(l => l.Id == id); if (lookupDto == null) { throw new ArgumentException($"There is no {typeof(TLookup).Name} with Id {id}."); } return lookupDto; } private async Task<List<LookupDto>> GetLookupDtosAsync<TLookup>(CancellationToken cancellationToken) where TLookup : class, ILookup, new() { List<TLookup> cachedItems = this.cache.Get<TLookup>(); if (cachedItems == null) { cachedItems = await this.lookupRepository.GetLookupsAsync<TLookup>(cancellationToken); this.cache.Set(cachedItems); } List<LookupDto> lookupDtos = cachedItems .Where(l => !l.Deleted) .Select(this.mapper.Map<LookupDto>).ToList(); return lookupDtos; } } }<file_sep>๏ปฟnamespace Owt.Common.Contacts { public interface IValidableContactDto { string Firstname { get; } string Lastname { get; } string Address { get; } string Email { get; } string MobilePhoneNumber { get; } } }<file_sep>๏ปฟnamespace Owt.Services.Security { public enum SecurityEntityTypes { Contact, ContactSkills } }<file_sep>๏ปฟnamespace Owt.Web.Controllers { using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using System.Web.Http; using Owt.Common.Lookups; using Owt.Services.Lookups; /// <summary> /// Allow to handle lookups /// </summary> [RoutePrefix("api")] public class LookupController : ApiController { private readonly ILookupService lookupService; /// <summary> /// Constructor /// </summary> /// <param name="lookupService"></param> public LookupController(ILookupService lookupService) { this.lookupService = lookupService ?? throw new ArgumentNullException(nameof(lookupService)); } /// <summary> /// Returns skills /// </summary> /// <param name="cancellationToken"></param> /// <returns></returns> [HttpGet] [Route("skills")] public async Task<IHttpActionResult> GetSkillsAsync(CancellationToken cancellationToken = default(CancellationToken)) { List<LookupDto> skills = await this.lookupService.GetSkillsAsync(cancellationToken); return this.Ok(skills); } /// <summary> /// Returns a skill /// </summary> /// <param name="id">Id of the skill</param> /// <param name="cancellationToken"></param> /// <returns></returns> [HttpGet] [Route("skills/{id:int}")] public async Task<IHttpActionResult> GetSkillAsync(int id, CancellationToken cancellationToken = default(CancellationToken)) { LookupDto skill = await this.lookupService.GetSkillAsync(id, cancellationToken); return this.Ok(skill); } /// <summary> /// Returns expertise levels /// </summary> /// <param name="cancellationToken"></param> /// <returns></returns> [HttpGet] [Route("expertiseLevels")] public async Task<IHttpActionResult> GetExpertiseLevelsAsync(CancellationToken cancellationToken = default(CancellationToken)) { List<LookupDto> expertiseLevels = await this.lookupService.GetExpertiseLevelsAsync(cancellationToken); return this.Ok(expertiseLevels); } /// <summary> /// Returns an expertise level /// </summary> /// <param name="id">Id of the expertise level</param> /// <param name="cancellationToken"></param> /// <returns></returns> [HttpGet] [Route("expertiseLevels/{id:int}")] public async Task<IHttpActionResult> GetExpertiseLevelAsync(int id, CancellationToken cancellationToken = default(CancellationToken)) { LookupDto expertiseLevel = await this.lookupService.GetExpertiseLevelAsync(id, cancellationToken); return this.Ok(expertiseLevel); } } }<file_sep>๏ปฟnamespace Owt.Web.Controllers { using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using System.Web.Http; using Owt.Common.Contacts; using Owt.Services.Contacts; /// <summary> /// Allow to handle contact and its skills /// </summary> [RoutePrefix("api/contacts")] [Authorize] public class ContactsController : ApiController { private readonly IContactService contactService; /// <summary> /// Constructor /// </summary> /// <param name="contactService"></param> public ContactsController(IContactService contactService) { this.contactService = contactService ?? throw new ArgumentNullException(nameof(contactService)); } /// <summary> /// Returns a list of contact /// </summary> /// <param name="limit">Limits the output</param> /// <param name="cancellationToken"></param> /// <returns>List of contact</returns> [HttpGet] [Route("")] public async Task<IHttpActionResult> GetContactsAsync(int? limit = null, CancellationToken cancellationToken = default(CancellationToken)) { List<ContactDto> contacts = await this.contactService.GetContactsAsync(limit, cancellationToken); return this.Ok(contacts); } /// <summary> /// Get a contact by its id /// </summary> /// <param name="id">Id of the contact</param> /// <param name="cancellationToken"></param> /// <returns>A contact</returns> [HttpGet] [Route("{id:int}")] public async Task<IHttpActionResult> GetContactAsync(int id, CancellationToken cancellationToken = default(CancellationToken)) { ContactDto contact = await this.contactService.GetContactAsync(id, cancellationToken); return this.Ok(contact); } /// <summary> /// Returns contact with its skills /// </summary> /// <param name="id">Id of the contact</param> /// <param name="cancellationToken"></param> /// <returns>A contact with its skills</returns> [HttpGet] [Route("{id:int}/details")] public async Task<IHttpActionResult> GetContactDetailsAsync(int id, CancellationToken cancellationToken = default(CancellationToken)) { ContactDetailsDto contact = await this.contactService.GetContactDetailsAsync(id, cancellationToken); return this.Ok(contact); } /// <summary> /// Returns skills of a contact /// </summary> /// <param name="id">Id of the contact</param> /// <param name="cancellationToken"></param> /// <returns>A list of contact's skills</returns> [HttpGet] [Route("{id:int}/skills")] public async Task<IHttpActionResult> GetContactSkillsAsync(int id, CancellationToken cancellationToken = default(CancellationToken)) { List<ContactSkillDto> contactSkills = await this.contactService.GetContactSkillsAsync(id, cancellationToken); return this.Ok(contactSkills); } /// <summary> /// Create a contact /// </summary> /// <param name="newContact">Contact to create</param> /// <param name="cancellationToken"></param> /// <returns>The created contact excerpt</returns> [HttpPost] [Route("")] public async Task<IHttpActionResult> CreateContactAsync(NewContactDto newContact, CancellationToken cancellationToken = default(CancellationToken)) { ContactExcerptDto contactExcerpt = await this.contactService.CreateContactAsync(newContact, cancellationToken); return this.Ok(contactExcerpt); } /// <summary> /// Add a skill to a contact /// </summary> /// <param name="id">Id of the contact</param> /// <param name="newContactSkill">Skill to add</param> /// <param name="cancellationToken"></param> /// <returns>A list of contact's skills</returns> [HttpPost] [Route("{id:int}/skills")] public async Task<IHttpActionResult> CreateContactSkillAsync(int id, NewContactSkillDto newContactSkill, CancellationToken cancellationToken = default(CancellationToken)) { List<ContactSkillDto> contactSkills = await this.contactService.CreateContactSkillAsync(id, newContactSkill, cancellationToken); return this.Ok(contactSkills); } /// <summary> /// Update a contact /// </summary> /// <param name="id">Id of the contact</param> /// <param name="contactToUpdate">Contact values to udpate</param> /// <param name="cancellationToken"></param> /// <returns>The updated contact</returns> [HttpPut] [Route("{id:int}")] public async Task<IHttpActionResult> UpdateContactAsync(int id, ContactDto contactToUpdate, CancellationToken cancellationToken = default(CancellationToken)) { ContactDto contact = await this.contactService.UpdateContactAsync(id, contactToUpdate, cancellationToken); return this.Ok(contact); } /// <summary> /// Update a contact skill /// </summary> /// <param name="id">Id of the contact</param> /// <param name="contactSkillId">Id of the skill</param> /// <param name="skillToUpdate">Values of the skill to update</param> /// <param name="cancellationToken"></param> /// <returns>A list of contact's skills</returns> [HttpPut] [Route("{id:int}/skills/{contactSkillId:int}")] public async Task<IHttpActionResult> UpdateContactSkillAsync(int id, int contactSkillId, ContactSkillDto skillToUpdate, CancellationToken cancellationToken = default(CancellationToken)) { List<ContactSkillDto> contactSkills = await this.contactService.UpdateContactSkillAsync(id, contactSkillId, skillToUpdate, cancellationToken); return this.Ok(contactSkills); } /// <summary> /// Soft delete a contact /// </summary> /// <param name="id">Id of the contact</param> /// <param name="cancellationToken"></param> /// <returns></returns> [HttpPost] [Route("{id:int}/delete")] public async Task<IHttpActionResult> DeleteContactAsync(int id, CancellationToken cancellationToken = default(CancellationToken)) { await this.contactService.DeleteContactAsync(id, cancellationToken); return this.Ok(); } /// <summary> /// Soft delete a contact skill /// </summary> /// <param name="id">Id of the contact</param> /// <param name="contactSkillId">Id of the contact skill</param> /// <param name="cancellationToken"></param> /// <returns></returns> [HttpPost] [Route("{id:int}/skills/{contactSkillId:int}/delete")] public async Task<IHttpActionResult> DeleteContactSkillAsync(int id, int contactSkillId, CancellationToken cancellationToken = default(CancellationToken)) { List<ContactSkillDto> contactSkills = await this.contactService.DeleteContactSkillAsync(id, contactSkillId, cancellationToken); return this.Ok(contactSkills); } } }<file_sep>๏ปฟnamespace Owt.Data { public interface IOwnable { string CreatedBy { get; } } }<file_sep>๏ปฟnamespace Owt.Common.Contacts { public interface IContactDto { int Id { get; set; } string Firstname { get; set; } string Lastname { get; set; } string FullName { get; set; } string Address { get; set; } string Email { get; set; } string MobilePhoneNumber { get; set; } } }<file_sep>๏ปฟnamespace Owt.Data.Contacts { using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; [Table("ContactsSkills", Schema = "op")] public class ContactSkill : IDeletable, IOwnable { [Key] // ReSharper disable once UnusedAutoPropertyAccessor.Local public int Id { get; private set; } public int ContactId { get; set; } public int SkillId { get; set; } public int ExpertiseLevelId { get; set; } public bool Deleted { get; set; } public string CreatedBy { get; set; } } }<file_sep>๏ปฟnamespace Owt.Web { using System; using System.IO; using Castle.Windsor; using Castle.Windsor.Installer; public static class IocContainer { internal static IWindsorContainer Container { get; private set; } public static void Setup(FileInfo castleConfigFile) { if (castleConfigFile == null) { throw new ArgumentNullException(nameof(castleConfigFile)); } if (!castleConfigFile.Exists) { throw new FileNotFoundException("Unable to find file.", castleConfigFile.FullName); } Container = new WindsorContainer(); Container.Install(Configuration.FromXmlFile(castleConfigFile.FullName)); } public static void Dispose() { Container?.Dispose(); } } }<file_sep>๏ปฟnamespace Owt.Services.Security { using Owt.Data; public class NoSecurityService : ISecurityService { public void Ensure(SecurityEntityTypes contact, SecurityMethods create) { } public string GetCurrentIdentityName() => "NoSecurity"; public void EnsureOwnership(IOwnable ownable) { } } }<file_sep>๏ปฟnamespace Owt.Services.Caching { using System; using System.Collections.Generic; public class Cache : ICache { private DateTime cacheInitializationDate; private readonly int cacheDurationInMinutes; private readonly Dictionary<string, object> dico = new Dictionary<string, object>(); public Cache(int cacheDurationInMinutes) { this.cacheDurationInMinutes = cacheDurationInMinutes; this.Invalidate(); } public void Set<TEntity>(List<TEntity> entities) { string cacheKey = GetCacheKey<TEntity>(); if (!this.dico.ContainsKey(cacheKey)) { this.dico.Add(cacheKey, null); } this.dico[cacheKey] = entities; } public List<TEntity> Get<TEntity>() { if (this.MustInvalidate()) { this.Invalidate(); } string cacheKey = GetCacheKey<TEntity>(); if (this.dico.ContainsKey(cacheKey)) { return (List<TEntity>)this.dico[cacheKey]; } return null; } private bool MustInvalidate() => (DateTime.UtcNow - this.cacheInitializationDate).TotalMinutes > this.cacheDurationInMinutes; public void Invalidate() { this.cacheInitializationDate = DateTime.UtcNow; this.dico.Clear(); } private static string GetCacheKey<TEntity>() => typeof(TEntity).FullName; } }<file_sep>๏ปฟnamespace Owt.Services.Lookups { using Castle.MicroKernel.Registration; using Castle.MicroKernel.SubSystems.Configuration; using Castle.Windsor; using Owt.Data.Lookups; public class Installer : IWindsorInstaller { public void Install(IWindsorContainer container, IConfigurationStore store) { container.Register( Component .For<ILookupService>() .ImplementedBy<LookupService>() .LifestyleTransient(), Component .For<ILookupRepository>() .ImplementedBy<LookupRepository>() .LifestyleTransient() ); } } }<file_sep>๏ปฟnamespace Owt.Data.Lookups { using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Threading; using System.Threading.Tasks; public class LookupRepository : ILookupRepository { private readonly OwtDbContext dbContext; public LookupRepository(OwtDbContext dbContext) { this.dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext)); } public async Task<List<TLookup>> GetLookupsAsync<TLookup>(CancellationToken cancellationToken) where TLookup : class, ILookup, new() { return await this.dbContext .Set<TLookup>() .Where(l => !l.Deleted) .AsNoTracking() .ToListAsync(cancellationToken); } } }<file_sep>๏ปฟnamespace Owt.Data.Contacts { using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; public class ContactRepository : IContactRepository { private readonly OwtDbContext dbContext; public ContactRepository(OwtDbContext dbContext) { this.dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext)); } public async Task<Contact> CreateContactAsync(Contact contact, CancellationToken cancellationToken) { if (contact == null) { throw new ArgumentNullException(nameof(contact)); } Contact addedContact = this.dbContext.Set<Contact>().Add(contact); return addedContact; } public async Task<Contact> GetContactAsync( Expression<Func<Contact, bool>> filter, CancellationToken cancellationToken) { Contact contact = await this.GetContactsQueryable() .FirstOrDefaultAsync(filter, cancellationToken); return contact; } public async Task<Contact> GetContactModelWithSkillsAsync(Expression<Func<Contact, bool>> filter, CancellationToken cancellationToken) { Contact contact = await this.GetContactsQueryable() .Include(e => e.ContactSkills) .FirstOrDefaultAsync(filter, cancellationToken); return contact; } public async Task SaveChangesAsync(CancellationToken cancellationToken) { await this.dbContext.SaveChangesAsync(cancellationToken); } public async Task<List<Contact>> GetContactsAsync( int limit, CancellationToken cancellationToken) { IQueryable<Contact> queryable = this.GetContactsQueryable(); List<Contact> contacts = await queryable .Take(limit) .AsNoTracking() .ToListAsync(cancellationToken); return contacts; } public async Task<ContactSkill> GetContactSkillAsync(int contactId, Expression<Func<ContactSkill, bool>> filter, CancellationToken cancellationToken) { if (filter == null) { throw new ArgumentNullException(nameof(filter)); } IQueryable<ContactSkill> queryable = ApplyDeletionFilter(await this.GetContactSkillsQueryableAsync(contactId, cancellationToken)); return await queryable.FirstOrDefaultAsync(filter, cancellationToken); } public async Task<List<ContactSkill>> GetContactSkillsAsync(int contactId, CancellationToken cancellationToken) { IQueryable<ContactSkill> queryable = ApplyDeletionFilter(await this.GetContactSkillsQueryableAsync(contactId, cancellationToken)); return await queryable.ToListAsync(cancellationToken); } public async Task<ContactSkill> CreateContactSkillAsync(ContactSkill contactSkill, CancellationToken cancellationToken) { if (contactSkill == null) { throw new ArgumentNullException(nameof(contactSkill)); } ContactSkill addedContactSkill = this.dbContext.Set<ContactSkill>().Add(contactSkill); return addedContactSkill; } private async Task<IQueryable<ContactSkill>> GetContactSkillsQueryableAsync(int contactId, CancellationToken cancellationToken) { IQueryable<ContactSkill> queryable = this.dbContext.Set<ContactSkill>() .Where(cs => cs.ContactId == contactId) .AsNoTracking(); queryable = ApplyDeletionFilter(queryable); return queryable; } public async Task UpdateContactAsync(Contact contact, CancellationToken cancellationToken) { await this.UpdateEntityAsync(contact, cancellationToken); if (contact.ContactSkills != null) { foreach (ContactSkill cs in contact.ContactSkills) { await this.UpdateContactSkillAsync(cs, cancellationToken); } } } public async Task UpdateContactSkillAsync(ContactSkill contactSkill, CancellationToken cancellationToken) { await this.UpdateEntityAsync(contactSkill, cancellationToken); } private async Task UpdateEntityAsync<TEntity>(TEntity entity, CancellationToken cancellationToken) where TEntity : class { if (entity == null) { throw new ArgumentNullException(nameof(entity)); } this.dbContext .Set<TEntity>() .Attach(entity); this.dbContext.Entry(entity).State = EntityState.Modified; } private IQueryable<Contact> GetContactsQueryable(params Expression<Func<Contact, object>>[] includes) { IQueryable<Contact> queryable = this.dbContext .Set<Contact>() .AsQueryable(); foreach (Expression<Func<Contact, object>> include in includes) { queryable = queryable.Include(include); } queryable = ApplyDeletionFilter(queryable); return queryable; } private static IQueryable<TDeletable> ApplyDeletionFilter<TDeletable>(IQueryable<TDeletable> queryable) where TDeletable : class, IDeletable => queryable.Where(c => !c.Deleted); } }<file_sep>๏ปฟnamespace Owt.Data.Lookups { using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; public interface ILookupRepository { Task<List<TLookup>> GetLookupsAsync<TLookup>(CancellationToken cancellationToken) where TLookup : class, ILookup, new(); } }<file_sep>๏ปฟnamespace Owt.Data.Lookups { using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; [Table("ExpertiseLevels", Schema = "cfg")] public class ExpertiseLevel : ILookup { // ReSharper disable once UnusedAutoPropertyAccessor.Local [Key] public int Id { get; private set; } public string Name { get; set; } public bool Deleted { get; set; } } }<file_sep>๏ปฟnamespace Owt.Services.Contacts { using System; using AutoMapper; using Owt.Common.Contacts; using Owt.Common.Lookups; using Owt.Data.Contacts; using Owt.Services.Lookups; public class ContactSkillToDtoConverter : ITypeConverter<ContactSkill, ContactSkillDto> { private readonly ILookupService lookupService; public ContactSkillToDtoConverter(ILookupService lookupService) { this.lookupService = lookupService ?? throw new ArgumentNullException(nameof(lookupService)); } public ContactSkillDto Convert(ContactSkill source, ContactSkillDto destination, ResolutionContext context) { if (destination == null) { destination = new ContactSkillDto(); } if (source == null) { return destination; } destination.Id = source.Id; LookupDto skill = AsyncHelper.RunSync(() => this.lookupService.GetSkillAsync(source.SkillId, default)); destination.Skill = context.Mapper.Map<LookupDto>(skill); LookupDto expertiseLevel = AsyncHelper.RunSync(() => this.lookupService.GetExpertiseLevelAsync(source.ExpertiseLevelId, default)); destination.ExpertiseLevel = context.Mapper.Map<LookupDto>(expertiseLevel); destination.ContactId = source.ContactId; return destination; } } }<file_sep>๏ปฟnamespace Owt.Services.Security { using System; using System.Collections.Generic; using System.Security; using System.Threading; using Owt.Data; public class DummySecurityService : ISecurityService { private readonly Dictionary<string, HashSet<string>> dummyUserRights = new Dictionary<string, HashSet<string>>(StringComparer.InvariantCultureIgnoreCase); public DummySecurityService() { // TODO : retrieve from Repository+Database this.dummyUserRights.Add( @"W10X64-DEV\Proxmox", new HashSet<string>(StringComparer.InvariantCultureIgnoreCase) { GetDummyRightName(SecurityEntityTypes.Contact, SecurityMethods.View), GetDummyRightName(SecurityEntityTypes.Contact, SecurityMethods.Create), GetDummyRightName(SecurityEntityTypes.Contact, SecurityMethods.Update), GetDummyRightName(SecurityEntityTypes.Contact, SecurityMethods.Delete), GetDummyRightName(SecurityEntityTypes.ContactSkills, SecurityMethods.View), GetDummyRightName(SecurityEntityTypes.ContactSkills, SecurityMethods.Create), GetDummyRightName(SecurityEntityTypes.ContactSkills, SecurityMethods.Update), GetDummyRightName(SecurityEntityTypes.ContactSkills, SecurityMethods.Delete) }); } public void Ensure(SecurityEntityTypes entityType, SecurityMethods method) { string rightToCheck = GetDummyRightName(entityType, method); string currentIdentityName = this.GetCurrentIdentityName(); if (!this.dummyUserRights.ContainsKey(currentIdentityName) || !this.dummyUserRights[currentIdentityName].Contains(rightToCheck)) { throw new SecurityException(); } } public string GetCurrentIdentityName() { string currentIdentityName = Thread.CurrentPrincipal?.Identity?.Name; if (string.IsNullOrWhiteSpace(currentIdentityName)) { throw new ApplicationException($"Unable to retrieve the current identity."); } return currentIdentityName; } public void EnsureOwnership(IOwnable ownable) { if (ownable == null) { throw new ArgumentNullException(nameof(ownable)); } if (!string.Equals(ownable.CreatedBy, GetCurrentIdentityName(), StringComparison.InvariantCultureIgnoreCase)) { throw new SecurityException(); } } private static string GetDummyRightName(SecurityEntityTypes entityType, SecurityMethods method) => $"{Enum.GetName(entityType.GetType(), entityType)}_{Enum.GetName(method.GetType(), method)}"; } }<file_sep>๏ปฟnamespace Owt.Data { using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; public static class OwtModelBuilder { public static void Build(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>(); } } }<file_sep>๏ปฟnamespace Owt.Services.Caching { using System.Collections.Generic; public interface ICache { void Set<TEntity>(List<TEntity> entities); List<TEntity> Get<TEntity>(); void Invalidate(); } }<file_sep>๏ปฟnamespace Owt.Services.Lookups { using AutoMapper; using Owt.Common.Lookups; using Owt.Data.Lookups; public class MappingProfile : Profile { public MappingProfile() { this.CreateMap<Skill, LookupDto>(); this.CreateMap<ExpertiseLevel, LookupDto>(); } } }<file_sep>๏ปฟnamespace Owt.Common.Contacts { using Owt.Common.Lookups; public class NewContactSkillDto { public int ContactId { get; set; } public LookupDto Skill { get; set; } public LookupDto ExpertiseLevel { get; set; } } }<file_sep>๏ปฟnamespace Owt.Services.Security { public enum SecurityMethods { Create, View, Update, Delete } }<file_sep>๏ปฟnamespace Owt.Services.Contacts { using System; using System.Collections.Generic; using System.Linq; using System.Text; using EmailValidation; using Owt.Common.Contacts; using PhoneNumbers; public class ContactValidator : IContactValidator { private readonly HashSet<string> supportedValidationRegions; public ContactValidator(HashSet<string> supportedValidationRegions) { this.supportedValidationRegions = supportedValidationRegions ?? throw new ArgumentNullException(nameof(supportedValidationRegions)); if (this.supportedValidationRegions.Count == 0) { throw new ArgumentException($"At least 1 supported region must be defined."); } } public void ValidateContact(IValidableContactDto validableContactDto) { if (validableContactDto == null) { throw new ArgumentNullException(nameof(validableContactDto)); } ValidateNotEmpty(nameof(validableContactDto.Firstname), validableContactDto.Firstname); ValidateNotEmpty(nameof(validableContactDto.Lastname), validableContactDto.Lastname); ValidateNotEmpty(nameof(validableContactDto.Address), validableContactDto.Address); this.ValidateMobilePhoneNumber(validableContactDto.MobilePhoneNumber); this.ValidateEmailAddress(validableContactDto.Email); } private void ValidateEmailAddress(string email) { if (!EmailValidator.Validate((email ?? string.Empty).Trim())) { throw new ApplicationException("Email is not valid."); } } private void ValidateMobilePhoneNumber(string mobilePhoneNumber) { PhoneNumberUtil instance = PhoneNumberUtil.GetInstance(); HashSet<string> validSupportedRegions = this.supportedValidationRegions .Join( instance.GetSupportedRegions(), s => s, r => r, (s, r) => s) .OrderBy(code => code) .ToHashSet(); bool validPhoneNumber = false; foreach (string region in validSupportedRegions) { try { PhoneNumber phoneNumber = instance.Parse(mobilePhoneNumber, region); if (instance.GetNumberType(phoneNumber) != PhoneNumberType.MOBILE) { continue; } validPhoneNumber = true; break; } catch (NumberParseException) { } } if (validPhoneNumber) { return; } StringBuilder errorMessage = new StringBuilder(); errorMessage.AppendLine("Invalid mobile phone number."); errorMessage.AppendLine("Examples :"); foreach (string region in validSupportedRegions) { PhoneNumber example = instance.GetExampleNumberForType(region, PhoneNumberType.MOBILE); StringBuilder formattedExample = new StringBuilder(); if (example.NumberOfLeadingZeros > 0) { formattedExample.Append("("); for (int i = 0; i < example.NumberOfLeadingZeros; i++) { formattedExample.Append("0"); } formattedExample.Append(")"); } formattedExample.Append(example.NationalNumber); errorMessage.AppendLine($"\t{region} : {formattedExample}"); } throw new ApplicationException(errorMessage.ToString()); } private static void ValidateNotEmpty(string propertyName, string value) { if (string.IsNullOrWhiteSpace(value.Trim())) { throw new ApplicationException($"Property '{propertyName}' cannot be null"); } } } }<file_sep>๏ปฟnamespace Owt.Services.Contacts { using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Owt.Common.Contacts; public interface IContactService { Task<ContactExcerptDto> CreateContactAsync(NewContactDto newContact, CancellationToken cancellationToken); Task<ContactDto> UpdateContactAsync(int id, ContactDto contactToUpdate, CancellationToken cancellationToken); Task DeleteContactAsync(int id, CancellationToken cancellationToken); Task<ContactDto> GetContactAsync(int id, CancellationToken cancellationToken); Task<List<ContactDto>> GetContactsAsync(int? limit, CancellationToken cancellationToken); Task<ContactDetailsDto> GetContactDetailsAsync(int id, CancellationToken cancellationToken); Task<List<ContactSkillDto>> GetContactSkillsAsync(int contactId, CancellationToken cancellationToken); Task<List<ContactSkillDto>> UpdateContactSkillAsync(int contactId, int contactSkillId, ContactSkillDto skillToUpdate, CancellationToken cancellationToken); Task<List<ContactSkillDto>> DeleteContactSkillAsync(int contactId, int contactSkillId, CancellationToken cancellationToken); Task<List<ContactSkillDto>> CreateContactSkillAsync(int contactId, NewContactSkillDto newContactSkill, CancellationToken cancellationToken); } }<file_sep>๏ปฟnamespace Owt.Services.Security { using Owt.Data; public interface ISecurityService { void Ensure(SecurityEntityTypes contact, SecurityMethods create); string GetCurrentIdentityName(); void EnsureOwnership(IOwnable ownable); } }<file_sep>๏ปฟnamespace Owt.Common.Contacts { public class ContactExcerptDto { public int Id { get; set; } } }<file_sep>๏ปฟnamespace Owt.Data.Contacts { using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; public interface IContactRepository { Task<Contact> CreateContactAsync(Contact contact, CancellationToken cancellationToken); Task<Contact> GetContactAsync(Expression<Func<Contact, bool>> filter, CancellationToken cancellationToken); Task<Contact> GetContactModelWithSkillsAsync(Expression<Func<Contact, bool>> filter, CancellationToken cancellationToken); Task SaveChangesAsync(CancellationToken cancellationToken); Task<List<Contact>> GetContactsAsync(int limit, CancellationToken cancellationToken); Task UpdateContactAsync(Contact contact, CancellationToken cancellationToken); Task UpdateContactSkillAsync(ContactSkill contactSkill, CancellationToken cancellationToken); Task<ContactSkill> GetContactSkillAsync(int contactId, Expression<Func<ContactSkill, bool>> filter, CancellationToken cancellationToken); Task<List<ContactSkill>> GetContactSkillsAsync(int contactId, CancellationToken cancellationToken); Task<ContactSkill> CreateContactSkillAsync(ContactSkill contactSkill, CancellationToken cancellationToken); } }<file_sep>๏ปฟnamespace Owt.Services { using Castle.MicroKernel.Registration; using Castle.MicroKernel.SubSystems.Configuration; using Castle.Windsor; using Owt.Data; using Owt.Services.Caching; public class DependenciesInstaller : IWindsorInstaller { public void Install(IWindsorContainer container, IConfigurationStore store) { container.Register( Component .For<OwtDbContext>() .LifestyleTransient(), Component .For<ICache>() .ImplementedBy<Cache>() .DependsOn(Dependency.OnValue("cacheDurationInMinutes", 60)) .LifestyleSingleton() ); } } }<file_sep>๏ปฟnamespace Owt.Data { using System.Data.Entity; using Owt.Data.Contacts; using Owt.Data.Lookups; public class OwtDbContext : DbContext { public OwtDbContext() : base("OwtDbContext") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { OwtModelBuilder.Build(modelBuilder); base.OnModelCreating(modelBuilder); } public DbSet<Contact> Contacts { get; set; } public DbSet<Skill> Skills { get; set; } public DbSet<ContactSkill> ContactsSkills { get; set; } public DbSet<ExpertiseLevel> ExpertiseLevels { get; set; } } }<file_sep>๏ปฟnamespace Owt.Services.Contacts { using System.Collections.Generic; using Castle.MicroKernel.Registration; using Castle.MicroKernel.SubSystems.Configuration; using Castle.Windsor; using Owt.Data.Contacts; public class Installer : IWindsorInstaller { public void Install(IWindsorContainer container, IConfigurationStore store) { container.Register( Component .For<IContactService>() .ImplementedBy<ContactService>() .LifestyleTransient(), Component .For<IContactRepository>() .ImplementedBy<ContactRepository>() .LifestyleTransient(), Component .For<IContactValidator>() .ImplementedBy<ContactValidator>() .DependsOn( Dependency.OnValue( "supportedValidationRegions", new HashSet<string>(new[] { "CH", "FR" }))) .LifestyleTransient() ); } } }<file_sep>๏ปฟnamespace Owt.Web { using System; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.MapHttpAttributeRoutes(); MediaTypeHeaderValue appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => string.Equals(t.MediaType, "application/xml", StringComparison.InvariantCultureIgnoreCase)); config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType); } } }<file_sep>๏ปฟnamespace Owt.Common.Contacts { using Owt.Common.Lookups; public class ContactSkillDto { public int Id { get; set; } public int ContactId { get; set; } public LookupDto Skill { get; set; } public LookupDto ExpertiseLevel { get; set; } } }<file_sep>๏ปฟnamespace Owt.Services.Lookups { using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Owt.Common.Lookups; public interface ILookupService { Task<List<LookupDto>> GetSkillsAsync(CancellationToken cancellationToken); Task<LookupDto> GetSkillAsync(int id, CancellationToken cancellationToken); Task<List<LookupDto>> GetExpertiseLevelsAsync(CancellationToken cancellationToken); Task<LookupDto> GetExpertiseLevelAsync(int id, CancellationToken cancellationToken); } }<file_sep>๏ปฟnamespace Owt.Common.Contacts { using System.Collections.Generic; public class ContactDetailsDto : IContactDto { public int Id { get; set; } public string Firstname { get; set; } public string Lastname { get; set; } public string FullName { get; set; } public string Address { get; set; } public string Email { get; set; } public string MobilePhoneNumber { get; set; } public List<ContactSkillDto> ContactSkills { get; set; } } }<file_sep>๏ปฟnamespace Owt.Common.Contacts { public class ContactDto : IValidableContactDto, IContactDto { public int Id { get; set; } public string Firstname { get; set; } public string Lastname { get; set; } public string FullName { get; set; } public string Address { get; set; } public string Email { get; set; } public string MobilePhoneNumber { get; set; } } }<file_sep>๏ปฟnamespace Owt.Services.Contacts { using System; using AutoMapper; using Owt.Common.Contacts; using Owt.Data.Contacts; using Owt.Services.Lookups; public class ContactSkillFromDtoConverter : ITypeConverter<ContactSkillDto, ContactSkill> { private readonly ILookupService lookupService; public ContactSkillFromDtoConverter(ILookupService lookupService) { this.lookupService = lookupService ?? throw new ArgumentNullException(nameof(lookupService)); } public ContactSkill Convert(ContactSkillDto source, ContactSkill destination, ResolutionContext context) { if (destination == null) { destination = new ContactSkill(); } if (source == null) { return destination; } if (source.Skill == null) { throw new ArgumentException($"{nameof(source.Skill)} must be specified."); } destination.SkillId = AsyncHelper.RunSync(() => this.lookupService.GetSkillAsync(source.Skill.Id, default)).Id; if (source.ExpertiseLevel == null) { throw new ArgumentException($"{nameof(source.ExpertiseLevel)} must be specified."); } destination.ExpertiseLevelId = AsyncHelper.RunSync(() => this.lookupService.GetExpertiseLevelAsync(source.ExpertiseLevel.Id, default)).Id; destination.ContactId = source.ContactId; return destination; } } }<file_sep>๏ปฟnamespace Owt.Services.Contacts { using Owt.Common.Contacts; public interface IContactValidator { void ValidateContact(IValidableContactDto validableContactDto); } }<file_sep>๏ปฟnamespace Owt.Services.Contacts { using AutoMapper; using Owt.Common.Contacts; using Owt.Data.Contacts; public class MappingProfile : Profile { public MappingProfile() { this.CreateMap<Contact, ContactDto>() .ForMember(dto => dto.FullName, opt => opt.MapFrom(src => $"{src.Firstname} {src.Lastname}".Trim())); this.CreateMap<ContactDto, Contact>(); this.CreateMap<NewContactDto, Contact>(); this.CreateMap<Contact, ContactExcerptDto>(); this.CreateMap<Contact, ContactDetailsDto>(); this.CreateMap<ContactSkill, ContactSkillDto>() .ConvertUsing<ContactSkillToDtoConverter>(); this.CreateMap<NewContactSkillDto, ContactSkill>() .ConvertUsing<ContactSkillFromNewDtoConverter>(); this.CreateMap<ContactSkillDto, ContactSkill>() .ConvertUsing<ContactSkillFromDtoConverter>(); } } }<file_sep>namespace Owt.Web { using System; using System.Configuration; using System.IO; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Dispatcher; using AutoMapper; using Castle.MicroKernel.Registration; public class WebApiApplication : HttpApplication { protected void Application_Start() { GlobalConfiguration.Configure(WebApiConfig.Register); SetupCastle(); ConfigureAutoMapperCastle(); SetupControllers(); } private static void SetupControllers() { IocContainer.Container.Register( Classes.FromThisAssembly() .BasedOn<IHttpController>() .LifestyleTransient()); } private static void SetupCastle() { const string SettingsKey = "castleConfigFile"; if (ConfigurationManager.AppSettings.AllKeys.All(k => !string.Equals(k, SettingsKey, StringComparison.InvariantCultureIgnoreCase))) { throw new ApplicationException($"Unable to find settings key '{SettingsKey}'."); } IocContainer.Setup(new FileInfo(ConfigurationManager.AppSettings[SettingsKey])); GlobalConfiguration.Configuration.Services.Replace( typeof(IHttpControllerActivator), new WindsorCompositionRoot(IocContainer.Container)); } private static void ConfigureAutoMapperCastle() { // Register all mapper profiles IocContainer.Container.Register( Classes.FromAssemblyInThisApplication(typeof(IocContainer).Assembly) .BasedOn<Profile>() .WithServiceBase()); // Register IConfigurationProvider with all registered profiles IocContainer.Container.Register( Component.For<IConfigurationProvider>().UsingFactoryMethod( kernel => { return new MapperConfiguration( configuration => { kernel.ResolveAll<Profile>().ToList().ForEach(configuration.AddProfile); }); }).LifestyleSingleton()); // Register IMapper with registered IConfigurationProvider IocContainer.Container.Register( Component.For<IMapper>().UsingFactoryMethod( kernel => new Mapper(kernel.Resolve<IConfigurationProvider>(), kernel.Resolve))); // Register converters IocContainer.Container.Register( Classes.FromAssemblyInThisApplication(typeof(IocContainer).Assembly) .BasedOn(typeof(ITypeConverter<,>)) .WithServiceSelf() .LifestyleTransient()); } public override void Dispose() { IocContainer.Dispose(); base.Dispose(); } } }
717f23158d6812683653827e9b9618354e2bcd40
[ "C#" ]
43
C#
pandadoudou/Owt
91b92fe5066f8ab4986ab7fba6363687195bef3d
92eecd5d213402390f3d7e43b62c7eecb85d6497
refs/heads/master
<file_sep><?php include("utility.inc"); include("ccconfig.inc"); include("app_logic.inc"); ?> <?php ////////////////////////////////////////////////////////////////////////////////////////////////// // Write to a chatroom ////////////////////////////////////////////////////////////////////////////////////////////////// header("Content-Type: text/plain"); switch($_POST['message_type']) { case 0: App::writechat_text($_POST['creator_id'], $_POST['chatroom'], $_POST['msg_written'], $_POST['message']); break; case 1: App::writechat_picture($_POST['creator_id'], $_POST['chatroom'], $_POST['msg_written'], $_POST['message']); break; } ?> <file_sep><?php include("utility.inc"); include("ccconfig.inc"); include("app_logic.inc"); ?> <?php ////////////////////////////////////////////////////////////////////////////////////////////////// // Write to a chatroom ////////////////////////////////////////////////////////////////////////////////////////////////// header("Content-Type: text/plain"); $json_result = Array(); if(App::picture_hash_exists($_POST['hash'])) $json_result['exists'] = True; else $json_result['exists'] = False; echo json_encode($json_result, JSON_PRETTY_PRINT); ?> <file_sep><?php class App { public static $servername = "localhost"; public static $user = "catchat"; public static $password = "<PASSWORD>"; public static $upload_dir = "/web/azenguard.com/public/CatChat/uploaded_files/"; public static $thumbnail_dir = "/web/azenguard.com/public/CatChat/thumbnails/"; ###################### # Write a text message public static function writechat_text($creator_id, $chatroom, $msg_written, $message) { if(!$conn = new mysqli(self::$servername, self::$user, self::$password)) die("Couldn't connect to DB"); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $query = "INSERT INTO catchat.chats (chatroom, msg_written, creator_id, message_type, message) VALUES (?,?,?,?,?);"; if($stmt = $conn->prepare($query)) { $stmt->bind_param("isiis", $chatroom, $msg_written, $creator_id, $message_type, $message); $chatroom = (string)$chatroom; $msg_written = $msg_written; $creator_id = (string)$creator_id; $message_type = (string)0; $message = $message; $stmt->execute(); $result = $stmt->errno; $writeresponse = array(); $writeresponse['status'] = "Okay"; $stmt->close(); echo json_encode($writeresponse, JSON_PRETTY_PRINT); } else die("SHIT FUCK"); $conn->close(); } ######################### # Write a picture message public static function writechat_picture($creator_id, $chatroom, $msg_written, $hash) { if(!$conn = new mysqli(self::$servername, self::$user, self::$password)) die("Couldn't connect to DB"); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $query = "INSERT INTO catchat.chats (chatroom, msg_written, creator_id, message_type, message) VALUES (?,?,?,?,?);"; if($stmt = $conn->prepare($query)) { $stmt->bind_param("isiis", $chatroom, $msg_written, $creator_id, $message_type, $message); $chatroom = (string)$chatroom; $msg_written = $msg_written; $creator_id = (string)$creator_id; $message_type = (string)1; $message = $hash; $stmt->execute(); $result = $stmt->errno; $writeresponse = array(); $writeresponse['status'] = "Okay"; $stmt->close(); echo json_encode($writeresponse, JSON_PRETTY_PRINT); } else die("SHIT FUCK"); $conn->close(); } ######################################## # Check if a picture is already uploaded public static function picture_hash_exists($hash) { if(!$conn = new mysqli(self::$servername, self::$user, self::$password)) die("Couldn't connect to DB"); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $hash = $_POST["hash"]; $query = "SELECT hash FROM catchat.fileshare WHERE hash=?;"; if(!$stmt = $conn->prepare($query)) die("This don't work43"); $stmt->bind_param("s", $hash); $stmt->bind_result($hash_pipe); $stmt->execute(); $found = False; while ($stmt->fetch()) { $found = True; } $stmt->close(); return $found; } } ?> <file_sep><?php $servername; $servername = "localhost"; $user = "catchat"; $password = "<PASSWORD>"; $upload_dir = "/web/azenguard.com/public/CatChat/uploaded_files/"; $thumbnail_dir = "/web/azenguard.com/public/CatChat/thumbnails/"; ?> <file_sep><?php /** * Created by PhpStorm. * User: james * Date: 29/04/16 * Time: 8:09 PM */ session_start(); $_SESSION["favcolor"] = "green"; <file_sep><?php function imageCreateFromAny($filepath) { $type = exif_imagetype($filepath); // [] if you don't have exif you could use getImageSize() $allowedTypes = array( 1, // [] gif 2, // [] jpg 3, // [] png 6 // [] bmp ); if (!in_array($type, $allowedTypes)) { return false; } switch ($type) { case 1 : $im = imageCreateFromGif($filepath); break; case 2 : $im = imageCreateFromJpeg($filepath); break; case 3 : $im = imageCreateFromPng($filepath); break; case 6 : $im = imageCreateFromBmp($filepath); break; } return $im; } function make_thumb($src, $dest, $desired_width) { /* read the source image */ $source_image = imageCreateFromAny($src); $width = imagesx($source_image); $height = imagesy($source_image); /* find the "desired height" of this thumbnail, relative to the desired width */ $desired_height = floor($height * ($desired_width / $width)); /* create a new, "virtual" image */ $virtual_image = imagecreatetruecolor($desired_width, $desired_height); /* copy source image at a resized size */ imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height); /* create the physical thumbnail image to its destination */ imagepng($virtual_image, $dest); } ?> <file_sep> <?php die("THIS IS WRONG"); ////////////////////////////////////////////////////////////////////////////////////////////////// // Get a complete chatroom conversation ////////////////////////////////////////////////////////////////////////////////////////////////// header("Content-Type: text/plain"); $servername = "localhost"; $user = "catchat"; $password = "<PASSWORD>"; $conn = new mysqli($servername, $user, $password); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $chatroom = $_POST["chatroom"]; $after = $_POST["after"]; $before = $_POST["before"]; switch($_POST['rangetype']) { # No range is set case "none": $query = "SELECT idchats, msg_written, creator_id, message_type, message FROM catchat.chats WHERE 'chatroom'=?"; $stmt = $conn->prepare($query); $stmt->bind_param("i", $chatroom); break; # An ID based range is set case "id": $query = "SELECT idchats, msg_written, creator_id, message_type, message FROM catchat.chats WHERE 'chatroom'=?"; if($after !== "") $query .= " AND idchats>?"; if($before !== "") $query .= " AND idchats<?"; $stmt = $conn->prepare($query); if($after !== "" && $before == "") $stmt->bind_param("ii", $chatroom, $after); if($after == "" && $before !== "") $stmt->bind_param("ii", $chatroom, $before); if($after !== "" && $before !== "") $stmt->bind_param("iii", $chatroom, $after, $before); break; case "date": break; } $stmt->bind_result($idchats, $msg_written, $creator_id, $message_type, $message); $stmt->execute(); $chat_history = array(); $chat_history["chat_id"] = $chatroom; $chat_log = array(); while ($stmt->fetch()) { array_push($chat_log, array("idchats"=>$idchats, "msg_written"=>$msg_written, "creator"=>$creator_id, "message_type"=>$message_type, "message"=>$message)); } $chat_history["chat_log"] = $chat_log; $stmt->close(); echo json_encode($chat_history, JSON_PRETTY_PRINT); $conn->close(); ?> <file_sep><?php include("utility.inc"); include("ccconfig.inc"); include("app_logic.inc"); ?> <?php ////////////////////////////////////////////////////////////////////////////////////////////////// // Write a file to the chatroom ////////////////////////////////////////////////////////////////////////////////////////////////// header("Content-Type: text/plain"); $filename = basename($_FILES['userfile']['name']); $hash = hash_file("md5", $_FILES['userfile']['tmp_name']); $uploadfile = $upload_dir . $hash; $file_size = $_FILES['userfile']['size']; $tmp_name = $_FILES['userfile']['tmp_name']; $creator_id = $_POST['creator_id']; # Verify the file is all good, then move it. Make thumbnails if appropriate if(!move_uploaded_file($tmp_name, $uploadfile)) die("nigger lips"); # Create a thumbnail $thumbnailfile = $thumbnail_dir . $hash; make_thumb($uploadfile, $thumbnailfile, 200); # Create the DB entry for this file $conn = new mysqli($servername, $user, $password); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $query = "INSERT INTO catchat.fileshare (uploader_id, true_filename, hash, size, type) VALUES (?,?,?,?,?);"; if($stmt = $conn->prepare($query)) { $stmt->bind_param("issii", $creator_id, $filename, $hash, $file_size, $filetype); $creator_id = (string)$creator_id; $filename = $filename; $hash = $hash; $file_size = $file_size; $filetype = 0; # mime_content_type $stmt->execute(); $result = $stmt->errno; $writeresponse = array(); $writeresponse['status'] = "Okay"; $stmt->close(); echo json_encode($writeresponse, JSON_PRETTY_PRINT); } else die("SHIT FUCK"); #App::writechat_picture($_POST['creator_id'], $_POST['chatroom'], $_POST['msg_written'], $hash); $conn->close(); ?>
fb91a39fe3b5b21224b1ae2bfb51a946acc52de9
[ "PHP" ]
8
PHP
dirk103/CatChat-Backend
f0a399fd6ef4df04403a29f5f375428bd7967c2f
a3c685114447d2b6256e301603e9045a583cbe40
refs/heads/master
<repo_name>DavidMah/Realm-of-the-Automated-God<file_sep>/README.md # Realm Of the Automated God https://github.com/DavidMah/Realm-of-the-Automated-God Realm of the Automated God is a Bot that plays Realm of the Mad God. **Unfortunately, t's really janky and I'm certain that you won't be able to get it to work on your machine without many hours of work. This is because it was made for the purpose of tinkering with and showing the worth of the Robot.java library, and that task is a success** # Instructions Run `Runner` with java Within five seconds, place your mouse pointer at the top left of the main gameplay square of Realm of the Mad God. The program will report to stdout when it has confirmed the top left coordinate. Then within three seconds, place the mouse pointer at the bottom right of the main gameplay square. The bot will confirm the bottom right coordinate and take control of the mouse/keyboard. # Extension One can extend UserCharacter.java to create a different bot. MadGod.java handles the scanning of game data from your screen and Runner passes it to UserCharacter. ## Author <NAME> from the University of Washington <file_sep>/UserCharacter.java import java.awt.Robot; import java.awt.Point; import java.util.*; public class UserCharacter { private static int RADIUS = 1; private static int DEGREES = 1; private static int AUTO_ATTACK_KEY = 74; private static int NEXUS_KEY = 70; private static int UP_KEY = 87; private static int LEFT_KEY = 65; private static int DOWN_KEY = 83; private static int RIGHT_KEY = 68; private static int LEFT_MONITOR_WIDTH = 1920; private int screenX; private int screenY; private int screenWidth; private int centerX; private int centerY; private List<int[]>[] enemyQuadrants; private int health; private int targetQuadrant; private int targetAim; private Robot control; public UserCharacter(Robot controller, Point topLeft, Point bottomRight) { control = controller; screenX = (int)(topLeft.getX() - LEFT_MONITOR_WIDTH); screenY = (int)(topLeft.getY()); screenWidth = (int)(bottomRight.getX() - topLeft.getX()); centerX = screenX + (screenWidth / 2); centerY = screenY + (screenWidth / 2); targetQuadrant = -1; triggerAutoAttack(); } private void triggerAutoAttack() { control.keyPress(AUTO_ATTACK_KEY); control.keyRelease(AUTO_ATTACK_KEY); } public void runActions() { monitorHealth(); moveTo(findBestQuadrant()); aimAtEnemies(); } private void moveTo(int tQuadrant) { if(tQuadrant != targetQuadrant) { control.keyRelease(UP_KEY); control.keyRelease(LEFT_KEY); control.keyRelease(DOWN_KEY); control.keyRelease(RIGHT_KEY); if(tQuadrant % 7 < 2) // 7, 0, 1 control.keyPress(UP_KEY); if(tQuadrant > 4) // 5, 6, 7 control.keyPress(LEFT_KEY); if(tQuadrant % 6 > 2) // 3, 4, 5 control.keyPress(DOWN_KEY); if(tQuadrant > 0 && tQuadrant < 4) // 1, 2, 3 control.keyPress(RIGHT_KEY); targetQuadrant = tQuadrant; } } private int findBestQuadrant() { int tQuadrant = 0; int bestQuadrant = -1; for(int i = 0; i < enemyQuadrants.length; i++) { List<int[]> quad = enemyQuadrants[i]; if(bestQuadrant < quad.size()) { tQuadrant = i; bestQuadrant = quad.size(); } } return tQuadrant; } private void aimAtEnemies() { int x = (int)(Math.sin(Math.toRadians(targetAim * 1.0)) * 150); int y = (int)(Math.cos(Math.toRadians(targetAim * 1.0)) * 150); control.mouseMove(centerX + x, centerY + y); } private void monitorHealth() { if(health < 30) { System.out.println("Detected that character may die with a health ratio of " + health); control.keyPress(NEXUS_KEY); control.delay(50); control.keyRelease(NEXUS_KEY); System.exit(0); } } public void processEnemyData(List<int[]> data) { enemyQuadrants = new List[8]; processMovementCoordinateData(data, enemyQuadrants); processAimingCoordinateData(data); } // Elements of data are pairs: [magnitude, angle] // Quadrants start at North as 0. // Go around to quadrant 7 which is north north west(just west of north) private void processMovementCoordinateData(List<int[]> data, List<int[]>[] quadrants) { for(int i = 0; i < 8; i++) quadrants[i] = new ArrayList<int[]>(); for(int[] coordinate: data) { int deg = coordinate[DEGREES]; int quadrant = (deg + 15) % 360 / 45; quadrants[quadrant].add(coordinate); } } private void processAimingCoordinateData(List<int[]> data) { if(data.isEmpty()) return; int[] best = data.get(0); for(int[] coordinate: data) { if(coordinate[RADIUS] > best[RADIUS]) best = coordinate; } targetAim = best[DEGREES]; } public void processHealthData(int hp) { health = hp; } } <file_sep>/CoordinateTester.java import java.awt.*; public class CoordinateTester { public static void main(String[] args) throws Exception { // PointerInfo p = MouseInfo.getPointerInfo(); // System.out.println(p.getLocation()); // Thread.sleep(1000); Robot r = new Robot(); // int i = 700; // while(true){ // r.mouseMove(i, 500); // System.out.println(i); // i -= 20; // r.delay(100); // } Toolkit tk = Toolkit.getDefaultToolkit(); Dimension dim = tk.getScreenSize(); System.out.println(dim.width); System.out.println(dim.height); } } <file_sep>/MadGodTester.java import java.util.*; import java.awt.*; public class MadGodTester { public static void main(String[] args) { try { Robot r = new Robot(); Point[] positions = getScreenCoordinates(); Point t = positions[0]; Point l = positions[1]; MadGod m = new MadGod(r, t, l); // System.out.println("health " + m.getHP()); m.getAllies(); } catch (AWTException e) { e.printStackTrace(); } } public static Point[] getScreenCoordinates() { try { System.out.println("Place Mouse in Top Left"); Thread.sleep(5000); Point topLeft = MouseInfo.getPointerInfo().getLocation(); System.out.println("Recorded Top Left: " + topLeft); System.out.println("Place Mouse in Bottom Right"); Thread.sleep(3000); Point bottomRight = MouseInfo.getPointerInfo().getLocation(); System.out.println("Recorded Bttom Right: + bottomRight"); Point[] positions = new Point[2]; positions[0] = topLeft; positions[1] = bottomRight; return positions; } catch (Exception e) { e.printStackTrace(); System.exit(1); } return null; } }
bd0ea49028e93b94e48c66e1e0e4d37fdb596a2d
[ "Markdown", "Java" ]
4
Markdown
DavidMah/Realm-of-the-Automated-God
8ba2fd14b7e98b5e7f6720cb248353e455464015
5c0c4fb5fc7027682bb70d0e2d542d121fcb00e0
refs/heads/master
<repo_name>bshlgrs/wireworld_editor<file_sep>/test/helpers/api/worlds_helper_test.rb require 'test_helper' class Api::WorldsHelperTest < ActionView::TestCase end <file_sep>/app/models/world.rb class World < ActiveRecord::Base end <file_sep>/app/assets/javascripts/editor.js var WireworldEditor = function (canvas, world) { this.world = world; // This is for debugging purposes. window.cont = this; this.canvas = canvas; this.ctx = canvas.getContext("2d"); this.selecting = false; this.selectStart = undefined; this.selectEnd = undefined; this.colors = {"head": ["rgb(200,0,0)", "rgb(255,0,0)"], "tail": ["rgb(0,0,200)", "rgb(0,0,255)"], "wire": ["rgb(200,200,100)", "rgb(255,255,150)"]}; this.mode = "view"; this.stepTime = 100; var that = this; this.playing = false; this.drawCell = function(x, y, cellType) { if (cellType) { var startX = (x - this.world.screenX) * this.world.pixelsPerCell; var startY = (y - this.world.screenY) * this.world.pixelsPerCell; var selected = this.cellSelected(x, y) this.ctx.fillStyle = this.colors[cellType][0 + selected]; var size; if (!selected) { if (this.world.pixelsPerCell > 10) { size = this.world.pixelsPerCell - 2; } else if (this.world.pixelsPerCell > 5) { size = this.world.pixelsPerCell - 1; } else { size = this.world.pixelsPerCell; } this.ctx.fillRect(startX, startY, size, size); } else { if (this.world.pixelsPerCell > 10) { size = this.world.pixelsPerCell - 4; this.ctx.fillRect(startX + 1, startY + 1, size, size); } else if (this.world.pixelsPerCell > 5) { size = this.world.pixelsPerCell - 2; this.ctx.fillRect(startX + 1, startY + 1, size, size); } else { size = this.world.pixelsPerCell; this.ctx.fillRect(startX, startY, size, size); } } } } this.cellSelected = function (x, y) { if (this.selectStart) { var start = that.calculateCell(this.selectStart); var end = that.calculateCell(this.selectEnd); return ((start.x <= x == end.x >= x) && (start.y <= y == end.y >= y)); } return false; } this.drawWorld = function () { this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); for (var y in this.world.grid) { if (this.world.grid.hasOwnProperty(y)) { for (var x in this.world.grid[y]) { if (this.world.grid[y].hasOwnProperty(x)) { this.drawCell(x, y, this.world.grid[y][x]); } } } } if (!this.playing) { this.ctx.fillStyle = "rgba(100, 100, 200, 0.2)"; this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height); } if (this.selectStart) { if (this.selecting) { this.ctx.fillStyle = "rgba(150, 100, 256, 0.3)"; } else { this.ctx.fillStyle = "rgba(100, 100, 256, 0.2)"; } var start = that.selectStart; var end = that.selectEnd; this.ctx.fillRect(start.x, start.y, end.x - start.x, end.y - start.y); } }; this.evolve = function () { var newWorld = {}; for (var y in this.world.grid) { if (this.world.grid.hasOwnProperty(y)) { y = parseInt(y); newWorld[y] = {} for (var x in this.world.grid[y]) { if (this.world.grid[y].hasOwnProperty(x)) { x = parseInt(x); var cell = this.world.grid[y][x]; if (cell == "tail") { newWorld[y][x] = "wire"; } else if (cell == "head") { newWorld[y][x] = "tail" } else if (cell == "wire") { var count = 0; for (var dx = -1; dx <= 1; dx++) { for (var dy = -1; dy <= 1; dy++) { if (this.world.grid[y+dy] && this.world.grid[y+dy][x+dx] == "head") { count++; } }; }; if (count == 1 || count == 2) { newWorld[y][x] = "head"; } else { newWorld[y][x] = "wire"; } } } } } } this.world.grid = newWorld; this.drawWorld(); }; this.play = function () { if (!this.playing) { this.playing = true; this.evolve(); $("#play").addClass("active"); $("#pause").removeClass("active"); $("#fps").html("fps: "); setTimeout(this.step, this.stepTime); } }; this.previousTime = Date.now(); this.step = function () { if (that.playing) { setTimeout(that.step, that.stepTime); that.evolve(); $("#fps").html("fps: "+ (1000 / (Date.now() - that.previousTime))) that.previousTime = Date.now() } }; this.pause = function () { this.playing = false; $("#play").removeClass("active"); $("#pause").addClass("active"); this.drawWorld(); $("#fps").html("paused"); }; this.getMousePos = function (canvas, e) { var rect = that.ctx.canvas.getBoundingClientRect(); return { x: e.clientX - rect.left, y: e.clientY - rect.top }; } this.calculateCell = function (pos) { return {x: Math.floor(pos.x / that.world.pixelsPerCell + that.world.screenX), y: Math.floor(pos.y / that.world.pixelsPerCell + that.world.screenY)}; } this.getMouseCell = function (canvas, evt) { var pos = this.getMousePos(canvas, evt); return {x: Math.floor(pos.x / that.world.pixelsPerCell + that.world.screenX), y: Math.floor(pos.y / that.world.pixelsPerCell + that.world.screenY)}; } this.getCell = function (x, y) { return this.world.getCell(x, y); } this.placeCell = function (x, y, type) { return this.world.placeCell(x, y, type); } this.mousePressed = false; this.handleClick = function(e) { that.mousePressed = true; that.mousePos = that.getMousePos(that.canvas, e); Behaviors[that.mode].handleClick(that, e, that.getMouseCell(that.canvas, e)); e.preventDefault(); }; this.handleUnclick = function(e) { that.mousePressed = false; that.selecting = false; that.drawWorld(); if (Behaviors[that.mode].handleUnclick) { Behaviors[that.mode].handleUnclick(that, e, that.getMouseCell(that.canvas, e)) } that.lastDrawn = undefined; } this.handleDrag = function(e) { that.mousePos = that.getMousePos(that.canvas, e); var cell = that.getMouseCell(that.canvas, e); $("#coords").html(cell.x + "," + cell.y); if (that.mousePressed && Behaviors[that.mode].handleDragWhileClicked) { Behaviors[that.mode].handleDragWhileClicked(that, e, cell); } } this.drawWorld(); this.step(); $(canvas).on("mousedown", this.handleClick); $(canvas).on("mouseup", this.handleUnclick); $(canvas).mousemove(this.handleDrag); this.scalingFactor = 1.5; // What's 2.5 in the following functions? A magic number. I should probably // fix that at some point. this.zoomIn = function() { that.world.pixelsPerCell *= this.scalingFactor; that.world.screenX += that.canvas.width / (2.5*that.world.pixelsPerCell*this.scalingFactor); that.world.screenY += that.canvas.height / (2.5*that.world.pixelsPerCell*this.scalingFactor) that.drawWorld(); }; this.zoomOut = function() { that.world.screenX -= that.canvas.width / (2.5*that.world.pixelsPerCell*this.scalingFactor); that.world.screenY -= that.canvas.height / (2.5*that.world.pixelsPerCell*this.scalingFactor) that.world.pixelsPerCell /= this.scalingFactor; that.drawWorld(); }; this.clear = function () { this.world.grid = {}; this.drawWorld(); }; $("#speed-controller").on("input", function () { var newSpeed = parseInt($("#speed-controller").val()); that.stepTime = 150 - newSpeed*1.4; }) window.onload = function() { var viewportWidth = window.innerWidth; var viewportHeight = window.innerHeight; var canvasWidth = viewportWidth; var canvasHeight = viewportHeight; that.canvas.setAttribute("width", canvasWidth); that.canvas.setAttribute("height", canvasHeight); that.canvas.style.top = (viewportHeight - canvasHeight) / 2; that.canvas.style.left = (viewportWidth - canvasWidth) / 2; that.canvas.visibility = 'normal'; }; window.onresize = function () { window.onload(); that.drawWorld(); }; this.play(); this.stats = function () { var result = {"head":0, "tail": 0, "wire": 0}; for (row in this.world.grid) { if (this.world.grid.hasOwnProperty(row)) { for (cell in this.world.grid[row]) { result[this.world.grid[row][cell]] += 1; } } } return result; }; this.changeMode = function (newMode) { that.mode = newMode; $(".mode-selector").removeClass("active"); $(_.filter($(".mode-selector"), function(x) { return $(x).data("mode") == newMode; })[0]).addClass("active"); }; var key_bindings = { 86: "view", 73: "ignite", 80: "pen", 83: "select", 77: "move", 68: "douse", 69: "erase"}; $("body").keydown(" ", function (e) { if (e.which == 32) { if (that.playing) { that.pause(); } else { that.play(); } } else if (key_bindings[e.which]) { that.changeMode(key_bindings[e.which]); } }); $(".mode-selector").on("click", function (e) { that.changeMode($(e.currentTarget).data('mode')); }); $("#play").on("click", function(e) { that.play(); }); $("#pause").on("click", function(e) { that.pause(); }); $("#step").on("click", function(e) { that.evolve(); }); $("#clear").on("click", function (e) { that.clear(); }); $("#save").on('click', function (e) { that.world.save(); }); $("#zoom_in").on('click',function(e){ that.zoomIn(); }); $("#zoom_out").on('click',function(e){ that.zoomOut(); }); $("#filename").html(this.world.name); }; <file_sep>/app/assets/javascripts/behaviors.js $(function () { var Behaviors = window.Behaviors = {}; var deselect = function (that) { that.selecting = false; that.selectStart = undefined; that.selectEnd = undefined; } Behaviors.view = { handleClick: function (that, e, cell) { deselect(that); var pos = that.getMousePos(that.canvas, e); that.dragX = pos.x; that.dragY = pos.y; }, handleDragWhileClicked: function (that, e, cell) { var pos = that.getMousePos(that.canvas, e); that.world.screenX += (that.dragX - pos.x)/that.world.pixelsPerCell; that.world.screenY += (that.dragY - pos.y)/that.world.pixelsPerCell; that.dragX = pos.x; that.dragY = pos.y; that.drawWorld(); } }; Behaviors.pen = { handleClick: function (that, e, cell) { deselect(that); if (!that.getCell(cell.x, cell.y)) { that.placeCell(cell.x, cell.y, "wire"); that.lastDrawn = cell; that.drawWorld(); } }, handleDragWhileClicked: function (that, e, cell) { if (!that.getCell(cell.x, cell.y)) { if (that.lastDrawn) { Helper.drawLine(that.lastDrawn.x, that.lastDrawn.y, cell.x, cell.y, function (x, y) { that.placeCell(x, y, "wire"); }); } else { that.placeCell(cell.x, cell.y, "wire"); } that.lastDrawn = cell; that.drawWorld(); } } }; Behaviors.ignite = { handleClick: function (that, e, cell) { deselect(that); if (that.getCell(cell.x, cell.y) == "wire") { that.placeCell(cell.x, cell.y, "head"); that.lastDrawn = cell; that.drawWorld(); } }, handleDragWhileClicked: function(that, e, cell) { if (that.lastDrawn && (cell.x != that.lastDrawn.x || cell.y != that.lastDrawn.y)) { if (that.getCell(cell.x, cell.y) == "wire" || that.getCell(cell.x, cell.y) == "head") { that.placeCell(cell.x, cell.y, "tail"); that.lastDrawn = undefined; that.drawWorld(); } } } } Behaviors.douse = { handleClick : function (that, e, cell) { deselect(that); if (that.getCell(cell.x, cell.y) == "head") { that.placeCell(cell.x, cell.y, "tail"); that.drawWorld(); } }, handleDragWhileClicked: function (that, e, cell) { if (that.getCell(cell.x, cell.y) == "head") { that.placeCell(cell.x, cell.y, "tail"); that.drawWorld(); } } } Behaviors.erase = { handleClick : function (that, e, cell) { deselect(that); that.placeCell(cell.x, cell.y, undefined); that.drawWorld(); }, handleDragWhileClicked: function (that, e, cell) { that.placeCell(cell.x, cell.y, undefined); that.drawWorld(); } } Behaviors.select = { handleClick : function (that, e, cell) { if (that.selectStart && that.cellSelected(cell.x, cell.y)) { that.moving = true; // If the cursor is inside the area already selected... // we want to move the selection console.log("moving"); that.lastDrawn = cell; } else { // we want to select that.selecting = true; that.selectStart = that.selectEnd = that.getMousePos(that.canvas, e); } that.drawWorld(); }, handleDragWhileClicked : function (that, e, cell) { if (that.moving) { // TODO: I need to move the box around here. } else { that.selectEnd = that.getMousePos(that.canvas, e); } that.drawWorld(); }, handleUnclick : function (that, e, cell) { that.selecting = false; that.drawWorld(); } } Behaviors.move = { handleClick : function (that, e, cell) { deselect(that); that.selectedCellType = that.getCell(cell.x, cell.y); that.lastDrawn = cell; }, handleDragWhileClicked : function (that, e, cell) { if (that.selectedCellType) { if (that.lastDrawn && (cell.x != that.lastDrawn.x || cell.y != that.lastDrawn.y)) { that.placeCell(that.lastDrawn.x, that.lastDrawn.y, undefined); that.placeCell(cell.x, cell.y, that.selectedCellType); that.lastDrawn = cell; that.drawWorld(); } } } } });<file_sep>/db/migrate/20141207224858_unfuck_worlds.rb class UnfuckWorlds < ActiveRecord::Migration def change remove_column :worlds, :contents add_column :worlds, :grid, :string add_column :worlds, :pixels_per_cell, :integer add_column :worlds, :screen_x, :integer add_column :worlds, :screen_y, :integer create_table :users do |t| t.string :username, :null => false t.string :password_digest, :null => false t.string :session_token, :null => false t.timestamps end add_index :users, :username, :unique => true add_index :users, :session_token, :unique => true end end <file_sep>/test/helpers/worlds_helper_test.rb require 'test_helper' class WorldsHelperTest < ActionView::TestCase end <file_sep>/app/controllers/worlds_controller.rb class WorldsController < ApplicationController def show @world = World.find(params[:id]) end end <file_sep>/app/helpers/api/worlds_helper.rb module Api::WorldsHelper end <file_sep>/config/routes.rb Rails.application.routes.draw do resources :worlds, only: [:show] root :to => 'main#main' namespace :api do resources :worlds, :except => [:new, :edit] end end <file_sep>/app/controllers/api/worlds_controller.rb class Api::WorldsController < ApplicationController def create @world = World.create(world_params) @world.grid = params[:world][:grid] # todo: user id @world.save! render :json => @world end def update world = World.find(params[:id]) world.update_attributes(world_params) world.grid = params[:world][:grid] world.save! render :json => {"status" => "success"} end def index render :json => World.all end def show render :json => World.find(params[:id]) end def delete end def world_params params.require(:world).permit([ :name, :description, :pixels_per_cell, :screen_x, :screen_y]) end end <file_sep>/app/assets/javascripts/drawing_helper.js $(function () { var Helper = window.Helper = {}; Helper.drawLine = function(x0, y0, x1, y1, callback) { var dx = x1 - x0; var dy = y1 - y0; var xo = 1; var yo = 1; if (x1 == x0){ xo = 0; } if (y1 == y0){ yo=0 } if (y0 > y1){ var py = -1; var yf = y1-1; }else{ var py = 1; var yf = y1+1; } if (x0 > x1){ var px = -1; var xf = x1-1; }else{ var px = 1; var xf = x1+1; } if (Math.abs(dx) >= Math.abs(dy)){ var D = (2*dy - dx); callback(x0,y0); var y = y0; var x = x0; for (x = (x0+px); x != xf; x = x+px){ if ((D*yo) > 0){ y = y+py; callback(x,y); D = D + py*(2*dy-2*dx); } else { callback(x,y); D = D + py*(2*dy); } } } else { var D = (2*dx - dy); callback(x0,y0); var y = y0; var x = x0; for (y = (y0+py); y != yf; y = y+py){ if ((D*xo) > 0){ x = x+px; callback(x,y); D = D + px*(2*dx-2*dy); } else { callback(x,y); D = D + px*(2*dx); } } } }; })
ecd2c1b8b01af8cb777ddf4580d8361776fe313f
[ "JavaScript", "Ruby" ]
11
Ruby
bshlgrs/wireworld_editor
c9a653f4f40266b4b426116487677564640f1f4a
799fa7fcbbeee4c971bec3de0c6a5c3256d85cb2
refs/heads/master
<repo_name>Supowang/stm32_lwip<file_sep>/README.md # stm32_lwip lwip port to stm32 <file_sep>/STM32F103RC/Src/main.c /** ****************************************************************************** * File Name : main.c * Description : Main program body ****************************************************************************** * This notice applies to any and all portions of this file * that are not between comment pairs USER CODE BEGIN and * USER CODE END. Other portions of this file, whether * inserted by the user or by software development tools * are owned by their respective copyright owners. * * Copyright (c) 2018 STMicroelectronics International N.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted, provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of other * contributors to this software may be used to endorse or promote products * derived from this software without specific written permission. * 4. This software, including modifications and/or derivative works of this * software, must execute solely and exclusively on microcontroller or * microprocessor devices manufactured by or for STMicroelectronics. * 5. Redistribution and use of this software other than as permitted under * this license is void and will automatically terminate your rights under * this license. * * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "stm32f1xx_hal.h" #include "fatfs.h" #include "sdio.h" #include "spi.h" #include "usart.h" #include "gpio.h" extern void lwip_demo(void *pdata); /* USER CODE BEGIN Includes */ /* USER CODE END Includes */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ /* Private variables ---------------------------------------------------------*/ FATFS fs; FIL file; FRESULT f_res; UINT fnum; BYTE ReadBuffer[1024]={0}; BYTE WriteBuffer[]= "Welcome to supowang\r\n"; /* USER CODE END PV */ static void printf_fatfs_error(FRESULT fresult); /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); unsigned int sys_now(void) { return HAL_GetTick(); } /* USER CODE BEGIN PFP */ /* Private function prototypes -----------------------------------------------*/ /* USER CODE END PFP */ /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ int main(void) { /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /* MCU Configuration----------------------------------------------------------*/ /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init(); /* USER CODE BEGIN Init */ /* USER CODE END Init */ /* Configure the system clock */ SystemClock_Config(); /* USER CODE BEGIN SysInit */ /* USER CODE END SysInit */ /* Initialize all configured peripherals */ MX_GPIO_Init(); MX_SPI1_Init(); MX_USART1_UART_Init(); MX_USART2_UART_Init(); MX_SDIO_SD_Init(); MX_FATFS_Init(); /* USER CODE BEGIN 2 */ /* ๅ‘ไธฒๅฃ1ๅ‘้€ๅผ€ๆœบๅญ—็ฌฆ */ /* printf("**** (C) COPYRIGHT 2013 ๅˆถ้€ ่€…็ง‘ๆŠ€ *******\r\n"); //ใ€‚ printf("* *\r\n"); printf("* *\r\n"); printf("* MCUๅนณๅฐ:STM32F103RCT6 *\r\n"); printf("* ไปฅๅคช็ฝ‘็กฌไปถ:ENC28J60 *\r\n"); printf("* ๅ›บไปถๅบ“๏ผš3.5 *\r\n"); printf("* ไพ‹็จ‹็‰ˆๆœฌ: 0.2 *\r\n"); printf("* *\r\n"); printf("***************************************************\r\n"); */ printf("****** ๅณๅฐ†่ฟ›่กŒๆต‹่ฏ•... ******\r\n"); if(retSD == 0) { //ๅœจSDๅกๆŒ‚่ฝฝๆ–‡ไปถ็ณป็ปŸ๏ผŒๆ–‡ไปถ็ณป็ปŸๆŒ‚่ฝฝๆ—ถไผšๅฏนSDๅกๅˆๅง‹ๅŒ– f_res = f_mount(&fs,(TCHAR const*)SDPath,1); printf_fatfs_error(f_res); /*----------------------- ๆ ผๅผๅŒ–ๆต‹่ฏ• ---------------------------*/ /* ๅฆ‚ๆžœๆฒกๆœ‰ๆ–‡ไปถ็ณป็ปŸๅฐฑๆ ผๅผๅŒ–ๅˆ›ๅปบๅˆ›ๅปบๆ–‡ไปถ็ณป็ปŸ */ if(f_res == FR_NO_FILESYSTEM) { printf("ใ€‹SDๅก่ฟ˜ๆฒกๆœ‰ๆ–‡ไปถ็ณป็ปŸ๏ผŒๅณๅฐ†่ฟ›่กŒๆ ผๅผๅŒ–...\r\n"); /* ๆ ผๅผๅŒ– */ f_res=f_mkfs((TCHAR const*)SDPath,0,0); if(f_res == FR_OK) { printf("ใ€‹SDๅกๅทฒๆˆๅŠŸๆ ผๅผๅŒ–ๆ–‡ไปถ็ณป็ปŸใ€‚\r\n"); /* ๆ ผๅผๅŒ–ๅŽ๏ผŒๅ…ˆๅ–ๆถˆๆŒ‚่ฝฝ */ f_res = f_mount(NULL,(TCHAR const*)SDPath,1); /* ้‡ๆ–ฐๆŒ‚่ฝฝ */ f_res = f_mount(&fs,(TCHAR const*)SDPath,1); } else { printf("ใ€Šใ€Šๆ ผๅผๅŒ–ๅคฑ่ดฅใ€‚ใ€‹ใ€‹\r\n"); while(1); } } else if(f_res!=FR_OK) { printf("๏ผ๏ผSDๅกๆŒ‚่ฝฝๆ–‡ไปถ็ณป็ปŸๅคฑ่ดฅใ€‚(%d)\r\n",f_res); printf_fatfs_error(f_res); while(1); } else { printf("ใ€‹ๆ–‡ไปถ็ณป็ปŸๆŒ‚่ฝฝๆˆๅŠŸ๏ผŒๅฏไปฅ่ฟ›่กŒ่ฏปๅ†™ๆต‹่ฏ•\r\n"); } /*----------------------- ๆ–‡ไปถ็ณป็ปŸๆต‹่ฏ•๏ผšๅ†™ๆต‹่ฏ• -----------------------------*/ /* ๆ‰“ๅผ€ๆ–‡ไปถ๏ผŒๅฆ‚ๆžœๆ–‡ไปถไธๅญ˜ๅœจๅˆ™ๅˆ›ๅปบๅฎƒ */ printf("****** ๅณๅฐ†่ฟ›่กŒๆ–‡ไปถๅ†™ๅ…ฅๆต‹่ฏ•... ******\r\n"); f_res = f_open(&file, "FatFs.txt",FA_CREATE_ALWAYS | FA_WRITE ); if ( f_res == FR_OK ) { printf("ใ€‹ๆ‰“ๅผ€/ๅˆ›ๅปบFatFs่ฏปๅ†™ๆต‹่ฏ•ๆ–‡ไปถ.txtๆ–‡ไปถๆˆๅŠŸ๏ผŒๅ‘ๆ–‡ไปถๅ†™ๅ…ฅๆ•ฐๆฎใ€‚\r\n"); /* ๅฐ†ๆŒ‡ๅฎšๅญ˜ๅ‚จๅŒบๅ†…ๅฎนๅ†™ๅ…ฅๅˆฐๆ–‡ไปถๅ†… */ f_res=f_write(&file,WriteBuffer,sizeof(WriteBuffer),&fnum); if(f_res==FR_OK) { printf("ใ€‹ๆ–‡ไปถๅ†™ๅ…ฅๆˆๅŠŸ๏ผŒๅ†™ๅ…ฅๅญ—่Š‚ๆ•ฐๆฎ๏ผš%d\r\n",fnum); printf("ใ€‹ๅ‘ๆ–‡ไปถๅ†™ๅ…ฅ็š„ๆ•ฐๆฎไธบ๏ผš\r\n%s\r\n",WriteBuffer); } else { printf("๏ผ๏ผๆ–‡ไปถๅ†™ๅ…ฅๅคฑ่ดฅ๏ผš(%d)\r\n",f_res); } /* ไธๅ†่ฏปๅ†™๏ผŒๅ…ณ้—ญๆ–‡ไปถ */ f_close(&file); } else { printf("๏ผ๏ผๆ‰“ๅผ€/ๅˆ›ๅปบๆ–‡ไปถๅคฑ่ดฅใ€‚\r\n"); } /*------------------- ๆ–‡ไปถ็ณป็ปŸๆต‹่ฏ•๏ผš่ฏปๆต‹่ฏ• ------------------------------------*/ printf("****** ๅณๅฐ†่ฟ›่กŒๆ–‡ไปถ่ฏปๅ–ๆต‹่ฏ•... ******\r\n"); f_res = f_open(&file, "FatFs.txt", FA_OPEN_EXISTING | FA_READ); if(f_res == FR_OK) { printf("ใ€‹ๆ‰“ๅผ€ๆ–‡ไปถๆˆๅŠŸใ€‚\r\n"); f_res = f_read(&file, ReadBuffer, sizeof(ReadBuffer), &fnum); if(f_res==FR_OK) { printf("ใ€‹ๆ–‡ไปถ่ฏปๅ–ๆˆๅŠŸ,่ฏปๅˆฐๅญ—่Š‚ๆ•ฐๆฎ๏ผš%d\r\n",fnum); printf("ใ€‹่ฏปๅ–ๅพ—็š„ๆ–‡ไปถๆ•ฐๆฎไธบ๏ผš\r\n%s \r\n", ReadBuffer); } else { printf("๏ผ๏ผๆ–‡ไปถ่ฏปๅ–ๅคฑ่ดฅ๏ผš(%d)\r\n",f_res); } } else { printf("๏ผ๏ผๆ‰“ๅผ€ๆ–‡ไปถๅคฑ่ดฅใ€‚\r\n"); } /* ไธๅ†่ฏปๅ†™๏ผŒๅ…ณ้—ญๆ–‡ไปถ */ f_close(&file); /* ไธๅ†ไฝฟ็”จ๏ผŒๅ–ๆถˆๆŒ‚่ฝฝ */ f_res = f_mount(NULL,(TCHAR const*)SDPath,1); /* ๆณจ้”€ไธ€ไธชFatFS่ฎพๅค‡๏ผšSDๅก */ FATFS_UnLinkDriver(SDPath); } lwip_demo(NULL); //ๅˆๅง‹ๅŒ–ๅ†…ๆ ธ๏ผŒๅฏๅŠจLwIP็›ธๅ…ณ /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { /* USER CODE END WHILE */ printf("Welcome to here\r\n"); HAL_Delay(1000); /* USER CODE BEGIN 3 */ } /* USER CODE END 3 */ } /** System Clock Configuration */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct; RCC_ClkInitTypeDef RCC_ClkInitStruct; /**Initializes the CPU, AHB and APB busses clocks */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { _Error_Handler(__FILE__, __LINE__); } /**Initializes the CPU, AHB and APB busses clocks */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK) { _Error_Handler(__FILE__, __LINE__); } /**Configure the Systick interrupt time */ HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000); /**Configure the Systick */ HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK); /* SysTick_IRQn interrupt configuration */ HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0); } /* USER CODE BEGIN 4 */ /** * ๅ‡ฝๆ•ฐๅŠŸ่ƒฝ: FatFSๆ–‡ไปถ็ณป็ปŸๆ“ไฝœ็ป“ๆžœไฟกๆฏๅค„็†. * ่พ“ๅ…ฅๅ‚ๆ•ฐ: FatFSๆ–‡ไปถ็ณป็ปŸๆ“ไฝœ็ป“ๆžœ๏ผšFRESULT * ่ฟ” ๅ›ž ๅ€ผ: ๆ—  * ่ฏด ๆ˜Ž: ๆ—  */ static void printf_fatfs_error(FRESULT fresult) { switch(fresult) { case FR_OK: //(0) printf("ใ€‹ๆ“ไฝœๆˆๅŠŸใ€‚\r\n"); break; case FR_DISK_ERR: //(1) printf("๏ผ๏ผ็กฌไปถ่พ“ๅ…ฅ่พ“ๅ‡บ้ฉฑๅŠจๅ‡บ้”™ใ€‚\r\n"); break; case FR_INT_ERR: //(2) printf("๏ผ๏ผๆ–ญ่จ€้”™่ฏฏใ€‚\r\n"); break; case FR_NOT_READY: //(3) printf("๏ผ๏ผ็‰ฉ็†่ฎพๅค‡ๆ— ๆณ•ๅทฅไฝœใ€‚\r\n"); break; case FR_NO_FILE: //(4) printf("๏ผ๏ผๆ— ๆณ•ๆ‰พๅˆฐๆ–‡ไปถใ€‚\r\n"); break; case FR_NO_PATH: //(5) printf("๏ผ๏ผๆ— ๆณ•ๆ‰พๅˆฐ่ทฏๅพ„ใ€‚\r\n"); break; case FR_INVALID_NAME: //(6) printf("๏ผ๏ผๆ— ๆ•ˆ็š„่ทฏๅพ„ๅใ€‚\r\n"); break; case FR_DENIED: //(7) case FR_EXIST: //(8) printf("๏ผ๏ผๆ‹’็ป่ฎฟ้—ฎใ€‚\r\n"); break; case FR_INVALID_OBJECT: //(9) printf("๏ผ๏ผๆ— ๆ•ˆ็š„ๆ–‡ไปถๆˆ–่ทฏๅพ„ใ€‚\r\n"); break; case FR_WRITE_PROTECTED: //(10) printf("๏ผ๏ผ้€ป่พ‘่ฎพๅค‡ๅ†™ไฟๆŠคใ€‚\r\n"); break; case FR_INVALID_DRIVE: //(11) printf("๏ผ๏ผๆ— ๆ•ˆ็š„้€ป่พ‘่ฎพๅค‡ใ€‚\r\n"); break; case FR_NOT_ENABLED: //(12) printf("๏ผ๏ผๆ— ๆ•ˆ็š„ๅทฅไฝœๅŒบใ€‚\r\n"); break; case FR_NO_FILESYSTEM: //(13) printf("๏ผ๏ผๆ— ๆ•ˆ็š„ๆ–‡ไปถ็ณป็ปŸใ€‚\r\n"); break; case FR_MKFS_ABORTED: //(14) printf("๏ผ๏ผๅ› ๅ‡ฝๆ•ฐๅ‚ๆ•ฐ้—ฎ้ข˜ๅฏผ่‡ดf_mkfsๅ‡ฝๆ•ฐๆ“ไฝœๅคฑ่ดฅใ€‚\r\n"); break; case FR_TIMEOUT: //(15) printf("๏ผ๏ผๆ“ไฝœ่ถ…ๆ—ถใ€‚\r\n"); break; case FR_LOCKED: //(16) printf("๏ผ๏ผๆ–‡ไปถ่ขซไฟๆŠคใ€‚\r\n"); break; case FR_NOT_ENOUGH_CORE: //(17) printf("๏ผ๏ผ้•ฟๆ–‡ไปถๅๆ”ฏๆŒ่Žทๅ–ๅ †็ฉบ้—ดๅคฑ่ดฅใ€‚\r\n"); break; case FR_TOO_MANY_OPEN_FILES: //(18) printf("๏ผ๏ผๆ‰“ๅผ€ๅคชๅคšๆ–‡ไปถใ€‚\r\n"); break; case FR_INVALID_PARAMETER: // (19) printf("๏ผ๏ผๅ‚ๆ•ฐๆ— ๆ•ˆใ€‚\r\n"); break; } } /* USER CODE END 4 */ /** * @brief This function is executed in case of error occurrence. * @param None * @retval None */ void _Error_Handler(char * file, int line) { /* USER CODE BEGIN Error_Handler_Debug */ /* User can add his own implementation to report the HAL error return state */ while(1) { } /* USER CODE END Error_Handler_Debug */ } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t* file, uint32_t line) { /* USER CODE BEGIN 6 */ /* User can add his own implementation to report the file name and line number, ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* USER CODE END 6 */ } #endif /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
03589bd37e6e8c51db9081f555b606ca31764f5c
[ "Markdown", "C" ]
2
Markdown
Supowang/stm32_lwip
38312e11005437da4485092dfaa554a86f8912ea
4512be2a65d6d2df31047801f269a24bd0d6ca6c
refs/heads/master
<repo_name>juanpablogd/Secad<file_sep>/Scripts/Login/scripts.js var socket = io.connect(Config.UrlSocketLogin+'/web'); $(document).ready(function () { $("#ingresar").click(function () { if (!$("#usuario").val()) { bootbox.alert("por favor ingrese el nombre de usuario", function () {}); $("#usuario").focus() } else if (!$("#contrasena").val()) { bootbox.alert("por favor ingrese la contraseรฑa", function () {}); $("#contrasena").focus(); } else { var usuario = $("#usuario").val(); var login = $("#contrasena").val(); var modulo = $("#modulo").val(); var data= {'usr': usuario,'mod': modulo,'pas': login}; var DataAES =Func.Ecrypted(data); socket.emit('LoginUsuario',DataAES,function(data){ var dat=Func.Decrypted(data); if (dat.length>0){ localStorage.dt=data; bootbox.alert("Bienvenido, " + dat[0].nombre, function () {}); window.location.assign(Config.NextLogin); }else{ localStorage.clear(); bootbox.alert("Usuario no encontrado!", function () {}) } }); } }); });<file_sep>/Scripts/Func.js var Func={ Decrypted : function (message) { try { var text=CryptoJS.AES.decrypt(message,Config.cl).toString(CryptoJS.enc.Utf8) } catch(err) { this.CerrarAPP(); return false; } if(text==''){ this.CerrarAPP(); return false; }else{ var decrypted =JSON.parse(CryptoJS.AES.decrypt(message,Config.cl).toString(CryptoJS.enc.Utf8)); return decrypted; } }, Ecrypted: function (json){ var ciphertext = CryptoJS.AES.encrypt(JSON.stringify(json), Config.cl); return ciphertext.toString(); }, DataLogin: function (){ var DatosUsuario=this.Decrypted(localStorage.dt); return DatosUsuario; }, GetNombre: function (){ var data=this.DataLogin(); return data[0].nombre; }, GetIdPerfil: function (){ var data=this.DataLogin(); return data[0].id_perfil; }, GetAdmin: function (){ var data=this.DataLogin(); if(data[0].id_perfil_admin==24){ return true; }else{ return false; } }, GetHoraLogin: function (){ var data=this.DataLogin(); return data[0].hora; }, GetCl: function (){ var data=this.DataLogin(); return data[0].contrasegna; }, GetUsuario: function (){ var data=this.DataLogin(); return data[0].usuario; }, CerrarAPP: function(){ localStorage.clear(); window.location.assign("../Login/index.html"); }, ValidaUsuario: function(){ if(!localStorage.dt){ this.CerrarAPP(); }else{ var id_perfil=this.GetIdPerfil(); if(Config.id_perfil.indexOf(id_perfil)<0){ this.CerrarAPP(); } } }, IntevaloLogin:function(){ var app=this app.ValidaUsuario(); setInterval(function(){ console.log('Valido'); app.ValidaUsuario(); }, 1000*5); }, degToRad:function(deg) { return deg * Math.PI * 2 / 360; } } <file_sep>/Scripts/Config.js var Config={ UrlSocketLogin: 'http://saga.cundinamarca.gov.co:4171', UrlSocket: 'http://saga.cundinamarca.gov.co:3377', cl:'1erf2a5f1e87g1', NextLogin:'../Home/', // TABLA public.p_perfil id_perfil:[21,18], // tipo 'C' id_perfil_admin:[24,68] // tipo 'A' };
580e095df4874ce3eaac3a9b3b6478e885290fb0
[ "JavaScript" ]
3
JavaScript
juanpablogd/Secad
e9b1f3788f2d5c40de11d23fc161ce5385b76e13
f30bb7919c57c915b128aeeb735cef05bc18660c
refs/heads/master
<repo_name>tianxingjian/TestJdom<file_sep>/src/cn/com/arap/ReceiveDataRead.java package cn.com.arap; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import java.util.List; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.jdom.xpath.XPath; public class ReceiveDataRead { public static void paraseXml(InputStream source){ SAXBuilder sax = new SAXBuilder(); try { Document doc = sax.build(source); Element rootEle = doc.getRootElement(); Element baseInfo = (Element)XPath.selectSingleNode(rootEle, "//data/basedata"); Element billtype = baseInfo.getChild("billtype"); Element billData = (Element)XPath.selectSingleNode(rootEle, "//data/aggVo"); Element head = billData.getChild("head"); Element bodys = billData.getChild("bodys"); } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String args[]){ InputStream in = null; try { in = new FileInputStream("src/recbillData.xml"); paraseXml(in); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(in != null){ try { in.close(); } catch (IOException e) { System.out.println("รŽร„ยผรพยนร˜ยฑร•ยณรถยดรญยฃยก"); } } } } } <file_sep>/src/com/why/jdom/ReadXML.java package com.why.jdom; import java.io.IOException; import java.util.Iterator; import java.util.List; import org.jdom.input.SAXBuilder; import org.jdom.xpath.XPath; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; public class ReadXML { /** * @param args */ public static void main(String[] args) { SAXBuilder sax = new SAXBuilder(); try { Document doc = sax.build("src/config.xml"); Element rootEle = doc.getRootElement(); Element driverClassNameElement = (Element)XPath.selectSingleNode(rootEle, "//sys-config/jdbc-info/driver-class-name"); String driverClassName = driverClassNameElement.getText(); System.out.println("driverClassName = " + driverClassName); List provinceList = XPath.selectNodes(rootEle, "//sys-config/provinces-info/province"); for(Iterator it = provinceList.iterator();it.hasNext();){ Element provinceEle = (Element)it.next(); String proId = provinceEle.getAttributeValue("id"); String proName = provinceEle.getAttributeValue("name"); System.out.println("provinceId = " + proId + " provinceName = " + proName); List cityEleList = (List)provinceEle.getChildren("city"); for(Iterator cityIt = cityEleList.iterator();cityIt.hasNext();){ Element cityEle = (Element)cityIt.next(); String cityId = cityEle.getAttributeValue("id"); String cityName = cityEle.getText(); System.out.println(" cityId = " + cityId + " cityName = " + cityName); } } } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } <file_sep>/test/cn/com/TxtFileReaderTest.java package cn.com; import java.security.KeyStore.Entry; import java.util.Iterator; import java.util.Map; import nc.ui.pub.file.TxtFileReader; import org.junit.Test; public class TxtFileReaderTest { @Test public void test() throws Exception { String path = "test/ๆ•ฐๆฎๅฏผๅ…ฅๆ ผๅผ.txt"; TxtFileReader reader = new TxtFileReader(); reader.openFile(path); Map<String, String[][]> map = reader.readFile(); Iterator<Map.Entry<String, String[][]>> entrys = map.entrySet().iterator(); while(entrys.hasNext()){ Map.Entry<String, String[][]> entry = entrys.next(); System.out.println(entry.getKey() + " - > " + entry.getValue()); String [][]tmp = entry.getValue(); for(int i = 0; i < tmp.length; i ++){ for(int j = 0; j < tmp[i].length; j++){ System.out.print(tmp[i][j] + "\t"); } } } } } <file_sep>/src/nc/ui/pub/file/TxtFileReader.java package nc.ui.pub.file; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import nc.vo.pub.BusinessException; public class TxtFileReader { /** ๅ˜้‡ๅฎšไน‰ */ private FileInputStream fileIn = null; private String rBreak = "\\|";//้ป˜่ฎค็š„ๆ‹†่กŒๅˆ†ๅ‰ฒ็ฌฆ private String cBreak = ":";//้ป˜่ฎค็š„ๆ‹†ๅˆ—ๅˆ†ๅ‰ฒ็ฌฆ private int keyIndex = 0; //keyๅ€ผ็ดขๅผ•ๅˆ— private String m_sFilePath; public void setrBreak(String rBreak) { this.rBreak = rBreak; } public void setcBreak(String cBreak) { this.cBreak = cBreak; } public void setKeyIndex(int keyIndex) { this.keyIndex = keyIndex; } public void closeFile() throws BusinessException{ try { this.fileIn.close(); } catch (IOException e) { throw new BusinessException("ๆ–‡ไปถๅ…ณ้—ญๅคฑ่ดฅ๏ผ"); }finally{ this.fileIn =null; } } public void openFile(String sPath) throws Exception { m_sFilePath = sPath; File file = new File(m_sFilePath); if (!file.exists()) { throw new Exception("็›ฎๆ ‡ๆ–‡ไปถ่ฎฟ้—ฎๅคฑ่ดฅ๏ผš" + m_sFilePath); } try { fileIn = new FileInputStream(m_sFilePath); } catch (Exception ne) { fileIn = null; throw new Exception("ๆ–‡ไปถๆ‰“ๅผ€ๅคฑ่ดฅ๏ผ"); } } public Map<String, String[][]> readFile() throws BusinessException, UnsupportedEncodingException{ if(fileIn == null){ throw new BusinessException("ๆ–‡ไปถๆ‰“ๅผ€ๅคฑ่ดฅ๏ผ"); } Map<String, String[][]> record = new HashMap<String, String[][]>(); InputStreamReader reader = null; BufferedReader bufferReader = null; reader = new InputStreamReader(fileIn, "UTF-8"); bufferReader = new BufferedReader(reader); String line; String[][] array = null; int count = 0; ImpDataVO dataVO = null; try { while ((line=bufferReader.readLine())!=null){ dataVO = processLine(line); record.put(dataVO.getKey(), dataVO.getArray()); count++; } } catch (IOException e) { throw new BusinessException("็ฌฌ[" + count + "]่กŒๆ–‡ไปถ่ฏปๅ–ๅคฑ่ดฅ๏ผ"); }finally{ try { bufferReader.close(); } catch (IOException e) { throw new BusinessException("ๆ–‡ไปถๅ…ณ้—ญๅคฑ่ดฅ๏ผ"); }finally{ bufferReader = null; } try { reader.close(); } catch (IOException e) { throw new BusinessException("ๆ–‡ไปถๅ…ณ้—ญๅคฑ่ดฅ๏ผ"); }finally{ reader = null; } closeFile(); } return record; } private ImpDataVO processLine(String lineStr){ String keyStr = null; String[]tables = lineStr.split(rBreak); List<String[]> list = new ArrayList<String[]>(); for(int i = 0; i < tables.length; i++){ if(i == keyIndex){ continue; } String[]rows = tables[i].split(cBreak); list.add(rows); } keyStr = tables[keyIndex]; return new ImpDataVO(keyStr, list.toArray(new String[0][0])); } }
552a7ab00e6f09ed633caf73cfce416ca382c0a2
[ "Java" ]
4
Java
tianxingjian/TestJdom
703a468f8c525b4ed317014dacea69bc937d560f
a33ca92919e18031718e6358f952e83d6e923f96
refs/heads/master
<file_sep>import pygame ############################################################################### #๊ธฐ๋ณธ ์ดˆ๊ธฐํ™” (๋ฐ˜๋“œ์‹œ ํ•ด์•ผํ•˜๋Š” ๊ฒƒ๋“ค) pygame.init() #์ดˆ๊ธฐํ™” ๋ฐ˜๋“œ์‹œ ํ•„์š”ํ•จ # ํ™”๋ฉด ํฌ๊ธฐ ์„ค์ • screen_width = 480 screen_height = 640 screen = pygame.display.set_mode((screen_width,screen_height)) #ํ™”๋ฉด ํƒ€์ดํ‹€ ์„ค์ • pygame.display.set_caption("EL Game")#๊ฒŒ์ž„ ์ด๋ฆ„ #FPS clock = pygame.time.Clock() ################################################################################# # 1. ์‚ฌ์šฉ์ž ๊ฒŒ์ž„ ์ดˆ๊ธฐํ™”(๋ฐฐ๊ฒฝํ™”๋ฉด, ๊ฒŒ์ž„ ์ด๋ฏธ์ง€, ์ขŒํ‘œ, ์†๋„,์ , ํฐํŠธ ๋“ฑ) # ์ด๋ฒคํŠธ ๋ฃจํ”„ running = True #๊ฒŒ์ž„์ด ์ง„ํ–‰์ค‘์ธ๊ฐ€? while running: dt = clock.tick(30) #๊ฒŒ์ž„ํ™”๋ฉด์˜ ์ดˆ๋‹น ํ”„๋ ˆ์ž„ ์ˆ˜ ์„ค์ • #2. ์ด๋ฒคํŠธ ์ฒ˜๋ฆฌ print("fps : "+str(clock.get_fps())) for event in pygame.event.get(): #์–ด๋–ค ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€๋Š”๊ฐ€? if event.type == pygame.QUIT: #์ฐฝ์ด ๋‹ซํžˆ๋Š” ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€๋Š”๊ฐ€? running = False #๊ฒŒ์ž„์ด ์ง„ํ–‰์ค‘์ด ์•„๋‹ˆ๋‹ค. if event.type==pygame.KEYDOWN: #ํ‚ค๊ฐ€ ๋ˆŒ๋ ธ๋Š”์ง€ ํ™•์ธ if event.key==pygame.K_LEFT: to_x-= character_speed elif event.key==pygame.K_RIGHT: to_x += character_speed elif event.key == pygame.K_UP: to_y -= character_speed elif event.key == pygame.K_DOWN: to_y += character_speed if event.type == pygame.KEYUP: #๋ฐฉํ–ฅํ‚ค๋ฅผ ๋–ผ๋ฉด ๋ฉˆ์ถค if event.key == pygame.K_LEFT or event.key==pygame.K_RIGHT: to_x = 0 elif event.key == pygame.K_UP or event.key==pygame.K_DOWN: to_y = 0 character_x_pos += to_x*dt character_y_pos += to_y*dt #๊ฐ€๋กœ ๊ฒฝ๊ณ„๊ฐ’ ์ฒ˜๋ฆฌ if character_x_pos < 0: character_x_pos = 0 elif character_x_pos > screen_width - character_width: character_x_pos = screen_width - character_width #์„ธ๋กœ ๊ฒฝ๊ณ„๊ฐ’ ์ฒ˜๋ฆฌ if character_y_pos < 0: character_y_pos = 0 elif character_y_pos > screen_height - character_height: character_y_pos = screen_height - character_height #์ถฉ๋Œ์ฒ˜๋ฆฌ character_rect = character.get_rect() character_rect.left = character_x_pos #์‹ค์‹œ๊ฐ„์œผ๋กœ ์œ„์น˜ ์—…๋ฐ์ดํŠธ character_rect.top = character_y_pos enemy_rect = enemy.get_rect() enemy_rect.left = enemy_x_pos enemy_rect.top = enemy_y_pos if character_rect.colliderect(enemy_rect): #์ถฉ๋Œ์ฒ˜๋ฆฌ ํ•จ์ˆ˜ colliderect print("์ถฉ๋Œ!!") running = False screen.blit(background,(0,0)) #๋ฐฐ๊ฒฝ์ด ๋‚˜ํƒ€๋‚  ์ง€์  ์„ค์ • screen.blit(character,(character_x_pos,character_y_pos)) #์บ๋ฆญํ„ฐ๊ฐ€ ๋‚˜ํƒ€๋‚  ์ง€์  ์„ค์ • screen.blit(enemy,(enemy_x_pos,enemy_y_pos)) #์  ๊ทธ๋ฆฌ๊ธฐ #ํƒ€์ด๋จธ ์ง‘์–ด ๋„ฃ๊ธฐ #๊ฒฝ๊ณผ ์‹œ๊ฐ„ ๊ณ„์‚ฐ elapsed_time = (pygame.time.get_ticks() - start_ticks)/1000 #๊ฒฝ๊ณผ ์‹œ๊ฐ„์„ (ms) 1000์œผ๋กœ ๋‚˜๋ˆ„์–ด์„œ ์ดˆ ๋‹จ์œ„๋กœ ํ‘œ์‹œ timer = game_font.render(str(int(total_time - elapsed_time)),True,(255,255,255)) # ์ถœ๋ ฅํ•  ๊ธ€์ž,์‹œ๊ฐ„, True, ๊ธ€์ž์ƒ‰์ƒ screen.blit(timer,(10,10)) #๋งŒ์•ฝ ์‹œ๊ฐ„์ด 0 ์ดํ•˜์ด๋ฉด ๊ฒŒ์ž„ ์ข…๋ฃŒ if total_time - elapsed_time<=0: print("TIME OVER") running = False pygame.display.update() # ๊ฒŒ์ž„ํ™”๋ฉด์„ ๋‹ค์‹œ ๊ทธ๋ฆฐ๋‹ค. #์ž ์‹œ ๋Œ€๊ธฐ pygame.time.delay(2000) #pygame ์ข…๋ฃŒ pygame.quit()<file_sep>#include <Windows.h> #include <stdio.h> #include <conio.h> #define BALL_SIZE 20 // ๋ณผ์˜ ํฌ๊ธฐ ์ƒ์ˆ˜๋ฅผ ์ •์˜ #define BAR_HOR_SIZE 50 // ๋ฐ”์˜ ์ˆ˜ํ‰ ํฌ๊ธฐ ์ƒ์ˆ˜๋ฅผ ์ •์˜ #define BAR_VER_SIZE 10 // ๋ฐ”์˜ ์ˆ˜์ง ํฌ๊ธฐ ์ƒ์ˆ˜๋ฅผ ์ •์˜ #define BLOCK_VER_SIZE 20 //๋ฒฝ๋Œ์˜ ์ˆ˜์ง ํฌ๊ธฐ ์ƒ์ˆ˜ #define BLOCK_HOR_SIZE 100 //๋ฒฝ๋Œ์˜ ์ˆ˜ํ‰ ํฌ๊ธฐ ์ƒ์ˆ˜ #define BAR_MOVE_STEP 15 // ๋ฐ”์˜ ์ˆ˜ํ˜• ์ด๋™ ํฌ๊ธฐ ์ƒ์ˆ˜๋ฅผ ์ •์˜ #define MOVE_STEP 5 // ๋ณผ์˜ ์ด๋™ ๊ฐ„๊ฒฉ ์ƒ์ˆ˜๋ฅผ ์ •์˜ #define _B 523.2511 //๋ฐ”์™€ ๋ณผ์˜ ์ถฉ๋Œ์Œ #define _S 987.7666 //๋ณผ๊ณผ ๋ฒฝ๋Œ์˜ ์ถฉ๋Œ์Œ int main(void) { int ball_cnt[4] = { 0, }; //4๊ฐœ์˜ ๋ฒฝ๋Œ ๊ฐ๊ฐ์˜ ๋ณผ๊ณผ์˜ ์ถฉ๋Œ ์นด์šดํŠธ int bar_x = 250; // ๋ง‰๋Œ€์˜ ์‹œ์ ์˜ x,y ์ขŒํ‘œ int bar_y = 200; int ball_x = 300; // ๋ณผ์˜ ์‹œ์ ์˜ x,y ์ขŒํ‘œ int ball_y = 200; int block_x[4] = { 50,160,270,380 }; //๋ฒฝ๋Œ 4๊ฐœ ๊ฐ๊ฐ์˜ x ์‹œ์ž‘ ์ขŒํ‘œ int block_y = 80; int dx = MOVE_STEP; // ์‹œ์ž‘์‹œ x์ขŒํ‘œ์˜ ์ด๋™ ๊ฐ’ int dy = MOVE_STEP; // ์‹œ์ž‘์‹œ y์ขŒํ‘œ์˜ ์ด๋™ ๊ฐ’ char c; // ํ‚ค ์ž…๋ ฅ ์ €์žฅ ๋ณ€์ˆ˜ int score = 0; //๋ฒฝ๋Œ ์ ์ˆ˜. 100์ ์”ฉ ๋Š˜์–ด๋‚จ HWND hwnd = GetForegroundWindow(); // ํ˜„์žฌ ์œˆ๋„์šฐ์˜ ํ•ธ๋“ค์„ ๊ตฌํ•œ๋‹ค. HDC hdc = GetWindowDC(hwnd); // ์œˆ๋„์šฐ์˜ ๋””๋ฐ”์ด์Šค ์ปจํ…Œ์ŠคํŠธ(Device context)์˜ ํ•ธ๋“ค์„ ๊ตฌํ•˜์—ฌ ์œˆ๋„์šฐ์— ์ ‘๊ทผํ•œ๋‹ค. TCHAR str[50]; // ์ถœ๋ ฅํ•  ๋ฌธ์ž์—ด์„ ์ €์žฅํ•  ๋ฐฐ์—ด // ๋ฐฐ๊ฒฝ์„ ํฐ์ƒ‰์œผ๋กœ ์„ค์ • SelectObject(hdc, CreatePen(PS_SOLID, 1, RGB(255, 255, 255))); SelectObject(hdc, CreateSolidBrush(RGB(255, 255, 255))); Rectangle(hdc, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN)); // ๊ทธ๋ฆฌ๋Š” ํŽœ์˜ ํ…Œ๋‘๋ฆฌ ์ƒ‰์€ ํŒŒ๋ž€์ƒ‰, ์ฑ„์šฐ๋Š” ์ƒ‰์€ ํฐ์ƒ‰์œผ๋กœ ์„ค์ • SelectObject(hdc, CreatePen(PS_SOLID, 3, RGB(0, 0, 255))); SelectObject(hdc, CreateSolidBrush(RGB(255, 255, 255))); // ํŒŒ๋ž€์ƒ‰ ํ…Œ๋‘๋ฆฌ๋ฅผ ๊ฐ–๋Š” ์‚ฌ๊ฐํ˜•์„ ๊ทธ๋ฆฐ๋‹ค. ๋ฐ”ํƒ•์ƒ‰์€ ํฐ์ƒ‰ Rectangle(hdc, 30, 40, 500, 400 + BALL_SIZE + MOVE_STEP); //system("pause"); TextOut(hdc, 200, 450, L"BAR X control : j,k", 19); // ํ™”๋ฉด ์•„๋ž˜์— ๋ฌธ์ž์—ด ์ถœ๋ ฅ TextOut(hdc, 200, 250, L"PRESS ANY KEY!",15); //ํ”„๋กœ๊ทธ๋žจ ์‹œ์ž‘์ „ ๋ฉ”์‹œ์ง€ c = _getch(); // ํ‚ค๋ฅผ ์ž…๋ ฅ๋ฐ›๋Š” ๋ฌธ์ž.ํ‚ค๋ฅผ ๋ˆ„๋ฅด๋ฉด ํ”„๋กœ๊ทธ๋žจ์ด ์‹คํ–‰๋จ. SelectObject(hdc, CreatePen(PS_SOLID, 3, RGB(255, 255, 255))); //์‹œ์ž‘์ „ ๋ฉ”์‹œ์ง€๋ฅผ ์ง€์šฐ๊ธฐ ์œ„ํ•œ ํฐ์ƒ‰ ์‚ฌ๊ฐํ˜• SelectObject(hdc, CreateSolidBrush(RGB(255, 255, 255))); Rectangle(hdc, 200, 200, 350, 300); while (1) { score = ball_cnt[0] + ball_cnt[1] + ball_cnt[2] + ball_cnt[3]; //score๊ฐ’์„ ํ‘œํ˜„ wsprintf(str, TEXT("SCORE : %d"), score*100); //๋ฒฝ๋Œ์„ ๊นฐ๋•Œ๋งˆ๋‹ค score๊ฐ€ 100์ ์”ฉ ๋Š˜์–ด๋‚จ. TextOut(hdc,520, 120, str, lstrlen(str)); // ๊ทธ๋ฆฌ๋Š” ํŽœ์˜ ํ…Œ๋‘๋ฆฌ ์ƒ‰์€ ํŒŒ๋ž€์ƒ‰, ์ฑ„์šฐ๋Š” ์ƒ‰์€ ๋นจ๊ฐ•์ƒ‰์œผ๋กœ ์„ค์ • SelectObject(hdc, CreatePen(PS_SOLID, 3, RGB(0, 0, 255))); SelectObject(hdc, CreateSolidBrush(RGB(255, 0, 0))); // ์›์„ ๊ทธ๋ฆฐ๋‹ค. Ellipse(hdc, ball_x, ball_y, ball_x + BALL_SIZE, ball_y + BALL_SIZE); // ๋ฐ”๋ฅผ ๊ทธ๋ฆฐ๋‹ค. Rectangle(hdc, bar_x, 400, bar_x + BAR_HOR_SIZE, 400 + BAR_VER_SIZE); Sleep(30); // ์‹œ๊ฐ„ ์ง€์—ฐ // ๊ทธ๋ฆฌ๋Š” ํŽœ์˜ ์ƒ‰์€ ํฐ์ƒ‰, ์ฑ„์šฐ๋Š” ์ƒ‰์€ ํฐ์ƒ‰ SelectObject(hdc, CreatePen(PS_SOLID, 3, RGB(255, 255, 255))); SelectObject(hdc, CreateSolidBrush(RGB(255, 255, 255))); // ๋ฐ”ํƒ•์ƒ‰(ํฐ์ƒ‰)์œผ๋กœ ์›์„ ๊ทธ๋ ค์„œ ์›์„ ์ง€์šด๋‹ค. Ellipse(hdc, ball_x, ball_y, ball_x + BALL_SIZE, ball_y + BALL_SIZE); // ๋ฐ”๋ฅผ ์ง€์šด๋‹ค. Rectangle(hdc, bar_x, 400, bar_x + BAR_HOR_SIZE, 400 + BAR_VER_SIZE); for (int i = 0; i < 4; i++) { if (ball_cnt[i] == 0) { SelectObject(hdc, CreatePen(PS_SOLID, 3, RGB(0, 0, 0))); //๋ฒฝ๋Œ์„ ๊ทธ๋ฆฐ๋‹ค.์ƒ‰๊น”์€ ๊ฐˆ์ƒ‰, ํ…Œ๋‘๋ฆฌ๋Š” ๊ฒ€์€์ƒ‰ SelectObject(hdc, CreateSolidBrush(RGB(153, 51, 51))); Rectangle(hdc, block_x[i], block_y, block_x[i] + BLOCK_HOR_SIZE, block_y + BLOCK_VER_SIZE); } else { SelectObject(hdc, CreatePen(PS_SOLID, 3, RGB(255, 255, 255))); //๋ฒฝ๋Œ์„ ์ง€์šด๋‹ค. SelectObject(hdc, CreateSolidBrush(RGB(255, 255, 255))); Rectangle(hdc, block_x[i], block_y, block_x[i] + BLOCK_HOR_SIZE, block_y + BLOCK_VER_SIZE); } } // ์ด๋™ํ•˜๋Š” ์œ„์น˜์˜ x,y ์ขŒํ‘œ ๊ฐ’์œผ๋กœ ๋ณ€๊ฒฝํ•˜๊ธฐ ์œ„ํ•ด ์ขŒํ‘œ ๊ฐ’์„ dx,dy๋งŒํผ ์ด๋™ if (_kbhit()) // ํ‚ค๊ฐ€ ๋ˆŒ๋Ÿฌ์กŒ๋Š”์ง€ ๊ฒ€์‚ฌ { c = _getch(); // ํ‚ค๊ฐ€ ๋ˆŒ๋Ÿฌ์ง„ ๊ฒฝ์šฐ ์ž…๋ ฅ ๋ฌธ์ž ๊ฐ’์„ ์–ป๋Š”๋‹ค. if (c == 'j' || c == 'J') bar_x = bar_x - BAR_MOVE_STEP; // ์†Œ๋ฌธ์ž j๊ฐ€ ์ž…๋ ฅ๋œ ๊ฒฝ์šฐ x์ขŒํ‘œ ๊ฐ’์€ dx๋งŒํผ ๊ฐ์†Œ if (c == 'k' || c == 'K') bar_x = bar_x + BAR_MOVE_STEP; // ์†Œ๋ฌธ์ž k๊ฐ€ ์ž…๋ ฅ๋œ ๊ฒฝ์šฐ x์ขŒํ‘œ ๊ฐ’์€ dx๋งŒํผ ์ฆ๊ฐ€ } //if // ์ถฉ๋Œ ๊ฒ€์‚ฌ, ๋ณผ์˜ x์ขŒํ‘œ๊ฐ€ ๋ฐ”์˜ x์ขŒํ‘œ์™€ ํฌ๊ธฐ ๋ฒ”์œ„ ์•ˆ์— ์œ„์น˜ํ•˜๋Š”๊ฐ€ // ๋ณผ์˜ y ์ขŒํ‘œ๊ฐ€ ๋ณผ์˜ ํฌ๊ธฐ๋ฅผ ๊ณ ๋ คํ•œ ๋ฐ”์˜ y์ขŒํ‘œ์™€ ๋ฐ”์˜ ์ˆ˜์ง ๋‘๊ป˜ ์ขŒํ‘œ ๋ฒ”์œ„ ์•ˆ์— ์žˆ๋Š”๊ฐ€ if (bar_x <= ball_x && ball_x <= (bar_x + BAR_HOR_SIZE)) if ((400 - BALL_SIZE) <= ball_y && ball_y <= (400 + BAR_VER_SIZE)) { Beep(_B, 20); dy = -MOVE_STEP; } for (int i = 0; i < 4; i++) { //๋ฒฝ๋Œ๊ณผ ๋ณผ์˜ ์ถฉ๋Œ๊ฒ€์‚ฌ. if (ball_x >= block_x[i]-20 && ball_x <= (block_x[i] + BLOCK_HOR_SIZE+20)) if (block_y <= ball_y && ball_y <= block_y + BLOCK_VER_SIZE) { Beep(_S, 20); dy = MOVE_STEP; ball_cnt[i] = 1; } } if (score == 4) { //ํ”„๋กœ๊ทธ๋žจ ์ข…๋ฃŒ ์กฐ๊ฑด.์ด score์ ์ˆ˜๊ฐ€ 400์ ์ด ๋˜๋ฉด ์ข…๋ฃŒ๋œ๋‹ค. TextOut(hdc, 200, 250, L"GAME OVER!", 15); getchar(); break; } ball_x = ball_x + dx; ball_y = ball_y + dy; // ๋ฐ”์˜ ์ขŒ์ธก, ์šฐ์ธก ๊ฒฝ๊ณ„ ๊ฐ’ ๊ฒ€์‚ฌ ๋ฐ ์„ค์ • if (bar_x >= (500 - (BAR_HOR_SIZE + MOVE_STEP))) bar_x = 500 - (BAR_HOR_SIZE + MOVE_STEP); // x ์ขŒํ‘œ ๊ฐ’์˜ ์šฐ์ธก ๊ฒฝ๊ณ„๋ฅผ ๋งŒ๋‚œ ๊ฒฝ์šฐ x ์ขŒํ‘œ ๊ฐ’ ์ œํ•œ if (bar_x <= 30 + MOVE_STEP) bar_x = 30 + MOVE_STEP; // x ์ขŒํ‘œ ๊ฐ’์˜ ์ขŒ์ธก ๊ฒฝ๊ณ„๋ฅผ ๋งŒ๋‚œ ๊ฒฝ์šฐ x ์ขŒํ‘œ ๊ฐ’ ์ œํ•œ // ๋ณผ์˜ ์ขŒ์ธก, ์šฐ์ธก ๊ฒฝ๊ณ„ ๊ฐ’ ๊ฒ€์‚ฌ ๋ฐ ์„ค์ • if (ball_x >= (500 - (BALL_SIZE + MOVE_STEP))) dx = -MOVE_STEP; // x ์ขŒํ‘œ ๊ฐ’์˜ ์šฐ์ธก ๊ฒฝ๊ณ„๋ฅผ ๋งŒ๋‚œ ๊ฒฝ์šฐ x ์ขŒํ‘œ ๊ฐ’ ์ œํ•œ if (ball_x <= 30 + MOVE_STEP) dx = +MOVE_STEP; // x ์ขŒํ‘œ ๊ฐ’์˜ ์ขŒ์ธก ๊ฒฝ๊ณ„๋ฅผ ๋งŒ๋‚œ ๊ฒฝ์šฐ x ์ขŒํ‘œ ๊ฐ’ ์ œํ•œ if (ball_y >= 400) // ๋ณผ์ด ๋ฐ”๋‹ฅ์— ๋‹ฟ์€ ๊ฒฝ์šฐ, ๋ณผ์˜ ์‹œ์ž‘ ์œ„์น˜ x,y ์ขŒํ‘œ๋ฅผ ๋ฅผ ์ดˆ๊ธฐํ™” { ball_y = 200; ball_x = 300; } if (ball_y <= (40 + MOVE_STEP)) dy = +MOVE_STEP; // y ์ขŒํ‘œ ๊ฐ’์ด ์œ„์ธก ๊ฒฝ๊ณ„๋ฅผ ๋งŒ๋‚œ ๊ฒฝ์šฐ y์ขŒํ‘œ ๊ฐ’ ์ œํ•œ } //while return 0; }<file_sep># ๋™๋„ค์— ํ•ญ์ƒ ๋Œ€๊ธฐ ์†๋‹˜์ด ์žˆ๋Š” ๋ง›์žˆ๋Š” ์น˜ํ‚จ์ง‘ # ๋Œ€๊ธฐ ์†๋‹˜์˜ ์น˜ํ‚จ ์š”๋ฆฌ ์‹œ๊ฐ„์„ ์ค„์ด๊ณ ์ž ์ž๋™ ์ฃผ๋ฌธ ์‹œ์Šคํ…œ # ์‹œ์Šคํ…œ ์ฝ”๋“œ๋ฅผ ํ™•์ธํ•˜๊ณ  ์ ์ ˆํ•œ ์˜ˆ์™ธ์ฒ˜๋ฆฌ ๊ตฌ๋ฌธ์„ ๋„ฃ์œผ์‹œ์˜ค. # 1 ๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ์ˆซ์ž๊ฐ€ ์•„๋‹Œ ์ž…๋ ฅ๊ฐ’์ด ๋“ค์–ด์˜ฌ ๋•Œ๋Š” ValueError ๋กœ ์ฒ˜๋ฆฌ # ์ถœ๋ ฅ ๋ฉ”์„ธ์ง€๋„ ์ž…๋ ฅ # ๋Œ€๊ธฐ ์†๋‹˜์ด ์ฃผ๋ฌธํ•  ์ˆ˜ ์žˆ๋Š” ์ด ์น˜ํ‚จ๋Ÿ‰์€ 10๋งˆ๋ฆฌ๋กœ ํ•œ์ • # ์น˜ํ‚จ ์†Œ์ง„์‹œ ์‚ฌ์šฉ์ž ์ •์˜ ์—๋Ÿฌ ๋ฅผ ๋ฐœ์ƒ์‹œํ‚ค๊ณ  ํ”„๋กœ๊ทธ๋žจ ์ข…๋ฃŒ class ChickenError(Exception): pass # def __init__(self,msg): # self.msg = msg # def __str__(self): # return self.msg chicken = 10 waiting =1 while(True): try: print("[๋‚จ์€ ์น˜ํ‚จ : {}]".format(chicken)) order = int(input("๋ช‡ ๋งˆ๋ฆฌ ์ฃผ๋ฌธํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ?")) if order > chicken: print("์žฌ๋ฃŒ๊ฐ€ ๋ถ€์กฑํ•ฉ๋‹ˆ๋‹ค.") elif order <1: raise ValueError else: print("[๋Œ€๊ธฐ ๋ฒˆํ˜ธ {}] {} ๋งˆ๋ฆฌ ์ฃผ๋ฌธ ์™„๋ฃŒ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.".format(waiting,order)) waiting +=1 chicken -= order if chicken<=0: raise ChickenError except ValueError: print("์ž˜๋ชป๋œ ๊ฐ’์„ ์ž…๋ ฅํ•˜์…จ์Šต๋‹ˆ๋‹ค.") except ChickenError: print("์žฌ๊ณ ๊ฐ€ ์†Œ์ง„๋˜์–ด ๋” ์ด์ƒ ์ฃผ๋ฌธ์„ ๋ฐ›์ง€ ์•Š์Šต๋‹ˆ๋‹ค.") break finally: print("์ด์šฉํ•ด์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค.") <file_sep>try: print("๋‚˜๋ˆ„๊ธฐ ์ „์šฉ ๊ณ„์‚ฐ๊ธฐ ์ž…๋‹ˆ๋‹ค") nums = [] nums.append(int(input("์ฒซ ๋ฒˆ์งธ ์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” : "))) nums.append(int(input("๋‘ ๋ฒˆ์งธ ์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” : "))) nums.append(int(nums[0]/nums[1])) print("{} / {} = {} ".format(nums[0],nums[1],nums[2]) except ValueError: print("์—๋Ÿฌ! ์ž˜๋ชป๋œ ๊ฐ’์„ ์ž…๋ ฅํ•˜์˜€์Šต๋‹ˆ๋‹ค.") except ZeroDivisionError as err: print(err) except: print("์•Œ ์ˆ˜ ์—†๋Š” ์˜ค๋ฅ˜ ๋ฐœ์ƒ")<file_sep># import sys # print("Python","Java",file = sys.stdout) # print("Python","Java",file = sys.stderr) # scores = {"์ˆ˜ํ•™":0,"์˜์–ด" : 50,"์ฝ”๋”ฉ": 100} # for subject,score in scores.items(): # print(subject.ljust(8),str(score).rjust(4),sep = ":") # ljust : ์™ผ์ชฝ ์ •๋ ฌ # for num in range(1,21): # print("๋Œ€๊ธฐ๋ฒˆํ˜ธ : "+str(num).zfill(3).rjust(4)) # answer = input("์•„๋ฌด ๊ฐ’์ด๋‚˜ ์ž…๋ ฅ : ") # print("์ž…๋ ฅํ•˜์‹  ๊ฐ’์€ {} ์ž…๋‹ˆ๋‹ค.".format(answer)) #๋นˆ ์ž๋ฆฌ๋Š” ๋นˆ๊ณ ๊ฐ€๋А๋กœ ๋‘๊ณ , ์˜ค๋ฅธ์ชฝ ์ •๋ ค๋ฅผ ํ•˜๋˜, ์ด 10์ž๋ฆฌ ๊ณต๊ฐ„์„ ํ™•๋ณด print("{0:>10}".format(500)) #์–‘์ˆ˜์ผ ๋• + ๋กœ, ์Œ์ˆ˜์ผ๋• - print("{0:>+10}".format(500)) print("{0:>+10}".format(-500)) #์™ผ์ชฝ ์ •๋ ฌํ•˜๊ณ , ๋นˆ์นธ์œผ๋กœ _๋กœ ์ฑ„์›€ print("{0:_<+10}".format(500)) # 3์ž๋ฆฌ ๋งˆ๋‹ค ์ฝค๋งˆ๋ฅผ ์ฐ์–ด์ฃผ๊ธฐ print("{0:,}".format(1000000000000)) # 3์ž๋ฆฌ ๋งˆ๋‹ค ์ฝค๋งˆ๋ฅผ ์ฐ์–ด์ฃผ๊ธฐ + - print("{0:+,}".format(1000000000000)) # 3์ž๋ฆฌ ๋งˆ๋‹ค ์ฝค๋งˆ๋ฅผ ์ฐ๊ณ , ๋ถ€ํ˜ธ๋„ ๋ถ™์ด๊ณ , ์ž๋ฆฟ์ˆ˜ ํ™•๋ณด print("{0:^<+30,}".format(1000000000000000)) # ์†Œ์ˆ˜์  ์ถœ๋ ฅ print("{0:f}".format(5/3)) # ์†Œ์ˆ˜์ ์„ ํŠน์ • ์ž๋ฆฌ๊นŒ์ง€๋งŒ print("{0:.2f}".format(5/3))<file_sep>menu = ("๋ˆ๊นŒ์Šค","์น˜์ฆˆ๊นŒ์Šค") print(menu[0]) print(menu[1]) #menu.add ํŠœํ”Œ์€ ์ถ”๊ฐ€ ๋ณ€๊ฒฝ์ด ๋ถˆ๊ฐ€ (name,age,hobby) = ("์ด๋™์šฐ",20,"์ฝ”๋”ฉ") print(name,age,hobby)<file_sep>lst = ["๊ฐ€","๋‚˜","๋‹ค"] for lst_idx,lst_val in enumerate(lst): print(lst_idx,lst_val)<file_sep># ์ง‘ํ•ฉ(set) # ์ค‘๋ณต์•ˆ๋จ, ์ˆœ์„œ ์—†์Œ my_set = {1,2,3,3,3} print(my_set) java = {"์œ ์žฌ์„","๊น€ํƒœํ˜ธ","์–‘์„ธํ˜•"} python = set(["์œ ์žฌ์„","๋ฐ•๋ช…์ˆ˜"]) # ๊ต์ง‘ํ•ฉ (java ์™€ใ… python์„ ๋ชจ๋‘ ํ•  ์ˆ˜ ์žˆ๋Š” ์‚ฌ๋žŒ) print(java & python) print(java.intersection(python)) #ํ•ฉ์ง‘ํ•ฉ print(java | python) print(java.union(python)) #์ฐจ์ง‘ํ•ฉ print(java - python) print(java.difference(python)) #ํŒŒ์ด์ฌ์„ ํ• ์ค‘ ์•„๋Š” ์‚ฌ๋žŒ ๋Š˜์–ด๋‚จ python.add("๊น€ํƒœํ˜ธ") print(python) #java๋ฅผ ๊นŒ๋จน์Œ print(java) java.remove("๊น€ํƒœํ˜ธ") print(java)<file_sep>class ThilandPackage: def detail(self): print("[ํƒœ๊ตญ ํŒจํ‚ค์ง€ 3๋ฐ• 5์ผ] ๋ฐฉ์ฝ•, ํŒŒํƒ€์•ผ ์—ฌ์ƒ 50๋งŒ์›")<file_sep>import pickle # with open("profile.pickle","rb") as profile_file: # print(pickle.load(profile_file)) # with open("study.txt","w",encoding="utf8")as study_file: # study_file.write("ํŒŒ์ด์ฌ์„ ์—ด์‹ฌํžˆ ํ•˜๊ณ ์žˆ์Œ") with open("study.txt","r",encoding="utf8")as study_file: print(study_file.read())<file_sep># import theater_module # theater_module.price(3) #3๋ช…์ด์„œ ์˜ํ™”๋ณด๋Ÿฌ # theater_module.price_morning(4) # theater_module.price_soldier(5) # import theater_module as mv # mv.price(3) # mv.price_morning(4) # mv.price_soldier(5) # from theater_module import* # price(3) # price_morning(3) # price_soldier(4) # from theater_module import price,price_morning # price(5) # price_morning(6) from theater_module import price_soldier as price # price_soldier(5) price(5)<file_sep>#include<stdio.h> #include<math.h> //์ˆ˜ํ•™๊ณต์‹์„ ์“ฐ๊ธฐ์œ„ํ•œ ํ—ค๋” #include<Windows.h> //๊ทธ๋ž˜ํ”ฝ์„ ์ถœ๋ ฅํ•˜๊ธฐ์œ„ํ•œ ํ—ค๋” #include<thread> //๋ณ‘๋ ฌํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•œ thread ํ—ค๋”ํŒŒ์ผ using namespace std; //thread๋Š” C++์— ์ •์˜๋˜์–ด์žˆ๋Š” ํด๋ž˜์Šค(std)์ด๋ฏ€๋กœ ์„ ์–ธํ•ด์•ผ ํ•œ๋‹ค. #define PI 3.141592654 //PI์ƒ์ˆ˜ ์ •์˜ #define CT 525 //ํƒœ์–‘๊ณ„์˜ ๊ถค๋„์˜ ์ค‘์‹ฌ์ . HWND hwnd = GetForegroundWindow(); // ํ˜„์žฌ ์œˆ๋„์šฐ์˜ ํ•ธ๋“ค์„ ๊ตฌํ•œ๋‹ค. HDC hdc = GetWindowDC(hwnd); void func1() //์ˆ˜์„ฑ์˜ ๊ทธ๋ž˜ํ”ฝ๋ฅผ ํ‘œํ˜„ํ•˜๋Š” ํ•จ์ˆ˜ { float a = 0.0; //๋ณ€์ˆ˜ a์˜ ์ดˆ๊ธฐํ™”. ์—ฌ๊ธฐ์„œ a๋Š” ๋ผ๋””์•ˆ์˜ ์—ญํ•  while (1) { //whileํ•จ์ˆ˜ ์กฐ๊ฑด๋ฌธ์— true ๊ฐ’์„ ๋„ฃ์–ด์„œ ๋ฌดํ•œ๋ฐ˜๋ณต ์‹œํ‚จ๋‹ค a = 2 * PI; //whileํ•จ์ˆ˜ ์•ˆ์—์„œ ๋ณ€์ˆ˜ a๊ฐ’ ๋‹ค์‹œ ์ดˆ๊ธฐํ™” while (a > 0) { //๋ณ€์ˆ˜ a์˜ ๊ฐ’์ด ์–‘์ผ ๊ฒฝ์šฐ ๋ฐ˜๋ณต. a์˜ ๊ฐ’์ด 0๋ณด๋‹ค ์ž‘์ด์ง€๋ฉด //ํƒˆ์ถœํ•˜์—ฌ ์œ„์˜ while๋ฌธ์—์„œ ๋‹ค์‹œ ์ดˆ๊ธฐํ™”๋ฅผ ๋ฐ›๊ณ  ๋ฌดํ•œ๋ฐ˜๋ณต๋œ๋‹ค. int Mercu = 20; //์ˆ˜์„ฑ์˜ ๋ฐ˜์ง€๋ฆ„. ํ–‰์„ฑ์˜ ์‹ค์ œ ํฌ๊ธฐ์— ๋น„๋ก€ํ•˜์ง€ ์•Š๊ณ  ์ ์ ˆํ•œ ํฌ๊ธฐ๋ฅผ ๋Œ€์ž…ํ•˜์˜€๋‹ค float x = CT - cos(a) * 100; //์ˆ˜์„ฑ ์ขŒํ‘œ์˜ x๊ฐ’. ์ค‘์‹ฌ CT๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์ฝ”์‚ฌ์ธ์— ๋ณ€์ˆ˜ a๋ฅผ ๋Œ€์ž…,์ˆ˜์„ฑ ๊ถค๋„์˜ ๋ฐ˜์ง€๋ฆ„ 100์„ ๊ณฑํ•œ๋‹ค. float y = CT - sin(a) * 100; //์ˆ˜์„ฑ ์ขŒํ‘œ์˜ y๊ฐ’. ์ค‘์‹ฌ CT๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์‚ฌ์ธ์— ๋ณ€์ˆ˜ a๋ฅผ ๋Œ€์ž…,์ˆ˜์„ฑ ๊ถค๋„์˜ ๋ฐ˜์ง€๋ฆ„ 100์„ ๊ณฑํ•œ๋‹ค. SelectObject(hdc, CreatePen(PS_SOLID, 1, RGB(0, 0, 0))); //์ˆ˜์„ฑ ํƒœ๋‘๋ฆฌ ์ƒ‰๊น” SelectObject(hdc, CreateSolidBrush(RGB(75, 105, 120))); //์ˆ˜์„ฑ์˜ ์ƒ‰๊น”. ์ฒญํšŒ์ƒ‰์œผ๋กœ ์„ค์ •. Ellipse(hdc, x, y, x + Mercu, y + Mercu); //์ˆ˜์„ฑ์˜ ์ดˆ๊ธฐ์œ„์น˜. ์ด๋•Œ a๋Š” 2*PI์ด๋ฏ€๋กœ, ์ดˆ๊ธฐ์œ„์น˜๋Š” (425,525)์ด๋‹ค. a -= 0.01; //๋ณ€์ˆ˜ a์˜ ์ดˆ๊ธฐ๊ฐ’ 2*PI์—์„œ -0.01์”ฉ ๊ฐ์†Œ. ์ค„์–ด๋“  a์˜ ๊ฐ’์— ๋”ฐ๋ผ ์ˆ˜์„ฑ์˜ ์œ„์น˜๊ฐ€ ๋ณ€ํ•˜์—ฌ ํƒœ์–‘ ์ฃผ์œ„๋ฅผ ๊ณต์ „ํ•œ๋‹ค. //์ด๋•Œ ์ˆ˜์„ฑ์€ ๋ฐ˜์‹œ๊ณ„ ๋ฐฉํ–ฅ์œผ๋กœ ๊ณต์ „ํ•œ๋‹ค. Sleep(24.1); // ์ˆ˜์„ฑ์˜ ๊ณต์ „ ์ฃผ๊ธฐ. ์ง€๊ตฌ์˜ ๊ณต์ „์ฃผ๊ธฐ์†๋„(365์ผ)๋ฅผ 100์ด๋ผ ํ–ˆ์„๋•Œ ์ˆ˜์„ฑ์˜ ๊ณต์ „์†๋„๋Š” 24.1 ์ด๋‹ค SelectObject(hdc, CreatePen(PS_SOLID, 1, RGB(0, 0, 0))); //์ˆ˜์„ฑ์˜ ์ด๋™๊ฒฝ๋กœ๋ฅผ ๊ฒ€์€์ƒ‰์œผ๋กœ ์ง€์šด๋‹ค. SelectObject(hdc, CreateSolidBrush(RGB(0, 0, 0))); Ellipse(hdc, x, y, x + Mercu, y + Mercu); } } } void func2() //๊ธˆ์„ฑ์˜ ๊ทธ๋ž˜ํ”ฝ๋ฅผ ํ‘œํ˜„ํ•˜๋Š” ํ•จ์ˆ˜ { float b = 0.0; //๋ณ€์ˆ˜ b์˜ ์ดˆ๊ธฐํ™”. b๋Š” ๋ผ๋””์•ˆ while (1) { b = 2 * PI; //๋ณ€์ˆ˜ b์˜ ์ดˆ๊ธฐ๊ฐ’. while (b > 0) { //while๋ฌธ์˜ ์กฐ๊ฑด. int Vinus = 25; //๊ธˆ์„ฑ์˜ ๋ฐ˜์ง€๋ฆ„. float x = CT + cos(b) * 145; //๊ธˆ์„ฑ์˜ x๊ฐ’๊ณผ y๊ฐ’. ์ˆ˜์„ฑ๊ณผ ์ฝ”์‚ฌ์ธ,์‚ฌ์ธ ์—ฐ์‚ฐ์„ ๋ฐ˜๋Œ€๋กœํ•ด ์ดˆ๊ธฐ ์œ„์น˜๋ฅผ ๋ฐ˜๋Œ€๋กœ ํ•˜์˜€์Œ. float y = CT + sin(b) * 145; //๊ธˆ์„ฑ ๊ถค๋„์˜ ๋ฐ˜์ง€๋ฆ„์€ ์ค‘์‹ฌ(CT,CT)์„ ๊ธฐ์ค€์œผ๋กœ 145๋กœ ์„ค์ •ํ–ˆ๋‹ค. SelectObject(hdc, CreatePen(PS_SOLID, 1, RGB(0, 0, 0))); //๊ธˆ์„ฑ์˜ ํƒœ๋‘๋ฆฌ๋Š” ๊ฒ€์€์ƒ‰, ๋‚ด๋ถ€ ์ƒ‰์€ ๋ถ‰์€์ƒ‰์œผ๋กœ ํ•˜์˜€์Œ. SelectObject(hdc, CreateSolidBrush(RGB(204, 0, 0))); Ellipse(hdc, x, y, x + Vinus, y + Vinus); //๊ธˆ์„ฑ์˜ ์œ„์น˜ b -= 0.01; //๊ธˆ์„ฑ๋„ ๋ฐ˜์‹œ๊ณ„๋ฐฉํ–ฅ์œผ๋กœ ๊ณต์ „ํ•˜๊ฒŒ ์„ค์ •ํ–ˆ๋‹ค Sleep(67.37); //๊ธˆ์„ฑ์˜ ๊ณต์ „์†๋„๋Š” ์ง€๊ตฌ๋ฅผ 100์ด๋ผ ํ•˜์˜€์„๋•Œ 67.37์ด๋‹ค. SelectObject(hdc, CreatePen(PS_SOLID, 1, RGB(0, 0, 0))); //๊ธˆ์„ฑ์˜ ์ด๋™๊ฒฝ๋กœ๋ฅผ ๊ฒ€์€์ƒ‰์œผ๋กœ ์ง€์›€ SelectObject(hdc, CreateSolidBrush(RGB(0, 0, 0))); Ellipse(hdc, x, y, x + Vinus, y + Vinus); } } } void func3() //์ง€๊ตฌ์˜ ๊ทธ๋ž˜ํ”ฝ๋ฅผ ํ‘œํ˜„ํ•˜๋Š” ํ•จ์ˆ˜ { float c = 0.0; //๋ผ๋””์•„์ดˆ๊ธฐํ™” while (1) { //๋ฌดํ•œ๋ฐ˜๋ณต c = 2 * PI; //๋ผ๋””์•ˆ ์ดˆ๊ธฐ๊ฐ’ while (c > 0) { int Earth = 26; //์ง€๊ตฌ์˜ ๋ฐ˜์ง€๋ฆ„.๊ธˆ์„ฑ๊ณผ ๋น„์Šทํ•˜๊ฒŒ ์„ค์ •ํ•จ float x = CT + cos(c) * 195; //์ง€๊ตฌ์˜ xy๊ฐ’. ์ง€๊ตฌ ๊ถค๋„์˜ ๋ฐ˜์ง€๋ฆ„์€ ์ค‘์‹ฌ(CT,CT)์„ ๊ธฐ์ค€์œผ๋กœ 195๋กœ ์„ค์ •ํ–ˆ๋‹ค. float y = CT + sin(c) * 195; SelectObject(hdc, CreatePen(PS_SOLID, 1, RGB(0, 200, 0))); //์ง€๊ตฌ์˜ ํƒœ๋‘๋ฆฌ๋Š” ์ดˆ๋ก์ƒ‰, ๋‚ด๋ถ€์ƒ‰์€ ํŒŒ๋ž€์ƒ‰์œผ๋กœ ์„ค์ •ํ–ˆ๋‹ค SelectObject(hdc, CreateSolidBrush(RGB(0, 0, 255))); Ellipse(hdc, x, y, x + Earth, y + Earth); c -= 0.01; Sleep(100); //์ง€๊ตฌ์˜ ๊ณต์ „ ์†๋„ SelectObject(hdc, CreatePen(PS_SOLID, 1, RGB(0, 0, 0))); SelectObject(hdc, CreateSolidBrush(RGB(0, 0, 0))); Ellipse(hdc, x, y, x + Earth, y + Earth); } } } void func4() //ํ™”์„ฑ์˜ ๊ทธ๋ž˜ํ”ฝ๋ฅผ ํ‘œํ˜„ํ•˜๋Š” ํ•จ์ˆ˜ { float d = 0.0; while (1) { d = 2 * PI; while (d > 0) { int Mars = 23; //ํ™”์„ฑ์˜ ๋ฐ˜์ง€๋ฆ„. ์ง€๊ตฌ๋ณด๋‹ค ์กฐ๊ธˆ ์ž‘๊ฒŒ ์„ค์ • float x = CT - cos(d) * 255; //ํ™”์„ฑ๊ถค๋„์˜ ๋ฐ˜์ง€๋ฆ„์€ 255๋กœ ์„ค์ •ํ•˜์˜€๋‹ค. float y = CT - sin(d) * 255; SelectObject(hdc, CreatePen(PS_SOLID, 1, RGB(255, 140, 0))); //ํ™”์„ฑ์˜ ์ƒ‰๊น”์€ ์ฃผํ™ฉ์ƒ‰์œผ๋กœ ์„ค์ •ํ–ˆ๋‹ค. SelectObject(hdc, CreateSolidBrush(RGB(255, 165, 0))); Ellipse(hdc, x, y, x + Mars, y + Mars); d -= 0.01; Sleep(188.21); //ํ™”์„ฑ์˜ ๊ณต์ „์†๋„๋Š” ์ง€๊ตฌ(100)์„ ๊ธฐ์ค€์œผ๋กœ 188.21์ด๋‹ค. SelectObject(hdc, CreatePen(PS_SOLID, 1, RGB(0, 0, 0))); SelectObject(hdc, CreateSolidBrush(RGB(0, 0, 0))); Ellipse(hdc, x, y, x + Mars, y + Mars); } } } void func5() //๋ชฉ์„ฑ์˜ ๊ทธ๋ž˜ํ”„๋ฅผ ํ‘œํ˜„ํ•˜๋Š” ํ•จ์ˆ˜ { float e = 0.0; while (1) { e = 2 * PI; while (e > 0) { int Jupiter = 50; //๋ชฉ์„ฑ์˜ ๋ฐ˜์ง€๋ฆ„์€ 50์œผ๋กœ ์„ค์ •. float x = CT - cos(e) * 325; //๋ชฉ์„ฑ์˜ ๊ถค๋„ ๋ฐ˜์ง€๋ฆ„์€ 325๋กœ ์„ค์ •ํ–ˆ๋‹ค. float y = CT - sin(e) * 325; SelectObject(hdc, CreatePen(PS_SOLID, 1, RGB(0, 0, 0))); //๋ชฉ์„ฑ์˜ ์ƒ‰๊น”์€ ๊ฐˆ์ƒ‰์œผ๋กœ ์„ค์ •ํ–ˆ๋‹ค. SelectObject(hdc, CreateSolidBrush(RGB(160, 80, 45))); Ellipse(hdc, x, y, x + Jupiter, y + Jupiter); e -= 0.01; Sleep(1186); //๋ชฉ์„ฑ์˜ ๊ณต์ „์†๋„๋Š” ์ง€๊ตฌ(100)์„ ๊ธฐ์ค€์œผ๋กœ 1186์ด๋‹ค. SelectObject(hdc, CreatePen(PS_SOLID, 1, RGB(0, 0, 0))); SelectObject(hdc, CreateSolidBrush(RGB(0, 0, 0))); Ellipse(hdc, x, y, x + Jupiter, y + Jupiter); } } } void func6() //ํ† ์„ฑ์˜ ๊ทธ๋ž˜ํ”„๋ฅผ ํ‘œํ˜„ํ•˜๋Š” ํ•จ์ˆ˜ { float f = 0.0; while (1) { f = 2 * PI; while (f > 0) { int Saturn = 35; float x = CT + cos(f) * 370; //ํ† ์„ฑ์˜ ์ดˆ๊ธฐ ์œ„์น˜๋ฅผ ๋ชฉ์„ฑ๊ณผ ๋ฐ˜๋Œ€๋กœ ์„ค์ •ํ•˜์—ฌ ์‹œ๊ฐ์ ์œผ๋กœ ์šฉ์ดํ•˜๊ฒŒ ํ–ˆ๋‹ค float y = CT + sin(f) * 370; SelectObject(hdc, CreatePen(PS_SOLID, 1, RGB(100, 100, 0))); //ํ† ์„ฑ์˜ ์ƒ‰๊น”์€ ๊ธˆ์ƒ‰์œผ๋กœ ์„ค์ •ํ–ˆ๋‹ค. SelectObject(hdc, CreateSolidBrush(RGB(255, 215, 0))); Ellipse(hdc, x, y, x + Saturn, y + Saturn); f -= 0.01; Sleep(2950); //ํ† ์„ฑ์˜ ๊ณต์ „์†๋„๋Š” 2950์ด๋‹ค. SelectObject(hdc, CreatePen(PS_SOLID, 1, RGB(0, 0, 0))); SelectObject(hdc, CreateSolidBrush(RGB(0, 0, 0))); Ellipse(hdc, x, y, x + Saturn, y + Saturn); } } } void main() { //๊ทธ๋ž˜ํ”ฝ์„ ๊ตฌํ˜„ํ•  ๋ฉ”์ธํ•จ์ˆ˜. int x = 25, y = 25; //ํ–‰์„ฑ๋“ค์˜ ๊ณต์ „ ์ด๋™๋ฐฉํ–ฅ์„ ํฐ ์„ ์œผ๋กœ ์„ค์ •ํ•˜๊ธฐ ์œ„ํ•ด 4๊ฐœ์˜ ๋ณ€์ˆ˜์˜ ์ดˆ๊ธฐ๊ฐ’์„ ์ง€์ •ํ–ˆ๋‹ค. int w = 1025, h = 1025; SelectObject(hdc, CreatePen(PS_SOLID, 1, RGB(0, 0, 0))); //์‹œ๊ฐ์  ์šฉ์ดํ•จ์„ ์œ„ํ•ด์„œ ๋ฐฐ๊ฒฝ์„ ๊ฒ€์€์ƒ‰์œผ๋กœ ์„ค์ •ํ•ด์˜€๋‹ค. SelectObject(hdc, CreateSolidBrush(RGB(0, 0, 0))); Rectangle(hdc, 0, 0, 2 * CT, 2 * CT); for (int i = 1; i <= 8; i++) { // 8๊ฐœ ํ–‰์„ฑ(์ˆ˜๊ธˆ์ง€ํ™”๋ชฉํ† )์˜ ๊ณต์ „ ์ด๋™๋ฐฉํ–ฅ์„ ํ‘œํ˜„ํ•˜๊ธฐ ์œ„ํ•ด ํฐ์„  ์› 8๊ฐœ๋ฅผ ๋งŒ๋“ ๋‹ค. SelectObject(hdc, CreatePen(PS_SOLID, 1, RGB(255, 255, 255))); SelectObject(hdc, CreateSolidBrush(RGB(0, 0, 0))); Ellipse(hdc, x += 50, y += 50, w -= 50, h -= 50); } SelectObject(hdc, CreatePen(PS_SOLID, 1, RGB(255, 0, 0))); //ํƒœ์–‘์˜ ํƒœ๋‘๋ฆฌ๋Š” ๋นจ๊ฐ„์ƒ‰,๋‚ด๋ถ€๋Š” ์ฃผํ™ฉ์ƒ‰์œผ๋กœ ์„ค์ •ํ–ˆ๋‹ค. SelectObject(hdc, CreateSolidBrush(RGB(210, 95, 0))); Ellipse(hdc, CT - 50, CT - 50, CT + 50, CT + 50); //ํƒœ์–‘์˜ ์ฅ์น˜๋Š” ์ค‘์‹ฌ, ๋ฐ˜์ง€๋ฆ„์€ 100์œผ๋กœ ์„ค์ •ํ–ˆ๋‹ค. SelectObject(hdc, CreatePen(PS_SOLID, 1, RGB(0, 0, 0))); //์ฒœ์™•์„ฑ,ํ•ด์™•์„ฑ,๋ช…์™•์„ฑ์€ ์ด๋™์„ ๋ฌ˜์‚ฌํ•˜์ง€ ์•Š๊ณ  ๊ตฌํ˜„๋งŒ ํ–ˆ๋‹ค.์ƒ‰์€ ๊ฐ๊ฐ ํŒŒ๋ž€์ƒ‰,๋‚จ์ƒ‰, ํšŒ์ƒ‰์œผ๋กœ ์„ค์ •ํ–ˆ๋‹ค. SelectObject(hdc, CreateSolidBrush(RGB(0, 0, 255))); // ์ฒœ์™•์„ฑ ํ•ด์™•์„ฑ ๋ช…์™•์„ฑ์˜ ๊ถค๋„ ๋ฐ˜์ง€๋ฆ„์€ ๊ฐ๊ฐ 400,450,500์œผ๋กœ ์„ค์ •ํ–ˆ๋‹ค. Ellipse(hdc, CT - 400, CT, CT - 400 + 30, CT + 30); SelectObject(hdc, CreatePen(PS_SOLID, 1, RGB(0, 0, 0))); SelectObject(hdc, CreateSolidBrush(RGB(0, 0, 140))); Ellipse(hdc, CT - 450, CT, CT - 450 + 30, CT + 30); SelectObject(hdc, CreatePen(PS_SOLID, 1, RGB(0, 200, 0))); SelectObject(hdc, CreateSolidBrush(RGB(210, 180, 140))); Ellipse(hdc, CT - 500, CT, CT - 500 + 15, CT + 15); thread t1(func1); //์ˆ˜์„ฑ์˜ thread๊ฐ์ฒด. func1์„ ๋‚˜๋จธ์ง€ ํ•จ์ˆ˜์™€ ๋ณ‘๋ ฌ ์ง„ํ–‰ํ•œ๋‹ค. thread t2(func2); thread t3(func3); thread t4(func4); thread t5(func5); thread t6(func6); t1.join(); // func1ํ•จ์ˆ˜๊ฐ€ ์ข…๋ฃŒ๋˜๋ฉด ๋ฆฌํ„ด. ๋ฌดํ•œ ๋ฐ˜๋ณต ์‹œ์ผฐ๋‹ค. t2.join(); t3.join(); t4.join(); t5.join(); t6.join(); }<file_sep># import travel.thilrand # # import travel.thilrand.ThilandPackage # trip_to = travel.thilrand.ThilandPackage() # trip_to.detail() # from travel.thilrand import ThilandPackage # trip_to = ThilandPackage() # trip_to.detail() # from travel import vientnam # trip_to = vientnam.VietnamPackage() # trip_to.detail() from travel import* trip_to = vientnam.VietnamPackage() trip_to.detail() <file_sep># menu = {"์ปคํ”ผ","์šฐ์œ ","์ฃผ์Šค"} #์ง‘ํ•ฉ # print(menu,type(menu)) # menu = list(menu) #๋ฆฌ์ŠคํŠธ # print(menu,type(menu)) from random import* lst = range(1,21) lst = list(lst) shuffle(lst) # print(lst) # print(sample(lst,1)) sel = list(sample(lst,4)) print(sel) print('''---๋‹น์ฒจ์ž ๋ฐœํ‘œ--- ์น˜ํ‚จ ๋‹น์ฒจ์ž : {} ์ปคํ”ผ ๋‹น์ฒจ์ž : {} ---์ถ•ํ•˜ํ•ฉ๋‹ˆ๋‹ค---'''.format(sel[0],sel[1:]))<file_sep>gun = 10 def checkpoint(soldiers): global gun #์ „์—ญ ๊ณต๊ฐ„์— ์žˆ๋Š” gun ์‚ฌ์šฉํ•œ๋‹ค ๊ถŒ์žฅ๋˜์ง€๋Š” ์•Š์Œ gun = gun-soldiers print("๋‚จ์€ ์ด : {}".format(gun)) def checkpoint_ret(gun,soldiers): gun = gun - soldiers print("๋‚จ์€ ์ด : {}".format(gun)) return gun print("์ „์ฒด ์ด : {}".format(gun)) # checkpoint(2) gun = checkpoint_ret(gun,2) #๋ฆฌํ„ถํ•œ ๊ฐ’์„ ๋‹ค์‹œ ์ €์žฅํ•ด์ค€๋‹ค. print("์ „์ฒด ์ด : {}".format(gun))<file_sep>#์ผ๋ฐ˜ ๊ฐ€๊ฒฉ def price(people): print("{} ๋ช… ๊ฐ€๊ฒฉ์€ {} ์› ์ž…๋‹ˆ๋‹ค.".format(people,people*10000)) #์กฐ์กฐํ• ์ธ def price_morning(people): print("{} ๋ช… ๊ฐ€๊ฒฉ์€ {} ์› ์ž…๋‹ˆ๋‹ค.".format(people,people*6000)) #๊ตฐ์ธ def price_soldier(people): print("{} ๋ช… ๊ฐ€๊ฒฉ์€ {} ์› ์ž…๋‹ˆ๋‹ค.".format(people,people*4000)) <file_sep>from random import* class Unit: def __init__(self,name,hp,speed): self.name = name self.hp = hp self.speed = speed print("{} ์œ ๋‹›์ด ์ƒ์„ฑ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.".format(name)) def move(self,location): print("[์ง€์ƒ ์œ ๋‹› ์ด๋™]") print("{} : {} ๋ฐฉํ–ฅ์œผ๋กœ ์ด๋™ํ•ฉ๋‹ˆ๋‹ค.[์†๋„ : {} ".format(\ self.name,location,self.speed)) def damaged(self,damage): self.hp -= damage print("{} : {} ๋ฐ๋ฏธ์ง€๋ฅผ ์ž…์—ˆ์Šต๋‹ˆ๋‹ค.[ํ˜„์žฌ ์ฒด๋ ฅ : {} ]".format(\ self.name,damage,self.hp)) if self.hp <=0: print("{} ๋Š” ํŒŒ๊ดด๋˜์—ˆ์Šต๋‹ˆ๋‹ค.".format(self.name)) class AttackUnit(Unit): def __init__(self,name,hp,speed,damage): Unit.__init__(self,name,hp,speed) self.damage = damage def attack(self,location): print("{} : {} ๋ฐฉํ–ฅ์œผ๋กœ ๊ณต๊ฒฉํ•ฉ๋‹ˆ๋‹ค.[๊ณต๊ฒฉ๋ ฅ : {}]".format(\ self.name,location,self.damage)) class Flyable: def __init__(self,flying_speed): self.flying_speed = flying_speed def fly(self,name,location): print("{} : {} ๋ฐฉํ–ฅ์œผ๋กœ ๋‚ ์•„๊ฐ‘๋‹ˆ๋‹ค.[์†๋„ : {} ] ".format(\ name,location,self.flying_speed)) class FlyableAttackUnit(AttackUnit,Flyable): def __init__(self,name,hp,damage,flying_speed): AttackUnit.__init__(self,name,hp,0,damage) Flyable.__init__(self,flying_speed) def move(self,location): print("[๊ณต์ค‘ ์œ ๋‹› ์ด๋™]") self.fly(self.name,location) #๋งˆ๋ฆฐ ์ƒ์„ฑ ํด๋ž˜์Šค class Marine(AttackUnit): def __init__(self): AttackUnit.__init__(self,"๋งˆ๋ฆฐ",40,1,5) def stimpack(self): if self.hp >10: self.hp -= 10 print("{} : ์ŠคํŒ€ํŒฉ์„ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.(HP 10 ๊ฐ์†Œ)".format(self.name)) else: print("{} : ์ฒด๋ ฅ์ด ๋ถ€์กฑํ•˜์—ฌ ์ŠคํŒ€ํŒฉ์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.".format(self.name)) #ํƒฑํฌ ์ƒ์„ฑ ํด๋ž˜์Šค class Tank(AttackUnit): seize_developed = False def __init__(self): AttackUnit.__init__(self,"ํƒฑํฌ",150,1,35) self.seize_mode = False def set_seize_mode(self): if Tank.seize_developed == False: return if self.seize_mode==False: print("{} : ์‹œ์ฆˆ๋ชจ๋“œ๋กœ ์ „ํ™˜ํ•ฉ๋‹ˆ๋‹ค.".format(self.name)) self.damage *=2 self.seize_mode = True else: print("{} : ์‹œ์ฆˆ๋ชจ๋“œ๋ฅผ ํ•ด์ œํ•ฉ๋‹ˆ๋‹ค.".format(self.name)) self.damage /=2 self.seize_mode = False class Wraith(FlyableAttackUnit): def __init__(self): FlyableAttackUnit.__init__(self,"๋ ˆ์ด์Šค",80,20,5) self.clocked = False def clocking(self): if self.clocked == True: print("{} : ํด๋กœํ‚น ๋ชจ๋“œ ํ•ด์ œ".format(self.name)) self.clocked = False else: print("{} : ํด๋กœํ‚น ๋ชจ๋“œ ์ „ํ™˜".format(self.name)) self.clocked = True def game_start(): print("[์•Œ๋ฆผ] ์ƒˆ๋กœ์šด ๊ฒŒ์ž„์„ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค.") def game_over(): print("Player : gg") print("[Player] ๋‹˜์ด ๊ฒŒ์ž„์—์„œ ํ‡ด์žฅํ•˜์…จ์Šต๋‹ˆ๋‹ค.") #๊ฒŒ์ž„ ์‹œ์ž‘ game_start() m1 = Marine() m2 = Marine() m3 = Marine() t1 = Tank() t2 = Tank() w1 = Wraith w2 = Wraith #์ƒ์„ฑ๋œ ์œ ๋‹› ์ผ๊ด„ ๊ด€๋ฆฌ attack_units = [] attack_units.append(m1) attack_units.append(m2) attack_units.append(m3) attack_units.append(t1) attack_units.append(t2) attack_units.append(w1) attack_units.append(w2) #์ „๊ตฐ ์ด๋™ for unit in attack_units: unit.move("1์‹œ") Tank.seize_developed = True print("[์•Œ๋ฆผ] ํƒฑํฌ ์‹œ์ฆˆ ๋ชจ๋“œ ๊ฐœ๋ฐœ์ด ์™„๋ฃŒ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.") #๊ณต๊ฒฉ ๋ชจ๋“œ ์ค€๋น„ for unit in attack_units: if isinstance(unit,Marine): unit.stimpack() elif isinstance(unit,Tank): unit.seize_mode() elif isinstance(unit,Wraith): unit.clocking() #์ „๊ตฐ ๊ณต๊ฒฉ for unit in attack_units: unit.attack("1์‹œ") #์ „๊ตฐ ํ”ผํ•ด for unit in attack_units: unit.damaged(randint(5,21)) #๊ฒŒ์ž„ ์˜ค๋ฒ„ game_over() <file_sep>import pygame import os pygame.init() #์ดˆ๊ธฐํ™” ๋ฐ˜๋“œ์‹œ ํ•„์š”ํ•จ # ํ™”๋ฉด ํฌ๊ธฐ ์„ค์ • screen_width = 640 screen_height = 480 screen = pygame.display.set_mode((screen_width,screen_height)) #ํ™”๋ฉด ํƒ€์ดํ‹€ ์„ค์ • pygame.display.set_caption("PangPang Game")#๊ฒŒ์ž„ ์ด๋ฆ„ #FPS clock = pygame.time.Clock() #๋ฐฐ๊ฒฝ ์ด๋ฏธ์ง€ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ current_path = os.path.dirname(__file__) #ํ˜„์žฌ ํŒŒ์ผ์˜ ์œ„์น˜ ๋ณ€ํ™˜ image_path = os.path.join(current_path,"images") #images ํด๋” ์œ„์น˜ ๋ณ€ํ™˜ background = pygame.image.load(os.path.join(image_path,"backgr.png")) #์Šคํ…Œ์ด์ง€ ๋งŒ๋“ค๊ธฐ stage = pygame.image.load(os.path.join(image_path,"stage1.png")) stage_size = stage.get_rect().size stage_height = stage_size[1] #์บ๋ฆญํ„ฐ ๋งŒ๋“ค๊ธฐ character = pygame.image.load(os.path.join(image_path,"character.png")) character_size = character.get_rect().size character_width = character_size[0] character_height = character_size[1] character_x_pos = screen_width/2 - character_width/2 character_y_pos = screen_height - character_height - stage_height # ์ด๋ฒคํŠธ ๋ฃจํ”„ running = True #๊ฒŒ์ž„์ด ์ง„ํ–‰์ค‘์ธ๊ฐ€? while running: dt = clock.tick(30) #๊ฒŒ์ž„ํ™”๋ฉด์˜ ์ดˆ๋‹น ํ”„๋ ˆ์ž„ ์ˆ˜ ์„ค์ • print("fps : "+str(clock.get_fps())) for event in pygame.event.get(): #์–ด๋–ค ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€๋Š”๊ฐ€? if event.type == pygame.QUIT: #์ฐฝ์ด ๋‹ซํžˆ๋Š” ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€๋Š”๊ฐ€? running = False #๊ฒŒ์ž„์ด ์ง„ํ–‰์ค‘์ด ์•„๋‹ˆ๋‹ค. screen.blit(background,(0,0)) screen.blit(stage,(0,screen_height - stage_height)) screen.blit(character,(character_x_pos,character_y_pos)) pygame.display.update() # ๊ฒŒ์ž„ํ™”๋ฉด์„ ๋‹ค์‹œ ๊ทธ๋ฆฐ๋‹ค. #์ž ์‹œ ๋Œ€๊ธฐ pygame.time.delay(2000) #pygame ์ข…๋ฃŒ pygame.quit() <file_sep># ๋ฆฌ์ŠคํŠธ [] subway1 = 10 subway2 = 20 subway3 = 30 subway = [10,20,30] print(subway) subway = ["์œ ์žฌ์„","์กฐ์„ธํ˜ธ","๋ฐ•๋ช…์ˆ˜"] # ์กฐ์„ธํ˜ธ๊ฐ€ ๋ช‡๋ฒˆ์ฉจ ์นธ์— ํƒ€๊ณ ์žˆ๋‚˜. print(subway.index("์กฐ์„ธํ˜ธ")) # ํ•˜ํ•˜๊ฐ€ ๋‹ค์Œ ์ •๋ฅ˜์žฅ์—์„œ ํƒ‘์Šน subway.append("ํ•˜ํ•˜") print(subway) # ์ •ํ˜•๋ˆ์„ ์œ ์žฌ์„ ์กฐ์„ธํ˜ธ ์‚ฌ์ด์— ํƒ‘์Šน subway.insert(1,"์ •ํ˜•๋ˆ") print(subway) #์ง€ํ•˜์ฒ ์— ์žˆ๋Š” ์‚ฌ๋žŒ์„ ํ•œ ๋ช…์”ฉ ๋’ค์—์„œ ๊บผ๋ƒ„ subway.pop() print(subway) # subway.pop() # print(subway) # subway.pop() # print(subway) #๊ฐ™์€ ์ด๋ฆ„์˜ ์‚ฌ๋žŒ์ด ๋ช‡๋ช… ์žˆ๋Š”์ง€ subway.append("์œ ์žฌ์„") print(subway.count("์œ ์žฌ์„")) #์ •๋ ฌ๋„ ๊ฐ€๋Šฅ num_list = [5,2,4,3,1] num_list.sort() print(num_list) #๋’ค์ง‘๊ธฐ ๊ฐ€๋Šฅ num_list.reverse() print(num_list) #๋ชจ๋‘ ์ง€์šฐ๊ธฐ # num_list.clear() print(num_list) #๋‹ค์–‘ํ•œ ์ž๋ฃŒํ˜•๊ณผ ํ•จ๊ป˜ ์‚ฌ์šฉ ๊ฐ€๋Šฅ mix_list = ["์กฐ์„ธํ˜ธ",20,True] print(mix_list) #๋ฆฌ์ŠคํŠธ ํ™•์žฅ num_list.extend(mix_list) print(num_list)<file_sep># ์ถœ์„๋ฒˆํ˜ธ ์•ž์— 100์„ ๋ถ™์ž„ # student = [1,2,3,4,5] # student = [i+100 for i in student] # print(student) # student = ["iron man","thor","i am groot"] # student = [len(i) for i in student] # print(student) # student = ["iron man","thor","i am groot"] # student = [i.upper() for i in student] # print(student) from random import* cnt = 0 for i in range(1,51): t = randrange(1,51) if t >=5 and t <=15: print("[O] {}๋ฒˆ์งธ ์†๋‹˜ (์†Œ์š”์‹œ๊ฐ„ : {} ๋ถ„)".format(i,t)) cnt+=1 else: print("[ ] {}๋ฒˆ์งธ ์†๋‹˜ (์†Œ์š”์‹œ๊ฐ„ : {} ๋ถ„)".format(i,t)) print("์ด ํƒ‘์Šน ์Šน๊ฐ : {} ๋ถ„".format(cnt)) <file_sep>class BigNumberError(Exception): def __init__(self,meg): self.meg = meg def __str__(self): return self.meg try: print("ํ•œ ์ž๋ฆฌ ์ˆซ์ž ๋‚˜๋ˆ„๊ธฐ ์ „์šฉ ๊ณ„์‚ฐ๊ธฐ ์ž…๋‹ˆ๋‹ค.") num1 = int(input("์ฒซ ๋ฒˆ์งธ ์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” : ")) num2 = int(input("๋‘ ๋ฒˆ์งธ ์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” : ")) if num1 >= 10 or num2 >=10: # raise ValueError # ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•˜๋ฉด ์ดํ›„์˜ ๋ฌธ์žฅ์„ ์‹คํ–‰ํ•˜์ง€ ์•Š๊ณ  ๋ฐ”๋กœ ์—๋Ÿฌ์ฒ˜๋ฆฌ ๋ฌธ์žฅ์œผ๋กœ raise BigNumberError("์ž…๋ ฅ๊ฐ’ : {} {} ".format(num1,num2)) # ์‚ฌ์šฉ์ž ์ง€์ • ์—๋Ÿฌ์ฒ˜๋ฆฌ print("{} / {} = {} ".format(num1,num2,int(num1/num2))) except ValueError: print("์ž˜๋ชป๋œ ๊ฐ’์„ ์ž…๋ ฅํ–ˆ์Šต๋‹ˆ๋‹ค. ํ•œ์ž๋ฆฌ ์ˆซ์ž๋งŒ ์ž…๋ ฅํ•˜์„ธ์š”.") except BigNumberError as err: print("์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€์Šต๋‹ˆ๋‹ค. ํ•œ์ž๋ฆฌ ์ˆซ์ž๋งŒ ์ž…๋ ฅํ•˜์„ธ์š”.") print(err) finally: print("๊ณ„์‚ฐ๊ธฐ๋ฅผ ์ด์šฉํ•ด ์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค.")<file_sep># import pickle # cnt = 1 # while cnt<=50: # with open("{}์ฃผ์ฐจ.txt","w",encoding="utf8".format(cnt))as record_file: # record_file.write("""-{}์ฃผ์ฐจ ์ฃผ๊ฐ„๋ณด๊ณ - # ๋ถ€์„œ : # ์ด๋ฆ„ : # ์—…๋ฌด์š”์•ฝ : # """.format(cnt)) for i in range(1,3): with open(str(i)+"์ฃผ์ฐจ.txt","w",encoding="utf8")as report_file: report_file.write("-{} ์ฃผ์ฐจ ์ฃผ๊ฐ„๋ณด๊ณ  - ".format(i)) report_file.write("\n๋ถ€์„œ : ") report_file.write("\n์ด๋ฆ„ : ") report_file.write("\n์—…๋ฌด ์š”์•ฝ : ")<file_sep>import pygame pygame.init() #์ดˆ๊ธฐํ™” ๋ฐ˜๋“œ์‹œ ํ•„์š”ํ•จ # ํ™”๋ฉด ํฌ๊ธฐ ์„ค์ • screen_width = 480 screen_height = 640 screen = pygame.display.set_mode((screen_width,screen_height)) #ํ™”๋ฉด ํƒ€์ดํ‹€ ์„ค์ • pygame.display.set_caption("EL Game")#๊ฒŒ์ž„ ์ด๋ฆ„ #๋ฐฐ๊ฒฝ ์ด๋ฏธ์ง€ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ1 background = pygame.image.load("C:\\Users\\Administrator\\Desktop\\๋‚˜๋„์ฝ”๋”ฉํŒŒ์ด์ฌ\\๋‚˜๋„์ฝ”๋”ฉํŒŒ์ด์ฌ๊ฒŒ์ž„\\background.png") #(์บ๋ฆญํ„ฐ) ์Šคํ”„๋ผ์ดํŠธ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ character = pygame.image.load("C:\\Users\\Administrator\\Desktop\\๋‚˜๋„์ฝ”๋”ฉํŒŒ์ด์ฌ\\๋‚˜๋„์ฝ”๋”ฉํŒŒ์ด์ฌ๊ฒŒ์ž„\\char1.png") character_size = character.get_rect().size #์ด๋ฏธ์ง€์˜ ํฌ๊ธฐ๋ฅผ ๊ตฌํ•ด์˜ด character_width = character_size[0] #์บ๋ฆญํ„ฐ์˜ ๊ฐ€๋กœํฌ๊ธฐ character_height = character_size[1] #์บ๋ฆญํ„ฐ์˜ ์„ธ๋กœํฌ๊ธฐ character_x_pos = screen_width/2 - character_width/2 #ํ™”๋ฉด ๊ฐ€๋กœ์˜ ์ ˆ๋ฐ˜ ํฌ๊ธฐ, ์บ๋ฆญํ„ฐ์˜ ์ฒ˜์Œ x์œ„์น˜ character_y_pos = screen_height - character_height#ํ™”๋ฉด ์„ธ๋กœํฌ๊ธฐ ๊ฐ€์žฅ ์•„๋ž˜์— ํ•ด๋‹นํ•˜๋Š” ๊ณณ์— ์œ„์น˜ # ์ด๋ฒคํŠธ ๋ฃจํ”„ running = True #๊ฒŒ์ž„์ด ์ง„ํ–‰์ค‘์ธ๊ฐ€? while running: for event in pygame.event.get(): #์–ด๋–ค ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€๋Š”๊ฐ€? if event.type == pygame.QUIT: #์ฐฝ์ด ๋‹ซํžˆ๋Š” ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€๋Š”๊ฐ€? running = False #๊ฒŒ์ž„์ด ์ง„ํ–‰์ค‘์ด ์•„๋‹ˆ๋‹ค. screen.blit(background,(0,0)) #๋ฐฐ๊ฒฝ์ด ๋‚˜ํƒ€๋‚  ์ง€์  ์„ค์ • screen.blit(character,(character_x_pos,character_y_pos)) #์บ๋ฆญํ„ฐ๊ฐ€ ๋‚˜ํƒ€๋‚  ์ง€์  ์„ค์ • pygame.display.update() # ๊ฒŒ์ž„ํ™”๋ฉด์„ ๋‹ค์‹œ ๊ทธ๋ฆฐ๋‹ค. #pygame ์ข…๋ฃŒ pygame.quit() <file_sep>import pygame pygame.init() #์ดˆ๊ธฐํ™” ๋ฐ˜๋“œ์‹œ ํ•„์š”ํ•จ # ํ™”๋ฉด ํฌ๊ธฐ ์„ค์ • screen_width = 480 screen_height = 640 screen = pygame.display.set_mode((screen_width,screen_height)) #ํ™”๋ฉด ํƒ€์ดํ‹€ ์„ค์ • pygame.display.set_caption("EL Game")#๊ฒŒ์ž„ ์ด๋ฆ„ #FPS clock = pygame.time.Clock() #๋ฐฐ๊ฒฝ ์ด๋ฏธ์ง€ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ1 background = pygame.image.load("C:\\Users\\Administrator\\Desktop\\๋‚˜๋„์ฝ”๋”ฉํŒŒ์ด์ฌ\\๋‚˜๋„์ฝ”๋”ฉํŒŒ์ด์ฌ๊ฒŒ์ž„\\background.png") #(์บ๋ฆญํ„ฐ) ์Šคํ”„๋ผ์ดํŠธ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ character = pygame.image.load("C:\\Users\\Administrator\\Desktop\\๋‚˜๋„์ฝ”๋”ฉํŒŒ์ด์ฌ\\๋‚˜๋„์ฝ”๋”ฉํŒŒ์ด์ฌ๊ฒŒ์ž„\\char1.png") character_size = character.get_rect().size #์ด๋ฏธ์ง€์˜ ํฌ๊ธฐ๋ฅผ ๊ตฌํ•ด์˜ด character_width = character_size[0] #์บ๋ฆญํ„ฐ์˜ ๊ฐ€๋กœํฌ๊ธฐ character_height = character_size[1] #์บ๋ฆญํ„ฐ์˜ ์„ธ๋กœํฌ๊ธฐ character_x_pos = screen_width/2 - character_width/2 #ํ™”๋ฉด ๊ฐ€๋กœ์˜ ์ ˆ๋ฐ˜ ํฌ๊ธฐ, ์บ๋ฆญํ„ฐ์˜ ์ฒ˜์Œ x์œ„์น˜ character_y_pos = screen_height - character_height#ํ™”๋ฉด ์„ธ๋กœํฌ๊ธฐ ๊ฐ€์žฅ ์•„๋ž˜์— ํ•ด๋‹นํ•˜๋Š” ๊ณณ์— ์œ„์น˜ #์ด๋™ํ•  ์ขŒํ‘œ to_x = 0 to_y = 0 #์ด๋™์†๋„ character_speed = 0.5 # ์ด๋ฒคํŠธ ๋ฃจํ”„ running = True #๊ฒŒ์ž„์ด ์ง„ํ–‰์ค‘์ธ๊ฐ€? while running: dt = clock.tick(30) #๊ฒŒ์ž„ํ™”๋ฉด์˜ ์ดˆ๋‹น ํ”„๋ ˆ์ž„ ์ˆ˜ ์„ค์ • print("fps : "+str(clock.get_fps())) for event in pygame.event.get(): #์–ด๋–ค ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€๋Š”๊ฐ€? if event.type == pygame.QUIT: #์ฐฝ์ด ๋‹ซํžˆ๋Š” ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€๋Š”๊ฐ€? running = False #๊ฒŒ์ž„์ด ์ง„ํ–‰์ค‘์ด ์•„๋‹ˆ๋‹ค. if event.type==pygame.KEYDOWN: #ํ‚ค๊ฐ€ ๋ˆŒ๋ ธ๋Š”์ง€ ํ™•์ธ if event.key==pygame.K_LEFT: to_x-= character_speed elif event.key==pygame.K_RIGHT: to_x += character_speed elif event.key == pygame.K_UP: to_y -= character_speed elif event.key == pygame.K_DOWN: to_y += character_speed if event.type == pygame.KEYUP: #๋ฐฉํ–ฅํ‚ค๋ฅผ ๋–ผ๋ฉด ๋ฉˆ์ถค if event.key == pygame.K_LEFT or pygame.K_RIGHT: to_x = 0 elif event.key == pygame.K_UP or pygame.KEYDOWN: to_y = 0 character_x_pos += to_x*dt character_y_pos += to_y*dt #๊ฐ€๋กœ ๊ฒฝ๊ณ„๊ฐ’ ์ฒ˜๋ฆฌ if character_x_pos < 0: character_x_pos = 0 elif character_x_pos > screen_width - character_width: character_x_pos = screen_width - character_width if character_y_pos < 0: character_y_pos = 0 elif character_y_pos > screen_height - character_height: character_y_pos = screen_height - character_height screen.blit(background,(0,0)) #๋ฐฐ๊ฒฝ์ด ๋‚˜ํƒ€๋‚  ์ง€์  ์„ค์ • screen.blit(character,(character_x_pos,character_y_pos)) #์บ๋ฆญํ„ฐ๊ฐ€ ๋‚˜ํƒ€๋‚  ์ง€์  ์„ค์ • pygame.display.update() # ๊ฒŒ์ž„ํ™”๋ฉด์„ ๋‹ค์‹œ ๊ทธ๋ฆฐ๋‹ค. #pygame ์ข…๋ฃŒ pygame.quit() <file_sep># def open_account(): # print("์ƒˆ๋กœ์šด ๊ณ„์ขŒ๊ฐ€ ์ƒ์„ฑ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.") # def deposit(balance,money): # print("์ž…๊ธˆ์ด ์™„๋ฃŒ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ์ž”์•ก์€ {} ์› ์ž…๋‹ˆ๋‹ค.".format(balance+money)) # return balance+money # def withdraw(balance,money): # if balance< money: # print("์ถœ๊ธˆ์ด ๋ถˆ๊ฐ€๋Šฅ ํ•ฉ๋‹ˆ๋‹ค. ์ž”์•ก์€ {} ์› ์ž…๋‹ˆ๋‹ค.".format(balance)) # return balance # else: # print("์ถœ๊ธˆ์ด ์™„๋ฃŒ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ์ž”์•ก์€ {} ์› ์ž…๋‹ˆ๋‹ค.".format(balance - money)) # return balance - money # def withdraw_night(balance,money): # commission = 100 # return commission,balance - money - commission # balance = 0 # balance = deposit(balance,1000) # print(balance) # balance = withdraw(balance,4000) # commission,balance = withdraw_night(balance,500) # print("์ˆ˜์ˆ˜๋ฃŒ {} ์›, ์ž”์•ก์€ {} ์› ์ž…๋‹ˆ๋‹ค.".format(commission,balance)) # def profile(name,age,lang): # print("์ด๋ฆ„ : {}\t๋‚˜์ด : {}\t์ฃผ ์‚ฌ์šฉ ์–ธ์–ด : {}".\ # format(name,age,lang)) # profile("์œ ์žฌ์„",20,"python") #๊ฐ™์€ ํ•™๊ต ๊ฐ™์€ ํ•™๋…„ ๊ฐ™์€ ๋ฐ˜ ๊ฐ™์€ ์ˆ˜์—… # def profile(name,age=17,lang): # print("์ด๋ฆ„ : {}\t๋‚˜์ด : {}\t์ฃผ ์‚ฌ์šฉ ์–ธ์–ด : {}".\ # format(name,age,lang)) <file_sep># ์ถœ๋ ฅ ์˜ˆ์ œ # ์ด 3๋Œ€์˜ ๋งค๋ฌผ # ๊ฐ•๋‚จ ์•„ํŒŒํŠธ ๋งค๋งค 10์–ต 2010๋…„ # ๋งˆํฌ ์˜คํ”ผ์Šคํ…” ์ „์„ธ 5์–ต 2007๋…„ # ์†กํŒŒ ๋นŒ๋ผ ์›”์„ธ 500/50 2000๋…„ class House: def __init__(self,location,house_type,deal_type,price,year): self.location = location self.house_type = house_type self.deal_type = deal_type self.price = price self.year = year def show(self): print("{} {} {} {} {}๋…„ ".format(self.location,\ self.house_type,self.deal_type,self.price,self.year)) cases = [] case1 = House("๊ฐ•๋‚จ","์•„ํŒŒํŠธ","๋งค๋งค","10์–ต","2010") case2 = House("๋งˆํฌ","์˜คํ”ผ์Šคํ…”","์ „์„ธ","5์–ต","2007") cases.append(case1) cases.append(case2) for case in cases: case.show() # case1.show() # case2.show()<file_sep>def std_weight(height,gender): if gender == "๋‚จ์ž": weight = height*height*22/10000 return weight else: weight = height*height*21/10000 return weight height = int(input("ํ‚ค๋ฅผ ์ž…๋ ฅ : ")) gender = input("์„ฑ๋ณ„์„ ์ž…๋ ฅ : ") weight = round(std_weight(height,gender),2) #๋ฐ˜์˜ฌ๋ฆผ ํ•จ์ˆ˜ round print("ํ‚ค {} {}์˜ ํ‘œ์ค€ ์ฒด์ค‘์€ {}kg ์ž…๋‹ˆ๋‹ค.".format(height,gender,weight)) <file_sep># weather = input("์˜ค๋Š˜ ๋‚ ์”จ๋Š” ์–ด๋•Œ์š”? ") # if weather=="๋น„" or weather == "๋ˆˆ": # print("์šฐ์‚ฐ์„ ์ฑ™๊ธฐ์„ธ์š”") # elif weather == "๋ฏธ์„ธ๋จผ์ง€": # print("๋งˆ์Šคํฌ๋ฅผ ์ฑ™๊ธฐ์„ธ์š”") # else: # print("์ค€๋น„๋ฌผ์ด ํ•„์š”์—…์–ด์š”") temp = int(input("๊ธฐ์˜จ์€ ์–ด๋•Œ์š” ? ")) if temp >=30: print("๋„ˆ๋ฌด ๋”์›Œ์š”") elif temp>=10 and temp <=29: print("๋”ฑ ์ข‹์•„์š”") elif temp >=0 and temp <=9: print("์กฐ๊ธˆ ์Œ€์Œ€") else : print("๋„˜ ์ถ”์›€")<file_sep># for waiting in range(0,5): # print("๋Œ€๊ธฐ๋ฒˆํ˜ธ : {}".format(waiting)) # star = ["A","B","C"] # for customer in star: # print("{},์ปคํ”ผ๊ฐ€ ์ค€๋น„๋˜์—ˆ์Šต๋‹ˆ๋‹ค.".format(customer)) # #while # customer = "A" # index = 5 # while index >=1: # print("{}, ์ปคํ”ผ๊ฐ€ ์ค€๋น„๋˜์—ˆ์Šต๋‹ˆ๋‹ค.{} ๋ฒˆ ๋‚จ์•˜์–ด์š”.".format(customer,index)) # index -=1 # if index==0: # print("์ปคํ”ผ๋Š” ํ๊ธฐ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.") # customer = "Q" # index = 0 # while True: # print("{}, ์ปคํ”ผ๊ฐ€ ์ค€๋น„๋˜์—ˆ์Šต๋‹ˆ๋‹ค.{} ๋ฒˆ ๋‚จ์•˜์–ด์š”.".format(customer,index)) # index +=1 # customer = "Q" # person = "Unknown" # while person != customer: # print("{}, ์ปคํ”ผ๊ฐ€ ์ค€๋น„๋˜์—ˆ์Šต๋‹ˆ๋‹ค.".format(customer)) # person = input("์ด๋ฆ„์ด?") absent = [2,5] nobook = [7] for student in range(1,11): if student in absent: continue elif student in nobook: print("์˜ค๋Š˜์ˆ˜์—… ์—ฌ๊ธฐ๊นŒ์ง€, {} ๋”ฐ๋ผใ…์™€".format(student)) break print("{}, ์ผ์–ด๋‚˜".format(student))<file_sep>#include <Windows.h> #include <stdio.h> #include <math.h> #define BALL_SIZE 12 // ๋ณผ์˜ ํฌ๊ธฐ ์ƒ์ˆ˜๋ฅผ ์ •์˜ #define MOVE_STEP 3 // ๋ณผ์˜ ์ด๋™ ๊ฐ„๊ฒฉ ์ƒ์ˆ˜๋ฅผ ์ •์˜ #define X_END 800 // x ์ขŒํ‘œ์˜ ์šฐ์ธก ๊ฒฝ๊ณ„ ๊ฐ’ ์„ค์ • #define Y_END 400 // y ์ขŒํ‘œ์˜ ํ•˜๋‹จ ๊ฒฝ๊ณ„ ๊ฐ’ ์„ค์ • #define PI 3.141592654 // PI ์ƒ์ˆ˜ ๊ฐ’ #define G 9.8 // ์ค‘๋ ฅ ๊ฐ€์†๋„ ์ƒ์ˆ˜ ๊ฐ’ int main(void) { int x; // ๋ณผ์˜ x,y ์ขŒํ‘œ int y; int v0 = 80; // ์ดˆ๊ธฐ ๋ฐœ์‚ฌ ์†๋„ ๊ฐ’ int degree; // ํฌ๋ฌผ์„ ์˜ ๋ฐœ์‚ฌ ๊ฐ๋„ double t = 0.0; // ์‹œ๊ฐ„ ๊ฐ’ double dt = 0.1; // ์‹œ๊ฐ„ ์ฆ๊ฐ€ ๊ฐ’ TCHAR str[50]; // ์ถœ๋ ฅํ•  ๋ฌธ์ž์—ด์„ ์ €์žฅํ•  ๋ฐฐ์—ด HWND hwnd = GetForegroundWindow(); // ํ˜„์žฌ ์œˆ๋„์šฐ์˜ ํ•ธ๋“ค์„ ๊ตฌํ•œ๋‹ค. HDC hdc = GetWindowDC(hwnd); // ์œˆ๋„์šฐ์˜ ๋””๋ฐ”์ด์Šค ์ปจํ…Œ์ŠคํŠธ(Device context)์˜ ํ•ธ๋“ค์„ ๊ตฌํ•˜์—ฌ ์œˆ๋„์šฐ์— ์ ‘๊ทผํ•œ๋‹ค. // ๋ฐฐ๊ฒฝ์„ ํฐ์ƒ‰์œผ๋กœ ์„ค์ • SelectObject(hdc, CreatePen(PS_SOLID, 1, RGB(255, 255, 255))); SelectObject(hdc, CreateSolidBrush(RGB(255, 255, 255))); Rectangle(hdc, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN)); // ๊ทธ๋ฆฌ๋Š” ํŽœ์˜ ํ…Œ๋‘๋ฆฌ ์ƒ‰์€ ํŒŒ๋ž€์ƒ‰, ์ฑ„์šฐ๋Š” ์ƒ‰์€ ํฐ์ƒ‰์œผ๋กœ ์„ค์ • SelectObject(hdc, CreatePen(PS_SOLID, 3, RGB(0, 0, 255))); SelectObject(hdc, CreateSolidBrush(RGB(255, 255, 255))); // ํŒŒ๋ž€์ƒ‰ ํ…Œ๋‘๋ฆฌ๋ฅผ ๊ฐ–๋Š” ์‚ฌ๊ฐํ˜•์„ ๊ทธ๋ฆฐ๋‹ค. ๋ฐ”ํƒ•์ƒ‰์€ ํฐ์ƒ‰ Rectangle(hdc, 30, 40, 800 + BALL_SIZE + MOVE_STEP, 400 + BALL_SIZE + MOVE_STEP); // ๋ฐœ์‚ฌ๋Œ€๋ฅผ ๊ทธ๋ฆฐ๋‹ค. Rectangle(hdc, 50, 380, 55, 410); TextOut(hdc, 350, 450, L"ํฌ๋ฌผ์„  ์šด๋™ ์‹œ๋ฎฌ๋ ˆ์ด์…˜", 6); // ํ™”๋ฉด ์•„๋ž˜์— ๋ฌธ์ž์—ด ์ถœ๋ ฅ // ์ดˆ๊ธฐ ์†๋„ ๊ฐ’์„ ์œˆ๋„์šฐ ์ฐฝ ํ•˜๋‹จ์— ์ถœ๋ ฅํ•œ๋‹ค. wsprintf(str, TEXT("์ดˆ๊ธฐ ์†๋„ ๊ฐ’=%d"), v0); // ์†๋„ ๊ฐ’์„ ์ถœ๋ ฅํ•˜๊ธฐ ์œ„ํ•ด ๋ฌธ์ž์—ด๋กœ ๋ณ€ํ™˜ TextOut(hdc, 50, 440, str, lstrlen(str)); // ์†๋„ ๊ฐ’์„ ํ™”๋ฉด์— ์ถœ๋ ฅ for (degree = 0; degree <= 90; degree += 5) //ํฌ๋ฌผ์„ ์˜ ๊ฐ๋„ ๊ฐ’์„ 5๋„์”ฉ ์ฆ๊ฐ€์‹œํ‚ค๋ฉฐ ๊ณ„์‚ฐ { t = 0; // ์‹œ์ž‘ ์‹œ๊ฐ„ ๊ฐ’์„ 0์œผ๋กœ ์„ค์ • while (1) { // ๊ทธ๋ฆฌ๋Š” ํŽœ์˜ ํ…Œ๋‘๋ฆฌ ์ƒ‰์€ ํŒŒ๋ž€์ƒ‰, ์ฑ„์šฐ๋Š” ์ƒ‰์€ ๋นจ๊ฐ•์ƒ‰์œผ๋กœ ์„ค์ • SelectObject(hdc, CreatePen(PS_SOLID, 3, RGB(0, 0, 255))); SelectObject(hdc, CreateSolidBrush(RGB(255, 0, 0))); // ํฌ๋ฌผ์„  ์šด๋™์˜ X,Y ์ขŒํ‘œ ๊ณ„์‚ฐ x = 50 + (int)(v0 * cos((degree)*PI / 180) * t); // x์ขŒํ‘œ์˜ ๊ณ„์‚ฐ y = 400 - (int)(v0 * sin((degree)*PI / 180) * t - 1.0 / 2.0 * G * t * t); // y์ขŒํ‘œ์˜ ๊ณ„์‚ฐ // ๋ณผ์„ ๊ทธ๋ฆฐ๋‹ค. Ellipse(hdc, x, y, x + BALL_SIZE, y + BALL_SIZE); Sleep(30); // ์‹œ๊ฐ„ ์ง€์—ฐ // ๊ทธ๋ฆฌ๋Š” ํŽœ์˜ ์ƒ‰์€ ํฐ์ƒ‰, ์ฑ„์šฐ๋Š” ์ƒ‰์€ ํฐ์ƒ‰ SelectObject(hdc, CreatePen(PS_SOLID, 3, RGB(255, 255, 255))); SelectObject(hdc, CreateSolidBrush(RGB(255, 255, 255))); // ๋ฐ”ํƒ•์ƒ‰(ํฐ์ƒ‰)์œผ๋กœ ์›์„ ๊ทธ๋ ค์„œ ์›์„ ์ง€์šด๋‹ค. Ellipse(hdc, x, y, x + BALL_SIZE, y + BALL_SIZE); // ๊ทธ๋ฆฌ๋Š” ํŽœ์˜ ์ƒ‰์€ ๋นจ๊ฐ•์ƒ‰, ์ฑ„์šฐ๋Š” ์ƒ‰์€ ํฐ์ƒ‰ SelectObject(hdc, CreatePen(PS_SOLID, 3, RGB(255, 0, 0))); SelectObject(hdc, CreateSolidBrush(RGB(255, 255, 255))); // ์ž‘์€ ์›์œผ๋กœ ๊ถค์ ์„ ๊ทธ๋ ค๋‘”๋‹ค. Ellipse(hdc, x, y, x + 1, y + 1); // ๊ฐ๋„ ๊ฐ’์„ ์œˆ๋„์šฐ ์ฐฝ ํ•˜๋‹จ์— ์ถœ๋ ฅํ•œ๋‹ค. wsprintf(str, TEXT(" %3d๋„"), degree); // ๊ฐ๋„ ๊ฐ’์„ ์ถœ๋ ฅํ•˜๊ธฐ ์œ„ํ•ด ๋ฌธ์ž์—ด๋กœ ๋ณ€ํ™˜ TextOut(hdc, x, 420, str, lstrlen(str)); // ๊ฐ๋„ ๊ฐ’์„ ํ™”๋ฉด์— ์ถœ๋ ฅ // ์‹œ๊ฐ„ ๊ฐ’์„ ์ฆ๊ฐ€ t += dt; // ๋ณผ์˜ ์ขŒํ‘œ๊ฐ€ x,y ํ•œ๊ณ„ ๊ฐ’์— ๋„๋‹ฌํ–ˆ๋Š”์ง€ ๊ฒ€์‚ฌํ•˜๊ณ  ๋„๋‹ฌํ–ˆ์œผ๋ฉด ๊ณ„์‚ฐ ์ค‘๋‹จ if (x >= X_END) break; // ๋ณผ์˜ x์ขŒํ‘œ ๊ฐ’์ด 800์„ ๋„˜์–ด ๊ฐ€๋Š” ๊ฒฝ์šฐ ์ค‘๋‹จ if (y > Y_END) break; // ๋ณผ์˜ y์ขŒํ‘œ ๊ฐ’์ด 400์„ ๋„˜์–ด ๊ฐ€๋Š” ๊ฒฝ์šฐ ์ค‘๋‹จ } //while }//for return 0; }<file_sep>import pygame import os pygame.init() #์ดˆ๊ธฐํ™” ๋ฐ˜๋“œ์‹œ ํ•„์š”ํ•จ # ํ™”๋ฉด ํฌ๊ธฐ ์„ค์ • screen_width = 640 screen_height = 480 screen = pygame.display.set_mode((screen_width,screen_height)) #ํ™”๋ฉด ํƒ€์ดํ‹€ ์„ค์ • pygame.display.set_caption("PangPang Game")#๊ฒŒ์ž„ ์ด๋ฆ„ #FPS clock = pygame.time.Clock() #๋ฐฐ๊ฒฝ ์ด๋ฏธ์ง€ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ current_path = os.path.dirname(__file__) #ํ˜„์žฌ ํŒŒ์ผ์˜ ์œ„์น˜ ๋ณ€ํ™˜ image_path = os.path.join(current_path,"images") #images ํด๋” ์œ„์น˜ ๋ณ€ํ™˜ background = pygame.image.load(os.path.join(image_path,"backgr.png")) #์Šคํ…Œ์ด์ง€ ๋งŒ๋“ค๊ธฐ stage = pygame.image.load(os.path.join(image_path,"stage1.png")) stage_size = stage.get_rect().size stage_height = stage_size[1] #์บ๋ฆญํ„ฐ ๋งŒ๋“ค๊ธฐ character = pygame.image.load(os.path.join(image_path,"character.png")) character_size = character.get_rect().size character_width = character_size[0] character_height = character_size[1] character_x_pos = screen_width/2 - character_width/2 character_y_pos = screen_height - character_height - stage_height character_to_x = 0 character_speed = 5 #๋ฌด๊ธฐ ๋งŒ๋“ค๊ธฐ weapon = pygame.image.load(os.path.join(image_path,"wp.png")) weapon_size = weapon.get_rect().size weapon_width = weapon_size[0] #๋ฌด๊ธฐ๋Š” ํ•œ๋ฒˆ์— ์—ฌ๋Ÿฌ๊ฐœ ๋ฐœ์‚ฌ ๊ฐ€๋Šฅ weapons = [] #๋ฌด๊ธฐ ์ด๋™์†๋„ weapon_speed = 10 # ๊ณต ๋งŒ๋“ค๊ธฐ ball_images = [ pygame.image.load(os.path.join(image_path,"ball1.png")), pygame.image.load(os.path.join(image_path,"ball2.png")), pygame.image.load(os.path.join(image_path,"ball3.png")), pygame.image.load(os.path.join(image_path,"ball4.png"))] #ํฌ๊ธฐ์— ๋”ฐ๋ผ ์†๋„๊ฐ€ ๋‹ค๋ฆ„ ball_speed_y = [-18,-15,-12,-9] # index 0,1,2,3 #๊ณต๋“ค balls = [] #์ตœ์ดˆ ๋ฐœ์ƒํ•˜๋Š” ํฐ ๊ณต balls.append({ "pos_x" : 50, #๊ณต์˜ x,y ์ขŒํ‘œ "pos_y" : 50, "img_idx" : 0,#๊ณต์˜ ์ด๋ฏธ์ง€ ์ธ๋ฑ์Šค "to_x":3,# ๊ณต์˜ x์ถ• ์ด๋™๋ฐฉํ–ฅ "to_y":-6, # y์ถ• ์ด๋™๋ฐฉํ–ฅ "init_spd_y" : ball_speed_y[0]# y ์ตœ์ดˆ ์†๋„ }) # ์‚ฌ๋ผ์งˆ ๋ฌด๊ธฐ, ๊ณต ์ •๋ณด ์ €์žฅ ๋ณ€์ˆ˜ weapon_to_remove = -1 ball_to_remove = -1 #Font ์ •์˜ game_font = pygame.font.Font(None,40) total_time = 100 start_game = pygame.time.get_ticks() game_result = "Game Over" # ์ด๋ฒคํŠธ ๋ฃจํ”„ running = True #๊ฒŒ์ž„์ด ์ง„ํ–‰์ค‘์ธ๊ฐ€? while running: dt = clock.tick(30) #๊ฒŒ์ž„ํ™”๋ฉด์˜ ์ดˆ๋‹น ํ”„๋ ˆ์ž„ ์ˆ˜ ์„ค์ • print("fps : "+str(clock.get_fps())) for event in pygame.event.get(): #์–ด๋–ค ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€๋Š”๊ฐ€? if event.type == pygame.QUIT: #์ฐฝ์ด ๋‹ซํžˆ๋Š” ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€๋Š”๊ฐ€? running = False #๊ฒŒ์ž„์ด ์ง„ํ–‰์ค‘์ด ์•„๋‹ˆ๋‹ค. if event.type == pygame.KEYDOWN: if event.key==pygame.K_LEFT: character_to_x -= character_speed elif event.key == pygame.K_RIGHT: character_to_x += character_speed elif event.key == pygame.K_SPACE: weapon_x_pos = character_x_pos + character_width/2 - weapon_width/2 weapon_y_pos = character_y_pos weapons.append([weapon_x_pos,weapon_y_pos]) if event.type == pygame.KEYUP: if event.key==pygame.K_LEFT or event.key==pygame.K_RIGHT: character_to_x = 0 character_x_pos += character_to_x if character_x_pos <0: character_x_pos = 0 elif character_x_pos>screen_width - character_width: character_x_pos = screen_width-character_width #๋ฌด๊ธฐ์œ„์น˜ ์กฐ์ • weapons = [[w[0],w[1] - weapon_speed] for w in weapons] #์ฒœ์žฅ์— ๋‹ฟ์€ ๋ฌด๊ธฐ ์—†์—๊ธฐ weapons = [[w[0],w[1]] for w in weapons if w[1] > 0] #๊ณต ์œ„์น˜ ์ •์˜ for ball_idx,ball_val in enumerate(balls): ball_pos_x = ball_val["pos_x"] ball_pos_y = ball_val["pos_y"] ball_img_idx = ball_val["img_idx"] ball_size = ball_images[ball_img_idx].get_rect().size ball_width = ball_size[0] ball_height = ball_size[1] #๊ฐ€๋กœ๋ฒฝ์— ๋‹ฟ์•˜์„ ๋•Œ ๊ณต ์ด๋™ ๋ฐฉํ–ฅ ๋ณ€๊ฒฝ if ball_pos_x < 0 or ball_pos_x > screen_width - ball_width: ball_val["to_x"] = ball_val["to_x"]*-1 #์„ธ๋กœ ์œ„์น˜ #์Šคํ…Œ์ด์ง€์— ํŠ•๊ฒจ์„œ ์˜ฌ๋ผ๊ฐ€๋Š” ์ฒ˜๋ฆฌ if ball_pos_y >= screen_height - stage_height - ball_height: ball_val["to_y"] = ball_val["init_spd_y"] else:# ๊ทธ ์™ธ์—๋Š” ์†๋„๋ฅผ ์ฆ๊ฐ€ ball_val["to_y"]+=0.5 ball_val["pos_x"]+=ball_val["to_x"] ball_val["pos_y"]+=ball_val["to_y"] # ์บ๋ฆญํ„ฐ rect์ •๋ณด ์—…๋ฐ์ดํŠธ character_rect = character.get_rect() character_rect.left = character_x_pos character_rect.top = character_y_pos for ball_idx,ball_val in enumerate(balls): ball_pos_x = ball_val["pos_x"] ball_pos_y = ball_val["pos_y"] ball_img_idx = ball_val["img_idx"] # ๊ณต rext์ •๋ณด ์—…๋ฐ์ดํŠธ ball_rect = ball_images[ball_img_idx].get_rect() ball_rect.left = ball_pos_x ball_rect.top = ball_pos_y # ๊ณต๊ณผ ์บ๋ฆญํ„ฐ ์ถฉ๋Œ์ฒ˜๋ฆฌ if character_rect.colliderect(ball_rect): running = False break #๊ณต๊ณผ ๋ฌด๊ธฐ๋“ค ์ถฉ๋Œ์ฒ˜๋ฆฌ for weapon_idx,weapon_val in enumerate(weapons): weapon_pos_x = weapon_val[0] weapon_pos_y = weapon_val[1] #๋ฌด๊ธฐ rect ์ •๋ณด ์—…๋ฐ์ดํŠธ weapon_rect = weapon.get_rect() weapon_rect.left = weapon_pos_x weapon_rect.top = weapon_pos_y #์ถฉ๋Œ ์ฒดํฌ if weapon_rect.colliderect(ball_rect): weapon_to_remove = weapon_idx # ํ•ด๋‹น ๋ฌด๊ธฐ ์—†์• ๊ธฐ ์œ„ํ•œ ๊ฐ’ ์„ค์ • ball_to_remove = ball_idx #๊ฐ€์žฅ ์ž‘์€ ๊ณต์ด ์•„๋‹ˆ๋ผ๋ฉด ๋‹ค์Œ ๋‹จ๊ณ„์˜ ๊ณต์œผ๋กœ ๋‚˜๋ˆ ์ฃผ๊ธฐ if ball_img_idx < 3: ball_width = ball_rect.size[0] ball_height = ball_rect.size[1] #๋‚˜๋ˆ ์ง„ ๊ณต ์ •๋ณด small_ball_rect = ball_images[ball_img_idx+1].get_rect() small_ball_width = small_ball_rect.size[0] small_ball_height = small_ball_rect.size[1] #์™ผ์ชฝ์œผ๋กœ ํŠ•๊ฒจ๋‚˜๊ฐ€๋Š” ์ž‘์€ ๊ณต balls.append({ "pos_x" : ball_pos_x+(ball_width/2)-(small_ball_width/2), #๊ณต์˜ x,y ์ขŒํ‘œ "pos_y" : ball_pos_y+(ball_height/2)-(small_ball_height/2), "img_idx" : ball_img_idx+1,#๊ณต์˜ ์ด๋ฏธ์ง€ ์ธ๋ฑ์Šค "to_x":-3,# ๊ณต์˜ x์ถ• ์ด๋™๋ฐฉํ–ฅ "to_y":-6, # y์ถ• ์ด๋™๋ฐฉํ–ฅ "init_spd_y" : ball_speed_y[ball_img_idx+1]# y ์ตœ์ดˆ ์†๋„ }) # ์˜ค๋ฅธ์ชฝ์œผ๋กœ ํŠ•๊ฒจ๋‚˜๊ฐ€๋Š” ์ž‘์€ ๊ณต balls.append({ "pos_x" : ball_pos_x+(ball_width/2)-(small_ball_width/2), #๊ณต์˜ x,y ์ขŒํ‘œ "pos_y" : ball_pos_y+(ball_height/2)-(small_ball_height/2), "img_idx" : ball_img_idx+1,#๊ณต์˜ ์ด๋ฏธ์ง€ ์ธ๋ฑ์Šค "to_x":+3,# ๊ณต์˜ x์ถ• ์ด๋™๋ฐฉํ–ฅ "to_y":-6, # y์ถ• ์ด๋™๋ฐฉํ–ฅ "init_spd_y" : ball_speed_y[ball_img_idx+1]# y ์ตœ์ดˆ ์†๋„ }) break #์ถฉ๋Œ๋œ ๊ณต, ๋ฌด๊ธฐ ์—†์• ๊ธฐ if ball_to_remove >-1: del balls[ball_to_remove] ball_to_remove = -1 if weapon_to_remove >-1: del weapons[weapon_to_remove] weapon_to_remove = -1 #๋ชจ๋“  ๊ณต์„ ์—†์•ค ๊ฒฝ์šฐ ๊ฒŒ์ž„ ์ข…๋ฃŒ if len(balls)==0: game_result = "Mission Complete" running = False screen.blit(background,(0,0)) for weapon_x_pos,weapon_y_pos in weapons: screen.blit(weapon,(weapon_x_pos,weapon_y_pos)) for idx,val in enumerate(balls): ball_pos_x = val["pos_x"] ball_pos_y = val["pos_y"] ball_img_idx = val["img_idx"] screen.blit(ball_images[ball_img_idx],(ball_pos_x,ball_pos_y)) screen.blit(stage,(0,screen_height - stage_height)) screen.blit(character,(character_x_pos,character_y_pos)) #๊ฒฝ๊ณผ ์‹œ๊ฐ„ ๊ณ„์‚ฐ elapsed_time = (pygame.time.get_ticks() - start_game)/1000 timer = game_font.render("Time : {}".format(int(total_time - elapsed_time)),True,(255,255,255)) screen.blit(timer,(10,10)) #์‹œ๊ฐ„ ์ดˆ๊ณผํ–ˆ๋‹ค๋ฉด if total_time-elapsed_time<=0: game_result = "Time Over" running = False pygame.display.update() # ๊ฒŒ์ž„ํ™”๋ฉด์„ ๋‹ค์‹œ ๊ทธ๋ฆฐ๋‹ค. #pygame ์ข…๋ฃŒ #๊ฒŒ์ž„ ์˜ค๋ฒ„ ๋ฉ”์‹œ์ง€ msg = game_font.render(game_result,True,(255,255,0)) #๋…ธ๋ž€์ƒ‰ ๊ธ€์ž msg_rect = msg.get_rect(center = (int(screen_width/2),int(screen_height/2))) screen.blit(msg,msg_rect) pygame.display.update() #์ž ์‹œ ๋Œ€๊ธฐ pygame.time.delay(2000) pygame.quit() <file_sep># ์‚ฌ์ „{} cabinet = {3:"์œ ์žฌ์„",100:"๊น€ํƒœํ˜ธ"} print(cabinet[3]) print(cabinet[100]) print(cabinet.get(3)) print(cabinet.get(5,"์‚ฌ์šฉ๊ฐ€๋Šฅ")) #๊ธฐ์™•์ด๋ฉด get ํ•จ์ˆ˜๋ฅผ ์“ฐ๋Š” ๊ฒƒ ์ถ”์ฒœ. ํ”„๋กœ๊ทธ๋žจ์„ ์ด์–ด์„œ ์‹คํ–‰ ์‹œ์ผœ์ค€๋‹ค. print(3 in cabinet) #True print(5 in cabinet) #False print(cabinet) cabinet = {"A-3":"์œ ์žฌ์„","B-100":"๊น€ํƒœํ˜ธ"} cabinet["C-20"] = "์กฐ์ƒˆํ˜ธ" cabinet["A-3"] = "๊น€์ข…๊ตญ" print(cabinet) # ๊ฐ„ ์†๋‹˜ del cabinet["A-3"] print(cabinet) #์ด ์‚ฌ์šฉ์ค‘์ธ ์—ด์‡ ๋“ค ์ถœ๋ ฅ print(cabinet.keys()) # ๊ฐ’๋“ค ๋งŒ ์ถœ๋ ฅ print(cabinet.values()) #ํ‚ค ์™€ ๊ฐ’ ๋ชจ๋‘ ์ถœ๋ ฅ print(cabinet.items())<file_sep>import pygame pygame.init() #์ดˆ๊ธฐํ™” ๋ฐ˜๋“œ์‹œ ํ•„์š”ํ•จ # ํ™”๋ฉด ํฌ๊ธฐ ์„ค์ • screen_width = 480 screen_height = 640 screen = pygame.display.set_mode((screen_width,screen_height)) #ํ™”๋ฉด ํƒ€์ดํ‹€ ์„ค์ • pygame.display.set_caption("EL Game")#๊ฒŒ์ž„ ์ด๋ฆ„ #๋ฐฐ๊ฒฝ ์ด๋ฏธ์ง€ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ1 background = pygame.image.load("C:\\Users\\Administrator\\Desktop\\๋‚˜๋„์ฝ”๋”ฉํŒŒ์ด์ฌ\\๋‚˜๋„์ฝ”๋”ฉํŒŒ์ด์ฌ๊ฒŒ์ž„\\background.png") # ์ด๋ฒคํŠธ ๋ฃจํ”„ running = True #๊ฒŒ์ž„์ด ์ง„ํ–‰์ค‘์ธ๊ฐ€? while running: for event in pygame.event.get(): #์–ด๋–ค ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€๋Š”๊ฐ€? if event.type == pygame.QUIT: #์ฐฝ์ด ๋‹ซํžˆ๋Š” ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€๋Š”๊ฐ€? running = False #๊ฒŒ์ž„์ด ์ง„ํ–‰์ค‘์ด ์•„๋‹ˆ๋‹ค. # screen.fill((0,0,255)) #๋ฐฐ๊ฒฝ์„ ๋‹จ์ƒ‰์œผ๋กœ ์ฑ„์šด๋‹ค. screen.blit(background,(0,0)) #๋ฐฐ๊ฒฝ์ด ๋‚˜ํƒ€๋‚  ์ง€์  ์„ค์ • pygame.display.update() # ๊ฒŒ์ž„ํ™”๋ฉด์„ ๋‹ค์‹œ ๊ทธ๋ฆฐ๋‹ค. #pygame ์ข…๋ฃŒ pygame.quit() <file_sep>import pygame pygame.init() #์ดˆ๊ธฐํ™” ๋ฐ˜๋“œ์‹œ ํ•„์š”ํ•จ # ํ™”๋ฉด ํฌ๊ธฐ ์„ค์ • screen_width = 480 screen_height = 640 screen = pygame.display.set_mode((screen_width,screen_height)) #ํ™”๋ฉด ํƒ€์ดํ‹€ ์„ค์ • pygame.display.set_caption("EL Game")#๊ฒŒ์ž„ ์ด๋ฆ„ # ์ด๋ฒคํŠธ ๋ฃจํ”„ running = True #๊ฒŒ์ž„์ด ์ง„ํ–‰์ค‘์ธ๊ฐ€? while running: for event in pygame.event.get(): #์–ด๋–ค ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€๋Š”๊ฐ€? if event.type == pygame.QUIT: #์ฐฝ์ด ๋‹ซํžˆ๋Š” ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€๋Š”๊ฐ€? running = False #๊ฒŒ์ž„์ด ์ง„ํ–‰์ค‘์ด ์•„๋‹ˆ๋‹ค. #pygame ์ข…๋ฃŒ pygame.quit() <file_sep># print("๋‚˜๋Š” {}์‚ด ์ž…๋‹ˆ๋‹ค.".format(20)) # print("๋‚˜๋Š” {}์ƒ‰๊ณผ {}์ƒ‰์„ ์ข‹์•„ํ•ด์š”.".format("ํŒŒ๋ž€","๋นจ๊ฐ„")) # print("๋‚˜๋Š” {age}์‚ด ์ด๋ฉฐ, {color}์ƒ‰์„ ์ข‹์•„ํ•ด์š”.".format(age = 20,color = "๋นจ๊ฐ„")) # age = 20 # color = "๋…ธ๋ž€" # print(f"๋‚˜๋Š” {age}์‚ด ์ด๋ฉฐ, {color}์ƒ‰์„ ์ข‹์•„ํ•ด์š”.") # print("๋ฐฑ๋ฌธ์ด๋ถˆ์—ฌ์ผ๊ฒฌ \n๋ฐฑ๊ฒฌ์ด ๋ถˆ์—ฌ์ผํƒ€.") # print("์ €๋Š” \"๋‚˜๋„์ฝ”๋”ฉ\" ์ž…๋‹ˆ๋‹ค.") # # \\ : ๋ฌธ์žฅ ๋‚ด์—์„œ \ ๋กœ # print("C:\\Users\\Administrator\\Desktop\\๋‚˜๋„์ฝ”๋”ฉํŒŒ์ด์ฌ> ") # # \r : ์ปค์„œ๋ฅผ ๋งจ ์•ž์œผ๋กœ ์ด๋™ # print(" Red Apple\rPine") #Red ๊ฐ€ Pine ์œผ๋กœ ๋Œ€์ฒด # # \b : ๋ฐฑ์ŠคํŽ˜์ด์Šค # print("Redd\b Apple") # # \t : tab # print("Red\tApple") # site = "http://naver.com" # site1 = site[7:] # site2 = site.replace("http://","") # print(site2) # site3 = site2[:site2.index(".")] #index is number. # print(site3) # password = site3[:3]+str(len(site3))+str(site3.count("e"))+"!" # #len and count is number, so we should write str # print("{} ์˜ ๋น„๋ฐ€๋ฒˆํ˜ธ๋Š” {} ์ž…๋‹ˆ๋‹ค.".format(site,password)) <file_sep># # ๋งˆ๋ฆฐ : ๊ณต๊ฒฉ ์œ ๋‹›, ๊ตฐ์ธ. ์ด ์ ์ˆ˜ ์žˆ์Œ # name = "๋งˆ๋ฆฐ" # hp = 40 # damage = 5 # print("{} ์œ ๋‹›์ด ์ƒ์„ฑ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.".format(name)) # print("์ฒด๋ ฅ {} , ๊ณต๊ฒฉ๋ ฅ {} \n".format(hp,damage)) # # ํƒฑํฌ : ๊ณต๊ฒฉ ์œ ๋‹›, ํƒฑํฌ. ์ผ๋ฐ˜/์‹œ์ฆˆ๋ชจ๋“œ # tank_name ="ํƒฑํฌ" # tank_hp = 150 # tank_damage = 35 # print("{} ์œ ๋‹›์ด ์ƒ์„ฑ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.".format(tank_name)) # print("์ฒด๋ ฅ {} , ๊ณต๊ฒฉ๋ ฅ {} \n".format(tank_hp,tank_damage)) # def attack(name,location,damage): # print("{} : {} ๋ฐฉํ–ฅ์œผ๋กœ ์ ๊ตฐ์„ ๊ณต๊ฒฉ ํ•ฉ๋‹ˆ๋‹ค.[๊ณต๊ฒฉ๋ ฅ {}]".format(\ # name, location,damage)) # attack(name,"1์‹œ",damage) # attack(tank_name,"1์‹œ",tank_damage) # class Unit: # def __init__(self,name,hp,damage): # self.name = name # self.hp = hp # marine = Unit("๋งˆ๋ฆฐ",40,5) # marine2 = Unit("๋งˆ๋ฆฐ",40,5) # tank = Unit("ํƒฑํฌ",150,35) # ๋ ˆ์ด์Šค : ๊ณต์ค‘์œ ๋‹›, ๋น„ํ–‰๊ธฐ, ํด๋กœํ‚น # wraith1 = Unit("๋ ˆ์ด์Šค",80,5) # print("์œ ๋‹› ์ด๋ฆ„ : {}, ๊ณต๊ฒฉ๋ ฅ : {} ".format(wraith1.name,wraith1.damage)) # #๋งˆ์ธ๋“œ ์ปจํŠธ๋กค : ์ƒ๋Œ€๋ฐฉ ์œ ๋‹›์„ ๋‚ด ๊ฒƒ์œผ๋กœ # wraith2 = Unit("๋นผ์•—์€ ๋ ˆ์ด์Šค",80,5) # wraith2.clocking = True #ํŒŒ์ด์ฌ ์—์„œ๋Š” ํด๋ž˜์Šค ์™ธ๋ถ€์—์„œ ๋ณ€์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด ์“ธ ์ˆ˜ ์žˆ๋‹ค. # if wraith2.clocking == True: # print("{} ๋Š” ํ˜„์žฌ ํด๋กœํ‚น ์ƒํƒœ์ž…๋‹ˆ๋‹ค.".format(wraith2.name)) # if wraith1.clocking == True: #๊ธฐ์กด์˜ ๊ฐœ์ฒด์—๋Š” ์ถ”๊ฐ€ ๋˜์ง€ ์•Š๋Š”๋‹ค. # print("{} ๋Š” ํ˜„์žฌ ํด๋กœํ‚น ์ƒํƒœ์ž…๋‹ˆ๋‹ค.".format(wraith2.name)) class Unit: def __init__(self,name,hp): self.name = name self.hp = hp class AttackUnit(Unit): def __init__(self,name,hp,damage): Unit.__init__(self,name,hp) self.damage = damage def attack(self,location): print("{} : {} ๋ฐฉํ–ฅ์œผ๋กœ ์ ๊ตฐ์„ ๊ณต๊ฒฉ ํ•ฉ๋‹ˆ๋‹ค.[๊ณต๊ฒฉ๋ ฅ : {} ]".format(\ self.name,location,self.damage)) def damaged(self,damage): print("{} : {} ๋ฐ๋ฏธ์ง€๋ฅผ ์ž…์—ˆ์Šต๋‹ˆ๋‹ค.".format(self.name,damage)) self.hp -=damage print("{} : ํ˜„์žฌ ์ฒด๋ ฅ์€ {} ์ž…๋‹ˆ๋‹ค.".format(self.name,self.hp)) if self.hp<=0 : print("{} : ํŒŒ๊ดด๋˜์—ˆ์Šต๋‹ˆ๋‹ค.".format(self.name)) firebat1 = AttackUnit("ํŒŒ์ด์–ด๋ฑƒ",50,16) firebat1.attack("5์‹œ") firebat1.damaged(25) firebat1.damaged(25) # ๋“œ๋ž์‰ฝ : ๊ณต์ค‘์œ ๋‹›, ์ˆ˜์†ก๊ธฐ class Flyable: def __init__(self,flying_speed): self.flying_speed = flying_speed def fly(self,name,location): print("{} : {} ๋ฐฉํ–ฅ์œผ๋กœ ๋‚ ์•„๊ฐ‘๋‹ˆ๋‹ค.[์†๋„ {}]".format(\ name,location,self.flying_speed)) class FlyableAttackUnit(AttackUnit,Flyable): def __init__(self,name,hp,damage,flying_speed): AttackUnit.__init__(self,name,hp,damage) Flyable.__init__(self,flying_speed) #๋ฐœํ‚ค๋ฆฌ : ๊ณต์ค‘ ๊ณต๊ฒฉ ์œ ๋‹›, ํ•œ๋ฒˆ์— 4๋ฒˆ ๊ณต๊ฒฉ valkyrie = FlyableAttackUnit("๋ฐœํ‚ค๋ฆฌ",200,6,5) valkyrie.fly(valkyrie.name,"3์‹œ") <file_sep>class Unit: def __init__(self,name,hp,speed): self.name = name self.hp = hp self.speed = speed def move(self,location): print("[์ง€์ƒ ์œ ๋‹› ์ด๋™]") print("{} : {} ๋ฐฉํ–ฅ์œผ๋กœ ์ด๋™ํ•ฉ๋‹ˆ๋‹ค.[์†๋„ : {}]".format(\ self.name,location,self.speed)) class AttackUnit(Unit): def __init__(self,name,hp,speed,damage): Unit.__init__(self,name,hp,speed) self.damage = damage def attack(self,location): print("{} : {} ๋ฐฉํ–ฅ์œผ๋กœ ์ ์„ ๊ณต๊ฒฉํ•ฉ๋‹ˆ๋‹ค.[๊ณต๊ฒฉ๋ ฅ : {} ]".formant(\ self.name,location,self.damage)) def damaged(self,damage): print("{} : {} ๋ฐ๋ฏธ์ง€๋ฅผ ์ž…์—ˆ์Šต๋‹ˆ๋‹ค.".format(self.name,damage)) self.hp -= damage print("{} : ํ˜„์žฌ ์ฒด๋ ฅ์€ {} ์ž…๋‹ˆ๋‹ค.".format(self.name,self.hp)) if self.hp <=0: print("{} : ํŒŒ๊ดด๋˜์—ˆ์Šต๋‹ˆ๋‹ค.".format(self.name)) class Flyable: def __init__(self,flying_speed): self.flying_speed = flying_speed def fly(self,name,location): print("{} : {} ๋ฐฉํ–ฅ์œผ๋กœ ๋‚ ์•„๊ฐ‘๋‹ˆ๋‹ค.[์†๋„ : {}]".format(name,location,self.flying_speed)) class FlyableAttackUnit(AttackUnit,Flyable): def __init__(self,name,hp,damage,flying_speed): AttackUnit.__init__(self,name,hp,0,damage) #์ง€์ƒ ์Šคํ”ผ๋“œ๋Š” 0 Flyable.__init__(self,flying_speed) def move(self,location): print("[๊ณต์ค‘ ์œ ๋‹› ์ด๋™]") self.fly(self.name,location) # ๋ฒŒ์ฒ˜ : ์ง€์ƒ์œ ๋‹›, ๊ธฐ๋™์„ฑ ์ข‹์Œ # vulture = AttackUnit("๋ฒŒ์ฒ˜",80,10,20) # battlecruiser = FlyableAttackUnit("๋ฐฐํ‹€ํฌ๋ฃจ์ €",500,25,3) # vulture.move("11์‹œ") # battlecruiser.move("9์‹œ") #๊ฑด๋ฌผ class BuildingUinit(Unit): def __init__(self,name,hp,location): # Unit.__init__(self,name,hp,0) super().__init__(name,hp,0) self.location = location # supply_depot = BuildingUinit("์„œํ”Œ๋ผ์ด ๋””ํฟ",500,"7์‹œ") # def game_start(): # print("[์•Œ๋ฆผ] ์ƒˆ๋กœ์šด ๊ฒŒ์ž„์„ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค.") # def game_over(): # pass <file_sep>import pygame import os pygame.init() #์ดˆ๊ธฐํ™” ๋ฐ˜๋“œ์‹œ ํ•„์š”ํ•จ # ํ™”๋ฉด ํฌ๊ธฐ ์„ค์ • screen_width = 640 screen_height = 480 screen = pygame.display.set_mode((screen_width,screen_height)) #ํ™”๋ฉด ํƒ€์ดํ‹€ ์„ค์ • pygame.display.set_caption("PangPang Game")#๊ฒŒ์ž„ ์ด๋ฆ„ #FPS clock = pygame.time.Clock() #๋ฐฐ๊ฒฝ ์ด๋ฏธ์ง€ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ current_path = os.path.dirname(__file__) #ํ˜„์žฌ ํŒŒ์ผ์˜ ์œ„์น˜ ๋ณ€ํ™˜ image_path = os.path.join(current_path,"images") #images ํด๋” ์œ„์น˜ ๋ณ€ํ™˜ background = pygame.image.load(os.path.join(image_path,"backgr.png")) #์Šคํ…Œ์ด์ง€ ๋งŒ๋“ค๊ธฐ stage = pygame.image.load(os.path.join(image_path,"stage1.png")) stage_size = stage.get_rect().size stage_height = stage_size[1] #์บ๋ฆญํ„ฐ ๋งŒ๋“ค๊ธฐ character = pygame.image.load(os.path.join(image_path,"character.png")) character_size = character.get_rect().size character_width = character_size[0] character_height = character_size[1] character_x_pos = screen_width/2 - character_width/2 character_y_pos = screen_height - character_height - stage_height character_to_x = 0 character_speed = 5 #๋ฌด๊ธฐ ๋งŒ๋“ค๊ธฐ weapon = pygame.image.load(os.path.join(image_path,"wp.png")) weapon_size = weapon.get_rect().size weapon_width = weapon_size[0] #๋ฌด๊ธฐ๋Š” ํ•œ๋ฒˆ์— ์—ฌ๋Ÿฌ๊ฐœ ๋ฐœ์‚ฌ ๊ฐ€๋Šฅ weapons = [] #๋ฌด๊ธฐ ์ด๋™์†๋„ weapon_speed = 10 # ์ด๋ฒคํŠธ ๋ฃจํ”„ running = True #๊ฒŒ์ž„์ด ์ง„ํ–‰์ค‘์ธ๊ฐ€? while running: dt = clock.tick(30) #๊ฒŒ์ž„ํ™”๋ฉด์˜ ์ดˆ๋‹น ํ”„๋ ˆ์ž„ ์ˆ˜ ์„ค์ • print("fps : "+str(clock.get_fps())) for event in pygame.event.get(): #์–ด๋–ค ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€๋Š”๊ฐ€? if event.type == pygame.QUIT: #์ฐฝ์ด ๋‹ซํžˆ๋Š” ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€๋Š”๊ฐ€? running = False #๊ฒŒ์ž„์ด ์ง„ํ–‰์ค‘์ด ์•„๋‹ˆ๋‹ค. if event.type == pygame.KEYDOWN: if event.key==pygame.K_LEFT: character_to_x -= character_speed elif event.key == pygame.K_RIGHT: character_to_x += character_speed elif event.key == pygame.K_SPACE: weapon_x_pos = character_x_pos + character_width/2 - weapon_width/2 weapon_y_pos = character_y_pos weapons.append([weapon_x_pos,weapon_y_pos]) if event.type == pygame.KEYUP: if event.key==pygame.K_LEFT or event.key==pygame.K_RIGHT: character_to_x = 0 character_x_pos += character_to_x if character_x_pos <0: character_x_pos = 0 elif character_x_pos>screen_width - character_width: character_x_pos = screen_width-character_width #๋ฌด๊ธฐ์œ„์น˜ ์กฐ์ • weapons = [[w[0],w[1] - weapon_speed] for w in weapons] #์ฒœ์žฅ์— ๋‹ฟ์€ ๋ฌด๊ธฐ ์—†์—๊ธฐ weapons = [[w[0],w[1]] for w in weapons if w[1] > 0] screen.blit(background,(0,0)) for weapon_x_pos,weapon_y_pos in weapons: screen.blit(weapon,(weapon_x_pos,weapon_y_pos)) screen.blit(stage,(0,screen_height - stage_height)) screen.blit(character,(character_x_pos,character_y_pos)) pygame.display.update() # ๊ฒŒ์ž„ํ™”๋ฉด์„ ๋‹ค์‹œ ๊ทธ๋ฆฐ๋‹ค. #์ž ์‹œ ๋Œ€๊ธฐ pygame.time.delay(2000) #pygame ์ข…๋ฃŒ pygame.quit() <file_sep># def profile(name,age,lang): # print(name,age,lang) # profile(name = "์œ ์žฌ์„",lang = "ํŒŒ์ด์ฌ",age = 20) # def profile(name,age,lang1,lang2,lang3,lang4,lang5): # print("์ด๋ฆ„ : {} ๋‚˜์ด : {} ".format(name,age),end = " ") # print(lang1,lang2,lang3,lang4,lang5) def profile(name,age,*lang): print("์ด๋ฆ„ : {} ๋‚˜์ด : {} ".format(name,age),end = " ") for langu in lang: print(langu,end=" ") print() profile("์œ ์žฌ์„",20,"P","C","V","T","H") profile("๊น€ํƒœํ˜ธ",25,"K","s")<file_sep>import pickle # profile_file = open("profile.pickle","wb") #์“ฐ๊ธฐ # profile={"์ด๋ฆ„":"๋ฐ•๋ช…์ˆ˜","๋‚˜์ด":30,"์ทจ๋ฏธ":["์ถ•๊ตฌ","๊ณจํ”„","์ฝ”๋”ฉ"]} # print(profile) # pickle.dump(profile,profile_file) #profile์— ์žˆ๋Š” ์ •๋ณด๋ฅผ file ์— ์ €์žฅ # profile_file.close() profile_file = open("profile.pickle","rb") #์ฝ๊ธฐ profile = pickle.load(profile_file) #file ์— ์žˆ๋Š” ์ •๋ณด๋ฅผ profile ์— ๋ถˆ๋Ÿฌ์˜ค๊ธฐ print(profile) profile_file.close()
0207a004b33878d6f683c2e29edaa1ed6afb75a9
[ "Python", "C++" ]
40
Python
dongwoo0524/memo_git
6dd37183d7154bebf30cd0b9af512db48b040740
8259c76963bca7ff7711387d1b6248eaf66b56eb
refs/heads/master
<file_sep> --็ญ‰ๅพ…้กต้ขๅนถ็‚นๅ‡ป๏ผŒpage:้œ€่ฆ็ญ‰ๅพ…ๅ‡บ็Žฐ็š„้กต้ข๏ผŒsleeptime:็ญ‰ๅพ…้—ด้š”๏ผŒtimeout:็ญ‰ๅพ…่ถ…ๆ—ถๆ—ถ้—ด,fuzzy:ๆ‰พ่‰ฒ็›ธไผผๅบฆ function WaitingAndClick(waitpage,clickicon,unit,timeout,sleeptime,fuzzy) sleeptime = sleeptime or 1000 --้ป˜่ฎค้‡ๅคๅˆคๆ–ญ็ญ‰ๅพ…ๆ—ถ้—ดไธบ1000ๆฏซ็ง’ timeout = timeout or 3000 --้ป˜่ฎค่ถ…ๆ—ถๆ—ถ้—ด3000ๆฏซ็ง’ fuzzy = fuzzy or 90 --้ป˜่ฎค็›ธไผผๅบฆ90% unit = unit or 0 --ๅ†…้ขๅ†…้ƒจ้ƒจไปถ๏ผŒ้ป˜่ฎคๆ ‡็ญพไธบ0 --ๅ•็‚นๆจก็ณŠๆฏ”่‰ฒ local function IsColor(pixelpoint,fuzzy) local fl,abs = math.floor,math.abs fuzzy = fl(0xff*(100-fuzzy)*0.01) local r,g,b = fl(pixelpoint[3]/0x10000),fl(pixelpoint[3]%0x10000/0x100),fl(pixelpoint[3]%0x100) local rr,gg,bb = getColorRGB(pixelpoint[1],pixelpoint[2]) if abs(r-rr)<fuzzy and abs(g-gg)<fuzzy and abs(b-bb)<fuzzy then return true end end if waitpage[clickicon].Unit ~= unit and waitpage[clickicon].Unit ~=0 then nLog("ๆ ‡็ญพ้”™่ฏฏ๏ผŒ่ฏทไป”็ป†ๆ ธๅฏน") return end local curtime = 0 local mismatching = 0 while true do for k,v in pairs(waitpage) do if v.Pixelpoint and (v.Unit == unit or v.Unit == 0) and not IsColor(v.Pixelpoint,fuzzy) then nLog("ๅ›พๆ ‡๏ผš<"..k..">ไธๅŒน้…") mismatching = 1 break end end if mismatching == 0 then break end mismatching = 0 if curtime >= timeout then nLog("่ถ…ๆ—ถๆœชๆ‰พๅˆฐ้กต้ข") return end mSleep(sleeptime) curtime = curtime + sleeptime end touchDown(0,waitpage[clickicon].Pixelpoint[1],waitpage[clickicon].Pixelpoint[2]) mSleep(100) touchUp(0,waitpage[clickicon].Pixelpoint[1],waitpage[clickicon].Pixelpoint[2]) return true end<file_sep>-- ๅฎˆๆœ›้ปŽๆ˜Žmac -- main.lua -- Create By TouchSpriteStudio on 10:29:23 -- Copyright ยฉ TouchSpriteStudio . All rights reserved. require("TSLib") require('tsp') require('AWZ') if not(t) then t ={} degree = 90 end t['ๅนฟๅ‘Š่ดญไนฐๆŒ‰้’ฎ'] = { 0xcc9c68,"-145|36|0x7e5d29,150|34|0x433f3b,81|68|0xd9bc6d,100|41|0x745420",degree,200,1231,545,1332} t['่ฟ”ๅ›žๆŒ‰้’ฎ'] = { 0xfff6e2,"2|3|0x432f1c,19|-12|0x4c361b,53|-38|0xb1967c,18|-38|0xdfbb98",degree,8,51,122,144} t['่ฟ”ๅ›žๆŒ‰้’ฎ2'] = { 0xfff5e2,"21|-16|0x45372c,26|-28|0xc3a486,-1|-20|0x362a21",degree,2,48,70,113} t['็งปๅŠจๅปบ็ญ‘ๆ็คบ'] = { 0xffffff,"5|-44|0x346a40,-157|-41|0x7a2829,-153|-12|0xffffff,-30|16|0x417a56",degree,23,18,726,1311} function ad_() if d("ๅนฟๅ‘Š่ดญไนฐๆŒ‰้’ฎ")then click(715,36,2) elseif d('่ฟ”ๅ›žๆŒ‰้’ฎ',true)then elseif d('่ฟ”ๅ›žๆŒ‰้’ฎ2',true)then elseif d('็งปๅŠจๅปบ็ญ‘ๆ็คบ',true)then else click(40,40,2) end end t['ๅฎขๆœๅœจไธŠ_็™ฝ'] = { 0xd7c3a3,"5|0|0x6a8580,14|-5|0xf4dfb9,24|-10|0x6b8583",degree,72,320,114,356} t['ๅฎขๆœๅœจไธŠ_ๅคœ'] = { 0x75849e,"6|-4|0x315479,15|-7|0x8698b2,24|-12|0x33557b",degree,72,320,114,356} t['ๅฎขๆœๅœจไธ‹_็™ฝ'] = { 0xb7a68b,"5|-1|0x516769,15|-7|0xd4be9d,24|-13|0x52696b",degree,66,920,113,964} t['ๅฎขๆœๅœจไธ‹_ๅคœ'] = { 0x74849f,"5|-3|0x315378,14|-7|0x8898b6,24|-16|0x385779",degree,65,914,122,954} function center() click(693,1277,2) --็‚นๅˆฐๅŸŽๅค– click(693,1277,3) --็‚นๅ›žๅŸŽๅ†… if d('ๅฎขๆœๅœจไธŠ_็™ฝ') or d("ๅฎขๆœๅœจไธŠ_ๅคœ")then return "top" elseif d('ๅฎขๆœๅœจไธ‹_็™ฝ') or d("ๅฎขๆœๅœจไธ‹_ๅคœ") then return 'bottom' end end t['ไบคๆ˜“'] = { 0xe4c023,"1|-9|0xd5b62b,13|25|0xd57700,21|2|0xffec09",degree,527,737,619,836} t['ไบคๆ˜“2'] = { 0xf7eb19,"-5|-1|0x876919,-32|8|0xd2af23",degree,554,670,713,870} t['ไบคๆ˜“_ๅ…่ดน-ไบคๆ˜“่กŒ็•Œ้ข'] = { 0xefd884,"-7|1|0x523910,14|31|0xd9c574,17|-322|0xc6ac74,17|-324|0x55422b",degree,628,59,741,484} t['ไบคๆ˜“_็ฎฑๅญ'] = { 0xfef8d3,"-25|52|0xede5c8,-45|-3|0xb37645,25|-12|0xb87b42",degree,34,523,724,1047} t['ไบคๆ˜“_็ฎฑๅญ']={{117,642,0xeadcbb},{281,642,0xb07640},{464,644,0x1e1111},{648,640,0xf2e6c5},{110,951,0x281f25},{275,946,0x936031},{467,947,0xe3d6b6},{644,946,0xe8dbbb},} t['ไบคๆ˜“_็ฎฑๅญ_่ดญไนฐ'] = { 0x66885e,"-58|-54|0x95b27e,62|-19|0x3d5c36",degree,250,652,509,749} t['ไบคๆ˜“_็ฎฑๅญ_่ดญไนฐ_ๅ…ณ้—ญ'] = { 0xcdb195,"1|12|0x3a2d1b,12|11|0xe4d3b2,-36|-30|0xc29f76,32|21|0x443521",degree,643,303,738,394} function _trade() _trade__ = _trade__ or 0 _trade__ = _trade__ + 1 if _trade__ >= 2 then _trade__ = 0 return true end click(520,671,2) --็‚นๅ‡ปไบคๆ˜“่กŒ log('็‚นๅ‡ปไบคๆ˜“ไธญๅฟƒ') if d('ไบคๆ˜“',true) or d("ไบคๆ˜“2",true)then if d('ไบคๆ˜“_ๅ…่ดน-ไบคๆ˜“่กŒ็•Œ้ข')then for i,v in ipairs(t['ไบคๆ˜“_็ฎฑๅญ'])do click(v[1],v[2]) if not(d('ไบคๆ˜“_็ฎฑๅญ_่ดญไนฐ',true,1,2))then d('ไบคๆ˜“_็ฎฑๅญ_่ดญไนฐ_ๅ…ณ้—ญ',true) end end return true end end end t['ไธฐๆ”ถ_ไฝฟ็”จ'] = { 0xfcfafa,"2|-4|0x784a26,3|-6|0xf1ece8,-26|31|0xe2c779,15|-37|0xcc9c68",degree,202,939,545,1034} t['ไธฐๆ”ถ_ไฝฟ็”จ_็กฎๅฎš'] = { 0x3c4a5c,"12|0|0x8f97a2,-21|-34|0x6a80a6,336|-34|0xcb9b67",degree,44,763,707,854} function _foison() _trade__ = _trade__ or 0 _trade__ = _trade__ + 1 if _trade__ >= 2 then _trade__ = 0 return true end click(226,712,2) --็‚นๅ‡ปไธฐๆ”ถ log('็‚นๅ‡ป็”Ÿไบงไธญๅฟƒ') if d("ไธฐๆ”ถ_ไฝฟ็”จ",true)then d('ไธฐๆ”ถ_ไฝฟ็”จ_็กฎๅฎš',true) return true end end t['่‹ฑ้›„ๆ‹›ๅ‹Ÿ'] = { 0xfffce6,"4|4|0x5a553c,4|-2|0x1f1a0a,6|1|0xf5f5ed",degree,52,691,95,740} t['่‹ฑ้›„ๆ‹›ๅ‹Ÿ็•Œ้ข'] = { 0xfff6e2,"25|-23|0x3f301a,670|-25|0xc6ac74,671|-27|0x4f3a25",degree,9,11,745,88} t['่‹ฑ้›„ๆ‹›ๅ‹Ÿ_ๅ…่ดน'] = { 0xf5efbd,"-2|0|0x6e5018,-106|0|0x604110,89|146|0x5d732d",degree,32,977,360,1242} t['่‹ฑ้›„ๆ‹›ๅ‹Ÿ_X'] = { 0xad9477,"-412|1235|0x3e5e37,-253|1236|0x3e5e37",degree,178,10,744,1331} t['่‹ฑ้›„ๆ‹›ๅ‹Ÿ_ๅฎŒๆˆ'] = { 0x7596a7,"28|-21|0x7a9aab,14|-38|0x7997ab",degree,584,630,657,733} function _hero() _trade__ = _trade__ or 0 _trade__ = _trade__ + 1 if _trade__ >= 2 then _trade__ = 0 return true end click(6,755,2) local heroface = false -- if d('่‹ฑ้›„ๆ‹›ๅ‹Ÿ',true)then --็‚นๅ‡ป่‹ฑ้›„ log('็‚นๅ‡ป่‹ฑ้›„ๆ‹›ๅ‹Ÿ') local ii = 1 while (d("่‹ฑ้›„ๆ‹›ๅ‹Ÿ็•Œ้ข") and ii < 5) do heroface = true if d('่‹ฑ้›„ๆ‹›ๅ‹Ÿ_ๅ…่ดน',true)then delay(2) click(40,40,2) delay(2) end click(110,1235,2) ii = ii + 1 delay(2) end if heroface then return true end -- end end t['ๆขๅคๆŒ‰้’ฎ'] = { 0xc62719,"-1|16|0xc8d96d",degree,489,533,568,600} t['ๆ€ฅๆ•‘ๅธ็ฏท้กต้ข'] = { 0x6d4d19,"-139|3|0x3a5435,-389|5|0x704f19,-541|-1213|0xfff0d6,-546|-1204|0x31281e",degree,7,8,747,1331} t['ๆ€ฅๆ•‘ๅธ็ฏท้กต้ขๆ— '] = { 0x565656,"-262|1|0x595959,-522|-7|0x525252,-586|-43|0x7f7f7f,-52|10|0xf4f0ed",degree,7,1240,744,1329} function _hospital() _trade___ = _trade___ or 0 _trade___ = _trade___ + 1 if _trade___ > 2 then _trade___ = 0 return true end click(228,502,2) --็‚นๅ‡ปๅŒป้™ข delay(2) log('็‚นๅ‡ปๅŒป้™ข') if d('ๆขๅคๆŒ‰้’ฎ',true)then return d('ๆ€ฅๆ•‘ๅธ็ฏท้กต้ข',true) or d('ๆ€ฅๆ•‘ๅธ็ฏท้กต้ขๆ— ') end end t['่ฎญ็ปƒๆŒ‰้’ฎ'] = { 0x84ee27,"0|-9|0x9af131,1|14|0x3aec1f,1|30|0x482815",degree,446,663,696,869} t['่ฎญ็ปƒ็•Œ้ข'] = { 0xeec686,"511|0|0xf2ce8e,382|163|0x906c31,27|158|0x4b633f",degree,7,1092,736,1328} t['ๆญฃๅœจ่ฎญ็ปƒ'] = { 0xa77c44,"210|142|0x3f613a,556|169|0xe4cc79,494|112|0x65441d",degree,19,1111,722,1327} function _arms_ss() _trade___ = _trade___ or 0 _trade___ = _trade___ + 1 if _trade___ > 2 then _trade___ = 0 return true end click(ๅ…ต่ฅไฝ็ฝฎ[step_][1],ๅ…ต่ฅไฝ็ฝฎ[step_][2],2); log('็‚นๅ‡ปๅฐ„ๆ‰‹'); if d("่ฎญ็ปƒๆŒ‰้’ฎ",true)then return d("่ฎญ็ปƒ็•Œ้ข",true,3,2) or d("ๆญฃๅœจ่ฎญ็ปƒ") end end function _arms_ys() _trade___ = _trade___ or 0 _trade___ = _trade___ + 1 if _trade___ > 2 then _trade___ = 0 return true end click(ๅ…ต่ฅไฝ็ฝฎ[step_][1],ๅ…ต่ฅไฝ็ฝฎ[step_][2],2); log('็‚นๅ‡ปๅฐ„ๆ‰‹'); if d("่ฎญ็ปƒๆŒ‰้’ฎ",true)then return d("่ฎญ็ปƒ็•Œ้ข",true,3,2)or d("ๆญฃๅœจ่ฎญ็ปƒ") end end function _arms_cl() _trade___ = _trade___ or 0 _trade___ = _trade___ + 1 if _trade___ > 2 then _trade___ = 0 return true end click(ๅ…ต่ฅไฝ็ฝฎ[step_][1],ๅ…ต่ฅไฝ็ฝฎ[step_][2],2); log('็‚นๅ‡ปๅฐ„ๆ‰‹'); if d("่ฎญ็ปƒๆŒ‰้’ฎ",true)then return d("่ฎญ็ปƒ็•Œ้ข",true,3,2)or d("ๆญฃๅœจ่ฎญ็ปƒ") end end t['ๆ€ป้ƒจๅ‡็บง'] = { 0xe5ba85,"1|45|0xfce8be,-2|52|0x624326",degree,255,484,372,607} t['ๆœช่พพ่ฆๆฑ‚็•Œ้ข'] = { 0x797979,"272|56|0x7d7d7d,410|45|0x606060,588|-1|0x868686,565|68|0x9a9a9a",degree,23,1189,723,1321} t['ๆœช่พพ่ฆๆฑ‚็•Œ้ข2'] = { 0x2d2d2d,"189|45|0x555555,476|2|0x7e7e7e,476|0|0x2e2e2e,-78|-1133|0x3e3127,-60|-1146|0xc7a789",degree,5,52,740,1327} t['่ทณ่ฝฌX'] = { 0xa14b4a,"-10|-9|0x86403f,9|-9|0x86403f",70,451,752,515,1174} t['ๅ…ถๅฎƒๅ‡็บง'] = { 0xd6ac7b,"-1|42|0xe5cfa9,-2|50|0x5d3d20,9|46|0xe4d4ae",70,377,746,500,944} t['ๅ…ถๅฎƒๅ‡็บง2'] = { 0xe1b684,"-2|19|0xedcc9c,-3|54|0x614227,-9|49|0xfeeac0,9|48|0xfceac0",70,356,767,480,967} t['ๅ…ถๅฎƒๅ‡็บง3'] = { 0xe0c193,"1|-25|0xd8ac7b,-19|0|0x9e795b,20|0|0x9d7d60,-5|24|0xe9d4ae",degree,422,720,600,954} t['ๅ‡็บง_้‡‘ๅธ็กฎๅฎš'] = { 0xd6b523,"12|-6|0xeed820,17|-6|0x44623e,-50|-33|0xffffff,14|-61|0x17191b",degree,95,420,647,1206} t['ๅ‡็บง็•Œ้ข'] = { 0x6f5019,"-7|37|0x403524,-440|-34|0x709b58,-296|34|0xa9d796",degree,22,1180,728,1321} t['ๆดพ้ฃ'] = { 0xf8f5f3,"6|0|0x744b21,7|-2|0xede7e2,-71|-33|0x583920,42|37|0xe2c577,-85|6|0x8a642a",degree,518,282,722,1206} t['ๆดพ้ฃ2'] = { 0xdfd4cc,"-2|0|0x7a4a28,-59|27|0x87632d,85|-25|0x65411b",degree,498,144,718,796} t['ๅ‡†ๅค‡ๅผ€ไป“ๅบ“_ๅ‰ๅพ€'] = { 0x7a4b27,"-4|8|0xfbfaf9,13|11|0x845729,7|-16|0xbf9856",degree,519,950,725,1123} t['ๅผ€ไป“ๅบ“็•Œ้ข'] = { 0xd7b493,"23|17|0x3c2e1a,-13|38|0xfff3dd,60|325|0x50404,60|326|0x4e4a3f,64|328|0x1f1e1a",degree,5,8,149,373} t['ๅผ€ไป“ๅบ“็•Œ้ข_ไฝฟ็”จ'] = { 0xf6f3f0,"0|2|0x7a4a29,26|1|0xffffff,9|-27|0xa28353",degree,514,394,740,810} t['ๅผ€ไป“ๅบ“็•Œ้ข_ไฝฟ็”จ_ไฝฟ็”จ'] = { 0x774a25,"6|-1|0xfffefe,-302|-194|0xfef1db,-301|-204|0x9c8156,57|20|0x8a6632",degree,34,464,717,906} t['่พพๆˆ็›ฎๆ ‡'] = { 0xf3c484,"-46|-5|0xf3c484,50|-5|0xf3c484,-1|-8|0xa88248",degree,1,251,749,305} function _up_city() _trade___ = _trade___ or 0 _trade___ = _trade___ + 1 if _trade___ > 8 then _trade___ = 0 return true end click(388,341,2) --็‚นๅ‡ปๆ€ป้ƒจ if d('ๆ€ป้ƒจๅ‡็บง',true)then while d("ๅ‡็บง็•Œ้ข") or d('ๆœช่พพ่ฆๆฑ‚็•Œ้ข') or d('ๆœช่พพ่ฆๆฑ‚็•Œ้ข2') or d('ๅผ€ไป“ๅบ“็•Œ้ข') do delay(2) if d("่ทณ่ฝฌX")then click(x+160,y,4) if not(d('ๅ‡†ๅค‡ๅผ€ไป“ๅบ“_ๅ‰ๅพ€',true))then click_center_ = click_center_ or 0 click_center_ = click_center_ + 1 click(750/2,1334/2+(click_center_%5-2)*20,1) click(750/2,1334/2+(click_center_%5-2)*20,2) if d('ๅ…ถๅฎƒๅ‡็บง',true)then elseif d('ๅ…ถๅฎƒๅ‡็บง2',true)then elseif d('ๅ…ถๅฎƒๅ‡็บง3',true)then elseif d('ๅ‡็บง_้‡‘ๅธ็กฎๅฎš',true)then end end elseif d('ๅผ€ไป“ๅบ“็•Œ้ข')then if d('่พพๆˆ็›ฎๆ ‡')then click(40,40,2) elseif d('ๅผ€ไป“ๅบ“็•Œ้ข_ไฝฟ็”จ',true)then if d('ๅผ€ไป“ๅบ“็•Œ้ข_ไฝฟ็”จ_ไฝฟ็”จ',true)then else return true end end elseif d("ๅ‡็บง็•Œ้ข",true)then delay(2) return d("ๆดพ้ฃ",true) or d("ๆดพ้ฃ2",true) end end end end function _getthing() end t['ๆธธๆˆๆญฃๅธธ']={{591,77,0xe131a},{600,70,0xbfcdd8},{604,68,0x717e8c},{516,96,0xcda16c},} t['ๆธธๆˆๆญฃๅธธ_ๅŸŽๅ†…'] = {{49,279,0xffc983},{68,291,0x332319},{50,305,0xffedcf},} t['ๆธธๆˆๆญฃๅธธ_ๅŸŽๅค–'] = { 0x100c09,"-22|0|0xffedce,-28|-7|0x815c42,-42|-15|0xf9cd92,-58|-7|0xb79571",degree,16,168,95,234} function game_() if d('ๆธธๆˆๆญฃๅธธ')then if d('ๆธธๆˆๆญฃๅธธ_ๅŸŽๅ†…')then local ๅŸบๅœฐ_ = center() delay(rd(2,3)) if ๅŸบๅœฐ_ == 'top' then -- _up_city() step_ = step_ or 1 log("step_ --->"..step_) ๅ…ต่ฅไฝ็ฝฎ={[2]={263,666,0xbba69c},[3]={375,575,0xa6927e},[4]={522,685,0x895f49},} if step_ == 1 and _hospital()then step_ = step_ + 1 elseif step_ == 2 and _arms_ss()then step_ = step_ + 1 elseif step_ == 3 and _arms_ys()then step_ = step_ + 1 elseif step_ == 4 and _arms_cl()then step_ = step_ + 1 elseif step_ == 5 and _up_city()then return 'ๅˆ‡ๅท' end elseif ๅŸบๅœฐ_ == 'bottom' then step = step or 1 log("step --->"..step) if step == 1 and _trade() then step = step + 1 elseif step == 2 and _foison() then step = step + 1 elseif step == 3 and _hero() then step = step + 1 elseif step == 4 then toast("ๅ‡†ๅค‡้‡‡็Ÿฟ",2) end end elseif d('ๆธธๆˆๆญฃๅธธ_ๅŸŽๅค–')then click(693,1277,2) --็‚นๅˆฐๅŸŽๅค– elseif d('่ฟ”ๅ›žๆŒ‰้’ฎ2',true)then end return true end end function main() local TimeLine = os.time() local TimeOut = 60*10 while os.time()-TimeLine<TimeOut do if active('com.more.dayzsurvival.ios',6)then local res__ = game_() if res__ == 'ๅˆ‡ๅท' then return true elseif not(res__)then ad_() end delay(2) end end end while true do main() awz_next() delay(2) end <file_sep>require("tsp") --้‡ๆž„ไธ€ไธชget function get_(url) local sz = require("sz") local http = require("szocket.http") local res, code = http.request(url); if code == 200 then return res else log( res ) end end --ๅ–ๆ‰‹ๆœบๅท function getPhone() local postArr = {}; postArr['s']="App.SmsNikeReg.GetPhone"; postArr['name'] = info.smsname; local data = post('http://sms.wenfree.cn/public/',postArr); if (data) then local url = data['data']['url']; info.smsname = data['data']['name']; local res = get_(url); if res then log(res) local resArr = split(res,"|") if resArr[1] == "1" then info.phone = resArr[5] info.pid = resArr[2] return true end end end log("ๅ–ๆ‰‹ๆœบๅทๅ‡บ้”™"); end -- //ๅ–็Ÿญไฟก function getMessage() local postArr = {}; postArr['s']="App.SmsNikeReg.GetSms"; postArr['name']=info.smsname; postArr['phone']=info.pid; local data = post('http://sms.wenfree.cn/public/',postArr); if (data) then local url = data['data']['url']; local res = get_(url); -- log(res.."=>"..#res) if res then log(res) local resArr = split(res,"|") if resArr[1] == "1" then info.yzm = resArr[2] return true end end end log("ๅ–ๆ‰‹็Ÿญไฟกๅ‡บ้”™"); end -- info={} -- info.phone = "17728609851" -- info.smsname = "้ฃž็Œช" sys = { clear_bid = (function(bid) closeApp(bid) delay(1) os.execute("rm -rf "..(appDataPath(bid)).."/Documents/*") --Documents os.execute("rm -rf "..(appDataPath(bid)).."/Library/*") --Library os.execute("rm -rf "..(appDataPath(bid)).."/tmp/*") --tmp clearPasteboard() --[[ local path = _G.const.cur_resDir os.execute( table.concat( { string.format("mkdir -p %s/keychain", path), 'killall -SIGSTOP SpringBoard', "cp -f -r /private/var/Keychains/keychain-2.db " .. path .. "/keychain/keychain-2.db", "cp -f -r /private/var/Keychains/keychain-2.db-shm " .. path .. "/keychain/keychain-2.db-shm", "cp -f -r /private/var/Keychains/keychain-2.db-wal " .. path .. "/keychain/keychain-2.db-wal", 'killall -SIGCONT SpringBoard', }, '\n' ) ) ]] clearAllKeyChains() clearIDFAV() --clearCookies() end) } --url่งฃ็  function decodeURI(s) s = string.gsub(s, '%%(%x%x)', function(h) return string.char(tonumber(h, 16)) end) return s end --url็ผ–็  function encodeURI(s) s = string.gsub(s, "([^%w%.%- ])", function(c) return string.format("%%%02X", string.byte(c)) end) return string.gsub(s, " ", "+") end --ๆๅ–token function local_token_() local appbid = 'com.nike.onenikecommerce' local localPath = appDataPath(appbid).."/Documents/ifkc.plist" --่ฎพ็ฝฎ plist ่ทฏๅพ„ local toketext = readFile_(localPath) return encodeURI(toketext) end --่ฏปๆ–‡ไปถ function readFile_(path) local file = io.open(path,"r"); if file then local _list = ''; for l in file:lines() do _list = _list..l end file:close(); return _list end end --ไธŠไผ token function update_token() local url = 'http://nikeapi.honghongdesign.cn' local arr ={} arr['s']='App.NikeToken.Token' arr['token'] = local_token_() arr['email'] = var.account.email log( post(url,arr) ) end --ไธŠไผ ๅธๅท function updateNike() local sz = require("sz") local json = sz.json local url = 'http://nikeapi.honghongdesign.cn' local Arr={} Arr.s = 'App.NikeSelect.NikeInserts' Arr.email = var.account.email Arr.password = <PASSWORD> Arr.phone = var.account.phone local address_ = {} address_['firstName'] = first_name_ address_['lastName'] = last_names_ address_['country'] = "ไธญๅ›ฝ" address_['state'] = 'ๅนฟไธœ็œ' address_['city'] = 'ๆทฑๅœณๅธ‚' address_['county'] = '็ฝ—ๆน–ๅŒบ' address_['address1'] = var.account.address_area address_['address2'] = var.account.address_class Arr.address = json.encode(address_) Arr.iphone = getDeviceName() Arr.note = UIv.note log( post(url,Arr) ) end --ๅœฐๅ€ function address_rd() local ๅœฐๅ€ = { "ๅปถ่Šณ่ทฏ4038ๅท", "็ฝ—ๆฒ™่ทฏ4099ๅท", "ๅปถ่Šณ่ทฏ600ๅท", "ๅปถ่Šณ่ทฏ588ๅท", "็ฝ—ๆน–ๅนฟๅฒญๅฐๅŒบ", "็ฝ—ๆฒ™่ทฏๆ–ฐไธ–็•Œๅ››ๅญฃๅพกๅ›ญ", "ๅคงๆพŽ่Šฑๅ›ญ", "ไธญ้œ‡ๅคงๅŽฆ", "้€šๅ‘่Šฑๅ›ญ", "็ฝ—่Šณ่‹‘", "้“ถไธฐ่Šฑๅ›ญ", "้พ™ๆณ‰่Šฑๅ›ญ", "่Šณๆ˜ฅ่Šฑๅ›ญ", "ๆทฑๆธฏๆ–ฐๆ‘", "้”ฆ็ปฃๆ–ฐๆ‘", "ๅ…ดๅŽ่‹‘", "ๅŽๅ…ด่Šฑๅ›ญ", "่ตค้พ™ๆ–ฐๆ‘", "็ปไบŒ่ทฏ1ๅท", "็ปไบŒ่ทฏ3ๅท", "็ฝ—่Šณ่ทฏ190ๅท", "็ปไบŒ่ทฏ19ๅทๅๅคช่ฝฉ", "ๅนฟ้™ตๅฎถๅ›ญ", "็ฝ—ๆน–ๅ…šๆ ก", "่ฅฟๅฒญ่Šฑๅ›ญ", "ๅฎ‰ไธš่Šฑๅ›ญ", } local ๅœฐๅ€ๆ่ฟฐ = {"ๆ ‹","้˜","ๅฐๅŒบ","่ทฏ"} local ๅœฐๅ€L = {"ๅฎค","ๅท","ๅฑ‚",""} local res = '' res = ๅœฐๅ€[rd(1,#ๅœฐๅ€)]..rd(1,9)..rd(1,99)..ๅœฐๅ€ๆ่ฟฐ[rd(1,#ๅœฐๅ€ๆ่ฟฐ)]..rd(1,9)..rd(0,100)..ๅœฐๅ€ๆ่ฟฐ[rd(1,#ๅœฐๅ€ๆ่ฟฐ)] return res end --ๅ–ๅธๅท function get_account() local getIdUrl = 'http://nikeapi.honghongdesign.cn/?s=App.NikeSelect.NikeFetch&re_login='..UIv.re_login..'&note='..UIv.note log( getIdUrl ) local data = get(getIdUrl); if data ~= nil and data~= '' and data ~= 'timeout' then log(data) if type(data.data) == "table" then var.account.login = data.data.email var.account.pwd = <PASSWORD> var.account.phone = data.data.phone var.account.id = data.data.id var.account.token = data.data.token var.account.address = data.data.data.address log('var.account.token') log(var.account.token) log('var.account.token-end') if var.account.token then if #var.account.token >2 then AccountInfoBack() end end local account_txt = "ๆ‰ง่กŒ่‡ณ "..var.account.id .."\n่ดฆๅท = "..var.account.login.."\nๅฏ†็  = "..var.<PASSWORD> dialog(account_txt,2) log(account_txt) else dialog("ๆš‚ๆ— ๅธๅท", 60*3) return false end end delay(2) end --่ฟ˜ๅŽŸๅ–ๅˆฐ็š„ๅธๅท function AccountInfoBack() local sz = require("sz") local json = sz.json local appbid = 'com.nike.onenikecommerce' local AccountInfo = appDataPath(appbid).."Documents/ifkc.plist" log(AccountInfo); local url = 'http://nikeapi.honghongdesign.cn/' .. var.account.token log( url ) downFile(url, AccountInfo) toast('ไธ‹่ฝฝๅฎŒๆˆ',1) mSleep(2000) end --่ฟ”ๅ›žๅค็™ปไฟกๆฏ function backId() local postUrl = 'http://nikeapi.honghongdesign.cn/' local postArr = {} postArr.s = 'NikeBack.back' postArr.id = var.account.id log(post(postUrl,postArr)) end function updateNikeLog(txt) adbox = adbox or 0 if adbox == 0 then adbox = 1 --ๅˆ›ๅปบๆ–‡ๆœฌ่ง†ๅ›พ fwShowWnd("window1",0,0,200,30,1); mSleep(500) end fwShowTextView("window1","text1",txt,"center","FF0000","FFDAB9",10,0,0,0,200,30,0.8); --fwShowTextView("window1","text1","ๆ–‡ๆœฌ่ง†ๅ›พ","center","FF0000","FFDAB9",10,0,0,0,200,30,0.5); end -- local_token_() -- sys.clear_bid("com.nike.onenikecommerce") -- getPhone() <file_sep> require("TSLib") log('statr') -- log( get("http://127.0.0.1:8080/api/reportInfo") ) log('end')<file_sep> --็ฒพๅ‡†ๆป‘ๅŠจ็š„ๅŽŸ็†ๅฐฑๆ˜ฏ้€š่ฟ‡ๅ‘ๆป‘ๅŠจๆ–นๅ‘็š„ๅž‚็›ด็บฟๆ–นๅ‘็งปๅŠจ 1 ๅƒ็ด ๆฅ็ปˆๆญขๆป‘ๅŠจๆƒฏๆ€ง --็ฎ€ๅ•็š„ๅž‚็›ด็ฒพๅ‡†ๆป‘ๅŠจ function ld(x1,y1,x2,y2) -- touchDown( x1, y1) -- for i = x1, x2, math.random(5,10) do -- touchMove( i+math.random(-5,5), y1+math.random(-50,50)) -- mSleep(math.random(20,50)) -- end -- touchMove( x2, y2) -- mSleep(50) -- touchUp( x2, y2) -- mSleep(50) touchDown(x1,y1) for i = 0, 500, 50 do touchMove(200, 1000-i) mSleep(10) end --ๅช่ฆๆจชๅ‘ๆป‘ๅŠจ 1 ๅƒ็ด ๅฐฑๅฏไปฅ็ฒพๅ‡†ๆป‘ๅŠจ --ๆจชๅ‘ๆป‘ๅŠจ 1 ๅƒ็ด  touchMove(x2, y2) mSleep(50) touchUp( x2, y2) mSleep(50) end ld(125, 792, 443, 792) <file_sep> openURL("http://m.baihe.com/regChat?channel=hscm&code=11")<file_sep>function rndPassWord() --้šๆœบๆ•ฐ้‡ไธชๆ•ฐ local capLetter = stringRandom("QWERTYUIOPASDFGHJKLZXCVBNM",math.random(2,4),1) local lowelLetter = stringRandom("qwertyuiopasdfghjklzxcvbnm",math.random(2,4),1) local number = stringRandom("123456789",math.random(4,6)) local pas = {capLetter..lowelLetter..number,lowelLetter..capLetter..number,number..capLetter..lowelLetter} return pas[math.random(1,#pas)] end function getUserInfo() local adrreses = { {"็ฝ—ๆฒ™่ทฏๅ…ฐไบญๅ›ฝ้™…&&้˜##0#ๅฎค"}, {"ๆฒฟๆฒณๅ—่ทฏ2007ๅท&&ๅฐๅŒบ##ๆ ‹#0##ๅท"}, {"ๅปถ่Šณ่ทฏ4038ๅท&&ๅฐๅŒบ##ๆ ‹#0##ๅท"}, {"็ฝ—ๆฒ™่ทฏ4099ๅท&&ๅฐๅŒบ##ๆ ‹#0##ๅฎค"}, {"ๅปถ่Šณ่ทฏ600ๅท&&ๅฐๅŒบ##ๆ ‹#0##ๅฎค"}, {"ๅปถ่Šณ่ทฏ588ๅท&&ๅฐๅŒบ##ๆ ‹#0##ๅท"}, {"็ฝ—ๆน–ๅนฟๅฒญๅฐๅŒบ##ๆ ‹#0##ๅท"}, {"็ฝ—ๆฒ™่ทฏๆ–ฐไธ–็•Œๅ››ๅญฃๅพกๅ›ญ###ๆ ‹#0##ๅท"}, {"ๅคงๆพŽ่Šฑๅ›ญ##ๆ ‹##0#ๅฎค"}, {"ไธญ้œ‡ๅคงๅŽฆ&&้˜##0#ๅฎค"}, {"้€šๅ‘่Šฑๅ›ญ##ๆ ‹#0##ๅท"}, {"็ฝ—่Šณ่‹‘##ๆ ‹##0#ๅฎค"}, {"้“ถไธฐ่Šฑๅ›ญ##ๆ ‹#0##ๅท"}, {"้พ™ๆณ‰่Šฑๅ›ญ##ๆ ‹#0##ๅท"}, {"่Šณๆ˜ฅ่Šฑๅ›ญ##ๆ ‹#0##ๅท"}, {"ๆทฑๆธฏๆ–ฐๆ‘##ๆ ‹#0##ๅท"}, {"้”ฆ็ปฃๆ–ฐๆ‘##ๆ ‹#0##ๅท"}, {"ๅ…ดๅŽ่‹‘##ๆ ‹##0#ๅฎค"}, {"ๅŽๅ…ด่Šฑๅ›ญ##ๆ ‹##0#ๅฎค"}, {"่ตค้พ™ๆ–ฐๆ‘##ๆ ‹#0##ๅท"}, {"็ปไบŒ่ทฏ1ๅท&&ๅฐๅŒบ##ๆ ‹#0#"}, {"็ปไบŒ่ทฏ3ๅท&&ๅฐๅŒบ##ๆ ‹#0#"}, {"็ฝ—่Šณ่ทฏ190ๅท&&ๅฐๅŒบ##ๆ ‹#0#"}, {"็ปไบŒ่ทฏ19ๅทๅๅคช่ฝฉ##ๆ ‹##0#ๅฎค"}, {"ๅนฟ้™ตๅฎถๅ›ญ##ๆ ‹##0#ๅฎค"}, {"็ฝ—ๆน–ๅ…šๆ ก##ๆ ‹#0#"}, {"่ฅฟๅฒญ่Šฑๅ›ญ##ๆ ‹#0#"}, {"ๅฎ‰ไธš่Šฑๅ›ญ##ๆ ‹#0#"}, {"็ฝ—่Šณๅ—่ทฏๅ—ๅปถ็บฟๅฐๅŸŽ &&้˜##0#ๅฎค"}, {"ๅปถ่Šณ่ทฏไบคๅ‰ๅฃ้พ™้—จๅฐๅŒบ"}, {"ๅปถ่Šณ่ทฏ็ฝ—่ŠณๅคงๅŽฆ#0##ๅท"}, {"็ฝ—่Šณ็”ณ้€šๅฐๅŒบ"}, {"ๅปถ่Šณ่ทฏ่ฏๅˆธไบคๆ˜“ๆ‰€#0##ๅฎค"}, {"็ฝ—่Šณๆฐดไบงๅ…ปๆฎ–ๆœ‰้™ๅ…ฌๅธ#0##ๅท"}, {"็ฝ—่Šณ่ทฏๆ”ฏ่กŒ่ฅไธš้ƒจ#ๆ ‹#0##ๅท"}, {"็ฝ—่Šณๅ—่ทฏไบคๅ‰ๅฃ่ฅฟๅ—่ง’ๅนฟๅœบ###ๆ ‹#0##ๅท"}, {"็ฝ—่Šณๅ—่ทฏไบคๅ‰ๅฃๅธŒๅธƒๅคงๅŽฆ##ๆ ‹##0#ๅฎค"}, {"ๅปถ่Šณ่ทฏ็ฝ—่Šณ่‚กไปฝๆœ‰้™ๅ…ฌๅธ1118ๅท&&ๅฐๅŒบ##0#ๅฎค"}, {"้€šๅ‘่Šฑๅ›ญ##ๆ ‹#0##ๅท"}, {"็ฝ—่Šณ่ทฏๅนฟไธœๅŠžไบ‹ๅค„##ๆ ‹##0#ๅฎค"}, {"ๅปถ่Šณ่ทฏๆ˜“่พพๅ•†่กŒ &&้˜##0#ๅฎค"}, {"็ฝ—่Šณๅ—่ทฏๅดๅทžๆ‘##ๆ ‹#0##ๅท"}, {"ๅปถ่Šณ่ทฏ็ฝ—่ŠณๅคงๅŽฆ#0##ๅท"}, {"ๅปถ่Šณ่ทฏ็ฝ—่พพ่Šฑๅ›ญ##ๆ ‹#0##ๅฎค"}, {"็ฝ—่Šณๅ—่ทฏไฟ่Žฑๅคง้…’ๅบ—#0##ๅฎค"}, {"็ฝ—่Šณๅ—่ทฏ้พ™ๆš„ๅคงๅŽฆ#0##ๅท"}, {"็ฝ—่ŠณๅŽๅŽ้›†ๅ›ข#ๆ ‹#0##ๅท"}, } local first_names = "่ตต้’ฑๅญ™ๆŽๅ‘จๅด้ƒ‘็Ž‹ๅ†ฏ้™ˆ่คšๅซ่’‹ๆฒˆ้Ÿฉๆจๆœฑ็งฆๅฐค่ฎธ".. "ไฝ•ๅ•ๆ–ฝๅผ ๅญ”ๆ›นไธฅๅŽ้‡‘้ญ้™ถๅงœๆˆš่ฐข้‚นๅ–ปๆŸๆฐด็ชฆ็ซ ".. "ไบ‘่‹ๆฝ˜่‘›ๅฅš่Œƒๅฝญ้ƒŽ้ฒ้Ÿฆๆ˜Œ้ฉฌ่‹—ๅ‡ค่Šฑๆ–นไฟžไปป่ขๆŸณ".. "้…†้ฒๅฒๅ”่ดนๅป‰ๅฒ‘่–›้›ท่ดบๅ€ชๆฑคๆป•ๆฎท็ฝ—ๆฏ•้ƒ้‚ฌๅฎ‰ๅธธ".. "ไนไบŽๆ—ถๅ‚…็šฎๅž้ฝๅบทไผไฝ™ๅ…ƒๅœ้กพๅญŸๅนณ้ป„ๅ’Œ็ฉ†่งๅฐน".. "ๅงš้‚ตๆน›ๆฑช็ฅๆฏ›็ฆน็‹„็ฑณ่ดๆ˜Ž่‡ง่ฎกไผๆˆๆˆด่ฐˆๅฎ‹่Œ…ๅบž".. "็†Š็บช่ˆ’ๅฑˆ้กน็ฅ่‘ฃ็ฒฑๆœ้˜ฎ่“้—ตๅธญๅญฃ้บปๅผบ่ดพ่ทฏๅจ„ๅฑ".. "ๆฑŸ็ซฅ้ขœ้ƒญๆข…็››ๆž—ๅˆ้’Ÿๅพ้‚ฑ้ช†้ซ˜ๅค่”ก็”ฐๆจŠ่ƒกๅ‡Œ้œ".. "่™žไธ‡ๆ”ฏๆŸฏๆ˜็ฎกๅข่Žซ็ปๆˆฟ่ฃ˜็ผชๅนฒ่งฃๅบ”ๅฎ—ไธๅฎฃ่ดฒ้‚“".. "้ƒๅ•ๆญๆดชๅŒ…่ฏธๅทฆ็Ÿณๅด”ๅ‰้’ฎ้พš็จ‹ๅต‡้‚ขๆป‘่ฃด้™†่ฃ็ฟ".. "่€็พŠๆ–ผๆƒ ็”„้บดๅฎถๅฐ่Šฎ็พฟๅ‚จ้ณๆฑฒ้‚ด็ณœๆพไบ•ๆฎตๅฏŒๅทซ".. "ไนŒ็„ฆๅทดๅผ“็‰งๅฑฑ่ฐท่ฝฆไพฏ่“ฌๅ…จ้ƒ—็ญไปฐ็ง‹ไปฒไผŠๅฎซ".. "ๅฎไป‡ๆšด็”˜ๅމๆˆŽ็ฅ–ๆญฆ็ฌฆๅˆ˜ๆ™ฏ่ฉนๆŸ้พ™ๅถๅนธๅธ้Ÿถ".. "้ƒœ้ปŽ่“Ÿ่–„ๅฐๅฎฟ็™ฝๆ€€่’ฒ้‚ฐไปŽ้„‚็ดขๅ’ธ็ฑ่ต–ๅ“่”บๅฑ ่’™".. "ๆฑ ไน”้˜ด่ƒฅ่ƒฝ่‹ๅŒ้—ป่Ž˜ๅ…š็ฟŸ่ฐญ่ดกๅŠณ้€„ๅงฌ็”ณๆ‰ถๅ ต".. "ๅ†‰ๅฎฐ้ƒฆ้›็’ฉๆก‘ๆก‚ๆฟฎ็‰›ๅฏฟ้€š่พนๆ‰ˆ็‡•ๅ†€้ƒๆตฆๅฐšๅ†œ".. "ๆธฉๅˆซๅบ„ๆ™ๆŸด็žฟ้˜Žๅ……ๆ…•่ฟž่Œนไน ๅฎฆ่‰พ้ฑผๅฎนๅ‘ๅคๆ˜“ๆ…Ž".. "ๆˆˆๅป–ๅบพ็ปˆๆšจๅฑ…่กกๆญฅ้ƒฝ่€ฟๆปกๅผ˜ๅŒกๅ›ฝๆ–‡ๅฏ‡ๅนฟ็ฆ„้˜™ไธœ".. "ๆฎดๆฎณๆฒƒๅˆฉ่”š่ถŠ้š†ๅธˆๅทฉๅŽ่‚ๆ™ๅ‹พๆ•–่žๅ†ท่จพ่พ›้˜š".. "้‚ฃ็ฎ€้ฅถ็ฉบๆ›พๆฏ‹ๆฒ™ๅ…ป้ž ้กปไธฐๅทขๅ…ณ่’ฏ็›ธๆŸฅๅพŒ่†็บข" local last_names = "ๅฎ‰ๅฝคๅซ็ฅ–่ตฉๆถคๅฝฐ็ˆต่ˆžๆทฑ็พค้€‚ๆธบ่พž่Žžๅปถ็จทๆกฆ่ตๅธ…้€‚ไบญๆฟฎๅญ˜ๅŸŽ็จทๆพ„ๆทปๆ‚Ÿ็ปข็ปขๆพน่ฟชๅฉ•็ฎซ่ฏ†ๆ‚Ÿ่ˆžๆทปๅ‰‘ๆทฑ็ฆ„ๅปถๆถค" .. "ๆฟฎๅญ˜็ฝก็ฆ„็‘›็‘›ๅ—ฃๅซšๆœตๅฏ…ๆทปๆธŸ้ปŽ่‡ป่ˆž็ปขๅŸŽ้ชฅๅฝฐๆธบ็ฆพๆ•™็ฅ–ๅ‰‘้ปŽ่Žžๅ’ธๆต“่Šฆๆพนๅธ…่‡ปๆธŸๆทป็ฆพไบญๆทปไบญ้œ–ๆทฑ็ญ–่‡ป็จท่พž" .. "ๆ‚Ÿๆ‚Ÿๆพ„ๆถ‰ๅŸŽ้ธฅ้ปŽๆ‚Ÿไน”ๆ’้ปŽ้ฒฒๆถ‰่Žž้œ–็”ฒๆทฑๅฉ•ไน”็จ‹ๆพน็”ทๅฒณๆทฑๆถ‰็›Šๆพนๆ‚Ÿ็ฎซไน”ๅคš่Œ้€‚่Šฆ็‘›ๆพ„ๅฉ•ๆœต้€‚็ฅ–้œ–็‘›ๅคๅซš" .. "ๆถ‰็”ท็‚็ฎซ่Šฆ้ปŽ็น็ปข่Šฆ็จ‹่ฏ†ๅ—ฃ็‚็‘ฐๆžๅ…้ปŽๅบธๅ—ฃ่ต็ฝก็บตๆทป็ฆ„้œ–็”ทๅปถ็”ฒๅฝฐๅ’ธ็จท็ฎซๅฒณๆ‚Ÿ่Œ็ฅ–ๆ’็‚ๅบธ็…็”ท่Žžๅบธๆต“" .. "ๅคš็ฝกๅปถ็‘›ๆฟฎๅญ˜็ˆตๆทปๅ‰‘็›Š้ชฅๆพ„ๅปถ่ฟชๅฏ…ๅฉ•็จ‹้œ–่ฏ†็‘ฐ่ฏ†็จ‹็พคๆ•™ๆœตๆ‚Ÿ่ˆžๅฒณๆต“็ฎซๅŸŽ้€‚็จ‹็ฆพๅซš็ฝกๅ’ธ่Œ้“ƒ็ˆตๆธบๆทป่พžๅซš" .. "ๆต“ๅฏ…้ฒฒๅ—ฃ็‘›้ธฅๅคšๆ•™็‘›่ฟชๅค้“ƒ็น็พค้ปŽ็›Šๆพ„็จ‹่Žžๆทฑๅคๆพน็ฆ„่Œๆพน่ตฉๆพ„่—‰็พค็ฎซ้ชฅๅฎšๅฝฐๅฏ…่‡ปๆธŸๆžๅ…็นๆทฑ็พค้ปŽ็”ฒ้ฒฒ" .. "ไบญ้ปŽ่—ๆต“ๆถคๆธŸ่Žžๅฏ…่พžๅ—ฃๅค่ฟชๅซšๆทป็ญ–ๅบธ็ญ–่—‰็‘ฐๅฝฐ็ฎซ็›Š่Žžๆธบไน”ๅฝฐๅปถ่ˆž็ฅ–ๅฉ•ๆพนๆธบ้ธฅ็บตๅ—ฃ็‘›่—ๆฟฎๅญ˜ๅฉ•่Œ็จ‹่Šฆ็พค" .. "็ฆพๅซš็จ‹่พž็ฅ–้ปŽ่Œๆต“ๆกฆ่—ๆธŸ็ฆพๅฝฐๅธ…่พž้“ƒ้“ƒ้ปŽๅ…็ปขๆฟฎๅญ˜ๅ‰‘่พž็ฆพ็‘ฐๆทปๅปถๆทปๆ‚Ÿ่ต็ฅ–ๅ’ธ่Žž็”ท็ปข็ญ–ๅฉ•่—‰็ฆพๆต“็นๆถค็ฅ–" .. "ๆฑ‰้ชฅ่ˆž็‘›ๅคš็จท่ต่ŽžๆธŸ้ปŽ่ˆžๆกฆ้ปŽ็พค่—ๆธบ้ปŽๅคๆกฆๅ’ธ่ฟชๆพˆ่ˆžๅ…็จทๅ’ธๅ‰‘ๅฎšไบญๆพ„ๆฟฎๅญ˜้ฒฒ่‡ปๅ…จ้ธฅๅคš่ต็จ‹ๆทป็‘›ไบญๅธ…ๆ‚Ÿ" .. "็”ฒ็”ทๅธ…ๆถค้€‚็บตๆธŸ้ฒฒไบญๆ‚Ÿ็…ไบญๆทปๅ…่ˆž็ฆพๅบธๅ’ธ็‘›ๆ•™้ฒฒๅ…็ฎซ่Šฆๅ…็‘›ๅ’ธ้ธฅๅธ…ๆ‚Ÿๅปถ็‚้ปŽ็น็ฎซ็ˆตๅ‰‘้œ–ๅ‰‘้œ–็ฆ„้ธฅๆ‚Ÿๆถ‰" .. "ๅฝฐ็พคๆ‚Ÿ่พžๅธ…ๆธบ่Žžๆพ„ๆกฆ็‘›้€‚่‡ป็›Š้œ–็นไบญๆพน่พžๅค็จ‹ๅ—ฃ้“ƒ็ฎซ็ญ–ๆพˆๆž่ต่Žž็ˆตๆธŸ็ฆ„็พคๆžๆทป่Šฆ็พคๆต“่ต่Œ็›ŠๅŸŽๆพ„่ตฉ็…" .. "ๅปถ็พคไน”็น้ฒฒ็ฅ–็พคๆ‚Ÿ้ปŽๅฎšๅบธๆพ„่Šฆๅปถ้œ–็ฝก้ฒฒๅ’ธๆธบ็บตไบญ็ฆ„้ธฅ่ตฉๆถคๅ‰‘ๆพน่—็บตๆฟฎๅญ˜ๆพ„่Šฆๅ‰‘ๅปถ็‘ฐ็จท้ปŽ็›Š่ตฉๆพ„ๅ…ๆ‚Ÿๆพˆ" .. "็”ฒๅ—ฃ็ปขๆœต็›Š็”ฒๆ‚Ÿๆถคๅฉ•็พคๅ’ธ่‡ป็ฎซ้ฒฒๅฏ…้ธฅๆกฆ็›Š็‚่ˆžๅ…ๅบธ่Šฆ่—‰ๅฏ…ๆธบๅ’ธ่ตๆพ„็จ‹ๅ‰‘็‘ฐ้œ–็‘ฐ้“ƒๅธ…็”ท้“ƒๆ‚Ÿ่ฏ†็‘ฐไป•ไป•ๅŸŽ" .. "ๅ…่Žžๅ…จๆœตๆถค้“ƒๅ‰‘ๆธบ็จทๅ‰‘็‚้“ƒ็ฎซๅ…จไป•็›Š็บต่Šฆๆกฆ็‚ๆฟฎๅญ˜ๅŸŽๆœตๆœตๅ’ธ็จ‹ๅ‰‘ๆพ„ๅฎšๆพˆ็ˆตๅฏ…ๅบธๅฎš่Žž็‘›ๆ•™ๅฝฐ้ปŽ็ฎซไป•้ปŽๆกฆ" .. "่ตฉๆทฑ่ตฉ็ˆต่ฟชๆ‚Ÿ็นๆถค็…ๆทป็ฎซๆกฆๅธ…็‘›้ปŽ้ปŽ็ญ–่ฏ†ๅฏ…ๅซšๆถ‰่ฟช็ญ–ๆฑ‰่ˆžๅฎšๅฝฐๅ…็”ท็ฅ–ๆ•™ๆพ„็พค็‘›ๆฟฎๅญ˜็”ท็ฆพๆ•™่Žž็ฆพ้ธฅๆพˆๆฟฎ" .. "ๅญ˜ๅฒณๅŸŽๅซšๆทฑ่ˆžๆ•™ๅฒณๆพ„ไบญ็ฆพๅคๆœตไบญ่Œ่Žž็จทๅฏ…็‘ฐๅŸŽๅบธไบญ่ˆž็ฆพ็‘›ๆ’ๅคๆต“ๅฝฐ่Žžๆพ„ๆพˆ้ธฅ่‡ป็จทๆ•™็…่พž็›Šๅ‰‘่—‰้ปŽๆทป็‘›" .. "ๅปถ่ˆžๅคไป•ๅฒณๅคšๅฉ•้ชฅ่ฟชๅธ…้ปŽๆ‚Ÿๅ…จๆพ„่ฏ†็›Š็”ฒๆกฆ็บต้€‚็ฝกๅฝฐๆพ„็ฆพๅฉ•็จ‹้ปŽๅŸŽๆถคๆต“ๆž็ฎซๅ’ธๆธŸๅฒณๆธŸๆพน่‡ป็น่ฏ†็นๆพ„็ฎซ่พž" .. "ๆต“้ฒฒ่ฏ†ๆ‚Ÿๅ…ๆ‚Ÿ็ฆพ่ฏ†็พค็ฅ–่ฟชๆธŸ้ฒฒ็พคๅบธ่Žž็นๆ‚Ÿๆพน็‘ฐๆ‚Ÿ้ธฅๆฑ‰็พค็”ฒ่Žžๅบธ่Œ็…่Žžๆกฆ้ฒฒๆœตๆทฑไน”่พžๅ…ๅฝฐๆธบๆœต็‘ฐไบญ็‘ฐๆœต" .. "ๅฎšๆทฑ็”ท่ฏ†็พค่Œ้œ–็›Š็”ท่ˆžๅŸŽๅ…่ˆž็ˆต่ตฉๆž็ฝก็ฝก็พคๆพน่Šฆ่—‰็ˆตๆ‚ŸๆธŸๆพน็ฆพๅคšๅบธ็ฎซๅคไน”่Šฆ็”ฒๆฟฎๅญ˜ๅคšๆธŸ่—‰็น่ตๆฑ‰็บตไบญ" .. "็ฆพๅŸŽๆžๅ‰‘้œฒไปฅ็މๆ˜ฅ้ฃžๆ…งๅจœๆ‚ ไบฆๅ…ƒๆ™”ๆ›œ้œœๅฎๆกƒๅฝฆไปช้›จ็ด้’็ญ ้€ธๆ›ผไปฃ่€ๅญคๆ˜†็ง‹่•Š่ฏญ่Žบไธ็บข็พฒ็››้™ๅ—ๆท‘้œ‡ๆ™ด" .. "ๅฝญ็ฅฏๅฑฑ้œžๅ‡ๆŸ”้šฝๆพ็ฟ ้ซ˜้ชŠ้›…ๅฟต็š“ๅŒๆด›็ดซ็‘ž่‹ฑๆ€ๆญ†่“‰ๅจŸๆณข่Šธ่ท็ฌ‘ไบ‘่‹ฅๅฎๅคๅฆๅ˜‰ๅฝฉๅฆ‚้นๅฏ„่ŠๆŸณๅ‡Œ่Žน่ถ่ˆ’ๆฌ" .. "่™นๆธ…็ˆฝๆœˆๅทงไนพๅ‹‹็ฟฐ่Šณ็ฝ—ๅˆš้ธฟ่ฟๆžซ้˜ณ่‘ณๆฐๆ€€ๆ‚ฆๅ‡กๅ“ฒ็‘ถๅ‡ฏ็„ถๅฐšไธนๅฅ‡ๅผ˜้กบไพ้›ช่กๅ›็•…็™ฝๆŒฏ้ฆจๅฏปๆถต้—ฎๆด่พ‰ๅฟ†ๅ‚ฒ" .. "ไผŸ็ปๆถฆๅฟ—ๅŽๅ…ฐ่Šนไฟฎๆ™จๆœจๅฎ›ไฟŠๅš้Ÿถๅคฉ้”ๆบช็‡•ๅฎถๆฒˆๆ”พๆ˜Žๅ…‰ๅƒๆฐธๆบถๆ˜Šๆข…ๅท็œŸๅฐ”้ฆฅ่Žฒๆ€œๆƒœไฝณๅนฟ้ฆ™ๅฎ‡ๆง็บ่Šทๅธ†็ง€" .. "็†ๆŸไนฆๆฒ›็ชไป™ไน‹็ซนๅ‘ๅ‰ๆฌฃๆ—ปๆ™“ๅ†ฌๅนปๅ’Œ้›ๆทณๆตฉๆญŒ่ฃๆ‡ฟๆ–‡ๅนผๅฒšๆ˜•็‰ง็ปฟ่ฝฉๅทฅๆ—ญ้ขœ้†‰็Ž‘ๅ“่ง…ๅถๅคœ็ต่ƒœๆ™—ๆจๆตไฝ" .. "ไน็ซ้Ÿณ้‡‡็ฟ็ฟŽ่ฑๆฐ‘็”ปๆขฆๅฏ’ๆณฝๆ€กไธฝๅฟƒ็Ÿณ้‚ต็Žฎไฝ‘ๆ—บๅฃฎๅไธ€ๅญฆ่ฐท้Ÿตๅฎœๅ†ฐ่ตซๆ–ฐ่•พ็พŽๆ™–้กน็ณๅนณๆ ‘ๅˆ็‚ณ้ชๆฐ”ๆตทๆฏ…ๆ•ฌ" .. "ๆ›ฆๅฉ‰็ˆฐไผฏ็Šๅฝฑ้ฒธๅฎนๆ™ถๅฉทๆž—ๅญๆ˜Œๆขง่Š™ๆพ่ฏ—ๆ˜Ÿๅ†‰ๅˆๆ˜ ๅ–„่ถŠๅŽŸ่Œ‚ๅ›ฝ่…พๅญŸๆฐด็ƒŸๅŠๅณฏ่މ็ปฎๅพทๆ…ˆๆ•ๆ‰ๆˆˆๆข“ๆ™ฏๆ™บ็›ผ้œ" .. "็‡่‹—็†™ๅงไปŽ่ฐŠ้ฃŽๅ‘้’ฐ็Ž›ๅฟๅฉ€่ฒๆ˜ถๅฏ่Œๅฐๅ€ฉๅฆ™ๆถ›ๅง—ๆ–นๅ›พ่ฟŽๆƒ ๆ™คๅฎฃๅบทๅจ…็ŽŸๅฅ•้”ฆๆฟฏ็ฉ†็ฆงไผถไธฐ่‰ฏ็ฅบ็ๆ›ฒๅ–†ๆ‰ฌๆ‹”" .. "้ฉฐ็ปฃ็ƒๅก้•ฟ้›ฏ้ข–่พฐๆ…•ๆ‰ฟ่ฟœๅฝฌๆ–ฏ่–‡ๆˆ่ช็ˆฑๆœ‹่ฆ็”ฐ่‡ดไธ–ๅฎžๆ„ซ่ฟ›็€šๆœๅผบ้“ญ็…ฆๆœ—็ฒพ่‰บ็†นๅปบๅฟปๆ™ๅ†ทไฝฉไธœๅคๅšๆปจ่ฑ" .. "ๅ›ก้“ถๅ’ๆญฃๅ„ฟ็‘œๅฎ่”“็ซฏ่““่Šฌ็ขงไบบๅผ€็ ๆ˜‚็ฌๆด‹็’ ๆก่ˆŸๅงฃ็›ไบฎ็…ŠไฟกไปŠๅนดๅบ„ๆทผๆฒ™้ป›็ƒจๆฅ ๆก‚ๆ–่ƒค้ช„ๅ…ดๅฐ˜ๆฒณๆ™‹ๅฟๆ˜“" .. "ๆ„‰่•ด้›„่ฎฟๆน›่“ๅช›้ชžๅจดๅ„’ๅฆฎๆ—‹ๅ‹ๅจ‡ๆณฐๅŸบ็คผ่Šฎ็พฝๅฆžๆ„็ฟ”ๅฒ‘่‹‘ๆš–็Žฅๅฐง็’‡้˜”็‡Žๅฒ้–่กŒ็‘พ่ต„ๆผชๆ™Ÿๅ† ๅŒ้ฝๅคๅ‰่ฑ†ๅ”ฑ" .. "้Ÿซ็ด ็›ˆๅฏ†ๅฏŒๅ…ถ็ฟฎ็† ็ปๆพŽๆทก้Ÿฆ่ฏšๆปข็Ÿฅ้น่‹’ๆŠ’่‰ณไน‰ๅฉง้—ณ็ฆๅฃคๆจ่Šƒๆดฒ้˜ต็’Ÿ่Œต้ฉนๆถ†ๆฅๆทๅซ’ๅœฃๅŸๆบ็’ž่ฅฟๆ—Žไฟจ้ข‚็ฟ" .. "ๆƒ…็Ž„ๅˆฉ็—ด่•™ๅŠ›ๆฝๅฌ็ฃŠๅฎธ็ฌ›ไธญๅฅฝไปป่ฝถ็Žฒ่žบ้ƒ็•ดไผšๆš„ๅณป็•ฅ็ผ็ฐ้ป˜ๆฑ ๆธฉ็‚ซๅญฃ้›ฐๅธๆ‰่ง‰็ปด้ฅฎๆน‰่ฎธๅฎต่Œ‰่ดคๆ˜ฑ่•ค็‘" .. "้”‹็บฌๆธŠ่ถ…่ๅซ”ๅคง้œๆฅš้€š้‚ˆ้ฃ™้œ“่ฐงไปคๅŽšๆœฌ้‚ƒๅˆๅฎพๆฒ‰ๆ˜ญๅณฐไธš่ฑช่พพๅฝ—็บณ้ฃ’ๅฃๆ–ฝๆฌขๅงฎ็”ซๆน˜ๆผพ้—ฒๆฉ่ŽŽ็ฅฅๅฏ็…œ้ธฃๅ“" .. "ๅธŒ่ž้‡ŽๅŒ–้’Šไปฒ่”š็”Ÿๆ”ธ่ƒฝ่ก่่ฟˆๆœ›่ตทๅพฎ้นค่ซ้“ๅจฅๆณ“้‡‘็จ็ญฑ่ตžๅ…ธๅ‹‡ๆ–Œๅชšๅฏฟๅ–œ้ฃ‡ๆฟกๅฎ•่Œœ้ญ็ซ‹่ฃ•ๅผผ็ฟผๅคฎ่Ž˜็ปš็„ฑ" .. "ๅฅฅ่็ฑณ่กฃๆฃฎ่ƒ่ˆช็’งไธบ่ทƒ่’™ๅบ†็ฒๅ€š็ฉนๆญฆ็”œ็’ไฟ่Œนๆ‚Œๆ ผ็ฉฐ็š›็’Ž้พ™ๆๆนƒๅ†œ็ฆๆ—ท็ซฅไบ˜่‹‡่Œƒๅฏฐ็“ƒๅฟ ่™Ž้ข่“„้œˆ่จ€็ฆน" .. "็ซ ่Šฑๅฅ็‚Ž็ฑๆšฎๅ‡่‘›่ดžไพ ไธ“ๆ‡‹ๆพœ้‡็บถๅธƒ็šŽๆบ่€€้ธพๆ…จๆ›พไผ˜ๆ ‹ๅฆƒๆธธไนƒ็”จ่ทฏไฝ™็‰่—ป่€˜ๅ†›่ŠŠๆ—ฅ่ตกๅ‹ƒๅซ่ฝฝๆ—ถไธ‰้—ตๅงฟ" .. "้บฆ็‘—ๆณ‰้ƒŽๆ€ฟๆƒฌ่Œ็…งๅคซ้‘ซๆจฑ็ญ้’งๆŽฃ่Šซไพฌไธ่‚ฒๆตฆ็ฃฌ็Œฎ่‹“็ฟฑ้›ๅฉต้˜‘ๅฅณๅŒ—ๆœช้™ถๅนฒ่‡ชไฝœไผฆ็งๆบฅๆก€ๅทž่ไธพๆ่Œ—ๆดฝ็„•" .. "ๅน็”˜็ก•่ต‹ๆผ ้ข€ๅฆค่ฏบๅฑ•ไฟๆœ”่Š็ง‰่‹ๆดฅ็ฉบๆดฎๆตŽๅฐนๅ‘จๆฑŸ่ก็ฎ€่Žฑๆฆ†่ด่ง่‰พไปๆผซ้”Ÿ่ฐจ้ญ„่”ผ่ฑซ็บฏ็ฟŠๅ ‚ๅซฃ่ช‰้‚ฆๆžœๆšŽ็" .. "ไธดๅ‹คๅขจ่–„้ข‰ๆฃ ็พกๆตšๅ…†็Žฏ้“„" local emailSuffix = {{"vvccb.com"},{"ssnms.com"},{"zzaha.com"}} local size = {"6","6.5","7","7.5","8","8.5","9","9.5","10"} local rnd1 = math.random(1,#first_names/3) local rnd2 = math.random(1,#last_names/3) local rnd3 = math.random(1,9) local rnd4 = math.random(10,30) local rnd5 = math.random(1,#last_names/3) local rnd6 = math.random(1,#last_names/3) local rnd7 = string.sub(last_names,(rnd1-1)*3+1,(rnd1-1)*3+3) local rnd8 = string.sub(last_names,(rnd1-1)*3+1,(rnd1-1)*3+3) local adrees = adrreses[math.random(1,#adrreses)][1] adrees = string.gsub(adrees,"#",rnd3) adrees = string.gsub(adrees,"##",rnd4) adrees = string.gsub(adrees,"&",rnd7) adrees = string.gsub(adrees,"&&",rnd7..rnd8) return { brithday = "19"..math.random(70,99).."-"..string.format("%02d",math.random(1,12)).."-"..string.format("%02d",math.random(1,30)), firstName = string.sub(first_names,(rnd1-1)*3+1,(rnd1-1)*3+3), lastName = string.sub(last_names,(rnd1-1)*3+1,(rnd1-1)*3+3), email = rndPassWord().."@"..emailSuffix[math.random(1,#emailSuffix)][1], password = <PASSWORD>(), avatar = "https://source.unsplash.com/random/20*20", nikeShoeSize = size[math.random(1,#size)], gender = tostring(math.random(1,2)), code = "", phone = "", adressInfo={ ["code"] = "518000", ["country"] = "CN", ["label"] = "Shipping Address 1", ["line1"] = adrees, ["line2"] = adrees, ["line3"] = "", ["locality"] = "ๆทฑๅœณๅธ‚", ["email"] ="", ["name"] = { ["alternate"] ={ ["family"] = "", ["given"] = "", }, ["primary"] ={ ["family"] = "", ["given"] = "", }, }, ["phone"] = { ["primary"] ="", }, ["preferred"] = "0", ["province"] = "CN-44", ["region"]= "็ฝ—ๆน–ๅŒบ", ["type"] = "SHIPPING", ["zone"] = "็ฝ—ๆน–ๅŒบ", ["email"] = "", }, } end function GetLocalInfo() --่ฏปๅ–ๆœฌๅœฐไปปๅŠก่ฟ›ๅบฆ local info ={} info = plist.read(_Path_OldTask) return info end function getDevInfo() --่Žทๅ–ๆœฌๆœบไฟกๆฏ local dev = {} dev.name =device.name() dev.serial_number =device.serial_number() dev.udid =device.udid() dev.ip = GetlocalIP() return dev end function getAcc() local info = GetLocalInfo() --้ฆ–ๅ…ˆๆŸฅ็œ‹ๆ˜ฏๅฆๅญ˜ๆกฃไปปๅŠก local dev = getDevInfo() if info ~=nil then if info.Status == '1' then Showlog("[getacc] is suncess") else if info.model=="reg" and string.find(device.name(),"reg")==nil then Showlog("[getacc] device is no reg pass") else return info end end end os.execute("rm -rf ".._Path_OldTask) info = getUserInfo() info.Status = '0' info.isReg = false info.isModify = false info.isClear = false info.isReduction = true info.drawTime = 0 info.openTime = 0 SaveInfo(info) for i =1,10 do sys.msleep(500) if plist.read(_Path_OldTask)~=nil then return info end end sys.alert("ๆ— ๆณ•ๅญ˜ๅ‚จไปปๅŠกๆ•ฐๆฎ") lua_exit() return info end function PassAcc(info) --่ทณ่ฟ‡่ฟ™ไธชๅธๅท info.Status = '1' SaveInfo(info) end function SaveInfo(info) --ไฟๅญ˜ๆœฌๅœฐไปปๅŠก่ฟ›ๅบฆ plist.write(_Path_OldTask,info) end function _Init() --if device.is_screen_locked() == true then s_unlockScreen() end --่งฃ้”่ฎพๅค‡ s_ClickTSAlertButton() --็‚นๆމ้”™่ฏฏ็ช—ไฝ“ initDevice() --ๅˆๅง‹ๅŒ–่ฎพๅค‡ initWebView() --ๅˆๅง‹ๅŒ–ๆตฎๅŠจ็ช—ๅฃ --editHost() --ๅŠซๆŒๆŠ–้Ÿณๆ’ญๆ”พๆ•ฐๆฎ closeApp(_appBid,1) --ๅ…ณ้—ญApp --checkDebIsInstall() --VPN_init() --ๅˆๅง‹ๅŒ–VPN --if device.is_screen_locked() == true then s_unlockScreen() end --่งฃ้”่ฎพๅค‡ showWebview("ๅˆๅง‹ๅŒ–ๅฎŒๆฏ•") ------ๅˆๅง‹ๅŒ–ๅ…จๅฑ€ๅ˜้‡------ end function doMain(info) if info.isClear == false then clearFile() info.isClear = true SaveInfo(info) end if info.isReduction == false then ReductionDataInfo(info) info.isReduction = true SaveInfo(info) end local oldSession = "" --ๅœบๆ™ฏๅค‡ไปฝ local repeatTime = 0 --้‡ๅคๅœบๆ™ฏ่ฎกๆฌก while true do if app.front_bid() ~= _appBid then --ๆ‰“ๅผ€APP ๅนถๆˆๅŠŸ่ฟ›ๅ…ฅ็•Œ้ขๅˆคๆ–ญ showWebview("ๅผ€ๅฏๅบ”็”จ") info.openTime = info.openTime+1 SaveInfo(info) if info.openTime>=50 then Showlog("[Main] openTime is max",true,false,true) lua_exit() PassAcc(info) return false end runApp(_appBid) sys.msleep(4000) else info.openTime = 0 SaveInfo(info) local recursiveDescription = s_viewsinfo() or "" if string.find(recursiveDescription,"SNKRS_inhouse.SplashLottieView")==nil then sys.msleep(1000) local vState = s_getVcState(info) local session = vState.session if session then if session == "dismissView" then showWebview("ๅ…ณ้—ญๅนฟๅ‘Š","ๆฃ€ๆŸฅๅผ‚ๅธธ:"..repeatTime) sys.msleep(2000) elseif session == "waitPhone" then showWebview("็ญ‰ๅพ…ๆŽฅๆ”ถๆ‰‹ๆœบ","ๆฃ€ๆŸฅๅผ‚ๅธธ:"..repeatTime) sys.msleep(500) if info.phone == "" then info.phone = DMGetPhone() SaveInfo(info) end elseif session == "sendPhobe" then showWebview("่พ“ๅ…ฅๆ‰‹ๆœบ","ๆฃ€ๆŸฅๅผ‚ๅธธ:"..repeatTime) sys.msleep(500) elseif session == "clearPhone" then showWebview("ๆธ…้™คๆ‰‹ๆœบ","ๆฃ€ๆŸฅๅผ‚ๅธธ:"..repeatTime) sys.msleep(500) elseif session == "waitMsg" then showWebview("็ญ‰ๅพ…็Ÿญไฟก","ๆฃ€ๆŸฅๅผ‚ๅธธ:"..repeatTime) sys.msleep(500) info.code = DMGetMsg(info.phone) SaveInfo(info) if repeatTime >= 12 then info.phone = "" SaveInfo(info) return false end elseif session == "sendMsg" then showWebview("ๅ‘้€็Ÿญไฟก ["..info.code.."]","ๆฃ€ๆŸฅๅผ‚ๅธธ:"..repeatTime) sys.msleep(500) info.code = "" SaveInfo(info) if repeatTime >= 12 then info.phone = "" SaveInfo(info) return false end elseif session == "error" then showWebview("ๆณจๅ†Œ้”™่ฏฏ") sys.msleep(500) return false elseif session == "page1" then showWebview("็‚นๅ‡ปๆณจๅ†Œ","ๆฃ€ๆŸฅๅผ‚ๅธธ:"..repeatTime) sys.msleep(500) elseif session == "page2" then showWebview("ๅกซๅ†™ไธชไบบ่ต„ๆ–™","ๆฃ€ๆŸฅๅผ‚ๅธธ:"..repeatTime) sys.msleep(500) elseif session == "page3" then showWebview("็”ตๅญ้‚ฎไปถ","ๆฃ€ๆŸฅๅผ‚ๅธธ:"..repeatTime) sys.msleep(500) elseif session == "page4" then showWebview("ๅกซๅ†™ๅ‡บ็”Ÿๆ—ฅๆœŸ","ๆฃ€ๆŸฅๅผ‚ๅธธ:"..repeatTime) sys.msleep(500) elseif session == "none" then showWebview("ๆœช็Ÿฅ็Šถๆ€","ๆฃ€ๆŸฅๅผ‚ๅธธ:"..repeatTime) sys.msleep(1500) elseif session == "loadView" then showWebview("็ญ‰ๅพ…ๅŠ ่ฝฝ","ๆฃ€ๆŸฅๅผ‚ๅธธ:"..repeatTime) sys.msleep(5000) elseif session == "getProfile" then showWebview("่Žทๅ–ไธชไบบ่ต„ๆ–™","ๆฃ€ๆŸฅๅผ‚ๅธธ:"..repeatTime) sys.msleep(1000) local gender = vState.nowinfo.gender or 0 local addresses = vState.nowinfo.addresses or 0 local lastName = vState.nowinfo.lastName or "" local firstName = vState.nowinfo.firstName or "" local nikeShoeSize = vState.nowinfo.nikeShoeSize or "0" local avatar = vState.nowinfo.avatar or "" local pdata = {} if tostring(gender)=="0" then pdata.gender = info.gender end if tostring(addresses)=="0" then pdata.adressInfo = info.adressInfo end if tostring(lastName)=="" then pdata.lastName = info.lastName end if tostring(firstName)=="" then pdata.firstName = info.firstName end if tonumber(nikeShoeSize)==0 then pdata.nikeShoeSize = info.nikeShoeSize end if tostring(avatar)=="" then pdata.avatar = info.avatar end if next(pdata) then local s_url = "http://1172.16.17.32:9999/modifyinfo" local c,h,b = http.tspost(s_url,10,{},json.encode(pdata)) showWebview("ๅผ€ๅง‹ไฟฎๆ”น่ต„ๆ–™") sys.msleep(8000) else info.isModify = true SaveInfo(info) showWebview("ไฟฎๆ”น่ต„ๆ–™ๅฎŒๆฏ•","้‡ๅฏApp") return false end elseif session == "clickView" then showWebview("ๆŸฅ็œ‹ๅ•†ๅ“่ฏฆๆƒ…") sys.msleep(5000) elseif session == "drawView" then showWebview("ๆป‘ๅŠจๅ•†ๅ“") sys.msleep(5000) info.drawTime = info.drawTime + 1 SaveInfo(info) if info.drawTime >=30 then SetAcc(info,1) return true end elseif session == "waitView" then showWebview("็ญ‰ๅพ…Appๅ“ๅบ”","ๆฃ€ๆŸฅๅผ‚ๅธธ:"..repeatTime) sys.msleep(5000) else showWebview(session) sys.msleep(1000) end if oldSession == session then repeatTime = repeatTime +1 else repeatTime =0 end oldSession = session --[[ ่ฟ™้‡Œๆ˜ฏๆŸไธชไธ€ไธช็”ป้ขๅœ้กฟ่ถ…ๆ—ถ็š„้”™่ฏฏ่งฆๅ‘ ๆฒกๆ—ถ้—ดๅ†™ไบ† --]] end else showWebview("็ญ‰ๅพ…่ฟ›ๅ…ฅไธปๅฑๅน•") sys.msleep(5000) end end end end function SetAcc(info,status) --ไธŠไผ ๅผ‚ๅธธๆ•ฐๆฎ --็Šถๆ€ 1/ๆˆๅŠŸ,2/็ฆ็”จ,3/ๅผ‚ๅธธ,4/ๅฏ†็ ้”™่ฏฏ 5/ๆœ‰้ชŒ่ฏ็  6/ๆˆๅท Showlog("[SetAcc] status = "..status) info.Status = '1' SaveInfo(info) if status == 1 then reportAcc(info) end end function reportAcc(info) Showlog("[rertMyInfo] postData") local pdata = {} local ugcPlist,cookies,keychain = backupInfo() pdata.username = info.phone pdata.password = <PASSWORD> pdata.email = info.email pdata.nickname = info.firstName..info.lastName pdata.address = info.adressInfo.locality..info.adressInfo.region..info.adressInfo.line1 pdata.cookies = cookies pdata.plist = ugcPlist pdata.keychain = keychain while true do local url = _Api["reportAcoountInfo"] local ret = PostApi(url,pdata) --ๆ›ดๆ–ฐๆ•ฐๆฎ if ret.code == 100 then break else sys.alert("[postApi] setAccountInfo code = "..ret.code.." msg = "..ret.msg,4) end sys.msleep(6000) end end function _TaskMain() _Sever = "http://192.168.6.254:6969/api/snkrs/" _Api ={ ["reportAcoountInfo"] = _Sever.."reportAcoountInfo", --่Žทๅ–ไปปๅŠก } _appBid = 'com.nike.onenikecommerce' --appBID _appDataPath = appDataPath(_appBid) _Path_OldTask = userPath().."/res/Nikebackup.txt" --ไปปๅŠกๅค‡ไปฝ่ทฏๅพ„ _Path_Scp = userPath().."/lua/myluas/" --่„šๆœฌ่ทฏๅพ„ if _appDataPath == nil then dialog("ๆœชๅฎ‰่ฃ…Nikeๅฎขๆˆท็ซฏ") lua_exit() end _Init() while true do local _info = getAcc() doMain(_info) closeApp(_appBid,1) end end require "Common" require "Function" require "Cycript" _TaskMain() --Dialog(rndPassWord()) --[[ authorization = [_TtC13SNKRS_inhouse13NikeAPIClient accessToken] --]] --[[ local accounts = {} accounts.cookies = "<KEY>" accounts.plist = "<KEY>" accounts.keychain = file.reads("/var/mobile/Media/keychain.txt") ReductionDataInfo(accounts) --่ฟ˜ๅŽŸๆ•ฐๆฎ dialog("end") --]] --info = getUserInfo() --reportAcc(info) --[[ local infos = { ["adressInfo"] = info.adressInfo } local s_url = "http://127.0.0.1:9999/modifyinfo" pdata = json.encode(infos) local c,h,b = http.tspost(s_url,10,{},pdata) dialog(c) if c == 200 then dialog(b) end --]] <file_sep>-- ็งฏๅˆ†ๅข™ๅฏนๆŽฅ -- xiaoq.lua -- Create By TouchSpriteStudio on 13:15:24 -- Copyright ยฉ TouchSpriteStudio . All rights reserved. package.loaded['AWZ'] = nil require("TSLib") require("AWZ") require("tsp") local var={} local jfq={} jfq.url = 'https://m.applyape.com/api/' jfq.model = '' jfq.adid = '217655' jfq.appid = '1492988924' jfq.kid = 'ๅŠ ๆฒน' jfq.idfa = '' jfq.os_version = '' jfq.device = 'iPhone10,2' jfq.source = 'pengzhi' jfq.udid = '' jfq.callback = false jfq.name = 'ๅŠ ๆฒนไน‹ๅฎถๅŠ ๆฒน' jfq.bid = 'com.oilHome.www' function start() local info = getOnlineName() jfq.idfa = strSplit(info[8],":")[2] jfq.os_version = strSplit(info[3],":")[2] jfq.udid = strSplit(info[4],":")[2] end function idfa_idfaPc() jfq.model = 'idfaPc' local service = jfq.url..jfq.model local postArr = {} postArr.adid = jfq.adid postArr.appid = jfq.appid postArr.ip = ip() postArr.kid = urlEncoder(jfq.kid) postArr.os_version = jfq.os_version postArr.device = jfq.device postArr.source = jfq.source postArr.udid = jfq.udid postArr.idfa = jfq.idfa -- log(postArr) local res = post(service,postArr) if (res[jfq.idfa] == '0') then log("ๆŽ’้‡ๆˆๅŠŸ","all") return true end end function idfa_click() jfq.model = 'click' local service = jfq.url..jfq.model local postArr = {} postArr.adid = jfq.adid postArr.appid = jfq.appid postArr.ip = ip() postArr.kid = urlEncoder(jfq.kid) postArr.os_version = jfq.os_version postArr.device = jfq.device postArr.source = jfq.source postArr.udid = jfq.udid postArr.idfa = jfq.idfa if jfq.callback then postArr.callbackurl = urlEncoder("http://wenfree.cn/api/Public/idfa/?service=Idfa.Callback&idfa="..jfq.idfa.."&appid="..jfq.appid) end -- log(postArr) local res = post(service,postArr) if (res['code'] == '0' or res['code'] == 0 ) then log("็‚นๅ‡ปๆˆๅŠŸ","all") return true end end function idfa_activate() jfq.model = 'activate' local service = jfq.url..jfq.model local postArr = {} postArr.adid = jfq.adid postArr.appid = jfq.appid postArr.ip = ip() postArr.kid = urlEncoder(jfq.kid) postArr.os_version = jfq.os_version postArr.device = jfq.device postArr.source = jfq.source postArr.udid = jfq.udid postArr.idfa = jfq.idfa local res = post(service,postArr) if (res['code'] == '0' or res['code'] == 0 ) then log("ไธŠๆŠฅๆˆๅŠŸ","all") return true end end function up(name,other) local url = 'http://wenfree.cn/api/Public/idfa/' local idfalist ={} idfalist.service = 'Idfa.Idfa' idfalist.phonename = getDeviceName() -- idfalist.phoneimei = getIMEI() idfalist.phoneos = jfq.os_version idfalist.idfa = jfq.idfa idfalist.ip = ip() idfalist.account = jfq.kid idfalist.password = <PASSWORD> idfalist.phone = var.phone idfalist.appid = jfq.appid idfalist.name = name idfalist.other = other return post(url,idfalist) end t={} local degree = 85 t['agree']={0xff5100,"-196|-35|0xff7f00,-507|24|0xf2f2f2",degree,48,1124,707,1274} t['skip']={0xf2f2f2,"506|-8|0xff4800,-17|-45|0xf2f2f2",degree,43,1190,713,1319} function app() local timeLine = os.time() while os.time() - timeLine < rd(20,30) do if active(jfq.bid,5)then if d("agree",true,2)then elseif d("skip",true,2)then end end delay(1) end end function all() vpnx() if false or (vpn())then awzNew() start() if (idfa_idfaPc())then up(jfq.name,'ๆŽ’้‡ๆˆๅŠŸ') if(idfa_click())then app() if not(jfq.callback) then idfa_activate() end end end end end while (true) do local ret,errMessage = pcall(all) if ret then else log(errMessage) dialog(errMessage, 10) mSleep(2000) end end <file_sep>-- ็งฏๅˆ†ๅข™ๅฏนๆŽฅ -- xtjfq.lua -- Create By TouchSpriteStudio on 16:26:24 -- Copyright ยฉ TouchSpriteStudio . All rights reserved. -- ็งฏๅˆ†ๅข™ๅฏนๆŽฅ -- xiaoq.lua -- Create By TouchSpriteStudio on 13:15:24 -- Copyright ยฉ TouchSpriteStudio . All rights reserved. package.loaded['AWZ'] = nil require("TSLib") require("AWZ") require("tsp") local var={} local jfq={} jfq.url = 'http://ad.masaike2018.com/ad/' jfq.model = '' jfq.adid = '1185' jfq.appid = '1487600417' jfq.keyword = '่ŠฑๆŸ' jfq.idfa = '' jfq.os_version = '' jfq.device = 'iPhone10,3' jfq.udid = '' jfq.callback = true jfq.name = '่Šๅคฉ่ฏๆœฏ็ฅžๅ™จ' jfq.source = 'hbmh' jfq.channel = 'mz' jfq.bid = 'com.mei.kingkong' function start() local info = getOnlineName() jfq.idfa = strSplit(info[8],":")[2] jfq.os_version = strSplit(info[3],":")[2] jfq.device = strSplit(info[3],":")[2] jfq.udid = strSplit(info[4],":")[2] end function idfa_idfaPc() jfq.model = 'idfaRepeat' local service = jfq.url..jfq.model local postArr = {} postArr.appid = jfq.appid postArr.source = jfq.source postArr.idfa = jfq.idfa -- log(postArr) local postdata = '' for k,v in pairs(postArr) do postdata = postdata .. '&'..k..'='..v end local service = service .."?"..postdata log(service); local res = get(service) if res and (res['status'] == 1) then log(res); jfq.token = res.token log("ๆŽ’้‡ๆˆๅŠŸ","all") return true end end function idfa_click() jfq.model = 'click' local service = jfq.url..jfq.model local postArr = {} postArr.appid = jfq.appid postArr.source = jfq.source postArr.device = jfq.device postArr.idfa = jfq.idfa postArr.os = jfq.os_version if jfq.callback then postArr.callback = urlEncoder("http://wenfree.cn/api/Public/idfa/?service=Idfa.Callback&idfa="..jfq.idfa.."&appid="..jfq.appid) end local postdata = '' for k,v in pairs(postArr) do postdata = postdata .. '&'..k..'='..v end local service = service .."?"..postdata log(service) local res = get(service) log(res) if res and (res['status']) == 1 then log("็‚นๅ‡ปๆˆๅŠŸ","all") return true end end function up(name,other) local url = 'http://wenfree.cn/api/Public/idfa/' local idfalist ={} idfalist.service = 'Idfa.Idfa' idfalist.phonename = getDeviceName() -- idfalist.phoneimei = getIMEI() idfalist.phoneos = jfq.os_version idfalist.idfa = jfq.idfa idfalist.ip = ip() idfalist.account = jfq.keyword idfalist.password = <PASSWORD> idfalist.phone = var.phone idfalist.appid = jfq.appid idfalist.name = name idfalist.other = other log( post(url,idfalist) ) end t={} local degree = 85 t['agree']={0xff5100,"-196|-35|0xff7f00,-507|24|0xf2f2f2",degree,48,1124,707,1274} t['skip']={0xf2f2f2,"506|-8|0xff4800,-17|-45|0xf2f2f2",degree,43,1190,713,1319} function app() local timeLine = os.time() while os.time() - timeLine < rd(20,30) do if active(jfq.bid,5)then if d("agree",true,2)then elseif d("skip",true,2)then end end delay(1) end end function all() vpn.off() if false or (vpn.on())then awzNew() start() if (idfa_idfaPc())then up(jfq.name,'ๆŽ’้‡ๆˆๅŠŸ') if(idfa_click())then up(jfq.name,'็‚นๅ‡ปๆˆๅŠŸ') app() end end end end while (true) do local ret,errMessage = pcall(all) if ret then else log(errMessage) dialog(errMessage, 10) mSleep(2000) end end <file_sep>require("TSLib") require("tsp") --getๅ‡ฝๆ•ฐ function get_lx(url) local sz = require("sz") local http = require("szocket.http") local res, code = http.request(url); if code == 200 then return res end end --ๆฅไฟกๅนณๅฐ function _vCode_lx() --ๆฅไฟก local User = 'APIak7LKwM4sSFAj' local Pass = '<PASSWORD>' local PID = '32431' local token,number = "<KEY>","15232533495" return { login=(function() local RetStr for i=1,5,1 do toast("่Žทๅ–token\n"..i.."ๆฌกๅ…ฑ5ๆฌก") mSleep(1500) local lx_url = 'http://api.smskkk.com/api/do.php?action=loginIn&name='..User..'&password='..<PASSWORD> log(lx_url) RetStr = get_lx(lx_url) if RetStr then RetStr = strSplit(RetStr,"|") if RetStr[1] == 1 or RetStr[1] == '1' then token = RetStr[2] log('token='..token,true) break end else log(RetStr) end end return RetStr; end), getPhone=(function() local RetStr="" local lx_url = "http://api.smskkk.com/api/do.php?action=getPhone&sid="..PID..","..PID.."&token="..token log(lx_url) RetStr = get_lx(lx_url) if RetStr ~= "" and RetStr ~= nil then RetStr = strSplit(RetStr,"|") end if RetStr[1] == 1 or RetStr[1]== '1' then number = RetStr[2] log(number) local phone_title = (string.sub(number,1,3)) local blackPhone = {'144','141','142','143','144','145','146','147'} for k,v in ipairs(blackPhone) do if phone_title == v then local lx_url = 'http://api.smskkk.com/api/do.php?action=addBlacklist&sid='..PID..'&phone='..number..'&token='..token get_lx(lx_url); log("ๆ‹‰้ป‘->"..number) return false end end return number end end), getMessage=(function() local Msg for i_ = 1,2 do for i=1,25,1 do mSleep(3000) local lx_url = "http://api.smskkk.com/api/do.php?action=getMessage&sid="..PID.."&token="..token.."&phone="..number log(lx_url) RetStr = get_lx(lx_url) if RetStr then local arr = strSplit(RetStr,"|") if arr[1] == '1' then Msg = arr[2] local i,j = string.find(Msg,"%d+") Msg = string.sub(Msg,i,j) if type(tonumber(Msg))== "number" then log(Msg); if i_ == 2 then return Msg end break end end end toast(tostring(RetStr).."\n"..i.."ๆฌกๅ…ฑ25ๆฌก") end end return false end), addBlack=(function() local lx_url = 'http://api.smskkk.com/api/do.php?action=addBlacklist&sid='..PID..'&phone='..number..'&token='..token log("ๆ‹‰้ป‘"..number..'\n'..lx_url); return get_lx(lx_url); end), } end DM = _vCode_lx() DM.login() --inputText(DM.getPhone()) inputText(DM.getMessage()) <file_sep>-- lua-img-ๅฐ็™ฝ -- main.lua -- Create By TouchSpriteStudio on 22:15:43 -- Copyright ยฉ TouchSpriteStudio . All rights reserved. function lzScreen(x1,y1,x2,y2,scale) scale = scale or 1; local path=userPath().."/res/yb.jpg"; snapshot("yb.jpg",x1,y1,x2,y2,scale); --os.remove(path) return path; end -----------postไผ ๅ›พ็‰‡ function UploadImgByBase64() --่ฏปๅ–ๅ›พ็‰‡ๅนถ่ฝฌไธบbase64 require("ZZBase64") local files local ptah = userPath().."/res/yb.jpg" local file = io.open(ptah,"rb") files = file:read("*a") file:close() --ๅ›พ็‰‡่ฝฌๆˆbase64ๆ–‡ๆœฌ local fileBase64 = ZZBase64.encode(files) -- ๅฏน่ฑก็ฑปๅž‹ local post_data = { ["file_name"] = "yb.jpg", ["file_type"] = "image/jpg", ["file"] = fileBase64 } --ไธŠไผ ๅ›พ็‰‡ local sz = require("sz") local cjson = sz.json local http = sz.i82.http local service_url = 'http://dogstar.api.yesapi.cn/?s=App.CDN.UploadImgByBase64&app_key=CEE4B8A091578B252AC4C92FB4E893C3' headers = {} headers['User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36' headers_send = cjson.encode(headers) post_send = cjson.encode(post_data) nLog(post_send) post_escaped = http.build_request(post_send) status_resp, headers_resp, body_resp = http.post(service_url, 9, headers_send, post_escaped) nLog(body_resp) if status_resp == 200 then --TODO๏ผšๅฎž็Žฐไฝ ็š„ๆขฆๆƒณ end end local w,h = getScreenSize() lzScreen(1,1,w,h,0.5) UploadImgByBase64() <file_sep>require('tsp') --่ฏปๆ–‡ไปถ function readFile_(path) local path = path or '/var/mobile/Media/TouchSprite/lua/account.txt' local file = io.open(path,"r"); if file then local _list = ''; for l in file:lines() do _list = _list..l end file:close(); return _list end end --ๅ–ๅธๅทtoken function llsGameToken() local appbid = bid local AccountInfo = appDataPath(appbid).."/Documents/AccountInfo.json" local account = readFile_(AccountInfo) if (account) then local allinfo = account local sz = require("sz") local json = sz.json account = json.decode(account) if(account[1]['app_token'])then return {account[1]['app_token'],allinfo} end end return account end function update_token() local RokToken = llsGameToken(); local info_ ={} info_['token']=RokToken[1] info_['idfa']=RokToken[2] -- info_['fighting']=__game.fighting info_['red']=__game.red info_['s']='Rok.Token' _api_rok(info_) end --ๅ†™ๅ…ฅ function writeFile_(info,way,path) local path = path or '/var/mobile/Media/TouchSprite/lua/account.txt' local way = way or 'a' local f = assert(io.open(path, way)) f:write(info) f:write('') f:close() end require('ui'); function _api_rok(info) local url = 'http://rok.honghongdesign.cn/public/'; log(post(url,info)); end --ไธŠไผ ๅธๅทไธ“็”จ function update_token_new() local RokToken = llsGameToken(); local info_ ={} info_['token']=RokToken[1] info_['idfa']=RokToken[2] info_['fighting']=__game.fighting info_['red']=__game.red info_['user_id'] = UIv.user_id info_['s']='Rok.Token' info_['note']= getDeviceName() .. 'ๆ–ฐไธŠไผ ' info_['locals'] = lcoalsBid[UIv.locals+1] _api_rok(info_) end lcoalsBid = {"ๅ›ฝๆœ","ๅ›ฝ้™…ๆœ","ๅฐๆœ","ๆ—ฅๆœ"} local bidarr = {} bidarr['ๅ›ฝ้™…ๆœ'] = "com.lilithgame.roc.ios" bidarr['ๅ›ฝๆœ'] = "com.lilithgames.rok.ios.offical" bidarr['ๅฐๆœ'] = "com.lilithgame.roc.ios.tw" bidarr['ๆ—ฅๆœ'] = "com.lilithgames.rok.ios.jp" bid = bidarr[lcoalsBid[UIv.locals+1]] if update_account then log('ๆญฃๅผๅฏๅŠจไธไธŠไผ ') else log('ๅ•็‹ฌๅฏๅŠจไธŠไผ ๅธๅท') __game={} update_token_new() log('ไธŠไผ ๅธๅทๅฎŒๆˆ',"all") end <file_sep>dyjit = require("mt") _appBid = 'com.nike.onenikecommerce' --appBID _appDataPath = appDataPath(_appBid) function s_getVcState(info) local path = _appDataPath.."/Documents/state.plist" local firstName = info.firstName local lastName = info.lastName local phone = info.phone local code = info.code local password = <PASSWORD>.password local brithday = info.brithday local email = info.email local gender = tonumber(info.gender)-1 local isModify = info.isModify info.session = "" info.nowinfo = {} plist.write(path,info) local script = [==[ local ffi = require("ffi") ffi.cdef[[ id objc_getClass(const char * name); unsigned int sleep(unsigned int); ]] local dic = runtime.NSMutableDictionary:alloc():initWithContentsOfFile_(runtime.Obj("]==]..path..[==[")) local rootVc = runtime.UIWindow:keyWindow():rootViewController() if rootVc:isKindOfClass_(runtime.ONCAppWireframeNavigationController:class()) then local topVC = rootVc:topViewController() if topVC:isKindOfClass_(ffi.C.objc_getClass("SNKRS_inhouse.OnboardingLoginViewController")) then local preVC = runtime.UIWindow:keyWindow():rootViewController():presentedViewController():topViewController() if tostring(preVC) ~= "nil" then if preVC:isKindOfClass_(ffi.C.objc_getClass("NUWebViewController")) then local webView = preVC:webView() local html = webView:stringByEvaluatingJavaScriptFromString_(runtime.Obj("document.getElementsByTagName('html')[0].innerHTML")) if html:containsString_(runtime.Obj("ๆ‰‹ๆœบๅท็ ")) then local phone = webView:stringByEvaluatingJavaScriptFromString_(runtime.Obj("document.getElementsByClassName('phoneNumber')[0].value")) local vercode = webView:stringByEvaluatingJavaScriptFromString_(runtime.Obj("document.getElementsByClassName('code')[0].value")) if "]==]..phone..[==[" == "" then webView:stringByEvaluatingJavaScriptFromString_(runtime.Obj("document.getElementsByClassName('phoneNumber')[0].value=''")) dic:setObject_forKey_(runtime.Obj("waitPhone"),runtime.Obj("session")) dic:writeToFile_atomically_(runtime.Obj("]==]..path..[==["),1) elseif phone:isEqualToString_(runtime.Obj("")) then webView:stringByEvaluatingJavaScriptFromString_(runtime.Obj("document.getElementsByClassName('phoneNumber')[0].value=']==]..phone..[==['")) webView:stringByEvaluatingJavaScriptFromString_(runtime.Obj("document.getElementsByClassName('sendCodeButton')[0].click()")) dic:setObject_forKey_(runtime.Obj("sendPhobe"),runtime.Obj("session")) dic:writeToFile_atomically_(runtime.Obj("]==]..path..[==["),1) elseif vercode:isEqualToString_(runtime.Obj("")) then if "]==]..phone..[==[" == "" then webView:stringByEvaluatingJavaScriptFromString_(runtime.Obj("document.getElementsByClassName('phoneNumber')[0].value=''")) dic:setObject_forKey_(runtime.Obj("waitPhone"),runtime.Obj("session")) dic:writeToFile_atomically_(runtime.Obj("]==]..path..[==["),1) elseif "]==]..code..[==[" == "" then dic:setObject_forKey_(runtime.Obj("waitMsg"),runtime.Obj("session")) dic:writeToFile_atomically_(runtime.Obj("]==]..path..[==["),1) else webView:stringByEvaluatingJavaScriptFromString_(runtime.Obj("document.getElementsByClassName('code')[1].value=']==]..code..[==['")) webView:stringByEvaluatingJavaScriptFromString_(runtime.Obj("document.querySelector('div.mobileJoinContinue > input').click();")) dic:setObject_forKey_(runtime.Obj("sendMsg"),runtime.Obj("session")) dic:writeToFile_atomically_(runtime.Obj("]==]..path..[==["),1) end end elseif html:containsString_(runtime.Obj("ๅ‡บ้”™ไบ†")) then dic:setObject_forKey_(runtime.Obj("error"),runtime.Obj("session")) dic:writeToFile_atomically_(runtime.Obj("]==]..path..[==["),1) elseif html:containsString_(runtime.Obj("้ฆ–้€‰ไบงๅ“")) then webView:stringByEvaluatingJavaScriptFromString_(runtime.Obj("document.querySelector('div.firstName > input').value=']==]..firstName..[==['")) webView:stringByEvaluatingJavaScriptFromString_(runtime.Obj("document.querySelector('div.lastName > input').value=']==]..lastName..[==['")) webView:stringByEvaluatingJavaScriptFromString_(runtime.Obj("document.querySelector('div.password > input').value=']==]..password..[==['")) webView:stringByEvaluatingJavaScriptFromString_(runtime.Obj("document.querySelectorAll('input[type=\"button\"]')[]==]..gender..[==[].click()")) webView:stringByEvaluatingJavaScriptFromString_(runtime.Obj("document.querySelector('div.mobileJoinSubmit > input').click();")) dic:setObject_forKey_(runtime.Obj("page2"),runtime.Obj("session")) dic:writeToFile_atomically_(runtime.Obj("]==]..path..[==["),1) elseif html:containsString_(runtime.Obj("็”ตๅญ้‚ฎไปถ")) then webView:stringByEvaluatingJavaScriptFromString_(runtime.Obj("document.querySelectorAll('input[type=\"email\"]')[0].value=']==]..email..[==['")) webView:stringByEvaluatingJavaScriptFromString_(runtime.Obj("document.querySelector('div.captureEmailSubmit > input').click();")) dic:setObject_forKey_(runtime.Obj("page3"),runtime.Obj("session")) dic:writeToFile_atomically_(runtime.Obj("]==]..path..[==["),1) elseif html:containsString_(runtime.Obj("ๅ‡บ็”Ÿๆ—ฅๆœŸ")) then webView:stringByEvaluatingJavaScriptFromString_(runtime.Obj("document.querySelector('input[type=\"date\"]').value = ']==]..brithday..[==['")) webView:stringByEvaluatingJavaScriptFromString_(runtime.Obj("document.querySelector('div.mobileJoinDobEmailSubmit > input').click();")) dic:setObject_forKey_(runtime.Obj("page4"),runtime.Obj("session")) dic:writeToFile_atomically_(runtime.Obj("]==]..path..[==["),1) else dic:setObject_forKey_(runtime.Obj("loadView"),runtime.Obj("session")) dic:writeToFile_atomically_(runtime.Obj("]==]..path..[==["),1) end return end else topVC:didSelectWithLoginAction_(0) dic:setObject_forKey_(runtime.Obj("page1"),runtime.Obj("session")) dic:writeToFile_atomically_(runtime.Obj("]==]..path..[==["),1) end dic:setObject_forKey_(runtime.Obj("none"),runtime.Obj("session")) dic:writeToFile_atomically_(runtime.Obj("]==]..path..[==["),1) elseif topVC:isKindOfClass_(runtime.ONCTabBarContainerViewController:class()) then local loadingVc = topVC:loadingViewController() if tostring(loadingVc) ~= "nil" then dic:setObject_forKey_(runtime.Obj("loadView"),runtime.Obj("session")) dic:writeToFile_atomically_(runtime.Obj("]==]..path..[==["),1) else local isModify ="]==]..tostring(isModify)..[==[" if isModify == "false" then topVC:setActiveTabType_animated_(0,1) topVC:setActiveTabType_animated_(3,1) local profile = runtime.ONCProfileManager:sharedInstance():profile() local adressInfo = runtime.NSMutableDictionary:alloc():init() local urlString = profile:avatar():urlString() if tostring(urlString)~="nil" then adressInfo:setObject_forKey_(profile:avatar():urlString(),runtime.Obj("avatar")) end adressInfo:setObject_forKey_(runtime.NSNumber:numberWithLongLong_(profile:gender()),runtime.Obj("gender")) adressInfo:setObject_forKey_(runtime.NSNumber:numberWithInteger_(profile:addresses():count()),runtime.Obj("addresses")) adressInfo:setObject_forKey_(profile:lastName(),runtime.Obj("lastName")) adressInfo:setObject_forKey_(profile:firstName(),runtime.Obj("firstName")) adressInfo:setObject_forKey_(profile:nikeShoeSize(),runtime.Obj("nikeShoeSize")) dic:setObject_forKey_(runtime.Obj("getProfile"),runtime.Obj("session")) dic:setObject_forKey_(adressInfo,runtime.Obj("nowinfo")) dic:writeToFile_atomically_(runtime.Obj("]==]..path..[==["),1) else local preVC = rootVc:presentedViewController() if tostring(preVC) ~= "nil" then if preVC:isKindOfClass_(ffi.C.objc_getClass("StoryKit.StoryContainerViewController")) then local StoryViewController = preVC:childViewControllers():objectAtIndex_(0) if StoryViewController:isKindOfClass_(ffi.C.objc_getClass("StoryKit.StoryViewController")) then StoryViewController:dismissView() end end dic:setObject_forKey_(runtime.Obj("dismissView"),runtime.Obj("session")) dic:writeToFile_atomically_(runtime.Obj("]==]..path..[==["),1) else local navigationVC = topVC:childViewControllerForStatusBarStyle() if string.find(tostring(navigationVC:description()),"ONCFeedNavigationController")~=nil then local tabTopVC = navigationVC:topViewController() if tabTopVC:isKindOfClass_(runtime.ONCFeedContainerViewController:class()) then local childVC = tabTopVC:visibleChildViewController() local collectionView = childVC:rootView():collectionView() local nowRow = collectionView:indexPathsForVisibleItems():firstObject():row() local indexPath if nowRow+2>=collectionView:numberOfItemsInSection_(0) then indexPath = runtime.NSIndexPath:indexPathForRow_inSection_(0,0) else indexPath = runtime.NSIndexPath:indexPathForRow_inSection_(nowRow+2,0) end collectionView:scrollToItemAtIndexPath_atScrollPosition_animated_(indexPath,2,1) local rnd = math.random(1,100) if rnd<=50 then local threadId = childVC:displayItemAtIndexPath_(indexPath):threadId() childVC:didSelectItemWithThreadId_(threadId) if rnd <=30 then childVC:userDidTapLikeForCardAtIndexPath_(indexPath) end dic:setObject_forKey_(runtime.Obj("clickView"),runtime.Obj("session")) dic:writeToFile_atomically_(runtime.Obj("]==]..path..[==["),1) else dic:setObject_forKey_(runtime.Obj("drawView"),runtime.Obj("session")) dic:writeToFile_atomically_(runtime.Obj("]==]..path..[==["),1) end elseif tabTopVC:isKindOfClass_(runtime.ONCThreadViewController:class()) then for i = 1,5 do local collectionView = tabTopVC:rootView():collectionView() local nowRow = collectionView:indexPathsForVisibleItems():firstObject():row() local rows = collectionView:numberOfItemsInSection_(0) if nowRow+4>=rows then if i==1 then topVC:setActiveTabType_animated_(0,1) end break else local indexPath = runtime.NSIndexPath:indexPathForRow_inSection_(nowRow+2,0) collectionView:scrollToItemAtIndexPath_atScrollPosition_animated_(indexPath,2,1) end end dic:setObject_forKey_(runtime.Obj("drawView"),runtime.Obj("session")) dic:writeToFile_atomically_(runtime.Obj("]==]..path..[==["),1) end else topVC:setActiveTabType_animated_(0,1) dic:setObject_forKey_(runtime.Obj("none"),runtime.Obj("session")) dic:writeToFile_atomically_(runtime.Obj("]==]..path..[==["),1) end end end end else dic:setObject_forKey_(runtime.Obj("waitView"),runtime.Obj("session")) dic:writeToFile_atomically_(runtime.Obj("]==]..path..[==["),1) end else dic:setObject_forKey_(runtime.Obj("mainView"),runtime.Obj("session")) dic:writeToFile_atomically_(runtime.Obj("]==]..path..[==["),1) end ]==] dyjit.run(_appBid,script) mSleep(400) local session = "" for i = 1,3 do session = plist.read(path).session if session~="" then break end mSleep(1000) end return plist.read(path) end function s_ClickTSAlertButton() --็‚นๆމ่งฆๅŠจ้”™่ฏฏ็ช—ไฝ“ local script = [==[ pcall(function() local windows = runtime.UIApplication:sharedApplication():windows() local wCount = runtime.NSNumber:numberWithInt_(windows:count()):intValue() if wCount then for i = 0,wCount-1 do local window = windows:objectAtIndex_(i) if window:isKindOfClass_(runtime.UIWindow:class()) then local TSUserAlertRootViewController = window:rootViewController() if TSUserAlertRootViewController then if TSUserAlertRootViewController:isKindOfClass_(runtime.TSUserAlertRootViewController:class()) then local TSUserAlertView = TSUserAlertRootViewController:presentedViewController() if TSUserAlertView then if TSUserAlertView:isKindOfClass_(runtime.TSUserAlertView:class()) then local actions = TSUserAlertView:actions() local count = runtime.NSNumber:numberWithInt_(actions:count()):intValue() if count then for i = 0,count-1 do local action = actions:objectAtIndex_(i) TSUserAlertView:__dismissWithAction_(action) end end end end end end end end end end) ]==] dyjit.run("com.apple.springboard",script) sys.msleep(500) end function s_viewsinfo() --ๆ‰“ๅฐUIๅฑ‚็บงๅ…ณ็ณป local path = _appDataPath.."/Documents/Nike.txt" if appIsRunning(_appBid) == false then return nil end os.execute('rm -rf '..path) dyjit.run(_appBid,[==[ local UIApp = runtime.UIApplication:sharedApplication() local c = UIApp:keyWindow():recursiveDescription() if c~=nil then c:writeToFile_atomically_encoding_error_(runtime.Obj("]==]..path..[==["),1,4,nil) end ]==]) sys.msleep(300) if file.exists(path) then local vc=file.reads(path); if vc ==nil then return nil end if vc ~="" then return vc else return nil end else return nil end end --[[ require("Function") require("Common") local info = {} info.isModify = true info.firstName = "12" info.lastName = "23" info.phone = "" info.code = "12" info.password = "12" info.brithday = "12" info.email = "12" info.gender = "12" local vs = s_getVcState(info) Showlog(vs.session) require("Function") require("Common") local info = {} info.isModify = true info.firstName = "12" info.lastName = "23" info.phone = "12" info.code = "12" info.password = "12" info.brithday = "12" info.email = "12" info.gender = "12" local vs = s_getVcState(info) Showlog(vs.session) require("Function") require("Common") local info = { phone = "13610238793", code ="613308", firstName = "่ฅฟ", lastName = "ๆน–้ข", password = "<PASSWORD>", gerden = "1", nikeShoeSize = "8.5", email = "<EMAIL>", brithday = "1986-04-27", isModify = true, avatar = "https://tpc.googlesyndication.com/simgad/9221216781670028002?sqp=4sqPyQQ7QjkqNxABHQAAtEIgASgBMAk4A0DwkwlYAWBfcAKAAQGIAQGdAQAAgD-oAQGwAYCt4gS4AV_FAS2ynT4&rs=AOga4qkXfqToEs1uiWJASwg93zHWub0SsQ", adressInfo = { ["code"] = "313000", ["country"] = "CN", ["code"] = "313000", ["country"] = "CN", ["label"] = "Shipping Address 2", ["line1"] = "็ฝ—ๆน–ๆœบๅœบ", ["line2"] = "็ฝ—ๆน–ๆ–ฐ่‹‘", ["line3"] = "", ["gender"] = 1, ["locality"] = "ๆทฑๅœณๅธ‚", ["email"] = "<EMAIL>", ["name"] = { ["alternate"] ={ ["family"] = "", ["given"] = "", }, ["primary"] ={ ["family"] = "ๆณข", ["given"] = "ๆ–ฝๅทฅ", }, }, ["phone"] = { ["primary"] = "18673539917", }, ["preferred"] = "0", ["province"] = "CN-44", ["region "]= "ๅฐๅœฐๆ–น", ["type"] = "SHIPPING", ["zone"] = "ๅฐๅœฐๆ–น", ["email"] = "", } } local infos = { avatar = "https://source.unsplash.com/random/20*20", gerden = "1", nikeShoeSize = "11.5", firstName = "fa", lastName = "xiao", } local s_url = "http://127.0.0.1:9999/modifyinfo" pdata = json.encode(infos) local c,h,b = http.tspost(s_url,10,{},pdata) dialog(c) if c == 200 then dialog(b) end --]] -- --[==[ //ๆณจๅ†Œ็•Œ้ข NUWebViewController var wv = #0x1063d9930 [wv stringByEvaluatingJavaScriptFromString:@"document.getElementsByClassName('phoneNumber')[0].value='17018020466'"] //ๅกซๅ†™ๆ‰‹ๆœบๅท็  [wv stringByEvaluatingJavaScriptFromString:@"document.getElementsByClassName('sendCodeButton')[0].click()"] //ๅ‘้€้ชŒ่ฏ็  [wv stringByEvaluatingJavaScriptFromString:@"document.getElementsByClassName('code')[1].value='757363'"] //ๅกซๅ†™้ชŒ่ฏ็  [wv stringByEvaluatingJavaScriptFromString:@"document.querySelector('div.mobileJoinContinue > input').click();"] //็ปง็ปญ [wv stringByEvaluatingJavaScriptFromString:@"var lastName = document.querySelector('div.lastName > input');lastName.value='้น'"] //ๅง“ [wv stringByEvaluatingJavaScriptFromString:@"var firstName = document.querySelector('div.lastName > input');firstName.value='้™ˆ'"] //ๅ [wv stringByEvaluatingJavaScriptFromString:@"document.querySelector('div.lastName > input').value='้™ˆ';document.querySelector('div.firstName > input').value='้น';document.querySelector('div.password > input').value='<PASSWORD>';"] //ๅง“ๅ [wv stringByEvaluatingJavaScriptFromString:@"document.querySelectorAll('input[type=\"button\"]')[0].click();"] //้€‰ๆ€งๅˆซ 0/็”ท 1/ๅฅณ [wv stringByEvaluatingJavaScriptFromString:@"document.querySelector('div.mobileJoinSubmit > input').click();"] //ๆณจๅ†Œ [wv stringByEvaluatingJavaScriptFromString:@"document.querySelectorAll('input[type=\"email\"]')[0].value='<EMAIL>'"] //่พ“ๅ…ฅ็”ตๅญ้‚ฎไปถ [wv stringByEvaluatingJavaScriptFromString:@"document.querySelector('div.captureEmailSubmit > input').click();"] //ไฟๅญ˜็”ตๅญ้‚ฎไปถ [wv stringByEvaluatingJavaScriptFromString:@"document.querySelector('input[type=\"date\"]').value = '1986-04-27'"] //่พ“ๅ…ฅๅ‡บ็”Ÿๆ—ฅๆœŸ [wv stringByEvaluatingJavaScriptFromString:@"document.querySelector('div.mobileJoinDobEmailSubmit > input').click();"] //ไฟๅญ˜ๅ‡บ็”Ÿๆ—ฅๆœŸ // ้€‰ๆ‹ฉๅ›ฝๅฎถๅœฐๅŒบ // ็งปๅŠจๅˆฐๅบ•้ƒจ [#ONCTabBarContainerViewController setActiveTabType:0 animated:YES] --ๅˆ‡ๆขไธป้กตTAB [[[[[[[UIWindow keyWindow] rootViewController] topViewController] viewControllerMap] objectForKey:0] topViewController] visibleChildViewController] ๅˆ†้กต1็š„ไธปๆŽงๅˆถๅ™จ [[[[[[UIWindow keyWindow] rootViewController] topViewController] viewControllerMap] objectForKey:1] topViewController] ๅˆ†้กต2็š„ไธปๆŽงๅˆถๅ™จ [[[[[[UIWindow keyWindow] rootViewController] topViewController] viewControllerMap] objectForKey:2] topViewController] ๅˆ†้กต4็š„ไธปๆŽงๅˆถๅ™จ [[[[[[UIWindow keyWindow] rootViewController] topViewController] viewControllerMap] objectForKey:3] topViewController] ๅˆ†้กต4็š„ไธปๆŽงๅˆถๅ™จ ๅˆ†้กต1 ๆŽงๅˆถๅ™จ ONCFeedContainerViewController or ONCThreadViewController ๅบ•ๅฑ‚ไธป้กตๆŽงๅˆถๅ™จ ONCFeedContainerViewController visibleChildViewController =ONCFeedViewController [vc collectionView:#0x106064c00 didSelectItemAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]] ่ฟ›ๅ…ฅ่ฏฆๆƒ…้กต var threadId = [[vc displayItemAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]] threadId] ่Žทๅ–ๅ•ๅ“ID [vc didSelectItemWithThreadId:threadId] ๆ นๆฎID่ฟ›ๅ…ฅ่ฏฆๆƒ…้กต var collectionView = [[vc rootView] collectionView] [collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0] atScrollPosition:1 animated:YES] ๅˆ†้กต1 ๆป‘ๅŠจ ่ฏฆๆƒ…้กตๆŽงๅˆถๅ™จ ONCThreadViewController //topViewController var collectionView = [[vc rootView] collectionView] [collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:[collectionView numberOfSections] inSection:0] atScrollPosition:1 animated:YES] ่ฏฆๆƒ…้กต ๆป‘ๅŠจ [vc userDidTapLikeForCardAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]] --ๆ”ถ่—่ฟ™ไธชๅ•†ๅ“ var navVc = [[[[[UIWindow keyWindow] rootViewController] topViewController] viewControllerMap] objectForKey:0] [navVc popToViewController:[vc bottomViewController] animated:YES] --ๅฏผ่ˆชๆŽงๅˆถๅ™จ่ฟ”ๅ›žๅˆฐๅบ•ๅฑ‚ๆŽงๅˆถๅ™จ ๅˆ†้กต4 ๆŽงๅˆถๅ™จ ONCProfileViewController or ONCSettingsViewController ไธชไบบไธป้กตๆŽงๅˆถๅ™จ ONCProfileViewController ๆขๅคดๅƒ var url = [NSURL URLWithString: @"https://image.baidu.com/search/detail?ct=503316480&z=undefined&tn=baiduimagedetail&ipn=d&word=UIImage%20&step_word=&ie=utf-8&in=&cl=2&lm=-1&st=undefined&hd=undefined&latest=undefined&copyriht=ndefined&cs=3806547475,570102247&os=561112789,3202358382&simid=0,0&pn=99&rn=1&di=80410&ln=1508&fr=&fmq=1566755759392_R&fm=&ic=undefined&s=undefined&se=&sme=&tab=0&width=undefined&height=undefined&face=undefined&is=0,0&istype=0ist=jit=&bdtype=0&spn=0&pi=0&gsm=3c&objurl=http%3A%2F%2Fimg-blog.csdnimg.cn%2F20190309113305425.jpg&rpstart=0&rpnum=0&adpicid=0&force=undefined&ctd=1566755769188^3_1377X964%1"] var image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]] var pManger = [ONCProfileManager sharedInstance] [pManger saveAndPersistAvatar:image withCompletionBlock:nil] [pManger saveProfileToKeychain:[[ONCProfileManager sharedInstance] profile]] [pManger refreshProfileWithCompletion:nil] var adress = [[_TtC13SNKRS_inhouse11AddressForm alloc] initWithCountry:@"CN"] var addressID = [adress addressID] local adreesinfo = dic:valueForKey_(runtime.Obj("adressInfo")) local adressID = runtime._TtC13SNKRS_inhouse11AddressForm:alloc():initWithCountry_(runtime.Obj("CN")):addressID() adreesinfo:setObject_forKey_(adressID,runtime.Obj("guid")) local oncAddress = runtime.ONCAddress:addressFromProfileDictionary_(adreesinfo) local adrDict = runtime.NSMutableDictionary:alloc():init() adrDict:setObject_forKey_(oncAddress,adressID) pManger:profile():setAddresses_(adrDict) --]==]<file_sep>-- ๆๅ–codes -- nikereg -- Create By TouchSpriteStudio on 02:31:56 -- Copyright ยฉ TouchSpriteStudio . All rights reserved. require("TSLib") require("tsp") require("AWZ") local sz = require("sz") local json = sz.json require("other") var={} var.bid='com.nike.omega' var.account={} var.account.login = '' var.account.pwd = nil var.account.address_country = 'CN' var.account.phone = nil function backId() local postUrl = 'http://zzaha.com/phalapi/public/' local postArr = {} postArr.s = 'Nikeback.Back' postArr.id = var.account.id log(post(postUrl,postArr)) end function disable() local postUrl = 'http://zzaha.com/phalapi/public/' local postArr = {} postArr.s = 'Nikeback.disable' postArr.id = var.account.id log(post(postUrl,postArr)) end function getLogin(again) local getIdUrl = 'http://zzaha.com/phalapi/public/?s=Nikeagain.Again&again='..again..'&name='..'iPhone'..rd(1,50); local data = get(getIdUrl); if data then return data end; end function updateNikeLog(workstate) local sz = require("sz") local url = 'http://zzaha.com/phalapi/public/' local Arr={} Arr.s = 'Nikesave.Save' Arr.address_mail = var.account.login Arr.workstate = workstate post(url,Arr) end function updateNike() local sz = require("sz") local url = 'http://zzaha.com/phalapi/public/' local Arr={} Arr.s = 'Nikesave.Save' Arr.address_mail = var.account.login Arr.address_pwd = var.account.pwd Arr.address_phone = var.account.phone Arr.address_xin = var.account.xin Arr.address_ming = var.account.ming Arr.address_sheng = 'ๅนฟไธœ็œ' Arr.address_shi = 'ๆทฑๅœณๅธ‚' Arr.address_qu = '็ฝ—ๆน–ๅŒบ' Arr.address_area = var.account.address_area Arr.address_country = var.account.address_country Arr.iphone = getDeviceName() Arr.imei = sz.system.serialnumber() Arr.birthday = var.birthday Arr.moon = var.moon Arr.codes = var.codes Arr.sms = UIvalues.sms log(Arr) if post(url,Arr)then return true end end function boxshow(txt,x1,y1,x2,y2) local x1 = x1 or 0 local y1 = y1 or 0 local x2 = x2 or 300 local y2 = y2 or 30 adbox__ = adbox__ or 0 if adbox__ == 0 then adbox__ = 1 fwShowWnd("wid",w/2+50,0,w/2+300,50,1) mSleep(2000) end fwShowTextView("wid","textid",txt,"left","FF0000","FFDAB9",10,0,x1,y1, x2,y2,0.5) --fwShowTextView("wid","textid","่ฟ™ๆ˜ฏไธ€ไธชๆ–‡ๆœฌ่ง†ๅ›พ","center","FF0000","FFDAB9",0,20,0,0,200,100,0.5) end w,h = getScreenSize(); function delay(times) local times = times or 1 local timeLine = os.time() while os.time() - timeLine <= times do mSleep(1000) if (times-(os.time() - timeLine) > 3) then local text = "ๅ€’่ฎกๆ—ถ->ใ€Œ".. times-(os.time() - timeLine) .."ใ€" -- log("ๅ€’่ฎกๆ—ถ->ใ€Œ".. times-(os.time() - timeLine) .."ใ€",true) boxshow(text,0,0,200,30); end end end t={} local degree = 90 t['็™ปๅฝ•็•Œ้ข_ๅŠ ๅ…ฅ'] = { 0,"92|-55|0xffffff,-78|36|0xffffff,439|-11|0xfefefe,-122|-12|0xffffff,-17|-18|0,-111|-426|0xffffff",degree,14,635,731,1276} t['ๅˆ›ๅปบNIKEๅธๆˆท_็ปง็ปญๆŒ‰้’ฎ'] = { 0xffffff,"-291|-37|0,307|160|0xb80c,-297|182|0xb80c,323|-34|0",degree,16,18,729,1163} t['ๅˆ›ๅปบNIKEๅธๆˆท_ๆ‰‹ๆœบๅธๅท'] = { 0xa9a9a9,"-1|13|0xffffff,-1|22|0xa9a9a9,-142|16|0x111111,-184|15|0x111111",degree,10,118,735,778} t['ๅˆ›ๅปบNIKEๅธๆˆท_ๅ‘้€้ชŒ่ฏ็ '] = { 0x111111,"-56|-35|0xe5e5e5,96|37|0xe5e5e5,-55|36|0xe5e5e5",degree,486,251,743,677} t['ๅˆ›ๅปบNIKEๅธๆˆท_่พ“ๅ…ฅ้ชŒ่ฏ็ '] = { 0xa9a9a9,"-1|21|0xa9a9a9,-100|2|0xadadad,-82|22|0xa9a9a9,-89|19|0xffffff,-191|-52|0xffffff,555|93|0xffffff",degree,1,260,748,954} t['ๅˆ›ๅปบNIKEๅธๆˆท_ๆณจๅ†Œโ€”โ€”ๅกซ่ต„ๆ–™'] = { 0xffffff,"-299|-40|0,311|36|0,-291|59|0x8d8d8d,295|137|0x8d8d8d,-239|-237|0x111111",degree,9,340,741,1216} t['ๅˆ›ๅปบNIKEๅธๆˆท_ๆ‚จๅทฒ็™ปๅฝ•โ€”โ€”ๅกซ่ต„ๆ–™'] = { 0xffffff,"-1|-1|0,-299|-40|0,324|39|0,-291|128|0x8d8d8d,307|51|0x8d8d8d,-14|78|0",degree,21,406,720,1191} t['ๅˆ›ๅปบNIKEๅธๆˆท_ๆ‚จๅทฒ็™ปๅฝ•โ€”โ€”็”ตๅญ้‚ฎไปถๅœฐๅ€'] = { 0x8d8d8d,"-152|4|0x919191,-193|-21|0xe5e5e5,443|-15|0xe5e5e5,407|-38|0xe5e5e5",degree,23,546,728,870} t['ๆญฅ้ชคโ€”โ€”็ซ‹ๅณๅผ€ๅง‹'] = { 0x111111,"-284|-52|0xffffff,375|-48|0xffffff,373|57|0xffffff,-278|57|0xffffff",degree,21,1147,730,1319} t['ๆญฅ้ชคโ€”โ€”็”ทๅฅณ้€‰ๆ‹ฉ'] = { 0xffffff,"-7|2|0,-150|-53|0xffffff,159|213|0xfcfcfc,159|212|0",degree,145,488,620,989} t['ๆญฅ้ชคโ€”โ€”ไฟๅญ˜ๆ‚จ็š„้ž‹็ '] = { 0x80808,"1|-1|0xffffff,-677|-2|0xffffff,-672|-2|0",degree,10,44,731,329} t['ๆญฅ้ชคโ€”โ€”้€‰ๆ‹ฉๆ„Ÿ่ง‰ๅ…ด่ถฃ็š„ๅ†…ๅฎน'] = { 0xffffff,"-405|14|0xffffff,-109|13|0",degree,102,107,624,294} t['NIKE็™ปๅฝ•ๆˆๅŠŸ'] = { 0x111111,"0|5|0xffffff,0|10|0x111111,0|16|0xffffff,0|20|0x111111,30|22|0x111111",degree,163,1242,268,1324} t['NIKE-้ฆ–้กต'] = { 0x111111,"0|6|0xffffff,17|11|0x111111,15|9|0xffffff,-16|-9|0xffffff,-18|-9|0x111111",degree,21,1244,124,1323} t['ๅผน็ช—_่พ“ๅ…ฅ็š„ๅฎŒๆˆ']={ 0x007aff, "-43|-20|0x007aff", degree, 646, 594, 742, 956 } --ๅคš็‚นๆ‰พ่‰ฒ function reg() local timeline = os.time() local outTimes = 3*60; var.account.login = mail_rand(rd(2,3)) if true or UIvalues.password_key == '0' then var.account.pwd = myRand(3,1,1)..myRand(3,2,2)..myRand(3,2,2)..myRand(1,3) log(var.account.pwd) else var.account.pwd = <PASSWORD> end boxshow('ๅ‡†ๅค‡ๆณจๅ†Œ'); while os.time()-timeline < outTimes do if active(var.bid,3) then if d('็™ปๅฝ•็•Œ้ข_ๅŠ ๅ…ฅ',true)then elseif d('ๅˆ›ๅปบNIKEๅธๆˆท_็ปง็ปญๆŒ‰้’ฎ')then if d('ๅˆ›ๅปบNIKEๅธๆˆท_ๆ‰‹ๆœบๅธๅท',true,1,3)then boxshow('ๅกซๆ‰‹ๆœบๅท'); var.account.phone = vCode.getPhone() if var.account.phone then inputword(var.account.phone) end elseif d('ๅˆ›ๅปบNIKEๅธๆˆท_ๅ‘้€้ชŒ่ฏ็ ',true,1,2)then boxshow('ๅ‘้€้ชŒ่ฏ็ '); elseif d('ๅˆ›ๅปบNIKEๅธๆˆท_่พ“ๅ…ฅ้ชŒ่ฏ็ ',true,1,2)then log(x..','..y) boxshow('่พ“ๅ…ฅ้ชŒ่ฏ็ '); if d('ๅผน็ช—_่พ“ๅ…ฅ็š„ๅฎŒๆˆ')then sms = vCode.getMessage() if sms then log(sms,true); inputword(sms); delay(2) d('ๅผน็ช—_่พ“ๅ…ฅ็š„ๅฎŒๆˆ',true) else return false end end elseif d('ๅˆ›ๅปบNIKEๅธๆˆท_็ปง็ปญๆŒ‰้’ฎ',true,1,5)then boxshow('็ปง็ปญๆŒ‰้’ฎ'); end elseif d('ๅˆ›ๅปบNIKEๅธๆˆท_ๆณจๅ†Œโ€”โ€”ๅกซ่ต„ๆ–™')then boxshow('ๆณจๅ†Œโ€”โ€”ๅกซ่ต„ๆ–™'); local info = {{200,263,0xffffff},{491,400,0xffffff}, {390,508,0xffffff}, {371,582,0xffffff},} for i,v in ipairs(info)do click(v[1],v[2]); if i == 1 then local str_len = utf8.len(first_names) local str_rnd = (math.random(1,str_len) -1) * 3 var.account.xin = utf8.char(utf8.codepoint(first_names,str_rnd + 1,str_rnd + 2)) clearTxt(); delay(1); input(var.account.xin); d('ๅผน็ช—_่พ“ๅ…ฅ็š„ๅฎŒๆˆ',true) elseif i == 2 then local str_len = utf8.len(last_names) local str_rnd = (math.random(1,str_len) -1) * 3 var.account.ming = utf8.char(utf8.codepoint(last_names,str_rnd + 1,str_rnd + 2)) clearTxt(); input(var.account.ming); d('ๅผน็ช—_่พ“ๅ…ฅ็š„ๅฎŒๆˆ',true) elseif i == 3 then clearTxt() input(var.account.pwd) d('ๅผน็ช—_่พ“ๅ…ฅ็š„ๅฎŒๆˆ',true) elseif i == 4 then var.birthday = '' var.year = os.date(os.date("%Y")) var.moon = os.date(os.date("%m")) var.day = os.date("%d") local rd__ = rd(9,14) click_random(228,1001,rd__) var.year = (var.year+1-rd__*2) local rd__ = rd(2,5) click_random(364,1053,rd__) var.moon = var.moon-rd__ if var.moon <= 0 then var.moon = var.moon + 12 end local rd__ = rd(2,5) click_random(508,1053,rd__) var.day = var.day-rd__ if var.day <= 0 then var.day = var.day + 30 end var.birthday = var.year ..'/'.. var.moon ..'/'.. var.day d('ๅผน็ช—_่พ“ๅ…ฅ็š„ๅฎŒๆˆ',true) end end d('ๅˆ›ๅปบNIKEๅธๆˆท_ๆณจๅ†Œโ€”โ€”ๅกซ่ต„ๆ–™',true,1,6); elseif d('ๅˆ›ๅปบNIKEๅธๆˆท_ๆ‚จๅทฒ็™ปๅฝ•โ€”โ€”ๅกซ่ต„ๆ–™')then boxshow('ๅกซ่ต„ๆ–™้‚ฎ็ฎฑ'); moveTo(360,1046,360,1263,15); delay(2); if d('ๅˆ›ๅปบNIKEๅธๆˆท_ๆ‚จๅทฒ็™ปๅฝ•โ€”โ€”็”ตๅญ้‚ฎไปถๅœฐๅ€',true,1,2)then input(var.account.login); d('ๅˆ›ๅปบNIKEๅธๆˆท_ๆ‚จๅทฒ็™ปๅฝ•โ€”โ€”ๅกซ่ต„ๆ–™',true,1,5); end elseif d('ๆญฅ้ชคโ€”โ€”็ซ‹ๅณๅผ€ๅง‹',true)then boxshow('ๆญฅ้ชคโ€”โ€”็ซ‹ๅณๅผ€ๅง‹'); elseif d('ๆญฅ้ชคโ€”โ€”็”ทๅฅณ้€‰ๆ‹ฉ')then local sex_ = rd(1,2); local sex__ = {{374,666,0},{377,818,0},}; click(sex__[sex_][1],sex__[sex_][2]); boxshow('ๆญฅ้ชคโ€”โ€”็”ทๅฅณ้€‰ๆ‹ฉ'); elseif d('ๆญฅ้ชคโ€”โ€”ไฟๅญ˜ๆ‚จ็š„้ž‹็ ')then boxshow('ๆญฅ้ชคโ€”โ€”ไฟๅญ˜ๆ‚จ็š„้ž‹็ '); local shoes = {{644,479,0},{105,587,0},{210,588,0},{320,587,0},{428,587,0},{528,585,0},{643,585,0},} local rd_ = rd(1,7) click(shoes[rd_][1],shoes[rd_][2]) elseif d('ๆญฅ้ชคโ€”โ€”้€‰ๆ‹ฉๆ„Ÿ่ง‰ๅ…ด่ถฃ็š„ๅ†…ๅฎน')then local choice = {{204,521,0x5b5754},{565,529,0x505721},{185,964,0x92867e},{543,967,0xf0423b},} for i,v in ipairs(choice) do if rd(1,100)> 20 then click(v[1],v[2],2); end end d('ๆญฅ้ชคโ€”โ€”็ซ‹ๅณๅผ€ๅง‹',true); elseif d('NIKE็™ปๅฝ•ๆˆๅŠŸ') or d('NIKE-้ฆ–้กต')then updateNike(); return true else if d('ๅผน็ช—_่พ“ๅ…ฅ็š„ๅฎŒๆˆ',true,1)then end end end delay(1) log('login->'..os.time()-timeline) end end t['็‚นๅ‡ปๆˆ‘'] = { 0xcccccc,"1|-10|0xffffff,0|-19|0xcccccc,2|15|0xffffff,18|7|0xcccccc",degree,642,1252,722,1324} t['ๆ”ถไปถ็ฎฑ'] = { 0x111111,"-7|-1|0xffffff,-15|181|0x111111,-14|172|0xffffff,1|196|0x111111",degree,604,1056,725,1325} t['ๆ”ถไปถ็ฎฑ_1'] = { 0xfa5401,"59|18|0x111111,1|43|0xfa5401",degree,530,951,731,1229} t['ๆ”ถไปถ็ฎฑ็•Œ้ข'] = { 0x111111,"0|11|0xffffff,15|16|0x111111,-642|-1210|0x111111,-629|-1211|0xffffff",degree,12,44,734,1329} t['ๆ”ถไปถ็ฎฑ็•Œ้ขโ€”โ€”็”Ÿๆ—ฅๅฟซไน'] = { 0xc9b8ea,"8|26|0xd8ace0,-9|23|0xffffff",degree,15,138,217,1232} t['ไผšๅ‘˜็”Ÿๆ—ฅไธ“ๅฑž็ฆๅˆฉ'] = { 0,"-469|-12|0x7aff,-480|0|0x7aff,-468|13|0x7aff",degree,7,43,516,121} t['ไผšๅ‘˜็”Ÿๆ—ฅไธ“ๅฑž็ฆๅˆฉโ€”โ€”code'] = { 0xffffff,"-23|-57|0xe5e5e5,-41|62|0xe5e5e5,479|62|0xe5e5e5,462|-57|0xe5e5e5,188|-7|0x111111",degree,17,138,720,1319} t['ๆˆ‘็š„็•Œ้ข-่ฎพ็ฝฎ'] = { 0xcccccc,"-1|-11|0xffffff,-187|-21|0xcccccc,-189|-6|0xffffff,-570|-9|0xcccccc,-580|-19|0xffffff",degree,20,383,732,1109} t['่ฎพ็ฝฎ็•Œ้ขโ€”โ€”็”Ÿๆ—ฅ'] = { 0xff841f,"-4|11|0xff8521",degree,553,361,741,515} t['่ฎพ็ฝฎ็•Œ้ขโ€”โ€”ๆฒกๆœ‰็”Ÿๆ—ฅ'] = { 0x1d1d1d,"304|-357|0x111111,301|-355|0xffffff,-64|-348|0x111111,-54|-347|0xffffff",degree,8,40,740,617} t['่ฎพ็ฝฎ็•Œ้ข'] = { 0x1a1a1a,"-3|-7|0xe8e8e8,-1|-9|0x111111,-369|0|0x111111,-358|0|0xffffff,-13|-7|0xf9f9f9",degree,9,43,731,137} t['่ฎพ็ฝฎ็•Œ้ข_้…้€ไฟกๆฏ'] = { 0xc7c7cc,"-595|-60|0xe5e5e5,-671|-9|0,-671|-8|0xf7f7f7,-611|7|0xffffff,-609|9|0",degree,1,570,745,1190} t['่ฎพ็ฝฎ็•Œ้ข_ๅคดๅƒ็›ธๆœบ'] = { 0xffffff,"-37|-21|0xd8d8d8,-35|-25|0xffffff,15|-3|0xd8d8d8,71|-2|0xd8d8d8,-92|-1|0xd8d8d8,-9|80|0xd8d8d8,-12|-84|0xd8d8d8",degree,258,283,489,499} t['่ฎพ็ฝฎ็•Œ้ข_ๅคดๅƒไบบๅคด'] = { 0xf7f7f7,"-1|-50|0xf7f7f7,0|-57|0xd8d8d8,1|-76|0xd8d8d8,-81|3|0xd8d8d8,81|5|0xd8d8d8,-2|82|0xf7f7f7,50|51|0xf7f7f7",degree,248,279,500,487} t['้…้€ไฟกๆฏ็•Œ้ข'] = { 0xffffff,"3|-2|0x111111,-13|0|0xffffff,-15|0|0x111111,-396|5|0x111111,313|30|0xffffff",degree,2,38,748,133} t['้…้€ไฟกๆฏ็•Œ้ข_ๆ–ฐๅœฐๅ€'] = { 0xffffff,"-389|-47|0x121212,132|65|0x121212",degree,12,1044,731,1228} t['้…้€ไฟกๆฏ็•Œ้ข_ๅœฐๅ€ๅฎŒๆˆ'] = { 0xffffff,"4|-23|0x1d1d1d,5|12|0x1d1d1d,624|-1|0x121212,624|-2|0xffffff",degree,11,135,735,440} t['ๆทปๅŠ ๅœฐๅ€็•Œ้ข'] = { 0x111111,"-3|24|0xffffff,7|27|0x111111,-428|10|0x111111,-125|9|0xffffff,261|16|0xffffff",degree,6,39,749,175} t['ๆทปๅŠ ๅœฐๅ€็•Œ้ข_็บข่‰ฒ'] = { 0xff0015,"-7|98|0xff0015,-57|45|0xff0015",degree,9,132,736,671} t['ๆทปๅŠ ๅœฐๅ€็•Œ้ข_ๆญฃ็กฎๆทปๅŠ '] = { 0xffffff,"-261|-52|0x121212,267|63|0x121212,-309|10|0x121212",degree,13,1000,735,1190} t['ๅผน็ช—โ€”โ€”้ชŒ่ฏๅธๆˆท'] = { 0xc7c7cc,"7|-21|0xc7c7cc,46|-57|0xcccccc,264|39|0xffffff,264|40|0xcccccc",degree,149,437,605,902} t['ๅผน็ช—โ€”โ€”้ชŒ่ฏๅธๆˆท_่พ“ๅฏ†็ '] = { 0xffffff,"-138|-45|0x111111,154|0|0x111111,35|51|0x111111,-241|-1|0xffffff,-243|-1|0x111111",degree,144,241,607,691} t['ๅผน็ช—_่พ“ๅ…ฅๅœฐๅ€็š„ๅฎŒๆˆ'] = { 0x111111,"-5|3|0xffffff,-42|3|0x111111",degree,614,648,740,913} t['ๅผน็ช—_้€‰ๆ‹ฉ็…ง็‰‡'] = { 0,"1|-4|0xefefef,1|-123|0,41|130|0,39|132|0xffffff",degree,231,963,472,1328} t['ๅผน็ช—_้€‰ๆ‹ฉๆ—ถๅˆป'] = { 0xc7c7cc,"-370|-140|0x111111,-367|-142|0xffffff,-54|-137|0x111111,-56|-144|0xffffff",degree,46,50,743,371} t['ๅผน็ช—_้€‰ๆ‹ฉๆ—ถๅˆป็…ง็‰‡'] = { 0x111111,"-1|3|0xf7f7f7,36|-6|0x111111,328|2|0x111111,331|4|0xffffff,-334|4|0x111111,-329|4|0xffffff",degree,9,49,743,123} t['ๅผน็ช—_็…ง็‰‡้€‰ๅ–'] = { 0xffffff,"3|-5|0x141414,38|-6|0x141414,39|-9|0xffffff,-648|-13|0x141414,-647|-12|0xf3f3f3",degree,12,1219,746,1325} function readBirthday() local timeline = os.time() local outTimes = 5*60 local msgbox = 0 updateNikeLog('ๅ‡†ๅค‡ไฟฎๆญฃ็”Ÿๆ—ฅ'); local readBirthday = true local address = true local ่ฎพ็ฝฎok = 0 local header = true while os.time()-timeline < outTimes do if active(var.bid,3) then if d('NIKE็™ปๅฝ•ๆˆๅŠŸ') or d('NIKE-้ฆ–้กต')then d('็‚นๅ‡ปๆˆ‘',true,1,2); elseif d('ๆˆ‘็š„็•Œ้ข-่ฎพ็ฝฎ',false,1)then if address or readBirthday then d('ๆˆ‘็š„็•Œ้ข-่ฎพ็ฝฎ',true,1) elseif header and d('่ฎพ็ฝฎ็•Œ้ข_ๅคดๅƒ็›ธๆœบ',true,1,2)then elseif header and d('่ฎพ็ฝฎ็•Œ้ข_ๅคดๅƒไบบๅคด',true,1,2)then else ่ฎพ็ฝฎok = ่ฎพ็ฝฎok + 1 if ่ฎพ็ฝฎok > 5 then updateNikeLog('ๅฎŒๆˆๆณจๅ†Œ'); return true end end elseif d("่ฎพ็ฝฎ็•Œ้ข")then if readBirthday and d('่ฎพ็ฝฎ็•Œ้ขโ€”โ€”็”Ÿๆ—ฅ')then var.birthday = ocr(566,379,744,475); var.birthday = string.gsub(var.birthday, "%s+", "") var.birthday = string.gsub(var.birthday, "|", "/") local moonArr = split(var.birthday,"/") var.moon = moonArr[2] boxshow(var.birthday); updateNike(); updateNikeLog('ไฟฎๆญฃ็”Ÿๆ—ฅ') readBirthday = false elseif address and d('่ฎพ็ฝฎ็•Œ้ข_้…้€ไฟกๆฏ',true,1,2)then else click(34,76,2) end elseif d("้…้€ไฟกๆฏ็•Œ้ข")then if d("้…้€ไฟกๆฏ็•Œ้ข_ๅœฐๅ€ๅฎŒๆˆ")then click(40,80,1) address = false elseif d('้…้€ไฟกๆฏ็•Œ้ข_ๆ–ฐๅœฐๅ€',true)then end elseif d('ๆทปๅŠ ๅœฐๅ€็•Œ้ข')then local fix = { {299,211,0xffffff}, --ๅง“ {658,211,0xffffff}, --ๅ {620,332,0xffffff}, --็”ต่ฏ {420,587,0xffffff}, --็œๅธ‚ๅŒบ {426,719,0xffffff}, --่ก—้“ {405,933,0xffffff}, --้‚ฎ็ผ– } for i,v in ipairs(fix)do if d('ๆทปๅŠ ๅœฐๅ€็•Œ้ข_็บข่‰ฒ')then break; end click(v[1],v[2]); clearTxt(); if i == 1 then inputStr(var.account.xin or myRand(7,1)) elseif i == 2 then inputStr(var.account.ming or myRand(7,rd(1,2))) elseif i == 3 then inputword(var.account.phone or myRand(2)) elseif i == 4 then delay(1) click_N(121,1181,8) click_N(370,1181,5) click_N(621,1181,6) elseif i == 5 then local addr_list = split(street_addrs,",") local addr = addr_list[math.random(1,#addr_list)] local where ={ string.format("ๅปถ่Šณ่ทฏ4038ๅท %s%sๅฐๅŒบ%d%dๆ ‹%d0%d%dๅท", myRand(7,1),myRand(7,1),rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9) ), string.format("็ฝ—ๆฒ™่ทฏ4099ๅท %s%sๅฐๅŒบ%d%dๆ ‹%d0%d%dๅฎค", myRand(7,1),myRand(7,1),rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9) ), string.format("ๅปถ่Šณ่ทฏ600ๅท %s%sๅฐๅŒบ%d%dๆ ‹%d0%d%dๅฎค", myRand(7,1),myRand(7,1),rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9) ), string.format("ๅปถ่Šณ่ทฏ588ๅท %s%s%sๅฐๅŒบ%d%dๆ ‹%d0%d%dๅท", myRand(7,1),myRand(7,1),myRand(7,1),rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9) ), string.format("็ฝ—ๆน–ๅนฟๅฒญๅฐๅŒบ %d%dๆ ‹%d0%d%dๅท", rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9) ), string.format("็ฝ—ๆฒ™่ทฏ ๆ–ฐไธ–็•Œๅ››ๅญฃๅพกๅ›ญ %d%d%dๆ ‹%d0%d%dๅท", rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9) ), string.format("ๅคงๆพŽ่Šฑๅ›ญ %d%dๆ ‹%d%d0%dๅฎค", rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9) ), string.format("ไธญ้œ‡ๅคงๅŽฆ %s%s้˜%d%d0%dๅฎค", rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9) ), string.format("้€šๅ‘่Šฑๅ›ญ %d%dๆ ‹%d0%d%dๅท", rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9) ), string.format("็ฝ—่Šณ่‹‘ %d%dๆ ‹%d%d0%dๅฎค", rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9) ), string.format("้“ถไธฐ่Šฑๅ›ญ %d%dๆ ‹%d0%d%dๅท", rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9) ), string.format("้พ™ๆณ‰่Šฑๅ›ญ %d%dๆ ‹%d0%d%dๅท", rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9) ), string.format("่Šณๆ˜ฅ่Šฑๅ›ญ %d%dๆ ‹%d0%d%dๅท", rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9) ), string.format("ๆทฑๆธฏๆ–ฐๆ‘ %d%dๆ ‹%d0%d%dๅท", rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9) ), string.format("้”ฆ็ปฃๆ–ฐๆ‘ %d%dๆ ‹%d0%d%dๅท", rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9) ), string.format("ๅ…ดๅŽ่‹‘ %d%dๆ ‹%d%d0%dๅฎค", rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9) ), string.format("ๅŽๅ…ด่Šฑๅ›ญ %d%dๆ ‹%d%d0%dๅฎค", rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9) ), string.format("่ตค้พ™ๆ–ฐๆ‘ %d%dๆ ‹%d0%d%dๅท", rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9) ), string.format("็ปไบŒ่ทฏ1ๅท %s%sๅฐๅŒบ%d%dๆ ‹%d0%d", myRand(7,1),myRand(7,1),rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9) ), string.format("็ปไบŒ่ทฏ3ๅท %s%s%sๅฐๅŒบ%d%dๆ ‹%d0%d", myRand(7,1),myRand(7,1),myRand(7,1),rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9) ), string.format("็ฝ—่Šณ่ทฏ190ๅท %s%s%sๅฐๅŒบ%d%dๆ ‹%d0%d", myRand(7,1),myRand(7,1),myRand(7,1),rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9) ), string.format("็ปไบŒ่ทฏ19ๅทๅๅคช่ฝฉ %d%dๆ ‹%d%d0%dๅฎค", rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9) ), string.format("ๅนฟ้™ตๅฎถๅ›ญ %d%dๆ ‹%d%d0%dๅฎค", rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9) ), string.format("็ฝ—ๆน–ๅ…šๆ ก %d%dๆ ‹%d0%d", rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9) ), string.format("่ฅฟๅฒญ่Šฑๅ›ญ %d%dๆ ‹%d0%d", rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9) ), string.format("ๅฎ‰ไธš่Šฑๅ›ญ %d%dๆ ‹%d0%d", rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9),rd(1,9) ), } var.account.address_area = where[rd(1,#where)] inputStr(var.account.address_area) elseif i == 6 then inputStr('518000') end delay(1) d('ๅผน็ช—_่พ“ๅ…ฅๅœฐๅ€็š„ๅฎŒๆˆ',true) end if d('ๆทปๅŠ ๅœฐๅ€็•Œ้ข_ๆญฃ็กฎๆทปๅŠ ',true,1,5)then address = false else click(40,80) end else if d('ๅผน็ช—โ€”โ€”้ชŒ่ฏๅธๆˆท',true,1,3)then elseif d("ๅผน็ช—โ€”โ€”้ชŒ่ฏๅธๆˆท_่พ“ๅฏ†็ ",true,1,2)then boxshow('ๅฏ†็ :'..var.account.pwd); input(var.account.pwd); click(493,647,2); elseif d('ๅผน็ช—_้€‰ๆ‹ฉ็…ง็‰‡',true)then updateNikeLog('่ฎพ็ฝฎๅคดๅƒ'); header = false elseif d('ๅผน็ช—_้€‰ๆ‹ฉๆ—ถๅˆป',true)then elseif d('ๅผน็ช—_้€‰ๆ‹ฉๆ—ถๅˆป็…ง็‰‡')then moveTo(300,200,300,800-rd(200,600),rd(20,30)) --ไธ‹ๆป‘ delay(5) click(rd(31,723),rd(235,1119)) click(696, 1265) elseif d("ๅผน็ช—_็…ง็‰‡้€‰ๅ–",true,1,8)then end end end delay(1) log('readCode->'..os.time()-timeline) end end t['้€‰่ดญๆœชๆฟ€ๆดป'] = { 0xcccccc,"0|-6|0xffffff,0|-10|0xcccccc,0|10|0xcccccc,36|-3|0xcccccc,22|-3|0xffffff,8|-3|0xcccccc",degree,14,1244,740,1327} function look() local timeline = os.time() local outTimes = rd(300,500) local ็‚นๅ‡ปๆฌกๆ•ฐ = 0 updateNikeLog('ๆณจๅ†Œๆดป่ทƒ'); while os.time()-timeline < outTimes do if active(var.bid,3) then if d('้€‰่ดญๆœชๆฟ€ๆดป',true,1,2)then elseif d('NIKE็™ปๅฝ•ๆˆๅŠŸ')then ็‚นๅ‡ปๆฌกๆ•ฐ = ็‚นๅ‡ปๆฌกๆ•ฐ + 1 if rd(1,100)>50 then moveTo(300,rd(800,900),300,rd(400,500),rd(5,20)) else click(rd(40,600),rd(300,900),rd(2,20)) end else click(40,80) end end if ็‚นๅ‡ปๆฌกๆ•ฐ > rd(2,10) then updateNikeLog('ๆต่งˆ็ป“ๆŸ'); return true end delay(1) log('readCode->'..os.time()-timeline) end end function main() if reg()then if readBirthday()then look() end end end <file_sep> require("tsp") require("api") -- openURL("http://m.baihe.com/regChat?channel=hscm&code=11") t={} t['็™พๅˆ็ฝ‘-็”ทๅฅณ']={0x6cabfd, "354|1|0xff7a5e,145|-4|0x5eb4fb,146|-4|0xff9c5d",90,21,1121,732,1264} t['็™พๅˆ็ฝ‘->']={0x969799, "-10|-10|0x969799,-10|11|0x969799,-7|0|0xffffff",90,528,1155,740,1323} t['็™พๅˆ็ฝ‘-ๅผน็ช—->็กฎๅฎš']={0x1989fa, "0|0|0x1989fa,0|-5|0x1989fa",90,594,627,739,889} t['็™พๅˆ็ฝ‘-ๅผน็ช—->้€‰ๆ‹ฉ็”Ÿๆ—ฅ']={0x323233, "0|0|0x323233,250|-2|0x323233,500|-2|0x323233",90,22,964,709,1085} t['็™พๅˆ็ฝ‘-ๅผน็ช—->้€‰ๆ‹ฉๅฑ…ไฝๅœฐ']={0x323233, "0|0|0x323233,227|3|0xffffff,393|0|0x323233",90,76,954,645,1089} t['็™พๅˆ็ฝ‘-ๅผน็ช—->้€‰ๆ‹ฉ่บซ้ซ˜']={0x323233, "0|0|0x323233,-348|5|0xffffff,335|8|0xffffff",90,12,945,737,1110} t['็™พๅˆ็ฝ‘-ๅผน็ช—->้€‰ๆ‹ฉ่บซ้ซ˜->5ไธ‡']={0x323233, "0|0|0x323233,-12|-14|0xffffff,-7|-16|0x323233,-100|-21|0x323233,-91|-23|0xfcfcfc,-90|-24|0x383839",90,279,999,452,1051} t['็™พๅˆ็ฝ‘-ๆœชๅฉš-็ฆปๅผ‚-ๅคฑๅถ']={0xffffff, "0|0|0xffffff,245|3|0xff5f5e,513|-1|0xff5f5e,391|-27|0xffffff,391|-43|0xff5f5e",90,11,1130,708,1315} t['็™พๅˆ็ฝ‘-้šๆœบๆ˜ต็งฐ-ๅ‘้€']={0xff6968, "144|4|0xff5f5e,70|2|0xff5f5e,69|2|0xffffff,-59|-1|0xff5f5e",90,430,1152,732,1292} t['็™พๅˆ็ฝ‘-่ฏท่พ“ๅ…ฅๆ‰‹ๆœบๅท']={0x969799, "0|0|0x969799,446|-19|0xff5f5e,530|20|0xff5f5e,478|1|0xffffff",90,16,1156,737,1285} t['็™พๅˆ็ฝ‘-ๅ‘้€']={0xff5f5e, "0|0|0xff5f5e,3|-20|0xff5f5e,18|-3|0xffffff",90,568,597,742,1316} --ๆณจๅ†Œ่ฟ‡ t['็™พๅˆ็ฝ‘-็‚นๅ‡ปไธ‹่ฝฝ']={0xf2317d, "0|0|0xf2317d,141|118|0x0202ee,325|142|0x0000ee",90,10,865,733,1244} t['็™พๅˆ็ฝ‘-ๆธ…็†่พ“ๅ…ฅ']={0xffffff, "0|0|0xffffff,-1|-9|0xc8c9cc,104|18|0xff5f5e",90,505,623,735,1311} t['็™พๅˆ็ฝ‘-ๆธ…็†่พ“ๅ…ฅ-ๅฎŒๆˆ']={0x007aff, "0|0|0x007aff,1|-6|0x007aff",90,644,541,733,1034} --้ชŒ่ฏ็  t['็™พๅˆ็ฝ‘-่ฏท่พ“ๅ…ฅ้ชŒ่ฏ็ ']={0x969799, "0|0|0x969799,388|-21|0xeeeeee,414|-17|0xffffff,442|-4|0xff5f5e",95,7,1152,732,1323} t['็™พๅˆ็ฝ‘-่ฏท่พ“ๅ…ฅๅฏ†็ ']={0x969799, "0|0|0x969799,391|-3|0xffffff,393|-3|0x969799,384|-3|0x969799,375|-3|0x999a9c,428|-3|0xffffff,429|-3|0xff5f5e",95,2,1138,733,1302} t['็™พๅˆ็ฝ‘-ๆณจๅ†ŒๅฎŒๆˆ']={0xff5f5e, "0|0|0xff5f5e,3|-18|0xffffff,203|-6|0xf0f0f0,202|-6|0xff5f5e,423|-17|0xfe6261",90,59,1133,655,1294} t['็™พๅˆ็ฝ‘-ๅกไฝ']={0x007aff, "0|0|0x007aff,-27|-96|0xff5f5e,-66|-120|0xff5f5e",90,565,605,740,1079} function reg() high = 1 openURL("http://m.baihe.com/regChat?channel=hscm&code=11") local timeLine = os.time() while (os.time()-timeLine < 120 ) do if d("็™พๅˆ็ฝ‘-็”ทๅฅณ",true,rd(1,2) ) then elseif d("็™พๅˆ็ฝ‘->",true ) then elseif d("็™พๅˆ็ฝ‘-ๅกไฝ",true ) then elseif d("็™พๅˆ็ฝ‘-ๅผน็ช—->็กฎๅฎš" ) then if ( d("็™พๅˆ็ฝ‘-ๅผน็ช—->้€‰ๆ‹ฉ็”Ÿๆ—ฅ") )then for i=1,rd(2,3) do moveTo(125,850,125,1100,20) end for i=1,rd(2,3) do moveTo(370,850,370,1100,20) end for i=1,rd(2,3) do moveTo(622,850,622,1100,20) end d("็™พๅˆ็ฝ‘-ๅผน็ช—->็กฎๅฎš",true ) elseif d("็™พๅˆ็ฝ‘-ๅผน็ช—->้€‰ๆ‹ฉๅฑ…ไฝๅœฐ") then for i=1,rd(2,5) do moveTo(125,1100,125,850,20) end for i=1,rd(2,5) do moveTo(558,1100,558,850,20) end d("็™พๅˆ็ฝ‘-ๅผน็ช—->็กฎๅฎš",true ) elseif d("็™พๅˆ็ฝ‘-ๅผน็ช—->้€‰ๆ‹ฉ่บซ้ซ˜") then local movteaa = { 10,2,3 } for i=1,rd(1,movteaa[high] ) do moveTo(558,1100,558,rd(850,1000),20) delay(0.5) end high = high + 1 d("็™พๅˆ็ฝ‘-ๅผน็ช—->็กฎๅฎš",true ) end elseif d("็™พๅˆ็ฝ‘-ๆœชๅฉš-็ฆปๅผ‚-ๅคฑๅถ",true ) then elseif d("็™พๅˆ็ฝ‘-้šๆœบๆ˜ต็งฐ-ๅ‘้€",true ) then d("็™พๅˆ็ฝ‘-ๅ‘้€",true) elseif d("็™พๅˆ็ฝ‘-่ฏท่พ“ๅ…ฅๅฏ†็ ",true) then input( "<PASSWORD>" ) delay(1) d("็™พๅˆ็ฝ‘-ๅ‘้€",true) d("็™พๅˆ็ฝ‘-ๆธ…็†่พ“ๅ…ฅ-ๅฎŒๆˆ",true) elseif d("็™พๅˆ็ฝ‘-่ฏท่พ“ๅ…ฅ้ชŒ่ฏ็ ",true) then if ( getMessage() )then input( appinfo.sms ) delay(1) d("็™พๅˆ็ฝ‘-ๅ‘้€",true) delay(2) else delay(3) end d("็™พๅˆ็ฝ‘-ๆธ…็†่พ“ๅ…ฅ-ๅฎŒๆˆ",true) elseif d("็™พๅˆ็ฝ‘-่ฏท่พ“ๅ…ฅๆ‰‹ๆœบๅท",true,1,2)then if ( getPhone() )then input( appinfo.phone ) delay(1) d("็™พๅˆ็ฝ‘-ๅ‘้€",true) delay(2) end d("็™พๅˆ็ฝ‘-ๆธ…็†่พ“ๅ…ฅ-ๅฎŒๆˆ",true) elseif d("็™พๅˆ็ฝ‘-ๆณจๅ†ŒๅฎŒๆˆ",true) then Idfa() return true end end end while true do if vpn() then reg() end vpnx() delay(2) end <file_sep>-- ไธ–็บชไฝณ็ผ˜-mac -- sjjy.lua -- Create By TouchSpriteStudio on 21:25:52 -- Copyright ยฉ TouchSpriteStudio . All rights reserved. require("TSLib") require("tsp") var = {} var.appbid = "com.jiayuan.jiayuaniphone"; var.phone = '' var.password = '' t={} sys = { clear_bid = (function(bid) closeApp(bid) delay(1) os.execute("rm -rf "..(appDataPath(bid)).."/Documents/*") --Documents os.execute("rm -rf "..(appDataPath(bid)).."/Library/*") --Library os.execute("rm -rf "..(appDataPath(bid)).."/tmp/*") --tmp clearPasteboard() --[[ local path = _G.const.cur_resDir os.execute( table.concat( { string.format("mkdir -p %s/keychain", path), 'killall -SIGSTOP SpringBoard', "cp -f -r /private/var/Keychains/keychain-2.db " .. path .. "/keychain/keychain-2.db", "cp -f -r /private/var/Keychains/keychain-2.db-shm " .. path .. "/keychain/keychain-2.db-shm", "cp -f -r /private/var/Keychains/keychain-2.db-wal " .. path .. "/keychain/keychain-2.db-wal", 'killall -SIGCONT SpringBoard', }, '\n' ) ) ]] clearAllKeyChains() clearIDFAV() --clearCookies() delay(2) return true end) } --getๅ‡ฝๆ•ฐ function get_lx(url) local sz = require("sz") local http = require("szocket.http") local res, code = http.request(url); if code == 200 then return res end end --ๆฅไฟกๅนณๅฐ function _vCode_lx() --ๆฅไฟก local User = 'api-18190-rKpL6bd' local Pass = '<PASSWORD>' local PID = '2099' local token,number = "<KEY>","" return { login=(function() local RetStr for i=1,5,1 do toast("่Žทๅ–token\n"..i.."ๆฌกๅ…ฑ5ๆฌก") mSleep(1500) local lx_url = 'http://api.banma1024.net/api/do.php?action=loginIn&name='..User..'&password='..<PASSWORD> log(lx_url) RetStr = get_lx(lx_url) if RetStr then RetStr = strSplit(RetStr,"|") if RetStr[1] == 1 or RetStr[1] == '1' then token = RetStr[2] log('token='..token,true) break end else log(RetStr) end end return RetStr; end), getPhone=(function() local RetStr="" local url___ = "http://api.banma1024.net/api/do.php?action=getPhone&sid="..PID.."&token="..token log(url___) RetStr = get_lx(url___) if RetStr ~= "" and RetStr ~= nil then log(RetStr) RetStr = strSplit(RetStr,"|") end if RetStr[1] == 1 or RetStr[1]== '1' then number = RetStr[2] log(number) local phone_title = (string.sub(number,1,3)) local blackPhone = {'165','144','141','142','143','144','145','146','147','199'} for k,v in ipairs(blackPhone) do if phone_title == v then local lx_url = 'http://api.banma1024.net/api/do.php?action=addBlacklist&sid='..PID..'&phone='..number..'&token='..token get_lx(lx_url); log("ๆ‹‰้ป‘->"..number) return false end end return number end end), getMessage=(function() local Msg for i=1,25,1 do mSleep(3000) RetStr = get_lx("http://api.banma1024.net/api/do.php?action=getMessage&sid="..PID.."&token="..token.."&phone="..number) log(RetStr); if RetStr then local arr = strSplit(RetStr,"|") if arr[1] == '1' then Msg = arr[2] local i,j = string.find(Msg,"%d+") Msg = string.sub(Msg,i,j) end if type(tonumber(Msg))== "number" then log(Msg); return Msg end end toast(tostring(RetStr).."\n"..i.."ๆฌกๅ…ฑ25ๆฌก") end return false end), addBlack=(function() local lx_url = 'http://api.banma1024.net/api/do.php?action=addBlacklist&sid='..PID..'&phone='..number..'&token='..token log("ๆ‹‰้ป‘"..number..'\n'..lx_url); return get_lx(lx_url); end), } end local dxcode = _vCode_lx() dxcode.login() function rdclicks(x,y,n) if n == 0 then return false end for i=1,n do click(x,y,0.5) end end t['ๆ‰‹ๆœบๅทๆณจๅ†Œ็•Œ้ข']={ 0x4f98d6, "-199|-445|0x363839,-205|-447|0xfefefe,-571|7|0x4a95d5,-569|14|0xffffff,-569|16|0x4a95d5", 90, 48, 55, 702, 570 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๆ‰‹ๆœบๅทๆณจๅ†Œ็•Œ้ข_่Žทๅ–้ชŒ่ฏ็ ']={ 0xffffff, "-105|-14|0xffffff,-220|-18|0xf85e74,144|31|0xf83d84", 90, 79, 578, 671, 703 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅฎŒๆˆ็•Œ้ข']={ 0xb2b3b3, "0|12|0x373a3b,-143|12|0x363a3b,-595|0|0xff2581,-574|2|0xffffff", 90, 43, 1246, 710, 1312 } --ๅคš็‚นๆ‰พ่‰ฒ local degree = 85 t['ๅกซๅ†™่ต„ๆ–™']={0x4a90e2,"27|110|0xfedae6,-356|119|0xd6eeff",degree,17,43,721,603} function reg() local timeline = os.time() local outTimes = 60 * 1 local ๆ‰‹ๆœบๅท = true local ็Ÿญไฟก = false var.password = "<PASSWORD>" local fix_info = false while os.time()-timeline < outTimes do if active(var.appbid,5) then if d('ๅกซๅ†™่ต„ๆ–™') or d('ไธŠไผ ๅคดๅƒ_่ทณ่ฟ‡') then return true elseif d('ๆ‰‹ๆœบๅทๆณจๅ†Œ็•Œ้ข') then if ๆ‰‹ๆœบๅท then var.phone = dxcode.getPhone() if var.phone then click(354,326) input[3](var.phone) ๆ‰‹ๆœบๅท = false ็Ÿญไฟก = true end elseif ็Ÿญไฟก then if d('ๆ‰‹ๆœบๅทๆณจๅ†Œ็•Œ้ข_่Žทๅ–้ชŒ่ฏ็ ',true) then else var.sms = dxcode.getMessage() if var.sms then input[3](var.sms) click(187,437) input[3](sms) ็Ÿญไฟก = false ๆไบค = true up('็‚นๅ‡ปๆณจๅ†Œ') else return false end end end elseif ๆไบค then if d('ๅกซๅ†™่ต„ๆ–™') then up('ๅกซๅ†™่ต„ๆ–™') return true end end end delay(2) end end t['ๅกซ่ต„ๆ–™1็•Œ้ข']={ 0x000000, "-10|-12|0xfefefe,285|4|0x000000,290|16|0xfefefe,296|19|0x000000,303|19|0xfefefe", 90, 29, 134, 362, 208 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅกซ่ต„ๆ–™1็•Œ้ข_่ฏท่พ“ๅ…ฅๆ˜ต็งฐ']={ 0xd9d9d9, "-13|-3|0xd9d9d9,-28|-8|0xd9d9d9,-89|1|0xd9d9d9,-98|-1|0xd9d9d9", 90, 176, 386, 334, 432 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅกซ่ต„ๆ–™1็•Œ้ข_็”ทๅฅณๆฏ”ไพ‹']={ 0xfed9e7, "-380|2|0xdaeeff,-348|46|0xd1edff,24|48|0xfedfe4", 90, 114, 471, 623, 569 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅกซ่ต„ๆ–™1็•Œ้ข_็”Ÿๆ—ฅๆœช้€‰ๆ‹ฉ']={ 0xd9d9d9, "6|8|0xd9d9d9,82|-4|0xf3f3f3,84|6|0xdadada,84|17|0xdbdbdb", 90, 545, 607, 644, 651 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅกซ่ต„ๆ–™1็•Œ้ข_ๅœฐๅŒบๆœช้€‰ๆ‹ฉ']={ 0xd9d9d9, "6|8|0xd9d9d9,82|-4|0xf3f3f3,84|6|0xdadada,84|17|0xdbdbdb", 90, 544, 701, 645, 739 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅกซ่ต„ๆ–™1็•Œ้ข_ไธ‹ไธ€ๆญฅ']={ 0x333333, "0|-2|0x979797,-44|-9|0x333333,29|-3|0x353535", 90, 605, 58, 713, 109 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅกซ่ต„ๆ–™2็•Œ้ข']={ 0x000000, "-2|0|0xa2a2a2,-3|1|0xfefefe,285|19|0x000000,287|20|0x545454,290|20|0xfefefe", 90, 19, 130, 339, 204 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅกซ่ต„ๆ–™2็•Œ้ข_่บซ้ซ˜ๆœช้€‰ๆ‹ฉ']={ 0xefefef, "-2|-21|0xf8f8f8,-85|-18|0xf4f4f4,-88|2|0xf5f5f5,-9|5|0xe4e4e4", 95, 545, 389, 643, 431 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅกซ่ต„ๆ–™2็•Œ้ข_ๅญฆๅކๆœช้€‰ๆ‹ฉ']={ 0xe0e0e0, "0|7|0xd9d9d9,8|21|0xdcdcdc,79|-4|0xd9d9d9,76|7|0xffffff", 95, 540, 484, 652, 520 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅกซ่ต„ๆ–™2็•Œ้ข_ๆœˆ่–ชๆœช้€‰ๆ‹ฉ']={ 0xe0e0e0, "0|7|0xd9d9d9,8|21|0xdcdcdc,79|-4|0xd9d9d9,76|7|0xffffff", 95, 546, 576, 646, 612 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅกซ่ต„ๆ–™2็•Œ้ข_ๅฉšๅฒๆœช้€‰ๆ‹ฉ']={ 0xe0e0e0, "0|7|0xd9d9d9,8|21|0xdcdcdc,79|-4|0xd9d9d9,76|7|0xffffff", 95, 546, 666, 646, 704 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅฎŒๆˆ']={ 0x2099ff, "11|4|0x1493ff,35|16|0x1c97ff,21|10|0x2b9eff,37|-1|0xa2d4ff", 90, 649, 837, 718, 881 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅฎŒๆˆ_็”Ÿๆ—ฅ']={ 0x696969, "-6|12|0xa1a1a1,51|27|0x333333,51|0|0x4e4e4e,51|-1|0xffffff", 90, 342, 839, 405, 875 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅฎŒๆˆ_ๆ‰€ๅœจๅœฐๅŒบ']={ 0xbebebe, "-2|26|0xaeaeae,123|0|0x737373,124|25|0x949494,98|-1|0x848484", 90, 305, 838, 441, 877 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅฎŒๆˆ_่บซ้ซ˜']={ 0xe8e8e8, "1|0|0xb3b3b3,-11|20|0xc0c0c0,49|3|0xa2a2a2,47|29|0xb6b6b6", 90, 337, 836, 413, 878 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅฎŒๆˆ_ๅญฆๅކ']={ 0x868686, "-4|6|0xbdbdbd,4|28|0xb5b5b5,56|2|0x646464,51|28|0xaaaaaa", 90, 340, 839, 411, 874 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅฎŒๆˆ_ๆœˆ่–ช']={ 0xc7c7c7, "1|0|0x4e4e4e,-3|26|0xb1b1b1,55|1|0x6a6a6a,52|27|0x939393", 90, 344, 838, 407, 879 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅฎŒๆˆ_ๅฉšๅฒ']={ 0x969696, "-2|0|0x606060,-4|28|0x787878,53|4|0x7b7b7b,56|26|0xe9e9e9", 90, 334, 837, 413, 879 } --ๅคš็‚นๆ‰พ่‰ฒ t['ไธŠไผ ๅคดๅƒ_่ทณ่ฟ‡']={ 0x363839, "-424|88|0x000000,-417|89|0xfefefe,-361|356|0xd8d8d8,-317|385|0xfefefe", 90, 30, 57, 725, 652 } --ๅคš็‚นๆ‰พ่‰ฒ local degree = 85 t['ๅกซ่ต„ๆ–™2/ๅฎŒๆˆๆณจๅ†Œ']={0xf84680,"242|-38|0xf83a85,-256|20|0xf96c6e",degree,47,800,682,1000} local degree = 85 t['ไธป็•Œ้ขโ€”โ€”ๅฎŒๆˆ']={0xff1a83,"-13|19|0xff2b7e,-24|7|0xff5071",degree,16,1226,132,1320} function ๅกซ่ต„ๆ–™() local timeline = os.time() local outTimes = 60 * 2 local ๆฏ”ไพ‹็”ท = math.random(1,100) while os.time()-timeline < outTimes do if active(var.appbid,5) then if d('ไธป็•Œ้ขโ€”โ€”ๅฎŒๆˆ')then up('ๅฎŒๆ•ดๆณจๅ†Œ') return true elseif d('ๅกซ่ต„ๆ–™1็•Œ้ข') then if d('ๅกซ่ต„ๆ–™1็•Œ้ข_ไธ‹ไธ€ๆญฅ',true) then elseif d('ๅกซ่ต„ๆ–™1็•Œ้ข_่ฏท่พ“ๅ…ฅๆ˜ต็งฐ') then click(586,409) elseif d('ๅกซ่ต„ๆ–™1็•Œ้ข_็”ทๅฅณๆฏ”ไพ‹') then if ๆฏ”ไพ‹็”ท < 50 then click(167,520) else click(516,510) end elseif d('ๅกซ่ต„ๆ–™1็•Œ้ข_็”Ÿๆ—ฅๆœช้€‰ๆ‹ฉ',true) then elseif d('ๅกซ่ต„ๆ–™1็•Œ้ข_ๅœฐๅŒบๆœช้€‰ๆ‹ฉ',true) then end elseif d('ๅกซ่ต„ๆ–™2็•Œ้ข') then if d('ๅกซ่ต„ๆ–™2็•Œ้ข_่บซ้ซ˜ๆœช้€‰ๆ‹ฉ',true) then elseif d('ๅกซ่ต„ๆ–™2็•Œ้ข_่บซ้ซ˜ๆœช้€‰ๆ‹ฉ' ,true) then elseif d('ๅกซ่ต„ๆ–™2็•Œ้ข_ๅญฆๅކๆœช้€‰ๆ‹ฉ' ,true) then elseif d('ๅกซ่ต„ๆ–™2็•Œ้ข_ๆœˆ่–ชๆœช้€‰ๆ‹ฉ' ,true) then elseif d('ๅกซ่ต„ๆ–™2็•Œ้ข_ๅฉšๅฒๆœช้€‰ๆ‹ฉ' ,true) then elseif d('ๅกซ่ต„ๆ–™2/ๅฎŒๆˆๆณจๅ†Œ' ,true,1,3) then delay(8) end elseif d('ๅฎŒๆˆ') then if d('ๅฎŒๆˆ_็”Ÿๆ—ฅ') then local ้šๆœบ1 = math.random(1,5) local ้šๆœบ2 = math.random(1,3) local ้šๆœบ3 = math.random(1,3) for i = 1 , ้šๆœบ1 do click(234,1055) end for i = 1 , ้šๆœบ2 do click(381,1058) end for i = 1 , ้šๆœบ3 do click(518,1052) end d('ๅฎŒๆˆ',true) elseif d('ๅฎŒๆˆ_ๆ‰€ๅœจๅœฐๅŒบ') then local ้šๆœบ4 = math.random(1,10) local ้šๆœบ5 = math.random(1,10) for i = 1 , ้šๆœบ4 do click(201,1178) end for i = 1 , ้šๆœบ5 do click(547,1186) end d('ๅฎŒๆˆ',true) elseif d('ๅฎŒๆˆ_่บซ้ซ˜') then if ๆฏ”ไพ‹็”ท < 50 then for i = 1 ,math.random(4,8) do moveTo(387,1114,386,915) end else for i = 1 ,math.random(3,4) do moveTo(387,1114,386,915) end end d('ๅฎŒๆˆ',true) elseif d('ๅฎŒๆˆ_ๅญฆๅކ') then for i = 1 , math.random(1,5) do click(379,1185) end d('ๅฎŒๆˆ',true) elseif d('ๅฎŒๆˆ_ๆœˆ่–ช') then for i = 1 , math.random(1,4) do click(379,1185) end d('ๅฎŒๆˆ',true) elseif d('ๅฎŒๆˆ_ๅฉšๅฒ') then click(379,1185) d('ๅฎŒๆˆ',true) else d('ๅฎŒๆˆ',true) end else d('ไธŠไผ ๅคดๅƒ_่ทณ่ฟ‡',true) end end delay(1) end end function up(other) local url = 'http://hb.wenfree.cn/api/Public/idfa/' local postdate = {} postdate.service = 'Idfa.Idfa' postdate.name = 'ไธ–็บชไฝณ็ผ˜' postdate.idfa = var.phone postdate.password = <PASSWORD> postdate.other = other log(post(url,postdate)) -- body end require("AWZ") function all() if sys.clear_bid(var.appbid)then if reg()then ๅกซ่ต„ๆ–™() end end end while (true) do local ret,errMessage = pcall(all) if ret then else log(errMessage) dialog(errMessage, 10) mSleep(2000) end end <file_sep>ts = require("ts") function downloadurl(url,path) --ไธ‹่ฝฝๆ–‡ไปถๅˆฐๆŒ‡ๅฎš่ทฏๅพ„ local download = function(url,path) return ts.tsDownload(path,url) end for i = 1 ,5 do local code, info =download(url, path) if code == 200 then if info == "success" then return true else Showlog("[downloadurl] err info ="..info) end else Showlog("[downloadurl] err c ="..code) end end return false end file = { --ๆ–‡ไปถๅค„็†ๆจกๅ— exists = function(file_name) local f = io.open(file_name, "r") return f ~= nil and f:close() end, reads = function(file_name) local f = io.open(file_name,"r") if f then local c = f:read("*a") f:close() return c else return nil end end, writes = function(file_name,str,mode) mode = mode or "w" local f = io.open(file_name, mode) if f == nil then return "" end local ret = f:write(str) f:close() --[[ mode = mode or "w+" writeFileString(file_name,str,mode) --]] end, } function Showlog(s) toast(s) end function runOs(script) script ="Clutch -i" local p = io.popen(script) for v in p:lines() do nLog(v) end nLog("end") end _appBid = 'com.nike.onenikecommerce' --appBID ่ฟ™้‡Œๅ†™ๅ…ฅไฝ ่ฆ็ ธๅฃณ็š„BID _appDataPath = appDataPath(_appBid).."/Documents/" --ๆฒ™็›’่ทฏๅพ„ if _appDataPath then local pathData = '/usr/bin/Clutch' os.execute("rm -rf "..pathData) if file.exists(pathData) == false then local url = "http://code-55331.oss-cn-shenzhen.aliyuncs.com/tool/Clutch" if downloadurl(url,pathData) == false then dialog("Clutch ไธ‹่ฝฝๅคฑ่ดฅ",2)lua_exit() end end mSleep(1000) os.execute("chmod a+x /usr/bin/Clutch")- local script ="Clutch -i" local p = io.popen(script) local item = "0" for v in p:lines() do if string.find(v,_appBid) ~=nil then item = string.match(v,"(.-):.-") if item == nil then dialog("Clutch ๆœชๆฃ€ๆต‹ๅˆฐๅฎ‰่ฃ…1") lua_exit() end end end if item == "0" then dialog("Clutch ๆœชๆฃ€ๆต‹ๅˆฐๅฎ‰่ฃ…2") lua_exit() end script ="Clutch -d "..item p = io.popen(script) for v in p:lines() do Showlog(v) if string.find(v,"Finished dumping") ~=nil then dialog("็ ธๅฃณๆˆๅŠŸ math-oๆ–‡ไปถไฝ็ฝฎ:/private/var/mobile/Documents/Dumped/ ๆญค็›ฎๅฝ•ไธ‹ๆŸฅๆ‰พ") end end --DYLD_INSERT_LIBRARIES=dumpdecrypted.dylib /var/containers/Bundle/Application/B8416315-EF7E-4464-8F7F-4C1B92CBF1AF/WeChat.app/WeChat --DONE: /private/var/mobile/Documents/Dumped/cn.dxwt.Community10000-iOS10.0-(Clutch-2.0.4).ipa else dialog("ๆœชๅฎ‰่ฃ…ๅบ”็”จ",2) os.exit() end --[[ --]] <file_sep>-- nike-wen-tn-mac -- main.lua -- Create By TouchSpriteStudio on 21:34:14 -- Copyright ยฉ TouchSpriteStudio . All rights reserved. <file_sep>-- ็งฏๅˆ†ๅข™ๅฏนๆŽฅ -- jfqhj.lua -- Create By TouchSpriteStudio on 21:19:35 -- Copyright ยฉ TouchSpriteStudio . All rights reserved. require("TSLib") require('tsp') jfq ={} jfq.url = '' jfq.model = '' jfq.adid = '' jfq.appid = '' jfq.keyword = '' jfq.idfa = '' jfq.os_version = '' jfq.device = 'iPhone10,3' jfq.udid = '' jfq.callback = 'true' jfq.appname = '' jfq.source = '' jfq.channel = '' jfq.bid = '' var = {} function start() local sz = require('sz') -- local info = getOnlineName() -- log(info) jfq.idfa = '7654715C-5F65-4AA0-A4E0-7888B83528D9' --'748A5260-6A2A-466F-99E6-7CC70CDD2244' --strSplit(info[8],":")[2] jfq.os_version = '12.1.2' --strSplit(info[3],":")[2] jfq.devicename = getDeviceName() jfq.udid = '049F46E85CF3F6B0E8B18DC6943857527F834FA0' --strSplit(info[4],":")[2] jfq.imei = sz.system.serialnumber() jfq.medel = 'iPhone10,3' -- log(jfq); end --input('A4941D558FD54855AB0BB7441F8EB9CE5FDAC218') function get_task() local sz = require('sz') local url = 'http://wenfree.cn/api/Public/tjj/?service=Tjj.gettask' local postArr = {} postArr.phonename = getDeviceName() postArr.imei = sz.system.serialnumber() local taskData = post(url,postArr) if taskData ~= nil then log(taskData) if taskData.data == "ๆ–ฐๅขžๆ‰‹ๆœบ" or taskData.data == "ๆš‚ๆ— ไปปๅŠก" then log(taskData.data,true) delay(30) return false else return taskData.data end end end function idfa_Distinct() -- local url_ = 'http://phalapipro.wenfree.cn/api/app.php'; -- var['s']="App.Idfa.Distinct"; -- log('idfa_Distinct') ---- log(var) -- local res = post(url_,var); -- log(res); local url = 'http://api.xqkapp.cn/'; local url_model = 'openapi/upstream/idfaQueryApi' local service = url..url_model local postArr = {} postArr['appkey'] = var['adid'] postArr['chid'] = '219' postArr['idfa'] = jfq['idfa'] postArr['model'] = jfq.medel postArr['udid'] = jfq.udid postArr['system'] = jfq['os_version'] postArr['keyword'] = urlEncoder('็ซๅธไบคๆ˜“') postArr['keyword'] = '็ซๅธไบคๆ˜“' postArr['user_ip'] = ip() -- log(postArr) local postdata = '' for k,v in pairs(postArr) do postdata = postdata .. '&'..k..'='..v end local service = service .."?"..postdata log(service); local res = get(service) log(res) return res end function idfa_Click() local url_ = 'http://phalapipro.wenfree.cn/api/app.php'; var['s']="App.Idfa.Click"; log('idfa_Click') -- log(var) return post(url_,var) end function idfa_Report() end function openApp(bid,opentime) local timeLine = os.time() while os.time()- timeLine < opentime do if active(bid,5)then local w,h = getScreenSize() moveTo(0.8*w,0.8*h,0.2*w,0.2*h,rd(10,30)) end delay(1) end end function idfa(way,t,k_) local t = t var.appid = t.appid var.adid = t.adid var.done = t.done var.state = t.state var.keyword = t.keyword var.appbid = t.appbid var.time = t.time var.groups = t.groups var.id = t.id var.note = t.note var.todo = t.todo var.work = t.work var.addtime = t.addtime var.task_id = t.task_id var.date = t.date var.downtime = t.downtime or 60 var.opentime = t.opentime or rd(150,300); var.way = t.way var.idfa = jfq.idfa var.os_version = jfq.os_version var.device = jfq.device var.udid = jfq.udid var.imei = jfq.imei -- var.callback = jfq.callback if way == 'Distinct' then log("Distinct") delay(0.5) if idfa_Distinct() then idfa_setp[k_] = {} idfa_setp[k_]['open'] = true idfa_setp[k_]['timeLine'] = os.time() end lua_exit() elseif way == 'Click' then log("Click") if idfa_setp[k_]['open'] then log(idfa_Click()); while os.time()- idfa_setp[k_]['timeLine'] < var.downtime do log('็ญ‰ไธ‹่ฝฝๆ—ถ้—ด'); end openApp(var.appbid,var.opentime) end elseif way == 'Report' then log('Report') end end --log( readPasteboard() ) start() local task_data = get_task() if task_data then setp = { 'Distinct','Click','Report' } idfa_setp = {} for k,v in ipairs(setp) do for k_,v_ in ipairs(task_data) do --็ฌฌๅ‡ ไธชไปปๅŠก็š„่ฎฐๅฝ• log(idfa_setp); idfa(v,v_,k_) end end end <file_sep>-- nike-arrow -- arrow.lua -- Create By TouchSpriteStudio on 20:35:53 -- Copyright ยฉ TouchSpriteStudio . All rights reserved. require("tsp") local arrowbid = "com.liguangming.Shadowrocket" function ip() local url = 'http://nikeapi.honghongdesign.cn/?s=App.IndexIp.Ip' local ip___ = get(url) if ip___ then return ip___['data'] end end function whiteip() local url = 'http://www.jinglingdaili.com/Users-whiteIpAddNew.html?appid=2420&appkey=ef2f43ef02109467a23c34f5b1e0982c&type=dt&index=&whiteip='..ip() return get(url) end function getNetIPproxy() local url = 'http://t.ipjldl.com/index.php/api/entry?method=proxyServer.generate_api_url&packid=0&fa=0&fetch_key=&groupid=0&qty=1&time=102&pro=&city=&port=1&format=json&ss=5&css=&dt=1&specialTxt=3&specialJson=&usertype=2' local ip___ = get(url) if ip___ then log(ip___['data'][1]) return ip___['data'][1] end end if t == nil then t={} end t['vpn-้ฆ–้กต-ๆœชๆฟ€ๆดป']={0x000000, "0|0|0x000000,1|-2|0xf5f5f5,1|-4|0x222222,0|-19|0x808080",90,65,1243,124,1323} t['vpn-้ฆ–้กต-ๆฟ€ๆดป']={0x4587c2, "0|0|0x4587c2,1|-2|0xf5f5f5,1|-4|0x5d96c9,0|-19|0x4587c2",90,65,1243,124,1323} t['vpn-้ฆ–้กต-็ผ–่พ‘']={0x4587c2, "0|0|0x4587c2,-13|-1|0xffffff,-687|0|0xff9400",90,2,524,739,996} t['vpn-้ฆ–้กต-ๅผ€ๅ…ณๅผ€']={0xffffff, "0|0|0xffffff,67|-1|0xe5e5e5,-32|3|0xd9d9d9,16|-29|0xe3e3e3",90,601,192,729,296} t['vpn-้ฆ–้กต-ๅผ€ๅ…ณๅ…ณ']={0x4486c0, "0|0|0x4486c0,69|-1|0x407fb6,18|-29|0x4486c0",90,604,194,730,287} t['vpn-้ฆ–้กต-่ฟžๆŽฅๆˆๅŠŸ']={0x000000, "0|0|0x000000,-2|-22|0xffffff,-3|38|0xffffff",90,259,186,453,293} t['vpn-้ฆ–้กต-็ผ–่พ‘่Š‚็‚น']={0xed402e, "0|0|0xed402e,1|-7|0xed402e,-14|-18|0xffffff",90,245,782,516,1175} t['vpn-้ฆ–้กต-็ผ–่พ‘่Š‚็‚น-HTTP']={0x8e8e93, "0|0|0x8e8e93,8|-8|0x8e8e93,20|-8|0xffffff,23|8|0x8e8e93,117|0|0xc7c7cc,108|-10|0xc7c7cc",90,561,191,729,293} hpptwz = {301, 781} t['vpn-้ฆ–้กต-็ผ–่พ‘่Š‚็‚น-ๅฎŒๆˆ']={0xffffff, "0|0|0xffffff,5|-3|0x4386c5,34|-7|0x4386c5,39|-12|0xffffff",90,622,53,727,113} t['vpn-ๅ…ถๅฎƒ']={0xffffff, "0|0|0xffffff,22|-15|0x4386c5,399|-5|0xffffff,664|-10|0xffffff,656|3|0x4386c5",90,23,41,729,116} function Shadowrockets() local setp_ = '' local setp__ = "" local setp___ = 0 local vpnInputKey = false local timeline = os.time() local outTimes = 60 while (os.time()-timeline < outTimes) do if active(arrowbid,5) then if d('vpn-้ฆ–้กต-ๆฟ€ๆดป') then setp_ = 'vpn-้ฆ–้กต-ๆฟ€ๆดป' if d('vpn-้ฆ–้กต-็ผ–่พ‘') then setp_ = 'vpn-้ฆ–้กต-็ฌฌไธ€้กต' if vpnInputKey then if d('vpn-้ฆ–้กต-ๅผ€ๅ…ณๅผ€',true)then elseif d('vpn-้ฆ–้กต-ๅผ€ๅ…ณๅ…ณ') then if d('vpn-้ฆ–้กต-่ฟžๆŽฅๆˆๅŠŸ') then return true end end else if d('vpn-้ฆ–้กต-ๅผ€ๅ…ณๅ…ณ',true)then else d('vpn-้ฆ–้กต-็ผ–่พ‘',true) end end elseif d('vpn-้ฆ–้กต-็ผ–่พ‘่Š‚็‚น')then setp_ = 'vpn-้ฆ–้กต-็ผ–่พ‘่Š‚็‚น' if d("vpn-้ฆ–้กต-็ผ–่พ‘่Š‚็‚น-HTTP") == nil then click(649, 239) click(301, 781) end log(whiteip()) local vpnList = getNetIPproxy() local vpnlistWz = {{200, 398, 0xffffff},{200, 484, 0xffffff}} click( vpnlistWz[1][1],vpnlistWz[1][2],1) keyDown("Clear") keyUp("Clear") delay(1) inputText(vpnList['IP']) delay(1) click( vpnlistWz[2][1],vpnlistWz[2][2],1) keyDown("Clear") keyUp("Clear") delay(1) inputText(vpnList['Port']) delay(1) if d('vpn-้ฆ–้กต-็ผ–่พ‘่Š‚็‚น-ๅฎŒๆˆ',true)then vpnInputKey = true end end elseif d('vpn-้ฆ–้กต-ๆœชๆฟ€ๆดป',true)then setp_ = 'vpn-้ฆ–้กต-ๆœชๆฟ€ๆดป' elseif d('vpn-ๅ…ถๅฎƒ',true)then setp_ = 'ๅ…ถๅฎƒUI' else setp_ = 'ๅ…ถๅฎƒ' end if setp_ == setp__ then setp___ = setp___ + 1 else setp__ = setp_ end if setp___ >= 15 then closeApp(arrowbid,1) setp___ = 0 end log({setp_,setp___,'vpn->'..os.time()-timeline}) if setp_ == 'ๅ…ถๅฎƒ' then delay(0.5) else delay(rd(1,3)) end end end end nLog('arrow ๅŠ ๆˆชๅฎŒๆˆ') <file_sep>require("TSLib") awzbid = 'AWZ' require("tsp") function locks() local flag = deviceIsLock(); if flag == 0 then -- log("ๆœช้”ๅฎš"); else unlockDevice(); --่งฃ้”ๅฑๅน• end end function activeawz(app,t) local t = t or 0.5 locks() local bid = frontAppBid(); if bid == app then mSleep(t*1000) return true else nLog(app.."๏ผŒๅ‡†ๅค‡ๅฏๅŠจ") runApp(app) end end function awz_next() function nextrecord() local sz = require("sz"); local http = require("szocket.http"); local res, code = http.request("http://127.0.0.1:1688/cmd?fun=nextrecord"); if code == 200 then local resJson = sz.json.decode(res); local result = resJson.result; nLog("the result is: " .. result); if tonumber(result) == 1 then return true end end end out_time = os.time() while os.time()-out_time <= 10 do if activeawz(awzbid,2)then elseif nextrecord()then return true end mSleep(1000* 2) end end function renameCurrentRecord(name) local sz = require("sz"); local http = require("szocket.http"); local res, code = http.request("http://127.0.0.1:1688/cmd?fun=renamecurrentrecord&name="..name); if code == 200 then local resJson = sz.json.decode(res); local result = resJson.result; nLog("the result is: " .. result); return true end end function reName(newName) timeLine = os.time() outTime = 60 * 0.5 while (os.time()-timeLine < outTime) do if activeawz(awzbid,3)then if renameCurrentRecord(newName)then return true end end mSleep(1000) end nLog('้‡ๅ‘ฝไปค่ถ…ๆ—ถ') end function newRecord() local sz = require("sz"); local http = require("szocket.http"); local res, code = http.request("http://127.0.0.1:1688/cmd?fun=newrecord"); if code == 200 then local resJson = sz.json.decode(res); local result = resJson.result; nLog("the result is: " .. result); if result == 3 then --//IPๅœฐๅ€้‡ๅค log('ip ๅœฐๅ€้‡ๅค') return true elseif result == 1 then return true elseif result == 2 then log('ๆญฃๅœจไธ€้”ฎๆ–ฐๆœบing') end end end function awzNew() local timeLine = os.time() local outTime = 60 * 0.5 while (os.time()-timeLine < outTime) do if activeawz(awzbid,3)then if newRecord() then return true end end mSleep(1000) end nLog('ๆ–ฐๆœบ่ถ…ๆ—ถ') end if not(t) then t = {} end -- t['awz-ไธ€้”ฎๆ–ฐๆœบๆจช']={0xffffff, "-9|-110|0xffffff,0|-187|0x6f7179,-1|73|0x6f7179,-28|-65|0x6f7179", 90, 577, 445, 654, 724} t['awz-ไธ€้”ฎๆ–ฐๆœบ็ซ–']={0xffffff, "0|0|0xffffff,-42|-18|0x6f7179,87|24|0x6f7179,150|1|0x6f7179",90,16,562,312,660} function clickNew() closeApp(awzbid,0) delay(1) local timeLine = os.time() local outTime = 60 * 0.5 while (os.time()-timeLine < outTime) do if activeawz(awzbid,3)then if d("awz-ไธ€้”ฎๆ–ฐๆœบ็ซ–",true) then return true end end mSleep(1000) end nLog('ๆ–ฐๆœบ่ถ…ๆ—ถ') end function setCurrentRecordLocation(location) local sz = require("sz"); local http = require("szocket.http"); local res, code = http.request("http://127.0.0.1:1688/cmd?fun=setcurrentrecordlocation&location="..location); if code == 200 then local resJson = sz.json.decode(res); local result = resJson.result; toast("the result is: " .. result, 2); if tonumber(result) == 1 then return true end end end function NewPlace(location) timeLine = os.time() outTime = 60 * 0.5 while (os.time()-timeLine < outTime) do if activeawz(awzbid,3)then elseif setCurrentRecordLocation(location) then return true end mSleep(1000) end nLog('่ฎพ็ฝฎ่ถ…ๆ—ถ') end --("116.7361382365_39.8887921413_ๅŒ—ไบฌ่€่ƒกๅŒ") function getAll() local sz = require("sz"); local http = require("szocket.http"); local res, code = http.request("http://127.0.0.1:1688/cmd?fun=getallrecordnames"); if code == 200 then local resJson = sz.json.decode(res); local result = resJson.result; toast("the result is: " .. result, 2); if tonumber(result) == 1 then return #readFile('/var/mobile/iggrecords.txt') end end end function getAllmun() timeLine = os.time() outTime = 60 * 0.5 while (os.time()-timeLine < outTime) do if activeawz(awzbid,3)then else return getAll() end mSleep(1000) end nLog('่ฎพ็ฝฎ่ถ…ๆ—ถ') end ----่Žทๅ–ๅฝ“ๅ‰ๅ function getOnlineName() function getName() local sz = require("sz"); local http = require("szocket.http"); local res, code = http.request("http://127.0.0.1:1688/cmd?fun=getcurrentrecordparam"); if code == 200 then local resJson = sz.json.decode(res); local result = resJson.result; nLog("the result is: " .. result); if tonumber(result) == 1 then jg = readFile('/var/mobile/iggparams.txt') nLog(jg[1]) awz_online_name = strSplit(jg[1],'/') awz_online_name[2] = awz_online_name[2] or 'AOC' nLog(awz_online_name[2]) return awz_online_name[2] end end end timeLine = os.time() outTime = 60 * 0.5 while (os.time()-timeLine < outTime) do if activeawz(awzbid,3)then else return getName() end mSleep(1000) end nLog('่ฎพ็ฝฎ่ถ…ๆ—ถ') end function getTrueName_awz() function getTrueName() local sz = require("sz"); local http = require("szocket.http"); local res, code = http.request("http://127.0.0.1:1688/cmd?fun=getcurrentrecordparam"); if code == 200 then local resJson = sz.json.decode(res); local result = resJson.result; nLog("the result is: " .. result); if tonumber(result) == 1 then jg = readFile('/var/mobile/iggparams.txt') return jg[1],jg[4] --name,idfa end end end timeLine = os.time() outTime = 60 * 0.5 while (os.time()-timeLine < outTime) do if activeawz(awzbid,3)then else return getTrueName() end mSleep(1000) end end --new ๆ–ฐๅฐ่ฃ… function new_fun(todos) local timeLine = os.time() local outTime = 10 while (os.time()-timeLine < outTime) do if activeawz(awzbid,3)then local sz = require("sz"); local http = require("szocket.http"); local res, code = http.request("http://127.0.0.1:1688/cmd?fun="..todos); if code == 200 then local resJson = sz.json.decode(res); local result = resJson.result; return result end end end end require('tsp') function setAWZ(id) if new_fun( 'getallrecordnames') == 1 then jg = readFile('/var/mobile/iggrecords.txt') log( jg ) for k,v in ipairs( jg ) do local a,b = string.find(v,id) if ( a ) then new_fun( "activerecord&record="..v ) delay(1) reName(id..'-'..__game.note) delay(1) return true end end clickNew() delay(5) reName(id..'-'..__game.note) local i = 0 while i < 20 do if active(_app.bid,5)then if d("ๅผน็ช—-ๆމๆกฃ") then return true elseif d("e-ๅŒๆ„ๅนถ็ปง็ปญ",true,1,2) or d("e-ๅŒๆ„ๅนถ็ปง็ปญ6s",true) then end end i=i+1 delay(1) end end end nLog('new ๅŠ ๆˆชๅฎŒๆˆ')<file_sep>-- ไธ‡ๅ›ฝ่ง‰้†’ -- main.lua -- Create By TouchSpriteStudio on 13:31:43 -- Copyright ยฉ TouchSpriteStudio . All rights reserved. --unlockDevice() -- require("TSLib") --require("tsp") update__ = true update__ = false update_account = true function file_exists(file_name) local f = io.open(file_name, "r") return f ~= nil and f:close() end --res, code = http.request("http://ip.chinaz.com/getip.aspx"); --็”จhttp.getๅฎž็Žฐไธ‹่ฝฝๆ–‡ไปถๅŠŸ่ƒฝ function downFile() local sz = require("sz") local http = require("szocket.http") local url = "https://img.wenfree.cn/rok/new.lua" local res, code = http.request(url); if code == 200 then local file = io.open("/User/Media/TouchSprite/lua/new.lua", "w+") if file then file:write(res) file:close() return status; else return -1; end else return status; end end if not(file_exists("/User/Media/TouchSprite/lua/new.lua")) then downFile() end __UI = {} _UI = {} require('tsp') require('ZZBase64') require("yzm") require("function") require('token') require('api') init(1) _app = {} _app.bid = 'com.lilithgames.rok.ios.offical' -- com.lilithgame.roc.ios.tw -- com.lilithgames.rok.ios.jp _app.yzmid = 0; t={} degree = 80 --ๅŠ ๆˆชๅ…จๅ†›ๅ‡บๅ‡ป require("UIs") require('change_qu') require('ad') --ไธดๆ—ถๅขžๅŠ ็š„ temporary t['ไธดๆ—ถ-ๅ…่ดนๅฅณ็Ž‹']={0xffffee, "0|0|0xffffee,27|-33|0xe20000,12|-24|0xfb57a1",90,912,82,1252,164} t['ไธดๆ—ถ-ๅ…่ดนๅฅณ็Ž‹-้ข†ๅ–']={0x1274ba, "0|0|0x1274ba,-39|-18|0x00cffe",90,752,416,997,535} function game() ๆ‰“้‡Ž้™ไฝŽkey = false; ๆ‰“้‡Žๅขž้•ฟkey = true; ้‡‡็Ÿฟ่ฐƒไฝŽไธ€ๆฌก = true ไปปๅŠก่ฎฐๆ•ฐ = 0 ๆ‰“้‡Žๆฌกๆ•ฐ่ฎฐๆ•ฐ = 0; ๆ”ถ้›†ๆฌกๆ•ฐ = 0 ่ฏป้‚ฎไปถๆฌกๆ•ฐ = 0 ๆ—ฅๅކๅฅ–ๅŠฑ = 0 ้™ค่‰ๆฌกๆ•ฐ = 0 ๅปบ้€ ๆฌกๆ•ฐ = 0 ้‡‡็Ÿฟๆฌกๆ•ฐ = 0 ๅ‡็บงๆฌกๆ•ฐ = 0 ๆ–ฅๅ€™ๆฌกๆ•ฐ = 0 ้ข†้‚ฎไปถๅฅ–ๅŠฑ = 0 ไฟฎ็†ๅŸŽๅข™ = 0 ็ ”็ฉถๆฌกๆ•ฐ = 0 ้€ ๅ…ตๆฌกๆ•ฐ = 0 ่”็›Ÿๆฌกๆ•ฐ = 0 ้€็‰ฉ่ต„ๆฌกๆ•ฐ = 0 ่ฟœๅพๆฌกๆ•ฐ = 0 ่‹ฑ้›„ๆฌกๆ•ฐ = 0 arrowKey = 0 ๆ—ฅ่ฝๅณก่ฐทๆฌกๆ•ฐ = 0 ๅ…จๅ†›ๅ‡บๅ‡ปๆ’คๅ›žKey = true tipsKey = 0 ๅ‡็บง่ฝฆไบงๆฌกๆ•ฐ = 0 ้™ๆญข็”ป้ข = 0 ๆตๆฃฎๅคๅทๆฌกๆ•ฐ = 0 VIPๆฌกๆ•ฐ = 0 ๅŒป้™ขๆฌกๆ•ฐ = 0 ๆ‰“็ ๆฌกๆ•ฐ = 0 --ๅนฟๅ‘Š้ƒจๅˆ† ๅˆ ้™คๆ—งๅนฟๅ‘Škey = true ๅ‘ๅนฟๅ‘Šๆฌกๆ•ฐ = 1 --ๆ˜ฏๅฆๆˆชๅ›พ _app.upimg = true _app.allimg = true __ๆ–ฐๅˆๅง‹ๅŒ– = true local timeline = os.time() + rd(1,5)*60 while os.time()-timeline < 60 * 35 do if active(_app.bid,12)then if d('ๆธธๆˆไธป็•Œ้ข') or d('ๆธธๆˆไธป็•Œ้ข-ๅคœ')then tipsKey = 0 d('ๅผน็ช—_็ป‘ๅฎšๅธๅท',true,1) --ๆฏๆฌก้ƒฝ็‚นๅธฎๅŠฉ d('ๆ”ถ้›†-ๅธฎๅŠฉ',true,2) -- if __ๆ–ฐๅˆๅง‹ๅŒ– then -- ๅˆๅง‹ๅŒ–() -- __ๆ–ฐๅˆๅง‹ๅŒ– = false -- end -- _init() _Collect() -- ๆตๆฃฎๅคๅท() if _UI.็ฅž็ง˜ๅ•†ไบบ and d("็ฅž็ง˜ๅ•†ไบบๆฅไบ†",true,1,2) then show_state("็ฅž็ง˜ๅ•†ไบบ") _็ฅž็ง˜ๅ•†ๅบ—() end if _UI.VIPๅฅ–ๅŠฑ and _SignIn() then elseif _UI.่ฏป้‚ฎไปถ and _mail() then elseif _UI.ๆ—ฅๅކๅฅ–ๅŠฑ and _book() then elseif _UI.้“ๅŒ ้“บ then show_state("้“ๅŒ ้“บ") todo = { _init(), _้“ๅŒ ้“บ() } elseif _UI.ๅŒป้™ข then todo = { _init(), _Hospital() } elseif _UI.่‹ฑ้›„ๅ‡็บงๅŠ ็‚น then show_state("่‹ฑ้›„ๅ‡็บงๅŠ ็‚น") todo = { _ๅŠ ๅคฉ่ต‹() } elseif _UI.่ฟœๅพ then show_state("่ฟœๅพ") todo = { _่ฟœๅพ() } elseif _UI.ๅปบ้€  then show_state("ๆ–ฐๅปบ็ญ‘") todo = { _NewBuild() } elseif _UI.่‹ฑ้›„ then show_state("้…’้ฆ†ๅฌๅ”ค") todo = { _init(),_Hero() } elseif _UI.ๅ‡็บง then show_state("ๅ‡็บงไธปๅŸŽ") todo = { _init(),_ๅ‡็บง() } elseif _UI.ๆœ็ดขๆ‘ๅบ„ then show_state("ๆœ็ดขๆ‘ๅบ„") todo = { read_mail() } elseif _UI.ๅฅ–ๅŠฑ then show_state("ๅฅ–ๅŠฑ") todo = { _Award() } elseif _UI.ไปปๅŠก then show_state("ไปปๅŠก") todo = { _task() } elseif _UI.้€ ๅ…ต.key then show_state("้€ ๅ…ต") todo = { _init(),_soldier() } elseif _UI.ๆ–ฅๅ€™ then show_state("ๆ–ฅๅ€™") todo = { _init(),_Acouts() } elseif _UI.้€็‰ฉ่ต„ then show_state("้€็‰ฉ่ต„") todo = { _init(),_songwuzi()} elseif _UI.ไธป็บฟๅŠŸ่ƒฝ.ๅ…จๅ†›ๅ‡บๅ‡ป then show_state("ๅ…จๅ†›ๅ‡บๅ‡ป") todo = { _all_arm() } elseif _UI.ๆ‰“้‡Ž then show_state("ๆ‰“้‡Ž") todo = { _monster() } elseif _UI.่”็›ŸๆๅŠฉ then show_state("่”็›ŸๆๅŠฉ") _lm() elseif _UI.้‡‡้›†.key then show_state("้‡‡้›†") _Collection() elseif __UI.ไธป็บฟๅŠŸ่ƒฝ.ๅนฟๅ‘Šๅผ€ๅ…ณ then show_state("ๅ‘ๅนฟๅ‘Š") if __UI.ไธป็บฟๅŠŸ่ƒฝ.ๅนฟๅ‘Šๆ–นๆณ• == "1" then --็Ž‹ๅ›ฝๅ–Š่ฏ if ad() then __UI.ไธป็บฟๅŠŸ่ƒฝ.ๅนฟๅ‘Šๅผ€ๅ…ณ = false end elseif __UI.ไธป็บฟๅŠŸ่ƒฝ.ๅนฟๅ‘Šๆ–นๆณ• == "2" then if ads_() and ๅ‘ๅนฟๅ‘Šๆฌกๆ•ฐ >= 3 then __UI.ไธป็บฟๅŠŸ่ƒฝ.ๅนฟๅ‘Šๅผ€ๅ…ณ = false end elseif __UI.ไธป็บฟๅŠŸ่ƒฝ.ๅนฟๅ‘Šๆ–นๆณ• == "3" then choice = 2 show_state("ๅนฟๅ‘Š-่”็›Ÿ"..top_key) if ๅ‘้‚ฎไปถ_่”็›Ÿ() and ๅ‘ๅนฟๅ‘Šๆฌกๆ•ฐ > 4 then __UI.ไธป็บฟๅŠŸ่ƒฝ.ๅนฟๅ‘Šๅผ€ๅ…ณ = false end elseif __UI.ไธป็บฟๅŠŸ่ƒฝ.ๅนฟๅ‘Šๆ–นๆณ• == "4" then choice = 1 show_state("ๅนฟๅ‘Š-ๆˆ˜ๅŠ›"..top_key) if ๅ‘้‚ฎไปถ_่”็›Ÿ() and ๅ‘ๅนฟๅ‘Šๆฌกๆ•ฐ > 4 then __UI.ไธป็บฟๅŠŸ่ƒฝ.ๅนฟๅ‘Šๅผ€ๅ…ณ = false end end else return 'next' end else --่ฟ™ๆ˜ฏ่ฎฐๅฝ•ๆ˜ฏๅฆๅ‡บๅผน็ช—็š„ๅ‚ๆ•ฐๅ€ผ if _Evevnt() then local tips_res = _Tips() if tips_res == 'ๅฐๅท' or tips_res == 'ไผ‘ๆฏ' then return end end tipsKey = tipsKey + 1 --้•ฟๆ—ถ้—ดๅœจไธๆญฃๅธธ็š„็Šถๆ€ไธ‹,ๆŸฅไธ€ไธ‹ๆ˜ฏๅฆๆ˜ฏๅœจๅผ•ๅฏผไธ‹ if ( tipsKey > 10 ) then _Arrow() end end end end show_state("--") return 'next' end function main() while true do ๆ˜ฏๅฆ้€‰่ฟ‡ๅŒบ = false ้€‰ๅŒบๅผ€ๅ…ณ = false require('new') ๆ‹‰ๅ›พๆป‘ๅŠจๆฌกๆ•ฐ = 0 --ๆ‹‰ๅ–ๅธๅท if AccountInfoBack() then if __game.is_vpn == 0 or vpn() then --่ฏปๅ‡บtoken __game.token = llsGameToken()[1] if not(file_exists("/User/Media/TouchSprite/lua/" ..__game.token..".txt")) then local sz = require("sz") local json = sz.json writeFile( {json.encode({['top_key'] = 1,['top_key_max'] = 20})} ,'w',"/User/Media/TouchSprite/lua/" ..__game.token..".txt") end now_key = (readFileString("/User/Media/TouchSprite/lua/" ..__game.token..".txt")) now_key = string.gsub(now_key, "1:","") now_key = json.decode(now_key) top_key = now_key['top_key'] top_key_max = now_key['top_key_max'] log( now_key ) --ๅˆๅง‹ๅŒ–UI่ฎพ็ฝฎ __UI = __game.wei_ui --ๅฎŒๅ…จๆ ผๅผๅŒ– _UI.ๅ›ฝๅฎถ = 5 --ๅฐๅŠŸ่ƒฝ _UI.้™ค่‰ = __UI['ๅฐๅŠŸ่ƒฝ']['้™ค่‰'] _UI.VIPๅฅ–ๅŠฑ = __UI['ๅฐๅŠŸ่ƒฝ']['VIPๅฅ–ๅŠฑ'] _UI.ๆ”ถ้›†่ต„ๆบ = __UI['ๅฐๅŠŸ่ƒฝ']['ๆ”ถ้›†่ต„ๆบ'] _UI.่ฏป้‚ฎไปถ = __UI['ๅฐๅŠŸ่ƒฝ']['่ฏป้‚ฎไปถ'] _UI.ๆ—ฅๅކๅฅ–ๅŠฑ = __UI['ๅฐๅŠŸ่ƒฝ']['ๆ—ฅๅކๅฅ–ๅŠฑ'] --ๆ”ฏ็บฟๅŠŸ่ƒฝ _UI.่ฟœๅพ = __UI['ๆ”ฏ็บฟๅŠŸ่ƒฝ']['่ฟœๅพ'] _UI.่‹ฑ้›„ๅ‡็บงๅŠ ็‚น = __UI['ๆ”ฏ็บฟๅŠŸ่ƒฝ']['่‹ฑ้›„ๅ‡็บงๅŠ ็‚น'] _UI.ๆ—ฅ่ฝๅณก่ฐท = __UI['ๆ”ฏ็บฟๅŠŸ่ƒฝ']['ๆ—ฅ่ฝๅณก่ฐท'] _UI.็ฅž็ง˜ๅ•†ไบบ = __UI['ๆ”ฏ็บฟๅŠŸ่ƒฝ']['็ฅž็ง˜ๅ•†ไบบ'] _UI.้“ๅŒ ้“บ = __UI['ๆ”ฏ็บฟๅŠŸ่ƒฝ']['้“ๅŒ ้“บ'] _UI.ๅชไนฐ็ฌฌไธ€ๆŽ’ = __UI.ๆ”ฏ็บฟๅŠŸ่ƒฝ.ๅชไนฐ็ฌฌไธ€ๆŽ’ --ไธป็บฟๅŠŸ่ƒฝ _UI.ไฟฎๅŸŽๅข™ = __UI.ไธป็บฟๅŠŸ่ƒฝ.ไฟฎๅŸŽๅข™ _UI.ๅปบ้€  = __UI.ไธป็บฟๅŠŸ่ƒฝ.ๅปบ้€  _UI.่‹ฑ้›„ = __UI.ไธป็บฟๅŠŸ่ƒฝ.้…’้ฆ†ๅฌๅ”ค _UI.ๅ‡็บง = __UI.ไธป็บฟๅŠŸ่ƒฝ.ๅ‡็บง _UI.ๅƒๅŠ ้€Ÿ = __UI.ไธป็บฟๅŠŸ่ƒฝ.ๅƒๅŠ ้€Ÿ _UI.ๆœ็ดขๆ‘ๅบ„ = __UI.ไธป็บฟๅŠŸ่ƒฝ.ๆœ็ดขๆ‘ๅบ„ _UI.ๅฅ–ๅŠฑ = __UI.ไธป็บฟๅŠŸ่ƒฝ.ๅฅ–ๅŠฑ _UI.ไปปๅŠก = __UI.ไธป็บฟๅŠŸ่ƒฝ.ไปปๅŠก _UI.ๅ‡็บง่ฝฆ้—ด = __UI.ไธป็บฟๅŠŸ่ƒฝ.ๅ‡็บง่ฝฆ้—ด _UI.ๅŽ‹ๅ ก = __UI.ไธป็บฟๅŠŸ่ƒฝ.ๅŽ‹ๅ ก _UI.่”็›Ÿๅ็งฐ = __UI.ไธป็บฟๅŠŸ่ƒฝ.่”็›Ÿๅ็งฐ if __UI.ไธป็บฟๅŠŸ่ƒฝ.ๅนฟๅ‘Šๅผ€ๅ…ณ then if __UI.ๅˆ†ไบซๅนฟๅ‘Š then __UI.ๅˆ†ไบซๅนฟๅ‘Š = split(__UI.ๅˆ†ไบซๅนฟๅ‘Š,"|") end if __UI.้‚ฎไปถๅนฟๅ‘Š then __UI.้‚ฎไปถๅนฟๅ‘Š = split(__UI.้‚ฎไปถๅนฟๅ‘Š,"|") end end --้€ ๅ…ตๅŠŸ่ƒฝ _UI.้€ ๅ…ต = {} _UI.้€ ๅ…ต.key = __UI.ไธป็บฟๅŠŸ่ƒฝ.้€ ๅ…ตkey _UI.้€ ๅ…ต.ๆญฅๅ…ต = __UI.ไธป็บฟๅŠŸ่ƒฝ.ๆญฅๅ…ต _UI.้€ ๅ…ต.้ช‘ๅ…ต = __UI.ไธป็บฟๅŠŸ่ƒฝ.้ช‘ๅ…ต _UI.้€ ๅ…ต.ๅผ“ๅ…ต = __UI.ไธป็บฟๅŠŸ่ƒฝ.ๅผ“ๅ…ต _UI.้€ ๅ…ต.่ฝฆๅ…ต = __UI.ไธป็บฟๅŠŸ่ƒฝ.่ฝฆๅ…ต --ๅ…ถๅฎƒๅŠŸ่ƒฝ _UI.ๆ–ฅๅ€™ = __UI.ไธป็บฟๅŠŸ่ƒฝ.ๆ–ฅๅ€™ _UI.ๆ–ฅๅ€™ๆฌกๆ•ฐ = tonumber(__UI.ไธป็บฟๅŠŸ่ƒฝ.ๆ–ฅๅ€™ๆฌกๆ•ฐ) or 5 _UI.ๆ‰“้‡Ž = __UI.ไธป็บฟๅŠŸ่ƒฝ.ๆ‰“้‡Ž _UI.ๆ‰“้‡Žๆฌกๆ•ฐ = tonumber(__UI.ๆ‰“้‡Žๆฌกๆ•ฐ) _UI.ๆ‰“้‡Žๅƒไฝ“ๅŠ› = __UI.ไธป็บฟๅŠŸ่ƒฝ.ๅƒไฝ“ๅŠ› _UI.monsterlevel = __UI.monsterlevel or 1 _UI.monsteDW = __UI.monsteDW or '้ป˜่ฎค' _UI.ไธป็บฟๅŠŸ่ƒฝ = {} _UI.ไธป็บฟๅŠŸ่ƒฝ.ๅ…จๅ†›ๅ‡บๅ‡ป = __UI.ไธป็บฟๅŠŸ่ƒฝ.ๅ…จๅ†›ๅ‡บๅ‡ป if _UI.ไธป็บฟๅŠŸ่ƒฝ.ๅ…จๅ†›ๅ‡บๅ‡ป then _UI.ๆ‰“้‡Ž = false end --้‡‡้›†่ฎพ็ฝฎ _UI.้‡‡้›† = {} _UI.้‡‡้›†.key = __UI.ไธป็บฟๅŠŸ่ƒฝ.้‡‡้›†key _UI.้‡‡้›†.็ง็ฑป = __UI.้‡‡้›†็ง็ฑป _UI.้‡‡้›†.่”็›Ÿ็Ÿฟๅœบ = __UI.ไธป็บฟๅŠŸ่ƒฝ.่”็›Ÿ็Ÿฟๅœบ if __UI.ไธป็บฟๅŠŸ่ƒฝ.้‡‡็Ÿฟ็ญ‰็บง then _UI.้‡‡้›†.้‡‡็Ÿฟ็ญ‰็บง = tonumber(__UI.ไธป็บฟๅŠŸ่ƒฝ.้‡‡็Ÿฟ็ญ‰็บง) else _UI.้‡‡้›†.้‡‡็Ÿฟ็ญ‰็บง = 1 end --่”็›Ÿ็ง‘ๆŠ€ๆๅŠฉ _UI.่”็›ŸๆๅŠฉ = __UI.ไธป็บฟๅŠŸ่ƒฝ.่”็›ŸๆๅŠฉ _UI.ๅปบ็ญ‘ๅˆ—้˜Ÿ = false --็‰ฉ่ต„่ฟ้€ _UI.็‰ฉ่ต„่ฟ้€ = __UI.ไธป็บฟๅŠŸ่ƒฝ.็‰ฉ่ต„่ฟ้€ if __UI.Rไฝ็ฝฎ == 'ๅๆ ‡' then _UI.ๅๆ ‡ = split(__UI.ๅๆ ‡,',') end _UI.ๅŒป้™ข = true log(__UI); game() --ๆธ…็†ๅธๅท clearOneAccount(); delay(1) end else log('ๅธๅทไผ‘ๆฏไธญ') delay(10); pressHomeKey(0) pressHomeKey(1) end end end function all() local sz=require('sz') __game = {} -- __game.imei = getDeviceID() __game.imei = getDeviceName() __game.phone_name = getDeviceName() main() end while (true) do local ret,errMessage = pcall(all) if ret then else vpnx(); log(errMessage) dialog(errMessage, 10) mSleep(2000) end end <file_sep> --ๆทฑๅบฆๆ‰“ๅฐไธ€ไธช่กจ,ๅฏไปฅๅ•็‹ฌ่ฐƒ็”จ function print_r(t) local print_r_cache={} local function sub_print_r(t,indent) if (print_r_cache[tostring(t)]) then nLog(indent.."*"..tostring(t)) else print_r_cache[tostring(t)]=true if (type(t)=="table") then for pos,val in pairs(t) do if type(pos) == "string" then pos = "'"..pos.."'" end if (type(val)=="table") then nLog(indent.."["..pos.."] = { --"..tostring(t)) sub_print_r(val,indent..string.rep(" ",string.len(pos)+8)) nLog(indent..string.rep(" ",string.len(pos)+6).."},") elseif (type(val)=="string") then nLog(indent.."["..pos.."] = ".."'"..val.."',") else nLog(indent.."["..pos.."] = "..tostring(val)..",") end end else nLog(indent..tostring(t)) end end end if (type(t)=="table") then nLog("{ --"..tostring(t)) sub_print_r(t," ") nLog("}") elseif (type(t)=="string") then nLog(t) end end --ๆ‰“ๅฐๅ‡ฝๆ•ฐ,ๆ—ฅๅฟ—ๅ‡ฝๆ•ฐ function log(txt,show,times) if txt == nil or txt == '' then txt = 'Null'end local times = 1; if type(txt) == 'table' then print_r(txt) if show then log('table',true) end else if show == 'all' then toast(show,times) nLog(txt) elseif show then toast(txt,times) else nLog(txt) end end end --ๆ–‡ไปถๆŒ‰่กŒๅ†™ๅ…ฅ------------ๆ–‡ไปถ่ทฏๅพ„๏ผŒๅ†…ๅฎน๏ผŒๆ–นๅผ๏ผˆaไธบ่ฟฝๅŠ ๏ผŒwๆธ…้™ค้‡ๅ†™๏ผŒ๏ผ‰ function writeFile(file_name,string,way) local string = string or "0.0.0.0" local way = way or 'a' local f = assert(io.open(file_name, way)) f:write(string.."\n") f:close() end --ๅฐ†ๆŒ‡ๅฎšๆ–‡ไปถไธญ็š„ๅ†…ๅฎนๆŒ‰่กŒ่ฏปๅ–,่ฟ”ๅ›žไธ€ไธช่กจ function readFile(path) local file = io.open(path,"r"); if file then local _list = {}; for l in file:lines() do table.insert(_list,l) end file:close(); return _list end end --ๅญ˜ๅ…ฅไธ€ไธช่กจ function saves(path,t) for i,v in ipairs(t)do if i == 1 then writeFile(path,v,"w") else writeFile(path,v) end end end --่ฏปๅ‡บ่กจ function readAccount(accunt_path) return readFile(accunt_path) end account = {} account[1] = "11231313|123123123" account[2] = "11233313|123123123" account[3] = "3333313|123123123" account[4] = "12222313|123123123" account[5] = "222313|123123123" local accunt_path = "/User/Media/TouchSprite/lua/1.txt" saves(accunt_path,account); --ๅ…ˆ้ป˜่ฎคๅ†™ๅ…ฅไธ€ไบ›ๆ•ฐๆฎ while (true) do a = readAccount(accunt_path)--่ฏปๅ‡บๆ•ฐๆฎ log(a) if #a == 1 then return end mSleep(2000) table.remove(a,1)--ๆธ…้™ค็ฌฌไธ€้กน mSleep(1000) saves(accunt_path,a)--้‡ๆ–ฐๅ†™ๅ…ฅ end log("END") <file_sep>-- ไธ‡ๅ›ฝ่ง‰้†’ -- main.lua -- Create By TouchSpriteStudio on 13:31:43 -- Copyright ยฉ TouchSpriteStudio . All rights reserved. --unlockDevice() -- require("TSLib") --require("tsp") update__ = true update__ = false update_account = true function file_exists(file_name) local f = io.open(file_name, "r") return f ~= nil and f:close() end --res, code = http.request("http://ip.chinaz.com/getip.aspx"); --็”จhttp.getๅฎž็Žฐไธ‹่ฝฝๆ–‡ไปถๅŠŸ่ƒฝ function downFile() local sz = require("sz") local http = require("szocket.http") local url = "https://img.wenfree.cn/rok/new.lua" local res, code = http.request(url); if code == 200 then local file = io.open("/User/Media/TouchSprite/lua/new.lua", "w+") if file then file:write(res) file:close() return status; else return -1; end else return status; end end if not(file_exists("/User/Media/TouchSprite/lua/new.lua")) then downFile() end __UI = {} _UI = {} require('tsp') require('ZZBase64') require("yzm") require("function") require('token') require('api') init(1) _app = {} _app.bid = 'com.lilithgames.rok.ios.offical' -- com.lilithgame.roc.ios.tw _app.yzmid = 0; t={} degree = 80 --ๅŠ ๆˆชๅ…จๅ†›ๅ‡บๅ‡ป require("UIs") require('change_qu') require('ad') --ไธดๆ—ถๅขžๅŠ ็š„ temporary t['ไธดๆ—ถ-ๅ…่ดนๅฅณ็Ž‹']={0xffffee, "0|0|0xffffee,27|-33|0xe20000,12|-24|0xfb57a1",90,912,82,1252,164} t['ไธดๆ—ถ-ๅ…่ดนๅฅณ็Ž‹-้ข†ๅ–']={0x1274ba, "0|0|0x1274ba,-39|-18|0x00cffe",90,752,416,997,535} function game() ๆ‰“้‡Ž้™ไฝŽkey = false; ๆ‰“้‡Žๅขž้•ฟkey = true; ้‡‡็Ÿฟ่ฐƒไฝŽไธ€ๆฌก = true ไปปๅŠก่ฎฐๆ•ฐ = 0 ๆ‰“้‡Žๆฌกๆ•ฐ่ฎฐๆ•ฐ = 0; ๆ”ถ้›†ๆฌกๆ•ฐ = 0 ่ฏป้‚ฎไปถๆฌกๆ•ฐ = 0 ๆ—ฅๅކๅฅ–ๅŠฑ = 0 ้™ค่‰ๆฌกๆ•ฐ = 0 ๅปบ้€ ๆฌกๆ•ฐ = 0 ้‡‡็Ÿฟๆฌกๆ•ฐ = 0 ๅ‡็บงๆฌกๆ•ฐ = 0 ๆ–ฅๅ€™ๆฌกๆ•ฐ = 0 ้ข†้‚ฎไปถๅฅ–ๅŠฑ = 0 ไฟฎ็†ๅŸŽๅข™ = 0 ็ ”็ฉถๆฌกๆ•ฐ = 0 ้€ ๅ…ตๆฌกๆ•ฐ = 0 ่”็›Ÿๆฌกๆ•ฐ = 0 ้€็‰ฉ่ต„ๆฌกๆ•ฐ = 0 ่ฟœๅพๆฌกๆ•ฐ = 0 ่‹ฑ้›„ๆฌกๆ•ฐ = 0 arrowKey = 0 ๆ—ฅ่ฝๅณก่ฐทๆฌกๆ•ฐ = 0 ๅ…จๅ†›ๅ‡บๅ‡ปๆ’คๅ›žKey = true tipsKey = 0 ๅ‡็บง่ฝฆไบงๆฌกๆ•ฐ = 0 ้™ๆญข็”ป้ข = 0 ๆตๆฃฎๅคๅทๆฌกๆ•ฐ = 0 VIPๆฌกๆ•ฐ = 0 ๅŒป้™ขๆฌกๆ•ฐ = 0 --ๆ˜ฏๅฆๆˆชๅ›พ _app.upimg = true _app.allimg = true local timeline = os.time() + rd(1,5)*60 while os.time()-timeline < 60 * 35 do if active(_app.bid,12)then if d('ๆธธๆˆไธป็•Œ้ข') or d('ๆธธๆˆไธป็•Œ้ข-ๅคœ')then tipsKey = 0 d('ๅผน็ช—_็ป‘ๅฎšๅธๅท',true,1) --ๆฏๆฌก้ƒฝ็‚นๅธฎๅŠฉ d('ๆ”ถ้›†-ๅธฎๅŠฉ',true,2) if _init() then if __UI.ไธป็บฟๅŠŸ่ƒฝ.ๅนฟๅ‘Šๅผ€ๅ…ณ and rd(1,100) > 40 then ad() end return 'next' end else --่ฟ™ๆ˜ฏ่ฎฐๅฝ•ๆ˜ฏๅฆๅ‡บๅผน็ช—็š„ๅ‚ๆ•ฐๅ€ผ if _Evevnt() then local tips_res = _Tips() if tips_res == 'ๅฐๅท' or tips_res == 'ไผ‘ๆฏ' then return end end tipsKey = tipsKey + 1 --้•ฟๆ—ถ้—ดๅœจไธๆญฃๅธธ็š„็Šถๆ€ไธ‹,ๆŸฅไธ€ไธ‹ๆ˜ฏๅฆๆ˜ฏๅœจๅผ•ๅฏผไธ‹ if ( tipsKey > 10 ) then _Arrow() end end end end show_state("--") return 'next' end function game() ๅˆ ้™คๆ—งๅนฟๅ‘Škey = true tipsKey = 0 ๅ‘ๅนฟๅ‘Šๆฌกๆ•ฐ = 1 local timeline = os.time() + rd(1,5)*60 while os.time()-timeline < 60 * 30 do if active(_app.bid,12)then if d('ๆธธๆˆไธป็•Œ้ข') or d('ๆธธๆˆไธป็•Œ้ข-ๅคœ')then tipsKey = 0 if _init() then if _UI.ๅนฟๅ‘Š then if ads_() and ๅ‘ๅนฟๅ‘Šๆฌกๆ•ฐ >= 3 then return 'next' end else show_state("ๆœช่ฎพๅนฟๅ‘Š่ฏ") delay(3) return 'next' end end else --่ฟ™ๆ˜ฏ่ฎฐๅฝ•ๆ˜ฏๅฆๅ‡บๅผน็ช—็š„ๅ‚ๆ•ฐๅ€ผ if _Evevnt() then local tips_res = _Tips() if tips_res == 'ๅฐๅท' or tips_res == 'ไผ‘ๆฏ' then return end end tipsKey = tipsKey + 1 --้•ฟๆ—ถ้—ดๅœจไธๆญฃๅธธ็š„็Šถๆ€ไธ‹,ๆŸฅไธ€ไธ‹ๆ˜ฏๅฆๆ˜ฏๅœจๅผ•ๅฏผไธ‹ if ( tipsKey > 5 ) then _Arrow() end end end end show_state("--") return 'next' end ๅ‘้‚ฎไปถ_่”็›Ÿ() lua_exit() function all() local sz=require('sz') __game = {} -- __game.imei = getDeviceID() __game.imei = getDeviceName() __game.phone_name = getDeviceName() main() end while (true) do local ret,errMessage = pcall(all) if ret then else vpnx(); log(errMessage) dialog(errMessage, 10) mSleep(2000) end end <file_sep>๏ปฟ --[[ ๆ ผๅผ่ฏดๆ˜Ž๏ผš { ไธ‹ๆ‹‰้€‰้กนๆ ‡้ข˜, { customKeyMap = ่‡ชๅฎšไน‰ๅฟซๆท้”ฎๆ˜ ๅฐ„่กจ, singlePosFormatRule = ๅ•็‚นๅ–่‰ฒ็”Ÿๆˆๆ ผๅผๅ‡ฝๆ•ฐ, multiPosFormatRule = ๅคš็‚นๅ–่‰ฒ็”Ÿๆˆๆ ผๅผๅ‡ฝๆ•ฐ, currentPosInfo = ้ผ ๆ ‡ๆ‰€ๆŒ‡ๅฝ“ๅ‰็‚น็š„ๆ ผๅผ็”Ÿๆˆๅ‡ฝๆ•ฐ๏ผˆ้ขๆฟไธŠ้‚ฃไธช้š็€้ผ ๆ ‡็งปๅŠจๆ—ถๅˆปๅœจๅ˜ๅŒ–็š„ๅ†…ๅฎน๏ผ‰, makeScriptRule = { -- ่‡ชๅฎšไน‰่„šๆœฌ่ง„ๅˆ™ ็”Ÿๆˆ็ฌฌ 1 ไธชๆ–‡ๆœฌๆก†ๅ†…ๅฎน็š„ๅ‡ฝๆ•ฐ, ็”Ÿๆˆ็ฌฌ 2 ไธชๆ–‡ๆœฌๆก†ๅ†…ๅฎน็š„ๅ‡ฝๆ•ฐ, ็”Ÿๆˆ็ฌฌ 3 ไธชๆ–‡ๆœฌๆก†ๅ†…ๅฎน็š„ๅ‡ฝๆ•ฐ, testRule = { -- [+ 1.7.7] ็ฌฌ 1 ไธชๆ–‡ๆœฌๆก†็š„ๅ†…ๅฎน็š„ๆต‹่ฏ•ๅ‡ฝๆ•ฐ, ็ฌฌ 2 ไธชๆ–‡ๆœฌๆก†็š„ๅ†…ๅฎน็š„ๆต‹่ฏ•ๅ‡ฝๆ•ฐ, ็ฌฌ 3 ไธชๆ–‡ๆœฌๆก†็š„ๅ†…ๅฎน็š„ๆต‹่ฏ•ๅ‡ฝๆ•ฐ, }, }, }, } customKeyMap ่ฏดๆ˜Ž๏ผš ๅฏๅ‚่€ƒ scripts/config/colorpicker/keymap.lua ็š„่ฟ”ๅ›žๅ€ผ singlePosFormatRuleใ€multiPosFormatRule ๅ‚ๆ•ฐ่ฏดๆ˜Ž๏ผš p๏ผš ๅฝ“ๅ‰็‚นไฟกๆฏ๏ผŒๅŒ…ๆ‹ฌ xใ€yใ€cใ€rใ€gใ€bใ€num a๏ผš ๅๆ ‡็ผ“ๅ†ฒไฝ A ็š„ไฟกๆฏ๏ผŒๅŒ…ๆ‹ฌ xใ€y s๏ผš ๅๆ ‡็ผ“ๅ†ฒไฝ S ็š„ไฟกๆฏ๏ผŒๅŒ…ๆ‹ฌ xใ€y x๏ผš ๅๆ ‡็ผ“ๅ†ฒไฝ X ็š„ไฟกๆฏ๏ผŒๅŒ…ๆ‹ฌ xใ€y c๏ผš ๅๆ ‡็ผ“ๅ†ฒไฝ C ็š„ไฟกๆฏ๏ผŒๅŒ…ๆ‹ฌ xใ€y set: ๆ‰ฉๅฑ•่ฎพ็ฝฎๅˆ—่กจ makeScriptRule ๅ‚ๆ•ฐ่ฏดๆ˜Ž๏ผš poslist: { p, p, p, ... a = {x, y}, s = {x, y}, x = {x, y}, c = {x, y}, } set: ๆ‰ฉๅฑ•่ฎพ็ฝฎๅˆ—่กจ ๅฆ‚้œ€่‡ชๅฎšไน‰ๆ ผๅผ๏ผŒๅฏไปฅๅคๅˆถๅฝ“ๅ‰ๆ–‡ไปถ็š„่€ƒๅค‡ไปฝ้‡ๅ‘ฝๅ็„ถๅŽๅšไฟฎๆ”น ไฟฎๆ”นๅฎŒๆˆๅŽ๏ผŒๅฏไปฅๅœจๆ–‡ไปถ scripts/config/colorpicker/cf_enabled.lua ๅบ”็”จๆทปๅŠ ่‡ชๅฎšไน‰ๆ ผๅผ --]] return {"็ฒพ็ฎ€ๅŽป็ฉบๆ ผ็‰ˆHex - By ๆกƒๆกƒ", -- ๆ„Ÿ่ฐขๆกƒๅญๅ…ฑไบซๆ ผๅผ { settingsRule = { title = "่‡ชๅฎšไน‰ๆ ผๅผ [็ฒพ็ฎ€ๅŽป็ฉบๆ ผ็‰ˆHex - By ๆกƒๆกƒ] ็š„ๅ‚ๆ•ฐ่ฎพ็ฝฎ", caption = {"ๅ‚ๆ•ฐๅ", "ๅ‚ๆ•ฐๅ€ผ"}, args = { {"็›ธไผผๅบฆ(1-100 ็ฉบไธบ100%)", "85"}, {"ๅฝ“ๅ‰isColorๅ‡ฝๆ•ฐๅฎšไน‰๏ผˆ็›ดๆŽฅๅคๅˆถไฝฟ็”จ๏ผ‰", isColorCodeDefine} }, }, singlePosFormatRule = (function(p, a, s, x, c, set) return string.format("%d,%d,0x%06x", p.x, p.y, p.c) end), multiPosFormatRule = (function(p, a, s, x, c, set) return string.format("%d,%d,0x%06x\n", p.x, p.y, p.c) end), currentPosInfo = (function(p, a, s, x, c, set) return string.format("X:%d Y:%d \r\nR:%d G:%d B:%d \r\nC:0x%06x", p.x, p.y, p.r, p.g, p.b, p.c) end), makeScriptRule = { (function(poslist, set) local ret = "--ๅ–่‰ฒๅˆ—่กจ\r\n{\r\n" for _,currentPos in ipairs(poslist) do ret = ret..string.format("\t{%d,%d,0x%06x},\r\n", currentPos.x, currentPos.y, currentPos.c) end return ret.."}" end), (function(poslist, set) local ret = "if " for i,currentPos in ipairs(poslist) do ret = ret..string.format("isColor(%d,%d,0x%06x"..(function(Sets) if Sets ~= "" then return "," .. Sets else return "" end end)(set["็›ธไผผๅบฆ(1-100 ็ฉบไธบ100%)"])..")", currentPos.x, currentPos.y, currentPos.c) if i~=#poslist then ret = ret.." and " end end return ret.." then" end), make_findMultiColorInRegionFuzzy, testRule = { -- [+ 1.7.7] (function(s) return multiColorCodeDefine..[[ if multiColor(]]..s..[[, 80) then nLog("็›ธไผผๅบฆ80ไปฅไธŠ") else nLog("็›ธไผผๅบฆ80ไปฅไธ‹") end ]] end), (function(s) return isColorCodeDefine..s..[[ nLog("ๅŒน้…") else nLog("ไธๅŒน้…") end ]] end), (function(s) return s..[[ nLog("ๅคš็‚นๆ‰พ่‰ฒ็ป“ๆžœ๏ผš"..tostring(x).." ,"..tostring(y)) ]] end), }, }, }, }<file_sep>require("TSLib") require("tsp") require("AWZ") require("smdate") function upidfa(name,other) local url = 'http://idfa888.com/Public/idfa/?service=idfa.idfa' local idfalist ={} idfalist.phonename = phonename or getDeviceName() idfalist.phoneimei = phoneimei or getDeviceType(); idfalist.phoneos = phoneos or getOSType(); idfalist.name = name idfalist.idfa = getidfa() or idfa idfalist.ip = ip() or "192.168.1.1" idfalist.account = account idfalist.password = <PASSWORD> idfalist.phone = phone idfalist.other = other return post(url,idfalist) end function getdate() local sz = require("sz") local json = sz.json local url = "http://news.wenfree.cn/phalapi/public/?" local arr = {} arr['service'] = 'App.Site.Idcard' local data = post(url,arr) if data then -- log(data) return data end end --inf = getdate() --log(inf) init(0) var = '' appbid = 'com.ycgame.t11pub' url = 'https://lnk0.com/Ql8QJ5?td_subid=9420001' t = {} t['openU_ๆ‰“ๅผ€']={ 0x007aff, "29|-3|0x007aff,27|-6|0xffffff,-91|0|0x007aff", 90, 332, 597, 552, 658 } --ๅคš็‚นๆ‰พ่‰ฒ t['reg_ๅฟซ้€Ÿๆธธๆˆ']={ 0x4f4f4f, "-6|-62|0xdf5c55,-4|-85|0xd41e13,0|-120|0xd41e13", 90, 53, 226, 160, 473 } --ๅคš็‚นๆ‰พ่‰ฒ t['reg_่ดฆๅทๆณจๅ†Œ']={ 0x4a4a4a, "-3|-118|0x2dba41,-14|-85|0x2dba41,11|-84|0x2dba41", 90, 78, 483, 112, 654 } --ๅคš็‚นๆ‰พ่‰ฒ t['reg_่ดฆๅทๆณจๅ†Œ็•Œ้ข']={ 0x4a90e2, "-16|-156|0x4a90e2,3|-359|0x9b9b9b,-3|-560|0x9b9b9b", 90, 4, 207, 133, 925 } --ๅคš็‚นๆ‰พ่‰ฒ t['reg_้”ฎ็›˜ๅฎŒๆˆ']={ 0x007aff, "-5|-33|0x007aff", 90, 327, 1023, 489, 1107 } --ๅคš็‚นๆ‰พ่‰ฒ t['reg_่ฟ›ๅ…ฅๆธธๆˆ']={ 0xffffff, "-13|-73|0xf7c559,3|106|0xf4ac44,14|-55|0xf6ba5c", 90, 81, 428, 187, 705 } --ๅคš็‚นๆ‰พ่‰ฒ t['reg_้€‰ๆ‹ฉ่ง’่‰ฒ']={{111,93,0x46424c},{197,86,0x4e4753},{295,94,0x4c4551},{394,88,0x48444d},{484,93,0x4c4651},{586,82,0x46424c},} --ๅคš็‚นๅ–่‰ฒ t['reg_้€‰ๆ‹ฉ่ง’่‰ฒ_่ฟ›ๅ…ฅๆธธๆˆ6G']={ 0xf6b64e, "-8|-78|0xf7c155,-7|67|0xf7bf54", 90, 63, 906, 134, 1109 } --ๅคš็‚นๆ‰พ่‰ฒ t['reg_้€‰ๆ‹ฉ่ง’่‰ฒ_่ฟ›ๅ…ฅๆธธๆˆ']={ 0xf5b14b, "-3|-46|0xf5b349,-4|90|0xf5b44c", 90, 53, 890, 130, 1114 } --ๅคš็‚นๆ‰พ่‰ฒ t['reg_่ทณ่ฟ‡']={ 0xe4d2ad, "0|-4|0xe4d2ad,-2|-4|0xd4c198", 90, 610, 1081, 623, 1099 } --ๅคš็‚นๆ‰พ่‰ฒ t['reg_่ทณ่ฟ‡1']={ 0xdcc9a2, "1|-2|0xe4d2ad", 90, 610, 1069, 625, 1089 } --ๅคš็‚นๆ‰พ่‰ฒ t['reg_ๆต้‡ไธ‹่ฝฝ็กฎๅฎš']={ 0xe05140, "6|57|0xda4434,5|-79|0xdb4535", 90, 153, 436, 213, 693 } --ๅคš็‚นๆ‰พ่‰ฒ t['reg_ๆป‘ๅŠจ้ชŒ่ฏ็•Œ้ข']={ 0xafb0b2, "17|95|0xffffff,-499|3|0xafb0b2,-507|40|0xffffff,-514|734|0xffffff,-483|761|0xafb0b2", 90, 30, 154, 598, 986 } --ๅคš็‚นๆ‰พ่‰ฒ t['reg_ๆณจๅ†Œๅคฑ่ดฅ']={ 0xfe3233, "-35|-6|0xfe3233,-109|-3|0xf8f9fd,-10|-782|0xfe3233,-107|-772|0xf8f9fd", 90, 449, 152, 620, 968 } --ๅคš็‚นๆ‰พ่‰ฒ function openU() local timeline = os.time() local outtime = 30 openURL(url) delay(3) while os.time() - timeline < outtime do if d('openU_ๆ‰“ๅผ€',true) then delay(20) return true end end return true end function reg() account = myRand(4,8) password = <PASSWORD>(4,9) regdate = xinxi[math.random(1,#xinxi)] ๆณจๅ†Œ็กฎ่ฎคkey = false local timeline = os.time() local outtime = math.random(300,360) while os.time() - timeline < outtime do if active(appbid,5) then if d('reg_ๆณจๅ†Œๅคฑ่ดฅ') then return false elseif d('reg_่ดฆๅทๆณจๅ†Œ',true) then elseif ๆณจๅ†Œ็กฎ่ฎคkey and d('reg_่ดฆๅทๆณจๅ†Œ็•Œ้ข',true) then elseif d('reg_่ดฆๅทๆณจๅ†Œ็•Œ้ข') then click(506,444) delay(2) inputword(account..'\n') delay(2) d('reg_้”ฎ็›˜ๅฎŒๆˆ',true) click(401,372) inputword(password) delay(2) d('reg_้”ฎ็›˜ๅฎŒๆˆ',true) click(306,506) input(regdate[1]) delay(2) d('reg_้”ฎ็›˜ๅฎŒๆˆ',true) click(206,536) inputword(regdate[2]) delay(2) d('reg_้”ฎ็›˜ๅฎŒๆˆ',true) click(306,506) click(596,866) input(regdate[1]) delay(2) d('reg_้”ฎ็›˜ๅฎŒๆˆ',true) ๆณจๅ†Œ็กฎ่ฎคkey = true elseif d('reg_่ฟ›ๅ…ฅๆธธๆˆ',true) then elseif d('reg_่ทณ่ฟ‡',true) or d('reg_่ทณ่ฟ‡1',true) then return true elseif d('reg_ๆต้‡ไธ‹่ฝฝ็กฎๅฎš',true) then elseif d('reg_้€‰ๆ‹ฉ่ง’่‰ฒ_่ฟ›ๅ…ฅๆธธๆˆ',true) then click(87,1001) elseif d('reg_ๆป‘ๅŠจ้ชŒ่ฏ็•Œ้ข') then moveTo(101,323,104,770) elseif d('reg_้€‰ๆ‹ฉ่ง’่‰ฒ') then ่ง’่‰ฒ = {{111,93,0x46424c},{197,86,0x4e4753},{295,94,0x4c4551},{394,88,0x48444d},{484,93,0x4c4651},{586,82,0x46424c},} key = ่ง’่‰ฒ[math.random(1,6)] click(key[1],key[2]) else click(462,107) end end delay(1) log('ไผ‘ๆฏ1็ง’') end return false end function reg1() account = myRand(4,8) password = <PASSWORD>) regdate = xinxi[math.random(1,#xinxi)] ๆณจๅ†Œ็กฎ่ฎคkey = false local timeline = os.time() local outtime = math.random(60,120) while os.time() - timeline < outtime do if active(appbid,5) then if d('reg_ๆณจๅ†Œๅคฑ่ดฅ') then return false elseif d('reg_่ดฆๅทๆณจๅ†Œ',true) then elseif ๆณจๅ†Œ็กฎ่ฎคkey and d('reg_่ดฆๅทๆณจๅ†Œ็•Œ้ข',true) then elseif d('reg_่ดฆๅทๆณจๅ†Œ็•Œ้ข') then click(506,444) delay(2) inputword(account..'\n') delay(2) d('reg_้”ฎ็›˜ๅฎŒๆˆ',true) click(401,372) inputword(password) delay(2) d('reg_้”ฎ็›˜ๅฎŒๆˆ',true) click(306,506) input(regdate[1]) delay(2) d('reg_้”ฎ็›˜ๅฎŒๆˆ',true) click(206,536) inputword(regdate[2]) delay(2) d('reg_้”ฎ็›˜ๅฎŒๆˆ',true) click(306,506) click(596,866) input(regdate[1]) delay(2) d('reg_้”ฎ็›˜ๅฎŒๆˆ',true) ๆณจๅ†Œ็กฎ่ฎคkey = true elseif d('reg_่ฟ›ๅ…ฅๆธธๆˆ',true) then elseif d('reg_่ทณ่ฟ‡',true) or d('reg_่ทณ่ฟ‡1',true) then return true elseif d('reg_ๆต้‡ไธ‹่ฝฝ็กฎๅฎš',true) then elseif d('reg_้€‰ๆ‹ฉ่ง’่‰ฒ_่ฟ›ๅ…ฅๆธธๆˆ',true) then click(87,1001) elseif d('reg_ๆป‘ๅŠจ้ชŒ่ฏ็•Œ้ข') then moveTo(101,323,104,770) elseif d('reg_้€‰ๆ‹ฉ่ง’่‰ฒ') then ่ง’่‰ฒ = {{111,93,0x46424c},{197,86,0x4e4753},{295,94,0x4c4551},{394,88,0x48444d},{484,93,0x4c4651},{586,82,0x46424c},} key = ่ง’่‰ฒ[math.random(1,6)] click(key[1],key[2]) else click(462,107) end end delay(1) log('ไผ‘ๆฏ1็ง’') end return true end ----ๆณจๅ†Œ --[[ while true do setAirplaneMode(true); --ๆ‰“ๅผ€้ฃž่กŒๆจกๅผ delay(15) setAirplaneMode(false); --ๅ…ณ้—ญ้ฃž่กŒๆจกๅผ delay(15) -- vpnx() -- delay(3) if true or vpn() then if awzNew() then if openU() then if reg() then reName('ๅฎŒๆˆ') upidfa('่œ€้—จๆ‰‹ๆธธ','ๆณจๅ†ŒๅฎŒๆˆ') end end end end end --]]-- ----ๅค็™ป --[[]] while true do setAirplaneMode(true); --ๆ‰“ๅผ€้ฃž่กŒๆจกๅผ delay(15) setAirplaneMode(false); --ๅ…ณ้—ญ้ฃž่กŒๆจกๅผ delay(15) -- vpnx() -- delay(3) if true or vpn() then if awz_next() then -- if openU() then if reg1() then reName('ๅค็™ปๅฎŒๆˆ') upidfa('่œ€้—จๆ‰‹ๆธธ','ๅค็™ปๅฎŒๆˆ') end -- end end end end --]]-- <file_sep>require("TSLib") require("tsp") local sz = require("sz") local json = sz.json w,h = getScreenSize(); MyTable = { ["style"] = "default", ["rettype"] = "table", ["width"] = w, ["height"] = h, ["config"] = "nikeapps.dat", ["timer"] = 99, ["orient"] = 0, ["pagetype"] = "multi", ["title"] = "Nike", ["cancelname"] = "ๅ–ๆถˆ", ["okname"] = "ๅผ€ๅง‹", pages = { { { ["type"] = "Label", ["text"] = "ๅŠŸ่ƒฝ้€‰ๆ‹ฉ", ["size"] = 16, ["align"] = "left", ["color"] = "0,0,0", }, { ["id"] = "work", ["type"] = "RadioGroup", ["list"] = "ๆณจๅ†Œ(nike),ๆๅ–(nike),ๅค็™ปๅธๅท(snkrs)", ["select"] = "0", }, { ["type"] = "Label", ["text"] = "ๆณจๅ†Œๆ‰นๆฌก", ["size"] = 16, ["align"] = "left", ["color"] = "0,0,0", }, { ["id"] = "sms", ["type"] = "Edit", ["prompt"] = "1", ["text"] = "1", ["kbtype"] = "", ["width"] = 200, }, { ["type"] = "Label", ["text"] = "ๆๅ–Nๅคฉๅ‰็š„ๅธๅท", ["size"] = 16, ["align"] = "left", ["color"] = "0,0,0", }, { ["id"] = "day", ["type"] = "Edit", ["prompt"] = "1", ["text"] = "1", ["kbtype"] = "number", ["width"] = 200, }, { ["type"] = "Label", ["text"] = "ๆๅ–Nๅค็™ปๆฌกๆ•ฐ็š„ๅธๅท", ["size"] = 16, ["align"] = "left", ["color"] = "0,0,0", }, { ["id"] = "again", ["type"] = "Edit", ["prompt"] = "1", ["text"] = "0", ["kbtype"] = "number", ["width"] = 200, }, { ["type"] = "Label", ["text"] = "ๆธ…็†ๆจกๅผ", ["size"] = 16, ["align"] = "left", ["color"] = "0,0,0", }, { ["id"] = "clearMode", ["type"] = "RadioGroup", ["list"] = "็ˆฑไผช่ฃ…,็ˆฑๆ–ฐๆœบ,่‡ชๆธ…็†", ["select"] = "0", }, { ["type"] = "Label", ["text"] = "็ฝ‘็ปœๆจกๅผ", ["size"] = 16, ["align"] = "left", ["color"] = "0,0,0", }, { ["id"] = "netMode", ["type"] = "RadioGroup", ["list"] = "4G,ไธๆ–ญ็ฝ‘,vpn,rocket", ["select"] = "0", }, { ["type"] = "Label", ["text"] = "้ฃž่กŒๆจกๅผๆ—ถ้—ด", ["size"] = 16, ["align"] = "left", ["color"] = "0,0,0", }, { ["id"] = "wifitime", ["type"] = "Edit", ["prompt"] = "้ฃž่กŒๆจกๅผๆ—ถ้—ด", ["text"] = "30", ["kbtype"] = "number", ["width"] = 475, }, { ["type"] = "Label", ["text"] = "้‚ฎ็ฎฑไพ‹่กจ", ["size"] = 16, ["align"] = "left", ["color"] = "0,0,0", }, { ["type"] = "TextArea", -- ๅฟ…ๅกซ๏ผŒๆŽงไปถ็ฑปๅž‹๏ผŒ่พ“ๅ…ฅๆก† ["id"] = "mail", -- ้€‰ๅกซ๏ผŒๆ— ๏ผŒๆŽงไปถID ไปฅ tableๆ ผๅผ่ฟ”ๅ›ž่ฟ”ๅ›žๅ€ผๆ—ถๅฟ…ๅกซ,ๅฆๅˆ™ๆ— ๆณ•่Žทๅ–่ฟ”ๅ›žๅ€ผ ["text"] = <EMAIL>\<EMAIL>\<EMAIL>\<EMAIL>", ["prompt"] = "ๅกซๅ…ฅ้‚ฎ็ฎฑ,ไธ€่กŒไธ€ไธช", -- ้€‰ๅกซ๏ผŒๆ— ๏ผŒๆ็คบๆ–‡ๅญ— ["size"] = 12, -- ้€‰ๅกซ๏ผŒ15๏ผŒๅญ—ไฝ“ๅคงๅฐ ["align"] = "left", -- ้€‰ๅกซ๏ผŒๅฑ…ๅทฆ๏ผŒๅฏน้ฝๆ–นๅผ ["width"] = 475, ["height"] = 100, -- ้€‰ๅกซ๏ผŒ75๏ผŒ็ฉบ้—ด้ซ˜ๅบฆ(ไป…ๆ”ฏๆŒ iOS) ["color"] = "255,0,0", -- ้€‰ๅกซ๏ผŒ้ป‘่‰ฒ๏ผŒๅญ—ไฝ“้ขœ่‰ฒ ["kbtype"] = "ascii", -- ้€‰ๅกซ๏ผŒๆ ‡ๅ‡†้”ฎ็›˜๏ผŒ้”ฎ็›˜็ฑปๅž‹ }, { ["type"] = "Label", ["text"] = "้šๆœบๅฏ†็ ", ["size"] = 16, ["align"] = "left", ["color"] = "0,0,0", }, { ["id"] = "password_key", ["type"] = "RadioGroup", ["list"] = "้šๆœบๅฏ†็ (8ไฝ),ๅ›บๅฎšๅฏ†็ ", ["select"] = "0", }, { ["type"] = "Label", ["text"] = "่พ“ๅ…ฅๅฏ†็ ", ["size"] = 16, ["align"] = "left", ["color"] = "0,0,0", }, { ["id"] = "password", ["type"] = "Edit", ["prompt"] = "่ฟ™้‡Œๆ˜ฏๅฏ†็ ", ["text"] = "Shuai2019tk", ["kbtype"] = "ascii", ["width"] = 475, }, { ["type"] = "Label", ["text"] = "็Ÿญไฟกๅนณๅฐ", ["size"] = 16, ["align"] = "left", ["color"] = "0,0,0", }, { ["id"] = "smsPT", ["type"] = "RadioGroup", ["list"] = "ๆ–‘้ฉฌ,ไฟก้ธฝ,ๆ— ๅนณๅฐ", ["select"] = "0", }, { ["type"] = "Label", ["text"] = "ๆดป่ทƒๆœ€็Ÿญๆ—ถ้—ด(็ง’)", ["size"] = 16, ["align"] = "left", ["color"] = "0,0,0", }, { ["id"] = "look_min_time", ["type"] = "Edit", ["prompt"] = "ๆดป่ทƒๆœ€็Ÿญๆ—ถ้—ด(็ง’)", ["text"] = "30", ["kbtype"] = "number", ["width"] = 475, }, { ["type"] = "Label", ["text"] = "ๆดป่ทƒๆœ€้•ฟๆ—ถ้—ด(็ง’)", ["size"] = 16, ["align"] = "left", ["color"] = "0,0,0", }, { ["id"] = "look_max_time", ["type"] = "Edit", ["prompt"] = "ๆดป่ทƒๆœ€้•ฟๆ—ถ้—ด(็ง’)", ["text"] = "240", ["kbtype"] = "number", ["width"] = 475, }, { ["type"] = "Label", ["text"] = "ๆ”ฏไป˜ๅนณๅฐ", ["size"] = 16, ["align"] = "left", ["color"] = "0,0,0", }, { ["id"] = "pay", ["type"] = "RadioGroup", ["list"] = "ๅพฎไฟก,ๆ”ฏไป˜ๅฎ,้šๆœบ", ["select"] = "0", }, } } } local MyJsonString = json.encode(MyTable); UIret,UIvalues = showUI(MyJsonString) if UIret == 1 then nLog(UIvalues.mail) mailheader = strSplit(UIvalues.mail,"\n") log(mailheader) else lua_exit() end <file_sep> require('tsp') --่ฏปๆ–‡ไปถ function readFile_(path) local path = path or '/var/mobile/Media/TouchSprite/lua/account.txt' local file = io.open(path,"r"); if file then local _list = ''; for l in file:lines() do _list = _list..l end file:close(); return _list end end function local_token() local appbid = 'com.nike.onenikecommerce' local localPath = appDataPath(appbid).."/Documents/ifkc.plist" --่ฎพ็ฝฎ plist ่ทฏๅพ„ return readFile_(localPath) end --ๅ†™ๅ…ฅ function writeFile_(info,way,path) local path = path or '/var/mobile/Media/TouchSprite/lua/account.txt' local way = way or 'a' local f = assert(io.open(path, way)) f:write(info) f:write('') f:close() end --็”จhttp.getๅฎž็Žฐไธ‹่ฝฝๆ–‡ไปถๅŠŸ่ƒฝ local sz = require("sz") local cjson = sz.json local http = sz.i82.http function downFile(url, path) status, headers, body = http.get(url) if status == 200 then file = io.open(path, "wb") if file then file:write(body) file:close() return true else return -1; end else return status; end end --ๅ–ๅธ็ฉบ้—ฒๅธๅท function AccountInfoBack() local sz = require("sz") local json = sz.json local appbid = 'com.nike.onenikecommerce' local AccountInfo = appDataPath(appbid).."/Documents/ifkc.plist" local url = 'http://nikeapi.honghongdesign.cn/' .. var.account.token downFile(url, AccountInfo) mSleep(2000) end <file_sep>require "TSLib" ts = require("ts") plist = ts.plist http = { --httpๆจกๅ— tsget = function(url,sleep,header) sleep = sleep or 10 header = header or {} ts.setHttpsTimeOut(sleep) header["typeget"] = "ios" if header['Content-Type']==nil then header['Content-Type'] = "application/json" end if string.find(url,"https")~=nil then return ts.httpsGet(url, header) else return ts.httpGet(url, header) end end, tspost = function(url,sleep,header,str) sleep = sleep or 10 header = header or {} ts.setHttpsTimeOut(sleep) header["typeget"] = "ios" if header['Content-Type']==nil then header['Content-Type'] = "application/json" end if string.find(url,"https")~=nil then return ts.httpsPost(url, header,str) else return ts.httpPost(url, header,str) end end, download = function(url,path) return ts.tsDownload(path,url) end, curlGet = function(u,s,header,isProxy,isHead,isDirect) if isProxy ==nil then isProxy = true end if isHead ==nil then isHead = false end if isDirect ==nil then isDirect = false end local headers = "" for k,v in pairs(header) do headers = headers.. " -H '"..k..":"..v.."'" end if isProxy == true then headers = headers.." -H 'Proxy-Authorization:Basic cDFod2xFOTZJVk5Kc2R5ZTppRWZjdGU5S0pMTDhuUTR3'" end local script = 'curl "'..u..'"'..headers..' -m '..s..' -w "curl_code=%{http_code}" -k' if isHead == true then script = script.." -i" end if isProxy == true then script = script..' -x transfer.mogumiao.com:9001' end if isDirect == true then script = script.." -L" end local p = io.popen(script) local code,body =-1,nil local res = "" for v in p:lines() do res = res ..v end code = tonumber( string.split(res,"curl_code=")[2]) body = string.split(res,"curl_code=")[1] return code,{},body end, curlPost = function(u,s,header,postdata,isProxy,isHead,isDirect) if isProxy ==nil then isProxy = true end if isHead ==nil then isHead = false end if isDirect ==nil then isDirect = false end local headers = "" for k,v in pairs(header) do headers = headers.. " -H '"..k..":"..v.."'" end if isProxy == true then headers = headers.." -H 'Proxy-Authorization:Basic cDFod2xFOTZJVk5Kc2R5ZTppRWZjdGU5S0pMTDhuUTR3'" end local script = 'curl "'..u..'"'..headers..' -m '..s..' -w "curl_code=%{http_code}" -k -X POST -d "'..postdata..'"' if isHead == true then script = script.." -i" end if isProxy == true then script = script..' -x transfer.mogumiao.com:9001' end if isDirect == true then script = script.." -L" end --nLog(script) local p = io.popen(script) local code,body =-1,nil local res = "" for v in p:lines() do res = res ..v end code = tonumber( string.split(res,"curl_code=")[2]) body = string.split(res,"curl_code=")[1] return code,{},body end, } screen = { --ๅฑๅน•ๅค„็† image = function(left,top,right,bottom) return img.screen(left,top,right,bottom) end, } clear = { --ๆธ…็†ๆจกๅ— keychain = function(bid) clearKeyChain(bid); end, all_keychain = function() clearAllKeyChains() end, pasteboard = function() clearPasteboard(); end, cookies = function() clearCookies() end, caches = function() os.execute("su mobile -c uicache"); end, all_photos = function() clearAllPhotos() end, app_data = function(bid) cleanApp(bid) end, idfav = function() clearIDFAV() --if str == nil then clearIDFAV() else return clearIDFAV(str) end end, } device = { --่ฎพๅค‡ไฟกๆฏ่Žทๅ–ๆจกๅ— name = function() --่Žทๅ–่ฎพๅค‡ๅ return getDeviceName() end, udid = function() --่Žทๅ–่ฎพๅค‡UDID return ts.system.udid() end, serial_number = function() --่Žทๅ–่ฎพๅค‡ๅบๅˆ—ๅท return ts.system.serialnumber() end, wifi_mac = function() --่Žทๅ–่ฎพๅค‡WIFI MACๅœฐๅ€ return ts.system.wifimac() end, bt_mac = function() --่Žทๅ–่ฎพๅค‡่“็‰™ MACๅœฐๅ€ return ts.system.btmac() end, is_screen_locked = function() return deviceIsLock()~=0 end , lock_screen = function() --้”ๅฎšๅฑๅน• lockDevice() end, unlock_screen = function() --่งฃ้”ๅฑๅน• unlockDevice() end, turn_off_bluetooth = function() setBTEnable(false); --ๅ…ณ้—ญ่“็‰™ end, turn_on_bluetooth = function() setBTEnable(true); --ๆ‰“ๅผ€่“็‰™ end, turn_off_data = function() setCellularDataEnable(false) --ๅ…ณ้—ญ่œ‚็ช็ฝ‘็ปœ end, turn_on_data = function() setCellularDataEnable(true) --ๆ‰“ๅผ€่œ‚็ช็ฝ‘็ปœ end, set_volume = function(num) setVolumeLevel(num) --่ฆ่ฎพ็ฝฎ็š„่ฎพๅค‡้Ÿณ้‡๏ผŒ่Œƒๅ›ด 0 - 1 end, set_brightness = function(num) setBacklightLevel(num); --่ฆ่ฎพ็ฝฎ็š„ๅฑๅน•ไบฎๅบฆๅ€ผ๏ผŒ่Œƒๅ›ด 0 - 1 end, set_autolock_time = function(time) setAutoLockTime(time) --0 ๅˆฐ 5,0 ๆ˜ฏไปฃ่กจๆฐธไธ้”ๅฑ๏ผŒ1 ~ 5 ไธบ้”ๅฑๆ—ถ้—ด๏ผŒๅ•ไฝไธบๅˆ† end, turn_on_wifi = function() setWifiEnable(true); --ๆ‰“ๅผ€ WiFi end, turn_off_wifi = function() setWifiEnable(false); --ๅ…ณ้—ญ WiFi end, join_wifi = function(wifiname,password,types) --WiFi ๅŠ ๅฏ†็ฑปๅž‹๏ผš0 - ๆ— ๅฏ†็ ๏ผŒ1 - WEP,2 - WPA,3 - WPA2,4 - WPA ไผไธš็‰ˆ๏ผŒ5 - WPA2 ไผไธš็‰ˆ connectToWifi(wifiname,password,types) end, } app = { front_bid = function() return frontAppBid() end, data_path = function(bid) return appDataPath(bid) end, close = function(bid) closeApp(bid) end , run = function(bid) runApp(bid) end, open_url = function(url) openURL(url) end, input_text = function(str) inputText(str) end, uninstall = function(bid) uninstallApp(bid) end , } file = { --ๆ–‡ไปถๅค„็†ๆจกๅ— exists = function(file_name) local f = io.open(file_name, "r") return f ~= nil and f:close() end, reads = function(file_name) local f = io.open(file_name,"r") if f then local c = f:read("*a") f:close() return c else return nil end end, writes = function(file_name,str,mode) mode = mode or "w" local f = io.open(file_name, mode) if f == nil then return "" end local ret = f:write(str) f:close() --[[ mode = mode or "w+" writeFileString(file_name,str,mode) --]] end, } sys = { --็ณป็ปŸๆจกๅ— msleep = function(sleep) mSleep(sleep) end, toast = function(str,sleep) sleep = sleep or 1 toast(str,sleep) end, alert = function(str,sleep) sleep = sleep or 1 dialog(str,sleep) end, } json = { --json ๅบๅˆ—ๅŒ– encode = function(str) err,info = pcall(function() return ts.json.encode(str) end) if err then return info end end, decode = function(str) err,info = pcall(function() return ts.json.decode(str) end) if err then return info end end, } nLog('Common') <file_sep>-- ไธ‡ๅ›ฝ่ง‰้†’ -- main.lua t['ๅฏน่ฏๆก†']={0xf2f2f2, "0|0|0xf2f2f2,-21|-3|0xededed",90,123,652,178,746} t['ๅฏน่ฏๆก†-็Ž‹ๅ›ฝ']={0x594a30, "0|0|0x594a30,-5|5|0x008fbe",90,13,47,109,608} t['ๅฏน่ฏๆก†-็Ž‹ๅ›ฝ-ๆฟ€ๆดป']={0xf0e9df, "0|0|0xf0e9df,-5|5|0x008fbe",90,13,47,109,608} t['ๅฏน่ฏๆก†-ๆ‰“ๅผ€ไพง่พน']={0xfff2e6, "0|0|0xfff2e6,-1|-7|0xb2925e,-1|-11|0xfff2e6",90,12,3,51,56} t['ๅฏน่ฏๆก†-ๆ‰“ๅผ€ไพง่พน-ๅ‘้€']={0x006adf, "0|0|0x006adf,8|-14|0xe9fbff",90,1261,176,1330,567} _adText = { "ๆธธๆˆๅทฅๅ…ทไบบrok", } function ad() if d('ๅฏน่ฏๆก†',true,1,3) then if d('ๅฏน่ฏๆก†-็Ž‹ๅ›ฝ',true) or d('ๅฏน่ฏๆก†-็Ž‹ๅ›ฝ-ๆฟ€ๆดป') then else d('ๅฏน่ฏๆก†-ๆ‰“ๅผ€ไพง่พน',true) end click(523,711,3) inputStr( _adText[rd(1,#_adText)] ) delay(2) if d('ๅฏน่ฏๆก†-ๆ‰“ๅผ€ไพง่พน-ๅ‘้€',true,1,20) then return true end end end t['ๅนฟๅ‘Š-ๆ”ถ่—ๅคน']={0xb46d12, "0|0|0xb46d12,10|5|0xffa700",90,466,-1,524,40} t['ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-ๅ…จ้ƒจ็‚น็‰นๆฎŠ']={0xffffff, "0|0|0xffffff,-234|1|0x098b08",90,188,101,569,186} t['ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-็‰นๆฎŠๆฟ€ๆดป']={0xffffff, "0|0|0xffffff,-58|2|0x088508",90,193,114,563,181} t['ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-็‰นๆฎŠๆฟ€ๆดป-ๆ— ไนฆ็ญพ']={0xffffff, "0|0|0xffffff,113|4|0x066f9a,120|3|0xffffff",90,500,351,788,421} t['ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-็‰นๆฎŠๆฟ€ๆดป-ๅ…ณ้—ญ']={0xd3d1ca, "0|0|0xd3d1ca,-11|-9|0xd7d6ce,-9|-2|0x9b9a8d",90,1110,65,1162,107} t['ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-็‰นๆฎŠๆฟ€ๆดป-ๆ”ถ่—่‡ชๅทฑ']={0x995200, "0|0|0x995200,56|-3|0x1274ba,-62|-3|0x1075ba",90,160,79,1319,682} t['ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-็‰นๆฎŠๆฟ€ๆดป-ๆ”ถ่—่‡ชๅทฑ-็›Ÿไธป']={0xd967f7, "0|0|0xd967f7,-63|0|0x1174ba,56|0|0x1274ba",90,71,55,1296,712} t['ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-ๆฟ€ๆดป่‡ชๅทฑ็š„ๆ”ถ่—']={0x003658, "0|0|0x003658,-5|-130|0x0898d5",90,125,170,263,448} t['ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-็‰นๆฎŠๆฟ€ๆดป-ๆ”ถ่—ๅฎŒๆˆ']={0x007aff, "0|0|0x007aff,49|-5|0x007aff,14|18|0x007aff",90,1017,61,1310,635} t['ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-็‰นๆฎŠๆฟ€ๆดป-็กฎๅฎš']={0x1274ba, "0|0|0x1274ba,-59|-17|0x00ccfe,52|17|0x00b7f3",90,273,140,1039,608} t['ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-็‰นๆฎŠๆฟ€ๆดป-ๆœ‰ไนฆ็ญพ']={0x055987, "0|0|0x055987,13|-9|0x025788,14|8|0x005886,9|0|0x1587bf",90,854,190,910,261} t['ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-ไธ–็•Œ้ข‘้“']={0x008fbe, "0|0|0x008fbe,0|-6|0x7b705f,63|2|0xffffff",90,384,74,756,688} t['ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-ไธ–็•Œ้ข‘้“-็กฎๅฎšๅ‘้€']={0x0e75e5, "0|0|0x0e75e5,-20|-12|0xffffff,-201|-3|0xc5b499",90,382,275,936,549} function ads_() d('ๆธธๆˆไธป็•Œ้ข-ๅŸŽๅ†…',true,2) if d('ๆธธๆˆไธป็•Œ้ข-้‡Žๅค–',false,1,3) then if d('ๅนฟๅ‘Š-ๆ”ถ่—ๅคน',true,1,2) then d('ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-ๅ…จ้ƒจ็‚น็‰นๆฎŠ',true,1,3) if d('ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-็‰นๆฎŠๆฟ€ๆดป') then if d("ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-็‰นๆฎŠๆฟ€ๆดป-ๆœ‰ไนฆ็ญพ",true,1,2) then if d('ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-ไธ–็•Œ้ข‘้“',true,1,2)then if d('ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-ไธ–็•Œ้ข‘้“-็กฎๅฎšๅ‘้€',true,1,2)then delay(30) return true end end else log('ๆ— ไนฆ็ญพ') d('ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-็‰นๆฎŠๆฟ€ๆดป-ๅ…ณ้—ญ',true,1,2) click(663, 358,2) d('ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-็‰นๆฎŠๆฟ€ๆดป-ๆ”ถ่—่‡ชๅทฑ',true,1,2) d("ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-็‰นๆฎŠๆฟ€ๆดป-ๆ”ถ่—่‡ชๅทฑ-็›Ÿไธป",true,1,2) d('ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-ๆฟ€ๆดป่‡ชๅทฑ็š„ๆ”ถ่—',true,1,2) click(576, 251,5) clearTxt() input( _adText[rd(1,#_adText)] ) delay(5) d("ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-็‰นๆฎŠๆฟ€ๆดป-ๆ”ถ่—ๅฎŒๆˆ",true,1,2) d("ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-็‰นๆฎŠๆฟ€ๆดป-็กฎๅฎš",true,1,2) return false; end end end end end <file_sep>-- ๅฆ™ๅฅๅบทๆณจๅ†Œ -- main.lua -- Create By TouchSpriteStudio on 22:10:07 -- Copyright ยฉ TouchSpriteStudio . All rights reserved. <file_sep> require("tsp") t={} t['็ซ‹ๅณ่ดญไนฐ']={0xef853c, "0|0|0xef853c,-102|37|0xffeab9,-56|44|0xd94644,-134|-46|0xffebb9",90,0,0,485,960} t['ๅฅฝ']={0x007aff, "0|0|0x007aff,-483|-152|0xf2f2f7,3|-155|0xf1f2f7",90,22,470,610,725} t['ไผ˜ๅฅๅบท']={0xfffdf0, "0|0|0xfffdf0,54|-53|0xff9d1d,-25|29|0xf0e2bc",90,165,269,438,502} t['vpn-ๅฅฝ']={0x007aff, "0|0|0x007aff,-289|-104|0xffffff,-298|0|0x007aff",90,89,322,491,477} function vpn() setVPNEnable(true) mSleep(1000) local LineTime = os.time() local OutTimes = 60 while (os.time()-LineTime<OutTimes) do local flag = getVPNStatus() if flag.active then nLog("VPN ๆ‰“ๅผ€็Šถๆ€"..flag.status) if flag.status == 'ๅทฒ่ฟžๆŽฅ' then return true else setVPNEnable(true) delay(6) end else nLog("VPN ๅ…ณ้—ญ็Šถๆ€"..flag.status) end mSleep(1000) if d("vpn-ๅฅฝ") then log("ๅ‡†ๅค‡่พ“ๅ…ฅ") click(154,347,2) inputText(1) delay(1) d("vpn-ๅฅฝ",true,1,2) end end end require("new") function ็ซ‹ๅณ่ดญไนฐ() url = "https://sourl.cn/9dhxs4" openURL(url) -- body local timeLine = os.time() while (os.time()-timeLine < 60 ) do if d( "็ซ‹ๅณ่ดญไนฐ" ,true , 1,3 ) then elseif ( d("ไผ˜ๅฅๅบท") or d("ๅฅฝ",true,1,3) ) then return true else moveTo(200,700,200,200,20) delay(1) end end end for i=0,200 do vpnx() delay(3) if true or clickNew() then delay(3) if ( vpn() )then ็ซ‹ๅณ่ดญไนฐ() end end end -- https://sourl.cn/9dhxs4<file_sep>-- lua-img-ๅฐ็™ฝ -- ZZBase64.lua -- Create By TouchSpriteStudio on 22:16:22 -- Copyright ยฉ TouchSpriteStudio . All rights reserved. ZZBase64 = {} local string = string ZZBase64.__code = { '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', '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', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', }; ZZBase64.__decode = {} for k,v in pairs(ZZBase64.__code) do ZZBase64.__decode[string.byte(v,1)] = k - 1 end function ZZBase64.encode(text) local len = string.len(text) local left = len % 3 len = len - left local res = {} local index = 1 for i = 1, len, 3 do local a = string.byte(text, i ) local b = string.byte(text, i + 1) local c = string.byte(text, i + 2) -- num = a<<16 + b<<8 + c local num = a * 65536 + b * 256 + c for j = 1, 4 do --tmp = num >> ((4 -j) * 6) local tmp = math.floor(num / (2 ^ ((4-j) * 6))) --curPos = tmp&0x3f local curPos = tmp % 64 + 1 res[index] = ZZBase64.__code[curPos] index = index + 1 end end if left == 1 then ZZBase64.__left1(res, index, text, len) elseif left == 2 then ZZBase64.__left2(res, index, text, len) end return table.concat(res) end function ZZBase64.__left2(res, index, text, len) local num1 = string.byte(text, len + 1) num1 = num1 * 1024 --lshift 10 local num2 = string.byte(text, len + 2) num2 = num2 * 4 --lshift 2 local num = num1 + num2 local tmp1 = math.floor(num / 4096) --rShift 12 local curPos = tmp1 % 64 + 1 res[index] = ZZBase64.__code[curPos] local tmp2 = math.floor(num / 64) curPos = tmp2 % 64 + 1 res[index + 1] = ZZBase64.__code[curPos] curPos = num % 64 + 1 res[index + 2] = ZZBase64.__code[curPos] res[index + 3] = "=" end function ZZBase64.__left1(res, index,text, len) local num = string.byte(text, len + 1) num = num * 16 tmp = math.floor(num / 64) local curPos = tmp % 64 + 1 res[index ] = ZZBase64.__code[curPos] curPos = num % 64 + 1 res[index + 1] = ZZBase64.__code[curPos] res[index + 2] = "=" res[index + 3] = "=" end function ZZBase64.decode(text) local len = string.len(text) local left = 0 if string.sub(text, len - 1) == "==" then left = 2 len = len - 4 elseif string.sub(text, len) == "=" then left = 1 len = len - 4 end local res = {} local index = 1 local decode = ZZBase64.__decode for i =1, len, 4 do local a = decode[string.byte(text,i )] local b = decode[string.byte(text,i + 1)] local c = decode[string.byte(text,i + 2)] local d = decode[string.byte(text,i + 3)] --num = a<<18 + b<<12 + c<<6 + d local num = a * 262144 + b * 4096 + c * 64 + d local e = string.char(num % 256) num = math.floor(num / 256) local f = string.char(num % 256) num = math.floor(num / 256) res[index ] = string.char(num % 256) res[index + 1] = f res[index + 2] = e index = index + 3 end if left == 1 then ZZBase64.__decodeLeft1(res, index, text, len) elseif left == 2 then ZZBase64.__decodeLeft2(res, index, text, len) end return table.concat(res) end function ZZBase64.__decodeLeft1(res, index, text, len) local decode = ZZBase64.__decode local a = decode[string.byte(text, len + 1)] local b = decode[string.byte(text, len + 2)] local c = decode[string.byte(text, len + 3)] local num = a * 4096 + b * 64 + c local num1 = math.floor(num / 1024) % 256 local num2 = math.floor(num / 4) % 256 res[index] = string.char(num1) res[index + 1] = string.char(num2) end function ZZBase64.__decodeLeft2(res, index, text, len) local decode = ZZBase64.__decode local a = decode[string.byte(text, len + 1)] local b = decode[string.byte(text, len + 2)] local num = a * 64 + b num = math.floor(num / 16) res[index] = string.char(num) end <file_sep>-- nike-mac -- zl.lua -- Create By TouchSpriteStudio on 20:35:53 -- Copyright ยฉ TouchSpriteStudio . All rights reserved. require("TSLib") require('tsp') local axjbid = 'YOY' function locks() local flag = deviceIsLock(); if flag == 0 then else unlockDevice(); --่งฃ้”ๅฑๅน• end end function activeaxj(app,t) t = t or 0.5 locks() local bid = frontAppBid(); if bid ~= app then nLog(app.."๏ผŒๅ‡†ๅค‡ๅฏๅŠจ") runApp(app) mSleep(t*1000) return true end end function axj_next() function nextrecord() local sz = require("sz"); local http = require("szocket.http"); local res, code = http.request("http://127.0.0.1:1688/cmd?fun=nextrecord"); if code == 200 then local resJson = sz.json.decode(res); local result = resJson.result; nLog("the result is: " .. result); if tonumber(result) == 1 then return true end end end local out_time = os.time() while os.time()-out_time <= 10 do if activeaxj(axjbid,2)then elseif nextrecord()then return true end mSleep(1000* 2) end end function axjNew() local timeLine = os.time() local outTime = 60 * 0.5 function newRecord() local sz = require("sz"); local http = require("szocket.http"); local res, code = http.request("http://127.0.0.1:1688/cmd?fun=newrecord"); if code == 200 then local resJson = sz.json.decode(res); local result = resJson.result; nLog("the result is: " .. result); if result == 3 then --//IPๅœฐๅ€้‡ๅค dialog('ip ๅœฐๅ€้‡ๅค', 3) return true elseif result == 1 then return true elseif result == 2 then toast('ๆญฃๅœจไธ€้”ฎๆ–ฐๆœบing',1) end end end while (os.time()-timeLine < outTime) do if activeaxj(axjbid,3)then elseif newRecord() then return true end mSleep(1000) end nLog('ๆ–ฐๆœบ่ถ…ๆ—ถ') end nLog('AXJ ๅŠ ๆˆชๅฎŒๆˆ')<file_sep>if not(t)then t={} end t['>ๅผ•ๅฏผ้กต-ๅŒๆ„<']={0x111111, "0|0|0x111111,266|-1|0x111111,-261|1|0x111111,-32|150|0x111111,0|147|0xffffff",90,23,162,612,1081} t['ๅผ•ๅฏผ้กต-็™ปๅฝ•-ๅŠ ๅ…ฅ']={0x111111, "0|0|0x111111,21|2|0xffffff,25|2|0x111111,45|1|0x111111,156|6|0xffffff,-99|6|0xffffff,-272|8|0xffffff",90,9,851,595,1029} t['ๆณจๅ†Œ-ๅˆ›ๅปบๆ‚จ็š„NIKEไผšๅ‘˜']={0xffffff, "0|0|0xffffff,-2|-24|0x000000,-238|-52|0x000000,270|26|0x000000,226|-718|0xffffff,232|-724|0x111111,266|-384|0xe5e5e5",90,20,92,622,1094} t['ๆณจๅ†Œ-ๅˆ›ๅปบๆ‚จ็š„NIKEไผšๅ‘˜-ๅ‘้€้ชŒ่ฏ็ ']={0x111111, "0|0|0x111111,-9|-29|0xe5e5e5,-5|30|0xe5e5e5",90,395,258,566,451} t['ๆณจๅ†Œ-ๅˆ›ๅปบๆ‚จ็š„NIKEไผšๅ‘˜-้”™่ฏฏๆ็คบ']={0xfe0000, "0|0|0xfe0000,-48|-79|0xfe0000",90,14,263,621,886} t['ๆณจๅ†Œ-ๅˆ›ๅปบๆ‚จ็š„NIKEไผšๅ‘˜-่พ“ๅ…ฅ้ชŒ่ฏ็ ']={0xa9a9a9, "0|0|0xa9a9a9,0|21|0xa9a9a9,0|52|0xe5e5e5,-18|-26|0xe5e5e5",90,70,597,245,770} t['ๆณจๅ†Œ-ๅˆ›ๅปบๆ‚จ็š„NIKEไผšๅ‘˜-ๅ‰ๅพ€']={0x007aff, "0|0|0x007aff,-3|0|0xffffff",90,495,986,629,1129} t['ๆณจๅ†Œ-ๅˆ›ๅปบๆ‚จ็š„NIKEไผšๅ‘˜-็ปง็ปญ']={0xffffff, "0|0|0xffffff,10|-6|0x000000,-279|-42|0x000000,209|33|0x000000",90,20,804,603,1087} t['ๆณจๅ†Œ-ๅˆ›ๅปบๆ‚จ็š„NIKEไผšๅ‘˜-็ปง็ปญ-Up']={0x000000, "0|0|0x000000,-1|-3|0xffffff,-251|-37|0x000000,247|38|0x000000",90,29,458,615,699} t['ๆณจๅ†Œ-ๅกซ่ต„ๆ–™้กต้ข']={0x111111, "0|0|0x111111,-18|-10|0xbcbcbc,460|-796|0x111111,454|-806|0xffffff,210|-898|0x000000",90,30,68,550,1068} t['ๆณจๅ†Œ-ๅกซ่ต„ๆ–™้กต้ข2']={0x000000, "0|0|0x000000,-8|-1|0xffffff,-226|-14|0x000000,301|1|0x000000,-199|138|0x8d8d8d,42|87|0x000000,268|60|0x8d8d8d",90,12,865,617,1096} t['ๆณจๅ†Œ-ๅกซ่ต„ๆ–™้กต้ข-ๅง“']={0x8d8d8d, "0|0|0x8d8d8d,172|-1|0xe5e5e5,-77|2|0xe5e5e5,57|-36|0xe5e5e5,53|42|0xe5e5e5",90,19,97,317,451} t['ๆณจๅ†Œ-ๅกซ่ต„ๆ–™้กต้ข-็”ทๅฅณ']={0x111111, "-5|0xbcbcbc,397|-110|0x8e8e8e,120|-109|0x8d8d8d",90,18,468,621,846} t['ๆณจๅ†Œ-ๅกซ่ต„ๆ–™้กต้ข-ๆˆ‘ๅŒๆ„']={0xffffff, "0|0|0xffffff,4|-22|0xbcbcbc,27|-1|0xbcbcbc,4|20|0xbcbcbc,-14|2|0xbcbcbc",90,17,722,119,917} t['ๆณจๅ†Œ-ๅกซ่ต„ๆ–™้กต้ข-ๅŠ ๅ…ฅๆˆ‘ไปฌ']={0x000000, "0|0|0x000000,9|3|0xffffff,287|-30|0x000000,-201|47|0x000000,66|97|0x000000,68|108|0xffffff",90,23,743,616,1087} t['ๆณจๅ†Œ-่พ“ๅ…ฅ็”ตๅญ้‚ฎไปถ']={0xffffff, "0|0|0xffffff,0|-4|0x000000,-239|-36|0x000000,239|42|0x000000,213|-426|0x111111,210|-435|0xffffff,210|-441|0x111111,30|-543|0x000000",90,16,113,623,757} t['ๆณจๅ†Œ-่พ“ๅ…ฅ็”ตๅญ้‚ฎไปถ-็”ตๅญ้‚ฎไปถๅœฐๅ€']={0x8d8d8d, "0|0|0x8d8d8d,27|0|0x8d8d8d,3|40|0xe5e5e5,6|-37|0xe5e5e5",90,77,417,268,625} t['ๆณจๅ†Œ-่พ“ๅ…ฅ็”ตๅญ้‚ฎไปถ-ไฟๅญ˜']={0xffffff, "0|0|0xffffff,-15|-5|0x000000,-269|-2|0x000000,256|-12|0x000000,-250|-204|0xe5e5e5,226|-126|0xe5e5e5",90,29,448,603,769} t['ๆณจๅ†ŒๆˆๅŠŸ-ไธป็•Œ้ข']={0x111111, "0|0|0x111111,20|-18|0xffffff,19|-24|0x111111,184|-2|0xcccccc,359|-3|0xcccccc,499|-3|0xcccccc",90,5,1036,622,1122} t['ๆณจๅ†ŒๆˆๅŠŸ-ไธป็•Œ้ข']={0x111111, "0|0|0x111111,12|-14|0xffffff,15|-12|0x111111,472|-11|0xcccccc,-39|-967|0xff0015",90,6,51,618,1121} t['่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘']={0xcccccc, "0|0|0xcccccc,-160|8|0xcccccc,-314|-1|0xcccccc,-481|5|0x111111",90,27,1045,592,1116} t['่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ']={0xffffff, "0|0|0xffffff,14|-4|0xcccccc,-24|998|0x111111,-36|1014|0xffffff",90,100,50,616,1114} t['่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข']={0x111111, "0|0|0x111111,316|-1|0x111111,265|2|0xffffff,263|0|0xffffff,5|1|0xffffff,311|13|0x161616,309|13|0xffffff",90,8,56,353,108} t['่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข-ๅคดๅƒ']={0xbcbcbc, "0|0|0xbcbcbc,10|98|0x111111,10|104|0xffffff,10|114|0xcecece,-30|-34|0xbcbcbc",90,14,150,614,832} t['่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข-ๅคดๅƒ-้€‰ๆ‹ฉ็…ง็‰‡']={0x007aff, "0|0|0x007aff,-12|119|0x007aff",90,191,771,424,966} t['่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข-ๅคดๅƒ-ๆ‰€ๆœ‰็…ง็‰‡']={0xc4c4c6, "0|0|0xc4c4c6,-50|-138|0x007aff,-410|-24|0x000000",90,8,46,626,496} --ๅทฆ(56,188),ๅณ(588,1084) t['่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข-ไป˜ๆฌพไฟกๆฏ']={0x111111, "0|0|0x111111,10|-10|0x111111,16|-16|0xffffff,22|-18|0x111111,110|-18|0x171717,110|-16|0xfdfdfd,530|-14|0x191919",90,20,146,612,1016} t['่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข-ไป˜ๆฌพไฟกๆฏ-ๅทฒ็ป้€‰ๆ‹ฉ']={0xffffff, "0|0|0xffffff,0|-13|0x111111,8|8|0x111111",90,24,147,104,400} t['่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข-ไป˜ๆฌพไฟกๆฏ-้€‰ๆ‹ฉ']={0x00aaef, "0|0|0x00aaef,-6|148|0x00c800",90,25,143,369,402} t['่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข-้…้€ไฟกๆฏ']={0x191919, "0|0|0x191919,-534|-10|0x111111,-512|-8|0xffffff,-510|-8|0x151515,-416|4|0x111111,-418|-2|0xfdfdfd,-418|-4|0x171717",90,12,140,620,1002} t['่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข-้…้€ๅœฐๅ€้กต้ข']={0x111111, "0|0|0x111111,1|-2|0xffffff,5|15|0x212121,-90|6|0xffffff,-88|-8|0x161616,-339|1|0x111111",90,11,54,381,114} t['่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข-้…้€ๅœฐๅ€้กต้ข-ๅทฒ็ปๆœ‰ๅœฐๅ€']={0xffffff, "0|0|0xffffff,0|-8|0x111111,16|-1|0x111111,-13|-5|0x111111",90,20,135,110,291} t['่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข-้…้€ๅœฐๅ€้กต้ข-ๆ–ฐๅœฐๅ€']={0xffffff, "0|0|0xffffff,-274|6|0x111111,291|7|0x111111,47|-53|0x111111,275|-50|0xffffff,288|52|0xffffff",90,11,144,628,325} t['่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข-้…้€ๅœฐๅ€้กต้ข-ๆ–ฐๅœฐๅ€-ไธ‹ไธ€ๆญฅ']={0x111111, "0|0|0x111111,-10|0|0xffffff,-10|-11|0x111111,-10|10|0x111111",90,98,494,239,721} t['่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข-้…้€ๅœฐๅ€้กต้ข-ๆ–ฐๅœฐๅ€-ๅฎŒๆˆ']={0x111111, "0|0|0x111111,-449|8|0xededed,-546|9|0x111111",90,9,539,634,725} t['่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข-้…้€ๅœฐๅ€้กต้ข-ๆ–ฐๅœฐๅ€-ไฟๅญ˜']={0x111111, "0|0|0x111111,-1|15|0x111111,0|12|0xffffff,-276|21|0x111111,294|19|0x111111",90,9,939,611,1042} t['่ฎพ็ฝฎ-่ฟ”ๅ›ž<']={0x111111, "0|0|0x111111,9|0|0xffffff,10|-9|0x111111,10|11|0x111111",90,16,58,51,105} t['ๅผน็ช—-่พ“ๅ…ฅๅฎŒๆˆ']={0x007aff, "0|0|0x007aff,24|-10|0x007aff",90,532,447,639,1135} t['ๅผน็ช—-่พ“ๅ…ฅ>']={0x007aff, "0|0|0x007aff,0|-13|0xf0f1f2,-14|-13|0x007aff,15|-13|0x007aff",90,78,491,195,742} t['ๅผน็ช—-ไธ็ฌฆๅˆๆณจๅ†Œๆกไปถ']={0x363636, "0|0|0x363636,-307|349|0xffffff,-93|62|0x000000,1|2|0x363636,-533|353|0x000000,22|363|0x000000,-419|52|0x000000",90,8,140,625,583} --ๅค็™ป t['look-้ฆ–้กต-ๆฟ€ๆดป']={0x111111, "0|0|0x111111,24|-7|0xffffff,26|-8|0x111111,188|-11|0xcccccc,347|-8|0xcccccc,479|-10|0xcccccc",90,14,1038,621,1119} t['look-้ฆ–้กต-ๆฟ€ๆดป-ๅ–œๆฌขๅฟƒ']={0xf5f5f5, "0|0|0xf5f5f5,17|-4|0x111111,-17|-4|0x111111,0|16|0x111111,-65|18|0x171717,-65|10|0xf5f5f5,-65|0|0x111111",90,25,232,146,1018} t['look-้ฆ–้กต-ๆŒ‰ๅฐบ็ ็ญ›้€‰']={0x111111, "0|0|0x111111,5|0|0xfcfcfc,25|0|0x111111,17|15|0x111111,19|15|0xfcfcfc,25|16|0x111111,199|6|0x757575",90,14,67,265,107} t['look-้ž‹่ฏฆๆƒ…x']={0xfdfdfd, "0|0|0xfdfdfd,280|3|0x111111,-289|5|0x111111,238|-937|0xffffff,254|-935|0x595959",90,19,31,616,1108} t['look-้ฆ–้กตๆœชๆฟ€ๆดป']={0xcccccc, "0|0|0xcccccc,0|14|0xffffff,-14|14|0xcccccc,18|14|0xcccccc,17|10|0xffffff,21|-8|0xcccccc,0|-26|0xcccccc,0|-20|0xffffff,-20|-10|0xcccccc",90,10,1039,141,1121} t['look-ๅผ‚ๅธธ-ๆœ็ดขๅ–ๆถˆ']={0x484848, "0|0|0x484848,-5|0|0xffffff,13|46|0xe5e5e5,-494|8|0x111111",90,6,39,621,186} t['look-ๅผ‚ๅธธ-่ดญ็‰ฉๅๅฅฝ่ฎพ็ฝฎ']={0x111111, "0|0|0x111111,-19|6|0xffffff,-166|-897|0x111111,-167|-911|0xfafafa,-151|-912|0x111111,-166|-710|0xcccccc",90,11,59,626,1102} <file_sep>require("tsp") init(1) if not(t)then t={} degree = 90 end t['่ฝฆ']={0x005cb3, "0|0|0x005cb3,-30|11|0xffbd79",90,977,184,1332,345} t['้€ ่ฝฆ']={0x006a9d, "0|0|0x006a9d,-157|9|0x20aa10,-311|-16|0x0c83bd",90,752,167,1333,512} t['่ฎญ็ปƒ']={0x00c2fe, "0|0|0x00c2fe,-54|-8|0x1176bc,-314|7|0xffab00",90,581,532,1148,674} t['ๅŠ ้€Ÿ']={0xdfa30f, "0|0|0xdfa30f,144|-13|0x00699b,-137|-26|0x077bb2",90,664,164,1330,526} t['ๅŠ ้€Ÿ-ไฝฟ็”จ']={0x1274ba, "0|0|0x1274ba,-88|-20|0x00cffd,52|23|0x00aeeb",90,718,323,1169,465} t['ๅŠ ้€Ÿ-ไฝฟ็”จ-X']={0x1274ba, "0|0|0x1274ba,-20|-5|0x00c3ff,-54|-9|0xe1ebef",90,716,182,1164,464} t['ๅŠ ้€Ÿ-ไฝฟ็”จ-TOP']={0x1274ba, "0|0|0x1274ba,-46|-7|0x00c8ff,-13|-23|0x00d0f9",90,721,192,1156,332} t['้€ ๅ…ต-ๅ‡†ๅค‡่ฎญ็ปƒ']={0x0375ac, "0|0|0x0375ac,-151|16|0x1ba80e,-302|-15|0x128bc5",90,50,91,1310,705} t['้€ ๅ…ต-ๅ‡†ๅค‡่ฎญ็ปƒ']={0xd1e6e9, "0|0|0xd1e6e9,-102|7|0x6dd151,-239|-11|0xd9e7ee,-239|-4|0x26a3d8",90,102,261,1240,743} t['้€ ๅ…ต-ๅ‡†ๅค‡่ฎญ็ปƒ-ๅผ“ๆ‰‹']={0xe0ebef, "0|0|0xe0ebef,-5|11|0x57c2f2,-139|12|0xe5e8e1,-276|2|0xe4edf0",90,118,279,1272,735} t['้€ ๅ…ต-่ฎญ็ปƒ-ๅฏไปฅๅ‡็บง']={0x34bc00, "0|0|0x34bc00,12|-4|0xf2ff00",90,514,114,1029,167} t['้€ ๅ…ต-่ฎญ็ปƒ-ๅฏไปฅๅ‡็บง-้ป„่‰ฒ']={0xb56a00, "0|0|0xb56a00,-2|11|0xffd27f",90,186,142,282,222} t['้€ ๅ…ต-่ฎญ็ปƒ'] = { 0xfafeff,"20|-28|0xcffe,-92|-14|0xc5ff",degree,914,574,1137,659} t['้€ ๅ…ต-ๅŠ ้€Ÿ'] = { 0xd3d1c9,"-151|515|0x1176bc,-232|500|0xd1ff,-38|545|0xb6f3",degree,858,58,1365,680} t['้€ ๅ…ต-ๅ‡†ๅค‡่ฎญ็ปƒ-ๅ…ณ้—ญ']={0x245aa0, "0|0|0x245aa0,-90|-13|0x0fa2e0,107|-12|0x0fa1e0,142|8|0x002b4d",90,49,202,1323,648} t['้€ ๅ…ต-ๅ‡†ๅค‡่ฎญ็ปƒ-ๅ…ณ้—ญ']={0xd3d1c9, "0|0|0xd3d1c9,-162|523|0x00c2ff,-479|522|0xffb000",90,570,67,1166,656} t['้€ ๅ…ต-้ช‘ๅ…ตๅทฅๅŽ‚']={0x1f6198, "0|0|0x1f6198,-4|-3|0xa8553c,-21|22|0xfdd274,-19|26|0x18557d",90,323,6,583,208} t['้€ ๅ…ต-ๅผ“ๅ…ตๅทฅๅŽ‚']={0x0b56ff, "0|0|0x0b56ff,11|16|0xbf9d85,-4|4|0xfda92b,-9|1|0x0a34b1",90,798,47,1005,367} t['้€ ๅ…ต-่ฝฆๅ…ตๅทฅๅŽ‚']={0xffe290, "0|0|0xffe290,22|6|0x0063be,44|6|0xfefcd9,-31|-12|0x00549d,-28|-1|0xffa86d",90,20,159,1317,750} t['้€ ๅ…ต-่ฝฆๅ…ตๅทฅๅŽ‚-่ฝฆ']={0x005cb3, "0|0|0x005cb3,-30|11|0xffbd79",90,977,184,1332,345} t['้€ ๅ…ต-่ฝฆๅ…ตๅทฅๅŽ‚-่ฝฆ-็™ฝๅคฉ']={0x005eb2, "0|0|0x005eb2,-30|2|0xfebf7a",90,910,176,1329,583} t['้€ ๅ…ต-่ฝฆๅ…ตๅทฅๅŽ‚-่ฝฆ-ๅคœ้‡Œ']={0x2048c0, "0|0|0x2048c0,-6|3|0x0a2260",90,962,162,1327,444} t['้€ ๅ…ต-่ฝฆๅ…ตๅทฅๅŽ‚-่ฝฆ-ๆญฃๅœจ็”Ÿไบง']={0xe0a00c, "0|0|0xe0a00c,3|-24|0xf3f1f0,123|-9|0x026698,-142|-22|0x0876ab",90,858,223,1333,655} t['้€ ๅ…ต-่ต„ๆบไธ่ถณ']={0x00c2fe, "0|0|0x00c2fe,384|-383|0xd2d0ca,-13|-382|0x858278,47|-237|0x055171",90,459,79,1102,633} t['้€ ๅ…ต-่ต„ๆบไธ่ถณ-ไฝฟ็”จ']={0x1274ba, "0|0|0x1274ba,7|-20|0x00cefc,20|22|0x01a4e4",90,908,162,1136,471} t['้€ ๅ…ต-่ต„ๆบไธ่ถณ-ไฝฟ็”จ*']={0x1274ba, "0|0|0x1274ba,1|13|0x009edf",90,745,175,912,652} t['้€ ๅ…ต-่ต„ๆบไธ่ถณ-ไฝฟ็”จ-X']={0xd3d2cb, "0|0|0xd3d2cb,-7|-8|0xd8d7ce,-54|21|0xbdbdad,-57|46|0x044a68",90,1026,34,1216,160} t['่”็›Ÿ-ๅ…ณ้—ญ']={0x6ae4ff, "0|0|0x6ae4ff,-99|7|0x6de4ff,-313|8|0x74e5ff,-417|7|0x014874",90,761,660,1327,738} t['้€ ๅ…ต-ๅŠ ้€Ÿ']={0xe0a20e, "0|0|0xe0a20e,1|-45|0xf2ede3,-121|-31|0x0f8ac1,141|-83|0xeff0eb",90,294,203,1295,735} function _soldier() log("<--้€ ๅ…ต-->") local ๅ…ต็ง_ = { ["ๆญฅๅ…ต"]={ 571, 477, 0xecc3a7}, ["ๅผ“ๅ…ต"]={ 338, 516, 0xf4caaa}, ["้ช‘ๅ…ต"]={ 923, 554, 0xfed7b5}, ["่ฝฆๅ…ต"]={ 1066, 435, 0xffbf80} } d("่”็›Ÿ-ๅ…ณ้—ญ",true) k = 'ๆญฅๅ…ต' k = 'ๅผ“ๅ…ต' k = '้ช‘ๅ…ต' -- k = '่ฝฆๅ…ต' v = ๅ…ต็ง_[k] log('ๅ‡†ๅค‡้€ ->'..k ) click( v[1],v[2],1) if not ( d('้€ ๅ…ต-ๅ‡†ๅค‡่ฎญ็ปƒ') or d("้€ ๅ…ต-ๅ‡†ๅค‡่ฎญ็ปƒ-ๅผ“ๆ‰‹") ) then click( v[1],v[2],1) d('้€ ๅ…ต-ๅ‡†ๅค‡่ฎญ็ปƒ',true,1,1) d("้€ ๅ…ต-ๅ‡†ๅค‡่ฎญ็ปƒ-ๅผ“ๆ‰‹",true) else if d('้€ ๅ…ต-ๅ‡†ๅค‡่ฎญ็ปƒ',true,1,2) or d("้€ ๅ…ต-ๅ‡†ๅค‡่ฎญ็ปƒ-ๅผ“ๆ‰‹",true) then end end -- if k == "่ฝฆๅ…ต" then -- click(657,183) -- elseif d("้€ ๅ…ต-่ฎญ็ปƒ-ๅฏไปฅๅ‡็บง",true,1,1) and d( "้€ ๅ…ต-่ฎญ็ปƒ-ๅฏไปฅๅ‡็บง-้ป„่‰ฒ",true,1,2 ) then -- log("ๆŠŠๅžƒๅœพๅ…ตๅ‡็บง") -- end if d('้€ ๅ…ต-่ฎญ็ปƒ',true,1,2) or d('้€ ๅ…ต-ๅŠ ้€Ÿ',true,1,2) then if d('้€ ๅ…ต-่ต„ๆบไธ่ถณ',true,1,2) then d('้€ ๅ…ต-่ต„ๆบไธ่ถณ-ไฝฟ็”จ',true,1,2) d('้€ ๅ…ต-่ต„ๆบไธ่ถณ-ไฝฟ็”จ*',true,1,2) d('้€ ๅ…ต-่ต„ๆบไธ่ถณ-ไฝฟ็”จ-X',true,1,2) d('้€ ๅ…ต-่ฎญ็ปƒ',true,1,2) end else d("้€ ๅ…ต-ๅ‡†ๅค‡่ฎญ็ปƒ-ๅ…ณ้—ญ",true) end click( v[1],v[2],1) d("้€ ๅ…ต-ๅŠ ้€Ÿ",true) d('ๅŠ ้€Ÿ-ไฝฟ็”จ',1,1) d('ๅŠ ้€Ÿ-ไฝฟ็”จ-X',1,1) d('ๅŠ ้€Ÿ-ไฝฟ็”จ-TOP',1,1) d('ๅŠ ้€Ÿ-ไฝฟ็”จ-X',1,1) d('ๅŠ ้€Ÿ-ไฝฟ็”จ-TOP',1,1) end for i=1,50 do _soldier() end <file_sep>-- ๆๅ–้“พๆŽฅ -- main.lua -- Create By TouchSpriteStudio on 22:54:13 -- Copyright ยฉ TouchSpriteStudio . All rights reserved. require('tsp') urlarr = {{"https://v.douyin.com/XnbKXx/"}, {"https://v.douyin.com/XnVh97/"}, {"https://v.douyin.com/Xn4Mqo/"}, {"https://v.douyin.com/Xn4d2W/"}, {"https://v.douyin.com/XnKpSt/"}, {"https://v.douyin.com/Xn31uQ/"}, {"https://v.douyin.com/XWfFDV/"}, {"https://v.douyin.com/XWjpUC/"}, {"https://v.douyin.com/XWddnH/"}, {"https://v.douyin.com/X7Ny9W/"}, {"https://v.douyin.com/XWkMJE/"}, {"https://v.douyin.com/Xnc5Cj/"}, {"https://v.douyin.com/XWP7Rg/"}, {"https://v.douyin.com/Xn4xgy/"}, {"https://v.douyin.com/XnEqEo/"}, {"https://v.douyin.com/Xnqy4f/"}, {"https://v.douyin.com/XWk24a/"}, {"https://v.douyin.com/XWSJ2R/"}, {"https://v.douyin.com/XWaGsG/"}, {"https://v.douyin.com/XW6fL1/"}, {"https://v.douyin.com/Xn3TRo/"}, {"https://v.douyin.com/X7UBnQ/"}, {"https://v.douyin.com/X7JYyu/"}, {"https://v.douyin.com/X769p7/"}, {"https://v.douyin.com/X7RubL/"}, {"https://v.douyin.com/X7dSCa/"}, {"https://v.douyin.com/X7Y5rr/"}, {"https://v.douyin.com/X7Rf6x/"}, {"https://v.douyin.com/X78LWR/"}, {"https://v.douyin.com/X7Fjwe/"}, {"https://v.douyin.com/X7Ba31/"}, {"https://v.douyin.com/X7jHor/"}, {"https://v.douyin.com/X7yMr4/"}, {"https://v.douyin.com/X78Msg/"}, {"https://v.douyin.com/X7Fq2Y/"}, {"https://v.douyin.com/X7Yen4/"}, {"https://v.douyin.com/X72SFp/"}, {"https://v.douyin.com/X7UQPt/"}, {"https://v.douyin.com/XWoE2D/"}, {"https://v.douyin.com/XWoMMf/"}, {"https://v.douyin.com/X72N6U/"}, {"https://v.douyin.com/X7RJm9/"}, {"https://v.douyin.com/X7AMNH/"}, {"https://v.douyin.com/X7d4TG/"}, {"https://v.douyin.com/X76oo7/"}, {"https://v.douyin.com/XWEQTF/"}, {"https://v.douyin.com/X7DxC1/"}, {"https://v.douyin.com/X7FLw8/"}, {"https://v.douyin.com/X7Jyfa/"}, {"https://v.douyin.com/XWoqyp/"}, {"https://v.douyin.com/X7Nhjt/"}, {"https://v.douyin.com/XWoDaU/"}, {"https://v.douyin.com/X71LKL/"}, {"https://v.douyin.com/X7MWoL/"}, {"https://v.douyin.com/X7h2Jc/"}, {"https://v.douyin.com/X7FR4f/"}, {"https://v.douyin.com/X7rswS/"}, {"https://v.douyin.com/X7FaGQ/"}, {"https://v.douyin.com/X7SRuD/"}, {"https://v.douyin.com/X7AtWW/"}, {"https://v.douyin.com/X7NgV6/"}, {"https://v.douyin.com/X7UBqA/"}, {"https://v.douyin.com/X7Fgem/"}, {"https://v.douyin.com/X7Ff3V/"}, {"https://v.douyin.com/X7DeQ2/"}, {"https://v.douyin.com/X7YS1q/"}, {"https://v.douyin.com/X78wcX/"}, {"https://v.douyin.com/XWEJ3r/"}, {"https://v.douyin.com/X7Rkxd/"}, {"https://v.douyin.com/X7e8eN/"}, {"https://v.douyin.com/X7Uprq/"}, {"https://v.douyin.com/X78KXA/"}, {"https://v.douyin.com/X7JcAn/"}, {"https://v.douyin.com/X7Loqg/"}, {"https://v.douyin.com/X7j68y/"}, {"https://v.douyin.com/X7SoSb/"}, {"https://v.douyin.com/X7NkSN/"}, {"https://v.douyin.com/X78e8M/"}, {"https://v.douyin.com/X7Ns7L/"}, {"https://v.douyin.com/X7ULGJ/"}, {"https://v.douyin.com/X7dRhQ/"}, {"https://v.douyin.com/X7AnM6/"}, {"https://v.douyin.com/X7DfVt/"}, {"https://v.douyin.com/X7Drpd/"}, {"https://v.douyin.com/X722FG/"}, {"https://v.douyin.com/X7hBdd/"}, {"https://v.douyin.com/X7MwaL/"}, {"https://v.douyin.com/X7DJKY/"}, {"https://v.douyin.com/X7DuWg/"}, {"https://v.douyin.com/X7yM36/"}, {"https://v.douyin.com/X7Fe1p/"}, {"https://v.douyin.com/X7BpN8/"}, {"https://v.douyin.com/X76u5o/"}, {"https://v.douyin.com/X71a7L/"}, {"https://v.douyin.com/X7NXHQ/"}, {"https://v.douyin.com/X7eGTD/"}, {"https://v.douyin.com/X7YfQ6/"}, {"https://v.douyin.com/X7LFyo/"}, {"https://v.douyin.com/X7yFF1/"}, {"https://v.douyin.com/X7JqEN/"}, {"https://v.douyin.com/XntDv5/"}, {"https://v.douyin.com/Xn3Usp/"}, {"https://v.douyin.com/XnGxYv/"}, {"https://v.douyin.com/XnQNdf/"}, {"https://v.douyin.com/XnCV1p/"}, {"https://v.douyin.com/XnK9sa/"}, {"https://v.douyin.com/XnVHGV/"}, {"https://v.douyin.com/Xnw6cT/"}, {"https://v.douyin.com/XnTrpv/"}, {"https://v.douyin.com/X8DBbY/"}, {"https://v.douyin.com/XnGEro/"}, {"https://v.douyin.com/XW16Qy/"}, {"https://v.douyin.com/XnsR8M/"}, {"https://v.douyin.com/XnsoHA/"}, {"https://v.douyin.com/XnWUUQ/"}, {"https://v.douyin.com/Xnbcmu/"}, {"https://v.douyin.com/XnQt6V/"}, {"https://v.douyin.com/Xnc79A/"}, {"https://v.douyin.com/Xn4aXy/"}, {"https://v.douyin.com/XWr4SV/"}, {"https://v.douyin.com/Xn7R82/"}, {"https://v.douyin.com/XnVu1j/"}, {"https://v.douyin.com/XnVXR5/"}, {"https://v.douyin.com/XnsPFD/"}, {"https://v.douyin.com/Xncfra/"}, {"https://v.douyin.com/XnoAAB/"}, {"https://v.douyin.com/XWJRNy/"}, {"https://v.douyin.com/XnbXM6/"}, {"https://v.douyin.com/Xn39oD/"}, {"https://v.douyin.com/XnwXvd/"}, {"https://v.douyin.com/XnTut6/"}, {"https://v.douyin.com/XnsPNt/"}, {"https://v.douyin.com/XnTuAK/"}, {"https://v.douyin.com/XncFJK/"}, {"https://v.douyin.com/Xntmcm/"}, {"https://v.douyin.com/XnEJkd/"}, {"https://v.douyin.com/XngwHK/"}, {"https://v.douyin.com/Xnwpkp/"}, {"https://v.douyin.com/Xnb7g2/"}, {"https://v.douyin.com/XnWCdS/"}, {"https://v.douyin.com/XWeQYV/"}, {"https://v.douyin.com/XW5cJE/"}, {"https://v.douyin.com/XWMqme/"}, {"https://v.douyin.com/XW2dBm/"}, {"https://v.douyin.com/XWjNpm/"}, {"https://v.douyin.com/XWNTvq/"}, {"https://v.douyin.com/XWL1PW/"}, {"https://v.douyin.com/XWf8oh/"}, {"https://v.douyin.com/XWrBJ8/"}, {"https://v.douyin.com/XWSGXq/"}, {"https://v.douyin.com/XWP38t/"}, {"https://v.douyin.com/XWdTcp/"}, {"https://v.douyin.com/XWeUkF/"}, {"https://v.douyin.com/XWjJTd/"}, {"https://v.douyin.com/XWh89C/"}, {"https://v.douyin.com/XWkUHt/"}, {"https://v.douyin.com/XWLBAv/"}, {"https://v.douyin.com/XWhQRP/"}, {"https://v.douyin.com/XWUhc8/"}, {"https://v.douyin.com/XWRRdP/"}, {"https://v.douyin.com/XWrYvm/"}, {"https://v.douyin.com/XWmSpb/"}, {"https://v.douyin.com/XWyqth/"}, {"https://v.douyin.com/XW2FjV/"}, {"https://v.douyin.com/XW2QwK/"}, {"https://v.douyin.com/XWFaEu/"}, {"https://v.douyin.com/XWSXvP/"}, {"https://v.douyin.com/XW88N9/"}, {"https://v.douyin.com/XW8Jmr/"}, {"https://v.douyin.com/XWfB3o/"}, {"https://v.douyin.com/XWPvkc/"}, {"https://v.douyin.com/XW2URQ/"}, {"https://v.douyin.com/XWjDHt/"}, {"https://v.douyin.com/XWYdDH/"}, {"https://v.douyin.com/XWLoqF/"}, {"https://v.douyin.com/XWPdG2/"}, {"https://v.douyin.com/XWUyFb/"}, {"https://v.douyin.com/XWeku5/"}, {"https://v.douyin.com/XWeqhm/"}, {"https://v.douyin.com/XWhvgr/"}, {"https://v.douyin.com/XWU7x3/"}, {"https://v.douyin.com/XnVutK/"}, {"https://v.douyin.com/XWPt88/"}, {"https://v.douyin.com/Xng3Vx/"}, {"https://v.douyin.com/XWBvUy/"}, {"https://v.douyin.com/XWdnpX/"}, {"https://v.douyin.com/XncgMw/"}, {"https://v.douyin.com/XnEora/"}, {"https://v.douyin.com/XntdLN/"}, {"https://v.douyin.com/X7LNuE/"}, {"https://v.douyin.com/XFeBCo/"}, {"https://v.douyin.com/XWYvcM/"}, {"https://v.douyin.com/XFda1M/"}, {"https://v.douyin.com/XnKNxE/"}, {"https://v.douyin.com/XWacUT/"}, {"https://v.douyin.com/XWRYTL/"}, {"https://v.douyin.com/XNwHRh/"}, {"https://v.douyin.com/XF2RoP/"}, {"https://v.douyin.com/XWyVGf/"}, {"https://v.douyin.com/XFdqrk/"}, } nike ={} nike.login = '<EMAIL>' nike.pwd = '<PASSWORD>' inputText(nike.pwd) <file_sep> require("TSLib") require('tsp') if not(t)then t={} end if not(UIv) then var = {} var.bid = 'com.nike.onenikecommerce' UIv = {} UIv.again = 0 UIv.note = 'wen' UIv.look_min_time = 90 UIv.look_max_time = 150 end function snkrs_look() local timeline = os.time() local outTimes = math.random( UIv.look_min_time+0 ,UIv.look_max_time+0 ) local ็œ‹้ž‹ๅ‘ไธ‹ๆป‘ๅŠจ่ฎกๆ•ฐ = 0 local ้ž‹่ฏฆๆƒ…ไธ‹ๆป‘่ฎกๆ•ฐ = 0 local setp_ = '' local setp__ = "" local setp___ = 0 updateNikeLog('ๆต่งˆใ€Œ SNKRS ใ€') delay(1) local ๆ‘˜่ฆ็ƒญๅ– = {{59, 82, 0xffffff},{168, 81, 0xe9e9e9},{295, 83, 0xffffff}} while (os.time()-timeline < outTimes) do if active(var.bid,3) then if ( d('look-้ฆ–้กต-ๆฟ€ๆดป') ) then setp_ = '้ฆ–้กต-ๆฟ€ๆดป' ็œ‹้ž‹ๅ‘ไธ‹ๆป‘ๅŠจ่ฎกๆ•ฐ = 0 click(ๆ‘˜่ฆ็ƒญๅ–[rd(1,2)][1],ๆ‘˜่ฆ็ƒญๅ–[1][2],2) moveTo(300,800,300,800-rd(200,400),rd(20,30)) --ไปŽไธ‹ๅ‘ไธŠๆป‘ๅŠจ elseif d('look-้ฆ–้กต-ๆŒ‰ๅฐบ็ ็ญ›้€‰') then setp_ = '้ฆ–้กต-ๆŒ‰ๅฐบ็ ็ญ›้€‰' ็œ‹้ž‹ๅ‘ไธ‹ๆป‘ๅŠจ่ฎกๆ•ฐ = ็œ‹้ž‹ๅ‘ไธ‹ๆป‘ๅŠจ่ฎกๆ•ฐ + 1 if ( ็œ‹้ž‹ๅ‘ไธ‹ๆป‘ๅŠจ่ฎกๆ•ฐ > rd(6,10) ) then moveTo(300,500,300,500+rd(200,400),rd(20,30)) --ๅ‘ไธ‹ๆป‘ๅŠจ else moveTo(300,800,300,800-rd(200,400),rd(20,30)) --ๅ‘ไธŠๆป‘ๅŠจ if rd(1,100)>50 then d('look-้ฆ–้กต-ๆฟ€ๆดป-ๅ–œๆฌขๅฟƒ',true,1,2) end if rd(1,100) > 50 then log('ๅ‡†ๅค‡็œ‹่ฏฆๆƒ…') click(rd(88,651),rd(187,946),2) ้ž‹่ฏฆๆƒ…ไธ‹ๆป‘่ฎกๆ•ฐ = 0 end end elseif d('look-้ž‹่ฏฆๆƒ…x') then setp_ = '้ž‹่ฏฆๆƒ…' ้ž‹่ฏฆๆƒ…ไธ‹ๆป‘่ฎกๆ•ฐ = ้ž‹่ฏฆๆƒ…ไธ‹ๆป‘่ฎกๆ•ฐ + 1 moveTo(300,800,300,800-rd(200,400),rd(20,30)) --ๅ‘ไธŠๆป‘ๅŠจ if rd(1,100) > 90 then d('look-้ž‹่ฏฆๆƒ…x',true) elseif ้ž‹่ฏฆๆƒ…ไธ‹ๆป‘่ฎกๆ•ฐ > rd(5,8) then d('look-้ž‹่ฏฆๆƒ…x',true) end elseif d('look-ๅผ‚ๅธธ-่ดญ็‰ฉๅๅฅฝ่ฎพ็ฝฎ',true)then setp_ = '่ดญ็‰ฉๅๅฅฝ่ฎพ็ฝฎ' elseif d('look-้ฆ–้กตๆœชๆฟ€ๆดป',true)then setp_ = '้ฆ–้กตๆœชๆฟ€ๆดป' else setp_ = 'ๅ…ถๅฎƒ' moveTo(300,500,300,500+rd(200,400),rd(20,30)) --ๅ‘ไธ‹ๆป‘ๅŠจ end --ๅผ€ๅง‹ๆŸฅ็œ‹่ฎพ็ฝฎ้กต้ข if setp_ == setp__ then setp___ = setp___ + 1 else setp__ = setp_ end --ๅฏน่ถ…ๆ—ถ่ฟ›่กŒ่ฎพ็ฝฎ if setp___ >= 30 then click(672, 106) closeApp(frontAppBid(),1) setp___ = 0 end delay(rd(1,2)) --ๆ˜พ็คบๆ—ฅๅฟ— updateNikeLog(setp_.."->"..setp___) log('look->'..os.time()-timeline) end end -- body get("http://127.0.0.1:8080/api/reportInfo"); backId() return true end -- get_account() -- 0,0,200,100 <file_sep>require('tsp') -- require('AWZ') -- require('ZZBase64') -- require("yzm") -- require('api') -- require('token') init(0) -- t={} -- t['ๅผน็ช—-ๅ…ต่ฅ่ฏฆๆƒ…-x']={0xd3d1ca, "0|0|0xd3d1ca,0|34|0x04445f,-44|3|0xbdbbae",90,996,45,1201,149} -- t['ๅคด่ก”-ๅคด่ก”ๅ† ']={0x995300, "0|0|0x995300,-12|-6|0xffa800,402|2|0x42c6ee",90,23,91,1273,622} -- d("ๅคด่ก”-ๅคด่ก”ๅ† ",true,1,2) -- input("Ax112211") -- input("<EMAIL>") sys = { clear_bid = (function(bid) closeApp(bid) delay(1) os.execute("rm -rf "..(appDataPath(bid)).."/Documents/*") --Documents os.execute("rm -rf "..(appDataPath(bid)).."/Library/*") --Library os.execute("rm -rf "..(appDataPath(bid)).."/tmp/*") --tmp clearPasteboard() --[[ local path = _G.const.cur_resDir os.execute( table.concat( { string.format("mkdir -p %s/keychain", path), 'killall -SIGSTOP SpringBoard', "cp -f -r /private/var/Keychains/keychain-2.db " .. path .. "/keychain/keychain-2.db", "cp -f -r /private/var/Keychains/keychain-2.db-shm " .. path .. "/keychain/keychain-2.db-shm", "cp -f -r /private/var/Keychains/keychain-2.db-wal " .. path .. "/keychain/keychain-2.db-wal", 'killall -SIGCONT SpringBoard', }, '\n' ) ) ]] clearAllKeyChains() clearIDFAV() --clearCookies() end) } -- sys.clear_bid("com.lilithgames.rok.ios.offical") -- log( readPasteboard() ) -- input("3625858761") input("172.16.31.10") click(684,1293) input("1080") click(684,1293) input("a3621d4f-0fda-4109-8db2-8b59a565892e") click(684,1293) input("่ดขไปฃไป˜") -- log( appDataPath("com.saurik.Cydia") ) <file_sep>-- ้ชŒ่ฏ็ ่ฏ†ๅˆซ -- main.lua -- Create By TouchSpriteStudio on 00:17:50 -- Copyright ยฉ TouchSpriteStudio . All rights reserved. function _yzmsb() require('tsp') init(1) local _time1 = os.time() url = 'http://api.ttshitu.com/imageXYPlus' postData = {} postData['username'] = 'ouwen000' postData['password'] = '<PASSWORD>' postData['typeid'] = '20' --postData['typename'] = 'ไธ‡ๅ›ฝ่ง‰้†’' snapshot("yzm.jpg", 400,21,934,640); path = userPath(); ts = require('ts') ts.imgSize(path.."/res/yzm.jpg",path.."/res/yzm2.jpg",259,300); imagepath = path .. "/res/yzm2.jpg" require("ZZBase64") function base64s() local files local file = io.open(imagepath,"rb") if file then files = file:read("*a") file:close() return ZZBase64.encode(files); else return ""; end end postData['image'] = base64s() local imgRes = post(url,postData) log(os.time()-_time1); if imgRes.message == 'success' then log('้ชŒ่ฏ็ ็ป“ๆžœไธบ๏ผš'..imgRes.data.result ) local _clickArr = strSplit(imgRes.data.result,"|"); for i,v in ipairs(_clickArr) do _clickArr[i]= strSplit(v,","); click(_clickArr[i][1]*2+400,_clickArr[i][2]*2+21) end log(_clickArr) return true end end <file_sep>-- nike -- Function.lua -- Create By TouchSpriteStudio on 18:09:27 -- Copyright ยฉ TouchSpriteStudio . All rights reserved. function stringRandom(str,num,offset) offset = offset or 1 local len = string.len(str)/offset local strRandom = "" for i = 1,num do local index = math.random(1,string.len(str)/offset) local char = string.sub(str, index, index+offset-1) strRandom = strRandom..char end return strRandom end function DMGetPhone() local url = 'http://api.duomi01.com/api?action=getPhone' local par = "&token=<PASSWORD>&sid=11256" while true do local code, header, body = http.tsget(url..par) if code == 200 then local b = string.split(body,"|") local status = b[1] local msg = b[2] --pid local location = b[3] if status == "1" then return msg,location else if msg then sleepLong(10,"[DMGetPhone] err:"..msg) end end else Showlog("[DMGetPhone] err code:"..code) end sys.msleep(2000) end end function DMGetMsg(phone) --่Žทๅ–ๆ‰‹ๆœบ็Ÿญไฟก --sid=้กน็›ฎid&phone=ๅ–ๅ‡บๆฅ็š„ๆ‰‹ๆœบๅท&token=็™ปๅฝ•ๆ—ถ่ฟ”ๅ›ž็š„ไปค็‰Œ&author=่ฝฏไปถไฝœ่€… ็”จๆˆทๅ(่ฟ™้‡Œๆ˜ฏไผ ไฝœ่€…ๆณจๅ†Œๆ—ถ็š„็”จๆˆทๅ)ใ€‚ local url = "http://api.duomi01.com/api?action=getMessage" local par = "&token=<PASSWORD>&sid=11256&phone="..phone.."&author=huhai123" while true do local code, header, body = http.tsget(url..par) if code == 200 then local b = string.split(body,"|") local status = b[1] local msg = b[2] if status == "1" then if string.find(msg,"ๆ‰‹ๆœบ้ชŒ่ฏ็ ๆ˜ฏ")~=nil then msg = string.match(msg,".-ๆ‰‹ๆœบ้ชŒ่ฏ็ ๆ˜ฏ.-(%d+).-") end return msg else if msg then sleepLong(5,"[DMGetMsg] err:"..msg) end return "" end else Showlog("[DMGetMsg] err code:"..code) end sys.msleep(5000) end end function sleepLong(sleep,why) --้•ฟๅปถ่ฟŸ ๅ•ไฝ็ง’ for i=1, sleep do Showlog("wait "..i.."/"..math.floor( sleep).." err:"..why) sys.msleep(1000) end end function Showlog(strs, is_msg,is_alert,is_err) -- ๆ‰“ๅฐไฟกๆฏ if strs ==nil then return end is_msg = is_msg or true; is_alert = is_alert or false; is_err = is_err or false; strs = mlog(strs) if is_msg == true then sys.toast(strs) end if is_alert == true then sys.alert(strs,2) end if is_err == true then local errMsg = '+++ใ€ไธฅ้‡้”™่ฏฏใ€‘+++ \r\n +++ใ€ไธฅ้‡้”™่ฏฏใ€‘+++ \r\n +++ใ€ไธฅ้‡้”™่ฏฏใ€‘+++ \r\n +++ใ€ไธฅ้‡้”™่ฏฏใ€‘+++ \r\n +++ใ€ไธฅ้‡้”™่ฏฏใ€‘+++ \r\n' dialog(errMsg..strs) lua_exit() end local logPath = userPath().."/log/่„šๆœฌๆ—ฅๅฟ—.log" local logs = readFileString(logPath) if type(logs) == "string" then if #logs>=5000 then writeFileString(logPath,"",'w',1) end end strs= '['..os.date("%H:%M:%S", os.time()).."]:"..strs writeFileString(logPath,strs,'a',1) end ------ๆ‰“ๅฐ---- function PrintTable(table , level,key) level = level or 1 key = key or "" local str = "" local function getindent(l) local indent = "" for i = 1, l do indent = indent.."\t" end return indent end if key ~= "" then str = str..getindent(level-1)..'['..key..']'.." ".."=".." ".."{ --table \n" else str = str..getindent(level-1) .. "{ --table \n" end for k,v in pairs(table) do if type(v) == "table" then key = k str = str..PrintTable(v, level + 1,key).."\n" else local sk = "" if type(k) == "string" then sk = '["'..k..'"]' end if type(k) == "number" then sk = '['..k..']' end if type(v) == "string" then sv = '"'..v..'"' else sv = tostring(v) end local content = string.format("%s%s = %s,", getindent(level),tostring(sk), tostring(sv)) str = str..content.."\n" end end if level == 1 then str = str..getindent(level-1) .. "}" else str = str..getindent(level-1) .. "}," end return str end function mlog(...) local args = {...} local ret = "" for i=1,#args do local logs = "" if type(args[i]) == "table" then logs= PrintTable(args[i]) elseif type(args[i]) == "string" then logs = tostring(args[i]) if tostring(args[i]) == "nil" then logs = "nil" end if tostring(args[i]) == "" then logs = "็ฉบ" end elseif type(args[i]) == "number" then logs = tostring(args[i]) elseif type(args[i]) == "boolean" then logs = tostring(args[i]) else logs = "ไธๆ”ฏๆŒ็š„ๆ‰“ๅฐ็ฑปๅž‹ ".. tostring(type(args[i])) end ret = ret == '' and logs or ret..'\t'..logs end return ret end function nlog(...) local arg = ... local logs = mlog(arg) nLog(logs) end function Dialog(...) local arg = ... local logs = mlog(arg) dialog(logs) end function initWebView() local width,height = getScreenSize(); fwShowWnd("wid",0,height-300,width, height-100,0); --ๅผ€ๅฏไธ€ไธชๆตฎๅŠจ็ช—ไฝ“ showWebview("ๆธ…็†ๅžƒๅœพ") os.execute('cd /var/mobile/Library/Preferences/ && find . -name "*.plist.*" | xargs rm -r') os.execute('cd /private/var/root/Library/Preferences/ && find . -name "*.plist.*" | xargs rm -r') os.execute('rm -rf /private/var/log/*') os.execute('rm -rf /private/var/logs/*') --fwShowButton("wid","btn1","ๆš‚ๅœ/็ปง็ปญ่„šๆœฌ","000000","B0C4DE",nil,13,0,220,190,280); --fwShowButton("wid","btn2","ๅœๆญข่„šๆœฌ","000000","B0C4DE",nil,13,width-200,220,width-10,280); end function showWebview(title,arg1) --ๆ˜พ็คบไธ€ไธชweb็ช—ไฝ“ title = title or "" arg1 = arg1 or "" local color = 'FFFFFF' if string.find(title,"็งไฟก") ~=nil then color = 'B23AEE' elseif string.find(title,"็ˆฌ") ~=nil then color = '1E90FF' elseif string.find(title,"ๆณจๅ†Œ") ~=nil then color = '228B22' elseif string.find(title,"ๅˆท่ตž") ~=nil then color = 'B03060' elseif string.find(title,"็‚ธ") ~= nil then color = 'FF4500' end Showlog(title..","..arg1) local tab = fwGetWndPos("wid"); if tab then local width,height = getScreenSize(); if tab.ret == 0 then fwShowWnd("wid",0,height-300,width, height-100,0) end fwShowTextView("wid","textid1",title,"center","000000",color,30,1,0,0,width/2.5,200,1) fwShowTextView("wid","textid2",arg1,"left","FFFFFF","000000",20,1,width/2.5+20,0,width,200,1) end end -----่ฟ˜ๅŽŸๆธ…็† function backupInfo() --ๅค‡ไปฝๆ•ฐๆฎ local path_cookies = _appDataPath.."/Library/Cookies/Cookies.binarycookies" local path_ugcPlist = _appDataPath..'/Library/Preferences/com.nike.onenikecommerce.plist' local path_keychain = "/var/mobile/Media/nike_keychian.plist" os.execute("rm -rf "..path_keychain) local ugcPlist,cookies,keychain if file.exists(path_cookies)then cookies = file.reads(path_cookies):base64_encode() end if file.exists(path_ugcPlist) then ugcPlist = file.reads(path_ugcPlist):base64_encode() end while true do Showlog("keychain backup") os.execute('keychain -ghost -p '..path_keychain..' -g com.nike') if file.exists(path_keychain) then keychain = file.reads(path_keychain):base64_encode() break end mSleep(1000) end return ugcPlist,cookies,keychain end function ReductionDataInfo(accounts) --่ฟ˜ๅŽŸๆ•ฐๆฎ clearFile() accounts.cookies = accounts.cookies or "" accounts.plist = accounts.plist or "" accounts.keychain = accounts.keychain or "" local path_ugcPlist = _appDataPath..'/Library/Preferences/com.ss.iphone.ugc.Aweme.plist' local path_cookies = _appDataPath.."/Library/Cookies/Cookies.binarycookies" local path_keychain = "/var/mobile/Media/nike_keychian.plist" os.execute("rm -rf "..path_cookies) os.execute("mkdir -p ".._appDataPath.."/Library/Cookies/") os.execute("mkdir -p ".._appDataPath.."/Library/Preferences/") if accounts.plist ~= "" then Showlog("[ReductionDataInfo] ugcPlist") file.writes(path_ugcPlist,accounts.plist:base64_decode(),"w+") end if accounts.cookies ~= "" then Showlog("[ReductionDataInfo] cookies") file.writes(path_cookies,accounts.cookies:base64_decode(),"w+") end os.execute("chown mobile "..path_cookies) os.execute("chmod 0644 "..path_cookies) os.execute("chown mobile "..path_ugcPlist) os.execute("chmod 0644 "..path_ugcPlist) --keychianๆขๅค if accounts.keychain ~="" then Showlog("[ReductionDataInfo] keychain") file.writes(path_keychain,accounts.keychain:base64_decode(),"w+") while true do local script='keychain -recover -p '..path_keychain..' -g com.nike' local p = io.popen(script) for v in p:lines() do if string.find(v,"ADD KEYCHAIN SUCCESS") ~=nil then return true end end mSleep(1000) end else Showlog("keychain is nil",true,false,true) end end function clearFile() closeApp(_appBid,1) local dataPath =app.data_path(_appBid) if dataPath == nil then return end os.execute('rm -rf '..dataPath..'/Documents/*') os.execute('rm -rf '..dataPath..'/StoreKit/*') os.execute('rm -rf '..dataPath..'/tmp/*') os.execute('rm -rf '..dataPath..'/*.plist') os.execute([[find ]]..dataPath..[[/Library/* | egrep -v '(Application Support|Caches)' | xargs rm -rf]]) clearPasteboard() clearAllKeyChains() clearKeyChain(_appBid) clearIDFAV() clearCookies() end -----็ฝ‘็ปœ่ฏทๆฑ‚ function PostApi(url,data,sleep) --post sleep = sleep or 10 checkerr = checkerr or false local minM,maxM = 3000,8000 --้šๆœบๅปถๆ—ถ local jsonData = json.encode(data) local i = 0,0 while (true) do Showlog(url) Showlog(jsonData) local c, h, b = http.tspost(url, 10,{['Content-Type']="application/json" },jsonData) if c == 200 then return json.decode(b) elseif c == 500 then Showlog("post data = "..jsonData.." url = "..url) sys.alert(url..' err = 500 ',2) else Showlog("post data = "..jsonData.." url = "..url.." err = "..c) i=i + 1 if i%4== 0 then VPN_DisConnect() end end if i >= 20 then dialog("็ฝ‘็ปœๅ‡บ็Žฐ้—ฎ้ข˜ ่ฏทๆŸฅ็œ‹",10) end sys.msleep(math.random(minM,maxM)) end end function GetApi(url,head,loop) --get checkerr = checkerr or false loop = loop or false head = head or {} local minM,maxM = 5000,7000 --้šๆœบๅปถๆ—ถ local i = 1 while (true) do local c, h, b = http.tsget(url,10,head) if c == 200 then return json.decode(b) elseif c == 500 then sys.alert(url..' err = 500',2) else Showlog("[GetApi] ๆœๅŠกๅ™จ็นๅฟ™ -1 url = "..url) i=i+1 if i>=4 then if string.find(url,_Sever) ==nil and loop ==false then return -1,{},nil end end end if i % 3 ==0 then VPN_CheckConnect() end if i >= 100 then appClose(_appBid) sys.alert("็ฝ‘็ปœๅ‡บ็Žฐ้—ฎ้ข˜ ่ฏทๆŸฅ็œ‹",2) rebootWifi() end sys.msleep(math.random(minM,maxM)) end end function httpsGet(url,sleep,header) header = header or {} sleep = sleep or 10 if header['Content-Type']==nil then header['Content-Type'] = "application/json" end return https.get(url, sleep, header) end function httpsPost(url,sleep,header,str) sleep = sleep or 10 header = header or {} if header['Content-Type']==nil then header['Content-Type'] = "application/json" end return https.post(url, sleep, header,str) end -----ๅˆๅง‹ๅŒ–ๆ“ไฝœ function initDevice() --ๅฏน่ฎพๅค‡ๅšๅˆๆœŸๅค„็† device.turn_off_bluetooth() --ๅ…ณ้—ญ่“็‰™ device.set_volume(0) --้™้Ÿณ device.set_brightness(0.5) --่ฎพ็ฝฎไบฎๅบฆ sys.msleep(2000) --device.set_autolock_time(0) --ๆฐธไธ้”ๅฑ end function initWebView() local width,height = getScreenSize(); fwShowWnd("wid",0,height-300,width, height-100,0); --ๅผ€ๅฏไธ€ไธชๆตฎๅŠจ็ช—ไฝ“ showWebview("ๆธ…็†ๅžƒๅœพ") os.execute('cd /var/mobile/Library/Preferences/ && find . -name "*.plist.*" | xargs rm -r') os.execute('cd /private/var/root/Library/Preferences/ && find . -name "*.plist.*" | xargs rm -r') os.execute('rm -rf /private/var/log/*') os.execute('rm -rf /private/var/logs/*') end function showWebview(title,arg1) --ๆ˜พ็คบไธ€ไธชweb็ช—ไฝ“ title = title or "" arg1 = arg1 or "" local color = 'FFFFFF' if string.find(title,"็งไฟก") ~=nil then color = 'B23AEE' elseif string.find(title,"็ˆฌ") ~=nil then color = '1E90FF' elseif string.find(title,"ๆณจๅ†Œ") ~=nil then color = '228B22' elseif string.find(title,"ๅˆท่ตž") ~=nil then color = 'B03060' elseif string.find(title,"็‚ธ") ~= nil then color = 'FF4500' end Showlog(title..","..arg1) ---[[ local tab = fwGetWndPos("wid"); if tab then local width,height = getScreenSize(); if tab.ret == 0 then fwShowWnd("wid",0,height-300,width, height-100,0) end fwShowTextView("wid","textid1",title,"center","000000",color,30,1,0,0,width/2.5,200,1) fwShowTextView("wid","textid2",arg1,"left","FFFFFF","000000",20,1,width/2.5+20,0,width,200,1) end --]] end function GetlocalIP() --่Žทๅ–ๆœฌๆœบIP local ip = nil local j = 1 while true do for i,v in ipairs(ts.system.localwifiaddr()) do --่Žทๅ–ๆœฌๅœฐ็ฝ‘็ปœๅœฐๅ€ if string.find(v[1],"en")~=nil then ip = v[2] break end end if ip == nil then j = j + 1 if j %4 ==0 then rebootWifi() end else break end sys.msleep(2000) end return ip end<file_sep>๏ปฟ --[[ ๆ ผๅผ่ฏดๆ˜Ž๏ผš { ไธ‹ๆ‹‰้€‰้กนๆ ‡้ข˜, { customKeyMap = ่‡ชๅฎšไน‰ๅฟซๆท้”ฎๆ˜ ๅฐ„่กจ, singlePosFormatRule = ๅ•็‚นๅ–่‰ฒ็”Ÿๆˆๆ ผๅผๅ‡ฝๆ•ฐ, multiPosFormatRule = ๅคš็‚นๅ–่‰ฒ็”Ÿๆˆๆ ผๅผๅ‡ฝๆ•ฐ, currentPosInfo = ้ผ ๆ ‡ๆ‰€ๆŒ‡ๅฝ“ๅ‰็‚น็š„ๆ ผๅผ็”Ÿๆˆๅ‡ฝๆ•ฐ๏ผˆ้ขๆฟไธŠ้‚ฃไธช้š็€้ผ ๆ ‡็งปๅŠจๆ—ถๅˆปๅœจๅ˜ๅŒ–็š„ๅ†…ๅฎน๏ผ‰, makeScriptRule = { -- ่‡ชๅฎšไน‰่„šๆœฌ่ง„ๅˆ™ ็”Ÿๆˆ็ฌฌ 1 ไธชๆ–‡ๆœฌๆก†ๅ†…ๅฎน็š„ๅ‡ฝๆ•ฐ, ็”Ÿๆˆ็ฌฌ 2 ไธชๆ–‡ๆœฌๆก†ๅ†…ๅฎน็š„ๅ‡ฝๆ•ฐ, ็”Ÿๆˆ็ฌฌ 3 ไธชๆ–‡ๆœฌๆก†ๅ†…ๅฎน็š„ๅ‡ฝๆ•ฐ, testRule = { -- [+ 1.7.7] ็ฌฌ 1 ไธชๆ–‡ๆœฌๆก†็š„ๅ†…ๅฎน็š„ๆต‹่ฏ•ๅ‡ฝๆ•ฐ, ็ฌฌ 2 ไธชๆ–‡ๆœฌๆก†็š„ๅ†…ๅฎน็š„ๆต‹่ฏ•ๅ‡ฝๆ•ฐ, ็ฌฌ 3 ไธชๆ–‡ๆœฌๆก†็š„ๅ†…ๅฎน็š„ๆต‹่ฏ•ๅ‡ฝๆ•ฐ, }, }, }, } customKeyMap ่ฏดๆ˜Ž๏ผš ๅฏๅ‚่€ƒ scripts/config/colorpicker/keymap.lua ็š„่ฟ”ๅ›žๅ€ผ singlePosFormatRuleใ€multiPosFormatRule ๅ‚ๆ•ฐ่ฏดๆ˜Ž๏ผš p๏ผš ๅฝ“ๅ‰็‚นไฟกๆฏ๏ผŒๅŒ…ๆ‹ฌ xใ€yใ€cใ€rใ€gใ€bใ€num a๏ผš ๅๆ ‡็ผ“ๅ†ฒไฝ A ็š„ไฟกๆฏ๏ผŒๅŒ…ๆ‹ฌ xใ€y s๏ผš ๅๆ ‡็ผ“ๅ†ฒไฝ S ็š„ไฟกๆฏ๏ผŒๅŒ…ๆ‹ฌ xใ€y x๏ผš ๅๆ ‡็ผ“ๅ†ฒไฝ X ็š„ไฟกๆฏ๏ผŒๅŒ…ๆ‹ฌ xใ€y c๏ผš ๅๆ ‡็ผ“ๅ†ฒไฝ C ็š„ไฟกๆฏ๏ผŒๅŒ…ๆ‹ฌ xใ€y set: ๆ‰ฉๅฑ•่ฎพ็ฝฎๅˆ—่กจ makeScriptRule ๅ‚ๆ•ฐ่ฏดๆ˜Ž๏ผš poslist: { p, p, p, ... a = {x, y}, s = {x, y}, x = {x, y}, c = {x, y}, } set: ๆ‰ฉๅฑ•่ฎพ็ฝฎๅˆ—่กจ ๅฆ‚้œ€่‡ชๅฎšไน‰ๆ ผๅผ๏ผŒๅฏไปฅๅคๅˆถๅฝ“ๅ‰ๆ–‡ไปถ็š„่€ƒๅค‡ไปฝ้‡ๅ‘ฝๅ็„ถๅŽๅšไฟฎๆ”น ไฟฎๆ”นๅฎŒๆˆๅŽ๏ผŒๅฏไปฅๅœจๆ–‡ไปถ scripts/config/colorpicker/cf_enabled.lua ๅบ”็”จๆทปๅŠ ่‡ชๅฎšไน‰ๆ ผๅผ --]] function make_FMC(poslist) local ret = "" local firstPos for i,currentPos in ipairs(poslist) do if i==1 then firstPos = currentPos ret = ret..string.format("0x%06x, \"", firstPos.c) else ret = ret..string.format("%d|%d|0x%06x", currentPos.x - firstPos.x, currentPos.y - firstPos.y, currentPos.c) if i~=#poslist then ret = ret.."," end end end return ret..'"' end local function is_same_0(n) return (tonumber(n) or 0)==0 end return {"ๆจ - By wenfree", -- ๆ„Ÿ่ฐขๆกƒๅญๅ…ฑไบซๆ ผๅผ { settingsRule = { title = "่‡ชๅฎšไน‰ๆ ผๅผ [็ฒพ็ฎ€ๅŽป็ฉบๆ ผ็‰ˆHex - By ๆกƒๆกƒ] ็š„ๅ‚ๆ•ฐ่ฎพ็ฝฎ", caption = {"ๅ‚ๆ•ฐๅ", "ๅ‚ๆ•ฐๅ€ผ"}, args = { {"็›ธไผผๅบฆ(1-100 ็ฉบไธบ100%)", "85"}, {"ๅฝ“ๅ‰isColorๅ‡ฝๆ•ฐๅฎšไน‰๏ผˆ็›ดๆŽฅๅคๅˆถไฝฟ็”จ๏ผ‰", isColorCodeDefine} }, }, singlePosFormatRule = (function(p, a, s, x, c, set) return string.format("%d,%d,0x%06x", p.x, p.y, p.c) end), multiPosFormatRule = (function(p, a, s, x, c, set) return string.format("%d,%d,0x%06x\n", p.x, p.y, p.c) end), currentPosInfo = (function(p, a, s, x, c, set) return string.format("X:%d Y:%d \r\nR:%d G:%d B:%d \r\nC:0x%06x", p.x, p.y, p.r, p.g, p.b, p.c) end), makeScriptRule = { (function(poslist, set) local ret = "t['']={" for _,currentPos in ipairs(poslist) do ret = ret..string.format("{%d,%d,0x%06x},", currentPos.x, currentPos.y, currentPos.c) end return ret.."} --ๅคš็‚นๅ–่‰ฒ" end), (function(poslist) local ax, ay, sx, sy = poslist.a.x, poslist.a.y, poslist.s.x, poslist.s.y if is_same_0(ax) and is_same_0(ax) and is_same_0(sx) and is_same_0(sy) then sx, sy = getImageSize() if sx~=0 or sy~=0 then sx, sy = sx-1, sy-1 end end return string.format("t['']={ %s, 90, %d, %d, %d, %d } --ๅคš็‚นๆ‰พ่‰ฒ", make_FMC(poslist), ax, ay, sx, sy) end), make_findMultiColorInRegionFuzzy, testRule = { -- [+ 1.7.7] (function(s) return multiColorCodeDefine..[[ if multiColor(]]..s..[[, 80) then nLog("็›ธไผผๅบฆ80ไปฅไธŠ") else nLog("็›ธไผผๅบฆ80ไปฅไธ‹") end ]] end), (function(s) return isColorCodeDefine..s..[[ nLog("ๅŒน้…") else nLog("ไธๅŒน้…") end ]] end), (function(s) return s..[[ nLog("ๅคš็‚นๆ‰พ่‰ฒ็ป“ๆžœ๏ผš"..tostring(x).." ,"..tostring(y)) ]] end), }, }, }, }<file_sep>require("TSLib") width,hight=getScreenSize() nLog(width..'*'..hight) w = { --ๆทฑๅบฆๆ‰“ๅฐไธ€ไธช่กจ print_r = function (t) local print_r_cache={} local function sub_print_r(t,indent) if (print_r_cache[tostring(t)]) then nLog(indent.."*"..tostring(t)) else -- mSleep(100) print_r_cache[tostring(t)]=true if (type(t)=="table") then for pos,val in pairs(t) do if (type(val)=="table") then nLog(indent.."["..pos.."] = "..tostring(t).." {") sub_print_r(val,indent..string.rep(" ",string.len(pos)+8)) nLog(indent..string.rep(" ",string.len(pos)+6).."},") elseif (type(val)=="string") then nLog(indent..'["'..pos..'"] = "'..val..'",') else if (type(val)=="number") then nLog(indent..'["'..pos..'"] = '..val ) else nLog(indent..'["'..pos..'"] = "'..val..'"') end end end else nLog(indent..tostring(t)) end end end if (type(t)=="table") then nLog(tostring(t).." {") sub_print_r(t," ") nLog("}") elseif (type(t)=="string") then nLog(t) end end, --่งฃ้” lock = function () local flag = deviceIsLock(); if flag ~= 0 then unlockDevice(); --่งฃ้”ๅฑๅน• end end, --appๅœจๅ‰็ซฏ active = function (app,times) local times = times or 5 w.lock() local bid = frontAppBid(); if bid ~= app then w.log(app.."๏ผŒๅ‡†ๅค‡ๅฏๅŠจ") runApp(app) mSleep(times*1000) elseif bid == app then w.log("ๅœจๅ‰็ซฏ") return true end end, closeX = function (app_bid,times,way) local times = times or 1 nLog("kill "..app_bid) if way then closeApp(app_bid,1) else closeApp(app_bid) end mSleep(times*1000) end, log = function (txt,show,times) local times = 1 if type(txt) == 'table' then w.print_r(txt) return end if show == 'all' then toast(txt,times) nLog(txt) elseif show then toast(txt,times) else nLog(txt) end end, click = function (x,y,times,stayTime,logtxt) local times = times or 1 local stayTime = stayTime or 0.05 if logtxt then nLog("ๅ‡†ๅค‡็‚นๅ‡ป->"..logtxt.."("..x..","..y..")") end local offset_x = math.random(-3,3) local offset_y = math.random(-3,3) touchDown(1, x, y) mSleep(stayTime * 1000) touchUp(1, x, y) mSleep(times * 1000) end, delay = function (times) local times = times or 1 mSleep(times*1000) end, --ๅ•็‚นๆจก็ณŠๆฏ”่‰ฒ isColor = function (x,y,c,s) local fl,abs,s= math.floor,math.abs, s or 90 s = fl(0xff*(100-s)*0.01) local r,g,b = fl(c/0x10000),fl(c%0x10000/0x100),fl(c%0x100) local rr,gg,bb = getColorRGB(x,y) if abs(r-rr)<s and abs(g-gg)<s and abs(b-bb)<s then return true end end, --่พ“ๅ…ฅ--- input = function (txt,way,times) local times = times or 1 if way then inputStr(txt) else inputText(txt) end delay(times) end, downFile = function (url, path) --็”จhttp.getๅฎž็Žฐไธ‹่ฝฝๆ–‡ไปถๅŠŸ่ƒฝ local sz = require("sz") json = sz.json http = sz.i82.http status, headers, body = http.get(url) if status == 200 then file = io.open(path, "wb") if file then file:write(body) file:close() return true else return -1; end else return status; end end, ip = function() local http = require("szocket.http") local res, code = http.request("http://ip.cn",30); if code ~= nil then local i,j = string.find(res, '%d+%.%d+%.%d+%.%d+') return string.sub(res,i,j) end end, rd = function (min,max) local min = min or 1 local max = max or min if min >= max then return math.random(max,min) else return math.random(min,max) end end, --ๅญ—็ฌฆไธฒๅˆ†ๅ‰ฒ split = function (str,delim) if type(delim) ~= "string" or string.len(delim) <= 0 then return end local start = 1 local t = {} while true do local pos = string.find (str, delim, start, true) -- plain find if not pos then break end table.insert (t, string.sub (str, start, pos - 1)) start = pos + string.len (delim) end table.insert (t, string.sub (str, start)) return t end, vpnx = function () setVPNEnable(false) mSleep(1000) end, vpn = function () setVPNEnable(true) mSleep(1000) local LineTime = os.time() local OutTimes = 60 while (os.time()-LineTime<OutTimes) do local flag = getVPNStatus() if flag.active then w.log("VPN ๆ‰“ๅผ€็Šถๆ€"..flag.status) if flag.status == 'ๅทฒ่ฟžๆŽฅ' then return true else setVPNEnable(true) delay(6) end else w.log("VPN ๅ…ณ้—ญ็Šถๆ€"..flag.status) end mSleep(1000) end end, vpnstate = function () local flag = getVPNStatus() if flag.active then w.log("VPN ๆ‰“ๅผ€็Šถๆ€"..flag.status) if flag.status == 'ๅทฒ่ฟžๆŽฅ' then return true end else w.log("VPN ๅ…ณ้—ญ็Šถๆ€"..flag.status) end end, ---------------VPN--------------- boxshow = function (txt,x1,y1,x2,y2) adbox = adbox or 0 if adbox == 0 then adbox = 1 fwShowWnd("wid",0,0,0,0,1) mSleep(2000) end fwShowTextView("wid","textid",txt,"center","FF0000","FFDAB9",10,0,x1,y1, x2,y2,0.5) --fwShowTextView("wid","textid","่ฟ™ๆ˜ฏไธ€ไธชๆ–‡ๆœฌ่ง†ๅ›พ","center","FF0000","FFDAB9",0,20,0,0,200,100,0.5) end, post = function (url,arr) w.log('tsp-post') local sz = require("sz") local cjson = sz.json local http = sz.i82.http local safari = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36' local headers = {} headers['User-Agent'] = safari headers['Referer'] = url headers['content-type'] = 'application/x-www-form-urlencoded' headers_send = cjson.encode(headers) post_send = cjson.encode(arr) post_escaped = http.build_request(post_send) w.log(post_send) local status_resp, headers_resp, body_resp = http.post(url, 30, headers_send, post_escaped) w.log(status_resp) if status_resp == 200 then w.log(body_resp) if body_resp ~= 'timeout' then local json = sz.json return json.decode(body_resp) else w.log('่ถ…ๆ—ถไบ†') end end end, get = function (url) local sz = require("sz") local http = require("szocket.http") local res, code = http.request(url); if code == 200 then local json = sz.json if res ~= nil then return json.decode(res) end end end, inputword = function (key) if key ~= nil then for i = 1,string.len(key) do w.log(string.sub(key,i,i)) inputkey = string.sub(key,i,i) if type(tonumber(inputkey)) == 'number' then w.log('munber->'..inputkey) keyDown(inputkey) keyUp(inputkey) else if inputkey ~= string.lower(inputkey) then w.log('่พ“ๅ…ฅๅคงๅ†™') keyDown("CapsLock") keyDown(string.lower(inputkey)) keyUp(string.lower(inputkey)) keyUp("CapsLock") else if inputkey == '@' then w.log('่พ“ๅ…ฅ็ฌฆๅท') keyDown("LeftShift") keyDown(2) keyUp(2) keyUp("LeftShift") else keyDown(string.lower(inputkey)) keyUp(string.lower(inputkey)) end end end mSleep(500) end else w.log('ไธ€ไธช็ฉบๅ€ผ',true) end end, clearTxt = function () keyDown("Clear") keyUp("Clear") end, mc = function(color_table,clickkey,n,options) options = options or {["dim"] = 90,["flag"] = false} n = n or 1 if n > #color_table then w.log("็‚นๅ‡ป่ถ…่กจ") return end clickkey = clickkey or false if multiColor(color_table,options) then w.log("ๆ‰พๅˆฐ้ขœ่‰ฒ") if ( clickkey )then w.log({"ๅ‡†ๅค‡็‚นๅ‡ป",color_table[n][1],color_table[n][2]} ) w.click(color_table[n][1],color_table[n][2]) end return true else -- w.log("ๆœชๆ‰พๅˆฐ้ขœ่‰ฒ") end end, fmc = function(tmp,degree,x1,y1,x2,y2,n) n = n or 1 degree = degree or 90 x,y=findMultiColorInRegionFuzzyByTable(tmp,degree,x1,y1,x2,y2,{orient = n}) if x ~= -1 and y ~= -1 then w.log("ๆ‰พๅˆฐ".."\r\n"..x..","..y) return true else w.log("ๆœชๆ‰พๅˆฐ".."\r\n"..x..","..y) end end, } w.log('ๅŸบ็ก€ๅ‡ฝๆ•ฐๅŠ ่ฝฝๅฎŒๆˆ') local deskbid=frontAppBid(); if deskbid == nil or deskbid == '' then w.log('com.apple.springbord') else w.log(deskbid) end <file_sep>require("TSLib") require("tsp") require("nameStr") require("alz") --require("UI") local sz = require("sz") local json = sz.json --local ts = require("ts") sys = { clear_bid = (function(bid) closeApp(bid) delay(1) os.execute("rm -rf "..(appDataPath(bid)).."/Documents/*") --Documents os.execute("rm -rf "..(appDataPath(bid)).."/Library/*") --Library os.execute("rm -rf "..(appDataPath(bid)).."/tmp/*") --tmp clearPasteboard() --[[ local path = _G.const.cur_resDir os.execute( table.concat( { string.format("mkdir -p %s/keychain", path), 'killall -SIGSTOP SpringBoard', "cp -f -r /private/var/Keychains/keychain-2.db " .. path .. "/keychain/keychain-2.db", "cp -f -r /private/var/Keychains/keychain-2.db-shm " .. path .. "/keychain/keychain-2.db-shm", "cp -f -r /private/var/Keychains/keychain-2.db-wal " .. path .. "/keychain/keychain-2.db-wal", 'killall -SIGCONT SpringBoard', }, '\n' ) ) ]] clearAllKeyChains() clearIDFAV() --clearCookies() end) } var={} var.bid='com.nike.onenikecommerce' var.account={} var.account.login = '' var.account.pwd = '' var.account.address_country = 'CN' var.account.phone = '' var.looktime = 5 var.wifitime = 30 file_name = '/var/mobile/Media/lua/back_account.txt' function backWirteFile(file_name,string,way) way = way or 'a' --w or a local f = assert(io.open(file_name, way)) f:write(string) f:close() end function local_token() local appbid = 'com.nike.onenikecommerce' local localPath = appDataPath(appbid).."/Documents/ifkc.plist" --่ฎพ็ฝฎ plist ่ทฏๅพ„ local toketext = readFileString(localPath) local toketext = string.gsub(toketext,'&','|') local toketext = string.gsub(toketext,'+','^') return toketext end --่ฏปๆ–‡ไปถ function readFile_(path) local path = path or '/var/mobile/Media/TouchSprite/lua/account.txt' local file = io.open(path,"r"); if file then local _list = ''; for l in file:lines() do _list = _list..l end file:close(); return _list end end function decodeURI(s) s = string.gsub(s, '%%(%x%x)', function(h) return string.char(tonumber(h, 16)) end) return s end function encodeURI(s) s = string.gsub(s, "([^%w%.%- ])", function(c) return string.format("%%%02X", string.byte(c)) end) return string.gsub(s, " ", "+") end function local_token_() local appbid = 'com.nike.onenikecommerce' local localPath = appDataPath(appbid).."/Documents/ifkc.plist" --่ฎพ็ฝฎ plist ่ทฏๅพ„ local toketext = readFile_(localPath) return encodeURI(toketext) end function update_token() local url = 'http://nikeapi.honghongdesign.cn' local arr ={} arr['s']='App.NikeToken.Token' arr['email'] = var.account.login arr['token'] = local_token_() arr['id'] = var.account.id post(url,arr); end function updateNike() local sz = require("sz") local url = 'http://zzaha.com/phalapi/public/' local Arr={} Arr.s = 'Nikesave.Save' Arr.address_mail = var.account.login Arr.address_pwd = var.account.pwd Arr.address_phone = var.account.phone Arr.address_xin = first_name_ Arr.address_ming = last_names_ Arr.address_sheng = 'ๅนฟไธœ็œ' Arr.address_shi = 'ๆทฑๅœณๅธ‚' Arr.address_qu = '็ฝ—ๆน–ๅŒบ' Arr.address_area = var.account.address_area Arr.address_country = var.account.address_country Arr.iphone = getDeviceName() Arr.imei = sz.system.serialnumber() Arr.birthday = var.birthday Arr.moon = var.moon Arr.codes = var.codes log(Arr) if post(url,Arr)then return true end end --ๅ›žไผ ๆ‰‹ๆœบ function updatePhone() local sz = require("sz") local url = 'http://zzaha.com/phalapi/public/' local Arr={} Arr.s = 'Nikesave.Phone' Arr.imei = sz.system.serialnumber() Arr.name = getDeviceName() Arr.whos = 'whos' return post(url,Arr) end --updateLog function updateNikeLog(workstate) log(workstate); return ''; -- local sz = require("sz") -- local url = 'http://zzaha.com/phalapi/public/' -- local Arr={} -- Arr.s = 'Nikesave.Save' -- Arr.address_mail = var.account.login -- Arr.workstate = workstate -- post(url,Arr) end function backId() local postUrl = 'http://nikeapi.honghongdesign.cn/' local postArr = {} postArr.s = 'NikeBack.back' postArr.id = var.account.id log(post(postUrl,postArr)) end function backphone() local sz = require("sz") local postUrl = 'http://zzaha.com/phalapi/public/' local postArr = {} postArr.s = 'Nikesave.phoneback' postArr.imei = sz.system.serialnumber() log(post(postUrl,postArr)) end function disable() local postUrl = 'http://zzaha.com/phalapi/public/' local postArr = {} postArr.s = 'Nikeback.disable' postArr.id = var.account.id log(post(postUrl,postArr)) end t={} t['ๅผ€ๅฑ็™ปๅฝ•']={ 0xffffff, "276|-9|0x111111,288|2|0x111111,280|-61|0xffffff,336|56|0xffffff", 90, 28, 1052, 572, 1213 } --็™ปๅฝ•_ๅŠ ๅ…ฅ t['็™ปๅฝ•Nike+ๅธๅท']={ 0xffffff, "302|6|0x000000,-334|4|0x000000,-9|-38|0x000000,295|-705|0x363636", 90, 46, 24, 716, 860 } --็™ปๅฝ•_x t['็™ปๅฝ•Nike+ๅธๅท_ไฝฟ็”จ็”ตๅญ้‚ฎไปถ็™ปๅฝ•']={ 0x8d8d8d, "-13|-192|0x111111,-11|-194|0xefefef,1|-195|0x111111,2|-199|0xefefef", 90, 43, 240, 305, 533 } --ๅคš็‚นๆ‰พ่‰ฒ t['็™ปๅฝ•Nike+ๅธๅท_็”ตๅญ้‚ฎไปถ']={ 0x8d8d8d, "7|-13|0xffffff,9|-18|0x8d8d8d,98|4|0x8d8d8d,430|-9|0xffffff", 90, 72, 289, 660, 327} t['็™ปๅฝ•Nike+ๅธๅท_ๅฏ†็ ']={ <PASSWORD>, "44|-<PASSWORD>", 90, 83, 385, 152, 449 } --ๅคš็‚นๆ‰พ่‰ฒ ----------------ๆณจๅ†Œ็”จ----------- t['็™ปๅฝ•Nike+ๅธๅท_ๆ‰‹ๆœบๅท็ ']={ 0xffffff, "-208|-17|0xa9a9a9,-300|-4|0xa9a9a9,-389|-2|0x111111", 90, 63, 425, 510, 493 } --ๅคš็‚นๆ‰พ่‰ฒ t['็™ปๅฝ•Nike+ๅธๅท_่พ“ๅ…ฅ้ชŒ่ฏ็ ']={ 0xa9a9a9, "-121|17|0xa9a9a9", 90, 71, 539, 410, 598 } --ๅคš็‚นๆ‰พ่‰ฒ t['็™ปๅฝ•Nike+ๅธๅท_ๅ‘้€้ชŒ่ฏ็ ']={ 0xe5e5e5, "-65|2|0x111111,-1|-18|0xe5e5e5", 90, 536, 431, 687, 491 } --ๅคš็‚นๆ‰พ่‰ฒ t['็™ปๅฝ•Nike+ๅธๅท_็บขๆก†']={ 0xfe0000, "-635|3|0xfe0000,-604|-103|0x111111,-606|-102|0xededed,-599|-104|0x111111,-621|-68|0xe5e5e5", 90, 34, 395, 717, 656 } -- t['็™ปๅฝ•Nike+ๅธๅท_็ปง็ปญ']={ 0xffffff, "-14|-6|0x000000,-300|-16|0x000000,15|-48|0x000000,336|-5|0x000000,15|31|0x000000", 90, 14, 644, 735, 1177 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅผน็ช—_่พ“ๅ…ฅ็š„ๅฎŒๆˆ']={ 0x007aff, "-43|-20|0x007aff", 90, 646, 594, 742, 956 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅผน็ช—_็Žฐๅœจไธ็”จ']={ 0x000000, "196|-56|0xaaaaaa,318|-4|0x000000,-56|-304|0xffffff,250|-243|0x000000", 90, 103, 480, 646, 856 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๆณจๅ†Œ่ฟ”ๅ›ž็•Œ้ข']={ 0xffffff, "9|-41|0x000000,-312|-5|0x000000,325|-9|0x000000,325|118|0x8d8d8d,-312|113|0x8d8d8d,-1|137|0x8d8d8d", 90, 25, 943, 729, 1321 } --ๆณจๅ†Œ t['่พ“ๅ…ฅๆ‚จ็š„็”ตๅญ้‚ฎไปถ']={ 0xffffff, "9|-40|0x000000,-307|-4|0x000000,327|-6|0x000000,4|37|0x000000,321|-490|0x363636", 90, 21, 25, 722, 690 } --ๅคš็‚นๆ‰พ่‰ฒ t['่พ“ๅ…ฅๆ‚จ็š„็”Ÿๆ—ฅ']={ 0xffffff, "9|-44|0x000000,-306|-8|0x000000,329|-10|0x000000,3|33|0x000000,-306|96|0x8d8d8d,330|96|0x8d8d8d", 90, 24, 531, 727, 810 } --ๅคš็‚นๆ‰พ่‰ฒ t['ไธชไบบ้กต้ข']={ 0x000000, "-188|5|0xb8b8b8,-375|-4|0xb8b8b8,-564|-3|0xb8b8b8,18|11|0xffffff", 90, 22, 1274, 728, 1306 } --ๅคš็‚นๆ‰พ่‰ฒ t['ไธชไบบ้กต้ข_่ฎพ็ฝฎๆŒ‰้’ฎ']={ 0xffffff, "10|0|0xb8b8b8,-10|0|0xb8b8b8,-17|0|0xffffff", 90, 668, 55, 731, 108 } --ๅคš็‚นๆ‰พ่‰ฒ -- t['ไธชไบบ้กต้ข_้ž‹็ ้€‰ๆ‹ฉ']={ 0xffffff, "19|-588|0x000000,-15|-715|0xbcbcbc,23|-769|0xd8d8d8", 90, 15, 137, 737, 1174 } --ๅคš็‚นๆ‰พ่‰ฒ t['ไธชไบบ้กต้ข_้ž‹็ ้€‰ๆ‹ฉ']={ 0xfdfdfd, "3|-3|0x000000,-51|16|0xffffff,-49|24|0x000000,-46|21|0xffffff", 90, 12, 934, 111, 1006} --ๅคš็‚นๆ‰พ่‰ฒ t['ไธชไบบ้กต้ข_้ž‹็ ๆป‘่กจ']={ 0x000000, "3|161|0xffffff,-47|554|0x000000", 90, 639, 715, 742, 1319 } --ๅคš็‚นๆ‰พ่‰ฒ t['ไธชไบบ้กต้ข_้€š็Ÿฅ่ฎพ็ฝฎ']={ 0x000000, "2|0|0xffffff,3|-53|0xc8c7cc,-3|48|0xc8c7cc,2|-98|0xf7f7f7,-8|88|0xf7f7f7", 90, 15, 190, 172, 761 } --ๅคš็‚นๆ‰พ่‰ฒ t['ไธชไบบ้กต้ข_ๅฏๅŠจ้€š็Ÿฅ']={ 0xffffff, "-620|-59|0xf7f7f7,-623|153|0xf7f7f7,-626|582|0xf7f7f7,45|582|0xf7f7f7", 90, 19, 190, 717, 884 } --ๅคš็‚นๆ‰พ่‰ฒ t['ไธชไบบ้กต้ข_้€š็Ÿฅๅผ€ๅฏ']={ 0x4bd763, "-3|291|0x4cd864,-9|393|0x4cd964,-2|489|0x4cd864", 90, 567, 190, 739, 807 } --ๅคš็‚นๆ‰พ่‰ฒ t['ไธชไบบ้กต้ข_ๆœช่ฎพๅคดๅƒ']={ 0x000000, "0|7|0xffffff,0|17|0xe4e4e4,12|-98|0xbcbcbc,12|-111|0xd8d8d8", 90, 168, 155, 568, 450} t['ไธชไบบ้กต้ข_็…ง็‰‡']={0xc7c7cc, "-5|-1|0xffffff,-9|-11|0xc7c7cc,-62|-139|0x007aff,-358|-147|0x000000,-682|-132|0xf9f9f9",90,6,26,742,298} --ๅคš็‚นๆ‰พ่‰ฒ t['ไธชไบบ้กต้ข_ๆ—ถๅˆป']={ 0x1b86fb, "-284|-11|0x000000,-318|7|0x000000,-636|-3|0x007aff", 90, 1, 33, 737, 117} t['้…้€ๅœฐๅ€_ๆ–ฐๅœฐๅ€']={ 0x1a1a1a, "224|1082|0x000000,-337|1069|0xb8b8b8,-394|-47|0x1a1a1a", 90, 12, 53, 734, 1321} t['้…้€ๅœฐๅ€_ๆทปๅŠ ๅœฐๅ€']={ 0x1a1a1a, "327|45|0x1a1a1a,-353|-50|0x1a1a1a,-30|0|0xffffff,-358|-943|0x000000", 90, 9, 42, 747, 1138} t['้…้€ๅœฐๅ€_ๆทปๅŠ ๆˆๅŠŸ']={ 0x000000, "10|219|0xffffff,12|212|0x000000,635|472|0x1a1a1a", 90, 13, 46, 734, 772} t['ๅผน็ช—_ๅ‡บ้”™ไบ†']={ 0xffffff, "3|4|0x000000,-299|48|0x000000,355|-39|0x000000,339|-311|0x363636", 90, 2, 63, 742, 495 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅผน็ช—_ๅ‡บ้”™ไบ†_']={ 0x000000, "-238|-16|0xffffff,362|41|0x5c5c5c,360|-263|0x5c5c5c", 90, 95, 498, 743, 839 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅผน็ช—_ๅ‡บ้”™ไบ†__']={ 0x000000, "-232|-70|0xaaaaaa,200|-70|0xaaaaaa", 90, 100, 402, 654, 1069 } --ๅคš็‚นๆ‰พ่‰ฒ t['็™ปๅฝ•_ๅ‡บ้”™ไบ†']={ 0x363636, "-5|-12|0xffffff,11|14|0x363636,8|230|0xfe0000", 90, 567, 33, 732, 556 } --ๅคš็‚นๆ‰พ่‰ฒ t['็™ปๅฝ•_ๅ‡บ้”™ไบ†_ๅ›ฝๅฎถ/ๅœฐๅŒบ']={ 0x000000, "-12|0|0xffffff,-14|0|0x000000,-14|-13|0x000000,-14|13|0x000000,-14|14|0xebebeb,-121|-10|0xffffff,-124|-13|0x000000", 90, 285, 22, 467, 73 } --ๅคš็‚นๆ‰พ่‰ฒ t['็™ปๅฝ•_ๅ‡บ้”™ไบ†_ๅ›ฝๅฎถ/ๅœฐๅŒบ_ไธญๅ›ฝ']={ 0xfcfcfc, "-2|-2|0x1d1d1d,7|-3|0xf6f6f6,8|-7|0x131313,8|64|0xc8c7cc,8|125|0x111111,38|132|0x111111,38|133|0xe8e8e8", 90, 33, 1121, 125, 1301 } --ๅคš็‚นๆ‰พ่‰ฒ t['็™ปๅฝ•_ๅ‡บ้”™ไบ†_ๅ›ฝๅฎถ/ๅœฐๅŒบ_็พŽๅ›ฝ']={ 0x111111,"-69|476|0xffffff,-65|476|0x111111,578|489|0",90,9,505,735,1293 } t['็™ปๅฝ•_ๅ‡บ้”™ไบ†_่ฏญ่จ€']={ 0x1b1b1b, "8|-2|0xf6f6f6,-7|-235|0x000000,315|-234|0xffffff,318|-234|0x000000", 90, 6, 7, 510, 324 } --ๅคš็‚นๆ‰พ่‰ฒ t['็™ปๅฝ•_ๅ‡บ้”™ไบ†_่ฏญ่จ€']={0,"-4|3|0xffffff,-4|6|0,-4|8|0xffffff,-4|11|0,-374|9|0",90,6,10,441,84} t['ๅ…จๅฑ้”™่ฏฏ_่ดญไนฐๆœชๆˆๅŠŸ']={0xffffff, "-21|0|0x545454,21|0|0x545454,9|10|0xffffff,1|-17|0x545454",90,601,47,746,171} --ๅคš็‚นๆ‰พ่‰ฒ t['ๅผน็ช—_้€‰ๆ‹ฉ็…ง็‰‡']={ 0x007aff, "-87|-5|0x007aff,-128|-6|0x007aff,-124|-7|0xf9f9f9", 90, 233, 976, 491, 1051} t['ๅผน็ช—_็…ง็‰‡็กฎ่ฎค้€‰ๅ–']={ 0xffffff, "-2|2|0x141414", 90, 680, 1253, 699, 1267} t['ๅผน็ช—_ๅฏ†็ ๆ— ๆ•ˆ']={ 0x000000, "40|6|0x000000,121|334|0x000000,121|336|0xffffff,123|338|0x000000,34|203|0x000000,35|203|0xffffff", 90, 110, 457, 641, 868} t['ๆˆ‘_ไป˜ๆฌพไฟกๆฏ_็•Œ้ข']={ 0x01aaef, "0|129|0x00c800,3|251|0x1a1a1a", 90, 94, 138, 198, 558} function errors() if d('ๅผน็ช—_้€‰ๆ‹ฉ็…ง็‰‡',true)then elseif d('ๅผน็ช—_็…ง็‰‡็กฎ่ฎค้€‰ๅ–',true)then elseif d('ๅผน็ช—_ๅ‡บ้”™ไบ†',true)then elseif d('้”™่ฏฏ_ๆœชไธญ็ญพ',true)then elseif d('็™ปๅฝ•_ๅ‡บ้”™ไบ†',true)then elseif d('ๅ…จๅฑ้”™่ฏฏ_่ดญไนฐๆœชๆˆๅŠŸ',true)then elseif d('ๅผน็ช—_ๅ‡บ้”™ไบ†',true)then elseif d('ๅผน็ช—_ๅ‡บ้”™ไบ†__',true)then click(29,80) moveTo(300,200,300,733,rd(5,20)) delay(2) click(29,80) elseif d('็™ปๅฝ•_ๅ‡บ้”™ไบ†_ๅ›ฝๅฎถ/ๅœฐๅŒบ')then updateNikeLog('ไฟฎๆ”นๅœฐๅŒบ') moveTo(300,800,300,800-rd(300,400),rd(20,30)) --ไธŠๆป‘ delay(rd(2,3)) if d('็™ปๅฝ•_ๅ‡บ้”™ไบ†_ๅ›ฝๅฎถ/ๅœฐๅŒบ_็พŽๅ›ฝ',true)then elseif d('็™ปๅฝ•_ๅ‡บ้”™ไบ†_ๅ›ฝๅฎถ/ๅœฐๅŒบ_ไธญๅ›ฝ',true)then end else return true end end local function mail_rand(length) --้šๆœบ้‚ฎ็ฎฑ local char ='0123456789abcdefghijklmnopqrstuvwxyz' if length < 0 then return false; end local string = ''; local rnd local s local mailheader={} mailheader[0] = '@shuaisports.com' mailheader[1] = '@ssnms.com' mailheader[2] = '@zzaha.com' mailheader[3] = '@vvccb.com' local mail_suffix = mailheader[math.random(#mailheader)] for var = 1,length do rnd = math.random(1,string.len(char)) s = string.sub(char,rnd,rnd+1) string = string..s end return string..os.date("%S")..myRand(4,1,2)..mail_suffix; end function click_random(x,y,n) if n > 1 then for i=1,n do click(x,y,0.8) end else click(x,y,0.8) end end t["ๆˆ‘_่ฎพ็ฝฎ็•Œ้ข_"]={ 0xfbfbfb, "-4|-2|0x0c0c0c,-4|12|0x000000,19|12|0x000000,-356|-3|0x000000", 90, 10, 46, 543, 124} t["ๆˆ‘_้€€ๅ‡บ็™ปๅฝ•_็บข"]={ 0xff3b30, "-4|128|0x007aff", 90, 244, 1073, 516, 1298} t['ๆˆ‘_ๆœชๆฟ€ๆดป']={ 0xb8b8b8, "-26|-21|0xffffff,23|-27|0xffffff,4|6|0xb8b8b8", 90, 601, 1253, 709, 1315 } --ๅคš็‚นๆ‰พ่‰ฒ function logout() local timeline = os.time() local outTimes = 120 while os.time()-timeline < outTimes do if active(var.bid,3) then if d('ไธป่œๅ•_้ฆ–้กต') then click( 657, 1281,3) elseif d('ไธชไบบ้กต้ข')then if d('ไธชไบบ้กต้ข_่ฎพ็ฝฎๆŒ‰้’ฎ',true)then elseif d("ๆˆ‘_่ฎพ็ฝฎ็•Œ้ข_")then t["ๆˆ‘_้€€ๅ‡บ็™ปๅฝ•"]={ 0x000000, "4|3|0xffffff,125|184|0xb8b8b8,297|184|0x000000", 90, 218, 1034, 723, 1323} if d("ๆˆ‘_้€€ๅ‡บ็™ปๅฝ•",true)then else delay(2) moveTo(300,900,300,300,20) delay(3) end end elseif d("ๆˆ‘_้€€ๅ‡บ็™ปๅฝ•_็บข",true)then elseif d("ๆˆ‘_ๆœชๆฟ€ๆดป",true)then elseif d('ๅผ€ๅฑ็™ปๅฝ•')then return true else errors() end end delay(1) end end local degree = 85 t['ไธป็•Œ้ข_็™ปๅฝ•NIKEๅธๅท']={0x363636,"-244|83|0xffffff,-239|78|0x111111,-246|86|0x111111,-459|78|0x111111,-453|83|0xffffff",90,106,16,730,255} t['้”™่ฏฏ_็™ปๅฝ•ๅคฑ่ดฅ']={ 0xfe2020, "249|-7|0xfe0000,324|-2|0xfe0000", 90, 20, 140, 723, 703 } --ๅคš็‚นๆ‰พ่‰ฒ t['้”™่ฏฏ_้€‰ๅฏนๅ›ฝๅฎถ']={ 0x000000, "-72|-5|0xffffff,-339|1|0x000000,340|49|0xb2b2b2", 90, 8, 48, 733, 165 } --ๅคš็‚นๆ‰พ่‰ฒ t['้”™่ฏฏ_ๆœชไธญ็ญพ']={ 0xffffff, "8|-9|0xffffff,-1|-22|0x545455,-23|0|0x545454,22|0|0x545454,-1|22|0x535354", 90, 564, 16, 744, 131 } --ๅคš็‚นๆ‰พ่‰ฒ t['้”™่ฏฏ_้ชŒ่ฏๆ‰‹ๆœบๅท']={ 0xefefef, "537|-6|0xe5e5e5,-22|329|0x000000,604|252|0x000000", 90, 36, 448, 714, 827 } --ๅคš็‚นๆ‰พ่‰ฒ t['้”™่ฏฏ_ๅฏ†็ ้”™่ฏฏ']={ 0xffffff, "-1|1|0xfe0a0a,312|-214|0x363636,300|552|0x000000", 90, 28, 62, 720, 910} t['้”™่ฏฏ_ๆœช่พ“ๅ…ฅๅฏ†็ ']={ <PASSWORD>8d8d, "-30|40|0xfe0000,550|-2|0xfe0000,307|438|0x000000,27|88|0xfe0000,28|88|0xfff1f1", 90, 13, 355, 713, 928} t['็™ปๅฝ•็•Œ้ขn_็”ตๅญ้‚ฎไปถ'] = { 0x8f8f8f,"3|5|0xffffff,14|20|0x8d8d8d,155|-2|0x8d8d8d,155|19|0x8d8d8d,152|8|0xffffff,149|3|0x8d8d8d",degree,84,244,701,472} t['็™ปๅฝ•็•Œ้ขn_ๅฏ†็ '] = { <PASSWORD>,"18|0|<PASSWORD>,1|-18|0xffffff,-2|-20|0x8d8d8d,43|-21|0x8d8d8d,42|-5|0x8d8d8d,42|-1|0xffffff,43|1|0x<PASSWORD>",degree,85,361,155,484} t['้”™่ฏฏ็š„็™ปๅฝ•'] = { 0x8d8d8d,"390|-295|0xfe0000,-113|-197|0xfe0000,387|-120|0xfe0000,-60|-2|0x8d8d8d,264|-373|0xfe0000",degree,15,20,725,839} function login() local timeline = os.time() local outTimes = 3*60 local loginKey = true local pwdKey = true local lookPwd = false local ๆ˜ฏๅฆ่พ“ๅ…ฅ่ฟ‡ๅฏ†็  = false updateNikeLog('ๆญฃๅœจ็™ปๅฝ•') while os.time()-timeline < outTimes do if active(var.bid,3) then if d('ๅผ€ๅฑ็™ปๅฝ•',true)then delay(5) elseif d('้”™่ฏฏ_้ชŒ่ฏๆ‰‹ๆœบๅท')then updateNikeLog('้‡ๆ–ฐ่ฎค่ฏ'); var.account.phone = vCode.getPhone() if var.account.phone then t['้ชŒ่ฏไฝ ็š„ๆ‰‹ๆœบๅท_ๆ‰‹ๆœบๅท็ ']={ 0xb3b3b3, "8|-4|0xffffff,8|-6|0xa9a9a9,17|-22|0xa9a9a9,-83|-15|0xa9a9a9,-83|-12|0xffffff,-66|-9|0xa9a9a9,-49|-15|0xffffff,-45|-19|0xfafafa", 90, 155, 475, 514, 537} if d('้ชŒ่ฏไฝ ็š„ๆ‰‹ๆœบๅท_ๆ‰‹ๆœบๅท็ ',false)then click( 471, 503 ,rd(3,5)) clearTxt() inputword(var.account.phone) delay(3) end end t['้ชŒ่ฏไฝ ็š„ๆ‰‹ๆœบๅท_ๅ‘้€้ชŒ่ฏ็ ']={ 0x111111, "3|2|0xe5e5e5,7|6|0x111111", 90, 535, 376, 686, 435} if var.account.phone and d('้ชŒ่ฏไฝ ็š„ๆ‰‹ๆœบๅท_ๅ‘้€้ชŒ่ฏ็ ')then if d('้ชŒ่ฏไฝ ็š„ๆ‰‹ๆœบๅท_ๅ‘้€้ชŒ่ฏ็ ',true)then sms = vCode.getMessage() if sms ~= "" then log(sms,true) inputword(sms) ้ชŒ่ฏ็  = false ็™ปๅฝ• = true else return false end end end t['้ชŒ่ฏไฝ ็š„ๆ‰‹ๆœบๅท_็ปง็ปญ']={ 0xffffff, "-2|-4|0x000000,-311|-44|0x000000,315|26|0x000000", 90, 33, 203, 733, 966} if var.account.phone and d('้ชŒ่ฏไฝ ็š„ๆ‰‹ๆœบๅท_็ปง็ปญ',true)then delay(rd(8,10)) end elseif d('็™ปๅฝ•Nike+ๅธๅท') or d('ไธป็•Œ้ข_็™ปๅฝ•NIKEๅธๅท')then if d('็™ปๅฝ•Nike+ๅธๅท_ไฝฟ็”จ็”ตๅญ้‚ฎไปถ็™ปๅฝ•',true)then delay(3) elseif d('็™ปๅฝ•็•Œ้ขn_็”ตๅญ้‚ฎไปถ',true)then updateNikeLog('่พ“ๅ…ฅๅธๅท..'); delay(rd(2,3)) clearTxt() input(var.account.login) elseif d('็™ปๅฝ•็•Œ้ขn_ๅฏ†็ ',true)then updateNikeLog('่พ“ๅ…ฅๅฏ†็ ..'); delay(3) input(var.account.pwd) pwdKey = false lookPwd = true ๆ˜ฏๅฆ่พ“ๅ…ฅ่ฟ‡ๅฏ†็  = true else if d('็™ปๅฝ•Nike+ๅธๅท_็ปง็ปญ',true) or d('็™ปๅฝ•Nike+ๅธๅท',true)then delay(rd(8,10)) end end d('้”™่ฏฏ็š„็™ปๅฝ•',true) d('ๅผน็ช—_่พ“ๅ…ฅ็š„ๅฎŒๆˆ',true) elseif d("้”™่ฏฏ_ๆœช่พ“ๅ…ฅๅฏ†็ ",true)then input(var.account.pwd) updateNikeLog('็™ปๅฝ•้‡ๅˆฐ้”™่ฏฏ'); delay(2) return false elseif d('้”™่ฏฏ็š„็™ปๅฝ•',true) then elseif d('look-้ฆ–้กต-่œๅ•') then if ๆ˜ฏๅฆ่พ“ๅ…ฅ่ฟ‡ๅฏ†็  then update_token(); end return true elseif lookPwd and d('้”™่ฏฏ_ๅฏ†็ ้”™่ฏฏ')or d('้”™่ฏฏ_้€‰ๅฏนๅ›ฝๅฎถ') then updateNikeLog('ๅฏ†็ ้”™่ฏฏ'); disable(); return false else log('tips') t['ๅผน็ช—_่พ“ๅ…ฅ็š„ๅฎŒๆˆ_black']={0x000000, "12|-7|0x000000,3|-4|0xffffff,-27|-5|0xffffff,-29|-7|0x000000,-18|6|0xffffff",90,623,696,735,1058} --ๅคš็‚นๆ‰พ่‰ฒ if d('ๅผน็ช—_่พ“ๅ…ฅ็š„ๅฎŒๆˆ',true)then elseif d('ๅผน็ช—_่พ“ๅ…ฅ็š„ๅฎŒๆˆ_black',true)then else errors() end end end delay(1) log('login->'..os.time()-timeline) end end t['ไธป่œๅ•_้ฆ–้กต']={ 0x000000, "187|-2|0xb8b8b8,374|9|0xb8b8b8,562|2|0xb8b8b8,-4|4|0xffffff", 90, 21, 1254, 707, 1312 } --้ฆ–้กต,ๅ‘็Žฐ,ๆ”ถไปถ็ฎฑ,ๆˆ‘ t['็ฒพ้€‰ๆฟ€ๆดปไธญ']={ 0x0f0f0f, "0|42|0x000000,2|45|0xb2b2b2", 90, 167, 40, 199, 145 } --ๅคš็‚นๆ‰พ่‰ฒ t['็ƒญๅ–ๆฟ€ๆดปไธญ']={ 0x000000, "0|48|0x000000,0|49|0xb2b2b2", 90, 360, 48, 375, 144 } --ๅคš็‚นๆ‰พ่‰ฒ t['็ƒญๅ–ๆฟ€ๆดปไธญ_ๅˆ‡ๆขๆจกๅผ']={ 0xb8b8b8, "-9|7|0xffffff,-9|8|0xb8b8b8,0|-9|0xb8b8b8", 90, 174, 133, 201, 210 } --ๅคš็‚นๆ‰พ่‰ฒ t['็ƒญๅ–ๆฟ€ๆดปไธญ_ๅคงๅ›พๆจกๅผ']={ 0xffffff, "1|-1|0xb8b8b8,10|-10|0xb8b8b8,-11|11|0xb8b8b8,-11|1|0xffffff", 90, 173, 129, 203, 221 } --ๅคš็‚นๆ‰พ่‰ฒ t['็ƒญๅ–ๆฟ€ๆดปไธญ_ๆฒกๆœ‰็ฌฌไบŒไธชๅ•†ๅ“']={ 0x000000, "3|2|0xf5f5f5", 90, 7, 1085, 735, 1223 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๆœชๆ”ถ่—็š„้ž‹ๅญ']={ 0xf5f5f5, "-70|-15|0x000000,-71|-14|0xf5f5f5,-71|12|0xf5f5f5,-70|11|0x000000,69|12|0x000000,68|-15|0xf5f5f5", 90, 493, 7, 743, 1231 } --ๅคš็‚นๆ‰พ่‰ฒ t['้ž‹ๅญ่ฏฆๆƒ…้กต้ข']={ 0x000000, "12|0|0xffffff,11|-10|0x000000,11|11|0x000000,698|-1|0xffffff", 90, 5, 34, 746, 115 } --ๅคš็‚นๆ‰พ่‰ฒ t['้ž‹ๅญ่ฏฆๆƒ…้กต้ข_ๅฟƒ']={ 0x111111, "0|-11|0xffffff,-16|-10|0x111111,9|-13|0x111111,0|15|0x111111,-12|8|0xffffff,-10|6|0x111111", 90, 443, 10, 495, 1300 } t['้ž‹ๅญ่ฏฆๆƒ…้กต้ข_ๅฟƒ_็‚นไบฎ']={ 0xff0015, "0|-10|0xffffff,-16|-4|0xff0015,17|-4|0xff0015,1|15|0xff0015", 90,443, 10, 495, 1300 } t['้ž‹ๅญ่ฏฆๆƒ…้กต้ข_ไธ‹ๅ•ๆŒ‰้’ฎ']={ 0x000000, "-4|2|0xf5f5f5,-28|-4|0x000000,-6|-37|0x000000,-7|28|0x000000,-6|69|0xffffff", 90, 13, 17, 87, 1250 } --ๅคš็‚นๆ‰พ่‰ฒ t['ไธบไฝ ็š„่ฎขๅ•ไป˜ๆฌพ_x']={ 0x000000, "-449|1215|0x00aaef,-674|1165|0x1a1a1a,5|1259|0x1a1a1a,11|1252|0x1a1a1a", 90, 10, 12, 738, 1320 } --ๅคš็‚นๆ‰พ่‰ฒ t['ไธบไฝ ็š„่ฎขๅ•ไป˜ๆฌพ_x_wechat']={ 0x000000, "-429|1196|0x00c800,-420|1218|0x00c800,-667|1249|0x1a1a1a", 90, 13, 8, 736, 1315 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๆœ็ดข้กต้ข_ๅ–ๆถˆ']={ 0x000000, "-1|43|0xb2b2b2,-676|-5|0x111111,-663|-4|0xffffff,-659|-4|0x111111", 90, 10, 41, 742, 163 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅผน็ช—_ๅณไธŠ่ง’็š„x']={ 0xffffff, "-23|1|0x545454,-1|-22|0x545455,21|0|0x545454,0|22|0x535354", 90, 640, 42, 711, 101 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅผน็ช—_็ซ‹ๅณ่ดญไนฐๅผน็ช—']={ 0xffffff, "325|15|0x1a1a1a,-360|-3|0x1a1a1a,188|-497|0x00aaef", 90, 6, 314, 737, 1320 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅผน็ช—_็ปง็ปญ้€‰ๆ‹ฉ็ ']={ 0xb8b8b8, "678|8|0xb8b8b8,331|-40|0xb8b8b8,331|59|0xb8b8b8,321|9|0xffffff", 90, 6, 314, 737, 1320 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅผน็ช—_็ปง็ปญ้€‰ๆ‹ฉ็ _ไธŠ้ƒจๅˆ†']={ 0x000000, "3|0|0xffffff,-20|0|0xffffff,-670|-2|0x000000,-672|-6|0xffffff", 90, 7, 240, 741, 950 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅผน็ช—_็ปง็ปญ้€‰ๆ‹ฉ็ _้šๆœบๅฏ้€‰']={ 0x000000, "5|0|0xffffff,0|-7|0x000000", 90, 46, 753, 697, 1136 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅผน็ช—_็ปง็ปญ้€‰ๆ‹ฉ็ _็ปง็ปญ้ป‘']={ 0xffffff, "-333|8|0x1a1a1a,346|2|0x1a1a1a,-3|-48|0x1a1a1a,-7|51|0x1a1a1a", 90, 17, 1168, 727, 1309 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅผน็ช—_็ปง็ปญ้€‰ๆ‹ฉ็ _็ปง็ปญ้ป‘_็ผ–่พ‘']={ 0x000000, "-1|-10|0x0d0d0d,-514|128|0xff0000", 90, 25, 567, 737, 889} t['ๅผน็ช—_ๅˆ ้™ค้”™่ฏฏๅœฐๅ€']={ 0x000000, "-2|-2|0xffffff,-326|-182|0x1a1a1a,349|-83|0x1a1a1a,17|-140|0xffffff", 90, 21, 224, 733, 1330} t['ๅผน็ช—_ๅˆ ้™ค้”™่ฏฏๅœฐๅ€_็บข่‰ฒๆก†']={ 0xff0000, "0|15|0xff0000", 90, 14, 432, 741, 928} t['ๅผน็ช—_่ฏท่พ“ๅ…ฅๅฏ†็ ']={ 0xffffff, "48|-144|0xdddddd,-2|-334|0x000000,174|-377|0xffffff,-352|30|0xffffff", 90, 98, 66, 654, 672 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅผน็ช—_ๆทปๅŠ ้…้€ๅœฐๅ€']={ 0xff0000, "-525|620|0xb8b8b8,-200|573|0xb8b8b8,42|119|0x00aaef,145|580|0xb8b8b8", 90, 19, 460, 740, 1321 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅผน็ช—_ๆทปๅŠ ้…้€ๅœฐๅ€_ๅกซ']={ 0xffffff, "-338|-6|0x1a1a1a,344|-55|0x1a1a1a,-324|-954|0x000000,320|-941|0x000000,319|-941|0xffffff", 90, 19, 460, 740, 1321 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅผน็ช—_ๆทปๅŠ ้…้€ๅœฐๅ€_ไธŠ้ƒจๅˆ†']={ 0x000000, "2|0|0xffffff,1|-4|0xffffff,1|-3|0x000000,-665|-8|0x000000", 90, 14, 286, 727, 347 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅผน็ช—_่พ“ๅ…ฅๅœฐๅ€็š„ๅฎŒๆˆ']={ 0x191919, "-16|-5|0x000000,-17|-7|0xffffff", 90, 641, 665, 740, 898 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅผน็ช—_่พ“ๅ…ฅๅœฐๅ€ๅŽไธŠๆ‹‰ไธ€ไธ‹']={ 0x1a1a1a, "-677|0|0x1a1a1a,-682|8|0x1a1a1a,-683|8|0xffffff,4|8|0xffffff", 90, 19, 1310, 727, 1333 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅผน็ช—_ๅกซๅœฐๅ€_ไธŠๆป‘ไบ†']={ 0xffffff, "-15|0|0x1a1a1a,-316|-51|0x1a1a1a,365|44|0x1a1a1a,393|-995|0xffffff,-336|-988|0xffffff", 90, 0, 70, 749, 1332 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅผน็ช—_ๅ–ๅ…‰ไบ†']={ 0x000000, "-137|-68|0xaaaaaa,107|-68|0xaaaaaa,4|-226|0x000000", 90, 114, 487, 633, 854 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅผน็ช—_ๆ™ฎ้€š่พพ']={ 0x1a1a1a, "0|3|0xffffff,-322|-153|0xffffff,-318|-150|0x000000,303|-151|0x000000", 90, 10, 1055, 743, 1327} t['ๅˆ†ไบซๆŒ‰้’ฎ']={ 0x000000, "-2|-8|0xffffff,-1|-8|0x000000,0|-13|0x000000,-2|9|0xffffff,0|10|0x000000,-24|10|0x000000,18|0|0x000000", 90, 247, 418, 312, 1221} t['ไธป่œๅ•_้ฆ–้กตๆœชๆฟ€ๆดป']={0xffffff,"2|-21|0xb8b8b8,-14|-4|0xb8b8b8,6|1|0xb8b8b8,5|2|0xffffff,12|14|0xffffff",90,56,1258,124,1310} t['ๆ”ถไปถ็ฎฑ้กต้ข'] = { 0,"-18|-26|0xffffff,-21|-26|0,18|7|0,12|12|0xffffff,12|11|0",degree,420,1234,523,1322} t['ๆˆ‘็š„้กต้ข'] = { 0,"-1|-18|0xffffff,-1|-21|0,-16|16|0,12|16|0xffffff,15|16|0",degree,612,1237,702,1319} t['ๆต่งˆ้กต้ข'] = { 0xffffff,"9|-7|0,-8|10|0,-3|-3|0,-15|-2|0xffffff,-19|-10|0,18|13|0",degree,227,1242,330,1322} t['้ฆ–้กต้กต้ข'] = { 0,"-13|2|0xffffff,-15|13|0,16|11|0,4|-11|0xffffff,13|-19|0",degree,38,1236,143,1323} t['ๆŒ‰ๅฐบ็ ็ญ›้€‰'] = { 0x111111,"6|-1|0xffffff,7|-1|0x111111,28|-1|0x111111,199|-1|0x757575,199|18|0x757575,21|15|0x111111,20|15|0xffffff",degree,7,50,273,112} t['่ดญ็‰ฉๅๅฅฝ่ฎพ็ฝฎ'] = { 0x111111,"0|-8|0xfafafa,-13|-13|0x111111,14|-13|0x111111,178|1109|0x111111,174|1106|0xffffff,174|1101|0xffffff",degree,260,75,720,1304} t['้ž‹ๅญ่ฏฆๆƒ…้กต้ข'] = { 0xffffff,"-1|-23|0x3f3f3f,22|1|0x3f3f3f,-1|23|0x3f3f3f,9|11|0xffffff,-26|3|0x3f3f3f",degree,621,65,716,143} t['look-้ฆ–้กต-่œๅ•']={0x111111, "0|0|0x111111,16|-9|0xffffff,18|-10|0x111111,164|-7|0xcccccc",90,9,1231,328,1321} ๆ‘˜่ฆ็ƒญๅ–={{60, 82, 0xffffff},{174, 81, 0xe2e2e2}} t['look-้ฆ–้กต-ๆŒ‰ๅฐบ็ ็ญ›้€‰']={0x111111, "0|0|0x111111,7|-1|0xfcfcfc,9|-1|0x111111,91|-20|0x757575,-5|-18|0x111111,-6|-18|0xfcfcfc",90,19,47,258,207} t['look-้ฆ–้กต-ๅ–œๆฌขๅฟƒ']={0xf6f6f6, "0|0|0xf6f6f6,2|-10|0x111111,-14|-6|0x111111,15|-4|0xf6f6f6,18|-4|0x111111,2|11|0xf6f6f6,2|16|0x111111",90,86,160,148,1332} t['look-้ž‹ๅนป็ฏx']={0xffffff, "0|0|0xffffff,-6|-12|0x4e4e4e,-10|-9|0xffffff,-112|11|0x4d4d4d,-106|6|0xffffff",90,507,115,720,191} t['look-้ž‹่ฏฆๆƒ…x']={0xffffff, "0|0|0xffffff,9|-9|0xffffff,-11|-9|0xffffff,31|-1|0x4e4840,0|33|0x4e4a43",70,626,63,715,148} t['look-้ž‹่ฏฆๆƒ…-ๅบ•้ป‘']={0xffffff, "0|0|0xffffff,-252|-61|0x111111,303|-61|0x111111,276|56|0x111111,-246|56|0x111111",90,24,1168,722,1304} t['look-่ดญ็‰ฉๅๅฅฝ่ฎพ็ฝฎ']={0x111111, "0|0|0x111111,183|1110|0x111111,181|1103|0xffffff,22|-9|0x111111,6|-10|0xfafafa",90,322,82,614,1270} t['look-้ฆ–้กตๆœชๆฟ€ๆดป']={0xcccccc, "0|0|0xcccccc,-17|-8|0xffffff,-21|-8|0xcccccc,0|-26|0xcccccc,17|3|0xffffff,17|12|0xcccccc",90,36,1235,136,1315} t['look-้ฆ–้กต-x']={0xffffff, "0|0|0xffffff,0|-10|0x414141,-6|-6|0xfbfbfb,-13|1|0x414141,1|14|0x414141",90,661,56,712,104} function snkrslook() if UIvalues == nil then UIvalues = {} UIvalues.look_min_time = 90 UIvalues.look_max_time = 150 end local timeline = os.time() local outTimes = math.random(UIvalues.look_min_time+0,UIvalues.look_max_time+0) local ็œ‹้ž‹ๅ‘ไธ‹ๆป‘ๅŠจ่ฎกๆ•ฐ = 0 local ้ž‹่ฏฆๆƒ…ไธ‹ๆป‘่ฎกๆ•ฐ = 0 local setp_ = '' local setp__ = "" local setp___ = 0 updateNikeLog('ๆต่งˆใ€Œ'..outTimes..'ใ€') while (os.time()-timeline < outTimes) do if active(var.bid,3) then if ( d('look-้ฆ–้กต-่œๅ•') ) then setp_ = 'look-้ฆ–้กต-่œๅ•' ็œ‹้ž‹ๅ‘ไธ‹ๆป‘ๅŠจ่ฎกๆ•ฐ = 0 click(ๆ‘˜่ฆ็ƒญๅ–[rd(1,2)][1],ๆ‘˜่ฆ็ƒญๅ–[1][2],2) moveTo(300,800,300,800-rd(200,400),rd(20,30)) --ๅ‘ไธŠๆป‘ๅŠจ elseif d('look-้ฆ–้กต-ๆŒ‰ๅฐบ็ ็ญ›้€‰') then setp_ = 'look-้ฆ–้กต-ๆŒ‰ๅฐบ็ ็ญ›้€‰' ็œ‹้ž‹ๅ‘ไธ‹ๆป‘ๅŠจ่ฎกๆ•ฐ = ็œ‹้ž‹ๅ‘ไธ‹ๆป‘ๅŠจ่ฎกๆ•ฐ + 1 if ( ็œ‹้ž‹ๅ‘ไธ‹ๆป‘ๅŠจ่ฎกๆ•ฐ > rd(6,10) ) then moveTo(300,500,300,500+rd(200,400),rd(20,30)) --ๅ‘ไธ‹ๆป‘ๅŠจ else moveTo(300,800,300,800-rd(200,400),rd(20,30)) --ๅ‘ไธŠๆป‘ๅŠจ if rd(1,100)>50 then d('look-้ฆ–้กต-ๅ–œๆฌขๅฟƒ',true,1,'ๅ–œๆฌข',2) end if rd(1,100) > 40 then log('ๅ‡†ๅค‡็œ‹่ฏฆๆƒ…') click(rd(88,651),rd(187,946),2) ้ž‹่ฏฆๆƒ…ไธ‹ๆป‘่ฎกๆ•ฐ = 0 end end elseif d('look-้ž‹่ฏฆๆƒ…x') or d('look-้ž‹่ฏฆๆƒ…-ๅบ•้ป‘')then setp_ = 'look-้ž‹่ฏฆๆƒ…x' ้ž‹่ฏฆๆƒ…ไธ‹ๆป‘่ฎกๆ•ฐ = ้ž‹่ฏฆๆƒ…ไธ‹ๆป‘่ฎกๆ•ฐ + 1 moveTo(300,800,300,800-rd(200,400),rd(20,30)) --ๅ‘ไธŠๆป‘ๅŠจ if rd(1,100) > 90 then d('look-้ž‹่ฏฆๆƒ…x',true) elseif ้ž‹่ฏฆๆƒ…ไธ‹ๆป‘่ฎกๆ•ฐ > rd(5,8) then d('look-้ž‹่ฏฆๆƒ…x',true) end elseif d('look-่ดญ็‰ฉๅๅฅฝ่ฎพ็ฝฎ',true)then setp_ = 'look-่ดญ็‰ฉๅๅฅฝ่ฎพ็ฝฎ' elseif d('look-้ฆ–้กตๆœชๆฟ€ๆดป',true)then setp_ = 'look-้ฆ–้กตๆœชๆฟ€ๆดป' elseif d('look-้ฆ–้กต-x',true)then setp_ = 'look-้ฆ–้กต-x' else setp_ = 'ๅ…ถๅฎƒ' end if setp_ == setp__ then setp___ = setp___ + 1 else setp__ = setp_ end if setp___ >= 15 then click(672, 106) setp___ = 0 end log({setp_,setp__,setp___}) if setp_ == 'ๅ…ถๅฎƒ' then delay(0.5) else delay(rd(1,3)) end log('look->'..os.time()-timeline) end end -- body return true end function delay(times) local times = times or 1 local timeLine = os.time() while os.time() - timeLine <= times do mSleep(1000) if (times-(os.time() - timeLine) > 3) then log("ๅ€’่ฎกๆ—ถ->ใ€Œ".. times-(os.time() - timeLine) .."ใ€",true) end end end function ip() local url = 'http://nikeapi.honghongdesign.cn/?s=App.IndexIp.Ip' local ip___ = get(url) if ip___ then return ip___['data'] end end function whiteip() local url = 'http://www.jinglingdaili.com/Users-whiteIpAddNew.html?appid=2420&appkey=ef2f43ef02109467a23c34f5b1e0982c&type=dt&index=&whiteip='..ip() return get(url) end function getNetIPproxy() local url = 'http://t.ipjldl.com/index.php/api/entry?method=proxyServer.generate_api_url&packid=0&fa=0&fetch_key=&groupid=0&qty=1&time=102&pro=&city=&port=1&format=json&ss=5&css=&dt=1&specialTxt=3&specialJson=&usertype=2' local ip___ = get(url) if ip___ then log(ip___['data'][1]) return ip___['data'][1] end end if t == nil then t={} end t['vpn-้ฆ–้กต-ๆœชๆฟ€ๆดป']={0x000000, "0|0|0x000000,1|-2|0xf5f5f5,1|-4|0x222222,0|-19|0x808080",90,65,1243,124,1323} t['vpn-้ฆ–้กต-ๆฟ€ๆดป']={0x4587c2, "0|0|0x4587c2,1|-2|0xf5f5f5,1|-4|0x5d96c9,0|-19|0x4587c2",90,65,1243,124,1323} t['vpn-้ฆ–้กต-็ผ–่พ‘']={0x4587c2, "0|0|0x4587c2,-13|-1|0xffffff,-687|0|0xff9400",90,2,524,739,996} t['vpn-้ฆ–้กต-ๅผ€ๅ…ณๅผ€']={0xffffff, "0|0|0xffffff,67|-1|0xe5e5e5,-32|3|0xd9d9d9,16|-29|0xe3e3e3",90,601,192,729,296} t['vpn-้ฆ–้กต-ๅผ€ๅ…ณๅ…ณ']={0x4486c0, "0|0|0x4486c0,69|-1|0x407fb6,18|-29|0x4486c0",90,604,194,730,287} t['vpn-้ฆ–้กต-่ฟžๆŽฅๆˆๅŠŸ']={0x000000, "0|0|0x000000,-2|-22|0xffffff,-3|38|0xffffff",90,259,186,453,293} t['vpn-้ฆ–้กต-็ผ–่พ‘่Š‚็‚น']={0xed402e, "0|0|0xed402e,1|-7|0xed402e,-14|-18|0xffffff",90,245,782,516,1175} t['vpn-้ฆ–้กต-็ผ–่พ‘่Š‚็‚น-HTTP']={0x8e8e93, "0|0|0x8e8e93,8|-8|0x8e8e93,20|-8|0xffffff,23|8|0x8e8e93,117|0|0xc7c7cc,108|-10|0xc7c7cc",90,561,191,729,293} hpptwz = {301, 781} t['vpn-้ฆ–้กต-็ผ–่พ‘่Š‚็‚น-ๅฎŒๆˆ']={0xffffff, "0|0|0xffffff,5|-3|0x4386c5,34|-7|0x4386c5,39|-12|0xffffff",90,622,53,727,113} t['vpn-ๅ…ถๅฎƒ']={0xffffff, "0|0|0xffffff,22|-15|0x4386c5,399|-5|0xffffff,664|-10|0xffffff,656|3|0x4386c5",90,23,41,729,116} function Shadowrockets_out() local arrowbid = "com.liguangming.Shadowrocket" local setp_ = '' local setp__ = "" local setp___ = 0 local timeline = os.time() local outTimes = 60 while (os.time()-timeline < outTimes) do if active(arrowbid,5) then if d('vpn-้ฆ–้กต-ๆฟ€ๆดป') then setp_ = 'vpn-้ฆ–้กต-ๆฟ€ๆดป' if d('vpn-้ฆ–้กต-็ผ–่พ‘') then setp_ = 'vpn-้ฆ–้กต-็ฌฌไธ€้กต' if d('vpn-้ฆ–้กต-ๅผ€ๅ…ณๅ…ณ',true)then else if d('vpn-้ฆ–้กต-ๅผ€ๅ…ณๅผ€')then return true end end elseif d('vpn-้ฆ–้กต-็ผ–่พ‘่Š‚็‚น')then setp_ = 'vpn-้ฆ–้กต-็ผ–่พ‘่Š‚็‚น' if d("vpn-้ฆ–้กต-็ผ–่พ‘่Š‚็‚น-HTTP") == nil then click(649, 239) click(301, 781) end log(whiteip()) local vpnList = getNetIPproxy() local vpnlistWz = {{200, 398, 0xffffff},{200, 484, 0xffffff}} click( vpnlistWz[1][1],vpnlistWz[1][2],1) keyDown("Clear") keyUp("Clear") delay(1) inputText(vpnList['IP']) delay(1) click( vpnlistWz[2][1],vpnlistWz[2][2],1) keyDown("Clear") keyUp("Clear") delay(1) inputText(vpnList['Port']) delay(1) if d('vpn-้ฆ–้กต-็ผ–่พ‘่Š‚็‚น-ๅฎŒๆˆ',true)then vpnInputKey = true end end elseif d('vpn-้ฆ–้กต-ๆœชๆฟ€ๆดป',true)then setp_ = 'vpn-้ฆ–้กต-ๆœชๆฟ€ๆดป' elseif d('vpn-ๅ…ถๅฎƒ',true)then setp_ = 'ๅ…ถๅฎƒUI' else setp_ = 'ๅ…ถๅฎƒ' end if setp_ == setp__ then setp___ = setp___ + 1 else setp__ = setp_ end if setp___ >= 15 then closeApp(arrowbid,1) setp___ = 0 end log({setp_,setp___,'vpn->'..os.time()-timeline}) if setp_ == 'ๅ…ถๅฎƒ' then delay(0.5) else delay(rd(1,3)) end end end end function Shadowrockets() local arrowbid = "com.liguangming.Shadowrocket" local setp_ = '' local setp__ = "" local setp___ = 0 local vpnInputKey = false local timeline = os.time() local outTimes = 60 while (os.time()-timeline < outTimes) do if active(arrowbid,5) then if d('vpn-้ฆ–้กต-ๆฟ€ๆดป') then setp_ = 'vpn-้ฆ–้กต-ๆฟ€ๆดป' if d('vpn-้ฆ–้กต-็ผ–่พ‘') then setp_ = 'vpn-้ฆ–้กต-็ฌฌไธ€้กต' if vpnInputKey then if d('vpn-้ฆ–้กต-ๅผ€ๅ…ณๅผ€',true)then elseif d('vpn-้ฆ–้กต-ๅผ€ๅ…ณๅ…ณ') then if d('vpn-้ฆ–้กต-่ฟžๆŽฅๆˆๅŠŸ') then return true end end else if d('vpn-้ฆ–้กต-ๅผ€ๅ…ณๅ…ณ',true)then else d('vpn-้ฆ–้กต-็ผ–่พ‘',true) end end elseif d('vpn-้ฆ–้กต-็ผ–่พ‘่Š‚็‚น')then setp_ = 'vpn-้ฆ–้กต-็ผ–่พ‘่Š‚็‚น' if d("vpn-้ฆ–้กต-็ผ–่พ‘่Š‚็‚น-HTTP") == nil then click(649, 239) click(301, 781) end log(whiteip()) local vpnList = getNetIPproxy() local vpnlistWz = {{200, 398, 0xffffff},{200, 484, 0xffffff}} click( vpnlistWz[1][1],vpnlistWz[1][2],1) keyDown("Clear") keyUp("Clear") delay(1) inputText(vpnList['IP']) delay(1) click( vpnlistWz[2][1],vpnlistWz[2][2],1) keyDown("Clear") keyUp("Clear") delay(1) inputText(vpnList['Port']) delay(1) if d('vpn-้ฆ–้กต-็ผ–่พ‘่Š‚็‚น-ๅฎŒๆˆ',true)then vpnInputKey = true end end elseif d('vpn-้ฆ–้กต-ๆœชๆฟ€ๆดป',true)then setp_ = 'vpn-้ฆ–้กต-ๆœชๆฟ€ๆดป' elseif d('vpn-ๅ…ถๅฎƒ',true)then setp_ = 'ๅ…ถๅฎƒUI' else setp_ = 'ๅ…ถๅฎƒ' end if setp_ == setp__ then setp___ = setp___ + 1 else setp__ = setp_ end if setp___ >= 15 then closeApp(arrowbid,1) setp___ = 0 end log({setp_,setp___,'vpn->'..os.time()-timeline}) if setp_ == 'ๅ…ถๅฎƒ' then delay(0.5) else delay(rd(1,3)) end end end end nLog('arrow ๅŠ ๆˆชๅฎŒๆˆ') function get_account() getIdUrl = 'http://nikeapi.honghongdesign.cn/?s=App.NikeSelect.NikeFetch&re_login='..UIvalues.again local data = get(getIdUrl); if data ~= nil and data~= '' and data ~= 'timeout' then log(data) if type(data.data) == "table" then var.account.login = data.data.email var.account.pwd = <PASSWORD> var.account.phone = data.data.data.verifiedPhone var.account.id = data.data.id var.account.first_name_ = data.data.data.firstName var.account.last_names_ = data.data.data.lastName var.account.address_country = data.data.data.address1 var.account.token = data.data.token log('var.account.token') log(var.account.token) log('var.account.token-end') if var.account.token then if #var.account.token >10 then AccountInfoBack() end end local account_txt = "ๆ‰ง่กŒ่‡ณ "..var.account.id .."\n่ดฆๅท = "..var.account.login.."\nๅฏ†็  = "..<PASSWORD> dialog(account_txt,2) log(account_txt) else dialog("ๆš‚ๆ— ๅธๅท", 60*3) return false end end delay(2) end --็”จhttp.getๅฎž็Žฐไธ‹่ฝฝๆ–‡ไปถๅŠŸ่ƒฝ local sz = require("sz") local cjson = sz.json local http = sz.i82.http function downFile(url, path) status, headers, body = http.get(url) if status == 200 then file = io.open(path, "wb") if file then file:write(body) file:close() return true else return -1; end else return status; end end --่ฟ˜ๅŽŸๅธๅท function AccountInfoBack() local sz = require("sz") local json = sz.json local appbid = 'com.nike.onenikecommerce' local AccountInfo = appDataPath(appbid).."/Documents/ifkc.plist" log(AccountInfo); local url = 'http://nikeapi.honghongdesign.cn/' .. var.account.token downFile(url, AccountInfo) toast('ไธ‹่ฝฝๅฎŒๆˆ',1) mSleep(2000) end function main() if UIvalues.netMode ~= '3' or Shadowrockets_out() then get_account() if UIvalues.netMode == '3' then Shadowrockets() end if false or login()then get("http://127.0.0.1:8080/api/reportInfo"); if snkrslook() then backId() updateNikeLog('SNKRSๅค็™ปๅฎŒๆˆ') end closeX(var.bid) delay(2) end end end <file_sep> require("TSLib") require("tsp") function get(url) local sz = require("sz") local http = require("szocket.http") local res, code = http.request(url); if code == 200 then local json = sz.json if res ~= nil then return json.decode(res) end end end function get_(url) local sz = require("sz") local http = require("szocket.http") local res, code = http.request(url); if code == 200 then if res ~= nil then return res end end end function _vCode_ym() --็ˆฑๅฐšๅนณๅฐ local User = 'shuaishuai87' local Pass = '<PASSWORD>' local PID = '1059' local token,number,pid = "","","" local Urls = 'http://v6.aishangpt.com:88/yhapi.ashx' return { login=(function() local RetStr for i=1,5,1 do toast("่Žทๅ–token\n"..i.."ๆฌกๅ…ฑ5ๆฌก") mSleep(1500) local urls = Urls..'?act=login&ApiName='..User..'&PassWord='..Pass log(urls) RetStr = get_(urls) if RetStr then nLog(RetStr) RetStr = strSplit(RetStr,"|") if RetStr[1] == '1' then token = RetStr[2] log('token='..token,true) break else toast("fail--"..RetStr[1]) mSleep(1500) end end end return RetStr; end), getPhone=(function() local RetStr="" local lx_url = Urls.."?act=getPhone&iid="..PID.."&token="..token log(lx_url) RetStr = get_(lx_url) if RetStr ~= "" and RetStr ~= nil then log(RetStr,true) RetStr = strSplit(RetStr,"|") end if RetStr[1]== '1' then pid = RetStr[2] number = RetStr[5] log(number) local phone_title = (string.sub(number,1,3)) local blackPhone = {'165','144','141','142','143','144','145','146','147'} for k,v in ipairs(blackPhone) do if phone_title == v then local lx_url = Urls..'?act=addBlack&pid='..pid..'&token='..token.."&reason=%E4%B8%8D%E8%83%BD%E4%BD%BF%E7%94%A8" get_(lx_url); log("ๆ‹‰้ป‘->"..number) return false end end local self_phone = get('http://39.108.184.74/api/Public/tjj/?service=Nike.Checkphone&phone='..number) if self_phone.data then log("ๆ‰‹ๆœบๅทๅฏไปฅไฝฟ็”จ") return number else toast('่‡ชๅทฑ้กถๅท\nๅ‡†ๅค‡ๆ‹‰้ป‘'); local lx_url = Urls..'?act=addBlack&pid='..pid..'&token='..token.."&reason=%E4%B8%8D%E8%83%BD%E4%BD%BF%E7%94%A8" get_(lx_url); log("ๆ‹‰้ป‘->"..number) end else log(RetStr[1],true) end end), getMessage=(function() local Msg for i=1,25,1 do mSleep(3000) local urls = Urls.. "?act=getPhoneCode&pid="..pid.."&token="..token log(urls) RetStr = get_(urls) if RetStr then local arr = strSplit(RetStr,"|") if arr[1] == '1' then Msg = arr[2] log(Msg,true) end if type(tonumber(Msg))== "number" then return Msg end end toast(tostring(RetStr).."\n"..i.."ๆฌกๅ…ฑ25ๆฌก") end return "" end), addBlack=(function() local lx_url = Urls..'?act=addBlack&pid='..pid..'&token='..token.."&reason=%E4%B8%8D%E8%83%BD%E4%BD%BF%E7%94%A8" return get_(lx_url) end), } end --ๆฅไฟกๅนณๅฐ function _vCode_lx() --ๆฅไฟก local User = 'yxs123456' local Pass = '<PASSWORD>' local PID = '1018' local token,uid,number = "","" return { login=(function() local RetStr for i=1,5,1 do toast("่Žทๅ–token\n"..i.."ๆฌกๅ…ฑ5ๆฌก") mSleep(1500) local lx_url = 'http://api.smskkk.com/api/do.php?action=loginIn&name='..User..'&password='..Pass log(lx_url) RetStr = httpGet(lx_url) if RetStr then RetStr = strSplit(RetStr,"|") if RetStr[1] == 1 or RetStr[1] == '1' then token = RetStr[2] log('token='..token,true) break end else log(RetStr) end end return RetStr; end), getPhone=(function() local RetStr="" local urls = "http://api.smskkk.com/api/do.php?action=getPhone&sid="..PID.."&token="..token log(urls) RetStr = httpGet(urls) if RetStr ~= "" and RetStr ~= nil then RetStr = strSplit(RetStr,"|") end if RetStr[1] == 1 or RetStr[1]== '1' then number = RetStr[2] log(number) local phone_title = (string.sub(number,1,3)) local blackPhone = {'165','144','141','142','143','144','145','146','147'} for k,v in ipairs(blackPhone) do if phone_title == v then local lx_url = 'http://api.smskkk.com/api/do.php?action=addBlacklist&sid='..PID..'&phone='..number..'&token='..token httpGet(lx_url); log("ๆ‹‰้ป‘->"..number) return false end end local self_phone = get('http://39.108.184.74/api/Public/tjj/?service=Nike.Checkphone&phone='..number) if self_phone.data then log("ๆ‰‹ๆœบๅทๅฏไปฅไฝฟ็”จ") return number else toast('่‡ชๅทฑ้กถๅท\nๅ‡†ๅค‡ๆ‹‰้ป‘'); local lx_url = 'http://api.smskkk.com/api/do.php?action=addBlacklist&sid='..PID..'&phone='..number..'&token='..token httpGet(lx_url); log("ๆ‹‰้ป‘->"..number) end end end), getMessage=(function() local Msg for i=1,25,1 do mSleep(3000) local urls = "http://api.smskkk.com/api/do.php?action=getMessage&sid="..PID.."&token="..token.."&phone="..number log(urls) RetStr = httpGet(urls) if RetStr then local arr = strSplit(RetStr,"|") if arr[1] == '1' then Msg = arr[2] local i,j = string.find(Msg,"%d+") Msg = string.sub(Msg,i,j) end if type(tonumber(Msg))== "number" then return Msg end end toast(tostring(RetStr).."\n"..i.."ๆฌกๅ…ฑ25ๆฌก") end return "" end), addBlack=(function() local lx_url = 'http://api.smskkk.com/api/do.php?action=addBlacklist&sid='..PID..'&phone='..number..'&token='..token return httpGet(lx_url) end), } end --165 function _vCode_dm() local User = 'shuaishuai' local Pass = '<PASSWORD>' local PID = '3215' local token,uid,number = "","" local api_url = "http://api.yyyzmpt.com/index.php/" return { login=(function() local RetStr for i=1,5,1 do toast("่Žทๅ–token\n"..i.."ๆฌกๅ…ฑ5ๆฌก") mSleep(1500) local urls = api_url..'reg/login?username='..User..'&password='..<PASSWORD> nLog(urls) RetStr = get(urls) if RetStr then if RetStr['errno'] == 0 then token = RetStr['ret']['token'] -- log('token='..token,true) nLog('token='..token) break else toast(RetStr.errmsg) mSleep(2000) end end end return RetStr; end), getPhone=(function() local RetStr="" local urls = api_url..'clients/online/setWork?token='..token..'&t=1&pid='..PID nLog(urls) RetStr = get(urls) if RetStr then if RetStr['errno'] == 0 then number = RetStr['ret']['number'] toast('number='..number) nLog('number='..number) return number else toast(RetStr.errmsg) mSleep(2000) end end end), getMessage=(function() local Msg for i=1,25,1 do mSleep(3000) local urls = api_url..'clients/sms/getSms?type=1&token='..token..'&project='..PID..'&number='..number nLog(urls) RetStr = get(urls) if RetStr then if RetStr['errno'] == 0 then Msg = RetStr['ret']['tst'] -- log('token='..token,true) nLog('Msg='..Msg) local i,j = string.find(Msg,"%d+") Msg = string.sub(Msg,i,j) return Msg else toast(RetStr.errmsg) mSleep(2000) end end toast(i.."ๆฌกๅ…ฑ25ๆฌก") end return "" end), addBlack=(function() return httpGet( api_url.."?action=getMessage&sid="..PID.."&token="..token.."&phone="..number) end), } end --code = _vCode_hy() --code.login() --delay(3) --log( --code.getPhone() ) <file_sep>-- ๆๅ–codes -- main.lua -- Create By TouchSpriteStudio on 02:31:56 -- Copyright ยฉ TouchSpriteStudio . All rights reserved. require("TSLib") require("tsp") local sz = require("sz") local json = sz.json require("other") var={} var.bid='com.nike.omega' var.account={} var.account.login = '' var.account.pwd = '' var.account.address_country = 'CN' var.account.phone = '' w,h = getScreenSize(); function boxshow(txt,x1,y1,x2,y2) local x1 = x1 or 0 local y1 = y1 or 0 local x2 = x2 or 300 local y2 = y2 or 30 adbox__ = adbox__ or 0 if adbox__ == 0 then adbox__ = 1 fwShowWnd("wid",w/2+50,0,w/2+300,50,1) mSleep(2000) end fwShowTextView("wid","textid",txt,"left","FF0000","FFDAB9",10,0,x1,y1, x2,y2,0.5) --fwShowTextView("wid","textid","่ฟ™ๆ˜ฏไธ€ไธชๆ–‡ๆœฌ่ง†ๅ›พ","center","FF0000","FFDAB9",0,20,0,0,200,100,0.5) end function backId() local postUrl = 'http://zzaha.com/phalapi/public/' local postArr = {} postArr.s = 'Nikeback.Back' postArr.id = var.account.id log(post(postUrl,postArr)) end function disable() local postUrl = 'http://zzaha.com/phalapi/public/' local postArr = {} postArr.s = 'Nikeback.disable' postArr.id = var.account.id log(post(postUrl,postArr)) end function getLogin(again) local getIdUrl = 'http://zzaha.com/phalapi/public/?s=Nikeagain.Again&again='..again..'&sms=old&name='..'iPhone'..rd(1,50); local data = get(getIdUrl); if data then return data end; end function updateNikeLog(workstate) local sz = require("sz") local url = 'http://zzaha.com/phalapi/public/' local Arr={} Arr.s = 'Nikesave.Save' Arr.address_mail = var.account.login Arr.workstate = workstate post(url,Arr) end function updateNike() local sz = require("sz") local url = 'http://zzaha.com/phalapi/public/' local Arr={} Arr.s = 'Nikesave.Save' Arr.address_mail = var.account.login Arr.address_pwd = var.account.pwd Arr.address_phone = var.account.phone Arr.address_xin = first_name_ Arr.address_ming = last_names_ Arr.address_sheng = 'ๅนฟไธœ็œ' Arr.address_shi = 'ๆทฑๅœณๅธ‚' Arr.address_qu = '็ฝ—ๆน–ๅŒบ' Arr.address_area = var.account.address_area Arr.address_country = var.account.address_country Arr.iphone = 'iPhone'..rd(1,50) Arr.imei = sz.system.serialnumber() Arr.birthday = var.birthday Arr.moon = var.moon Arr.codes = var.codes log(Arr) if post(url,Arr)then return true end end t={} local degree = 90 t['ๅผน็ช—_่พ“ๅ…ฅ็š„ๅฎŒๆˆ']={ 0x007aff, "-43|-20|0x007aff", 90, 646, 594, 742, 956 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅผน็ช—_้ชŒ่ฏไฝ ็š„ๆ‰‹ๆœบๅท'] = { 0x111111,"-400|1|0x111111,-175|31|0xffffff,-503|579|0,29|319|0xe5e5e5,114|651|0",degree,26,107,721,843} t['ๅผน็ช—_ไฟๅญ˜ๆ‚จ็š„้ž‹็ '] = { 0x80808,"1|-1|0xffffff,-677|-2|0xffffff,-672|-2|0",degree,10,44,731,329} t['ๅผน็ช—_้€‰ๆ‹ฉ่ฏญ่จ€-็กฎๅฎš'] = { 0x121212,"237|-55|0xffffff,233|56|0xffffff,-276|-53|0xffffff,-282|55|0xffffff",degree,21,1100,730,1321} t['ๅผน็ช—_้€‰ๆ‹ฉๆ„Ÿ่ง‰ๅ…ด่ถฃ็š„ๅ†…ๅฎน'] = { 0xffffff,"-405|14|0xffffff,-109|13|0",degree,102,107,624,294} t['ๅผน็ช—_้ชŒ่ฏไฝ ็š„ๆ‰‹ๆœบๅท2'] = { 0xefefef,"324|7|0xffffff,458|-26|0xe5e5e5,553|247|0,-66|302|0",degree,36,358,734,912} t['็™ปๅฝ•']={0xffffff,"-46|12|0xffffff,-341|0|0,-321|18|0",degree,128,1095,523,1150} t['็™ปๅฝ•็•Œ้ข'] = { 0x171717,"-268|99|0xffffff,-293|72|0xb80c,318|137|0xb80c",degree,25,551,733,1089} t['็™ปๅฝ•็•Œ้ขโ€”โ€”ไฝฟ็”จ็”ตๅญ้‚ฎไปถ็™ปๅฝ•'] = { 0x8d8d8d,"-42|-199|0x111111,-42|-194|0x111111,-44|-196|0xefefef,-42|-189|0x111111",degree,42,249,320,564} t['ๅผน็ช—โ€”โ€”็บข่‰ฒ'] = { 0xfe0000,"-43|-38|0xfe0000,-38|41|0xfe0000,-3|-4|0xffffff",degree,12,85,728,593} -- 452,308 -- 457,415 t['็ซ‹ๅณๅผ€ๅง‹'] = { 0x111111,"-284|-52|0xffffff,375|-48|0xffffff,373|57|0xffffff,-278|57|0xffffff",degree,21,1147,730,1319} t['็™ปๅฝ•ๆˆๅŠŸ'] = { 0x111111,"0|5|0xffffff,0|10|0x111111,0|16|0xffffff,0|20|0x111111,30|22|0x111111",degree,163,1242,268,1324} t['ๅผน็ช—_ๅฏ†็ ้”™่ฏฏ'] = { 0xfe3131,"154|0|0xfe0000,152|0|0xffffff,328|-5|0xfe1414",degree,38,79,416,535} function login() local timeline = os.time() local outTimes = 3*60 local data = getLogin(0); if data ~= nil then log(data) if type(data.data) == "table" then var.account.login = data.data.address_mail var.account.pwd = data.data.address_pwd var.account.phone = data.data.address_phone var.account.id = data.data.id var.account.first_name_ = data.data.address_xin var.account.last_names_ = data.data.address_ming var.account.address_country = data.data.address_country local account_txt = "ๆ‰ง่กŒ่‡ณ "..var.account.id .."\n่ดฆๅท = "..var.account.login.."\nๅฏ†็  = "..var.account.pwd dialog(account_txt,2) log(account_txt) else dialog("ๆš‚ๆ— ๅธๅท", 60*3) return false end end updateNikeLog('ๆญฃๅœจ็™ปๅฝ•'); while os.time()-timeline < outTimes do if active(var.bid,3) then if d('็™ปๅฝ•็•Œ้ข')then if d('็™ปๅฝ•็•Œ้ขโ€”โ€”ไฝฟ็”จ็”ตๅญ้‚ฎไปถ็™ปๅฝ•',true)then elseif d('ๅผน็ช—_ๅฏ†็ ้”™่ฏฏ')then disable(); updateNikeLog('ๅฏ†็ ้”™่ฏฏ'); return false; else click(452,308,3); input('\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b'); input(var.account.login); updateNikeLog('่พ“ๅ…ฅๅธๅท'); click(457,415,3); input('\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b') input(var.account.pwd); updateNikeLog('่พ“ๅ…ฅๅฏ†็ '); d('ๅผน็ช—_่พ“ๅ…ฅ็š„ๅฎŒๆˆ',true); d('็™ปๅฝ•็•Œ้ข',true,1,5); updateNikeLog('ๆญฃๅœจ็™ปๅฝ•'); end elseif d('็™ปๅฝ•',true)then updateNikeLog('่ฟ›ๅ…ฅ็™ปๅฝ•'); elseif d('ๅผน็ช—_้€‰ๆ‹ฉ่ฏญ่จ€-็กฎๅฎš',true)then elseif d('็ซ‹ๅณๅผ€ๅง‹',true)then updateNikeLog('ไธ‹ไธ€ๆญฅ') elseif d('ๅผน็ช—_ไฟๅญ˜ๆ‚จ็š„้ž‹็ ')then local shoes = { {644,479,0}, {105,587,0}, {210,588,0}, {320,587,0}, {428,587,0}, {528,585,0}, {643,585,0}, } local rd_ = rd(1,7) click(shoes[rd_][1],shoes[rd_][2]) elseif d('็™ปๅฝ•ๆˆๅŠŸ')then updateNikeLog('็™ปๅฝ•ๆˆๅŠŸ'); return true elseif d('ๅผน็ช—_้ชŒ่ฏไฝ ็š„ๆ‰‹ๆœบๅท') or d('ๅผน็ช—_้ชŒ่ฏไฝ ็š„ๆ‰‹ๆœบๅท2') then updateNikeLog('้ชŒ่ฏไฝ ็š„ๆ‰‹ๆœบๅท็ '); boxshow('้ชŒ่ฏๆ‰‹ๆœบ',0,0,200,30); disable() return false elseif d('ๅผน็ช—_้€‰ๆ‹ฉๆ„Ÿ่ง‰ๅ…ด่ถฃ็š„ๅ†…ๅฎน')then click(212,498); d('็ซ‹ๅณๅผ€ๅง‹',true); else if d('ๅผน็ช—โ€”โ€”็บข่‰ฒ')then click(686,82,2) elseif d('ๅผน็ช—_ๅฏ†็ ้”™่ฏฏ')then disable(); return false; end end end delay(1) log('login->'..os.time()-timeline) end end t['็‚นๅ‡ปๆˆ‘'] = { 0xcccccc,"1|-10|0xffffff,0|-19|0xcccccc,2|15|0xffffff,18|7|0xcccccc",degree,642,1252,722,1324} t['ๆ”ถไปถ็ฎฑ'] = { 0x111111,"-7|-1|0xffffff,-15|181|0x111111,-14|172|0xffffff,1|196|0x111111",degree,604,1056,725,1325} t['ๆ”ถไปถ็ฎฑ_1'] = { 0xfa5401,"59|18|0x111111,1|43|0xfa5401",degree,530,951,731,1229} t['ๆ”ถไปถ็ฎฑ็•Œ้ข'] = { 0x111111,"0|11|0xffffff,15|16|0x111111,-642|-1210|0x111111,-629|-1211|0xffffff",degree,12,44,734,1329} t['ๆ”ถไปถ็ฎฑ็•Œ้ขโ€”โ€”็”Ÿๆ—ฅๅฟซไน'] = { 0xc9b8ea,"8|26|0xd8ace0,-9|23|0xffffff",degree,15,138,217,1232} t['ไผšๅ‘˜็”Ÿๆ—ฅไธ“ๅฑž็ฆๅˆฉ'] = { 0,"-469|-12|0x7aff,-480|0|0x7aff,-468|13|0x7aff",degree,7,43,516,121} t['ไผšๅ‘˜็”Ÿๆ—ฅไธ“ๅฑž็ฆๅˆฉโ€”โ€”code'] = { 0xffffff,"-23|-57|0xe5e5e5,-41|62|0xe5e5e5,479|62|0xe5e5e5,462|-57|0xe5e5e5,188|-7|0x111111",degree,17,138,720,1319} t['ๆˆ‘็š„็•Œ้ข-่ฎพ็ฝฎ'] = { 0xcccccc,"-1|-11|0xffffff,-187|-21|0xcccccc,-189|-6|0xffffff,-570|-9|0xcccccc,-580|-19|0xffffff",degree,20,383,732,1109} t['่ฎพ็ฝฎ็•Œ้ขโ€”โ€”็”Ÿๆ—ฅ'] = { 0xff841f,"-4|11|0xff8521",degree,553,361,741,515} t['่ฎพ็ฝฎ็•Œ้ขโ€”โ€”ๆฒกๆœ‰็”Ÿๆ—ฅ'] = { 0x1d1d1d,"304|-357|0x111111,301|-355|0xffffff,-64|-348|0x111111,-54|-347|0xffffff",degree,8,40,740,617} var.account.login = '<EMAIL>' var.account.pwd = '<PASSWORD>' function ocr(x1,y1,x2,y2) local ress = ocrText(x1,y1,x2,y2, 0) or 0 if ress == '' then nLog('nil') return 0 end return ress end function click_random(x,y,n) if n > 1 then for i=1,n do click(x,y,0.8) end else click(x,y,0.8) end end t['่ฎพ็ฝฎ็•Œ้ข'] = { 0x1a1a1a,"-3|-7|0xe8e8e8,-1|-9|0x111111,-369|0|0x111111,-358|0|0xffffff,-13|-7|0xf9f9f9",degree,9,43,731,137} t['่ฎพ็ฝฎ็•Œ้ข-ๆœ‰็”Ÿๆ—ฅ'] = { 0xff8522,"0|-1|0xff841f",degree,522,329,744,597} t['่ฎพ็ฝฎ็•Œ้ข-ๆœ‰็”Ÿๆ—ฅไธŠ'] = { 0xff841f,"0|-1|0xff841f",degree,588,250,742,360} t['่ฎพ็ฝฎ็•Œ้ข-็”Ÿๆ—ฅๆ— '] = { 0x1d1d1d,"61|-16|0xf8f8f8,63|-17|0x1d1d1d",degree,12,260,159,345} t['ๆˆ‘็š„็•Œ้ข'] = { 0x111111,"-1|-11|0xffffff,-1|-20|0x111111,-17|16|0x111111,12|12|0xffffff,16|12|0x111111",degree,622,1244,727,1322} t['ๆˆ‘็š„็•Œ้ข_ไฝ ็š„ไธ“ๅฑž็ฆๅˆฉ'] = { 0x111111,"-4|0|0xffffff,-459|-15|0x1d1d1d,-463|-15|0xffffff,-478|-15|0x1d1d1d,-642|-7|0x1d1d1d",degree,20,495,731,1194} t['ไฝ ็š„ไธ“ๅฑž็ฆๅˆฉ_็”Ÿๆ—ฅๅฟซไน'] = { 0xcb62c2,"-207|-137|0xdadada,-183|-159|0xf9f9f9,268|20|0xd8d8d8",degree,71,259,691,1102} t['ไผšๅ‘˜็”Ÿๆ—ฅไธ“ๅฑž็ฆๅˆฉ2'] = { 0x111111,"332|1|0xffffff,334|3|0x111111,457|0|0x111111,466|0|0x111111",degree,6,48,740,122} function readCode() local timeline = os.time() local outTimes = 2*60 local msgbox = 0 updateNikeLog('ๅ‡†ๅค‡่ฏป็ '); local readBirthday = true var.codes = ''; while os.time()-timeline < outTimes do if active(var.bid,3) then if d('็™ปๅฝ•ๆˆๅŠŸ')then d('็‚นๅ‡ปๆˆ‘',true,1,2); elseif readBirthday and d('ๆˆ‘็š„็•Œ้ข-่ฎพ็ฝฎ',true,1)then -- elseif d('ๆ”ถไปถ็ฎฑ',true)then -- elseif d('ๆ”ถไปถ็ฎฑ_1',true)then elseif d('่ฎพ็ฝฎ็•Œ้ข')then if readBirthday and d('่ฎพ็ฝฎ็•Œ้ข-ๆœ‰็”Ÿๆ—ฅ')then var.birthday = ocr(566,379,744,475); var.birthday = string.gsub(var.birthday, "%s+", "") var.birthday = string.gsub(var.birthday, "|", "/") local moonArr = split(var.birthday,"/") var.moon = moonArr[2] boxshow(var.birthday); updateNike(); updateNikeLog('ไฟฎๆญฃ็”Ÿๆ—ฅ') backId(); readBirthday = false elseif readBirthday and d('่ฎพ็ฝฎ็•Œ้ข-ๆœ‰็”Ÿๆ—ฅไธŠ')then var.birthday = ocr(555,254,746,361); var.birthday = string.gsub(var.birthday, "%s+", "") var.birthday = string.gsub(var.birthday, "|", "/") local moonArr = split(var.birthday,"/") var.moon = moonArr[2] boxshow(var.birthday); updateNike(); updateNikeLog('ไฟฎๆญฃ็”Ÿๆ—ฅ') backId(); readBirthday = false elseif readBirthday and d('่ฎพ็ฝฎ็•Œ้ข-็”Ÿๆ—ฅๆ— ',true,1,2)then click_random(227,1005,rd(8,12)) click_random(367,1053,rd(2,3)) click_random(521,1053,rd(2,3)) click(678,859,5) else click(40,80,2) end elseif d('ๆˆ‘็š„็•Œ้ข')then if d('ๆˆ‘็š„็•Œ้ข_ไฝ ็š„ไธ“ๅฑž็ฆๅˆฉ',true,1,2)then else moveTo(300,800,300,500,20) delay(1) end elseif d("ไผšๅ‘˜็”Ÿๆ—ฅไธ“ๅฑž็ฆๅˆฉ") or d('ไผšๅ‘˜็”Ÿๆ—ฅไธ“ๅฑž็ฆๅˆฉ2')then if d('ไผšๅ‘˜็”Ÿๆ—ฅไธ“ๅฑž็ฆๅˆฉโ€”โ€”code',true,2)then var.codes = readPasteboard(); updateNike() updateNikeLog('่ฏป็ ๆˆๅŠŸ'); return true else moveTo(300,800,400,500,10) delay(2) end elseif d('ไฝ ็š„ไธ“ๅฑž็ฆๅˆฉ_็”Ÿๆ—ฅๅฟซไน',true,1,2)then end end delay(1) log('readCode->'..os.time()-timeline) end end w,h = getScreenSize(); function delay(times) local times = times or 1 local timeLine = os.time() while os.time() - timeLine <= times do mSleep(1000) if (times-(os.time() - timeLine) > 3) then local text = "ๅ€’่ฎกๆ—ถ->ใ€Œ".. times-(os.time() - timeLine) .."ใ€" -- log("ๅ€’่ฎกๆ—ถ->ใ€Œ".. times-(os.time() - timeLine) .."ใ€",true) boxshow(text,0,0,200,30); end end end function all() setWifiEnable(false) setAirplaneMode(true) delay(10) setAirplaneMode(false) delay(30) if true or vpn()then sys.clear_bid(var.bid); if login()then readCode() end end delay(2) end while (true) do local ret,errMessage = pcall(all) if ret then else log(errMessage) dialog(errMessage, 15) mSleep(1000) closeApp(frontAppBid()) mSleep(2000) end end <file_sep> --unlockDevice() require("TSLib") --require("tsp") --res, code = http.request("http://ip.chinaz.com/getip.aspx"); --็”จhttp.getๅฎž็Žฐไธ‹่ฝฝๆ–‡ไปถๅŠŸ่ƒฝ function downFile(url, path) local sz = require("sz") local http = require("szocket.http") local url = "http://wenfree.cn/api/Public/idfa/?service=Git.Get&url="..url local res, code = http.request(url); -- nLog(res) if code == 200 then local json = sz.json local data = json.decode(res) local body = data.data local file = io.open(path, "wb") if file then file:write(body) file:close() return status; else return -1; end else return status; end end --downFile("http://mu1234.applinzi.com/wechat-reply.txt", --"/User/Media/TouchSprite/lua/wechat-reply.txt") --ๆฃ€ๆต‹ๆŒ‡ๅฎšๆ–‡ไปถๆ˜ฏๅฆๅญ˜ๅœจ function file_exists(file_name) local f = io.open(file_name, "r") return f ~= nil and f:close() end game_lua = { {"tsp",'https://img.wenfree.cn/lua/bh/tsp.lua'}, {"main",'https://img.wenfree.cn/lua/bh/main.lua'}, } local ver_ = 2 local name_ = "bh" local v_url = 'http://wenfree.cn/api/Public/idfa/?service=Git.Update&name='..name_..'&v='..ver_ function get_(url) local sz = require("sz") local http = require("szocket.http") local res, code = http.request(url); -- nLog(res); if code == 200 then local json = sz.json if res ~= nil then return json.decode(res) end end end local version = get_(v_url); if version then if version.data then t1=os.time(); nLog(t1) for i,v in ipairs(game_lua)do nLog(v[1]) nLog(v[2]) downFile(v[2],"/User/Media/TouchSprite/lua/"..v[1]..".lua") mSleep(30) toast(v[1],1) end nLog('end->'..os.time()-t1) else nLog('ๆ— ้œ€ๆ›ดๆ–ฐ'); for i,v in ipairs(game_lua)do if not(file_exists("/User/Media/TouchSprite/lua/"..v[1]..".lua"))then nLog('ๆ–‡ไปถไธๅญ˜๏ผŒไธ‹่ฝฝไธ€ไธช->'..v[1]) downFile(v[2],"/User/Media/TouchSprite/lua/"..v[1]..".lua") if v[1] == 'main' then downFile(v[2],"/User/Media/TouchSprite/"..v[1]..".lua") end end end end end <file_sep>require('AWZ') info = {} info.IDFA = '' info.IMEI = '' function url_() local url = 'https://nike.onelnk.com/3CPe?pid=smzdm_int&c=Mar_Memsale&af_dp=mynike://x-callback-url/shop&af_channel=SMZDM&af_sub1=AFF&af_sub2=MEMSALE&af_sub3=CONTENT&af_prt=annalect&imei='.. info.IMEI ..'&idfa=' .. info.IDFA log( url ) return url end awzNew() local alsinfo = getOnlineName() info.name = 'nike' info.IDFA = alsinfo.IDFA info.IMEI = alsinfo.IMEI log(info) openURL(url_()) function idfa_save_hb() local url = "http://hb.wenfree.cn/api/Public/idfa/" local postarr = {} postarr['service'] = "Idfa.Idfa" postarr['idfa'] = info.IDFA postarr['name'] = info.name post(url,postarr) end idfa_save_hb() <file_sep>require("TSLib") require("tsp") function get_account() local url = 'http://wenfree.cn/api/Public/idfa/' local postdata = {}; postdata.service = 'Idfa.GetNday'; postdata.name = 'ๅฉšๆ‹็ฝ‘'; postdata.rate = '50'; postdata.day = '7'; local res = post(url,postdata) log(res); if res then return res end end --get_account() --็ฒพๅ‡†ๆป‘ๅŠจ็š„ๅŽŸ็†ๅฐฑๆ˜ฏ้€š่ฟ‡ๅ‘ๆป‘ๅŠจๆ–นๅ‘็š„ๅž‚็›ด็บฟๆ–นๅ‘็งปๅŠจ 1 ๅƒ็ด ๆฅ็ปˆๆญขๆป‘ๅŠจๆƒฏๆ€ง --็ฎ€ๅ•็š„ๅž‚็›ด็ฒพๅ‡†ๆป‘ๅŠจ function ld(x1,y1,x2,y2) touchDown(x1,y1) for i = x1, x2, rd(1,5) do touchMove(i, y1+rd(-15,15)) mSleep(rd(10,50)) end --ๅช่ฆๆจชๅ‘ๆป‘ๅŠจ 1 ๅƒ็ด ๅฐฑๅฏไปฅ็ฒพๅ‡†ๆป‘ๅŠจ --ๆจชๅ‘ๆป‘ๅŠจ 1 ๅƒ็ด  touchMove(x2, y2) mSleep(50) touchUp( x2, y2) mSleep(50) end --ld(125, 792, 353, 792) t={} t['้ฆ–้กต_็™ปๅฝ•็•Œ้ข']={ 0xff5f5e, "-2|-3|0xffffff,-192|8|0xffffff,152|14|0xf64a56,474|11|0xff6273,340|-30|0xfffcfc", 90, 17, 70, 735, 188 } --ๅคš็‚นๆ‰พ่‰ฒ t['้ฆ–้กต_็™ปๅฝ•็•Œ้ข_ๆ‰‹ๆœบๅท/้‚ฎ็ฎฑ']={ 0xffffff, "-60|8|0xc7c7cd,-48|-16|0xc7c7cd,-194|1|0xffffff,-202|0|0xc9c9cf", 90, 62, 252, 607, 317 } --ๅคš็‚นๆ‰พ่‰ฒ t['้ฆ–้กต_็™ปๅฝ•็•Œ้ข_่ฏท่พ“ๅ…ฅๅฏ†็ ']={ 0xc7c7cd, "-1|3|0xffffff,-1|5|0xc9c9cf,-1|9|0xffffff,421|1|0xcccccc", 90, 51, 359, 710, 437 } --ๅคš็‚นๆ‰พ่‰ฒ t['้ฆ–้กต_็™ปๅฝ•็•Œ้ข_็™ปๅฝ•ๆŒ‰้’ฎ']={ 0xfffefe, "8|1|0xff5051,290|47|0xfe2e6d,-303|-42|0xff7230", 90, 39, 595, 728, 727 } --ๅคš็‚นๆ‰พ่‰ฒ t['้”™่ฏฏ_่พ“ๅ…ฅ้ชŒ่ฏ็ ']={ 0xfc6e27, "34|-4|0xf9f9f9,36|-4|0xfc712b,430|-14|0x000000", 90, 9, 52, 478, 112 } --ๅคš็‚นๆ‰พ่‰ฒ t['ๅผน็ช—_ๆž้ชŒ่ฏๆป‘ๅŠจ']={ 0x7e7e7e, "24|-119|0x66d200,79|-5|0x7e7e7e,119|-1|0x7e7e7e,134|1|0xffffff", 90, 104, 730, 647, 944 } --ๅคš็‚นๆ‰พ่‰ฒ var={} var.app = 'com.baihe.online' function login() local ่ฎกๆ—ถ = os.time() local ่ถ…ๆ—ถ = 60*15 var.account = get_account(); while ((os.time()-่ฎกๆ—ถ<่ถ…ๆ—ถ )) do if active(var.app,5)then if d("้ฆ–้กต_็™ปๅฝ•็•Œ้ข")then if d('้ฆ–้กต_็™ปๅฝ•็•Œ้ข_ๆ‰‹ๆœบๅท/้‚ฎ็ฎฑ',true)then input[3](var.account.data.phone) delay(1) elseif d('้ฆ–้กต_็™ปๅฝ•็•Œ้ข_่ฏท่พ“ๅ…ฅๅฏ†็ ',true)then input[1](var.account.data.password) delay(1) elseif d('้ฆ–้กต_็™ปๅฝ•็•Œ้ข_็™ปๅฝ•ๆŒ‰้’ฎ',true,3)then end elseif d("ๅผน็ช—_ๆž้ชŒ่ฏๆป‘ๅŠจ") then ld(125, 792, 370, 792) delay(5) end end delay(1) end end --login() function getRGB(x,y) local colorRGB ={} colorRGB.r,colorRGB.g,colorRGB.b = getColorRGB(x,y) return colorRGB end function left() keepScreen(true) local left_top_x = 140 local left_top_y = 398 local left_top_y_max = 644 local color1 = {} local color2 = {} for i = left_top_y,left_top_y_max do color1 = getRGB(left_top_x,i) color2 = getRGB(left_top_x,i+5) -- log(color1) -- log(color2) local key_true = 0 for k,v in pairs(color1)do if color2[k]- v > 100 then key_true = key_true + 1 end end if key_true >= 2 then keepScreen(false) return i+5; end end keepScreen(false) end function right_p(y) keepScreen(true) local left_top_x = 266 local left_top_y = y local left_top_x_max = 620 local color1 = {} local color2 = {} for i = left_top_x,left_top_x_max do color1 = getRGB(i,y) color2 = getRGB(i+5,y) -- log(color1) -- log(color2) local key_true = 0 for k,v in pairs(color1)do if v - color2[k] > 80 then key_true = key_true + 1 end end if key_true >= 2 then keepScreen(false) return i+1; end end keepScreen(false) end log( left()) local left_p = left() if left_p then log(right_p(left_p)) local right_p = right_p(left_p) if right_p then ld(125, 792, right_p, 792) end end <file_sep>-- ไธ‡ๅ›ฝ่ง‰้†’ -- main.lua -- Create By TouchSpriteStudio on 13:31:43 -- Copyright ยฉ TouchSpriteStudio . All rights reserved. require('tsp') require('AWZ') require('ui') require('ZZBase64') require("yzm") init(1) _app = {} _app.bid = 'com.lilithgames.rok.ios.offical' _UI = {} local _key = {} _key['on']= true _key['off']= false _UI.ๅ›ฝๅฎถ = UIv.ๅ›ฝๅฎถ + 1 _UI.ๅ‡็บง = _key[UIv.ๅ‡็บง] _UI.ๅฅ–ๅŠฑ = _key[UIv.ๅฅ–ๅŠฑ] _UI.้€ ๅ…ต = {} _UI.้€ ๅ…ต.key = _key[UIv.้€ ๅ…ตkey] _UI.้€ ๅ…ต.ๆญฅๅ…ต = _key[UIv.ๆญฅๅ…ต] _UI.้€ ๅ…ต.้ช‘ๅ…ต = _key[UIv.้ช‘ๅ…ต] _UI.้€ ๅ…ต.ๅผ“ๅ…ต = _key[UIv.ๅผ“ๅ…ต] _UI.้€ ๅ…ต.่ฝฆๅ…ต = _key[UIv.่ฝฆๅ…ต] _UI.ๅปบ้€  = _key[UIv.ๅปบ้€ ] _UI.่‹ฑ้›„ = _key[UIv.่‹ฑ้›„] _UI.้‡‡้›† = {} _UI.้‡‡้›†.key = _key[UIv.้‡‡้›†key] _UI.้‡‡้›†.็ง็ฑป = UIv.้‡‡้›†็ง็ฑป+1 _UI.ๆ–ฅๅ€™ = _key[UIv.ๆ–ฅๅ€™] _UI.ไปปๅŠก = _key[UIv.ไปปๅŠก] log(_UI) t={} degree = 85 t['็ฎญๅคดๅ‘ไธ‹'] = { 0xab4d21,"6|7|0xf0eca5,0|13|0xa15828,0|15|0xe9cb72,-11|50|0x687782,24|37|0xbbd3ea,4|86|0x596d84",degree,0,0,1334,750} t['็ฎญๅคดๅ‘ๅทฆไธ‹'] = { 0xa15026,"-2|8|0xfef5b3,-14|12|0xd9c574,-23|39|0xbfd4e8,-32|58|0xa9c4e4,-59|63|0x5c7188",degree,0,0,1334/2,750} t['็ฎญๅคดๅ‘ๅทฆไธ‹2'] = { 0x596d83,"17|-62|0xe8e9e8,39|-29|0xc3d7eb,16|-15|0x839db6,10|-21|0x576674,48|-51|0xf4edaa",degree,0,0,1334/2,750} t['็ฎญๅคดๅ‘ๅทฆไธŠ'] = { 0xa25228,"-7|-4|0xf6eaaa,-13|-15|0xd3c97f,-61|-62|0x647991,-58|-38|0xafc8e4,-47|-42|0x8ca6c0",degree,0,0,1334,750} t['็ฎญๅคดๅ‘ๅณ'] = { 0xa15026,"8|-3|0xfdf4b3,19|-1|0xd9d08a,82|-3|0x677c96,63|-19|0xa9c4e4,41|-14|0xc2d8ec",degree,0,0,1334,750} t['็ฎญๅคดๅ‘ๅณ2'] = { 0xa3542b,"9|-2|0xfff7b5,18|1|0xae834c,20|1|0xd3c97f,78|-1|0x687e94",degree,0,0,1334,750} t['็ฎญๅคดๅ‘ๅณ-ๆ”ปๅ‡ป'] = { 0xaf2f23,"184|67|0x820c0c,192|10|0x820c0c,-7|60|0x830b0b",degree,837,458,1065,543} --ไบ‹ไปถ t['e-ๅ›ฝๅฎถ้€‰ๆ‹ฉ'] = { 0xf9db41,"-50|-32|0xeca140,-35|-63|0xfbd13f,-577|451|0x61f634",degree,259,24,1244,612} --1็ฝ—้ฉฌ๏ผŒ2ๅพทๅ›ฝ๏ผŒ3ไธๅˆ—็›ด๏ผŒ4ๆณ•ๅ…ฐ่ฅฟ๏ผŒ5่ฅฟ็ญ็‰™๏ผŒ6ไธญๅ›ฝ๏ผŒ7ๆ—ฅๆœฌ๏ผŒ8้Ÿฉๅ›ฝ๏ผŒ9้˜ฟๆ‹‰ไผฏ๏ผŒ10ๅฅฅๆ–ฏๆ›ผ๏ผŒ11ๆ‹œๅ ๅบญ t['e-ๅ›ฝๅฎถ้€‰ๆ‹ฉ-ไฝ็ฝฎ']={{98,664,0x542b9f},{287,664,0x333333},{470,663,0xd0952d},{655,663,0xd9a72f},{838,664,0xef9798},{1023,665,0x732c1b},{1208,663,0xa0939e}, {693,667,0x2c3786},{879,667,0x12582e},{1065,663,0x8f2323},{1249,665,0xce8c29},} t['e-ๅ›ฝๅฎถ้€‰ๆ‹ฉ-ไฝ็ฝฎ-็กฎๅฎš'] = { 0xffb000,"2|-8|0xb67016",degree,1061,498,1193,551} function _Evevnt() if d('e-ๅ›ฝๅฎถ้€‰ๆ‹ฉ')then if _UI.ๅ›ฝๅฎถ > 7 then moveTo(1247,663,139,666,10) delay(2) end click(t['e-ๅ›ฝๅฎถ้€‰ๆ‹ฉ-ไฝ็ฝฎ'][_UI.ๅ›ฝๅฎถ][1],t['e-ๅ›ฝๅฎถ้€‰ๆ‹ฉ-ไฝ็ฝฎ'][_UI.ๅ›ฝๅฎถ][2],2) d('e-ๅ›ฝๅฎถ้€‰ๆ‹ฉ-ไฝ็ฝฎ-็กฎๅฎš',true,2) else return true end end function _Arrow() local ret = false _arrow = _arrow or 0 local result = false keepScreen(true) if d('็ฎญๅคดๅ‘ไธ‹')then _arrow = _arrow + 1 click(x,y + (_arrow%3+1)*50+100) _arrow = _arrow + 1 click(x,y + (_arrow%3+1)*50+100) _arrow = _arrow + 1 click(x,y + (_arrow%3+1)*50+100) ret = true elseif d('็ฎญๅคดๅ‘ๅทฆไธ‹') or d('็ฎญๅคดๅ‘ๅทฆไธ‹2') then log("ๅ‘ๅทฆ") log({'x',x,'y',y}) _arrow = _arrow + 1 click(x - (_arrow%3+1)*50-50 ,y + (_arrow%3+1)*50+50 ) _arrow = _arrow + 1 click(x - (_arrow%3+1)*50-50 ,y + (_arrow%3+1)*50+50 ) _arrow = _arrow + 1 click(x - (_arrow%3+1)*50-50 ,y + (_arrow%3+1)*50+50 ) ret = true elseif d('็ฎญๅคดๅ‘ๅทฆไธŠ')then _arrow = _arrow + 1 click(x - (_arrow%3+1)*50 ,y - (_arrow%3+1)*50 ) _arrow = _arrow + 1 click(x - (_arrow%3+1)*50 ,y - (_arrow%3+1)*50 ) _arrow = _arrow + 1 click(x - (_arrow%3+1)*50 ,y - (_arrow%3+1)*50 ) ret = true elseif d('็ฎญๅคดๅ‘ๅณ') or d("็ฎญๅคดๅ‘ๅณ2")then _arrow = _arrow + 1 click(x + (_arrow%3+1)*50+100 ,y ) _arrow = _arrow + 1 click(x + (_arrow%3+1)*50+100 ,y ) _arrow = _arrow + 1 click(x + (_arrow%3+1)*50+100 ,y ) ret = true elseif d('็ฎญๅคดๅ‘ๅณ-ๆ”ปๅ‡ป',true,2)then ret = true end keepScreen(false) return x end t['ๆธธๆˆไธป็•Œ้ข'] = { 0x13567e,"83|1|0x1f5a80,54|625|0xf5e18a,56|727|0xf4bd63",degree,0,0,123,749} t['ๆธธๆˆไธป็•Œ้ข-ๅคœ'] = { 0xf5bd63,"-1|-102|0xf2dc88,-56|-727|0xa507e,27|-731|0xf476f",degree,0,0,123,749} t['ๆธธๆˆไธป็•Œ้ข-้‡Žๅค–'] = { 0xb527f,"0|1|0x3ea0c4,-1|15|0x7fdef5,-1|16|0x4192b3,-21|-2|0x66ddf8,-24|-2|0xa507c",degree,18,640,108,726} t['ๆธธๆˆไธป็•Œ้ข-ๅŸŽๅ†…'] = { 0x2074a0,"0|-10|0xffffff,0|15|0x6ce6ff,10|29|0x24776,15|33|0x82e7fe,-42|32|0x8578f",degree,27,653,106,722} t['่”็›ŸๅŠ ๅ…ฅ'] = { 0x1274ba,"-60|-12|0xc8f6,-18|20|0xace9,47|1|0xc7ff",degree,586,203,753,269} t['่”็›ŸๅŠ ๅ…ฅไธ่ƒฝ'] = { 0x939585,"-271|98|0xd3ff",degree,545,87,993,301} function _init() d('ๆธธๆˆไธป็•Œ้ข-ๅŸŽๅ†…',true,2) d('ๆธธๆˆไธป็•Œ้ข-้‡Žๅค–',true,1,3) if d('่”็›ŸๅŠ ๅ…ฅ',true)then d("่”็›ŸๅŠ ๅ…ฅไธ่ƒฝ",true) elseif d('ๆธธๆˆไธป็•Œ้ข-ๅŸŽๅ†…')then log('ๅˆๅง‹ๅŒ–ๅฎŒๆˆ') return true end end t['ๅผน็ช—-ไปปๅŠกx'] = { 0xd3d1ca,"-11|-10|0xd7d6ce,-11|-4|0x9c9b8d,6|13|0x9d9a8f,9|9|0xd2cfc6",degree,1113,66,1165,112} t['ๅผน็ช—-้‚ฎไปถ้ขๆฟx'] = { 0xd3d1c9,"-12|-10|0xd7d4cc,-13|-7|0x9e9991,9|14|0xa09c93",degree,1256,25,1317,70} t['ๅผน็ช—-่ต„ๆ–™้ขๆฟx'] = { 0xd3d1ca,"-11|-10|0xd7d5ce,-13|-7|0x9a968e,8|13|0x9c988e",degree,1115,66,1161,110} t['ๅผน็ช—-่ฎพ็ฝฎ้ขๆฟx'] = { 0xd3d1ca,"-13|-8|0x9b978f,-9|10|0xd2d0c7,14|12|0x9a968d",degree,1136,24,1187,71} t['ๅผน็ช—-่“่‰ฒๆŒ‰้’ฎ'] = { 0x1274ba,"-107|-25|0xd4ff,-110|24|0xb5f0,115|24|0xb5f0,109|-24|0xd4ff",degree,333,164,1000,596} t['ๅผน็ช—-่ฟ”ๅ›žๆŒ‰้’ฎ'] = { 0xd6d4cf,"15|-9|0x8e8c86,10|-14|0xdbd9d3,10|13|0xd0d0cb,0|24|0x959287",degree,3,3,86,82} t['ๅผน็ช—-ๆญฃๅœจๅŠ ่ฝฝ'] = { 0xbb2fe,"2|14|0x64ae,7|-2|0xdb2fe,14|8|0x180d5",degree,343,652,558,690} t['ๅผน็ช—-ๅ‡็บง็ฎญๅคด-็‰ฉ่ดจไธ่ถณ'] = { 0xd3d1ca,"-464|378|0xc7ff,-378|377|0x1274ba,-304|404|0xb7f3",degree,232,97,1095,651} t['ๅผน็ช—-ๆ‹›ๅˆฐ่‹ฑ้›„'] = { 0x1274ba,"-84|-26|0xd2fd,88|25|0xb5f1",degree,67,574,339,695} t['ๅผน็ช—-ๅผ€็ฎฑ็กฎๅฎš'] = { 0x1577bc,"-81|-27|0xd4ff,422|15|0xffa700,619|10|0xffa900",degree,274,591,1061,695} t['ๅผน็ช—-ๅ‡็บง็กฎ่ฎค'] = { 0x1274ba,"-95|-7|0xc9ff,159|-389|0x858278,318|1|0xc2ff",degree,230,94,1088,661} t['ๅผน็ช—-ๅ–ๆถˆๅŸŽๅธ‚็ผ–่พ‘'] = { 0xd6d4cc,"-264|615|0xc0fc,-537|608|0xc4ff,-824|606|0xc5ff",degree,186,6,1328,717} t['ๅผน็ช—-็ฝ‘็ปœๆ–ญๅผ€'] = { 0x1176bc,"50|-291|0x858278,118|-289|0xc6c3b6",degree,362,183,974,568} t['ๅผน็ช—_็‚นๅ‡ปไปปๅŠก_ๅฎ็Ÿณ'] = { 0xd3d1c9,"-460|407|0xffb100,-305|382|0xfebf00",degree,483,102,1099,662} t['ๅผน็ช—_็ป‘ๅฎšๅธๅท'] = { 0xd3d1c9,"-274|395|0xc1fe,-497|388|0xc5ff,-591|234|0xf2a643",degree,241,99,1098,644} t['ๅผน็ช—_ๅผนๅ‡บๅฎ็ฎฑ'] = { 0x9bab6e,"-596|544|0xb77016,-397|533|0xb77016,-501|516|0xffc000,-502|568|0xfca100",degree,487,78,1195,716} t['ๅผน็ช—โ€”ๅ›žๅคฉๆ”นๅ‘ฝ'] = { 0xadafaf,"-595|521|0xb77016,-409|552|0xfeaa00",degree,462,21,1223,740} t['ๅผน็ช—โ€”้ชŒ่ฏๅ›พ็‰‡'] = { 0x1274ba,"-51|-7|0xd3ff,43|17|0xb5f1,58|-5|0x1077bc,-10|-131|0xffef00",degree,663,90,1029,458} t['ๅผน็ช—โ€”้ชŒ่ฏๅ›พ็‰‡-็กฎๅฎš'] = { 0x539ffe,"83|0|0x539ffe,-339|-2|0xffffff,-323|-10|0x7e7e7e,-406|-3|0x7e7e7e",degree,392,644,944,730} t['ๅผน็ช—โ€”appๆ›ดๆ–ฐ'] = { 0xc3ff,"-82|-24|0xd3fd,64|20|0xb5f0,192|-1|0xdf3d33,343|2|0xdd3c33",degree,384,427,966,569} function _Tips() local tips = { 'ๅผน็ช—-็ฝ‘็ปœๆ–ญๅผ€', 'ๅผน็ช—-ไปปๅŠกx', 'ๅผน็ช—-้‚ฎไปถ้ขๆฟx', 'ๅผน็ช—-่ต„ๆ–™้ขๆฟx', 'ๅผน็ช—-่ฎพ็ฝฎ้ขๆฟx', 'ๅผน็ช—-่“่‰ฒๆŒ‰้’ฎ', 'ๅผน็ช—-่ฟ”ๅ›žๆŒ‰้’ฎ', 'ๅผน็ช—-ๆ‹›ๅˆฐ่‹ฑ้›„', 'ๅผน็ช—-ๅ‡็บง็กฎ่ฎค', 'ๅผน็ช—-ๅผ€็ฎฑ็กฎๅฎš', 'ๅผน็ช—-ๅ–ๆถˆๅŸŽๅธ‚็ผ–่พ‘', 'ๅผน็ช—-ๅ‡็บง็ฎญๅคด-็‰ฉ่ดจไธ่ถณ', 'ๅผน็ช—โ€”appๆ›ดๆ–ฐ', 'ๅผน็ช—_็ป‘ๅฎšๅธๅท', 'ๅผน็ช—_ๅผนๅ‡บๅฎ็ฎฑ', 'ๅผน็ช—โ€”ๅ›žๅคฉๆ”นๅ‘ฝ', 'ๅผน็ช—_็‚นๅ‡ปไปปๅŠก_ๅฎ็Ÿณ', 'ๅผน็ช—โ€”้ชŒ่ฏๅ›พ็‰‡', 'ๅผน็ช—-ๆญฃๅœจๅŠ ่ฝฝ', } for k,v in pairs(tips)do if v == "ๅผน็ช—-ๆญฃๅœจๅŠ ่ฝฝ" then if d(v)then delay(15) return false end elseif v == "ๅผน็ช—โ€”้ชŒ่ฏๅ›พ็‰‡" then if d(v,true,1,5) then local time_ = os.time() while ( os.time() - time_ < 120 ) do if d("ๅผน็ช—โ€”้ชŒ่ฏๅ›พ็‰‡-็กฎๅฎš")then delay(1) if _yzmsb()then d("ๅผน็ช—โ€”้ชŒ่ฏๅ›พ็‰‡-็กฎๅฎš",true,1,5) delay(10); return true end end end click(20,20); end else if d(v,true,1,2)then return false end end end _other = _other or 0 _other = _other + 1 local other_w = {{50,174},{1128,44}, -- {837,535},{1050,171},{42,40} } local other_w_c = _other%(#other_w+1) if other_w_c == 0 then moveTo(500,200,500,300,rd(10,20)) else click(other_w[other_w_c][1],other_w[other_w_c][2],0.2) end log('e') return true end t['ๅ‡็บง-ๅ‡็บง็ฎญๅคด'] = { 0x1faa0f,"12|28|0x9203,-2|-29|0x70d255",degree,478,356,597,477} t['ๅ‡็บง-ๅ‡็บง็ฎญๅคด้’้“œ'] = { 0xeab212,"0|-30|0xfee35c,-9|22|0xde9800",degree,485,356,585,460} t['ๅ‡็บง-ๅ‡็บงๆŒ‰้’ฎ'] = { 0xc2ff,"101|2|0xc2ff,-158|2|0xfeaf00,-298|-3|0xfeb200",degree,638,381,1162,682} t['ๅ‡็บง-ๅ‰ๅพ€'] = { 0x1274ba,"-37|-18|0xd3fd,63|14|0xace9",degree,671,496,1120,656} t['ๅ‡็บง-ๅ‰ๅพ€-ๅ‡็บง็ฎญๅคด'] = { 0x17a50a,"-3|22|0x9203,-1|-26|0x5ecb43",degree,448,360,885,607} t['ๅ‡็บง-ๆญฃๅœจๅ‡็บงไธญ'] = { 0xe0a10f,"27|-1|0xdea716,-8|-22|0xf0efe9,-1|-22|0xf1c03a,-32|17|0xcf920d,-41|18|0xe6e4d9",degree,470,357,861,570} t['ๅ‡็บง-ๆญฃๅœจๅ‡็บงไธญ-ๆ€ป้ƒจ'] = { 0xe3a412,"29|1|0xdea716,-1|-19|0xf1be35,-6|-20|0xf4ece1,-1|23|0xce9408,-35|8|0xf2e3cd,-31|20|0xcf920d",degree,478,344,616,490} t['ๅ‡็บง-ๅฎ็Ÿณ'] = { 0xfeaf00,"148|-67|0x334e,397|2|0xc1fe,471|29|0x1176bc",degree,325,414,1020,611} t['ๅ‡็บง-ๅฎ็Ÿณไธ่ถณ'] = { 0x980e0e,"11|1|0xffa700",degree,754,529,848,626} t['ๅ‡็บง-ๆ–ฐๆ‰‹ไฟๆŠค็กฎๅฎš'] = { 0x1274ba,"-115|-4|0xc7ff,114|4|0xc2ff,241|-23|0xd4ff,461|33|0x1176bc",degree,297,456,1040,615} function _build() log("ๅ‡็บง") click(469,218,2) --็‚นๅ‡ปๅธ‚ๆ”ฟๅŽ… if d("ๅ‡็บง-ๅ‡็บง็ฎญๅคด",true,1,2) or d('ๅ‡็บง-ๅ‡็บง็ฎญๅคด้’้“œ',true,1,2)then while d("ๅ‡็บง-ๅ‡็บงๆŒ‰้’ฎ") or d("ๅ‡็บง-ๅ‰ๅพ€") do if d("ๅ‡็บง-ๅ‡็บงๆŒ‰้’ฎ",false,1,2)then local dengji = ocrText(783,171,835,206, 10,'1234567890') log({"dengji",dengji}) if dengji == "" or dengji== nil then dengji = 100 end if dengji+0 <= 3 and not(d("ๅ‡็บง-ๅฎ็Ÿณไธ่ถณ")) then click(766,571) d("ๅ‡็บง-ๅฎ็Ÿณ",true,1,5) else if d("ๅ‡็บง-ๅ‡็บงๆŒ‰้’ฎ",true,1,2)then d("ๅ‡็บง-ๆ–ฐๆ‰‹ไฟๆŠค็กฎๅฎš",true,1,2) _UI.ๅ‡็บง = false delay(3) end end elseif d("ๅ‡็บง-ๅ‰ๅพ€",true,1,2)then if d("ๅ‡็บง-ๅ‰ๅพ€-ๅ‡็บง็ฎญๅคด",true,1,2)then elseif d('ๅ‡็บง-ๆญฃๅœจๅ‡็บงไธญ')then _UI.ๅ‡็บง = false return true end end end elseif d('ๅ‡็บง-ๆญฃๅœจๅ‡็บงไธญ-ๆ€ป้ƒจ') then _UI.ๅ‡็บง = false return true end end t['ๅฅ–ๅŠฑ-ๆœ‰ๅฅ–ๅŠฑ'] = { 0xe0ac64,"6|-9|0xfef6a4,34|-41|0xe30000",degree,8,119,109,221} t['ๅฅ–ๅŠฑ-ๅฅ–ๅŠฑ้ขๆฟ-้ข†ๅ–'] = { 0xbf0f,"-58|-16|0xd40f,57|15|0x9e0d",degree,954,173,1137,657} t['ๅฅ–ๅŠฑ-ๅฅ–ๅŠฑ้ขๆฟ-้ข†ๅ–ๅˆ†็ฑป'] = { 0x1e6184,"-32|-31|0xe20000",degree,31,112,157,525} t['ๅฅ–ๅŠฑ-ๅฅ–ๅŠฑ้ขๆฟ-็บข่‰ฒ-้“ถ'] = { 0xc2c4d4,"37|-36|0xe20000",degree,606,155,717,249} t['ๅฅ–ๅŠฑ-ๅฅ–ๅŠฑ้ขๆฟ-็บข่‰ฒ-้ป„'] = { 0xf4b246,"37|-35|0xe20000",degree,1013,148,1166,258} t['ๅฅ–ๅŠฑ-ๅฅ–ๅŠฑ้ขๆฟ-้ข†ๅ–็ฎฑๅญ'] = { 0xffff19,"-26|2|0xfec404",degree,292,132,1160,278} function _Award() log("ๅฅ–ๅŠฑ") if d("ๅฅ–ๅŠฑ-ๆœ‰ๅฅ–ๅŠฑ",true,1,3)then local _jlcs = 1 while _jlcs< 30 and (d("ๅฅ–ๅŠฑ-ๅฅ–ๅŠฑ้ขๆฟ-้ข†ๅ–",true,1,2) or d("ๅฅ–ๅŠฑ-ๅฅ–ๅŠฑ้ขๆฟ-็บข่‰ฒ-้“ถ",true,1,2)or d("ๅฅ–ๅŠฑ-ๅฅ–ๅŠฑ้ขๆฟ-็บข่‰ฒ-้ป„",true,1,2)or d("ๅฅ–ๅŠฑ-ๅฅ–ๅŠฑ้ขๆฟ-้ข†ๅ–็ฎฑๅญ",true) or d("ๅฅ–ๅŠฑ-ๅฅ–ๅŠฑ้ขๆฟ-้ข†ๅ–ๅˆ†็ฑป",true,1,2)) do _jlcs=_jlcs+1 end else _UI.ๅฅ–ๅŠฑ = false return false end end t['้€ ๅ…ต-่ฎญ็ปƒ'] = { 0xfafeff,"20|-28|0xcffe,-92|-14|0xc5ff",degree,914,574,1137,659} t['้€ ๅ…ต-ๅŠ ้€Ÿ'] = { 0xd3d1c9,"-151|515|0x1176bc,-232|500|0xd1ff,-38|545|0xb6f3",degree,858,58,1165,680} function _soldier() log("้€ ๅ…ต") local ๅ…ต่ฅไฝ็ฝฎ={ {{549,449,0x4b3e35},{686,595,0x880ba},}, {{549,449,0x4b3e35},{686,595,0x880ba},}, {{549,449,0x4b3e35},{686,595,0x880ba},}, {{549,449,0x4b3e35},{686,595,0x880ba},}, } local ๅ…ต็ง = { "ๆญฅๅ…ต","้ช‘ๅ…ต","ๅผ“ๅ…ต","่ฝฆๅ…ต", } for k,v in ipairs(ๅ…ต็ง) do if _UI.้€ ๅ…ต[v] then click(ๅ…ต่ฅไฝ็ฝฎ[k][1][1],ๅ…ต่ฅไฝ็ฝฎ[k][1][2],2) click(ๅ…ต่ฅไฝ็ฝฎ[k][1][1],ๅ…ต่ฅไฝ็ฝฎ[k][1][2],2) click(ๅ…ต่ฅไฝ็ฝฎ[k][2][1],ๅ…ต่ฅไฝ็ฝฎ[k][2][2],2) if d('้€ ๅ…ต-่ฎญ็ปƒ',true) or d('้€ ๅ…ต-ๅŠ ้€Ÿ',true,1,2) then _UI.้€ ๅ…ต[v] = false end end end _UI.้€ ๅ…ต.key = false end t['ๅปบ้€ -ๆœ‰ๅปบ้€ '] = { 0xe20000,"20|-4|0xe20000",degree,75,511,116,557} t['ๅปบ้€ -่ฃ…้ฅฐ'] = { 0x656257,"-29|-37|0xe30000",degree,3,602,97,700} t['ๅปบ้€ -ๅฏไปฅๅปบ้€ '] = { 0x255273,"-132|1|0x9ee6ff,111|1|0x9ee6ff",degree,134,469,419,665} t['ๅปบ้€ -ๅฏไปฅๅปบ้€ ๅˆ†็ฑป'] = { 0x757568,"-42|-34|0xe20000",degree,3,478,99,570} t['ๅปบ้€ -ๅ‡†ๅค‡ๅปบ้€ '] = { 0x89a05,"-131|4|0xe50909,-171|-35|0xf27979,-151|6|0xf3e9e5",degree,6,2,1252,744} t['ๅปบ้€ -ๅปบ้€ ๅ–ๆถˆ'] = { 0xd3d1c9,"-24|242|0xd0ff,-30|441|0xffb000,-187|466|0xfca000",degree,898,58,1169,681} t['ๅปบ้€ -็ผ–่พ‘ๅŸŽๅธ‚'] = { 0xd59813,"24|-16|0xe20000",degree,1115,145,1210,286} function _NewBuild() log("ๅปบ้€ ") if d('ๅปบ้€ -ๆœ‰ๅปบ้€ ')then click(64,564,2) d("ๅปบ้€ -่ฃ…้ฅฐ",true,1,2) click(53,411,2) while d("ๅปบ้€ -ๅฏไปฅๅปบ้€ ") or d("ๅปบ้€ -ๅฏไปฅๅปบ้€ ๅˆ†็ฑป",true,1,2)do if d("ๅปบ้€ -ๅฏไปฅๅปบ้€ ",true,1,2) then if d('ๅปบ้€ -ๅ‡†ๅค‡ๅปบ้€ ',false,1,2)then log({x,y}) if x > 1000 then moveTo(600,300,400,300,5) delay(2) end d('ๅปบ้€ -ๅ‡†ๅค‡ๅปบ้€ ',true,1,2) if d('ๅปบ้€ -ๅปบ้€ ๅ–ๆถˆ',true,1,2)then _UI.ๅปบ้€  = false return false end else _NewBuild_lun = _NewBuild_lun or 0 _NewBuild_lun = _NewBuild_lun + 1 if _NewBuild_lun%4 == 0then moveTo(600,300,400,300,5)--ๅ‘ๅทฆ elseif _NewBuild_lun%4 == 1then moveTo(400,300,600,300,5)--ๅ‘ๅณ elseif _NewBuild_lun%4 == 2then moveTo(300,500,300,300,5)--ๅ‘ไธŠ elseif _NewBuild_lun%4 == 3then moveTo(400,100,400,300,5)--ๅ‘ไธ‹ end delay(0.5) d('ๅปบ้€ -ๅ‡†ๅค‡ๅปบ้€ ',true,1,2) if d('ๅปบ้€ -ๅปบ้€ ๅ–ๆถˆ',true,1,2)then _UI.ๅปบ้€  = false return false end end end end d('ๅปบ้€ -็ผ–่พ‘ๅŸŽๅธ‚',true,1,2 ) else _UI.ๅปบ้€  = false end end t['่‰-ๅคœ'] = { 0x378a56,"22|39|0x328057,17|3|0x51c1a,15|18|0xd131e",degree,9,6,1252,742} t['่‰-็™ฝ'] = { 0xabf54d,"20|41|0xa2eb50,16|5|0x133618,-10|12|0xd3117",degree,10,6,1242,741} t['ๆ ‘-็™ฝ'] = { 0xaefb4f,"-31|-59|0x6ba83a,12|-38|0x143516,41|-23|0x82c146",degree,6,3,1242,738} t['่‰-้“ฒๅญ'] = { 0xeb3535,"-24|24|0xe50909,-162|2|0xe4f1f4,-155|-12|0x28a4dc",degree,5,4,1244,742} t['่‰-้“ฒๅญ-ๆ˜ฏ'] = { 0x1274ba,"-98|-19|0xd2ff,473|9|0xbffc",degree,331,450,1019,600} function _glass() log("้™ค่‰") for i=1,10 do if d("ๆ ‘-็™ฝ",false,1,2) or d('่‰-ๅคœ',false,2,2) or d('่‰-็™ฝ',false,2,2)then if x < 150 then moveTo(300,600,500,600,10) delay(2) end if y > 500 then moveTo(300,600,300,400,10) delay(2) end if d("ๆ ‘-็™ฝ",true,1,2) or d('่‰-ๅคœ',true,2,2) or d('่‰-็™ฝ',true,2,2)then log({x,y}) if d("่‰-้“ฒๅญ",true)then d("่‰-้“ฒๅญ-ๆ˜ฏ",true) end end end end end t['็ญพๅˆฐ-vip'] = { 0xffb400,"36|-13|0xe20000",degree,128,45,203,88} t['็ญพๅˆฐ-้ข†ๅ–'] = { 0xc40e,"-47|-18|0xc80e,44|21|0xc760a",degree,855,121,1126,489} t['็ญพๅˆฐ-้ข†ๅ–-็บข'] = { 0,"13|7|0xcddce2,13|-55|0xe20000",degree,987,141,1136,254} t['็ญพๅˆฐ-้ข†ๅ–-้ป„'] = { 0xf5b347,"37|-34|0xe20000",degree,767,526,877,629} function _SignIn() log("็ญพๅˆฐ") if d("็ญพๅˆฐ-vip",true,1,2)then if d("็ญพๅˆฐ-้ข†ๅ–-้ป„",true,1,2)then elseif d("็ญพๅˆฐ-้ข†ๅ–",true,1,2)then elseif d("็ญพๅˆฐ-้ข†ๅ–-็บข",true,1,2)then end end end t['ๆ”ถ้›†-็މ็ฑณ'] = { 0xffff6b,"-5|-3|0xffe731,6|8|0x7fe81d,-10|18|0x236602,-12|6|0x5bc40f",70,94,50,1208,716} t['ๆ”ถ้›†-ๆœจๆ'] = { 0xe0e0e1,"-5|-20|0xd3955f,12|-34|0x7a2f0a,2|-35|0xe1702b",70,20,85,1250,745} t['ๆ”ถ้›†-ๆœจๆ้ป„'] = { 0x6e2a08,"-19|2|0xecb87b,-16|21|0xd0905c,-5|7|0x92380b",degree,21,43,1232,712} t['ๆ”ถ้›†-็Ÿณๅคด'] = { 0xd8dfee,"0|-7|0x969fb7,-15|10|0x9da6c1,-16|16|0x606a83,12|11|0x485168",80,50,20,1250,736} t['ๆ”ถ้›†-ๆกๆ‰‹'] = { 0xdedee0,"8|-19|0x2f9c01,0|-36|0xfcf2e1,-12|-41|0xffe67e,-12|-25|0x33a600",70,54,85,1224,723} function _Collect() log("ๆ”ถ้›†") local ๆ”ถ้›† = {"ๆ”ถ้›†-็މ็ฑณ","ๆ”ถ้›†-ๆœจๆ","ๆ”ถ้›†-็Ÿณๅคด","ๆ”ถ้›†-ๆกๆ‰‹","ๆ”ถ้›†-ๆœจๆ้ป„"} for k,v in ipairs(ๆ”ถ้›†) do d(v,true,2,2) end end t['่‹ฑ้›„-ๆ”พๅคง้•œ'] = { 0xd8edf6,"7|6|0x1188bb,17|33|0x6093,-16|43|0xcce6ea,-20|29|0x6195",degree,415,475,515,570} t['่‹ฑ้›„-ๅผ€ๅฏ'] = { 0x1274ba,"-93|-24|0xd3ff,111|25|0xb3ef,47|32|0x1176bc",degree,213,531,1107,705} t['่‹ฑ้›„-ๅผ€ๅฏ-็กฎๅฎš'] = { 0x1274ba,"-76|-23|0xd1ff,105|20|0xb6f3,570|5|0xffac00",degree,270,596,1080,700} function _Hero() log("่‹ฑ้›„") click(314,344,2) if d("่‹ฑ้›„-ๆ”พๅคง้•œ",true,1,2)then local _opentimes = 0 while (d("่‹ฑ้›„-ๅผ€ๅฏ",true,1,5) or d("่‹ฑ้›„-ๅผ€ๅฏ-็กฎๅฎš",true,1,3)) and _opentimes < 10 do _opentimes = _opentimes + 1 end _UI.่‹ฑ้›„ = false end end t['้‡‡็Ÿฟ-ๆ”พๅคง้•œ'] = { 0xe5984,"-5|-15|0xfdffff,-1|22|0x5585,11|13|0x7ce7ff",degree,13,507,107,613} t['้‡‡็Ÿฟ-ๆœ็ดข'] = { 0x1274ba,"-69|-29|0xd3fe,81|23|0xb4f0",degree,130,454,1201,605} t['้‡‡็Ÿฟ-ๆœ็ดข-ๆ”ปๅ‡ป'] = { 0x970e0e,"-104|-23|0xe94d3d,63|29|0xc12724,-103|24|0xd4302b",degree,167,94,1195,732} t['้‡‡็Ÿฟ-ๆœ็ดข-้‡‡้›†'] = { 0x1273b9,"-85|-29|0xd1fc,93|31|0x1175bb,88|-25|0xd2fe",degree,73,51,1233,739} t['้‡‡็Ÿฟ-ๅˆ›ๅปบ้ƒจ้˜Ÿ'] = { 0x1375ba,"-82|-24|0xd3fd,86|33|0x1175bb",degree,927,14,1195,727} t['้‡‡็Ÿฟ-่กŒๅ†›'] = { 0xfdae00,"118|-1|0xfeae00,-118|-6|0xfdb100,-340|-14|0xcafd,-208|8|0xbcf8",degree,612,603,1164,719} function _Collection() log("้‡‡้›†") if _UI.้‡‡้›†.key then local ้‡‡้›†ไฝ็ฝฎ={{269,665,0xb3b0b0},{474,661,0x428a22},{675,662,0xc28f71},{861,659,0x585858},{1064,661,0x878787},} if d('้‡‡็Ÿฟ-ๆ”พๅคง้•œ',true,1,2)then _Collection_lun = _Collection_lun or 0 _Collection_lun = _Collection_lun + 1 local _Coll_key = _Collection_lun%5+1 if tonumber(_UI.้‡‡้›†.็ง็ฑป) >= 6 then log({'_Coll_key',_Coll_key}) click( ้‡‡้›†ไฝ็ฝฎ[_Coll_key][1],้‡‡้›†ไฝ็ฝฎ[_Coll_key][2],2 ) else click( ้‡‡้›†ไฝ็ฝฎ[tonumber(_UI.้‡‡้›†.็ง็ฑป)][1],้‡‡้›†ไฝ็ฝฎ[tonumber(_UI.้‡‡้›†.็ง็ฑป)][2],2 ) end if d("้‡‡็Ÿฟ-ๆœ็ดข",true,1,2)then click(663,367,2) --็‚นๅฑไธญ้—ด if d("ๆ–ฅๅ€™-ๆœ็ดข-็ปฟ")then log("ๆœชๅผ€่’") _UI.้‡‡้›†.key = false return false end d("้‡‡็Ÿฟ-ๆœ็ดข-ๆ”ปๅ‡ป",true,1,2) d("้‡‡็Ÿฟ-ๆœ็ดข-้‡‡้›†",true,1,2) d("้‡‡็Ÿฟ-ๅˆ›ๅปบ้ƒจ้˜Ÿ",true,1,2) if d("้‡‡็Ÿฟ-่กŒๅ†›",true,1,2) and _Coll_key ~=1 then _UI.้‡‡้›†.key = false elseif _Coll_key == 1 then log('ๆ‰“้‡Žไธญไผ‘ๆฏ15็ง’','all') delay(15) end end end end end local ๆ–ฅๅ€™ไฝ็ฝฎ={{808,404,0xb2004},{952,564,0x97fb8},} t['ๆ–ฅๅ€™-ๆœ็ดข'] = { 0xffac00,"-91|-29|0xffbf00,83|16|0xffa500",degree,894,263,1159,561} t['ๆ–ฅๅ€™-ๆœ็ดข-็ปฟ'] = { 0xb67016,"-75|-29|0xffc000,94|22|0xffa400",degree,97,25,1230,722} t['ๆ–ฅๅ€™-ๆœ็ดข-ๆดพ้ฃ'] = { 0xb67016,"-8|-19|0xffbe00,-93|-20|0xffbe00,79|25|0xffa500",degree,916,7,1195,572} t['ๆ–ฅๅ€™-ๆœ็ดข-ๆดพ้ฃไธญ'] = { 0xffffff,"5|-5|0xb66200,-22|-36|0xbc13eb",degree,1224,158,1332,436} t['ๆ–ฅๅ€™-ไผ‘ๆฏไธญ'] = { 0xffffff,"7|1|0x7d7d7d,-1|-13|0x7d7d7d,3|8|0xbdbdbd",degree,406,331,471,419} function _Acouts() log("ๆ–ฅๅ€™") click(ๆ–ฅๅ€™ไฝ็ฝฎ[1][1],ๆ–ฅๅ€™ไฝ็ฝฎ[1][2],2) click(ๆ–ฅๅ€™ไฝ็ฝฎ[2][1],ๆ–ฅๅ€™ไฝ็ฝฎ[2][2],2) if d("ๆ–ฅๅ€™-ๆœ็ดข",true,1,2)then d("ๆ–ฅๅ€™-ๆœ็ดข-็ปฟ",true,1,2) d("ๆ–ฅๅ€™-ๆœ็ดข-ๆดพ้ฃ",true,1,2) if d("ๆ–ฅๅ€™-ๆœ็ดข-ๆดพ้ฃไธญ")then _UI.ๆ–ฅๅ€™ = false end elseif d("ๆ–ฅๅ€™-ไผ‘ๆฏไธญ")then _UI.ๆ–ฅๅ€™ = false end end t['ๅŒป้™ข+'] = { 0xf31919,"0|-13|0xfe3333,-11|1|0xf11616,1|11|0xe90202,15|-1|0xeaeee7",degree,606,225,699,323} t['ๅŒป้™ข-ๆฒป็–—'] = { 0xc2ff,"100|-25|0xd1ff,-160|25|0xfea200,-399|-28|0xfebf00",degree,566,549,1153,669} t['ๅŒป้™ข-ๆฒปๅฅฝ'] = { 0x9d4400,"9|0|0x9a4300,26|-4|0xc86600",75,609,228,703,335} function _Hospital() log("ๅŒป้™ข") if d("ๅŒป้™ข+",true,1,2)then d("ๅŒป้™ข-ๆฒป็–—",true,1,2) elseif d("ๅŒป้™ข-ๆฒปๅฅฝ",true,1,2)then else return false end end --็ฎ€ๅ•ๆธ…็† function clearOneAccount() log('็ฎ€ๅ•ๆธ…็†') local sonlist={ '/tmp/', '/Library/', } for k,v in ipairs(sonlist)do local dataPath = appDataPath(_app.bid) local AllPath = dataPath..v log(AllPath) delFile(AllPath) end end t['ไปปๅŠก_็‚นๅ‡ปไปปๅŠก'] = { 0xe4b067,"-18|15|0x6d0000,-16|-7|0x560000",degree,18,141,76,196} t['ไปปๅŠก_็‚นๅ‡ปไปปๅŠก_ๅ‰ๅพ€'] = { 0x1274ba,"-56|-18|0xd4fe,59|7|0xb6f3",degree,937,139,1163,429} t['ไปปๅŠก_็‚นๅ‡ปไปปๅŠก_่ฎญ็ปƒ'] = { 0xc9ff,"-349|-175|0x14d900,-309|15|0xffac00",degree,595,387,1140,668} t['ไปปๅŠก_็‚นๅ‡ปไปปๅŠก_่ฎญ็ปƒ_ๅ–ๆถˆ'] = { 0xc0fe,"-445|-7|0xfeb200,-264|-67|0x334e",degree,286,356,1070,630} t['ไปปๅŠก_็‚นๅ‡ปไปปๅŠก_้‡‡็Ÿฟ'] = { 0x8c7ff,"162|-26|0x1077bc,162|19|0x1076bd",degree,128,429,1173,600} function _task() _setp['ไปปๅŠก'] = _setp['ไปปๅŠก'] + 1 if _setp['ไปปๅŠก'] > 2 then _UI.ไปปๅŠก = false return false end if d('ไปปๅŠก_็‚นๅ‡ปไปปๅŠก',true,1,3)then click(122,336,2) d("ๅฅ–ๅŠฑ-ๅฅ–ๅŠฑ้ขๆฟ-้ข†ๅ–",true,1,2) if d("ไปปๅŠก_็‚นๅ‡ปไปปๅŠก_ๅ‰ๅพ€",true,1,3)then if d("ไปปๅŠก_็‚นๅ‡ปไปปๅŠก_้‡‡็Ÿฟ",true,1,2)then else click(809,507,2) end delay(1) if d("ๆธธๆˆไธป็•Œ้ข-้‡Žๅค–")then click(663,367,2) --็‚นๅฑไธญ้—ด d("้‡‡็Ÿฟ-ๆœ็ดข-ๆ”ปๅ‡ป",true,1,2) d("้‡‡็Ÿฟ-ๆœ็ดข-้‡‡้›†",true,1,2) d("้‡‡็Ÿฟ-ๅˆ›ๅปบ้ƒจ้˜Ÿ",true,1,2) if d("้‡‡็Ÿฟ-่กŒๅ†›",true,1,2)then _UI.ไปปๅŠก = false end else d("ไปปๅŠก_็‚นๅ‡ปไปปๅŠก_่ฎญ็ปƒ_ๅ–ๆถˆ",true,1,2) if d('ไปปๅŠก_็‚นๅ‡ปไปปๅŠก_่ฎญ็ปƒ',true) or d('้€ ๅ…ต-ๅŠ ้€Ÿ') then _UI.ไปปๅŠก = false end end end end end function allclear() main_path = '/var/mobile/awzdata/'.._app.bid.."/" --้ๅކๆ–‡ไปถ function getList(path) local a = io.popen("ls "..path); local f = {}; for l in a:lines() do table.insert(f,l) end a:close() return f end list = getList(main_path) --ๆ–‡ไปถๅคนไพ‹่กจ son = '/Library/' son2 = '/tmp/' function delFile(path)--ๅธฎไฝ ็Žฉๅนณๅฐ็ฆ็”จๆญคๅ‡ฝๆ•ฐ os.execute("rm -rf "..path); end function ๆธ…็†() for i,v in pairs(list)do all = main_path..v..son nLog(all) delFile(all) end for i,v in pairs(list)do all = main_path..v..son2 nLog(all) delFile(all) end end ๆธ…็†() end function game() local timeline = os.time() while os.time()-timeline < 60 * 5 do if active(_app.bid,8)then if d('ๆธธๆˆไธป็•Œ้ข') or d('ๆธธๆˆไธป็•Œ้ข-ๅคœ')then if d("ๆธธๆˆไธป็•Œ้ข-ๅŸŽๅ†…")then d('ๅผน็ช—_็ป‘ๅฎšๅธๅท',true,1) _glass() _SignIn() _Collect() if _init()then if _Hospital() then elseif _UI.ๅปบ้€  then _NewBuild() elseif _UI.่‹ฑ้›„ then _Hero() elseif _UI.ๅ‡็บง then _build() elseif _UI.ๅฅ–ๅŠฑ then _Award() elseif _UI.ไปปๅŠก then _task() elseif _UI.้€ ๅ…ต.key then _soldier() elseif _UI.ๆ–ฅๅ€™ then _Acouts() elseif _UI.้‡‡้›†.key then if d("ๆธธๆˆไธป็•Œ้ข-ๅŸŽๅ†…",true,1,2)then _Collection() end else return 'next' end end elseif d("ๆธธๆˆไธป็•Œ้ข-้‡Žๅค–")then click(65,681,2) end else if _Evevnt() then _Arrow() _Tips() end end end end return 'next' end function main() while true do _setp = {} _setp['ไปปๅŠก'] = 0 _UI.ๅ›ฝๅฎถ = UIv.ๅ›ฝๅฎถ + 1 _UI.ๅ‡็บง = _key[UIv.ๅ‡็บง] _UI.ๅฅ–ๅŠฑ = _key[UIv.ๅฅ–ๅŠฑ] _UI.้€ ๅ…ต = {} _UI.้€ ๅ…ต.key = _key[UIv.้€ ๅ…ตkey] _UI.้€ ๅ…ต.ๆญฅๅ…ต = _key[UIv.ๆญฅๅ…ต] _UI.้€ ๅ…ต.้ช‘ๅ…ต = _key[UIv.้ช‘ๅ…ต] _UI.้€ ๅ…ต.ๅผ“ๅ…ต = _key[UIv.ๅผ“ๅ…ต] _UI.้€ ๅ…ต.่ฝฆๅ…ต = _key[UIv.่ฝฆๅ…ต] _UI.ๅปบ้€  = _key[UIv.ๅปบ้€ ] _UI.่‹ฑ้›„ = _key[UIv.่‹ฑ้›„] _UI.้‡‡้›† = {} _UI.้‡‡้›†.key = _key[UIv.้‡‡้›†key] _UI.้‡‡้›†.็ง็ฑป = UIv.้‡‡้›†็ง็ฑป+1 _UI.ๆ–ฅๅ€™ = _key[UIv.ๆ–ฅๅ€™] _UI.ไปปๅŠก = _key[UIv.ไปปๅŠก] game() -- clearOneAccount(); allclear(); delay(1) awz_next() delay(1) end end main() <file_sep>-- ็งฏๅˆ†ๅข™ๅฏนๆŽฅ -- AWZ.lua -- Create By TouchSpriteStudio on 13:18:42 -- Copyright ยฉ TouchSpriteStudio . All rights reserved. require("TSLib") local awzbid = 'AWZ' function locks() local flag = deviceIsLock(); if flag == 0 then -- log("ๆœช้”ๅฎš"); else unlockDevice(); --่งฃ้”ๅฑๅน• end end function activeawz(app,t) t = t or 0.5 locks() bid = frontAppBid(); if bid ~= app then nLog(app.."๏ผŒๅ‡†ๅค‡ๅฏๅŠจ") runApp(app) mSleep(t*1000) return true end end function awz() openURL("IGG://cmd/newrecord"); mSleep(3000) local logTxt = '/var/mobile/iggresult.txt' out_time = os.time() while os.time()-out_time <= 10 do if activeawz(awzbid,2)then elseif file_exists(logTxt)then local new = readFile(logTxt)[1] if new == "1" then return true elseif new == "3" then toast('IP-->้‡ๅค่ฏทๆณจๆ„',1) return true elseif new == '2' then toast('ไธ€้”ฎๆ–ฐๆœบไธญ',2) end mSleep(2000) end mSleep(1000* 3) end end function awz_() openURL("IGG://cmd/open"); mSleep(2000) local logTxt = '/var/mobile/iggresult.txt' local out_time = os.time() while os.time()-out_time <= 10 do if activeawz(awzbid,2)then else openURL("IGG://cmd/newrecord"); mSleep(3000) return true end mSleep(1000* 3) end end function awz_next() function nextrecord() local sz = require("sz"); local http = require("szocket.http"); local res, code = http.request("http://127.0.0.1:1688/cmd?fun=nextrecord"); if code == 200 then local resJson = sz.json.decode(res); local result = resJson.result; nLog("the result is: " .. result); if tonumber(result) == 1 then return true end end end out_time = os.time() while os.time()-out_time <= 10 do if activeawz(awzbid,2)then elseif nextrecord()then return true end mSleep(1000* 2) end end function renameCurrentRecord(name) local sz = require("sz"); local http = require("szocket.http"); local res, code = http.request("http://127.0.0.1:1688/cmd?fun=renamecurrentrecord&name="..name); if code == 200 then local resJson = sz.json.decode(res); local result = resJson.result; nLog("the result is: " .. result); return true end end function reName(newName) timeLine = os.time() outTime = 60 * 0.5 while (os.time()-timeLine < outTime) do if activeawz(awzbid,3)then elseif renameCurrentRecord(newName)then return true end mSleep(1000) end nLog('้‡ๅ‘ฝไปค่ถ…ๆ—ถ') end function newRecord() local sz = require("sz"); local http = require("szocket.http"); local res, code = http.request("http://127.0.0.1:1688/cmd?fun=newrecord"); if code == 200 then local resJson = sz.json.decode(res); local result = resJson.result; nLog("the result is: " .. result); if result == 3 then --//IPๅœฐๅ€้‡ๅค dialog('ip ๅœฐๅ€้‡ๅค', 3) return true elseif result == 1 then return true elseif result == 2 then toast('ๆญฃๅœจไธ€้”ฎๆ–ฐๆœบing',1) end end end function awzNew() timeLine = os.time() outTime = 60 * 0.5 while (os.time()-timeLine < outTime) do if activeawz(awzbid,3)then elseif newRecord() then return true end mSleep(1000) end nLog('ๆ–ฐๆœบ่ถ…ๆ—ถ') end function setCurrentRecordLocation(location) local sz = require("sz"); local http = require("szocket.http"); local res, code = http.request("http://12192.168.127.12:1688/cmd?fun=setcurrentrecordlocation&location="..location); if code == 200 then local resJson = sz.json.decode(res); local result = resJson.result; toast("the result is: " .. result, 2); if tonumber(result) == 1 then return true end end end function NewPlace(location) timeLine = os.time() outTime = 60 * 0.5 while (os.time()-timeLine < outTime) do if activeawz(awzbid,3)then elseif setCurrentRecordLocation(location) then return true end mSleep(1000) end nLog('่ฎพ็ฝฎ่ถ…ๆ—ถ') end --("116.7361382365_39.8887921413_ๅŒ—ไบฌ่€่ƒกๅŒ") function getAll() local sz = require("sz"); local http = require("szocket.http"); local res, code = http.request("http://127.0.0.1:1688/cmd?fun=getallrecordnames"); if code == 200 then local resJson = sz.json.decode(res); local result = resJson.result; toast("the result is: " .. result, 2); if tonumber(result) == 1 then return #readFile('/var/mobile/iggrecords.txt') end end end function getAllmun() timeLine = os.time() outTime = 60 * 0.5 while (os.time()-timeLine < outTime) do if activeawz(awzbid,3)then else return getAll() end mSleep(1000) end nLog('่ฎพ็ฝฎ่ถ…ๆ—ถ') end --่Žทๅ–ๅฝ“ๅ‰ๅ function getOnlineName() function getName() local sz = require("sz"); local http = require("szocket.http"); local res, code = http.request("http://127.0.0.1:1688/cmd?fun=getcurrentrecordparam"); if code == 200 then local resJson = sz.json.decode(res); local result = resJson.result; nLog("the result is: " .. result); if tonumber(result) == 1 then local jg = readFile('/var/mobile/iggparams.txt') return jg end end end timeLine = os.time() outTime = 60 * 0.5 while (os.time()-timeLine < outTime) do if activeawz(awzbid,3)then else return getName() end mSleep(1000) end nLog('่ฎพ็ฝฎ่ถ…ๆ—ถ') end function getTrueName_awz() function getTrueName() local sz = require("sz"); local http = require("szocket.http"); local res, code = http.request("http://127.0.0.1:1688/cmd?fun=getcurrentrecordparam"); if code == 200 then local resJson = sz.json.decode(res); local result = resJson.result; nLog("the result is: " .. result); if tonumber(result) == 1 then jg = readFile('/var/mobile/iggparams.txt') return jg[1],jg[4] --name,idfa end end end timeLine = os.time() outTime = 60 * 0.5 while (os.time()-timeLine < outTime) do if activeawz(awzbid,3)then else return getTrueName() end mSleep(1000) end end nLog('AWZ ๅŠ ๆˆชๅฎŒๆˆ') <file_sep> require("TSLib") require("tsp") var = {} var.appbid = "com.baihe.online"; var.phone = '15033485259' var.password = '<PASSWORD>' t={} sys = { clear_bid = (function(bid) closeApp(bid) delay(1) os.execute("rm -rf "..(appDataPath(bid)).."/Documents/*") --Documents os.execute("rm -rf "..(appDataPath(bid)).."/Library/*") --Library os.execute("rm -rf "..(appDataPath(bid)).."/tmp/*") --tmp clearPasteboard() --[[ local path = _G.const.cur_resDir os.execute( table.concat( { string.format("mkdir -p %s/keychain", path), 'killall -SIGSTOP SpringBoard', "cp -f -r /private/var/Keychains/keychain-2.db " .. path .. "/keychain/keychain-2.db", "cp -f -r /private/var/Keychains/keychain-2.db-shm " .. path .. "/keychain/keychain-2.db-shm", "cp -f -r /private/var/Keychains/keychain-2.db-wal " .. path .. "/keychain/keychain-2.db-wal", 'killall -SIGCONT SpringBoard', }, '\n' ) ) ]] clearAllKeyChains() clearIDFAV() --clearCookies() delay(2) return true end) } --getๅ‡ฝๆ•ฐ function get_lx(url) local sz = require("sz") local http = require("szocket.http") local res, code = http.request(url); if code == 200 then return res end end --ๆฅไฟกๅนณๅฐ function _vCode_lx() --ๆฅไฟก local User = 'api-<PASSWORD>' local Pass = '<PASSWORD>' local PID = '1770' local token,number = "<KEY>","" return { login=(function() local RetStr for i=1,5,1 do toast("่Žทๅ–token\n"..i.."ๆฌกๅ…ฑ5ๆฌก") mSleep(1500) local lx_url = 'http://api.banma1024.net/api/do.php?action=loginIn&name='..User..'&password='..Pass log(lx_url) RetStr = get_lx(lx_url) if RetStr then RetStr = strSplit(RetStr,"|") if RetStr[1] == 1 or RetStr[1] == '1' then token = RetStr[2] log('token='..token,true) break end else log(RetStr) end end return RetStr; end), getPhone=(function() local RetStr="" local url___ = "http://api.banma1024.net/api/do.php?action=getPhone&sid="..PID.."&token="..token log(url___) RetStr = get_lx(url___) if RetStr ~= "" and RetStr ~= nil then log(RetStr) RetStr = strSplit(RetStr,"|") end if RetStr[1] == 1 or RetStr[1]== '1' then number = RetStr[2] log(number) local phone_title = (string.sub(number,1,3)) local blackPhone = {'165','144','141','142','143','144','145','146','147'} for k,v in ipairs(blackPhone) do if phone_title == v then local lx_url = 'http://api.banma1024.net/api/do.php?action=addBlacklist&sid='..PID..'&phone='..number..'&token='..token get_lx(lx_url); log("ๆ‹‰้ป‘->"..number) return false end end return number end end), getMessage=(function() local Msg for i=1,25,1 do mSleep(3000) RetStr = get_lx("http://api.banma1024.net/api/do.php?action=getMessage&sid="..PID.."&token="..token.."&phone="..number) log(RetStr); if RetStr then local arr = strSplit(RetStr,"|") if arr[1] == '1' then Msg = arr[2] local i,j = string.find(Msg,"%d+") Msg = string.sub(Msg,i,j) end if type(tonumber(Msg))== "number" then log(Msg); return Msg end end toast(tostring(RetStr).."\n"..i.."ๆฌกๅ…ฑ25ๆฌก") end return false end), addBlack=(function() local lx_url = 'http://api.banma1024.net/api/do.php?action=addBlacklist&sid='..PID..'&phone='..number..'&token='..token log("ๆ‹‰้ป‘"..number..'\n'..lx_url); return get_lx(lx_url); end), } end local dxcode = _vCode_lx() dxcode.login() t['็™ปๅฝ•็•Œ้ขโ€”โ€”ๆณจๅ†Œ']={0xff676f, "-317|3|0xff7272,-254|8|0xffffff,-474|10|0xffffff,172|6|0xfffcfc",90,15,48,735,200} --ๅคš็‚นๆ‰พ่‰ฒ t['ๆณจๅ†Œ็•Œ้ข']={0xff6c6b, "-1|-1|0xffeaea,-201|-33|0xffffff,-202|0|0xf34252,-491|-38|0xffffff,-536|2|0xffffff",90,16,53,736,241} --ๅคš็‚นๆ‰พ่‰ฒ t['ๆณจๅ†Œ็•Œ้ขโ€”โ€”ๆ‰‹ๆœบๅท']={0xcacacf, "43|-13|0xffffff,41|-26|0xc7c7cc",90,233,352,508,426} --ๅคš็‚นๆ‰พ่‰ฒ t['ๆณจๅ†Œ็•Œ้ขโ€”โ€”็ซ‹ๅณๆณจๅ†Œ']={0xffffff, "284|-49|0xff2e6d,-317|44|0xff7330,-19|-4|0xff514f",90,30,563,720,734} --ๅคš็‚นๆ‰พ่‰ฒ t['่พ“ๅ…ฅ้ชŒ่ฏ็ ็•Œ้ข']={0xfc6e27, "92|-10|0xf9f9f9,94|-12|0xfc6e27,92|13|0xfc6e27,434|3|0xeeeeee,435|3|0x000000,432|8|0x000000",90,11,52,481,116} --ๅคš็‚นๆ‰พ่‰ฒ t['ๅŸบๆœฌไฟกๆฏ็•Œ้ข']={0xfc6e27, "15|-18|0xfc6e27,15|15|0xf9f9f9,390|-9|0xdedede,391|-9|0x000000,389|-6|0x161616,389|-5|0xf9f9f9",90,14,48,714,672} --ๅคš็‚นๆ‰พ่‰ฒ t['ๅŸบๆœฌไฟกๆฏ็•Œ้ข-้šๆœบๆ˜ต็งฐ']={0xff5f5e, "-62|-29|0xff5f5e,56|30|0xff5f5e,86|0|0xff5f5e,5|-2|0xffffff",90,523,140,734,227} --ๅคš็‚นๆ‰พ่‰ฒ t['ๅŸบๆœฌไฟกๆฏ็•Œ้ข-้šๆœบ็”ทๅฅณ']={0x7ba2fe, "405|3|0xff7d5e,-49|-47|0x809efe,539|43|0xff615e",90,35,383,708,629} --ๅคš็‚นๆ‰พ่‰ฒ t['ๅฎŒๅ–„ไฟกๆฏ็•Œ้ข']={0xfc6e27, "156|-11|0xf9f9f9,158|1|0xfc6e27,379|7|0xf9f9f9,382|4|0x000000,382|2|0xf9f9f9",90,5,51,476,115} --ๅคš็‚นๆ‰พ่‰ฒ t['ๅฎŒๅ–„ไฟกๆฏ็•Œ้ข-ๅฎŒๆˆๆณจๅ†Œ']={0xffffff, "-315|-43|0xfe7d46,270|42|0xff4971",90,59,1085,711,1252} --ๅคš็‚นๆ‰พ่‰ฒ --้”™่ฏฏไฟกๆฏ t['ๅทฒ็ปๆณจๅ†Œ-ไธ–็บชไพ็ผ˜']={0xff7e6a, "-444|-308|0xff4e56,-107|-170|0xfef6fb,-293|-141|0xff8989",90,4,43,659,503} --ๅคš็‚นๆ‰พ่‰ฒ t['ๅทฒ็ปๆณจๅ†Œ-ๅ…่ดนๆ‰“ๆ‹›ๅ‘ผ']={0xff6e1d, "-251|-40|0xff6e1d,242|-36|0xff6e1d,249|41|0xff6e1d,-76|2|0xffffff,250|-869|0xffffff",90,62,96,669,1132} --ๅคš็‚นๆ‰พ่‰ฒ t['ๅทฒ็ปๆณจๅ†Œ-ไธŠไผ ๅคดๅƒ']={0xffffff, "-488|558|0xfc6e27,-9|642|0xfc6e27,6|727|0xfc6e27,-503|715|0xffffff,-505|715|0xfc6e27",90,78,209,686,1054} --ๅคš็‚นๆ‰พ่‰ฒ function rdclicks(x,y,n) if n == 0 then return false end for i=1,n do click(x,y,0.5) end end function reg() local timeline = os.time() local outTimes = 60 * 3 var.password = "<PASSWORD>" local fix_info = false while os.time()-timeline < outTimes do if active(var.appbid,5) then if d('็™ปๅฝ•็•Œ้ขโ€”โ€”ๆณจๅ†Œ',true) then elseif d('ๆณจๅ†Œ็•Œ้ข')then if d('ๆณจๅ†Œ็•Œ้ขโ€”โ€”ๆ‰‹ๆœบๅท')then var.phone = dxcode.getPhone() if var.phone then d('ๆณจๅ†Œ็•Œ้ขโ€”โ€”ๆ‰‹ๆœบๅท',true) input[3](var.phone) end elseif d('ๆณจๅ†Œ็•Œ้ขโ€”โ€”็ซ‹ๅณๆณจๅ†Œ',true)then end elseif d('่พ“ๅ…ฅ้ชŒ่ฏ็ ็•Œ้ข')then var.sms = dxcode.getMessage() if var.sms then input[3](var.sms) else return false end elseif d('ๅฎŒๅ–„ไฟกๆฏ็•Œ้ข')then local fix____ ={{657,432,0xffffff},{650,541,0xffffff},{653,646,0xd9d9d9},{561,759,0xffffff}, {524,870,0xffffff},{429,972,0xcccccc},} --ๅคš็‚นๅ–่‰ฒ for i,v in ipairs(fix____) do if i == 1 then click(v[1],v[2],2) rdclicks(119,1201,rd(2,5)) rdclicks(378,1146,rd(2,5)) rdclicks(625,1147,rd(2,5)) click(687,778)--็กฎๅฎš elseif i == 2 then click(v[1],v[2],3) click(687,778)--็กฎๅฎš elseif i == 3 then click(v[1],v[2],2) click(rd(70,667),rd(876,1276)) click(687,778)--็กฎๅฎš elseif i == 4 or i ==5 then rdclicks(v[1],v[2],rd(2,4)) elseif i == 6 then click(v[1],v[2],1) end end if d('ๅฎŒๅ–„ไฟกๆฏ็•Œ้ข-ๅฎŒๆˆๆณจๅ†Œ',true)then fix_info = true up('็‚นๅ‡ปๆไบค') -- return true end elseif d('ๅŸบๆœฌไฟกๆฏ็•Œ้ข')then d('ๅŸบๆœฌไฟกๆฏ็•Œ้ข-้šๆœบๆ˜ต็งฐ',true,1) click(633,292) input[1](var.password) d('ๅŸบๆœฌไฟกๆฏ็•Œ้ข-้šๆœบ็”ทๅฅณ',true,rd(1,2),3) elseif fix_info and (d('ๅทฒ็ปๆณจๅ†Œ-ๅ…่ดนๆ‰“ๆ‹›ๅ‘ผ',true,1,rd(2,5)) or d('ๅทฒ็ปๆณจๅ†Œ-ไธŠไผ ๅคดๅƒ',true)) then log("ๅฎŒๆˆๆณจๅ†Œ",true) return true elseif d('ๅทฒ็ปๆณจๅ†Œ-ไธ–็บชไพ็ผ˜') or d('ๅทฒ็ปๆณจๅ†Œ-ๅ…่ดนๆ‰“ๆ‹›ๅ‘ผ') or d('ๅทฒ็ปๆณจๅ†Œ-ไธŠไผ ๅคดๅƒ',true) then dxcode.addBlack() up('ๆณจๅ†Œ่ฟ‡ๆ‹‰้ป‘') return false end end delay(2) end end function up(other) local url = 'http://hb.wenfree.cn/api/Public/idfa/' local postdate = {} postdate.service = 'Idfa.Idfa' postdate.name = '็™พๅˆๅฉšๆ‹' postdate.idfa = var.phone postdate.password = <PASSWORD> postdate.other = other log(post(url,postdate)) -- body end require("AWZ") function all() while true do if true or vpn.on() then if sys.clear_bid(var.appbid)then if reg()then up('ๅฎŒๆ•ดๆณจๅ†Œ') end end end end end while (true) do local ret,errMessage = pcall(all) if ret then else log(errMessage) dialog(errMessage, 10) mSleep(2000) end end <file_sep>-- ็ง’ๅ…ต require("tsp") init(1) -- ไธ‡ๅ›ฝ่ง‰้†’ -- ui.lua -- Create By TouchSpriteStudio on 20:40:56 -- Copyright ยฉ TouchSpriteStudio . All rights reserved. require('tsp') local sz = require("sz") local cjson = sz.json -- local ts = require("ts") -- local cjson = ts.json w,h = getScreenSize(); log({w,h}) MyTable = { ["style"] = "default", ["rettype"] = "table", ["width"] = w, ["height"] = h, ["orient"] = "0", ["bgcolor"] = "255,255,255", ["btnbkcolor"] = "238,236,225", ["config"] = "rok", ["pagetype"] = "multi", ["selpage"] = "1", ["pagenumtype"] = "number", ["titles"] = "็ฌฌ1้กต", ["timer"] = "30", ["cancelname"] = "ๅ–ๆถˆ", ["okname"] = "็กฎๅฎš", pages= { { {["type"] = "Label",["color"] = "255,30,2",["size"] = "12",["align"] = "left",["text"] = "ๅ…ต็ง้€‰ๆ‹ฉ",}, { ["type"] = "RadioGroup", ["select"] = "1", ["id"] = "ๅ…ต็ง้€‰ๆ‹ฉ", ["list"] = "ๆญฅๅ…ต,ๅผ“ๅ…ต,้ช‘ๅ…ต,่ฝฆๅ…ต", }, {["type"] = "Label",["color"] = "255,30,2",["size"] = "12",["align"] = "left",["text"] = "ๆ˜ฏๅฆๅ‡็บงไฝŽ้˜ถๅ…ต",}, { ["type"] = "Switch", ["id"] = "update", ["size"] = "m", ["state"] = "off", ["align"] = "left", }, } }, } local MyJsonString = cjson.encode(MyTable); UIret,UIv = showUI(MyJsonString) if UIret == 1 then log(UIv) else lua_exit() end if not(t)then t={} degree = 90 end t['่ฝฆ']={0x005cb3, "0|0|0x005cb3,-30|11|0xffbd79",90,977,184,1332,345} t['้€ ่ฝฆ']={0x006a9d, "0|0|0x006a9d,-157|9|0x20aa10,-311|-16|0x0c83bd",90,752,167,1333,512} t['่ฎญ็ปƒ']={0x00c2fe, "0|0|0x00c2fe,-54|-8|0x1176bc,-314|7|0xffab00",90,581,532,1148,674} t['ๅŠ ้€Ÿ']={0xdfa30f, "0|0|0xdfa30f,144|-13|0x00699b,-137|-26|0x077bb2",90,664,164,1330,526} t['ๅŠ ้€Ÿ-ไฝฟ็”จ']={0x1274ba, "0|0|0x1274ba,-88|-20|0x00cffd,52|23|0x00aeeb",90,718,323,1169,465} t['ๅŠ ้€Ÿ-ไฝฟ็”จ-X']={0x1274ba, "0|0|0x1274ba,-20|-5|0x00c3ff,-54|-9|0xe1ebef",90,716,182,1164,464} t['ๅŠ ้€Ÿ-ไฝฟ็”จ-TOP']={0x1274ba, "0|0|0x1274ba,-46|-7|0x00c8ff,-13|-23|0x00d0f9",90,721,192,1156,332} t['้€ ๅ…ต-ๅ‡†ๅค‡่ฎญ็ปƒ']={0x0375ac, "0|0|0x0375ac,-151|16|0x1ba80e,-302|-15|0x128bc5",90,50,91,1310,705} t['้€ ๅ…ต-ๅ‡†ๅค‡่ฎญ็ปƒ']={0xd1e6e9, "0|0|0xd1e6e9,-102|7|0x6dd151,-239|-11|0xd9e7ee,-239|-4|0x26a3d8",90,102,261,1240,743} t['้€ ๅ…ต-ๅ‡†ๅค‡่ฎญ็ปƒ-ๅผ“ๆ‰‹']={0xe0ebef, "0|0|0xe0ebef,-5|11|0x57c2f2,-139|12|0xe5e8e1,-276|2|0xe4edf0",90,118,279,1272,735} t['้€ ๅ…ต-่ฎญ็ปƒ-ๅฏไปฅๅ‡็บง']={0x34bc00, "0|0|0x34bc00,12|-4|0xf2ff00",90,514,114,1029,167} t['้€ ๅ…ต-่ฎญ็ปƒ-ๅฏไปฅๅ‡็บง-้ป„่‰ฒ']={0xb56a00, "0|0|0xb56a00,-2|11|0xffd27f",90,186,142,282,222} t['้€ ๅ…ต-่ฎญ็ปƒ'] = { 0xfafeff,"20|-28|0xcffe,-92|-14|0xc5ff",degree,914,574,1137,659} t['้€ ๅ…ต-ๅŠ ้€Ÿ'] = { 0xd3d1c9,"-151|515|0x1176bc,-232|500|0xd1ff,-38|545|0xb6f3",degree,858,58,1365,680} t['้€ ๅ…ต-ๅ‡†ๅค‡่ฎญ็ปƒ-ๅ…ณ้—ญ']={0x245aa0, "0|0|0x245aa0,-90|-13|0x0fa2e0,107|-12|0x0fa1e0,142|8|0x002b4d",90,49,202,1323,648} t['้€ ๅ…ต-ๅ‡†ๅค‡่ฎญ็ปƒ-ๅ…ณ้—ญ']={0xd3d1c9, "0|0|0xd3d1c9,-162|523|0x00c2ff,-479|522|0xffb000",90,570,67,1166,656} t['้€ ๅ…ต-้ช‘ๅ…ตๅทฅๅŽ‚']={0x1f6198, "0|0|0x1f6198,-4|-3|0xa8553c,-21|22|0xfdd274,-19|26|0x18557d",90,323,6,583,208} t['้€ ๅ…ต-ๅผ“ๅ…ตๅทฅๅŽ‚']={0x0b56ff, "0|0|0x0b56ff,11|16|0xbf9d85,-4|4|0xfda92b,-9|1|0x0a34b1",90,798,47,1005,367} t['้€ ๅ…ต-่ฝฆๅ…ตๅทฅๅŽ‚']={0xffe290, "0|0|0xffe290,22|6|0x0063be,44|6|0xfefcd9,-31|-12|0x00549d,-28|-1|0xffa86d",90,20,159,1317,750} t['้€ ๅ…ต-่ฝฆๅ…ตๅทฅๅŽ‚-่ฝฆ']={0x005cb3, "0|0|0x005cb3,-30|11|0xffbd79",90,977,184,1332,345} t['้€ ๅ…ต-่ฝฆๅ…ตๅทฅๅŽ‚-่ฝฆ-็™ฝๅคฉ']={0x005eb2, "0|0|0x005eb2,-30|2|0xfebf7a",90,910,176,1329,583} t['้€ ๅ…ต-่ฝฆๅ…ตๅทฅๅŽ‚-่ฝฆ-ๅคœ้‡Œ']={0x2048c0, "0|0|0x2048c0,-6|3|0x0a2260",90,962,162,1327,444} t['้€ ๅ…ต-่ฝฆๅ…ตๅทฅๅŽ‚-่ฝฆ-ๆญฃๅœจ็”Ÿไบง']={0xe0a00c, "0|0|0xe0a00c,3|-24|0xf3f1f0,123|-9|0x026698,-142|-22|0x0876ab",90,858,223,1333,655} t['้€ ๅ…ต-่ต„ๆบไธ่ถณ']={0x00c2fe, "0|0|0x00c2fe,384|-383|0xd2d0ca,-13|-382|0x858278,47|-237|0x055171",90,459,79,1102,633} t['้€ ๅ…ต-่ต„ๆบไธ่ถณ-ไฝฟ็”จ']={0x1274ba, "0|0|0x1274ba,7|-20|0x00cefc,20|22|0x01a4e4",90,908,162,1136,471} t['้€ ๅ…ต-่ต„ๆบไธ่ถณ-ไฝฟ็”จ*']={0x1274ba, "0|0|0x1274ba,1|13|0x009edf",90,745,175,912,652} t['้€ ๅ…ต-่ต„ๆบไธ่ถณ-ไฝฟ็”จ-X']={0xd3d2cb, "0|0|0xd3d2cb,-7|-8|0xd8d7ce,-54|21|0xbdbdad,-57|46|0x044a68",90,1026,34,1216,160} t['่”็›Ÿ-ๅ…ณ้—ญ']={0x6ae4ff, "0|0|0x6ae4ff,-99|7|0x6de4ff,-313|8|0x74e5ff,-417|7|0x014874",90,761,660,1327,738} t['้€ ๅ…ต-ๅŠ ้€Ÿ']={0xe0a20e, "0|0|0xe0a20e,1|-45|0xf2ede3,-121|-31|0x0f8ac1,141|-83|0xeff0eb",90,294,203,1295,735} function _soldier() log("<--้€ ๅ…ต-->") local ๅ…ต็ง_ = { ["ๆญฅๅ…ต"]={ 571, 477, 0xecc3a7}, ["ๅผ“ๅ…ต"]={ 338, 516, 0xf4caaa}, ["้ช‘ๅ…ต"]={ 923, 554, 0xfed7b5}, ["่ฝฆๅ…ต"]={ 1066, 435, 0xffbf80} } d("่”็›Ÿ-ๅ…ณ้—ญ",true) local klist = {"ๆญฅๅ…ต","ๅผ“ๅ…ต","้ช‘ๅ…ต","่ฝฆๅ…ต"} k = klist[ tonumber( UIv['ๅ…ต็ง้€‰ๆ‹ฉ'] )+1 ] v = ๅ…ต็ง_[k] log('ๅ‡†ๅค‡้€ ->'..k ) click( v[1],v[2],1) if not ( d('้€ ๅ…ต-ๅ‡†ๅค‡่ฎญ็ปƒ') or d("้€ ๅ…ต-ๅ‡†ๅค‡่ฎญ็ปƒ-ๅผ“ๆ‰‹") ) then click( v[1],v[2],1) d('้€ ๅ…ต-ๅ‡†ๅค‡่ฎญ็ปƒ',true,1,1) d("้€ ๅ…ต-ๅ‡†ๅค‡่ฎญ็ปƒ-ๅผ“ๆ‰‹",true) else if d('้€ ๅ…ต-ๅ‡†ๅค‡่ฎญ็ปƒ',true,1,2) or d("้€ ๅ…ต-ๅ‡†ๅค‡่ฎญ็ปƒ-ๅผ“ๆ‰‹",true) then end end if ( UIv.update ) then if k == "่ฝฆๅ…ต" then click(657,183) elseif d("้€ ๅ…ต-่ฎญ็ปƒ-ๅฏไปฅๅ‡็บง",true,1,1) and d( "้€ ๅ…ต-่ฎญ็ปƒ-ๅฏไปฅๅ‡็บง-้ป„่‰ฒ",true,1,2 ) then log("ๆŠŠๅžƒๅœพๅ…ตๅ‡็บง") end end if d('้€ ๅ…ต-่ฎญ็ปƒ',true,1,2) or d('้€ ๅ…ต-ๅŠ ้€Ÿ',true,1,2) then if d('้€ ๅ…ต-่ต„ๆบไธ่ถณ',true,1,2) then d('้€ ๅ…ต-่ต„ๆบไธ่ถณ-ไฝฟ็”จ',true,1,2) d('้€ ๅ…ต-่ต„ๆบไธ่ถณ-ไฝฟ็”จ*',true,1,2) d('้€ ๅ…ต-่ต„ๆบไธ่ถณ-ไฝฟ็”จ-X',true,1,2) d('้€ ๅ…ต-่ฎญ็ปƒ',true,1,2) end else d("้€ ๅ…ต-ๅ‡†ๅค‡่ฎญ็ปƒ-ๅ…ณ้—ญ",true) end click( v[1],v[2],1) d("้€ ๅ…ต-ๅŠ ้€Ÿ",true) d('ๅŠ ้€Ÿ-ไฝฟ็”จ',1,1) d('ๅŠ ้€Ÿ-ไฝฟ็”จ-X',1,1) d('ๅŠ ้€Ÿ-ไฝฟ็”จ-TOP',1,1) d('ๅŠ ้€Ÿ-ไฝฟ็”จ-X',1,1) d('ๅŠ ้€Ÿ-ไฝฟ็”จ-TOP',1,1) end for i=1,9999 do _soldier() end <file_sep> require("UIs") require("api") require("ui") require("re-login") var = {} var.bid = 'com.nike.onenikecommerce' var.account={} var.account.email = nil var.account.password = nil var.account.phone = nil info = {} local ๅ = {"ๅฏน","่ฟ›","ๅคš","ๅ…จ","ๅปบ","ไป–","ๅ…ฌ","ๅผ€","ไปฌ","ๅœบ","ๅฑ•","ๆ—ถ","็†","ๆ–ฐ","ๆ–น","ไธป","ไผ","่ต„","ๅฎž","ๅญฆ","ๆŠฅ","ๅˆถ", "ๆ”ฟ","ๆตŽ","็”จ","ๅŒ","ไบŽ","ๆณ•","้ซ˜","้•ฟ","็Žฐ","ๆœฌ","ๆœˆ","ๅฎš","ๅŒ–","ๅŠ ","ๅŠจ","ๅˆ","ๅ“","้‡","ๅ…ณ","ๆœบ","ๅˆ†","ๅŠ›","่‡ช","ๅค–", "่€…","ๅŒบ","่ƒฝ","่ฎพ","ๅŽ","ๅฐฑ","็ญ‰","ไฝ“","ไธ‹","ไธ‡","ๅ…ƒ","็คพ","่ฟ‡","ๅ‰","้ข"} local ๅง“ = {"่ตต","้’ฑ","ๅญ™","ๆŽ","ๅ‘จ","ๅด","้ƒ‘","็Ž‹"} function snkrs_reg() --่ฎพ็ฝฎๆ—ถ้—ด็บฟ local timeline = os.time() --่ฎพ็ฝฎๆณจๅ†Œๆ—ถ้—ด local outTimes = 150; --ไธป็บฟ็จ‹ while os.time()-timeline < outTimes do if active(var.bid,3) then if d(">ๅผ•ๅฏผ้กต-ๅŒๆ„<",true,1,2)then updateNikeLog(">ๅผ•ๅฏผ้กต-ๅŒๆ„<") elseif d('ๅผ•ๅฏผ้กต-็™ปๅฝ•-ๅŠ ๅ…ฅ',true,1,6) then updateNikeLog("็™ปๅฝ•-ๅŠ ๅ…ฅ") elseif d("ๆณจๅ†Œ-ๅˆ›ๅปบๆ‚จ็š„NIKEไผšๅ‘˜") then updateNikeLog("ๅˆ›ๅปบๆ‚จ็š„NIKEไผšๅ‘˜") --็‚นๅ‡ปๆ‰‹ๆœบๅท็  click(320,545) clearTxt() if getPhone() then var.account.phone = info.phone inputword( var.account.phone ) end d("ๆณจๅ†Œ-ๅˆ›ๅปบๆ‚จ็š„NIKEไผšๅ‘˜-ๅ‘้€้ชŒ่ฏ็ ",true,1,5) if d("ๆณจๅ†Œ-ๅˆ›ๅปบๆ‚จ็š„NIKEไผšๅ‘˜-้”™่ฏฏๆ็คบ")then log( get_("http://jmmjj.cn:88/yhapi.ashx?act=addBlack&token=87976e4530c590320c1dffac4173ec0f&pid="..info.pid.."&reason=used") ) return false end if d("ๆณจๅ†Œ-ๅˆ›ๅปบๆ‚จ็š„NIKEไผšๅ‘˜-่พ“ๅ…ฅ้ชŒ่ฏ็ ",true,1,5) then --่ฎพ็ฝฎๅ–็Ÿญไฟกๆ—ถ้—ด local sms_true = true local getSMStimes = 0 while ( getSMStimes < 30 ) do getSMStimes = getSMStimes + 1 if getMessage() then inputword( info.yzm ) sms_true = false break end delay(3) end if sms_true then log('็Ÿญไฟก่ถ…ๆ—ถ') return false end end --่ฎพ็ฝฎ่พ“ๅ…ฅๅฎŒๆˆ if d("ๆณจๅ†Œ-ๅˆ›ๅปบๆ‚จ็š„NIKEไผšๅ‘˜-ๅ‰ๅพ€",true,1,2) then elseif d("ๅผน็ช—-่พ“ๅ…ฅๅฎŒๆˆ",true,1,4) then if d("ๆณจๅ†Œ-ๅˆ›ๅปบๆ‚จ็š„NIKEไผšๅ‘˜-็ปง็ปญ",true,1,5) or d("ๆณจๅ†Œ-ๅˆ›ๅปบๆ‚จ็š„NIKEไผšๅ‘˜-็ปง็ปญ-Up",true,1,5) then --ๆœ‰2ไธช็ปง็ปญ end end elseif d("ๆณจๅ†Œ-ๅกซ่ต„ๆ–™้กต้ข") or d("ๆณจๅ†Œ-ๅกซ่ต„ๆ–™้กต้ข2") then updateNikeLog("ๅกซ่ต„ๆ–™้กต้ข") --่พ“ๅ…ฅๅง“ๅ็š„ไฝ็ฝฎ d("ๆณจๅ†Œ-ๅกซ่ต„ๆ–™้กต้ข-ๅง“",true ) -- click(170, 450,2) first_name_ = ๅง“[rd(1,#ๅง“)] -- clearTxt() delay(1) input(first_name_,true) d("ๅผน็ช—-่พ“ๅ…ฅ>",true,1,2) -- clearTxt() delay(1) last_names_ = ๅ[rd(1,#ๅ)] input(last_names_,true) d("ๅผน็ช—-่พ“ๅ…ฅ>",true,1,2) var.account.password = "<PASSWORD>" if UIv.password_key == "0" then var.account.password = myRand(3,1,1)..myRand(3,3,2)..myRand(1,4) end input(var.account.password,true) d("ๅผน็ช—-่พ“ๅ…ฅ>",true,1,2) for i=0,rd(8,12) do click(154, 805+rd(-50,50),rd(3,5)/10) --ๅ‘ไธŠ็ฟปๅŠจ end d("ๅผน็ช—-่พ“ๅ…ฅๅฎŒๆˆ",true,1,2) d("ๆณจๅ†Œ-ๅกซ่ต„ๆ–™้กต้ข-็”ทๅฅณ",true,rd(3,4),2) d("ๆณจๅ†Œ-ๅกซ่ต„ๆ–™้กต้ข-ๆˆ‘ๅŒๆ„",true,1) d("ๆณจๅ†Œ-ๅกซ่ต„ๆ–™้กต้ข-ๅŠ ๅ…ฅๆˆ‘ไปฌ",true,1,5) elseif d("ๆณจๅ†Œ-่พ“ๅ…ฅ็”ตๅญ้‚ฎไปถ") then updateNikeLog("่พ“ๅ…ฅ็”ตๅญ้‚ฎ") var.account.email = myRand(3,rd(3,5),2).. os.date("%S",os.time())..rd(1,30)..myRand(3,rd(1,3),2)..myRand(1,rd(1,3))..mailheader[rd(1,#mailheader)] if d("ๆณจๅ†Œ-่พ“ๅ…ฅ็”ตๅญ้‚ฎไปถ-็”ตๅญ้‚ฎไปถๅœฐๅ€",true,1,2)then input( var.account.email ) d("ๅผน็ช—-่พ“ๅ…ฅๅฎŒๆˆ",true,1,3) end d("ๆณจๅ†Œ-่พ“ๅ…ฅ็”ตๅญ้‚ฎไปถ-ไฟๅญ˜",true,1,10) elseif d("ๆณจๅ†ŒๆˆๅŠŸ-ไธป็•Œ้ข")then updateNikeLog("ๆณจๅ†ŒๆˆๅŠŸ") --ๆณจๅ†ŒๆˆๅŠŸๅ‡†ๅค‡ไธŠไผ  updateNike() update_token() get("http://127.0.0.1:8080/api/reportInfo"); return true else if d("ๅผน็ช—-ไธ็ฌฆๅˆๆณจๅ†Œๆกไปถ") then return end end end delay(1) log( "snkrs_reg->"..os.time()-timeline ) end end function snkrs_setting() --่ฎพ็ฝฎๆ—ถ้—ด็บฟ local timeline = os.time() --่ฎพ็ฝฎๆณจๅ†Œๆ—ถ้—ด local outTimes = 60*5; local pay_key = true --ไธป็บฟ็จ‹ while os.time()-timeline < outTimes do if active(var.bid,3) then if d( "ๆณจๅ†ŒๆˆๅŠŸ-ไธป็•Œ้ข" )then updateNikeLog("ๅ‡†ๅค‡่ฎพ็ฝฎ") d("่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘",true,1) elseif d("่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ",true,1,2)then elseif d("่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข")then --่ฎพ็ฝฎๅคดๅƒ่ฟ™้‡Œ if false and d("่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข-ๅคดๅƒ",true,1,2)then d("่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข-ๅคดๅƒ-้€‰ๆ‹ฉ็…ง็‰‡",true,1,2) d("่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข-ๅคดๅƒ-ๆ‰€ๆœ‰็…ง็‰‡",true,1,2) click(rd(56,588),rd(188,1084),2) click(579, 1064) elseif pay_key and d("่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข-ไป˜ๆฌพไฟกๆฏ",true,1,5) then if d("่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข-ไป˜ๆฌพไฟกๆฏ-ๅทฒ็ป้€‰ๆ‹ฉ") or d("่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข-ไป˜ๆฌพไฟกๆฏ-้€‰ๆ‹ฉ",true,rd(2,3) , 3) then pay_key = false end elseif d("่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข-้…้€ไฟกๆฏ",true,1,3)then if d("่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข-้…้€ๅœฐๅ€้กต้ข-ๅทฒ็ปๆœ‰ๅœฐๅ€")then updateNike() return true elseif d("่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข-้…้€ๅœฐๅ€้กต้ข-ๆ–ฐๅœฐๅ€",true,1,2)then updateNikeLog("ๅ‡†ๅค‡ๅกซ่ต„ๆ–™") --่ฎพ็ฝฎๅง“ๆฐ click(120,214,2) input(first_name_ or ๅง“[rd(1,#ๅง“)]) d("่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข-้…้€ๅœฐๅ€้กต้ข-ๆ–ฐๅœฐๅ€-ไธ‹ไธ€ๆญฅ",true,1,2) input(last_names_ or ๅ[rd(1,#ๅ)]) d("่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข-้…้€ๅœฐๅ€้กต้ข-ๆ–ฐๅœฐๅ€-ไธ‹ไธ€ๆญฅ",true,1,2) inputword(var.account.phone or "18128823269") d("่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข-้…้€ๅœฐๅ€้กต้ข-ๆ–ฐๅœฐๅ€-ไธ‹ไธ€ๆญฅ",true,1,2) for i=1,9 do click(323,984,1) end d("่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข-้…้€ๅœฐๅ€้กต้ข-ๆ–ฐๅœฐๅ€-ไธ‹ไธ€ๆญฅ",true,1,2) for i=1,6 do click(323,984,1) end d("่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข-้…้€ๅœฐๅ€้กต้ข-ๆ–ฐๅœฐๅ€-ไธ‹ไธ€ๆญฅ",true,1,2) for i=1,7 do click(323,984,1) end d("่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข-้…้€ๅœฐๅ€้กต้ข-ๆ–ฐๅœฐๅ€-ไธ‹ไธ€ๆญฅ",true,1,2) --ๅ‡†ๅค‡่พ“ๅ…ฅๅœฐๅ€ var.account.address_area = address_rd() input( var.account.address_area ) d("่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข-้…้€ๅœฐๅ€้กต้ข-ๆ–ฐๅœฐๅ€-ไธ‹ไธ€ๆญฅ",true,1,2) var.account.address_class = ๅ[rd(1,#ๅ)]..ๅ[rd(1,#ๅ)]..ๅ[rd(1,#ๅ)]..'ๅ…ฌๅฏ“' input( var.account.address_class ) d("่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข-้…้€ๅœฐๅ€้กต้ข-ๆ–ฐๅœฐๅ€-ไธ‹ไธ€ๆญฅ",true,1,2) input( '518000' ) d("่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข-้…้€ๅœฐๅ€้กต้ข-ๆ–ฐๅœฐๅ€-ๅฎŒๆˆ",true,1,2) d("่ฎพ็ฝฎ-ไธป็•Œ้ข-ๆˆ‘-่ฎพ็ฝฎ้กต้ข-้…้€ๅœฐๅ€้กต้ข-ๆ–ฐๅœฐๅ€-ไฟๅญ˜",true,1,2) end else moveTo(width/2,hight*0.8,width/2,hight*0.4,10) delay(1) end else d("่ฎพ็ฝฎ-่ฟ”ๅ›ž<",true,1,2) if d(">ๅผ•ๅฏผ้กต-ๅŒๆ„<",true,1,2) then return false end end end delay(1) end end function main() while ( true ) do if UIv.netMode == "0" then setAirplaneMode(true) delay(15) setAirplaneMode(false) delay(15) elseif UIv.netMode == "1" then vpnx() delay(5) if vpn() then log('vpn ่ฟžๆŽฅๆˆๅŠŸ็ปง็ปญ่ฟ›่กŒ') else return end end if UIv.clearMode == '0' then require("AWZ") elseif UIv.clearMode == '1' then require("AXJ") end if UIv.clearMode == '0' then awzNew() end local smsnamelist = {} smsnamelist['0'] = 'ไบ‘ๆตท' smsnamelist['1'] = '้—ช็”ต' info.smsname = smsnamelist[ UIv.smsName ] if UIv.work == '0' then if snkrs_reg() then snkrs_setting() end elseif UIv.work == "1" then active(var.bid,15) get_account() closeApp(var.bid,1) delay(2) snkrs_look() end end end while (true) do local ret,errMessage = pcall( main ) if ret then else log(errMessage) dialog(errMessage, 15) mSleep(1000) closeApp(frontAppBid()) mSleep(2000) end end <file_sep>-- ไธ‡ๅ›ฝ่ง‰้†’ -- ad.lua t['ๅฏน่ฏๆก†']={0xf2f2f2, "0|0|0xf2f2f2,-21|-3|0xededed",90,123,652,178,746} t['ๅฏน่ฏๆก†-็Ž‹ๅ›ฝ']={0x594a30, "0|0|0x594a30,-5|5|0x008fbe",90,13,47,109,608} t['ๅฏน่ฏๆก†-็Ž‹ๅ›ฝ-ๆฟ€ๆดป']={0xf0e9df, "0|0|0xf0e9df,-5|5|0x008fbe",90,13,47,109,608} t['ๅฏน่ฏๆก†-ๆ‰“ๅผ€ไพง่พน']={0xfff2e6, "0|0|0xfff2e6,-1|-7|0xb2925e,-1|-11|0xfff2e6",90,12,3,51,56} t['ๅฏน่ฏๆก†-ๆ‰“ๅผ€ไพง่พน-ๅ‘้€']={0x006adf, "0|0|0x006adf,8|-14|0xe9fbff",90,1261,176,1330,567} function ad() if d('ๅฏน่ฏๆก†',true,1,3) then if d('ๅฏน่ฏๆก†-็Ž‹ๅ›ฝ',true) or d('ๅฏน่ฏๆก†-็Ž‹ๅ›ฝ-ๆฟ€ๆดป') then else d('ๅฏน่ฏๆก†-ๆ‰“ๅผ€ไพง่พน',true) end click(523,711,3) inputStr( _UI.ๅนฟๅ‘Šๅ‘Š[rd(1,#_UI.ๅนฟๅ‘Š)] ) delay(2) if d('ๅฏน่ฏๆก†-ๆ‰“ๅผ€ไพง่พน-ๅ‘้€',true,1,20) then return true end end end t['ๅนฟๅ‘Š-ๆ”ถ่—ๅคน']={0xb46d12, "0|0|0xb46d12,10|5|0xffa700",90,466,-1,524,40} t['ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-ๅ…จ้ƒจ็‚น็‰นๆฎŠ']={0xffffff, "0|0|0xffffff,-234|1|0x098b08",90,188,101,569,186} t['ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-็‰นๆฎŠๆฟ€ๆดป']={0xffffff, "0|0|0xffffff,-58|2|0x088508",90,193,114,563,181} t['ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-ๅˆ ้™คไธ€ๆฌก']={0x005588, "0|0|0x005588,-4|-13|0x005588,70|-5|0x00c2fe",90,910,186,1089,377} t['ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-็‰นๆฎŠๆฟ€ๆดป-ๆ— ไนฆ็ญพ']={0xffffff, "0|0|0xffffff,113|4|0x066f9a,120|3|0xffffff",90,500,351,788,421} t['ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-็‰นๆฎŠๆฟ€ๆดป-ๅ…ณ้—ญ']={0xd3d1ca, "0|0|0xd3d1ca,-11|-9|0xd7d6ce,-9|-2|0x9b9a8d",90,1110,65,1162,107} t['ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-็‰นๆฎŠๆฟ€ๆดป-ๆ”ถ่—่‡ชๅทฑ']={0x995200, "0|0|0x995200,56|-3|0x1274ba,-62|-3|0x1075ba",90,160,79,1319,682} t['ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-็‰นๆฎŠๆฟ€ๆดป-ๆ”ถ่—่‡ชๅทฑ-็›Ÿไธป']={0xd967f7, "0|0|0xd967f7,-63|0|0x1174ba,56|0|0x1274ba",90,71,55,1296,712} t['ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-ๆฟ€ๆดป่‡ชๅทฑ็š„ๆ”ถ่—']={0x003658, "0|0|0x003658,-5|-130|0x0898d5",90,125,170,263,448} t['ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-็‰นๆฎŠๆฟ€ๆดป-ๆ”ถ่—ๅฎŒๆˆ']={0x007aff, "0|0|0x007aff,49|-5|0x007aff,14|18|0x007aff",90,1017,61,1310,635} t['ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-็‰นๆฎŠๆฟ€ๆดป-็กฎๅฎš']={0x1274ba, "0|0|0x1274ba,-59|-17|0x00ccfe,52|17|0x00b7f3",90,273,140,1039,608} t['ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-็‰นๆฎŠๆฟ€ๆดป-ๆœ‰ไนฆ็ญพ']={0x055987, "0|0|0x055987,13|-9|0x025788,14|8|0x005886,9|0|0x1587bf",90,854,190,910,261} t['ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-ไธ–็•Œ้ข‘้“']={0x008fbe, "0|0|0x008fbe,0|-6|0x7b705f,63|2|0xffffff",90,384,74,756,688} t['ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-ไธ–็•Œ้ข‘้“-็กฎๅฎšๅ‘้€']={0x0e75e5, "0|0|0x0e75e5,-20|-12|0xffffff,-201|-3|0xc5b499",90,382,275,936,549} function ads_() d('ๆธธๆˆไธป็•Œ้ข-ๅŸŽๅ†…',true,2) if d('ๆธธๆˆไธป็•Œ้ข-้‡Žๅค–',false,1,3) then if d('ๅนฟๅ‘Š-ๆ”ถ่—ๅคน',true,1,2) then d('ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-ๅ…จ้ƒจ็‚น็‰นๆฎŠ',true,1,3) if d('ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-็‰นๆฎŠๆฟ€ๆดป') then -- ๅฏนๆ—ง็š„ๅนฟๅ‘Šๆ–‡, ่ฟ›่กŒๅˆ ้™ค if ๅˆ ้™คๆ—งๅนฟๅ‘Škey then d("ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-ๅˆ ้™คไธ€ๆฌก",true,1,2) ๅˆ ้™คๆ—งๅนฟๅ‘Škey = false end if d("ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-็‰นๆฎŠๆฟ€ๆดป-ๆœ‰ไนฆ็ญพ",true,1,2) then if d('ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-ไธ–็•Œ้ข‘้“',true,1,2)then if d('ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-ไธ–็•Œ้ข‘้“-็กฎๅฎšๅ‘้€',true,1,2)then delay(10) ๅ‘ๅนฟๅ‘Šๆฌกๆ•ฐ = ๅ‘ๅนฟๅ‘Šๆฌกๆ•ฐ + 1 ๅˆ ้™คๆ—งๅนฟๅ‘Škey = true return true end end else log('ๆ— ไนฆ็ญพ') d('ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-็‰นๆฎŠๆฟ€ๆดป-ๅ…ณ้—ญ',true,1,2) click(663, 358,2) d('ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-็‰นๆฎŠๆฟ€ๆดป-ๆ”ถ่—่‡ชๅทฑ',true,1,2) d("ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-็‰นๆฎŠๆฟ€ๆดป-ๆ”ถ่—่‡ชๅทฑ-็›Ÿไธป",true,1,2) d('ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-ๆฟ€ๆดป่‡ชๅทฑ็š„ๆ”ถ่—',true,1,2) click(576, 251,5) clearTxt() input( __UI.ๅˆ†ไบซๅนฟๅ‘Š[ๅ‘ๅนฟๅ‘Šๆฌกๆ•ฐ] ) delay(5) d("ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-็‰นๆฎŠๆฟ€ๆดป-ๆ”ถ่—ๅฎŒๆˆ",true,1,2) d("ๅนฟๅ‘Š-ๆ”ถ่—ๅคน-็‰นๆฎŠๆฟ€ๆดป-็กฎๅฎš",true,1,2) return false; end end end end end t['ๅ‘ๅนฟๅ‘Š-ๆ‰งๆ”ฟๅฎ˜่ต„ๆ–™-ไธ€ๆŽ’']={0xd06f3b, "142|-10|0xefd134,275|-9|0x31405a,419|-2|0xfdef5a,564|-6|0xffff77,702|-5|0xfaefd7",90,245,502,1083,606} --ๆ›ดๅคšไฟกๆฏ,ๆŽ’่กŒๆฆœ,็ปŸๅธ…,้ƒจ้˜Ÿ,ๆˆๅฐฑ,่ฎพ็ฝฎ t['ๅ‘ๅนฟๅ‘Š-ๆ‰งๆ”ฟๅฎ˜่ต„ๆ–™-ๆŽ’่กŒๆฆœ']={0xc6310f, "0|0|0xc6310f,-154|18|0x117db4,-687|-7|0xd93611",90,145,114,1174,203} t['ๅ‘ๅนฟๅ‘Š-ๆŽ’่กŒๆฆœ-่”็›Ÿ-ๆˆ˜ๅŠ›']={0x953e08, "1|-212|0x964009",90,147,109,291,526} t['ๅ‘ๅนฟๅ‘Š-ๆŽ’่กŒๆฆœ']={0xd3d1ca, "0|0|0xd3d1ca,-20|70|0xb56908,-11|77|0xeba13f,-972|74|0xb66b08",90,108,10,1258,165} t['ๅ‘ๅนฟๅ‘Š-ๆŽ’่กŒๆฆœ-123']={0xfe7e45, "0|85|0x7b7b7b,0|168|0xd07b56",90,155,181,213,532} t['ๅ‘ๅนฟๅ‘Š-ๆŽ’่กŒๆฆœ-ๅฎšไฝ']={0x0c72a9, "0|0|0x0c72a9,35|1|0x3d90bc,38|69|0x0d74ac,0|66|0x0c71a9,-4|33|0x064462",90,137,174,224,337} t['ๅ‘ๅนฟๅ‘Š-ๆŽ’่กŒๆฆœ-ไธชไบบ้‚ฎไปถ']={0xfcecb8, "-3|9|0xc9a366,-23|-7|0xfcfafa",90,826,514,941,604} t['ๅ‘ๅนฟๅ‘Š-ๆŽ’่กŒๆฆœ-็›Ÿไธป้‚ฎไปถ']={0x1274ba, "0|0|0x1274ba,7|-8|0x00c5ff,15|-49|0x1a93c9",90,771,508,945,652} t['ๅ‘ๅนฟๅ‘Š-้‚ฎไปถ้กต้ข']={0x676767, "0|0|0x676767,-4|14|0x888888,-48|6|0x8c8c8c",90,892,105,1091,158} t['ๅ‘ๅนฟๅ‘Š-้‚ฎไปถๅฎŒๆˆ-ๅทฆไธ‹่ง’']={0x007aff, "0|0|0x007aff,6|0|0xbab9b8,14|-3|0x007aff",90,25,270,122,545} t['ๅ‘ๅนฟๅ‘Š-้‚ฎไปถ-ไธไฟๅญ˜']={0x1176bc, "0|0|0x1176bc,-37|7|0x00c0fd,-213|2|0xdf3d34",90,413,445,925,547} t['ๅ‘ๅนฟๅ‘Š-้‚ฎไปถๅ‘้€']={0x00b9f7, "0|0|0x00b9f7,13|-10|0x008ac3",90,900,23,1098,154} choice = 1 --1,ไธบ่”็›Ÿ,2ไธบไธชไบบๆˆ˜ๅŠ› top_key = 20 function ๅ‘้‚ฎไปถ_่”็›Ÿ() click(40,40) d( "ๅ‘ๅนฟๅ‘Š-ๆ‰งๆ”ฟๅฎ˜่ต„ๆ–™-ไธ€ๆŽ’",true,2 ) d( "ๅ‘ๅนฟๅ‘Š-ๆ‰งๆ”ฟๅฎ˜่ต„ๆ–™-ๆŽ’่กŒๆฆœ") d( "ๅ‘ๅนฟๅ‘Š-ๆŽ’่กŒๆฆœ-่”็›Ÿ-ๆˆ˜ๅŠ›",true,choice,2 ) local i = 0 while i < 10 and d("ๅ‘ๅนฟๅ‘Š-ๆŽ’่กŒๆฆœ")do if d("ๅ‘ๅนฟๅ‘Š-ๆŽ’่กŒๆฆœ-123") then top_now = 1 elseif d("ๅ‘ๅนฟๅ‘Š-ๆŽ’่กŒๆฆœ-ๅฎšไฝ") then local x1,y1,x2,y2 = x+15,y+18,x+55,y+58 top_now = ocrText(x1,y1,x2,y2, 0) or 0 top_now = tonumber(top_now) end log({x,y,['top_now'] = top_now }) if top_now > 0 and top_key - top_now < 6 then --็‚นๅ‡ป่ฎก็ฎ—ๅ‡บๆฅ็š„ๆญฃ็กฎไฝ็ฝฎ click( x,y+20+ (top_key-top_now) *84,3 ) break else moveTo(400,500,400,300,1) delay(3) end i = i + 1 end if d("ๅ‘ๅนฟๅ‘Š-ๆŽ’่กŒๆฆœ-ไธชไบบ้‚ฎไปถ",true,1,3) or d("ๅ‘ๅนฟๅ‘Š-ๆŽ’่กŒๆฆœ-็›Ÿไธป้‚ฎไปถ",true,1,3) then d("ๅ‘ๅนฟๅ‘Š-้‚ฎไปถ-ไธไฟๅญ˜",true,1,2) click(468,153,2) input(__UI.้‚ฎไปถๅนฟๅ‘Š[1]) click(368,223,2) input(__UI.้‚ฎไปถๅนฟๅ‘Š[2]) d("ๅ‘ๅนฟๅ‘Š-้‚ฎไปถๅฎŒๆˆ-ๅทฆไธ‹่ง’",true,1,2) if d("ๅ‘ๅนฟๅ‘Š-้‚ฎไปถๅ‘้€",true,1,2) then ๅ‘ๅนฟๅ‘Šๆฌกๆ•ฐ = ๅ‘ๅนฟๅ‘Šๆฌกๆ•ฐ + 1 top_key = top_key + 1 if top_key >= top_key_max then top_key = 1 end writeFile( {json.encode({['top_key'] = top_key,['top_key_max'] = top_key_max})} ,'w',"/User/Media/TouchSprite/lua/" ..__game.token..".txt") return true end end end <file_sep>-- ไธ‡ๅ›ฝ่ง‰้†’ -- ui.lua -- Create By TouchSpriteStudio on 20:40:56 -- Copyright ยฉ TouchSpriteStudio . All rights reserved. require('tsp') local sz = require("sz") local json = sz.json local w,h = getScreenSize(); MyTable = { ["style"] = "default", ["rettype"] = "table", ["width"] = w, ["height"] = h, ["config"] = "wgjx.dat", ["timer"] = 60, views = { {["type"] = "Label", ["text"] = "ไธ‡ๅ›ฝ่ง‰้†’ๆŒ‚ๆœบ่„šๆœฌ",["size"] = 25,["align"] = "center",["color"] = "0,100,100", }, {["type"] = "Label", ["text"] = "ๅŠŸ่ƒฝ่ฎพ็ฝฎ",["size"] = 14,["align"] = "left",["color"] = "0,0,0", }, {["type"] = "Label", ["text"] = "ๅ›ฝๅฎถ้€‰ๆ‹ฉ",["size"] = 14,["align"] = "left", ['width'] = '150', ['nowrap'] = '1', ["color"] = "0,0,0", }, {["type"] = "ComboBox",["list"] = "1็ฝ—้ฉฌ,2ๅพทๅ›ฝ,3ไธๅˆ—็›ด,4ๆณ•ๅ…ฐ่ฅฟ,5่ฅฟ็ญ็‰™,6ไธญๅ›ฝ,7ๆ—ฅๆœฌ,8้Ÿฉๅ›ฝ,9้˜ฟๆ‹‰ไผฏ,10ๅฅฅๆ–ฏๆ›ผ,11ๆ‹œๅ ๅบญ",["select"] = "5", ['id'] = 'ๅ›ฝๅฎถ', ['width'] = '200' }, {["type"] = "Label", ["text"] = "ๅปบ็ญ‘ๅ‡็บง",["size"] = 14,["align"] = "left", ['width'] = '150', ['nowrap'] = '1', ["color"] = "0,0,0", }, {["type"] = "Switch",["size"] = "s",["align"] = "left",["state"] = "on", ['id'] = 'ๅ‡็บง', }, {["type"] = "Label", ["text"] = "ๅฅ–ๅŠฑ",["size"] = 14,["align"] = "left", ['width'] = '150', ['nowrap'] = '1', ["color"] = "0,0,0", }, {["type"] = "Switch",["size"] = "s",["align"] = "left",["state"] = "on", ['id'] = 'ๅฅ–ๅŠฑ', }, {["type"] = "Label", ["text"] = "้€ ๅ…ตkey",["size"] = 14,["align"] = "left", ['width'] = '150', ['nowrap'] = '1', ["color"] = "0,0,0", }, {["type"] = "Switch",["size"] = "s",["align"] = "left",["state"] = "on", ['id'] = '้€ ๅ…ตkey', }, {["type"] = "Label", ["text"] = "ๆญฅๅ…ต",["size"] = 14,["align"] = "center", ['width'] = '220', ['nowrap'] = '1', ["color"] = "0,0,0", }, {["type"] = "Switch",["size"] = "s",["align"] = "left",["state"] = "on", ['id'] = 'ๆญฅๅ…ต', }, {["type"] = "Label", ["text"] = "้ช‘ๅ…ต",["size"] = 14,["align"] = "center", ['width'] = '220', ['nowrap'] = '1', ["color"] = "0,0,0", }, {["type"] = "Switch",["size"] = "s",["align"] = "left",["state"] = "on", ['id'] = '้ช‘ๅ…ต', }, {["type"] = "Label", ["text"] = "ๅผ“ๅ…ต",["size"] = 14,["align"] = "center", ['width'] = '220', ['nowrap'] = '1', ["color"] = "0,0,0", }, {["type"] = "Switch",["size"] = "s",["align"] = "left",["state"] = "on", ['id'] = 'ๅผ“ๅ…ต', }, {["type"] = "Label", ["text"] = "่ฝฆๅ…ต",["size"] = 14,["align"] = "center", ['width'] = '220', ['nowrap'] = '1', ["color"] = "0,0,0", }, {["type"] = "Switch",["size"] = "s",["align"] = "left",["state"] = "on", ['id'] = '่ฝฆๅ…ต', }, {["type"] = "Label", ["text"] = "ๅปบ้€ ",["size"] = 14,["align"] = "left", ['width'] = '150', ['nowrap'] = '1', ["color"] = "0,0,0", }, {["type"] = "Switch",["size"] = "s",["align"] = "left",["state"] = "on", ['id'] = 'ๅปบ้€ ', }, {["type"] = "Label", ["text"] = "่‹ฑ้›„",["size"] = 14,["align"] = "left", ['width'] = '150', ['nowrap'] = '1', ["color"] = "0,0,0", }, {["type"] = "Switch",["size"] = "s",["align"] = "left",["state"] = "on", ['id'] = '่‹ฑ้›„', }, {["type"] = "Label", ["text"] = "้‡‡้›†key",["size"] = 14,["align"] = "left", ['width'] = '150', ['nowrap'] = '1', ["color"] = "0,0,0", }, {["type"] = "Switch",["size"] = "s",["align"] = "left",["state"] = "on", ['id'] = '้‡‡้›†key', }, {["type"] = "Label", ["text"] = "็ง็ฑป",["size"] = 14,["align"] = "right", ['width'] = '45', ['nowrap'] = '1', ["color"] = "0,0,0", }, {["type"] = "RadioGroup",["list"] = "้‡Ž,็ฒฎ,ๆœจ,็Ÿณ,้‡‘,่ฝฎ",["select"] = "0", ['id'] = '้‡‡้›†็ง็ฑป', }, {["type"] = "Label", ["text"] = "ๆ–ฅๅ€™",["size"] = 14,["align"] = "left", ['width'] = '150', ['nowrap'] = '1', ["color"] = "0,0,0", }, {["type"] = "Switch",["size"] = "s",["align"] = "left",["state"] = "on", ['id'] = 'ๆ–ฅๅ€™', }, {["type"] = "Label", ["text"] = "ไปปๅŠก",["size"] = 14,["align"] = "left", ['width'] = '150', ['nowrap'] = '1', ["color"] = "0,0,0", }, {["type"] = "Switch",["size"] = "s",["align"] = "left",["state"] = "on", ['id'] = 'ไปปๅŠก', }, } } local MyJsonString = json.encode(MyTable); UIret,UIv = showUI(MyJsonString) if UIret == 1 then log(UIv) else lua_exit() end <file_sep>-- nike -- main.lua -- Create By TouchSpriteStudio on 00:05:42 -- Copyright ยฉ TouchSpriteStudio . All rights reserved. <file_sep> -- nike-mac -- main.lua -- Create By TouchSpriteStudio on 23:41:13 -- Copyright ยฉ TouchSpriteStudio . All rights reserved. --unlockDevice() require("TSLib") --require("tsp") --res, code = http.request("http://ip.chinaz.com/getip.aspx"); --็”จhttp.getๅฎž็Žฐไธ‹่ฝฝๆ–‡ไปถๅŠŸ่ƒฝ function downFile(url, path) local sz = require("sz") local http = require("szocket.http") local url = "http://wenfree.cn/api/Public/idfa/?service=Git.Get&url="..url local res, code = http.request(url); -- nLog(res) if code == 200 then local json = sz.json local data = json.decode(res) local body = data.data local file = io.open(path, "wb") if file then file:write(body) file:close() return status; else return -1; end else return status; end end --downFile("http://mu1234.applinzi.com/reply.txt", --"/User/Media/TouchSprite/lua/reply.txt") --ๆฃ€ๆต‹ๆŒ‡ๅฎšๆ–‡ไปถๆ˜ฏๅฆๅญ˜ๅœจ function file_exists(file_name) local f = io.open(file_name, "r") return f ~= nil and f:close() end game_lua = { {"UI",'https://img.wenfree.cn/nike-wenfree/UI.lua'}, {"tsp",'https://img.wenfree.cn/nike-wenfree/tsp.lua'}, {"nameStr",'https://img.wenfree.cn/nike-wenfree/nameStr.lua'}, {"alz",'https://img.wenfree.cn/nike-wenfree/alz.lua'}, {"AWZ",'https://img.wenfree.cn/nike-wenfree/AWZ.lua'}, {"nike",'https://img.wenfree.cn/nike-wenfree/nike.lua'}, {"main",'https://img.wenfree.cn/nike-wenfree/main.lua'}, } local ver_ = 20 local name_ = "nike" local v_url = 'http://wenfree.cn/api/Public/idfa/?service=Git.Update&name='..name_..'&v='..ver_ function get_(url) local sz = require("sz") local http = require("szocket.http") local res, code = http.request(url); -- nLog(res); if code == 200 then local json = sz.json if res ~= nil then return json.decode(res) end end end local version = get_(v_url); if false and version then if version.data then t1=os.time(); nLog(t1) for i,v in ipairs(game_lua)do nLog(v[1]) nLog(v[2]) downFile(v[2],"/User/Media/TouchSprite/lua/"..v[1]..".lua") mSleep(30) toast(v[1],1) end nLog('end->'..os.time()-t1) else nLog('ๆ— ้œ€ๆ›ดๆ–ฐ'); for i,v in ipairs(game_lua)do if not(file_exists("/User/Media/TouchSprite/lua/"..v[1]..".lua"))then nLog('ๆ–‡ไปถไธๅญ˜๏ผŒไธ‹่ฝฝไธ€ไธช->'..v[1]) downFile(v[2],"/User/Media/TouchSprite/lua/"..v[1]..".lua") if v[1] == 'main' then downFile(v[2],"/User/Media/TouchSprite/"..v[1]..".lua") end end end end end require('tsp') require('AWZ') require('other') require('axj') require('UI') --ๅ›žไผ ๆ‰‹ๆœบ function updatePhone() local sz = require("sz") local url = 'http://zzaha.com/phalapi/public/' local Arr={} Arr.s = 'Nikesave.Phone' Arr.imei = sz.system.serialnumber() Arr.name = getDeviceName() Arr.whos = 'whos' return post(url,Arr) end --readUI function readUI() local sz = require("sz") local url = 'http://zzaha.com/phalapi/public/' local Arr={} Arr.s = 'NikeWebuI.readUI' Arr.imei = sz.system.serialnumber() return post(url,Arr) end --readUIAll function readUIall() local sz = require("sz") local url = 'http://zzaha.com/phalapi/public/' local Arr={} Arr.s = 'NikeWebuI.readUIall' return post(url,Arr) end function all() while (true) do --ๆ›ดๆ–ฐๆ‰‹ๆœบ่ฎพ็ฝฎ -- UIvalues if UIvalues.netMode == '0' then setAirplaneMode(true) delay(15) setAirplaneMode(false) setWifiEnable(false) delay(30) end if UIvalues.smsPT == "0" then vCode = _vCode_bm() --็ญ้ฉฌ vCode.login() elseif UIvalues.smsPT == "1" then vCode = _vCode_reyne() --ไฟก้ธฝ vCode.login() end if UIvalues.clearMode == '0' then awzNew() elseif UIvalues.clearMode == '1' then axjNew() elseif UIvalues.clearMode == '2' then sys.clear_bid('com.nike.onenikecommerce') delay(1) end if UIvalues.work == "0" then log('ๅ‡†ๅค‡ๆณจๅ†Œ') --็”จnikeๆณจๅˆ  package.loaded['nikereg'] = nil require('nikereg') main() elseif UIvalues.work == "1" then log('ๆๅ–code') --ๆๅ–nike(code) package.loaded['nikecode'] = nil require('nikecode') main() elseif UIvalues.work == "2" then log('snkrsๅค็™ป') --snkrsๅค็™ป package.loaded['snkrs'] = nil require('snkrs') main() end end end while (true) do local ret,errMessage = pcall(all) if ret then else log(errMessage) dialog(errMessage, 15) mSleep(1000) closeApp(frontAppBid()) mSleep(2000) end end <file_sep>local ts = require("ts") serialnumber = ts.system.serialnumber()--่Žทๅ–่ฎพๅค‡็š„ๅบๅˆ—ๅท๏ผŒๅฎ‰ๅ“ไธๅŒ็š„ๆ‰‹ๆœบๅฏ่ƒฝ่ฟ”ๅ›ž็ฉบๅ€ผ mSleep(1000*4) toast(serialnumber, 2) mSleep(1000*2) toast("end", 2) mSleep(1000*2)<file_sep> require("tsp") w.log("ๆขฆๅนปไบ’้€š็‰ˆ-ๅฏๅŠจ") init(1) page = {} page['ไธป็•Œ้ข'] = {{1205, 1, 0x4f859f},{110, 31, 0xb0b8d0},{220, 44, 0xa0acc8}} page['ไธป็•Œ้ข-ๅฑ•็คบไปปๅŠก'] ={{1317, 217, 0x96bfce}} page['ไธป็•Œ้ข-ไปปๅŠก'] = { {{1282, 261, 0xf70301},{1291, 261, 0xf70301}}, 70, 1106,230,1330,505 } page['ไธป็•Œ้ข-ไปปๅŠก-ๆˆ˜ๆ–—'] = {{{1283, 235, 0xebeae6},{1279, 231, 0xb81c10},{1282, 231, 0xf3f0ec}},90,1254,222,1332,250} page['ไธป็•Œ้ข-ไฝฟ็”จ'] = { {{655, 467, 0xffffff},{665, 460, 0x701428},{674, 461, 0xffffff}}, 90,617,444,708,485} page['ๅผน็ช—-ๅฏน่ฏๆก†'] = {{1300, 555, 0xa0c0c8},{1309, 563, 0x93b9c3},{1293, 562, 0x98bcc8}} page['ๅผน็ช—-ๅฏน่ฏๆก†-ๅฏน่ฏ'] = { {{1106, 456, 0xffffff},{1104, 430, 0x385868},{1106, 480, 0x305060}},90,989,292,1204,568 } page['ๅผน็ช—-...']= {{{1242, 452, 0xf5f9f5},{1232, 451, 0xf8fcf8},{1253, 451, 0xf8fcf8},{1243, 445, 0x405860}}, 90,1209,341,1276,531} function d(name,clickKey,n ) if w.fmc( page[name][1],page[name][2],page[name][3],page[name][4],page[name][5],page[name][6] ) then w.log( "ๆ‰พๅˆฐ->" .. name ) if clickKey then w.click( page[name][1][n][1],page[name][1][n][2] ) end end end function main() if w.mc(page['ไธป็•Œ้ข']) then w.log("ไธป็•Œ้ข") if d('ไธป็•Œ้ข-ไฝฟ็”จ' ,true,1)then elseif d( 'ไธป็•Œ้ข-ไปปๅŠก' ,true,1 ) or d( 'ไธป็•Œ้ข-ไปปๅŠก-ๆˆ˜ๆ–—' ,true,1 ) then else w.mc( page['ไธป็•Œ้ข-ๅฑ•็คบไปปๅŠก'],true,1) end else if w.mc( page['ๅผน็ช—-ๅฏน่ฏๆก†'] ) then if d("ๅผน็ช—-ๅฏน่ฏๆก†-ๅฏน่ฏ",true,1) then else w.mc( page['ๅผน็ช—-ๅฏน่ฏๆก†'] ) w.click(x,y) end else w.click(40,40) end end w.delay(1) end while (true) do main() end <file_sep> -- othet.lua -- Create By TouchSpriteStudio on 02:35:44 -- Copyright ยฉ TouchSpriteStudio . All rights reserved. sys = { clear_bid = (function(bid) closeApp(bid) delay(1) os.execute("rm -rf "..(appDataPath(bid)).."/Documents/*") --Documents os.execute("rm -rf "..(appDataPath(bid)).."/Library/*") --Library os.execute("rm -rf "..(appDataPath(bid)).."/tmp/*") --tmp clearPasteboard() --[[ local path = _G.const.cur_resDir os.execute( table.concat( { string.format("mkdir -p %s/keychain", path), 'killall -SIGSTOP SpringBoard', "cp -f -r /private/var/Keychains/keychain-2.db " .. path .. "/keychain/keychain-2.db", "cp -f -r /private/var/Keychains/keychain-2.db-shm " .. path .. "/keychain/keychain-2.db-shm", "cp -f -r /private/var/Keychains/keychain-2.db-wal " .. path .. "/keychain/keychain-2.db-wal", 'killall -SIGCONT SpringBoard', }, '\n' ) ) ]] clearAllKeyChains() clearIDFAV() --clearCookies() end) } --getๅ‡ฝๆ•ฐ function get_lx(url) local sz = require("sz") local http = require("szocket.http") local res, code = http.request(url); if code == 200 then return res end end function checkPhone(phone) local url____ = 'http://zzaha.com/phalapi/public/?s=App.Nikecheck.Checkphone&phone='..phone log(url____) local self_phone = get(url____) log(self_phone) log(self_phone.data) return self_phone.data end function _vCode_bm() --ๆ–‘้ฉฌๅนณๅฐ local User = 'api-43502-rO6j2eO' local Pass = '<PASSWORD>' local PID = '175' local token,number = "<KEY>","" return { login=(function() local RetStr for i=1,5,1 do toast("่Žทๅ–token\n"..i.."ๆฌกๅ…ฑ5ๆฌก") mSleep(1500) local lx_url = 'http://api.banma1024.net/api/do.php?action=loginIn&name='..User..'&password='..<PASSWORD> log(lx_url) RetStr = get_lx(lx_url) if RetStr then RetStr = strSplit(RetStr,"|") if RetStr[1] == 1 or RetStr[1] == '1' then token = RetStr[2] log('token='..token,true) return 'token='..token end else log(RetStr) end end return RetStr; end), getPhone=(function() local RetStr="" local url___ = "http://api.banma1024.net/api/do.php?action=getPhone&sid="..PID.."&token="..token log(url___) RetStr = get_lx(url___) if RetStr ~= "" and RetStr ~= nil then log(RetStr) RetStr = strSplit(RetStr,"|") end if RetStr[1] == 1 or RetStr[1]== '1' then number = RetStr[2] log(number) local phone_title = (string.sub(number,1,3)) local blackPhone = {'165','144','141','142','143','144','145','146','147'} for k,v in ipairs(blackPhone) do if phone_title == v then local lx_url = 'http://api.banma1024.net/api/do.php?action=addBlacklist&sid='..PID..'&phone='..number..'&token='..token get_lx(lx_url); log("ๆ‹‰้ป‘->"..number) return false end end return number end end), getMessage=(function() local Msg for i=1,25,1 do mSleep(3000) RetStr = get_lx("http://api.banma1024.net/api/do.php?action=getMessage&sid="..PID.."&token="..token.."&phone="..number) log(RetStr); if RetStr then local arr = strSplit(RetStr,"|") if arr[1] == '1' then Msg = arr[2] local i,j = string.find(Msg,"%d+") Msg = string.sub(Msg,i,j) end if type(tonumber(Msg))== "number" then log(Msg); return Msg end end toast(tostring(RetStr).."\n"..i.."ๆฌกๅ…ฑ25ๆฌก") end return false end), addBlack=(function() local lx_url = 'http://api.banma1024.net/api/do.php?action=addBlacklist&sid='..PID..'&phone='..number..'&token='..token log("ๆ‹‰้ป‘"..number..'\n'..lx_url); return get_lx(lx_url); end), } end function _vCode_reyne() --reyne local User = 'shuaishuaiPYh' local Pass = '<PASSWORD>' local PID = '29456' local apiurl = 'http://api.reyne.cn/api/do.php' local token,number = "","" return { login=(function() local RetStr for i=1,5,1 do toast("่Žทๅ–token\n"..i.."ๆฌกๅ…ฑ5ๆฌก") mSleep(1500) local lx_url = apiurl..'?action=loginIn&name='..User..'&password='..Pass log(lx_url) RetStr = get_lx(lx_url) if RetStr then RetStr = strSplit(RetStr,"|") if RetStr[1] == 1 or RetStr[1] == '1' then token = RetStr[2] log('token='..token,true) return 'token='..token end else log(RetStr) end end return RetStr; end), getPhone=(function() local RetStr="" local url___ = apiurl .. "?action=getPhone&sid="..PID.."&token="..token log(url___) RetStr = get_lx(url___) if RetStr ~= "" and RetStr ~= nil then log(RetStr) RetStr = strSplit(RetStr,"|") end if RetStr[1] == 1 or RetStr[1]== '1' then number = RetStr[2] log(number) local phone_title = (string.sub(number,1,3)) local blackPhone = {'165','144','141','142','143','144','145','146','147'} for k,v in ipairs(blackPhone) do if phone_title == v then local lx_url = apiurl .. '?action=addBlacklist&sid='..PID..'&phone='..number..'&token='..token get_lx(lx_url); log("ๆ‹‰้ป‘->"..number) return false end end return number end end), getMessage=(function() local Msg for i=1,25,1 do mSleep(3000) RetStr = get_lx( apiurl .."?action=getMessage&sid="..PID.."&token="..token.."&phone="..number) log(RetStr); if RetStr then local arr = strSplit(RetStr,"|") if arr[1] == '1' then Msg = arr[2] local i,j = string.find(Msg,"%d+") Msg = string.sub(Msg,i,j) end if type(tonumber(Msg))== "number" then log(Msg); return Msg end end toast(tostring(RetStr).."\n"..i.."ๆฌกๅ…ฑ25ๆฌก") end return false end), addBlack=(function() local lx_url = apiurl .. '?action=addBlacklist&sid='..PID..'&phone='..number..'&token='..token log("ๆ‹‰้ป‘"..number..'\n'..lx_url); return get_lx(lx_url); end), } end function mail_rand(length) --้šๆœบ้‚ฎ็ฎฑ local char ='0123456789abcdefghijklmnopqrstuvwxyz' if length < 0 then return false; end local string = ''; local rnd local s local mailheader={} mailheader[0] = '@shuaisports.com' mailheader[1] = '@ssnms.com' mailheader[2] = '@zzaha.com' mailheader[3] = '@vvccb.com' local mail_suffix = mailheader[math.random(#mailheader)] for var = 1,length do rnd = math.random(1,string.len(char)) s = string.sub(char,rnd,rnd+1) string = string..s end return string..os.date("%S")..myRand(4,1,2)..mail_suffix; end function click_random(x,y,n) if n > 1 then for i=1,n do click(x,y,0.8) end else click(x,y,0.8) end end first_names = "่ตต้’ฑๅญ™ๆŽๅ‘จๅด้ƒ‘็Ž‹ๅ†ฏ้™ˆ่คšๅซ่’‹ๆฒˆ้Ÿฉๆจๆœฑ็งฆๅฐค่ฎธ".. "ไฝ•ๅ•ๆ–ฝๅผ ๅญ”ๆ›นไธฅๅŽ้‡‘้ญ้™ถๅงœๆˆš่ฐข้‚นๅ–ปๆŸๆฐด็ชฆ็ซ ".. "ไบ‘่‹ๆฝ˜่‘›ๅฅš่Œƒๅฝญ้ƒŽ้ฒ้Ÿฆๆ˜Œ้ฉฌ่‹—ๅ‡ค่Šฑๆ–นไฟžไปป่ขๆŸณ".. "้…†้ฒๅฒๅ”่ดนๅป‰ๅฒ‘่–›้›ท่ดบๅ€ชๆฑคๆป•ๆฎท็ฝ—ๆฏ•้ƒ้‚ฌๅฎ‰ๅธธ".. "ไนไบŽๆ—ถๅ‚…็šฎๅž้ฝๅบทไผไฝ™ๅ…ƒๅœ้กพๅญŸๅนณ้ป„ๅ’Œ็ฉ†่งๅฐน".. "ๅงš้‚ตๆน›ๆฑช็ฅๆฏ›็ฆน็‹„็ฑณ่ดๆ˜Ž่‡ง่ฎกไผๆˆๆˆด่ฐˆๅฎ‹่Œ…ๅบž".. "็†Š็บช่ˆ’ๅฑˆ้กน็ฅ่‘ฃ็ฒฑๆœ้˜ฎ่“้—ตๅธญๅญฃ้บปๅผบ่ดพ่ทฏๅจ„ๅฑ".. "ๆฑŸ็ซฅ้ขœ้ƒญๆข…็››ๆž—ๅˆ้’Ÿๅพ้‚ฑ้ช†้ซ˜ๅค่”ก็”ฐๆจŠ่ƒกๅ‡Œ้œ".. "่™žไธ‡ๆ”ฏๆŸฏๆ˜็ฎกๅข่Žซ็ปๆˆฟ่ฃ˜็ผชๅนฒ่งฃๅบ”ๅฎ—ไธๅฎฃ่ดฒ้‚“".. "้ƒๅ•ๆญๆดชๅŒ…่ฏธๅทฆ็Ÿณๅด”ๅ‰้’ฎ้พš็จ‹ๅต‡้‚ขๆป‘่ฃด้™†่ฃ็ฟ".. "่€็พŠๆ–ผๆƒ ็”„้บดๅฎถๅฐ่Šฎ็พฟๅ‚จ้ณๆฑฒ้‚ด็ณœๆพไบ•ๆฎตๅฏŒๅทซ".. "ไนŒ็„ฆๅทดๅผ“็‰งๅฑฑ่ฐท่ฝฆไพฏ่“ฌๅ…จ้ƒ—็ญไปฐ็ง‹ไปฒไผŠๅฎซ".. "ๅฎไป‡ๆšด็”˜ๅމๆˆŽ็ฅ–ๆญฆ็ฌฆๅˆ˜ๆ™ฏ่ฉนๆŸ้พ™ๅถๅนธๅธ้Ÿถ".. "้ƒœ้ปŽ่“Ÿ่–„ๅฐๅฎฟ็™ฝๆ€€่’ฒ้‚ฐไปŽ้„‚็ดขๅ’ธ็ฑ่ต–ๅ“่”บๅฑ ่’™".. "ๆฑ ไน”้˜ด่ƒฅ่ƒฝ่‹ๅŒ้—ป่Ž˜ๅ…š็ฟŸ่ฐญ่ดกๅŠณ้€„ๅงฌ็”ณๆ‰ถๅ ต".. "ๅ†‰ๅฎฐ้ƒฆ้›็’ฉๆก‘ๆก‚ๆฟฎ็‰›ๅฏฟ้€š่พนๆ‰ˆ็‡•ๅ†€้ƒๆตฆๅฐšๅ†œ".. "ๆธฉๅˆซๅบ„ๆ™ๆŸด็žฟ้˜Žๅ……ๆ…•่ฟž่Œนไน ๅฎฆ่‰พ้ฑผๅฎนๅ‘ๅคๆ˜“ๆ…Ž".. "ๆˆˆๅป–ๅบพ็ปˆๆšจๅฑ…่กกๆญฅ้ƒฝ่€ฟๆปกๅผ˜ๅŒกๅ›ฝๆ–‡ๅฏ‡ๅนฟ็ฆ„้˜™ไธœ".. "ๆฎดๆฎณๆฒƒๅˆฉ่”š่ถŠ้š†ๅธˆๅทฉๅŽ่‚ๆ™ๅ‹พๆ•–่žๅ†ท่จพ่พ›้˜š".. "้‚ฃ็ฎ€้ฅถ็ฉบๆ›พๆฏ‹ๆฒ™ๅ…ป้ž ้กปไธฐๅทขๅ…ณ่’ฏ็›ธๆŸฅๅพŒ่†็บข" last_names = "ๅฎ‰ๅฝคๅซ็ฅ–่ตฉๆถคๅฝฐ็ˆต่ˆžๆทฑ็พค้€‚ๆธบ่พž่Žžๅปถ็จทๆกฆ่ตๅธ…้€‚ไบญๆฟฎๅญ˜ๅŸŽ็จทๆพ„ๆทปๆ‚Ÿ็ปข็ปขๆพน่ฟชๅฉ•็ฎซ่ฏ†ๆ‚Ÿ่ˆžๆทปๅ‰‘ๆทฑ็ฆ„ๅปถๆถค" .. "ๆฟฎๅญ˜็ฝก็ฆ„็‘›็‘›ๅ—ฃๅซšๆœตๅฏ…ๆทปๆธŸ้ปŽ่‡ป่ˆž็ปขๅŸŽ้ชฅๅฝฐๆธบ็ฆพๆ•™็ฅ–ๅ‰‘้ปŽ่Žžๅ’ธๆต“่Šฆๆพนๅธ…่‡ปๆธŸๆทป็ฆพไบญๆทปไบญ้œ–ๆทฑ็ญ–่‡ป็จท่พž" .. "ๆ‚Ÿๆ‚Ÿๆพ„ๆถ‰ๅŸŽ้ธฅ้ปŽๆ‚Ÿไน”ๆ’้ปŽ้ฒฒๆถ‰่Žž้œ–็”ฒๆทฑๅฉ•ไน”็จ‹ๆพน็”ทๅฒณๆทฑๆถ‰็›Šๆพนๆ‚Ÿ็ฎซไน”ๅคš่Œ้€‚่Šฆ็‘›ๆพ„ๅฉ•ๆœต้€‚็ฅ–้œ–็‘›ๅคๅซš" .. "ๆถ‰็”ท็‚็ฎซ่Šฆ้ปŽ็น็ปข่Šฆ็จ‹่ฏ†ๅ—ฃ็‚็‘ฐๆžๅ…้ปŽๅบธๅ—ฃ่ต็ฝก็บตๆทป็ฆ„้œ–็”ทๅปถ็”ฒๅฝฐๅ’ธ็จท็ฎซๅฒณๆ‚Ÿ่Œ็ฅ–ๆ’็‚ๅบธ็…็”ท่Žžๅบธๆต“" .. "ๅคš็ฝกๅปถ็‘›ๆฟฎๅญ˜็ˆตๆทปๅ‰‘็›Š้ชฅๆพ„ๅปถ่ฟชๅฏ…ๅฉ•็จ‹้œ–่ฏ†็‘ฐ่ฏ†็จ‹็พคๆ•™ๆœตๆ‚Ÿ่ˆžๅฒณๆต“็ฎซๅŸŽ้€‚็จ‹็ฆพๅซš็ฝกๅ’ธ่Œ้“ƒ็ˆตๆธบๆทป่พžๅซš" .. "ๆต“ๅฏ…้ฒฒๅ—ฃ็‘›้ธฅๅคšๆ•™็‘›่ฟชๅค้“ƒ็น็พค้ปŽ็›Šๆพ„็จ‹่Žžๆทฑๅคๆพน็ฆ„่Œๆพน่ตฉๆพ„่—‰็พค็ฎซ้ชฅๅฎšๅฝฐๅฏ…่‡ปๆธŸๆžๅ…็นๆทฑ็พค้ปŽ็”ฒ้ฒฒ" .. "ไบญ้ปŽ่—ๆต“ๆถคๆธŸ่Žžๅฏ…่พžๅ—ฃๅค่ฟชๅซšๆทป็ญ–ๅบธ็ญ–่—‰็‘ฐๅฝฐ็ฎซ็›Š่Žžๆธบไน”ๅฝฐๅปถ่ˆž็ฅ–ๅฉ•ๆพนๆธบ้ธฅ็บตๅ—ฃ็‘›่—ๆฟฎๅญ˜ๅฉ•่Œ็จ‹่Šฆ็พค" .. "็ฆพๅซš็จ‹่พž็ฅ–้ปŽ่Œๆต“ๆกฆ่—ๆธŸ็ฆพๅฝฐๅธ…่พž้“ƒ้“ƒ้ปŽๅ…็ปขๆฟฎๅญ˜ๅ‰‘่พž็ฆพ็‘ฐๆทปๅปถๆทปๆ‚Ÿ่ต็ฅ–ๅ’ธ่Žž็”ท็ปข็ญ–ๅฉ•่—‰็ฆพๆต“็นๆถค็ฅ–" .. "ๆฑ‰้ชฅ่ˆž็‘›ๅคš็จท่ต่ŽžๆธŸ้ปŽ่ˆžๆกฆ้ปŽ็พค่—ๆธบ้ปŽๅคๆกฆๅ’ธ่ฟชๆพˆ่ˆžๅ…็จทๅ’ธๅ‰‘ๅฎšไบญๆพ„ๆฟฎๅญ˜้ฒฒ่‡ปๅ…จ้ธฅๅคš่ต็จ‹ๆทป็‘›ไบญๅธ…ๆ‚Ÿ" .. "็”ฒ็”ทๅธ…ๆถค้€‚็บตๆธŸ้ฒฒไบญๆ‚Ÿ็…ไบญๆทปๅ…่ˆž็ฆพๅบธๅ’ธ็‘›ๆ•™้ฒฒๅ…็ฎซ่Šฆๅ…็‘›ๅ’ธ้ธฅๅธ…ๆ‚Ÿๅปถ็‚้ปŽ็น็ฎซ็ˆตๅ‰‘้œ–ๅ‰‘้œ–็ฆ„้ธฅๆ‚Ÿๆถ‰" .. "ๅฝฐ็พคๆ‚Ÿ่พžๅธ…ๆธบ่Žžๆพ„ๆกฆ็‘›้€‚่‡ป็›Š้œ–็นไบญๆพน่พžๅค็จ‹ๅ—ฃ้“ƒ็ฎซ็ญ–ๆพˆๆž่ต่Žž็ˆตๆธŸ็ฆ„็พคๆžๆทป่Šฆ็พคๆต“่ต่Œ็›ŠๅŸŽๆพ„่ตฉ็…" .. "ๅปถ็พคไน”็น้ฒฒ็ฅ–็พคๆ‚Ÿ้ปŽๅฎšๅบธๆพ„่Šฆๅปถ้œ–็ฝก้ฒฒๅ’ธๆธบ็บตไบญ็ฆ„้ธฅ่ตฉๆถคๅ‰‘ๆพน่—็บตๆฟฎๅญ˜ๆพ„่Šฆๅ‰‘ๅปถ็‘ฐ็จท้ปŽ็›Š่ตฉๆพ„ๅ…ๆ‚Ÿๆพˆ" .. "็”ฒๅ—ฃ็ปขๆœต็›Š็”ฒๆ‚Ÿๆถคๅฉ•็พคๅ’ธ่‡ป็ฎซ้ฒฒๅฏ…้ธฅๆกฆ็›Š็‚่ˆžๅ…ๅบธ่Šฆ่—‰ๅฏ…ๆธบๅ’ธ่ตๆพ„็จ‹ๅ‰‘็‘ฐ้œ–็‘ฐ้“ƒๅธ…็”ท้“ƒๆ‚Ÿ่ฏ†็‘ฐไป•ไป•ๅŸŽ" .. "ๅ…่Žžๅ…จๆœตๆถค้“ƒๅ‰‘ๆธบ็จทๅ‰‘็‚้“ƒ็ฎซๅ…จไป•็›Š็บต่Šฆๆกฆ็‚ๆฟฎๅญ˜ๅŸŽๆœตๆœตๅ’ธ็จ‹ๅ‰‘ๆพ„ๅฎšๆพˆ็ˆตๅฏ…ๅบธๅฎš่Žž็‘›ๆ•™ๅฝฐ้ปŽ็ฎซไป•้ปŽๆกฆ" .. "่ตฉๆทฑ่ตฉ็ˆต่ฟชๆ‚Ÿ็นๆถค็…ๆทป็ฎซๆกฆๅธ…็‘›้ปŽ้ปŽ็ญ–่ฏ†ๅฏ…ๅซšๆถ‰่ฟช็ญ–ๆฑ‰่ˆžๅฎšๅฝฐๅ…็”ท็ฅ–ๆ•™ๆพ„็พค็‘›ๆฟฎๅญ˜็”ท็ฆพๆ•™่Žž็ฆพ้ธฅๆพˆๆฟฎ" .. "ๅญ˜ๅฒณๅŸŽๅซšๆทฑ่ˆžๆ•™ๅฒณๆพ„ไบญ็ฆพๅคๆœตไบญ่Œ่Žž็จทๅฏ…็‘ฐๅŸŽๅบธไบญ่ˆž็ฆพ็‘›ๆ’ๅคๆต“ๅฝฐ่Žžๆพ„ๆพˆ้ธฅ่‡ป็จทๆ•™็…่พž็›Šๅ‰‘่—‰้ปŽๆทป็‘›" .. "ๅปถ่ˆžๅคไป•ๅฒณๅคšๅฉ•้ชฅ่ฟชๅธ…้ปŽๆ‚Ÿๅ…จๆพ„่ฏ†็›Š็”ฒๆกฆ็บต้€‚็ฝกๅฝฐๆพ„็ฆพๅฉ•็จ‹้ปŽๅŸŽๆถคๆต“ๆž็ฎซๅ’ธๆธŸๅฒณๆธŸๆพน่‡ป็น่ฏ†็นๆพ„็ฎซ่พž" .. "ๆต“้ฒฒ่ฏ†ๆ‚Ÿๅ…ๆ‚Ÿ็ฆพ่ฏ†็พค็ฅ–่ฟชๆธŸ้ฒฒ็พคๅบธ่Žž็นๆ‚Ÿๆพน็‘ฐๆ‚Ÿ้ธฅๆฑ‰็พค็”ฒ่Žžๅบธ่Œ็…่Žžๆกฆ้ฒฒๆœตๆทฑไน”่พžๅ…ๅฝฐๆธบๆœต็‘ฐไบญ็‘ฐๆœต" .. "ๅฎšๆทฑ็”ท่ฏ†็พค่Œ้œ–็›Š็”ท่ˆžๅŸŽๅ…่ˆž็ˆต่ตฉๆž็ฝก็ฝก็พคๆพน่Šฆ่—‰็ˆตๆ‚ŸๆธŸๆพน็ฆพๅคšๅบธ็ฎซๅคไน”่Šฆ็”ฒๆฟฎๅญ˜ๅคšๆธŸ่—‰็น่ตๆฑ‰็บตไบญ" .. "็ฆพๅŸŽๆžๅ‰‘้œฒไปฅ็މๆ˜ฅ้ฃžๆ…งๅจœๆ‚ ไบฆๅ…ƒๆ™”ๆ›œ้œœๅฎๆกƒๅฝฆไปช้›จ็ด้’็ญ ้€ธๆ›ผไปฃ่€ๅญคๆ˜†็ง‹่•Š่ฏญ่Žบไธ็บข็พฒ็››้™ๅ—ๆท‘้œ‡ๆ™ด" .. "ๅฝญ็ฅฏๅฑฑ้œžๅ‡ๆŸ”้šฝๆพ็ฟ ้ซ˜้ชŠ้›…ๅฟต็š“ๅŒๆด›็ดซ็‘ž่‹ฑๆ€ๆญ†่“‰ๅจŸๆณข่Šธ่ท็ฌ‘ไบ‘่‹ฅๅฎๅคๅฆๅ˜‰ๅฝฉๅฆ‚้นๅฏ„่ŠๆŸณๅ‡Œ่Žน่ถ่ˆ’ๆฌ" .. "่™นๆธ…็ˆฝๆœˆๅทงไนพๅ‹‹็ฟฐ่Šณ็ฝ—ๅˆš้ธฟ่ฟๆžซ้˜ณ่‘ณๆฐๆ€€ๆ‚ฆๅ‡กๅ“ฒ็‘ถๅ‡ฏ็„ถๅฐšไธนๅฅ‡ๅผ˜้กบไพ้›ช่กๅ›็•…็™ฝๆŒฏ้ฆจๅฏปๆถต้—ฎๆด่พ‰ๅฟ†ๅ‚ฒ" .. "ไผŸ็ปๆถฆๅฟ—ๅŽๅ…ฐ่Šนไฟฎๆ™จๆœจๅฎ›ไฟŠๅš้Ÿถๅคฉ้”ๆบช็‡•ๅฎถๆฒˆๆ”พๆ˜Žๅ…‰ๅƒๆฐธๆบถๆ˜Šๆข…ๅท็œŸๅฐ”้ฆฅ่Žฒๆ€œๆƒœไฝณๅนฟ้ฆ™ๅฎ‡ๆง็บ่Šทๅธ†็ง€" .. "็†ๆŸไนฆๆฒ›็ชไป™ไน‹็ซนๅ‘ๅ‰ๆฌฃๆ—ปๆ™“ๅ†ฌๅนปๅ’Œ้›ๆทณๆตฉๆญŒ่ฃๆ‡ฟๆ–‡ๅนผๅฒšๆ˜•็‰ง็ปฟ่ฝฉๅทฅๆ—ญ้ขœ้†‰็Ž‘ๅ“่ง…ๅถๅคœ็ต่ƒœๆ™—ๆจๆตไฝ" .. "ไน็ซ้Ÿณ้‡‡็ฟ็ฟŽ่ฑๆฐ‘็”ปๆขฆๅฏ’ๆณฝๆ€กไธฝๅฟƒ็Ÿณ้‚ต็Žฎไฝ‘ๆ—บๅฃฎๅไธ€ๅญฆ่ฐท้Ÿตๅฎœๅ†ฐ่ตซๆ–ฐ่•พ็พŽๆ™–้กน็ณๅนณๆ ‘ๅˆ็‚ณ้ชๆฐ”ๆตทๆฏ…ๆ•ฌ" .. "ๆ›ฆๅฉ‰็ˆฐไผฏ็Šๅฝฑ้ฒธๅฎนๆ™ถๅฉทๆž—ๅญๆ˜Œๆขง่Š™ๆพ่ฏ—ๆ˜Ÿๅ†‰ๅˆๆ˜ ๅ–„่ถŠๅŽŸ่Œ‚ๅ›ฝ่…พๅญŸๆฐด็ƒŸๅŠๅณฏ่މ็ปฎๅพทๆ…ˆๆ•ๆ‰ๆˆˆๆข“ๆ™ฏๆ™บ็›ผ้œ" .. "็‡่‹—็†™ๅงไปŽ่ฐŠ้ฃŽๅ‘้’ฐ็Ž›ๅฟๅฉ€่ฒๆ˜ถๅฏ่Œๅฐๅ€ฉๅฆ™ๆถ›ๅง—ๆ–นๅ›พ่ฟŽๆƒ ๆ™คๅฎฃๅบทๅจ…็ŽŸๅฅ•้”ฆๆฟฏ็ฉ†็ฆงไผถไธฐ่‰ฏ็ฅบ็ๆ›ฒๅ–†ๆ‰ฌๆ‹”" .. "้ฉฐ็ปฃ็ƒๅก้•ฟ้›ฏ้ข–่พฐๆ…•ๆ‰ฟ่ฟœๅฝฌๆ–ฏ่–‡ๆˆ่ช็ˆฑๆœ‹่ฆ็”ฐ่‡ดไธ–ๅฎžๆ„ซ่ฟ›็€šๆœๅผบ้“ญ็…ฆๆœ—็ฒพ่‰บ็†นๅปบๅฟปๆ™ๅ†ทไฝฉไธœๅคๅšๆปจ่ฑ" .. "ๅ›ก้“ถๅ’ๆญฃๅ„ฟ็‘œๅฎ่”“็ซฏ่““่Šฌ็ขงไบบๅผ€็ ๆ˜‚็ฌๆด‹็’ ๆก่ˆŸๅงฃ็›ไบฎ็…ŠไฟกไปŠๅนดๅบ„ๆทผๆฒ™้ป›็ƒจๆฅ ๆก‚ๆ–่ƒค้ช„ๅ…ดๅฐ˜ๆฒณๆ™‹ๅฟๆ˜“" .. "ๆ„‰่•ด้›„่ฎฟๆน›่“ๅช›้ชžๅจดๅ„’ๅฆฎๆ—‹ๅ‹ๅจ‡ๆณฐๅŸบ็คผ่Šฎ็พฝๅฆžๆ„็ฟ”ๅฒ‘่‹‘ๆš–็Žฅๅฐง็’‡้˜”็‡Žๅฒ้–่กŒ็‘พ่ต„ๆผชๆ™Ÿๅ† ๅŒ้ฝๅคๅ‰่ฑ†ๅ”ฑ" .. "้Ÿซ็ด ็›ˆๅฏ†ๅฏŒๅ…ถ็ฟฎ็† ็ปๆพŽๆทก้Ÿฆ่ฏšๆปข็Ÿฅ้น่‹’ๆŠ’่‰ณไน‰ๅฉง้—ณ็ฆๅฃคๆจ่Šƒๆดฒ้˜ต็’Ÿ่Œต้ฉนๆถ†ๆฅๆทๅซ’ๅœฃๅŸๆบ็’ž่ฅฟๆ—Žไฟจ้ข‚็ฟ" .. "ๆƒ…็Ž„ๅˆฉ็—ด่•™ๅŠ›ๆฝๅฌ็ฃŠๅฎธ็ฌ›ไธญๅฅฝไปป่ฝถ็Žฒ่žบ้ƒ็•ดไผšๆš„ๅณป็•ฅ็ผ็ฐ้ป˜ๆฑ ๆธฉ็‚ซๅญฃ้›ฐๅธๆ‰่ง‰็ปด้ฅฎๆน‰่ฎธๅฎต่Œ‰่ดคๆ˜ฑ่•ค็‘" .. "้”‹็บฌๆธŠ่ถ…่ๅซ”ๅคง้œๆฅš้€š้‚ˆ้ฃ™้œ“่ฐงไปคๅŽšๆœฌ้‚ƒๅˆๅฎพๆฒ‰ๆ˜ญๅณฐไธš่ฑช่พพๅฝ—็บณ้ฃ’ๅฃๆ–ฝๆฌขๅงฎ็”ซๆน˜ๆผพ้—ฒๆฉ่ŽŽ็ฅฅๅฏ็…œ้ธฃๅ“" .. "ๅธŒ่ž้‡ŽๅŒ–้’Šไปฒ่”š็”Ÿๆ”ธ่ƒฝ่ก่่ฟˆๆœ›่ตทๅพฎ้นค่ซ้“ๅจฅๆณ“้‡‘็จ็ญฑ่ตžๅ…ธๅ‹‡ๆ–Œๅชšๅฏฟๅ–œ้ฃ‡ๆฟกๅฎ•่Œœ้ญ็ซ‹่ฃ•ๅผผ็ฟผๅคฎ่Ž˜็ปš็„ฑ" .. "ๅฅฅ่็ฑณ่กฃๆฃฎ่ƒ่ˆช็’งไธบ่ทƒ่’™ๅบ†็ฒๅ€š็ฉนๆญฆ็”œ็’ไฟ่Œนๆ‚Œๆ ผ็ฉฐ็š›็’Ž้พ™ๆๆนƒๅ†œ็ฆๆ—ท็ซฅไบ˜่‹‡่Œƒๅฏฐ็“ƒๅฟ ่™Ž้ข่“„้œˆ่จ€็ฆน" .. "็ซ ่Šฑๅฅ็‚Ž็ฑๆšฎๅ‡่‘›่ดžไพ ไธ“ๆ‡‹ๆพœ้‡็บถๅธƒ็šŽๆบ่€€้ธพๆ…จๆ›พไผ˜ๆ ‹ๅฆƒๆธธไนƒ็”จ่ทฏไฝ™็‰่—ป่€˜ๅ†›่ŠŠๆ—ฅ่ตกๅ‹ƒๅซ่ฝฝๆ—ถไธ‰้—ตๅงฟ" .. "้บฆ็‘—ๆณ‰้ƒŽๆ€ฟๆƒฌ่Œ็…งๅคซ้‘ซๆจฑ็ญ้’งๆŽฃ่Šซไพฌไธ่‚ฒๆตฆ็ฃฌ็Œฎ่‹“็ฟฑ้›ๅฉต้˜‘ๅฅณๅŒ—ๆœช้™ถๅนฒ่‡ชไฝœไผฆ็งๆบฅๆก€ๅทž่ไธพๆ่Œ—ๆดฝ็„•" .. "ๅน็”˜็ก•่ต‹ๆผ ้ข€ๅฆค่ฏบๅฑ•ไฟๆœ”่Š็ง‰่‹ๆดฅ็ฉบๆดฎๆตŽๅฐนๅ‘จๆฑŸ่ก็ฎ€่Žฑๆฆ†่ด่ง่‰พไปๆผซ้”Ÿ่ฐจ้ญ„่”ผ่ฑซ็บฏ็ฟŠๅ ‚ๅซฃ่ช‰้‚ฆๆžœๆšŽ็" .. "ไธดๅ‹คๅขจ่–„้ข‰ๆฃ ็พกๆตšๅ…†็Žฏ้“„"; street_addrs = "้‡ๅบ†ๅคงๅŽฆ,้ป‘้พ™ๆฑŸ่ทฏ,ๅๆข…ๅบต่ก—,้ตไน‰่ทฏ,ๆน˜ๆฝญ่ก—,็‘ž้‡‘ๅนฟๅœบ,ไป™ๅฑฑ่ก—,ไป™ๅฑฑไธœ่ทฏ,ไป™ๅฑฑ่ฅฟๅคงๅŽฆ,็™ฝๆฒ™ๆฒณ่ทฏ,่ตต็บขๅนฟๅœบ," .. "ๆœบๅœบ่ทฏ,ๆฐ‘่ˆช่ก—,้•ฟๅŸŽๅ—่ทฏ,ๆตไบญ็ซ‹ไบคๆกฅ,่™นๆกฅๅนฟๅœบ,้•ฟๅŸŽๅคงๅŽฆ,็คผ้˜ณ่ทฏ,้ฃŽๅฒ—่ก—,ไธญๅท่ทฏ,็™ฝๅก”ๅนฟๅœบ,ๅ…ด้˜ณ่ทฏ,ๆ–‡้˜ณ่ก—,็ปฃๅŸŽ่ทฏ,ๆฒณๅŸŽๅคงๅŽฆ," .. "้”ฆๅŸŽๅนฟๅœบ,ๅด‡้˜ณ่ก—,ๅŽๅŸŽ่ทฏ,ๅบทๅŸŽ่ก—,ๆญฃ้˜ณ่ทฏ,ๅ’Œ้˜ณๅนฟๅœบ,ไธญๅŸŽ่ทฏ,ๆฑŸๅŸŽๅคงๅŽฆ,้กบๅŸŽ่ทฏ,ๅฎ‰ๅŸŽ่ก—,ๅฑฑๅŸŽๅนฟๅœบ,ๆ˜ฅๅŸŽ่ก—,ๅ›ฝๅŸŽ่ทฏ,ๆณฐๅŸŽ่ก—,ๅพท้˜ณ่ทฏ," .. "ๆ˜Ž้˜ณๅคงๅŽฆ,ๆ˜ฅ้˜ณ่ทฏ,่‰ณ้˜ณ่ก—,็ง‹้˜ณ่ทฏ,็ก•้˜ณ่ก—,้’ๅจ้ซ˜้€Ÿ,็‘ž้˜ณ่ก—,ไธฐๆตท่ทฏ,ๅŒๅ…ƒๅคงๅŽฆ,ๆƒœ็ฆ้•‡่ก—้“,ๅคๅบ„่ก—้“,ๅคๅบ™ๅทฅไธšๅ›ญ,ไธญๅฑฑ่ก—,ๅคชๅนณ่ทฏ," .. "ๅนฟ่ฅฟ่ก—,ๆฝๅŽฟๅนฟๅœบ,ๅšๅฑฑๅคงๅŽฆ,ๆน–ๅ—่ทฏ,ๆตŽๅฎ่ก—,่Š็ฝ˜่ทฏ,ๆ˜“ๅทžๅนฟๅœบ,่ทๆณฝๅ››่ทฏ,่ทๆณฝไบŒ่ก—,่ทๆณฝไธ€่ทฏ,่ทๆณฝไธ‰ๅคงๅŽฆ,่ง‚ๆตทไบŒๅนฟๅœบ,ๅนฟ่ฅฟๆ”ฏ่ก—," .. "่ง‚ๆตทไธ€่ทฏ,ๆตŽๅฎๆ”ฏ่ก—,่Ž’ๅŽฟ่ทฏ,ๅนณๅบฆๅนฟๅœบ,ๆ˜Žๆฐด่ทฏ,่’™้˜ดๅคงๅŽฆ,้’ๅฒ›่ทฏ,ๆน–ๅŒ—่ก—,ๆฑŸๅฎๅนฟๅœบ,้ƒฏๅŸŽ่ก—,ๅคฉๆดฅ่ทฏ,ไฟๅฎš่ก—,ๅฎ‰ๅพฝ่ทฏ,ๆฒณๅŒ—ๅคงๅŽฆ," .. "้ป„ๅฒ›่ทฏ,ๅŒ—ไบฌ่ก—,่Ž˜ๅŽฟ่ทฏ,ๆตŽๅ—่ก—,ๅฎ้˜ณๅนฟๅœบ,ๆ—ฅ็…ง่ก—,ๅพทๅŽฟ่ทฏ,ๆ–ฐๆณฐๅคงๅŽฆ,่ทๆณฝ่ทฏ,ๅฑฑ่ฅฟๅนฟๅœบ,ๆฒ‚ๆฐด่ทฏ,่‚ฅๅŸŽ่ก—,ๅ…ฐๅฑฑ่ทฏ,ๅ››ๆ–น่ก—,ๅนณๅŽŸๅนฟๅœบ," .. "ๆณ—ๆฐดๅคงๅŽฆ,ๆต™ๆฑŸ่ทฏ,ๆ›ฒ้˜œ่ก—,ๅฏฟๅบท่ทฏ,ๆฒณๅ—ๅนฟๅœบ,ๆณฐๅฎ‰่ทฏ,ๅคงๆฒฝ่ก—,็บขๅฑฑๅณกๆ”ฏ่ทฏ,่ฅฟ้™ตๅณกไธ€ๅคงๅŽฆ,ๅฐ่ฅฟ็บฌไธ€ๅนฟๅœบ,ๅฐ่ฅฟ็บฌๅ››่ก—,ๅฐ่ฅฟ็บฌไบŒ่ทฏ," .. "่ฅฟ้™ตๅณกไบŒ่ก—,่ฅฟ้™ตๅณกไธ‰่ทฏ,ๅฐ่ฅฟ็บฌไธ‰ๅนฟๅœบ,ๅฐ่ฅฟ็บฌไบ”่ทฏ,ๆ˜ŽๆœˆๅณกๅคงๅŽฆ,้’้“œๅณก่ทฏ,ๅฐ่ฅฟไบŒ่ก—,่ง‚้Ÿณๅณกๅนฟๅœบ,็žฟๅก˜ๅณก่ก—,ๅ›ขๅฒ›ไบŒ่ทฏ,ๅ›ขๅฒ›ไธ€่ก—," .. "ๅฐ่ฅฟไธ‰่ทฏ,ๅฐ่ฅฟไธ€ๅคงๅŽฆ,้ƒ“ๅŸŽๅ—่ทฏ,ๅ›ขๅฒ›ไธ‰่ก—,ๅˆ˜ๅฎถๅณก่ทฏ,่ฅฟ่—ไบŒ่ก—,่ฅฟ่—ไธ€ๅนฟๅœบ,ๅฐ่ฅฟๅ››่ก—,ไธ‰้—จๅณก่ทฏ,ๅŸŽๆญฆๆ”ฏๅคงๅŽฆ,็บขๅฑฑๅณก่ทฏ,้ƒ“ๅŸŽๅŒ—ๅนฟๅœบ," .. "้พ™็พŠๅณก่ทฏ,่ฅฟ้™ตๅณก่ก—,ๅฐ่ฅฟไบ”่ทฏ,ๅ›ขๅฒ›ๅ››่ก—,็Ÿณๆ‘ๅนฟๅœบ,ๅทซๅณกๅคงๅŽฆ,ๅ››ๅท่ทฏ,ๅฏฟๅผ ่ก—,ๅ˜‰็ฅฅ่ทฏ,ๅ—ๆ‘ๅนฟๅœบ,่ŒƒๅŽฟ่ทฏ,่ฅฟๅบท่ก—,ไบ‘ๅ—่ทฏ,ๅทจ้‡ŽๅคงๅŽฆ," .. "่ฅฟๆฑŸๅนฟๅœบ,้ฑผๅฐ่ก—,ๅ•ๅŽฟ่ทฏ,ๅฎš้™ถ่ก—,ๆป•ๅŽฟ่ทฏ,้’œ้‡Žๅนฟๅœบ,่ง‚ๅŸŽ่ทฏ,ๆฑถไธŠๅคงๅŽฆ,ๆœๅŸŽ่ทฏ,ๆป‹้˜ณ่ก—,้‚นๅŽฟๅนฟๅœบ,ๆฟฎๅŽฟ่ก—,็ฃๅฑฑ่ทฏ,ๆฑถๆฐด่ก—,่ฅฟ่—่ทฏ," .. "ๅŸŽๆญฆๅคงๅŽฆ,ๅ›ขๅฒ›่ทฏ,ๅ—้˜ณ่ก—,ๅนฟๅทž่ทฏ,ไธœๅนณ่ก—,ๆžฃๅบ„ๅนฟๅœบ,่ดตๅทž่ก—,่ดนๅŽฟ่ทฏ,ๅ—ๆตทๅคงๅŽฆ,็™ปๅทž่ทฏ,ๆ–‡็™ปๅนฟๅœบ,ไฟกๅทๅฑฑๆ”ฏ่ทฏ,ๅปถๅฎ‰ไธ€่ก—,ไฟกๅทๅฑฑ่ทฏ," .. "ๅ…ดๅฎ‰ๆ”ฏ่ก—,็ฆๅฑฑๆ”ฏๅนฟๅœบ,็บขๅฒ›ๆ”ฏๅคงๅŽฆ,่Žฑ่ŠœไบŒ่ทฏ,ๅดๅŽฟไธ€่ก—,้‡‘ๅฃไธ‰่ทฏ,้‡‘ๅฃไธ€ๅนฟๅœบ,ไผ้พ™ๅฑฑ่ทฏ,้ฑผๅฑฑๆ”ฏ่ก—,่ง‚่ฑกไบŒ่ทฏ,ๅดๅŽฟไบŒๅคงๅŽฆ,่Žฑ่Šœไธ€ๅนฟๅœบ," .. "้‡‘ๅฃไบŒ่ก—,ๆตท้˜ณ่ทฏ,้พ™ๅฃ่ก—,ๆ’ๅฑฑ่ทฏ,้ฑผๅฑฑๅนฟๅœบ,ๆŽ–ๅŽฟ่ทฏ,็ฆๅฑฑๅคงๅŽฆ,็บขๅฒ›่ทฏ,ๅธธๅทž่ก—,ๅคงๅญฆๅนฟๅœบ,้พ™ๅŽ่ก—,้ฝๆฒณ่ทฏ,่Žฑ้˜ณ่ก—,้ป„ๅŽฟ่ทฏ,ๅผ ๅบ—ๅคงๅŽฆ," .. "็ฅšๅฑฑ่ทฏ,่‹ๅทž่ก—,ๅŽๅฑฑ่ทฏ,ไผ้พ™่ก—,ๆฑŸ่‹ๅนฟๅœบ,้พ™ๆฑŸ่ก—,็Ž‹ๆ‘่ทฏ,็ดๅฑฟๅคงๅŽฆ,้ฝไธœ่ทฏ,ไบฌๅฑฑๅนฟๅœบ,้พ™ๅฑฑ่ทฏ,็‰Ÿๅนณ่ก—,ๅปถๅฎ‰ไธ‰่ทฏ,ๅปถๅ‰่ก—,ๅ—ไบฌๅนฟๅœบ," .. "ไธœๆตทไธœๅคงๅŽฆ,้“ถๅท่ฅฟ่ทฏ,ๆตทๅฃ่ก—,ๅฑฑไธœ่ทฏ,็ปๅ…ดๅนฟๅœบ,่Šๆณ‰่ทฏ,ไธœๆตทไธญ่ก—,ๅฎๅค่ทฏ,้ฆ™ๆธฏ่ฅฟๅคงๅŽฆ,้š†ๅพทๅนฟๅœบ,ๆ‰ฌๅทž่ก—,้ƒง้˜ณ่ทฏ,ๅคชๅนณ่ง’ไธ€่ก—," .. "ๅฎๅ›ฝไบŒๆ”ฏ่ทฏ,ๅคชๅนณ่ง’ไบŒๅนฟๅœบ,ๅคฉๅฐไธœไธ€่ทฏ,ๅคชๅนณ่ง’ไธ‰ๅคงๅŽฆ,ๆผณๅทž่ทฏไธ€่ทฏ,ๆผณๅทž่ก—ไบŒ่ก—,ๅฎๅ›ฝไธ€ๆ”ฏๅนฟๅœบ,ๅคชๅนณ่ง’ๅ…ญ่ก—,ๅคชๅนณ่ง’ๅ››่ทฏ,ๅคฉๅฐไธœไบŒ่ก—," .. "ๅคชๅนณ่ง’ไบ”่ทฏ,ๅฎๅ›ฝไธ‰ๅคงๅŽฆ,ๆพณ้—จไธ‰่ทฏ,ๆฑŸ่ฅฟๆ”ฏ่ก—,ๆพณ้—จไบŒ่ทฏ,ๅฎๅ›ฝๅ››่ก—,ๅคงๅฐงไธ€ๅนฟๅœบ,ๅ’ธ้˜ณๆ”ฏ่ก—,ๆดชๆณฝๆน–่ทฏ,ๅดๅ…ดไบŒๅคงๅŽฆ,ๆพ„ๆตทไธ‰่ทฏ,ๅคฉๅฐไธ€ๅนฟๅœบ," .. "ๆ–ฐๆน›ไบŒ่ทฏ,ไธ‰ๆ˜ŽๅŒ—่ก—,ๆ–ฐๆน›ๆ”ฏ่ทฏ,ๆน›ๅฑฑไบ”่ก—,ๆณฐๅทžไธ‰ๅนฟๅœบ,ๆน›ๅฑฑๅ››ๅคงๅŽฆ,้—ฝๆฑŸไธ‰่ทฏ,ๆพณ้—จๅ››่ก—,ๅ—ๆตทๆ”ฏ่ทฏ,ๅดๅ…ดไธ‰ๅนฟๅœบ,ไธ‰ๆ˜Žๅ—่ทฏ,ๆน›ๅฑฑไบŒ่ก—," .. "ไบŒ่ฝปๆ–ฐๆ‘้•‡,ๆฑŸๅ—ๅคงๅŽฆ,ๅดๅ…ดไธ€ๅนฟๅœบ,็ ๆตทไบŒ่ก—,ๅ˜‰ๅณชๅ…ณ่ทฏ,้ซ˜้‚ฎๆน–่ก—,ๆน›ๅฑฑไธ‰่ทฏ,ๆพณ้—จๅ…ญๅนฟๅœบ,ๆณฐๅทžไบŒ่ทฏ,ไธœๆตทไธ€ๅคงๅŽฆ,ๅคฉๅฐไบŒ่ทฏ,ๅพฎๅฑฑๆน–่ก—," .. "ๆดžๅบญๆน–ๅนฟๅœบ,็ ๆตทๆ”ฏ่ก—,็ฆๅทžๅ—่ทฏ,ๆพ„ๆตทไบŒ่ก—,ๆณฐๅทžๅ››่ทฏ,้ฆ™ๆธฏไธญๅคงๅŽฆ,ๆพณ้—จไบ”่ทฏ,ๆ–ฐๆน›ไธ‰่ก—,ๆพณ้—จไธ€่ทฏ,ๆญฃ้˜ณๅ…ณ่ก—,ๅฎๆญฆๅ…ณๅนฟๅœบ,้—ฝๆฑŸๅ››่ก—," .. "ๆ–ฐๆน›ไธ€่ทฏ,ๅฎๅ›ฝไธ€ๅคงๅŽฆ,็Ž‹ๅฎถ้บฆๅฒ›,ๆพณ้—จไธƒๅนฟๅœบ,ๆณฐๅทžไธ€่ทฏ,ๆณฐๅทžๅ…ญ่ก—,ๅคงๅฐงไบŒ่ทฏ,้’ๅคงไธ€่ก—,้—ฝๆฑŸไบŒๅนฟๅœบ,้—ฝๆฑŸไธ€ๅคงๅŽฆ,ๅฑไธœๆ”ฏ่ทฏ,ๆน›ๅฑฑไธ€่ก—," .. "ไธœๆตท่ฅฟ่ทฏ,ๅพๅฎถ้บฆๅฒ›ๅ‡ฝ่ฐทๅ…ณๅนฟๅœบ,ๅคงๅฐงไธ‰่ทฏ,ๆ™“ๆœ›ๆ”ฏ่ก—,็ง€ๆน›ไบŒ่ทฏ,้€้ฅไธ‰ๅคงๅŽฆ,ๆพณ้—จไนๅนฟๅœบ,ๆณฐๅทžไบ”่ก—,ๆพ„ๆตทไธ€่ทฏ,ๆพณ้—จๅ…ซ่ก—,็ฆๅทžๅŒ—่ทฏ," .. "็ ๆตทไธ€ๅนฟๅœบ,ๅฎๅ›ฝไบŒ่ทฏ,ไธดๆทฎๅ…ณๅคงๅŽฆ,็‡•ๅ„ฟๅฒ›่ทฏ,็ดซ่†ๅ…ณ่ก—,ๆญฆ่ƒœๅ…ณๅนฟๅœบ,้€้ฅไธ€่ก—,็ง€ๆน›ๅ››่ทฏ,ๅฑ…ๅบธๅ…ณ่ก—,ๅฑฑๆตทๅ…ณ่ทฏ,้„ฑ้˜ณๆน–ๅคงๅŽฆ,ๆ–ฐๆน›่ทฏ," .. "ๆผณๅทž่ก—,ไป™ๆธธ่ทฏ,่Šฑ่Žฒ่ก—,ไนๆธ…ๅนฟๅœบ,ๅทขๆน–่ก—,ๅฐๅ—่ทฏ,ๅดๅ…ดๅคงๅŽฆ,ๆ–ฐ็”ฐ่ทฏ,็ฆๆธ…ๅนฟๅœบ,ๆพ„ๆตท่ทฏ,่ކ็”ฐ่ก—,ๆตทๆธธ่ทฏ,้•‡ๆฑŸ่ก—,็Ÿณๅฒ›ๅนฟๅœบ,ๅฎœๅ…ดๅคงๅŽฆ," .. "ไธ‰ๆ˜Ž่ทฏ,ไปฐๅฃ่ก—,ๆฒ›ๅŽฟ่ทฏ,ๆผณๆตฆๅนฟๅœบ,ๅคง้บฆๅฒ›,ๅฐๆนพ่ก—,ๅคฉๅฐ่ทฏ,้‡‘ๆน–ๅคงๅŽฆ,้ซ˜้›„ๅนฟๅœบ,ๆตทๆฑŸ่ก—,ๅฒณ้˜ณ่ทฏ,ๅ–„ๅŒ–่ก—,่ฃๆˆ่ทฏ,ๆพณ้—จๅนฟๅœบ,ๆญฆๆ˜Œ่ทฏ," .. "้—ฝๆฑŸๅคงๅŽฆ,ๅฐๅŒ—่ทฏ,้พ™ๅฒฉ่ก—,ๅ’ธ้˜ณๅนฟๅœบ,ๅฎๅพท่ก—,้พ™ๆณ‰่ทฏ,ไธฝๆฐด่ก—,ๆตทๅท่ทฏ,ๅฝฐๅŒ–ๅคงๅŽฆ,้‡‘็”ฐ่ทฏ,ๆณฐๅทž่ก—,ๅคชๆน–่ทฏ,ๆฑŸ่ฅฟ่ก—,ๆณฐๅ…ดๅนฟๅœบ,้’ๅคง่ก—," .. "้‡‘้—จ่ทฏ,ๅ—้€šๅคงๅŽฆ,ๆ—Œๅพท่ทฏ,ๆฑ‡ๆณ‰ๅนฟๅœบ,ๅฎๅ›ฝ่ทฏ,ๆณ‰ๅทž่ก—,ๅฆ‚ไธœ่ทฏ,ๅฅ‰ๅŒ–่ก—,้นŠๅฑฑๅนฟๅœบ,่Žฒๅฒ›ๅคงๅŽฆ,ๅŽไธฅ่ทฏ,ๅ˜‰ไน‰่ก—,ๅค็”ฐ่ทฏ,ๅ—ๅนณๅนฟๅœบ,็ง€ๆน›่ทฏ," .. "้•ฟๆฑ€่ก—,ๆน›ๅฑฑ่ทฏ,ๅพๅทžๅคงๅŽฆ,ไธฐๅŽฟๅนฟๅœบ,ๆฑ•ๅคด่ก—,ๆ–ฐ็ซน่ทฏ,้ป„ๆตท่ก—,ๅฎ‰ๅบ†่ทฏ,ๅŸบ้š†ๅนฟๅœบ,้Ÿถๅ…ณ่ทฏ,ไบ‘้œ„ๅคงๅŽฆ,ๆ–ฐๅฎ‰่ทฏ,ไป™ๅฑ…่ก—,ๅฑไธœๅนฟๅœบ,ๆ™“ๆœ›่ก—," .. "ๆตท้—จ่ทฏ,็ ๆตท่ก—,ไธŠๆญ่ทฏ,ๆฐธๅ˜‰ๅคงๅŽฆ,ๆผณๅนณ่ทฏ,็›ๅŸŽ่ก—,ๆ–ฐๆตฆ่ทฏ,ๆ–ฐๆ˜Œ่ก—,้ซ˜็”ฐๅนฟๅœบ,ๅธ‚ๅœบไธ‰่ก—,้‡‘ไนกไธœ่ทฏ,ๅธ‚ๅœบไบŒๅคงๅŽฆ,ไธŠๆตทๆ”ฏ่ทฏ,ๆŽๆ‘ๆ”ฏๅนฟๅœบ," .. "ๆƒ ๆฐ‘ๅ—่ทฏ,ๅธ‚ๅœบ็บฌ่ก—,้•ฟๅฎ‰ๅ—่ทฏ,้™ตๅŽฟๆ”ฏ่ก—,ๅ† ๅŽฟๆ”ฏๅนฟๅœบ,ๅฐๆธฏไธ€ๅคงๅŽฆ,ๅธ‚ๅœบไธ€่ทฏ,ๅฐๆธฏไบŒ่ก—,ๆธ…ๅนณ่ทฏ,ๅนฟไธœๅนฟๅœบ,ๆ–ฐ็–†่ทฏ,ๅšๅนณ่ก—,ๆธฏ้€š่ทฏ," .. "ๅฐๆธฏๆฒฟ,็ฆๅปบๅนฟๅœบ,้ซ˜ๅ”่ก—,่ŒŒๅนณ่ทฏ,ๆธฏ้’่ก—,้ซ˜ๅฏ†่ทฏ,้˜ณ่ฐทๅนฟๅœบ,ๅนณ้˜ด่ทฏ,ๅคๆดฅๅคงๅŽฆ,้‚ฑๅŽฟ่ทฏ,ๆธคๆตท่ก—,ๆฉๅŽฟๅนฟๅœบ,ๆ—…้กบ่ก—,ๅ ‚้‚‘่ทฏ,ๆŽๆ‘่ก—," .. "ๅณๅขจ่ทฏ,ๆธฏๅŽๅคงๅŽฆ,ๆธฏ็Žฏ่ทฏ,้ฆ†้™ถ่ก—,ๆ™ฎ้›†่ทฏ,ๆœ้˜ณ่ก—,็”˜่‚ƒๅนฟๅœบ,ๆธฏๅค่ก—,ๆธฏ่”่ทฏ,้™ตๅŽฟๅคงๅŽฆ,ไธŠๆตท่ทฏ,ๅฎๅฑฑๅนฟๅœบ,ๆญฆๅฎš่ทฏ,้•ฟๆธ…่ก—,้•ฟๅฎ‰่ทฏ," .. "ๆƒ ๆฐ‘่ก—,ๆญฆๅŸŽๅนฟๅœบ,่ŠๅŸŽๅคงๅŽฆ,ๆตทๆณŠ่ทฏ,ๆฒงๅฃ่ก—,ๅฎๆณข่ทฏ,่ƒถๅทžๅนฟๅœบ,่Žฑๅทž่ทฏ,ๆ‹›่ฟœ่ก—,ๅ† ๅŽฟ่ทฏ,ๅ…ญ็ ๅคด,้‡‘ไนกๅนฟๅœบ,็ฆนๅŸŽ่ก—,ไธดๆธ…่ทฏ,ไธœ้˜ฟ่ก—," .. "ๅดๆทž่ทฏ,ๅคงๆธฏๆฒฟ,่พฝๅฎ่ทฏ,ๆฃฃ็บฌไบŒๅคงๅŽฆ,ๅคงๆธฏ็บฌไธ€่ทฏ,่ดฎๆฐดๅฑฑๆ”ฏ่ก—,ๆ— ๆฃฃ็บฌไธ€ๅนฟๅœบ,ๅคงๆธฏ็บฌไธ‰่ก—,ๅคงๆธฏ็บฌไบ”่ทฏ,ๅคงๆธฏ็บฌๅ››่ก—,ๅคงๆธฏ็บฌไบŒ่ทฏ," .. "ๆ— ๆฃฃไบŒๅคงๅŽฆ,ๅ‰ๆž—ๆ”ฏ่ทฏ,ๅคงๆธฏๅ››่ก—,ๆ™ฎ้›†ๆ”ฏ่ทฏ,ๆ— ๆฃฃไธ‰่ก—,้ป„ๅฐๆ”ฏๅนฟๅœบ,ๅคงๆธฏไธ‰่ก—,ๆ— ๆฃฃไธ€่ทฏ,่ดฎๆฐดๅฑฑๅคงๅŽฆ,ๆณฐๅฑฑๆ”ฏ่ทฏ,ๅคงๆธฏไธ€ๅนฟๅœบ,ๆ— ๆฃฃๅ››่ทฏ," .. "ๅคง่ฟžๆ”ฏ่ก—,ๅคงๆธฏไบŒ่ทฏ,้”ฆๅทžๆ”ฏ่ก—,ๅพทๅนณๅนฟๅœบ,้ซ˜่‹‘ๅคงๅŽฆ,้•ฟๅฑฑ่ทฏ,ไน้™ต่ก—,ไธด้‚‘่ทฏ,ๅซฉๆฑŸๅนฟๅœบ,ๅˆๆฑŸ่ทฏ,ๅคง่ฟž่ก—,ๅšๅ…ด่ทฏ,่’ฒๅฐๅคงๅŽฆ,้ป„ๅฐๅนฟๅœบ," .. "ๅŸŽ้˜ณ่ก—,ไธดๆท„่ทฏ,ๅฎ‰้‚ฑ่ก—,ไธดๆœ่ทฏ,้’ๅŸŽๅนฟๅœบ,ๅ•†ๆฒณ่ทฏ,็ƒญๆฒณๅคงๅŽฆ,ๆตŽ้˜ณ่ทฏ,ๆ‰ฟๅพท่ก—,ๆท„ๅทๅนฟๅœบ,่พฝๅŒ—่ก—,้˜ณไฟก่ทฏ,็›Š้ƒฝ่ก—,ๆพๆฑŸ่ทฏ,ๆตไบญๅคงๅŽฆ," .. "ๅ‰ๆž—่ทฏ,ๆ’ๅฐ่ก—,ๅŒ…ๅคด่ทฏ,ๆ— ๆฃฃ่ก—,้“ๅฑฑๅนฟๅœบ,้”ฆๅทž่ก—,ๆก“ๅฐ่ทฏ,ๅ…ดๅฎ‰ๅคงๅŽฆ,้‚นๅนณ่ทฏ,่ƒถไธœๅนฟๅœบ,็ซ ไธ˜่ทฏ,ไธนไธœ่ก—,ๅŽ้˜ณ่ทฏ,้’ๆตท่ก—,ๆณฐๅฑฑๅนฟๅœบ," .. "ๅ‘จๆ‘ๅคงๅŽฆ,ๅ››ๅนณ่ทฏ,ๅฐไธœ่ฅฟไธƒ่ก—,ๅฐไธœไธœไบŒ่ทฏ,ๅฐไธœไธœไธƒๅนฟๅœบ,ๅฐไธœ่ฅฟไบŒ่ทฏ,ไธœไบ”่ก—,ไบ‘้—จไบŒ่ทฏ,่Š™่“‰ๅฑฑๆ‘,ๅปถๅฎ‰ไบŒๅนฟๅœบ,ไบ‘้—จไธ€่ก—,ๅฐไธœๅ››่ทฏ," .. "ๅฐไธœไธ€่ก—,ๅฐไธœไบŒ่ทฏ,ๆญๅทžๆ”ฏๅนฟๅœบ,ๅ†…่’™ๅค่ทฏ,ๅฐไธœไธƒๅคงๅŽฆ,ๅฐไธœๅ…ญ่ทฏ,ๅนฟ้ฅถๆ”ฏ่ก—,ๅฐไธœๅ…ซๅนฟๅœบ,ๅฐไธœไธ‰่ก—,ๅ››ๅนณๆ”ฏ่ทฏ,้ƒญๅฃไธœ่ก—,้’ๆตทๆ”ฏ่ทฏ," .. "ๆฒˆ้˜ณๆ”ฏๅคงๅŽฆ,่œๅธ‚ไบŒ่ทฏ,่œๅธ‚ไธ€่ก—,ๅŒ—ไปฒไธ‰่ทฏ,็‘žไบ‘่ก—,ๆปจๅŽฟๅนฟๅœบ,ๅบ†็ฅฅ่ก—,ไธ‡ๅฏฟ่ทฏ,ๅคงๆˆๅคงๅŽฆ,่Š™่“‰่ทฏ,ๅކๅŸŽๅนฟๅœบ,ๅคงๅ่ทฏ,ๆ˜Œๅนณ่ก—,ๅนณๅฎš่ทฏ," .. "้•ฟๅ…ด่ก—,ๆตฆๅฃๅนฟๅœบ,่ฏธๅŸŽๅคงๅŽฆ,ๅ’Œๅ…ด่ทฏ,ๅพท็››่ก—,ๅฎๆตท่ทฏ,ๅจๆตทๅนฟๅœบ,ไธœๅฑฑ่ทฏ,ๆธ…ๅ’Œ่ก—,ๅงœๆฒŸ่ทฏ,้›’ๅฃๅคงๅŽฆ,ๆพๅฑฑๅนฟๅœบ,้•ฟๆ˜ฅ่ก—,ๆ˜†ๆ˜Ž่ทฏ,้กบๅ…ด่ก—," .. "ๅˆฉๆดฅ่ทฏ,้˜ณๆ˜Žๅนฟๅœบ,ไบบๅ’Œ่ทฏ,้ƒญๅฃๅคงๅŽฆ,่ฅๅฃ่ทฏ,ๆ˜Œ้‚‘่ก—,ๅญŸๅบ„ๅนฟๅœบ,ไธฐ็››่ก—,ๅŸ•ๅฃ่ทฏ,ไธน้˜ณ่ก—,ๆฑ‰ๅฃ่ทฏ,ๆดฎๅ—ๅคงๅŽฆ,ๆก‘ๆข“่ทฏ,ๆฒพๅŒ–่ก—,ๅฑฑๅฃ่ทฏ," .. "ๆฒˆ้˜ณ่ก—,ๅ—ๅฃๅนฟๅœบ,ๆŒฏๅ…ด่ก—,้€šๅŒ–่ทฏ,็ฆๅฏบๅคงๅŽฆ,ๅณ„ๅŽฟ่ทฏ,ๅฏฟๅ…‰ๅนฟๅœบ,ๆ›นๅŽฟ่ทฏ,ๆ˜Œไน่ก—,้“ๅฃ่ทฏ,ๅ—ไนๆฐด่ก—,ๅฐๆน›ๅนฟๅœบ,ไธœๅ…‰ๅคงๅŽฆ,้ฉผๅณฐ่ทฏ,ๅคชๅนณๅฑฑ," .. "ๆ ‡ๅฑฑ่ทฏ,ไบ‘ๆบชๅนฟๅœบ,ๅคชๆธ…่ทฏ"; function ocr(x1,y1,x2,y2) local ress = ocrText(x1,y1,x2,y2, 0) or 0 if ress == '' then nLog('nil') return 0 end return ress end function updateNike() local sz = require("sz") local url = 'http://zzaha.com/phalapi/public/' local Arr={} Arr.s = 'Nikesave.Save' Arr.address_mail = var.account.login Arr.address_pwd = <PASSWORD> Arr.address_phone = var.account.phone Arr.address_xin = first_name_ Arr.address_ming = last_names_ Arr.address_sheng = 'ๅนฟไธœ็œ' Arr.address_shi = 'ๆทฑๅœณๅธ‚' Arr.address_qu = '็ฝ—ๆน–ๅŒบ' Arr.address_area = var.account.address_area Arr.address_country = var.account.address_country Arr.iphone = 'iPhone'..rd(1,50) Arr.imei = sz.system.serialnumber() Arr.birthday = var.birthday Arr.moon = var.moon Arr.codes = var.codes log(Arr) if post(url,Arr)then return true end end function click_N(x,y,n) if n > 0 then for i=1,n do click(x,y) end end end <file_sep> --unlockDevice() require("TSLib") --require("tsp") --res, code = http.request("http://ip.chinaz.com/getip.aspx"); --็”จhttp.getๅฎž็Žฐไธ‹่ฝฝๆ–‡ไปถๅŠŸ่ƒฝ function downFile(url, path) local sz = require("sz") local http = require("szocket.http") local res, code = http.request(url); -- nLog(res) if code == 200 then local body = res local file = io.open(path, "w+") if file then file:write(body) file:close() return status; else return -1; end else return status; end end function delFile(path)--ๅธฎไฝ ็Žฉๅนณๅฐ็ฆ็”จๆญคๅ‡ฝๆ•ฐ os.execute("rm -rf "..path); end --ๆฃ€ๆต‹ๆŒ‡ๅฎšๆ–‡ไปถๆ˜ฏๅฆๅญ˜ๅœจ function file_exists(file_name) local f = io.open(file_name, "r") return f ~= nil and f:close() end game_lua = { {"AWZ",'https://img.wenfree.cn/snkrs/AWZ.lua'}, {"AXJ",'https://img.wenfree.cn/snkrs/AXJ.lua'}, {"UIs",'https://img.wenfree.cn/snkrs/UIs.lua'}, {"api",'https://img.wenfree.cn/snkrs/api.lua'}, {"re-login",'https://img.wenfree.cn/snkrs/re-login.lua'}, {"tsp",'https://img.wenfree.cn/snkrs/tsp.lua'}, {"ui",'https://img.wenfree.cn/snkrs/ui.lua'}, {"main",'https://img.wenfree.cn/snkrs/main.lua'}, {"snkrs",'https://img.wenfree.cn/snkrs/snkrs.lua'}, } function get_(url) local sz = require("sz") local http = require("szocket.http") local res, code = http.request(url); if code == 200 then local json = sz.json if res ~= nil then return json.decode(res) end end end t1=os.time(); nLog(t1) for i,v in ipairs(game_lua)do nLog(v[1]) nLog(v[2]) local path = "/User/Media/TouchSprite/lua/"..v[1]..".lua" delFile(path) downFile(v[2],path) toast('ไธ‹่ฝฝ->'..v[1],1) end nLog('end----->'..os.time()-t1) dialog('่ฏท็”จsnkrsๅฏๅŠจ',3) require('snkrs')
2f026b4e7f03774add111bdc8985cb7c3c2a06c3
[ "Lua" ]
62
Lua
thorn5918/lua-touchsprte
c3f6f6de3d79ddd6efd35426f2d99da7b4652d82
cdc2bb7b6580958a4e693718065404a2a5da72ff
refs/heads/master
<repo_name>shinyT/Web-Server<file_sep>/Config.cc #include "Config.h" using namespace std; /*DONE*/ Config::Config() { } /*DONE*/ Config::~Config() { } /*DONE*/ void Config::parse(const char* filename) { host_.clear(); media_.clear(); parameter_.clear(); string line; // open file ifstream file(filename); if (!file.is_open()) return; // parse file while (!file.eof()) { getline(file,line); parseLine(line); } // close file file.close(); } /*DONE*/ string& Config::host(string name) { return host_[name]; } /*DONE*/ string& Config::media(string name) { return media_[name]; } /*DONE*/ string& Config::parameter(string name) { return parameter_[name]; } /*DONE*/ void Config::parseLine(std::string &line) { vector<string> tokens = tokenizer_.parse(line); if (tokens.size() < 3) return; if (tokens.at(0) == "host") host_[tokens.at(1)] = tokens.at(2); else if (tokens.at(0) == "media") media_[tokens.at(1)] = tokens.at(2); else if (tokens.at(0) == "parameter") parameter_[tokens.at(1)] = tokens.at(2); } /*DONE*/ /*static*/ bool Config::Test(ostream & os) { bool success = true; Config c; c.parse("test.conf"); TEST(equalStrings(c.host("carmelo.cs.byu.edu"),"/tmp/web1")); TEST(equalStrings(c.host("localhost"),"/tmp/web2")); TEST(equalStrings(c.media("txt"), "text/plain")); TEST(equalStrings(c.media("html"), "text/html")); TEST(equalStrings(c.media("jpg"), "image/jpeg")); TEST(equalStrings(c.media("gif"), "image/gif")); TEST(equalStrings(c.media("png"), "image/png")); TEST(equalStrings(c.media("pdf"), "application/pdf")); TEST(equalStrings(c.media("py"), "text/x-script.python")); TEST(equalStrings(c.parameter("timeout"), "1")); return success; } <file_sep>/server.h /** LAB 4 - WEB SERVER A web server in C++ that implements some of the HTTP 1.1 specification given in RFC 2616. Uses a scalable event-driven server architecture using the epoll interface to manage a set of sockets in a single thread. Syntax: web -p [port] -d -t (default port is 8080. -d turns debug on. -t runs the test driver INSTEAD of the server.) Features: 1. GET method 2. multiple requests on one TCP connection (In accordance with HTTP 1.1) 3. multiple hosts on one web server (In accordance with HTTP 1.1) 4. serves "/index.html" if the URI given is "/" 5. These headers: (ignores other headers) Date (using RFC 822 / RFC 1123 format dates) Server Content-Type Content-Length Last-Modified (using RFC 822 / RFC 1123 format dates) 6. One listening socket that handles all clients' requests 7. Closes connection when client closes it 8. Closes connection when it times out 9. Timeout second can be set in .config file 10. Determines content-type of a file using its extension. (extensions must be defined in the .config file.) 11. These response codes: 200 OK 400 Bad Request : if the web server parses the request and the method or URI is empty, or if the request contains a host that this server doesn't handle 403 Forbidden: if the web server does not have permission to open the requested file 404 Not Found: if the web server cannot find the requested file 500 Internal Server Error: if the web server encounters any other error when trying to open a file 501 Not Implemented: if the web server does not implement the requested method 12. Reads in a config file with any number of lines of the following syntaxes: host [name] [path] //where the document root is located for a given host. This path can be either relative "web1" or absolute "/tmp/web1". A relative path starts in the current directory, whereas an absolute path starts in the root directory. media [ext] [type] //The MIME type to use in the Content-Type header for a document that ends in the given extension. If a document has no extension, or if its extension is not listed in the configuration file, then your server should treat it as a text/plain file. parameter [name] [value] //time, in seconds, that a socket is allowed to be idle before it will be closed. 13. Separate cache for each socket 14. Configures each client to use non-blocking socket I/O, and continues to call recv() on the client until it returns an error code indicating that no data is available. Extra credit: (NOT YET IMPLEMENTED) 1. HEAD and range requests (extra credit) */ #ifndef SERVER_H #define SERVER_H #include <arpa/inet.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <sys/epoll.h> #include <iostream> #include "Utils.h" #include "handler.h" #include <list> #include <map> #include <string> #include "Config.h" #include <iterator> #define MAX_EVENTS 1000 //----------------------------- VARIABLES -------------------------- /** * Has to be global because other files use debugging too. Default: false. */ bool debug = false; /** * For testing */ bool test = false; //------------------------------ FUNCTIONS -------------------------- /** The whole server. - Processes command line arguments - If the -t flag is on, runs a test driver and exits the program - Parses the configuration file * - Makes an epoller with a listening socket. * Polls the epoller continuously, accepting and handling clients * and timing them out. */ int main(int argc, char **argv); /** * Process command line args. Port cannot be 0. * Default values: port = 8080, debug = off. * Syntax: server -p port -d -t * -d: debug on * -t: run the test driver instead of running the program. * @param argc same as main's parameter. * @param argv same as main's parameter. * @param port the variable that will store the port argument. */ void ProcessCommandLineArgs(int argc, char ** argv, int & port); /** * Creates a listening socket, sets it up with setsockopt, bind, and listen. * @param port the port of the listening socket. * @return the file descriptor of the listening socket. */ int SetUpListeningSocket(int port); /** Calls epoll_wait with the given parameters. However, the call will always wait for a maximum of 1 millisecond. ----------- FROM EPOLL_WAIT MANUAL PAGE: ----------- int epoll_wait(int epfd, struct epoll_event *events, int maxevents, int timeout); The epoll_wait() system call waits for events on the epoll instance referred to by the file descriptor epfd. The memory area pointed to by events will contain the events that will be available for the caller. Up to maxevents are returned by epoll_wait(). The maxevents argument must be greater than zero. The call waits for a maximum time of timeout milliseconds. Specifying a timeout of -1 makes epoll_wait() wait indefiโ€ nitely, while specifying a timeout equal to zero makes epoll_wait() to return immediately even if no events are available (return code equal to zero). @param epfd the file descriptor of the epoll instance you want to wait for events on. @param events will contain the events that will be available for the caller @param maxEvents the maximum number of events returned by epoll_wait(). @return the number of file descriptors ready for the requested I/O */ int DoPoll(int epfd, struct epoll_event * events, int maxEvents); /** Handles the request of the socket. If it's closed, it closes the socket and removes it from the handlerMap and the epoller. @pre readySocket is one of the sockets that the epoller listed as being ready. @param readySocket the socket to handle. @param handlerMap the map to look up the readySocket's handler in. @param epfd the epoller's file descriptor. */ void HandleReadySocket(int readySocket, map<int, Handler> & handlerMap, int epfd, Config config); /** * Compares each socket in the handler map's most recent time it was handled * with the current time. If the difference is greater than the timeout * (aka it was idle too long), then it boots off the client. */ void TimeOutSockets(int epfd, map<int, Handler> & handlerMap, int timeout); /** * Does 3 things necessary when you boot off a client: * 1. removes client socket from epoller * 2. Closes client socket * 3. removes client's handler from handlermap. * * @param epfd the epoller * @param c the client socket fd * @param handlerMap the handler map */ void BootOffClient( int epfd, int c, map<int, Handler> & handlerMap); /** * Removes the given socket from the given epoll file descriptor. * @param epfd the epoll file descriptor * @param removeThisSocket socket to remove */ void RemoveSocketFromPoller(int epfd, int removeThisSocket); /** * Adds the given socket to the given epoll file descriptor. * * (epollFileDescriptor, operationToBePerformedOnTargetFileDescriptor, targetFileDescriptor, epollEventData) ----------- FROM EPOLL_CTL MANUAL PAGE: ----------- int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event); This system call performs control operations on the epoll instance referred to by the file descriptor epfd. It requests that the operation op be performed for the target file descriptor, fd. The event argument describes the object linked to the file descriptor fd. The struct epoll_event is defined as : typedef union epoll_data { void *ptr; int fd; uint32_t u32; uint64_t u64; } epoll_data_t; struct epoll_event { uint32_t events; Epoll events epoll_data_t data; User data variable }; The events member is a bit set composed using the available event types. EPOLL_CTL_ADD Register the target file descriptor fd on the epoll instance referred to by the file descriptor epfd and associate the event event with the internal file linked to fd. * @param epfd the epoll file descriptor * @param addThisSocket targetFileDescriptor, which will be added to the epoller. */ void AddSocketToPoller(int epfd, int addThisSocket); /** Test driver for the other cpp files in this project. */ void TestEverything(); #endif // SERVER_H <file_sep>/handler.cc #include "handler.h" /*static*/ bool Handler::Test(ostream & os) { os << "=============Testing Handler ============" << endl; bool success = true; if (!TestGetFilePath(os)) success = false; if (!TestGetFileSize(os)) success = false; if (!TestGetLastModified(os)) success = false; if (!TestGetContentType(os)) success = false; return success; } /*static*/ bool Handler::TestGetFilePath(ostream & os) { bool success = true; os << "--------------Testing GetFilePath...-------------------" << endl; //I just use this to experiment to see how the HTTPRequest parser works. string s = string("GET / HTTP/1.1\r\nHost:carmelo.cs.byu.edu\r\nUser-Agent:downloader\r\nFrom: Lexi\r\n\r\n"); HTTPRequest request; request.parse(s); cout << "Host: " << request.header(string("Host")) << " URI: " << request.uri() << endl; //Set up test object Config config; config.parse("web.conf"); Config * p_config = &config; Handler h(p_config, 1); //Basic test TEST(equalStrings(h.GetFilePath(request), "/tmp/web1/index.html")); os << endl; return success; } /*static*/ /*DONE*/ bool Handler::TestGetFileSize(ostream & os) { bool success = true; os << "------------- Testing GetFileSize ---------------" << endl; int index = open("/home/lexi/Documents/index.html", O_RDONLY); int article = open("/home/lexi/Documents/article.pdf", O_RDONLY); int image = open("/home/lexi/Documents/image.jpg", O_RDONLY); TEST(GetFileSize(index) == 30); TEST(GetFileSize(article) == 17); TEST(GetFileSize(image) == 5); os << endl; return success; } /*static*/ /*DONE*/ bool Handler::TestGetLastModified(ostream & os) { bool success = true; os << "-------------------- Testing GetLastModified ---------------" << endl; int index = open("/home/lexi/Documents/index.html", O_RDONLY); int article = open("/home/lexi/Documents/article.pdf", O_RDONLY); int image = open("/home/lexi/Documents/image.jpg", O_RDONLY); os << "index.html\nExpected: Fri 11 Jan 2013 02:31:55 PM MST\nActual: " << GetLastModified(index) << "\n" << endl; os << "article.pdf\nExpected: Fri 11 Jan 2013 02:36:23 PM MST\nActual: " << GetLastModified(article) << "\n" << endl; os << "image.jpg\nExpected: Fri 11 Jan 2013 02:35:42 PM MST\nActual: " << GetLastModified(image) << "\n" << endl; os << endl; return success; } /*static*/ /*DONE*/ bool Handler::TestGetContentType(ostream & os) { bool success = true; os << "------------- Testing GetContentType -----------" << endl; //Set up test object Config config; config.parse("web.conf"); Config * p_config = &config; Handler h(p_config, 1); TEST(equalStrings(h.GetContentType("/home/lexi/Documents/index.html"), "text/html")); TEST(equalStrings(h.GetContentType("/home/lexi/Documents/article.pdf"), "application/pdf")); TEST(equalStrings(h.GetContentType("/home/lexi/Documents/image.jpg"), "image/jpeg")); //I assume that if it isn't there, it will simply return an empty string. TEST(equalStrings(h.GetContentType(".aoksdjfpaos"), "")); os << endl; return success; } /*DONE*/ Handler::Handler() { //Do nothing } /*DONE*/ Handler::Handler(Config * config, int c) : config(config), cache(""), storedTime(GetCurrentTime()), c(c) { //Do nothing } /*DONE*/ Handler::~Handler() { //Do nothing } /*DONE*/ Handler::Handler(const Handler & other) { this->cache = other.cache; this->storedTime = other.storedTime; this->config = other.config; this->c = other.c; } /*DONE*/ bool Handler::Handle() { //Update time storedTime = GetCurrentTime(); //Read until it would have blocked... string str = read_all_available(c, closed); //Add it to the current leftovers from last time, if there were any... cache.append(str); //Parse all the HTTP requests out of it, and handle each one. while (HasSubstring(str, "\r\n\r\n")) { string requestStr = remove_newline(str, "\r\n\r\n"); HTTPRequest httpRequest; httpRequest.parse(requestStr); HandleRequest(httpRequest); } //Let the caller know if the socket is closed or not. return closed; } /*DONE*/ double Handler::GetTime() { return storedTime; } /*DONE* - unless you want extra credit*/ void Handler::HandleRequest(HTTPRequest r) { string method = r.method(); DEBUG("method: " << method << endl); //NOTE: THIS TEST MUST COME FIRST! (Before testing the method) //If the method is empty, or the URI is empty, or the host is unknown... if (equalStrings(method, "") || equalStrings(r.uri(), "") || equalStrings(config->host(r.header(string("Host"))), "")) { //...then it is a Bad request HTTPResponse response; response.version("HTTP/1.1"); response.header("Server", "Lexi's Server"); response.header("Date", GetDate(time(NULL))); response.header("Content-Length", "37"); response.header("Content-Type", "text/html"); response.code("400"); response.phrase("Bad Request"); Send(response.str(), c); Send("<html><h1>400 Bad Request</h1></html>", c); } else if (equalStrings(method, "GET")) { HandleGETRequest(r); } else { //Requested method not implemented HTTPResponse response; response.version("HTTP/1.1"); response.header("Server", "Lexi's Server"); response.header("Date", GetDate(time(NULL))); response.header("Content-Length", "41"); response.header("Content-Type", "text/html"); response.code("501"); response.phrase("Not Implemented"); Send(response.str(), c); Send("<html><h1>501 Not Implemented</h1></html>", c); } return; } /*DONE*/ void Handler::HandleGETRequest(HTTPRequest r) { DEBUG("Handling GET request" << endl); string filePath = GetFilePath(r); DEBUG("Host: " << r.header(string("Host")) << " FilePath: " << filePath << endl); int fd = open(filePath.c_str(), O_RDONLY); if (fd == -1) { //Send responses based on different errors if (errno == EACCES) { HTTPResponse response; response.version("HTTP/1.1"); response.header("Server", "Lexi's Server"); response.header("Date", GetDate(time(NULL))); response.code("403"); response.header("Content-Length", "35"); response.header("Content-Type", "text/html"); response.phrase("Forbidden"); DEBUG("403 Forbidden" << endl); Send(response.str(), c); Send("<html><h1>403 Forbidden</h1></html>", c); close(fd); } else if (errno == ENOENT) { HTTPResponse response; response.version("HTTP/1.1"); response.header("Server", "Lexi's Server"); response.header("Date", GetDate(time(NULL))); response.header("Content-Length", "35"); response.header("Content-Type", "text/html"); response.code("404"); response.phrase("Not found"); DEBUG("404 Not found" << endl); Send(response.str(), c); Send("<html><h1>404 Not Found</h1></html>", c); close(fd); } else { perror("open"); SendCode500(); close(fd); } } else { //Call all the calls that might have Code-500 errors. string lastModified = GetLastModified(fd); if (equalStrings(lastModified, "")) { perror("fstat"); SendCode500(); } string contentLength = GetContentLength(fd); if (equalStrings(contentLength, "")) { perror("fstat"); SendCode500(); } int fileSize = GetFileSize(fd); if (fileSize == -1) { perror("fstat"); SendCode500(); } //Since they didn't have errors, now use the data to send the OK response //and the requested file. HTTPResponse response; response.version("HTTP/1.1"); response.header("Server", "Lexi's Server"); response.header("Date", GetDate(time(NULL))); response.code("200"); response.phrase("OK"); response.header("Last-Modified", lastModified); response.header("Content-Length", contentLength); response.header("Content-Type", GetContentType(filePath)); DEBUG("200 OK" << endl); Send(response.str(), c); sendfile(c, fd, NULL, fileSize); close(fd); } return; } /*DONE*/ string Handler::GetFilePath(HTTPRequest r) { string host = r.header(string("Host")); string directory = config->host(host); if (equalStrings(directory, "")) { return ""; } else { string uri = r.uri(); if (equalStrings(uri, "/")) { uri = "/index.html"; } string filepath = directory.append(uri); return filepath; } } /*static*/ size_t Handler::GetFileSize(int fd) { //Fill in this buffer with information about the file... struct stat buf; int result = fstat(fd, &buf); if (result == -1) { //Signals that an error occurred. return -1; } //st_size: total size in bytes. return buf.st_size; } /*static*/ string Handler::GetLastModified(int fd) { //Fill in this buffer with information about the file... struct stat buf; int result = fstat(fd, &buf); if (result == -1) { //Signals that an error occurred. return ""; } //st_mtime: time of last modification return GetDate(buf.st_mtime); } /*static*/ string Handler::GetContentType(string fileName) { //Plus one so it is pointing after the period. unsigned int pos = fileName.find_last_of(".") + 1; //Make sure we didn't go off the edge assert(fileName.size() > pos); string extension = fileName.substr(pos, fileName.size() - pos); return config->media(extension); } /*static*/ string Handler::GetContentLength(int fd) { //Fill in this buffer with information about the file... struct stat buf; int result = fstat(fd, &buf); if (result == -1) { //Signals that an error occurred. return ""; } //st_size: total size in bytes. return itoa(buf.st_size, 10); } void Handler::SendCode500() { HTTPResponse response; response.version("HTTP/1.1"); response.header("Server", "Lexi's Server"); response.header("Date", GetDate(time(NULL))); response.code("500"); response.phrase("Internal Server Error"); response.header("Content-Length", "47"); response.header("Content-Type", "text/html"); Send(response.str(), c); DEBUG("Internal Server Error" << endl); Send("<html><h1>500 Internal Server Error</h1></html>", c); // Exit the program exit(-1); return; }<file_sep>/Makefile # Makefile for CS 360 example code CXX= g++ -g -Wall -lrt OBJS = server.o Utils.o handler.o HTTPRequest.o HTTPResponse.o URL.o Config.o Tokenizer.o client.o LIBS= CCFLAGS= -g all: server client server: server.o Utils.o handler.o HTTPRequest.o HTTPResponse.o URL.o Config.o Tokenizer.o $(CXX) -o web server.o Utils.o handler.o HTTPRequest.o HTTPResponse.o URL.o Config.o Tokenizer.o $(LIBS) client: client.o Utils.o handler.o HTTPRequest.o HTTPResponse.o URL.o Config.o Tokenizer.o $(CXX) -o client client.o Utils.o handler.o HTTPRequest.o HTTPResponse.o URL.o Config.o Tokenizer.o $(LIBS) clean: rm -f $(OBJS) $(OBJS:.o=.d) realclean: rm -f $(OBJS) $(OBJS:.o=.d) msgd test # These lines ensure that dependencies are handled automatically. %.d: %.cc $(SHELL) -ec '$(CC) -M $(CPPFLAGS) $< \ | sed '\''s/\($*\)\.o[ :]*/\1.o $@ : /g'\'' > $@; \ [ -s $@ ] || rm -f $@' include $(OBJS:.o=.d) <file_sep>/README.md Web-Server ========== A web server in C++ that implements some of the HTTP 1.1 specification given in RFC 2616. Uses a scalable event-driven server architecture using the epoll interface to manage a set of sockets in a single thread. Syntax: -------------------------------- web -p [port] -d -t (default port is 8080. -d turns debug on. -t runs the test driver INSTEAD of the server.) Features: ------------------------------- 1. GET method 2. multiple requests on one TCP connection (In accordance with HTTP 1.1) 3. multiple hosts on one web server (In accordance with HTTP 1.1) 4. serves "/index.html" if the URI given is "/" 5. These headers: (ignores other headers) - Date (using RFC 822 / RFC 1123 format dates) - Server - Content-Type - Content-Length - Last-Modified (using RFC 822 / RFC 1123 format dates) 6. One listening socket that handles all clients' requests 7. Closes connection when client closes it 8. Closes connection when it times out 9. Timeout second can be set in .config file 10. Determines content-type of a file using its extension. (extensions must be defined in the .config file.) 11. These response codes: - 200 OK - 400 Bad Request : if the web server parses the request and the method or URI is empty, or if the request contains a host that this server doesn't handle - 403 Forbidden: if the web server does not have permission to open the requested file - 404 Not Found: if the web server cannot find the requested file - 500 Internal Server Error: if the web server encounters any other error when trying to open a file - 501 Not Implemented: if the web server does not implement the requested method 12. Reads in a config file with any number of lines of the following syntaxes: - host [name] [path] //where the document root is located for a given host. This path can be either relative "web1" or absolute "/tmp/web1". A relative path starts in the current directory, whereas an absolute path starts in the root directory. - media [ext] [type] //The MIME type to use in the Content-Type header for a document that ends in the given extension. If a document has no extension, or if its extension is not listed in the configuration file, then your server should treat it as a text/plain file. - parameter [name] [value] //time, in seconds, that a socket is allowed to be idle before it will be closed. 13. Separate cache for each socket 14. Configures each client to use non-blocking socket I/O, and continues to call recv() on the client until it returns an error code indicating that no data is available. <file_sep>/client.cc #include "client.h" int main(int argc, char **argv) { //VARIABLES string IPAddressStr; //The IP Address of the machine name given on the command line. int s; //The client socket file descriptor int port; //The port to connect to on the server string cache = ""; //The cache for the read function calls //Get arguments ProcessCommandLineArgs(argc, argv, port, IPAddressStr); DEBUG("Port: " << port << endl); DEBUG("IPAddressStr: " << IPAddressStr << endl); // create socket s = socket(PF_INET, SOCK_STREAM, 0); if (s < 0) { perror("socket"); exit(-1); } // setup socket address structure and connect to server struct sockaddr_in server; memset(&server, 0, sizeof (server)); server.sin_family = AF_INET; server.sin_port = htons(port); if (!inet_aton(IPAddressStr.c_str(), &server.sin_addr)) { perror("inet_addr() conversion error"); exit(-1); } if (connect(s, (const struct sockaddr *) &server, sizeof (server)) < 0) { perror("connect"); exit(-1); } //PARSE USER INPUT AND DO SOMETHING ABOUT IT cout << "Press enter to send a pretedermined message." << endl; while (1) { bool shouldBreak = false; HandleUserInput(shouldBreak, s, cache); if(shouldBreak) { break; } } DEBUG("Socket closed"); // Close socket close(s); return 0; } /*DONE*/ void ProcessCommandLineArgs(int argc, char ** argv, int & port, string & IPAddressStr) { int option; port = 8080; //Default. debug = false; //Default. string machineName = ""; //Default to signal to use the loopback address. // process command line options using getopt() // see "man 3 getopt" while ((option = getopt(argc, argv, "p:s:d")) != -1) { switch (option) { case 'p': port = atoi(optarg); break; case 'd': debug = true; break; case 's': machineName = optarg; break; default: //They had an option that wasn't specified cout << "client [-p port] [-s server] [-d]" << endl; perror("commandlineargs"); exit(EXIT_FAILURE); } } //If there are no more option characters, getopt() returns -1. if (equalStrings(machineName, "")) { IPAddressStr = "127.0.0.1"; } else { IPAddressStr = hostNameToIPAddress(machineName); } return; } /*DONE*/ void HandleUserInput(bool & shouldBreak, int s, string & cache) { //Get input shouldBreak = false; string userInput; getline(cin, userInput); //Send request DEBUG("Sending message" << endl); string request = "A / HTTP/1.1\r\nHost:localhost\r\nUser-Agent:client\r\nFrom: Lexi\r\n\r\n"; Send(request, s); PrintToFile("ClientOUT.txt", request); //Read Response DEBUG("Reading response" << endl); string response = read_newline(s, "\r\n\r\n", cache); HTTPResponse r; r.parse(response); string document = read_length(s, atoi(r.header("Content-Length").c_str()), cache); PrintToFile("ClientIN.txt", response.append(document)); //Break if the socket is closed if(equalStrings(response, "")) { shouldBreak = true; } return; }<file_sep>/handler.h #include <errno.h> #include <stdio.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <string> #include <iostream> #include "Utils.h" #include "HTTPRequest.h" #include "URL.h" #include "Config.h" #include "Utils.h" #include "HTTPResponse.h" #include <sys/sendfile.h> #include <sys/stat.h> #include <fcntl.h> class Handler { public: /** * Tests this class */ static bool Test(ostream & os); //Testing sub-methods static bool TestGetFilePath(ostream & os); static bool TestGetFileSize(ostream & os); static bool TestGetLastModified(ostream & os); static bool TestGetContentLength(ostream & os); static bool TestGetContentType(ostream & os); /** * Required for stl map. */ Handler(); /** * @param config pointer to the parsed config file. * @param c the client file descriptor * @post time is initialized to the current time * @post cache is initialized to "" * @post config is initialized to config * @post c is intialized to c */ Handler(Config * config, int c); /** * Dtor: Doesn't need to do anything. */ ~Handler(); /** * Copy Ctor * @post this->c = other.c * @post this->cache = other.cache * @post this->time = other.time * @post this->config = other.config */ Handler(const Handler & other); /** * Handle a client request. * * @return true if the socket is closed, else false. */ bool Handle(); /** * Gets the stored time. */ double GetTime(); /** * @pre fd is a file descriptor of a file. * @return the size of the given file, in integer form, or -1 if an error * occurred. */ static size_t GetFileSize(int fd); /** * @pre fd is a file descriptor of a file. * @return the date the file was last modified, according to the date * format of HTTP 1.1, or "" if an error occurred. */ static string GetLastModified(int fd); /** * Gets the content type for a given file by looking at the file's * extension. The fileName can have any amount of characters before * the extension. * * @pre fileName has an extension (.txt, etc.) * @pre there is at least one character after the last period in the string. * @param fileName the name of the file * @return the content type of the file, according to the config file. */ string GetContentType(string fileName); /** * @pre fd is a file descriptor of a file. * @return the size of the given file, in bytes, in string form, or "" if * an error occurred. */ static string GetContentLength(int fd); private: /** * The flag if the client socket is closed or not. */ bool closed; /** * The file descriptor of the client it will handle. */ int c; /** * The cache for this handler's associated socket. */ string cache; /** * The time at which the "handle" method was most recently called. * If it has never been called before, it will return the time its * constructor was made. */ double storedTime; /** * A pointer to the object storing the parsed configuration settings. */ Config * config; /** * Handles a HTTP request. * * @param r the request to handle. */ void HandleRequest(HTTPRequest r); /** * Handles a GET request. * * @pre r's method is GET. * @param r the request to handle. */ void HandleGETRequest(HTTPRequest r); /** * Sends a HTTPResponse with a code-500 * Internal Server Error, and signals that the program is true. * @post closed = true */ void SendCode500(); /** * Converts the request r into an absolute pathname of the requested file * on the server's machine. * * @return the absolute pathname of the requested file, or the empty string * if the config file does not have a directory associated with the * specified host. */ string GetFilePath(HTTPRequest r); }; <file_sep>/Utils.h #ifndef UTILS_H #define UTILS_H #include <string> #include <errno.h> #include <cassert> #include <stdio.h> #include <algorithm> #include <arpa/inet.h> #include <netdb.h> #include <netinet/in.h> #include <stdlib.h> #include <sys/socket.h> #include <iostream> #include <cstring> #include <fstream> using namespace std; /** * For use in the DEBUG macro. It is defined wherever the program parses the debug flag. */ extern bool debug; /** * Syntax: DEBUG(stringToPrint); * Output: Prints the file name and line number, followed by the stringToPrint, to standard output * if the debug flag is set to true. */ #define DEBUG(str) if(debug) do {std::cout << "[" << __FILE__ << ", " << __LINE__ << "] " << str << flush;}while(false) /** * Syntax: TEST(boolean) * The boolean is something that you want to be true. If it is not, then it will write * "Test Failed [Filename, Line#]" to standard output. */ #define TEST(cond) \ do {\ if (!(cond)) {\ success = false; cout << "Test Failed [" << __FILE__ << ", " << __LINE__ << "]" << endl;\ }\ }while(false) /** * Tests the Utils.cc file. */ bool TestUtils(ostream & os); /** * TEST FUNCTIONS * Each of these tests the function indicated. */ bool TestHasSubstring(ostream & os); bool Testremove_newline(ostream & os); bool TestGetDate(ostream & os); /** * @return true if s1.compare(s1) == 0. I.e., they are the exact same string. */ bool equalStrings(string s1, string s2); /** * @pre str does not start with a whitespace character. * @pre str ends with a whitespace. * @pre str has at least 1 "word" where a word is a grouping of consecutive * non-whitespace characters. * @return first non-whitespace part of the string. */ string firstWord(const string & str); /** * @pre str does not start with a whitespace character. * @pre str ends with a whitespace. * @pre str has at least 2 "words" where a word is a grouping of consecutive * non-whitespace characters. * @return second non-whitespace part of the string. */ string secondWord(const string & str); /** * @pre str does not start with a whitespace character. * @pre str ends with a whitespace. * @pre str has at least 3 "words" where a word is a grouping of consecutive * non-whitespace characters. * @return third non-whitespace part of the string. */ string thirdWord(const string & str); /** * @pre str does not start with a whitespace character. * @pre str ends with a whitespace. * @pre str has at least 4 "words" where a word is a grouping of consecutive * non-whitespace characters. * @return third non-whitespace part of the string. */ string fourthWord(const string & str); /** * Completely sends a message over a socket, unless there was an * error. It does not handle the errors. You have no way of knowing if * this function call had an error or not. * * @pre "socket" is in a connected state. * @param socket the socket which you want to send the message with. * @param message what you want to send over the socket. */ void Send(string message, int socket); /** * Read from a socket until a sentinel is reached. * It will return all the characters, up to AND INCLUDING the sentinel. * If an error occurred or the socket is closed, then this function will return * the empty string. * Note: The sentinel cannot be empty, so the string will be at least one * character. * * @param s the socket file descriptor * @param sentinel the sentinel * @param cache it will append read chars to this and search for the sentinel, and once it * finds the sentinel, the cache will consist solely of the remaining characters after the sentinel. * @return a string of chars from the socket, up to and including the sentinel. Returns empty string * if the socket is closed. * @pre the sentinel cannot be the empty string. * @pre the socket must be ready to call "recv." */ string read_newline(int socket, string sentinel, string & cache); /** * Read from a socket for a specified length. * If an error occurred or the socket is closed, then this function will return * the empty string. * * @pre the socket must be ready to call "recv." * @pre length must be > 0 in order to differentiate an error from a correct thing. * @param s the socket file descriptor * @param length the number of chars you want to read * @param cache it will append read chars to this until it reaches the appropriate length, * and then it will return what was in the cache before and the chars needed to reach the * appropriate length, and THEN the cache will consist of the excess characters. * @return a string of "length" chars from the socket. Returns an empty string if the socket is closed. */ string read_length(int socket, unsigned int length, string & cache); /** * C++ version 0.4 std::string style "itoa": * Contributions from <NAME>, <NAME>, * <NAME>, <NAME>, <NAME> * and <NAME> */ string itoa(int value, int base); /** * Converts a host name into an IP Address string in the 4-dot formation. * Chooses the first IPAddress on the list (doesn't randomize). * * @param host the host name * @return an IP Address of that host in 4-dot formation. If there is no such * host name, it returns an empty string, "". */ string hostNameToIPAddress(string host); /** * The exact same as "getline(istream & is, string & str", * but it does not discard the delimiter. */ void myGetLine(istream & is, string & str); bool hasOneWord(const string & str); bool hasTwoWords(const string & str); bool hasThreeWords(const string & str); bool hasFourWords(const string & str); /** * Gets the current time. The unit is SECONDS. But it's a double * so it has a fraction with it. */ double GetCurrentTime(); /** * Determines if the string has a given substring. * * @param str the string in question * @param substr the substring in question * @return true if str contains the given substring within it. */ bool HasSubstring(string str, string substring); /** * Takes off the front of a string, up to and including the sentinel, * and returns it. * * @pre sentinel is a substring of str. * @pre sentinel is not the empty string * @post str has all of the characters removed from the beginning, up to and * including the sentinel. * @return a substring of str, starting at position 0, up to and including the sentinel. */ string remove_newline(string & str, const string & sentinel); /** * Removes all the chars up to and including the sentinel, * off of the given string. * * @pre sentinel is a substring of string * @pre sentinel is not the empty string * @post str has all the chars up to and including the sentinel removed. * @param str the string * @param sentinel the sentinel * @param pos the position of the first character of the sentinel in str. * (AKA The result of str.find(sentinel).) */ void ChopOffFrontOfString(string & str, string & sentinel, int pos); /** * Read from a socket until it would have blocked. * It will return all the characters read. * If an error occurred it will exit the program. * If the socket is closed, the closed flag will be true. * * @pre the socket must be ready to call "recv." * @param socket the socket file descriptor * @param closed a status flag, true if the socket is closed. * @return All the characters read that were available without having to block. */ string read_all_available(int socket, bool & closed); /** * Converts the given time into a date format compliant with HTTP/1.1 * Date header syntax and last-modified header syntax. * Taken from the CS360 slides. * * @param t the time you want to convert * @return the newly-formated date */ string GetDate(time_t t); /** * Prints the given string to the given file. If it doesn't open, then * it prints a debugging message. * * @param fileName the file to print to * @param WhatToPrint the */ void PrintToFile(char * fileName, string WhatToPrint); #endif /* UTILS_H */ <file_sep>/server.cc #include "server.h" /*DONE*/ int main(int argc, char **argv) { //My variables: int port; map<int, Handler> handlerMap; //Set up Config-related variables: Config config; Config * p_config = &config; config.parse("web.conf"); int timeout = atoi(config.parameter("timeout").c_str()); //Process Command line args ProcessCommandLineArgs(argc, argv, port); //Run test driver instead of actual program if it is indicated. if (test) { TestEverything(); return 0; } //Set up listening socket int s = SetUpListeningSocket(port); DEBUG("listening socket: " << s << endl); //Make epoller int epfd = epoll_create(1); //Add listening socket to poller AddSocketToPoller(epfd, s); //LOOP FOREVER. while (1) { // Do poll. struct epoll_event events[MAX_EVENTS]; int numberOfReadySockets = DoPoll(epfd, events, MAX_EVENTS); //For each index of ready sockets... for (int i = 0; i < numberOfReadySockets; i++) { //Get the ready socket's fd and handle the listening socket one way, //and the client sockets a different way. int readySocket = events[i].data.fd; if (readySocket == s) { //Accept new client int c = accept(s, NULL, NULL); if (c < 0) { perror("accept"); //Poll again. break; } DEBUG("Accepted new client: " << c << endl); //Add new client to the handler map and to the epoller. AddSocketToPoller(epfd, c); Handler h(p_config, c); //<----- gets the current time set here. handlerMap[c] = h; DEBUG("Handler map size: " << handlerMap.size() << endl); } else { HandleReadySocket(readySocket, handlerMap, epfd, config); //^--- sets current time here } } //Time out idle sockets TimeOutSockets(epfd, handlerMap, timeout); } } /*DONE*/ void ProcessCommandLineArgs(int argc, char ** argv, int & port) { int option; port = 8080; //Default. // process command line options using getopt() // see "man 3 getopt" while ((option = getopt(argc, argv, "p:dt")) != -1) { switch (option) { case 'p': port = atoi(optarg); if (port == 0) { cout << "server -p port [-d]" << endl; perror("commandLineArgs"); exit(EXIT_FAILURE); } break; case 'd': debug = true; //global variable. break; case 't': test = true; //global variable break; default: //They had an option that wasn't specified cout << "server -p port [-d]" << endl; perror("commandLineArgs"); exit(EXIT_FAILURE); } } //If there are no more option characters, getopt() returns -1. } /*DONE*/ int SetUpListeningSocket(int port) { //Variables: struct sockaddr_in server; int s; // setup socket address structure memset(&server, 0, sizeof (server)); server.sin_family = AF_INET; server.sin_port = htons(port); server.sin_addr.s_addr = INADDR_ANY; // create socket s = socket(PF_INET, SOCK_STREAM, 0); if (!s) { perror("socket"); exit(-1); } // set socket to immediately reuse port when the application closes int opt = 1; if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof (opt)) < 0) { perror("setsockopt"); exit(-1); } // call bind to associate the socket with our local address and // port if (bind(s, (const struct sockaddr *) &server, sizeof (server)) < 0) { perror("bind"); exit(-1); } // convert the socket to listen for incoming connections if (listen(s, SOMAXCONN) < 0) { perror("listen"); exit(-1); } return s; } /*DONE*/ int DoPoll(int epfd, struct epoll_event * events, int maxEvents) { int nfds = epoll_wait(epfd, events, maxEvents, 1); if (nfds < 0) { perror("epoll"); exit(EXIT_FAILURE); } return nfds; } /*DONE*/ void HandleReadySocket(int readySocket, map<int, Handler> & handlerMap, int epfd, Config config) { //Assert that the readySocket does exist in the handler map. assert(handlerMap.find(readySocket) != handlerMap.end()); //Handle the socket. bool closed = handlerMap[readySocket].Handle(); //If the socket is closed, remove it from the epoller, close the socket, //and erase it & its handler from the handler map. if (closed) { DEBUG("Boot off client: " << readySocket << endl); BootOffClient(epfd, readySocket, handlerMap); } } /*DONE*/ void TimeOutSockets(int epfd, map<int, Handler> & handlerMap, int timeout) { double currentTime = GetCurrentTime(); //Make a list of all the sockets that are timed out. list<int> timedOutFds; for (map<int, Handler>::iterator it = handlerMap.begin(); it != handlerMap.end(); it++) { //If it's been idle too long, add it to the list double mostRecentHandledTime = (*it).second.GetTime(); if ((currentTime - mostRecentHandledTime) > timeout) { DEBUG("Delay too long: " << (currentTime - mostRecentHandledTime) << endl); timedOutFds.push_back((*it).first); } } //Go through the list of timed-out sockets and boot off each one for(list<int>::iterator it = timedOutFds.begin(); it != timedOutFds.end(); it++) { BootOffClient(epfd, (*it), handlerMap); } } /*DONE*/ void BootOffClient(int epfd, int c, map<int, Handler> & handlerMap) { RemoveSocketFromPoller(epfd, c); close(c); handlerMap.erase(c); } /*DONE*/ void RemoveSocketFromPoller(int epfd, int removeThisSocket) { struct epoll_event ev; ev.events = EPOLLIN; ev.data.fd = removeThisSocket; epoll_ctl(epfd, EPOLL_CTL_DEL, removeThisSocket, &ev); } /*DONE*/ void AddSocketToPoller(int epfd, int addThisSocket) { struct epoll_event ev; ev.events = EPOLLIN; ev.data.fd = addThisSocket; epoll_ctl(epfd, EPOLL_CTL_ADD, addThisSocket, &ev); } /*INCOMPLETE*/ void TestEverything() { bool success = true; if (!Config::Test(cout)) success = false; if (!TestUtils(cout)) success = false; if (!Handler::Test(cout)) success = false; cout << "\n\n"; if (success) { cout << "Tests Succeeded!" << endl; } else { cout << "Tests Failed!" << endl; } } <file_sep>/Utils.cc #include "Utils.h" bool TestUtils(ostream & os) { bool success = true; os << " ========== TESTING Utils.cc ===============" << endl; if (!TestHasSubstring(os)) success = false; if (!Testremove_newline(os)) success = false; if (!TestGetDate(os)) success = false; return success; } /*DONE*/ bool TestHasSubstring(ostream & os) { bool success = true; os << "Testing hasSubstring..." << endl; //1. Basic test string hello = "hello"; string lo = "lo"; TEST(HasSubstring(hello, lo)); //2. Testing that the function even works on empty strings. //An empty string has no substrings at all. string emptyString = ""; TEST(!HasSubstring(emptyString, lo)); //3. Testing a case when it fails with a completely different character string a = "a"; TEST(!HasSubstring(hello, a)); //4. Fails because it checks for the WHOLE substring, not just a part. string elloo = "elloo"; TEST(!HasSubstring(hello, elloo)); return success; } bool Testremove_newline(ostream & os) { bool success = true; os << "Testing remove_newline..." << endl; //1. Test - only takes first occurrence of sentinel string hello = "hello"; string result = remove_newline(hello, "l"); TEST(equalStrings(hello, "lo")); TEST(equalStrings(result, "hel")); //2. Other test - if sentinel is not there, then assertions go off string i = "i"; //remove_newline(hello, i); //should crash - and it did. //3. Test really long thing string longString = "aaaaaaaaaaabbbbbbcccccccddddddeeeeeeeeefffffffffggggggg"; result = remove_newline(longString, "dddeeeeeeeee"); TEST(equalStrings(longString, "fffffffffggggggg")); TEST(equalStrings(result, "aaaaaaaaaaabbbbbbcccccccddddddeeeeeeeee")); //4. Test one where the result is the empty hello = "hello"; result = remove_newline(hello, "o"); TEST(equalStrings(result, "hello")); TEST(equalStrings(hello, "")); return success; } bool TestGetDate(ostream & os) { bool success = true; os << "Testing GetDate..." << endl; //Pass in time(NULL) for current time string now = GetDate(time(NULL)); os << "Curent time\nexpected: check your system's clock\nactual: " << now << endl << endl; return success; } /*DONE*/ bool equalStrings(string s1, string s2) { if (s1.compare(s2) == 0) { return true; } else { return false; } } /*DONE*/ string firstWord(const string & str) { assert(!isspace(str.at(0))); string whitespaceChars = " \t\n\v\f\r"; size_t whitespaceIndex = str.find_first_of(whitespaceChars); assert(whitespaceIndex != string::npos); return str.substr(0, whitespaceIndex); } /*DONE*/ string secondWord(const string & str) { assert(!isspace(str.at(0))); string whitespaceChars = " \t\n\v\f\r"; //abc def\n //012 456 7 //firstWSIndex = 3 size_t firstWSIndex = str.find_first_of(whitespaceChars, 0); assert(firstWSIndex != string::npos); //firstNonWSIndex = 4 size_t firstNonWSIndex = str.find_first_not_of(whitespaceChars, firstWSIndex); assert(firstNonWSIndex != string::npos); //secondWSIndex = 7 size_t secondWSIndex = str.find_first_of(whitespaceChars, firstNonWSIndex); assert(secondWSIndex != string::npos); //starts on and includes index 4, and the length is 7-4 = 3. return str.substr(firstNonWSIndex, secondWSIndex - firstNonWSIndex); } /*DONE*/ string thirdWord(const string & str) { assert(!isspace(str.at(0))); string whitespaceChars = " \t\n\v\f\r"; //abc def hij\n //012 456 8910 11 //firstWSIndex = 3 size_t firstWSIndex = str.find_first_of(whitespaceChars, 0); assert(firstWSIndex != string::npos); //firstNonWSIndex = 4 size_t firstNonWSIndex = str.find_first_not_of(whitespaceChars, firstWSIndex); assert(firstNonWSIndex != string::npos); //secondWSIndex = 7 size_t secondWSIndex = str.find_first_of(whitespaceChars, firstNonWSIndex); assert(secondWSIndex != string::npos); //secondNonWSIndex = 8 size_t secondNonWSIndex = str.find_first_not_of(whitespaceChars, secondWSIndex); assert(secondNonWSIndex != string::npos); //thirdWSIndex = 11 size_t thirdWSIndex = str.find_first_of(whitespaceChars, secondNonWSIndex); assert(thirdWSIndex != string::npos); //starts on and includes index 8, and the length is 11-8 = 3. return str.substr(secondNonWSIndex, thirdWSIndex - secondNonWSIndex); } /*DONE*/ string fourthWord(const string & str) { assert(!isspace(str.at(0))); string whitespaceChars = " \t\n\v\f\r"; //abc def hij k l \n //012 456 8910 11 12-13 14 // * first nonWS // * second nonWS // *third nonWS //firstWSIndex = 3 size_t firstWSIndex = str.find_first_of(whitespaceChars, 0); assert(firstWSIndex != string::npos); //firstNonWSIndex = 4 size_t firstNonWSIndex = str.find_first_not_of(whitespaceChars, firstWSIndex); assert(firstNonWSIndex != string::npos); //secondWSIndex = 7 size_t secondWSIndex = str.find_first_of(whitespaceChars, firstNonWSIndex); assert(secondWSIndex != string::npos); //secondNonWSIndex = 8 size_t secondNonWSIndex = str.find_first_not_of(whitespaceChars, secondWSIndex); assert(secondNonWSIndex != string::npos); //thirdWSIndex = 11 size_t thirdWSIndex = str.find_first_of(whitespaceChars, secondNonWSIndex); assert(thirdWSIndex != string::npos); //thirdNonWSIndex = 12 size_t thirdNonWSIndex = str.find_first_not_of(whitespaceChars, thirdWSIndex); assert(thirdNonWSIndex != string::npos); //fourthWSIndex = 14 size_t fourthWSIndex = str.find_first_of(whitespaceChars, thirdNonWSIndex); assert(fourthWSIndex != string::npos); //starts on and includes index 12, and the length is 14-12 = 2. return str.substr(thirdNonWSIndex, fourthWSIndex - thirdNonWSIndex); } /*DONE*/ void Send(string message, int socket) { //Leave early if it's trying to send an empty string. if (message.compare("") == 0) { DEBUG("Tried to send empty string." << endl); return; } const char * ptr = message.c_str(); int nleft = message.size(); int nwritten = -1; //While you have more of the message to send... keep sending. while (nleft) { //"send": On success, it returns the number of characters sent. On //error, -1 is returned, and errno is set appropriately. if ((nwritten = send(socket, ptr, nleft, 0)) < 0) { if (errno == EINTR) { // the socket call was interrupted -- try again continue; } else { // an error occurred, so break out perror("write"); break; } } else if (nwritten == 0) { // the socket is closed break; } //Update the number of characters left so the while loop knows when to stop nleft -= nwritten; //Update the pointer to point at the next part of the string that you need to send. ptr += nwritten; } } /*DONE*/ string read_newline(int socket, string sentinel, string & cache) { //I make the assumption that a char is one byte. assert(sizeof (char) == 1); //Sentinel cannot be empty or it's useless. assert(sentinel.compare("") != 0); //------------- VARIABLES ------------------------- int numberBytesRead = 0; size_t sentinelPosition = 0; //Allocate a buffer char * buf = (char *) calloc(1024, sizeof (char)); //------------------------------------------------ //Loop forever until you reach the sentinel (then return it) or there //was an error or the socket closed (which returns ""). while (1) { //If we've reached the sentinel, then return the the message up to and //including the sentinel, and leave the remaining characters (if //applicable) in the static "message" string for next time. //NOTE: "find" returns the position of the first occurrence in the string of the searched content. //If the content is not found, the member value npos is returned. //(If the sentinel is more than one character, it returns the position [index starting at 0] of the //first character of the sentinel.) sentinelPosition = cache.find(sentinel); //If the sentinel has been reached... if (sentinelPosition != string::npos) { //substr(pos, n): character sequence that starts at character position //pos and has a length of n characters. int totalLengthOfMessage = sentinel.size() + sentinelPosition; string returnString = cache.substr(0, totalLengthOfMessage); cache = cache.substr(totalLengthOfMessage, cache.size() - totalLengthOfMessage); //Free up the allocated space and null the invalid pointer for good habit. free(buf); buf = NULL; return returnString; } //About "recv": Returns the # of bytes received, or -1 if an error //occurred. Returns 0 when the peer has performed an orderly shutdown. //If no messages are available at the socket, the receive calls wait for //a message to arrive, unless the socket is non-blocking. //PUT CHARACTERS FROM SOCKET INTO THE BUFFER... //1024 is an arbitrary decision. numberBytesRead = recv(socket, buf, 1024, 0); if (numberBytesRead < 0) { if (errno == EINTR) { //the socket call was interrupted -- try again //Free up the allocated space and null the invalid pointer for good habit. free(buf); buf = NULL; DEBUG("continue" << endl); continue; } else { //an error occurred, so break out //Free up the allocated space and null the invalid pointer for good habit. free(buf); buf = NULL; DEBUG("Error: exit the program" << endl); perror("recv"); exit(-1); } } else if (numberBytesRead == 0) { //the socket is closed //Free up the allocated space and null the invalid pointer for good habit. free(buf); buf = NULL; DEBUG("Socket closed: return \"\"" << endl); return ""; } //APPEND THE BUFFER CHARS (THAT WERE JUST READ) TO THE MESSAGE //Appends a copy of the string formed by the first n characters in the array //of characters pointed by s. (const char * s, size_t n) cache.append(buf, numberBytesRead); } } /*DONE*/ string read_length(int socket, unsigned int length, string & cache) { //I make the assumption that a char is one byte. assert(sizeof (char) == 1); assert(length > 0); //------------- VARIABLES ------------------------- int numberBytesRead = 0; //Allocate a buffer char * buf = (char *) calloc(1024, sizeof (char)); //------------------------------------------------ //Loop forever until you've read enough characters (then return it) or there //was an error or the socket closed (which returns ""). while (1) { //If we've read enough characters to return a substring with the intended //characters, then return the intended length of characters, and leave //the remaining characters (if applicable) in the static "message" string //for next time. if (cache.size() >= length) { //substr(pos, n): character sequence that starts at character position //pos and has a length of n characters. string returnString = cache.substr(0, length); cache = cache.substr(length, cache.size() - length); //Free up the allocated space and null the invalid pointer for good habit. free(buf); buf = NULL; return returnString; } //About "recv": Returns the # of bytes received, or -1 if an error //occurred. Returns 0 when the peer has performed an orderly shutdown. //If no messages are available at the socket, the receive calls wait for //a message to arrive, unless the socket is non-blocking. //PUT CHARACTERS FROM SOCKET INTO THE BUFFER... //1024 is an arbitrary decision. numberBytesRead = recv(socket, buf, 1024, 0); if (numberBytesRead < 0) { if (errno == EINTR) { //the socket call was interrupted -- try again //Free up the allocated space and null the invalid pointer for good habit. free(buf); buf = NULL; DEBUG("continue" << endl); continue; } else { //an error occurred, so break out //Free up the allocated space and null the invalid pointer for good habit. free(buf); buf = NULL; DEBUG("Error: exit the program" << endl); perror("recv"); exit(-1); } } else if (numberBytesRead == 0) { //the socket is closed //Free up the allocated space and null the invalid pointer for good habit. free(buf); buf = NULL; DEBUG("Socket closed: return \"\"" << endl); return ""; } //APPEND THE BUFFER CHARS (THAT WERE JUST READ) TO THE MESSAGE... //Appends a copy of the string formed by the first n characters in the array //of characters pointed by s. (const char * s, size_t n) cache.append(buf, numberBytesRead); } } /*DONE*/ string itoa(int value, int base) { std::string buf; // check that the base if valid if (base < 2 || base > 16) return buf; enum { kMaxDigits = 35 }; buf.reserve(kMaxDigits); // Pre-allocate enough space. int quotient = value; // Translating number to string with base: do { buf += "0123456789abcdef"[ std::abs(quotient % base) ]; quotient /= base; } while (quotient); // Append the negative sign if (value < 0) buf += '-'; std::reverse(buf.begin(), buf.end()); return buf; } /*DONE*/ string hostNameToIPAddress(string host) { DEBUG("host: " << host << endl); // use DNS to get host name struct hostent *hostEntry; hostEntry = gethostbyname(host.c_str()); if (!hostEntry) { cout << "No such host name: " << host << endl; perror("DNS"); exit(-1); } //Choose the first IP Address. string IPAddress = inet_ntoa(*(struct in_addr *) hostEntry->h_addr_list[0]); DEBUG("IPAddress: " << IPAddress << endl); return IPAddress; } /*DONE*/ void myGetLine(istream & is, string & str) { getline(is, str); str += "\n"; } /*DONE*/ bool hasOneWord(const string & str) { if ((!isspace(str.at(0))) == false) { return false; } string whitespaceChars = " \t\n\v\f\r"; size_t whitespaceIndex = str.find_first_of(whitespaceChars); if ((whitespaceIndex != string::npos) == false) { return false; } return true; } /*DONE*/ bool hasTwoWords(const string & str) { if ((!isspace(str.at(0))) == false) { return false; } string whitespaceChars = " \t\n\v\f\r"; //abc def\n //012 456 7 //firstWSIndex = 3 size_t firstWSIndex = str.find_first_of(whitespaceChars, 0); if ((firstWSIndex != string::npos) == false) { return false; } //firstNonWSIndex = 4 size_t firstNonWSIndex = str.find_first_not_of(whitespaceChars, firstWSIndex); if ((firstNonWSIndex != string::npos) == false) { return false; } //secondWSIndex = 7 size_t secondWSIndex = str.find_first_of(whitespaceChars, firstNonWSIndex); if ((secondWSIndex != string::npos) == false) { return false; } //starts on and includes index 4, and the length is 7-4 = 3. return true; } /*DONE*/ bool hasThreeWords(const string & str) { if ((!isspace(str.at(0))) == false) { return false; } string whitespaceChars = " \t\n\v\f\r"; //abc def hij\n //012 456 8910 11 //firstWSIndex = 3 size_t firstWSIndex = str.find_first_of(whitespaceChars, 0); if ((firstWSIndex != string::npos) == false) { return false; } //firstNonWSIndex = 4 size_t firstNonWSIndex = str.find_first_not_of(whitespaceChars, firstWSIndex); if ((firstNonWSIndex != string::npos) == false) { return false; } //secondWSIndex = 7 size_t secondWSIndex = str.find_first_of(whitespaceChars, firstNonWSIndex); if ((secondWSIndex != string::npos) == false) { return false; } //secondNonWSIndex = 8 size_t secondNonWSIndex = str.find_first_not_of(whitespaceChars, secondWSIndex); if ((secondNonWSIndex != string::npos) == false) { return false; } //thirdWSIndex = 11 size_t thirdWSIndex = str.find_first_of(whitespaceChars, secondNonWSIndex); if ((thirdWSIndex != string::npos) == false) { return false; } //starts on and includes index 8, and the length is 11-8 = 3. return true; } /*DONE*/ bool hasFourWords(const string & str) { if (!isspace(str.at(0)) == false) { return false; } string whitespaceChars = " \t\n\v\f\r"; //abc def hij k l \n //012 456 8910 11 12-13 14 // * first nonWS // * second nonWS // *third nonWS //firstWSIndex = 3 size_t firstWSIndex = str.find_first_of(whitespaceChars, 0); if ((firstWSIndex != string::npos) == false) { return false; } //firstNonWSIndex = 4 size_t firstNonWSIndex = str.find_first_not_of(whitespaceChars, firstWSIndex); if ((firstNonWSIndex != string::npos) == false) { return false; } //secondWSIndex = 7 size_t secondWSIndex = str.find_first_of(whitespaceChars, firstNonWSIndex); if ((secondWSIndex != string::npos) == false) { return false; } //secondNonWSIndex = 8 size_t secondNonWSIndex = str.find_first_not_of(whitespaceChars, secondWSIndex); if ((secondNonWSIndex != string::npos) == false) { return false; } //thirdWSIndex = 11 size_t thirdWSIndex = str.find_first_of(whitespaceChars, secondNonWSIndex); if ((thirdWSIndex != string::npos) == false) { return false; } //thirdNonWSIndex = 12 size_t thirdNonWSIndex = str.find_first_not_of(whitespaceChars, thirdWSIndex); if ((thirdNonWSIndex != string::npos) == false) { return false; } //fourthWSIndex = 14 size_t fourthWSIndex = str.find_first_of(whitespaceChars, thirdNonWSIndex); if ((fourthWSIndex != string::npos) == false) { return false; } return true; } /*DONE*/ double GetCurrentTime() { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); double time = ts.tv_sec + ts.tv_nsec / 1000000000.0; return time; } /*DONE*/ bool read_once(int socket, string & cache) { //I make the assumption that a char is one byte. assert(sizeof (char) == 1); //------------- VARIABLES ------------------------- int numberBytesRead = 0; //Allocate a buffer char * buf = (char *) calloc(1024, sizeof (char)); //------------------------------------------------ //About "recv": Returns the # of bytes received, or -1 if an error //occurred. Returns 0 when the peer has performed an orderly shutdown. //If no messages are available at the socket, the receive calls wait for //a message to arrive, unless the socket is non-blocking. //PUT CHARACTERS FROM SOCKET INTO THE BUFFER... //1024 is an arbitrary decision. numberBytesRead = recv(socket, buf, 1024, 0); if (numberBytesRead < 0) { if (errno == EINTR) { //Free up the allocated space and null the invalid pointer for good habit. free(buf); buf = NULL; //Socket is still open, although it was interrupted. return true; } else { //an error occurred, so break out //Free up the allocated space and null the invalid pointer for good habit. free(buf); buf = NULL; DEBUG("Error: exit the program" << endl); perror("recv"); exit(-1); } } else if (numberBytesRead == 0) { //the socket is closed //Free up the allocated space and null the invalid pointer for good habit. free(buf); buf = NULL; DEBUG("Socket closed" << endl); return false; } //APPEND THE BUFFER CHARS TO THE MESSAGE //Appends a copy of the string formed by the first n characters in the array //of characters pointed by s. (const char * s, size_t n) cache.append(buf, numberBytesRead); //Free up the allocated space and null the invalid pointer for good habit. free(buf); buf = NULL; return true; } /*INCOMPLETE*/ bool HasSubstring(string str, string substring) { if (str.find(substring) == string::npos) { return false; } else { return true; } } /*DONE*/ string remove_newline(string & str, const string & sentinel) { assert(HasSubstring(str, sentinel)); assert(!equalStrings(str, "")); //----------Store the first part in a string-------- int sentinelPosition = str.find(sentinel); //substr(pos, n): character sequence that starts at character position //pos and has a length of n characters. int totalLengthOfMessage = sentinel.size() + sentinelPosition; string returnString = str.substr(0, totalLengthOfMessage); //---------Remove the first part from the original string-------- str = str.substr(totalLengthOfMessage, str.size() - totalLengthOfMessage); return returnString; } /*DONE*/ string read_all_available(int socket, bool & closed) { //I make the assumption that a char is one byte. assert(sizeof (char) == 1); //------------- VARIABLES ------------------------- int numberBytesRead = 0; closed = false; //Default string cache; //Allocate a buffer char * buf = (char *) calloc(1024, sizeof (char)); //------------------------------------------------ //Loop forever until it would have blocked, //if there's an error, or if the socket is closed (which returns ""). while (1) { //About "recv": Returns the # of bytes received, or -1 if an error //occurred. Returns 0 when the peer has performed an orderly shutdown. //If no messages are available at the socket, the receive calls wait for //a message to arrive, unless the socket is non-blocking. //PUT CHARACTERS FROM SOCKET INTO THE BUFFER... //1024 is an arbitrary decision. numberBytesRead = recv(socket, buf, 1024, MSG_DONTWAIT); if (numberBytesRead < 0) { if (errno == EINTR) { //the socket call was interrupted -- try again //Free up the allocated space and null the invalid pointer for good habit. free(buf); buf = NULL; continue; } else if (errno == EAGAIN || errno == EWOULDBLOCK) { return cache; } else { //an error occurred, so break out //Free up the allocated space and null the invalid pointer for good habit. free(buf); buf = NULL; DEBUG("Error: exit the program" << endl); perror("recv"); exit(-1); } } else if (numberBytesRead == 0) { //the socket is closed //Free up the allocated space and null the invalid pointer for good habit. free(buf); buf = NULL; closed = true; return cache; } //APPEND THE BUFFER CHARS (THAT WERE JUST READ) TO THE MESSAGE //Appends a copy of the string formed by the first n characters in the array //of characters pointed by s. (const char * s, size_t n) cache.append(buf, numberBytesRead); } } /*DONE*/ string GetDate(time_t t) { struct tm *gmt; char buf [200]; memset(buf, 0, 200); gmt = gmtime(&t); if (gmt == NULL) { return ""; } if (strftime(buf, sizeof (buf), "%a, %d %b %Y %H:%M:%S GMT", gmt) == 0) { return ""; } return string(buf); } void PrintToFile(char * fileName, string WhatToPrint) { ofstream outputFile; outputFile.open(fileName, ios_base::trunc); if (outputFile.is_open()) { outputFile << WhatToPrint << endl << endl; } else { DEBUG("Failed to open output file." << endl); } outputFile.close(); return; }<file_sep>/client.h #ifndef CLIENT_H #define CLIENT_H #include <arpa/inet.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <fstream> #include <iostream> #include "Utils.h" #include "HTTPResponse.h" using namespace std; /** * Debug flag. If it is set to true, then the DEBUG-macro-statements will print out. */ bool debug; /** * Sets up a client that connects to the machine name arg specified by -s and port arg specified by -p * with an optional debug option (-d). Then it reads input from the user and handles it somehow, specified * by the function HandleUserInput. */ int main(int argc, char **argv); /** * * * @param argc the argc argument passed to "main" from the terminal * @param argv the argv argument passed to "main" from the terminal * @param port reference to the int which will be set with the port to which the client will connect. * @param IPAddressStr where to store the IP Address of the machine name * @post if the -d flag exists, debug will be set to true. Otherwise, it will be set to false. * @post the port number from "-p [port]" will be stored in port. If not specified, port will * be set to a default value of 3000. */ void ProcessCommandLineArgs(int argc, char ** argv, int & port, string & IPAddressStr); /** * Reads from the socket and handles it. * Currently: Sends a GET request to the server whenever the user presses enter. * Reads response * * @param shouldBreak will be set to true if it should break, false otherwise. * @param s the socket of the client * @param cache the cache of the client */ void HandleUserInput(bool & shouldBreak, int s, string & cache); #endif /* CLIENT_H */
5e3fbf5aefd7f44efcade29b1f9b1b3d491f9388
[ "Markdown", "Makefile", "C++" ]
11
C++
shinyT/Web-Server
dd864a3828faa8665abdbd8230d63196a72670cc
844ff88246bd3bf67f734f9ad812e2f583fc4a99
refs/heads/master
<repo_name>afeiship/react-native-country-code-picker<file_sep>/src/components/list-header.js import { View } from 'react-native'; import style from './style'; export default class extends Component { render() { const { title } = this.props; return ( <View style={style.header.view}> <Text style={style.header.text}>{ title }</Text> </View> ); } } <file_sep>/src/components/list-item.js import { Text, TouchableOpacity } from 'react-native'; import style from './style'; export default class extends Component { render() { const { countryName, phoneCode } = this.props.item; return ( <TouchableOpacity style={style.cell.view}> <Text style={style.cell.text}>{countryName}({phoneCode})</Text> </TouchableOpacity> ); } } <file_sep>/README.md # react-native-country-code-picker > Country code picker for react native <file_sep>/src/components/section-item.js import { Text } from 'react-native'; import style from './style'; export default class extends Component { render() { const { title } = this.props; return ( <Text style={style.section.item}>{title}</Text> ); } }
83aabada361864999ed92648342dcb75ab456013
[ "JavaScript", "Markdown" ]
4
JavaScript
afeiship/react-native-country-code-picker
17c30340b2790e0febd7cbc71a9e737ce2087ce3
b31d76aae45e3b937e2ce56907d0e5e34dc27eb4
refs/heads/master
<file_sep>package com.revature.services; import com.revature.daos.ReimbursementStatusDAO; import com.revature.daos.ReimbursementStatusDAOImpl; import com.revature.models.ReimbursementStatus; public class ReimbursementStatusService { private static ReimbursementStatusDAO reimbursementStatusDao = new ReimbursementStatusDAOImpl(); public ReimbursementStatus findReimbursementByStatus(int reimbStatusID) { return reimbursementStatusDao.findReimbursementByStatus(reimbStatusID); } } <file_sep>package com.revature.utils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class ConnectionUtil { public static Connection getConnection() throws SQLException { //For many frameworks using JDBC it is necessary to "register" the driver in order for the framework to be aware of it. try { Class.forName("org.postgresql.Driver"); }catch (ClassNotFoundException e) { e.printStackTrace(); } String url = "jdbc:postgresql://training-db.czhqtlklzwf7.us-east-2.rds.amazonaws.com:5432/postgres"; String user = "postgres"; //It is possible to use environment variables to hide this information String pass = "<PASSWORD>"; return DriverManager.getConnection(url, user, pass); } } <file_sep>DROP TABLE IF EXISTS ers_reimbursement; DROP TABLE IF EXISTS ers_reimbursement_status; DROP TABLE IF EXISTS ers_reimbursement_type; DROP TABLE IF EXISTS ers_users; DROP TABLE IF EXISTS ers_user_roles; CREATE TABLE ers_reimbursement( reimb_id SERIAL PRIMARY KEY, reimb_amount numeric(20,2) NOT NULL, reimb_submitted timestamp DEFAULT current_timestamp, reimb_resolved timestamp, reimb_description varchar(250), reimb_receipt bytea, reimb_author integer NOT NULL REFERENCES ers_users(ers_user_id), reimb_resolver integer REFERENCES ers_users(ers_user_id), reimb_status_id integer NOT NULL REFERENCES ers_reimbursement_status(reimb_status_id), reimb_type_id integer NOT NULL REFERENCES ers_reimbursement_type(reimb_type_id) ) CREATE TABLE ers_users( ers_user_id SERIAL PRIMARY KEY, ers_username varchar(50) UNIQUE, ers_password varchar(64) NOT NULL, user_first_name varchar(100) NOT NULL, user_last_name varchar(100) NOT NULL, user_email varchar(150) UNIQUE NOT NULL, user_role_id integer NOT NULL REFERENCES ers_user_roles(ers_user_role_id) ) CREATE TABLE ers_reimbursement_status( reimb_status_id integer NOT NULL PRIMARY KEY, reimb_status varchar(10) NOT NULL ) CREATE TABLE ers_reimbursement_type( reimb_type_id integer NOT NULL PRIMARY KEY, reimb_type varchar(10) NOT NULL ) CREATE TABLE ers_user_roles( ers_user_role_id integer NOT NULL PRIMARY KEY, user_role varchar(10)NOT NULL ) INSERT INTO ers_reimbursement_status(reimb_status_id, reimb_status) VALUES (1, 'PENDING'), (2, 'APPROVED'), (3, 'DENIED'); INSERT INTO ers_reimbursement_type(reimb_type_id, reimb_type) VALUES (1, 'LODGING'), (2, 'TRAVEL'), (3, 'MEDICAL'), (4, 'BUSINESS'), (5, 'OTHER'); INSERT INTO ERS_USER_ROLES (ers_user_role_id, user_role) VALUES (1, 'EMPLOYEE'), (2, 'ADMIN'); INSERT INTO ers_users(ers_username, ers_password, user_first_name, user_last_name, user_email, user_role_id) VALUES ('asdf', 'asdf', 'as', 'df', '<EMAIL>', 1); INSERT INTO ers_users(ers_username, ers_password, user_first_name, user_last_name, user_email, user_role_id) VALUES ('profoak', '<PASSWORD>', 'Professor', 'Oak', '<EMAIL>', 2); INSERT INTO ERS_REIMBURSEMENT (reimb_amount, reimb_description, reimb_author, reimb_status_id, reimb_type_id ) VALUES (100, 'travel to town', 1, 1, 2); INSERT INTO ERS_REIMBURSEMENT (reimb_amount, reimb_description, reimb_author, reimb_status_id, reimb_type_id ) VALUES (100, 'got hurt working hard', 1, 1, 3); INSERT INTO ERS_REIMBURSEMENT (reimb_amount, reimb_description, reimb_author, reimb_status_id, reimb_type_id ) VALUES (2000, 'had to buy some pokeballs', 1, 1, 4);<file_sep>const URL = 'http://localhost:8080/project1/' let submitButton = document.getElementById("submit"); submitButton.onclick = addUser; function getUserInfo(){ let firstname = document.getElementById("firstname").value; let lastname = document.getElementById("lastname").value; let newEmail = document.getElementById("email").value; let username = document.getElementById("username").value; let password = document.getElementById("password").value; let user = { firstName:firstname, lastName:lastname, email:newEmail, userName:username, pass:<PASSWORD> } return user; } async function addUser(){ let user = getUserInfo(); let response = await fetch(URL + 'login' , { method:'POST', body:JSON.stringify(user) }) if(response.status===201){ console.log("User successfully created") }else{ console.log("Something went wrong trying to create the new user") } }<file_sep>const URL = 'http://localhost:8080/project1/' let<file_sep>package com.revature.daos; import java.util.List; import com.revature.models.UserRole; public class UserRoleDAOImpl implements UserRoleDAO{ @Override public UserRole getUserRoleByUserRoleID(int userRoleID) { // TODO Auto-generated method stub return null; } } <file_sep>package com.revature.web; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.revature.controllers.ReimbursementController; import com.revature.controllers.UserController; public class FrontControllerServlet extends HttpServlet{ UserController userController = new UserController(); ReimbursementController reimbController = new ReimbursementController(); @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ response.setContentType("application/json"); response.setStatus(404); final String URL = request.getRequestURI().replace("/project1/", ""); System.out.println(URL); String[] urlSections = URL.split("/"); if(request.getMethod().equals("POST")) { switch(urlSections[0]) { case "signUp": try { userController.addUser(request, response); } catch (NoSuchAlgorithmException | InvalidKeySpecException | IOException e) { e.printStackTrace(); } break; case "login": if(urlSections.length == 1) { userController.login(request, response); } break; case "signOut": userController.logout(request, response); break; case "employee": if(urlSections[1].equals("submit")) { if(urlSections.length > 2) { reimbController.getReimbursementType(request, response); }else { reimbController.submitRequest(request, response); } }else if(urlSections[1].equals("pending")) { reimbController.pendingEmployeeRequest(request, response); }else if(urlSections[1].equals("past")) { reimbController.pastRequests(request,response); } break; case "manager": if(urlSections[1].equals("all")) { reimbController.getAllReimbursements(request, response); }else if(urlSections[1].equals("approve")) { reimbController.approveReimbursement(request, response, urlSections[3]); }else if(urlSections[1].equals("deny")) { reimbController.denyReimbursement(request, response, urlSections[3]); }else if(urlSections[1].equals("pending")) { reimbController.pendingRequest(request, response, urlSections[3]); } break; } } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } } <file_sep>package com.revature.models; import java.sql.Timestamp; public class Reimbursement { protected int reimbursementID; protected double reimbursementAmount; protected Timestamp reimbursementSubmitted; protected Timestamp reimbursementResolved; protected String reimburementDescription; protected byte reimbursementReceipt; protected int reimbursementAuthor; protected int reimbursementResolver; protected int reimbursementStatusID; protected int reimbursementTypeID; public Reimbursement(int reimbursementID, double reimbursementAmount, Timestamp reimbursementSubmitted, Timestamp reimbursementResolved, String reimburementDescription, byte reimbursementReceipt, int reimbursementAuthor, int reimbursementResolver, int reimbursementStatusID, int reimbursementTypeID) { super(); this.reimbursementID = reimbursementID; this.reimbursementAmount = reimbursementAmount; this.reimbursementSubmitted = reimbursementSubmitted; this.reimbursementResolved = reimbursementResolved; this.reimburementDescription = reimburementDescription; this.reimbursementReceipt = reimbursementReceipt; this.reimbursementAuthor = reimbursementAuthor; this.reimbursementResolver = reimbursementResolver; this.reimbursementStatusID = reimbursementStatusID; this.reimbursementTypeID = reimbursementTypeID; } public Reimbursement() { super(); } public int getReimbursementID() { return reimbursementID; } public void setReimbursementID(int reimbursementID) { this.reimbursementID = reimbursementID; } public double getReimbursementAmount() { return reimbursementAmount; } public void setReimbursementAmount(double reimbursementAmount) { this.reimbursementAmount = reimbursementAmount; } public Timestamp getReimbursementSubmitted() { return reimbursementSubmitted; } public void setReimbursementSubmitted(Timestamp reimbursementSubmitted) { this.reimbursementSubmitted = reimbursementSubmitted; } public Timestamp getReimbursementResolved() { return reimbursementResolved; } public void setReimbursementResolved(Timestamp reimbursementResolved) { this.reimbursementResolved = reimbursementResolved; } public String getReimburementDescription() { return reimburementDescription; } public void setReimburementDescription(String reimburementDescription) { this.reimburementDescription = reimburementDescription; } public byte getReimbursementReceipt() { return reimbursementReceipt; } public void setReimbursementReceipt(byte reimbursementReceipt) { this.reimbursementReceipt = reimbursementReceipt; } public int getReimbursementAuthor() { return reimbursementAuthor; } public void setReimbursementAuthor(int reimbursementAuthor) { this.reimbursementAuthor = reimbursementAuthor; } public int getReimbursementResolver() { return reimbursementResolver; } public void setReimbursementResolver(int reimbursementResolver) { this.reimbursementResolver = reimbursementResolver; } public int getReimbursementStatusID() { return reimbursementStatusID; } public void setReimbursementStatusID(int reimbursementStatusID) { this.reimbursementStatusID = reimbursementStatusID; } public int getReimbursementTypeID() { return reimbursementTypeID; } public void setReimbursementTypeID(int reimbursementTypeID) { this.reimbursementTypeID = reimbursementTypeID; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((reimburementDescription == null) ? 0 : reimburementDescription.hashCode()); long temp; temp = Double.doubleToLongBits(reimbursementAmount); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + reimbursementAuthor; result = prime * result + reimbursementID; result = prime * result + reimbursementReceipt; result = prime * result + ((reimbursementResolved == null) ? 0 : reimbursementResolved.hashCode()); result = prime * result + reimbursementResolver; result = prime * result + reimbursementStatusID; result = prime * result + ((reimbursementSubmitted == null) ? 0 : reimbursementSubmitted.hashCode()); result = prime * result + reimbursementTypeID; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Reimbursement other = (Reimbursement) obj; if (reimburementDescription == null) { if (other.reimburementDescription != null) return false; } else if (!reimburementDescription.equals(other.reimburementDescription)) return false; if (Double.doubleToLongBits(reimbursementAmount) != Double.doubleToLongBits(other.reimbursementAmount)) return false; if (reimbursementAuthor != other.reimbursementAuthor) return false; if (reimbursementID != other.reimbursementID) return false; if (reimbursementReceipt != other.reimbursementReceipt) return false; if (reimbursementResolved == null) { if (other.reimbursementResolved != null) return false; } else if (!reimbursementResolved.equals(other.reimbursementResolved)) return false; if (reimbursementResolver != other.reimbursementResolver) return false; if (reimbursementStatusID != other.reimbursementStatusID) return false; if (reimbursementSubmitted == null) { if (other.reimbursementSubmitted != null) return false; } else if (!reimbursementSubmitted.equals(other.reimbursementSubmitted)) return false; if (reimbursementTypeID != other.reimbursementTypeID) return false; return true; } @Override public String toString() { return "Reimbursement [reimbursementID=" + reimbursementID + ", reimbursementAmount=" + reimbursementAmount + ", reimbursementSubmitted=" + reimbursementSubmitted + ", reimbursementResolved=" + reimbursementResolved + ", reimburementDescription=" + reimburementDescription + ", reimbursementReceipt=" + reimbursementReceipt + ", reimbursementAuthor=" + reimbursementAuthor + ", reimbursementResolver=" + reimbursementResolver + ", reimbursementStatusID=" + reimbursementStatusID + ", reimbursementTypeID=" + reimbursementTypeID + ", toString()=" + super.toString() + "]"; } } <file_sep>const URL = 'http://localhost:8080/project1/' let signUpButton = document.getElementById("signUpButton") let loginButton = document.getElementById("loginButton") signUpButton.onclick = signUp loginButton.onclick = login; function getUserInfo(newUsername, newPassword, newFirstName = "", newLastName = "", newEmail = ""){ let credentials = { userName:newUsername, pass:<PASSWORD>, firstName:newFirstName, lastName:newLastName, email:newEmail, userRoleID:0, userRole:"" } return credentials } async function signUp(){ event.preventDefault(); let newFirstName = document.getElementById("newFirstName").value let newLastName = document.getElementById("newLastName").value let newEmail = document.getElementById("newEmail").value let newUsername = document.getElementById("newUsername").value let newPassword = document.getElementById("newPassword").value let info = getUserInfo(newUsername, newPassword, newFirstName, newLastName, newEmail ) let response = await fetch(URL + 'signUp', { method:'POST', body:JSON.stringify(info) }) if(response.status===201){ deleteSignUpForm() employeeService() }else{ console.log("New user was unsuccessfully created.") } } async function login(){ event.preventDefault(); let username = document.getElementById("LoginUsername").value; let password = document.getElementById("LoginPassword").value; let cred = getUserInfo(username, password); let response = await fetch(URL + 'login', { method:'POST', body:JSON.stringify(cred) }); if (response.status==201){ deleteSignUpForm(); let profileInfo = await response.json(); document.getElementById("registerPrompt").innerHTML = profileInfo.userRoleID + " " + profileInfo.firstName + ", " + "please use the navbar to perform your desired actions."; if (profileInfo.userRoleID == "2") { managerService(); } else { employeeService(); } } else { console.log("User login fail"); } } async function signOut(){ let response = await fetch(URL + 'signOut', { method:'POST' }) window.location.replace('http://localhost:8080/static/index.html') } async function employeeService(){ let navbarService = document.getElementById("servicesPlaceHolder"); let managerServTag = document.createElement("a"); managerServTag.setAttribute("data-toggle", "dropdown"); managerServTag.setAttribute("class", "nav-item nav-link dropdown-toggle"); managerServTag.innerHTML = "Services"; navbarService.appendChild(managerServTag); let managerServList = document.createElement("div"); managerServList.setAttribute("class", "dropdown-menu"); let managerServList1 = document.createElement("a"); managerServList1.setAttribute("class", "dropdown-item"); managerServList1.innerHTML = "View Past Tickets"; managerServList1.setAttribute("id", "viewPastTickets"); let managerServList2 = document.createElement("a"); managerServList2.setAttribute("class", "dropdown-item"); managerServList2.setAttribute("id", "viewPendingRequest"); managerServList2.innerHTML = "View Pending Request"; let managerServList3 = document.createElement("a"); managerServList3.setAttribute("class", "dropdown-item"); managerServList3.setAttribute("id", "submitNewRequest"); managerServList3.innerHTML = "Submit New Request"; managerServList.appendChild(managerServList1); managerServList.appendChild(managerServList2); managerServList.appendChild(managerServList3); navbarService.appendChild(managerServList); let viewPastTicketsButton = document.getElementById("viewPastTickets"); viewPastTicketsButton.onclick = viewPastTickets; let viewPendingRequestButton = document.getElementById("viewPendingRequest"); viewPendingRequestButton.onclick = viewPendingRequest; let submitNewRequestButton = document.getElementById("submitNewRequest"); submitNewRequestButton.onclick = submitNewRequest; } async function managerService(){ let navbarService = document.getElementById("servicesPlaceHolder"); let managerServTag = document.createElement("a"); managerServTag.setAttribute("data-toggle", "dropdown"); managerServTag.setAttribute("class", "nav-item nav-link dropdown-toggle"); managerServTag.innerHTML = "Services"; navbarService.appendChild(managerServTag); let managerServList = document.createElement("div"); managerServList.setAttribute("class", "dropdown-menu"); let managerServList1 = document.createElement("button"); managerServList1.setAttribute("class", "dropdown-item"); managerServList1.setAttribute("id", "viewAllRequest"); managerServList1.innerHTML = "View All Request"; let managerServList2 = document.createElement("button"); managerServList2.setAttribute("class", "dropdown-item"); managerServList2.setAttribute("id", "processRequest"); managerServList2.innerHTML = "Process Request"; managerServList.appendChild(managerServList1); managerServList.appendChild(managerServList2); navbarService.appendChild(managerServList); let viewAllRequestButton = document.getElementById("viewAllRequest"); viewAllRequestButton.onclick = viewAllRequestFunc; let processRequestButton = document.getElementById("processRequest"); processRequestButton.onclick = processRequest; } function getReimb(){ let storeAmount = Math.trunc(document.getElementById("input_amount").value * 100); let reimb_model = { reimbusermentID:0, reimbursementAmount:storeAmount, reimbursementSubmitted:"", reimbursementResolved:"", reimbursementDescription:document.getElementById("input_description").value, reimbursementReceipt:false, reimbursementAuthor:0, reimbursementResolver:0, reimbursementStatusID:0, reimbursementTypeID:document.getElementById("input_reimb_type").value } return reimb_model; } async function getAllReimb(){ let response = await fetch(URL + 'reimb') if(response.status===201){ let data = await response.json() populateReimbTable(data) }else{ console.log('Something went wrong') } } async function printTable(urlAttribute){ let response = await fetch(URL + urlAttribute, { method:'POST' }); if (response.status==201){ let pageFrontContainer = document.getElementById("pageFrontContainer"); pageFrontContainer.innerHTML = "<br><h2>Past Tickets</h2><br><br>"; let tableContainer = document.createElement("div"); tableContainer.setAttribute("class", "table-responsive"); let tableAllRequest = document.createElement("table"); tableAllRequest.setAttribute("class", "table table-striped table-sm"); let thead = document.createElement("thead"); let tr = document.createElement("tr"); let th = document.createElement("th"); th.setAttribute("scope","col"); th.innerText = "Reimb ID"; tr.appendChild(th); th = document.createElement("th"); th.setAttribute("scope","col"); th.innerText = "Reimb Amount"; tr.appendChild(th); th = document.createElement("th"); th.setAttribute("scope","col"); th.innerText = "Submit Time"; tr.appendChild(th); th = document.createElement("th"); th.setAttribute("scope","col"); th.innerText = "Resolved Time"; tr.appendChild(th); th = document.createElement("th"); th.setAttribute("scope","col"); th.innerText = "Description"; tr.appendChild(th); th = document.createElement("th"); th.setAttribute("scope","col"); th.innerText = "Author"; tr.appendChild(th); th = document.createElement("th"); th.setAttribute("scope","col"); th.innerText = "Resolver"; tr.appendChild(th); th = document.createElement("th"); th.setAttribute("scope","col"); th.innerText = "Status"; tr.appendChild(th); th = document.createElement("th"); th.setAttribute("scope","col"); th.innerText = "Type"; tr.appendChild(th); thead.appendChild(tr); tableAllRequest.appendChild(thead); let tbody = document.createElement("tbody"); tr = document.createElement("tr"); let td = document.createElement("td"); let reimbGroup = await response.json(); for (let reimbIndex in reimbGroup) { td.innerText = reimbGroup[reimbIndex].reimbursementID; tr.appendChild(td); td = document.createElement("td"); td.innerText = reimbGroup[reimbIndex].reimbursementAmount / 100; tr.appendChild(td); td = document.createElement("td"); td.innerText = reimbGroup[reimbIndex].reimbursementSubmitted; tr.appendChild(td); td = document.createElement("td"); td.innerText = reimbGroup[reimbIndex].reimbursementResolved; tr.appendChild(td); td = document.createElement("td"); td.innerText = reimbGroup[reimbIndex].reimbursementDescription; tr.appendChild(td); td = document.createElement("td"); td.innerText = reimbGroup[reimbIndex].reimbursementAuthor; tr.appendChild(td); td = document.createElement("td"); td.innerText = reimbGroup[reimbIndex].reimbursementResolver; tr.appendChild(td); td = document.createElement("td"); td.innerText = reimbGroup[reimbIndex].reimbursementStatusID; tr.appendChild(td); td = document.createElement("td"); td.innerText = reimbGroup[reimbIndex].reimbursementTypeID; tr.appendChild(td); td = document.createElement("td"); tbody.appendChild(tr); tr = document.createElement("tr"); } tableAllRequest.appendChild(tbody); tableContainer.appendChild(tableAllRequest); pageFrontContainer.appendChild(tableContainer); } else { console.log("Get User Requests Fail"); } } async function getPendingReimb(){ let response = await fetch(URL + 'pendingReimb') if(response.status===201){ let reimbData = await response.json() populateReimbTable(reimbData) }else{ console.log("There was a problem accessing reimbursements") } } function getUserReimnb(){ let reimbUser = document.getElementById("reimb-username").value let reimbAmount = document.getElementById("amount").value let reimbType = document.getElementById("type").value let reimbDescription = document.getElementById("description").value let reimb = { reimbursementAuthor:reimbUser, reimbursementAmount:reimbAmount, reimbursementTypeID:reimbType, reimbursementDescription:reimbDescription } return reimb } async function submitReimb(){ let response = await fetch(URL + 'employee/submit/type', { method:'POST' }); if (response.status==201){ let reimbTypeGroup = await response.json(); let pageFrontContainer = document.getElementById("pageFrontContainer"); pageFrontContainer.innerHTML = "<br><h2>Create Request</h2><br><br>"; let requestForm = document.createElement("form"); requestForm.setAttribute("method", "post"); let formGroup1 = document.createElement("div"); formGroup1.setAttribute("class", "form-group col-xs-6"); let formGroup1Label = document.createElement("label"); formGroup1Label.setAttribute("for", "REIMB_AMOUNT"); let formGroup1LabelH = document.createElement("h4"); formGroup1LabelH.innerText = "Reimbursment Amount"; let formGroup1Input = document.createElement("input"); formGroup1Input.setAttribute("type", "text"); formGroup1Input.setAttribute("class", "form-control"); formGroup1Input.setAttribute("name", "input_amount"); formGroup1Input.setAttribute("id", "input_amount"); formGroup1Input.setAttribute("placeholder", "999.99"); formGroup1Input.setAttribute("title", "enter your desired amount to reimburse"); formGroup1Label.appendChild(formGroup1LabelH); formGroup1.appendChild(formGroup1Label); formGroup1.appendChild(formGroup1Input); requestForm.appendChild(formGroup1); let formGroup2 = document.createElement("div"); formGroup2.setAttribute("class", "form-group col-xs-6"); let formGroup2Label = document.createElement("label"); formGroup2Label.setAttribute("for", "REIMB_DESCRIPTION"); let formGroup2LabelH = document.createElement("h4"); formGroup2LabelH.innerText = "Reimbursment Description"; let formGroup2Input = document.createElement("input"); formGroup2Input.setAttribute("type", "text"); formGroup2Input.setAttribute("class", "form-control"); formGroup2Input.setAttribute("name", "input_description"); formGroup2Input.setAttribute("id", "input_description"); formGroup2Input.setAttribute("placeholder", "Short description for reimbursement."); formGroup2Input.setAttribute("title", "enter the reason you requesting reimbursement"); formGroup2Label.appendChild(formGroup2LabelH); formGroup2.appendChild(formGroup2Label); formGroup2.appendChild(formGroup2Input); requestForm.appendChild(formGroup2); let formGroup3 = document.createElement("div"); formGroup3.setAttribute("class", "form-group col-xs-6"); let formGroup3Label = document.createElement("label"); formGroup3Label.setAttribute("for", "REIMB_TYPE"); let formGroup3LabelH = document.createElement("h4"); formGroup3LabelH.innerText = "Reimbursment Type"; let formGroup3Select = document.createElement("select"); formGroup3Select.setAttribute("class", "form-control"); formGroup3Select.setAttribute("name", "input_reimb_type"); formGroup3Select.setAttribute("id", "input_reimb_type"); let formGroup3SelectOption1 = document.createElement("option"); formGroup3SelectOption1.setAttribute("selected", true); formGroup3SelectOption1.innerHTML = "Make Selection"; formGroup3Select.appendChild(formGroup3SelectOption1); for (let reimbTypeIndex in reimbTypeGroup) { formGroup3Select.appendChild(appendSelectOption(reimbTypeGroup[reimbTypeIndex].reimbursementTypeID, reimbTypeGroup[reimbTypeIndex].reimb_type));//might be something here } formGroup3Label.appendChild(formGroup3LabelH); formGroup3.appendChild(formGroup3Label); formGroup3.appendChild(formGroup3Select); requestForm.appendChild(formGroup3); let formGroup4 = document.createElement("div"); formGroup4.setAttribute("class", "form-group col-xs-12"); formGroup4.innerHTML = "<br>"; let formGroup4Submit = document.createElement("button"); formGroup4Submit.setAttribute("class", "btn btn-lg btn-success"); formGroup4Submit.setAttribute("id", "createRequestButton"); formGroup4Submit.setAttribute("type", "submit"); formGroup4Submit.innerText = "Create"; let formGroup4Reset = document.createElement("button"); formGroup4Reset.setAttribute("class", "btn btn-lg"); formGroup4Reset.setAttribute("type", "reset"); formGroup4Reset.innerHTML = "Reset"; let formGroup4ResetI = document.createElement("i"); formGroup4ResetI.setAttribute("class", "glyphicon glyphicon-repeat") formGroup4Reset.appendChild(formGroup4ResetI); formGroup4.appendChild(formGroup4Submit); formGroup4.appendChild(formGroup4Reset); requestForm.appendChild(formGroup4); pageFrontContainer.appendChild(requestForm); let createRequestButton = document.getElementById("createRequestButton"); createRequestButton.onclick = submitRequest; } else { console.log("Connect to server fail."); function appendSelectOption(optionvalue, optionPrompt) { let SelectOption = document.createElement("option"); SelectOption.setAttribute("value", optionvalue); SelectOption.innerHTML = optionPrompt; return SelectOption; } } } async function processRequest(){ let response = await fetch(URL + 'manager/pending', { method:'POST' }); if (response.status==201){ let pageFrontContainer = document.getElementById("pageFrontContainer"); pageFrontContainer.innerHTML = "<br><h2>Pending Request</h2><br><br>"; let tableContainer = document.createElement("div"); tableContainer.setAttribute("class", "table-responsive"); let tableAllRequest = document.createElement("table"); tableAllRequest.setAttribute("class", "table table-striped table-sm"); let thead = document.createElement("thead"); let tr = document.createElement("tr"); let th = document.createElement("th"); th.setAttribute("scope","col"); th.innerText = "Reimb ID"; tr.appendChild(th); th = document.createElement("th"); th.setAttribute("scope","col"); th.innerText = "Reimb Amount"; tr.appendChild(th); th = document.createElement("th"); th.setAttribute("scope","col"); th.innerText = "Submit Time"; tr.appendChild(th); th = document.createElement("th"); th.setAttribute("scope","col"); th.innerText = "Resolved Time"; tr.appendChild(th); th = document.createElement("th"); th.setAttribute("scope","col"); th.innerText = "Description"; tr.appendChild(th); th = document.createElement("th"); th.setAttribute("scope","col"); th.innerText = "Author"; tr.appendChild(th); th = document.createElement("th"); th.setAttribute("scope","col"); th.innerText = "Resolver"; tr.appendChild(th); th = document.createElement("th"); th.setAttribute("scope","col"); th.innerText = "Status"; tr.appendChild(th); th = document.createElement("th"); th.setAttribute("scope","col"); th.innerText = "Type"; tr.appendChild(th); th = document.createElement("th"); th.setAttribute("scope","col"); th.innerText = "Process"; tr.appendChild(th); thead.appendChild(tr); tableAllRequest.appendChild(thead); let tbody = document.createElement("tbody"); tr = document.createElement("tr"); let td = document.createElement("td"); let tableCheckbox = document.createElement("input"); let reimbGroup = await response.json(); let i = 0; for (let reimbIndex in reimbGroup) { td.innerText = reimbGroup[reimbIndex].reimbursementID; tr.appendChild(td); td = document.createElement("td"); td.innerText = reimbGroup[reimbIndex].reimbursementAmount / 100; tr.appendChild(td); td = document.createElement("td"); td.innerText = reimbGroup[reimbIndex].reimbursementSubmitted; tr.appendChild(td); td = document.createElement("td"); td.innerText = reimbGroup[reimbIndex].reimbursementResolved; tr.appendChild(td); td = document.createElement("td"); td.innerText = reimbGroup[reimbIndex].reimbursementDescription; tr.appendChild(td); td = document.createElement("td"); td.innerText = reimbGroup[reimbIndex].reimbursementAuthor; tr.appendChild(td); td = document.createElement("td"); td.innerText = reimbGroup[reimbIndex].reimbursementResolver; tr.appendChild(td); td = document.createElement("td"); td.innerText = reimbGroup[reimbIndex].reimbursementStatusID; tr.appendChild(td); td = document.createElement("td"); td.innerText = reimbGroup[reimbIndex].reimbursementTypeID; tr.appendChild(td); td = document.createElement("td"); tableCheckbox.setAttribute("class", "form-check-input"); tableCheckbox.setAttribute("type", "checkbox"); tableCheckbox.setAttribute("id", "reimb_checkbox_"+i++); tableCheckbox.setAttribute("value", reimbGroup[reimbIndex].reimb_id); td.appendChild(tableCheckbox); tr.appendChild(td); td = document.createElement("td"); tableCheckbox = document.createElement("input"); tbody.appendChild(tr); tr = document.createElement("tr"); } let tableProcess = document.createElement("button"); tableProcess.setAttribute("id", "approveAll"); tableProcess.setAttribute("type", "submit"); tableProcess.setAttribute("class", "btn btn-primary"); tableProcess.innerHTML = "Approve All"; td.appendChild(tableProcess); tr.appendChild(td); td = document.createElement("td"); tableProcess = document.createElement("button"); tableProcess.setAttribute("id", "denyAll"); tableProcess.setAttribute("type", "submit"); tableProcess.setAttribute("class", "btn btn-primary"); tableProcess.innerHTML = "Deny All"; td.appendChild(tableProcess); tr.appendChild(td); td = document.createElement("td"); tableProcess = document.createElement("button"); tableProcess.setAttribute("id", "approve"); tableProcess.setAttribute("type", "submit"); tableProcess.setAttribute("class", "btn btn-primary"); tableProcess.innerHTML = "Approve Checked"; td.appendChild(tableProcess); tr.appendChild(td); td = document.createElement("td"); tableProcess = document.createElement("button"); tableProcess.setAttribute("id", "deny"); tableProcess.setAttribute("type", "submit"); tableProcess.setAttribute("class", "btn btn-primary"); tableProcess.innerHTML = "Deny Checked"; td.appendChild(tableProcess); tr.appendChild(td); tbody.appendChild(tr); tableAllRequest.appendChild(tbody); tableContainer.appendChild(tableAllRequest); pageFrontContainer.appendChild(tableContainer); let tableApproveAllButton = document.getElementById("approveAll"); tableApproveAllButton.onclick = approveAllRequest; let tableDenyAllButton = document.getElementById("denyAll"); tableDenyAllButton.onclick = denyAllRequest; let tableApproveButton = document.getElementById("approve"); tableApproveButton.onclick = approveRequest; let tableDenyButton = document.getElementById("deny"); tableDenyButton.onclick = denyRequest; } else { console.log("Get User Requests Fail"); } } async function submitRequest(){ event.preventDefault(); let response = await fetch(URL + 'employee/submit', { method:'POST', body:JSON.stringify(getReimb()) }); if (response.status==201){ let pageFrontContainer = document.getElementById("pageFrontContainer"); pageFrontContainer.innerHTML = "<br><h2>Request Submitted !</h2><br><br>"; } else { let pageFrontContainer = document.getElementById("pageFrontContainer"); pageFrontContainer.innerHTML = "<br><h2>Request Submit Ran Into Some Problem.</h2><br><br>"; } } async function approveRequest(){ let i = 0; let response = null; let reimbIdInprocess = document.getElementById("reimb_checkbox_"+i++); while (reimbIdInprocess != null) { if (reimbIdInprocess.checked) { response = await fetch(URL + 'manager/approve/single/' + reimbIdInprocess.getAttribute("value"), { method:'POST' }); } reimbIdInprocess = document.getElementById("reimb_checkbox_"+i++); } if (response.status==201){ processRequest(); } } async function denyRequest(){ let i = 0; let response = null; let reimbIdInprocess = document.getElementById("reimb_checkbox_"+i++); while (reimbIdInprocess != null) { if (reimbIdInprocess.checked) { response = await fetch(URL + 'manager/deny/single/' + reimbIdInprocess.getAttribute("value"), { method:'POST' }); } reimbIdInprocess = document.getElementById("reimb_checkbox_"+i++); } if (response.status==201){ processRequest(); } } function deleteSignUpForm(){ let signUpForm = document.getElementById("signUpForm"); signUpForm.innerHTML = " "; signUpForm = document.getElementById("loginNavbarAnchor"); signUpForm.innerHTML = " "; let profileImgNavbar = document.createElement("img"); profileImgNavbar.setAttribute("src", "https://github.com/mdo.png"); profileImgNavbar.setAttribute("alt", "mdo"); profileImgNavbar.setAttribute("width", "32"); profileImgNavbar.setAttribute("height", "32"); profileImgNavbar.setAttribute("class", "rounded-circle"); signUpForm.appendChild(profileImgNavbar); signUpForm = document.getElementById("loginNavbarMenu"); signUpForm.style.width = "100px"; signUpForm.innerHTML = " "; let profileList1 = document.createElement("button"); profileList1.setAttribute("class", "dropdown-item"); profileList1.setAttribute("id", "profile"); profileList1.innerHTML = "Profile"; signUpForm.appendChild(profileList1); let profileList2 = document.createElement("hr"); profileList2.setAttribute("class", "dropdown-divider"); signUpForm.appendChild(profileList2); let profileList3 = document.createElement("button"); profileList3.setAttribute("class", "dropdown-item"); profileList3.setAttribute("id", "signOut"); profileList3.innerHTML = "Sign out"; signUpForm.appendChild(profileList3); let profileButton = document.getElementById("profile"); profileButton.onclick = profile; let signOutButton = document.getElementById("signOut"); signOutButton.onclick = signOut; } <file_sep>const URL = 'http://localhost:8080/project1/' let button = document.getElementById('btnSubmit') button.onclick = submitLogin function loginInfo(){ let username = document.getElementById("username").value let password = document.getElementById("password").value let user = { userName:username, pass:<PASSWORD> } return user } async function submitLogin(){ let user = loginInfo() let response = await fetch(URL+'login', { method:'POST', body:JSON.stringify(user) }) if(response.status===201){ console.log("Login successful") //Map to new page }else{ } } <file_sep>package com.revature.daos; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import com.revature.models.Reimbursement; import com.revature.models.ReimbursementType; import com.revature.utils.ConnectionUtil; public class ReimbursementDAOImpl implements ReimbursementDAO{ @Override public List<Reimbursement> findAllReimbursements() { try(Connection conn = ConnectionUtil.getConnection()){ String sql = "SELECT * FROM ers_reimbursement"; Statement statement = conn.createStatement(); ResultSet result = statement.executeQuery(sql); List<Reimbursement> list = new ArrayList<>(); while(result.next()) { Reimbursement reimb = new Reimbursement(); reimb.setReimbursementID(result.getInt("reimb_id")); reimb.setReimbursementAmount(result.getDouble("reimb_amount")); reimb.setReimbursementSubmitted(result.getTimestamp("reimb_submitted")); reimb.setReimbursementResolved(result.getTimestamp("reimb_resolved")); reimb.setReimburementDescription(result.getString("reimb_description")); reimb.setReimbursementAuthor(result.getInt("reimb_author")); reimb.setReimbursementResolver(result.getInt("reimb_resolver")); reimb.setReimbursementStatusID(result.getInt("reimb_status_id")); reimb.setReimbursementTypeID(result.getInt("reimb_type_id")); list.add(reimb); } return list; }catch(SQLException e) { e.printStackTrace(); } return null; } @Override public boolean addReimbursement(Reimbursement reimb, String username) { try(Connection conn = ConnectionUtil.getConnection()){ String sql = "INSERT INTO ers_reimbursement(reimb_id, reimb_amount, reimb_submitted, reimb_resolved, reimb_description, reimb_receipt, reimb_author, reimb_resolver, reimb_status_id, reimb_type_id)" + " VALUES(?,?,?,?,?,?,?,?,?,?)"; PreparedStatement statement = conn.prepareStatement(sql); int index = 0; statement.setInt(++index, reimb.getReimbursementID()); statement.setDouble(++index, reimb.getReimbursementAmount()); statement.setTimestamp(++index, reimb.getReimbursementSubmitted()); statement.setTimestamp(++index, reimb.getReimbursementResolved()); statement.setString(++index, reimb.getReimburementDescription()); statement.setByte(++index, reimb.getReimbursementReceipt()); statement.setInt(++index, reimb.getReimbursementAuthor()); statement.setInt(++index, reimb.getReimbursementResolver()); statement.setInt(++index, reimb.getReimbursementStatusID()); statement.setInt(++index, reimb.getReimbursementTypeID()); statement.execute(); return true; }catch(SQLException e) { e.printStackTrace(); } return false; } @Override public List<Reimbursement> findReimbursement(String ers_username, boolean b) { try(Connection conn = ConnectionUtil.getConnection()){ }catch(SQLException e) { e.printStackTrace(); } return null; } @Override public List<ReimbursementType> findReimbursementByType() { try(Connection conn = ConnectionUtil.getConnection()){ ArrayList<ReimbursementType> reimbT = new ArrayList<ReimbursementType>(); String sql = "SELECT * FROM ERS_REIMBURSMENT_TYPE"; PreparedStatement statement = conn.prepareStatement(sql); ResultSet typeRS = statement.executeQuery(); try { while (typeRS.next()) { reimbT.add(new ReimbursementType(typeRS.getInt(1), typeRS.getString(2))); } return reimbT; } catch (SQLException e) { System.err.println("Select From Database Fail" + e.getMessage()); } }catch(SQLException e) { e.printStackTrace(); } return null; } } <file_sep>package com.revature.daos; import com.revature.models.ReimbursementStatus; public interface ReimbursementStatusDAO { public ReimbursementStatus findReimbursementByStatus(int reimbStatusID); } <file_sep>package com.revature.daos; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import com.revature.models.User; import com.revature.utils.ConnectionUtil; public class UserDAOImpl implements UserDAO { @Override public List<User> findAllUsers() { try(Connection conn = ConnectionUtil.getConnection()){ String sql = "SELECT * FROM ers_users"; Statement statement = conn.createStatement(); ResultSet result = statement.executeQuery(sql); List<User> list = new ArrayList<>(); while(result.next()) { User user = new User(); user.setUserName(result.getString("ers_username")); user.setPass(result.getString("<PASSWORD>")); user.setFirstName(result.getString("user_first_name")); user.setLastName(result.getString("user_last_name")); user.setEmail(result.getString("user_email")); user.setUserRole(result.getInt("user_role_id")); list.add(user); } return list; }catch(SQLException e) { e.printStackTrace(); } return null; } @Override public User findByUsersName(String username) { try(Connection conn = ConnectionUtil.getConnection()){ String sql = "SELECT * FROM ers_users WHERE ers_username = ?;"; PreparedStatement statement = conn.prepareStatement(sql); ResultSet result = statement.executeQuery(); statement.setString(1, username); User user = new User(); while(result.next()) { user.setUserID(result.getInt("ers_user_id")); user.setUserName(result.getString("ers_username")); user.setPass(result.getString("<PASSWORD>")); user.setFirstName(result.getString("user_first_name")); user.setLastName(result.getString("user_last_name")); user.setEmail(result.getString("user_email")); user.setUserRole(result.getInt("user_role_id")); } return user; }catch(SQLException e) { e.printStackTrace(); } return null; } @Override public boolean updateUser(User user) { try(Connection conn = ConnectionUtil.getConnection()){ String sql = "INSERT INTO ers_users (ers_username, ers_password, user_first_name, user_last_name, user_email)" + "VALUES (?,?,?,?,?)"; PreparedStatement statement = conn.prepareStatement(sql); int index = 0; statement.setString(++index, user.getUserName()); statement.setString(++index, user.getPass()); statement.setString(++index, user.getFirstName()); statement.setString(++index, user.getLastName()); statement.setString(++index, user.getEmail()); statement.execute(); return true; }catch(SQLException e) { e.printStackTrace(); } return false; } @Override public boolean addUser(User user) { try(Connection conn = ConnectionUtil.getConnection()){ String sql = "INSERT INTO ers_users (ers_username, ers_password, user_first_name, user_last_name, user_email, user_role_id)" + " VALUES (?,?,?,?,?,?)"; PreparedStatement statement = conn.prepareStatement(sql); int index = 0; statement.setString(++index, user.getUserName()); statement.setString(++index, user.getPass()); statement.setString(++index, user.getFirstName()); statement.setString(++index, user.getLastName()); statement.setString(++index, user.getEmail()); statement.setInt(++index, 1); statement.execute(); return true; }catch(SQLException e) { e.printStackTrace(); } return false; } @Override public int checkValidAccount(User user) { try { Connection connect = ConnectionUtil.getConnection(); Statement statement = connect.createStatement(); String username = user.getUserName(); String pass = <PASSWORD>(); ResultSet result = statement.executeQuery("SELECT user_role_id FROM ers_users WHERE ers_username = '" + username+ "' AND ers_password = '" + pass + "';"); int index = 0; if(result.next()) { username = user.getUserName(); pass = <PASSWORD>.get<PASSWORD>(); index = result.getInt(1); } return index; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return 0; } @Override public String login(User user) { try(Connection conn = ConnectionUtil.getConnection()){ String sql = "SELECT ers_password FROM ERS_USERS WHERE ers_username = '" + user.getUserName() + "'"; PreparedStatement prepStatement = conn.prepareStatement(sql); ResultSet result = prepStatement.executeQuery(); try { if (result.next()) { return result.getString(1); } else { System.out.println("User not found."); } } catch(SQLException e) { System.err.println("Access Result Set Fail: " + e.getMessage()); } }catch(SQLException e) { e.printStackTrace(); } return null; } } <file_sep>package com.revature.daos; import java.sql.Timestamp; import java.util.List; import com.revature.models.Reimbursement; import com.revature.models.ReimbursementType; public interface ReimbursementDAO { public boolean addReimbursement(Reimbursement reimb, String username); public List<Reimbursement> findAllReimbursements(); public List<Reimbursement> findReimbursement(String username, boolean pending); public List<ReimbursementType> findReimbursementByType(); } <file_sep>//package com.revature.web; // //import java.io.IOException; // //import javax.servlet.ServletException; //import javax.servlet.http.HttpServlet; //import javax.servlet.http.HttpServletRequest; //import javax.servlet.http.HttpServletResponse; //import javax.servlet.http.HttpSession; //NO LONGER USING THIS, TRYING TO USE FRONT CONTROLLER MODEL //public class LogoutServlet extends HttpServlet{ // // @Override // protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ // // HttpSession session = request.getSession(true); // // if(session!=null) { // session.invalidate(); // } // // response.sendRedirect(""); // } // //}
7603060800c60aee3857a63e09c759e3b854b854
[ "JavaScript", "Java", "SQL" ]
15
Java
210614-JavaFS/project1-tjwoods03
c95eda5f088fac69645c1c0b0e3419eed644ceb8
b39661becd29fba19cb9c3ed04e8e92ad9b5f005
refs/heads/master
<file_sep>๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace chatter { public class CMessageHandler { public enum MsgState { Idle, ReadyForRemote, WaitingResponse, ReadyForAck, SendAck, Done }; private MsgState _state = MsgState.Idle; private string _msg2Go = ""; private int _attempt = 0; private Queue<string> _msgs2Send = new Queue<string>(); private StringBuilder _buildMsg = new StringBuilder(); private string _lastAckMsg = ""; private string _lastAckIP = ""; private bool _imSendingAck = false; private DateTime _startTime; private string _name; private string _buddyIp = ""; private bool _msgProcessed = false; private string myip; public string Name { get { return this._name; } } public CMessageHandler(string name, string buddy, string myIP) { _name = name; _buddyIp = buddy; myip = myIP; } public ManualResetEvent SendDone = new ManualResetEvent(false); public ManualResetEvent ReceiveDone = new ManualResetEvent(false); public void PumpMessageFromRemote(string data, out string buddyIp, out bool isTyping) { // typing detection helpers buddyIp = _buddyIp; if (data.Contains('\t')) isTyping = true; else isTyping = false; if (!String.IsNullOrWhiteSpace(data)) { // build message up lock (_buildMsg) { _buildMsg.Append(data.TrimStart()); } } } public MsgState ProcessStates(out MessageEventArgs mea) { mea = processMea(); switch (this._state) { case MsgState.Idle: if (this._msgs2Send.Count > 0) { lock (this._msgs2Send) { this._msg2Go = this._msgs2Send.Dequeue(); } if (!String.IsNullOrWhiteSpace(this._msg2Go)) { this._msgProcessed = false; this._attempt = 0; this._imSendingAck = false; this._state = MsgState.ReadyForRemote; } } break; case MsgState.ReadyForRemote: this._startTime = DateTime.Now; if (this._attempt >= 3) this._state = MsgState.Idle; else if (this._msgProcessed) this._state = MsgState.WaitingResponse; break; case MsgState.WaitingResponse: // message was already sent out, check timeout DateTime endTime = DateTime.Now; if (endTime.Subtract(this._startTime).Milliseconds >= 799) { Sock.debug(_name + ": timeout, repeating"); this._msgProcessed = false; this._attempt++; this._state = MsgState.ReadyForRemote; } break; case MsgState.ReadyForAck: this._msgProcessed = false; this._msg2Go = this._lastAckMsg; this._state = MsgState.SendAck; break; case MsgState.SendAck: if (this._msgProcessed) { this._msgProcessed = false; this._imSendingAck = false; this._state = MsgState.Done; } break; case MsgState.Done: this._state = MsgState.Idle; break; default: break; } return this._state; } private MessageEventArgs processMea() { string localMsg; int myIndex; lock (_buildMsg) { localMsg = _buildMsg.ToString(); myIndex = localMsg.IndexOf("<EOF>"); if (myIndex >= 0) { localMsg = localMsg.Substring(0, myIndex + 1 + 4).Trim(); _buildMsg.Remove(0, myIndex + 1 + 4); } } if (myIndex >= 0) { MessageEventArgs mea = new MessageEventArgs(localMsg); if (mea.Valid) { // for safety _buddyIp = mea.FriendIP; if (this._state == MsgState.WaitingResponse || this._state == MsgState.SendAck) { Sock.debug(_name + ":got ACK:" + this._state.ToString() + ":Id=" + mea.Id); mea.IsAck = true; if (this._state == MsgState.WaitingResponse) this._state = MsgState.Done; return mea; } if (this._imSendingAck || mea.FriendIP == myip) { if (this._state == MsgState.WaitingResponse) this._state = MsgState.Done; return null; } else if (this._state == MsgState.Idle || this._state == MsgState.ReadyForRemote) { this._imSendingAck = true; _lastAckMsg = generate(mea.Id, mea.FriendName, mea.FriendIP, Sock.Checksum(mea.TextFromFriend)); // no need to send entire msg payload _lastAckIP = mea.FriendIP; Sock.debug(_name + ":Display(sendAck)" + this._state.ToString() + ":Id=" + mea.Id); this._state = MsgState.ReadyForAck; } else return mea; } else { Sock.debug(_name + ": oops, invalid message received"); } return mea; } else { return null; } } public string MessageReady { get { this._msgProcessed = true; return this._msg2Go; } } public void InjectTestMessage(string test) { int index = this._msg2Go.IndexOf("<EOF>"); if (index > -1) this._msg2Go = this._msg2Go.Insert(index, test); } public void AddMessageToSend(string msg) { lock (this._msgs2Send) { this._msgs2Send.Enqueue(msg); } } // function to get unique random number private static int last_number = 0; private static readonly Random getrandom = new Random(); private static readonly object syncLock = new object(); public static string GenerateMessage(string me, string ip, string msg) { int n = last_number; lock (syncLock) { // synchronize while (n == last_number) n = getrandom.Next(1, 0xFFFF); last_number = n; } return generate(n.ToString("X"), me, ip, msg); } private static string generate(string id, string me, string ip, string msg) { // | id | from name| from IP | text data message with EOF termination return "|" + id + "|" + me + "|" + ip + "|" + msg.Replace("|", "~") + "<EOF>"; } } } <file_sep>๏ปฟusing System; using System.IO; using System.IO.Compression; using System.Text; namespace chatter { internal static class StringCompressor { /// <summary> /// Compresses the string. /// </summary> /// <param name="text">The text.</param> /// <returns></returns> public static string CompressString(byte[] buffer) { //byte[] buffer = Encoding.Unicode.GetBytes(text); var memoryStream = new MemoryStream(); using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Compress, true)) { gZipStream.Write(buffer, 0, buffer.Length); } memoryStream.Position = 0; var compressedData = new byte[memoryStream.Length]; memoryStream.Read(compressedData, 0, compressedData.Length); var gZipBuffer = new byte[compressedData.Length + 4]; Buffer.BlockCopy(compressedData, 0, gZipBuffer, 4, compressedData.Length); Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gZipBuffer, 0, 4); return ToHexString(gZipBuffer, gZipBuffer.Length); } /// <summary> /// Decompresses the string. /// </summary> /// <param name="compressedText">The compressed text.</param> /// <returns></returns> public static byte[] DecompressString(string compressedText) { byte[] gZipBuffer = ToHexBytes(compressedText); using (var memoryStream = new MemoryStream()) { int dataLength = BitConverter.ToInt32(gZipBuffer, 0); memoryStream.Write(gZipBuffer, 4, gZipBuffer.Length - 4); var buffer = new byte[dataLength]; memoryStream.Position = 0; using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress)) { gZipStream.Read(buffer, 0, buffer.Length); } //return Encoding.Unicode.GetString(buffer); return buffer; } } public static string ToHexString(this byte[] hex, int length) { if (hex == null) return null; if (hex.Length == 0) return string.Empty; var s = new StringBuilder(); for (int i = 0; i < length; i++) { s.Append(hex[i].ToString("x2")); } return s.ToString(); } public static byte[] ToHexBytes(this string hex) { if (hex == null) return null; if (hex.Length == 0) return new byte[0]; int l = hex.Length / 2; var b = new byte[l]; for (int i = 0; i < l; ++i) { b[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16); } return b; } } } <file_sep>๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace chatter { public class CSavedIPs { static public List<string> PreviousIPList = new List<string>(); static public string Subs = ""; static public void ChangeSubList(string subs) { Subs = subs; UpdateFile(); } static public void AppendIP(string ip) { if (!PreviousIPList.Contains(ip)) { lock (PreviousIPList) { PreviousIPList.Add(ip); } UpdateFile(); } } static private void UpdateFile() { string[] lines = new string[1 + PreviousIPList.Count]; lines[0] = Subs; int i = 0; foreach (string item in PreviousIPList) lines[1 + i++] = item; try { if (File.Exists("myips.txt")) File.Delete("myips.txt"); File.WriteAllLines("myips.txt", lines); } catch { } } static public void ReadFile() { try { if (File.Exists("myips.txt")) { string[] lines = File.ReadAllLines("myips.txt"); Subs = lines[0]; PreviousIPList.Clear(); for (int i = 1; i < lines.Count(); i++) PreviousIPList.Add(lines[i]); } } catch { } } } } <file_sep>๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace chatter { public class MessageEventArgs : EventArgs { private string id; private string friendName; private string friendIP; private string textFromFriend; private bool valid = false; private bool isFile = false; private string fileName; private string fileData; private int chunkId = 0; private string checksum; public MessageEventArgs(string data) { if (data != null && data.Contains("|")) { data = data.Trim(); // important trim int loc, loc1, loc2, loc3; if (find4backwards(data, out loc, out loc1, out loc2, out loc3)) { id = data.Substring(loc + 1, loc1 - loc - 1); friendName = data.Substring(loc1 + 1, loc2 - loc1 - 1); friendIP = data.Substring(loc2 + 1, loc3 - loc2 - 1); textFromFriend = data.Substring(loc3 + 1, data.Length - loc3 - 1); checksum = Sock.Checksum(textFromFriend.Replace("<EOF>", "")); // sanity checks if (friendIP.Split('.').Count() != 4 || id.Length > 4 || id.Length == 0) { valid = false; } else if (textFromFriend.EndsWith("<EOF>")) { if (textFromFriend.StartsWith("<OBJECT>FILE")) { isFile = true; try { string[] splitObj = textFromFriend.Split('*'); this.chunkId = Convert.ToInt32(splitObj[1]); this.fileName = splitObj[2]; this.fileData = (splitObj[3].Substring(0, splitObj[3].Length - 4 - 1)); valid = true; } catch { valid = false; } textFromFriend = textFromFriend.Replace("<EOF>", ""); return; } textFromFriend = textFromFriend.Replace("<EOF>", ""); valid = true; } else { textFromFriend = ""; } } } } // loc loc1 loc2 loc3 // | id | from name| from IP | text data message with EOF termination private bool find4backwards(string msg, out int loc, out int loc1, out int loc2, out int loc3) { loc = -1; loc1 = -1; loc2 = -1; loc3 = msg.IndexOf("<EOF>"); if (loc3 > 0) { for (; loc3 > 0; loc3--) if (msg[loc3] == '|') { for (loc2 = loc3 - 1; loc2 > 0; loc2--) if (msg[loc2] == '|') { for (loc1 = loc2 - 1; loc1 > 0; loc1--) if (msg[loc1] == '|') { for (loc = loc1 - 1; loc >= 0; loc--) if (msg[loc] == '|') return true; break; } break; } break; } } return false; } public bool Valid { get { return this.valid; } } public int ChunkId { get { return this.chunkId; } } public bool IsAck { get; set; } public string Id { get { return this.id; } } public string FriendName { get { return this.friendName; } } public string FriendIP { get { return this.friendIP; } } public string TextFromFriend { get { return this.textFromFriend; } } public bool IsFile { get { return this.isFile; } } public string FileName { get { return this.fileName; } } public string FileData { get { return this.fileData; } } public string Checksum { get { return this.checksum; } } } } <file_sep>๏ปฟusing System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Runtime.InteropServices; using System.IO; using System.Threading; using System.Diagnostics; namespace chatter { public partial class Chatter : Form { private static class User32 { [DllImport("user32.dll")] public static extern int FlashWindow(IntPtr Hwnd, bool Revert); [DllImport("User32.dll")] internal static extern IntPtr SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll")] internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); internal static readonly IntPtr InvalidHandleValue = IntPtr.Zero; } public void ActivateMe() { // not the most elegant way but it works! this.WindowState = FormWindowState.Minimized; Process currentProcess = Process.GetCurrentProcess(); IntPtr hWnd = currentProcess.MainWindowHandle; if (hWnd != User32.InvalidHandleValue) { this.WindowState = FormWindowState.Normal; User32.SetForegroundWindow(hWnd); } } #region Constructor public Chatter() { InitializeComponent(); CSavedIPs.ReadFile(); this.comboBoxUsers.SelectedIndex = 0; userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name; this.groupBoxTop.Text = "Name: " + userName; this.textBoxSubs.Text = Sock.StartServer(); string[] split = this.textBoxSubs.Text.Split(','); string ipFirst = (split != null && split.Count() > 0) ? split[0] : "10.0.0"; Sock.NewData += Sock_NewDataReceivedEventHandler; Sock.Ack += Sock_Ack; myIP = Sock.GetIPAddress(ipFirst); this.groupBoxBottom.Text = "My IP: " + myIP; } #endregion #region Form Load Event private void Chatter_Load(object sender, EventArgs e) { if (myIP == "?") { appendText(richTextBoxChatOut, "Warning: IP not determined." + Environment.NewLine, Color.LightGreen); } else { buttonGoConnection_Click(null, null); } this.richTextBoxChatIn.Select(); this.richTextBoxChatIn.SelectionStart = 0; this.richTextBoxChatIn.Focus(); this._lastTyped.Interval = 2000; // 2 seconds this._lastTyped.Tick += _lastTyped_Tick; this._lastTyped.Start(); } #endregion #region Form Closing Event private void Chatter_FormClosing(object sender, FormClosingEventArgs e) { CSavedIPs.ChangeSubList(this.textBoxSubs.Text); this.isExit = true; // temp file cleanup try { foreach (string key in linkList.Keys) if (File.Exists(linkList[key])) File.Delete(linkList[key]); } catch { } Sock.KillTasks(); } #endregion private bool isExit = false; private string userName; private string myIP; private Dictionary<string, string> buddyList = new Dictionary<string, string>(); private System.Windows.Forms.Timer _lastTyped = new System.Windows.Forms.Timer(); private Dictionary<string, string> currentTempFile = new Dictionary<string, string>(); private Dictionary<string, string> currentChunk = new Dictionary<string, string>(); private Dictionary<string, int> currentChunkId = new Dictionary<string, int>(); private Dictionary<string, string> linkList = new Dictionary<string, string>(); #region Sock Events private void Sock_NewDataReceivedEventHandler(MessageEventArgs e) { this.Invoke((MethodInvoker)delegate { try { if (this.comboBoxUsers.Items.Contains(e.FriendName)) { // int index = this.comboBoxUsers.Items.IndexOf(e.FriendName); // if (index > -1) // this.comboBoxUsers.SelectedIndex = index; } else { this.comboBoxUsers.Items.Add(e.FriendName); this.buddyList[e.FriendName] = e.FriendIP; // auto select combo only if first buddy found if (this.comboBoxUsers.Items.Count <= 2) { int index = this.comboBoxUsers.Items.IndexOf(e.FriendName); if (index > -1) this.comboBoxUsers.SelectedIndex = index; } } if (e.IsFile) { if (e.ChunkId == -1) { if (currentChunkId[e.FriendIP] != -1) { byte[] data = StringCompressor.ToHexBytes(currentChunk[e.FriendIP]); currentChunk[e.FriendIP] = ""; if (!File.Exists(currentTempFile[e.FriendIP])) File.WriteAllBytes(currentTempFile[e.FriendIP], data); else appendAllBytes(currentTempFile[e.FriendIP], data); } appendText(richTextBoxChatOut, e.FriendName + ":\tSent a file->File_Waiting: ", Color.LightGreen); richTextBoxChatOut.InsertLink(e.FileName + " "); if (linkList.ContainsKey(e.FileName + " ")) linkList[e.FileName + " "] = currentTempFile[e.FriendIP]; else linkList.Add(e.FileName + " ", currentTempFile[e.FriendIP]); richTextBoxChatOut.AppendText(" " + Environment.NewLine); richTextBoxChatOut.ScrollToCaret(); } else { if (e.ChunkId == 0) { currentTempFile[e.FriendIP] = Path.GetTempFileName(); currentChunk[e.FriendIP] = e.FileData; currentChunkId[e.FriendIP] = 0; } else { // if this is a different chunk than before write it out if (currentChunkId[e.FriendIP] != e.ChunkId) { byte[] data = StringCompressor.ToHexBytes(currentChunk[e.FriendIP]); currentChunk[e.FriendIP] = ""; if (!File.Exists(currentTempFile[e.FriendIP])) File.WriteAllBytes(currentTempFile[e.FriendIP], data); else appendAllBytes(currentTempFile[e.FriendIP], data); } currentChunk[e.FriendIP] = e.FileData; currentChunkId[e.FriendIP] = e.ChunkId; } } } else if (e.TextFromFriend.StartsWith("<REMOTE>")) { processTypedMessage(e.TextFromFriend.Substring(8)); } else { appendText(richTextBoxChatOut, e.FriendName + ":\t", Color.LightGreen); appendText(richTextBoxChatOut, e.TextFromFriend + Environment.NewLine, Color.LightBlue); // scroll it automatically richTextBoxChatOut.ScrollToCaret(); } // make the form blink on taskbar if not already active User32.FlashWindow(this.Handle, false); } catch { } }); } #endregion #region General Helpers public void EnableGoButton() { if (!isExit) { this.Invoke((MethodInvoker)delegate { this.buttonGoConnection.Enabled = true; appendText(richTextBoxChatOut, "Finished Search." + Environment.NewLine, Color.LightGreen); }); } } static private void appendAllBytes(string path, byte[] bytes) { using (var stream = new FileStream(path, FileMode.Append)) { stream.Write(bytes, 0, bytes.Length); } } private void appendText(RichTextBox box, string text, Color color)//, Font font) { box.SelectionStart = box.TextLength; box.SelectionLength = 0; box.SelectionColor = color; //box.SelectionFont = font; box.AppendText(text); box.SelectionColor = box.ForeColor; } #endregion #region Form Control Events private void richTextBoxChatIn_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode.Equals(Keys.Enter)) { if (Control.ModifierKeys != Keys.Shift) { e.Handled = true; Sock.MyTypingStatus(false); processTypedMessage(this.richTextBoxChatIn.Text); } } } private void processTypedMessage(string message) { if (String.IsNullOrWhiteSpace(message)) { richTextBoxChatIn.Clear(); return; } string m = message.TrimEnd(); // cmd's if (m.StartsWith("<CMD>")) { m = m.Replace("<CMD>", "").ToLower(); if (m == "clear") { this.richTextBoxChatOut.Clear(); } else if (m == "max") { this.WindowState = FormWindowState.Maximized; } else if (m == "hide") { this.WindowState = FormWindowState.Minimized; } else if (m == "pop") { ActivateMe(); } else if (m == "debug") { Sock.InDebug = true; } else if (m == "normal") { Sock.InDebug = false; } else if (m == "exit") { this.Close(); } else if (m == "look") { this.buttonGoConnection_Click(null, null); } else if (m == "all") { this.comboBoxUsers.SelectedIndex = 0; } richTextBoxChatIn.Clear(); return; } if (this.comboBoxUsers.Items.Count == 1) { appendText(richTextBoxChatOut, "No friends can be found." + Environment.NewLine, Color.LightGreen); // scroll it automatically richTextBoxChatIn.Text = m; richTextBoxChatIn.SelectionStart = richTextBoxChatIn.Text.Length; richTextBoxChatIn.ScrollToCaret(); return; } // handle multi lines nicely if (m.Contains('\n')) { string[] splits = m.Split(new char[] { '\n' }, StringSplitOptions.None); m = ""; foreach (string s in splits) m += s + "\n\t\t"; m = m.TrimEnd(); } string buddyName = this.comboBoxUsers.Text; // ready to send message to a buddy if (this.comboBoxUsers.SelectedIndex != 0 && !Sock.SendToBuddy(userName, false, buddyList[buddyName], buddyName, m, null)) { appendText(richTextBoxChatOut, "Me:\t\t", Color.LightGreen); appendText(richTextBoxChatOut, m + " <remote ignored>" + Environment.NewLine, Color.LightSalmon); // scroll it automatically richTextBoxChatIn.Text = m; richTextBoxChatIn.SelectionStart = richTextBoxChatIn.Text.Length; richTextBoxChatIn.ScrollToCaret(); return; } else { appendText(richTextBoxChatOut, "Me:\t\t", Color.LightGreen); appendText(richTextBoxChatOut, m + Environment.NewLine, Color.LightSalmon); //richTextBoxChatOut.SelectionStart = richTextBoxChatOut.Text.Length; // scroll it automatically richTextBoxChatOut.ScrollToCaret(); } this.richTextBoxChatIn.Text = ""; // send message to each buddy if (this.comboBoxUsers.SelectedIndex == 0) { foreach (string key in this.buddyList.Keys) Sock.SendToBuddy(userName, false, buddyList[key], key, m, null); } } private void buttonGoConnection_Click(object sender, EventArgs e) { CSavedIPs.ChangeSubList(this.textBoxSubs.Text); Sock.SetSock(this.userName, this.myIP, this.textBoxSubs.Text); Sock.StartSearching(this); appendText(richTextBoxChatOut, "Searching..." + Environment.NewLine, Color.LightGreen); this.buttonGoConnection.Enabled = false; } private void textBoxPort_TextChanged(object sender, EventArgs e) { this.buttonGoConnection.Enabled = true; } private void buttonConnect_Click(object sender, EventArgs e) { if (this.comboBoxUsers.SelectedIndex != 0) { Sock.SendToBuddy(userName, true, buddyList[this.comboBoxUsers.Text], this.comboBoxUsers.Text, "Reconnected!", null); } } private void richTextBoxChatOut_LinkClicked(object sender, LinkClickedEventArgs e) { if (String.IsNullOrEmpty(e.LinkText)) { } else if (linkList.ContainsKey(e.LinkText)) { SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.FileName = e.LinkText.TrimEnd(); saveFileDialog1.Title = "Save File"; // If the file name is not an empty string open it for saving. if (saveFileDialog1.ShowDialog() == DialogResult.OK && saveFileDialog1.FileName != "") { try { File.Copy(linkList[e.LinkText], saveFileDialog1.FileName); } catch { } } } else { // enable html tags to display in browser System.Diagnostics.Process.Start(e.LinkText); } } private void richTextBoxChatOut_MouseUp(object sender, MouseEventArgs e) { //click event ContextMenu contextMenu = new System.Windows.Forms.ContextMenu(); MenuItem menuItem = new MenuItem("Copy"); menuItem.Click += new EventHandler(CopyAction); contextMenu.MenuItems.Add(menuItem); contextMenu.MenuItems.Add(menuItem); richTextBoxChatOut.ContextMenu = contextMenu; } void CopyAction(object sender, EventArgs e) { Clipboard.SetText(richTextBoxChatOut.SelectedText); } private void richTextBoxChatIn_MouseUp(object sender, MouseEventArgs e) { //click event ContextMenu contextMenu = new System.Windows.Forms.ContextMenu(); MenuItem menuItem = new MenuItem("Cut"); menuItem.Click += new EventHandler(CutAction2); contextMenu.MenuItems.Add(menuItem); menuItem = new MenuItem("Copy"); menuItem.Click += new EventHandler(CopyAction2); contextMenu.MenuItems.Add(menuItem); menuItem = new MenuItem("Paste"); menuItem.Click += new EventHandler(PasteAction2); contextMenu.MenuItems.Add(menuItem); richTextBoxChatIn.ContextMenu = contextMenu; } void CutAction2(object sender, EventArgs e) { richTextBoxChatIn.Cut(); } void CopyAction2(object sender, EventArgs e) { Clipboard.SetText(richTextBoxChatIn.SelectedText); } void PasteAction2(object sender, EventArgs e) { if (Clipboard.ContainsText()) { richTextBoxChatIn.Text += Clipboard.GetText(TextDataFormat.Text).ToString(); } } private void richTextBoxChatIn_TextChanged(object sender, EventArgs e) { Sock.MyTypingStatus(true); updateToolStrip(); _lastTyped.Stop(); // resets timer _lastTyped.Start(); GC.Collect(); // just helps ok } private void _lastTyped_Tick(object sender, EventArgs e) { Sock.MyTypingStatus(false); updateToolStrip(); } private void updateToolStrip() { if (!isExit) { this.Invoke((MethodInvoker)delegate { try { string list = Sock.TypingBuddyList; if (String.IsNullOrWhiteSpace(list)) this.toolStripLabelDisplay.Text = ""; else this.toolStripLabelDisplay.Text = "Typing: " + list; } catch { } }); } } private void Chatter_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; else e.Effect = DragDropEffects.None; } private void Chatter_DragDrop(object sender, DragEventArgs e) { if (this.comboBoxUsers.SelectedIndex == 0) { appendText(richTextBoxChatOut, "Warning: Cannot send to all users." + Environment.NewLine, Color.LightGreen); } if (e.Data.GetDataPresent(DataFormats.FileDrop)) { var files = (string[])e.Data.GetData(DataFormats.FileDrop); if (buddyList.ContainsKey(this.comboBoxUsers.Text)) { string file = files[0]; appendText(richTextBoxChatOut, "Me:\t\t", Color.LightGreen); appendText(richTextBoxChatOut, "Sending File: " + file + Environment.NewLine, Color.LightSalmon); richTextBoxChatOut.ScrollToCaret(); string ip = buddyList[this.comboBoxUsers.Text]; string fullname = this.comboBoxUsers.Text; Task.Factory.StartNew(() => dotheFileXfer(file, ip, fullname)); } } } #endregion #region File Drag & Drop Stream Helpers private void dotheFileXfer(string filepath, string ip, string fullname) { try { using (Stream source = File.OpenRead(filepath)) { byte[] buffer = new byte[1024 * 7]; int bytesRead; int chunkCount = 0; while ((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0) { if (isExit) return; if (!handleFileIO(buffer, bytesRead, filepath, chunkCount++, ip, fullname)) throw new Exception("file transfer errors on chunk: " + chunkCount); if (chunkCount % 12 == 0) InjectTestMessage("Working..."); } // send end of file confirmation buffer = new byte[0]; if (!handleFileIO(buffer, 0, filepath, -1, ip, fullname)) if (!handleFileIO(buffer, 0, filepath, -1, ip, fullname)) throw new Exception("file transfer errors on chunk: " + chunkCount); InjectTestMessage("Completed."); } } catch (Exception ex) { InjectTestMessage("ERROR: " + filepath + ":" + ex.ToString()); } } private MessageEventArgs _e = null; private ManualResetEvent AckDone = new ManualResetEvent(false); private void Sock_Ack(MessageEventArgs e) { _e = e; AckDone.Set(); } private bool handleFileIO(byte[] buffer, int length, string filepath, int chunk, string ip, string fullname) { string fileData = StringCompressor.ToHexString(buffer, length); string m = "<OBJECT>" + "FILE*" + chunk.ToString() + "*" + Path.GetFileName(filepath).Replace("?", "_") + "*" + fileData; string chk = Sock.Checksum(Sock.Checksum(m)); // do it twice, trust me _e = null; AckDone.Reset(); Sock.SendToBuddy(userName, false, ip, fullname, m, null); // wait for confirmations AckDone.WaitOne(5000); if (!isExit && (_e == null || !_e.Valid || _e.Checksum != chk)) { // try to repeat once _e = null; AckDone.Reset(); Sock.SendToBuddy(userName, false, ip, fullname, m, null); // wait for confirmations AckDone.WaitOne(5000); if (_e == null || !_e.Valid || _e.Checksum != chk) return false; } return true; } #endregion #region Debug Helper public void InjectTestMessage(string msg) { if (!isExit) { try { this.Invoke((MethodInvoker)delegate { if (!isExit) { appendText(richTextBoxChatOut, "Debug:\t\t", Color.LightGreen); } if (!isExit) { appendText(richTextBoxChatOut, msg + Environment.NewLine, Color.LightGray); } }); } catch { } } } #endregion } }<file_sep># chatter This is a Peer-to-Peer chat example in C# using TCP/IP sockets. Just for fun. # Peer-to-peer architecture P2P architecture is a commonly used computer networking architecture in which each workstation, or node, has the same capabilities and responsibilities. It is often compared and contrasted to the classic client/server architecture, in which some computers are dedicated to serving others. Peer-to-peer (P2P) computing or networking is a distributed application architecture that partitions tasks or workloads between peers. Peers are equally privileged, equipotent participants in the application. They are said to form a peer-to-peer network of nodes. # What is peer to peer network? When several computers are interconnected, but no computer occupies a privileged position, the network is usually referred to as a peer-to-peer network. In this type of network, every computer can communicate with all the other machines on the network, but in general each one stores its own files and runs its own applications. With a client-server network, one or more servers will perform critical functions on behalf of the other machines (the clients) on the network. These functions might include user authentication, data storage, and the running of large, shared, resource-intensive applications such as databases and client relationship management (CRM) software. Typically, both peer-to-peer and client-server networks rely on a shared Internet connection for access to external resources of these basic network structures. # Features: - Can drag and drop files into the upper RichTextBox, and will send almost any size to the connected peer. - Much cleaner Socket connections with Acknowledgments, and can even detect if the connected users are typing. - Can broadcast basic messages to all connected user(s). - Can automatically search for other peers on the network. - Debug mode allows extensive testing with console like printouts. <file_sep>๏ปฟ//#define DEBUG_LOOPBACK using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Net; using System.Net.Sockets; using System.Threading; using System.IO; using System.Security.Cryptography; namespace chatter { public class Sock { // helped a lot // https://msdn.microsoft.com/en-us/library/bew39x2a(v=vs.110).aspx static private int Port = 25011; static private int threadRunningCount = 0; static private bool stayAlive = true; static private string subsList; static private string myIP; static private string myPCName; static private Dictionary<string, Queue<string>> ipBuddyMessages = new Dictionary<string, Queue<string>>(); static private Dictionary<string, string> ipBuddyFullNameLookup = new Dictionary<string, string>(); static private Dictionary<string, int> ipBuddyIsTyping = new Dictionary<string, int>(); static private int myTypingStatus = 0; static private List<string> ipsInUse = new List<string>(); #region Public Events static public event NewDataReceivedEventHandler NewData; public delegate void NewDataReceivedEventHandler(MessageEventArgs e); static protected void OnNewDataReceived(MessageEventArgs e) { NewDataReceivedEventHandler handler = NewData; #if !DEBUG_LOOPBACK if (e.FriendIP == myIP) { debug("Newdata event ignored my ip!"); return; } #endif lock (handler) { if (handler != null) { handler(e); } } } static public event AckReceivedEventHandler Ack; public delegate void AckReceivedEventHandler(MessageEventArgs e); static protected void OnAckReceived(MessageEventArgs e) { AckReceivedEventHandler handler = Ack; if (e.FriendIP != myIP) { return; } lock (handler) { if (handler != null) { handler(e); } } } #endregion #region Typing Detection Helpers static public void MyTypingStatus(bool status) { if (status) { myTypingStatus++; if (myTypingStatus > 10) myTypingStatus = 10; } else { myTypingStatus /= 2; } } static public string TypingBuddyList { get { string typers = ""; try { foreach (string ip in ipsInUse) { if (ipBuddyFullNameLookup.ContainsKey(ip) && ipBuddyIsTyping[ip] != 0) typers += ipBuddyFullNameLookup[ip] + " "; } } catch { } return typers; } } #endregion #region General Startup Helpers static public bool SetSock(string myName, string ip, string subsList) { try { KillTasks(); stayAlive = true; myPCName = myName; Sock.subsList = subsList; myIP = ip; return true; } catch { return false; } } static public string GetIPAddress(string startWith) { IPHostEntry host; string localIP = "?"; host = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress ip in host.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { if (ip.ToString().StartsWith(startWith)) localIP = ip.ToString(); } } return localIP; } #endregion #region Thread Helpers static public void KillTasks() { stayAlive = false; while (threadRunningCount > 1) Thread.Sleep(200); } static void beginThread() { threadRunningCount++; debug("Thread count = " + threadRunningCount); } static void endThread() { threadRunningCount--; debug("Thread count = " + threadRunningCount); } static private bool checkForRunningThread(string buddyIp) { bool justAdded = false; lock (ipsInUse) { if (ipsInUse.Contains(buddyIp)) { return false; } else { ipsInUse.Add(buddyIp); justAdded = true; } } return justAdded; } #endregion #region Listening Socket Agent Thread static private void StartListening(IPHostEntry ipHostInfo) { //beginThread(); debug("Listening agent launched"); while (stayAlive) { try { IPAddress ipAddress = ipHostInfo.AddressList[0]; IPEndPoint localEndPoint = new IPEndPoint(ipAddress, Port); // Create a TCP/IP socket. Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); listener.Bind(localEndPoint); listener.Listen(10); while (stayAlive) { Socket handler = listener.Accept(); string buddyIp = handler.RemoteEndPoint.ToString(); int index = buddyIp.IndexOf(':'); if (index > -1) buddyIp = buddyIp.Substring(0, index); #if !DEBUG_LOOPBACK if (buddyIp == myIP) { // just ingore this situation handler.Shutdown(SocketShutdown.Both); handler.Disconnect(false); handler.Close(); debug("Listening agent ignored my ip!"); continue; } #endif if (!checkForRunningThread(buddyIp)) { handler.Shutdown(SocketShutdown.Both); handler.Disconnect(false); handler.Close(); debug("Listening agent skipped ip: " + buddyIp); continue; } debug("SSListener started for " + buddyIp); Task.Factory.StartNew(() => StartServerSide(handler, buddyIp)); } } catch (Exception e) { debug("Listening agent exception: " + e.ToString()); } Thread.Sleep(50); } //endThread(); } #endregion #region Server Thread static private void StartServerSide(Socket handler, string buddyIp) { beginThread(); Thread.Sleep(50); debug("Server thread launched"); int errors = 0; try { CMessageHandler m = new CMessageHandler("ServerMH", buddyIp, myIP); if (!ipBuddyMessages.ContainsKey(buddyIp)) ipBuddyMessages.Add(buddyIp, new Queue<string>()); if (!ipBuddyIsTyping.ContainsKey(buddyIp)) ipBuddyIsTyping.Add(buddyIp, 0); ipBuddyMessages[buddyIp].Enqueue(CMessageHandler.GenerateMessage(myPCName, myIP, "Connected!")); handler.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, false); // An incoming connection needs to be processed. while (stayAlive) { if (ipBuddyMessages[buddyIp].Count > 0) { lock (ipBuddyMessages[buddyIp]) { try { m.AddMessageToSend(ipBuddyMessages[buddyIp].Dequeue()); } catch { } } } MessageEventArgs mea; CMessageHandler.MsgState state = m.ProcessStates(out mea); messageHandling(m, mea); // Write to Client as needed if (state == CMessageHandler.MsgState.ReadyForRemote || state == CMessageHandler.MsgState.SendAck) { debug("Server sent out msg to " + buddyIp); send(handler, m.MessageReady, m); } else { if (myTypingStatus > 0) send(handler, "\t", m); else send(handler, " ", m); Thread.Sleep(150); // slow down pinging } if (!receive(handler, m)) { if (errors++ >= 3) { debug("Server error " + buddyIp); break; } } else errors = 0; CSavedIPs.AppendIP(buddyIp); } } catch (Exception e) { debug("Server exception for " + buddyIp + e.ToString()); if (_debug != null && ipBuddyFullNameLookup.ContainsKey(buddyIp)) _debug.InjectTestMessage("User aborted: " + ipBuddyFullNameLookup[buddyIp]); } if (handler != null) { handler.Shutdown(SocketShutdown.Both); handler.Disconnect(false); handler.Close(); //handler.Dispose(); } lock (ipsInUse) { if (ipsInUse.Contains(buddyIp)) ipsInUse.Remove(buddyIp); } //lock (ipBuddyMessages) //{ // if (ipBuddyMessages.ContainsKey(buddyIp)) // ipBuddyMessages.Remove(buddyIp); //} endThread(); } #endregion #region Server Thread Launcher static public string StartServer() { // Establish the local endpoint for the socket. // Dns.GetHostName returns the name of the // host running the application. string hostName = Dns.GetHostName(); IPHostEntry ipHostInfo = Dns.Resolve(hostName); // obsolete but it works if (CSavedIPs.Subs == "") { string subs = ""; foreach (IPAddress i in ipHostInfo.AddressList) { if (subs != "") subs += ","; string ip = i.ToString(); int loc = ip.IndexOf('.'); loc = ip.IndexOf('.', loc + 1); loc = ip.IndexOf('.', loc + 1); subs += ip.Substring(0, loc); } CSavedIPs.ChangeSubList(subs); } Task.Factory.StartNew(() => StartListening(ipHostInfo)); return CSavedIPs.Subs; } #endregion #region Message Handling static private void messageHandling(CMessageHandler m, MessageEventArgs mea) { if (mea == null) { } else if (mea.Valid && !String.IsNullOrWhiteSpace(mea.TextFromFriend)) { ipBuddyFullNameLookup[mea.FriendIP] = mea.FriendName; OnNewDataReceived(mea); OnAckReceived(mea); // Update good ip list as needed CSavedIPs.AppendIP(mea.FriendIP); // Signal that all bytes have been received. m.ReceiveDone.Set(); } else { OnAckReceived(mea); } } #endregion #region Client Thread static public void StartClientSide(Socket sender, string buddyIp) { beginThread(); debug("Client thread launched"); int errors = 0; try { #if !DEBUG_LOOPBACK if (!checkForRunningThread(buddyIp)) { endThread(); debug("Client ignored this ip: " + buddyIp); return; } #endif if (!ipBuddyMessages.ContainsKey(buddyIp)) ipBuddyMessages.Add(buddyIp, new Queue<string>()); if (!ipBuddyIsTyping.ContainsKey(buddyIp)) ipBuddyIsTyping.Add(buddyIp, 0); ipBuddyMessages[buddyIp].Enqueue(CMessageHandler.GenerateMessage(myPCName, myIP, "Connected!")); CMessageHandler m = new CMessageHandler("ClientMH", buddyIp, myIP); // Enter the working loop while (stayAlive) { if (ipBuddyMessages[buddyIp].Count > 0) { lock (ipBuddyMessages[buddyIp]) { try { m.AddMessageToSend(ipBuddyMessages[buddyIp].Dequeue()); } catch { } } } MessageEventArgs mea; CMessageHandler.MsgState state = m.ProcessStates(out mea); messageHandling(m, mea); // Write to Server as needed if (state == CMessageHandler.MsgState.ReadyForRemote || state == CMessageHandler.MsgState.SendAck) { debug("Client sent out msg to " + buddyIp); send(sender, m.MessageReady, m); } else { if (myTypingStatus > 0) send(sender, "\t", m); else send(sender, " ", m); Thread.Sleep(150); // slow down pinging } if (!receive(sender, m)) { if (errors++ >= 3) { debug("Client error " + buddyIp); break; } } else errors = 0; CSavedIPs.AppendIP(buddyIp); } sender.Shutdown(SocketShutdown.Both); sender.Close(); } catch (Exception e) { debug("Client exception for " + buddyIp + e.ToString()); if (_debug != null && ipBuddyFullNameLookup.ContainsKey(buddyIp)) _debug.InjectTestMessage("User aborted: " + ipBuddyFullNameLookup[buddyIp]); } lock (ipsInUse) { if (ipsInUse.Contains(buddyIp)) ipsInUse.Remove(buddyIp); } //lock (ipBuddyMessages) //{ // if (ipBuddyMessages.ContainsKey(buddyIp)) // ipBuddyMessages.Remove(buddyIp); //} endThread(); } #endregion #region Client Thread Launcher - a.k.a. Send to Buddy static public bool SendToBuddy(string myName, bool forceReconnect, string buddyIp, string buddyFullName, string msg, Socket client) { #if !DEBUG_LOOPBACK if (buddyIp == myIP) return true; // just ignore this situation #endif string fullMsg = CMessageHandler.GenerateMessage(myName, myIP, msg); if (client != null || forceReconnect) { #if DEBUG_LOOPBACK if (ipBuddyMessages.Count > 0 && ipsInUse.Contains(buddyIp)) return false; #else if (ipsInUse.Contains(buddyIp)) return false; #endif // this is a new connection! //if (!ipBuddyMessages.ContainsKey(buddyIp)) // ipBuddyMessages.Add(buddyIp, new Queue<string>()); //ipBuddyMessages[buddyIp].Enqueue(fullMsg); if (!String.IsNullOrEmpty(buddyFullName) && !ipBuddyFullNameLookup.ContainsKey(buddyIp)) ipBuddyFullNameLookup[buddyIp] = buddyFullName; debug("Client starting for " + buddyIp); Task.Factory.StartNew(() => StartClientSide(client, buddyIp)); } else { if (ipsInUse.Contains(buddyIp)) { lock (ipBuddyMessages[buddyIp]) { ipBuddyMessages[buddyIp].Enqueue(fullMsg); } } else { //#if !DEBUG_LOOPBACK //Task.Factory.StartNew(() => StartClientSide(buddyIp)); //#endif return false; // signal that this message did not go thru } } return true; } #endregion #region Receive Asynchronous Callback // Size of receive buffer. static private int BufferSize { get { return 1024 * 100; } } // Receive buffer. static private byte[] bufferRx = null; static private bool receive(Socket client, CMessageHandler m) { // Create the state object. StateObject state = new StateObject(m, client); bool ok = false; try { state.bytesRead = 0; if (bufferRx == null) bufferRx = new byte[BufferSize]; // Begin receiving the data from the remote device. client.BeginReceive(bufferRx, 0, BufferSize, 0, new AsyncCallback(receiveCallback), state); m.ReceiveDone.WaitOne(); ok = !state.Error; } catch (Exception e) { debug(m.Name + " " + e.ToString()); } //state.Dispose(); return ok; } private static void receiveCallback(IAsyncResult ar) { StateObject state = (StateObject)ar.AsyncState; Socket client = state.workSocket; try { do { // Read data from the remote device. state.bytesRead = client.EndReceive(ar); if (state.bytesRead > 0) { // pump message and detect user typing string buddyIp; bool isBuddyTyping; string msg = Encoding.ASCII.GetString(bufferRx, 0, state.bytesRead); state.m.PumpMessageFromRemote(msg, out buddyIp, out isBuddyTyping); if (!String.IsNullOrWhiteSpace(buddyIp) && ipBuddyIsTyping.ContainsKey(buddyIp)) { if (isBuddyTyping) { ipBuddyIsTyping[buddyIp]++; if (ipBuddyIsTyping[buddyIp] > 10) ipBuddyIsTyping[buddyIp] = 10; } else { // wait a little before turning off if (ipBuddyIsTyping[buddyIp] > 0) ipBuddyIsTyping[buddyIp]--; } } if (client.Available > 0) { bufferRx = new byte[BufferSize]; client.BeginReceive(bufferRx, 0, BufferSize, 0, new AsyncCallback(receiveCallback), state); } else break; } } while (state.bytesRead > 0); } catch (Exception e) { debug("AR error " + e.ToString()); state.bytesRead = 0; state.Error = true; } // Signal that all bytes have been received. if (!state.disposed) { state.m.ReceiveDone.Set(); if (state.bytesRead == 0) state.Dispose(); } } #endregion #region Send Asynchronous Callback static private void send(Socket client, String data, CMessageHandler m) { // Create the state object. StateObject state = new StateObject(m, client); // Convert the string data to byte data using ASCII encoding. byte[] byteData = Encoding.ASCII.GetBytes(data); // Begin sending the data to the remote device. client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(sendCallback), state); m.SendDone.WaitOne(); m.SendDone.Reset(); state.Dispose(); } private static void sendCallback(IAsyncResult ar) { StateObject state = (StateObject)ar.AsyncState; try { // Retrieve the socket from the state object. Socket client = state.workSocket; // Complete sending the data to the remote device. client.EndSend(ar); } catch (Exception e) { state.Error = true; debug(e.ToString()); } // Signal that all bytes have been sent. state.m.SendDone.Set(); } #endregion #region Client Connect Asynchronous Callback static private void connectCallback(IAsyncResult ar) { try { // Retrieve the socket from the state object. Socket client = (Socket)ar.AsyncState; // Complete the connection. client.EndConnect(ar); debug("Socket connected to " + client.RemoteEndPoint.ToString()); // Signal that the connection has been made. SendToBuddy(myPCName, true, client.RemoteEndPoint.ToString().Split(':')[0], "", "Connected!", client); } catch //(Exception e) { //debug(e.ToString()); } } #endregion #region Searching Thread static public void StartSearching(Chatter me) { _debug = me; Task.Factory.StartNew(() => { beginThread(); #if DEBUG_LOOPBACK debug("Loopback enabled, testing"); #endif debug("Search thread launched"); string[] octs = myIP.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries); List<string> subsToUse = new List<string>(subsList.Split(',')); subsToUse.ForEach(debug); // protect search function from invalid subnet parts bool ok = true; foreach (string sub in subsToUse) { if (sub.Split('.').Count() != 3) { ok = false; break; } foreach (string o in sub.Split('.')) { foreach (char c in o) if (c < '0' || c > '9') { ok = false; break; } if (ok) { if (Convert.ToInt32(o) > 255) ok = false; } } } if (ok) { int theSubIndex = 0; int subsubMe = Convert.ToInt32(octs[3]); string subPart = subsToUse[theSubIndex++].Trim(); int subsubStart = 2; #if DEBUG_LOOPBACK subsubStart = subsubMe - 1; // give it a little more time #endif string ipp = ""; int index = 0; bool usingPreviousList = true; int counts = 0; while (stayAlive) { using (TcpClient tcpClient = new TcpClient()) { try { if (usingPreviousList) { if (CSavedIPs.PreviousIPList.Count > index) { ipp = CSavedIPs.PreviousIPList[index++]; } else { index = 0; usingPreviousList = false; } } if (!usingPreviousList) { ipp = subPart + "." + subsubStart; } #if DEBUG_LOOPBACK if (!ipsInUse.Contains(ipp)) #else if (ipp != myIP && !ipsInUse.Contains(ipp)) #endif { // Create a TCP/IP socket. Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); var result = client.BeginConnect(ipp, Convert.ToInt32(Port), new AsyncCallback(connectCallback), client); if (result.AsyncWaitHandle.WaitOne(800)) { debug("Found buddy @" + ipp); } } } catch { } if (!usingPreviousList) { counts++; if (CSavedIPs.PreviousIPList.Count > 0 && counts >= 13) { counts = 0; usingPreviousList = true; continue; // try IP list again } subsubStart++; if (subsubStart == 127) subsubStart++; if (subsubStart >= 254) { subsubStart = 2; if (theSubIndex >= subsToUse.Count()) break; // stop searching! subPart = subsToUse[theSubIndex++].Trim(); } } } } } else { debug("Search invalid subnet(s)"); } endThread(); me.EnableGoButton(); return; }); } #endregion #region Checksum Msg Helper static public string Checksum(string msg) { MD5 md5 = System.Security.Cryptography.MD5.Create(); byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(msg); byte[] hash = md5.ComputeHash(inputBytes); return hash[0].ToString("X2") + hash[1].ToString("X2") + hash[2].ToString("X2") + hash[3].ToString("X2"); } #endregion #region Debug Helper static public bool InDebug { get; set; } static private Chatter _debug = null; static public void debug(string msg) { #if (!DEBUG) if (InDebug) #endif if (_debug != null) _debug.InjectTestMessage("{ " + msg + " }"); } #endregion } #region State object for receiving data from remote device. public class StateObject : IDisposable { public StateObject(CMessageHandler mh, Socket socket) { m = mh; workSocket = socket; } public CMessageHandler m; public Socket workSocket; public bool Error = false; public int bytesRead = 0; public bool disposed = false; public void Dispose() { m = null; workSocket = null; disposed = true; } } #endregion }
8560c063ede165d739371e15d5966358de303b19
[ "Markdown", "C#" ]
7
C#
HyeongD/chatter
c802e07a48f72ef854aa01cbba0ddf31377cb27c
866b80e382ac5f7f6e68456ecc9d63889909f0ac
refs/heads/master
<file_sep>import React from 'react' import PropTypes from 'prop-types' import {Link} from 'react-router-dom' import LoadingDots from './LoadingDots' const Header = ({loading}) => { return ( <nav> <Link to='/'>Home</Link> {' | '} <Link to='/courses'>Courses</Link> {' | '} <Link to='/about'>About</Link> {loading && <LoadingDots interval={100} dots={20} />} </nav> ) } Header.propTypes = { loading: PropTypes.bool.isRequired } export default Header <file_sep>import CourseApi from '../api/mockCourseApi' import * as types from './actionTypes' import {beginAjaxCall, ajaxCallError} from './ajaxStatusActions' export function loadCoursesSuccess (courses) { return {type: types.LOAD_COURSES_SUCCESS, courses} } export function createCourseSuccess (course) { return {type: types.CREATE_COURSE_SUCCESS, course} } export function updateCourseSuccess (course) { return {type: types.UPDATE_COURSE_SUCCESS, course} } // Functions below handle asynchronous calls. // Each returns a function that accepts a dispatch. // These are used by redux-thunk to support asynchronous interactions. export function loadCourses () { return function (dispatch) { dispatch(beginAjaxCall()) return CourseApi.getAllCourses().then(courses => { dispatch(loadCoursesSuccess(courses)) }).catch(error => { dispatch(ajaxCallError(error)) throw (error) }) } } export function saveCourse (course) { return function (dispatch, getState) { dispatch(beginAjaxCall()) return CourseApi.saveCourse(course).then(course => { course.id ? dispatch(updateCourseSuccess(course)) : dispatch(createCourseSuccess(course)) }).catch(error => { dispatch(ajaxCallError(error)) throw (error) }) } } <file_sep>import React from 'react' import {Route} from 'react-router-dom' import App from './components/App' import HomePage from './components/home/HomePage' import CoursesPage from './components/course/CoursesPage' import ManageCoursePage from './components/course/ManageCoursePage' import AboutPage from './components/about/AboutPage' export default () => { return ( <Route path='/'> <App> <Route exact path='/' component={HomePage} /> <Route exact path='/courses' component={CoursesPage} /> <Route exact path='/course/:id' component={ManageCoursePage} /> <Route exact path='/course' component={ManageCoursePage} /> <Route exact path='/about' component={AboutPage} /> </App> </Route> ) }
7328416d9379286b2c9c8f8c70f8415a85418af8
[ "JavaScript" ]
3
JavaScript
jonwainwright/pluralsight-redux-starter-mmt
9fac88e6439ba745af4900040514b38fd4254e46
f42258d6d70a96c88dd360b2daa1f03940fc9c93
refs/heads/master
<repo_name>sowmyaatmpdash/dashapp<file_sep>/DashApp/Scripts/Custom/site.js $(document).ready(function () { $('#ExistingUser').click(function (e) { location.href = '@Url.Content("~/User/UserLogin/")'; return false; }); $('#button-save').click(function () { var emailAddressValue = $("#textboxEmailAddress").val(); if (emailAddressValue == '') { $("#textboxpassword ").after('<span class="error">Email address is empty</span>'); return false; } if (emailAddressValue.length < 6) { $("#textboxpassword ").after('<span class="error">Email address is too short</span>'); return false; } if (emailAddressValue.length > 30) { $("#textboxpassword ").after('<span class="error">Email address is too long</span>'); return false; } var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i; return pattern.test(emailAddressValue); var passwordValue = $("#textboxpassword").val(); if (passwordValue == '') { $("#textboxpassword ").after('<span class="error">Please specify password</span>'); return false; } if (passwordValue.length < 6) { $("#textboxpassword").after('<span class="error">Password is too short.</span>'); return false; } if (passwordValue.length > 20) { $("#textboxpassword").after('<span class="error">Password is too long</span>'); return false; } if (passwordValue.search(/\d/) == -1) { $("#textboxpassword").after('<span class="error">Password should contain atleast one digit</span>'); return false; } else if (passwordValue.search(/[a-zA-Z]/) == -1) { $("#textboxpassword").after('<span class="error">Password should contain atleast one uppercase</span>'); return false; } else if (passwordValue.search(/[^a-zA-Z0-9\!\@\#\$\%\^\&\*\(\)\_\+]/) != -1) { $("#textboxpassword").after('<span class="error">Password contains invalid charecter</span>'); return false; } var addressValue = $("#textboxaddress").val(); if (addressValue == '') { $("#textboxaddress").after('<span class="error">Please specify address</span>'); return false; } if (addressValue.length < 6) { $("#textboxaddress").after('<span class="error">address is too short.</span>'); return false; } if (addressValue.length > 20) { $("#textboxaddress").after('<span class="error">address is too long</span>'); return false; } }); $("#btnShowModal").click(function () { $("#loginModal").modal('show'); }); $("#btnHideModal").click(function () { $("#loginModal").modal('hide'); }); $('div.emailclass').focusout(function () { var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i; return pattern.test(emailAddress); }); function checkPwd(str) { if (str.length < 6) { return ("too_short password"); } else if (str.length > 50) { return ("too_long password"); } else if (str.search(/\d/) == -1) { return ("no_number in password"); } else if (str.search(/[a-zA-Z]/) == -1) { return ("no_letter in password"); } else if (str.search(/[^a-zA-Z0-9\!\@\#\$\%\^\&\*\(\)\_\+]/) != -1) { return ("bad_char in password"); } return true; } $('div.emailclass').keyup(function () { if ($("#Validatetextbox").val() == "") { alert("There is no value in textbox"); } }); } );<file_sep>/DashApp/Models/UserProfileViewModel.cs ๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Web; namespace DashApp.Models { public class UserProfileViewModel { public int ID { get; set; } public string UserEmailId { get; set; } public string Password { get; set; } public string confirmPassword { get; set; } public string Gender { get; set; } public string CountryName { get; set; } public string StateName { get; set; } public string CityName { get; set; } public string Address { get; set; } } }<file_sep>/DashApp/Controllers/UserController.cs ๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Security; using DashApp.Models; using DashApp.Repsoitory; namespace DashApp.Controllers { public class UserController : Controller { // GET: User public ActionResult Login() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Login(UserProfileViewModel objUser) { if (ModelState.IsValid) { UserProfile profile = new UserProfile(); profile.ID = objUser.ID; profile.Password = <PASSWORD>; profile.StateName = objUser.StateName; profile.UserEmailId = objUser.UserEmailId; profile.Gender = objUser.Gender; profile.CityName = objUser.CityName; profile.Address = objUser.Address; profile.CountryName = objUser.CountryName; using (RegMVCEntities db = new RegMVCEntities()) { db.UserProfiles.Add(profile); db.SaveChanges(); } } return View(objUser); } public ActionResult UserLogin() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult UserLogin(UserProfileViewModel objUser) { if (ModelState.IsValid) { UserProfile profile = new UserProfile(); profile.ID = objUser.ID; profile.Password = <PASSWORD>; using (RegMVCEntities db = new RegMVCEntities()) { var obj = db.UserProfiles.Where(a => a.UserEmailId.Equals(profile.UserEmailId) && a.Password.Equals(profile.Password)).FirstOrDefault(); if (obj != null) { Session["UserID"] = obj.UserEmailId.ToString(); Session["UserName"] = obj.UserEmailId.ToString(); return RedirectToAction("UserProfile", obj); } } } return View(objUser); } [Authorize] public ActionResult UserProfile(UserProfile userProfile) { var userProfileViewModel = new UserProfileViewModel(); userProfileViewModel.ID = userProfile.ID; userProfileViewModel.Password = <PASSWORD>; userProfileViewModel.StateName = userProfile.StateName; userProfileViewModel.UserEmailId = userProfile.UserEmailId; userProfileViewModel.Gender = userProfile.Gender; userProfileViewModel.CityName = userProfile.CityName; userProfileViewModel.Address = userProfile.Address; userProfileViewModel.CountryName = userProfile.CountryName; userProfileViewModel.confirmPassword = userProfile.<PASSWORD>; if (Session["UserID"] != null) { return View(userProfileViewModel); } else { return RedirectToAction("Login"); } } [HttpPost] [ValidateAntiForgeryToken] [Authorize] public ActionResult UserProfile(UserProfileViewModel objUser) { if (ModelState.IsValid) { UserProfile profile = new UserProfile(); profile.ID = objUser.ID; profile.Password = <PASSWORD>; profile.StateName = objUser.StateName; profile.UserEmailId = objUser.UserEmailId; profile.Gender = objUser.Gender; profile.CityName = objUser.CityName; profile.Address = objUser.Address; profile.CountryName = objUser.CountryName; using (RegMVCEntities db = new RegMVCEntities()) { var obj = db.UserProfiles.Where(a => a.UserEmailId.Equals(profile.UserEmailId) && a.Password.Equals(profile.Password)).FirstOrDefault(); if (obj != null) { obj = profile; db.SaveChanges(); } } } return View(objUser); } public ActionResult LogOut() { FormsAuthentication.SignOut(); Session.Abandon(); return RedirectToAction("Login"); } } }
3fb411183852eac255e94935f794bd07413cf4a4
[ "JavaScript", "C#" ]
3
JavaScript
sowmyaatmpdash/dashapp
938421b9d76c0140f36314ce56f41bcecea2f273
6fd45656216723c1edff3a5b29f0014f4dec12f0
refs/heads/master
<repo_name>SUMSC/Web-2.0<file_sep>/application/views/PfConsultView.class.php <?php class PfConsultView extends View { public function render($action="submit"){ if($action == "submit") { $this->submit(); return ; } else { $this->error(); return ; } } public function submit(){ $pages[] = APP_PATH."application/views/PF_Consult/form.php"; $pages[] = APP_PATH."application/views/Index/foot.php"; $pages[] = APP_PATH."application/views/Index/footer.php"; foreach($pages as $page){ $this->page($page);} } }<file_sep>/application/views/PF_Repairmen/backend.php <?php ob_start(); ?> <script type="text/javascript"> function Trim(str,is_global='g') { str = String(str); var result; result = str.replace(/(^\s+)|(\s+$)/g,""); if(is_global.toLowerCase()=="g") { result = result.replace(/\s/g,""); } return result; } function x(form) { var name = Trim(document.getElementById("name").value,"g"); var qq = Trim(document.getElementById("qq").value,"g"); var gender = Trim(document.getElementById("gender").value,"g"); var introduction = Trim(document.getElementById("introduction").value,"g"); if(name == "") { alert("่ฟ™ๅ››้กนๅ‡ไธ่ƒฝไธบ็ฉบๅ“ฆ๏ผ"); return false; } if(qq == "") { alert("่ฟ™ๅ››้กนๅ‡ไธ่ƒฝไธบ็ฉบๅ“ฆ๏ผ"); return false; } if(gender == "") { alert("่ฟ™ๅ››้กนๅ‡ไธ่ƒฝไธบ็ฉบๅ“ฆ๏ผ"); return false; } if(introduction == "") { alert("่ฟ™ๅ››้กนๅ‡ไธ่ƒฝไธบ็ฉบๅ“ฆ๏ผ"); return false; } return true; } </script> <table class="table table-striped table-responsive"> <caption>repairmen </caption> <thead> <colgroup> <col width="10%"></col> <col></col> <col></col> <col></col> <col></col> <col></col> <col width="30%"></col> </colgroup> <tr> <th class="text-danger">ACTION</th> <th>name</th> <th>qq</th> <th>gender</th> <th>head</th> <th>free</th> <th>Introductions</th> </tr> </thead> <tbody> <?php $repairmen = (new PfRepairmenModel)->PfRepairmenSelect(); foreach($repairmen as $repairman){ ?> <tr id=<?php echo $repairman['rid']; ?>> <td> <form action='' method='POST'> <button class="btn btn-warning" type='submit' name='delete' value=<?php echo $repairman['rid'] ?>>ๅˆ ้™คๆญคๆก</button> </form> <button class="btn btn-primary" data-toggle="modal" data-target=<?php echo "#Modal".$repairman['rid']?>> ไฟฎๆ”นๆก็›ฎ </button> <button class="btn btn-primary" data-toggle="modal" data-target=<?php echo "#HModal".$repairman['rid']?>> ไธŠไผ ๆ–ฐๅคดๅƒ </button> <div class="modal fade" id=<?php echo "HModal".$repairman['rid']?> tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> <form method="POST" action=<?php echo APP_URL."/PfRepairmen/head/".$repairman['rid']?> class="form-horizontal" role="form" enctype="multipart/form-data"> <input type="file" name="file" id="file"> <input type="submit" name="submit" value="ๆไบค"> </form> </div> </div> </div> </div> <div class="modal fade" id=<?php echo "Modal".$repairman['rid']?> tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> &times; </button> <h4 class="modal-title" id="myModalLabel"> <?php echo "Code#".$repairman['rid']."Changing"?> </h4> </div> <div class="modal-body"> <form method="POST" action=<?php echo APP_URL."/PfRepairmen/change/".$repairman['rid']?> class="form-horizontal" role="form" enctype="multipart/form-data"> <div class="form-group"> <label for="name" class="col-sm-4 control-label">Name</label> <div class="col-sm-8"> <input type="text" class="form-control" name="name" value=<?php echo $repairman['name']?> id=<?php echo "name".$repairman['rid']?> placeholder="name"> </div> </div> <div class="form-group"> <label for="qq" class="col-sm-4 control-label">qq</label> <div class="col-sm-8"> <input type="text" class="form-control" name="qq" value=<?php echo $repairman['qq']?> id=<?php echo "qq".$repairman['rid']?> placeholder="qq"> </div> </div> <div class="form-group"> <label for="gender tag" class="col-sm-4 control-label">gender tag</label> <div class="col-sm-8"> <input type="text" class="form-control" name="gender" value=<?php echo $repairman['gender']?> id=<?php echo "gender".$repairman['rid']?> placeholder="gender tag"> </div> </div> <div class="form-group"> <label for="introduction" class="col-sm-4 control-label">introduction</label> <div class="col-sm-8"> <textarea class="form-control" name="introduction" id=<?php echo "introduction".$repairman['rid']?> placeholder="introduction" cols="30" rows="4"><?php echo $repairman['introduction']?></textarea> </div> </div> <div class="form-group"> <label for="free" class="col-sm-4 control-label">ๆ˜ฏๅฆๆ˜พ็คบๅœจๅˆ—่กจไธญ</label> <div class="radio-inline"> <label> <input type="radio" name="free" id=<?php echo "free".$repairman['rid']?> value="1" checked> ๆ˜พ็คบ </label> </div> <div class="radio-inline"> <label> <input type="radio" name="free" id=<?php echo "notfree".$repairman['rid']?> value="0">ไธๆ˜พ็คบ </label> </div> </div> <div class="form-group"> <input type="submit" name="submit" value="ๆไบค"> </div> </form> </div> </div> </div> </div> </td> <td> <?php echo $repairman['name']; ?> </td> <td> <?php echo $repairman['qq']; ?> </td> <td> <?php echo $repairman['gender']; ?> </td> <td> <img width=150px height=150px src=<?php echo APP_URL.$repairman['headlink'];?> class='img-responsive center-block' /> </td> <td> <?php echo $repairman['free']; ?> </td> <td> <?php echo $repairman['introduction']; ?> </td> </tr> <?php } ?> </tbody> </table> <h1>ADD NEW</h1> <div class="container-fluid"> <div class="row"> <form method="POST" onsubmit="return x();" action="<?php echo APP_URL."/PfRepairmen/addNew"?>" enctype="multipart/form-data"> <div class="col-md-5"> <div class="form-group"> <input class="form-control" name="name" id="name" placeholder="็งฐๅ‘ผ" type="text"> </div> </div> <div class="col-md-5"> <div class="form-group"> <input class="form-control" name="qq" id="qq" placeholder="qq" type="text"> </div> </div> <div class="col-md-2"> <div class="form-group"> <input class="form-control" name="gender" id="gender" placeholder="male" type="text"> </div> </div> <div class="col-md-12"> <div class="form-group"> <textarea name="introduction" id="introduction" class="form-control" cols="30" rows="4" placeholder="introduction"></textarea> </div> </div> <div align="center" class="col-md-12"> <div class="form-group"> <input type="submit" name="submit" value="ๆไบค"> </div> </div> </form> </div> </div> <?php if(isset($_POST['delete'])){ $user = $_POST['delete']; $tempArray = array('rid' => $user); (new PfRepairmenModel)->PfRepairmenDelete($tempArray); header("Location:".APP_URL."/PfRepairmen/jumping"); } if(isset($_POST['change'])){ $user = $_POST['change']; $tempArray = array('rid' => $user); header("Location:".APP_URL."/PfRepairmen/jumping?"); } ?> <file_sep>/application/views/PfRepairmenView.class.php <?php class PfRepairmenView extends View { public function render($action="index"){ if($action == "index") { $this->index(); return ; } else if($action == "backend") { $this->backend(); return ; } else { $this->error(); return ; } } public function index(){ $pages[] = APP_PATH."application/views/Index/header.php"; $pages[] = APP_PATH."application/views/PF_Repairmen/title.php"; $pages[] = APP_PATH."application/views/PF_Repairmen/repairmen.php"; $pages[] = APP_PATH."application/views/Index/foot.php"; $pages[] = APP_PATH."application/views/Index/footer.php"; foreach($pages as $page){ $this->page($page);} } public function backend(){ $pages[] = APP_PATH."application/views/Index/header.php"; $pages[] = APP_PATH."application/views/PF_Repairmen/backend.php"; $pages[] = APP_PATH."application/views/Index/foot.php"; $pages[] = APP_PATH."application/views/Index/footer.php"; foreach($pages as $page){ $this->page($page);} } }<file_sep>/application/models/PfConsultModel.class.php <?php class PfConsultModel extends Model{ public function descriptionSelect($cid){ $sql = sprintf("select description from %s where cid = %d ", $this->_table , $cid); $sth = $this->_dbHandle->prepare($sql); if ( $sth->execute() ) return $sth->fetchAll(); return 0; } public function consultSelect(){ $sql = sprintf("select * from `%s` ", $this->_table); $sth = $this->_dbHandle->prepare($sql); if ( $sth->execute() ) return $sth->fetchAll(); return 0; } public function consultSelectMax(){ $sql = sprintf("select max(cid) as cid from `%s` ", $this->_table); $sth = $this->_dbHandle->prepare($sql); if ( $sth->execute() ) return $sth->fetchAll(); return 0; } public function consultInsert( $data ){ $sql = sprintf( "insert into `%s` %s", $this->_table, $this->formatInsert($data) ); $result = $this->querySQL($sql); return $result; } public function consultDelete( $data ){ $sql = sprintf( "delete from `%s` where %s", $this->_table, $this->formatWhere($data) ); $result = $this->querySQL($sql); return $result; } public function consultUpdate($set,$where){ $sql = sprintf( "update `%s`set %s where %s", $this->_table, $this->formatUpdate($set) ,$this->formatWhere($where) ); $result = $this->querySQL($sql); return $result; } }<file_sep>/application/views/PF_Index/title.php <h2 align="center"> ็”ต่„‘ไน‰ไฟฎ </h2> <?php<file_sep>/application/views/IndexView.class.php <?php class IndexView extends View{ /* * ๅฆ‚ๆžœ่ฟ™ไธช้กต้ข็ป„ไปถๅขžๅŠ  * ้‡ๅ†™ render() ๆธฒๆŸ“่ฟ™ไธช้กต้ข * */ public function render($action="index"){ if($action == "index"){ $this->index(); return ; } else{ $this->error(); return ; } } public function index(){ $pages[] = APP_PATH."application/views/Index/header.php"; //$pages[] = APP_PATH."application/views/Index/index.php"; $pages[] = APP_PATH."application/views/Index/content.php"; $pages[] = APP_PATH."application/views/Index/foot.php"; $pages[] = APP_PATH."application/views/Index/footer.php"; foreach($pages as $page){ $this->page($page); } } } <file_sep>/application/views/ACT_Index/backstageActivity.php <div> <h1>ไธŠไผ ๆดปๅŠจ</h1> </div> <form method="POST" action="test2.php" enctype="multipart/form-data"> ๆ ‡้ข˜๏ผš<input type="text" name="title"> <br><br> ๅœฐ็‚น๏ผš<input type="text" name="place"> <br><br> ๆ—ถ้—ด๏ผš<input type="text" name="links"> <br><br> ๆญฃๆ–‡๏ผš<textarea name="content" rows="25" cols="150"></textarea> <br><br> ๅคดๅ›พ๏ผš <input type="file" name="file" id="file"> <br><br> <p><input type="submit" name="submit" value="ๆไบค"onClick="check(form)"></p> </form> <?php include('ๆ•ฐๆฎๅบ“ๅญ˜ๅ…ฅtest.php') ?> <file_sep>/application/models/PfRepairmenModel.class.php <?php class PfRepairmenModel extends Model { public function qIDSelect($id){ $sql = sprintf("select qq from %s where rid = %d", $this->_table ,$id ); $sth = $this->_dbHandle->prepare($sql); if ( $sth->execute() ) return $sth->fetchAll(); return 0; } public function nameSelect($id){ $sql = sprintf("select name from %s where rid = %d", $this->_table ,$id ); $sth = $this->_dbHandle->prepare($sql); if ( $sth->execute() ) return $sth->fetchAll(); return 0; } public function PfRepairmenSelect(){ $sql = sprintf("select * from `%s` ", $this->_table); $sth = $this->_dbHandle->prepare($sql); if ( $sth->execute() ) return $sth->fetchAll(); return 0; } public function PfRepairmenInsert( $data ){ $sql = sprintf( "insert into `%s` %s", $this->_table, $this->formatInsert($data) ); $result = $this->querySQL($sql); return $result; } public function PfRepairmenDelete( $data ){ $sql = sprintf( "delete from `%s` where %s", $this->_table, $this->formatWhere($data) ); $result = $this->querySQL($sql); return $result; } public function PfRepairmenUpdate($set,$where){ $sql = sprintf( "update `%s`set %s where %s", $this->_table, $this->formatUpdate($set) ,$this->formatWhere($where) ); $result = $this->querySQL($sql); return $result; } }<file_sep>/application/models/GT_IndexModel.class.php <?php class GT_IndexModel extends Model { public function select( $keyword) { //echo "aaaa<br>"; //echo $keyword["type"]; //echo "<br>"; //echo $this->formatInsert($keyword); //echo "<br>"; //echo $this->formatUpdate($keyword); //echo $this->formatWhere($keyword); $sql = sprintf("select * from `%s` where %s", $this->_table,$this->formatWhere($keyword)); return $this->selectSQL($sql); } } <file_sep>/sql/msc.sql ๏ปฟdrop database if exists `MSC`; create database `MSC` default character set utf8 COLLATE utf8_general_ci ; use `MSC`; /* PF Part */ create table pfrepairmen( rid int unsigned auto_increment, name varchar(32), qq varchar(64), introduction varchar(512), gender varchar(16), headlink varchar(1024) default '/images/defaultHead.jpg', free varchar(16) default '0', primary key(rid) )engine=InnoDB default charset=utf8; create table pffaq( qid int unsigned auto_increment, question varchar(1024), answer varchar(2048), primary key(qid) )engine=InnoDB auto_increment=1 default charset=utf8; create table pfconsult( cid int unsigned auto_increment, rid int NOT NULL, consultant varchar(16), consultantContact varchar(24), description varchar(1024), submitTime datetime, primary key(cid) )engine=InnoDB auto_increment=1 default charset=utf8; /* ACT Part */ create table actAct( id varchar(20), name varchar(32), dcp varchar(2048), actime varchar(2048), actsite varchar(2048), sponsornm varchar(32), spemail varchar(64), sptel varchar(32), spqq varchar(32), role int default '0', primary key(name) )engine=InnoDB default charset=utf8; create table actApplicant( id varchar(20), appname varchar(32), appemail varchar(64), sex varchar(16), apptel varchar(32), appqq varchar(32), role int default '0', primary key(appname) )engine=InnoDB default charset=utf8; /* TU Part */ create table tuFiles( username varchar(32), -- ็”จๆˆทๅ admin varchar(4), -- ็”จๆˆทๅฏน่ฏฅๆ–‡ไปถ็š„็ฎก็†ๆƒ้™ filename varchar(64), filedirectory varchar(64), -- ไฝ็ฝฎ uploadtime DATETIME, -- ไธŠไผ ๆ—ถ้—ด changetime DATETIME, -- ๆ›ดๆ”นๆ—ถ้—ด fileid int auto_increment, filetype varchar(5), -- ๆ–‡ไปถ็ฑปๅž‹(ๆ ผๅผ) remarks varchar(128), -- ๆ ‡่ฎฐๅค‡ๆณจๅ•ฅ็š„ primary key(fileid) )engine=InnoDB default charset=utf8; /* GT Part */ /* create table gt_index( name varchar(128), href varchar(128), primary key(name) )engine=InnoDB default charset=utf8; INSERT INTO gt_index (name,href) values ( "BaiDu", "http://www.baidu.com" ); INSERT INTO gt_index (name,href) values ( "BaiD", "http://www.baidu.com" ); INSERT INTO gt_index (name,href) values ( "Bai", "http://www.baidu.com" ); */ create table gt_index( type varchar(128), name varchar(128), href varchar(128), primary key(name) )engine=InnoDB default charset=utf8; INSERT INTO gt_index (type,name,href) values ("software", "BaiDu", "http://www.baidu.com" ); INSERT INTO gt_index (type,name,href) values ("web" ,"BaiD", "http://www.baidu.com" ); INSERT INTO gt_index (type,name,href) values ( "book","Bai", "http://www.baidu.com" ); INSERT INTO gt_index (type,name,href) values ("software", "BDu", "http://www.baidu.com" ); INSERT INTO gt_index (type,name,href) values ("web" ,"BaDu", "http://www.baidu.com" ); INSERT INTO gt_index (type,name,href) values ( "book","B", "http://www.baidu.com" ); <file_sep>/application/controllers/TU_IndexController.class.php <?php class TU_IndexController extends Controller{ function index(){ $this->assign('title', '้ฆ–้กต'); $this->assign('content', 'php MVC'); $this->render("tu_index"); } public function test(){ $this->render("test"); } } <file_sep>/application/models/ACTModel.class.php <?php class ACTModel extends Model{ public function Activityselect(){ $sql = sprintf("select * from `%s ", $this->_table); $sth = $this->_dbHandle->prepare($sql); if ( $sth->execute() ) return $sth->fetchAll(); return 0; } } public function Activityinsert( $data ){ $sql = sprintf( "insert into `%s` %s", $this->_table, $this->formatInsert($data) ); return $this->querySQL($sql); return $result; } public function Activitydelet($rid) { $sql = sprintf( "delete from `%s` where %s", $this->_table, $this->formatWhere($data) ); $result = $this->query($sql); return $result; } } public function ActivityUpdate($set,$where){ $sql = sprintf( "update `%s`set %s where %s", $this->_table, $this->formatUpdate($set) ,$this->formatWhere($where) ); $result = $this->query($sql); return $result; } } public function Submitselect() { $sql = sprintf("select * from `%s ", $this->_table); $sth = $this->_dbHandle->prepare($sql); if ( $sth->execute() ) return $sth->fetchAll(); return 0; } public function SubmitUpdate($set,$where){ $sql = sprintf( "update `%s`set %s where %s", $this->_table, $this->formatUpdate($set) ,$this->formatWhere($where) ); $result = $this->query($sql); return $result; } } public function Submitinsert( $data ){ $sql = sprintf( "insert into `%s` %s", $this->_table, $this->formatInsert($data) ); return $this->querySQL($sql); return $result; } public function Submitdelet($rid) { $sql = sprintf( "delete from `%s` where %s", $this->_table, $this->formatWhere($data) ); $result = $this->query($sql); return $result; } } ?><file_sep>/application/views/PF_Index/addfaq.php <?php ob_start(); ?> <script type="text/javascript"> function Trim(str,is_global='g') { str = String(str); var result; result = str.replace(/(^\s+)|(\s+$)/g,""); if(is_global.toLowerCase()=="g") { result = result.replace(/\s/g,""); } return result; } function x(form) { var question = Trim(document.getElementById("question").value,"g"); var answer = Trim(document.getElementById("answer").value,"g"); if(question == "") { alert("่ฟ™ไธค้กนๅ‡ไธ่ƒฝไธบ็ฉบๅ“ฆ๏ผ"); return false; } if(answer == "") { alert("่ฟ™ไธค้กนๅ‡ไธ่ƒฝไธบ็ฉบๅ“ฆ๏ผ"); return false; } return true; } </script> <table class="table table-striped table-responsive"> <caption>repairmen </caption> <thead> <colgroup> <col width="10%"></col> <col width="10%"></col> <col width="35%"></col> <col></col> </colgroup> <tr> <th>ID:</th> <th></th> <th>Q:</th> <th>A:</th> </tr> </thead> <tbody> <?php $faqs = (new PfFaqModel)->faqSelect(); foreach($faqs as $faq){ ?> <tr id=<?php echo $faq['qid']; ?>> <td><?php echo $faq['qid']; ?></td> <td> <form action='' method='POST'> <button class="btn btn-warning" type='submit' name='delete' value=<?php echo $faq['qid'] ?>>ๅˆ ้™คๆญคๆก</button> </form> </td> <td> <?php echo $faq['question']; ?> </td> <td> <?php echo $faq['answer']; ?> </td> </tr> <?php } ?> </tbody> </table> <h1>ADD NEW</h1> <div class="container-fluid"> <div class="row"> <form method="POST" onsubmit="return x();" action="<?php echo APP_URL."/PfFaq/newFaq"?>" enctype="multipart/form-data"> <div class="col-md-12"> <div class="form-group"> <textarea name="question" id="question" class="form-control" cols="30" rows="4" placeholder="question"></textarea> </div> </div> <div class="col-md-12"> <div class="form-group"> <textarea name="answer" id="answer" class="form-control" cols="30" rows="4" placeholder="answer"></textarea> </div> </div> <div align="center" class="col-md-12"> <div class="form-group"> <input type="submit" name="submit" value="ๆไบค"> </div> </div> </form> </div> </div> <?php if(isset($_POST['delete'])){ $qid = $_POST['delete']; $tempArray = array('rid' => $qid); (new PfRepairmenModel)->PfRepairmenDelete($tempArray); header("Location:".APP_URL."/PfFaq/addFaq"); } ?> <file_sep>/application/views/PfFaqView.class.php <?php class PfFaqView extends View { public function render($action="index"){ if($action == "index") { $this->index(); return ; } else if($action == "addFaq") { $this->addFaq(); return ; } else { $this->error(); return ; } } public function index(){ $pages[] = APP_PATH."application/views/Index/header.php"; $pages[] = APP_PATH."application/views/PF_Index/title.php"; foreach($pages as $page){ $this->page($page); } $faqs = (new PfFaqModel)->faqSelect(); echo "<h2 align='center'>ๅœจๆŠฅไฟฎไน‹ๅ‰๏ผŒๅปบ่ฎฎๆ‚จๅ…ˆๆต่งˆไปฅไธ‹ๅธธ่ง้—ฎ้ข˜๏ผš</h2>"; foreach($faqs as $faq){ echo "<hr>"; echo "<p>Q:".$faq['question']."</p>"; echo "<p>A:".$faq['answer']."</p>"; } while (array_shift($pages)) {} $pages[] = APP_PATH."application/views/PF_Index/form.php"; $pages[] = APP_PATH."application/views/Index/foot.php"; $pages[] = APP_PATH."application/views/Index/footer.php"; foreach($pages as $page){ $this->page($page);} } public function addFaq(){ $pages[] = APP_PATH."application/views/Index/header.php"; $pages[] = APP_PATH."application/views/PF_Index/addfaq.php"; $pages[] = APP_PATH."application/views/Index/foot.php"; $pages[] = APP_PATH."application/views/Index/footer.php"; foreach($pages as $page){ $this->page($page);} } }<file_sep>/DOCS/platformlist.md ##PLATFORM FUNCTION LIST## * ๅ’จ่ฏข * tipsSelect()ใ€€|ใ€€Model็ฑป๏ผŒๆ— ๅ‚ๆ•ฐ๏ผŒ่ฟ”ๅ›žไบŒ็ปดๆ•ฐ็ป„๏ผŒๆ•ฐ็ป„้‡Œๆ˜ฏ้”ฎๅ€ผๅฏน๏ผŒ่ฏฅ่ฟ”ๅ›žๅ€ผไธบๅŽๅฐๆทปๅŠ ็š„FAQ;ๅฆ‚ๆžœๅคฑ่ดฅๅˆ™่ฟ”ๅ›ž0. * pageShow()ใ€€|ใ€€View็ฑป๏ผŒๆ— ๅ‚ๆ•ฐ๏ผŒๆ— ่ฟ”ๅ›žๅ€ผใ€‚ๅฑ•็คบ้กต้ข๏ผšbarใ€FAQใ€่กจๅ•ใ€tableใ€footerใ€‚ * consultInsert($data)ใ€€|ใ€€Model็ฑป๏ผŒๅ‚ๆ•ฐไธบadd()ๆไพ›็š„้”ฎๅ€ผๅฏนๆ•ฐ็ป„๏ผŒๅฐ†ๅ„ไธช้”ฎๅ€ผๅฏน่งฃๆžๅนถๅญ˜ๅ…ฅๆ•ฐๆฎๅบ“ใ€‚ * consult()ใ€€|ใ€€Control็ฑป๏ผŒๅ‚ๆ•ฐๆš‚ๆ— ๏ผŒๆ— ่ฟ”ๅ›žๅ€ผใ€‚ๅฐ†ไปŽtipsSelect()ไธญ่ฟ”ๅ›žๆ•ฐ็ป„้‡Œ็š„ๆฏไธ€ไธช้”ฎๅ€ผๅฏน่งฃๆž๏ผŒๅนถ่ฐƒ็”จpageShow()ๆ˜พ็คบ้กต้ขใ€‚ * add()ใ€€|ใ€€Control็ฑป๏ผŒๅ‚ๆ•ฐๆš‚ๆ— ๏ผŒๆ— ่ฟ”ๅ›žๅ€ผใ€‚ๅœจๅ’จ่ฏข่กจๅ•ๆไบคๅŽ่ฟ่กŒ๏ผŒๅฐ†่กจๅ•็š„ๅ„้”ฎๅ€ผๅฏนๅญ˜ไธบๆ•ฐ็ป„ไฝœไธบๅ‚ๆ•ฐ่ฐƒ็”จconsultInsert()๏ผŒๅ†ไน‹ๅŽ่ทณ่ฝฌ้กต้ข่‡ณๅฐไผ™ๅญไปฌใ€‚ * ๅฐไผ™ * repairmenSelect()ใ€€|ใ€€Model็ฑป๏ผŒๆ— ๅ‚ๆ•ฐ๏ผŒ่ฟ”ๅ›žไบŒ็ปดๆ•ฐ็ป„๏ผŒๅญ˜ๅ‚จๅ„ไธชไน‰ไฟฎๅฐไผ™ๅญ็š„ไฟกๆฏใ€‚ * pageShow($repairmen)ใ€€|ใ€€View็ฑป๏ผŒๅ‚ๆ•ฐ็ฑปๅž‹ไบŒ็ปดๆ•ฐ็ป„๏ผŒๆ— ่ฟ”ๅ›žๅ€ผใ€‚ ๅฑ•็คบ้กต้ข๏ผšbarใ€ๅฐไผ™ๅญไปฌใ€footerใ€‚ * mailSelect($rid)ใ€€|ใ€€Model็ฑป๏ผŒๅ‚ๆ•ฐไธบ็ปดไฟฎไบบๅ‘˜id๏ผŒ่ฟ”ๅ›ž้”ฎๅ€ผๅฏนๆ•ฐ็ป„๏ผŒๅ†…ๅฎนไธบ็ปดไฟฎไบบๅ‘˜็š„้‚ฎไปถๅœฐๅ€ไปฅๅŠๆฑ‚ๅŠฉๅ†…ๅฎนใ€‚ * repairmen()ใ€€|ใ€€Control็ฑป๏ผŒๅ‚ๆ•ฐๆš‚ๆ— ๏ผŒๆ— ่ฟ”ๅ›žๅ€ผใ€‚่Žทๅ–repairmenSelect()่ฟ”ๅ›ž็š„ไบŒ็ปดๆ•ฐ็ป„๏ผŒไผ ็ป™pageShow()ๅฑ•็คบใ€‚ * mail($rid)ใ€€|ใ€€Control็ฑป๏ผŒๅ‚ๆ•ฐไธบ็ปดไฟฎไบบๅ‘˜id๏ผŒๆ— ่ฟ”ๅ›žๅ€ผ๏ผŒ็”จๆˆท้€‰ๆ‹ฉ็ปดไฟฎ่€…ๅŽ่ฟ่กŒใ€‚้ฆ–ๅ…ˆ่ฐƒ็”จmailSelect()๏ผŒ่งฃๆž่ฟ”ๅ›žๅ€ผ๏ผŒ็”จphpmailerๆ’ไปถๅ‘้€้‚ฎไปถ๏ผŒ่ทณ่ฝฌ่‡ณqqๅœจ็บฟๅฏน่ฏใ€‚ * ็ฎก็†ๅŽๅฐ * repairmenSelect()ใ€€|ใ€€Model็ฑป๏ผŒๆ— ๅ‚ๆ•ฐ๏ผŒ่ฟ”ๅ›ž็ปดไฟฎไบบๅ‘˜ไฟกๆฏใ€‚ * repairmanInsert($data)ใ€€|ใ€€Model็ฑป๏ผŒๅ‚ๆ•ฐไธบไธ€ไธชไบŒ็ปด้”ฎๅ€ผๅฏนๆ•ฐ็ป„๏ผŒๅฐ†็ปดไฟฎไบบๅ‘˜ไฟกๆฏๆ’ๅ…ฅๆ•ฐๆฎๅบ“ใ€‚ * repairmanDelete($rid)ใ€€|ใ€€Model็ฑป๏ผŒๅ‚ๆ•ฐไธบไธ€ไธชๆ•ดๆ•ฐ๏ผŒไปŽๆ•ฐๆฎๅบ“ๅˆ ้™คๅฏนๅบ”ไบบๅ‘˜็š„ๆก็›ฎใ€‚ * consultSelect()ใ€€|ใ€€Model็ฑป๏ผŒๆ— ๅ‚ๆ•ฐ๏ผŒ่ฟ”ๅ›ž็ปดไฟฎ่€…ไฟกๆฏใ€‚ * tipsInsert($data)ใ€€|ใ€€Model็ฑป๏ผŒๅ‚ๆ•ฐไธบไธ€ไธชไบŒ็ปด้”ฎๅ€ผๅฏนๆ•ฐ็ป„๏ผŒๅฐ†ไธ€ๆกFAQๆ’ๅ…ฅๆ•ฐๆฎๅบ“๏ผŒ่ฟ”ๅ›žไธ€ไธชPDOstatementๅฏน่ฑกใ€‚ * tipsDelete($rid)ใ€€|ใ€€Model็ฑป๏ผŒๅ‚ๆ•ฐไธบไธ€ไธชๆ•ดๆ•ฐ๏ผŒไปŽๆ•ฐๆฎๅบ“ๅˆ ้™คๅฏนๅบ”็š„FAQๆก็›ฎใ€‚ * tipsUpdate($faq,$qid)ใ€€|ใ€€Model็ฑป๏ผŒๅ‚ๆ•ฐไธบfaq้”ฎๅ€ผๅฏนๅ’Œ$qid๏ผŒไปŽๆ•ฐๆฎๅบ“ๅˆ ้™คๅฏนๅบ”็š„FAQๆก็›ฎใ€‚ * repairmenShow($repairman)ใ€€|ใ€€View็ฑป๏ผŒๅ‚ๆ•ฐไธบ๏ผŒ็ปดๆ•ฐ็ป„๏ผŒๅฑ•็คบ็ปดไฟฎไบบๅ‘˜ไฟฎๆ”น้กต้ข๏ผŒ่ฟ”ๅ›žไธ€ไธชPDOstatementๅฏน่ฑกใ€‚ * consultShow($consult)ใ€€|ใ€€View็ฑป๏ผŒๅ‚ๆ•ฐไธบไบŒ็ปดๆ•ฐ็ป„๏ผŒๅฑ•็คบ็ปดไฟฎ่ฎฐๅฝ•ใ€‚ * backstage($action)ใ€€|ใ€€Control็ฑป๏ผŒ$actionๆŽงๅˆถๅฑ•็คบrepairmen่ฟ˜ๆ˜ฏconsultใ€‚ * repairmanInsert()ใ€€|ใ€€Control็ฑป๏ผŒ่ฐƒ็”จModel็ฑป็š„repairmanInsert()๏ผŒๆ“ไฝœๆˆๅŠŸๅŽๅˆทๆ–ฐ้กต้ขใ€‚ * repairmanDelete()ใ€€|ใ€€Control็ฑป๏ผŒ่Žทๅพ—rid,ๅนถไผ ็ป™Model็ฑป็š„repairmanDelete()๏ผŒๆ“ไฝœๆˆๅŠŸๅŽๅˆทๆ–ฐ้กต้ขใ€‚ <file_sep>/application/views/GT_Index/Index.php <div class="list-group"> <?php $Data = $vars["data"]; foreach($Data as $arry ) { ?> <a href = "<?php echo $arry['href']?> " class =" list-group-item"> <?php echo $arry['name']?> </a> <?php } ?> </div><file_sep>/application/controllers/PfConsultController.class.php <?php class PfConsultController extends Controller { public function getConsult(){ session_start(); if($_SERVER["REQUEST_METHOD"] == "POST"){ $this->assign('consultant',$_POST['name']); $this->assign('consultantContact',$_POST['contact']); $this->assign('description',$_POST['problem']); $this->assign('submitTime',date("Y-m-d-h-i-s")); $data=array(); $data['consultant']=$this->_view->get('consultant'); $data['consultantContact']=$this->_view->get('consultantContact'); $data['description']=$this->_view->get('description'); $data['submitTime']=$this->_view->get('submitTime'); $thisConsult = new PfConsultModel; $thisConsult->consultInsert($data); $cid = $thisConsult->consultSelectMax(); $cid = $cid[0]['cid']; $_SESSION['cid'] = $cid; header("Location:".APP_URL."/PfRepairmen/index"); } } }<file_sep>/config/config.php <?php define ('DB_HOST', 'localhost'); define ('DB_USERNAME', 'msc'); define ('DB_PASSWORD', '<PASSWORD>'); define ('DB_NAME', 'MSC'); define ('ML_ADDRESS', '<EMAIL>'); define ('ML_HOST', 'smtp.126.com'); define ('ML_USERNAME', 'cproblemofficial'); define ('ML_PASSWORD', '<PASSWORD>'); <file_sep>/application/views/TU_Index/index.php <?php //ไธŠไผ ๆก†๏ผŒๆŸฅ็œ‹ใ€ๆœ็ดขๆŽฅๅฃ ?> <head> <meta charset="utf-8"> </head> <body> <form action="index.php" method="post" enctype="multipart/form-data" class="t_upform_static"> <p><label for="t_file" id="t_fileLabel"><span>็‚นๆˆ‘ไธŠไผ ๆ–‡ไปถ</span></label></p> <input type="file" name="file" hidden="hidden" id="t_file" /> <p><input type="text" name="fname" class="t_ipt" placeholder="ๆ–‡ไปถๅ" id="t_filename" maxlength="40" /></p> <span class="t_uploadtips">ๅชๆœ‰<a href="javascript:void(0);">็™ปๅฝ•</a>็”จๆˆทๅฏไปฅไธŠไผ ๅคงๆ–‡ไปถ(10M)ๅ“ฆ</span> <p><input type="submit" value="ๆไบค" class="t_btn" id="t_fsubmit" disabled="disabled"/></p> </form> </body> <file_sep>/application/controllers/GT_IndexController.class.php <?php class GT_IndexController extends Controller{ public function index() { $this->_view->render("index"); } public function book() { $keyword =array("type"=> __FUNCTION__); $data = (new GT_IndexModel)->select($keyword); //echo gettype($data); $this -> assign("data",$data); $this->_view->render("GTIndex"); } public function web() { $keyword =array("type"=> __FUNCTION__); $data = (new GT_IndexModel)->select($keyword); //echo gettype($data); $this -> assign("data",$data); $this->_view->render("GTIndex"); } public function software() { $keyword =array("type"=> __FUNCTION__); $data = (new GT_IndexModel)->select($keyword); //echo gettype($data); $this -> assign("data",$data); $this->_view->render("GTIndex"); } public function update() { $keyword =array("type"=> __FUNCTION__); $data = (new GT_IndexModel)->select($keyword); //echo gettype($data); $this -> assign("data",$data); $this->_view->render("GTIndex"); } } <file_sep>/application/views/GT_IndexView.class.php <?php class GT_IndexView extends View{ /* * ๅฆ‚ๆžœ่ฟ™ไธช้กต้ข็ป„ไปถๅขžๅŠ  * ้‡ๅ†™ render() ๆธฒๆŸ“่ฟ™ไธช้กต้ข * */ public function render($action="index"){ if($action == "index" || $action == "GTIndex"){ $this->showpage($action); return ; } else{ $this->error(); return ; } } public function showpage($action){ /* * ๅฆ‚ๆžœไฝ ๆœ‰ไธคไธชaction ้ƒฝ่ƒฝ่ฐƒ็”จ่ฟ™ไธชๅ‡ฝๆ•ฐ๏ผŒไฝ ๆ˜ฏๆƒณ่ฟ”ๅ›žๅŒไธ€ไธช้กต้ขๅ—๏ผŸ * ๅฆ‚ๆžœไฝ ไธๆ˜ฏ่ฟ”ๅ›žๅŒไธ€ไธช้กต้ข๏ผŒๅฐฑๅˆ†ไธคไธชๅ‡ฝๆ•ฐๅ†™๏ผŒไธ€ไธชๅ‡ฝๆ•ฐๅชๅšไธ€ไปถไบ‹ใ€‚ * ๅฆ‚ๆžœไฝ ่ฆ่ฟ”ๅ›žๅŒไธ€ไธช้กต้ข๏ผŒ$action ๅ€ผไธๅŒไฝ ๅœจไธ‹้ข็”จ$action ๅŽปๅŠ ่ฝฝ็ป„ไปถๆ˜ฏไธๆ˜ฏๆ„ๅ‘ณ็€ไฝ ่ฆๅ†™ไธคไธชไธ€ๆจกไธ€ๆ ท็š„ไธœ่ฅฟ๏ผŸ * ๆ‰€ไปฅ่ฟ™้‡Œไธ้œ€่ฆไผ ๅ‚ */ $pages[] = APP_PATH."application/views/Index/header.php"; $pages[] = APP_PATH."application/views/GT_Index/".$action.".php"; $pages[] = APP_PATH."application/views/Index/foot.php"; $pages[] = APP_PATH."application/views/Index/footer.php"; foreach($pages as $page){ $this->page($page); } } public function error(){ echo "NULL PAGE FOUND"; } } <file_sep>/application/views/PF_Index/faq.php <p>A:<?php echo $faq['ask']?></p> <p>Q:<?php echo $faq['question']?></p><file_sep>/DOCS/Growth.md mysql๏ผš softwareTable download course time bookTable download time webTable href time /Growth/... update userMessage๏ผˆ๏ผ‰//controller็ฑป ๅˆคๆ–ญๆ˜ฏๅฆ็™ปๅฝ• ๅˆคๆ–ญๆ˜ฏๅฆๆœ‰็ฎก็†ๅ‘˜ๆƒ้™ ่ฟ”ๅ›ž$TF showTip($TF)//View็ฑป ๆœ‰ๆƒ้™ๅˆ™ๅผนๅ‡บๆ›ดๆ–ฐไฟกๆฏ่กจๅ• ๆ— ๆƒ้™ๅˆ™ๆ็คบwarning updateSql๏ผˆ๏ผ‰// Model็ฑป ่กจๅ•ๆไบคๅŽadd่ฟ›ๆ•ฐๆฎๅบ“ function๏ผš getMessage()//Model็ฑป ่Žทๅ–ๆ•ฐๆฎๅบ“ๅฏนๅบ”ๅ†…ๅฎน ่ฟ”ๅ›žๅซๆœ‰ไธ‰ไธชไบŒ็ปดๆ•ฐ็ป„็š„ๆ•ฐ็ป„ $data pageHandle๏ผˆ๏ผ‰//controller็ฑป ๆŽฅๆ”ถ$data ่ฐƒ็”จshowPage๏ผˆ๏ผ‰ showPage๏ผˆ$data๏ผ‰//View็ฑป ไพๆฌกๅฑ•็คบsoftware books web ๅˆ—่กจ <file_sep>/application/views/PF_Index/form.php <script type="text/javascript"> function Trim(str,is_global) { var result; result = str.replace(/(^\s+)|(\s+$)/g,""); if(is_global.toLowerCase()=="g") { result = result.replace(/\s/g,""); } return result; } function x(form) { var name = Trim(document.getElementById("name").value,"g"); var contact = Trim(document.getElementById("contact").value,"g"); var problem = Trim(document.getElementById("problem").value,"g"); if(name == "") { alert("่ฟ™ไธ‰้กนๅ‡ไธ่ƒฝไธบ็ฉบๅ“ฆ๏ผ"); return false; } if(contact == "") { alert("่ฟ™ไธ‰้กนๅ‡ไธ่ƒฝไธบ็ฉบๅ“ฆ๏ผ"); return false; } if(problem == "") { alert("่ฟ™ไธ‰้กนๅ‡ไธ่ƒฝไธบ็ฉบๅ“ฆ๏ผ"); return false; } return true; } </script> <hr> <h2 align='center'>้—ฎ้ข˜้šพไปฅ็‹ฌ่‡ช่งฃๅ†ณ๏ผŸ</h2> <p>ๅกซๅ†™ไธ‹้ข็š„่กจๅ•๏ผŒๅนถๅœจ้šๅŽๅ’Œๆˆ‘ไปฌ็š„ๆˆๅ‘˜ๅ–ๅพ—่”็ณปใ€‚</p> <hr> <div class="row"> <form method="POST" onsubmit="return x();" action="<?php echo APP_URL."/PfConsult/getConsult"?>" enctype="multipart/form-data"> <div class="col-md-6"> <div class="form-group"> <input class="form-control" name="name" id="name" placeholder="็งฐๅ‘ผ" type="text"> </div> </div> <div class="col-md-6"> <div class="form-group"> <input class="form-control" name="contact" id="contact" placeholder="่”็ณปๆ–นๅผ" type="text"> </div> </div> <div class="col-md-12"> <div class="form-group"> <textarea id="problem" name="problem" class="form-control" id="" cols="30" rows="7" placeholder="้—ฎ้ข˜ๆ่ฟฐ"></textarea> </div> </div> <div align="center" class="col-md-12"> <div class="form-group"> <input type="submit" name="submit" value="ๆไบค"> </div> </div> </form> </div> <file_sep>/application/models/PfFaqModel.class.php <?php class PfFaqModel extends Model { public function faqSelect(){ $sql = sprintf("select * from `%s` ", $this->_table); $sth = $this->_dbHandle->prepare($sql); if ( $sth->execute() ) return $sth->fetchAll(); return 0; } public function faqInsert( $data ){ $sql = sprintf( "insert into `%s` %s", $this->_table, $this->formatInsert($data) ); $result = $this->querySQL($sql); return $result; } public function faqDelete( $data ){ $sql = sprintf( "delete from `%s` where %s", $this->_table, $this->formatWhere($data) ); $result = $this->querySQL($sql); return $result; } public function faqUpdate($set,$where){ $sql = sprintf( "update `%s`set %s where %s", $this->_table, $this->formatUpdate($set) ,$this->formatWhere($where) ); $result = $this->querySQL($sql); return $result; } }<file_sep>/js/TU_functions.js /* * * ้ข„่ฎกๅฎž็Žฐๆ–‡ไปถไธŠไผ ๅค„็†ๅ‡ฝๆ•ฐใ€่‡ชๅฎšๆ็คบๆก†ๅ‡ฝๆ•ฐใ€็”จไบŽ่งฃ่ฏปๆ ‡็ญพๅ‡ฝๆ•ฐ * */ var id = function(el){ return document.getElementById(el); } var t_exist = 0; var TU_alert = function(text,type,next){ if(!t_exist){ document.body.innerHTML += '<div class="t_shadow">' + ' <div id="t_alert">' + ' </div>' + '</div>'; t_exist = 1; } $(".t_shadow").show(); $("#t_alert").fadeIn(50); text = text || "ๆˆๅŠŸ"; type = type || "success"; next = next || "close"; id("t_alert").innerHTML='<img class="t_alert_img" src="images/'+type+'.png" width="32px" height="32px"><span class="t_alert_text">'+text+'</span>' +'<p><input type="button" class="t_btn t_alert_btn" value="็กฎๅฎš" onload="this.focus();" autofocus="autofocus"></p>'; $(".t_alert_btn").click(function(){ if(next=="reload"){ location.href=window.location.href; //้‡ๆ–ฐๅŠ ่ฝฝๆญค้กต }else if(next == "home"){ location.href='index'; //home่ทฏๅพ„ }else if(next == "close"){ $(".t_shadow").hide(); $("#t_alert").hide(50); id("t_alert").innerHTML=""; //ๅชๆ˜ฏๆธ…็ฉบๆ็คบๆก†ๅนถ้š่— }; }); }; <file_sep>/README.md # ๅˆๆฌกไฝฟ็”จ 1. git clone https://github.com/SUMSC/Web-2.0.git ๅˆฐๆœฌๅœฐไธ€ๆ–‡ไปถๅคน๏ผ› 2. cd Web-2.0/ ๅœจๆญคๆ–‡ไปถๅคนไธ‹็ผ–ๅ†™ไปฃ็ ๏ผŒๅพ…็ผ–ๅ†™ไปฃ็ ๅฎŒๆฏ•้œ€่ฆๅšไธŠไผ ๆ—ถ๏ผŒๅ‚็…ง`ๆฏๆฌกไธŠไผ ๆญฅ้ชค`๏ผš # ๆฏๆฌกไธŠไผ ๆญฅ้ชค 1. git pull -- ๅŒๆญฅ่ฟœ็ซฏไป“ๅบ“ๅˆฐๆœฌๅœฐ 2. git add XXX/ -- ๆทปๅŠ ไฝ ็ผ–ๅ†™็š„ไปฃ็  3. git commit -m 'XXX็š„ๆ›ดๆ–ฐ' -- ๆไบคไฝ ็š„ๆทปๅŠ ๅˆฐๆœฌๅœฐไป“ๅบ“ 4. git push -u origin master -- ไธŠไผ ๅˆฐ่ฟœ็ซฏ # ๆณจๆ„ ๆฏๆฌก็ผ–ๅ†™่‡ชๅทฑไปฃ็ ็š„ๆ—ถๅ€™ไธ่ฆ่ฝปๆ˜“ไฟฎๆ”น้ž่‡ชๅทฑไปฃ็ ๆฎต็š„ไปฃ็ ใ€‚ๅฆ‚ๆžœ่ฏฅไปฃ็ ๆ˜ฏๅ…ถไป–ๆˆๅ‘˜็ผ–ๅ†™๏ผŒ้œ€่ฆๅšๅ‡บไฟฎๆ”น็š„ๆ—ถๅ€™่”็ณปๅฏนๅบ”ไฝœ่€…๏ผŒๅ•†่ฎจๆ˜ฏๅฆ้œ€่ฆไฟฎๆ”น๏ผŒๅนถ็”ฑๅŽŸไฝœ่€…่ฟ›่กŒไฟฎๆ”นๅนถๆไบคๅˆฐ่ฟœ็ซฏใ€‚ ๅฆ‚ๆžœไฟฎๆ”น้ƒจๅˆ†ไผšๅฝฑๅ“ๅ…ถไป–ไฝœ่€…ไปฃ็ ๆฎต็š„็ผ–ๅ†™๏ผŒๅบ”่ฐจๆ…Žไฟฎๆ”น๏ผŒๅฎžๅœจๅฟ…่ฆไฟฎๆ”น้œ€่ฆ็ซ‹ๅณ้€š็Ÿฅๅ…ถไป–ไฝœ่€…๏ผŒไปฅ้˜ฒไธๅฟ…่ฆ็š„ไปฃ็ ๅ†ฒ็ชใ€‚ ๆฏไฝๆˆๅ‘˜ๅœจๆไบค่‡ชๅทฑ็š„ไปฃ็ ไน‹ๅ‰่ฆๅ…ˆ่กŒๅŒๆญฅ๏ผŒๅนถๅฎŒๆˆ่‡ชๅทฑๅŠŸ่ƒฝๅ—็š„ๆต‹่ฏ•๏ผŒๅนถไธŠไผ ๏ผŒๆญค่ฟ‡็จ‹ๅฐฝ้‡ๅฟซใ€‚ไปฅ้ฟๅ…Adminๅš่ฟ‡ๅคš็š„mergeๆ“ไฝœใ€‚ # pull ๅŽŸ็† ๆ‰ง่กŒpull็š„่ฟ‡็จ‹ไผšๅšgitๆ™บ่ƒฝๅˆๅนถใ€‚ ไพ‹ๅฆ‚๏ผŒAไฝœ่€…ไฟฎๆ”นไบ†Tempๆ–‡ไปถ็š„็ฌฌไบŒ่กŒ๏ผŒ็„ถๅŽpushไธŠๅŽป๏ผŒ็„ถๅŽBๅœจ่‡ชๅทฑๆœฌๅœฐๅœจๆ–‡ไปถ็ป“ๅฐพๆทปๅŠ ไบ†ไธ€่กŒ๏ผŒๆญคๆ—ถB็›ดๆŽฅpushไผšๅ†ฒ็ช๏ผŒๅช่ฆๅ…ˆๆ‰ง่กŒไธ€ๆญฅpullๆ“ไฝœ๏ผŒgitไผš่‡ชๅŠจๅˆๅนถไน‹ๅ‰Aๅš็š„ไฟฎๆ”นๅˆฐๅฝ“ๅ‰ๆœฌๅœฐๅบ“๏ผŒ็„ถๅŽBๅ†pushๅฐฑๆฒกๆœ‰ๅ†ฒ็ชไบ†ใ€‚ ไฝ†ๆ˜ฏๅฆ‚ๆžœAใ€B้ƒฝไฟฎๆ”นไบ†่ฟ™ไธ€่กŒ๏ผŒๅฐฑๆ— ๆณ•ๆ™บ่ƒฝๅˆๅนถ๏ผŒ้œ€่ฆadminๆ‰‹ๅŠจๅˆๅนถ๏ผŒๅ› ๆญคไธบ้ฟๅ…adminๅทฅไฝœ้‡๏ผŒ่ฏทๅ‹ฟไฟฎๆ”นๅ…ถไป–ไฝœ่€…็š„ไปฃ็ ใ€‚ <file_sep>/application/controllers/PfBackendController.php <?php class PfBackendController extends Controller { public function faqUpdate() { } public function repairmenUpdate() { } }<file_sep>/application/views/PF_Repairmen/repairmen.php <div class="container-fluid"> <div class="row"> <?php $cnt = 0; $judge = 0; $repairmen = (new PfRepairmenModel)->PfRepairmenSelect(); foreach($repairmen as $repairman){ if($repairman['free']!=0){ $head = $repairman['headlink']; ?> <div class='col-md-4 column'> <div class='row'> <div class='thumbnail'> <div class="col-md-12"><img class='img-responsive center-block' height=150px width=150px src=<?php echo APP_URL.$head;?> /></div> <div class="caption"> <?php echo "<h3 class='text-center'><strong>".$repairman['name']."</strong></h3>"; echo "<p class='text-muted'>".$repairman['gender']."</p>"; echo "<p class='text-muted'>".$repairman['introduction']."</p>"; $rid = $repairman["rid"]; ?> <a align='right' class='btn btn-primary' href='<?php echo APP_URL."/PfRepairmen/mail/id=$rid";?>'>Click Here Contact</a> </div> </div> </div> </div> <?php } } ?> </div> </div><file_sep>/application/views/Index/index.php <h2>ๅผ€ๅ‘ไธญ</h2> <pre>ๆœ‰ๆฒกๆœ‰่„‘ๅญๅคง็š„ไบบๆฅๅธฎๅฟ™ๆƒณๆƒณ่ฟ™ไธช้ฆ–้กต่ฏฅๅšๆˆไป€ไนˆๆ ทๅญ๏ผŸ</pre> <pre>ๅผ€ๅ‘่ฏดๆ˜Žๅ…ˆๆ‹ฟๆމไบ†๏ผŒๅคช้šพ็œ‹ใ€‚</pre> <!-- <h2>ๅผ€ๅ‘่ฏดๆ˜Ž</h2> <pre> 1. header.php ๅ’Œ footer.php ไปŽIndexๆ–‡ไปถๅคนไธญๅŠ ่ฝฝ(ๅ‚่€ƒIndexView.class.php ็š„ไปฃ็ )ใ€‚ 2. ๆฏไธชไบบ่‡ชๅทฑ้กต้ข็š„ๅ…ƒ็ด ๏ผŒ่ฏทๅœจmsc.css ๆ–‡ไปถไธญๆทปๅŠ ๆ ทๅผ๏ผŒๅนถไธ”ไธ€ไธชไบบ็š„ไปฃ็ ๅ†™ๅœจไธ€ๅ—ๅ†… ไปฃ็ ๆฎตๅ‰ๅ‚็…งๅทฒๆœ‰ๆณจ้‡Šๆ ผๅผ็ผ–ๅ†™ๆณจ้‡Šใ€‚ 3. ไธ่ฆไฟฎๆ”น้กน็›ฎไธญ้™คapplication, css, js, images, fonts, sql ๆ–‡ไปถๅคนไปฅๅค–็š„็จ‹ๅบใ€‚ 4. ๆ•ฐๆฎๅบ“็ปŸไธ€ไฝฟ็”จmscไฝœไธบ็”จๆˆท๏ผŒMSCไฝœไธบๆ•ฐๆฎๅบ“ๅใ€‚ๅช้œ€ๅฐ†msc.sqlๆ–‡ไปถๅฏผๅ…ฅๆ•ฐๆฎๅบ“ๅณๅฏใ€‚ ๅ…ณไบŽๆ•ฐๆฎๅบ“็”จๆˆท็š„้—ฎ้ข˜๏ผŒ็ฟป็œ‹SDOJ็พค็š„่Šๅคฉ่ฎฐๅฝ•ใ€‚ 5. ๅ‰็ซฏไปฃ็ ่ฏทๅ‚็…งIndex/ๆ–‡ไปถๅคนๅ†…็š„ไปฃ็ ๏ผŒไธ่ฆๅœจheaderๅ’Œfooterๆ–‡ไปถไธญๆทปๅŠ ๅ—ๅ…ƒ็ด ใ€‚ ๆ›ดๅคšๅ…ถไป–้—ฎ้ข˜๏ผŒ่ฏท่ฐจๆ…Žๆ“ไฝœใ€‚ </pre> <h2>ๆณจๆ„๏ผ</h2> <pre> 1. ๅ†้‡็”ณไธ€้๏ผŒไธ่ฆๆ›ดๆ”นๅŠจ้ž่‡ชๅทฑไปฃ็ ๆฎต็š„ไปฃ็ ใ€‚ 2. Github็š„ไฝฟ็”จ่ฟ˜ไธไผšไธŠไผ ็š„๏ผŒๆƒณๅŠžๆณ•ๅŽปๅญฆไผšใ€‚ 3. ๆฏๅคฉๅผ€ๅง‹ๅ†™ไน‹ๅ‰ๅ…ˆๆ‰ง่กŒgit pull๏ผŒๆฏๆฌกไธŠไผ ไน‹ๅ‰ไนŸ่ฆๆ‰ง่กŒgit pull </pre> <h2>ไธ€ไบ›ๆŠ€ๅทง</h2> <pre> 1. <F12>ๅผ€ๅฏ่ฐƒ่ฏ•็•Œ้ขใ€‚ๆœ€ๅฅฝๅฐ†่ฐƒ่ฏ•้กตๆ‹‰ๅ‡บๆฅๅ•็‹ฌๅšไธ€ไธช็ช—ๅฃใ€‚ 2. ๆœ‰ไปปไฝ•้—ฎ้ข˜ๅœจ็พค้‡Œๆๅ‡บๆฅๅนถๅœจGithubไธŠๆ›ดๆ–ฐ่‡ชๅทฑ็š„ไปฃ็ ๏ผŒไปฅๆ–นไพฟ่งฃๅ†ณ้—ฎ้ข˜็š„ไบบๅฏไปฅๅœจ่‡ชๅทฑๆœฌๅœฐ่ฐƒ่ฏ•ไฝ ็š„ไปฃ็ ใ€‚ 3. ๆœ‰ไปปไฝ•้—ฎ้ข˜่ฏทๅ…ˆๅŽป็œ‹Husky็š„ๅฎ˜ๆ–น่ฏดๆ˜Ž้กต๏ผŒๅ…ถๆฌกๅŽป็œ‹ๅ…ถไป–ไบบๅœจๅฎž็Žฐ่ฟ™ไธ€ๅ—็š„ๅ†™ๆณ•๏ผŒๆœ€ๅŽๅ†ๆ้—ฎใ€‚ </pre> <a href="http://www.baidu.com"><h2>็ป™ๅดๅˆš็š„ๅค–้ƒจ้“พๆŽฅ้—ฎ้ข˜็š„่งฃ็ญ”</h2></a> <pre> ๆ ‡้ข˜ๆ˜ฏๆŒ‡ๅ‘็™พๅบฆ้ฆ–้กต็š„้“พๆŽฅใ€‚ๅค–้ƒจ้“พๆŽฅ้œ€่ฆๅ†™http://www.baidu.com ่ฟ™ไธ€ๅฎŒๆ•ดๅฝขๅผ๏ผŒๅฆๅˆ™้ป˜่ฎคๆ˜ฏๆœฌ็ซ™ๅ†…้“พๆŽฅ๏ผŒ็›ดๆŽฅๆไบค็ป™localhostๅค„็†ไบ†ใ€‚ </pre>--> <file_sep>/DOCS/files.md * ไธŠไผ  * uploadPage(\$uid) | View็ฑป๏ผŒๅ‚ๆ•ฐไธบ็”จๆˆทid๏ผŒ็”จไบŽๅˆคๆ–ญ็”จๆˆทไธŠไผ ๆ–‡ไปถๆƒ้™๏ผŒ่ฟ”ๅ›žๅ€ผไธบ\$formData็”จไบŽๅฐ†ๆ–‡ไปถไฟกๆฏไผ ็ป™ๅค„็†phpใ€‚ๅฑ•็คบ headerใ€่กจๅ•ใ€่กจๅ•ๆŽงไปถใ€footerใ€‚ * saveFiles(\$formData) | Control็ฑป๏ผŒๅฏนๆ–‡ไปถๆฃ€ๆŸฅใ€้‡ๅ‘ฝๅใ€ไฟๅญ˜ใ€่ฟ”ๅ›žๅ€ผๅฏไธบ่กจ็คบๆ–‡ไปถไธŠไผ ็Šถๆ€็š„ๅญ—็ฌฆไธฒๆˆ–ๆ•ฐ็ป„ใ€‚ * infoSave() | Model็ฑป๏ผŒๅฐ†ไธŠไผ ๅฎŒๆˆ็š„ๆ–‡ไปถไฟกๆฏๅ†™ๅ…ฅๆ•ฐๆฎๅบ“ใ€‚่ฟ”ๅ›žๅ€ผๅฏไธบ่กจ็คบๆ“ไฝœๆ˜ฏๅฆๆˆๅŠŸ็š„ๅญ—็ฌฆไธฒๆˆ–ๆ•ฐ็ป„ใ€‚ * ๆต่งˆใ€ไธ‹่ฝฝ * filesList(\$fList) | View็ฑป๏ผŒๅ‚ๆ•ฐไธบไบŒ็ปดๆ•ฐ็ป„๏ผŒ็”จไบŽ้กต้ขไธบไน‹ๆ˜พ็คบ็›ธๅบ”ๆ–‡ไปถๅ›พๆ ‡ๅ’Œ้ข„่งˆๆ–นๅผ๏ผŒใ€‚ * queryFiles() | Model็ฑป๏ผŒ่ฟ”ๅ›žไบŒ็ปดๆ•ฐๅ€ผ๏ผŒ็”จไบŽๆŸฅ่ฏขๆ•ฐๆฎๅบ“ๅŽๅฐ†ๆ–‡ไปถ ๅใ€ๅคงๅฐใ€็ฑปๅž‹ใ€่ทฏๅพ„ ็ญ‰่ฟ”ๅ›žใ€‚ * fileList() | Control็ฑป๏ผŒๆŽฅๅ—queryFiles()็š„่ฟ”ๅ›žๆ•ฐ็ป„๏ผŒ็”Ÿๆˆๆ•ฐ็ป„ไผ ้€’็ป™filesList()ๅ‡ฝๆ•ฐ็”จไบŽๅฑ•็คบใ€‚<file_sep>/application/controllers/PfRepairmenController.class.php <?php class PfRepairmenController extends Controller{ function index(){ session_start(); $this->render("index"); } function splitParam($param){ return explode('=', $param); } function mail($params){ session_start(); $idArray = $this->splitParam($params[0]); $rid = $idArray[1]; $qid = (new PfRepairmenModel)->qIDSelect($rid); $mailRecipient = (new PfRepairmenModel)->nameSelect($rid); $qid = $qid[0]['qq']; $mailRecipient = $mailrecipient[0]['name']; $mailAddress=$qid."@qq.com"; $cid = $_SESSION['cid']; $content = (new PfConsultModel)->descriptionSelect($cid); $content=$content[0]['description']; $set = array(); $where = array(); $where["cid"] = $cid; $set['rid'] = $rid; (new PfConsultModel) ->consultUpdate($set,$where); require './PHPMailer/PHPMailerAutoload.php'; $mail = new PHPMailer; $mail->isSMTP(); $mail->Host = ML_HOST; $mail->SMTPAuth = true; $mail->Username = ML_USERNAME; $mail->Password = <PASSWORD>; $mail->SMTPSecure = 'tls'; $mail->Port = 25; $mail->setFrom(ML_ADDRESS, 'Cproblem'); $mail->addAddress($mailAddress, $mailRecipient); $mail->isHTML(true); $mail->Subject = "็”ต่„‘้—ฎ้ข˜ๅ’จ่ฏข้‚ฎไปถ"; $mail->Body = "$content"; $mail->AltBody = "$content"; if(!$mail->send()) { echo 'Message could not be sent.'; echo 'Mailer Error: ' . $mail->ErrorInfo; } else { echo 'Message has been sent'; ?> <?php header("Location:http://wpa.qq.com/msgrd?v=3&uin=".$qid."&site=qq&menu=yes"); } } function backend(){ $this->render("backend"); } function addNew(){ $data = array('qq' => $_POST['qq'], 'name' => $_POST['name'], 'introduction' =>$_POST['introduction'],'free' => 1 , 'gender' =>$_POST['gender'] ); (new PfRepairmenModel) -> PfRepairmenInsert($data); header("Location:".APP_URL."/PfRepairmen/backend"); } function change(){ var_dump($_POST); echo "<hr>"; $rid = explode('/', $_GET["url"]); $rid = $rid[2]; $params = array(); $where = array(); $where["rid"] = $rid; foreach ($_POST as $key => $value) { $params[$key] = $value; } array_pop($params); (new PfRepairmenModel) ->PfRepairmenUpdate($params,$where); $this->jumping(); } function head(){ if($_SERVER["REQUEST_METHOD"] == "POST") { $rid = explode('/', $_GET["url"]); $rid = $rid[2]; $file = $_POST['file']; // ๅ…่ฎธไธŠไผ ็š„ๅ›พ็‰‡ๅŽ็ผ€ $allowedExts = array("gif", "jpeg", "jpg", "png"); $temp = explode(".", $_FILES["file"]["name"]); echo $_FILES["file"]["size"]; $extension = end($temp); // ่Žทๅ–ๆ–‡ไปถๅŽ็ผ€ๅ echo "<hr>"; echo $extension; echo "<hr>"; if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/pjpeg") || ($_FILES["file"]["type"] == "image/x-png") || ($_FILES["file"]["type"] == "image/png")) && in_array($extension, $allowedExts)) { if ($_FILES["file"]["error"] > 0) { echo "้”™่ฏฏ๏ผš: " . $_FILES["file"]["error"] . "<br>"; } else { echo "ไธŠไผ ๆ–‡ไปถๅ: " . $_FILES["file"]["name"] . "<br>"; echo "ๆ–‡ไปถ็ฑปๅž‹: " . $_FILES["file"]["type"] . "<br>"; echo "ๆ–‡ไปถๅคงๅฐ: " . ($_FILES["file"]["size"] / 1024) . " kB<br>"; echo "ๆ–‡ไปถไธดๆ—ถๅญ˜ๅ‚จ็š„ไฝ็ฝฎ: " . $_FILES["file"]["tmp_name"] . "<br>"; // ๅˆคๆ–ญๅฝ“ๆœŸ็›ฎๅฝ•ไธ‹็š„ upload ็›ฎๅฝ•ๆ˜ฏๅฆๅญ˜ๅœจ่ฏฅๆ–‡ไปถ // ๅฆ‚ๆžœๆฒกๆœ‰ upload ็›ฎๅฝ•๏ผŒไฝ ้œ€่ฆๅˆ›ๅปบๅฎƒ๏ผŒupload ็›ฎๅฝ•ๆƒ้™ไธบ 777 if (file_exists("images/upload/".$rid."/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " ๆ–‡ไปถๅทฒ็ปๅญ˜ๅœจใ€‚ "; } else { mkdir('images/upload/'.$rid); // ๅฆ‚ๆžœ upload ็›ฎๅฝ•ไธๅญ˜ๅœจ่ฏฅๆ–‡ไปถๅˆ™ๅฐ†ๆ–‡ไปถไธŠไผ ๅˆฐ upload ็›ฎๅฝ•ไธ‹ move_uploaded_file($_FILES["file"]["tmp_name"], "images/upload/" .$rid."/". iconv("UTF-8","GBK","head.".$extension)); echo "ๆ–‡ไปถๅญ˜ๅ‚จๅœจ: " . "images/upload/" .$rid."/".$_FILES["file"]["name"]; $headlink = "/images/upload/" .$rid."/"."head.".$extension; $params = array(); $where = array(); $where["rid"] = $rid; $params['headlink'] = $headlink; (new PfRepairmenModel) ->PfRepairmenUpdate($params,$where); $this->jumping(); } } } } } function jumping(){ echo "Something changing...Please wait."; header("Location:".APP_URL."/PfRepairmen/backend"); } } <file_sep>/application/controllers/UserController.class.php <?php class UserController extends Controller{ public function login() { ?> <form method="post"> <input name="login" value="1" type="hidden" /> <label>username:<input type="text" name="username"></label> <br/><br/> <label>password:<input type="<PASSWORD>" name="password"></label> <br/><br/> <button type="submit" name="submit">login</button> </form> <?php $data = array(); if(isset($_POST['login'])) { $data['username'] = $_POST['username']; $data['password'] = $_POST['password']; } $tmp_data = array(); $tmp_data['username'] = $data['username']; $result = (new UserModel)->select($tmp_data); if( $result == array() ){ $this->error("็”จๆˆทไธๅญ˜ๅœจ"); }else { foreach($result as $row) if( $row['password'] == $data['password'] ) { $_SESSION['username'] = $data['username']; header("Location:".APP_URL); } else $this->error("ๅฏ†็ ้”™่ฏฏ"); } } } <file_sep>/application/controllers/PfFaqController.class.php <?php class PfFaqController extends Controller{ function index(){ $this->assign('title', '้ฆ–้กต'); $this->assign('content', 'php MVC'); $this->render("index"); } function addFaq(){ $this->render("addFaq"); } function newFaq(){ $data = array('question' => $_POST['question'], 'answer' => $_POST['answer']); (new PfFaqModel) -> faqInsert($data); header("Location:".APP_URL."/PfFaq/addFaq"); } } <file_sep>/application/views/TU_IndexView.class.php <?php class TU_IndexView extends View{ public function render($action="index"){ if($action == "index") { $this->index(); return ; } else if($action == "test") { $this->test(); return ; } else { $this->index(); return ; } } public function index(){ require(APP_PATH."application/views/TU_Index/index.php"); } public function test(){ $pages[] = APP_PATH."application/views/TU_Index/test.php"; $pages[] = APP_PATH."application/views/TU_Index/link.php"; foreach($pages as $page){ require($page); } } } <file_sep>/application/views/ACTView.class.php <?php class ACTView extends View{ public function render( $action="index"){ if($action == "index"){ $this->index(); return ; } else if($action == "add"){ $this->add(); return ; } } public function index( ){ $pages[] = APP_PATH."application/views/Index/header.php"; $pages[] = APP_PATH."application/views/Index/index.php"; $pages[] = APP_PATH."application/views/Index/foot.php"; $pages[] = APP_PATH."application/views/Index/footer.php"; foreach( $pages as $page) $this->page($page); } public function add( ){ $pages[] = APP_PATH."/application/views/Index/header.php"; $pages[] = APP_PATH."/application/views/Index/add.php"; $pages[] = APP_PATH."/application/views/Index/footer.php"; foreach( $pages as $page) $this->page($page); } } ?>
6ca58d8c3607f7f5c146b44f53e4ee355b173fb8
[ "Markdown", "SQL", "JavaScript", "PHP" ]
36
PHP
SUMSC/Web-2.0
0205d32f7325784f1f00916d615b7f19db50c51c
7ab3fb66d377384001452d64f8fd143a742c973e
refs/heads/master
<repo_name>adamosoftware/SourceFolderCleanup<file_sep>/SourceFolderCleanup/Services/FileSystemUtil.cs ๏ปฟusing SourceFolderCleanup.Static; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using WinForms.Library; namespace SourceFolderCleanup.Services { public class FileSystemUtil { /// <summary> /// Finds the maximum date modified of files in a path /// </summary> public DateTime GetFolderMaxDate(string path) { DateTime result = DateTime.MinValue; FileSystem.EnumFiles(path, "*", fileFound: (fi) => { if (fi.LastWriteTimeUtc > result) { result = fi.LastWriteTimeUtc; } return EnumFileResult.Continue; }); return result; } public async Task<long> GetFolderTotalSizeAsync(IEnumerable<FolderInfo> folders) { long result = 0; await Task.Run(() => { foreach (var folder in folders) { result += GetFolderSize(folder.Path); } }); return result; } public long GetFolderSize(string path) { long result = 0; FileSystem.EnumFiles(path, "*", fileFound: (fi) => { result += fi.Length; return EnumFileResult.Continue; }); return result; } public async Task<IEnumerable<FolderInfo>> GetBinObjFoldersAsync(string parentPath) { IEnumerable<FolderInfo> results = null; await Task.Run(() => { results = GetBinObjFolders(parentPath); }); return results; } public IEnumerable<FolderInfo> GetBinObjFolders(string parentPath) { return GetSubfoldersNamed(parentPath, new string[] { "bin", "obj" }, new string[] { "node_modules" }).Where(fi => fi.TotalSize > 0); } public async Task<IEnumerable<FolderInfo>> GetPackagesFoldersAsync(string parentPath) { IEnumerable<FolderInfo> results = null; await Task.Run(() => { results = GetPackagesFolders(parentPath); }); return results; } public IEnumerable<FolderInfo> GetPackagesFolders(string parentPath) { return GetSubfoldersNamed(parentPath, new string[] { "packages" }); } private IEnumerable<FolderInfo> GetSubfoldersNamed(string parentPath, string[] includeNames, string[] excludeNames = null) { List<FolderInfo> results = new List<FolderInfo>(); FileSystem.EnumFiles(parentPath, "*", directoryFound: (di) => { if (includeNames.Contains(di.Name) && (excludeNames?.All(name => !di.FullName.Contains(name)) ?? true)) { results.Add(new FolderInfo() { Path = di.FullName, TotalSize = GetFolderSize(di.FullName), MaxDate = GetFolderMaxDate(di.FullName) }); return EnumFileResult.NextFolder; } return EnumFileResult.Continue; }); return results; } } public class FolderInfo { public string Path { get; set; } public long TotalSize { get; set; } public DateTime MaxDate { get; set; } public string SizeText { get { return Readable.FileSize(TotalSize); } } public bool IsSelected { get; set; } public bool IsMonthsOld(int months) { return MaxDate < DateTime.Today.AddDays(months * -30); } } } <file_sep>/SourceFolderCleanup/Models/Settings.cs ๏ปฟusing JsonSettings.Library; using SourceFolderCleanup.Services; using System.Collections.Generic; using WinForms.Library.Models; using static System.Environment; namespace SourceFolderCleanup.Models { public class Settings : SettingsBase { public string SourcePath { get; set; } public bool Delete { get; set; } public int DeleteMonthsOld { get; set; } public bool DeleteBinAndObj { get; set; } public bool DeletePackages { get; set; } public bool Archive { get; set; } public int ArchiveMonthsOld { get; set; } public string ArchivePath { get; set; } public FormPosition FolderListPosition { get; set; } public List<FolderInfo> BinObjFolders { get; set; } public List<FolderInfo> PackagesFolders { get; set; } public override string Filename => BuildPath(SpecialFolder.LocalApplicationData, "SourceFolderCleanup", "settings.json"); } } <file_sep>/SourceFolderCleanup/Controls/ProgressLinkLabel.cs ๏ปฟusing System.ComponentModel; using System.Windows.Forms; namespace SourceFolderCleanup.Controls { public enum ProgressLinkLabelMode { Text, Progress } public partial class ProgressLinkLabel : UserControl { public ProgressLinkLabel() { InitializeComponent(); } public event LinkLabelLinkClickedEventHandler LinkClicked; public new string Text { get { return linkLabel1.Text; } set { linkLabel1.Text = value; } } private ProgressLinkLabelMode _mode; [Browsable(false)] public ProgressLinkLabelMode Mode { get { return _mode; } set { _mode = value; progressBar1.Visible = _mode == ProgressLinkLabelMode.Progress; linkLabel1.Visible = _mode == ProgressLinkLabelMode.Text; } } private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { LinkClicked?.Invoke(sender, e); } } } <file_sep>/README.md This is a small utility I'm working on to free up disk space on my Surface machine which has a relatively small 256GB drive. My main repo folder has large `package/`, `bin/` and `obj/` folders that accumulate a lot of stuff that doesn't need to be there all the time. There might something out there that already does this nicely, but as usual, this is just something I like working on. ![img](https://adamosoftware.blob.core.windows.net:443/images/source-folder-cleanup2.png) This makes use of my [WinForms.Library](https://github.com/adamosoftware/WinForms.Library) project to handle the form data binding with a `ControlBinder<T>` object, incidentally. I'm also using my [JsonSettings.Library](https://github.com/adamosoftware/JsonSettings) project to handle settings persistence in json. My `Settings` model is [here](https://github.com/adamosoftware/SourceFolderCleanup/blob/master/SourceFolderCleanup/Models/Settings.cs). ```csharp private void frmMain_Load(object sender, System.EventArgs e) { var monthValues = new int[] { 3, 6, 9, 12 }.Select(i => new ListItem<int>(i, i.ToString())); _settings = SettingsBase.Load<Settings>(); _binder = new ControlBinder<Settings>(); _binder.Add(tbSourcePath, model => model.SourcePath); _binder.Add(chkDelete, model => model.Delete); _binder.Add(chkDeleteBinObj, model => model.DeleteBinAndObj); _binder.Add(chkDeletePackages, model => model.DeletePackages); _binder.AddItems(cbDeleteMonths, (model) => model.DeleteMonthsOld = cbDeleteMonths.GetValue<int>(), (model) => cbDeleteMonths.SetValue(model.DeleteMonthsOld), monthValues); _binder.Add(chkArchive, model => model.Archive); _binder.Add(tbArchivePath, model => model.ArchivePath); _binder.AddItems(cbArchiveMonths, (model) => model.ArchiveMonthsOld = cbArchiveMonths.GetValue<int>(), (model) => cbArchiveMonths.SetValue(model.ArchiveMonthsOld), monthValues); _binder.Document = _settings; chkArchive_CheckedChanged(null, new EventArgs()); chkDelete_CheckedChanged(null, new EventArgs()); } ``` I'm also using WinForm.Library's [EnumFiles](https://github.com/adamosoftware/WinForms.Library/blob/master/WinForms.Library/FileSystem_DotNetSearch.cs#L27) method to [find](https://github.com/adamosoftware/SourceFolderCleanup/blob/master/SourceFolderCleanup/Services/FileSystemUtil.cs#L32) `bin` and `obj` directories. The base implementation looks like this: ```csharp public IEnumerable<string> GetSubfoldersNamed(string parentPath, string[] includeNames, string[] excludeNames = null) { List<string> results = new List<string>(); FileSystem.EnumFiles(parentPath, "*", directoryFound: (di) => { if (includeNames.Any(name => di.Name.Equals(name)) && (excludeNames?.All(name => !di.FullName.Contains(name)) ?? true)) { results.Add(di.FullName); return EnumFileResult.NextFolder; } return EnumFileResult.Continue; }); return results; } ``` <file_sep>/SourceFolderCleanup/Forms/FolderInfoSorter.cs ๏ปฟusing SourceFolderCleanup.Abstract; using SourceFolderCleanup.Services; using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace SourceFolderCleanup.Forms { internal class FolderInfoSorter : DataGridViewSorter<FolderInfo> { public FolderInfoSorter(DataGridView dataGridView, params ColumnInfo[] defaultSort) : base(dataGridView, defaultSort) { } protected override IEnumerable<FolderInfo> GetSortedData(DataGridViewColumn column, bool ascending, IEnumerable<FolderInfo> data) { if (column.Name.Equals("colMaxDate")) { return (ascending) ? data.OrderBy(item => item.MaxDate) : data.OrderByDescending(item => item.MaxDate); } if (column.Name.Equals("colSize")) { return (ascending) ? data.OrderBy(item => item.TotalSize) : data.OrderByDescending(item => item.TotalSize); } throw new NotImplementedException($"Column {column.Name} has no sort instructions"); } } } <file_sep>/SourceFolderCleanup/Models/ActivityLog.cs ๏ปฟusing System; using System.Collections.Generic; namespace SourceFolderCleanup.Models { public class ActivityLog { public DateTime Timestamp { get; set; } = DateTime.Now; public Settings Settings { get; set; } public List<Folder> Deleted { get; set; } public List<Archive> Archived { get; set; } public class Folder { public string Path { get; set; } public long TotalSize { get; set; } } public class Archive { public string SourcePath { get; set; } public string OutputZipFile { get; set; } } } } <file_sep>/SourceFolderCleanup/frmMain.cs ๏ปฟusing JsonSettings.Library; using SourceFolderCleanup.Controls; using SourceFolderCleanup.Forms; using SourceFolderCleanup.Models; using SourceFolderCleanup.Services; using SourceFolderCleanup.Static; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; using WinForms.Library; using WinForms.Library.Extensions.ComboBoxes; using WinForms.Library.Models; namespace SourceFolderCleanup { public partial class frmMain : Form { private Settings _settings; private ControlBinder<Settings> _binder; public frmMain() { InitializeComponent(); pllBinObjSize.LinkClicked += delegate(object sender, LinkLabelLinkClickedEventArgs e) { ShowFolderList(sender as LinkLabel, _settings.BinObjFolders); }; pllPackagesSize.LinkClicked += delegate (object sender, LinkLabelLinkClickedEventArgs e) { ShowFolderList(sender as LinkLabel, _settings.PackagesFolders); }; } private void ShowFolderList(LinkLabel control, IEnumerable<FolderInfo> folders) { var dlg = new frmFolderList() { Position = _settings.FolderListPosition }; dlg.Folders = folders; dlg.ShowDialog(); _settings.FolderListPosition = dlg.Position; control.Text = (dlg.SelectedSize != 0) ? $"{Readable.FileSize(folders.Sum(item => item.TotalSize))}, {Readable.FileSize(dlg.SelectedSize)} selected" : Readable.FileSize(folders.Sum(item => item.TotalSize)); UpdateDeleteButtonText(); } private async void frmMain_Load(object sender, System.EventArgs e) { var monthValues = new int[] { 3, 6, 9, 12 }.Select(i => new ListItem<int>(i, i.ToString())); _settings = SettingsBase.Load<Settings>(); _binder = new ControlBinder<Settings>(); _binder.Add(tbSourcePath, model => model.SourcePath); _binder.Add(chkDelete, model => model.Delete); _binder.Add(chkDeleteBinObj, model => model.DeleteBinAndObj); _binder.Add(chkDeletePackages, model => model.DeletePackages); _binder.AddItems(cbDeleteMonths, (model) => model.DeleteMonthsOld = cbDeleteMonths.GetValue<int>(), (model) => cbDeleteMonths.SetValue(model.DeleteMonthsOld), monthValues); _binder.Add(chkArchive, model => model.Archive); _binder.Add(tbArchivePath, model => model.ArchivePath); _binder.AddItems(cbArchiveMonths, (model) => model.ArchiveMonthsOld = cbArchiveMonths.GetValue<int>(), (model) => cbArchiveMonths.SetValue(model.ArchiveMonthsOld), monthValues); _binder.Document = _settings; UpdateArchiveInfo(); UpdateDeleteInfo(); } private void btnExit_Click(object sender, EventArgs e) { Close(); } private void frmMain_FormClosing(object sender, FormClosingEventArgs e) { _settings.Save(); } private void tbArchivePath_BuilderClicked(object sender, WinForms.Library.Controls.BuilderEventArgs e) { tbArchivePath.SelectFolder(e); } private void tbSourcePath_BuilderClicked(object sender, WinForms.Library.Controls.BuilderEventArgs e) { tbSourcePath.SelectFolder(e); } private void chkArchive_CheckedChanged(object sender, EventArgs e) { UpdateArchiveInfo(); } private void chkDelete_CheckedChanged(object sender, EventArgs e) { UpdateDeleteInfo(); } private void UpdateArchiveInfo() { cbArchiveMonths.Enabled = chkArchive.Checked; tbArchivePath.Enabled = chkArchive.Checked; linkLabel4.Enabled = chkArchive.Checked; } private void UpdateDeleteInfo() { chkDeleteBinObj.Enabled = chkDelete.Checked; chkDeletePackages.Enabled = chkDelete.Checked; cbDeleteMonths.Enabled = chkDelete.Checked; pllBinObjSize.Enabled = chkDelete.Checked; pllPackagesSize.Enabled = chkDelete.Checked; } private async void cbDeleteMonths_SelectedIndexChanged(object sender, EventArgs e) { btnDelete.Enabled = false; pllBinObjSize.Visible = false; pllPackagesSize.Visible = false; pllBinObjSize.Mode = ProgressLinkLabelMode.Progress; pllPackagesSize.Mode = ProgressLinkLabelMode.Progress; // data binding hasn't happened yet, so we need to read the combo box directly int monthsOld = cbDeleteMonths.GetValue<int>(); await AnalyzeFolders(monthsOld); } private async Task AnalyzeFolders(int monthsOld) { List<Task> tasks = new List<Task>(); if (_settings.DeleteBinAndObj) { pllBinObjSize.Visible = true; tasks.Add(AnalyzeBinObj(monthsOld)); } if (_settings.DeletePackages) { pllPackagesSize.Visible = true; tasks.Add(AnalyzePackages(monthsOld)); } await Task.WhenAll(tasks); pllBinObjSize.Enabled = chkDelete.Checked; pllPackagesSize.Enabled = chkDelete.Checked; btnDelete.Enabled = true; UpdateDeleteButtonText(); } private Task AnalyzePackages(int monthsOld) { return AnalyzeFolderAsync( pllPackagesSize, monthsOld, async (fsu) => await fsu.GetPackagesFoldersAsync(_settings.SourcePath), (results) => _settings.PackagesFolders = results.ToList()); } private Task AnalyzeBinObj(int monthsOld) { return AnalyzeFolderAsync( pllBinObjSize, monthsOld, async (fsu) => await fsu.GetBinObjFoldersAsync(_settings.SourcePath), (results) => _settings.BinObjFolders = results.ToList()); } private void UpdateDeleteButtonText() { long deleteSize = GetDeletableFolders().Sum(item => item.TotalSize); btnDelete.Text = $"Delete {Readable.FileSize(deleteSize)}"; btnDelete.Enabled = (deleteSize > 0); } private IEnumerable<FolderInfo> GetDeletableFolders() { List<FolderInfo> results = new List<FolderInfo>(); if (chkDeleteBinObj.Checked && _settings.BinObjFolders != null) { results.AddRange((_settings.BinObjFolders.Any(item => item.IsSelected)) ? _settings.BinObjFolders.Where(item => item.IsSelected) : _settings.BinObjFolders); } if (chkDeletePackages.Checked && _settings.PackagesFolders != null) { results.AddRange((_settings.PackagesFolders.Any(item => item.IsSelected)) ? _settings.PackagesFolders.Where(item => item.IsSelected) : _settings.PackagesFolders); } return results; } private async Task AnalyzeFolderAsync( ProgressLinkLabel linkLabel, int monthsOld, Func<FileSystemUtil, Task<IEnumerable<FolderInfo>>> getFolders, Action<IEnumerable<FolderInfo>> captureResults) { var fsu = new FileSystemUtil(); var folders = await getFolders.Invoke(fsu); var deletable = folders.Where(folder => folder.IsMonthsOld(monthsOld)); captureResults.Invoke(deletable); long deleteableBytes = deletable.Sum(item => item.TotalSize); linkLabel.Mode = ProgressLinkLabelMode.Text; linkLabel.Text = Readable.FileSize(deleteableBytes); } private async void btnDelete_Click(object sender, EventArgs e) { try { var folders = GetDeletableFolders().Select(fi => fi.Path); IProgress<string> progress = new Progress<string>(ShowCurrentDeletingFolder); await Task.Run(() => { foreach (var folder in folders) { // thanks to https://stackoverflow.com/a/27522561/2023653 although still a little confusing progress.Report(folder); Microsoft.VisualBasic.FileIO.FileSystem.DeleteDirectory(folder, Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.RecycleOption.DeletePermanently, Microsoft.VisualBasic.FileIO.UICancelOption.ThrowException); } }); int monthsOld = cbDeleteMonths.GetValue<int>(); await AnalyzeFolders(monthsOld); } catch (Exception exc) { MessageBox.Show(exc.Message); } finally { lblDeleting.Visible = false; llCancelDelete.Visible = false; } } private void ShowCurrentDeletingFolder(string path) { lblDeleting.Visible = true; llCancelDelete.Visible = true; lblDeleting.Text = path; } private async void chkDeleteBinObj_CheckedChanged(object sender, EventArgs e) { if (chkDeleteBinObj.Checked) { pllBinObjSize.Visible = true; int monthsOld = cbDeleteMonths.GetValue<int>(); await AnalyzeBinObj(monthsOld); } else { pllBinObjSize.Visible = false; } UpdateDeleteButtonText(); } private async void chkDeletePackages_CheckedChanged(object sender, EventArgs e) { if (chkDeletePackages.Checked) { pllPackagesSize.Visible = true; int monthsOld = cbDeleteMonths.GetValue<int>(); await AnalyzePackages(monthsOld); } else { pllPackagesSize.Visible = false; } UpdateDeleteButtonText(); } } } <file_sep>/SourceFolderCleanup/Abstract/DataGridViewSorter.cs ๏ปฟusing System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Windows.Forms; namespace SourceFolderCleanup.Abstract { public abstract class DataGridViewSorter<T> { private readonly Dictionary<int, ColumnInfo> _sortDirections; private IEnumerable<T> _data; public DataGridViewSorter(DataGridView dataGridView, params ColumnInfo[] defaultSorts) { var defaultSortDictionary = (defaultSorts ?? Enumerable.Empty<ColumnInfo>()).ToDictionary(item => item.Column.Index); DataGridView = dataGridView; DataGridView.ColumnHeaderMouseClick += DataGridView_ColumnHeaderMouseClick; _data = (dataGridView.DataSource as BindingSource).DataSource as IEnumerable<T>; _sortDirections = new Dictionary<int, ColumnInfo>(); foreach (var col in dataGridView.Columns.OfType<DataGridViewColumn>().Where(col => col.SortMode == DataGridViewColumnSortMode.Programmatic)) { bool ascending = (defaultSortDictionary.ContainsKey(col.Index)) ? defaultSortDictionary[col.Index].IsAscending : true; _sortDirections.Add(col.Index, new ColumnInfo() { Column = col, IsAscending = ascending }); } } private void DataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) { if (_sortDirections.ContainsKey(e.ColumnIndex)) { _sortDirections[e.ColumnIndex].IsAscending = !_sortDirections[e.ColumnIndex].IsAscending; _data = GetSortedData(_sortDirections[e.ColumnIndex].Column, _sortDirections[e.ColumnIndex].IsAscending, _data); BindingList<T> boundList = new BindingList<T>(); foreach (var item in _data) boundList.Add(item); BindingSource bs = new BindingSource(); bs.DataSource = boundList; DataGridView.DataSource = bs; } } public DataGridView DataGridView { get; } protected abstract IEnumerable<T> GetSortedData(DataGridViewColumn column, bool ascending, IEnumerable<T> data); public class ColumnInfo { public DataGridViewColumn Column { get; set; } public bool IsAscending { get; set; } } } } <file_sep>/SourceFolderCleanup/Forms/frmFolderList.cs ๏ปฟusing SourceFolderCleanup.Abstract; using SourceFolderCleanup.Services; using SourceFolderCleanup.Static; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Windows.Forms; using WinForms.Library; using WinForms.Library.Models; namespace SourceFolderCleanup.Forms { public partial class frmFolderList : Form { public frmFolderList() { InitializeComponent(); dgvFolders.AutoGenerateColumns = false; } public IEnumerable<FolderInfo> Folders { get; set; } public FormPosition Position { get; set; } public long SelectedSize { get; private set; } private FolderInfoSorter _sorter; private void frmFolderList_Load(object sender, System.EventArgs e) { if (Position != null) Position.Apply(this); try { SuspendLayout(); var list = new BindingList<FolderInfo>(); foreach (var folder in Folders.OrderByDescending(item => item.TotalSize)) list.Add(folder); BindingSource bs = new BindingSource(); bs.DataSource = list; dgvFolders.DataSource = bs; lblTotalSize.Text = Readable.FileSize(Folders.Sum(item => item.TotalSize)); _sorter = new FolderInfoSorter(dgvFolders, new DataGridViewSorter<FolderInfo>.ColumnInfo() { Column = colSize, IsAscending = false }); } finally { ResumeLayout(); } } private void dgvFolders_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (e.ColumnIndex == colPath.Index && e.RowIndex > -1) { var item = dgvFolders.Rows[e.RowIndex].DataBoundItem as FolderInfo; FileSystem.RevealInExplorer(item.Path); } } private void dgvFolders_CellEndEdit(object sender, DataGridViewCellEventArgs e) { UpdateSelectedSize(); } private void UpdateSelectedSize() { var dataSource = dgvFolders.DataSource as BindingSource; var list = dataSource.DataSource as BindingList<FolderInfo>; SelectedSize = list.Where(item => item.IsSelected).Sum(item => item.TotalSize); lblSelectedSize.Text = Readable.FileSize(SelectedSize); } private void frmFolderList_FormClosing(object sender, FormClosingEventArgs e) { Position = FormPosition.FromForm(this); } private void llSelectAll_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { foreach (DataGridViewRow row in dgvFolders.Rows) { row.Cells["colSelected"].Value = true; } UpdateSelectedSize(); } private void llInvertSelection_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { foreach (DataGridViewRow row in dgvFolders.Rows) { bool value = (bool)row.Cells["colSelected"].Value; row.Cells["colSelected"].Value = !value; } UpdateSelectedSize(); } } } <file_sep>/SourceFolderCleanup.Tests/FileSystemUtilTests.cs ๏ปฟusing System; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using SourceFolderCleanup.Services; namespace SourceFolderCleanup.Tests { [TestClass] public class FileSystemUtilTests { [TestMethod] public void GetBinFolders() { var fsu = new FileSystemUtil(); var results = fsu.GetBinObjFoldersAsync(@"C:\Users\Adam\Source\Repos").Result; Assert.IsTrue(results.All(folder => folder.Path.EndsWith("bin") || folder.Path.EndsWith("obj"))); Assert.IsTrue(results.Any(folder => folder.Path.EndsWith("obj"))); } [TestMethod] public void GetPackagesFolders() { var fsu = new FileSystemUtil(); var results = fsu.GetPackagesFoldersAsync(@"C:\Users\Adam\Source\Repos").Result; Assert.IsTrue(results.All(folder => folder.Path.EndsWith("packages"))); } [TestMethod] public void GetBinFoldersOlderThan() { var fsu = new FileSystemUtil(); var results = fsu.GetBinObjFoldersAsync(@"C:\Users\Adam\Source\Repos").Result; var cutoffDate = DateTime.Today.AddDays(-90); var deleteable = results.Where(folder => fsu.GetFolderMaxDate(folder.Path) < cutoffDate).ToArray(); } } }
2b23dff6ff85e5a400b18eeda96a1ffbab64ba26
[ "Markdown", "C#" ]
10
C#
adamosoftware/SourceFolderCleanup
91691b3ca9b383ae3da6d7674c74207f78df31fb
720c5150afa4d8a55d798a5fb62d20ced3f67ffe
refs/heads/master
<file_sep>#include <iostream> using namespace std; class phanso{ private: int tuso; int mauso; public: phanso(int t, int m){ tuso = t; mauso = m; } int getTuSo(){ return tuso; } void setTuSo(int t){ tuso = t; } int getMauSo(){ return mauso; } void getMauSo(int m){ mauso = m; } void output(); phanso cong(phanso); }; void phanso::output(){ cout<<tuso<<"/"<<mauso<<endl; } phanso phanso::cong(phanso ps){ phanso xkq; kq.tu = tu * ps.mau + mau * ps.tu; kq.mau = mau * ps.mau; return kq; } int main(){ phanso ps1; ps1.tu = 5; ps1.mau =7; ps1.output(); phanso ps2; ps2.tu = 4; ps2.mau = 3; ps2.output() ; phanso tong = ps1.cong(ps2); tong.output(); } <file_sep>#include<iostream> using namespace std; class Phanso{ private: int tuso; int mauso; public: Phanso(void);//ham dung mac dinh ~Phanso(void); //ham huy Phanso(int, int); // ham dung tham so Phanso(const Phanso &); //ham dung sao chep //phanso +-*/ Phanso Phanso operator +(Phanso); Phanso operator -(Phanso); Phanso operator *(Phanso); Phanso operator /(Phanso); //so sanh phan so >, <, >=, == voi phan so bool operator >(Phanso); bool operator <(Phanso); bool operator >=(Phanso); bool operator ==(Phanso); friend istream& operator >> (istream &, Phanso &); friend ostream& operator << (ostream &, Phanso); }; Phanso::Phanso(void){ tuso = 0; mauso = 1; } Phanso::~Phanso(){ } Phanso::Phanso(int ts, int ms) { tuso = ts; mauso = ms; } Phanso::Phanso(const Phanso &ps) { tuso = ps.tuso; mauso = ps.mauso; } istream& operator >>(istream &is, Phanso &ps) { cout << "Nhap vao tu so: "; is >> ps.tuso; do { cout << "Nhap vao mau so: "; is >> ps.mauso; if (ps.mauso == 0) cout << "\nMau so khong hop le, xin nhap lai."; } while (ps.mauso == 0); return is; } ostream& operator <<(ostream &os, Phanso ps) { os << ps.tuso << "/" << ps.mauso << endl;; return os; } Phanso Phanso::operator+(Phanso ps) { Phanso Tong; Tong.tuso = tuso * ps.mauso + mauso * ps.tuso; Tong.mauso = mauso * ps.mauso; return Tong; } Phanso Phanso::operator-(Phanso ps) { Phanso Hieu; Hieu.tuso = tuso * ps.mauso - mauso * ps.tuso; Hieu.mauso = mauso * ps.mauso; return Hieu; } Phanso Phanso::operator*(Phanso ps) { Phanso Tich; Tich.tuso = tuso * ps.tuso; Tich.mauso = mauso * ps.mauso; return Tich; } Phanso Phanso::operator/(Phanso ps) { /*Phanso Thuong; Thuong.tuso = tuso * ps.mauso; Thuong.mauso = mauso * ps.tuso; return Thuong; */ Phanso NghichDao(ps.mauso, ps.tuso); return *this*NghichDao; } bool Phanso::operator>(Phanso ps) { /*cach 1: /*if ((float)tuso / mauso > (float)ps.tuso / ps.mauso) return true; return false; cach 2: return (float)tuso / mauso > (float)ps.tuso / ps.mauso ? true : false;*/ return (float)tuso / mauso > (float)ps.tuso / ps.mauso; } bool Phanso::operator<(Phanso ps) { return (float)tuso / mauso < (float)ps.tuso / ps.mauso; } bool Phanso::operator>=(Phanso ps) { return (float)tuso / mauso >= (float)ps.tuso / ps.mauso; } bool Phanso::operator==(Phanso ps) { return (float)tuso / mauso == (float)ps.tuso / ps.mauso; } int main(){ Phanso ps1, ps2; cout << "---Nhap ps1--- "<<endl; cin >> ps1; cout << ps1; cout << "---Nhap ps2--- "<<endl; cin >> ps2; cout << ps2; cout << "\nps1 + ps2 = " << ps1 + ps2; cout << "\nps1 - ps2 = " << ps1 - ps2; cout << "\nps1 * ps2 = " << ps1 * ps2; cout << "\nps1 / ps2 = " << ps1 / ps2; if (ps1 > ps2) cout << "\nps1 > ps2 "<<endl; else if (ps1 < ps2) cout << "\nps1 < ps2"<<endl; else cout << "\nps1 = ps2"<<endl; } <file_sep>#include<iostream> using namespace std; class Sophuc{ private: float phanThuc; float phanAo; public: Sophuc(); ~Sophuc(); Sophuc(float,float); Sophuc(const Sophuc &); Sophuc operator +(Sophuc); Sophuc operator -(Sophuc); Sophuc operator *(Sophuc); Sophuc operator /(Sophuc); friend istream& operator>>(istream &, Sophuc &); friend ostream& operator<<(ostream &, Sophuc ); }; Sophuc::Sophuc(){ phanThuc = 0; phanAo = 0; } Sophuc::~Sophuc(){ } Sophuc::Sophuc(float t, float a){ phanThuc = t; phanAo = a; } Sophuc::Sophuc(const Sophuc &sp){ phanThuc = sp.phanThuc; phanAo = sp.phanAo; } istream& operator>>(istream &is, Sophuc &sp){ cout<<"Nhap phan thuc: "; is>>sp.phanThuc; cout<<"Nhap phan ao: "; is>>sp.phanAo; return is; } ostream& operator<<(ostream &os, Sophuc sp){ cout<<sp.phanThuc<<" + "<<"("<<sp.phanAo<<")i "<<endl; } Sophuc Sophuc::operator +(Sophuc sp){ Sophuc Tong; Tong.phanThuc = phanThuc + sp.phanThuc; Tong.phanAo = phanAo + sp.phanAo; return Tong; } Sophuc Sophuc::operator -(Sophuc sp){ Sophuc Hieu; Hieu.phanThuc = phanThuc - sp.phanThuc; Hieu.phanAo = phanAo - sp.phanAo; return Hieu; } Sophuc Sophuc::operator*(Sophuc sp){ Sophuc Tich; Tich.phanThuc = phanThuc*sp.phanThuc - phanAo*sp.phanAo; Tich.phanAo = phanThuc*sp.phanAo + phanAo*sp.phanThuc; return Tich; } Sophuc Sophuc::operator/(Sophuc sp){ Sophuc Thuong; Thuong.phanThuc = ( phanThuc*sp.phanThuc + phanAo*sp.phanAo) / (sp.phanThuc * sp.phanThuc + sp.phanAo*sp.phanAo); Thuong.phanAo = (sp.phanThuc*phanAo - sp.phanAo*phanThuc) / (sp.phanThuc*sp.phanThuc + sp.phanAo*sp.phanAo); return Thuong; } int main(){ Sophuc sp1, sp2; cout<<"-----Nhap sp1-----"<<endl; cin>>sp1; cout<<sp1; cout<<"-----Nhap sp2-----"<<endl; cin>>sp2; cout<<sp2; cout<<"\nsp1 + sp2 = "<<sp1 + sp2<<endl; cout<<"\nsp1 - sp2 = "<<sp1 - sp2<<endl; cout<<"\nsp1 * sp2 = "<<sp1 * sp2<<endl; cout<<"\nsp1 / sp2 = "<<sp1 / sp2<<endl; return 0; } <file_sep>#include<iostream> #include<string> #include<vector> using namespace std; class Person{ private: string name; int age; public: Person(){ } Person(string name, int age){ this->name = name; this->age = age; } string getName(){ return name; } int getAge(){ return age; } void setName(string n){ name = n; } void setAge(int a){ age = a; } }; class Employee : public Person{ private: float luongCB; float luongTT; float phuCap; public: Employee() : Person(){ } Employee(string name, int age, float lcb, float ltt, float pc) : Person(name, age){ luongCB = lcb; luongTT = ltt; phuCap = pc; } float getLuongCB(){ return luongCB; } float getLuongTT(){ return luongTT; } float getPhuCap(){ return phuCap; } void setLuongCB(float lcb){ luongCB = lcb; } void setLuongTT(float ltt){ luongTT = ltt; } void setPhuCap(float pc){ phuCap = pc; } float thuNhap(){ return luongCB + luongTT + phuCap; } }; class Manager : public Person{ private: vector<Employee> danhSach; public: Manager(){ } Manager(string name,int age, vector<Employee> s):Person(name,age){ danhSach = s; } vector<Employee> getDanhSach(){ return danhSach; } void setDanhSach(vector<Employee> ds){ danhSach = ds; } Employee thuNhapCaoNhat(){ Employee e; float Max = 0; for(int i = 0; i < danhSach.size(); i++){ if(Max < danhSach[i].thuNhap()){ e = danhSach[i]; Max = e.thuNhap(); } } return e; } }; int main(){ int n; cout<<"\nNhap so nhan vien: "; cin>>n; vector<Employee> danhSach; for(int i = 0; i < n; i++){ string name; int age; float luongCB, luongTT,phuCap; cout<<"\nNhan vien thu "<<i+1<<endl; cin.ignore(); cout<<"\nNhap ten: "; getline(cin,name); cout<<"\nNhap tuoi: "; cin>>age; cout<<"\nNhap luong CB: "; cin>>luongCB; cout<<"\nNhap luong TT: "; cin>>luongTT; cout<<"\nPhu cap: "; cin>>phuCap; danhSach.push_back(Employee(name,age,luongCB,luongTT,phuCap)); cout<<"\nThu nhap: "<<danhSach[i].thuNhap(); } string name; int age; cin.ignore(); cout<<"\nNhap ten quan li: "; getline(cin,name); cout<<"\nNhap tuoi: "; cin>>age; Manager ql = Manager(name,age,danhSach); cout<<"Nhan vien co luong cao nhat:\n"; cout<<"Ten: "<<ql.thuNhapCaoNhat().getName()<<endl<<"Tuoi: "<<ql.thuNhapCaoNhat().getAge()<<endl<<"Muc luong la: "<<ql.thuNhapCaoNhat().thuNhap(); return 0; } <file_sep>#include<iostream> using namespace std; class Time{ private: int hh; int mm; int ss; public: Time(void); ~Time(void); Time(int,int,int); Time(const Time&); friend istream& operator >>(istream &, Time &); friend ostream& operator <<(ostream &, Time ); Time operator +(Time); Time operator -(Time); bool operator >(Time); bool operator <(Time); bool operator ==(Time); }; Time::Time(void){ hh = 0; mm = 0; ss = 0; } Time::~Time(void){ } Time::Time(int h, int m, int s){ hh = (h>=0 && h<24) ? h : 0; mm = (m>=0 && m<60) ? m : 0; ss = (s>=0 && s<60) ? s : 0; } Time::Time(const Time &t){ hh = t.hh; mm = t.mm; ss = t.ss; } istream& operator >>(istream &is, Time &t){ cout<<"Enter hour: : "; is>>t.hh; cout<<"Enter minute: "; is>>t.mm; cout<<"Enter second: "; is>>t.ss; return is; } ostream& operator <<(ostream &os, Time t){ os<<t.hh<<" : "<<t.mm<<" : "<<t.mm<<endl; return os; } Time Time::operator +(Time t1){ Time t; int a,b; a = ss + t1.ss; t.ss = a%60; b = (a/60) + mm + t1.mm; t.mm = b % 60; t.hh = (b/60) + hh + t1.hh; t.hh = t.hh % 12; return t; } Time Time::operator -(Time t1){ Time t; int a, b, s; a = t.hh * 3600 + t.mm * 60 + t.ss; b = t1.hh * 3600 + t1.mm * 60 + t1.ss; s = b - a; t.ss = s % 3600 % 60; t.mm = s % 3600 / 60; t.hh = s / 3600; return t; } bool Time::operator ==(Time t){ return (hh == t.hh && mm == t.mm && ss == t.mm); } bool Time::operator <(Time t){ return (hh < t.hh && mm < t.mm && ss < t.mm); } bool Time::operator >(Time t){ return (hh > t.hh && mm > t.mm && ss > t.mm); } int main(){ Time t1, t2; cout<<"-----Time t1-----"<<endl; cin>>t1; cout<<t1<<endl; cout<<"-----Time t2-----"<<endl; cin>>t2; cout<<t2<<endl; cout<<"\nt1 + t2 = "<<t1 + t2<<endl; cout<<"\nt1 - t2 = "<<t1 - t2<<endl; if(t1 > t2) cout<<"\nt1 > t2"<<endl; else if(t1 < t2) cout<<"\nt1 < t2"<<endl; else cout<<"\nt1 = t2"<<endl; return 0; } <file_sep>#include<iostream> #include<string> #include<vector> using namespace std; class Person { private: string hoTen; int tuoi; public: string getHoTen() { return hoTen; } int getTuoi() { return tuoi; } void setHoTen(string ht) { hoTen = ht; } void setTuoi(int t) { tuoi = t; } void nhapThongTin() { fflush(stdin); cout << "Nhap ten: "; getline(cin, hoTen); cout << "Nhap tuoi: "; cin >> tuoi; } void inThongTin() { cout << hoTen << " " << tuoi; } }; class Student : public Person { private: float toan, ly, hoa; public: float getToan() { return toan; } float getLy() { return ly; } float getHoa() { return hoa; } void setToan(float t) { toan = t; } void setLy(float l) { ly = l; } void setHoa(float h) { hoa = h; } void nhapThongTin() { Person::nhapThongTin(); cout << "Nhap diem toan: "; cin >> toan; cout << "Nhap diem ly: "; cin >> ly; cout << "Nhap diem hoa: "; cin >> hoa; } void inThongTin() { Person::inThongTin(); cout << " " << toan << " " << ly << " " << hoa; } }; class Teacher : public Person { private: vector<Student> S; public: vector<Student> getS() { return S; } void setS(vector<Student> s) { S = s; } }; int main(){ //fflush(stdin); Student st1; st1.nhapThongTin(); st1.inThongTin(); cout << endl; Student st2; st2.nhapThongTin(); st2.inThongTin(); return 0; } <file_sep>#include<iostream> using namespace std; template <class T> class Phanso{ private: T tu; T mau; public: Phanso(){ } Phanso(const Phanso &ps){ tu = ps.tu; mau = ps.mau; } T getTu(){ return tu; } T getMau(){ return mau; } void setTu(T tuso){ tu = tuso; } void setMau(T mauso){ mau = mauso; } friend istream& operator >>(istream &is, Phanso &ps) { cout << "Nhap vao tu so: "; is >> ps.tu; do { cout << "Nhap vao mau so: "; is >> ps.mau; if (ps.mau == 0) cout << "\nMau so khong hop le, xin nhap lai."; } while (ps.mau == 0); return is; } friend ostream& operator <<(ostream &os, Phanso ps) { os << ps.tu << "/" << ps.mau << endl;; return os; } }; template <class T> class PhansoKT : public Phanso<T>{ public: void setMau(T mauso){ if(mauso == 0){ cout<<"Mau so phai khac 0 "; exit(1); }else{ Phanso<T>::setMau(mauso); } } friend PhansoKT operator +(PhansoKT P1, PhansoKT P2){ PhansoKT Tong; Tong.setTu(P1.getTu() * P2.getMau() + P1.getMau() * P2.getTu()); Tong.setMau(P1.getMau() * P2.getMau()); return Tong; } friend PhansoKT operator -(PhansoKT P1, PhansoKT P2){ PhansoKT Hieu; Hieu.setTu(P1.getTu() * P2.getMau() - P1.getMau() * P2.getTu()); Hieu.setMau(P1.getMau() * P2.getMau()); return Hieu; } friend PhansoKT operator *(PhansoKT P1, PhansoKT P2){ PhansoKT Tich; Tich.setTu(P1.getTu() * P2.getTu()); Tich.setMau(P1.getMau() * P2.getMau()); return Tich; } friend PhansoKT operator /(PhansoKT P1, PhansoKT P2){ PhansoKT Thuong; Thuong.setTu(P1.getTu() * P2.getMau()); Thuong.setMau(P1.getMau() * P2.getTu()); return Thuong; } }; int main(){ PhansoKT<int> p1; cout<<"Nhap p1: "; cin>>p1; cout<<p1; PhansoKT<int> p2; cout<<"Nhap p2: "; cin>>p2; cout<<p2; cout<<"Tong: "<<p1+p2<<endl; cout<<"Hieu: "<<p1-p2<<endl; } <file_sep>#include<iostream> using namespace std; long long Fact(long long n){ if(n == 0) return 1; else return n * Fact(n-1); } int main(){ long long n, k, CHKL, TH; cout<<"Nhap k = "; cin>>k; cout<<"Nhap n = "; cin>>n; CHKL = Fact(n) / Fact(n-k); cout<<CHKL<<endl; TH = Fact(n)/(Fact(k) * Fact(n-k)); cout<<TH<<endl; return 0; } <file_sep>#include<iostream> #define MAX 30 using namespace std; class Matrix{ private: int n; int A[MAX][MAX]; public: Matrix(); void Nhap(); int getN(); void setN(int); int getA(int,int); void setA(int,int,int); int Cong(Matrix); void Tru(Matrix); void Nhan(Matrix); void Xuat(); }; Matrix::Matrix(){ n = 2; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ A[i][j] = 0; } } } int Matrix::getA(int i, int j){ return A[i][j]; } void Matrix::setA(int i, int j, int value){ } void Matrix::Nhap(){ for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ cout<<"a["<<i<<"]["<<j<<"] = "; cin>>A[i][j]; } } } void Matrix::Xuat(){ for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ cout<<A[i][j]<<" "; } cout<<"\n"; } } int Matrix::getN(){ return n; } void Matrix::setN(int N){ n = N; } int Matrix::Cong(Matrix M){ Matrix result; if(M.getN() != n){ cout<<"\nKhong the cong hai ma tran cho nhau."; } else{ result.setN(n); for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ int value = A[i][j] + M.getA(i,j); result.setA(i,j,value); } } } return result; } int main(){ Matrix m1, m2, m3; m1.setN(2); m1.Nhap(); m1.Xuat(); m2.setN(2); m2.Nhap(); m2.Xuat(); m3 = m1.Cong(m2); m3.Xuat(); return 0; } <file_sep>#include<iostream> #include<string> #include<vector> using namespace std; class Nguoi{ private: string ten; int namSinh; public: Nguoi(){ } Nguoi(string t, int ns){ ten = t; namSinh = ns; } string getTen(){ return ten; } int getNamSinh(){ return namSinh; } void setTen(string t){ ten = t; } void setNamSinh(int ns){ namSinh = ns; } }; class Sinhvien : public Nguoi{ private: float diemToan; float diemLy; float diemHoa; public: Sinhvien(){ } Sinhvien(string t, int ns,float dt,float dl,float dh) : Nguoi(string t, int ns){ diemToan = dt; diemLy = dl; diemHoa = dh; } float getDiemToan(){ return diemToan; } float getDiemLy(){ return diemLy; } float getDiemHoa(){ return diemHoa; } void setDiemToan(float dt){ diemToan = dt; } void setDiemLy(float dl){ diemLy = dl; } coid setDiemHoa(float dh){ diemHoa = dh; } float tinhDiemTB(){ return (diemToan + diemLy + diemHoa) / 3.0; } }; class LopSinhHoat{ private: string tenLop; vector<Sinhvien> danhSach; public: LopSinhHoat(){ } LopSinhHoat(string tl, vector<Sinhvien> ds){ tenLop = tl; danhSach = ds; } string getTenLop(){ return tenLop; } vector<Sinhvien> getDanhSach(){ return danhSach; } void setTenLop(string tl){ tenLop = tl; } void setDanhSach(vector<Sinhvien> ds){ danhSach = ds; } }; <file_sep>#include<iostream> #include<vector> using namespace std; class Person{ private: string ten; int tuoi; public: Person(string _ten, int _tuoi){ ten = _ten; tuoi = _tuoi; } void setTen(string _ten){ ten = _ten; } void setTuoi(int _tuoi){ tuoi = _tuoi; } string getTen(){ return ten; } int getTuoi(){ return tuoi; } void inPerson(){ cout<<"Ten: "<<ten<<endl; cout<<"Tuoi: "<<tuoi<<endl; } }; template <class T> class Stack{ private: vector<T> list; int maxSize; public: void setList(vector<T> _list){ list = _list; } void setMaxSize(int _maxSize){ maxSize = _maxSize; } vector<T> getList(){ return list; } int getMaxSize(){ return maxSize; } void push(T var){ list.push_back(var); } T pop(){ T p = list.back(); //T p = list.front(); list.pop_back(); // list.erase(0); return p; } }; template <class T> class checkStack : public Stack<T>{ public: void push(T var){ if(Stack<T>::getMaxSize() == Stack<T>::getList().size()){ cout<<"Stack da day, khong the them"<<endl; exit(1); }else{ Stack<T>::push(var); } } T pop(){ if(Stack<T>::getList().size() == 0){ cout<<"Stack rong"<<endl; exit(1); }else{ return Stack<T>::pop(); } } }; int main(){ Person p1 = Person("Alice",5); Person p2 = Person("Johny",3); p1.inPerson(); p2.inPerson(); checkStack<Person> stack; vector<Person> list; stack.setList(list); stack.setMaxSize(2); stack.push(p1); stack.push(p2); // stack.push(p1); stack.pop().inPerson(); } <file_sep>#include<iostream> #include<vector> using namespace std; class Person{ private: string ten; int tuoi; public: Person(string _ten, int _tuoi){ ten = _ten; tuoi = _tuoi; } void setTen(string _ten){ ten = _ten; } void setTuoi(int _tuoi){ tuoi = _tuoi; } string getTen(){ return ten; } int getTuoi(){ return tuoi; } void inPerson(){ cout<<"Ten: "<<ten<<endl; cout<<"Tuoi: "<<tuoi<<endl; } }; template <class T> class Queue{ private: vector<T> list; int maxSize; public: void setList(vector<T> _list){ list = _list; } void setMaxSize(int _maxSize){ maxSize = _maxSize; } vector<T> getList(){ return list; } int getMaxSize(){ return maxSize; } void push(T var){ list.push_back(var); } T pop(){ T p = list.front(); list.erase(list.begin()); return p; } }; template <class T> class checkQueue : public Queue<T>{ public: void push(T var){ if(Queue<T>::getMaxSize() == Queue<T>::getList().size()){ cout<<"Queue da day, khong the them"<<endl; exit(1); }else{ Queue<T>::push(var); } } T pop(){ if(Queue<T>::getList().size() == 0){ cout<<"Queue rong"<<endl; exit(1); }else{ return Queue<T>::pop(); } } }; int main(){ Person p1 = Person("Alice",5); Person p2 = Person("Johny",3); p1.inPerson(); p2.inPerson(); checkQueue<Person> Queue; vector<Person> list; Queue.setList(list); Queue.setMaxSize(2); Queue.push(p1); Queue.push(p2); // stack.push(p1); Queue.pop().inPerson(); } <file_sep>#include<iostream> #include<string> #include<vector> using namespace std; class NhanVien{ protected: string ten; int namSinh; long long bacLuong; public: NhanVien(string t, int ns, long long bl){ ten = t; namSinh = ns; bacLuong = bl; } string getTen(){ return ten; } int getNamSinh(){ return namSinh; } long long getBacLuong(){ return bacLuong; } void setTen(string ten){ this->ten = ten; } void setNamSinh(int namSinh){ this->namSinh = namSinh; } void setBacLuong(long long bacLuong){ this->bacLuong = bacLuong; } long long tinhLuong(){ return bacLuong * 200; } void inThongTin(){ cout<<"Ten: "<<ten<<endl; cout<<"Nam sinh: "<<namSinh<<endl; cout<<"Bac luong: "<<bacLuong<<endl; } }; class QuanLy : public NhanVien{ private: string chucVu; float heSoPC; public: QuanLy(string t, int ns, long long bl, string cv,float pc) : NhanVien(t,ns,bl){ chucVu = cv; heSoPC = pc; } string getChucVu(){ return chucVu; } float getHeSoPC(){ return heSoPC; } void setChucVu(string cv){ chucVu = cv; } void setHeSoPC(float pc){ heSoPC = pc; } long long tinhLuong(){ return (bacLuong + heSoPC) * 200; } void inThongTin(){ NhanVien::inThongTin(); cout<<"Chuc vu: "<<chucVu<<endl; cout<<"He so phu cap: "<<heSoPC<<endl; } }; class Phong{ private: string tenPhong; vector<QuanLy> dsQuanLy; vector<NhanVien> dsNhanVien; public: Phong(string tp, vector<QuanLy> dsql,vector<NhanVien> dsnv){ tenPhong = tp; dsQuanLy = dsql; dsNhanVien = dsnv; } string getTenPhong(){ return tenPhong; } vector<QuanLy> getDanhSachQuanLy(){ return dsQuanLy; } vector<NhanVien> getDanhSachNhanVien(){ return dsNhanVien; } void setTenPhong(string tp){ tenPhong = tp; } void setDanhSachQuanLy(vector<QuanLy> dsql){ dsQuanLy = dsql; } void setDanhSachNhanVien(vector<NhanVien> dsnv){ dsNhanVien = dsnv; } void inThongTin(){ for(int i = 0; i < dsQuanLy.size(); i++){ dsQuanLy[i].inThongTin(); } for(int i = 0; i < dsNhanVien.size();i++){ dsNhanVien[i].inThongTin(); } } NhanVien tinhLuongCaoNhat(){ NhanVien nv = dsNhanVien[0]; for(int i = 0; i < dsNhanVien.size();i++){ if(nv.tinhLuong() < dsNhanVien[i].tinhLuong()) nv = dsNhanVien[i]; } //cout<<"Nhan vien co luong cao nhat: "<<nv.tinhLuong()<<endl; return nv; } }; int main(){ vector<QuanLy> danhSachQL; QuanLy ql1 = QuanLy("tuan",1998,4,"ql1",10000); danhSachQL.push_back(ql1); ql1.inThongTin(); QuanLy ql2 = QuanLy("van",1997,5,"ql2",20000); danhSachQL.push_back(ql2); ql2.inThongTin(); cout<<"-------------------------------------"<<endl; vector<NhanVien> danhSachNV; NhanVien nv1 = NhanVien("anh",1998,8); danhSachNV.push_back(nv1); NhanVien nv2 = NhanVien("nam",2000,6); danhSachNV.push_back(nv2); NhanVien nv3 = NhanVien("canh",2000,10); danhSachNV.push_back(nv3); NhanVien nv4 = NhanVien("tu",1997,20); Phong p1 = Phong("Phong 1",danhSachQL,danhSachNV); cout<<"Luong nhan vien cao nhat: "<<endl; cout<<"Ten: "<<p1.tinhLuongCaoNhat().getTen()<<endl; cout<<"Luong: "<<p1.tinhLuongCaoNhat().tinhLuong()<<endl; } <file_sep>#include<iostream> using namespace std; class RGB{ private: int red; int green; int blue; public: int getRed(); void setRed(int); }; int RGB::getRed(){ return red; } void RGB::setRed(int r){ if(r < 0 || r > 255){ cout<<"gia tri phai tu 0..255"; red = 0; }else red = r; } int main(){ RGB color1; color1.setRed(250); cout<<color1.getRed(); } <file_sep>#include<iostream> using namespace std; class Date{ private: int day; int month; int year; public: Date(void); ~Date(void); Date(int,int,int); Date(const Date &); Date operator -(Date); friend istream& operator >>(istream &, Date &); friend ostream& operator <<(ostream &, Date &); bool operator >(Date); bool operator <(Date); bool operator ==(Date); }; Date::Date(void){ day = 1; month = 1; year = 1000; } Date::~Date(void){ } Date::Date(int d, int m, int y){ day = d; month = m; year = y; } Date::Date(const Date &d){ day = d.day; month = d.month; year = d.year; } istream& operator >>(istream &is, Date &d){ cout<<"Enter day: "; is>>d.day cout<<"Enter month: "; is>>d.month; cout<<"Enter year: "; is>>d.year; return is; } ostream& operator <<(ostream &os, Date &d){ cout<<d.day<<" - "<<d.month<<" - "<<d.year<<endl; return os; } <file_sep>#include<iostream> #include<string> #include<vector> using namespace std; class Person{ protected: string hoTen; int tuoi; public: Person(){ } Person(string hoTen, int tuoi){ this->hoTen = hoTen; this->tuoi = tuoi; } string getHoTen(){ return hoTen; } int getTuoi(){ return tuoi; } void setHoTen(string hoTen){ this->hoTen = hoTen; } void setTuoi(int tuoi){ this->tuoi = tuoi; } }; class Student : public Person{ private: float toan, ly, hoa; public: Student(){ } Student(string hoTen, int tuoi, float toan, float ly, float hoa) : Person(hoTen, tuoi){ this->toan = toan; this->ly = ly; this->hoa = hoa; } float getToan(){ return toan; } float getLy(){ return ly; } float getHoa(){ return hoa; } void setToan(float toan){ this->toan = toan; } void setLy(float ly){ this->ly = ly; } void setHoa(float hoa){ this->hoa = hoa; } float tinhDiemTB(){ float DiemTB = (toan + ly + hoa) / 3.0; return DiemTB; } }; class Teacher : public Person{ private: vector<Student> danhSach; Person P; public: Teacher(){ } Teacher(string hoTen, int tuoi , vector<Student> ds) : Person(hoTen, tuoi){ danhSach = ds; } vector<Student> getDanhSach(){ return danhSach; } void setDanhSach(vector<Student> ds){ danhSach = ds; } Student diemCaoNhat(){ Student s = danhSach[0]; for(int i = 1; i < danhSach.size(); i++){ if(s.tinhDiemTB() < danhSach[i].tinhDiemTB()) s = danhSach[i]; } return s; } }; int main(){ int n; cout<<"\nNhap so sinh vien: "; cin>>n; vector<Student> danhSach; for(int i = 0; i < n; i++){ string hoTen; int tuoi; float toan, ly, hoa; cout<<"\nNhap sinh vien thu "<<i+1<<endl; cin.ignore(); cout<<"\nNhap ten sinh vien: "; getline(cin,hoTen); cout<<"\nNhap tuoi: "; cin>>tuoi; cout<<"\nNhap diem toan: "; cin>>toan; cout<<"\nNhap diem ly: "; cin>>ly; cout<<"\nNhap diem hoa: "; cin>>hoa; danhSach.push_back(Student(hoTen, tuoi,toan,ly,hoa)); cout<<"\nDiem trung binh: "<<danhSach[i].tinhDiemTB(); } string hoTen; int tuoi; cin.ignore(); cout<<"\nNhap ten giao vien: "; getline(cin,hoTen); cout<<"\nNhap tuoi: "; cin>>tuoi; Teacher tc = Teacher(hoTen,tuoi,danhSach); cout<<"\nSinh vien co diem trung binh cao nhat: "<<endl; cout<<"Ten: "<<tc.diemCaoNhat().getHoTen()<<"\nTuoi: "<<tc.diemCaoNhat().getTuoi()<<endl; } <file_sep>#include<iostream> #include<string> using namespace std; class Circle{ private: double radius; string color; public: //contructor with default values for data members Circle(double r = 1.0, string c = "red"){ radius = r; color = c; } double getRadius(){ return radius; } string getColor(){ return color; } double getArea(){ return radius*radius*3.1416; } }; int main(){ Circle c1(1.2,"blue"); cout<<"radius: "<<c1.getRadius()<<" Area: "<<c1.getArea()<<" color: "<<c1.getColor()<<endl; } <file_sep>#include<iostream> #include<string> using namespace std; const float LUONGCOBAN = 100; const float NGAYCONG = 100; class Nhanvien{ private: string hoTen; int CMND; public: Nhanvien(string ht, int cm){ hoTen = ht; CMND = cm; } string getHoTen(){ return hoTen; } int getCMND(){ return CMND; } void setHoTen(string ht){ hoTen = ht; } void setCMND(int cm){ CMND = cm; } virtual void inThongTin(){ cout<<hoTen<<" "<<CMND<<" "; } float tinhLuong(); }; class NhanvienHC: public Nhanvien{ private: float bacLuong; public: NhanvienHC(string ht, int cm, float bl) : Nhanvien(ht,cm){ bacLuong = bl; } float getBacLuong(){ return bacLuong; } void setBacLuong(float bl){ bacLuong = bl; } float tinhLuong(){ return bacLuong * LUONGCOBAN; } void inThongTin() { Nhanvien::inThongTin(); cout<<bacLuong<<endl; cout<<tinhLuong()<<endl; } void nhapThongTin(){ } }; class NhanvienCN : public Nhanvien{ private: int soNgayCong; public: NhanvienCN(string ht, int cm, int snc) : Nhanvien(ht,cm){ //Nhanvien::Nhanvien(ht,cm); soNgayCong = snc; } int getSoNgayCong(){ return soNgayCong; } void setSoNgayCong(int snc){ soNgayCong = snc; } float tinhLuong(){ return soNgayCong * NGAYCONG; } void inThongTin(){ Nhanvien::inThongTin(); cout<<soNgayCong<<endl; cout<<tinhLuong()<<endl; } }; int main(){ NhanvienHC nvhc("<NAME>", 123456, 3.99); nvhc.inThongTin(); NhanvienCN nvcn("<NAME>",234567, 15); nvcn.inThongTin(); return 0; } <file_sep>#include<iostream> #include<vector> using namespace std; class Diem{ private: string monhoc; float diemso; int tinchi; public: Diem(){ }; Diem(string mh, float ds, int tc):monhoc(mh),diemso(ds),tinchi(tc){ }; void inDiem(){ cout<<"Mon hoc: "<<monhoc<<endl; cout<<"Diem so: "<<diemso<<endl; cout<<"So tin chi: "<<tinchi<<endl; } }; class BangDiem{ private: int n; vector<Diem> bang; public: void nhapDiem(){ cout<<"Nhap so mon hoc: "; cin>>n; for(int i = 0; i < n; i++){ string monhoc; float diemso; int tinchi; cout<<"Mon hoc so "<<i<<endl; cout<<"Ten mon hoc: "; getline(cin,monhoc); cin.ignore(256,'\n') ; cout<<"Diem so: ";cin>>diemso; cout<<"Tin chi: ";cin>>tinchi; bang.push_back(Diem(monhoc,diemso,tinchi)); } } void inBangDiem(){ for(int i = 0; i < n; i++){ cout<<"Mon hoc so "<<i<<endl; bang[i].inDiem(); } } }; int main(){ // Diem diem1; // Diem diem("Toan roi rac",5.5,2); // diem1.inDiem(); BangDiem bd; bd.nhapDiem(); bd.inBangDiem(); return 0; } <file_sep>#include<iostream> using namespace std; class Date{ private: int day; int month; int year; int daysIn(int); public: Date(); int getDay(); void setDay(int); int getMonth(); void setMonth(int); int getYear(); void setYear(int); void normalize(); void advance(int , int, int); void print(); }; Date::Date(){ day = 1; month = 1; year = 2000; } int Date::getDay(){ return day; } void Date::setDay(int d){ year = d; } int Date::getMonth(){ return month; } void Date::setMonth(int m){ month = m; } int Date::getYear(){ return year; } void Date::setYear(int y){ year = y; } int Date::daysIn(int m){ int Months[] = {0,31,28,31,30,31,30,31,31,30,31,30,31}; return Months[m]; } void Date::normalize(){ if(day < 1) day = 1; if(day > daysIn(month)) day = daysIn(month); if(month < 1) month = 1; if(month > 12) month = 12; if(year < 1) year = 2000; } void Date::print(){ cout<<"Ngay "<<day<<" / "<<month<<" / "<<year<<endl; } void Date::advance(int d, int m, int y){ day += d; while(day > daysIn(month) ){ day = day - daysIn(month); month++; if(month > 12){ year++; month -= 12; } } month += m; while(month > 12){ year++; month -= 12; } year += y; } int main(){ Date date1; date1.print(); Date date2; date2.setDay(1); date2.setMonth(5); date2.setYear(2016); date2.print(); date2.normalize(); date2.advance(365,0,0); date2.print(); return 0; } <file_sep>#include<iostream> #include<vector> using namespace std; class Nguoi{ private: string HoTen; int NamSinh; string SoDienThoai; string Email; public: Nguoi(); string getHoTen(); void setHoTen(string); int getNamSinh(); void setNamSinh(int); string getSoDienThoai(); void setSoDienThoai(string); string getEmail(); void setEmail(string); }; class DanhBa{ private: int SoNguoi; vector<Nguoi> DanhSach; public: };
1faf941ea001dcd8cf6c189e31054db929f22fd9
[ "C++" ]
21
C++
ledinhhuan/laptrinhc-
8477af780269f319b892393781cba9844e8b9c7e
846087c52acf4f3c13b4cdeb52891d00acc09305
refs/heads/master
<file_sep># Write a program that interprets the Body Mass Index (BMI) based on a user's weight and height. # It should tell them the interpretation of their BMI based on the BMI value. # Under 18.5 they are underweight # Over 18.5 but below 25 they have a normal weight # Over 25 but below 30 they are slightly overweight # Over 30 but below 35 they are obese # Above 35 they are clinically obese. height = float(input("enter your height in m: ")) weight = float(input("enter your weight in kg: ")) bmi_now = weight / (height * height) print(bmi_now) bmi = int(bmi_now) if(bmi < 18.5): print("Underweight") elif(bmi>= 18.5 and bmi < 25): print("Normal") elif (bmi >= 25 and bmi <30): print("Slightly overweight") elif (bmi >=30 and bmi < 35): print("obese") else: print("clinically obese")<file_sep>#Given the names and grades for each student in a class of N students, #Store them in a nested list and print the name(s) of any student(s) having the second lowest grade. #Note: If there are multiple students with the second lowest grade, order their names alphabetically and print each name on a new line. #Level - Easy list = [] for _ in range(int(input())): name = input() score = float(input()) list.append([name, score]) second_highest = sorted(set([score for name, score in list]))[1] print('\n'.join(sorted([name for name, score in list if score == second_highest])))<file_sep>#The included code stub will read an integer,n , from STDIN. #Without using any string methods, try to print the following: 123...n #Note that "..." represents the consecutive values in between. Example: n=5, print 12345 #Contraints: 1<=n<=150 #Level - Easy n = int(input("Enter the value for n: ")) for i in range(1, n+1): print(i, end = "")<file_sep># Based on a user's order, work out their final bill. # Small Pizza: $15 # Small Pizza: $15 # Medium Pizza: $20 # Medium Pizza: $20 # Large Pizza: $25 # Large Pizza: $25 # Pepperoni for Small Pizza: +$2 # Pepperoni for Small Pizza: +$2 # Pepperoni for Medium or Large Pizza: +$3 # Pepperoni for Medium or Large Pizza: +$3 # Extra cheese for any size pizza: + $1 print("Welcome to Pizza Deliveries!") size = input("What size pizza do you want? S, M, or L ") add_pepperoni = input("Do you want pepperoni? Y or N ") extra_cheese = input("Do you want extra cheese? Y or N ") bill =0 if (size == 'S'): bill+=15 if(add_pepperoni =="Y"): bill+=2 elif (size == "M"): bill+=20 if(add_pepperoni =="Y"): bill+=3 else: bill+=25 if(add_pepperoni =="Y"): bill+=3 if(extra_cheese == "Y"): bill+=1 print(f" Your final bill is ${bill}")<file_sep># 100-days-of-code-python Udemy course - 100 days of python. Learn python step by step <file_sep>#If the bill was $150.00, split between 5 people, with 12% tip. #Each person should pay (150.00 / 5) * 1.12 = 33.6 #Format the result to 2 decimal places = 33.60 bill = float(input(" How much was total bill in $ ")) people = int(input(" Split between how many people? ") ) tip = int(input(" Input tip percentage? 10,12 or 15? ")) tip_as_percent = tip /100 tip_amt = bill * tip_as_percent total_bill = tip_amt + bill per_person = total_bill / people final = round(per_person,2) final ="{:.2f}".format(per_person) print(f" each person pays: ${final}") <file_sep>#Given a year, determine whether it is a leap year. If it is a leap year, return the Boolean True, otherwise return False. #The code stub provided reads from STDIN and passes arguments to the is_leap function. #Constraints: 1900<=year<=10^5 #Level - Medium def is_leap(year): leap = False if year % 400 == 0: return True if year % 100 == 0: return False if year % 4 == 0: return True else: print("Enter a year greater than or equal to 1990 ") return False return leap year = int(input("Enter a year ")) print(is_leap(year))<file_sep>#Say "Hello, World!" With Python # Level - Easy print("hello, World!")<file_sep># Write a program that adds the digits in a 2 digit number. # e.g. if the input was 35, then the output should be 3 + 5 = 8 two_digit_number = input("Type a two digit number: ") num = type(two_digit_number) one = two_digit_number[0] two = two_digit_number[1] print(int(one)+int(two))<file_sep># Create a program using maths and f-Strings that tells us how many days, weeks, months we have left if we live until 90 years old. # It will take your current age as the input and output a message with our time left in this format: # You have x days, y weeks, and z months left. # Where x, y and z are replaced with the actual calculated numbers. age = input("What is your current age?") diff = 90 - int(age) year = int(diff) * 365 weeks = int(diff) * 52 months =int(diff) * 12 print(f" You have {year} days, {weeks} weeks, and {months} months left")<file_sep># Rock, Paper and Scissors rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) ---.__(___) ''' import random print("User starts!") user_choice = int(input("Input 0 for Rock, 1 for Paper, 2 for Scissors ")) if(user_choice<=2): computer_choice = random.randint(0,2) print(f"Computer chooses {computer_choice}") if(user_choice == 0 and computer_choice == 2 ): print("User Wins!") elif(computer_choice == 0 and user_choice == 2 ): print("Computer Wins!") elif(user_choice > computer_choice): print("User Wins!") elif(user_choice < computer_choice): print("Computer Wins!") else: print("Draw") else: print("Invalid Input") <file_sep># You are going to write a program that tests the compatibility between two people. # To work out the love score between two people: # Take both people's names and check for the number of times the letters in the word TRUE occurs. # Then check for the number of times the letters in the word LOVE occurs. # Then combine these numbers to make a 2 digit number. # For Love Scores **less than 10** or **greater than 90**, the message should be: # `"Your score is **x**, you go together like coke and mentos."` # For Love Scores **between 40** and **50**, the message should be: # `"Your score is **y**, you are alright together."` # Otherwise, the message will just be their score. e.g.: # `"Your score is **z**."` print("Welcome to the Love Calculator!") name1 = input("What is your name? \n") name2 = input("What is their name? \n") name_combine=name1.lower()+name2.lower() count_t=name_combine.count("t") count_r=name_combine.count("r") count_u=name_combine.count("u") count_e=name_combine.count("e") total_true=count_t+count_r+count_u+count_e count_l=name_combine.count("l") count_o=name_combine.count("o") count_v=name_combine.count("v") count_e=name_combine.count("e") total_love=count_l+count_o+count_v+count_e total =str(total_love)+str(total_true) total_for_calc = int(total) if(total_for_calc<10 or total_for_calc>90): print(f" Your score is {total}, you go together like coke and mentos.") elif( total_for_calc>40 and total_for_calc <50): print(f"Your score is {total}, you are alright together.") else: print(f"Your score is {total}")<file_sep>#Consider a list (list = []). Perform the following commands #print the list #remove element from list #append element to end of the list #sort the list #pop last element from list #reverse the list #Level - Easy N = int(input(" Input number of commands you want to run ")) list = [] for i in range(0,N): ip=input(" enter command ").split() if ip[0] == "insert": list.insert(int(ip[1]),int(ip[2])) elif ip[0] == "print": print(list) elif ip[0] == "append": list.append(int(ip[1])) elif ip[0] == "remove": list.remove(int(ip[1])) elif ip[0] == "pop": list.pop() elif ip[0] == "sort": list.sort() else: list.reverse()<file_sep>#The provided code stub reads two integers from STDIN, a and b . Add code to print three lines where: #The first line contains the sum of the two numbers. #The second line contains the difference of the two numbers (first - second). #The third line contains the product of the two numbers. #Level - Easy a= int(input("Enter first number ")) b= int(input("Enter second number ")) print(" a+b : ",a+b) print(" a-b : ",a-b) print(" a*b : ",a*b)<file_sep>#You have a record of N students. # The provided code stub will read in a dictionary containing key/value pairs of name:[marks] for a list of students. Print the average of the marks array for the student name provided, showing 2 places after the decimal. # The user enters some integer N followed by the names and marks for N students. # You are required to save the record in a dictionary data type. # The user then enters a student's name. # Output the average percentage marks obtained by that student, correct to two decimal places. #Level - Easy N = int(input(" Number of Students ")) marks = {} for _ in range(N): name, *line = input(" Enter name of student and marks in subjects separated by ' ' ").split() scores = list(map(float, line)) marks[name] = scores query_name = input(" Enter name of student ") result = list(marks[query_name]) per = sum(result)/len(result) print(" %.2f" % per) <file_sep># Write a program that works out whether if a given number is an odd or even number. number = int(input("Which number do you want to check? ")) if number%2 == 0: print("This number is an even number") else: print("This number is an odd number")<file_sep>#The provided code stub reads an integer, n , from STDIN. For all non-negative integers i<n, print i^2. #Constraints: 1<=n<=20 #Level - Easy n= int(input("Enter value of n: ")) for i in range(n): print(i ** 2) <file_sep># Python practice from Hackerrank Includes my solutions for hackerranks python practice course as well as # Practice python from udemy Includes my solutions from 100 days of python to learn python <file_sep># write a program which will select a random name from a list of names. # The person selected will have to pay for everybody's food bill. # Split string method import random names_string = input("Give me everybody's names, separated by a comma. ") names = names_string.split(", ") len_of_list = len(names) bill = random.randint(0, len_of_list -1) print(f"{names[bill]}, will pay the bill today!")<file_sep># Random Heads or Tails using random import random choose = random.randint(0,1) if choose == 0: print("Heads") else: print("Tails")<file_sep># Given the participants' score sheet for your University Sports Day, you are required to find the runner-up score. You are given n scores. # Store them in a list and find the score of the runner-up. #Level - Easy n = int(input("enter number of scores ")) arr = map(int, input("Enter the numbers spaced out in same line ").split()) print (sorted(set(arr))[-2])<file_sep>#1. Create a greeting for your program. #2. Ask the user for the city that they grew up in. #3. Ask the user for the name of a pet. #4. Combine the name of their city and pet and show them their band name. print('Welcome to Band Name Generator\n') city = input("Input the name of city you grew up in\n") pet_name = input("Input name of your first pet\n") combine_name = print(city + pet_name)<file_sep>#The provided code stub reads two integers, a and b , from STDIN. #Add logic to print two lines. The first line should contain the result of integer division, a // b. #The second line should contain the result of float division, a / b. #Level - Easy a = int(input(" Enter first number ")) b = int(input(" Enter second number ")) print("Result of integer division a//b:", a//b) print("Result of float division a/b:", a/b)<file_sep># Let's learn about list comprehensions! You are given three integers x,y and z representing the dimensions of a cuboid along with an integer n. # Print a list of all possible coordinates given by (i,j,k) on a 3D grid where the sum of (i+j+k) is not equal to n. # Here, 0 <= i <= x; 0 <= j <= y; 0 <= k <= z . # Please use list comprehensions rather than multiple loops, as a learning exercise. #Level - Easy #----Using Loops----# loop = input("loop or comp: ") if(loop == 'loop'): x= int(input ("x: ")) y= int(input ("y: ")) z= int(input ("z: ")) n= int(input ("n: ")) for i in range(x+1): for j in range(y+1): for k in range(z+1): if sum((i,j,k)) !=n: print([i,j,k], end =" ") else: # list comprehension x= int(input ("x: ")) y= int(input ("y: ")) z= int(input ("z: ")) n= int(input ("n: ")) print([[i,j,k] for i in range(x+1) for j in range(y+1) for k in range(z+1) if sum([i,j,k]) != n]) <file_sep># Write a program that calculates the Body Mass Index (BMI) from a user's weight and height. # The BMI is a measure of some's weight taking into account their height. height = input("enter your height in m: ") weight = input("enter your weight in kg: ") bmi = int(height) /int (float(weight)*float(weight)) print(int(bmi))<file_sep>#Given an integer, , perform the following conditional actions: #If n is odd, print Weird #If n is even and in the inclusive range of 2 to 5, print Not Weird #If n is even and in the inclusive range of 6 to 20 , print Weird #If n is even and greater than 20, print Not Weird #Level - Easy import math import os import random import re import sys if __name__ == '__main__': n= int(input(" Enter a positive integer: ")) if(n % 2 == 1 or n>=6 and n<=20): print('Weird') elif(n%2 == 0 or n>=2 and n<=5 or n>=20 ): print('Not Weird') <file_sep># Your job is to write a program that allows you to mark a square on the map using a two-digit system. # The first digit is the vertical column number and the second digit is the horizontal row number # First your program must take the user input and convert it to a usable format. # Next, you need to use it to update your nested list with an "X". row1 = ["โฌœ๏ธ","โฌœ๏ธ","โฌœ๏ธ"] row2 = ["โฌœ๏ธ","โฌœ๏ธ","โฌœ๏ธ"] row3 = ["โฌœ๏ธ","โฌœ๏ธ","โฌœ๏ธ"] map = [row1, row2, row3] print(f"{row1}\n{row2}\n{row3}") position = input("Where do you want to put the treasure? ") hor = int(position[0]) ver = int(position[1]) selected_row = map[ver -1] selected_row[hor-1]="X"<file_sep># Write a program that switches the values stored in the variables a and b. a = input("a: ") b = input("b: ") c=a a=b b=c print("a: " + a) print("b: " + b) <file_sep>#Given an integer,n, and n space-separated integers as input, create a tuple,t, of those integers. #Then compute and print the result of hash(t). #Level - Easy N = int(input(" Enter tuple size")) list = map(int, input(" Enter tuple data").split()) print(hash(tuple(list)))
cbe4e455a676888114d79b28a98fdb41e9b23361
[ "Markdown", "Python" ]
29
Python
malvika1404/hackerrank-python
241ac580f12149973e2f08a6ee5df628975d545d
fc19e788e7ef1a31b56f8fccf90d79f6d9604d2b
refs/heads/master
<file_sep>package com.example.sys.cdailogue; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { final Context context = this; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate( savedInstanceState ); setContentView( R.layout.activity_main ); } public class ViewDialog{ public void showDialog(Activity activity,String msg) { final Dialog dialog = new Dialog(activity); dialog.requestWindowFeature( Window.FEATURE_NO_TITLE); dialog.setCancelable(false); dialog.setContentView( R.layout.activity_main); TextView t=dialog.findViewById( R.id.tv ); t.setText( msg ); Button b=dialog.findViewById( R.id.b ); b.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); } } ); dialog.show(); } } }
ec245f64f25798f6101a0549891fc3bafcb5f9fe
[ "Java" ]
1
Java
MohammadAsiff/Cdialogue
b0baec75091aa1dfcf62f72b2337c9e1b368bd28
56093ba6e88ec1bfe84ca39936ed456f2c5a43a1
refs/heads/master
<file_sep>package app.saran.getqure; import android.os.Bundle; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import org.json.JSONException; import org.json.JSONObject; import androidx.appcompat.app.AppCompatActivity; public class OPTicket extends AppCompatActivity { private TextView patientname,Time,hospital,id; private final String server ="http://192.168.43.26/example_4.json"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_opticket); id = (TextView)findViewById(R.id.patientId); patientname = (TextView)findViewById(R.id.patientName); Time = (TextView)findViewById(R.id.appointment_time); hospital = (TextView)findViewById(R.id.Hospital_Name); Patient op = new Patient(); JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, server, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { id.setText(response.getString("id")); patientname.setText(response.getString("patientname")); Time.setText(response.getString("Time")); hospital.setText(response.getString("hospital")); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(OPTicket.this,"error dude",Toast.LENGTH_LONG).show(); error.printStackTrace(); } }); MySingelten.getInstance(OPTicket.this).addToRequestque(jsonObjectRequest); } } <file_sep>package app.saran.getqure; import android.content.Context; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.Volley; public class MySingelten { private static MySingelten mInstance; private RequestQueue requestQueue; private static Context cntxt; public MySingelten(Context context){ cntxt = context; requestQueue = getRequestQueue(); } public RequestQueue getRequestQueue(){ if(requestQueue == null){ requestQueue = Volley.newRequestQueue(cntxt.getApplicationContext()); } return requestQueue; } public static synchronized MySingelten getInstance(Context context){ if (mInstance==null){ mInstance = new MySingelten(context); } return mInstance; } public<T> void addToRequestque(Request<T> request){ requestQueue.add(request); } } <file_sep>package app.saran.getqure; import android.content.Context; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; public class BackTask { Context context; ArrayList<HospitalDetails> arrayList = new ArrayList<>(); final String jsonUrl = "http://192.168.43.26/example_4.json"; public BackTask(Context context) { this.context = context; } public ArrayList<HospitalDetails> getData(){ final JsonArrayRequest jsonarray = new JsonArrayRequest(Request.Method.POST, jsonUrl, null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { int count = 0; System.out.println("hello" + response.length()); int x = response.length(); while(count<x){ try { JSONObject jsonObject = response.getJSONObject(count); HospitalDetails hospital = new HospitalDetails(jsonObject.getString("hospitalName"),jsonObject.getString("doctorName"),jsonObject.getString("description")); arrayList.add(hospital); count++; } catch (JSONException e) { System.out.println("Error"); e.printStackTrace(); } } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(context,error.toString() ,Toast.LENGTH_LONG).show(); error.printStackTrace(); } }); MySingelten.getInstance(context).addToRequestque(jsonarray); return arrayList; } } <file_sep>package app.saran.getqure; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; public class LoginActivity extends AppCompatActivity { private EditText email,passwaord; private TextView alrdy; private Button logIn; private FirebaseAuth.AuthStateListener authListener; private FirebaseAuth mAuth; final String Tag = "testcase"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); email = findViewById(R.id.lemail); passwaord = findViewById(R.id.lpassword); logIn = findViewById(R.id.Log_in); alrdy = findViewById(R.id.alrdy); mAuth = FirebaseAuth.getInstance(); alrdy.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(getApplicationContext(),MainUser.class)); } }); logIn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String Email = email.getText().toString().trim(); String Password = <PASSWORD>().<PASSWORD>().<PASSWORD>(); if (TextUtils.isEmpty(Email)) { email.setError("Invalid Email address"); return; } if (TextUtils.isEmpty(Password)) { passwaord.setError("Passward field can't be Empty"); return; } if(Password.length() < 8){ passwaord.setError("password cant be less then 8"); } mAuth.signInWithEmailAndPassword(Email,Password).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()){ finish(); startActivity(new Intent(getApplicationContext(),MainUser.class) ); } else{ startActivity(new Intent(getApplicationContext(),RegisterActivity.class)); } } }); } }); } } <file_sep>package app.saran.getqure; import android.content.Intent; import android.os.Bundle; import android.widget.Toast; import java.util.ArrayList; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; public class MainUser extends AppCompatActivity implements HospitalDetailAdapter.OnNoteClickListener { private static final String TAG = "testcase"; ArrayList<HospitalDetails> Hospitals; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_user); RecyclerView rvHospital = (RecyclerView)findViewById(R.id.Recyle); BackTask backTask = new BackTask(MainUser.this); Hospitals =backTask.getData(); if (Hospitals == null){ Toast.makeText(getApplicationContext(),"null",Toast.LENGTH_LONG).show(); } HospitalDetailAdapter hdAdapter = new HospitalDetailAdapter(Hospitals,this); rvHospital.setAdapter(hdAdapter); rvHospital.setLayoutManager(new LinearLayoutManager(this)); } @Override public void onNoteClick(int position) { Intent intent = new Intent(this,ApointmentActivity.class); intent.putExtra("Hospital & Doctor",Hospitals.get(position)); startActivity(intent); } } <file_sep>package app.saran.getqure; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; public class RegisterActivity extends AppCompatActivity { private EditText username,email,password; private Button register; private ProgressBar prog; private FirebaseAuth mAuth; private TextView already; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); username =findViewById(R.id.name); email =findViewById(R.id.email); password =findViewById(R.id.passWord); register =findViewById(R.id.register); prog = findViewById(R.id.progressBar); mAuth = FirebaseAuth.getInstance(); already =findViewById(R.id.alredy); already.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(getApplicationContext(),LoginActivity.class)); } }); final String TAG = "testcase"; if (mAuth.getCurrentUser() != null){ finish(); startActivity(new Intent(getApplicationContext(),LoginActivity.class)); } register.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String Email = email.getText().toString().trim(); String Password = password.getText().toString().trim(); if (TextUtils.isEmpty(Email)) { email.setError("Invalid Email address"); return; } if (TextUtils.isEmpty(Password)) { password.setError("Passward field can't be Empty"); return; } if(Password.length() < 8){ password.setError("password cant be less then 8"); } prog.setVisibility(View.INVISIBLE); register.setVisibility(View.INVISIBLE); mAuth.createUserWithEmailAndPassword(Email,Password).addOnCompleteListener(new OnCompleteListener<AuthResult>(){ @Override public void onComplete(@NonNull Task<AuthResult> task){ if(task.isSuccessful()){ FirebaseUser user = mAuth.getCurrentUser(); user.sendEmailVerification().addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Toast.makeText(RegisterActivity.this,"VERIFICATION EMAIL SENT",Toast.LENGTH_SHORT).show(); startActivity(new Intent(getApplicationContext(),MainUser.class)); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(RegisterActivity.this,"NOT SENT",Toast.LENGTH_SHORT).show(); } }); Toast.makeText(RegisterActivity.this,"created",Toast.LENGTH_SHORT).show(); startActivity(new Intent(getApplicationContext(),OPTicket.class)); Log.i(TAG,"done"); finish(); } else{ Toast.makeText(RegisterActivity.this,"Error"+ task.getException().getMessage(),Toast.LENGTH_SHORT).show(); Log.i(TAG,task.getException().getMessage()); startActivity(new Intent(getApplicationContext(),RegisterActivity.class)); } } }); } }); } } <file_sep>include ':app' rootProject.name='Get Qure'
848b3dfb9fd4c8732c2570f5bc12ad09c94758dc
[ "Java", "Gradle" ]
7
Java
Saranpandiyan963/GetQure
8190ad541800c571c21157f30f824eae3b6154c8
932ee084149e78f4a9f6a27f365a23278a89cb0e
refs/heads/master
<file_sep>// Infix Expression Parser.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <string> #include <sstream> #include "InfixExpressionParser.h" using namespace std; int main() { bool validExpression = false; char c; InfixExpressionParser exParser; while (1) { cout << "Enter a valid infix arithmetic expression" << endl << endl; getline(cin, exParser.expression); validExpression = exParser.errorChecking(); if (validExpression) { exParser.expressionEval(); } validExpression = false; cout << endl << "Enter C to continue \nEnter Q to quit" << endl << endl; cin >> c; if (c == 'q' || c == 'Q') { break; } } cout << endl; system("pause"); return 0; } <file_sep>#pragma once #include "stdafx.h" #include <iostream> #include <string> #include <sstream> #include <stack> #include <algorithm> using namespace std; class InfixExpressionParser { public: string expression; bool errorChecking(); void expressionEval(); InfixExpressionParser(); ~InfixExpressionParser(); private: int i = 0, j = 0; stack<int> numStack; stack<string> opStack; int stringToInt(); int opPrecedence(string strOperators, bool stackOp); void processStack(); }; <file_sep>#include "stdafx.h" #include "InfixExpressionParser.h" #include <iostream> #include <string> #include <sstream> #include <stack> #include <algorithm> InfixExpressionParser::InfixExpressionParser() { } InfixExpressionParser::~InfixExpressionParser() { } bool InfixExpressionParser::errorChecking() { //The following variables are counters int open = 0, closed = 0, binaryOp = 0, digits = 0, unaryOp = 0; for (i = 0; i < expression.length(); i++) { //Skips over unary operators and increments unaryOp for to make sure it isn't followed by a binary operator later, unaryOp is set back to zero at the end of the loop while ((expression[i] == '+' && expression[i + 1] == '+') || (expression[i] == '-' && expression[i + 1] == '-')) { i += 2; unaryOp++; } while ((expression[i] == '!' && expression[i + 1] != '=')) { i++; unaryOp++; } if (expression[i] == '-') { if ((i == 0 && isdigit(expression[i + 1])) || (expression[i + 1] == '(')) { i++; unaryOp++; } } //If the # of closed parentheses is greater than open parenthesis then the expression is illegal if (expression[i] == '(') { open++; } if (expression[i] == ')') { closed++; } if (closed > open) { cout << "Unpaired closed parenthesis @ char: " << i << '\n'; return false; } //Checks if element is a binary operator if ((expression[i] == '+' && expression[i + 1] != '+') || (expression[i] == '-' && expression[i + 1] != '-') || (expression[i] == '&' && expression[i + 1] == '&') || (expression[i] == '|' && expression[i + 1] == '|') || (expression[i] == '>' && expression[i + 1] == '=') || (expression[i] == '<' && expression[i + 1] == '=') || (expression[i] == '=' && expression[i + 1] == '=') || (expression[i] == '!' && expression[i + 1] == '=') || (isdigit(expression[i]) && expression[i + 1] == '(') || expression[i] == '^' || expression[i] == '*' || expression[i] == '/' || expression[i] == '%' || expression[i] == '>' || expression[i] == '<') { binaryOp++; //Makes sure an unary operator isn't followed by a binary operator if (unaryOp > 0) { cout << "An unary operator can't be followed by a binary operator @ char: " << i << '\n'; } } //Only need to count the digit in the ones place if (isdigit(expression[i]) && !isdigit(expression[i + 1])) { digits++; } //Expression can't start with a binary operation if (digits == 0 && binaryOp == 1) { cout << "Expression can't begin with a binary operator @ char: " << i << '\n'; return false; } //Binary operators = operands - 1 if the expression deviates from this then there if (binaryOp > digits) { cout << "Binary operator can't be followed by another binary operator @ char: " << i << '\n'; return false; } //Statement checks if an operand is followed by another operatand by eliminating spaces but doesn't account for other characters if (isdigit(expression[i]) && expression[i + 1] == ' ') { j = i + 1; while (expression[j] == ' ') { j++; } if (isdigit(expression[j])) { cout << "Operands without an operator @ char: " << i << '\n'; return false; } } //If the previous statement makes doesn't catch illegal # of operands this one will but it won't be able to tell the position if ((i == expression.length() - 1) && (digits > binaryOp + 1)) { cout << "Operands without an operator\n"; return false; } //Statement checks if expression divides by zero if (expression[i] == '/') { if (expression[i + 1] == '0') { cout << "Cannot divide by zero @ char: " << i << '\n'; return false; } if (expression[i + 1] == ' ') { j = i + 1; while (expression[j] == ' ') { j++; } if (expression[j] == 0) { cout << "Cannot divide by zero @ char: " << i << '\n'; return false; } } } unaryOp = 0; } //cout << endl << "digits: "<< digits << endl << "binaryOp: " << binaryOp; i = 0; return true; } void InfixExpressionParser::expressionEval() { for (i = 0; i < expression.length(); i++) { //If the first part of the expression is "-(" then it adds -1 to the number stack and "*" to the operation stack if (expression[i] == '-' && isdigit(expression[i + 1]) && opStack.empty()) { numStack.push(-1); opStack.push("*"); continue; } //If the expression has the a number next to an open parenthesis, push the number on the num stack and push the "*" operator else if (isdigit(expression[i]) && expression[i + 1] == '(') { numStack.push(stringToInt()); opStack.push("*"); continue; } //If increment or decrement operator, add it to the opStack else if (((expression[i] == '+' && expression[i + 1] == '+') || (expression[i] == '-' && expression[i + 1] == '-')) && opStack.empty()) { opStack.push(expression.substr(i, 2)); i++; continue; } //If the element at i is a digit convert it to integer type and add it to the numStack else if (isdigit(expression[i])) { numStack.push(stringToInt()); if (expression[i + 1] == '(') { opStack.push("*"); opStack.push("("); i++; } continue; } //First time case for any operator else if ((opPrecedence(expression, false) > 0) && opStack.empty()) { opStack.push(expression.substr(i, 1)); continue; } //Always immediately push open parenthesis on opStack else if (expression[i] == '(') { opStack.push(expression.substr(i, 1)); continue; } //Whenever a closed parenthesis is found process all internal operations until an open parenthesis is found else if (expression[i] == ')') { while (opStack.top() != "(") { processStack(); } //Removes open parenthesis ( opStack.pop(); continue; } //If the precedence of the operator at expression[i] >= to the precedence of the operator on the top of the opStack then place the operator on the opStack else if (opPrecedence(expression, false) >= opPrecedence(opStack.top(), true)) { if ((expression[i] == '+' && expression[i + 1] == '+') || (expression[i] == '-' && expression[i + 1] == '-') || (expression[i] == '>' && expression[i + 1] == '=') || (expression[i] == '<' && expression[i + 1] == '=') || (expression[i] == '=' && expression[i + 1] == '=') || (expression[i] == '!' && expression[i + 1] == '=') || (expression[i] == '&' && expression[i + 1] == '&') || (expression[i] == '|' && expression[i + 1] == '|')) { opStack.push(expression.substr(i, 2)); i++; continue; } else if ((expression[i] == '-' && expression[i + 1] == '(')) { i++; numStack.push(-1); opStack.push("*"); opStack.push("("); continue; } else { opStack.push(expression.substr(i, 1)); continue; } } //If the precedence of the operator at expression[i] < the precedence of the operator on the top of the stack then process stack until it is >= then place the new operator on the opStack else if (opPrecedence(expression, false) < opPrecedence(opStack.top(), true)) { while (!opStack.empty()) { if (opPrecedence(expression, false) < opPrecedence(opStack.top(), true)) { processStack(); } else { break; } } if ((expression[i] == '+' && expression[i + 1] == '+') || (expression[i] == '-' && expression[i + 1] == '-') || (expression[i] == '>' && expression[i + 1] == '=') || (expression[i] == '<' && expression[i + 1] == '=') || (expression[i] == '=' && expression[i + 1] == '=') || (expression[i] == '!' && expression[i + 1] == '=') || (expression[i] == '&' && expression[i + 1] == '&') || (expression[i] == '|' && expression[i + 1] == '|')) { opStack.push(expression.substr(i, 2)); i++; continue; } else if ((expression[i] == '-' && expression[i + 1] == '(')) { i++; numStack.push(-1); opStack.push("*"); opStack.push("("); continue; } else { opStack.push(expression.substr(i, 1)); continue; } } } //Once at the end of the expression process the numStack and opStack until opStack is empty while (!opStack.empty()) { processStack(); } //Prints the result stored in the numStack cout << endl << numStack.top() << endl; } int InfixExpressionParser::stringToInt() { int val = 0, temp; //Makes sure i is not out of bounds and that element expression[i] is a digit while (i < expression.length() && isdigit(expression[i])) { //Convert character value to int switch (expression[i]) { case '0': temp = 0; break; case '1': temp = 1; break; case '2': temp = 2; break; case '3': temp = 3; break; case '4': temp = 4; break; case '5': temp = 5; break; case '6': temp = 6; break; case '7': temp = 7; break; case '8': temp = 8; break; case '9': temp = 9; break; } //In the case of multiple digits the first digit is converted then multiplied by ten and added to the next digit val = val * 10 + temp; i++; } //Returns i to the proper index --i; return val; } int InfixExpressionParser::opPrecedence(string strOperators, bool stackOp) { //j is a separate counter for operators on the opStack so the elements called aren't out of bounds j = 0; int k; if (stackOp == false) { k = i; } else { k = j; } //Determines the operator then returns it's precedence value if (k < strOperators.length() && strOperators.length() >= 2) { //Since switch must have constant values the multicharacter operands are handled in an if statement if (strOperators[k] == '+' && strOperators[k + 1] == '+') { return 8; } if (strOperators[k] == '-' && strOperators[k + 1] == '-') { return 8; } if (strOperators[k] == '-' && strOperators[k + 1] == '(') { return 8; } if (strOperators[k] == '>' && strOperators[k + 1] == '=') { return 4; } if (strOperators[k] == '<' && strOperators[k + 1] == '=') { return 4; } if (strOperators[k] == '=' && strOperators[k + 1] == '=') { return 3; } if (strOperators[k] == '!' && strOperators[k + 1] == '=') { return 3; } if (strOperators[k] == '&' && strOperators[k + 1] == '&') { return 2; } if (strOperators[k] == '|' && strOperators[k + 1] == '|') { return 1; } } if (k < strOperators.length()) { switch (strOperators[k]) { case '!': return 8; break; case '^': return 7; break; case '*': return 6; break; case '/': return 6; break; case '%': return 6; break; case '+': return 5; break; case '-': return 5; break; case '>': return 4; break; case '<': return 4; break; default: return 0; break; } } return 0; } void InfixExpressionParser::processStack() { //stackSecond is the left hand side of the operation while stackFirst is the right hand side, temp is just placeholder to be pushed on the number stack int stackFirst = 0, stackSecond = 0, temp = 0; string operate = opStack.top(); opStack.pop(); //If statement performs the operation based on the operator on the top of the opStack if (operate == "!") { stackFirst = numStack.top(); numStack.pop(); temp = !stackFirst; numStack.push(temp); } else if (operate == "++") { stackFirst = numStack.top(); numStack.pop(); temp = ++stackFirst; numStack.push(temp); } else if (operate == "--") { stackFirst = numStack.top(); numStack.pop(); temp = --stackFirst; numStack.push(temp); } else if (operate == "^") { stackFirst = numStack.top(); numStack.pop(); stackSecond = numStack.top(); numStack.pop(); temp = pow(stackSecond, stackFirst); numStack.push(temp); } else if (operate == "*") { stackFirst = numStack.top(); numStack.pop(); stackSecond = numStack.top(); numStack.pop(); temp = stackSecond*stackFirst; numStack.push(temp); } else if (operate == "/") { stackFirst = numStack.top(); numStack.pop(); stackSecond = numStack.top(); numStack.pop(); if (stackFirst == 0) { cout << "Expression divided by zero during processing\nProgram will now end" << endl; system("pause"); exit; } temp = stackSecond / stackFirst; numStack.push(temp); } else if (operate == "%") { stackFirst = numStack.top(); numStack.pop(); stackSecond = numStack.top(); numStack.pop(); temp = stackSecond % stackFirst; numStack.push(temp); } else if (operate == "+") { stackFirst = numStack.top(); numStack.pop(); stackSecond = numStack.top(); numStack.pop(); temp = stackSecond + stackFirst; numStack.push(temp); } else if (operate == "-") { stackFirst = numStack.top(); numStack.pop(); stackSecond = numStack.top(); numStack.pop(); temp = stackSecond - stackFirst; numStack.push(temp); } else if (operate == ">=") { stackFirst = numStack.top(); numStack.pop(); stackSecond = numStack.top(); numStack.pop(); temp = stackSecond >= stackFirst; numStack.push(temp); } else if (operate == "<=") { stackFirst = numStack.top(); numStack.pop(); stackSecond = numStack.top(); numStack.pop(); temp = stackSecond <= stackFirst; numStack.push(temp); } else if (operate == ">") { stackFirst = numStack.top(); numStack.pop(); stackSecond = numStack.top(); numStack.pop(); temp = stackSecond>stackFirst; numStack.push(temp); } else if (operate == "<") { stackFirst = numStack.top(); numStack.pop(); stackSecond = numStack.top(); numStack.pop(); temp = stackSecond<stackFirst; numStack.push(temp); } else if (operate == "==") { stackFirst = numStack.top(); numStack.pop(); stackSecond = numStack.top(); numStack.pop(); temp = stackSecond == stackFirst; numStack.push(temp); } else if (operate == "!=") { stackFirst = numStack.top(); numStack.pop(); stackSecond = numStack.top(); numStack.pop(); temp = stackSecond != stackFirst; numStack.push(temp); } else if (operate == "&&") { stackFirst = numStack.top(); numStack.pop(); stackSecond = numStack.top(); numStack.pop(); temp = stackSecond&&stackFirst; numStack.push(temp); } else if (operate == "||") { stackFirst = numStack.top(); numStack.pop(); stackSecond = numStack.top(); numStack.pop(); temp = stackSecond || stackFirst; numStack.push(temp); } }
b2bb9e38ab9844f37300d7569dee8dbf69f104fb
[ "C++" ]
3
C++
brant-nathaniel/Infix_Expression_Parser
547c2e4d6fc1e6e403f4245ff19fce115817daf3
9676f35e7eb960d1f8144492d59295379e15cce1
refs/heads/master
<file_sep>-- phpMyAdmin SQL Dump -- version 5.0.2 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Jun 05, 2020 at 03:12 PM -- Server version: 10.4.11-MariaDB -- PHP Version: 7.2.29 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `axis_dbs` -- -- -------------------------------------------------------- -- -- Table structure for table `admin` -- CREATE TABLE `admin` ( `id` int(11) NOT NULL, `username` text NOT NULL, `email` text NOT NULL, `firstname` text NOT NULL, `lastname` text NOT NULL, `password` text NOT NULL, `status` text NOT NULL, `timestamp` timestamp NOT NULL DEFAULT current_timestamp() ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `admin` -- INSERT INTO `admin` (`id`, `username`, `email`, `firstname`, `lastname`, `password`, `status`, `timestamp`) VALUES (1, 'haseebmughal69', '<EMAIL>', 'Haseeb', 'Mughal', 'hello', 'active', '2020-05-10 13:02:52'), (2, 'fahad', '<EMAIL>', 'Fahad', 'Irshad', 'fahad', 'active', '2020-05-10 20:07:30'); -- -------------------------------------------------------- -- -- Table structure for table `projects` -- CREATE TABLE `projects` ( `id` int(11) NOT NULL, `name` text NOT NULL, `type_id` int(11) NOT NULL, `description` text DEFAULT NULL, `status` text NOT NULL, `start_date` text DEFAULT NULL, `end_date` text DEFAULT NULL, `start_admin_id` int(11) NOT NULL DEFAULT 0, `end_admin_id` int(11) DEFAULT 0 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `projects` -- INSERT INTO `projects` (`id`, `name`, `type_id`, `description`, `status`, `start_date`, `end_date`, `start_admin_id`, `end_admin_id`) VALUES (3, 'First Project', 1, 'This is first project', 'completed', '2020-05-14 01:48:44', '2020-05-14 02:09:38', 1, 1), (4, 'cdvdf', 1, 'asfasdfasd', 'active', '2020-05-14 02:16:37', NULL, 1, 0), (5, 'Test Project', 1, 'hi', 'active', '2020-06-05 13:15:57', NULL, 1, 0); -- -------------------------------------------------------- -- -- Table structure for table `project_requirements` -- CREATE TABLE `project_requirements` ( `id` int(11) NOT NULL, `name` text NOT NULL, `revision` int(11) NOT NULL DEFAULT 1, `project_id` int(11) NOT NULL, `supplier_id` int(11) NOT NULL DEFAULT 0, `supplier_date` text DEFAULT NULL, `description` text DEFAULT NULL, `status` text NOT NULL, `start_date` text DEFAULT NULL, `end_date` text DEFAULT NULL, `start_admin_id` int(11) DEFAULT 0, `start_user_id` int(11) NOT NULL DEFAULT 0, `end_admin_id` int(11) NOT NULL DEFAULT 0 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `project_requirements` -- INSERT INTO `project_requirements` (`id`, `name`, `revision`, `project_id`, `supplier_id`, `supplier_date`, `description`, `status`, `start_date`, `end_date`, `start_admin_id`, `start_user_id`, `end_admin_id`) VALUES (7, 'First Requirement', 1, 3, 1, NULL, 'nsdhbvhbfds', 'active', '2020-05-14 01:48:54', NULL, 1, 0, 0), (8, 'safsafas', 1, 4, 1, NULL, 'fsafas', 'completed', '2020-05-14 02:16:41', '2020-06-05 13:14:45', 1, 0, 1), (9, 'New Requirement', 1, 5, 1, '2020-06-05 13:42:49', 'hi', 'finished', '2020-06-05 13:16:14', '2020-06-05 13:17:21', 1, 0, 1), (10, 'Second Requirement', 3, 5, 1, '2020-06-05 14:26:04', 'jhdsfsd', 'finished', '2020-06-05 13:25:48', '', 1, 0, 1), (11, 'Fixing of Bulb', 2, 5, 1, '2020-06-05 14:36:45', 'fixing', 'finished', '2020-06-05 14:29:56', '2020-06-05 14:38:37', 1, 0, 1), (12, 'User Requirement', 1, 5, 1, '2020-06-05 15:09:08', 'user', 'finished', '2020-06-05 14:44:44', '2020-06-05 15:09:20', 0, 1, 1), (13, 'Door is not closing...', 1, 5, 1, '2020-06-05 15:10:30', 'fsafs', 'finished', '2020-06-05 15:09:56', '2020-06-05 15:10:53', 0, 1, 1); -- -------------------------------------------------------- -- -- Table structure for table `project_types` -- CREATE TABLE `project_types` ( `id` int(11) NOT NULL, `name` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `project_types` -- INSERT INTO `project_types` (`id`, `name`) VALUES (1, 'Construction'), (2, 'Upgradation'); -- -------------------------------------------------------- -- -- Table structure for table `project_users` -- CREATE TABLE `project_users` ( `id` int(11) NOT NULL, `project_id` int(11) NOT NULL, `user_id` int(11) NOT NULL, `description` text DEFAULT NULL, `start_date` text DEFAULT NULL, `end_date` text DEFAULT NULL, `start_admin_id` int(11) NOT NULL DEFAULT 0, `end_admin_id` int(11) NOT NULL DEFAULT 0, `status` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `project_users` -- INSERT INTO `project_users` (`id`, `project_id`, `user_id`, `description`, `start_date`, `end_date`, `start_admin_id`, `end_admin_id`, `status`) VALUES (5, 3, 2, 'fdgd', '2020-05-14 01:52:14', NULL, 1, 0, 'active'), (6, 3, 1, 'fdhfdg', '2020-05-14 01:52:17', NULL, 1, 0, 'active'), (7, 4, 2, 'sa', '2020-05-14 02:16:44', NULL, 1, 0, 'active'), (8, 4, 1, 'fasdfas', '2020-05-14 02:16:47', NULL, 1, 0, 'active'), (9, 5, 1, 'bla', '2020-06-05 13:16:28', NULL, 1, 0, 'active'); -- -------------------------------------------------------- -- -- Table structure for table `requirement_comments` -- CREATE TABLE `requirement_comments` ( `id` int(11) NOT NULL, `requirement_id` int(11) NOT NULL, `revision` int(11) NOT NULL, `user_id` int(11) NOT NULL DEFAULT 0, `supplier_id` int(11) NOT NULL DEFAULT 0, `title` text NOT NULL, `comment` text NOT NULL, `file` text NOT NULL, `filename` text NOT NULL, `date_time` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `requirement_comments` -- INSERT INTO `requirement_comments` (`id`, `requirement_id`, `revision`, `user_id`, `supplier_id`, `title`, `comment`, `file`, `filename`, `date_time`) VALUES (6, 7, 1, 2, 0, 'First comment', 'kjjksdfsd', 'files/5ebc884ca09720.44686523.png', 'Untitled.png', '2020-05-14 01:52:44'), (7, 8, 1, 1, 0, 'gsfgdesfds', 'dsfsd', 'files/5ebc8e059d1e24.72081401.png', 'Basic Recipe.png', '2020-05-14 02:17:09'), (8, 8, 1, 1, 0, 'Testing Comment', 'fhgbhyusaggfdhjas', 'files/5ebd82083d7051.45163699.png', 'Untitled.png', '2020-05-14 19:38:16'), (9, 8, 1, 1, 0, 'Title comment', '', '', '', '2020-05-14 19:43:59'), (10, 8, 1, 1, 0, 'ddsfksdjhn', 'nkjds sdbnhjfhgsdbfmn sdnmfbds fsdhjfsdbhjfnkjds sdbnhjfhgsdbfmn sdnmfbds fsdhjfsdbhjfnkjds sdbnhjfhgsdbfmn sdnmfbds fsdhjfsdbhjfnkjds sdbnhjfhgsdbfmn sdnmfbds fsdhjfsdbhjfnkjds sdbnhjfhgsdbfmn sdnmfbds fsdhjfsdbhjfnkjds sdbnhjfhgsdbfmn sdnmfbds fsdhjfsdbhjfnkjds sdbnhjfhgsdbfmn sdnmfbds fsdhjfsdbhjfnkjds sdbnhjfhgsdbfmn sdnmfbds fsdhjfsdbhjfnkjds sdbnhjfhgsdbfmn sdnmfbds fsdhjfsdbhjfnkjds sdbnhjfhgsdbfmn sdnmfbds fsdhjfsdbhjfnkjds sdbnhjfhgsdbfmn sdnmfbds fsdhjfsdbhjfnkjds sdbnhjfhgsdbfmn sdnmfbds fsdhjfsdbhjf', '', '', '2020-05-14 19:45:08'), (11, 8, 1, 1, 0, 'fdhgfdgfd', 'gdfgfdgsfd', 'files/5ebd83c9897c94.96913140.png', 'Untitled4.png', '2020-05-14 19:45:45'), (12, 8, 1, 1, 0, 'test', 'This is comment test', '', '', '2020-05-28 11:28:07'), (13, 8, 1, 1, 0, 'New Comment', 'hi', '', '', '2020-06-05 12:54:19'), (14, 9, 1, 1, 0, 'hgajsah', 'hnkjsahnkajdd', '', '', '2020-06-05 13:16:56'), (15, 9, 1, 1, 0, 'sdfsafssa', 'safdasfdas', '', '', '2020-06-05 13:16:58'), (16, 9, 1, 1, 0, 'asfdasda', 'asdasdas', '', '', '2020-06-05 13:17:00'), (17, 9, 1, 1, 0, 'asdas', 'asdas', '', '', '2020-06-05 13:17:03'), (18, 9, 1, 0, 1, 'new commentsakjd', 'jskijdsak', 'files/5eda3132dfc093.74163179.png', 'Untitled.png', '2020-06-05 13:49:06'), (19, 9, 1, 0, 1, 'zxfdasfd', 'fdsadasdas', '', '', '2020-06-05 14:00:46'), (20, 10, 1, 1, 0, 'dsfdsf', 'dsffdsf', 'files/5eda3683735286.15181995.png', 'Untitled2.png', '2020-06-05 14:11:47'), (21, 10, 1, 1, 0, 'sadsa', 'asdas', 'files/5eda36876520c7.74414750.png', 'Untitled4.png', '2020-06-05 14:11:51'), (22, 10, 2, 0, 1, 'Requirement Completed', 'done!!!', '', '', '2020-06-05 14:23:19'), (23, 10, 3, 1, 0, 'sdsad', 'sdasdasdsa', '', '', '2020-06-05 14:25:51'), (24, 10, 3, 0, 1, 'done!', 'dsad', '', '', '2020-06-05 14:26:17'), (25, 11, 1, 1, 0, 'Second floor bulb damage', 'jshjd', 'files/5eda3af83ff0c1.33068173.png', 'Untitled1.png', '2020-06-05 14:30:48'), (26, 11, 1, 0, 1, 'Fixed!', 'ok', '', '', '2020-06-05 14:34:28'), (27, 11, 2, 1, 0, 'Fan off', 'sdfsa', '', '', '2020-06-05 14:36:31'), (28, 11, 2, 0, 1, 'fan is fine!', 'dsaj', '', '', '2020-06-05 14:38:30'), (29, 12, 1, 1, 0, 'dsfsdf', 'sdfsd', '', '', '2020-06-05 15:09:03'), (30, 12, 1, 0, 1, 'dsfsd', 'sdfsd', '', '', '2020-06-05 15:09:12'), (31, 13, 1, 1, 0, 'hajsghy', '<PASSWORD>', '', '', '2020-06-05 15:10:22'), (32, 13, 1, 0, 1, 'zxcfsadas', 'asdasdas', '', '', '2020-06-05 15:10:46'); -- -------------------------------------------------------- -- -- Table structure for table `suppliers` -- CREATE TABLE `suppliers` ( `id` int(11) NOT NULL, `username` text NOT NULL, `email` text NOT NULL, `firstname` text NOT NULL, `lastname` text NOT NULL, `password` text NOT NULL, `status` text NOT NULL, `last_login` text DEFAULT NULL, `timestamp` timestamp NOT NULL DEFAULT current_timestamp() ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `suppliers` -- INSERT INTO `suppliers` (`id`, `username`, `email`, `firstname`, `lastname`, `password`, `status`, `last_login`, `timestamp`) VALUES (1, 'haseeb', '<EMAIL>', 'Haseeb', 'Mughal', 'hi', 'active', '2020-06-05 14:26:36', '2020-05-28 08:55:48'), (2, 'Fahad', '<EMAIL>', 'Fahad', 'Irshad', 'hello', 'active', NULL, '2020-06-05 11:22:46'); -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `id` int(11) NOT NULL, `username` text NOT NULL, `email` text NOT NULL, `firstname` text NOT NULL, `lastname` text NOT NULL, `password` text NOT NULL, `status` text NOT NULL, `last_login` text DEFAULT NULL, `timestamp` timestamp NOT NULL DEFAULT current_timestamp() ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `username`, `email`, `firstname`, `lastname`, `password`, `status`, `last_login`, `timestamp`) VALUES (1, 'haseebmughal', '<EMAIL>', 'Haseeb', 'Mughal', 'hello', 'active', '2020-06-05 14:26:37', '2020-05-10 13:03:49'), (2, 'fahad', '<EMAIL>', 'Fahad', 'Irshad', 'fahad', 'active', '2020-05-14 01:53:17', '2020-05-10 20:12:20'), (4, 'test', '<EMAIL>', 'te', 'st', 'hello', 'active', NULL, '2020-05-28 08:51:54'); -- -- Indexes for dumped tables -- -- -- Indexes for table `admin` -- ALTER TABLE `admin` ADD PRIMARY KEY (`id`); -- -- Indexes for table `projects` -- ALTER TABLE `projects` ADD PRIMARY KEY (`id`); -- -- Indexes for table `project_requirements` -- ALTER TABLE `project_requirements` ADD PRIMARY KEY (`id`); -- -- Indexes for table `project_types` -- ALTER TABLE `project_types` ADD PRIMARY KEY (`id`); -- -- Indexes for table `project_users` -- ALTER TABLE `project_users` ADD PRIMARY KEY (`id`); -- -- Indexes for table `requirement_comments` -- ALTER TABLE `requirement_comments` ADD PRIMARY KEY (`id`); -- -- Indexes for table `suppliers` -- ALTER TABLE `suppliers` ADD PRIMARY KEY (`id`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `admin` -- ALTER TABLE `admin` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT for table `projects` -- ALTER TABLE `projects` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; -- -- AUTO_INCREMENT for table `project_requirements` -- ALTER TABLE `project_requirements` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14; -- -- AUTO_INCREMENT for table `project_types` -- ALTER TABLE `project_types` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT for table `project_users` -- ALTER TABLE `project_users` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10; -- -- AUTO_INCREMENT for table `requirement_comments` -- ALTER TABLE `requirement_comments` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=33; -- -- AUTO_INCREMENT for table `suppliers` -- ALTER TABLE `suppliers` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
d64372c12fc14c81a7a65fdb68e09d04de3bfc4c
[ "SQL" ]
1
SQL
fahadirshad7007/axis_dbs
c5aa3b383bd024df304489c6048fcffc3f08080c
e0a24b3dee054f320c92fd0d4b9234d8d862f9a4
refs/heads/master
<file_sep>import Syspro from '../src/sysprojs' import 'isomorphic-fetch' import fetchMock from 'fetch-mock' import { Exception } from 'handlebars' /** * Syspro tests */ describe('Syspro test', () => { describe('initialization', () => { it('succeeds when all parameters are present', () => { expect( new Syspro({ host: 'test.com', port: '20000', operator: 'Bob', operator_pass: null, company: 'A', company_pass: null }) ).toBeInstanceOf(Syspro) }) it('errors when parameters are missing', () => { ;['host', 'port', 'operator', 'company'].forEach(val => { expect(() => { let syspro = new Syspro({ host: val === 'host' ? null : 'http://test.com', port: val === 'port' ? null : '20000', operator: val === 'operator' ? null : 'Bob', operator_pass: null, company_pass: null, company: val === 'company' ? null : 'A' }) }).toThrowError(`No ${val} was defined.`) }) }) }) describe('authentication', () => { let syspro: Syspro let url: string afterEach(fetchMock.restore) beforeEach(() => { syspro = new Syspro({ host: 'http://test.com', port: '20000', operator: 'bob', operator_pass: null, company_pass: null, company: 'A' }) url = syspro.logonQuery() }) it('fails authentication with bad credentials', async () => { fetchMock.mock(url, { body: 'ERROR: Invalid credentials' }) let resp = await syspro.authenticate() expect(resp.ok).toBe(false) expect(resp.type).toEqual('failure') }) it('passes authentication and sets token with valid credentials', async () => { const token = '<PASSWORD> ' fetchMock.mock(url, { body: token }) let resp = await syspro.authenticate() expect(resp.ok).toBe(true) expect(resp.type).toEqual('success') expect(syspro.token).toEqual(token.trim()) }) it('fails when the server doesnt respond properly', async () => { fetchMock.mock(url, 500) let resp = await syspro.authenticate() expect(resp.ok).toBe(false) expect(resp.type).toEqual('failure') }) it('catches exceptions', async () => { fetchMock.mock(url, { throws: Error('Error! Error!') }) let resp = await syspro.authenticate() expect(resp.ok).toBe(false) expect(resp.type).toEqual('failure') }) it('includes companypass when present', () => { syspro.settings.company_pass = '<PASSWORD>' expect(syspro.logonQuery()).toContain('CompanyPassword') }) }) }) <file_sep>// Import here Polyfills if needed. Recommended core-js (npm i -D core-js) // import "core-js/fn/array.find" // ... import { ApiResult } from './api' import 'isomorphic-fetch' interface Settings { [key: string]: string host: string port: string operator: string operator_pass: string company: string company_pass: string } export default class Syspro { settings: Settings token: string = '' constructor(settings: Settings) { if (!settings.host) { throw new Error('No host was defined.') } if (!settings.port) { throw new Error('No port was defined.') } if (!settings.operator) { throw new Error('No operator was defined.') } if (!settings.company) { throw new Error('No company was defined.') } this.settings = settings } public async authenticate(): Promise<ApiResult<string>> { try { const resp = await fetch(this.logonQuery()) if (!resp.ok) { return { type: 'failure', ok: false, error: { detail: 'There was a problem connecting to the Syspro service.', title: 'Unable to connect to Syspro.' } } } return this.parseLogonResponse(await resp.text()) } catch (e) { return { type: 'failure', ok: false, error: { detail: e.message, title: 'Unable to authenticate with Syspro.' } } } } baseUrl(): string { return `${this.settings.host}:${this.settings.port}/sysprowcfservice/rest` } logonQuery(): string { let paramString = `/Logon?Operator=${this.settings.operator}&OperatorPassword=${ this.settings.operator_pass }` if (this.settings.company_pass) paramString += `&CompanyPassword=${this.settings.company_pass}` return this.baseUrl() + paramString } private parseLogonResponse(response: string): ApiResult<string> { if (response.includes('ERROR')) { return { type: 'failure', ok: false, error: { detail: response, title: 'There was a problem logging in to Syspro.' } } } this.token = response.trim() return { type: 'success', ok: true, value: this.token } } } <file_sep>export type ApiResult<T> = ResultSuccess<T> | ResultFail<ErrorResource> export interface ErrorResource { status?: number title?: string detail?: string source?: string } export interface ResultSuccess<T> { type: 'success' ok: true value: T } export interface ResultFail<T> { type: 'failure' ok: false error: T }
bb070955b6082b1f74998ac40543a80ae789e96b
[ "TypeScript" ]
3
TypeScript
johnernaut/sysprojs
4b1739bc135976b0f4b2a7065adbc8f893bcb44e
67fa29108921b275adf255223224519281fc1c62
refs/heads/main
<file_sep>'use strict' // ะ—ะฐะดะฐะฝะธะต 1: //var Tc = 25; //var temp = (9 / 5) * Tc + 32; //console.log(temp); // ะ—ะฐะดะฐะฝะธะต 2: //var name = 'ะ’ะฐัะธะปะธะน'; //var admin = name; //console.log(admin); // ะ—ะฐะดะฐะฝะธะต 3: // 1000108 // ะ—ะฐะดะฐะฝะธะต 4: // async - ะฟั€ะธ ะฝะฐะปะธั‡ะธะธ ะดะฐะฝะฝะพะณะพ ั‚ะตะณะฐ, ัะบั€ะธะฟั‚ ะฝะฐั‡ะฝะตั‚ ะฒั‹ะฟะพะปะฝะตะฝะธะต ะดะพ ะทะฐะณั€ัƒะทะบะธ ัั‚ั€ะฐะฝะธั†ั‹ // defer - ะฟั€ะธ ะฝะฐะปะธั‡ะธะธ ะดะฐะฝะฝะพะณะพ ั‚ะตะณะฐ, ัะบั€ะธะฟั‚ ะฝะต ะฝะฐั‡ะฝะตั‚ ะฒั‹ะฟะพะปะฝัั‚ัั ะฟะพะบะฐ ะฝะต ะทะฐะณั€ัƒะถะตะฝะฐ ัั‚ั€ะฐะฝะธั†ะฐ ัะฐะนั‚ะฐ
00e84588c21dd3d911ac2b96c9b929b4d5d75778
[ "JavaScript" ]
1
JavaScript
KiriLLLLLLLL/GB-Javascript
dcb10ac8e4e0f536167a876f5e00334df614a842
9aa9ca3d028d9522a64fe610b5d6b3d1ee4a2478
refs/heads/master
<repo_name>maan10/SkinCancerClassification<file_sep>/dataset_input.py import os import pandas as pd import torch import torch.utils.data as data import torchvision.transforms as transforms import numpy as np from PIL import Image from glob import glob from sklearn.model_selection import train_test_split base_skin_dir = os.path.join('/home/yjzhang/Work/SkinCancer', 'input') imageid_path_dict = {os.path.splitext(os.path.basename(x))[0]: x for x in glob(os.path.join(base_skin_dir, '*', '*.jpg'))} lesion_type_dict = { 'nv': 'Melanocytic nevi', 'mel': 'dermatofibroma', 'bkl': 'Benign keratosis-like lesions ', 'bcc': 'Basal cell carcinoma', 'akiec': 'Actinic keratoses', 'vasc': 'Vascular lesions', 'df': 'Dermatofibroma' } tile_df = pd.read_csv(os.path.join(base_skin_dir, 'HAM10000_metadata.csv')) tile_df['path'] = tile_df['image_id'].map(imageid_path_dict.get) tile_df['cell_type'] = tile_df['dx'].map(lesion_type_dict.get) tile_df['cell_type_idx'] = pd.Categorical(tile_df['cell_type']).codes tile_df[['cell_type_idx', 'cell_type']].sort_values('cell_type_idx').drop_duplicates() train_df, test_df = train_test_split(tile_df, test_size=0.1) validation_df, test_df = train_test_split(test_df, test_size=0.5) train_df = train_df.reset_index() validation_df = validation_df.reset_index() test_df = test_df.reset_index() class SkinDataset(data.Dataset): def __init__(self, df, transform): self.df = df self.transform = transform def __len__(self): return len(self.df) def __getitem__(self, index): X = Image.open(self.df['path'][index]) y = torch.tensor(int(self.df['cell_type_idx'][index])) if self.transform: X = self.transform(X) return X, y<file_sep>/README.md # Skin Cancer Classification Skin Cancer MNIST: HAM10000 (https://www.kaggle.com/kmader/skin-cancer-mnist-ham10000/home) ## Model Resnet50 ## Result | Model | Prec@1 | | ------------------------------- | ------------ | | Resnet50 | 0.8922155689 | | ResNet50+Attention | 0.8942115768 | | ResNet50+Weighted Cross Entropy | 0.8882235529 | ## Train ```sh sh ./train.sh ``` ## Environment - Pytorch0.4.1 - python3.6.7 ## Note: **Data imbalance** ๅพฎ่ฝฏ้ข่ฏ• offline testใ€‚ไธป่ฆๆ˜ฏๆƒณ่งฃๅ†ณๆ•ฐๆฎไธๅ‡่กก้—ฎ้ข˜(Data Augmentation + Weighted Cross Entropy)ใ€‚<file_sep>/train.sh #!/usr/bin/env bash CUDA_VISIBLE_DEVICES=0 python train.py \ --net resnet50<file_sep>/models/resnet_attn.py import torch from torch import nn import torch.nn.functional as F from torch.nn import Parameter as P from models.resnet import resnet34, resnet50 class Self_Attn(nn.Module): """ Self attention Layer""" def __init__(self, in_dim, activation): super(Self_Attn, self).__init__() self.chanel_in = in_dim self.activation = activation self.query_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim // 8, kernel_size=1) self.key_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim // 8, kernel_size=1) self.value_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim, kernel_size=1) self.gamma = nn.Parameter(torch.zeros(1)) self.softmax = nn.Softmax(dim=-1) # def forward(self, x): """ inputs : x : input feature maps( B X C X W X H) returns : out : self attention value + input feature attention: B X N X N (N is Width*Height) """ m_batchsize, C, width, height = x.size() proj_query = self.query_conv(x).view(m_batchsize, -1, width * height).permute(0, 2, 1) # B x (N) x C proj_key = self.key_conv(x).view(m_batchsize, -1, width * height) # B x C x (*W*H) energy = torch.bmm(proj_query, proj_key) # transpose check attention = self.softmax(energy) # B x (N) x (N) proj_value = self.value_conv(x).view(m_batchsize, -1, width * height) # B x C x N out = torch.bmm(proj_value, attention.permute(0, 2, 1)) out = out.view(m_batchsize, C, width, height) out = self.gamma * out + x return out, attention # A non-local block as used in SA-GAN # Note that the implementation as described in the paper is largely incorrect; # refer to the released code for the actual implementation. class Attention(nn.Module): def __init__(self, ch, which_conv=nn.Conv2d, name='attention'): super(Attention, self).__init__() # Channel multiplier self.ch = ch self.which_conv = which_conv self.theta = self.which_conv(self.ch, self.ch // 8, kernel_size=1, padding=0, bias=False) self.phi = self.which_conv(self.ch, self.ch // 8, kernel_size=1, padding=0, bias=False) self.g = self.which_conv(self.ch, self.ch // 2, kernel_size=1, padding=0, bias=False) self.o = self.which_conv(self.ch // 2, self.ch, kernel_size=1, padding=0, bias=False) # Learnable gain parameter self.gamma = P(torch.tensor(0.), requires_grad=True) def forward(self, x, y=None): # Apply convs theta = self.theta(x) phi = F.max_pool2d(self.phi(x), [2,2]) g = F.max_pool2d(self.g(x), [2,2]) # Perform reshapes theta = theta.view(-1, self. ch // 8, x.shape[2] * x.shape[3]) phi = phi.view(-1, self. ch // 8, x.shape[2] * x.shape[3] // 4) g = g.view(-1, self. ch // 2, x.shape[2] * x.shape[3] // 4) # Matmul and softmax to get attention maps beta = F.softmax(torch.bmm(theta.transpose(1, 2), phi), -1) # Attention map times g path o = self.o(torch.bmm(g, beta.transpose(1,2)).view(-1, self.ch // 2, x.shape[2], x.shape[3])) return self.gamma * o + x class ResNet50_Attn(nn.Module): def __init__(self, pretrained=False, out_features=125): super(ResNet50_Attn, self).__init__() self.model = resnet50(pretrained=pretrained) self.avgpool = nn.AvgPool2d(7, stride=1) self.fc = nn.Linear(in_features=2048, out_features=out_features) self.attn = Attention(2048) def forward(self, x): # shape [N, C, H, W] x = self.model(x) attn_feature = self.attn(x) attn_feature = self.attn_avgpool(attn_feature) attn_feature = attn_feature.view(attn_feature.size(0), -1) x = self.fc(attn_feature) return x class ResNet50_Self_Attn(nn.Module): def __init__(self, pretrained=False, out_features=125): super(ResNet50_Self_Attn, self).__init__() self.model = resnet50(pretrained=pretrained) self.avgpool = nn.AvgPool2d(7, stride=1) self.fc = nn.Linear(in_features=2048, out_features=out_features) self.attn = Self_Attn(2048, 'relu') def forward(self, x): # shape [N, C, H, W] x = self.model(x) attn_feature, p = self.attn(x) attn_feature = self.avgpool(attn_feature) attn_feature = attn_feature.view(attn_feature.size(0), -1) x = self.fc(attn_feature) return x <file_sep>/train.py import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.distributed as dist import torch.optim as optim import torch.optim.lr_scheduler as lr_scheduler import torch.utils.data import torch.utils.data.distributed from torchvision import datasets, transforms import torchvision.models as models from models.resnet_attn import ResNet50_Attn, ResNet50_Self_Attn from dataset_input import SkinDataset, train_df, validation_df, test_df import os import shutil import numpy as np import tqdm import argparse parser = argparse.ArgumentParser(description='PyTorch Sketch Me That Shoe Example') parser.add_argument('--net', type=str, default='resnet50', help='The model to be used (vgg16, resnet34, resnet50, resnet101, resnet152)') parser.add_argument('--batch-size', type=int, default=64, metavar='N', help='input batch size for training (default: 64)') parser.add_argument('--test-batch-size', type=int, default=20, metavar='N', help='input batch size for testing (default: 10)') parser.add_argument('--epochs', type=int, default=2000, metavar='N', help='number of epochs to train (default: 10)') parser.add_argument('--epoch_count', type=int, default=1, help='the starting epoch count, we save the model by <epoch_count>,<save_latest_freq>+<epoch_count>...') parser.add_argument('--niter', type=int, default=50, help='# of iter at starting learning rate') parser.add_argument('--niter_decay', type=int, default=50, help='# of iter to linearly decay learning rate to zero') parser.add_argument('--weight_decay', type=float, default=0.0005, help='Adm weight decay') parser.add_argument('--lr', type=float, default=1e-5, metavar='LR', help='learning rate (default: 0.01)') parser.add_argument('--lr_policy', type=str, default='lambda', help='learning rate policy: lambda|step|plateau') parser.add_argument('--no-cuda', action='store_true', default=False, help='enables CUDA training') parser.add_argument('--seed', type=int, default=1, metavar='S', help='random seed (default: 1)') parser.add_argument('--log-interval', type=int, default=20, metavar='N', help='how many batches to wait before logging training status') parser.add_argument('--print-freq', '-p', default=100, type=int, metavar='N', help='print frequency (default: 10)') parser.add_argument('--classes', type=int, default=419, help='number of classes') parser.add_argument('--resume', default='', type=str, help='path to latest checkpoint (default: none)') parser.add_argument('--name', default='NetModel', type=str, help='name of experiment') parser.add_argument('--normalize_feature', default=False, type=bool, help='normalize_feature') best_acc = 0 def get_scheduler(optimizer, opt): if opt.lr_policy == 'lambda': def lambda_rule(epoch): lr_l = 1.0 - max(0, epoch + 1 + opt.epoch_count - opt.niter) / float(opt.niter_decay + 1) return lr_l scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule) elif opt.lr_policy == 'step': scheduler = lr_scheduler.StepLR(optimizer, step_size=opt.lr_decay_iters, gamma=0.1) elif opt.lr_policy == 'plateau': scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.2, threshold=0.01, patience=5) else: return NotImplementedError('learning rate policy [%s] is not implemented', opt.lr_policy) return scheduler def train(train_loader, model, id_criterion, optimizer, epoch): model.train() for data_sample, y in train_loader: data_gpu = data_sample.cuda() y_gpu = y.cuda() output = model(data_gpu) err = id_criterion(output, y_gpu) err.backward() optimizer.step() def test(train_loader,validation_set, model, id_criterion, epoch): model.eval() result_array = [] gt_array = [] for i in train_loader: data_sample, y = validation_set.__getitem__(i) data_gpu = data_sample.unsqueeze(0).cuda() output = model(data_gpu) result = torch.argmax(output) result_array.append(result.item()) gt_array.append(y.item()) correct_results = np.array(result_array) == np.array(gt_array) sum_correct = np.sum(correct_results) accuracy = sum_correct / train_loader.__len__() print('Epoch: {:d} Prec@1: {:.10f}'.format(epoch, accuracy)) return accuracy def main(): global args, best_acc args = parser.parse_args() opt = args args.cuda = not args.no_cuda and torch.cuda.is_available() torch.manual_seed(args.seed) if args.cuda: torch.cuda.manual_seed(args.seed) kwargs = {'num_workers': 10, 'pin_memory': True} if args.cuda else {} ###### DataSet ###### composed = transforms.Compose([transforms.RandomHorizontalFlip(), transforms.RandomVerticalFlip(), transforms.CenterCrop(256), transforms.RandomCrop(224), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])]) training_set = SkinDataset(train_df, transform=composed) training_generator = torch.utils.data.DataLoader(training_set, batch_size=args.batch_size, shuffle=True, **kwargs) validation_set = SkinDataset(validation_df, transform=composed) validation_generator = torch.utils.data.DataLoader(validation_set, batch_size=args.batch_size, shuffle=True, **kwargs) test_set = SkinDataset(validation_df, transform=composed) test_generator = torch.utils.data.SequentialSampler(test_set) ###### Model ###### if opt.net == 'resnet50': model = models.resnet50(pretrained=True) model.fc = nn.Linear(in_features=2048, out_features=7) elif opt.net == 'resnet50_self_attn': model = ResNet50_Self_Attn(pretrained=True, out_features=7) elif opt.net == 'resnet50_attn': model = ResNet50_Attn(pretrained=True, out_features=7) if args.cuda: model.cuda() cudnn.benchmark = True ###### Criteria ###### weights = [0.8, 1.0, 1.0, 1.0, 1.0, 1.0, 1.2] class_weights = torch.FloatTensor(weights).cuda() id_criterion = nn.CrossEntropyLoss(weight=class_weights) schedulers = [] optimizers = [] optimizer = optim.Adam(model.parameters(), lr=args.lr, betas=(0.9, 0.99), weight_decay=args.weight_decay) optimizers.append(optimizer) for optimizer in optimizers: schedulers.append(get_scheduler(optimizer, args)) n_parameters = sum([p.data.nelement() for p in model.parameters()]) print(' + Number of params: {}'.format(n_parameters)) for epoch in tqdm.tqdm(range(opt.epoch_count, opt.niter + opt.niter_decay + 1)): update_learning_rate(schedulers) # scheduler.step() # train for one epoch train(training_generator, model, id_criterion, optimizer, epoch) # evaluate on validation set if epoch % 5 == 0: prec1 = test(test_generator, validation_set, model, id_criterion, epoch) # remember best Accuracy and save checkpoint is_best = prec1 > best_acc best_acc = max(prec1, best_acc) save_checkpoint({ 'epoch': epoch + 1, 'state_dict': model.state_dict(), 'best_prec': best_acc, }, is_best) def adjust_learning_rate(optimizer, epoch): """Sets the learning rate to the initial LR decayed by 10 every 30 epochs""" lr = args.lr * (0.1**(epoch // 100)) for param_group in optimizer.state_dict()['param_groups']: param_group['lr'] = lr def update_learning_rate(schedulers): for scheduler in schedulers: scheduler.step() def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'): """Saves checkpoint to disk""" directory = "runs/%s/" % (args.name) if not os.path.exists(directory): os.makedirs(directory) filename = directory + filename torch.save(state, filename) if is_best: shutil.copyfile(filename, 'runs/%s/' % (args.name) + 'model_best.pth.tar') if __name__ == '__main__': main()
85bea78468e998c9f4d99bfe26c1aa44ff555619
[ "Markdown", "Python", "Shell" ]
5
Python
maan10/SkinCancerClassification
4a7b2eb92ae0155a44fbb7a11c7ad198d8329bfd
65e4ae4ea18ff8d178f383b7896230012ad229eb
refs/heads/master
<file_sep># ipnotifier send dynamic ip address by email <file_sep>import os import configparser class ConfigTestSupport(object): def setUp(self): super().setUp() print('setUp TestSupport') # Check if there is already a configurtion file config_filename = 'test_setting.ini' if not os.path.isfile(config_filename): # Create the configuration file as it doesn't exist yet cfgfile = open(config_filename, 'w') # Add content to the file Config = configparser.ConfigParser() Config.add_section('Session1') Config.set('Session1', 'username', 'abc') Config.set('Session1', 'password', '<PASSWORD>') Config.write(cfgfile) cfgfile.close() def tearDown(self): print('tearDown TestSupport') super().tearDown() <file_sep>[Skype] username = abc password = abc [Gmail] host = smtp.gmail.com port = 465 gmail_user = <EMAIL> gmail_password = <PASSWORD> [ip] public_ip = x.x.x.x <file_sep>[Session1] username = uname1 password = <PASSWORD> [Session2] username2 = uname2 <file_sep>import unittest import config_helper from test import test_support class ConfigHelperReadTestCase(test_support.ConfigTestSupport ,unittest.TestCase): def test_ReadSetting(self): username = config_helper.read_setting('Session1', 'username', 'test_setting.ini') self.assertEqual('abc', username) password = config_helper.read_setting('Session1', 'password', 'test_setting.ini') self.assertEqual('abcpwd', password) def test_ReadSetting_notFoundKey(self): username = config_helper.read_setting('Session1', 'notfound', 'test_setting.ini') self.assertIsNone(username) def test_ReadSetting_FileNotFound(self): username = config_helper.read_setting('Session1', 'username', 'not_found.ini') self.assertIsNone(username) <EMAIL> class ConfigHelperWriteTestCase(unittest.TestCase): def test_WriteSetting(self): config_helper.write_setting('Session1', 'username', 'uname1', 'test_setting.ini') username = config_helper.read_setting('Session1', 'username', 'test_setting.ini') self.assertEqual('uname1', username) def test_WriteSetting(self): config_helper.write_setting('Session2', 'username2', 'uname2', 'test_setting.ini') username = config_helper.read_setting('Session2', 'username2', 'test_setting.ini') self.assertEqual('uname2', username) if __name__ == '__main__': unittest.main() <file_sep>import configparser import logging import os import logging logging.basicConfig(filename='ipnotifier.log',level=logging.DEBUG) def read_setting(session, key, config_file='setting.ini'): config = configparser.ConfigParser() cwd = os.getcwd() config.read(cwd + "/" + config_file) try: return config[session][key] except KeyError: logging.error("Could not find the key: " + key + " in file " + config_file) return None def write_setting(session, key, value, config_file='setting.ini'): try: cwd = os.getcwd() config = configparser.ConfigParser() config.read(cwd + "/" + config_file) if not config.has_section(session): config.add_section(session) if not config.has_option(session, key) : config.set(session, key, value) config[session][key] = value with open(cwd + "/" + config_file, 'w') as f: config.write(f) except Exception as e: logging.error("Exception occured: {0}".format(e))<file_sep>import smtplib from email.mime.text import MIMEText from config_helper import read_setting import logging logging.basicConfig(filename='ipnotifier.log',level=logging.DEBUG) def send_email(subject, message): try: gmail_user = read_setting('Gmail', 'gmail_user') gmail_password = read_setting('Gmail', 'gmail_password') with smtplib.SMTP_SSL(host=read_setting('Gmail', 'host'), port=int(read_setting('Gmail', 'port'))) as server: server.ehlo() server.login(gmail_user, gmail_password) body = message from_address = gmail_user to_address = gmail_user email_text = create_email_text(body, gmail_user, gmail_user, subject) server.sendmail(from_addr=from_address, to_addrs=to_address, msg=email_text.as_string()) server.close() print('Email is sent!') except Exception as e: logging.error('Something went wrong...' + str(e)) def create_email_text(body, from_address, to_address, subject): email_text = MIMEText(body) email_text['Subject'] = subject email_text['From'] = from_address email_text['To'] = to_address return email_text <file_sep>from requests import get from send_email import send_email from config_helper import read_setting, write_setting import logging logging.basicConfig(filename='ipnotifier.log',level=logging.DEBUG) ip = get('https://api.ipify.org').text last_public_ip = read_setting('ip', 'public_ip') # get public ip if last_public_ip != ip: send_email('IPApp message', 'Hello Linh: this is your number today: ' + ip) write_setting('ip', 'public_ip', ip) else: logging.info('No email is sent') print('No email is sent')
701b67aaf9c5553bd859d1752e440f2dc68d7435
[ "Markdown", "Python", "INI" ]
8
Markdown
linhhoang/ipnotifier
02f555c7420da6a22951caeb342a57bd015c610b
053b772fae71f45a448866a34b34449426b24a15
refs/heads/master
<file_sep>(function($) { $.fn.agro = function(options) { if (this.length > 1) { this.each(function() { $(this).agro(options); }); return this; } var self = this, o = $.extend({}, $.fn.agro.defaults, options), a = {}, $sourceRows = this.find('tbody > tr'), $sourceCells = this.find('tbody > tr > td'), $a, $caption, $hidden, $thead, $theadRow, $tbody, $categories, $metrics, $categoryNames, metricCells, $filledCells, categories = [], metrics = [], renderCatCell, cellClasses = [], hidden = [], i, um = {}, r, rs, ui = {}, items = [], aggregators = { 'prob-or': function(values, unit) { var v, s = 1, m = (unit == 'percent') ? 0.01 : 1.0; for(v = 0; v < values.length; v += 1) { s *= (1 - values[v] * m); } return Number.parseFloat((1 - s) / m).toFixed(2); }, 'sum': function(values) { return values.reduce(function(sum, n) { return sum + n; }); } }, getTermCellCallback = function(category) { var uc = {}; return function(i) { var $term = $(this), termKey = $term.text().trim(), term = $term.html(), cellClass; if (!uc.hasOwnProperty(termKey)) { uc[termKey] = category.terms.length; category.terms.push(term); } cellClass = category.id + '-' + uc[termKey]; if (cellClasses.length < i + 1) { cellClasses.push([]); } cellClasses[i].push(cellClass); $term.addClass(cellClass); }; }, metricCellCallback = function(i) { var $metric = $(this), aggregate = $metric.data('aggregate'), unit = $metric.data('unit') || false, metricKey = $metric.text().trim(), metric = $metric.html(), cellClass; if (!um.hasOwnProperty(metricKey)) { um[metricKey] = metrics.length; if (aggregate === undefined || !aggregators.hasOwnProperty(aggregate)) { aggregate = 'sum'; } metrics.push({ name: metric, unit: unit, aggregate: aggregate }); } cellClass = 'm' + um[metricKey]; cellClasses[i].push(cellClass); $metric.addClass(cellClass); }; if (o.source === 'flat' || this.hasClass('agro-flat')) { // Flat source // Get categories, terms, and metrics from thead $categories = this.find('thead > tr:not(:last-child)'); $categories.each(function() { var $row = $(this), $name = $row.find('th:first-child'), $terms = $row.find('th + th'), category = { id: String.fromCharCode(categories.length + 97), name: $name.html(), terms: [] }, termCellCallback = getTermCellCallback(category); $terms.each(termCellCallback); categories.push(category); }); $metrics = this.find('thead > tr:last-child > th + th'); $metrics.each(metricCellCallback); // Apply category and metric classes to each column for (i = 0; i < cellClasses.length; i += 1) { $sourceCells.filter(':parent:nth-child(' + (i + 2) + ')').attr('class', cellClasses[i].join(' ')); } } else { // Stacked source // Get categories and metrics from thead, get terms from tbody $categoryNames = this.find('thead th.category'); $categoryNames.each(function() { var $name = $(this), index = $name.index() + 1, $terms = $sourceCells.filter(':nth-child(' + index + ')'), category = { id: String.fromCharCode(categories.length + 97), name: $name.html(), terms: [] }, termCellCallback = getTermCellCallback(category); $terms.each(termCellCallback); categories.push(category); }); // Apply category classes to each row metricCells = 'td:nth-child(' + ($categoryNames.length + 1) + ') ~ td:parent'; $sourceRows.each(function(r) { $(this).find(metricCells).attr('class', cellClasses[r].join(' ')); }); $metrics = this.find('thead th + th:not(.category)'); $metrics.each(metricCellCallback); // Apply metric classes to each column $metrics.each(function() { var $metric = $(this); $sourceCells.filter(':parent:nth-child(' + ($metric.index() + 1) + ')').addClass($metric.attr('class')); }); } $sourceRows.each(function() { var $sourceRow = $(this), $rowCells = $sourceRow.find('td'), $itemCell = $rowCells.eq(0), itemKey = $itemCell.text().trim(), itemHtml = $itemCell.html(); if (!ui.hasOwnProperty(itemKey)) { ui[itemKey] = items.length; items.push(itemHtml); } $rowCells.filter('[class]').addClass('i' + ui[itemKey]); }); if (o.display === undefined) { o.display = []; for(i = 0; i < categories.length; i += 1) { o.display.push({i:i,v:true}); } } if (o.aggregators !== undefined) { $.extend(aggregators, o.aggregators); } /* Render a cell in the agro table. Recursively renders subsequent branch cells in the tree. $row Row to append cell to, if cells in this column are visible classChain Array of classes corresponing to all categories subsequent data must belong to categoryChain Array of category names for displaying subcategories in merged/rolled up columns isPreviousColVisible Boolean, determines if previous column(s) merge/rollup into the current column colIndex The index of the current column, which may or may not be visible */ renderCatCell = function($row, classChain, categoryChain, isPreviousColVisible, colIndex) { var category, termId, $cell, $currentRow = $row, cellClass, cellCategories, cellSubcategories, cellSubcategoriesHtml, termDescendantCount, metricFilter, metricValueCount, metricValue, descendantCount = 0, aggregateValues, metric, $nextRow, categoryIndex, m, $metricCells, aggregateValue, summary, isNumber, d, isColVisible; if (colIndex < o.display.length) { // Render cell in category column categoryIndex = o.display[colIndex].i; category = categories[categoryIndex]; isColVisible = o.display[colIndex].v; if (isPreviousColVisible) { cellSubcategories = []; cellSubcategoriesHtml = ''; } else { cellSubcategories = categoryChain; cellSubcategoriesHtml = '<ul class="rollup"><li>' + categoryChain.join('</li><li>') + '</li></ul>'; } for (termId = 0; termId < category.terms.length; termId += 1) { cellClass = classChain.concat(category.id + '-' + termId); cellCategories = cellSubcategories.concat('<h4 data-col="' + colIndex + '">' + category.name + '</h4>' + category.terms[termId]); if (isColVisible) { $cell = $('<td></td>').appendTo($currentRow); } termDescendantCount = renderCatCell($currentRow, cellClass, cellCategories, isColVisible, colIndex + 1); descendantCount += termDescendantCount; if (isColVisible) { if (termDescendantCount > 0) { $cell.attr('rowspan', termDescendantCount) .data('col', colIndex) .attr('data-descendants', termDescendantCount) // debug .addClass(cellClass.join(' ')) .html(category.terms[termId] + cellSubcategoriesHtml); } else { $cell.remove(); } } if (termId < category.terms.length - 1 && termDescendantCount > 0) { $nextRow = $('<tr></tr>'); $tbody.append($nextRow); $currentRow = $nextRow; } } return descendantCount; } else { // After all category cells have been rendered, // display data cells. Aggregate if necessary. metricFilter = '.' + classChain.join('.'); metricValueCount = $sourceCells.filter(metricFilter).length; if (metricValueCount > 0) { for (m = 0; m < metrics.length; m += 1) { metric = metrics[m]; $metricCells = $sourceCells.filter('.m' + m + metricFilter); if ($metricCells.length > 1) { aggregateValues = []; summary = []; isNumber = true; $metricCells.each(function() { var cellValue = $(this).html() || '', value = parseFloat(cellValue); if (!Number.isNaN(value)) { aggregateValues.push(value); } else { isNumber = false; } summary.push(cellValue); }); if (isNumber) { metricValue = aggregators[metric.aggregate](aggregateValues, metric.unit); } else { metricValue = summary.join('<br>'); } } else { metricValue = $metricCells.html() || ''; } $currentRow.append('<td class="m' + m + '">' + metricValue + '</td>'); } return 1; } else { return 0; } } }; // Render the agro table structure $hidden = $('<select class="inactive"></select>').append('<option disabled="disabled">Show hidden columns&hellip;</option>'); $caption = $('<caption></caption>').append($hidden); $theadRow = $('<tr></tr>'); $thead = $('<thead></thead>'); $tbody = $('<tbody></tbody>'); $a = $('<table class="agro"></table>').append($caption).append($thead); this.after($a); // Show hidden columns $hidden.on('change', function() { var parts = this.value.split('|'), insertIndex = parseInt((parts[1] * (o.display.length + 1)) / parts[2], 10); o.display.splice(insertIndex, 0, {i:parseInt(parts[0], 10),v:true}); a.render(); $hidden.find(':selected').remove(); $hidden.children().first().prop('selected', true); $hidden.toggleClass('inactive', $hidden.children().length < 2); }); // Render the agro table data a.render = function(renderOptions) { var ro = renderOptions || {}, getColWidth = function(colIndex) { var c; if (colIndex !== undefined) { c = colIndex - 1; // If dragging a rolled up header, width is always 1 if (o.display[colIndex].v === false) { return 1; } while (c >= 0 && o.display[c].v === false) { c -= 1; } return colIndex - c; } return false; }, moveColRange = function(fromIndex, toOriginalIndex) { var w, toIndex, colRange, colsBefore; if (fromIndex + 1 !== toOriginalIndex) { w = o.display[fromIndex].w; toIndex = toOriginalIndex; // If the insertion index is after the range being moved, need to shift index if (toIndex >= fromIndex + w) { toIndex -= w; } colRange = o.display.splice(fromIndex - w + 1, w); colsBefore = o.display.splice(0, toIndex); o.display = colsBefore.concat(colRange).concat(o.display); } }; o.display = ro.display || o.display; // Calculate widths for columns for (i = 0; i < o.display.length; i += 1) { o.display[i].w = getColWidth(i); } console.log(o.display); $theadRow.empty().remove(); $tbody.empty().remove(); // Render table head $theadRow.append('<th data-col="-1"><div></div></th>'); $.each(o.display, function(i, c) { var $th, $h4, $hide, $edge, q, k; if (c.v) { $th = $('<th></th>'); $h4 = $('<h4>' + categories[c.i].name + '</h4>'); $hide = $('<span>&times;</span>'); $edge = $('<div></div>'); $h4.append($hide); $th.append($h4); $th.append($edge); $th.data('col', i); $theadRow.append($th); // Hide column $hide.on('click', function() { for (q = i - c.w + 1; q < i + 1; q += 1) { k = o.display[q]; $hidden.append('<option value="' + k.i + '|' + q + '|' + o.display.length + '">' + categories[k.i].name + '</option>'); } o.display.splice(i - c.w + 1, c.w); $hidden.removeClass('inactive'); a.render(); $hidden.children().first().prop('selected', true); }); } }); $.each(metrics, function(i, metric) { $theadRow.append('<th>' + metric.name + '</th>'); }); // Render table body $.each(items, function(i, item) { var $row = $('<tr></tr>'), itemClass = 'i' + i, $itemCell = $('<td>' + item + '</td>').appendTo($row), rowDescendants; $tbody.append($row); rowDescendants = renderCatCell($row, [itemClass], [], true, 0); $itemCell.attr('rowspan', rowDescendants); $row.nextAll(':empty').remove(); }); $thead.append($theadRow); $a.append($tbody); // Header drag and drop $a.find('th > h4').draggable({ axis: 'x', revert: 'invalid', revertDuration: 100 }); $a.find('td li > h4').draggable({ revert: 'invalid', revertDuration: 100 }); $a.find('th > h4').droppable({ accept: function($d) { var dragFrom = $d.closest('th,td').data('col'), dragInto = $(this).parent().data('col'); return $d.is('h4') && (dragFrom !== dragInto); }, tolerance: 'pointer', classes: { 'ui-droppable-hover': 'drop-into-hover' }, drop: function(event, ui) { var subcatCol = ui.draggable.data('col'), dragFrom = (subcatCol === undefined) ? ui.draggable.closest('th,td').data('col') : subcatCol, dragInto = $(this).parent().data('col'); console.log('Drop ' + (dragFrom - o.display[dragFrom].w + 1) + '-' + dragFrom + ' into ' + dragInto); o.display[dragFrom].v = false; moveColRange(dragFrom, dragInto); a.render(); } }); $a.find('th > div').droppable({ accept: function($d) { // Don't accept drops onto adjacent edges var dragFrom, dragAfter; // Always allow drag to edges from rolled up columns if ($d.data('col') !== undefined) { return true; } // Is a drag from a column head dragFrom = $d.closest('th,td').data('col'); dragAfter = $(this).parent().data('col'); if (dragFrom === undefined || dragAfter === undefined) { // Accept callback is called one last time after drop occurs // When this happens, col values are undefined. Not sure why. return false; } return $d.is('h4') && (dragFrom !== dragAfter) && (dragFrom !== dragAfter + o.display[dragFrom].w); }, tolerance: 'pointer', classes: { 'ui-droppable-hover': 'drop-edge-hover' }, drop: function(event, ui) { var subcatCol = ui.draggable.data('col'), dragFrom = (subcatCol === undefined) ? ui.draggable.closest('th,td').data('col') : subcatCol, dragAfter = $(this).parent().data('col'); console.log('Drop ' + (dragFrom - o.display[dragFrom].w + 1) + '-' + dragFrom + ' after ' + dragAfter); o.display[dragFrom].v = true; // will cease to be a rollup moveColRange(dragFrom, dragAfter + 1); a.render(); } }); }; a.message = function() { window.alert(self.attr('class')); } a.render(); // Public methods can always be called via the data object // Examples: // $collection.eq(0).data('render')(); // $instance.data('render')(); $.each(a, function(k, o) { self.data(k, o); }); // In single instances, methods can also be called via the object itself // Example: // $instance.render(); $.extend(this, a); return this; }; $(function() { $('.agro-source').agro(); }); })(jQuery);
8acc134380023dbfac7ca2e829aa406b789e8181
[ "JavaScript" ]
1
JavaScript
ahcurrier/agro
3c8529979774da3edee03a214ca401ce0c411ccd
7c6e957325313a7d59062278ee515cbcf7b5c1f1
refs/heads/master
<repo_name>Jeremip11/intellij-community<file_sep>/platform/lang-impl/src/com/intellij/internal/retype/RetypeSession.kt // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal.retype import com.intellij.codeInsight.CodeInsightSettings import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementPresentation import com.intellij.codeInsight.lookup.LookupManager import com.intellij.codeInsight.lookup.impl.LookupImpl import com.intellij.codeInsight.template.TemplateManager import com.intellij.codeInsight.template.impl.LiveTemplateLookupElement import com.intellij.diagnostic.ThreadDumper import com.intellij.ide.DataManager import com.intellij.internal.performance.LatencyDistributionRecordKey import com.intellij.internal.performance.TypingLatencyReportDialog import com.intellij.internal.performance.currentLatencyRecordKey import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.actionSystem.ex.ActionManagerEx import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.LogicalPosition import com.intellij.openapi.editor.actionSystem.LatencyRecorder import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.extensions.Extensions import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Key import com.intellij.util.Alarm class RetypeSession( private val project: Project, private val editor: EditorImpl, private val delayMillis: Int, private val threadDumpDelay: Int, private val threadDumps: MutableList<String> = mutableListOf() ) : Disposable { private val document = editor.document private val alarm = Alarm(Alarm.ThreadToUse.SWING_THREAD, this) private val threadDumpAlarm = Alarm(Alarm.ThreadToUse.POOLED_THREAD, this) private val originalText = editor.document.text private val lines = editor.document.text.split('\n').map { it + "\n" } private var line = -1 private var column = 0 private var typedChars = 0 private var completedChars = 0 private var backtrackedChars = 0 private val oldSelectAutopopup = CodeInsightSettings.getInstance().SELECT_AUTOPOPUP_SUGGESTIONS_BY_CHARS private val oldAddUnambiguous = CodeInsightSettings.getInstance().ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY private var needSyncPosition = false private var editorLineBeforeAcceptingLookup = -1 var startNextCallback: (() -> Unit)? = null private val disposeLock = Any() val currentLineText get() = lines[line] fun start() { editor.putUserData(RETYPE_SESSION_KEY, this) val vFile = FileDocumentManager.getInstance().getFile(document) val keyName = "${vFile?.name ?: "Unknown file"} (${document.textLength} chars)" currentLatencyRecordKey = LatencyDistributionRecordKey(keyName) line = editor.caretModel.logicalPosition.line - 1 val currentLineStart = document.getLineStartOffset(line + 1) WriteCommandAction.runWriteCommandAction(project) { document.deleteString(currentLineStart, document.textLength) } CodeInsightSettings.getInstance().apply { SELECT_AUTOPOPUP_SUGGESTIONS_BY_CHARS = false ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY = false } queueNext() } fun stop(startNext: Boolean) { if (!ApplicationManager.getApplication().isUnitTestMode) { WriteCommandAction.runWriteCommandAction(project) { document.replaceString(0, document.textLength, originalText) } } synchronized(disposeLock) { Disposer.dispose(this) } editor.putUserData(RETYPE_SESSION_KEY, null) CodeInsightSettings.getInstance().apply { SELECT_AUTOPOPUP_SUGGESTIONS_BY_CHARS = oldSelectAutopopup ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY = oldAddUnambiguous } currentLatencyRecordKey?.details = "typed $typedChars chars, completed $completedChars chars, backtracked $backtrackedChars chars" currentLatencyRecordKey = null if (startNext) { startNextCallback?.invoke() } } override fun dispose() { } private fun queueNext() { if (!alarm.isDisposed) { alarm.addRequest({ typeNext() }, delayMillis) } } private fun typeNext() { threadDumpAlarm.addRequest({ logThreadDump() }, threadDumpDelay) if (column == 0) { if (line >= 0) { if (checkPrevLineInSync()) return } line++ syncPositionWithEditor() } else if (needSyncPosition) { val lineDelta = editor.caretModel.logicalPosition.line - editorLineBeforeAcceptingLookup if (lineDelta > 0) { if (lineDelta == 1) { checkPrevLineInSync() } line += lineDelta column = 0 } syncPositionWithEditor() } if (TemplateManager.getInstance(project).getActiveTemplate(editor) != null) { TemplateManager.getInstance(project).finishTemplate(editor) queueNextOrStop(true) return } val lookup = LookupManager.getActiveLookup(editor) as LookupImpl? if (lookup != null) { val currentLookupElement = lookup.currentItem if (currentLookupElement?.shouldAccept(lookup.lookupStart) == true) { lookup.focusDegree = LookupImpl.FocusDegree.FOCUSED editorLineBeforeAcceptingLookup = editor.caretModel.logicalPosition.line executeEditorAction(IdeActions.ACTION_CHOOSE_LOOKUP_ITEM) queueNextOrStop(true) return } } val c = currentLineText[column] typedChars++ if (c == '\n') { column = 0 // line will be incremented in next loop // Check if the next line was partially inserted with some insert handler (e.g. braces in java) if (line + 1 < document.lineCount && line + 1 < lines.size && lines[line + 1].startsWith(getEditorLineText(line + 1))) { // the caret will be moved right during the next position sync executeEditorAction(IdeActions.ACTION_EDITOR_MOVE_CARET_RIGHT) } else { executeEditorAction(IdeActions.ACTION_EDITOR_ENTER) } } else { column++ editor.type(c.toString()) } queueNextOrStop(false) } private fun queueNextOrStop(needSyncPosition: Boolean) { this.needSyncPosition = needSyncPosition if ((column == 0 && line < lines.size - 1) || (column > 0 && column < currentLineText.length)) { queueNext() } else { stop(true) if (startNextCallback == null && !ApplicationManager.getApplication().isUnitTestMode) { TypingLatencyReportDialog(project, threadDumps).show() } } } private fun LookupElement.shouldAccept(lookupStartOffset: Int): Boolean { for (retypeFileAssistant in Extensions.getExtensions( RetypeFileAssistant.EP_NAME)) { if (!retypeFileAssistant.acceptLookupElement(this)) { return false } } if (this is LiveTemplateLookupElement) { return false } val lookupString = LookupElementPresentation.renderElement(this).itemText ?: return false val lookupStartColumn = editor.offsetToLogicalPosition(lookupStartOffset).column val textAtColumn = currentLineText.drop(lookupStartColumn) if (textAtColumn.take(lookupString.length) != lookupString) { return false } return textAtColumn.length == lookupString.length || !Character.isJavaIdentifierPart(textAtColumn[lookupString.length] + 1) } private fun checkPrevLineInSync(): Boolean { val prevLine = getEditorLineText(editor.caretModel.logicalPosition.line - 1) if (prevLine.trimEnd() != currentLineText.trimEnd()) { stop(false) Messages.showErrorDialog(project, "Text has diverged. Expected:\n$currentLineText\nActual:\n$prevLine", "Retype File") return true } return false } private fun getEditorLineText(line: Int): String { val prevLineStart = document.getLineStartOffset(line) val prevLineEnd = document.getLineEndOffset(line) return document.text.substring(prevLineStart, prevLineEnd) } private fun syncPositionWithEditor(): Boolean { var result = false val editorLine = editor.caretModel.logicalPosition.line val editorLineText = getEditorLineText(editorLine) while (column < editorLineText.length && column < currentLineText.length && editorLineText[column] == currentLineText[column]) { result = true completedChars++ column++ } if (editor.caretModel.logicalPosition.column < column) { editor.caretModel.moveToLogicalPosition(LogicalPosition(line, column)) } else if (editor.caretModel.logicalPosition.column > column) { // unwanted completion, backtrack println("Text has diverged, backtracking. Editor text:\n$editorLineText\nBuffer text:\n$currentLineText") val startOffset = document.getLineStartOffset(editorLine) + column val endOffset = document.getLineEndOffset(editorLine) backtrackedChars += endOffset - startOffset WriteCommandAction.runWriteCommandAction(project) { editor.document.deleteString(startOffset, endOffset) } } return result } private fun executeEditorAction(actionId: String) { val actionManager = ActionManagerEx.getInstanceEx() val action = actionManager.getAction(actionId) val event = AnActionEvent.createFromAnAction(action, null, "", DataManager.getInstance().getDataContext( editor.component)) action.beforeActionPerformedUpdate(event) actionManager.fireBeforeActionPerformed(action, event.dataContext, event) LatencyRecorder.getInstance().recordLatencyAwareAction(editor, actionId, System.currentTimeMillis()) action.actionPerformed(event) actionManager.fireAfterActionPerformed(action, event.dataContext, event) } private fun logThreadDump() { if (editor.isProcessingTypedAction) { threadDumps.add(ThreadDumper.dumpThreadsToString()) synchronized(disposeLock) { if (!threadDumpAlarm.isDisposed) { threadDumpAlarm.addRequest({ logThreadDump() }, 100) } } } } companion object { val LOG = Logger.getInstance("#com.intellij.internal.retype.RetypeSession") } } val RETYPE_SESSION_KEY = Key.create<RetypeSession>("com.intellij.internal.retype.RetypeSession") <file_sep>/platform/platform-tests/testSrc/com/intellij/formatting/fileSet/FileSetEntryTest.java // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.formatting.fileSet; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.testFramework.PlatformTestCase; import org.jetbrains.annotations.NotNull; public class FileSetEntryTest extends PlatformTestCase { public void testSimpleFileMask() { FileSetEntry entry = new FileSetEntry("*.java"); assertTrue(entry.matches(getProject(), createFile("src/test.java"))); assertFalse(entry.matches(getProject(), createFile("src/test.txt"))); assertTrue(entry.matches(getProject(), createFile("file3.java"))); } public void testFileMaskWithDir() { FileSetEntry entry = new FileSetEntry("/src/*.java"); assertTrue(entry.matches(getProject(), createFile("src/test.java"))); assertFalse(entry.matches(getProject(), createFile("src/test.txt"))); assertFalse(entry.matches(getProject(), createFile("file3.java"))); } public void testExtendedDirSpec() { FileSetEntry entry = new FileSetEntry("/src/**/test/*.java"); assertTrue(entry.matches(getProject(), createFile("src/test/file1.java"))); assertTrue(entry.matches(getProject(), createFile("src/dir1/test/file1.java"))); assertTrue(entry.matches(getProject(), createFile("src/dir1/dir2/test/file1.java"))); assertFalse(entry.matches(getProject(), createFile("src/dir1/dir2/test/dir3/file1.java"))); FileSetEntry entry2 = new FileSetEntry("/src/**/test/**/*.java"); assertTrue(entry2.matches(getProject(), createFile("src/test/a/file1.java"))); assertTrue(entry2.matches(getProject(), createFile("src/b/test/a/file1.java"))); } public void testAnyCharMarks() { FileSetEntry entry = new FileSetEntry("/test-??/**/test?.java"); assertFalse(entry.matches(getProject(), createFile("test-1/test2.java"))); assertTrue(entry.matches(getProject(), createFile("test-12/test3.java"))); assertTrue(entry.matches(getProject(), createFile("test-12/test/testa.java"))); } public void testRelativeDirTest() { FileSetEntry entry = new FileSetEntry("test/*.java"); assertTrue(entry.matches(getProject(), createFile("src/test/file1.java"))); assertTrue(entry.matches(getProject(), createFile("test/file2.java"))); assertTrue(entry.matches(getProject(), createFile("a/b/c/d/test/file3.java"))); } private VirtualFile createFile(@NotNull String path) { String[] dirNames = path.split("/"); VirtualFile baseDir = getProject().getBaseDir(); for (int i = 0; i < dirNames.length - 1; i ++) { VirtualFile existing = VfsUtilCore.findRelativeFile(dirNames[i], baseDir); if (existing == null) { baseDir = createChildDirectory(baseDir, dirNames[i]); } else { baseDir = existing; } } return createChildData(baseDir, dirNames[dirNames.length - 1]); } } <file_sep>/plugins/git4idea/src/git4idea/util/GitLocalCommitCompareInfo.java // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.util; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.changes.Change; import com.intellij.util.containers.hash.HashMap; import git4idea.branch.GitBranchWorker; import git4idea.repo.GitRepository; import org.jetbrains.annotations.NotNull; import java.util.Collection; import java.util.Map; public class GitLocalCommitCompareInfo extends GitCommitCompareInfo { @NotNull private final String myBranchName; public GitLocalCommitCompareInfo(@NotNull String branchName) { myBranchName = branchName; } public void reloadTotalDiff() throws VcsException { Map<GitRepository, Collection<Change>> newDiff = new HashMap<>(); for (GitRepository repository: getRepositories()) { newDiff.put(repository, GitBranchWorker.loadTotalDiff(repository, myBranchName)); } updateTotalDiff(newDiff); } } <file_sep>/plugins/git4idea/src/git4idea/ui/branch/GitCompareBranchesDiffPanel.java /* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package git4idea.ui.branch; import com.intellij.history.LocalHistory; import com.intellij.history.LocalHistoryAction; import com.intellij.icons.AllIcons; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.changes.Change; import com.intellij.openapi.vcs.changes.ChangesUtil; import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager; import com.intellij.openapi.vcs.changes.ui.SimpleChangesBrowser; import com.intellij.openapi.vcs.ui.ReplaceFileConfirmationDialog; import com.intellij.openapi.vcs.update.RefreshVFsSynchronously; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.HyperlinkAdapter; import com.intellij.ui.HyperlinkLabel; import com.intellij.ui.components.JBLabel; import com.intellij.ui.components.panels.HorizontalLayout; import com.intellij.util.ObjectUtils; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.MultiMap; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import com.intellij.vcsUtil.VcsFileUtil; import git4idea.commands.Git; import git4idea.commands.GitCommand; import git4idea.commands.GitCommandResult; import git4idea.commands.GitLineHandler; import git4idea.config.GitVcsSettings; import git4idea.repo.GitRepository; import git4idea.repo.GitRepositoryManager; import git4idea.util.GitCommitCompareInfo; import git4idea.util.GitFileUtils; import git4idea.util.GitLocalCommitCompareInfo; import org.jetbrains.annotations.NotNull; import javax.swing.*; import javax.swing.event.HyperlinkEvent; import java.awt.*; import java.util.Collection; import java.util.List; import java.util.Map; import static java.util.Collections.emptyList; /** * @author <NAME> */ class GitCompareBranchesDiffPanel extends JPanel { private static final Logger LOG = Logger.getInstance(GitCompareBranchesDiffPanel.class); private final String myBranchName; private final Project myProject; private final String myCurrentBranchName; private final GitCommitCompareInfo myCompareInfo; private final GitVcsSettings myVcsSettings; private final JBLabel myLabel; private final MyChangesBrowser myChangesBrowser; public GitCompareBranchesDiffPanel(Project project, String branchName, String currentBranchName, GitCommitCompareInfo compareInfo) { myProject = project; myCurrentBranchName = currentBranchName; myCompareInfo = compareInfo; myBranchName = branchName; myVcsSettings = GitVcsSettings.getInstance(project); myLabel = new JBLabel(); myChangesBrowser = new MyChangesBrowser(project, emptyList()); HyperlinkLabel swapSidesLabel = new HyperlinkLabel("Swap branches"); swapSidesLabel.addHyperlinkListener(new HyperlinkAdapter() { @Override protected void hyperlinkActivated(HyperlinkEvent e) { boolean swapSides = myVcsSettings.shouldSwapSidesInCompareBranches(); myVcsSettings.setSwapSidesInCompareBranches(!swapSides); refreshView(); } }); JPanel topPanel = new JPanel(new HorizontalLayout(JBUI.scale(10))); topPanel.add(myLabel); topPanel.add(swapSidesLabel); setLayout(new BorderLayout(UIUtil.DEFAULT_VGAP, UIUtil.DEFAULT_HGAP)); add(topPanel, BorderLayout.NORTH); add(myChangesBrowser); refreshView(); } private void refreshView() { boolean swapSides = myVcsSettings.shouldSwapSidesInCompareBranches(); String currentBranchText = String.format("current working tree on <b><code>%s</code></b>", myCurrentBranchName); String otherBranchText = String.format("files in <b><code>%s</code></b>", myBranchName); myLabel.setText(String.format("<html>Difference between %s and %s:</html>", swapSides ? otherBranchText : currentBranchText, swapSides ? currentBranchText : otherBranchText)); List<Change> diff = myCompareInfo.getTotalDiff(); if (swapSides) diff = swapRevisions(diff); myChangesBrowser.setChangesToDisplay(diff); } @NotNull private static List<Change> swapRevisions(@NotNull List<Change> changes) { return ContainerUtil.map(changes, change -> new Change(change.getAfterRevision(), change.getBeforeRevision())); } private class MyChangesBrowser extends SimpleChangesBrowser { public MyChangesBrowser(@NotNull Project project, @NotNull List<Change> changes) { super(project, false, true); setChangesToDisplay(changes); } @Override public void setChangesToDisplay(@NotNull Collection<? extends Change> changes) { List<Change> oldSelection = getSelectedChanges(); super.setChangesToDisplay(changes); myViewer.setSelectedChanges(swapRevisions(oldSelection)); } @NotNull @Override protected List<AnAction> createToolbarActions() { return ContainerUtil.append( super.createToolbarActions(), new MyCopyChangesAction() ); } @NotNull @Override protected List<AnAction> createPopupMenuActions() { return ContainerUtil.append( super.createPopupMenuActions(), new MyCopyChangesAction() ); } } private class MyCopyChangesAction extends DumbAwareAction { public MyCopyChangesAction() { super("Get from Branch", "Replace file content with its version from branch " + myBranchName, AllIcons.Actions.Download); copyShortcutFrom(ActionManager.getInstance().getAction("Vcs.GetVersion")); } @Override public void update(AnActionEvent e) { boolean isEnabled = !myChangesBrowser.getSelectedChanges().isEmpty(); boolean isVisible = myCompareInfo instanceof GitLocalCommitCompareInfo; e.getPresentation().setEnabled(isEnabled && isVisible); e.getPresentation().setVisible(isVisible); } @Override public void actionPerformed(AnActionEvent e) { String title = String.format("Get from Branch '%s'", myBranchName); List<Change> changes = myChangesBrowser.getSelectedChanges(); boolean swapSides = myVcsSettings.shouldSwapSidesInCompareBranches(); ReplaceFileConfirmationDialog confirmationDialog = new ReplaceFileConfirmationDialog(myProject, title); if (!confirmationDialog.confirmFor(ChangesUtil.getFilesFromChanges(changes))) return; FileDocumentManager.getInstance().saveAllDocuments(); LocalHistoryAction action = LocalHistory.getInstance().startAction(title); new Task.Modal(myProject, "Loading Content from Branch", false) { @Override public void run(@NotNull ProgressIndicator indicator) { GitRepositoryManager repositoryManager = GitRepositoryManager.getInstance(myProject); MultiMap<GitRepository, FilePath> toCheckout = MultiMap.createSet(); MultiMap<GitRepository, FilePath> toDelete = MultiMap.createSet(); for (Change change : changes) { FilePath currentPath = swapSides ? ChangesUtil.getAfterPath(change) : ChangesUtil.getBeforePath(change); FilePath branchPath = !swapSides ? ChangesUtil.getAfterPath(change) : ChangesUtil.getBeforePath(change); assert currentPath != null || branchPath != null; GitRepository repository = repositoryManager.getRepositoryForFile(ObjectUtils.chooseNotNull(currentPath, branchPath)); if (currentPath != null && branchPath != null) { if (Comparing.equal(currentPath, branchPath)) { toCheckout.putValue(repository, branchPath); } else { toDelete.putValue(repository, currentPath); toCheckout.putValue(repository, branchPath); } } else if (currentPath != null) { toDelete.putValue(repository, currentPath); } else { toCheckout.putValue(repository, branchPath); } } try { for (Map.Entry<GitRepository, Collection<FilePath>> entry : toDelete.entrySet()) { GitRepository repository = entry.getKey(); Collection<FilePath> rootPaths = entry.getValue(); VirtualFile root = repository.getRoot(); GitFileUtils.delete(myProject, root, rootPaths); } for (Map.Entry<GitRepository, Collection<FilePath>> entry : toCheckout.entrySet()) { GitRepository repository = entry.getKey(); Collection<FilePath> rootPaths = entry.getValue(); VirtualFile root = repository.getRoot(); for (List<String> paths : VcsFileUtil.chunkPaths(root, rootPaths)) { GitLineHandler handler = new GitLineHandler(myProject, root, GitCommand.CHECKOUT); handler.addParameters(myBranchName); handler.endOptions(); handler.addParameters(paths); GitCommandResult result = Git.getInstance().runCommand(handler); result.getOutputOrThrow(); } GitFileUtils.addPaths(myProject, root, rootPaths); } RefreshVFsSynchronously.updateChanges(changes); VcsDirtyScopeManager.getInstance(myProject).filePathsDirty(ChangesUtil.getPaths(changes), null); ((GitLocalCommitCompareInfo)myCompareInfo).reloadTotalDiff(); } catch (VcsException err) { ApplicationManager.getApplication().invokeLater(() -> { Messages.showErrorDialog(myProject, err.getMessage(), "Can't Copy Changes"); }); } } @Override public void onFinished() { action.finish(); refreshView(); } }.queue(); } } }
0db42e4184436edf20ee1052aea5c6faa5419cca
[ "Java", "Kotlin" ]
4
Kotlin
Jeremip11/intellij-community
52bd9dbe61ec6b53b4f3e809f8a8984274af5d57
d67547b2d8163508922765237ececf464e92ac68
refs/heads/master
<file_sep>const mongoose = require("mongoose"); const Schema = mongoose.Schema; //Creating a listingSchema for our databse const listingSchema = new Schema({ gender: { type:String, required: true }, category: { type: String, required: true }, name: { type: String, required: true }, size: { type: String, required: true }, condition: { type: String, required: false }, price: { type: Number, required: false }, user: { type: Schema.Types.ObjectId, ref: 'User' }, image_url: { type: String, required: true } }); const Listing = mongoose.model("Listing", listingSchema); module.exports = Listing;<file_sep>import React, { Component } from "react"; import UserForm from "../UserForm"; import API from "./API" // You need a constructor to recieve props in a stateful component & state has to be defined in a constructor if you're receiving props class UserEdit extends Component { constructor(props) { super(props); this.state = { first_name: "", last_name: "", email: "", userId: "" } } //mounts and will call this function componentDidMount() { API.getUser(this.props.match.params.id, this.setUser.bind(this)) } setUser(user) { this.setState({ username: user.username, first_name: user.first_name, last_name: user.last_name, email: user.email, userId: user._id }, () => console.log(this.state)) } deleteUser() { API.deleteUser(this.props.match.params.id) } handleChange(event) { let fieldName = event.target.getAttribute('id'); this.setState({ [fieldName]: event.target.value }, () => console.log(this.state)); } formSubmit(event) { console.log(event) event.preventDefault(); API.userEdit(this.state, "5abf07516cf565477b27fc54") } render() { return ( <div className="row"> <div className='col s8 offset-s2 center-align'> <h4 className="form-title">Edit Account</h4> </div> <UserForm handleChange={this.handleChange.bind(this)} formSubmit={this.formSubmit.bind(this)} editForm={true} {...this.state} {...this.props} /> </div> ) } } export default UserEdit;<file_sep>const db = require("../models"); //Defining methods for our salesController module.exports = { findAll: function(req, res) { db.Sale .find(req.query) .then(dbModel => res.json(dbModel)) .catch(err => res.status(422).json(err)); }, findById: function(req, res) { db.Sale .findById(req.params.id) .populate('buyer') .populate('listing') .then(dbModel => res.json(dbModel)) .catch(err => res.status(422).json(err)); }, create: function(req, res) { db.Sale .create(req.body) .then(dbModel => { db.User.findOneAndUpdate({_id: dbModel.buyer}, {$push: {sales: dbModel._id}}) res.json(dbModel) }) .catch(err => res.status(422).json(err)); } }; <file_sep>import React, { Component } from "react"; import "./signup.css" import API from "./API.js"; import UserForm from "../UserForm"; import { Redirect } from "react-router-dom"; // You need a constructor to recieve props in a stateful component & state has to be defined in a constructor if you're receiving props class Signup extends Component { constructor(props) { super(props); this.state = { username: '', first_name: '', last_name: '', email: '', password: '', success: false } } handleChange(event) { let fieldName = event.target.getAttribute('id'); this.setState({[fieldName]: event.target.value}); } //Sends the formSubmit to createUser API formSubmit(event){ event.preventDefault(); API.createUser(this.state, this.loginSuccess.bind(this), this.createToast) } loginSuccess() { this.setState({success: true}) } createToast(message) { window.M.toast({html: message}) } //Renders the component render () { return ( <div className='row'> { this.state.success ? <Redirect to="/" /> : null } <div className='col s8 offset-s2 center-align'> <h4 className="form-title">Sign Up</h4> </div> <UserForm handleChange={this.handleChange.bind(this)} formSubmit={this.formSubmit.bind(this)} {...this.props}/> </div> ) } } export default Signup;<file_sep>import React from "react"; import "./home.css" import ProductLists from "../ProductLists" const queryString = require('query-string'); //parsing URL paramaters with query-string library const Home = (props) => { const filter = queryString.parse(props.location.search); return ( <ProductLists {...filter} searchQuery={props.searchQuery} /> ) } export default Home;<file_sep>export { default } from './CategoryBar';<file_sep>import React, { Component } from "react"; import "./login.css" import API from "./API" import { withCookies } from 'react-cookie'; //Creating a stateful Login component class Login extends Component { constructor(props) { super(props); this.state = { username: '', password: '', cookies: null } } componentWillMount() { const { cookies } = this.props; this.setState({cookies: cookies}, this.alreadyLoggedIn) } alreadyLoggedIn(){ if(this.state.cookies.get('user')) { window.location.href = '/'; } } setUserId(user) { this.state.cookies.set('user', user) window.location.pathname = '/'; } //Creating a handleChange function, that changes the state of the component handleChange(event) { let logIn = event.target.getAttribute('id'); this.setState({ [logIn]: event.target.value }); } //Creating a form sumbit function. formSubmit(event) { event.preventDefault(); API.userLogin(this.state, this.setUserId.bind(this), this.errorLogin.bind(this)) } errorLogin() { window.M.toast({html: 'Invalid user or password!'}) } render() { return ( <div className="row"> <form className="col s8 offset-s2 center-align"> <h4 className="form-title">Log In</h4> <div className="row"> <div className="input-field col s12"> <input id="username" onChange={this.handleChange.bind(this)} value={this.state.username} type="text" className="validate" /> <label htmlFor="username">Username</label> </div> </div> <div className="row"> <div className="input-field col s12"> <input id="password" onChange={this.handleChange.bind(this)} value={this.state.password} type="password" className="validate" /> <label htmlFor="password">Password</label> </div> </div> </form> <div className="col s8 offset-s2 member center-align"> Don't have an account? <span onClick={() => this.props.handleFormChange('signup')}> <a href="#" className="sign-up">Sign up here</a></span> </div> <div className="col s8 offset-s2 member right-align"> <button onClick={this.formSubmit.bind(this)} className="btn waves-effect waves-light" type="submit" name="action">Submit <i className="material-icons right">send</i> </button> </div> </div> ) } } export default withCookies(Login);<file_sep>import axios from "axios" export default { // Gets all users createListing: function (listingData, callback) { return axios.post("/api/listings", listingData) .then(callback) .catch(function (error) { console.log(error); }); } };<file_sep>import React, { Component } from "react"; import { Link } from 'react-router-dom'; import "./nav.css"; import { withCookies } from 'react-cookie'; //Creating a stateful Nav component class Nav extends Component { constructor(props) { super(props) this.state = { query: null, cookies: null } } componentWillMount() { const { cookies } = this.props; this.setState({cookies: cookies}) } //Creating a renderSearchBar function renderSearchBar() { if(window.location.pathname === '/'){ return ( <form> <div className="input-field"> <i className="material-icons prefix">search</i> {/* onChange happens when someting is changed in the input field. */} {/* e.target.value will be whatever the user has in the input field at this time*/} <input onChange={(e) => this.props.updateSearchQuery(e.target.value)} type="text" className="validate"></input> <label>SEARCH</label> </div> </form> ) } } logOut() { this.state.cookies.remove('user'); window.location.reload() } renderLoginLogout() { if(this.state.cookies.get('user') !== undefined){ return ( <ul id="nav-mobile" className="right-align"> <li className="nav-link"> <Link to="/listings/new">List an Item</Link> </li> <li className="nav-link"> <Link to={`/users/${this.state.cookies.get('user')._id}/edit`}>Account</Link> </li> <li className="nav-link"><a href="#" onClick={(e) => {e.preventDefault(); this.logOut()}}>Log Out</a></li> </ul> ) } else { return ( <ul id="nav-mobile" className="align-right"> <li className="nav-link right"><a href="/signup">Login / Sign Up</a></li> </ul> ) } } render() { return ( <div className="row valign-wrapper"> <div className="col s6 m4"> {this.renderSearchBar()} </div> <div className="col s6 m8"> {this.renderLoginLogout()} </div> </div> ) } } export default withCookies(Nav);<file_sep>const db = require("../models"); // Defining methods for the listingsController module.exports = { findAll: function(req, res) { db.Listing .find(req.query) .populate('user') .then(dbModel => res.json(dbModel)) .catch(err => res.status(422).json(err)); }, findById: function(req, res) { db.Listing .findById(req.params.id) .populate('user') .then(dbModel => res.json(dbModel)) .catch(err => res.status(422).json(err)); }, create: function(req, res) { db.Listing .create(req.body) .then((dbModel) => { db.User.findOneAndUpdate({_id: dbModel.user}, {$push: {listings: dbModel._id}}) res.json(dbModel) }) .catch(err => res.status(422).json(err)); }, update: function(req, res) { db.Listing .findOneAndUpdate({ _id: req.params.id }, req.body) .then(dbModel => res.json(dbModel)) .catch(err => res.status(422).json(err)); }, remove: function(req, res) { db.Listing .findById({ _id: req.params.id }) .then(dbModel => dbModel.remove()) .then(dbModel => res.json(dbModel)) .catch(err => res.status(422).json(err)); }, search: function(req, res) { db.Listing .find({name: new RegExp('^'+req.query.q, "i")}) .then(dbModel => res.json(dbModel)) .catch(err => res.status(422).json(err)); } }; <file_sep>const mongoose = require("mongoose"); const Schema = mongoose.Schema; //Creating a saleSchema for our database const saleSchema = new Schema({ price: { type: Number, required: true }, listing: { type: Schema.Types.ObjectId, ref: 'Listing' }, buyer: { type: Schema.Types.ObjectId, ref: 'User' } }); const Sale = mongoose.model("Sale", saleSchema); module.exports = Sale;<file_sep>import React, { Component } from 'react'; import './App.css'; import Logo from './components/Logo'; import Nav from './components/Nav'; import Home from './components/Home'; import ImageCard from './components/ImageCard'; import Jcole from './components/Jcole'; import NewListing from './components/NewListing'; import UserEdit from './components/UserEdit'; import CategoryBar from './components/CategoryBar'; import 'materialize-css/dist/css/materialize.min.css'; import 'materialize-css/dist/js/materialize.min.js'; import { BrowserRouter as Router, Route, Switch } from "react-router-dom"; //Doing a get request to the backend class App extends Component { constructor(props) { super(props) this.state = { searchQuery: null } } homeComponent(props) { // ...props is passing all of this current component's props into the Home component return <Home searchQuery={this.state.searchQuery} {...props} /> } //receives a string to update our search query state. updateSearchQuery(query) { this.setState({ searchQuery: query }); } render() { return ( <Router> <div> <main> <Logo /> <Nav updateSearchQuery={this.updateSearchQuery.bind(this)} /> <CategoryBar /> <Switch> {/* Telling which component to render. */} <Route exact path="/" render={this.homeComponent.bind(this)} /> <Route exact path="/login" component={Jcole} /> <Route exact path="/signup" component={Jcole} /> <Route exact path="/listings/new" component={NewListing} /> <Route exact path="/users/:id/edit" component={UserEdit} /> <Route exact path="/image" component={ImageCard} /> <Route path="*" render={this.homeComponent.bind(this)} /> </Switch> </main> </div> </Router> ) } } export default App; <file_sep>import React from 'react'; import './category-bar.css' //Creating CategoryBar that contains routes for category that gets chosen const CategoryBar = () => { return ( <div className="row"> <div className="col s12 category-bar"> <a href="/?filter=boy">Boys</a> <a href="/?filter=girl">Girls</a> <a href="/?filter=tops">Tops</a> <a href="/?filter=dresses">Dresses</a> <a href="/?filter=bottoms">Bottoms</a> <a href="/?filter=accessories">Accessories</a> </div> </div> ) } export default CategoryBar<file_sep>import React from "react"; import "./logo.css" //Creating Thread Count logo for main page const Logo = () => { return ( <div className="row"> <div className="col-12 center-align"> <a href='/'><h3 className="logo">Thread Count</h3></a> </div> </div> ) }; export default Logo; <file_sep>const mongoose = require("mongoose"); const Schema = mongoose.Schema; const passportLocalMongoose = require('passport-local-mongoose'); //Creating a userSchema for our database const userSchema = new Schema({ first_name: { type: String, required: true }, last_name: { type: String, required: true }, email: { type: String, unique: true, match: [/.+@.+\..+/, "Please enter a valid e-mail address"] }, listings: [{ type: Schema.Types.ObjectId, ref: 'Listing' }], sales: [{ type: Schema.Types.ObjectId, ref: 'Sale' }], }); userSchema.plugin(passportLocalMongoose); const User = mongoose.model("User", userSchema); module.exports = User;<file_sep>import React, { Component } from "react"; import ImageCard from "../ImageCard" import PaymentForm from '../PaymentForm/PaymentForm'; import { withCookies } from 'react-cookie'; import API from "./API"; import { Redirect } from 'react-router-dom'; import './productlists.css'; //Creating a stateful ProductLists component; class ProductLists extends Component { constructor(props) { super(props) this.state ={ listings: [], filter: this.props.filter, orderSuccess: false, cookies: null, redirectHome: false, } } componentDidMount() { API.getListings(this.updateListings.bind(this)); const { cookies } = this.props; this.setState({cookies: cookies}) } componentWillReceiveProps(nextProps) { if(nextProps.searchQuery != ''){ API.searchListings(this.props.searchQuery, this.updateListings.bind(this)); } else { API.getListings(this.updateListings.bind(this)); } } showSuccessMessage(){ window.M.toast({html: "Purchase Confirmed!", displayLength: 1000, completeCallback: () => {window.location.reload()}}) } setItem(data){ this.setState({price: data.price, listingId: data.listingId, userId: JSON.parse(this.state.cookies.cookies.user)._id}) } createSales() { API.createSales({ listing: this.state.listingId, price: this.state.price, buyer: this.state.userId }, this.showSuccessMessage.bind(this)) } updateListings(listings) { let allListings = listings; if (this.state.filter) { allListings = allListings.filter((listing) => { if (listing.category === this.state.filter || listing.gender === this.state.filter) { return listing; } }) } this.setState({listings: allListings}) } renderLists(){ return this.state.listings.map((listing, idx) => { return <ImageCard key={idx} id={idx} listing={listing} setItem={this.setItem.bind(this)} deleteItem={API.deleteListings} redirectHome={this.redirectHome.bind(this)} cookies={this.state.cookies}/> }) } renderModal(){ return ( <div id="modal1" className="modal bottom-sheet"> <div className="modal-content" style={{height: '25%'}}> <PaymentForm createSales={this.createSales.bind(this)}/> </div> </div> ) } redirectHome() { this.setState({redirectHome: true}) } renderEmptyElement() { return ( <div className="row"> <div className="col s12 center-align"> <h1 className="no-listings"> Sorry, no listings yet!</h1> </div> </div> ) } render() { if(this.state.listings.length == 0){ return this.renderEmptyElement(); } else { return ( <div className="row"> {this.renderLists()} {this.renderModal()} { this.state.redirectHome ? <Redirect to="/" /> : null } </div> ) } } } export default withCookies(ProductLists);<file_sep>export {default} from "./Jcole" <file_sep>const router = require("express").Router(); const salesController = require("../../controllers/salesController"); // Matches with "/api/sale" router.route("/") .get(salesController.findAll) .post(salesController.create); // Matches with "/api/sale/:id" router .route("/:id") .get(salesController.findById) module.exports = router; <file_sep>import axios from "axios" export default { // Gets all users createUser: function(userData, successCallback, errorCallback) { return axios.post("/api/users", { username: userData.username, first_name: userData.first_name, last_name: userData.last_name, password: <PASSWORD>, email: userData.email }).then(function(response){ successCallback() }).catch(function(error){ errorCallback("There was an error signing up! Please try again!") }); } }; <file_sep>export {default} from "./ProductLists" <file_sep>import React, { Component } from "react"; import API from "./API"; import ReactFilestack from 'filestack-react'; import { Redirect } from "react-router-dom"; import { withCookies } from 'react-cookie'; import './newlisting.css'; //Creating a stateful NewListing component class NewListing extends Component { constructor(props) { //setting up prop that is bassed in your component super(props) this.state = { gender: '', category: '', size: '', condition: '', price: '', name: '', image_url: '', redirect: false, user: '' } } handleChange(event) { let listingInput = event.target.getAttribute('id'); this.setState({ [listingInput]: event.target.value }, () => console.log(this.state)); } componentDidMount() { const { cookies } = this.props; this.setState({cookies: cookies}, this.checkIfLoggedIn); // jquery document on ready, initialize materialize select dropdowns window.$('document').ready(() => { window.$('select').formSelect(); }) } // check if user is logged in or not, redirect to login page checkIfLoggedIn(){ if(!this.state.cookies.get('user')) { window.location.href = '/signup'; } else { this.setState({user: this.state.cookies.get('user')._id}, () => console.log(this.state)) } } // Creating a redirectHome function to send user back home if NewListing is successful redirectHome(){ this.setState({redirect: true}); } // Creating a formSubmit function for the form formSubmit(event) { event.preventDefault(); API.createListing(this.state, this.redirectHome.bind(this)) } renderUploadButton() { if (!this.state.image_url) { return ( <div className="col s12 right-align"> <ReactFilestack apikey="<KEY>" buttonText="Upload an image" buttonClass="btn waves-effect waves-light btn-small" onSuccess={response => this.setState({ image_url: response.filesUploaded[0].url }, () => console.log(this.state))} /> </div> ) } } // Creating a requiredFields function, so the form has to be completed before user can submit requiredFields(){ // get all the keys in the state let keys = Object.keys(this.state); // intialize the variable as false let emptyFields = false; // loop through all the keys and check the value in state to see if any of them are empty strings, if empty then set variable to true keys.forEach((key) => { if(this.state[key] === ''){ emptyFields = true; } }) return emptyFields; } //Rendering a new listing form render() { return ( <div className="row"> <div className="col s12 center"> <h5 className="form-title">Create a New Listing</h5> </div> <form className="col s12" id="new-listing"> <div className="input-field col s12"> <input id="name" type="text" onChange={this.handleChange.bind(this)} value={this.state.name} /> <label htmlFor="name">Item Name</label> </div> <div className="input-field col s12"> <select id="gender" onChange={this.handleChange.bind(this)} value={this.state.gender}> <option value="" disabled selected>Gender</option> <option value="boy">Boy</option> <option value="girl">Girl</option> </select> </div> <div className="input-field col s12"> <select id="category" onChange={this.handleChange.bind(this)} value={this.state.category}> <option value="" disabled selected>Category</option> <option value="tops">Tops</option> <option value="bottoms">Bottoms</option> <option value="dresses">Dresses</option> <option value="accessories">Accessories</option> </select> </div> <div className="input-field col s12"> <select id="size" onChange={this.handleChange.bind(this)} value={this.state.condition}> <option value="" disabled selected>Size</option> <option value="new born">New Born</option> <option value="infant">Infant</option> <option value="infant">Toddler</option> </select> </div> <div className="input-field col s12"> <select id="condition" onChange={this.handleChange.bind(this)} value={this.state.condition}> <option value="" disabled selected>Condition</option> <option value="new">New</option> <option value="gently used">Gently Used</option> </select> </div> {this.renderUploadButton()} <div className="input-field col s12"> <select id="price" onChange={this.handleChange.bind(this)} value={this.state.condition}> <option value="" disabled selected>Price</option> <option value="1.00">1.00</option> <option value="2.00">2.00</option> <option value="3.00">3.00</option> <option value="4.00">4.00</option> <option value="5.00">5.00</option> </select> </div> <div className="col s12"> <button disabled={this.requiredFields()} onClick={this.formSubmit.bind(this)} className="right btn waves-effect waves-light">Create Listing <i className="material-icons right">send</i> </button> </div> </form> { this.state.redirect ? <Redirect push to="/"/> : "" } </div> ) } } export default withCookies(NewListing); <file_sep>import React, { Component } from "react"; // You need a constructor to recieve props in a stateful component & state has to be defined in a constructor if you're receiving props class UserForm extends Component { constructor(props) { super(props); this.state = { editForm: props.editForm || false } } //Lifestyle function, gets called when different props are passed into this component. and then it will call this function with new props componentWillReceiveProps(nextProps) { this.setState({ first_name: nextProps.first_name, last_name: nextProps.last_name, email: nextProps.email, username: nextProps.username //materialize library, READ THE DOCS! }, () => window.M.updateTextFields()) } renderLoginLink(){ if(!this.state.editForm) { return( <div className="col s8 offset-s2 member center-align"> Already have an account? <span onClick={() => this.props.handleFormChange('login')}> <a href="#" className="sign-up">Log in here</a></span> </div> ) } } render() { return ( <div className="row"> <form className="col s8 offset-s2" id="user-signup"> <div className="row"> <div className="input-field col s12"> <input id="username" type="text" className="validate" onChange={this.props.handleChange.bind(this)} value={this.state.username} /> <label htmlFor="username">Username</label> </div> <div className="input-field col s6"> <input id="first_name" type="text" className="validate" onChange={this.props.handleChange.bind(this)} value={this.state.first_name} /> <label htmlFor="first_name">First Name</label> </div> <div className="input-field col s6"> <input id="last_name" type="text" className="validate" onChange={this.props.handleChange.bind(this)} value={this.state.last_name} /> <label htmlFor="last_name">Last Name</label> </div> </div> <div className="row"> <div className="input-field col s12"> <input id="email" type="email" className="validate" onChange={this.props.handleChange.bind(this)} value={this.state.email} /> <label htmlFor="email">Email</label> </div> </div> <div className="row"> <div className="input-field col s12"> <input id="password" type="<PASSWORD>" className="validate" onChange={this.props.handleChange.bind(this)} /> <label htmlFor="password">Password</label> </div> </div> {this.renderLoginLink()} <div className="right-align"> <button onClick={this.props.formSubmit.bind(this)} className="btn waves-effect waves-light">Submit <i className="material-icons right">send</i> </button> </div> </form> </div> ) } } export default UserForm;
3aa55b876c6f4b3de8fe709866d0ec1a6bc18f9d
[ "JavaScript" ]
22
JavaScript
Jenny-Le/Thread-Count
6fb248747bb884426d4e1f0f9bfb3d92b39b0579
15ed46af799170fb8a315d94c74b226ed9205483
refs/heads/master
<repo_name>gnouf1/Echecs<file_sep>/Pion.java /** * *class reprรฉsentant le Pion d'un jeu d'รฉchec */ public class Pion extends Piece { /** * constructeur de la class Pion initialise la couleur du Pion *@param color couleur du pion */ public Pion(int color) { super(); this.color = color; } /** *affiche la piece "Pion" sur le plateau * */ @Override public void displayShell() { String s; s = (color == 1 ? "\u001B[38;5;10m" : "\u001B[38;5;15m"); s += "P"; System.out.print(s); } /** * Retourne true si le mouvement est possible * selon les regles de du Pion * (independamment des autre pieces) * @param fx (from x) la position d'origine en x du Pion * @param fy (from y) la position d'origine en y du Pion * @param tx (to x) la future position en x du Pion * @param ty (to y) la future position en y du Pion */ @Override public boolean isMovePossible(int fx,int fy,int tx,int ty) { if(this.color == 0) { if(fy == 1) { boolean diag = ( (tx - fx == 1) || (tx - fx == -1) ) && (ty - fy == 1); return ( (tx == fx) && (ty - fy <= 2) && (ty - fy >= 1) ) || diag; } return ( ( (tx == fx) && (ty - fy == 1) ) || ((tx - fx == 1) || (tx - fx == -1) ) && (ty - fy == 1) ); } else { if(fy == 6) { boolean diag = ((tx - fx == 1) || (tx - fx == -1) ) && (ty - fy == -1); return ( (tx == fx) && (ty - fy >= -2) && (ty - fy <= -1) ) || diag; } return ( ( (tx == fx) && (ty - fy == -1) )|| ((tx - fx == 1) || (tx - fx == -1) ) && (ty - fy == -1)); } } } <file_sep>/Ai.java import java.util.concurrent.ThreadLocalRandom; /** * Classe de l'IA */ public class Ai { private Chessboard cb; private int color; private boolean alive; /** * Constructeur */ public Ai(Chessboard cb) { this.cb = cb; this.alive = true; } /** * Constructeur */ public Ai(Chessboard cb,int color) { this.cb = cb; this.color = color; this.alive = true; } /** * Accesseur de alive * @return alive */ public boolean getAlive() { return this.alive; } /** * test si l'ia est en vie */ private void testAlive() { this.alive = false; Box[][] board = cb.getBoard(); for(int i = 0; i < 8; i++) { for(int j = 0; j < 8; j++) { if(board[j][i].getPiece() != null) { if(board[j][i].getTypePiece().equals("Roi") && board[j][i].getColor() == this.color) this.alive = true; } } } } /** * Tour de jeu de l'IA */ public void makeMove() { this.testAlive(); if(this.alive == false) return; int move[] = {-1,-1,-1,-1}; int rv; if( this.cb.areYouInEchec( this.cb.findKing(this.color), this.color) == true) { System.out.printf("%s vous etes en รฉchec, vous devriez bouger !\n",(this.color == 0 ? "Blanc" : "Vert")); } if( this.cb.areYouInEchecEtMat(this.color) == true ) { System.out.printf("%s vous etes en รฉchec et mat\n",(this.color == 0 ? "Blanc" : "Vert")); this.alive = false; return; } do{ move[0] = ThreadLocalRandom.current().nextInt(0, 7 + 1); move[1] = ThreadLocalRandom.current().nextInt(0, 7 + 1); move[2] = ThreadLocalRandom.current().nextInt(0, 7 + 1); move[3] = ThreadLocalRandom.current().nextInt(0, 7 + 1); rv = cb.mouvement(this.color,move,true); } while(rv == -1); System.out.printf("#%d%d%d%d#\n",move[0],move[1],move[2],move[3]); cb.displayShell(); this.testAlive(); } } <file_sep>/Chessboard.java import java.util.EmptyStackException; import java.lang.ArrayIndexOutOfBoundsException; import java.util.List; import java.util.ArrayList; import java.util.Stack; /** * Classe gerant la partie Jeu */ public class Chessboard { //Plateau de jeu private Box board[][]; //Pile de pieces mortes private Stack<Piece> dead; //Pile d'evenement private Stack<int[]> pileUndo; /** * Constructeur de Chessboard */ public Chessboard() { this.dead = new Stack<Piece>(); //ref sur tab 2D de Box Box[][] tmp = new Box[8][8]; //allocation / creation de chaque Box for(int i = 0; i < 8; i++) { for(int j = 0; j < 8; j++) { int c = ( (j+i) % 2 == 0 ? 1 : 0 ); tmp[i][j] = new Box(c); } } for(int i = 0; i < 8; i++) tmp[i][1].changePiece(new Pion(0)); for(int i = 0; i < 8; i++) tmp[i][6].changePiece(new Pion(1)); tmp[2][0].changePiece(new Fou(0)); tmp[5][0].changePiece(new Fou(0)); tmp[2][7].changePiece(new Fou(1)); tmp[5][7].changePiece(new Fou(1)); tmp[0][0].changePiece(new Tour(0)); tmp[7][0].changePiece(new Tour(0)); tmp[0][7].changePiece(new Tour(1)); tmp[7][7].changePiece(new Tour(1)); tmp[1][0].changePiece(new Cheval(0)); tmp[6][0].changePiece(new Cheval(0)); tmp[1][7].changePiece(new Cheval(1)); tmp[6][7].changePiece(new Cheval(1)); tmp[3][0].changePiece(new Roi(0)); tmp[4][0].changePiece(new Reine(0)); tmp[3][7].changePiece(new Roi(1)); tmp[4][7].changePiece(new Reine(1)); this.board = tmp; this.pileUndo = new Stack<>(); } /** * Accesseur de board */ public Box[][] getBoard() { return this.board; } /** * Affiche le plateau de jeu en shell */ public void displayShell() { for(int i = 7; i >= 0; i--) { System.out.printf("%d ",i+1); for(int j = 0; j < 8; j++) { board[j][i].displayShell(); } System.out.println(); } System.out.print("\n\\ abcdefgh\n\nPieces Mortes :\n"); for(Piece p : this.dead) { p.displayShell(); System.out.print("\u001B[0m"); } System.out.println(); } /** * Teste si la piece passe au dessus d'une autre dans la ligne * @param deplacement coordonees du deplacement * @return false si la piece passe au dessus d'une autre */ public boolean traceLigne(int deplacement[]) { if(deplacement[0] == deplacement[2]) { if(deplacement[1] < deplacement[3]) { for(int i = deplacement[1] + 1; i < deplacement[3]; i++) { if(board[deplacement[0]][i].getPiece() != null) return false; } return true; } else { for(int i = deplacement[3] + 1; i < deplacement[1]; i++) { if(board[deplacement[0]][i].getPiece() != null) return false; } return true; } } if(deplacement[1] == deplacement[3]) { if(deplacement[0] < deplacement[2]) { for(int i = deplacement[0] + 1; i < deplacement[2]; i++) { if(board[i][deplacement[1]].getPiece() != null) return false; } return true; } else { for(int i = deplacement[2] + 1;i < deplacement[0]; i++) { if(board[i][deplacement[1]].getPiece() != null) return false; } return true; } } return false; } /** * Teste si la piece passe au dessus d'une autre dans la diagonale * @param deplacement coordonees du deplacement * @return false si la piece passe au dessus d'une autre */ public boolean traceDiag(int deplacement[]) { //verifie si il y a une case dans la diagonale d'un point a un autre int dx = deplacement[2] - deplacement[0]; int dy = deplacement[3] - deplacement[1]; if(dx == dy) { if(dx > 0) { for(int i = 1; i < dx; i++) { if(board[deplacement[0] + i][deplacement[1] + i].getPiece() != null) return false; } return true; } else { for(int i = 1; i < -dx; i++) { if(board[deplacement[0] - i][deplacement[1] - i].getPiece() != null) return false; } return true; } } else if(dx == -dy) { if(dx > 0) { for(int i = 1; i < dx; i++) { if(board[deplacement[0] + i][deplacement[1] - i].getPiece() != null) return false; } return true; } else { for(int i = 1; i < -dx; i++) { if(board[deplacement[0] - i][deplacement[1] + i].getPiece() != null) return false; } return true; } } else return false; } /** * Test si le mouvement est possible en prenant compte les autres pieces du plateau * @param color Couleur de la piece * @param deplacement Coordonรฉes de deplacement * @param ai Booleen pour enlever les affichages * @return true si le mouvement est possible en prenant toutes les pieces en compte */ public boolean movePossible(int color, int deplacement[],boolean ai){ //errors if(this.board[deplacement[0]][deplacement[1]].getPiece() == null) { if(!ai) System.out.println("Pas de piece dans cette case"); return false; } if(this.board[deplacement[0]][deplacement[1]].getColor() != color) { if(!ai) System.out.println("Cette piece ne vous appartient pas"); return false; } if (this.board[deplacement[0]][deplacement[1]].getPiece().isMovePossible(deplacement[0], deplacement[1], deplacement[2], deplacement[3]) == false) { if(!ai) System.out.println("Mouvement incorrect pour cette piece"); return false; } //ne pas manger ses cooequipiers if(this.board[deplacement[2]][deplacement[3]].getTypePiece() != null){ if(this.board[deplacement[2]][deplacement[3]].getColor() == color) { if(!ai) System.out.println("Vous ne pouvez pas manger vos propres piรจces"); return false; } } //cas special de la tour if(this.board[deplacement[0]][deplacement[1]].getTypePiece().equals("Tour") && !traceLigne(deplacement) ) { if(!ai) System.out.println("La tour passe au dessus d'une autre piece"); return false; } //cas special du fou if(this.board[deplacement[0]][deplacement[1]].getTypePiece().equals("Fou") && !traceDiag(deplacement) ) { if(!ai) System.out.println("Le Fou passe au dessus d'une autre piece"); return false; } //cas spรฉcial du pion //a retravailler if(this.board[deplacement[0]][deplacement[1]].getTypePiece().equals("Pion")){ int dx = deplacement[2] - deplacement[0]; int dy = deplacement[3] - deplacement[1]; if ( (deplacement[0] == deplacement[2]) && board[deplacement[2]][deplacement[3]].getTypePiece() != null){ if (!ai) System.out.print("Un pion ne peut pas prendre devant lui !\n"); return false; } if( dx == dy ^ dx == -dy) { //alors mouvement en diagonale if(dy == 1 && color == 0) { if(this.board[deplacement[2]][deplacement[3]].getTypePiece() == null) return false; return true; } if(dy == -1 && color == 1) { if(this.board[deplacement[2]][deplacement[3]].getTypePiece() == null) return false; return true; } return false; } } //fin if pion //cas special de la reine if(this.board[deplacement[0]][deplacement[1]].getTypePiece().equals("Reine") ) { boolean test; //test si le mouvement est en ligne ou en diagonale if((deplacement[0] == deplacement[2]) ^ (deplacement[1] == deplacement[3])) { test = traceLigne(deplacement); } else { test = traceDiag(deplacement); } if(!test) { if(!ai) System.out.println("La Reine passe au dessus d'une autre piece"); return false; } } //fin if reine return true; } /** * Deplace la piece si le mouvement est possible * @param color Couleur de la piece * @param deplacement Coordonรฉes de deplacement * @param ai Booleen pour enlever les affichages * @return -1 si le mouvement est impossible en prenant toutes les pieces en compte * @return 0 si le mouvement s'effectue normalement */ public int mouvement(int color, int deplacement[],boolean ai){ if(this.movePossible(color,deplacement,ai) == false) return -1; //main move Piece pi = this.board[deplacement[0]][deplacement[1]].getPiece(); setUndo(deplacement); if (this.board[deplacement[2]][deplacement[3]].getPiece() == null) { this.board[deplacement[2]][deplacement[3]].changePiece(pi); this.board[deplacement[0]][deplacement[1]].changePiece(null); } else { //Si il y a une piece dans la case d'arrivรฉe //si c'est une piece adverse //on la stocke dans une liste de pieces mortes this.dead.push(this.board[deplacement[2]][deplacement[3]].getPiece()); int[] d = new int[4]; d[0] = -1; d[1] = -1; d[2] = 666; d[3] = -1; setUndo(d); this.board[deplacement[2]][deplacement[3]].changePiece(pi); this.board[deplacement[0]][deplacement[1]].changePiece(null); } return 0; } /** * Transforme les pions arrivant au bout du plateau */ public void mutation() { for(int i = 0; i < 8; i++) { try{ if(board[i][7].getTypePiece().equals("Pion")) { int c = board[i][7].getColor(); board[i][7].changePiece(new Reine(c)); } }catch (NullPointerException e){} } for(int i = 0; i < 8; i++) { try{ if(board[i][0].getTypePiece().equals("Pion")) { int c = board[i][7].getColor(); board[i][0].changePiece(new Reine(c)); } }catch (NullPointerException e){} } } /** * Empile le tour */ public void setUndo(int a[]){ this.pileUndo.push(a); } /** * Depile le tour */ public void doUndo(){ int dep[]= {-1,-1,-1,-1}; int tmp[]= {-1,-1,-1,-1}; try { dep = this.pileUndo.pop(); }catch (EmptyStackException e ){ System.out.println("Vous ne pouvez pas retourner plus loin"); return; } if(dep[0] != -1) { tmp[0] = dep[2]; tmp[1] = dep[3]; tmp[2] = dep[0]; tmp[3] = dep[1]; Piece p = this.board[tmp[0]][tmp[1]].getPiece(); //System.out.printf("-> %d%d%d%d\n", tmp[0], tmp[1], tmp[2], tmp[3]); this.board[tmp[0]][tmp[1]].changePiece(null); this.board[tmp[2]][tmp[3]].changePiece(p); } else { dep = this.pileUndo.pop(); tmp[0] = dep[2]; tmp[1] = dep[3]; tmp[2] = dep[0]; tmp[3] = dep[1]; Piece p = this.board[tmp[0]][tmp[1]].getPiece(); System.out.printf("-> %d%d%d%d\n", tmp[0], tmp[1], tmp[2], tmp[3]); this.board[tmp[0]][tmp[1]].changePiece(null); this.board[tmp[2]][tmp[3]].changePiece(p); try{ p = this.dead.pop(); } catch (EmptyStackException e ){ System.out.println("Vous ne pouvez pas retourner plus loin"); return; } this.board[tmp[0]][tmp[1]].changePiece(p); } } /** * Trouve le Roi de la couleur c * @param c couleur du roi a trouver * @return les coordonnรฉes du roi de couleur c */ public int[] findKing(int c){ //Trouve le roi Piece king; int[] tmp = new int[2]; int i = 0, j = 0, flag = 0; for (i = 0; i < 8 && flag == 0; i = i+1){ for (j = 0; j < 8 && flag == 0; j = j + 1){ if (this.board[i][j].getTypePiece() == "Roi" && this.board[i][j].getColor() == c) { king = this.board[i][j].getPiece(); flag = 1; tmp[0] = i; tmp[1] = j; } } } return tmp; } /** * Detecte l'echec * @param roi Coordonnรฉes du roi * @param c Couleur du roi * @return true si echec */ public boolean areYouInEchec(int[] roi,int c){ int[] tmp = new int[4]; tmp[2] = roi[0]; tmp[3] = roi[1]; for (int h = 0; h<8; ++h){ for (int g = 0; g<8; ++g){ if (this.board[g][h].getPiece() != null && this.board[g][h].getColor() != c){ tmp[0] = g; tmp[1] = h; if (this.movePossible(1 - c, tmp, true) == true){ return true; } } } } return false; } private boolean areYouInMat(int c) { int[] k = this.findKing(c); int Somme = 0; for(int i = -1; i < 2; i++) { for(int j = -1; j < 2; j++) { int x = k[0] + j; int y = k[1] + i; if( ((x < 0)||(x > 7)||(y < 0)||(y > 7)) == false ) { //si dans le board if(this.board[x][y].getPiece() == null) { int[] tmpKing = new int[2]; tmpKing[0] = x; tmpKing[1] = y; if(areYouInEchec(tmpKing,c) == true) { Somme++; } } else { Somme++; } } else { Somme++; } } } if(Somme == 9) return true && this.areYouInEchec(k,c); return false; } /** * Detecte l'echec et mat * @param c Couleur du roi * @return true si echec et mat */ public boolean areYouInEchecEtMat(int c) { if(areYouInMat(c) == false) return false; for(int i = 0; i < 8; i++) { for(int j = 0; j < 8; j++) { if(this.board[j][i].getPiece() != null) { for(int k = 0; k < 8; k++) { for(int l = 0; l < 8; l++) { int[] dep = new int[4]; dep[0] = j; dep[1] = i; dep[2] = l; dep[3] = k; if(this.movePossible(c,dep,true) == true) { this.mouvement(c,dep,true); if(areYouInMat(c) == false) { this.doUndo(); return false; } else { this.doUndo(); } }//fin if } } }//fin if } } //Fin Pour return true; } } <file_sep>/Reine.java /** * *class reprรฉsentant la Reine d'un jeu d'รฉchec */ public class Reine extends Piece { /** * constructeur de la class Reine initialise la couleur de la Reine *@param color couleur de la Reine */ public Reine(int color) { super(); this.color = color; } /** *affiche la piece Reine sur le plateau * */ @Override public void displayShell() { String s; s = (color == 1 ? "\u001B[38;5;10m" : "\u001B[38;5;15m"); s += "Q"; System.out.print(s); } /** * Retourne true si le mouvement est possible * selon les regles de la Reine * (independamment des autre pieces) * @param fx (from x) la position d'origine en x de la Reine * @param fy (from y) la position d'origine en y de la Reine * @param tx (to x) la future position en x de la Reine * @param ty (to y) la future position en y de la Reine */ @Override public boolean isMovePossible(int fx,int fy,int tx,int ty) { int dx = tx - fx; int dy = ty - fy; boolean fou = (dx == dy) ^ (dx == -dy); boolean tour = (tx == fx) ^ (ty == fy); return fou ^ tour; } } <file_sep>/Main.java import java.util.Scanner; public class Main { public static void main(String[] args) { Chessboard cb = new Chessboard(); cb.displayShell(); Scanner sc = new Scanner(System.in); int color; System.out.println("Combien d'IA souhaitez vous ? 1 ou 2 ?"); String in = sc.next(); //COLOR 0 ######################################################### if(in.equals("1")){ // Cas ou y'a un joueur System.out.println("Choisis une รฉquipe (0 ou 1) / (blanc ou vert)"); in = sc.next(); if(in.equals("blanc") || in.equals("0")) color = 0; else if (in.equals("vert") || in.equals("1")) color = 1; else { System.out.println("Mauvais input, couleur par defaut = vert"); color = 1; } Player p = new Player(cb,color); Ai a = new Ai(cb,1 - color); while(p.getAlive() == true && a.getAlive() == true) { if (color == 0){ // Cas ou le joueur est blanc donc commence int val = 1; do{ val = p.gameLoop(); if(val == 1) cb.displayShell(); } while (val != 0); if(p.getAlive() == false) break; a.makeMove(); } else { a.makeMove(); if(a.getAlive() == false) break; int val = 1; do{ val = p.gameLoop(); if(val == 1) cb.displayShell(); } while (val != 0); } cb.mutation(); } if(p.getAlive() == false) { System.out.println("You lost"); } else if(a.getAlive() == false) { System.out.println("You won"); } } //COLOR 2 ######################################################### else if (in.equals("2")){//Cas sans joueur Ai Kasparof = new Ai(cb, 1); Ai Mickey = new Ai(cb, 0); while (Kasparof.getAlive() == true && Mickey.getAlive() == true){ Mickey.makeMove(); try { Thread.sleep(1000); } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } if(Mickey.getAlive() == false) break; Kasparof.makeMove(); cb.mutation(); } if (Kasparof.getAlive() == false){ System.out.println("Les blancs ont gagnรฉ"); } else if (Mickey.getAlive() == false){ System.out.println("Les verts ont gagnรฉ"); } } else { System.out.println("Mauvais input, fin du programme"); } } } <file_sep>/Makefile run: Main java -jar chess.jar Main Main: Chessboard.java Box.java Piece.java Main.java Pion.java Fou.java Tour.java Cheval.java Roi.java Reine.java Player.java javac $^ jar cfe chess.jar $@ *.class edit: xfce4-terminal -x vim -p Piece.java Pion.java Fou.java Tour.java Cheval.java Roi.java Reine.java & vim -p Makefile Player.java Ai.java Main.java Chessboard.java Box.java clean: rm -f *.class rm -f chess.jar <file_sep>/Piece.java /** * *class abtsraite reprรฉsentant la piece d'un jeu d'รฉchec */ public abstract class Piece { protected int color; /** * Pour afficher la piece sur le terminal */ public abstract void displayShell(); /** * Retourne true si le mouvement est possible * selon les regles de la piece * (independamment des autre pieces) * @param fx (from x) la position d'origine en x d'une piece * @param fy (from y) la position d'origine en y d'une piece * @param tx (to x) la future position en x d'une piece * @param ty (to y) la future position en y d'une piece */ public abstract boolean isMovePossible(int fx, int fy, int tx, int ty); /** * *renvoie la couleur de la piece */ public int getColor(){ return this.color; } } <file_sep>/README.md # Projet de JAVA ## Manuel utilisateur [fr] Pour lancer le programme l'utilisateur peut soit utiliser la commande `make` s'il souhaite recompiler le projet, soit `java -jar chess.jar` pour le lancer plus classiquement. Ensuite l'utilisateur devra choisir s'il veut jouer contre une IA ou deux IA. Ensuite il va devoir choisir sa couleur, s'il choisit 0 il sera blanc (en bas et il commencera), s'il choisit 1 il sera vert, assimilรฉ ร  noir (en haut il est le second ร  jouer). Pour jouer le joueur fournira un string de forme fxfy txty (avec fx une lettre en a et h, fy un chiffre en 1 et 8 puis la destination sous le mรชme format). **Exemple** : ``` a2a3 (Si le joueur est blanc) ``` Une fois que l'un des joueurs a gagnรฉ le jeu se ferme automatiquement. ## User manuel [en] For run the soft you need to use the command `make` if you want to compile again or just `java -jar chess.jar` for run this more classicaly. He gonna ask you (in french) how many AIs you want, if you answer "one" he gonna launche the game Ai (We name her Mickey) against you. If you answer "two" two AIs (Mickey and Kasparof) gonne play together without you. For play you need to enter things with the format : `#x#x` with '#' letter a->h and 'x' 1->8. The first couple is origin pos, and the second is destination. **Example** : ``` a2a3 (If the player is white) ``` ## Manuel technique [only in french] ### Les piรจces La gestion des piรจces se fait par le biais de diffรฉrente classes : - Piece.java - Pion.java - Tour.java - Fou.java - Cheval.java - Reine.java - Roi.java La classe `Piece` est une classe abstraite dont chacune des autres piรจces hรฉrite. La partie importante des classes de chacune des piรจces est la mรฉthode `isMoveIsPossible` qui est un boolรฉen et qui permet de vรฉrifier que les coordonnรฉes donnรฉe en entrรฉe par l'utilisateur sont valide et respecte les rรจgles des รฉchecs. Les piรจces ont directement dans leur constructeur un int ( 0 ou 1 ) qui permet de connaรฎtre leur couleur et ceci dรจs leur initialisation. Dans la classe mรจre (Piece.java) il y a trois assesseurs: - `getColor` : Qui permet de rรฉcupรฉrer le int de la couleur. - `getPiece` : Qui permet de tester la piรจce et retourne une `Piece`. - `getTypePiece` : Qui permet d'avoir le nom de la classe, elle retourne un String. ### Le plateau Les classes en rapport avec le plateau de jeu sont dans : - Box.java - Chessboard.java La classe Box permet de crรฉer les cases du plateau, elles stockent soit null, soit une piรจce. La plupart des mรฉthodes dans cette classe sont liรฉe ร  l'affichage nรฉanmoins la fonction `changePiece` permet, comme son nom l'indique de changer la piรจce dans la box concernรฉe. Cette mรฉthode est utilisรฉe beaucoup dans l'initialisation et dans les mรฉthodes de mouvement. Dans la classe Chessboard on peut observer de nombreuses mรฉthodes. Les mรฉthodes `traceDiag` et `traceLigne` permettent de vรฉrifier s'il y'a des piรจces dans des cases entre deux positions. Ce sont des mรฉthodes de vรฉrification tout comme la mรฉthode `movePossible` qui permet de vรฉrifier si un mouvement est possible en fonction de son environnement (piรจces alliรฉes sur la route par exemple) et c'est lร  sa diffรฉrence majeur avec `isMoveIsPossible`. La mรฉthode `mouvement` bouge les piรจces en vรฉrifiant que c'est possible (en utilisant les fonctions `movePossible` & `isMoveIsPossible`), elle prend un boolรฉen "AI" pour ne pas afficher les nombreux messages d'erreur lorsque l'IA test ses coups. La fonction `mutation` test la prรฉsence de pion de l'autre couleur sur la derniรจre ligne de chaque camps (8e ligne pour les verts et 1ere ligne pour les blancs) et remplace ce dernier par une reine. La mรฉthode `setUndo` va juste empiler les Strings entrรฉ par l'utilisateur. La mรฉthode `doUndo` elle va dรฉpiler, inverser le String pour bouger la piรจce ร  sa derniรจre position. Un flag a รฉtรฉ intรฉgrรฉ pour quand une piรจce en mange une autre et ainsi permettre ร  la fonction de remettre ladite piรจce mangรฉe en jeu. La mรฉthode `findKing` va trouver le roi, pour cela elle va parcourir l'ensemble des cases du plateau en cherchant le roi de la couleur spรฉcifiรฉ. Elle renvoie ses positions dans un tableau de int. La mรฉthode `areYouInEchec` va vรฉrifier si le roi d'une couleur est mis en รฉchec. Pour cela il va vรฉrifier que le roi n'est pas attaquable par une des piรจces adverses. La mรฉthode `areYouInMat` va vรฉrifier si le roi de la couleur spรฉcifiรฉe peut encore bougรฉ en situation d'รฉchec, elle ne prend pas en compte la situation oรน une piรจce le protรจge en se dรฉplaรงant. La mรฉthode `areYouInEchecEtMat` va lancer la prรฉcรฉdente fonction en bougeant chacune des piรจces de la couleur pour voir si l'une d'elle peut intercepter le rรฉgicide. ### Les joueurs (Humain et IA) Les classes en rapport avec les joueurs et les IA sont : - Player.java - Ai.java Dans la class player il y a les fonctions chargรฉes de rรฉcupรฉrer l'Input user et transforme les lettres de ce dernier en chiffre manipulable par le reste du programme. Et il y'a la mรฉthode `GameLoop` qui va dรฉterminer prรฉcisรฉment la routine de jeu pour un joueur humain. Dans la class Ai il y'a les mรฉthodes chargรฉes de choisir alรฉatoirement une piรจce ayant un coup valide et de l'effectuer.
b42da39a9898483cf45d8b14b6f61e262d2a21f8
[ "Markdown", "Java", "Makefile" ]
8
Java
gnouf1/Echecs
00958f298a0026a6ed144d43a149826a4e39802a
adff33d677bd8560534807bb0afe55e2cfccd8e7
refs/heads/master
<repo_name>OArtyomov/Skyou-TestTask<file_sep>/src/componentTest/java/com/skyou/actuator/ActuatorSecurityTest.java package com.skyou.actuator; import com.skyou.AbstractBaseIT; import org.junit.Test; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; public class ActuatorSecurityTest extends AbstractBaseIT { @Test public void testHealthIsUnsecured() throws Exception { mockMvc.perform(get("/actuator/health")) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("UP")) .andExpect(jsonPath("$.length()").value(1L)); } @Test public void testInfoEndpoint() throws Exception { mockMvc.perform(get("/actuator/info")) .andExpect(status().isOk()) .andExpect(jsonPath("$.git.length()").value(2L)) .andExpect(jsonPath("$.git.branch").isNotEmpty()) .andExpect(jsonPath("$.git.commit.id").isNotEmpty()) .andExpect(jsonPath("$.git.commit.time").isNotEmpty()); } }<file_sep>/README.md ### Skyou<file_sep>/yoda #!/usr/bin/env bash # Last Update 08/17/2016 source_docker() { export DOCKER_HOST_IP=localhost if [[ "$OSTYPE" == "darwin"* ]]; then if which docker-machine > /dev/null; then machine_name="${DOCKER_MACHINE_NAME:-dockerdev}" eval $(docker-machine env $machine_name) export DOCKER_HOST_IP=$(docker-machine ip $machine_name) elif which boot2docker > /dev/null; then eval $(boot2docker shellinit 2>/dev/null) export DOCKER_HOST_IP=$(boot2docker ip) fi fi echo docker host running on IP $DOCKER_HOST_IP } usage() { echo "Available Commands:" echo " yoda Run all tests. Run it before committing." echo " yoda deps <(up)|down|help> Start|stop dependencies" echo " yoda applocal <(up)|down|help> Start|stop local app" echo " yoda appdocker <(up)|down|help> Start|stop local app on docker" echo " yoda tests <(unit)|docker|local|help> Run tests" echo " yoda teardown Remove containers (app and dependencies)" echo " yoda help Show usage" exit } # Main Script while [ $# -ge 0 ]; do case $1 in "") echo "Running All tests. If you need usage help, use ./yoda help" source_docker ./gradlew clean build functionalTest exit ;; deps) case $2 in ""|up) echo "Running ./yoda deps up - For help ./yoda deps help" source_docker ./gradlew startDependencyContainer ;; down) source_docker ./gradlew removeAllContainers ;; help|*) echo "Available Commands:" echo " yoda deps (up) Start local depedencies." echo " yoda deps down Stop local depedencies." echo " yoda deps help Print this help." ;; esac exit ;; applocal) case $2 in "") echo "Running ./yoda applocal up - For help ./yoda applocal help" source_docker ./gradlew clean bootRun -Pargs="--debug" ;; up) source_docker ./gradlew clean bootRun -Pargs="--debug" ;; down) ps aux | grep bootRun | grep -v grep | awk '{print $2}' | xargs kill ;; help|*) echo "Available Commands:" echo " yoda applocal (up) Start the app locally (without depedencies)." echo " yoda applocal down Stop the local app (without stopping dependencies)." echo " yoda applocal help Print this help." ;; esac exit ;; appdocker) case $2 in "") echo "Running ./yoda appdocker up - For help ./yoda appdocker help" source_docker ./gradlew clean assemble startApplication ;; up) source_docker ./gradlew clean assemble startApplication ;; down) source_docker ./gradlew removeApplicationContainer ;; help|*) source_docker echo "Available Commands:" echo " yoda appdocker (up) Start the app on docker locally with depedencies." echo " yoda appdocker down Stop the docker app without stopping dependencies." echo " yoda appdocker help Print this help." ;; esac exit ;; tests) case $2 in "") echo "Running ./yoda tests unit - For help ./yoda tests help" ./gradlew clean test ;; unit) ./gradlew clean test ;; docker) (cd ruby && rspec && cd ..) ;; local) echo "Not implemented" ;; help|*) echo "Available Commands:" echo " yoda tests (unit) Run unit tests." echo " yoda tests docker Run the ruby tests in docker. You need to run ./yoda appdocker up first." echo " yoda tests local Run the ruby tests with local app. You need to run ./yoda applocal up first." echo " yoda tests help Print this help." ;; esac exit ;; teardown) source_docker ./gradlew removeAllContainers exit ;; help|*) usage exit ;; esac done <file_sep>/src/main/java/com/skyou/web/EventsController.java package com.skyou.web; import com.skyou.service.GitHubService; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE; @RestController @RequestMapping("/github") @Slf4j @AllArgsConstructor(onConstructor_ = {@Autowired}) public class EventsController { private GitHubService gitHubService; @RequestMapping(value = "/publicEvents", method = {RequestMethod.GET}, produces = {APPLICATION_JSON_UTF8_VALUE}) public String publicEvents(@RequestParam(required = false, defaultValue = "1") Long pageNumber, @RequestParam(required = false, defaultValue = "10") Long pageSize) { return gitHubService.getEvents(pageNumber, pageSize); } }<file_sep>/src/main/java/com/skyou/config/SwaggerConfig.java package com.skyou.config; import com.google.common.collect.ImmutableSet; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.annotations.ApiIgnore; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; import java.util.Collections; import java.util.Set; import static springfox.documentation.builders.PathSelectors.any; import static springfox.documentation.builders.RequestHandlerSelectors.basePackage; import static springfox.documentation.spi.DocumentationType.SWAGGER_2; @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(SWAGGER_2) .forCodeGeneration(true) .apiInfo(apiInfo()) .ignoredParameterTypes(ignoredTypes()) .alternateTypeRules() .pathProvider(new AlwaysRootPathProvider()) .select() .apis(basePackage("com.skyou")) .paths(any()) .build(); } private Set<Class> findIgnoredEntities() { return Collections.emptySet(); } private Class[] ignoredTypes() { return ImmutableSet.<Class>builder() .add(ApiIgnore.class) .addAll(findIgnoredEntities()) .build().toArray(new Class[]{}); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("ZCommerce API Description") .description("ZCommerce Public API") .termsOfServiceUrl("http://springfox.io") .contact(new Contact("Development Team", null, null)) .license("Apache License Version 2.0") .licenseUrl("https://github.com/springfox/springfox/blob/master/LICENSE") .version("1.0").build(); } }<file_sep>/_docker.gradle buildscript { dependencies { classpath fileTree(include: ['*.jar'], dir: 'plugins') } } ext { dockerNetwork = 'skyou-network' applicationContainer = 'skyou' applicationPort = 8080 jmxPort = 10080 jdwpPort = 9080 } task createNetwork(type: DockerCreateNetwork) { networkName = dockerNetwork } task removeAllContainers(type: DockerRemoveContainer) { containerIds = [ applicationContainer ] } task createApplicationContainer(type: DockerCreateImage) { targetFolder = projectDir tag = applicationContainer } task removeApplicationContainer(type: DockerRemoveContainer) { containerIds = [ applicationContainer ] } task startDependencyContainers(dependsOn: [createNetwork]) task startApplicationContainer(type: DockerStartContainer, dependsOn: [startDependencyContainers, createApplicationContainer, createNetwork]) { containerName = applicationContainer image = "${applicationContainer}:latest" connectedNetworks = dockerNetwork ports = [ "${applicationPort}": applicationPort, "${jmxPort}": jmxPort, "${jdwpPort}": jdwpPort ] environment = [ "SERVER_PORT": "${applicationPort}", "JAVA_OPTS": "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=${jdwpPort}" ] } task startApplication(dependsOn: startApplicationContainer) { doLast { try { DockerUtils.waitFor([ 'docker', 'exec', applicationContainer, 'curl', '-s', "http://localhost:${applicationPort}/actuator/health" ], 90) } catch (e) { logger.error('Timeout waiting for the app to start', e) def proc = ['docker', 'logs', applicationContainer].execute() proc.consumeProcessOutput(System.out, System.err) proc.waitFor() throw e; } } } <file_sep>/build.gradle buildscript { ext { springBootVersion = '2.1.0.RELEASE' gitPropertiesPluginVersion = '1.5.2' } repositories { mavenCentral() maven { url "https://plugins.gradle.org/m2/" } } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") classpath "gradle.plugin.com.gorylenko.gradle-git-properties:gradle-git-properties:${gitPropertiesPluginVersion}" } } apply plugin: 'java' apply plugin: 'org.springframework.boot' apply plugin: 'io.spring.dependency-management' apply plugin: 'idea' apply from: '_docker.gradle' apply plugin: "com.gorylenko.gradle-git-properties" sourceCompatibility = 1.8 targetCompatibility = 1.8 repositories { mavenCentral() } jar { baseName = 'skyou-testtask' } sourceSets { componentTest { java { compileClasspath += main.output compileClasspath += test.output runtimeClasspath += main.output runtimeClasspath += test.output } } functionalTest { java { compileClasspath += main.output runtimeClasspath += main.output } } } configurations { componentTestCompile.extendsFrom testCompile componentTestRuntime.extendsFrom testRuntime functionalTestCompile.extendsFrom componentTestCompile functionalTestRuntime.extendsFrom componentTestCompile } dependencyManagement { dependencies { dependency 'net.logstash.logback:logstash-logback-encoder:4.11' dependency 'org.codehaus.janino:janino:3.0.6' dependency 'joda-time:joda-time:2.9.9' dependency 'com.fasterxml.jackson.dataformat:jackson-dataformat-cbor:2.8.10' dependency 'org.apache.commons:commons-lang3:3.1' dependency 'org.codehaus.janino:janino:3.0.6' dependency 'io.springfox:springfox-swagger2:2.8.0' dependency 'io.springfox:springfox-swagger-ui:2.8.0' dependency "com.github.tomakehurst:wiremock-jre8:2.24.1" dependency 'org.apache.httpcomponents:httpclient:4.5.10' } } dependencies { compile "org.springframework.boot:spring-boot-starter" compile "org.springframework.boot:spring-boot-starter-actuator" compile "org.springframework.boot:spring-boot-starter-web" compile "org.springframework.boot:spring-boot-starter-security" compile 'org.projectlombok:lombok' compile 'org.codehaus.janino:janino' compile 'io.micrometer:micrometer-registry-prometheus' compile 'io.micrometer:micrometer-registry-jmx' compile 'org.apache.commons:commons-lang3' compile 'joda-time:joda-time' compile 'io.springfox:springfox-swagger2' compile 'io.springfox:springfox-swagger-ui' compile 'org.apache.httpcomponents:httpclient' testCompile 'org.springframework.boot:spring-boot-starter-test' testCompile 'org.springframework.security:spring-security-test' testCompile "com.github.tomakehurst:wiremock-jre8" } gitProperties { dateFormat = "yyyy-MM-dd HH:mm:ssZ" dateFormatTimeZone = 'GMT' } test { testLogging { events "passed", "skipped", "failed" afterSuite { desc, result -> if (!desc.parent) { println "Results: ${result.resultType} (${result.testCount} tests, ${result.successfulTestCount} successes, ${result.failedTestCount} failures, ${result.skippedTestCount} skipped)" } } } } task componentTest(type: Test) { testClassesDirs = sourceSets.componentTest.output.classesDirs classpath = sourceSets.componentTest.runtimeClasspath jvmArgs '-DXms2G', '-DXmx4G' testLogging { events 'passed', 'skipped', 'failed' exceptionFormat 'short' } } task functionalTest(type: Test, dependsOn: [startDependencyContainers, componentTest, startApplication]) { testClassesDirs = sourceSets.functionalTest.output.classesDirs classpath = sourceSets.functionalTest.runtimeClasspath jvmArgs '-DXms2G', '-DXmx4G' testLogging { events 'passed', 'skipped', 'failed' exceptionFormat 'short' } finalizedBy removeAllContainers } tasks.withType(JavaCompile) { options.compilerArgs << "-Xlint:unchecked" << "-Werror" } task wrapper(type: Wrapper) { gradleVersion = '4.5' } <file_sep>/src/componentTest/java/com/skyou/web/EventControllerIT.java package com.skyou.web; import com.skyou.AbstractBaseIT; import io.micrometer.core.instrument.util.IOUtils; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import javax.annotation.Resource; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; public class EventControllerIT extends AbstractBaseIT { @Resource private ApplicationContext applicationContext; @Test public void testGetEvents() throws Exception { String responseAsString = IOUtils.toString(applicationContext.getResource("classpath:github-events.json").getInputStream()); Long pageSize = 10L; Long pageNumber = 1L; stubFor(get(urlEqualTo("/events?page=" + pageNumber + "&per_page=" + pageSize)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", APPLICATION_JSON_VALUE) .withBody(responseAsString))); mockMvc.perform(MockMvcRequestBuilders.get("/github/publicEvents") .param("pageNumber", pageNumber.toString()) .param("pageSize", pageSize.toString())) .andExpect(content().contentType(APPLICATION_JSON_UTF8_VALUE)) .andExpect(status().isOk()); } }<file_sep>/Dockerfile FROM openjdk:8-jdk-alpine RUN apk --no-cache add curl ADD build/libs/Skyou-TestTask.jar /app/application.jar CMD ["java","-jar","/app/application.jar"]
64a7d7ed60629ef0e030c99898628ea2410ed459
[ "Markdown", "Gradle", "Java", "Dockerfile", "Shell" ]
9
Java
OArtyomov/Skyou-TestTask
15615e2e83a5498d56cae87efcff4eba26874bb0
0afa3b40e8754210d858e7b4459068993d65294c
refs/heads/master
<file_sep>package com.io17.excel2json; import java.util.LinkedList; import java.util.List; import org.json.JSONArray; import org.json.JSONObject; public class JSONUtils { public static List toList(JSONArray json) { List list = new LinkedList(); for (int i = 0; i < json.length(); i++) { list.add(json.get(i)); } return list; } } <file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.io17.excel2json</groupId> <artifactId>Excel2Json</artifactId> <version>0.0.1-SNAPSHOT</version> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.2</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <!-- <plugin> --> <!-- <groupId>org.apache.maven.plugins</groupId> --> <!-- <artifactId>maven-jar-plugin</artifactId> --> <!-- <configuration> --> <!-- <archive> --> <!-- <manifest> --> <!-- <addClasspath>true</addClasspath> --> <!-- <mainClass>com.io17.excel2json.Excel2Json</mainClass> --> <!-- </manifest> --> <!-- </archive> --> <!-- </configuration> --> <!-- </plugin> --> <!-- <plugin> --> <!-- <artifactId>maven-dependency-plugin</artifactId> --> <!-- <executions> --> <!-- <execution> --> <!-- <phase>install</phase> --> <!-- <goals> --> <!-- <goal>copy-dependencies</goal> --> <!-- </goals> --> <!-- <configuration> --> <!-- <outputDirectory>${project.build.directory}/lib</outputDirectory> --> <!-- </configuration> --> <!-- </execution> --> <!-- </executions> --> <!-- </plugin> --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>2.1</version> <configuration> <minimizeJar>false</minimizeJar> <transformers> <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> <mainClass>com.io17.excel2json.Excel2Json</mainClass> </transformer> </transformers> </configuration> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> </execution> </executions> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.11</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.11</version> </dependency> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20141113</version> </dependency> </dependencies> </project><file_sep>package com.io17.excel2json; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.json.JSONArray; import org.json.JSONObject; public class JSONAggregator { private JSONAggregatorConfiguration configuration; public JSONAggregator(JSONAggregatorConfiguration config) { this.configuration = config; } public JSONArray process(JSONArray json) { List<JSONObject> list = JSONUtils.toList(json); Map<String, List<JSONObject>> groups = list.stream().collect(Collectors.groupingBy(s -> s.getString(configuration.getPivotField()))); return toJSON(groups); } private JSONArray toJSON(Map<String, List<JSONObject>> groups) { JSONArray ja = new JSONArray(); for(String pivot : groups.keySet()){ JSONObject jo = new JSONObject(); List<JSONObject> group = groups.get(pivot); List<String> extractFields = configuration.getExtractFields(); for(String field : extractFields){ jo.put(field, group.get(0).opt(field)); } fixGroup(group); jo.put(configuration.getGroupField(), new JSONArray(group.toArray())); ja.put(jo); } return ja; } private JSONArray fixGroup(List<JSONObject> group) { JSONArray ja = new JSONArray(); for(JSONObject jo : group){ fixFields(group, jo); ja.put(jo); } return ja; } private void fixFields(List<JSONObject> group, JSONObject jo) { if(!configuration.shouldRetainFields()){ for(String field : configuration.getExtractFields()){ jo.remove(field); } } } } <file_sep>package com.io17.excel2json; import java.util.List; import org.json.JSONObject; public class JSONAggregatorConfiguration { private String pivotField; private List<String> extractFields; private String groupField; private boolean retainFields; public JSONAggregatorConfiguration(String pivotField) { this.pivotField = pivotField; } public JSONAggregatorConfiguration(JSONObject aggregateJSON) { pivotField = aggregateJSON.optString("_pivotField"); groupField = aggregateJSON.optString("_groupField"); retainFields = aggregateJSON.optBoolean("_retainFields"); extractFields = JSONUtils.toList(aggregateJSON.optJSONArray("_extractFields")); } public String getPivotField() { return pivotField; } public void setPivotField(String pivotField) { this.pivotField = pivotField; } public List<String> getExtractFields() { return extractFields; } public String getGroupField() { return groupField; } public boolean shouldRetainFields() { return retainFields; } }
efea64741dd80e6d7c62d0e66904e16b55dca979
[ "Java", "Maven POM" ]
4
Java
io17/Excel2Json
01cfe2fdf5425cffae15f99adae138d81dd9a4f0
efd10372e5ce2083ec956a7e6a80dde41564fb97
refs/heads/master
<repo_name>rvt-tex/playlister-sinatra-online-web-pt-100719<file_sep>/app/models/concerns/slugifiable.rb module Slugifiable module InstanceMethods def slug name = self.name.downcase.split(" ") name.join("-") end end module ClassMethods def find_by_slug(slug) slug = slug.split("-").map(&:capitalize) name = slug.join(" ") self.where("name like ?", "#{name}").first end end end<file_sep>/app/controllers/songs_controller.rb class SongsController < ApplicationController get '/songs' do @songs = Song.all erb :'/songs/index' end get '/songs/new' do erb :'/songs/new' end get '/songs/:slug' do @song = Song.find_by_slug(params[:slug]) erb :'/songs/show' end post '/songs' do @song = Song.new(name:params[:song_name]) @artist = Artist.find_or_create_by(name:params[:artist_name]) @genres = params[:genres].map {|genre_data| Genre.find(genre_data)} @song.artist = @artist @song.genres = @genres @song.save flash[:notice] = "Successfully created song." redirect to "/songs/#{@song.slug}" end get '/songs/:slug/edit' do @song = Song.find_by_slug(params[:slug]) erb :'/songs/edit' end patch '/songs/:slug' do @song = Song.find_by_slug(params[:slug]) @artist = Artist.find_or_create_by(name:params[:artist_name]) @genres = params[:genres].map {|genre_data| Genre.find(genre_data)} @song.artist = @artist @song.genres = @genres if @song.save flash[:message] = "Successfully updated song." redirect to "/songs/#{song_name}" else erb :'/songs/show' end end end
07297eb5b2abe4c06eea0a607b7a54a7921dedf1
[ "Ruby" ]
2
Ruby
rvt-tex/playlister-sinatra-online-web-pt-100719
66e47cefc934a5e73a04908c49d99d64fb2ba97d
ace998f0105c057ea0e668a8737f36ee78513b45
refs/heads/master
<repo_name>chenmike19999/t<file_sep>/sum.sql select a.tablespace_name, a.bytes / 1024 / 1024 "sum MB", (a.bytes - b.bytes) / 1024 / 1024 "used MB", b.bytes / 1024 / 1024 "free MB", round(((a.bytes - b.bytes) / a.bytes) * 100, 2) "used%" from (select tablespace_name, sum(bytes) bytes from dba_data_files group by tablespace_name) a, (select tablespace_name, sum(bytes) bytes, max(bytes) largest from dba_free_space group by tablespace_name) b where a.tablespace_name = b.tablespace_name order by ((a.bytes - b.bytes) / a.bytes) desc;
fd5e43b44950f476edd4cae991f2c8296d6c13b9
[ "SQL" ]
1
SQL
chenmike19999/t
4e10ea1f2994b81ffce955f941514cd8247f492e
31207bfe2866ff982e4bfd6ab2610e10c0eb9cdd
refs/heads/master
<repo_name>jhonymaurad/New-Visions-Assessment<file_sep>/client/src/data/students.js export const students = [ { _id: { $oid: '5dc194991c9d4400004c640a' }, name: '<NAME>', grade: 6, scores: [ { subject: 'Math', value: 85 }, { subject: 'English', value: 65 }, { subject: 'Science', value: 70 }, { subject: 'Social Studies', value: 95 } ] }, { _id: { $oid: '5dc1956a1c9d4400004c640c' }, name: '<NAME>', grade: 7, scores: [ { subject: 'Math', value: 95 }, { subject: 'English', value: 80 }, { subject: 'Science', value: 85 }, { subject: 'Social Studies', value: 95 } ] }, { _id: { $oid: '5dc196c71c9d4400004c640d' }, name: '<NAME>', grade: 8, scores: [ { subject: 'Math', value: 55 }, { subject: 'English', value: 85 }, { subject: 'Science', value: 75 }, { subject: 'Social Studies', value: 65 } ] }, { _id: { $oid: '5dc1971e1c9d4400004c640e' }, name: '<NAME>', grade: 6, scores: [ { subject: 'Math', value: 50 }, { subject: 'English', value: 90 }, { subject: 'Science', value: 95 }, { subject: 'Social Studies', value: 60 } ] }, { _id: { $oid: '5dc197461c9d4400004c640f' }, name: '<NAME>', grade: 8, scores: [ { subject: 'Math', value: 75 }, { subject: 'English', value: 75 }, { subject: 'Science', value: 75 }, { subject: 'Social Studies', value: 75 } ] }, { _id: { $oid: '5dc197651c9d4400004c6410' }, name: '<NAME>', grade: 7, scores: [ { subject: 'Math', value: 65 }, { subject: 'English', value: 95 }, { subject: 'Science', value: 100 }, { subject: 'Social Studies', value: 65 } ] }, { _id: { $oid: '5dc1979b1c9d4400004c6411' }, name: '<NAME>', grade: 6, scores: [ { subject: 'Math', value: 95 }, { subject: 'English', value: 75 }, { subject: 'Science', value: 60 }, { subject: 'Social Studies', value: 80 } ] }, { _id: { $oid: '5dc198051c9d4400004c6412' }, name: '<NAME>', grade: 7, scores: [ { subject: 'Math', value: 60 }, { subject: 'English', value: 90 }, { subject: 'Science', value: 90 }, { subject: 'Social Studies', value: 85 } ] }, { _id: { $oid: '5dc198291c9d4400004c6413' }, name: '<NAME>', grade: 8, scores: [ { subject: 'Math', value: 65 }, { subject: 'English', value: 70 }, { subject: 'Science', value: 80 }, { subject: 'Social Studies', value: 65 } ] }, { _id: { $oid: '5dc1984a1c9d4400004c6414' }, name: '<NAME>', grade: 6, scores: [ { subject: 'Math', value: 65 }, { subject: 'English', value: 80 }, { subject: 'Science', value: 75 }, { subject: 'Social Studies', value: 60 } ] }, { _id: { $oid: '5dc198871c9d4400004c6415' }, name: '<NAME>', grade: 7, scores: [ { subject: 'Math', value: 95 }, { subject: 'English', value: 90 }, { subject: 'Science', value: 75 }, { subject: 'Social Studies', value: 70 } ] }, { _id: { $oid: '5dc199101c9d4400004c6416' }, name: '<NAME>', grade: 8, scores: [ { subject: 'Math', value: 50 }, { subject: 'English', value: 70 }, { subject: 'Science', value: 80 }, { subject: 'Social Studies', value: 65 } ] }, { _id: { $oid: '5dc199561c9d4400004c6417' }, name: '<NAME>', grade: 6, scores: [ { subject: 'Math', value: 70 }, { subject: 'English', value: 80 }, { subject: 'Science', value: 90 }, { subject: 'Social Studies', value: 100 } ] }, { _id: { $oid: '5dc199731c9d4400004c6418' }, name: '<NAME>', grade: 7, scores: [ { subject: 'Math', value: 65 }, { subject: 'English', value: 70 }, { subject: 'Science', value: 75 }, { subject: 'Social Studies', value: 80 } ] }, { _id: { $oid: '5dc199991c9d4400004c6419' }, name: '<NAME>', grade: 8, scores: [ { subject: 'Math', value: 80 }, { subject: 'English', value: 75 }, { subject: 'Science', value: 70 }, { subject: 'Social Studies', value: 65 } ] }, { _id: { $oid: '5dc199ba1c9d4400004c641a' }, name: '<NAME>', grade: 6, scores: [ { subject: 'Math', value: 65 }, { subject: 'English', value: 95 }, { subject: 'Science', value: 70 }, { subject: 'Social Studies', value: 85 } ] }, { _id: { $oid: '5dc199d71c9d4400004c641b' }, name: '<NAME>', grade: 7, scores: [ { subject: 'Math', value: 75 }, { subject: 'English', value: 55 }, { subject: 'Science', value: 80 }, { subject: 'Social Studies', value: 80 } ] }, { _id: { $oid: '5dc199f61c9d4400004c641c' }, name: '<NAME>', grade: 8, scores: [ { subject: 'Math', value: 75 }, { subject: 'English', value: 75 }, { subject: 'Science', value: 80 }, { subject: 'Social Studies', value: 60 } ] }, { _id: { $oid: '5dc19a281c9d4400004c641d' }, name: '<NAME>', grade: 6, scores: [ { subject: 'Math', value: 60 }, { subject: 'English', value: 90 }, { subject: 'Science', value: 55 }, { subject: 'Social Studies', value: 90 } ] }, { _id: { $oid: '5dc19a531c9d4400004c641e' }, name: '<NAME>', grade: 7, scores: [ { subject: 'Math', value: 75 }, { subject: 'English', value: 70 }, { subject: 'Science', value: 80 }, { subject: 'Social Studies', value: 65 } ] } ]; export const groupByGrade = students => { let studentsByGrade = []; let six = []; let seven = []; let eigth = []; for (let student of students) { switch (student.grade) { case 6: six.push(student); break; case 7: seven.push(student); break; case 8: eigth.push(student); break; default: console.log('student needs a grade'); } } studentsByGrade.push(six); studentsByGrade.push(seven); studentsByGrade.push(eigth); return studentsByGrade; }; function average(student) { let scores = student.scores; let sum = 0; for (let subject of scores) { sum += subject.value; } return sum / scores.length; } export const findLowestAverages = students => { const lowestInEachGrade = []; //will contain 3 student object, one for each grade for (let i = 0; i < students.length; i++) { let avg = 0; let lowestStudent = {}; for (let j = 0; j < students[i].length; j++) { if (avg === 0) { lowestStudent = students[i][j]; lowestStudent['average'] = average(lowestStudent); avg = lowestStudent.average; } if (average(students[i][j]) < avg) { lowestStudent = students[i][j]; lowestStudent['average'] = average(lowestStudent); avg = lowestStudent.average; } } lowestInEachGrade.push(lowestStudent); avg = 0; lowestStudent = {}; } return lowestInEachGrade; }; <file_sep>/README.md # New-Visions-Assessment - I created a React front end environment to display the data. - The page contains: the original data of students, followed by the students sorted by grade. - To display the students with the lowest average click the button "Get lowest Avg" The assessment can be view at : https://reverent-northcutt-1c6978.netlify.com/ The results of the assessment can also be checked in the console, using the file: Assessment.js <file_sep>/client/src/components/Card.js import React from 'react'; const Card = props => ( <div className="card-container"> <h3>Name: {props.student.name}</h3> <p>Grade: {props.student.grade}</p> <h3>Scores for each subject:</h3> {props.student.scores.map(score => { return ( <p key={score.subject}> {score.subject} : {score.value} </p> ); })} </div> ); export default Card; <file_sep>/client/src/App.js import React from 'react'; import logo from './NewVisions_Primary_RGB.jpg'; import './App.css'; import { students, groupByGrade, findLowestAverages } from './data/students'; import StudentsList from './components/StudentsList'; class App extends React.Component { state = { students: students, studentsByGrade: [], studentsWithLowestAvg: [] }; componentDidMount() { let studentsByGrade = groupByGrade(this.state.students); this.setState({ studentsByGrade }); } handleGetAvg(e) { const studentsWithLowestAvg = findLowestAverages( this.state.studentsByGrade ); this.setState(prevState => ({ ...prevState.studentsWithLowestAvg, studentsWithLowestAvg })); } renderStudentsByGrade = () => { return ( <div> <h1>Students Sorted by Grade</h1> {this.state.studentsByGrade.map(grade => { return ( <div key={grade.name}> {grade.map(student => { return ( <div key={student.name}> <h3>{student.name}</h3> <h3>Grade: {student.grade}</h3> </div> ); })} </div> ); })} </div> ); }; renderAvg = () => { return ( <div> <h1>Students with the lowest average by grade</h1> {this.state.studentsWithLowestAvg.map(student => { return ( <div> <h3>{student.name}</h3> <h4>Grade:{student.grade}</h4> <h4>Average: {student.average}</h4> </div> ); })} </div> ); }; render() { return ( <div className="App"> <h1>Original Student Data</h1> <StudentsList students={this.state.students} className="card-list" /> {this.state.studentsByGrade !== null && this.renderStudentsByGrade()} <button onClick={() => this.handleGetAvg(this.state.studentsByGrade)}> Get Lowest Avg </button> {this.state.studentsWithLowestAvg !== null && this.renderAvg()} </div> ); } } export default App;
414e67d1425abdff56fdb0e99fbd687d1caf6043
[ "JavaScript", "Markdown" ]
4
JavaScript
jhonymaurad/New-Visions-Assessment
04b3e70a9a7fc14172083f69a4c4a5297b78e313
f0ae3bee80e97391a25d211139ca17af0884e5f7
refs/heads/main
<file_sep>class Grocery { name: string; quantity: number; price: number; constructor(name: string, quantity: number, price: number) { this.name = name; this.quantity = quantity; this.price = price; } } let groceries: Array<Grocery> = [ new Grocery('Milk', 2, 2.55), new Grocery('Eggs', 12, 3.99), new Grocery('Orange Juice', 1, 5.99) ] let output: string = ""; // looping over the groceries to create HTML output for (let i = 0; i < groceries.length; i++) { output = output.concat( "<li>" + "Name: " + groceries[i].name + ", " + "Quantity: " + groceries[i].quantity + ", " + "Price: " + groceries[i].price + ", " + "</li>" ); console.log("index: " + i); } console.log("output: " + output); // writing the output to the screen document.getElementById("groceries").innerHTML = "<ol>" + output + "</ol>"; <file_sep>var Grocery = /** @class */ (function () { function Grocery(name, quantity, price) { this.name = name; this.quantity = quantity; this.price = price; } return Grocery; }()); var groceries = [ new Grocery('Milk', 2, 2.55), new Grocery('Eggs', 12, 3.99), new Grocery('Orange Juice', 1, 5.99) ]; var output = ""; // looping over the groceries to create HTML output for (var i = 0; i < groceries.length; i++) { output = output.concat("<li>" + "Name: " + groceries[i].name + ", " + "Quantity: " + groceries[i].quantity + ", " + "Price: " + groceries[i].price + ", " + "</li>"); console.log("index: " + i); } console.log("output: " + output); // writing the output to the screen document.getElementById("groceries").innerHTML = "<ol>" + output + "</ol>";
4636805f673389913c58d819f3fc96d93f4bc805
[ "JavaScript", "TypeScript" ]
2
TypeScript
SWDV-665/week-1-typescript-assignment-dapletch
ec863305a886424327eaad7483d2d1ea36f66291
6bf4c7417eebec9446e0013fabaab35f63dae20a
refs/heads/master
<repo_name>sapinet/WHMCS-RocketChat<file_sep>/modules/notifications/RocketChat/RocketChat.php <?php namespace WHMCS\Module\Notification\RocketChat; use WHMCS\Config\Setting; use WHMCS\Exception; use WHMCS\Module\Notification\DescriptionTrait; use WHMCS\Module\Contracts\NotificationModuleInterface; use WHMCS\Notification\Contracts\NotificationInterface; class RocketChat implements NotificationModuleInterface { use DescriptionTrait; public function __construct() { $this->setDisplayName('Rocket.chat') ->setLogoFileName('logo.svg'); } public function settings() { return [ 'hookURL' => [ 'FriendlyName' => 'Webhook URL', 'Type' => 'text', 'Description' => 'Exemple: https://rocketchat.example.com/hooks/123456789[...]', 'Placeholder' => ' ', ], 'botUser' => [ 'FriendlyName' => '<NAME>', 'Type' => 'text', 'Description' => 'Exemple: WHMCS', 'Placeholder' => 'WHMCS', ], ]; } public function testConnection($settings) { $hookURL = $settings['hookURL']; $botUser = $settings['botUser']; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $hookURL); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, ' { "username": "' . $botUser . '", "text": "", "attachments": [ { "title": "Connected!", "text": "Connected with WHMCS", "color": "#00C853" } ] } '); $headers = array(); $headers[] = 'Content-Type: application/json'; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $result = curl_exec($ch); if (curl_errno($ch)) { throw new \Exception('Error:' . curl_error($ch)); } curl_close($ch); } public function notificationSettings() { return []; } public function getDynamicField($fieldName, $settings) { return []; } public function sendNotification(NotificationInterface $notification, $moduleSettings, $notificationSettings) { $hookURL = $moduleSettings['hookURL']; $botUser = $moduleSettings['botUser']; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $hookURL); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, ' { "username": "' . $botUser . '", "text": "", "attachments": [ { "title": "' . $notification->getTitle() . '", "title_link": "' . $notification->getUrl() . '", "text": "' . $notification->getMessage() . '", "color": "#00C853" } ] } '); $headers = array(); $headers[] = 'Content-Type: application/json'; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $result = curl_exec($ch); if (curl_errno($ch)) { throw new \Exception('Error:' . curl_error($ch)); } curl_close($ch); } } <file_sep>/README.md # WHMCS-RocketChat Send WHCMS notifications to RocketChat ## Installation 1. Place the RocketChat folder in your WHMCS installation (modules/notification/RocketChat) 2. Create a WebHook (Admin settings -> Integrations -> New integration -> Incoming WebHook) 3. Paste the WebHook URL in WHMCS notifications settings 4. Chose a username for the bot, and set it in WHMCS notifications settings 5. You should receive a message "Connected with WHMCS", otherwise, check your WebHook URL. ```
e23e19ac5e3f161388e607a0951873eb9707b925
[ "Markdown", "PHP" ]
2
PHP
sapinet/WHMCS-RocketChat
dfc6c9d77557f13463fb639ef08f625cc29da3f4
e915bd55e37e5c2a088019e8f86668c30aae984c
refs/heads/master
<repo_name>Zintori/MemeMe<file_sep>/MemeMe/ViewController.swift // // ViewController.swift // MemeMe // // Created by <NAME> on 9/26/16. // Copyright ยฉ 2016 <NAME>. All rights reserved. // import UIKit class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate { @IBOutlet weak var imagePickerView: UIImageView! @IBOutlet weak var cameraButton: UIBarButtonItem! @IBOutlet weak var topTextField: UITextField! @IBOutlet weak var bottomTextField: UITextField! @IBOutlet weak var shareButton: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() let memeTextAttributes = [ NSStrokeColorAttributeName : UIColor.black, NSForegroundColorAttributeName : UIColor.white, NSFontAttributeName : UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!, NSStrokeWidthAttributeName : -5 ] as [String : Any] topTextField.defaultTextAttributes = memeTextAttributes bottomTextField.defaultTextAttributes = memeTextAttributes reset() topTextField.textAlignment = NSTextAlignment.center bottomTextField.textAlignment = NSTextAlignment.center self.topTextField.delegate = self self.bottomTextField.delegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) cameraButton.isEnabled = UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) if (imagePickerView.image == nil) { shareButton.isEnabled = false } else { shareButton.isEnabled = true } subscribeToKeyboardNotifications() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(true) unsubscribeToKeyboardNotifications() } override var prefersStatusBarHidden: Bool { get { return false } } @IBAction func pickAnImage(_ sender: AnyObject) { let pickController = UIImagePickerController() pickController.delegate = self pickController.sourceType = UIImagePickerControllerSourceType.photoLibrary self.present(pickController, animated: true, completion: nil) } @IBAction func shareMeme(_ sender: AnyObject) { share() } @IBAction func pickAnImageFromCamera(_ sender: AnyObject) { let pickController = UIImagePickerController() pickController.delegate = self pickController.sourceType = UIImagePickerControllerSourceType.camera self.present(pickController, animated: true, completion: nil) } @IBAction func cancel(_ sender: AnyObject) { reset() } func imagePickerController(_ imagePickerController: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { //Tells the delegate that the user picked a still image or movie. let image = info[UIImagePickerControllerOriginalImage] as? UIImage imagePickerView.image = image dismiss(animated: true, completion: nil) } func imagePickerControllerDidCancel(_ imagePickerController: UIImagePickerController){ //Tells the delegate that the user cancelled the pick operation. dismiss(animated: true, completion: nil) } func subscribeToKeyboardNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } func unsubscribeToKeyboardNotifications() { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil) } func keyboardWillShow(notification: NSNotification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { if self.view.frame.origin.y == 0{ self.view.frame.origin.y -= keyboardSize.height } } } func keyboardWillHide(notification: NSNotification) { if self.view.frame.origin.y != 0 { self.view.frame.origin.y = 0 } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func generateMemedImage() -> UIImage { // Hide toolbar and navbar self.navigationController?.setNavigationBarHidden(true, animated: true) self.navigationController?.setToolbarHidden(true, animated: true) // Render view to an image UIGraphicsBeginImageContext(self.view.frame.size) view.drawHierarchy(in: self.view.frame, afterScreenUpdates: true) let memedImage : UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() // Show toolbar and navbar self.navigationController?.setToolbarHidden(false, animated: true) self.navigationController?.setToolbarHidden(false, animated: true) return memedImage } func share() { let memeImage = generateMemedImage() let viewController = UIActivityViewController.init(activityItems: [memeImage], applicationActivities:nil) self.present(viewController, animated: true, completion: nil) viewController.completionWithItemsHandler = { type, ok, items, err in //Return if cancelled if (!ok) { return } //activity completed self.save() } } func reset() { topTextField.text = "TOP" bottomTextField.text = "BOTTOM" imagePickerView.image = nil shareButton.isEnabled = false } func save() { let meme = Meme(topText:topTextField.text!, bottomText:bottomTextField.text!, originalImage:imagePickerView.image!, memeImage:generateMemedImage()) // Add it to the memes array in the Application Delegate let object = UIApplication.shared.delegate let appDelegate = object as! AppDelegate appDelegate.memes.append(meme) } } <file_sep>/CollectionViewController.swift // // CollectionViewController.swift // MemeMe // // Created by <NAME> on 11/13/16. // Copyright ยฉ 2016 <NAME>. All rights reserved. // import UIKit class CollectionViewController: UICollectionViewController { var memes: [Meme]! override func viewDidLoad() { super.viewDidLoad() let applicationDelegate = (UIApplication.shared.delegate as! AppDelegate) memes = applicationDelegate.memes // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.memes.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) let meme = self.memes[(indexPath as NSIndexPath).row] // Set the image //cell.imageView?.image = meme.memeImage return cell } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } <file_sep>/MemeMe/TableViewController.swift // // TableViewController.swift // MemeMe // // Created by <NAME> on 11/13/16. // Copyright ยฉ 2016 <NAME>. All rights reserved. // import UIKit class TableViewController: UITableViewController { var memes: [Meme]! override func viewDidLoad() { super.viewDidLoad() let applicationDelegate = (UIApplication.shared.delegate as! AppDelegate) memes = applicationDelegate.memes // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.memes.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "TableCell")! let meme = self.memes[(indexPath as NSIndexPath).row] // Set the image cell.imageView?.image = meme.memeImage return cell } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
2b04addd28b737a3036170c8b989d46f59bf3e10
[ "Swift" ]
3
Swift
Zintori/MemeMe
c62ab6b7d6d0d5163fb23dee370d8f484fa546a1
6af5395f3fa5232cdace5e2db9977c0cb2af93e6
refs/heads/master
<repo_name>shiv-am117/todo_react<file_sep>/todo/src/components/item.js import React, { Component } from "react"; import "./item.css"; class Item extends Component { state = { task: this.props.task, classes: "normal" }; handledone = () => { this.setState({ classes: "del" }); }; handleundone = () => { this.setState({ classes: "normal" }); }; render() { return ( <div> <span className="badge badge-secondary m-2 ">{this.props.id + 1}</span> <span className={this.state.classes}>{this.state.task}</span> <button className="btn btn-warning btn-sm " onClick={this.handledone}> Done </button> <button className="btn btn-danger btn-sm " onClick={this.handleundone}> Undone </button> </div> ); } } export default Item; <file_sep>/todo/src/App.js import React, { Component } from "react"; import Item from "./components/item.js"; import "./App.css"; class App extends Component { state = { value: "", id: 0, list: [] }; additem = () => { let listcopy = this.state.list; let idcopy = this.state.id; idcopy++; if (this.state.value !== "") listcopy.push(this.state.value); this.setState({ value: "", id: idcopy, list: listcopy }); }; addvalue = e => { this.setState({ value: e.target.value }); }; render() { return ( <div> <input className="input m-2" value={this.state.value} onChange={this.addvalue} type="text" placeholder="Enter the task" /> <button onClick={this.additem} className="btn btn-primary btn-sm m-2"> Add </button> <ul> {this.state.list.map(each => ( <li> <Item task={each} id={this.state.list.indexOf(each)} /> </li> ))} </ul> </div> ); } } export default App;
369c966a54813f5d993d8d40d7c5bd56254a1ad1
[ "JavaScript" ]
2
JavaScript
shiv-am117/todo_react
4bb8b23155e648eb5f51d7ccbcf1f70bb0e7e44c
60e459a2ab0aa4afc90449633d1d41ea983580dd
refs/heads/master
<repo_name>tinashechihoro/foodtasker<file_sep>/foodtasker/urls.py from django.conf.urls import url from django.contrib import admin from django.contrib.auth import views as auth_views from django.conf.urls.static import static from django.conf import settings from foodtaskerapp import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.home, name='home'), url(r'^restaurant/sign-in/$', auth_views.login, {'template_name': 'restaurant/sign_in.html'}, name='restaurant-sign-in'), url(r'^restaurant/sign-out/$', auth_views.logout, {'next_page': '/'}, name='restaurant-sign-out'), url(r'^restaurant/$', views.restaurant_home, name='restaurant_home'), url(r'^restaurant/sign-up/$', views.restaurant_sign_up, name='restaurant-sign-up'), ]+ static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) <file_sep>/foodtaskerapp/admin.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from foodtaskerapp.models import Restaurant admin.site.register(Restaurant) <file_sep>/foodtaskerapp/views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib.auth import authenticate,login from django.contrib.auth.models import User from foodtaskerapp.forms import UserForm, RestaurantForm def home(request): """home page""" return redirect(restaurant_home) @login_required(login_url='/restaurant/sign-in/') def restaurant_home(request): """restaurant_home""" return render(request, 'restaurant/home.html', {}) def restaurant_sign_up(request): """restaurant_sign_up""" user_form = UserForm() restaurant_form = RestaurantForm() if request.method == 'POST': user_form = UserForm(request.POST) restaurant_form = RestaurantForm(request.POST,request.FILES) if user_form.is_valid() and restaurant_form.is_valid(): new_user = User.objects.create_user(**user_form.cleaned_data) new_restaurant = restaurant_form.save(commit=False) new_restaurant.user = new_user new_restaurant.save() login(request,authenticate( username = user_form.cleaned_data['username'], password = user_form.cleaned_data['<PASSWORD>'] )) return redirect(restaurant_home) return render(request, 'restaurant/sign-up.html', {"user_form": user_form, "restaurant_form": restaurant_form }) <file_sep>/requirements.txt dj-database-url==0.5.0 Django==1.11.2 gunicorn==19.6.0 Pillow==3.1.2 psycogreen==1.0 psycopg2==2.7.4 whitenoise==3.2.1
5da6c0d9798c00e39ca71b79712010c7adecb396
[ "Python", "Text" ]
4
Python
tinashechihoro/foodtasker
9191dd10dd111cc410ae05a0eb83846556fcb3b4
5825701d3a10bd4ac8d577c5139b62c13c7adcab
refs/heads/master
<repo_name>indre93/fewpjs-document-onload-online-web-sp-000<file_sep>/index.js // Your code goes here document.addEventListener("DOMContentLoaded", function () { document.querySelector('p#text').textContent = "This is really cool!"; });
9f5a4aba28b7c87444059b8a38450b4116402d2a
[ "JavaScript" ]
1
JavaScript
indre93/fewpjs-document-onload-online-web-sp-000
766670b5bf52769ae063c3ac3c332bf83be661c9
98ed018a10755f56266818b80c3b284582a11517
refs/heads/master
<file_sep>var keystone = require('keystone'), Types = keystone.Field.Types; /** * StudentProject Model * ========== */ var StudentProject = new keystone.List('StudentProject', { map: { name: 'title' }, autokey: { path: 'slug', from: 'title', unique: true } }); StudentProject.add({ title: { type: String}, name: { type: String}, qualification: {type: Types.Select, options: 'Honors, Masters, PhD, PhD Candidate', default: 'Honors'}, yearOfCompletion: {type: Types.Select, options: 'pending, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020', default: 'pending'}, principalSupervisor: {type: String, default: 'Principal supervisor'}, associateSupervisor: {type: String, default: 'Associate supervisor'}, externalSupervisor: {type: String, default: 'External supervisor'}, state: { type: Types.Select, options: 'draft, published, archived', default: 'draft', index: true }, image: { type: Types.CloudinaryImage }, content: { brief: { type: Types.Html, wysiwyg: true, height: 150 }, extended: { type: Types.Html, wysiwyg: true, height: 400 }, }, categories: { type: Types.Relationship, ref: 'StudentProjectCategory', many: true } }); StudentProject.schema.virtual('content.full').get(function() { return this.content.extended || this.content.brief; }); StudentProject.defaultColumns = 'name|20%, qualification|20% ,title|50%, state|10%'; StudentProject.register(); <file_sep>var keystone = require('keystone'), Types = keystone.Field.Types; /** * Team Model * ========== */ var Team = new keystone.List('Team', { map: { name: 'name' }, autokey: { path: 'slug', from: 'name', unique: true } }); Team.add({ name: { type: String}, position: {type: String}, role: {type: String}, priority: {type: String, required: true, default: '0'}, state: { type: Types.Select, options: 'draft, published, archived', default: 'draft', index: true }, image: { type: Types.CloudinaryImage }, discription: { type: Types.Html, wysiwyg: true, height: 150 }, categories: { type: Types.Relationship, ref: 'TeamCategory', many: true } }); Team.schema.virtual('content.full').get(function() { return this.content.extended || this.content.brief; }); Team.defaultColumns = 'title, priority, state|20%, author|20%, publishedDate|20%'; Team.register(); <file_sep>var keystone = require('keystone'); /** * Team Category Model * ================== */ var TeamCategory = new keystone.List('TeamCategory', { autokey: { from: 'name', path: 'key', unique: true }, }); TeamCategory.add({ name: { type: String, required: true }, priority: {type: String, required: true, default: '0'}, }); TeamCategory.relationship({ ref: 'Team', path: 'categories' }); TeamCategory.register(); <file_sep>var keystone = require('keystone'); var Types = keystone.Field.Types; /** * HomeSlider Model * ========== */ var HomeSlider = new keystone.List('HomeSlider', { map: { name: 'title' }, autokey: { path: 'slug', from: 'title', unique: true }, }); HomeSlider.add({ title: { type: String, index: true, required: true }, state: { type: Types.Select, options: 'draft, published, archived', default: 'draft', index: true }, image1: { type: Types.CloudinaryImage }, image2: { type: Types.CloudinaryImage }, image3: { type: Types.CloudinaryImage }, image4: { type: Types.CloudinaryImage }, image5: { type: Types.CloudinaryImage }, }); HomeSlider.schema.virtual('content.full').get(function () { return this.content.extended || this.content.brief; }); HomeSlider.defaultColumns = 'title, state|20%'; HomeSlider.register(); <file_sep>var keystone = require('keystone'); var Types = keystone.Field.Types; /** * Publication Model * ========== */ var Publication = new keystone.List('Publication', { map: { name: 'refrence' }, autokey: { path: 'slug', from: 'refrence', unique: true }, }); Publication.add({ refrence: { type: String, required: true }, state: { type: Types.Select, options: 'draft, published, archived', default: 'draft', index: true }, link: { type: String}, linktext: { type: String}, categories: { type: Types.Relationship, ref: 'PublicationCategory', many: true }, }); Publication.schema.virtual('content.full').get(function () { return this.content.extended || this.content.brief; }); Publication.defaultColumns = 'title, state|20%, author|20%, publishedDate|20%'; Publication.register(); <file_sep># indiknowtech New Indiknowtech website
326ed0d5cbc5007e383c05dc9ea38cc0c94d4b5c
[ "JavaScript", "Markdown" ]
6
JavaScript
BertieC/indiknowtech
f606fcb4008c0dcb3a44601f309c4c8932889ae3
dd4f3c29f8e25967f0dfd0ff4f10a215f0e193c4
refs/heads/master
<repo_name>daniloprandi/Edilpiu<file_sep>/AttrezziElenco.aspx.cs ๏ปฟusing System; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Web.UI.WebControls; public partial class AttrezziElenco : System.Web.UI.Page { SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ToString()); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { conn.Open(); SqlCommand cmd = new SqlCommand("select count(*) from Attrezzi", conn); txtAttrezziTotTrov.Text = cmd.ExecuteScalar().ToString(); cmd.Dispose(); conn.Close(); SqlDataAdapter da = new SqlDataAdapter("select id_Attrezzi, descrizione_Attrezzi, note_Attrezzi, quantita_Attrezzi " + "from Attrezzi", conn); DataSet ds = new DataSet(); da.Fill(ds); gvElencoAttrezzi.DataSource = ds; gvElencoAttrezzi.DataBind(); da.Dispose(); conn.Close(); } } protected void btnTrovaAttrezzo_Click(object sender, EventArgs e) { conn.Open(); using (SqlCommand cmd = new SqlCommand("select id_Attrezzi, descrizione_Attrezzi, quantita_Attrezzi, note_Attrezzi " + " from Attrezzi where descrizione_Attrezzi like @descr", conn)) { cmd.Parameters.AddWithValue("@descr", txtTrovaDescrizione.Text + "%"); using (SqlDataReader dr = cmd.ExecuteReader()) { gvElencoAttrezzi.DataSource = dr; gvElencoAttrezzi.DataBind(); lblAttrezziTotTrov.Text = "attrezzi trovati: "; } cmd.CommandText = "select COUNT(*) from Attrezzi where descrizione_Attrezzi like @desc"; cmd.Parameters.Add("@desc", SqlDbType.NVarChar, 255).Value = txtTrovaDescrizione.Text + "%"; txtAttrezziTotTrov.Text = cmd.ExecuteScalar().ToString(); } conn.Close(); } protected void btnModifica_Click(object sender, EventArgs e) { string idAttrezzi = ((Button)sender).CommandArgument.ToString(); Response.Redirect("AttrezziNuovo.aspx?id_Attrezzi=" + idAttrezzi); } }<file_sep>/UtenteElenco.aspx.cs ๏ปฟusing System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class UtenteElenco : System.Web.UI.Page { SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ToString()); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { conn.Open(); SqlCommand cmd = new SqlCommand("select count(*) from Utenti", conn); txtUtentiTotTrov.Text = cmd.ExecuteScalar().ToString(); conn.Close(); SqlDataAdapter da = new SqlDataAdapter("select id_Utenti, cognome_Utenti, nome_Utenti, data_nascita_Utenti, " + " nome_Nazioni, codice_fiscale_Utenti from Utenti u inner join Nazioni n on u.id_Nazioni = n.id_Nazioni " + "order by cognome_Utenti, codice_fiscale_Utenti", conn); DataSet ds = new DataSet(); da.Fill(ds); gvElencoUtenti.DataSource = ds; gvElencoUtenti.DataBind(); } } protected void btnModifica_Click(object sender, EventArgs e) { string idUtenti = ((Button)sender).CommandArgument.ToString(); Response.Redirect("UtenteNuovo.aspx?id_Utenti=" + idUtenti); } protected void btnVisualizza_Click(object sender, EventArgs e) { } protected void btnTrovaUtente_Click(object sender, EventArgs e) { SqlCommand cmd = new SqlCommand("select id_Utenti, cognome_Utenti, nome_Utenti, data_nascita_Utenti, " + " nome_Nazioni, codice_fiscale_Utenti from Utenti u inner join Nazioni n on u.id_Nazioni = n.id_Nazioni where " + " cognome_Utenti like @cognome and nome_Utenti like @nome and codice_fiscale_Utenti like @cf", conn); cmd.Parameters.AddWithValue("@cognome", txtTrovaCognome.Text + "%"); cmd.Parameters.AddWithValue("@nome", txtTrovaNome.Text + "%"); cmd.Parameters.AddWithValue("@cf", txtTrovaCodiceFiscale.Text + "%"); conn.Open(); SqlDataReader dr = cmd.ExecuteReader(); gvElencoUtenti.DataSource = dr; gvElencoUtenti.DataBind(); lblUtentiTotTrov.Text = "utenti trovati: "; dr.Close(); dr.Dispose(); cmd.Dispose(); cmd = new SqlCommand("select COUNT(*) from Utenti where cognome_Utenti like @cognome and nome_Utenti like @nome and " + " codice_fiscale_Utenti like @cf ", conn); cmd.Parameters.AddWithValue("@cognome", txtTrovaCognome.Text + "%"); cmd.Parameters.AddWithValue("@nome", txtTrovaNome.Text + "%"); cmd.Parameters.AddWithValue("@cf", txtTrovaCodiceFiscale.Text + "%"); txtUtentiTotTrov.Text = cmd.ExecuteScalar().ToString(); cmd.Dispose(); conn.Close(); } }<file_sep>/AttrezziNuovo.aspx.cs ๏ปฟusing System; using System.Configuration; using System.Data; using System.Data.SqlClient; public partial class AttrezziNuovo : System.Web.UI.Page { SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ToString()); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { conn.Open(); if (Request.QueryString["id_Attrezzi"] != null) { int idAttrezzi; lblInsModAttrezzo.Text = "MODIFICA ATTREZZO"; btnSalvaAggiorna.Text = "AGGIORNA"; if (Int32.TryParse(Request.QueryString["id_Attrezzi"].ToString(), out idAttrezzi)) { using (SqlCommand cmd = new SqlCommand("select * from Attrezzi where id_Attrezzi = @idAttrezzi", conn)) { cmd.Parameters.Add("@idAttrezzi", System.Data.SqlDbType.Int).Value = idAttrezzi; using (SqlDataReader dr = cmd.ExecuteReader()) { if (dr.HasRows) { dr.Read(); txtDescrizione.Text = dr["descrizione_Attrezzi"].ToString(); txtQta.Text = dr["quantita_Attrezzi"].ToString(); txtNote.Text = dr["note_Attrezzi"].ToString(); } } } } } conn.Close(); } } protected void btnSalvaAggiorna_Click(object sender, EventArgs e) { lblErrori.Text = ""; if (txtDescrizione.Text.Trim() == "") { if (lblErrori.Text == "") lblErrori.Text = "<br>Il campo <b>DESCRIZIONE</b> รจ obbligatorio<br>"; else lblErrori.Text += lblErrori.Text + "<br>Il campo <b>DESCRIZIONE</b> รจ obbligatorio<br>"; } if (txtQta.Text.Trim() == "") { if (lblErrori.Text == "") lblErrori.Text = "<br>Il campo <b>QUANTITA'</b> รจ obbligatorio<br>"; else lblErrori.Text += lblErrori.Text + "<br>Il campo <b>QUANTITA'</b> รจ obbligatorio<br>"; } if (lblErrori.Text != "") return; conn.Open(); if (Request.QueryString["id_Attrezzi"] == null) { using (SqlCommand cmd = new SqlCommand("IF((SELECT COUNT(*) FROM Attrezzi WHERE descrizione_Attrezzi = @descr) > 0) " + "BEGIN SET @res = 'K1' RETURN END DECLARE @id AS INT SELECT @id = ISNULL(MAX(id_Attrezzi), 0) + 1 FROM Attrezzi " + "INSERT INTO Attrezzi (id_Attrezzi, descrizione_Attrezzi, note_Attrezzi, quantita_Attrezzi) values(@id, @descr, @note, " + "@qta) SET @res = 'OK'", conn)) { cmd.Parameters.Add("@descr", SqlDbType.NVarChar, 255).Value = txtDescrizione.Text; cmd.Parameters.Add("@note", SqlDbType.Text).Value = txtNote.Text; cmd.Parameters.Add("@qta", SqlDbType.Int).Value = txtQta.Text; cmd.Parameters.Add("@res", SqlDbType.Char, 2).Direction = ParameterDirection.Output; cmd.ExecuteNonQuery(); string res = cmd.Parameters["@res"].Value.ToString(); if (res == "OK") Response.Redirect("AttrezziElenco.aspx"); else Response.Write("<b>Attrezzo con descrizione: " + txtDescrizione.Text + "</b> giร  presente nel database. Attrezzo " + "non inserito.<br><br>"); } } else { using (SqlCommand cmd = new SqlCommand("update Attrezzi set descrizione_Attrezzi = @descr, note_Attrezzi = @note, " + " quantita_Attrezzi = @qta where id_Attrezzi = @id", conn)) { cmd.Parameters.Add("@descr", SqlDbType.NVarChar, 255).Value = txtDescrizione.Text; cmd.Parameters.Add("@note", SqlDbType.Text).Value = txtNote.Text; cmd.Parameters.Add("@qta", SqlDbType.Int).Value = txtQta.Text; cmd.Parameters.Add("@id", SqlDbType.Int).Value = Request.QueryString["id_Attrezzi"].ToString(); cmd.ExecuteNonQuery(); Response.Redirect("AttrezziElenco.aspx"); } } conn.Close(); } protected void btnAnnulla_Click(object sender, EventArgs e) { txtDescrizione.Text = ""; txtQta.Text = ""; txtNote.Text = ""; } }<file_sep>/Menu_Iniziale.aspx.cs ๏ปฟusing System; using System.Collections.Generic; using System.Configuration; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Menu_Iniziale : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void lkbNuovoUtente_Click(object sender, EventArgs e) { Response.Redirect("UtenteNuovo.aspx"); } protected void lkbModificaUtente_Click(object sender, EventArgs e) { } protected void lkbElencoUtenti_Click(object sender, EventArgs e) { Response.Redirect("UtenteElenco.aspx"); } protected void lkbCancellaUtente_Click(object sender, EventArgs e) { } protected void lkbNuovoRuolo_Click(object sender, EventArgs e) { } protected void lkbModificaRuolo_Click(object sender, EventArgs e) { } protected void lkbElencoRuoli_Click(object sender, EventArgs e) { } protected void lkbCancellaRuolo_Click(object sender, EventArgs e) { } protected void lbkNuovoCantiere_Click(object sender, EventArgs e) { } protected void lkbModificaCantiere_Click(object sender, EventArgs e) { } protected void lkbElencoCantieri_Click(object sender, EventArgs e) { } protected void lkbCancellaCantiere_Click(object sender, EventArgs e) { } protected void lkbNuovoMezzo_Click(object sender, EventArgs e) { } protected void lkbModificaMezzo_Click(object sender, EventArgs e) { } protected void lkbElencoMezzi_Click(object sender, EventArgs e) { } protected void lkbCancellaMezzo_Click(object sender, EventArgs e) { } protected void lkbNuovoAttrezzo_Click(object sender, EventArgs e) { Response.Redirect("AttrezziNuovo.aspx"); } protected void lkbModificaAttrezzo_Click(object sender, EventArgs e) { } protected void lkbElencoAttrezzi_Click(object sender, EventArgs e) { Response.Redirect("AttrezziElenco.aspx"); } protected void lkbCancellaAttrezzi_Click(object sender, EventArgs e) { } }<file_sep>/UtenteNuovo.aspx.cs ๏ปฟusing System; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Web.UI.WebControls; public partial class UtenteNuovo : System.Web.UI.Page { SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ToString()); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { conn.Open(); SqlCommand cmd = new SqlCommand("select * from sessi", conn); SqlDataReader dr = cmd.ExecuteReader(); ListItem li = new ListItem("- SELEZIONA -", ""); ddlSesso.Items.Add(li); while (dr.Read()) { li = new ListItem(dr["descrizione_Sessi"].ToString(), dr["id_Sessi"].ToString()); ddlSesso.Items.Add(li); } dr.Close(); cmd.Dispose(); cmd = new SqlCommand("select * from Nazioni", conn); dr = cmd.ExecuteReader(); li = new ListItem("- SELEZIONA -", ""); ddlNazionalita.Items.Add(li); while (dr.Read()) { li = new ListItem(dr["nome_Nazioni"].ToString(), dr["id_Nazioni"].ToString()); ddlNazionalita.Items.Add(li); } dr.Close(); cmd.Dispose(); cmd = new SqlCommand("select * from [Indirizzi.Tipologia]", conn); dr = cmd.ExecuteReader(); li = new ListItem("- SELEZIONA -", ""); ddlIndirizzoTip.Items.Add(li); while (dr.Read()) { li = new ListItem(dr["descrizione_IndirizziTipologia"].ToString(), dr["id_IndirizziTipologia"].ToString()); ddlIndirizzoTip.Items.Add(li); } dr.Close(); cmd.Dispose(); cmd = new SqlCommand("select * from [Indirizzi.Tipologia]", conn); dr = cmd.ExecuteReader(); li = new ListItem("- SELEZIONA -", ""); ddlIndirizzoTip2.Items.Add(li); while (dr.Read()) { li = new ListItem(dr["descrizione_IndirizziTipologia"].ToString(), dr["id_IndirizziTipologia"].ToString()); ddlIndirizzoTip2.Items.Add(li); } dr.Close(); cmd.Dispose(); cmd = new SqlCommand("select * from Province", conn); dr = cmd.ExecuteReader(); li = new ListItem("- SELEZIONA -", ""); ddlProvincia.Items.Add(li); while (dr.Read()) { li = new ListItem(dr["nome_Province"].ToString(), dr["id_Province"].ToString()); ddlProvincia.Items.Add(li); } dr.Close(); cmd.Dispose(); cmd = new SqlCommand("select * from Province", conn); dr = cmd.ExecuteReader(); li = new ListItem("- SELEZIONA -", ""); ddlProvincia2.Items.Add(li); while (dr.Read()) { li = new ListItem(dr["nome_Province"].ToString(), dr["id_Province"].ToString()); ddlProvincia2.Items.Add(li); } dr.Close(); cmd.Dispose(); cmd = new SqlCommand("select * from Nazioni", conn); dr = cmd.ExecuteReader(); li = new ListItem("- SELEZIONA -", ""); ddlNazione.Items.Add(li); while (dr.Read()) { li = new ListItem(dr["nome_Nazioni"].ToString(), dr["id_Nazioni"].ToString()); ddlNazione.Items.Add(li); } dr.Close(); cmd.Dispose(); cmd = new SqlCommand("select * from Nazioni", conn); dr = cmd.ExecuteReader(); li = new ListItem("- SELEZIONA -", ""); ddlNazione2.Items.Add(li); while (dr.Read()) { li = new ListItem(dr["nome_Nazioni"].ToString(), dr["id_Nazioni"].ToString()); ddlNazione2.Items.Add(li); } dr.Close(); cmd.Dispose(); //cmd = new SqlCommand("select descrizione_Ruoli, id_Ruoli from Ruoli", conn); //dr = cmd.ExecuteReader(); //li = new ListItem("- SELEZIONA -", ""); //lbxRuoli.Items.Add(li); //while (dr.Read()) //{ // li = new ListItem(dr["descrizione_Ruoli"].ToString(), dr["id_Ruoli"].ToString()); // lbxRuoli.Items.Add(li); //} //dr.Close(); //cmd.Dispose(); cmd = new SqlCommand("select descrizione_Ruoli, id_Ruoli from Ruoli", conn); dr = cmd.ExecuteReader(); li = new ListItem("- SELEZIONA -", ""); ddlRuolo1.Items.Add(li); while (dr.Read()) { li = new ListItem(dr["descrizione_Ruoli"].ToString(), dr["id_Ruoli"].ToString()); ddlRuolo1.Items.Add(li); } dr.Close(); cmd.Dispose(); cmd = new SqlCommand("select descrizione_Ruoli, id_Ruoli from Ruoli", conn); dr = cmd.ExecuteReader(); li = new ListItem("- SELEZIONA -", ""); ddlRuolo2.Items.Add(li); while (dr.Read()) { li = new ListItem(dr["descrizione_Ruoli"].ToString(), dr["id_Ruoli"].ToString()); ddlRuolo2.Items.Add(li); } dr.Close(); cmd.Dispose(); cmd = new SqlCommand("select descrizione_Ruoli, id_Ruoli from Ruoli", conn); dr = cmd.ExecuteReader(); li = new ListItem("- SELEZIONA -", ""); ddlRuolo3.Items.Add(li); while (dr.Read()) { li = new ListItem(dr["descrizione_Ruoli"].ToString(), dr["id_Ruoli"].ToString()); ddlRuolo3.Items.Add(li); } dr.Close(); cmd.Dispose(); if (Request.QueryString["id_Utenti"] != null) { lblInsModUtente.Text = "MODIFICA UTENTE"; btnSalvaAggiorna.Text = "AGGIORNA DATI"; int id = -1; if (Int32.TryParse(Request.QueryString["id_Utenti"].ToString(), out id)) { cmd = new SqlCommand("select * from Utenti where id_Utenti = @id", conn); cmd.Parameters.Add("@id", SqlDbType.Int).Value = id; dr = cmd.ExecuteReader(); if (dr.HasRows) { dr.Read(); txtCognome.Text = dr["cognome_Utenti"].ToString(); txtNome.Text = dr["nome_Utenti"].ToString(); txtDataNascita.Text = dr["data_nascita_Utenti"].ToString(); ddlSesso.Items[ddlSesso.SelectedIndex].Selected = false; ddlSesso.Items.FindByValue(dr["id_Sessi"].ToString()).Selected = true; ddlNazionalita.Items[ddlNazionalita.SelectedIndex].Selected = false; ddlNazionalita.Items.FindByValue(dr["id_Nazioni"].ToString()).Selected = true; txtCodiceFiscale.Text = dr["codice_fiscale_Utenti"].ToString(); txtCodiceFiscale.Enabled = false; txtTelefono.Text = dr["telefono_Utenti"].ToString(); txtEmail.Text = dr["email_Utenti"].ToString(); txtUserName.Text = dr["username_Utenti"].ToString(); txtPassword.Text = dr["<PASSWORD>"].ToString(); txtNote.Text = dr["note_Utenti"].ToString(); } dr.Close(); cmd.Dispose(); cmd = new SqlCommand("select * from Indirizzi where id_Utenti = @id", conn); cmd.Parameters.Add("@id", SqlDbType.Int).Value = id; dr = cmd.ExecuteReader(); if (dr.HasRows) { dr.Read(); ddlIndirizzoTip.Items[ddlIndirizzoTip.SelectedIndex].Selected = false; ddlIndirizzoTip.Items.FindByValue(dr["id_IndirizziTipologia"].ToString()).Selected = true; txtVia.Text = dr["via_Indirizzi"].ToString(); txtCap.Text = dr["cap_Indirizzi"].ToString(); txtCitta.Text = dr["citta_Indirizzi"].ToString(); ddlProvincia.Items[ddlProvincia.SelectedIndex].Selected = false; ddlProvincia.Items.FindByValue(dr["id_Province"].ToString()).Selected = true; ddlNazione.Items[ddlNazione.SelectedIndex].Selected = false; ddlNazione.Items.FindByValue(dr["id_Nazioni"].ToString()).Selected = true; if (dr.Read()) { tblIndirizzo2.Visible = true; ddlIndirizzoTip2.Items[ddlIndirizzoTip2.SelectedIndex].Selected = false; ddlIndirizzoTip2.Items.FindByValue(dr["id_IndirizziTipologia"].ToString()).Selected = true; txtVia2.Text = dr["via_Indirizzi"].ToString(); txtCap2.Text = dr["cap_Indirizzi"].ToString(); txtCitta2.Text = dr["citta_Indirizzi"].ToString(); ddlProvincia2.Items[ddlProvincia.SelectedIndex].Selected = false; ddlProvincia2.Items.FindByValue(dr["id_Province"].ToString()).Selected = true; ddlNazione2.Items[ddlNazione.SelectedIndex].Selected = false; ddlNazione2.Items.FindByValue(dr["id_Nazioni"].ToString()).Selected = true; } } } dr.Close(); cmd.Dispose(); cmd = new SqlCommand("select * from [Utenti.Ruoli] where id_Utenti = @id", conn); cmd.Parameters.Add("@id", SqlDbType.Int).Value = id; dr = cmd.ExecuteReader(); if (dr.HasRows) { dr.Read(); ddlRuolo1.Items[ddlRuolo1.SelectedIndex].Selected = false; ddlRuolo1.Items.FindByValue(dr["id_Ruoli"].ToString()).Selected = true; if (dr.Read()) { lblRuolo2.Visible = true; ddlRuolo2.Visible = true; btnAggiungiRuolo3.Visible = true; ddlRuolo2.Items[ddlRuolo2.SelectedIndex].Selected = false; ddlRuolo2.Items.FindByValue(dr["id_Ruoli"].ToString()).Selected = true; } if (dr.Read()) { lblRuolo3.Visible = true; ddlRuolo3.Visible = true; ddlRuolo3.Items[ddlRuolo3.SelectedIndex].Selected = false; ddlRuolo3.Items.FindByValue(dr["id_Ruoli"].ToString()).Selected = true; } } dr.Close(); cmd.Dispose(); } conn.Close(); } } protected void btnSalvaAggiorna_Click(object sender, EventArgs e) { lblErrori.Text = ""; if (txtCognome.Text.Trim() == "") lblErrori.Text = "Il campo <b>COGNOME</b> รจ obbligatorio<br>"; if (txtNome.Text.Trim() == "") { if (lblErrori.Text == "") lblErrori.Text = "Il campo <b>NOME</ b > รจ obbligatorio<br>"; else lblErrori.Text += lblErrori.Text + "Il campo <b>NOME</b> รจ obbligatorio<br>"; } if (txtDataNascita.Text.Trim() == "") { if (lblErrori.Text == "") lblErrori.Text = "Il campo <b>DATA DI NASCITA</b> รจ obbligatorio<br>"; else lblErrori.Text = lblErrori.Text + "Il campo <b>DATA DI NASCITA</b> รจ obbligatorio<br>"; } if (!(ddlNazionalita.SelectedIndex > 0)) { if (lblErrori.Text == "") lblErrori.Text = "Il campo <b>NAZIONALITA'</b> รจ obbligatorio<br>"; else lblErrori.Text = lblErrori.Text + "Il campo <b>NAZIONALITA'</b> รจ obbligatorio<br>"; } if (txtCodiceFiscale.Text.Trim() == "") { if (lblErrori.Text == "") lblErrori.Text = "Il campo <b>CODICE FISCALE</b> รจ obbligatorio<br>"; else lblErrori.Text = lblErrori.Text + "Il campo <b>CODICE FISCALE</b> รจ obbligatorio<br>"; } else { char[] cf = txtCodiceFiscale.Text.Trim().ToCharArray(); // VERIFICO LUNGHEZZA CODICE FISCALE if (cf.Length != 16) { if (lblErrori.Text == "") lblErrori.Text = "La lunghezza del <b>CODICE FISCALE</b> รจ sbagliata<br>"; else lblErrori.Text = lblErrori.Text + "La lunghezza del <b>CODICE FISCALE</b> รจ sbagliata<br>"; return; } byte[] cfAscii = System.Text.Encoding.ASCII.GetBytes( txtCodiceFiscale.Text.Trim().ToUpper()); // controllo che i primi sei caratteri siamo lettere for (int i = 0; i < 6; i++) { if ((cfAscii[i] >= 65) && (cfAscii[i] <= 90)) continue; else { if (lblErrori.Text == "") lblErrori.Text = "Il formato del <b>CODICE FISCALE</b> รจ sbagliato<br>"; else lblErrori.Text = lblErrori.Text + "Il formato del <b>CODICE FISCALE</b> รจ sbagliato<br>"; break; } } if (!((cfAscii[6] >= 48) && (cfAscii[6] <= 57) && (cfAscii[7] >= 48) && (cfAscii[7] <= 57))) { if (lblErrori.Text == "") lblErrori.Text = "Il formato del <b>CODICE FISCALE</b> รจ sbagliato<br>"; else lblErrori.Text = lblErrori.Text + "Il formato del <b>CODICE FISCALE</b> รจ sbagliato<br>"; } if (!((cfAscii[8] >= 65) && (cfAscii[8] <= 90))) { if (lblErrori.Text == "") lblErrori.Text = "Il formato del <b>CODICE FISCALE</b> รจ sbagliato<br>"; else lblErrori.Text = lblErrori.Text + "Il formato del <b>CODICE FISCALE</b> รจ sbagliato<br>"; } if (!((cfAscii[9] >= 48) && (cfAscii[9] <= 57) && (cfAscii[10] >= 48) && (cfAscii[10] <= 57))) { if (lblErrori.Text == "") lblErrori.Text = "Il formato del <b>CODICE FISCALE</b> รจ sbagliato<br>"; else lblErrori.Text = lblErrori.Text + "Il formato del <b>CODICE FISCALE</b> รจ sbagliato<br>"; } if (!((cfAscii[11] >= 65) && (cfAscii[11] <= 90))) { if (lblErrori.Text == "") lblErrori.Text = "Il formato del <b>CODICE FISCALE</b> รจ sbagliato<br>"; else lblErrori.Text = lblErrori.Text + "Il formato del <b>CODICE FISCALE</b> รจ sbagliato<br>"; } if (!((cfAscii[12] >= 48) && (cfAscii[12] <= 57) && (cfAscii[13] >= 48) && (cfAscii[13] <= 57) && (cfAscii[14] >= 48) && (cfAscii[14] <= 57))) { if (lblErrori.Text == "") lblErrori.Text = "Il formato del <b>CODICE FISCALE</b> รจ sbagliato<br>"; else lblErrori.Text = lblErrori.Text + "Il formato del <b>CODICE FISCALE</b> รจ sbagliato<br>"; } } if (!(ddlIndirizzoTip.SelectedIndex > 0)) { if (lblErrori.Text == "") lblErrori.Text = "Il campo <b>TIPOLOGIA INDIRIZZO</b> dell'indirizzo 1 รจ obbligatorio<br>"; else lblErrori.Text = lblErrori.Text + "Il campo <b>TIPOLOGIA INDIRIZZO</b> dell'indirizzo 1 รจ obbligatorio<br>"; } if (txtVia.Text.Trim() == "") { if (lblErrori.Text == "") lblErrori.Text = "Il campo <b>VIA</b> dell'indirizzo 1 รจ obbligatorio<br>"; else lblErrori.Text = lblErrori.Text + "Il campo <b>VIA</b> dell'indirizzo 1 รจ obbligatorio<br>"; } if (txtCap.Text.Trim() == "") { if (lblErrori.Text == "") lblErrori.Text = "Il campo <b>CAP</b> dell'indirizzo 1 รจ obbligatorio<br>"; else lblErrori.Text = lblErrori.Text + "Il campo <b>CAP</b> dell'indirizzo 1 รจ obbligatorio<br>"; } if (txtCitta.Text.Trim() == "") { if (lblErrori.Text == "") lblErrori.Text = "Il campo <b>CITTA'</b> dell'indirizzo 1 รจ obbligatorio<br>"; else lblErrori.Text = lblErrori.Text + "Il campo <b>CITTA'</b> dell'indirizzo 1 รจ obbligatorio<br>"; } if (!(ddlProvincia.SelectedIndex > 0)) { if (lblErrori.Text == "") lblErrori.Text = "Il campo <b>PROVINCIA</b> dell'indirizzo 1 รจ obbligatorio<br>"; else lblErrori.Text = lblErrori.Text + "Il campo <b>NAZIONALITA'</b> dell'indirizzo 1 รจ obbligatorio<br>"; } if (!(ddlNazione.SelectedIndex > 0)) { if (lblErrori.Text == "") lblErrori.Text = "Il campo <b>PROVINCIA</b> dell'indirizzo 1 รจ obbligatorio<br>"; else lblErrori.Text = lblErrori.Text + "Il campo <b>NAZIONALITA'</b> dell'indirizzo 1 รจ obbligatorio<br>"; } if (tblIndirizzo2.Visible == true) { if (!(ddlIndirizzoTip2.SelectedIndex > 0)) { if (lblErrori.Text == "") lblErrori.Text = "Il campo <b>TIPOLOGIA INDIRIZZO</b> dell'indirizzo 2 รจ obbligatorio<br>"; else lblErrori.Text = lblErrori.Text + "Il campo <b>TIPOLOGIA INDIRIZZO</b> dell'indirizzo 2 รจ obbligatorio<br>"; } if (txtVia2.Text.Trim() == "") { if (lblErrori.Text == "") lblErrori.Text = "Il campo <b>VIA</b> dell'indirizzo 2 รจ obbligatorio<br>"; else lblErrori.Text = lblErrori.Text + "Il campo <b>VIA</b> dell'indirizzo 2 รจ obbligatorio<br>"; } if (txtCap2.Text.Trim() == "") { if (lblErrori.Text == "") lblErrori.Text = "Il campo <b>CAP</b> dell'indirizzo 2 รจ obbligatorio<br>"; else lblErrori.Text = lblErrori.Text + "Il campo <b>CAP</b> dell'indirizzo 2 รจ obbligatorio<br>"; } if (txtCitta2.Text.Trim() == "") { if (lblErrori.Text == "") lblErrori.Text = "Il campo <b>CITTA'</b> dell'indirizzo 2 รจ obbligatorio<br>"; else lblErrori.Text = lblErrori.Text + "Il campo <b>CITTA'</b> dell'indirizzo 2 รจ obbligatorio<br>"; } if (!(ddlProvincia2.SelectedIndex > 0)) { if (lblErrori.Text == "") lblErrori.Text = "Il campo <b>PROVINCIA</b> dell'indirizzo 2 รจ obbligatorio<br>"; else lblErrori.Text = lblErrori.Text + "Il campo <b>PROVINCIA</b> dell'indirizzo 2 รจ obbligatorio<br>"; } if (!(ddlNazione2.SelectedIndex > 0)) { if (lblErrori.Text == "") lblErrori.Text = "Il campo <b>PROVINCIA</b> รจ obbligatorio<br>"; else lblErrori.Text = lblErrori.Text + "Il campo <b>PROVINCIA'</b> รจ obbligatorio<br>"; } } if (!(ddlRuolo1.SelectedIndex > 0)) { if (lblErrori.Text == "") lblErrori.Text = "Il campo <b>RUOLO 1</b> รจ obbligatorio<br>"; else lblErrori.Text = lblErrori.Text + "Il campo <b>RUOLO 1</b> รจ obbligatorio<br>"; } if (lblErrori.Text != "") return; conn.Open(); SqlCommand cmd; if (Request.QueryString["id_Utenti"] == null) { cmd = new SqlCommand("IF((SELECT COUNT(*) FROM Utenti WHERE codice_fiscale_Utenti = @cf) > 0) BEGIN SET @res = 'K1' RETURN END " + "DECLARE @id AS INT SELECT @id = ISNULL(MAX(id_Utenti), 10000) + 1 FROM Utenti INSERT INTO Utenti (id_Utenti, cognome_Utenti, nome_Utenti, " + "data_nascita_Utenti,id_Sessi, id_Nazioni, telefono_Utenti, email_Utenti, note_Utenti, username_Utenti, password_Utenti, codice_fiscale_Utenti)" + "values(@id, @cognome, @nome, @dataNascita, @idSessi, @idNazioni, @tel, @email, @note, @username, @pw, @cf) SET @res = 'OK'", conn); cmd.Parameters.Add("@cognome", SqlDbType.NVarChar, 255).Value = txtCognome.Text.ToUpper(); cmd.Parameters.Add("@nome", SqlDbType.NVarChar, 255).Value = txtNome.Text.ToUpper(); cmd.Parameters.Add("@dataNascita", SqlDbType.Date).Value = DateTime.Parse(txtDataNascita.Text); if (ddlSesso.SelectedIndex > 0) cmd.Parameters.Add("@idSessi", SqlDbType.NChar, 1).Value = ddlSesso.SelectedValue; cmd.Parameters.Add("@idNazioni", SqlDbType.NChar, 3).Value = ddlNazionalita.SelectedValue; cmd.Parameters.Add("@cf", SqlDbType.NChar, 16).Value = txtCodiceFiscale.Text.ToUpper(); cmd.Parameters.Add("@tel", SqlDbType.NVarChar, 255).Value = txtTelefono.Text; cmd.Parameters.Add("@email", SqlDbType.NVarChar, 255).Value = txtEmail.Text; cmd.Parameters.Add("@note", SqlDbType.Text).Value = txtNote.Text; cmd.Parameters.Add("@username", SqlDbType.NVarChar, 40).Value = txtUserName.Text; cmd.Parameters.Add("@pw", SqlDbType.NVarChar, 10).Value = txtPassword.Text; cmd.Parameters.Add("@res", SqlDbType.Char, 2).Direction = ParameterDirection.Output; cmd.ExecuteNonQuery(); string res = cmd.Parameters["@res"].Value.ToString(); // cmd.Dispose(); // cmd = new SqlCommand("select id_Utenti from Utenti where codice_fiscale_Utenti = @cf", conn); cmd.Parameters.AddWithValue("@cf", txtCodiceFiscale.Text); txtId.Text = cmd.ExecuteScalar().ToString(); int id = Convert.ToInt32(txtId.Text); cmd.Dispose(); // cmd = new SqlCommand("insert into Indirizzi(id_Utenti, via_Indirizzi, cap_Indirizzi, citta_Indirizzi, id_Province, id_Nazioni, id_IndirizziTipologia)" + " values(@id, @via, @cap, @citta, @idProv, @idNaz, @idIndTip)", conn); cmd.Parameters.AddWithValue("@id", txtId.Text).Value = id; cmd.Parameters.Add("@via", SqlDbType.NVarChar, 255).Value = txtVia.Text; cmd.Parameters.Add("@cap", SqlDbType.Int).Value = txtCap.Text; cmd.Parameters.Add("@citta", SqlDbType.NVarChar, 255).Value = txtCitta.Text; cmd.Parameters.Add("@idProv", SqlDbType.NChar, 2).Value = ddlProvincia.SelectedValue; cmd.Parameters.Add("@idNaz", SqlDbType.NChar, 3).Value = ddlNazione.SelectedValue; cmd.Parameters.Add("@idIndTip", SqlDbType.NChar, 2).Value = ddlIndirizzoTip.SelectedValue; cmd.ExecuteNonQuery(); cmd.Dispose(); if ((txtCitta2 != null) && (ddlIndirizzoTip2.SelectedIndex > 0)) { cmd = new SqlCommand("insert into Indirizzi(id_Utenti, via_Indirizzi, cap_Indirizzi, citta_Indirizzi, id_Province, " + "id_Nazioni, id_IndirizziTipologia)values(@id, @via, @cap, @citta, @idProv, @idNaz, @idIndTip)", conn); cmd.Parameters.Add("@id", SqlDbType.Int).Value = id; cmd.Parameters.Add("@via", SqlDbType.NVarChar, 255).Value = txtVia2.Text; cmd.Parameters.Add("@cap", SqlDbType.Int).Value = txtCap2.Text; cmd.Parameters.Add("@citta", SqlDbType.NVarChar, 255).Value = txtCitta2.Text; cmd.Parameters.Add("@idProv", SqlDbType.NChar, 2).Value = ddlProvincia2.SelectedValue; cmd.Parameters.Add("@idNaz", SqlDbType.NChar, 3).Value = ddlNazione2.SelectedValue; cmd.Parameters.Add("@idIndTip", SqlDbType.NChar, 2).Value = ddlIndirizzoTip2.SelectedValue; cmd.ExecuteNonQuery(); cmd.Dispose(); } cmd = new SqlCommand("insert into [Utenti.Ruoli] (id_Utenti, id_Ruoli)values(@id, @idR)", conn); cmd.Parameters.Add("@id", SqlDbType.Int).Value = id; cmd.Parameters.Add("@idR", SqlDbType.Int).Value = ddlRuolo1.SelectedValue; cmd.ExecuteNonQuery(); if ((ddlRuolo2.SelectedValue != null) && ((ddlRuolo2.SelectedIndex > 0))) { cmd = new SqlCommand("insert into [Utenti.Ruoli] (id_Utenti, id_Ruoli)values(@id, @idR)", conn); cmd.Parameters.Add("@id", SqlDbType.Int).Value = id; cmd.Parameters.Add("@idR", SqlDbType.Int).Value = ddlRuolo2.SelectedValue; cmd.ExecuteNonQuery(); } if ((ddlRuolo3.SelectedValue != null) && ((ddlRuolo3.SelectedIndex > 0))) { cmd = new SqlCommand("insert into [Utenti.Ruoli] (id_Utenti, id_Ruoli)values(@id, @idR)", conn); cmd.Parameters.Add("@id", SqlDbType.Int).Value = id; cmd.Parameters.Add("@idR", SqlDbType.Int).Value = ddlRuolo3.SelectedValue; cmd.ExecuteNonQuery(); } cmd.Dispose(); if (res == "OK") Response.Redirect("UtenteElenco.aspx"); else Response.Write("<b>CF: " + txtCodiceFiscale.Text + "</b> giร  presente nel database. Utente " + txtCognome.Text + " " + txtNome.Text + " non inserito<br><br>"); } else { cmd = new SqlCommand("update Utenti set cognome_Utenti = @cognome, nome_Utenti = @nome, data_nascita_Utenti = @dataNascita, " + " id_Sessi = @idSessi, id_Nazioni = @idNazioni, telefono_Utenti = @tel, email_Utenti = @email, note_Utenti = @note, username_Utenti = @username, " + "password_Utenti = @pw, codice_fiscale_Utenti = @cf where id_Utenti = @id", conn); cmd.Parameters.Add("@id", SqlDbType.Int).Value = Request.QueryString["id_Utenti"].ToString(); cmd.Parameters.Add("@cognome", SqlDbType.NVarChar, 255).Value = txtCognome.Text.ToUpper(); cmd.Parameters.Add("@nome", SqlDbType.NVarChar, 255).Value = txtNome.Text.ToUpper(); cmd.Parameters.Add("@dataNascita", SqlDbType.Date).Value = DateTime.Parse(txtDataNascita.Text); if (ddlSesso.SelectedIndex > 0) cmd.Parameters.Add("@idSessi", SqlDbType.NChar, 1).Value = ddlSesso.SelectedValue; cmd.Parameters.Add("@idNazioni", SqlDbType.NChar, 3).Value = ddlNazionalita.SelectedValue; cmd.Parameters.Add("@tel", SqlDbType.NVarChar, 255).Value = txtTelefono.Text; cmd.Parameters.Add("@email", SqlDbType.NVarChar, 255).Value = txtEmail.Text; cmd.Parameters.Add("@note", SqlDbType.Text).Value = txtNote.Text; cmd.Parameters.Add("@username", SqlDbType.NVarChar, 40).Value = txtUserName.Text; cmd.Parameters.Add("@pw", SqlDbType.NVarChar, 10).Value = txtPassword.Text; cmd.Parameters.Add("@cf", SqlDbType.NChar, 16).Value = txtCodiceFiscale.Text.ToUpper(); cmd.ExecuteNonQuery(); cmd.Dispose(); // cmd = new SqlCommand("select id_Utenti from Utenti where codice_fiscale_Utenti = @cf", conn); cmd.Parameters.AddWithValue("@cf", txtCodiceFiscale.Text); txtId.Text = cmd.ExecuteScalar().ToString(); int id = Convert.ToInt32(txtId.Text); cmd.Dispose(); // cmd = new SqlCommand("update Indirizzi set id_IndirizziTipologia = @idIndTip, via_Indirizzi = @via, cap_Indirizzi = @cap, " + " citta_Indirizzi = @citta, id_Province = @idProv, id_Nazioni = @idNaz where id_Utenti = @id", conn); cmd.Parameters.Add("@id", SqlDbType.Int).Value = Request.QueryString["id_Utenti"].ToString(); cmd.Parameters.Add("@via", SqlDbType.NVarChar, 255).Value = txtVia.Text; cmd.Parameters.Add("@cap", SqlDbType.Int).Value = txtCap.Text; cmd.Parameters.Add("@citta", SqlDbType.NVarChar, 255).Value = txtCitta.Text; cmd.Parameters.Add("@idProv", SqlDbType.NChar, 2).Value = ddlProvincia.SelectedValue; cmd.Parameters.Add("@idNaz", SqlDbType.NChar, 3).Value = ddlNazione.SelectedValue; cmd.Parameters.Add("@idIndTip", SqlDbType.NChar, 2).Value = ddlIndirizzoTip.SelectedValue; cmd.ExecuteNonQuery(); cmd.Dispose(); // if ((txtCitta2 != null) && (ddlIndirizzoTip2.SelectedIndex > 0)) { cmd = new SqlCommand("update Indirizzi set id_IndirizziTipologia = @idIndTip2, via_Indirizzi = @via2, cap_Indirizzi = @cap2, " + " citta_Indirizzi = @citta2, id_Province = @idProv2, id_Nazioni = @idNaz2 where id_Utenti = @id", conn); cmd.Parameters.Add("@id", SqlDbType.Int).Value = Request.QueryString["id_Utenti"].ToString(); cmd.Parameters.Add("@via2", SqlDbType.NVarChar, 255).Value = txtVia2.Text; cmd.Parameters.Add("@cap2", SqlDbType.Int).Value = txtCap2.Text; cmd.Parameters.Add("@citta2", SqlDbType.NVarChar, 255).Value = txtCitta2.Text; cmd.Parameters.Add("@idProv2", SqlDbType.NChar, 2).Value = ddlProvincia2.SelectedValue; cmd.Parameters.Add("@idNaz2", SqlDbType.NChar, 3).Value = ddlNazione2.SelectedValue; cmd.Parameters.Add("@idIndTip2", SqlDbType.NChar, 2).Value = ddlIndirizzoTip2.SelectedValue; cmd.ExecuteNonQuery(); cmd.Dispose(); } } conn.Close(); } protected void btnAnnulla_Click(object sender, EventArgs e) { txtCognome.Text = ""; txtNome.Text = ""; txtDataNascita.Text = ""; txtDataNascita.Text = ""; ddlSesso.Items[ddlSesso.SelectedIndex].Selected = false; ddlNazionalita.Items[ddlNazionalita.SelectedIndex].Selected = false; txtCodiceFiscale.Text = ""; txtTelefono.Text = ""; txtEmail.Text = ""; txtUserName.Text = ""; txtPassword.Text = ""; txtNote.Text = ""; ddlIndirizzoTip.Items[ddlIndirizzoTip.SelectedIndex].Selected = false; txtVia.Text = ""; txtCap.Text = ""; txtCitta.Text = ""; ddlProvincia.Items[ddlProvincia.SelectedIndex].Selected = false; ddlNazione.Items[ddlNazione.SelectedIndex].Selected = false; //for (int i = 0; i < lbxRuoli.Items.Count; i++) // lbxRuoli.Items[i].Selected = false; if (tblIndirizzo2.Visible == true) tblIndirizzo2.Visible = false; ddlRuolo1.Items[ddlRuolo1.SelectedIndex].Selected = false; if ((ddlRuolo2.Visible == true)) ddlRuolo2.Visible = false; if (ddlRuolo3.Visible == true) ddlRuolo3.Visible = false; } protected void btnMenuIniziale_Click(object sender, EventArgs e) { Response.Redirect("Menu_Iniziale.aspx"); } protected void btnElencoUtenti_Click(object sender, EventArgs e) { Response.Redirect("UtenteElenco.aspx"); } protected void btnAggiungiIndirizzo_Click(object sender, EventArgs e) { tblIndirizzo2.Visible = true; } protected void btnAnnullaInsIndirizzo_Click(object sender, EventArgs e) { ddlIndirizzoTip2.Items[ddlIndirizzoTip2.SelectedIndex].Selected = false; txtVia2.Text = ""; txtCap2.Text = ""; txtCitta2.Text = ""; ddlProvincia2.Items[ddlProvincia2.SelectedIndex].Selected = false; ddlNazione2.Items[ddlNazione2.SelectedIndex].Selected = false; tblIndirizzo2.Visible = false; } protected void btnAggiungiRuolo2_Click(object sender, EventArgs e) { lblRuolo2.Visible = true; ddlRuolo2.Visible = true; btnAggiungiRuolo3.Visible = true; } protected void brnAggiungiRuolo3_Click(object sender, EventArgs e) { lblRuolo3.Visible = true; ddlRuolo3.Visible = true; } }
dbe830f846c8c0384c5436ac71c2bbfd5b43315a
[ "C#" ]
5
C#
daniloprandi/Edilpiu
7e4ea8c772e240f6011b05fe5d57a4f66446ebb0
26c3032628015ac594bcc427d398f429daf4429f
refs/heads/master
<repo_name>curbyourcode/Library-App<file_sep>/app/invitation/model.js import DS from 'ember-data'; // ember g model invitation email:string........adding email:string it automatically generates the value in our Model export default DS.Model.extend({ email: DS.attr('string') }); <file_sep>/app/index/controller.js import Ember from 'ember'; export default Ember.Controller.extend({ // we can {{yield teh headerMessage}} headerMessage: 'Coming Soon', responseMessage: '', emailAddress: '', isValid: Ember.computed.match('emailAddress', /^.+@.+\..+$/), // isDisabled: Ember.computed.not('isValid'), actions: { sendInvitation: function() { var email = this.get('emailAddress'); // this.store.createRecord is letting our server now to save the new email address associated with invitations variable. var newInvitation = this.store.createRecord('invitation', { email:email }); // Promise: .save() promise: unique asynchronous feature in javascript. Basically, theyโ€™re objects that havenโ€™t completed yet, but are expected to in the future // promises us that it is trying to save our data. It could be successful or maybe return with an error. // .then catch the result of the promise with .then() which is a chained fucntion // response => model from server sent to call back as response. the model object contains the ID of our model. newInvitation.save().then((response) => { // in javascript .this points to the object that wraps around it. this.set('responseMessage', "Thank you! We saved your email address with the following id: " + response.get('id')); this.set('emailAddress', ''); }); } } }); <file_sep>/app/components/nav-link-to/component.js import Ember from 'ember'; export default Ember.LinkComponent.extend({ // tagName property : determines the main tag of a component tagName: 'li' }); <file_sep>/app/authors/route.js import Ember from 'ember'; export default Ember.Route.extend({ model() { return this.store.findAll('author'); }, // Any time when we invoke an action, it passes the selected author record to that function as a parameter, so we can set isEditing on that record only. actions: { editAuthor(author) { author.set('isEditing', true); }, cancelAuthorEdit(author) { author.set('isEditing', false); // In case of cancellation we revoke changes with rollbackAttributes author.rollbackAttributes(); }, saveAuthor(author) { if (author.get('isNotValid')) { return; } author.set('isEditing', false); author.save(); } } });
49bdeeeb946ef61b0fd2ca227a3f06031753a514
[ "JavaScript" ]
4
JavaScript
curbyourcode/Library-App
e6969448cdbf2ff322e0114bb3f0566aa400efd6
ffd1fe2b750510bdf94a0be84b0d8501318ad8dd
refs/heads/main
<file_sep># twitterplusone ## Explanation PERN twitter clone that allows tweets with 281 characters! ## Link to Live Site https://twitterplusone.herokuapp.com/ ## Technologies Used In this application I used PostGreSQL for my database, Express.js and Node.js for my backend and React.js for my frontend. I also used hooks and react-router as some new technologies to help improve the flow of my website a bit. I also used the Bulma framework to help style it and used the react-toastify package for the pop ups notifications. ## Unsolved Problems Some unsolved problems that I would like to work on in the future are adjusting my code so that the timeline is actually a separate page from the profiles. I would also like to get comments and retweets down and possibly notifications and uploading and displaying a profile picture. <file_sep>//DEPENDENCIES const express = require('express'); const app = express(); const cors = require('cors'); const path = require('path'); require("dotenv").config(); PORT = process.env.PORT //MIDDLEWARE app.use(express.json()) app.use(cors()) app.use(express.static(path.join(__dirname, 'client/build'))) //CONTROLLERS //Register/Login app.use("/auth", require("./controllers/jwtAuth.js")) //Dashboard app.use("/dashboard", require("./controllers/dashboard.js")) //Tweets app.use("/tweet", require("./controllers/tweet.js")) //CATCH FRONTEND ROUTES app.get('/*', function(req, res) { res.sendFile(path.join(__dirname, 'client/build/index.html'), function(err) { if (err) { res.status(500).send(err) } }) }) //LISTENER app.listen(PORT, () => { console.log(`Listening on port ${PORT}...`); }) <file_sep>import React, {Fragment, useState, useEffect} from 'react'; import 'bulma/css/bulma.css' import '../App.css' import {toast} from "react-toastify" const Dashboard = ({setAuth}) => { /////////////////////////////////////CONSTANTS//////////////////////// const [name, setName] = useState(""); const [id, setId] = useState(""); const [faves, setFaves] = useState([]) const [allTweets, setAllTweets] = useState([]) const [inputs, setInputs] = useState({ tweet: "", }) const [users, setUsers] = useState([]) const [following, setFollowing] = useState([]) const {tweet} = inputs; const onChange = (event) => { setInputs({...inputs, [event.target.name]:event.target.value}) } const [profile, setProfile] = useState("") const [count, setCount] = useState(parseInt(281)) //////////////////////////////USEEFFECT FUNCTIONS//////////////////////// async function getName() { try{ const response = await fetch("/dashboard",{ method: "GET", headers: {token: localStorage.token} }) const parseRes = await response.json() setName(parseRes.username) setId(parseRes.user_id) setFollowing(parseRes.following) }catch(err){ console.error(err.message) } } const getAllTweets = async() => { setProfile("all") try{ const response = await fetch(`/tweet/read/${id}`) const parseRes = await response.json() setAllTweets(parseRes); }catch(err){ console.log(err.message); } } const getUserTweets = async (event, username, user_id) => { setProfile(user_id); console.log(profile); console.log(user_id); try{ const response = await fetch(`tweet/user/${user_id}`) const parseRes = await response.json() setAllTweets(parseRes); }catch(err){ console.error(err.message); } const title = document.getElementById('title') if(title.innerHTML !== `@${username}'s Profile'`){ title.innerHTML = "@"+ username + "'s Profile" } closeUserModal(); getFaves(); } const getUsers = async() => { try{ const response = await fetch("/tweet/users") const parseRes = await response.json() setUsers(parseRes) }catch(err){ console.log(err.message); } } const getFaves = async () => { const user_id = id try{ const response = await fetch(`/tweet/faves/${user_id}`,{ method: "GET", }) const parseRes = await response.json(); setFaves(parseRes[0].favorites); }catch (err){ console.error(err.message); } } ///////////////////////////////MODAL CONTROLS//////////////////////// const openTweetModal = () => { let tweetModal = document.getElementById('tweet'); tweetModal.classList.add("is-active"); document.getElementById('tweet-box').focus(); dropMenu(); } const closeTweetModal = () => { let tweetModal = document.getElementById('tweet'); tweetModal.classList.remove("is-active"); setInputs({...inputs, tweet:''}) setCount(281) } const openUserModal = () => { let userModal = document.getElementById('users-list'); userModal.classList.add("is-active"); dropMenu(); } const closeUserModal = () => { let userModal = document.getElementById('users-list'); userModal.classList.remove("is-active"); } const dropMenu = (event) => { const isActive = document.getElementById('burger').classList; const menu = document.getElementById('menu').classList; if(isActive.length === 2){ isActive.add('is-active') menu.add('is-active') }else if(isActive.length === 3){ isActive.remove('is-active') menu.remove('is-active') } } /////////////////////////////SUBMITTING TWEET//////////////////////// const pressEnter = (event) => { if(event.key === 'Enter'){ submitTweet(event); } } const countChar = (event) => { if(event.keyCode === 8){ if(count === 281){ return }else{ setCount(count+1) } }else if(event.keyCode !== 9 && event.keyCode !== 13 && event.keyCode !== 16 && event.keyCode !== 17 && event.keyCode !== 18 && event.keyCode !== 20 && event.keyCode !== 27 && event.keyCode !== 33 && event.keyCode !== 34 && event.keyCode !== 35 && event.keyCode !== 36 && event.keyCode !== 37 && event.keyCode !== 38 && event.keyCode !== 39 && event.keyCode !== 40 && event.keyCode !== 46){ if(count === 0){ return }else{ setCount(count-1) } } } const submitTweet = async (event) => { event.preventDefault(); try{ const body = {id, tweet} const response = await fetch("/tweet/create", { method: "POST", headers:{"Content-Type": "application/json"}, body: JSON.stringify(body) }) getAllTweets(); closeTweetModal(); toast.success("Tweet Sent!", { position: "top-center", autoClose: 2000, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, draggable: true, progress: undefined, }) }catch(err){ console.log(err.message); } } ///////////////////////////FAVORITES CONTROLS//////////////////////// //TOGGLEING FAVORITES BUTTON const favToggle = async(event, username) => { const tweet_id = event.target.id const user_id = id if (event.target.classList[1] === 'unfavorite') { event.target.classList.remove('unfavorite'); event.target.classList.add('favorite'); }else{ event.target.classList.remove('favorite'); event.target.classList.add('unfavorite'); } try{ const body = {tweet_id, user_id} const response = await fetch("/tweet/favorite", { method: "PUT", headers: {"Content-Type": "application/json"}, body: JSON.stringify(body) }) }catch(err){ console.error(err.message); } getFaves(); if(profile === "all"){ getAllTweets(); }else{ getUserTweets(event, username, profile) } } //CHECKING FAVORITES const checkFav = (tweet_id, username) => { if(faves === null || faves.length === 0){ return(<div className="fav-button unfavorite" id={tweet_id} onClick={event => favToggle(event, username)}></div>) }else{ for(let i = 0; i < faves.length; i++){ if(faves[i] === tweet_id){ return(<div className="fav-button favorite" id={tweet_id} onClick={event => favToggle(event, username)}></div>) } } return(<div className="fav-button unfavorite" id={tweet_id} onClick={event => favToggle(event, username)}></div>) } } //////////////////////////////FOLLOWING CONTROLS//////////////////////// const followToggle = async(event) => { const button = event.target const currentUser = id; const username = button.value const user_id = button.id if(button.classList[1] === 'is-info'){ button.classList.remove('is-info') button.classList.add('is-danger') button.innerHTML="Unfollow" toast.success(`You are now following @${username}!`, { position: "top-center", autoClose: 2000, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, draggable: true, progress: undefined, }) }else{ button.classList.add('is-info') button.classList.remove('is-danger') button.innerHTML="Follow" toast.error(`You have unfollowed @${username}`, { position: "top-center", autoClose: 2000, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, draggable: true, progress: undefined, }) } try{ const body = {currentUser, user_id} const response = await fetch("/tweet/follow", { method: "PUT", headers: {"Content-Type": "application/json"}, body: JSON.stringify(body) }) }catch(err){ console.error(err.message); } getName(); getUsers(); if(profile === "all"){ getAllTweets(); }else{ getUserTweets(event, username, profile) } } //CHECK FOLLOWERS const checkFollow = (user_id, username) => { for(let i=0; i<following.length; i++){ if(following[i] === user_id){ return(<button id={user_id} value={username} onClick={event => followToggle(event)} className="button is-danger">Unfollow</button>) } } return(<button id={user_id} value={username} onClick={event => followToggle(event)} className="button is-info">Follow</button>) } /////////////////////////////DELETEING FUNCTIONS//////////////////////// const deleteTweet = async (event, username) => { const tweet_id = event.target.id try{ const response = await fetch(`/tweet/delete/${tweet_id}`, { method: "DELETE" }) toast.error("Tweet Deleted", { position: "top-center", autoClose: 2000, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, draggable: true, progress: undefined, }) }catch(err){ console.error(err.message); } if(profile === "all"){ getAllTweets(); }else{ getUserTweets(event, username, profile) } } const checkDelete = (user_id, tweet_id, username) => { if(user_id === id){ return(<button id={tweet_id} className="button is-danger" onClick={event => deleteTweet(event, username)}>DELETE</button>) } } //////////////////////////////////////LOGOUT//////////////////////// const logout = (event) => { event.preventDefault() localStorage.removeItem("token") setName(""); setId(""); setFaves([]); setAllTweets([]); setAuth(false); toast.info("Logged out. Thank you for using Twitter+1", { position: "top-center", autoClose: 2000, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, draggable: true, progress: undefined, }) } useEffect(() => { getName(); getUsers(); }, []) useEffect(() => { getFaves(); getAllTweets(); },[id, following]) return( <Fragment> <div> <nav className="navbar pt-2 pb-2 is-fixed-top is-link"> <div className="navbar-start"> <div className="navbar-brand"> <a className="navbar-item" href="/home"><img src="./icons/logo.png" width="32" height="32" alt="Twitter+1" />Twitter+1</a> <a role="button" id='burger' class="navbar-burger burger" aria-label="menu" aria-expanded="false" data-target="navbarBasicExample" onClick={event => dropMenu(event)}> <span aria-hidden="true"></span> <span aria-hidden="true"></span> <span aria-hidden="true"></span> </a> </div> </div> <div id="menu" className="navbar-menu"> <div className="navbar-end"> <a className="navbar-item" onClick={event=>getUserTweets(event, name, id)}>Hello @{name}!</a> <a className="navbar-item" onClick={openUserModal}>Following</a> <div className="buttons"> <a className=" ml-2 button is-primary" onClick={openTweetModal}>Add A Tweet+</a> <a className="mr-2 button is-danger " onClick={event => logout(event)}>Log Out</a> </div> </div> </div> </nav> <div className="modal" id="tweet"> <div className="modal-background"></div> <div className="modal-card"> <header className="modal-card-head"> <p className="modal-card-title">Send a Tweet!</p> </header> <section className="modal-card-body"> <form id="send-tweet" onSubmit={submitTweet}> <textarea id="tweet-box" name="tweet" value={tweet} cols="48" rows="6" form="send-tweet" maxLength="281" onKeyPress={event => pressEnter(event)} onKeyDown={event => countChar(event)} onChange={event => onChange(event)}/> <input type="submit" value="Submit" className="button is-info mr-4" /> </form> </section> <footer className="modal-card-foot"> <button className="button is-danger" onClick={closeTweetModal}>Cancel</button> <h3 id='char-count'>{count}</h3> </footer> </div> </div> <div className="modal" id="users-list"> <div className="modal-background"></div> <div className="modal-card"> <header className="modal-card-head"> <p className="modal-card-title">Following</p> </header> <section className="modal-card-body"> {users.map(user => user.user_id === id ? null : ( <div className="user"> <a onClick={event=>getUserTweets(event, user.username, user.user_id)} className="username">@{user.username}</a> {checkFollow(user.user_id, user.username)} </div> ))} </section> <footer className="modal-card-foot"> <button className="button is-danger" onClick={closeUserModal}>Close</button> </footer> </div> </div> <br/> <br/> <br/> <h1 id="title" className="is-size-1">Timeline</h1> <div className="tweets-container mt-4"> {allTweets.map(tweet => ( <div className="tweet"> <h1><a onClick={event=>getUserTweets(event, tweet.username, tweet.author)}>@{tweet.username}</a></h1> <p>{tweet.tweet}</p> <div className="tweet-footer"> <div className="fav-container"> <div className="faves-num">{tweet.favorites_num}</div> {checkFav(tweet.tweet_id, tweet.username)} </div> <div> {checkDelete(tweet.author, tweet.tweet_id, tweet.username)} </div> </div> </div> ))} </div> </div> </Fragment> ) } export default Dashboard; <file_sep>const auth = require('express').Router(); const bcrypt = require('bcrypt'); const pool = require('../db.js'); const jwtGenerator = require("../utils/jwtGen.js"); const validEmail = require("../middleware/validEmail.js"); const authorization = require("../middleware/authorization.js") //REGISTER ROUTE auth.post("/register", validEmail, async (req, res) => { try{ const {username, email, password} = req.body const userEmail = await pool.query("SELECT * FROM users WHERE email = $1", [email]); if(userEmail.rows.length !== 0){ return res.status(401).json("Email is already in use"); } const userName = await pool.query("SELECT * FROM users WHERE username = $1", [username]) if(userName.rows.length !== 0){ return res.status(401).json("Username taken"); } const salt = await bcrypt.genSalt(10); const bcryptPassword = await bcrypt.hash(password, salt) const newUser = await pool.query("INSERT INTO users(username, email, password) VALUES ($1, $2, $3) RETURNING *", [username, email, bcryptPassword]) await pool.query(`UPDATE users SET following = array_append(following, '${newUser.rows[0].user_id}') WHERE user_id = '${newUser.rows[0].user_id}';`) const token = jwtGenerator(newUser.rows[0].user_id) res.json({token}); }catch (err){ console.error(err.message); res.status(500).json("Server Error") } }) //LOGIN ROUTES auth.post("/login", async (req, res) => { try{ const {username, password} = req.body const user = await pool.query("SELECT * FROM users WHERE username = $1", [username]); if(user.rows.length === 0){ return res.status(401).json("Username or Password is incorrect") } const validPassword = await bcrypt.compare(password, user.rows[0].password); if(!validPassword){ return res.status(401).json("Username or Password is incorrect") } const token = jwtGenerator(user.rows[0].user_id) res.json({token}); }catch(err){ console.error(err.message); res.status(500).json("Server Error") } }) //VERIFY ROUTES auth.get("/verify", authorization, async (req, res) => { try{ res.json(true); }catch(err){ console.error(err.message); res.status(500).json("Server Error") } }) module.exports = auth <file_sep>import React, {Fragment, useState} from 'react'; import {Link} from "react-router-dom"; import 'bulma/css/bulma.css' import { toast } from 'react-toastify'; const Register = ({setAuth}) => { const [inputs, setInputs] = useState({ email: "", username: "", password: "" }) const {email, username, password} = inputs; const onChange = (event) => { setInputs({...inputs, [event.target.name]:event.target.value}) } const onSubmitForm = async (event) => { event.preventDefault(); try{ const body = {email, username, password}; const response = await fetch("/auth/register", { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify(body) }) const parseRes = await response.json() if(parseRes.token){ localStorage.setItem("token", parseRes.token) setAuth(true) toast.success("Successfully Registered!", { position: "top-center", autoClose: 2000, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, draggable: true, progress: undefined, }) }else{ setAuth(false) toast.error(parseRes, { position: "top-center", autoClose: 2000, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, draggable: true, progress: undefined, }) } }catch(err){ console.error(err.message) } } return( <Fragment> <h1 className="title is-1 has-text-centered">Register</h1> <form className="ml-6 mr-6 container" onSubmit={onSubmitForm}> <div className="field"> <div className="control"> <input className="input is-large" type="email" name="email" placeholder="email" value={email} onChange={event => onChange(event)}/> </div> </div> <div className="field"> <div className="control"> <input className="input is-large" type="text" name="username" placeholder="username" value={username} onChange={event => onChange(event)}/> </div> </div> <div className="field"> <div className="control"> <input className="input is-large" type="password" name="password" placeholder="<PASSWORD>" value={password} onChange={event => onChange(event)}/> </div> </div> <div className="field"> <div className="mb-3 control"> <input className="button is-success is-large is-fullwidth" type= "submit" value="Submit" /> </div> <div className="control"> <Link to="/login"><div className="button is-info is-large is-fullwidth">Back to Login</div></Link> </div> </div> </form> </Fragment> ) } export default Register;
2fe57589174a1a8fd7c04abad0d0724b58efe4bd
[ "Markdown", "JavaScript" ]
5
Markdown
masonsteeger/twitterplusone
4dc17411f5eb399f2bc3ba36b0a1336bdc0ebd09
ae45d199a783bda466fd83b2676b8cfe400c5abb
refs/heads/master
<repo_name>alexpcunningham/test-repo-aug-16<file_sep>/README.md # test-repo-aug-16 <file_sep>/constants.sh #!/bin/bash ######################################################################################################################################### # File : constants.sh # # Author : APC # # Date : 05/10/2015 # # # DESCRIPTION: # # This script searches BWA Perl source code files for constants In the BWA, constants # are given upper case names, and they often include underscore characters. As a result, # this script extracts strings that include upper case characters and underscores. # # USAGE: # # This script was originally written in order to check that all constants used in the # main BWA codee are declared in the constants file Cs.pm. As a result, you can either # search for constants in all Perl files EXCEPT Cs.pm using the following command: # # $ ./constants.sh perl_without_cs # # Or you can search for constants in Cs.pm only using the following command: # # $ ./constants.sh perl_cs_only # # # To remove duplicate lines, pipe STDOUT into 'sort -u' # # # This is just a further amendment. ######################################################################################################################################### # # /* Search all Perl source files except Cs.pm */ # if [ $1 = "perl_without_cs" ] then # # /* Makefile */ # perl -e 'while(<>){ @inputLine = (); push( @inputLine, ( split /\s+/, $_ ) ); foreach $var ( @inputLine ) { if( ( $var eq uc $var ) && ( $var =~ /[A-Z]/) && ( $var =~ /[_]/) && ($var !~ /[:\}]/) && ($var !~ /^ERR_/) ) { $var =~ s/[";,><\*\.\)\(]//g; print "$var\n"; } } }' /remote/ccge_vol2/bioinformatics/software/boadicea/boadicea_v4/git/BOADICEA/make/make.pl # # /* Bp.pm */ # perl -e 'while(<>){ @inputLine = (); push( @inputLine, ( split /\s+/, $_ ) ); foreach $var ( @inputLine ) { if( ( $var eq uc $var ) && ( $var =~ /[A-Z]/) && ( $var =~ /[_]/) && ($var !~ /[:\}]/) && ($var !~ /^ERR_/) ) { $var =~ s/[";,><\*\.\)\(]//g; print "$var\n"; } } }' /remote/ccge_vol2/bioinformatics/software/boadicea/boadicea_v4/git/BOADICEA/perl/modules/bp/Bp.pm # # /* Db.pm */ # perl -e 'while(<>){ @inputLine = (); push( @inputLine, ( split /\s+/, $_ ) ); foreach $var ( @inputLine ) { if( ( $var eq uc $var ) && ( $var =~ /[A-Z]/) && ( $var =~ /[_]/) && ($var !~ /[:\}]/) && ($var !~ /^ERR_/) ) { $var =~ s/[";,><\*\.\)\(]//g; print "$var\n"; } } }' /remote/ccge_vol2/bioinformatics/software/boadicea/boadicea_v4/git/BOADICEA/perl/modules/db/Db.pm # # /* Dt.pm */ # perl -e 'while(<>){ @inputLine = (); push( @inputLine, ( split /\s+/, $_ ) ); foreach $var ( @inputLine ) { if( ( $var eq uc $var ) && ( $var =~ /[A-Z]/) && ( $var =~ /[_]/) && ($var !~ /[:\}]/) && ($var !~ /^ERR_/) ) { $var =~ s/[";,><\*\.\)\(]//g; print "$var\n"; } } }' /remote/ccge_vol2/bioinformatics/software/boadicea/boadicea_v4/git/BOADICEA/perl/modules/dt/Dt.pm # # /* Er.pm */ # # perl -e 'while(<>){ @inputLine = (); push( @inputLine, ( split /\s+/, $_ ) ); foreach $var ( @inputLine ) { if( ( $var eq uc $var ) && ( $var =~ /[A-Z]/) && ( $var =~ /[_]/) && ($var !~ /[:\}]/) && ($var !~ /^ERR_/) ) { $var =~ s/[";,><\*\.\)\(]//g; print "$var\n"; } } }' /remote/ccge_vol2/bioinformatics/software/boadicea/boadicea_v4/git/BOADICEA/perl/modules/er/Er.pm # # /* Hd.pm */ # perl -e 'while(<>){ @inputLine = (); push( @inputLine, ( split /\s+/, $_ ) ); foreach $var ( @inputLine ) { if( ( $var eq uc $var ) && ( $var =~ /[A-Z]/) && ( $var =~ /[_]/) && ($var !~ /[:\}]/) && ($var !~ /^ERR_/) ) { $var =~ s/[";,><\*\.\)\(]//g; print "$var\n"; } } }' /remote/ccge_vol2/bioinformatics/software/boadicea/boadicea_v4/git/BOADICEA/perl/modules/hd/Hd.pm # # /* Io.pm */ # perl -e 'while(<>){ @inputLine = (); push( @inputLine, ( split /\s+/, $_ ) ); foreach $var ( @inputLine ) { if( ( $var eq uc $var ) && ( $var =~ /[A-Z]/) && ( $var =~ /[_]/) && ($var !~ /[:\}]/) && ($var !~ /^ERR_/) ) { $var =~ s/[";,><\*\.\)\(]//g; print "$var\n"; } } }' /remote/ccge_vol2/bioinformatics/software/boadicea/boadicea_v4/git/BOADICEA/perl/modules/io/Io.pm # # /* Pd.pm */ # perl -e 'while(<>){ @inputLine = (); push( @inputLine, ( split /\s+/, $_ ) ); foreach $var ( @inputLine ) { if( ( $var eq uc $var ) && ( $var =~ /[A-Z]/) && ( $var =~ /[_]/) && ($var !~ /[:\}]/) && ($var !~ /^ERR_/) ) { $var =~ s/[";,><\*\.\)\(]//g; print "$var\n"; } } }' /remote/ccge_vol2/bioinformatics/software/boadicea/boadicea_v4/git/BOADICEA/perl/modules/pd/Pd.pm # # /* Pg.pm */ # perl -e 'while(<>){ @inputLine = (); push( @inputLine, ( split /\s+/, $_ ) ); foreach $var ( @inputLine ) { if( ( $var eq uc $var ) && ( $var =~ /[A-Z]/) && ( $var =~ /[_]/) && ($var !~ /[:\}]/) && ($var !~ /^ERR_/) ) { $var =~ s/[";,><\*\.\)\(]//g; print "$var\n"; } } }' /remote/ccge_vol2/bioinformatics/software/boadicea/boadicea_v4/git/BOADICEA/perl/modules/pg/Pg.pm # # /* Rp.pm */ # perl -e 'while(<>){ @inputLine = (); push( @inputLine, ( split /\s+/, $_ ) ); foreach $var ( @inputLine ) { if( ( $var eq uc $var ) && ( $var =~ /[A-Z]/) && ( $var =~ /[_]/) && ($var !~ /[:\}]/) && ($var !~ /^ERR_/) ) { $var =~ s/[";,><\*\.\)\(]//g; print "$var\n"; } } }' /remote/ccge_vol2/bioinformatics/software/boadicea/boadicea_v4/git/BOADICEA/perl/modules/rp/Rp.pm # # /* Sa.pm */ # perl -e 'while(<>){ @inputLine = (); push( @inputLine, ( split /\s+/, $_ ) ); foreach $var ( @inputLine ) { if( ( $var eq uc $var ) && ( $var =~ /[A-Z]/) && ( $var =~ /[_]/) && ($var !~ /[:\}]/) && ($var !~ /^ERR_/) ) { $var =~ s/[";,><\*\.\)\(]//g; print "$var\n"; } } }' /remote/ccge_vol2/bioinformatics/software/boadicea/boadicea_v4/git/BOADICEA/perl/modules/sa/Sa.pm # # /* Se.pm */ # perl -e 'while(<>){ @inputLine = (); push( @inputLine, ( split /\s+/, $_ ) ); foreach $var ( @inputLine ) { if( ( $var eq uc $var ) && ( $var =~ /[A-Z]/) && ( $var =~ /[_]/) && ($var !~ /[:\}]/) && ($var !~ /^ERR_/) ) { $var =~ s/[";,><\*\.\)\(]//g; print "$var\n"; } } }' /remote/ccge_vol2/bioinformatics/software/boadicea/boadicea_v4/git/BOADICEA/perl/modules/se/Se.pm # # /* Vl.pm */ # perl -e 'while(<>){ @inputLine = (); push( @inputLine, ( split /\s+/, $_ ) ); foreach $var ( @inputLine ) { if( ( $var eq uc $var ) && ( $var =~ /[A-Z]/) && ( $var =~ /[_]/) && ($var !~ /[:\}]/) && ($var !~ /^ERR_/) ) { $var =~ s/[";,><\*\.\)\(]//g; print "$var\n"; } } }' /remote/ccge_vol2/bioinformatics/software/boadicea/boadicea_v4/git/BOADICEA/perl/modules/vl/Vl.pm # # /* bd.cgi */ # perl -e 'while(<>){ @inputLine = (); push( @inputLine, ( split /\s+/, $_ ) ); foreach $var ( @inputLine ) { if( ( $var eq uc $var ) && ( $var =~ /[A-Z]/) && ( $var =~ /[_]/) && ($var !~ /[:\}]/) && ($var !~ /^ERR_/) ) { $var =~ s/[";,><\*\.\)\(]//g; print "$var\n"; } } }' /remote/ccge_vol2/bioinformatics/software/boadicea/boadicea_v4/git/BOADICEA/perl/bd.cgi # # /* Search Cs.pm only */ # elif [ $1 = "perl_cs_only" ] then # # /* Cs.pm */ # perl -e 'while(<>){ @inputLine = (); push( @inputLine, ( split /\s+/, $_ ) ); foreach $var ( @inputLine ) { if( ( $var eq uc $var ) && ( $var =~ /[A-Z]/) && ( $var =~ /[_]/) && ($var !~ /[:\}]/) && ($var !~ /^ERR_/) ) { $var =~ s/[";,><\*\.\)\(]//g; print "$var\n"; } } }' /remote/ccge_vol2/bioinformatics/software/boadicea/boadicea_v4/git/BOADICEA/perl/modules/cs/Cs.pm # # /* Otherwise unexpected command so throw and error */ # else echo "constants.sh: unexpected usage: try running this script with one of the following commands: \"./constants.sh perl_without_cs\" or \"./constants.sh perl_cs_only\"" exit 1 fi exit 1 # # /* Search JavaScript source files */ # # # /* Search the JavaScript home directory */ # #cd /remote/ccge_vol2/bioinformatics/software/boadicea/boadicea_v4/git/BOADICEA/xhtml/javascript #grep -n "$1" * #printf "\n" # # /* Search the JavaScript constants library */ # #cd /remote/ccge_vol2/bioinformatics/software/boadicea/boadicea_v4/git/BOADICEA/xhtml/javascript/libraries/cs #grep -n "$1" * #printf "\n" # # /* Search the JavaScript validation library */ # #cd /remote/ccge_vol2/bioinformatics/software/boadicea/boadicea_v4/git/BOADICEA/xhtml/javascript/libraries/vl #grep -n "$1" * #printf "\n" # # /* Search the JavaScript error library */ # #cd /remote/ccge_vol2/bioinformatics/software/boadicea/boadicea_v4/git/BOADICEA/xhtml/javascript/libraries/er #grep -n "$1" * #printf "\n"
a3a8d6199a42997771144062ec8650c28ceb4f69
[ "Markdown", "Shell" ]
2
Markdown
alexpcunningham/test-repo-aug-16
6f3b82f845b7c4eebcced554945bbdbc403409fb
4faf83aaf00d16cd3341a0063c1cbdd4702989a2
refs/heads/master
<repo_name>DimitriHeloin/FilRougeFinal<file_sep>/app/models/project.rb # == Schema Information # # Table name: projects # # id :integer not null, primary key # title :string(255) # description :text # created_at :datetime # updated_at :datetime # memberscount :integer # membersmax :integer # user_id :integer # class Project < ActiveRecord::Base belongs_to :user has_many :users end <file_sep>/db/migrate/20140312135011_add_fields_to_projects.rb class AddFieldsToProjects < ActiveRecord::Migration def change add_column :projects, :memberscount, :integer add_column :projects, :membersmax, :integer add_reference :projects, :user, index: true end end <file_sep>/app/controllers/users_controller.rb class UsersController < ApplicationController before_action :set_user, only: [:show, :edit, :update] # GET /projects # GET /projects.json def index @users = User.all end helper_method :index # GET /projects/1 # GET /projects/1.json def show end # GET /projects/new # GET /projects/1/edit def edit end # DELETE /users/1 # DELETE /users/1.json # DELETE /projects/1 # DELETE /projects/1.json def destroy User.find(params[:id]).destroy flash[:success] = "User deleted." redirect_to users_url end def destroy User.find(params[:id]).destroy flash[:success] = "User deleted." redirect_to users_url end def recherche end def maincolor(path) img = Magick::Image.read(path).first pix = img.scale(1, 1) avg_color_hex = pix.to_color(pix.pixel_color(0,0)) return avg_color_hex end helper_method :maincolor # POST /projects # POST /projects.json private # Use callbacks to share common setup or constraints between actions. def set_user @user = User.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def user_params params.require(:user).permit(:pseudo, :description,:avatar) end end <file_sep>/config/routes.rb DeviseExample::Application.routes.draw do devise_for :users, :admins resources :projects resources :users get '/token' => 'home#token', as: :token resources :home, only: :index resources :admins, only: :index root 'home#index' get '/recherche' => 'users#recherche' get 'users_path', to: 'users#index' end
a2f1a9980e8704229b984148725d98cc7d834810
[ "Ruby" ]
4
Ruby
DimitriHeloin/FilRougeFinal
e344dca6aa0b4ea26d7f02f34bdd48f1ff039b74
4d430171a0287f50fdb36e0f4d32b2afda1bf886
refs/heads/master
<file_sep>FactoryGirl.define do factory :access_token, class: Doorkeeper::Application do application { create(:oauth_application) } resource_owner_id { create(:user).id } end end<file_sep>class Answer < ApplicationRecord belongs_to :question, touch: true belongs_to :user has_many :attachments, as: :attachmentable has_many :comments, as: :commentable validates :body, presence: true accepts_nested_attributes_for :attachments default_scope -> { order :created_at} after_create :calculate_rating private def calculate_rating Reputation.delay.calculate(self) end end <file_sep>require 'sidekiq/web' Rails.application.routes.draw do authenticate :user, lambda { |u| u.admin? } do mount Sidekiq::Web =>'/sidekiq' end use_doorkeeper devise_for :users, controllers: { omniauth_callbacks: 'omniauth_callbacks' } concern :commentable do resources :comments end resources :questions, concerns: :commentable, shallow: true do resources :answers, concerns: :commentable end namespace :api do namespace :v1 do resource :profiles do get :me, on: :collection end resources :questions end end root to: "questions#index" end <file_sep>require 'rails_helper' RSpec.describe Question, type: :model do subject { build(:question) } it { should have_many :answers } it { should have_many :attachments } it { should validate_presence_of :title } it { should validate_presence_of :body } it { should accept_nested_attributes_for :attachments } its(:title) { should == "MyString" } describe 'reputation' do let(:user) { create(:user) } subject { build(:question, user: user) } it 'should calculate reputation after creating' do expect(Reputation).to receive(:calculate).with(subject) subject.save! end it 'should not calculate reputation after update' do subject.save! expect(Reputation).to_not receive(:calculate) subject.update(title: '123') end it 'should save user reputation' do allow(Reputation).to receive(:calculate).and_return(5) expect { subject.save! }.to change(user, :reputation).by(5) end it 'test time' do now = Time.now.utc allow(Time).to receive(:now) { now } subject.save! expect(subject.created_at).to eq now end end it 'test double' do allow(Question).to receive(:find) { double(Question, title: '123') } expect(Question.find(155).title).to eq '123' end end <file_sep>require 'rails_helper' RSpec.describe Answer, type: :model do it { should belong_to :question } it { should have_many :attachments } it { should validate_presence_of :body } it { should accept_nested_attributes_for :attachments } describe 'reputation' do let(:user) { create(:user) } let(:question) { create(:question) } subject { build(:answer, user: user, question: question) } it 'should calculate reputation after creating' do expect(Reputation).to receive(:calculate).with(subject) subject.save! end it 'should not calculate reputation after update' do subject.save! expect(Reputation).to_not receive(:calculate) subject.update(body: '123') end end end <file_sep>source 'https://rubygems.org' git_source(:github) { |repo| "https://github.com/#{repo}.git" } ruby '2.7.0' gem 'rails', '~> 6.0.2', '>= 6.0.2.1' gem 'pg' gem 'puma', '~> 4.1' gem 'sass-rails', '>= 6' gem 'webpacker', '~> 4.0' gem 'turbolinks', '~> 5' gem 'jbuilder', '~> 2.7' gem 'bootsnap', '>= 1.4.2', require: false gem 'slim-rails' gem 'rails-controller-testing' gem 'devise' gem 'coffee-rails' gem 'jquery-rails' gem "twitter-bootstrap-rails" gem 'carrierwave' gem 'remotipart' gem 'private_pub' gem 'thin' gem 'responders' gem 'omniauth' gem 'omniauth-facebook' gem 'cancancan' gem 'pundit' gem 'doorkeeper' gem 'active_model_serializers' gem 'oj' gem 'oj_mimic_json' # gem 'delayed_job_active_record' gem 'whenever' gem 'sidekiq' gem 'sinatra', '>= 1.3.0', require: nil gem 'sidetiq' gem 'mysql2' gem 'thinking-sphinx' gem 'redis-rails' group :development, :test do gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] gem 'rspec-rails' gem 'factory_girl_rails' gem 'database_cleaner' gem 'capybara-webkit' end group :development do gem 'web-console', '>= 3.3.0' gem 'listen', '>= 3.0.5', '< 3.2' gem 'spring' gem 'spring-watcher-listen', '~> 2.0.0' end group :test do gem 'capybara', '>= 2.15' gem 'webdrivers' gem 'shoulda-matchers' gem 'launchy' gem 'json_spec' end gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] <file_sep>class Api::V1::ProfilesController < Api::V1::BaseController def me respond_with current_resource_owner end end<file_sep>require 'rails_helper' describe 'Questions API' do describe 'GET /index' do it_behaves_like "API Authenticable" context 'authorized' do let!(:questions) { create_list(:question, 2) } let(:question) { questions.first } let(:access_token) { create(:access_token) } let!(:answer) { create(:answer, question: question) } before do get '/api/v1/questions', format: :json, access_token: access_token.token end it 'returns 200 status code' do expect(response.status).to eq 200 end it 'returns list of questions' do expect(response.body).to have_json_size(2).at_path('questions') end it 'contains timestamp' do expect(response.body).to be_json_eql(questions.last.created_at.to_json).at_path("meta/timestamp") end %w(id title body created_at updated_at).each do |attr| it "question object contains #{attr}" do expect(response.body).to be_json_eql(question.send(attr.to_sym).to_json).at_path("questions/0/#{attr}") end end context 'answers' do it 'included in question object' do expect(response.body).to have_json_size(1).at_path("questions/0/answers") end %w(id body created_at updated_at).each do |attr| it "answer object contains #{attr}" do expect(response.body).to be_json_eql(answer.send(attr.to_sym).to_json).at_path("questions/0/answers/0/#{attr}") end end end end def do_request(options = {}) get 'api/v1/questions', { format: :json }.merge(options) end end end
6b111aea449ad1a71974654b897d2fc5e70c92af
[ "Ruby" ]
8
Ruby
r4o/qna
b26616be2b50f13ceccaca870747da1f5975a4c2
2b791147569f227fec15fbb90d6b16a5aceb0cda
refs/heads/master
<file_sep>#include <iostream> #include <fstream> #include <windows.h> #include <string> #include <time.h> #include <limits> using namespace std; const string programName = "SystemLogv0.4 | Basic SysInfo Logger\n"; const string programError = "[ERROR] : "; HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE); // handle standard output device. Initially, this is the active console screen buffer. //*************************************************************************************** // Preparatory functions //*************************************************************************************** void callTemplog(); void br(); void clear(); void eicarTest(); float colorSys(string, int); float createTemp(); float getInternet(); float getProcess(); float getStartup(); float getSysinfo(); //*************************************************************************************** // Call temp log using notepad //*************************************************************************************** void callTemplog() { system("start notepad temp.log"); } //*************************************************************************************** // br, breakline. //*************************************************************************************** void br() { cout << endl; } //*************************************************************************************** // Clear: Self explanatory //*************************************************************************************** void clear() { system("cls"); } //*************************************************************************************** // Font coloring: Green(OK), Red(Not Ok), Blue(Reading) //*************************************************************************************** float colorSys(string input, int num) { int txtLength = input.length(), count; switch(num) { case 1: //green for (count = 0; count < txtLength;count++) SetConsoleTextAttribute(console, 2); cout << input; SetConsoleTextAttribute(console, 07); break; case 2: //red for (count = 0; count < txtLength;count++) SetConsoleTextAttribute(console, 4); cout << input; SetConsoleTextAttribute(console, 07); break; case 3: //blue for (count = 0; count < txtLength;count++) SetConsoleTextAttribute(console, 1); cout << input; SetConsoleTextAttribute(console, 07); break; case 4: //purple for (count = 0; count < txtLength;count++) SetConsoleTextAttribute(console, 5); cout << input; SetConsoleTextAttribute(console, 07); break; default: //white for (count = 0; count < txtLength;count++) SetConsoleTextAttribute(console, 07); cout << input; SetConsoleTextAttribute(console, 07); break; } } //*************************************************************************************** // EICAR TEST FILE : http://www.eicar.org/86-0-Intended-use.html //*************************************************************************************** void eicarTest() { string result,final; system("title SystemLogv0.4 - Xtra - Test if AV is working"); ofstream eicar; eicar.open ("eicar.com"); eicar << "X5O!P%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*"; eicar.close(); system("start eicar.com"); ifstream testfile("eicar.com"); if(testfile.is_open()) { while(testfile.good()) { getline(testfile,result); final += result; } colorSys("NOT OK!\n", 2); system ("echo [TESTAV]: NOT OK! >> temp.log"); system("echo. >> temp.log"); } else { colorSys("OK! \n", 1); system ("echo [TESTAV]: OK! >> temp.log"); system("echo. >> temp.log"); } } //*************************************************************************************** //Create the temporary logfile. //*************************************************************************************** float createTemp() { system("del /f /a /q temp.log"); time_t rawtime; //creates and object of the built in time function struct tm * timeinfo; //no idea what this do time ( &rawtime ); //gets the time from the computer timeinfo = localtime ( &rawtime ); //store that time here ofstream templog; templog.open ("temp.log"); templog << "=============================================================================\n"; templog << programName; templog << "Plese pass this log to someone can analyze windows system logs.\n"; templog << "Time created: " << asctime(timeinfo); templog << "=============================================================================\n\n"; templog.close(); system("echo. >> pingLog.x"); system("echo. >> runLog.x"); system("echo. >> sysLog.x"); system("echo. >> startLog.x"); } //*************************************************************************************** //Get Running process //*************************************************************************************** float getProcess() { system("del /f /a /q runLog.x"); string result, final; colorSys("[Status] Get Running Process: ", 3); system("TASKLIST /v /fi \"STATUS eq running\" >> runLog.x"); ifstream logfile("runLog.x"); if(logfile.is_open()) { while(logfile.good()) { getline(logfile,result); final += result; } colorSys("OK!\n", 1); system ("echo [GETPROCESS]: OK! >> temp.log"); system("type runLog.x >> temp.log"); system("echo. >> temp.log"); } else { system ("echo [GETPROCESS]: ERROR LOGFILE ERROR! >> temp.log"); colorSys(programError+"Error! logifle can't be read or didn't exist!", 2); return 0; } } //*************************************************************************************** //Get Startup Process //*************************************************************************************** float getStartup() { system("del /f /a /q startLog.x"); string result, final; colorSys("[Status] Get Startup: ", 3); system("wmic startup get caption,command >> startLog.x"); ifstream logfile("startLog.x"); if(logfile.is_open()) { while(logfile.good()) { getline(logfile,result); final += result; } colorSys("OK!\n", 1); system ("echo [GETSTARTUP]: OK! >> temp.log"); system("type startLog.x >> temp.log"); system("echo. >> temp.log"); } else { system ("echo [GETSTARTUP]: ERROR LOGFILE ERROR! >> temp.log"); colorSys(programError+"Error! logifle can't be read or didn't exist!", 2); return 0; } } //*************************************************************************************** //Get SystemInfo //*************************************************************************************** float getSysinfo() { system("del /f /a /q sysLog.x"); string result, final; system("systeminfo >> sysLog.x"); colorSys("[Status] Get SysInfo: ", 3); ifstream logfile("sysLog.x"); if(logfile.is_open()) { while(logfile.good()) { getline(logfile,result); final += result; } colorSys("OK!\n", 1); system ("echo [GETSYSINFO]: OK! >> temp.log"); system("type sysLog.x >> temp.log"); system("echo. >> temp.log"); } else { system ("echo [GETSYSINFO]: ERROR LOGFILE ERROR! >> temp.log"); colorSys(programError+"Error! logifle can't be read or didn't exist!", 2); return 0; } } //*************************************************************************************** //Pinging google.com for checking the internet connection //*************************************************************************************** float getInternet() { system("del /f /a /q pingLog.x"); string result,final; colorSys("[Status] Pinging sophos.com: ", 3); system("ping sophos.com >>pingLog.x"); ifstream logfile("pingLog.x"); if (logfile.is_open()) { while(logfile.good()) { getline(logfile,result); final += result; } if(final.find("Reply from") != string::npos) { colorSys("OK!\n", 1); system("echo [PING]:OK! >> temp.log"); system("type pingLog.x >> temp.log"); system("echo. >> temp.log"); } else { colorSys("NOT OK!\n", 2); system("echo [PING]:NOT OK! >> temp.log"); system("type pingLog.x >> temp.log"); system("echo. >> temp.log"); } logfile.close(); } else { system("echo [PING]:ERROR LOGFILE ERROR! >> temp.log"); colorSys(programError+"Error! logifle can't be read or didn't exist!", 2); return 0; } } //*************************************************************************************** //Main Progam //*************************************************************************************** int main() { #ifdef _WIN32 || _WIN64 //do nothing #else cout << "This will not run in your system"; return 0; #endif clean: int choice = 0; system("title Creating temp.log"); colorSys("Creating temp.log, please wait..", 1); createTemp(); clear(); start: clear(); system("title SystemLogv0.4 - Basic Sysinfo Scanner"); colorSys("======================================================================\n",4); colorSys(programName,4); colorSys("Just another system information scanner, nothing special.\n",4); colorSys("THIS APPLICATION MUST BE IN ROOT ACCOUNT!\n",4); colorSys("======================================================================\n",4); colorSys(" Scan: \n", 4); colorSys("\t [1] System Information\n", 4); colorSys("\t [2] Running Process\n", 4); colorSys("\t [3] Startup Process\n", 4); colorSys("\t [4] Check Internet Connection (PING)\n", 4); colorSys("\t [5] Log ALL\n", 4); colorSys("\t [6] Xtra: Check your antivirus if working\n", 4); colorSys("\t [7] Refresh\n", 4); colorSys("\t [8] Open User Manual\n", 4); colorSys("\t [9] About\n", 4); colorSys("\t [CTRL+C] Exit\n", 4); br(); colorSys("\tInput: ", 4); while (!(cin >> choice)) { cin.clear(); cin.ignore(numeric_limits<int>::max(), '\n'); colorSys("\tPlease enter a proper input: ", 4); } br();br(); switch(choice) { case 1: system("title SystemLogv0.4 - Get System Information"); getSysinfo(); callTemplog(); goto start; break; case 2: system("title SystemLogv0.4 - Get Running Process"); getProcess(); callTemplog(); goto start; break; case 3: system("title SystemLogv0.4 - Get Startup Process"); getStartup(); callTemplog(); goto start; break; case 4: system("title SystemLogv0.4 - Pinging sophos.com"); getInternet(); callTemplog(); goto start; break; case 5: system("title SystemLogv0.4 - Log all"); getSysinfo(); getProcess(); getStartup(); getInternet(); callTemplog(); goto start; break; case 6: eicarTest(); callTemplog(); goto start; break; case 7: goto clean; break; case 8: system("start usermanual.pdf"); main(); break; case 9: clear(); system("title SystemLogv0.4 - About"); colorSys("======================================================================\n",1); colorSys(programName,5); br(); colorSys("SystemLog is a basic system information logger that gets specific logs in any\n",5); colorSys("Windows operating system later than Windows XP. This application uses some\n",5); colorSys("Windows utilities to get specific logs depending on the needs of the user.\n",5); br(); colorSys("======================================================================\n",1); br(); colorSys("Programming is art, I suck at art.\n",2); colorSys("(Press any key to go back.)",2); system("pause>nul"); goto start; break; case 0: while(true) { return 0; } break; default: main(); break; } return 0; } <file_sep>scanme My first C++ work, It's crap and it's only run for windows
f537325c6ec07828194e60725ed95a7641724238
[ "Markdown", "C++" ]
2
C++
colorfulnanairo/scanme
37e02faeb46b05a5caf5c1c5eddd0169d30a4000
14780c5ba219e3b6856b484cf34d38303095dd2d
refs/heads/master
<repo_name>albanm/node-libxslt<file_sep>/index.js /** * Node.js bindings for libxslt compatible with libxmljs * @module libxslt */ var fs = require('fs'); var libxmljs = require('node1-libxmljsmt-myh'); var binding = require('bindings')('node-libxslt'); binding.registerEXSLT(); /** * The libxmljs module. Prevents the need for a user's code to require it a second time. Also prevent weird bugs. */ exports.libxmljs = libxmljs; /** * A compiled stylesheet. Do not call this constructor, instead use parse or parseFile. * * store both the source document and the parsed stylesheet * if we don't store the stylesheet doc it will be deleted by garbage collector and it will result in segfaults. * * @constructor * @param {Document} stylesheetDoc - XML document source of the stylesheet * @param {Document} stylesheetObj - Simple wrapper of a libxslt stylesheet */ var Stylesheet = function(stylesheetDoc, stylesheetObj){ this.stylesheetDoc = stylesheetDoc; this.stylesheetObj = stylesheetObj; }; /** * Parse a XSL stylesheet * * If no callback is given the function will run synchronously and return the result or throw an error. * * @param {string|Document} source - The content of the stylesheet as a string or a [libxmljs document]{@link https://github.com/polotek/libxmljs/wiki/Document} * @param {parseCallback} [callback] - The callback that handles the response. Expects err and Stylesheet object. * @return {Stylesheet} Only if no callback is given. */ exports.parse = function(source, callback) { // stylesheet can be given as a string or a pre-parsed xml document if (typeof source === 'string') { try { source = libxmljs.parseXml(source, { nocdata: true }); } catch (err) { if (callback) return callback(err); throw err; } } if (callback) { binding.stylesheetAsync(source, function(err, stylesheet){ if (err) return callback(err); callback(null, new Stylesheet(source, stylesheet)); }); } else { return new Stylesheet(source, binding.stylesheetSync(source)); } }; /** * Callback to the parse function * @callback parseCallback * @param {error} [err] * @param {Stylesheet} [stylesheet] */ /** * Parse a XSL stylesheet * * @param {stringPath} sourcePath - The path of the file * @param {parseFileCallback} callback - The callback that handles the response. Expects err and Stylesheet object. */ exports.parseFile = function(sourcePath, callback) { fs.readFile(sourcePath, 'utf8', function(err, data){ if (err) return callback(err); exports.parse(data, callback); }); }; /** * Callback to the parseFile function * @callback parseFileCallback * @param {error} [err] * @param {Stylesheet} [stylesheet] */ /** * Options for applying a stylesheet * @typedef applyOptions * @property {String} outputFormat - Force the type of the output, either 'document' or 'string'. Default is to use the type of the input. * @property {boolean} noWrapParams - If true then the parameters are XPath expressions, otherwise they are treated as strings. Default is false. */ /** * Apply a stylesheet to a XML document * * If no callback is given the function will run synchronously and return the result or throw an error. * * @param {string|Document} source - The XML content to apply the stylesheet to given as a string or a [libxmljs document]{@link https://github.com/polotek/libxmljs/wiki/Document} * @param {object} [params] - Parameters passed to the stylesheet ({@link http://www.w3schools.com/xsl/el_with-param.asp}) * @param {applyOptions} [options] - Options * @param {applyCallback} [callback] - The callback that handles the response. Expects err and result of the same type as the source param passed to apply. * @return {string|Document} Only if no callback is given. Type is the same as the source param. */ Stylesheet.prototype.apply = function(source, params, options, callback) { // params and options parameters are optional if (typeof options === 'function') { callback = options; options = {}; } if (typeof params === 'function') { callback = params; params = {}; options = {}; } params = params || {}; options = options || {}; if (!options.noWrapParams) { var wrappedParams = {}; for(var p in params) { // string parameters must be surrounded by quotes to be usable by the stylesheet if (typeof params[p] === 'string') wrappedParams[p] = '"' + params[p] + '"'; else wrappedParams[p] = params[p]; } params = wrappedParams; } // Output format can be passed as explicit option or // is implicit and mapped to the input format var outputString; if (options.outputFormat) { outputString = (options.outputFormat === 'string'); } else { outputString = (typeof source === 'string'); } // xml can be given as a string or a pre-parsed xml document if (typeof source === 'string') { try { source = libxmljs.parseXml(source); } catch (err) { if (callback) return callback(err); throw err; } } // flatten the params object in an array var paramsArray = []; for(var key in params) { paramsArray.push(key); paramsArray.push(params[key]); } var docResult = new libxmljs.Document(); if (callback) { binding.applyAsync(this.stylesheetObj, source, paramsArray, outputString, docResult, function(err, strResult){ if (err) return callback(err); callback(null, outputString ? strResult : docResult); }); } else { var strResult = binding.applySync(this.stylesheetObj, source, paramsArray, outputString, docResult); return outputString ? strResult : docResult; } }; /** * Callback to the Stylesheet.apply function * @callback applyCallback * @param {error} [err] - Error either from parsing the XML document if given as a string or from applying the styleshet * @param {string|Document} [result] Result of the same type as the source param passed to apply */ /** * Apply a stylesheet to a XML file * * @param {string} sourcePath - The path of the file to read * @param {object} [params] - Parameters passed to the stylesheet ({@link http://www.w3schools.com/xsl/el_with-param.asp}) * @param {applyOptions} [options] - Options * @param {applyToFileCallback} callback The callback that handles the response. Expects err and result as string. */ Stylesheet.prototype.applyToFile = function(sourcePath, params, options, callback) { var that = this; fs.readFile(sourcePath, 'utf8', function(err, data){ if (err) return callback(err); that.apply(data, params, options, callback); }); }; /** * Callback to the Stylesheet.applyToFile function * @callback applyToFileCallback * @param {error} [err] - Error either from reading the file, parsing the XML document or applying the styleshet * @param {string} [result] */ <file_sep>/binding.gyp { "targets": [ { "target_name": "node-libxslt", "sources": [ "src/node_libxslt.cc", "src/stylesheet.cc" ], "include_dirs": ["<!(node -e \"require('nan')\")"], 'dependencies': [ './deps/libxslt.gyp:libxslt', './deps/libxslt.gyp:libexslt' ] } ] }<file_sep>/src/node_libxslt.cc #define BUILDING_NODE_EXTENSION #include <iostream> #include <node.h> #include <nan.h> #include <libxslt/xslt.h> #include <libxslt/transform.h> #include <libxslt/xsltutils.h> // includes from libxmljs #include <xml_syntax_error.h> #include <xml_document.h> #include "./node_libxslt.h" #include "./stylesheet.h" using namespace v8; //int vasprintf (char **strp, const char *fmt, va_list ap); int vasprintf(char** strp, const char* fmt, va_list ap) { va_list ap2; va_copy(ap2, ap); char tmp[1]; int size = vsnprintf(tmp, 1, fmt, ap2); if (size <= 0) return size; va_end(ap2); size += 1; *strp = (char*)malloc(size * sizeof(char)); return vsnprintf(*strp, size, fmt, ap); } static xmlDoc* copyDocument(Local<Value> input) { libxmljs::XmlDocument* docWrapper = Nan::ObjectWrap::Unwrap<libxmljs::XmlDocument>(Nan::To<v8::Object>(input).ToLocalChecked()); xmlDoc* stylesheetDoc = docWrapper->xml_obj; return xmlCopyDoc(stylesheetDoc, true); } // Directly inspired by nokogiri: // https://github.com/sparklemotion/nokogiri/blob/24bb843327306d2d71e4b2dc337c1e327cbf4516/ext/nokogiri/xslt_stylesheet.c#L76 static void xslt_generic_error_handler(void * ctx, const char *msg, ...) { char * message; va_list args; va_start(args, msg); vasprintf(&message, msg, args); va_end(args); strncpy((char*)ctx, message, 2048); free(message); } NAN_METHOD(StylesheetSync) { Nan::HandleScope scope; char* errstr = new char[2048]; xsltSetGenericErrorFunc(errstr, xslt_generic_error_handler); xmlDoc* doc = copyDocument(info[0]); xsltStylesheetPtr stylesheet = xsltParseStylesheetDoc(doc); xsltSetGenericErrorFunc(NULL, NULL); if (!stylesheet) { xmlFreeDoc(doc); return Nan::ThrowError(errstr); } Local<Object> stylesheetWrapper = Stylesheet::New(stylesheet); info.GetReturnValue().Set(stylesheetWrapper); } // for memory the segfault i previously fixed were due to xml documents being deleted // by garbage collector before their associated stylesheet. class StylesheetWorker : public Nan::AsyncWorker { public: StylesheetWorker(xmlDoc* doc, Nan::Callback *callback) : Nan::AsyncWorker(callback), doc(doc) {} ~StylesheetWorker() {} // Executed inside the worker-thread. // It is not safe to access V8, or V8 data structures // here, so everything we need for input and output // should go on `this`. void Execute () { libxmljs::WorkerSentinel workerSentinel(workerParent); // Error management is probably not really thread safe :( errstr = new char[2048];; xsltSetGenericErrorFunc(errstr, xslt_generic_error_handler); result = xsltParseStylesheetDoc(doc); xsltSetGenericErrorFunc(NULL, NULL); } // Executed when the async work is complete // this function will be run inside the main event loop // so it is safe to use V8 again void HandleOKCallback () { Nan::HandleScope scope; if (!result) { xmlFreeDoc(doc); Local<Value> argv[] = { Nan::Error(errstr) }; callback->Call(1, argv); } else { Local<Object> resultWrapper = Stylesheet::New(result); Local<Value> argv[] = { Nan::Null(), resultWrapper }; callback->Call(2, argv); } }; private: libxmljs::WorkerParent workerParent; xmlDoc* doc; xsltStylesheetPtr result; char* errstr; }; NAN_METHOD(StylesheetAsync) { Nan::HandleScope scope; xmlDoc* doc = copyDocument(info[0]); Nan::Callback *callback = new Nan::Callback(info[1].As<Function>()); StylesheetWorker* worker = new StylesheetWorker(doc, callback); Nan::AsyncQueueWorker(worker); return; } // duplicate from https://github.com/bsuh/node_xslt/blob/master/node_xslt.cc void freeArray(char **array, int size) { for (int i = 0; i < size; i++) { free(array[i]); } free(array); } // transform a v8 array into a char** to pass params to xsl transform // inspired by https://github.com/bsuh/node_xslt/blob/master/node_xslt.cc char** PrepareParams(Local<Array> array, Isolate *isolate) { uint32_t arrayLen = array->Length(); char** params = (char **)malloc(sizeof(char *) * (arrayLen + 1)); memset(params, 0, sizeof(char *) * (array->Length() + 1)); for (unsigned int i = 0; i < array->Length(); i++) { Local<String> param = Nan::To<v8::String>(Nan::Get(array, i).ToLocalChecked()).ToLocalChecked(); params[i] = (char *)malloc(sizeof(char) * (param->Utf8Length(isolate) + 1)); param->WriteUtf8(isolate, params[i]); } return params; } NAN_METHOD(ApplySync) { Nan::HandleScope scope; Stylesheet* stylesheet = Nan::ObjectWrap::Unwrap<Stylesheet>(Nan::To<v8::Object>(info[0]).ToLocalChecked()); libxmljs::XmlDocument* docSource = Nan::ObjectWrap::Unwrap<libxmljs::XmlDocument>(Nan::To<v8::Object>(info[1]).ToLocalChecked()); Local<Array> paramsArray = Local<Array>::Cast(info[2]); bool outputString = Nan::To<v8::Boolean>(info[3]).ToLocalChecked()->Value(); char** params = PrepareParams(paramsArray, info.GetIsolate()); xmlDoc* result = xsltApplyStylesheet(stylesheet->stylesheet_obj, docSource->xml_obj, (const char **)params); if (!result) { freeArray(params, paramsArray->Length()); return Nan::ThrowError("Failed to apply stylesheet"); } if (outputString) { // As well as a libxmljs document, prepare a string result unsigned char* resStr; int len; xsltSaveResultToString(&resStr,&len,result,stylesheet->stylesheet_obj); xmlFreeDoc(result); info.GetReturnValue().Set(Nan::New<String>(resStr ? (char*)resStr : "").ToLocalChecked()); if (resStr) xmlFree(resStr); } else { // Fill a result libxmljs document. // for some obscure reason I didn't manage to create a new libxmljs document in applySync, // but passing a document by reference and modifying its content works fine // replace the empty document in docResult with the result of the stylesheet libxmljs::XmlDocument* docResult = Nan::ObjectWrap::Unwrap<libxmljs::XmlDocument>(Nan::To<v8::Object>(info[4]).ToLocalChecked()); docResult->xml_obj->_private = NULL; xmlFreeDoc(docResult->xml_obj); docResult->xml_obj = result; result->_private = docResult; } freeArray(params, paramsArray->Length()); return; } // for memory the segfault i previously fixed were due to xml documents being deleted // by garbage collector before their associated stylesheet. class ApplyWorker : public Nan::AsyncWorker { public: ApplyWorker(Stylesheet* stylesheet, libxmljs::XmlDocument* docSource, char** params, int paramsLength, bool outputString, libxmljs::XmlDocument* docResult, Nan::Callback *callback) : Nan::AsyncWorker(callback), stylesheet(stylesheet), docSource(docSource), params(params), paramsLength(paramsLength), outputString(outputString), docResult(docResult) {} ~ApplyWorker() {} // Executed inside the worker-thread. // It is not safe to access V8, or V8 data structures // here, so everything we need for input and output // should go on `this`. void Execute () { libxmljs::WorkerSentinel workerSentinel(workerParent); result = xsltApplyStylesheet(stylesheet->stylesheet_obj, docSource->xml_obj, (const char **)params); } // Executed when the async work is complete // this function will be run inside the main event loop // so it is safe to use V8 again void HandleOKCallback () { Nan::HandleScope scope; if (!result) { Local<Value> argv[] = { Nan::Error("Failed to apply stylesheet") }; freeArray(params, paramsLength); callback->Call(1, argv); return; } if(!outputString) { // for some obscure reason I didn't manage to create a new libxmljs document in applySync, // but passing a document by reference and modifying its content works fine // replace the empty document in docResult with the result of the stylesheet docResult->xml_obj->_private = NULL; xmlFreeDoc(docResult->xml_obj); docResult->xml_obj = result; result->_private = docResult; Local<Value> argv[] = { Nan::Null() }; freeArray(params, paramsLength); callback->Call(1, argv); } else { unsigned char* resStr; int len; int cnt=xsltSaveResultToString(&resStr,&len,result,stylesheet->stylesheet_obj); xmlFreeDoc(result); Local<Value> argv[] = { Nan::Null(), Nan::New<String>(resStr ? (char*)resStr : "").ToLocalChecked()}; if (resStr) xmlFree(resStr); freeArray(params, paramsLength); callback->Call(2, argv); } }; private: libxmljs::WorkerParent workerParent; Stylesheet* stylesheet; libxmljs::XmlDocument* docSource; char** params; int paramsLength; bool outputString; libxmljs::XmlDocument* docResult; xmlDoc* result; }; NAN_METHOD(ApplyAsync) { Nan::HandleScope scope; Stylesheet* stylesheet = Nan::ObjectWrap::Unwrap<Stylesheet>(Nan::To<v8::Object>(info[0]).ToLocalChecked()); libxmljs::XmlDocument* docSource = Nan::ObjectWrap::Unwrap<libxmljs::XmlDocument>(Nan::To<v8::Object>(info[1]).ToLocalChecked()); Local<Array> paramsArray = Local<Array>::Cast(info[2]); bool outputString = Nan::To<v8::Boolean>(info[3]).ToLocalChecked()->Value(); //if (!outputString) { libxmljs::XmlDocument* docResult = Nan::ObjectWrap::Unwrap<libxmljs::XmlDocument>(Nan::To<v8::Object>(info[4]).ToLocalChecked()); //} Nan::Callback *callback = new Nan::Callback(info[5].As<Function>()); char** params = PrepareParams(paramsArray, info.GetIsolate()); ApplyWorker* worker = new ApplyWorker(stylesheet, docSource, params, paramsArray->Length(), outputString, docResult, callback); for (uint32_t i = 0; i < 5; ++i) worker->SaveToPersistent(i, info[i]); Nan::AsyncQueueWorker(worker); return; } NAN_METHOD(RegisterEXSLT) { exsltRegisterAll(); return; } // Compose the module by assigning the methods previously prepared void InitAll(Local<Object> exports) { Stylesheet::Init(exports); Nan::Set(exports, Nan::New("stylesheetSync").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(StylesheetSync)).ToLocalChecked()); Nan::Set(exports, Nan::New("stylesheetAsync").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(StylesheetAsync)).ToLocalChecked()); Nan::Set(exports, Nan::New("applySync").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(ApplySync)).ToLocalChecked()); Nan::Set(exports, Nan::New("applyAsync").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(ApplyAsync)).ToLocalChecked()); Nan::Set(exports, Nan::New("registerEXSLT").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(RegisterEXSLT)).ToLocalChecked()); } NODE_MODULE(node_libxslt, InitAll); <file_sep>/deps/libxslt.gyp { 'variables': { 'target_arch%': 'ia32', # build for a 32-bit CPU by default 'xmljs_include_dirs%': [], 'xmljs_libraries%': [], }, 'target_defaults': { 'default_configuration': 'Release', 'configurations': { 'Debug': { 'defines': [ 'DEBUG', '_DEBUG' ], 'msvs_settings': { 'VCCLCompilerTool': { 'RuntimeLibrary': 1, # static debug }, }, }, 'Release': { 'defines': [ 'NDEBUG' ], 'msvs_settings': { 'VCCLCompilerTool': { 'RuntimeLibrary': 0, # static release }, }, } }, 'defines': ['HAVE_CONFIG_H','LIBXSLT_STATIC','WITH_MODULES'], 'include_dirs': [ 'libxslt/', # platform and arch-specific headers 'libxslt.config/<(OS)/<(target_arch)', '<@(xmljs_include_dirs)' ] }, 'targets': [ { 'target_name': 'libxslt', 'type': 'static_library', 'sources': [ 'libxslt/libxslt/attributes.c', 'libxslt/libxslt/attrvt.c', 'libxslt/libxslt/documents.c', 'libxslt/libxslt/extensions.c', 'libxslt/libxslt/extra.c', 'libxslt/libxslt/functions.c', 'libxslt/libxslt/imports.c', 'libxslt/libxslt/keys.c', 'libxslt/libxslt/namespaces.c', 'libxslt/libxslt/numbers.c', 'libxslt/libxslt/pattern.c', 'libxslt/libxslt/preproc.c', 'libxslt/libxslt/preproc.h', 'libxslt/libxslt/security.c', 'libxslt/libxslt/security.h', 'libxslt/libxslt/templates.c', 'libxslt/libxslt/transform.c', 'libxslt/libxslt/variables.c', 'libxslt/libxslt/xslt.c', 'libxslt/libxslt/xsltlocale.c', 'libxslt/libxslt/xsltutils.c' ], 'link_settings': { 'libraries': [ '<@(xmljs_libraries)', ] }, 'direct_dependent_settings': { 'defines': ['LIBXSLT_STATIC'], 'include_dirs': [ 'libxslt/', # platform and arch-specific headers 'libxslt.config/<(OS)/<(target_arch)', '<@(xmljs_include_dirs)' ], } }, { 'target_name': 'libexslt', 'type': 'static_library', 'sources': [ 'libxslt/libexslt/common.c', 'libxslt/libexslt/crypto.c', 'libxslt/libexslt/date.c', 'libxslt/libexslt/dynamic.c', 'libxslt/libexslt/exslt.c', 'libxslt/libexslt/functions.c', 'libxslt/libexslt/math.c', 'libxslt/libexslt/saxon.c', 'libxslt/libexslt/sets.c', 'libxslt/libexslt/strings.c' ], 'dependencies': [ 'libxslt' ], 'link_settings': { 'libraries': [ '<@(xmljs_libraries)' ] } } ] }<file_sep>/src/stylesheet.cc #include <node.h> #include <nan.h> #include "./stylesheet.h" using namespace v8; Nan::Persistent<Function> Stylesheet::constructor; Stylesheet::Stylesheet(xsltStylesheetPtr stylesheetPtr) : stylesheet_obj(stylesheetPtr) {} Stylesheet::~Stylesheet() { xsltFreeStylesheet(stylesheet_obj); } void Stylesheet::Init(Local<Object> exports) { // Prepare constructor template Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(); tpl->SetClassName(Nan::New<String>("Stylesheet").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); constructor.Reset(Nan::GetFunction(tpl).ToLocalChecked()); } // not called from node, private api Local<Object> Stylesheet::New(xsltStylesheetPtr stylesheetPtr) { Nan::EscapableHandleScope scope; //Local<Object> wrapper = Nan::New(constructor)->NewInstance(); Local<Object> wrapper = Nan::NewInstance(Nan::New(constructor)).ToLocalChecked(); Stylesheet* stylesheet = new Stylesheet(stylesheetPtr); stylesheet->Wrap(wrapper); return scope.Escape(wrapper); } <file_sep>/src/node_libxslt.h #include <node.h> #include <nan.h> NAN_METHOD(StylesheetSync); NAN_METHOD(StylesheetASync); NAN_METHOD(ApplySync); NAN_METHOD(ApplyAsync); NAN_METHOD(RegisterEXSLT); <file_sep>/deps/checkdep.js "use strict"; var fs = require("fs"); var path = require("path"); var events = require("events"); var util = require("util"); function Semaphore(initial) { if (typeof initial === "undefined") initial = 1; this.counter = initial; } util.inherits(Semaphore, events.EventEmitter); Semaphore.prototype.wait = function(count) { if (typeof count === "undefined") count = 1; this.counter += count; } Semaphore.prototype.signal = function() { --this.counter; if (this.counter === 0) { this.emit("done"); } } function OsArch(os, arch, dir) { this.os = os; this.arch = arch; this.dir = dir; this.output = {}; } function multiMatch(s, r) { var m, res = [], n = 0; while ((m = r.exec(s)) !== null) { res[n++] = m; } return res; } function ConfigInput(data) { var text = this.text = data.toString(); var defs = this.defs = []; var d = multiMatch(text, /^#undef (\S+)/mg); d.forEach(function(m) { defs.push(m[1]); }); this.placeholders = text.match(/@\w+@/g); if (this.placeholders) { var re = text.replace(/([^A-Za-z0-9_@ ,;\r\n])/g, "\\$1"); re = re.replace(/@\w+@/g, "(.*?)"); this.re = new RegExp(re); this.defs = defs.concat(this.placeholders); } else { this.re = null; } } function ConfigOutput(data) { this.text = data.toString(); var defs = this.defs = {}; var d = multiMatch(this.text, /^\/\* #undef (\S+)\s*\*\/|^#define (\S+)\s*(.*)|^#undef (\S+)/mg); d.forEach(function(m) { var name = m[2], val = m[3]; if (m[1]) { name = m[1]; val = "/* #undef */"; } else if (m[4]) { name = m[4]; val = "#undef"; } defs[name] = val; }); } function deps(pkg, configs, callback) { var central = new Semaphore(); var indir = path.join(__dirname, pkg); var confdir = path.join(__dirname, pkg + ".config"); var archs = []; var input = {}; fs.readdir(confdir, function(err, oss) { if (err) { central.emit("error", err); return; } oss.forEach(function(os) { central.emit("os", os); }); central.wait(oss.length); central.signal(); }); central.on("os", function(os) { fs.readdir(path.join(confdir, os), function(err, archs) { if (err) { central.emit("error", err); return; } archs.forEach(function(arch) { central.emit("arch", os, arch); }); central.wait(archs.length); central.signal(); }); }); central.on("arch", function(os, arch) { var archdir = path.join(confdir, os, arch); var oa = new OsArch(os, arch, archdir); archs.push(oa); configs.forEach(function(cfg) { central.emit("oac", oa, cfg); }); central.wait(configs.length); central.signal(); }); central.on("oac", function(osArch, config) { fs.readFile(path.join(osArch.dir, config), function(err, content) { if (err) { central.emit("error", err); return; } osArch.output[config] = new ConfigOutput(content); central.signal(); }); }); configs.forEach(function(config) { fs.readFile(path.join(indir, config + ".in"), function(err, content) { if (err) { central.emit("error", err); return; } input[config] = new ConfigInput(content); central.signal(); }); }); central.wait(configs.length); central.on("done", function() { callback(pkg, configs, input, archs); }); } function pad(s, len) { if (typeof len === "undefined") len = 25; while (s.length < len) s += " "; if (s.length > len) s = s.substr(s.length - len); return s; } function report(pkg, configs, inputs, archs) { archs.forEach(function(arch, index) { console.log((index + 1) + ": " + arch.os + " / " + arch.arch); }); configs.forEach(function(config) { console.log(""); console.log("=== " + config + " ==="); var marks = archs.map(function(arch, index) { return String((index + 1)%10); }).join(" "); console.log(pad("") + " " + marks); var input = inputs[config]; var outputs = archs.map(function(arch) { var output = arch.output[config], defs = output.defs; if (input.placeholders) { var m = output.text.match(input.re); if (m !== null) { var i = m.length, p = input.placeholders; while (i > 0) { --i; defs[p[i]] = m[i + 1]; } } } return defs; }); inputs[config].defs.forEach(function(setting) { var same = outputs[0][setting]; var marks = outputs.map(function(output) { var val = output[setting]; if (same !== null && val !== same) same = null; if (typeof val === "undefined") val = "?"; else if (val === "#undef") val = "N"; else if (val === "/* #undef */") val = "n"; else if (val === "/**/") val = "Y"; else val = val.substr(0, 1); return val; }).join(" "); var note; if (same === null) note = " !!"; else if (typeof same === "undefined") note = " ??"; else note = " " + same; console.log(pad(setting) + " " + marks + note); }); }); } deps( "libxslt", ["config.h", "libxslt/xsltconfig.h", "libexslt/exsltconfig.h"], report); <file_sep>/example.js // Mostly to run for debugging purposes var fs = require('fs'); var libxslt = require('./index'); var stylesheetSource = fs.readFileSync('./test/resources/cd.xsl', 'utf8'); var docSource = fs.readFileSync('./test/resources/cd.xml', 'utf8'); var stylesheet = libxslt.parse(stylesheetSource); //var result = stylesheet.apply(docSource); //console.log(result); stylesheet.apply(docSource, function(err, result){ console.log(result); });<file_sep>/src/document.h // Very simple v8 wrapper for xml document, see "Wrapping C++ objects" section here http://nodejs.org/api/addons.html #ifndef SRC_DOCUMENT_H_ #define SRC_DOCUMENT_H_ #include <libxslt/xslt.h> #include <libxslt/transform.h> #include <libxslt/xsltutils.h> #include <libexslt/exslt.h> class Document : public Nan::ObjectWrap { public: static void Init(v8::Local<v8::Object> exports); static v8::Local<v8::Object> New(xmlDocumentPtr DocumentPtr); static NAN_METHOD(TransformSync); xmlDocumentPtr Document_obj; private: explicit Document(xmlDocumentPtr DocumentPtr); ~Document(); static Nan::Persistent<v8::Function> constructor; }; #endif // SRC_DOCUMENT_H_<file_sep>/README.md node-libxslt ============ [![Build status](https://travis-ci.org/albanm/node-libxslt.svg)](https://travis-ci.org/albanm/node-libxslt) [![Code Climate](https://codeclimate.com/github/albanm/node-libxslt/badges/gpa.svg)](https://codeclimate.com/github/albanm/node-libxslt) [![NPM version](https://badge.fury.io/js/libxslt.svg)](http://badge.fury.io/js/libxslt) Node.js bindings for [libxslt](http://xmlsoft.org/libxslt/) compatible with [libxmljs](https://github.com/polotek/libxmljs/issues/226). Installation ------------ npm install libxslt From source: git clone https://github.com/albanm/node-libxslt.git git submodule update --init npm install npm test Basic usage ----------- ```js var libxslt = require('libxslt'); libxslt.parse(stylesheetString, function(err, stylesheet){ var params = { MyParam: 'my value' }; // 'params' parameter is optional stylesheet.apply(documentString, params, function(err, result){ // err contains any error from parsing the document or applying the stylesheet // result is a string containing the result of the transformation }); }); ``` Libxmljs integration -------------------- Node-libxslt depends on [libxmljs](https://github.com/polotek/libxmljs/issues/226) in the same way that [libxslt](http://xmlsoft.org/libxslt/) depends on [libxml](http://xmlsoft.org/). This dependancy makes possible to bundle and to load in memory libxml only once for users of both libraries. The libxmljs module required by node-libxslt is exposed as ```require('libxslt').libxmljs```. This prevents depending on libxmljs twice which is not optimal and source of weird bugs. It is possible to work with libxmljs documents instead of strings: ```js var lixslt = require('libxslt'); var libxmljs = libxslt.libxmljs; var stylesheetObj = libxmljs.parseXml(stylesheetString, { nocdata: true }); var stylesheet = libxslt.parse(stylesheetObj); var document = libxmljs.parseXml(documentString); stylesheet.apply(document, function(err, result){ // result is now a libxmljs document containing the result of the transformation }); ``` This is only useful if you already needed to parse a document before applying the stylesheet for previous manipulations. Or if you wish to be returned a document instead of a string for ulterior manipulations. In these cases you will prevent extraneous parsings and serializations. Includes -------- XSL includes are supported but relative paths must be given from the execution directory, usually the root of the project. Includes are resolved when parsing the stylesheet by libxml. Therefore the parsing task becomes IO bound, which is why you should not use synchronous parsing when you expect some includes. Sync or async ------------- The same *parse()* and *apply()* functions can be used in synchronous mode simply by removing the callback parameter. In this case if a parsing error occurs it will be thrown. ```js var lixslt = require('libxslt'); var stylesheet = libxslt.parse(stylesheetString); var result = stylesheet.apply(documentString); ``` The asynchronous functions use the [libuv work queue](http://nikhilm.github.io/uvbook/threads.html#libuv-work-queue) to provide parallelized computation in node.js worker threads. This makes it non-blocking for the main event loop of node.js. Note that libxmljs parsing doesn't use the work queue, so only a part of the process is actually parallelized. A small benchmark is available in the project. It has a very limited scope, it uses always the same small transformation a few thousand times. To run it use: node benchmark.js This is an example of its results with an intel core i5 3.1GHz: ``` 10000 synchronous parse from parsed doc in 52ms = 192308/s 10000 asynchronous parse in series from parsed doc in 229ms = 43668/s 10000 asynchronous parse in parallel from parsed doc in 56ms = 178571/s 10000 synchronous apply from parsed doc in 329ms = 30395/s 10000 asynchronous apply in series from parsed doc in 569ms = 17575/s 10000 asynchronous apply in parallel from parsed doc in 288ms = 34722/s ``` Observations: - it's pretty fast ! - asynchronous is slower when running in series. - asynchronous can become faster when concurrency is high. Conclusion: - use asynchronous by default it will be kinder to your main event loop and is pretty fast anyway. - use synchronous only if you really want the highest performance and expect low concurrency. - of course you can also use synchronous simply to reduce code depth. If you don't expect a huge load it will be ok. - DO NOT USE synchronous parsing if there is some includes in your XSL stylesheets. Environment compatibility ------------------------- For now 64bits linux and 32bits windows are confirmed. Other environments are probably ok, but not checked. Please report an issue if you encounter some difficulties. Node-libxslt depends on [node-gyp](https://github.com/TooTallNate/node-gyp), you will need to meet its requirements. This can be a bit painful mostly for windows users. The node-gyp version bundled in your npm will have to be greater than 0.13.0, so you might have to follow [these instructions to upgrade](https://github.com/TooTallNate/node-gyp/wiki/Updating-npm's-bundled-node-gyp). There is no system dependancy otherwise, libxslt is bundled in the project. API Reference ============= Node.js bindings for libxslt compatible with libxmljs <a name="module_libxslt.libxmljs"></a> ### libxslt.libxmljs The libxmljs module. Prevents the need for a user's code to require it a second time. Also prevent weird bugs. **Kind**: static property of <code>[libxslt](#module_libxslt)</code> <a name="module_libxslt.parse"></a> ### libxslt.parse(source, [callback]) โ‡’ <code>Stylesheet</code> Parse a XSL stylesheet If no callback is given the function will run synchronously and return the result or throw an error. **Kind**: static method of <code>[libxslt](#module_libxslt)</code> **Returns**: <code>Stylesheet</code> - Only if no callback is given. | Param | Type | Description | | --- | --- | --- | | source | <code>string</code> &#124; <code>Document</code> | The content of the stylesheet as a string or a [libxmljs document](https://github.com/polotek/libxmljs/wiki/Document) | | [callback] | <code>parseCallback</code> | The callback that handles the response. Expects err and Stylesheet object. | <a name="module_libxslt.parseFile"></a> ### libxslt.parseFile(sourcePath, callback) Parse a XSL stylesheet **Kind**: static method of <code>[libxslt](#module_libxslt)</code> | Param | Type | Description | | --- | --- | --- | | sourcePath | <code>stringPath</code> | The path of the file | | callback | <code>parseFileCallback</code> | The callback that handles the response. Expects err and Stylesheet object. | <a name="module_libxslt..Stylesheet"></a> ### libxslt~Stylesheet **Kind**: inner class of <code>[libxslt](#module_libxslt)</code> * [~Stylesheet](#module_libxslt..Stylesheet) * [new Stylesheet(stylesheetDoc, stylesheetObj)](#new_module_libxslt..Stylesheet_new) * [.apply(source, [params], [options], [callback])](#module_libxslt..Stylesheet+apply) โ‡’ <code>string</code> &#124; <code>Document</code> * [.applyToFile(sourcePath, [params], [options], callback)](#module_libxslt..Stylesheet+applyToFile) <a name="new_module_libxslt..Stylesheet_new"></a> #### new Stylesheet(stylesheetDoc, stylesheetObj) A compiled stylesheet. Do not call this constructor, instead use parse or parseFile. store both the source document and the parsed stylesheet if we don't store the stylesheet doc it will be deleted by garbage collector and it will result in segfaults. | Param | Type | Description | | --- | --- | --- | | stylesheetDoc | <code>Document</code> | XML document source of the stylesheet | | stylesheetObj | <code>Document</code> | Simple wrapper of a libxslt stylesheet | <a name="module_libxslt..Stylesheet+apply"></a> #### stylesheet.apply(source, [params], [options], [callback]) โ‡’ <code>string</code> &#124; <code>Document</code> Apply a stylesheet to a XML document If no callback is given the function will run synchronously and return the result or throw an error. **Kind**: instance method of <code>[Stylesheet](#module_libxslt..Stylesheet)</code> **Returns**: <code>string</code> &#124; <code>Document</code> - Only if no callback is given. Type is the same as the source param. | Param | Type | Description | | --- | --- | --- | | source | <code>string</code> &#124; <code>Document</code> | The XML content to apply the stylesheet to given as a string or a [libxmljs document](https://github.com/polotek/libxmljs/wiki/Document) | | [params] | <code>object</code> | Parameters passed to the stylesheet ([http://www.w3schools.com/xsl/el_with-param.asp](http://www.w3schools.com/xsl/el_with-param.asp)) | | [options] | <code>applyOptions</code> | Options | | [callback] | <code>applyCallback</code> | The callback that handles the response. Expects err and result of the same type as the source param passed to apply. | <a name="module_libxslt..Stylesheet+applyToFile"></a> #### stylesheet.applyToFile(sourcePath, [params], [options], callback) Apply a stylesheet to a XML file **Kind**: instance method of <code>[Stylesheet](#module_libxslt..Stylesheet)</code> | Param | Type | Description | | --- | --- | --- | | sourcePath | <code>string</code> | The path of the file to read | | [params] | <code>object</code> | Parameters passed to the stylesheet ([http://www.w3schools.com/xsl/el_with-param.asp](http://www.w3schools.com/xsl/el_with-param.asp)) | | [options] | <code>applyOptions</code> | Options | | callback | <code>applyToFileCallback</code> | The callback that handles the response. Expects err and result as string. | <a name="module_libxslt..parseCallback"></a> ### libxslt~parseCallback : <code>function</code> Callback to the parse function **Kind**: inner typedef of <code>[libxslt](#module_libxslt)</code> | Param | Type | | --- | --- | | [err] | <code>error</code> | | [stylesheet] | <code>Stylesheet</code> | <a name="module_libxslt..parseFileCallback"></a> ### libxslt~parseFileCallback : <code>function</code> Callback to the parseFile function **Kind**: inner typedef of <code>[libxslt](#module_libxslt)</code> | Param | Type | | --- | --- | | [err] | <code>error</code> | | [stylesheet] | <code>Stylesheet</code> | <a name="module_libxslt..applyOptions"></a> ### libxslt~applyOptions Options for applying a stylesheet **Kind**: inner typedef of <code>[libxslt](#module_libxslt)</code> **Properties** | Name | Type | Description | | --- | --- | --- | | outputFormat | <code>String</code> | Force the type of the output, either 'document' or 'string'. Default is to use the type of the input. | | noWrapParams | <code>boolean</code> | If true then the parameters are XPath expressions, otherwise they are treated as strings. Default is false. | <a name="module_libxslt..applyCallback"></a> ### libxslt~applyCallback : <code>function</code> Callback to the Stylesheet.apply function **Kind**: inner typedef of <code>[libxslt](#module_libxslt)</code> | Param | Type | Description | | --- | --- | --- | | [err] | <code>error</code> | Error either from parsing the XML document if given as a string or from applying the styleshet | | [result] | <code>string</code> &#124; <code>Document</code> | Result of the same type as the source param passed to apply | <a name="module_libxslt..applyToFileCallback"></a> ### libxslt~applyToFileCallback : <code>function</code> Callback to the Stylesheet.applyToFile function **Kind**: inner typedef of <code>[libxslt](#module_libxslt)</code> | Param | Type | Description | | --- | --- | --- | | [err] | <code>error</code> | Error either from reading the file, parsing the XML document or applying the styleshet | | [result] | <code>string</code> | | *documented by [jsdoc-to-markdown](https://github.com/75lb/jsdoc-to-markdown)*. <file_sep>/src/stylesheet.h // Very simple v8 wrapper for xslt stylesheet, see "Wrapping C++ objects" section here http://nodejs.org/api/addons.html #ifndef SRC_STYLESHEET_H_ #define SRC_STYLESHEET_H_ #include <libxslt/xslt.h> #include <libxslt/transform.h> #include <libxslt/xsltutils.h> #include <libexslt/exslt.h> class Stylesheet : public Nan::ObjectWrap { public: static void Init(v8::Local<v8::Object> exports); static v8::Local<v8::Object> New(xsltStylesheetPtr stylesheetPtr); static NAN_METHOD(TransformSync); xsltStylesheetPtr stylesheet_obj; private: explicit Stylesheet(xsltStylesheetPtr stylesheetPtr); ~Stylesheet(); static Nan::Persistent<v8::Function> constructor; }; #endif // SRC_STYLESHEET_H_<file_sep>/common.gypi # imitation of this https://github.com/TooTallNate/node-vorbis/blob/master/common.gypi { 'variables': { 'node_xmljs': '<!(node -p -e "require(\'path\').dirname(require.resolve(\'node1-libxmljsmt-myh\'))")', 'xmljs_include_dirs': [ '<(node_xmljs)/src/', '<(node_xmljs)/vendor/libxml/include', '<(node_xmljs)/vendor/libxml.conf/include' ], 'conditions': [ ['OS=="win"', { 'xmljs_libraries': [ '<(node_xmljs)/build/$(Configuration)/xmljs-myh.lib' ], }, { 'xmljs_libraries': [ '<(node_xmljs)/build/$(BUILDTYPE)/xmljs-myh.node', '-Wl,-rpath,<(node_xmljs)/build/$(BUILDTYPE)' ], }], ], }, }<file_sep>/src/document.cc #include <node.h> #include <nan.h> #include "./document.h" using namespace v8; Nan::Persistent<Function> Document::constructor; Document::Document(xmlDocumentPtr documentPtr) : document_obj(documentPtr) {} Document::~Document() { xmlFreeDocument(document_obj); } void Document::Init(Local<Object> exports) { // Prepare constructor template Local<FunctionTemplate> tpl = FunctionTemplate::New(); tpl->SetClassName(String::NewSymbol("Document")); tpl->InstanceTemplate()->SetInternalFieldCount(1); constructor = Nan::Persistent<Function>::New(tpl->GetFunction()); } // not called from node, private api Local<Object> Document::New(xmlDocumentPtr documentPtr) { Nan::EscapableHandleScope scope; Local<Object> wrapper = Nan::New(constructor).ToLocalChecked()->NewInstance(); Document* Document = new Document(documentPtr); Document->Wrap(wrapper); return scope.Escape(wrapper); }
ba8ea8231dd662c5dc47379b1604670b04ce0a2b
[ "JavaScript", "Markdown", "Python", "C", "C++" ]
13
JavaScript
albanm/node-libxslt
e4422b5778fcdad60100e635e68d2e5fdac0abf4
22a8690a9fd4c57e2e9ad2120f34b7025ff935fd
refs/heads/master
<repo_name>RenaudLerognon/comparateur<file_sep>/README.md comparateur =========== <file_sep>/web/js/app.js 'use strict'; /* App Module */ var comparatorApp = angular.module('comparatorApp', [ 'comparatorControllers' ]); <file_sep>/web/js/controllers.js 'use strict'; /* Controllers */ var comparatorControllers = angular.module('comparatorControllers', []); comparatorControllers.controller('tableCtrl', ['$scope', function($scope) { $scope.$table = $('#table'); $scope.addThing = function() { // Get head elements var headTr = $scope.$table.find('thead tr')[0]; var $headTr = $(headTr); var headCols = $headTr.children(); var headLastCol = headCols[headCols.length - 1]; // Get body elements var bodyTrs = $scope.$table.find('tbody tr'); // Create new th var newTh = document.createElement('th') ; newTh.setAttribute('contenteditable', 'true'); var textTitle = document.createTextNode('Truc x'); var textRemove = document.createTextNode('Enlever'); var button = document.createElement('button'); button.setAttribute('type', 'button'); button.setAttribute('class', 'btn btn-danger btn-xs'); var span = document.createElement('span'); span.setAttribute('class', 'glyphicon glyphicon-remove-circle'); button.appendChild(span); button.appendChild(textRemove); newTh.appendChild(textTitle); newTh.appendChild(button); // Insert headTr.insertBefore(newTh, headLastCol); // For each row in table body for(var iTr = 0; iTr < bodyTrs.length; iTr++) { // Get row elements var bodyTr = bodyTrs[iTr]; var $bodyTr = $(bodyTr); var trCols = $bodyTr.children(); var trLastCol = trCols[trCols.length - 1]; // Create new td var newTd = document.createElement('td') ; newTd.setAttribute('contenteditable', 'true'); // Insert bodyTr.insertBefore(newTd, trLastCol); } var footTr = $(table).find('tfoot tr')[0]; var $footTr = $('footTr'); var footCols = $footTr.children(); var footLastCols = footCols[footCols.length - 1]; var newTd = document.createElement('td') ; newTd.setAttribute('contenteditable', 'false'); footTr.insertBefore(newTd, footLastCols); } $scope.addPoint = function() { var body = $scope.$table.find('tbody')[0]; var $body = $(body); var bodyRows = $body.children(); var $bodyLastRow = $(bodyRows[bodyRows.length - 1]); var trCols = $bodyLastRow.children(); // For each col on last row var newTr = document.createElement('tr'); for(var iRow = 0; iRow < trCols.length - 1; iRow++) { // Create new td var newTd = document.createElement('td'); newTd.setAttribute('contenteditable', 'true'); if(0 === iRow) { var textTitle = document.createTextNode('Point .'); var textRemove = document.createTextNode('Enlver'); var button = document.createElement('button'); button.setAttribute('type', 'button'); button.setAttribute('class', 'btn btn-danger btn-xs'); var span = document.createElement('span'); span.setAttribute('class', 'glyphicon glyphicon-remove-circle'); button.appendChild(span); button.appendChild(textRemove); newTd.appendChild(textTitle); newTd.appendChild(button); } // Insert in tr newTr.appendChild(newTd); } // Create last td var newTd = document.createElement('td'); newTd.setAttribute('contenteditable', 'false'); newTd.setAttribute('class', 'active'); // Insert in tr newTr.appendChild(newTd); body.appendChild(newTr); } } ]);
074f078e925390c447b50c9d720e33aad4c8071f
[ "Markdown", "JavaScript" ]
3
Markdown
RenaudLerognon/comparateur
baf7ef99cdac12e3a8dd3aaf37786b10c70ad7ac
5dc8d37aab9e9a0998ee1bab44baecb611808fc4
refs/heads/master
<repo_name>jliussuweno/ShoppingCartExample<file_sep>/Podfile platform :ios, '7.0' pod 'FMDB' pod 'BButton' pod 'PayPal-iOS-SDK'
b1644051e050a3889a121d1fefdff963b3974008
[ "Ruby" ]
1
Ruby
jliussuweno/ShoppingCartExample
020a196156b6bad1603cf374b67f7c6376c97114
3540d401d2db3569f61b153eded67a7cd7336a1b
refs/heads/main
<file_sep>//Conexao com BD MySQL const mysql = require('mysql'); const connection = mysql.createConnection({ host: 'XXX', user: 'XXX', password: 'XXX', database: 'u852189744_at_infnet' }); connection.connect(function(err){ if (err) console.error('Erro ao realizar a conexรฃo com BD: ' + err.stack); return; }); connection.query('SELECT * FROM tb_pacientes', function(err, rows, fields){ if(!err){ console.log('Resultado: ', rows); }else{ console.log('Erro ao realizar a consulta'); } });
12e873631a371fef2a5565be4829d44ae8b74cfe
[ "JavaScript" ]
1
JavaScript
feijobruno/at_projeto_bloco
31da0c65d857b455ab181c5313beb6a1eade4f74
401d6bde696dfc4eabd3233d9dcd183b873a1c54
refs/heads/master
<repo_name>Abhijeet399/OpenCV-Face-Recognition<file_sep>/Haar cascade of eye and face detection.py import numpy as np import cv2 face_cascade=cv2.CascadeClassifier('haarcascade_frontalface_default.xml') eye_cascade=cv2.CascadeClassifier('haarcascade_eye.xml') cap=cv2.VideoCapture(0) while True: ret,img=cap.read() gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray,1.3,5) for (x,y,w,h) in faces: cx=int(x+(w/2)) cy=int(y+(h/2)) if(w>h): cv2.circle(img,(cx,cy),(int(w/2)),(0,0,255),2) else: cv2.circle(img,(cx,cy),(int(h/2)),(0,0,255),2) roi_gray=gray[y:y+h,x:x+w] roi_color=img[y:y+h,x:x+w] eyes=eye_cascade.detectMultiScale(roi_gray) for (ex,ey,ew,eh) in eyes: cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(50,33,100),2) cv2.imshow('img',img) k=cv2.waitKey(30) & 0xFF if k ==27: break cap.release() cv2.destroyAllWindows()
1a61a52513fb96269f72158f8c9c971c634f4f08
[ "Python" ]
1
Python
Abhijeet399/OpenCV-Face-Recognition
87e1a6feb3b7387dc22bb46b540da7e6b1dd1042
6195d5c89e3f7dfe066e3cda034750b206d4b3bf
refs/heads/master
<file_sep>package com.nirvana.dal.po; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * * @author Bin * ๆŠฅ่ญฆๆ•ฐๆฎ็ฑป */ @Entity @Table(name = "alarmdata") public class AlarmData { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer dataid; //่บซไปฝ่ฏ private String did; //ๆŠฅ่ญฆๅŽŸๅ› ็ฑปๅž‹typeid private Integer reasontype; @Temporal(TemporalType.TIMESTAMP) private Date status_change_time; //ๆ˜ฏๅฆ่งฃๅ†ณ private Integer hasresloved; //ๆŠฅ่ญฆ็ญ‰็บง private Integer level; //ๆŠฅ่ญฆๆ—ถไผ ๆ„Ÿๅ™จๆ•ฐๆฎ private String data; public String getData() { return data; } public void setData(String data) { this.data = data; } public Integer getLevel() { return level; } public void setLevel(Integer level) { this.level = level; } public Integer getHasresloved() { return hasresloved; } public void setHasresloved(Integer hasresloved) { this.hasresloved = hasresloved; } public Integer getDataid() { return dataid; } public void setDataid(Integer dataid) { this.dataid = dataid; } public String getDid() { return did; } public void setDid(String did) { this.did = did; } public Integer getReasontype() { return reasontype; } public void setReasontype(Integer reasontype) { this.reasontype = reasontype; } public Date getStatus_change_time() { return status_change_time; } public void setStatus_change_time(Date status_change_time) { this.status_change_time = status_change_time; } @Override public String toString() { return "AlarmData [dataid=" + dataid + ", did=" + did + ", reasontype=" + reasontype + ", status_change_time=" + status_change_time + ", hasresloved=" + hasresloved + ", level=" + level + ", data=" + data + "]"; } } <file_sep>Access-Control-Allow-Origin=http://localhost:8081 Access-Control-Allow-Credentials=true Access-Control-Allow-Methods=POST, GET, OPTIONS, DELETE Access-Control-Max-Age=3600 Access-Control-Allow-Headers=Origin, X-Requested-With, Content-Type, Accept<file_sep>package com.nirvana.app.vo; public class LinkManVO { private Integer relationid; private String relationname; private String relationtel; private String relationaccount; private String relationpassword; private Integer userid; public Integer getUserid() { return userid; } public void setUserid(Integer userid) { this.userid = userid; } public Integer getRelationid() { return relationid; } public void setRelationid(Integer relationid) { this.relationid = relationid; } public String getRelationname() { return relationname; } public void setRelationname(String relationname) { this.relationname = relationname; } public String getRelationtel() { return relationtel; } public void setRelationtel(String relationtel) { this.relationtel = relationtel; } public String getRelationaccount() { return relationaccount; } public void setRelationaccount(String relationaccount) { this.relationaccount = relationaccount; } public String getRelationpassword() { return relationpassword; } public void setRelationpassword(String relationpassword) { this.relationpassword = relationpassword; } } <file_sep> package com.nirvana.dal.po; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * * @author Bin * ๅฎšไฝๆ•ฐๆฎ็ฑป */ @Entity @Table(name = "locationdata") public class LocationData { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer dataid; //่บซไปฝ่ฏ private String did; private String gps; //็ป็บฌๅบฆ private String longtitude; private String latitude; @Temporal(TemporalType.TIMESTAMP) private Date status_change_time; public Integer getDataid() { return dataid; } public void setDataid(Integer dataid) { this.dataid = dataid; } public String getDid() { return did; } public void setDid(String did) { this.did = did; } public String getGps() { return gps; } public void setGps(String gps) { this.gps = gps; } public String getLongtitude() { return longtitude; } public void setLongtitude(String longtitude) { this.longtitude = longtitude; } public String getLatitude() { return latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } public Date getStatus_change_time() { return status_change_time; } public void setStatus_change_time(Date status_change_time) { this.status_change_time = status_change_time; } @Override public String toString() { return "LocationData [dataid=" + dataid + ", did=" + did + ", gps=" + gps + ", longtitude=" + longtitude + ", latitude=" + latitude + ", status_change_time=" + status_change_time + "]"; } } <file_sep>package com.nirvana.app.vo; import java.util.List; public class NodeDataVO { private String name; private List<String> valueset = null; private List<DataVO> data = null; public String getName() { return name; } public void setName(String name) { this.name = name; } public List<String> getValueset() { return valueset; } public void setValueset(List<String> valueset) { this.valueset = valueset; } public List<DataVO> getData() { return data; } public void setData(List<DataVO> data) { this.data = data; } } <file_sep>package com.nirvana.app.controller; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.google.gson.Gson; import com.nirvana.app.util.GsonUtils; import com.nirvana.app.vo.AlarmFilterVO; import com.nirvana.app.vo.ExceptionVO; import com.nirvana.app.vo.Result; import com.nirvana.bll.service.AlarmDataService; /** * ๆŠฅ่ญฆ่ง†ๅ›พ่ฝฌๆขๅฑ‚ * ๆŽฅๅฃๅค„็†ๅฏๅ‚่€ƒๆŽฅๅฃๆ–‡ๆกฃ * @author Bin * */ @RestController @RequestMapping("/alarm") public class AlarmController extends BaseController { @Autowired private AlarmDataService alarmservicebo; @RequestMapping("/rmall") public void rmall(HttpServletRequest request, HttpServletResponse response, Integer communityId) throws IOException { Integer userid = (Integer) request.getSession().getAttribute("userid"); Result result = null; if (userid == null) { result = Result.getFailInstance("userid cannot been found", null); } else { alarmservicebo.rmall(communityId); result = Result.getSuccessInstance(null); result.setMsg("ๅ…จ้ƒจๅŽป้™ค"); } response.setContentType("text/html;charset=utf-8"); response.getWriter().print(GsonUtils.getDateFormatGson().toJson(result)); } @RequestMapping("/resolved") public void resolved(HttpServletRequest request, HttpServletResponse response, Integer communityId) throws IOException { Integer userid = (Integer) request.getSession().getAttribute("userid"); Result result = null; if (userid == null) { result = Result.getFailInstance("userid cannot been found", null); } else { // System.out.println(communityId); List<ExceptionVO> list = alarmservicebo.findAllRedo(communityId); result = Result.getSuccessInstance(list); } response.setContentType("text/html;charset=utf-8"); response.getWriter().print(GsonUtils.getDateFormatGson().toJson(result)); } @RequestMapping("/detection") public void detection(HttpServletRequest request, HttpServletResponse response, @RequestParam("exceptionId") Integer id, Integer communityId) throws IOException { Integer userid = (Integer) request.getSession().getAttribute("userid"); Result result = null; if (userid == null) { result = Result.getFailInstance("userid cannot been found", null); } else { List<ExceptionVO> list = null; if (id == 0) { list = alarmservicebo.findAllRedo(communityId); } else { list = alarmservicebo.detect(id, communityId); } result = Result.getSuccessInstance(list); } response.setContentType("text/html;charset=utf-8"); response.getWriter().print(GsonUtils.getDateFormatGson().toJson(result)); } @RequestMapping("/type") public void type(HttpServletRequest request, HttpServletResponse response) throws IOException { Integer userid = (Integer) request.getSession().getAttribute("userid"); Result result = null; if (userid == null) { result = Result.getFailInstance("userid cannot been found", null); } else { List<ExceptionVO> list = alarmservicebo.findAlltype(); result = Result.getSuccessInstance(list); } response.setContentType("text/html;charset=utf-8"); response.getWriter().print(new Gson().toJson(result)); } @RequestMapping("/solve") public void solve(HttpServletRequest request, HttpServletResponse response, @RequestParam("exceptionId") Integer id) throws IOException { alarmservicebo.sloveByAid(id); Result result = Result.getSuccessInstance(null); response.setContentType("text/html;charset=utf-8"); response.getWriter().print(new Gson().toJson(result)); } @RequestMapping("/times") public void times(HttpServletRequest request, HttpServletResponse response,Integer communityid) throws IOException { Integer userid = (Integer) request.getSession().getAttribute("userid"); Result result = null; if (userid == null) { result = Result.getFailInstance("userid cannot been found", null); } else { List<ExceptionVO> list = alarmservicebo.findAllTimes(communityid); result = Result.getSuccessInstance(list); } response.setContentType("text/html;charset=utf-8"); response.getWriter().print(new Gson().toJson(result)); } @RequestMapping("/filter") public void filter(HttpServletRequest request, HttpServletResponse response, @RequestParam("communityId") String id, @RequestParam("alarmType") String type, @RequestParam("startTime") String startTime, @RequestParam("endTime") String endTime) throws IOException { Integer userid = (Integer) request.getSession().getAttribute("userid"); Result result = null; if (userid == null) { result = Result.getFailInstance("userid cannot been found", null); } else { String[] ids = id.split(","); String[] types = type.split(","); Date start = null; Date end = null; SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); if (startTime == null || "".equals(startTime)) { end = new Date(); start = new Date(end.getTime()); start.setTime(start.getTime() - 7 * 24 * 60 * 60 * 1000); } else { try { // 2017/01/11 00:00:00 // 2017/01/12 24:00:00 startTime += " 00:00:00"; endTime += " 00:00:00"; start = sdf.parse(startTime); end = sdf.parse(endTime); end.setTime(end.getTime() + 24 * 60 * 60 * 1000); } catch (ParseException e) { e.printStackTrace(); } } System.out.println(ids.length + " " + types.length); AlarmFilterVO filtervo = alarmservicebo.findByFilter(ids, types, start, end); result = Result.getSuccessInstance(filtervo); } response.setContentType("text/html;charset=utf-8"); response.getWriter().print(new Gson().toJson(result)); } @RequestMapping("/people") public void people(HttpServletRequest request, HttpServletResponse response, @RequestParam("communityId") String communityid, @RequestParam("userId") String userids, @RequestParam("alarmType") String type, @RequestParam("startTime") String startTime, @RequestParam("endTime") String endTime) throws IOException { //ๅ‰็ซฏๆ•ฐๆฎๅŸบๆœฌๅค„็† ๅŒ…ๆ‹ฌๅญ—็ฌฆไธฒๅˆ†ๆ•ฐ็ป„ Result result = null; String[] ids = userids.split(","); String[] types = type.split(","); Date start = null; Date end = null; SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); if (startTime == null || "".equals(startTime)) { //้ป˜่ฎคๆ—ถ้—ด้—ด้š” end = new Date(); start = new Date(end.getTime()); start.setTime(start.getTime() - 7 * 24 * 60 * 60 * 1000); } else { try { // 2017/01/11 00:00:00 // 2017/01/12 24:00:00 startTime += " 00:00:00"; endTime += " 00:00:00"; start = sdf.parse(startTime); end = sdf.parse(endTime); end.setTime(end.getTime() + 24 * 60 * 60 * 1000); } catch (ParseException e) { e.printStackTrace(); } } System.out.println(ids.length + " " + types.length); AlarmFilterVO filtervo = alarmservicebo.findPeopleByFilter(communityid, ids, types, start, end); result = Result.getSuccessInstance(filtervo); response.setContentType("text/html;charset=utf-8"); response.getWriter().print(new Gson().toJson(result)); } } <file_sep>package com.nirvana.dal.po; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.validator.constraints.Length; /** * * @author Bin * ไบงๅ“ๆกˆไพ‹็ฑป */ @Entity @Table(name = "solutioncase") public class SolutionCase { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer caseid; //ๆกˆไพ‹ๆ ‡้ข˜ private String casetitle; //ๅ›พ็‰‡ private String caseimg; @Length(max = 10000) //ๅ†…ๅฎน private String casecontent; //ๆ˜ฏๅฆๆ˜พ็คบ private boolean isshow; public boolean isIsshow() { return isshow; } public void setIsshow(boolean isshow) { this.isshow = isshow; } public Integer getCaseid() { return caseid; } public void setCaseid(Integer caseid) { this.caseid = caseid; } public String getCasetitle() { return casetitle; } public void setCasetitle(String casetitle) { this.casetitle = casetitle; } public String getCaseimg() { return caseimg; } public void setCaseimg(String caseimg) { this.caseimg = caseimg; } public String getCasecontent() { return casecontent; } public void setCasecontent(String casecontent) { this.casecontent = casecontent; } @Override public String toString() { return "SolutionCase [caseid=" + caseid + ", casetitle=" + casetitle + ", caseimg=" + caseimg + ", casecontent=" + casecontent + ", isshow=" + isshow + "]"; } } <file_sep>package com.nirvana.bll.bo; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.nirvana.app.vo.CommunityVO; import com.nirvana.bll.service.CommunityService; import com.nirvana.dal.api.CommunityDao; import com.nirvana.dal.po.Community; @Service @Transactional public class CommunityServiceBO implements CommunityService{ @Autowired private CommunityDao communitydao; public void add(Community community) { communitydao.save(community); } public void delById(Integer id) { communitydao.delete(id); } public List<CommunityVO> findFuzzy(String key) { List<Community> polist = communitydao.fuzzyQueryOrderByGBK(key); return CommunityVO.toListVO(polist); } public Community findById(Integer id) { Community community = communitydao.findOne(id); return community; } public List<CommunityVO> findAll() { List<Community> list = communitydao.findAllOrderByGBK(); List<CommunityVO> polist = new ArrayList<CommunityVO>(); for(Community community:list){ polist.add(new CommunityVO(community.getCommunityid(),community.getCommunityname())); } return polist; } public List<CommunityVO> findAllNotEmpty() { List<Community> list = communitydao.findAllNotEmpty(); List<CommunityVO> polist = new ArrayList<CommunityVO>(); for(Community community:list){ polist.add(new CommunityVO(community)); } return polist; } } <file_sep>package com.nirvana.bll.service; import java.util.Date; import java.util.List; import com.nirvana.app.vo.AlarmFilterVO; import com.nirvana.app.vo.ExceptionVO; import com.nirvana.dal.po.AlarmData; /** * ๆŠฅ่ญฆๆ•ฐๆฎๆŽฅๅฃๅฎšไน‰ * @author Bin * */ public interface AlarmDataService { /** * ๆทปๅŠ ไธ€ๆกๆŠฅ่ญฆๆ•ฐๆฎ * @param data */ void addData(AlarmData data); /** * ๆ นๆฎ็”จๆˆทid ๆŸฅๆ‰พๅ…ถๆ‰€ๆœ‰ๆœช่งฃๅ†ณ็š„ๆŠฅ่ญฆๆ•ฐๆฎ * @param id * @return */ List<ExceptionVO> findAllRedo(Integer id); /** * ๆฃ€ๆต‹็คพๅŒบๆœ‰ๆฒกๆœ‰ๆœ€ๆ–ฐ็š„ๆŠฅ่ญฆๆ•ฐๆฎ * @param id ๆœ€ๆ–ฐไธ€ๆกๆŠฅ่ญฆๆ•ฐๆฎ็š„id * @param communityid ็คพๅŒบid * @return */ List<ExceptionVO> detect(Integer id,Integer communityid); /** * ๆŸฅๆ‰พๆ‰€ๆœ‰ๅผ‚ๅธธๆ•ฐๆฎ็š„ๆ‰€ๆœ‰ๅฏ่ƒฝ็ฑปๅž‹id * @return */ List<ExceptionVO> findAlltype(); /** * ๆŸฅๆ‰พๆ‰€ๆœ‰ๅผ‚ๅธธ็š„ๅ‡บ็Žฐ็š„ๆฌกๆ•ฐ * @return */ List<ExceptionVO> findAllTimes(Integer communityid); /** * ๆŠฅ่ญฆๆ•ฐๆฎ่ฟ‡ๆปคๅ™จ ๆ นๆฎๆกไปถ็ญ›้€‰ๅผ‚ๅธธ * @param ids ็คพๅŒบidๆ•ฐ็ป„ * @param types ๆŠฅ่ญฆ็ฑปๅž‹idๆ•ฐ็ป„ * @param start ๅผ€ๅง‹ๆ—ฅๆœŸ * @param end ็ป“ๆŸๆ—ฅๆœŸ * @return */ AlarmFilterVO findByFilter(String[] ids, String[] types, Date start, Date end); /** * ่งฃๅ†ณๆŸไธ€ไธชๆŠฅ่ญฆๆ•ฐๆฎ * @param id */ void sloveByAid(Integer id); /** * ๆ นๆฎ่บซไปฝ่ฏๆŸฅๆ‰พๆ‰€ๆœ‰ๆœช่งฃๅ†ณ็š„ๆŠฅ่ญฆๆ•ฐๆฎ * @param did * @return */ List<AlarmData> findUndoByDid(String did); /** * ็คพๅŒบๅ†…ๆŠฅ่ญฆๆ•ฐๆฎ็ญ›้€‰ๅ™จ * @param communityid ็คพๅŒบid * @param ids ็”จๆˆทidๆ•ฐ็ป„ * @param types ็ฑปๅž‹ๆ•ฐ็ป„ * @param start ๅผ€ๅง‹ๆ—ฅๆœŸ * @param end ็ป“ๆŸๆ—ฅๆœŸ * @return */ AlarmFilterVO findPeopleByFilter(String communityid, String[] ids, String[] types, Date start, Date end); /** * ๆธ…ๆฅš็คพๅŒบๅ†…ๆ‰€ๆœ‰็š„ๆŠฅ่ญฆๆ•ฐๆฎ * @param communityId */ void rmall(Integer communityId); } <file_sep>package com.nirvana.app.vo; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Set; import org.springframework.data.domain.Page; import com.nirvana.dal.po.Node; import com.nirvana.dal.po.User; public class NodeListVO { private Long count; private List<UserVO> data; public NodeListVO(Long count, List<UserVO> data) { super(); this.count = count; this.data = data; } public NodeListVO(Page<User> pages) { super(); this.count = pages.getTotalElements(); List<User> content = pages.getContent(); List<UserVO> list = new ArrayList<UserVO>(); for (int i = 0; i < content.size(); i++) { User user = content.get(i); Set<Node> nodes = user.getNodes(); ArrayList<Node> nodelist = new ArrayList<Node>(nodes); Collections.sort(nodelist, new Comparator<Node>() { public int compare(Node o1, Node o2) { if(o1.getNodeid()>o2.getNodeid()){ return 1; }else{ return -1; } } }); List<NodeVO> nodevos = new ArrayList<NodeVO>(); for (Node node : nodelist) { nodevos.add(new NodeVO(node)); } UserVO uservo = new UserVO(user,1); uservo.setNodes(nodevos); list.add(uservo); } this.data = list; } public Long getCount() { return count; } public void setCount(Long count) { this.count = count; } public List<UserVO> getData() { return data; } public void setData(List<UserVO> data) { this.data = data; } } <file_sep>package com.nirvana.app.validator; import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.CONSTRUCTOR; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; @Retention(RetentionPolicy.RUNTIME) @Target(value={FIELD,METHOD,CONSTRUCTOR,ANNOTATION_TYPE,PARAMETER}) @Documented @Constraint(validatedBy={BadWordsValidator.class}) public @interface BadWords { String message() default "่ฏทไธ่ฆๅŒ…ๅซไธๆ–‡ๆ˜Ž็š„่ฏๆฑ‡"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; } <file_sep>package com.nirvana.app.controller; import java.io.IOException; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.google.gson.Gson; import com.nirvana.app.util.GsonUtils; import com.nirvana.app.vo.CommunityVO; import com.nirvana.app.vo.Result; import com.nirvana.app.vo.UserVO; import com.nirvana.bll.service.CommunityService; import com.nirvana.bll.service.UserService; import com.nirvana.dal.po.Community; /** * ็คพๅŒบ่ง†ๅ›พ่ฝฌๆขๅฑ‚ * ๆŽฅๅฃๅค„็†ๅฏๅ‚่€ƒๆŽฅๅฃๆ–‡ๆกฃ * @author Bin * */ @RestController @RequestMapping("/community") public class CommunityController extends BaseController { @Autowired private CommunityService communityservicebo; @Autowired private UserService userservicebo; @RequestMapping("/userlist") public void userlist(HttpServletRequest request, HttpServletResponse response, @RequestParam("communityid") Integer communityid) throws IOException { List<UserVO> volist = userservicebo.findAllByCid(communityid); Result result = null; result = Result.getSuccessInstance(volist); response.setContentType("text/html;charset=utf-8"); response.getWriter().print(GsonUtils.getDateFormatGson().toJson(result)); } @RequestMapping("/location") public void location(HttpServletRequest request, HttpServletResponse response, @RequestParam("communityid") Integer communityid) throws IOException { Community po = communityservicebo.findById(communityid); Result result = null; if (po == null) { result = Result.getFailInstance("ๆ— ๆญค็คพๅŒบ", null); } else { CommunityVO vo = new CommunityVO(); vo.setLatitude(po.getLatitude()); vo.setLongtitude(po.getLongtitude()); result = Result.getSuccessInstance(vo); } response.setContentType("text/html;charset=utf-8"); response.getWriter().print(GsonUtils.getDateFormatGson().toJson(result)); } @RequestMapping("/manager") public void manager(HttpServletRequest request, HttpServletResponse response, @RequestParam("key") String key) throws IOException { Integer userid = (Integer) request.getSession().getAttribute("userid"); Result result = null; if (userid == null) { result = Result.getFailInstance("userid cannot been found", null); } else { List<UserVO> list = userservicebo.findManagersByKey(key); result = Result.getSuccessInstance(list); } response.setContentType("text/html;charset=utf-8"); response.getWriter().print(GsonUtils.getDateFormatGson().toJson(result)); } @RequestMapping("/create") public void create(HttpServletRequest request, HttpServletResponse response, Community community) throws IOException { Integer userid = (Integer) request.getSession().getAttribute("userid"); Result result = null; if (userid == null) { result = Result.getFailInstance("userid cannot been found", null); } else { communityservicebo.add(community); result = Result.getSuccessInstance(null); } response.setContentType("text/html;charset=utf-8"); response.getWriter().print(new Gson().toJson(result)); } @RequestMapping({ "/del" }) public void del(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") Integer id) throws IOException { Integer userid = (Integer) request.getSession().getAttribute("userid"); Result result = null; if (userid == null) { result = Result.getFailInstance("userid cannot been found", null); } else { communityservicebo.delById(id); result = Result.getSuccessInstance(null); } response.setContentType("text/html;charset=utf-8"); response.getWriter().print(new Gson().toJson(result)); } @RequestMapping({ "/search" }) public void search(HttpServletRequest request, HttpServletResponse response, @RequestParam("key") String key) throws IOException { Integer userid = (Integer) request.getSession().getAttribute("userid"); Result result = null; if (userid == null) { result = Result.getFailInstance("userid cannot been found", null); } else { List<CommunityVO> list = communityservicebo.findFuzzy(key); result = Result.getSuccessInstance(list); } response.setContentType("text/html;charset=utf-8"); response.getWriter().print(new Gson().toJson(result)); } @RequestMapping("/all") public void all(HttpServletRequest request, HttpServletResponse response) throws IOException { Integer userid = (Integer) request.getSession().getAttribute("userid"); Result result = null; if (userid == null) { result = Result.getFailInstance("userid cannot been found", null); } else { List<CommunityVO> list = communityservicebo.findAll(); result = Result.getSuccessInstance(list); } response.setContentType("text/html;charset=utf-8"); response.getWriter().print(new Gson().toJson(result)); } @RequestMapping("/list") public void list(HttpServletRequest request, HttpServletResponse response) throws IOException{ Integer userid = (Integer) request.getSession().getAttribute("userid"); Result result = null; if (userid == null) { result = Result.getFailInstance("userid cannot been found", null); } else { List<CommunityVO> list = communityservicebo.findAllNotEmpty(); result = Result.getSuccessInstance(list); } response.setContentType("text/html;charset=utf-8"); response.getWriter().print(new Gson().toJson(result)); } } <file_sep>package com.nirvana.dal.po; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * * @author Bin * ่Š‚็‚นๆ•ฐๆฎ็ฑป๏ผˆๅŒ…ๅซๆญฃๅธธๅ’Œๅผ‚ๅธธ๏ผ‰ๆŒ‰็…งไธ€ๅฎš็š„้ข‘็އไธŠไผ  */ @Entity @Table(name = "nodedata") public class NodeData { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer dataid; //่บซไปฝ่ฏ private String did; //ไผ ๆ„Ÿๅ™จ็ฑปๅž‹id private Integer sensortype; @Temporal(TemporalType.TIMESTAMP) private Date status_change_time; //่Š‚็‚นid ๆ— ็”จ ๅ› ไธบnodeidๆฒกๆœ‰ๅฎž็Žฐ private Integer nodeid; //ไธŠไผ ๆ•ฐๆฎ private String data; public Integer getDataid() { return dataid; } public void setDataid(Integer dataid) { this.dataid = dataid; } public String getDid() { return did; } public void setDid(String did) { this.did = did; } public Integer getSensortype() { return sensortype; } public void setSensortype(Integer sensortype) { this.sensortype = sensortype; } public Date getStatus_change_time() { return status_change_time; } public void setStatus_change_time(Date status_change_time) { this.status_change_time = status_change_time; } public Integer getNodeid() { return nodeid; } public void setNodeid(Integer nodeid) { this.nodeid = nodeid; } public String getData() { return data; } public void setData(String data) { this.data = data; } @Override public String toString() { return "NodeData [dataid=" + dataid + ", did=" + did + ", sensortype=" + sensortype + ", status_change_time=" + status_change_time + ", nodeid=" + nodeid + ", data=" + data + "]"; } } <file_sep>#NewSmartLab 1.็Žฏๅขƒ๏ผš java-v๏ผšjdk1.7 webๆœๅŠกๅ™จ๏ผštomacat8.0 ๆ•ฐๆฎๅบ“่ฎฟ้—ฎๅฑ‚๏ผšjpa ่ง†ๅ›พๅค„็†ๅฑ‚๏ผšspring smsๆœๅŠก๏ผšๆท˜ๅฎๅคง้ฑผ emailๆœๅŠก๏ผšsendcloud jsonๅค„็†๏ผšGoogleๅผ€ๅ‘็š„Gson ้กน็›ฎ็ฎก็†๏ผšgitไธญๅ›ฝ url๏ผšhttps://git.oschina.net/nirvana123/NewSmartLab ้กน็›ฎjarๅŒ…็ฎก็†๏ผšmaven ๆœๅŠกๅ™จ๏ผš่…พ่ฎฏไบ‘ ubuntu14 ๆ•ฐๆฎๅบ“๏ผšmysql5.0ไปฅไธŠ 2.้กน็›ฎ็ป“ๆž„ src main ้กน็›ฎไธป่ฆไปฃ็  java ๆบไปฃ็  app.config้กน็›ฎ่ฟ่กŒ้…็ฝฎ app.controller่ง†ๅ›พๅฑ‚MVCๆžถๆž„ไธญ็š„Cๅฑ‚ ็”จไบŽ่ทฏๅพ„ๅฎšๅ‘้กต้ข app.exception ้กน็›ฎ่‡ชๅฎšไน‰ๅผ‚ๅธธ app.interceptorๆŽฅๅฃ่ฎฟ้—ฎๆ‹ฆๆˆชๅ™จ app.util ๅทฅๅ…ท็ฑปๆ–‡ไปถๅคน app.validate ๆŽฅๅฃ่ฎฟ้—ฎๆ ก้ชŒ็ฑปๆ–‡ไปถๅคน app.vo ่ง†ๅ›พๅฑ•็คบ็ฑป bll.bo ้กน็›ฎๆœๅŠกๅฑ‚ๆŽฅๅฃ bll.service ๆœๅŠกๅฑ‚ๅฎž็Žฐ dal.api ๆ•ฐๆฎๅบ“่ฎฟ้—ฎๅฑ‚ๅฎž็Žฐ dal.po ้กน็›ฎ็š„ๆŒไน…ๅŒ–ๅฏน่ฑก resource ่ต„ๆบๆ–‡ไปถ ๆŽฅๅฃๆ–‡ๆกฃ datasource.propertiesๆ•ฐๆฎๅบ“้…็ฝฎๆ–‡ไปถ spring-jpa.xml springๅ’Œjpaๆ•ดๅˆ้…็ฝฎๆ–‡ไปถ spring-mvc.xml springmvcๆก†ๆžถ้…็ฝฎๆ–‡ไปถ test ๆต‹่ฏ•็ฑปๆ–‡ไปถๅคน pom.xml maven jar็ฎก็†ๆ–‡ไปถ .gitignore git็‰ˆๆœฌๆŽงๅˆถๆ–‡ไปถ readme.md markdownๆ–‡ไปถ ไป‹็ปๆ–‡ๆกฃ 3.้กน็›ฎๅฎ‰่ฃ…(ๅ‡่ฎพ็Žฏๅขƒๅฎ‰่ฃ…ๅฎŒๆฏ•) 1.git clone https://git.oschina.net/nirvana123/NewSmartLab.git 2.ๆ‰“ๅŒ…ๆˆwar 3.cd /opt/apache-tomcat็‰ˆๆœฌๅท็•ฅ/webapps/ 3.copy to ๆœๅŠกๅ™จไธ‹ /opt/apache-tomcat็‰ˆๆœฌๅท็•ฅ/webapps/ 4.cd /opt/apache-tomcat็‰ˆๆœฌๅท็•ฅ/bin/ 5. ./startdown.sh <file_sep>package com.nirvana.bll.service; import java.util.List; import com.nirvana.app.vo.NodeVO; public interface NodeService { //ๆทปๅŠ ่Š‚็‚น boolean add(String did, Integer nodetype); //ๆŸฅ่ฏข็”จๆˆท็š„ๆ‰€ๆœ‰่Š‚็‚น List<NodeVO> findAllByUid(Integer userid); void cstatus(Integer nodeid); void setfreq(Integer nodeid, Integer freq); } <file_sep>package com.nirvana.app.interceptor; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; public class AjaxInterceptor extends HandlerInterceptorAdapter { // static String Access_Control_Allow_Origin = ""; // static String Access_Control_Allow_Credentials = ""; // static String Access_Control_Allow_Methods = ""; // static String Access_Control_Max_Age = ""; // static String Access_Control_Allow_Headers = ""; // static{ // FileInputStream fis = null; // try { // fis = new FileInputStream("response.properties"); // } catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // Properties pro = new Properties(); // try { // pro.load(fis); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // Access_Control_Allow_Origin = pro.getProperty("Access-Control-Allow-Origin"); // Access_Control_Allow_Credentials = pro.getProperty("Access-Control-Allow-Credentials"); // Access_Control_Allow_Methods = pro.getProperty("Access-Control-Allow-Methods"); // Access_Control_Max_Age = pro.getProperty("Access-Control-Max-Age"); // Access_Control_Allow_Headers = pro.getProperty("Access-Control-Allow-Headers"); // try { // fis.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //่ฐƒ่ฏ•ๅŸŸ response.setHeader("Access-Control-Allow-Origin", "http://localhost:8081"); //่ฟ่กŒๅŸŸ //response.setHeader("Access-Control-Allow-Origin", "http://172.16.31.10"); //response.setHeader("Access-Control-Allow-Origin","http://mh100.com.cn" ); response.setHeader("Access-Control-Allow-Credentials","true"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept"); return true; } } <file_sep>package com.nirvana.app.vo; import com.nirvana.dal.po.ProductIntro; import java.util.ArrayList; import java.util.List; /** * Created by Andeper on 2017/1/10. */ public class ProductIntroVO { private String producttitle; private String productimg; private String productcontent; public ProductIntroVO(ProductIntro productIntro) { this.producttitle = productIntro.getProducttitle(); this.productimg = productIntro.getProductimg(); this.productcontent = productIntro.getProductcontent(); } public static List<ProductIntroVO> toListVO(List<ProductIntro> polist) { List<ProductIntroVO> list = new ArrayList<ProductIntroVO>(); for (int i = 0; i < polist.size(); i++) { list.add(new ProductIntroVO(polist.get(i))); } return list; } public String getProducttitle() { return producttitle; } public void setProducttitle(String producttitle) { this.producttitle = producttitle; } public String getProductcontent() { return productcontent; } public void setProductcontent(String productcontent) { this.productcontent = productcontent; } public String getProductimg() { return productimg; } public void setProductimg(String productimg) { this.productimg = productimg; } @Override public String toString() { return "ProductIntroVO{" + "producttitle='" + producttitle + '\'' + ", productimg='" + productimg + '\'' + ", productcontent='" + productcontent + '\'' + '}'; } } <file_sep>package com.nirvana.bll.service; import java.util.List; import com.nirvana.app.vo.SolutionCaseVO; import com.nirvana.dal.po.SolutionCase; public interface SolutionCaseService { /** * ๆทปๅŠ ๆกˆไพ‹ * @param solutionCase */ void add(SolutionCase solutionCase); /** * ๅˆ ้™คๆกˆไพ‹ * @param id */ void delById(Integer id); /** * ๆŸฅ่ฏขๆ‰€ๆœ‰ * @return */ List<SolutionCase> findAll(); /** * ๆŸฅ่ฏขๆ‰€ๆœ‰ๅฏๆ˜พ็คบ็š„ * @return */ List<SolutionCaseVO> findShowSolutionCase(); } <file_sep>package com.nirvana.dal.api; import java.util.Date; import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import com.nirvana.dal.po.NodeData; /** * * @author Bin * ่Š‚็‚นๆ•ฐๆฎไนฆๅบ“่ฎฟ้—ฎๅฑ‚ */ @Repository public interface NodeDataDao extends JpaRepository<NodeData, Integer> { /** * ๆŸฅ่ฏขๆ‰€ๅฑž็”จๆˆทไธ€็ง็ฑปๅž‹ไผ ๆ„Ÿๅ™จ็š„ๆ•ฐๆฎ ๆŒ‰ๆ—ถ้—ด้™็ปญๆŽ’ๅˆ— * @param did ่บซไปฝ่ฏ * @param type ่Š‚็‚น็ฑปๅž‹ * @param pageable ๅˆ†้กต * @return ่ฟ”ๅ›ž่Š‚็‚นๆ•ฐๆฎ้กต */ @Query(value = "SELECT n FROM NodeData n WHERE n.did=:did AND n.sensortype=:type ORDER BY n.status_change_time DESC") Page<NodeData> findLatestByDidAndType(@Param("did") String did, @Param("type") Integer type, Pageable pageable); /** * ๆŸฅ่ฏขๆ‰€ๅฑž็”จๆˆท ไธ€็ง็ฑปๅž‹ๆ•ฐๆฎ็š„ๆ‰€ๆœ‰ๆ•ฐๆฎ * @param did ่บซไปฝ่ฏ * @param type ่Š‚็‚น็ฑปๅž‹ * @param start ๅผ€ๅง‹ๆ—ถ้—ด * @param end ๆˆชๆญขๆ—ถ้—ด * @return ่Š‚็‚นๆ•ฐๆฎ้›†ๅˆ */ @Query("SELECT n FROM NodeData n WHERE n.did=:did AND n.sensortype=:type AND n.status_change_time>=:start AND n.status_change_time<=:end ORDER BY n.status_change_time") List<NodeData> findByDidAndTypeinWeek(@Param("did") String did, @Param("type") Integer type, @Param("start") Date start, @Param("end") Date end); /** * ๆ นๆฎ่บซไปฝ่ฏๆŸฅ่ฏขๆ‰€ๆœ‰่Š‚็‚นๆ•ฐๆฎ * @param useridentity * @return ่Š‚็‚นๆ•ฐๆฎ้›†ๅˆ */ @Query(value="SELECT n FROM NodeData n WHERE n.did=:did") List<NodeData> findByDid(@Param("did") String useridentity); } <file_sep>package com.nirvana.dal.api; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import com.nirvana.dal.po.Node; /** * * @author Bin * ่Š‚็‚นๆ•ฐๆฎๅบ“่ฎฟ้—ฎๅฑ‚ */ @Repository public interface NodeDao extends JpaRepository<Node, Integer> { /** * ๆŸฅ่ฏขๆ‰€ๆœ‰่Š‚็‚นๆ นๆฎ็”จๆˆทid * @param userid * @return ่ฟ”ๅ›ž่Š‚็‚น้›†ๅˆ */ @Query("SELECT n FROM Node n WHERE n.user.userid=:userid") List<Node> findAllTypeByUid(@Param("userid") Integer userid); /** * ๆ นๆฎ่บซไปฝ่ฏๅ’Œ่Š‚็‚น็ฑปๅž‹ๆŸฅ่ฏข็›ธๅบ”็š„่Š‚็‚น * @param did ่บซไปฝ่ฏ * @param nodetype ่Š‚็‚น็ฑปๅž‹id * @return ่ฟ”ๅ›ž็›ธๅบ”็š„่Š‚็‚น */ @Query("SELECT n FROM Node n WHERE n.user.useridentity=:did AND n.nodetype=:nodetype") Node findByDidAndTypeid(@Param("did") String did,@Param("nodetype") Integer nodetype); @Query("SELECT n FROM Node n WHERE n.nodeid=:nodeid") Node findOneById(@Param("nodeid") Integer nodeid); } <file_sep>package com.nirvana.app.validator; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; public class BadWordsValidator implements ConstraintValidator<BadWords, String> { private static final String[] BAD_WORDS={"ๅงๆงฝ","ไฝ ้บป็—น","fuck"}; private boolean checkValid(String val){ for (String str:BAD_WORDS){ if (val.contains(str)) return false; } return true; } public void initialize(BadWords arg0) { } public boolean isValid(String val, ConstraintValidatorContext arg1) { return checkValid(val); } } <file_sep>package com.nirvana.bll.bo; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.nirvana.app.vo.NoticeVO; import com.nirvana.bll.service.NoticeService; import com.nirvana.dal.api.NoticeDao; import com.nirvana.dal.api.UserDao; import com.nirvana.dal.po.Notice; import com.nirvana.dal.po.User; @Service @Transactional public class NoticeServiceBO implements NoticeService { @Autowired private NoticeDao noticedao; @Autowired private UserDao userdao; public void add(Notice notice) { noticedao.save(notice); } public void delById(Integer id) { noticedao.delete(id); } public List<NoticeVO> findAllList() { List<Notice> polist = noticedao.findAll(); return NoticeVO.toVoList(polist); } public List<NoticeVO> findAdmin(Integer num,Integer size) { PageRequest request = this.buildPageRequest(num, size); Page<Notice> page1 = noticedao.queryAdminNotTop(request); List<Notice> list1 = page1.getContent(); List<Notice> list2 = noticedao.queryAdminIsTop(); for (Notice n : list1) { list2.add(n); } return NoticeVO.toVoList(list2); } public List<NoticeVO> findByCommunityId(Integer id) { List<Notice> polist = noticedao.queryByCommunityId(id); return NoticeVO.toVoList(polist); } private PageRequest buildPageRequest(int pageNumber, int pagzSize) { return new PageRequest(pageNumber - 1, pagzSize, null); } public Page<Notice> findByTitleOrUn(String key, Integer num, Integer size, Integer communityid) { PageRequest request = this.buildPageRequest(num, size); Page<Notice> polist = null; if (communityid == null) { polist = noticedao.fuzzyQuery(key, request); } else { polist = noticedao.fuzzyQueryByCid(key, request, communityid); } return polist; } public List<NoticeVO> findNoticeByUid(Integer userid,Integer num,Integer size) { PageRequest request = this.buildPageRequest(num,size); User user = userdao.findOne(userid); List<Notice> list1 = null; List<Notice> list2 = new ArrayList<Notice>(); if (user.getCommunity() != null) { //ๆŒ‰็…ง็ฝฎ้กถๅœจๅ‰ ๆŒ‰็…งๆ—ถ้—ดๆŽ’ๅˆ— Page<Notice> page= noticedao.findNoticeByCidNotTop(user.getCommunity().getCommunityid(),request); list1 = page.getContent(); list2 = noticedao.findNoticeByCidIsTop(user.getCommunity().getCommunityid()); for (Notice n : list1) { if (n.isIstop()) { list2.add(n); } } for (Notice n : list1) { if (!n.isIstop()) { list2.add(n); } } } else { Page<Notice> page1= noticedao.queryAdminNotTop(request); list1 = page1.getContent(); list2 = noticedao.queryAdminIsTop(); for (Notice n : list1) { list2.add(n); } } List<NoticeVO> volist = new ArrayList<NoticeVO>(); for (Notice notice : list2) { NoticeVO vo = new NoticeVO(); vo.setNoticeid(notice.getNoticeid()); vo.setNoticetitle(notice.getNoticetitle()); vo.setNoticedate(notice.getNoticedate()); vo.setIsurl(notice.isIsurl()); if (notice.isIsurl()) { vo.setUrl(notice.getUrl()); } else { vo.setUrl(""); } vo.setAttachurl(notice.getAttachurl()); vo.setIsshort(notice.isIsshort()); vo.setIstop(notice.isIstop()); volist.add(vo); } return volist; } public NoticeVO findByNid(Integer noticeid) { Notice notice = noticedao.findOne(noticeid); if (notice == null) { return null; } NoticeVO vo = new NoticeVO(notice); return vo; } public List<NoticeVO> findByDate(Date start, Date end) { List<Notice> list = noticedao.findByDate(start, end); List<NoticeVO> volist = new ArrayList<NoticeVO>(); for (Notice notice : list) { NoticeVO vo = new NoticeVO(notice); volist.add(vo); } return volist; } public void setTopByNid(Integer noticeid) { Notice notice = noticedao.findOne(noticeid); if(notice.isIstop()==true){ notice.setIstop(false); }else{ notice.setIstop(true); } noticedao.save(notice); } } <file_sep>package com.nirvana.bll.service; import java.util.List; import org.springframework.data.domain.Page; import com.nirvana.app.vo.ConsultVO; import com.nirvana.app.vo.ConsulttypeVO; import com.nirvana.app.vo.UserVO; import com.nirvana.dal.po.Consult; public interface ConsultService { /** * ๆจก็ณŠๆŸฅ่ฏข็คพๅŒบๆ‰€ๆœ‰ๅ’จ่ฏข็ฑปๅž‹ * @param communityId * @param key * @return */ List<ConsulttypeVO> findAllTypeByCid(Integer communityId,String key); /** * ๆŸฅ่ฏข็คพๅŒบๅ†…ๅฏไปฅๆ‰€ๆœ‰่ขซๅ’จ่ฏข็š„ไบบ * @param communityId * @return */ List<UserVO> findAskByCid(Integer communityId); /** *ๆทปๅŠ ๅ’จ่ฏข * @param consult */ void addOne(Consult consult); /** * ๅˆ ้™คๅ’จ่ฏข * @param id */ void delById(Integer id); /** * ๅฎŒๆˆๆŸไธ€ไธชๅ’จ่ฏข * @param id */ void finishByCid(Integer id); /** * ๆ›ดๆ–ฐๅ’จ่ฏข * @param consult */ void update(Consult consult); /** * ๆŸฅ่ฏข็”จๆˆทไธบๅฎŒๆˆ็š„ๅ’จ่ฏข * @param id * @param num * @param size * @return */ Page<Consult> findUndoByUid(Integer id,Integer num,Integer size); /** * ๆŸฅ่ฏขๅฎŒๆˆ็š„ๅ’จ่ฏข * @param id * @param num * @param size * @return */ Page<Consult> findDoneByUid(Integer id,Integer num,Integer size); /** * ๆจก็ณŠๆŸฅ่ฏขๆ‰€ๆœ‰ๅ’จ่ฏข * @param communityid * @param key * @param num * @param size * @return */ Page<Consult> findByKey(Integer communityid,String key,Integer num,Integer size,Integer isfinish); } <file_sep>package com.nirvana.dal.po; import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.hibernate.annotations.ColumnDefault; /** * * @author Bin ่Š‚็‚น็ฑป */ @Entity @Table(name = "node") public class Node { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer nodeid; // ่Š‚็‚นๅๅญ— private String nodename; // ่Š‚็‚น็ฑปๅž‹id private Integer nodetype; // ่Š‚็‚น็Šถๆ€ // ๅพ…็”จ private Integer nodestatus; @Temporal(TemporalType.TIMESTAMP) // ่Š‚็‚นๆทปๅŠ ๆ—ถ้—ด private Date nodeaddtime; // ่Š‚็‚นไฝฟ็”จ่€… @ManyToOne(cascade = CascadeType.DETACH) @JoinColumn(name = "userid") private User user; // ่Š‚็‚นไธŠไผ ้ข‘็އ @ColumnDefault(value = "5") private Integer frequency; public Integer getFrequency() { return frequency; } public void setFrequency(Integer frequency) { this.frequency = frequency; } public Integer getNodeid() { return nodeid; } public void setNodeid(Integer nodeid) { this.nodeid = nodeid; } public String getNodename() { return nodename; } public Date getNodeaddtime() { return nodeaddtime; } public void setNodeaddtime(Date nodeaddtime) { this.nodeaddtime = nodeaddtime; } public void setNodename(String nodename) { this.nodename = nodename; } public Integer getNodetype() { return nodetype; } public void setNodetype(Integer nodetype) { this.nodetype = nodetype; } public Integer getNodestatus() { return nodestatus; } public void setNodestatus(Integer nodestatus) { this.nodestatus = nodestatus; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } @Override public String toString() { return "Node [nodeid=" + nodeid + ", nodename=" + nodename + ", nodetype=" + nodetype + ", nodestatus=" + nodestatus + ", nodeaddtime=" + nodeaddtime + ", user=" + user + "]"; } } <file_sep>package com.nirvana.dal.po; import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.hibernate.annotations.ColumnDefault; import org.hibernate.validator.constraints.Length; /** * * @author Bin * ๅ…ฌๅ‘Š็ฑป */ @Entity @Table(name = "notice") public class Notice { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer noticeid; //ๅ…ฌๅ‘Šๅ‘ๅธƒๆ—ฅๆœŸ @Temporal(TemporalType.TIMESTAMP) private Date noticedate; //ๅ…ฌๅ‘Šๆ ‡้ข˜ private String noticetitle; //ๅ…ฌๅ‘Šๅ†…ๅฎน @Length(max = 10000) private String noticecontent; //ๅ…ฌๅ‘Š็ฑปๅž‹id 1-่ถ…็ฎก ๅ…ฌๅ‘Š 2-็คพๅŒบๅ…ฌๅ‘Š private Integer noticetype; //้™„ไปถๅœฐๅ€ private String attachurl; //ๆ˜ฏๅฆๆ˜ฏๅค–ๆŽฅurl private boolean isurl; //ๅค–ๆŽฅ้“พๆŽฅURl private String url; //ๅ‘ๅธƒๅ…ฌๅ‘Š่€… @ManyToOne(cascade = CascadeType.DETACH) @JoinColumn(name = "userid") private User user; //ๅ…ฌๅ‘Šๆ‰€ๅฑž็คพๅŒบ @ManyToOne(cascade = CascadeType.DETACH) @JoinColumn(name = "communityid") private Community community; //ๆ˜ฏๅฆ็ฝฎ้กถ @ColumnDefault(value = "0") private boolean istop; //ๆ˜ฏๅฆๆ˜พ็คบ @ColumnDefault(value = "1") private boolean isshow; //ๆ˜ฏๅฆๆ˜ฏไธ€ๅฅ่ฏ @ColumnDefault(value="0") private boolean isshort; public boolean isIsshort() { return isshort; } public void setIsshort(boolean isshort) { this.isshort = isshort; } public boolean isIsshow() { return isshow; } public void setIsshow(boolean isshow) { this.isshow = isshow; } public boolean isIstop() { return istop; } public void setIstop(boolean istop) { this.istop = istop; } public boolean isIsurl() { return isurl; } public void setIsurl(boolean isurl) { this.isurl = isurl; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Integer getNoticeid() { return noticeid; } public void setNoticeid(Integer noticeid) { this.noticeid = noticeid; } public Date getNoticedate() { return noticedate; } public void setNoticedate(Date noticedate) { this.noticedate = noticedate; } public String getNoticetitle() { return noticetitle; } public void setNoticetitle(String noticetitle) { this.noticetitle = noticetitle; } public String getNoticecontent() { return noticecontent; } public void setNoticecontent(String noticecontent) { this.noticecontent = noticecontent; } public Integer getNoticetype() { return noticetype; } public void setNoticetype(Integer noticetype) { this.noticetype = noticetype; } public String getAttachurl() { return attachurl; } public void setAttachurl(String attachurl) { this.attachurl = attachurl; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Community getCommunity() { return community; } public void setCommunity(Community community) { this.community = community; } @Override public String toString() { return "Notice [noticeid=" + noticeid + ", noticedate=" + noticedate + ", noticetitle=" + noticetitle + ", noticecontent=" + noticecontent + ", noticetype=" + noticetype + ", attachurl=" + attachurl + ", isurl=" + isurl + ", url=" + url + ", user=" + user + ", community=" + community + "]"; } } <file_sep>package com.nirvana.dal.api; import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import com.nirvana.dal.po.Consult; /** * * @author Bin ๅ’จ่ฏขๆ•ฐๆฎๅบ“่ฎฟ้—ฎๅฑ‚ */ @Repository public interface ConsultDao extends JpaRepository<Consult, Integer> { /** * ๆŸฅ่ฏข็”จๆˆท็š„ๆ‰€ๆœ‰ๆœชๅฎŒๆˆ็š„ๅ’จ่ฏขๆœๅŠก * @param userid ็”จๆˆทid * @param pageable ๅˆ†้กต * @return ่ฟ”ๅ›žๅ’จ่ฏขๅˆ†้กต */ @Query("SELECT c FROM Consult c WHERE c.user.userid=:userid AND c.isfinish=0") Page<Consult> findUndoByUid(@Param("userid") Integer userid, Pageable pageable); /** * ๆŸฅ่ฏขๆ‰€ๆœ‰ๅทฒ็ปๅฎŒๆˆ็š„ๅ’จ่ฏขๆœๅŠก * @param userid ็”จๆˆทid * @param pageable ๅˆ†้กต * @return ๅ’จ่ฏขๅˆ†้กต */ @Query("SELECT c FROM Consult c WHERE c.user.userid=:userid AND c.isfinish=1") Page<Consult> findDoneByUid(@Param("userid") Integer userid, Pageable pageable); /** * ๆ นๆฎๆœ็ดขๅ€ผๆจก็ณŠๆŸฅ่ฏข็”จๆˆทๅๅญ— ๆŸฅๆ‰พ็ฌฆๅˆ็š„ๅ’จ่ฏขๆœๅŠก ๆŒ‰็…งๆ—ถ้—ด้™็ปญๆŽ’ๅˆ— * @param communityid ็คพๅŒบid * @param key ๆœ็ดขๅ€ผ * @param pageable ๅˆ†้กต * @return ๅ’จ่ฏขๆœๅŠก้กต */ @Query("SELECT c FROM Consult c WHERE c.user.community.communityid=:communityid AND c.user.username LIKE %:key% ORDER BY c.committime") Page<Consult> findPageByKeyAndCid(@Param("communityid") Integer communityid, @Param("key") String key, Pageable pageable); @Query("SELECT c FROM Consult c WHERE c.user.community.communityid=:communityid AND c.user.username LIKE %:key% AND c.isfinish=0 ORDER BY c.committime") Page<Consult> findPageByKeyAndCidfinish(@Param("communityid") Integer communityid, @Param("key") String key, Pageable pageable); } <file_sep>package com.nirvana.app.controller; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.google.gson.Gson; import com.nirvana.app.util.GsonUtils; import com.nirvana.app.vo.ConsultVO; import com.nirvana.app.vo.ConsulttypeVO; import com.nirvana.app.vo.Result; import com.nirvana.app.vo.UserVO; import com.nirvana.bll.service.ConsultService; import com.nirvana.bll.service.ConsulttypeService; import com.nirvana.bll.service.UserService; import com.nirvana.dal.po.Consult; import com.nirvana.dal.po.Consulttype; import com.nirvana.dal.po.User; /** * ๅ’จ่ฏข่ง†ๅ›พ่ฝฌๆขๅฑ‚ * ๆŽฅๅฃๅค„็†ๅฏๅ‚่€ƒๆŽฅๅฃๆ–‡ๆกฃ * @author Bin * */ @RestController @RequestMapping("/consult") public class ConsultController extends BaseController { @Autowired private ConsultService consultbo; @Autowired private ConsulttypeService typebo; @Autowired private UserService userservicebo; @RequestMapping("/type") public void type(HttpServletRequest request, HttpServletResponse response, @RequestParam("communityId") Integer communityId, String key) throws IOException { Integer userid = (Integer) request.getSession().getAttribute("userid"); Result result = null; if (userid == null) { result = Result.getFailInstance("userid cannot been found", null); } else { User user=userservicebo.findById(userid); if(user.getCommunity()!=null){ List<ConsulttypeVO> list = consultbo.findAllTypeByCid(user.getCommunity().getCommunityid(), key); result = Result.getSuccessInstance(list); }else{ result = Result.getFailInstance("ๆœช้€‰ๆ‹ฉ็คพๅŒบ", null); } } response.setContentType("text/html;charset=utf-8"); response.getWriter().print(new Gson().toJson(result)); } @RequestMapping("/typedel") public void typedel(HttpServletRequest request, HttpServletResponse response, @RequestParam("typeid") Integer typeid) throws IOException { Integer userid = (Integer) request.getSession().getAttribute("userid"); Result result = null; if (userid == null) { result = Result.getFailInstance("userid cannot been found", null); } else { typebo.delById(typeid); result = Result.getSuccessInstance(null); } response.setContentType("text/html;charset=utf-8"); response.getWriter().print(new Gson().toJson(result)); } @RequestMapping("/typecreate") public void create(HttpServletRequest request, HttpServletResponse response, Consulttype consulttype) throws IOException { Integer userid = (Integer) request.getSession().getAttribute("userid"); Result result = null; if (userid == null) { result = Result.getFailInstance("userid cannot been found", null); } else { typebo.add(consulttype); result = Result.getSuccessInstance(null); } response.setContentType("text/html;charset=utf-8"); response.getWriter().print(new Gson().toJson(result)); } @RequestMapping("/toask") public void toask(HttpServletRequest request, HttpServletResponse response, @RequestParam("communityId") Integer communityId) throws IOException { Result result = null; Integer userid = (Integer) request.getSession().getAttribute("userid"); User user = userservicebo.findById(userid); if(user.getCommunity()!=null){ List<UserVO> list = consultbo.findAskByCid(user.getCommunity().getCommunityid()); result = Result.getSuccessInstance(list); }else{ result=Result.getFailInstance("ๆœช้€‰ๆ‹ฉ็คพๅŒบ", null); } response.setContentType("text/html;charset=utf-8"); response.getWriter().print(new Gson().toJson(result)); } @RequestMapping("/create") public void create(HttpServletRequest request, HttpServletResponse response, Consult consult) throws IOException { Integer userid = (Integer) request.getSession().getAttribute("userid"); Result result = null; if (userid == null) { result = Result.getFailInstance("userid cannot been found", null); } else { Date now = new Date(); User user = userservicebo.findById(userid); consult.setCommittime(now); consult.setIsfinish(false); consult.setUser(user); consultbo.addOne(consult); result = Result.getSuccessInstance(null); } response.setContentType("text/html;charset=utf-8"); response.getWriter().print(new Gson().toJson(result)); } @RequestMapping("/del") public void del(HttpServletRequest request, HttpServletResponse response, @RequestParam("consultId") Integer id) throws IOException { Integer userid = (Integer) request.getSession().getAttribute("userid"); Result result = null; if (userid == null) { result = Result.getFailInstance("userid cannot been found", null); } else { consultbo.delById(id); result = Result.getSuccessInstance(null); } response.setContentType("text/html;charset=utf-8"); response.getWriter().print(new Gson().toJson(result)); } @RequestMapping("/finish") public void finish(HttpServletRequest request, HttpServletResponse response, @RequestParam("consultId") Integer id) throws IOException { Integer userid = (Integer) request.getSession().getAttribute("userid"); Result result = null; if (userid == null) { result = Result.getFailInstance("userid cannot been found", null); } else { consultbo.finishByCid(id); result = Result.getSuccessInstance(null); } response.setContentType("text/html;charset=utf-8"); response.getWriter().print(new Gson().toJson(result)); } @RequestMapping("/edit") public void edit(HttpServletRequest request, HttpServletResponse response, Consult consult) throws IOException { Integer userid = (Integer) request.getSession().getAttribute("userid"); Result result = null; if (userid == null) { result = Result.getFailInstance("userid cannot been found", null); } else { consultbo.update(consult); result = Result.getSuccessInstance(null); } response.setContentType("text/html;charset=utf-8"); response.getWriter().print(new Gson().toJson(result)); } @RequestMapping("/undo") public void undo(HttpServletRequest request, HttpServletResponse response, @RequestParam("num") Integer num, @RequestParam("size") Integer size) throws IOException { Integer userid = (Integer) request.getSession().getAttribute("userid"); Result result = null; if (userid == null) { result = Result.getFailInstance("userid cannot been found", null); } else { Page<Consult> page = consultbo.findUndoByUid(userid, num, size); List<Consult> list = page.getContent(); List<ConsultVO> volist = new ArrayList<ConsultVO>(); for (Consult consult : list) { ConsultVO vo = new ConsultVO(); vo.setConsultId(consult.getConsultid()); if (consult.getConsulttype() != null) { vo.setConsultType(consult.getConsulttype().getTypename()); vo.setTypeId(consult.getConsulttype().getTypeid()); } vo.setContent(consult.getContent()); if (consult.getToask() != null) { vo.setToaskId(consult.getToask().getUserid()); vo.setToaskName(consult.getToask().getUsername()); } vo.setFinish(false); vo.setCommitTime(consult.getCommittime()); volist.add(vo); } result = Result.getSuccessInstance(volist); result.setMsg(page.getTotalElements() + ""); } response.setContentType("text/html;charset=utf-8"); response.getWriter().print(new Gson().toJson(result)); } @RequestMapping("/done") public void done(HttpServletRequest request, HttpServletResponse response, @RequestParam("num") Integer num, @RequestParam("size") Integer size) throws IOException { Integer userid = (Integer) request.getSession().getAttribute("userid"); Result result = null; if (userid == null) { result = Result.getFailInstance("userid cannot been found", null); } else { Page<Consult> page = consultbo.findDoneByUid(userid, num, size); List<Consult> list = page.getContent(); List<ConsultVO> volist = new ArrayList<ConsultVO>(); for (Consult consult : list) { ConsultVO vo = new ConsultVO(); vo.setConsultId(consult.getConsultid()); if (consult.getConsulttype() != null) { vo.setConsultType(consult.getConsulttype().getTypename()); vo.setTypeId(consult.getConsulttype().getTypeid()); } vo.setContent(consult.getContent()); if (consult.getToask() != null) { vo.setToaskId(consult.getToask().getUserid()); vo.setToaskName(consult.getToask().getUsername()); } vo.setFinish(true); vo.setCommitTime(consult.getCommittime()); vo.setFinishTime(consult.getFinishtime()); volist.add(vo); } result = Result.getSuccessInstance(volist); result.setMsg(page.getTotalElements() + ""); } response.setContentType("text/html;charset=utf-8"); response.getWriter().print(new Gson().toJson(result)); } @RequestMapping("/list") public void list(HttpServletRequest request, HttpServletResponse response,@RequestParam("isfinish") Integer isfinish,@RequestParam("key") String key, @RequestParam("size") Integer size, @RequestParam("num") Integer num, @RequestParam("communityid") Integer communityid) throws IOException { Integer userid = (Integer) request.getSession().getAttribute("userid"); Result result = null; if (userid == null) { result = Result.getFailInstance("userid cannot been found", null); } else { Page<Consult> pages = consultbo.findByKey(communityid,key, num, size,isfinish); List<ConsultVO> volist = new ArrayList<ConsultVO>(); List<Consult> list = pages.getContent(); for (Consult consult : list) { ConsultVO vo = new ConsultVO(); vo.setConsultId(consult.getConsultid()); vo.setUsername(consult.getUser().getUsername()); if(consult.getConsulttype()!=null){ vo.setConsultType(consult.getConsulttype().getTypename()); } vo.setContent(consult.getContent()); if(consult.getToask()!=null){ vo.setToaskName(consult.getToask().getUsername()); } vo.setCommitTime(consult.getCommittime()); vo.setFinish(consult.isIsfinish()); if (consult.isIsfinish() == true) { vo.setFinishTime(consult.getFinishtime()); } volist.add(vo); } result = Result.getSuccessInstance(volist); result.setMsg(pages.getTotalElements() + ""); } response.setContentType("text/html;charset=utf-8"); response.getWriter().print(GsonUtils.getDateFormatGson().toJson(result)); } } <file_sep>package com.nirvana.bll.bo; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.nirvana.app.vo.NodeHomePageVO; import com.nirvana.app.vo.NodeVO; import com.nirvana.app.vo.UserVO; import com.nirvana.bll.service.UserService; import com.nirvana.dal.api.AlarmDataDao; import com.nirvana.dal.api.CommunityDao; import com.nirvana.dal.api.LocationDataDao; import com.nirvana.dal.api.NodeDao; import com.nirvana.dal.api.NodeDataDao; import com.nirvana.dal.api.UserDao; import com.nirvana.dal.po.AlarmData; import com.nirvana.dal.po.LocationData; import com.nirvana.dal.po.Node; import com.nirvana.dal.po.NodeData; import com.nirvana.dal.po.User; @Service @Transactional public class UserServiceBO implements UserService { @Autowired private UserDao userdao; @Autowired private NodeDao nodedao; @Autowired private NodeDataDao nodedatadao; @Autowired private AlarmDataDao alarmdatadao; @Autowired private LocationDataDao locationdatadao; @Autowired private CommunityDao communitydao; public UserVO login(String account, String password) { User user = userdao.findByAccountandPsd(account, password); if (user == null) { return null; } //ๅ‡†ๅค‡่ง†ๅ›พๅฑ•็คบ็ฑป UserVO vo = new UserVO(); vo.setUserid(user.getUserid()); vo.setUsername(user.getUsername()); vo.setTypeid(user.getTypeid()); vo.setIdentity(user.getUseridentity()); vo.setUsertel(user.getUsertel()); //้˜ฒๆญขnullpoint if (user.getCommunity() != null) { vo.setCommunityid(user.getCommunity().getCommunityid()); vo.setCommunityname(user.getCommunity().getCommunityname()); } vo.setState(user.getState()); vo.setAvatar(user.getAvatar()); return vo; } public void add(User user) { userdao.save(user); } public User findById(Integer id) { User user = userdao.findOne(id); return user; } public Page<User> findBykeypage(String key, Integer num, Integer size, Integer cid) { //ๅˆ›ๅปบๅˆ†้กต็ฑป PageRequest request = this.buildPageRequest(num, size); //ๆ นๆฎๆ˜ฏๅฆๆœ‰communityid ่ฟ›่กŒ็›ธๅบ”็š„ๆœ็ดข Page<User> pages = null; if (cid == null) { pages = this.userdao.findCommonByKey(key, request); } else { pages = userdao.findCommonByKeyAndCid(key, cid, request); } return pages; } /** * ๅˆ›ๅปบๅˆ†้กต็ฑปๅ‡ฝๆ•ฐ. * @param pageNumber ้กต็  * @param pagzSize ๆฏ้กตๆกๆ•ฐ * @return */ private PageRequest buildPageRequest(int pageNumber, int pagzSize) { return new PageRequest(pageNumber - 1, pagzSize, null); } public void updateloc(String did, String longtitude, String latitude, Date updatetime) { User user = userdao.findByDid(did); //ๆ›ดๆ–ฐ็›ธๅบ”็š„็”จๆˆท user.setLatitude(latitude); user.setLongtitude(longtitude); user.setLastupdatetime(updatetime); userdao.save(user); } public List<UserVO> findOnline(Integer cid) { List<User> list = null; if (cid == null) { list = userdao.findAll(); } else { list = userdao.findAllByCid(cid); } Date now = new Date(); List<UserVO> volist = new ArrayList<UserVO>(); for (User user : list) { // if(user.getLastupdatetime().) //ๆ นๆฎๆœ€ๆ–ฐ็š„ๆ›ดๆ–ฐๆ—ถ้—ดไธŽๅฝ“ๅ‰ๆ—ถ้—ดๅฏนๆฏ”ๆฅๅˆคๆ–ญๆ˜ฏๅฆๅœจๅœจ็บฟ if (user.getLastupdatetime() != null) { long between = now.getTime() - user.getLastupdatetime().getTime(); if (between < 60000 * 62 / user.getFrequency()) { volist.add(new UserVO(user, 2)); } } } return volist; } public void setFrequency(User user) { //้˜ฒๆญขๆจชๅ‘่ถŠๆƒ,userๆœ€ๅฅฝไปŽsessionไธญ่Žทๅ– User u = userdao.findOne(user.getUserid()); u.setFrequency(user.getFrequency()); u.setValid(user.getValid()); userdao.save(u); // List<Node> nodes = nodedao.findAllTypeByUid(user.getUserid()); // for(Node node:nodes){ // node.setFrequency(user.getFrequency()); // } // nodedao.save(nodes); // } public List<NodeHomePageVO> findNodeDataByUid(Integer userid) { User user = userdao.findOne(userid); String did = user.getUseridentity(); //ๆŸฅๆ‰พๆ‰€ๆœ‰่Š‚็‚น List<Node> nodes = nodedao.findAllTypeByUid(userid); System.out.println(nodes.size()); List<NodeHomePageVO> volist = new ArrayList<NodeHomePageVO>(); //ๅ‡†ๅค‡่ง†ๅ›พๅฑ•็คบ็ฑป for (Node node : nodes) { Integer type = node.getNodetype(); System.out.println(type); System.out.println(did); PageRequest request = this.buildPageRequest(1, 1); //ๆŸฅ่ฏขๆŸ่Š‚็‚นๆœ€ๆ–ฐ็š„ๆ•ฐๆฎ Page<NodeData> pages = nodedatadao.findLatestByDidAndType(did, type, request); List<NodeData> list = pages.getContent(); System.out.println(list.size()); NodeHomePageVO vo = new NodeHomePageVO(); //ๅˆคๆ–ญๆ˜ฏๅฆ่ฏฅ่Š‚็‚นไธŠไผ ่ฟ‡ๆ•ฐๆฎ if (list.size() > 0) { vo.setLatestData(list.get(0).getData()); vo.setLastestTime(list.get(0).getStatus_change_time()); } else { if (type == 4||type==66) { vo.setLatestData("ๆš‚ๆ— ๆ•ฐๆฎ,ๆš‚ๆ— ๆ•ฐๆฎ"); } else { vo.setLatestData("ๆš‚ๆ— ๆ•ฐๆฎ"); } } vo.setNodeName(node.getNodename()); vo.setNodeType(type); //่ฎก็ฎ—ไธ€ๆฎตๆ—ถ้—ด้‡Œ็š„ๆœ€้ซ˜ๆœ€ไฝŽๆ•ฐๆฎ //ๅฏนๆ•ฐๅ€ผ่ฟ›่กŒๅˆ†ๆžๅณๅฏ if (type == 12 || type == 4) { Integer h1 = 0, h2 = 0; Integer l1 = 10000, l2 = 10000; Date end = new Date(); Date start = new Date(); start.setTime(end.getTime() - 7 * 24 * 60 * 60 * 1000); //ๆŸฅ่ฏขไธ€ๅฎšๆ—ถ้—ดๆฎต็š„ๆ‰€ๆœ‰ๆ•ฐๆฎ List<NodeData> datas = nodedatadao.findByDidAndTypeinWeek(did, type, start, end); for (int i = 0; i < datas.size(); i++) { String value = datas.get(i).getData(); if (type == 4) { String v[] = value.split(","); //ๆฏ”่พƒ่ฟ‡็จ‹ if (Integer.parseInt(v[0]) > h1) { h1 = Integer.parseInt(v[0]); vo.setHighTime(datas.get(i).getStatus_change_time()); } if (Integer.parseInt(v[1]) > h2) { h2 = Integer.parseInt(v[1]); } if (Integer.parseInt(v[0]) < l1) { l1 = Integer.parseInt(v[0]); } if (Integer.parseInt(v[1]) < l2) { l2 = Integer.parseInt(v[1]); vo.setLowTime(datas.get(i).getStatus_change_time()); } }else { if (Integer.parseInt(value) > h1) { h1 = Integer.parseInt(value); vo.setHighTime(datas.get(i).getStatus_change_time()); } if (Integer.parseInt(value) < l1) { l1 = Integer.parseInt(value); vo.setLowTime(datas.get(i).getStatus_change_time()); } } } if (type == 4) { vo.setHigh(h1 + "," + h2); vo.setLow(l1 + "," + l2); } else { vo.setHigh(h1 + ""); vo.setLow(l1 + ""); } } volist.add(vo); } return volist; } public UserVO getDetailByUid(Integer userid) { User user = userdao.findOne(userid); UserVO vo = new UserVO(); vo.setUserid(user.getUserid()); vo.setUsername(user.getUsername()); if (user.getCommunity() != null) { vo.setCommunityid(user.getCommunity().getCommunityid()); vo.setCommunityname(user.getCommunity().getCommunityname()); } vo.setLatitude(user.getLatitude()); vo.setLongitude(user.getLongtitude()); vo.setState(user.getState()); vo.setUsertel(user.getUsertel()); return vo; } public void regist(User user) { user.setRegisttime(new Date()); user.setTypeid(3); user.setFrequency(5); user.setValid(0); user.setState(1); //todo ็คพๅŒบๅๆ— ๅ€ผ user.setUserapartment(""); userdao.save(user); } public UserVO findInfoByUid(Integer userid) { User user = userdao.findOne(userid); UserVO vo = new UserVO(); vo.setUsername(user.getUsername()); vo.setIdentity(user.getUseridentity()); vo.setGender(user.getGender()); vo.setAvatar(user.getAvatar()); vo.setUseremail(user.getUseremail()); vo.setUsertel(user.getUsertel()); vo.setAddress(user.getUseraddress()); if (user.getCommunity() != null) { vo.setCommunityid(user.getCommunity().getCommunityid()); vo.setCommunityname(user.getCommunity().getCommunityname()); } return vo; } /* * @Override public boolean checkPassword(Integer userid, String * oldPassword) { User user = userdao.findOne(userid); if * (user.getPassword().equals(oldPassword)) { return true; } else { return * false; } } */ public void updateinfo(Integer userid, User user) { //ๅฏไปฅ้€š่ฟ‡session่Žทๅ–ๅฝ“ๅ‰็”จๆˆท็š„userID๏ผŒ User u = userdao.findOne(userid); //ๆฒกๆœ‰ๅฏนๅฏ†็ ๅš่ถŠๆƒไฟๆŠค๏ผŒๆœ€ๅฅฝๅ…ˆๆไบคๅŽŸๅฏ†็ ไธŽๆ•ฐๆฎๅบ“ๅŽŸๅฏ†็ ๆฏ”่พƒไน‹ๅŽๅ†ไฟฎๆ”น if (!"".equals(user.getPassword()) && user.getPassword() != null) { u.setPassword(user.getPassword()); } u.setAvatar(user.getAvatar()); u.setGender(user.getGender()); u.setUseremail(user.getUseremail()); u.setUsertel(user.getUsertel()); u.setUseraddress(user.getUseraddress()); u.setCommunity(user.getCommunity()); if (user.getCommunity() != null) { u.setUserapartment(communitydao.findOne(user.getCommunity().getCommunityid()).getCommunityname()); } userdao.save(u); } public Integer getFrequencyByDid(String did) { User user = userdao.findByDid(did); return user.getFrequency(); } public void updatePassword(Integer userid, String newPassword) { User user = userdao.findOne(userid); user.setPassword(<PASSWORD>); userdao.save(user); } public List<UserVO> findManagersByKey(String key) { List<User> list = userdao.findManagerByKey(key); System.out.println(list.size()); //ๅ‡†ๅค‡่ง†ๅ›พๅฑ•็คบๅฑ‚ List<UserVO> volist = new ArrayList<UserVO>(); for (User user : list) { UserVO vo = new UserVO(); vo.setUserid(user.getUserid()); vo.setUsername(user.getUsername()); vo.setUsertel(user.getUsertel()); vo.setIdentity(user.getUseridentity()); if (user.getCommunity() != null) { vo.setCommunityname(user.getCommunity().getCommunityname()); vo.setCommunityid(user.getCommunity().getCommunityid()); } vo.setAccount(user.getAccount()); vo.setRegisttime(user.getRegisttime()); volist.add(vo); } return volist; } public void delByUid(Integer userid) { User user = userdao.findOne(userid); List<AlarmData> adatas = alarmdatadao.findByDid(user.getUseridentity()); List<NodeData> ndatas = nodedatadao.findByDid(user.getUseridentity()); List<LocationData> ldatas = locationdatadao.findByDid(user.getUseridentity()); //ๆณจๆ„ ่ฆๆŠŠ็›ธๅ…ณ็š„ๆ•ฐๆฎ็บง่”ๅˆ ้™ค alarmdatadao.delete(adatas); nodedatadao.delete(ndatas); locationdatadao.delete(ldatas); userdao.delete(userid); } public UserVO commonlogin(String account, String password) { User user = userdao.findCommonByAccountAndPsd(account, password); if (user == null) { return null; } UserVO vo = new UserVO(); vo.setUsername(user.getUsername()); vo.setDid(user.getUseridentity()); vo.setState(user.getState()); vo.setGender(user.getGender()); vo.setAddress(user.getUseraddress()); vo.setUseremail(user.getUseremail()); vo.setAccount(user.getAccount()); vo.setUsertel(user.getUsertel()); List<Node> polist = nodedao.findAllTypeByUid(user.getUserid()); List<NodeVO> volist = new ArrayList<NodeVO>(); for (Node n : polist) { volist.add(new NodeVO(n)); } vo.setNodes(volist); vo.setFrequency(user.getFrequency()); return vo; } public boolean didIsExist(String did) { User user = userdao.findByDid(did); if (user == null) { return false; } else { return true; } } public boolean accountIsExist(String account) { User user = userdao.findByAccount(account); if (user == null) { return false; } else { return true; } } public User findByDid(String did) { User user = userdao.findByDid(did); return user; } public List<UserVO> findAllByCid(Integer communityid) { List<User> polist = userdao.findAllByCid(communityid); List<UserVO> volist = new ArrayList<UserVO>(); for (User user : polist) { UserVO vo = new UserVO(); vo.setUserid(user.getUserid()); vo.setUsername(user.getUsername()); volist.add(vo); } return volist; } public Page<User> findRegisterByKey(String key, Integer size, Integer num) { PageRequest request = this.buildPageRequest(num, size); Page<User> page = userdao.findRegisterByKey(key, request); return page; } public void updateregister(User user) { User u = userdao.findOne(user.getUserid()); u.setUsername(user.getUsername()); u.setUseridentity(user.getUseridentity()); u.setUseraddress(user.getUseraddress()); u.setUsertel(user.getUsertel()); u.setUseremail(user.getUseremail()); u.setAccount(user.getAccount()); userdao.save(u); } public void frozen(Integer userid) { User user = userdao.findOne(userid); user.setState(0); userdao.save(user); } public void recovery(Integer userid) { User user = userdao.findOne(userid); user.setState(1); userdao.save(user); } public void update(User user) { userdao.save(user); } } <file_sep>package com.nirvana.bll.service; import java.util.Date; import java.util.List; import org.springframework.data.domain.Page; import com.nirvana.app.vo.NodeHomePageVO; import com.nirvana.app.vo.UserVO; import com.nirvana.dal.po.User; /** * * @author Bin ็”จๆˆทๆœๅŠกๆŽฅๅฃ */ public interface UserService { /** * ็”จๆˆท็™ปๅฝ• * * @param username * @param password * @return */ //todo UserVO login(String username, String password); /** * ๆทปๅŠ ็”จๆˆท * * @param user */ void add(User user); /** * ๆ นๆฎidๆœ็ดข็”จๆˆท * * @param id * @return */ User findById(Integer id); /** * ๆจก็ณŠๆŸฅ่ฏข็คพๅŒบไธญ็š„็”จๆˆท ๅนถๅˆ†้กต * @param key * @param num * @param size * @param cid * @return */ Page<User> findBykeypage(String key, Integer num, Integer size, Integer cid); /** * ๆ›ดๆ–ฐ็”จๆˆท็š„ไฝ็ฝฎไฟกๆฏ * @param did * @param longtitude * @param latitude * @param updatetime */ void updateloc(String did, String longtitude, String latitude, Date updatetime); /** * ๆŸฅ่ฏขๆ‰€ๆœ‰็คพๅŒบๅœจ็บฟ็š„็”จๆˆท * @param communityId * @return */ List<UserVO> findOnline(Integer communityId); /** * ่ฎพ็ฝฎ็”จๆˆท็š„ไฝ็ฝฎๆ•ฐๆฎไธŠไผ ้ข‘็އ * @param user */ void setFrequency(User user); /** * ๆŸฅ่ฏข็”จๆˆท้ฆ–้กต็š„ๆ˜พ็คบๆ•ฐๆฎ * @param userid * @return */ List<NodeHomePageVO> findNodeDataByUid(Integer userid); /** * ๆŸฅ่ฏข็”จๆˆท็š„็ป†่Š‚ไฟกๆฏ * @param userid * @return */ UserVO getDetailByUid(Integer userid); /** * ๆณจๅ†Œ็”จๆˆท * @param user */ void regist(User user); /** * ๆŸฅ่ฏข็”จๆˆท็š„ไฟกๆฏ * @param userid * @return */ UserVO findInfoByUid(Integer userid); // boolean checkPassword(Integer userid, String oldPassword); /** * ๆ›ดๆ–ฐ็”จๆˆท็š„ไฟกๆฏ * @param userid * @param user */ void updateinfo(Integer userid, User user); /** * ๆ นๆฎ็”จๆˆท็š„่บซไปฝ่ฏ่Žทๅ–ไธŠไผ ๅœฐๅ€ๆ•ฐๆฎ้ข‘็އ * @param did * @return */ Integer getFrequencyByDid(String did); /** * ไฟฎๆ”นๅฏ†็  * @param userid * @param newPassword */ void updatePassword(Integer userid, String newPassword); /** * ๆจก็ณŠๆœ็ดข็คพๅŒบ็ฎก็†ๅ‘˜ * @param key * @return */ List<UserVO> findManagersByKey(String key); /** * ๅˆ ้™ค็”จๆˆท * @param userid */ void delByUid(Integer userid); /** * ๆ™ฎ้€š็”จๆˆท็™ปๅฝ• * @param account * @param password * @return */ UserVO commonlogin(String account, String password); /** * ่บซไปฝ่ฏๅทๆ˜ฏๅฆๅทฒๅญ˜ๅœจ * @param did * @return */ boolean didIsExist(String did); /** * ่ดฆๆˆทๅๆ˜ฏๅฆๅญ˜ๅœจ * @param account * @return */ boolean accountIsExist(String account); /** * ๆ นๆฎ่บซไปฝ่ฏๅทๆŸฅๆ‰พ็”จๆˆท * @param did * @return */ User findByDid(String did); /** * ๆŸฅๆ‰พ็คพๅŒบไธ‹็š„ๆ‰€ๆœ‰็”จๆˆท * @param communityid * @return */ List<UserVO> findAllByCid(Integer communityid); /** * ๆจก็ณŠๆŸฅ่ฏขๆ‰€ๆœ‰ๆณจๅ†Œ็š„็”จๆˆท * @param key * @param size * @param num * @return */ Page<User> findRegisterByKey(String key, Integer size, Integer num); /** * ่ทŸๆ–ฐ็”จๆˆท * @param user */ void updateregister(User user); /** * ๅ†ป็ป“ๆŸ็”จๆˆท * @param userid */ void frozen(Integer userid); /** * ่งฃๅ†ปๆŸ็”จๆˆท * @param userid */ void recovery(Integer userid); void update(User user); } <file_sep>package com.nirvana.bll.service; import java.util.List; import com.nirvana.app.vo.ProductIntroVO; import com.nirvana.dal.po.ProductIntro; public interface ProductIntroService { /** * ๆทปๅŠ ไบงๅ“ไป‹็ป * @param intro */ void add(ProductIntro intro); /** * ๅˆ ้™คไป‹็ป * @param id */ void delById(Integer id); /** * ๆŸฅ่ฏขๆ‰€ๆœ‰ไบงๅ“ไป‹็ป * @return */ List<ProductIntro> findAll(); /** * ๆŸฅ่ฏขๆ‰€ๆœ‰ๅฏไปฅๆ˜พ็คบ็š„ไบงๅ“ไป‹็ป * @return */ List<ProductIntroVO> findShowProductIntro(); }
40b43d90cc7c7e4cf1588f4a14371870f3adb0dd
[ "Markdown", "Java", "INI" ]
30
Java
airy706/HealthCarePlatform
ceacc28d1a5ce3698f996fd3aafca528428293f1
9fcec5a94fc826e07a490f7accc37b474d5b623e
refs/heads/master
<file_sep>from setuptools import setup setup(name='runtime_mgr_api', version='1.2', description='Python wrapper for Runtime Manager API', url='https://docs.mulesoft.com/runtime-manager/runtime-manager-api', author='<NAME>', author_email='<EMAIL>', license='None', packages=['runtime_mgr_api'], zip_safe=True) <file_sep>ANYPOINT_BASE_URL = 'https://anypoint.mulesoft.com' ANYPOINT_LOGIN_URL = ANYPOINT_BASE_URL + '/accounts/login' ANYPOINT_ORG_URL = ANYPOINT_BASE_URL + '/accounts/api/me' ANYPOINT_ENV_URL = ANYPOINT_BASE_URL + \ '/accounts/api/organizations/{}/environments' ANYPOINT_CLUSTER_URL = ANYPOINT_BASE_URL + '/hybrid/api/v1/clusters' ANYPOINT_SERVER_URL = ANYPOINT_BASE_URL + '/hybrid/api/v1/servers' ANYPOINT_SERVERGROUP_URL = ANYPOINT_BASE_URL + '/hybrid/api/v1/serverGroups' ANYPOINT_APP_URL = ANYPOINT_BASE_URL + '/hybrid/api/v1/applications' ANYPOINT_TARGET_URL = ANYPOINT_BASE_URL + '/hybrid/api/v1/targets' APP_CHAR_REGEX = '[^A-Za-z0-9-]' APP_MIN_LEN = 3 APP_MAX_LEN = 42 <file_sep>from .constants import * import datetime import functools import requests import hashlib import time import re class UnauthorizedError(Exception): pass class AnypointAuthError(Exception): pass class AnypointRequestError(Exception): pass class OrgError(Exception): pass class EnvError(Exception): pass class DeployError(Exception): pass class ModifyAppError(Exception): pass class ComponentError(Exception): pass class API(object): def __init__(self, anypointUser, anypointPass, proxy=None, verifySSL=True): self.session = requests.session() self.session.verify = verifySSL if proxy is not None: self.session.proxies = {"https": proxy} self.__login(anypointUser, anypointPass) self.org_context = None self.env_context = None self.__refresh_orgs() self.__refresh_envs() self.__anypoint_user = anypointUser self.__anypoint_pass = anypointPass def __anypoint_request(self, *args, **kwargs): try: resp = self.session.request(*args, **kwargs) except requests.exceptions.Timeout: raise AnypointRequestError("Timed out during request to Anypoint") except requests.exceptions.TooManyRedirects: raise AnypointRequestError( "Too many redirects during request to Anypoint") if resp.status_code == 401: raise UnauthorizedError() return resp.json(), resp.status_code def __login(self, un=None, pw=None): if un is None: un = self.__anypoint_user if pw is None: pw = self.__anypoint_pass # clear headers so we are not passing token during login self.session.headers = {} args = 'POST', ANYPOINT_LOGIN_URL kwargs = {'data': { 'Content-Type': 'application/json', 'username': un, 'password': pw }} try: auth, code = self.__anypoint_request(*args, **kwargs) except UnauthorizedError: raise AnypointAuthError('Invalid credentials') self.session.headers['Authorization'] = 'Bearer {}'.format( auth['access_token'] ) @property def current_org(self): if self.org_context is None: return None return next( o for o in self.orgs if o['id'] == self.org_context ) @property def org_context(self): return self.__org_context @org_context.setter def org_context(self, value): self.__org_context = value self.session.headers['X-ANYPNT-ORG-ID'] = value @property def current_env(self): if self.env_context is None: return None return next( e for e in self.envs if e['id'] == self.env_context ) @property def env_context(self): return self.__env_context @env_context.setter def env_context(self, value): self.__env_context = value self.session.headers['X-ANYPNT-ENV-ID'] = value def __refresh_orgs(self): args = 'GET', ANYPOINT_ORG_URL try: resp, code = self.__anypoint_request(*args) self.orgs = resp['user']['memberOfOrganizations'] except AnypointRequestError: raise OrgError('Could not get Orgs') if self.org_context is None: self.org_context = next( (o for o in self.orgs if o['isMaster']), None )['id'] def switch_org(self, orgName): try: self.org_context = next( o for o in self.orgs if o['name'] == orgName )['id'] except StopIteration: raise OrgError('Could not find desired Org') self.env_context = None self.__refresh_envs() def __refresh_envs(self): url = ANYPOINT_ENV_URL.format(self.org_context) args = 'GET', url try: resp, code = self.__anypoint_request(*args) self.envs = resp['data'] except AnypointRequestError: raise EnvError('Could not get Envs') def switch_env(self, envName): try: self.env_context = next( e for e in self.envs if e['name'] == envName )['id'] except StopIteration: raise EnvError('Could not find desired Env') def get_apps(self, targetName=None): args = 'GET', ANYPOINT_APP_URL resp, code = self.__anypoint_request(*args) apps = resp['data'] if targetName is not None: apps = [a for a in apps if a['target']['name'] == targetName] return apps def get_servers(self): args = 'GET', ANYPOINT_SERVER_URL resp, code = self.__anypoint_request(*args) return resp['data'] def get_server_groups(self): args = 'GET', ANYPOINT_SERVERGROUP_URL resp, code = self.__anypoint_request(*args) return resp['data'] def get_clusters(self): args = 'GET', ANYPOINT_CLUSTER_URL resp, code = self.__anypoint_request(*args) return resp['data'] def get_targets(self): return ( self.get_servers() + self.get_server_groups() + self.get_clusters() ) def __verify_app_name(self, appName): assert len(appName) > APP_MIN_LEN, "App name too short" assert len(appName) <= APP_MAX_LEN, "App name too long" assert (not appName.startswith('-') and not appName.endswith('-')), \ "App name starts or ends with a dash" assert re.search(APP_CHAR_REGEX, appName) is None, \ "App name has invalid characters" def deploy_app(self, appName, zipFile, targetId=None, targetName=None): try: self.__verify_app_name(appName) except AssertionError as e: raise DeployError('App name invalid: {}'.format(str(e))) if targetId is None: targets = self.get_targets() try: targetId = next( t for t in targets if t['name'] == targetName )['id'] except StopIteration: raise DeployError('Target server or cluster not found') args = 'POST', ANYPOINT_APP_URL kwargs = {'files': { 'artifactName': appName, 'file': zipFile, 'targetId': str(targetId) }} resp, code = self.__anypoint_request(*args, **kwargs) if code != 202: raise DeployError( 'Deploy failed with HTTP code {}: {}'.format( str(code), resp['message'] ) ) def update_app(self, appName, zipFile, verify=True): apps = self.get_apps() try: app = next( a for a in apps if a['name'] == appName ) except StopIteration: raise DeployError('Target app not found') if verify: localhash = hashlib.sha1(zipFile.read()).hexdigest() zipFile.seek(0) if localhash == app['artifact']['fileChecksum']: raise DeployError('Application is already up-to-date') args = 'PATCH', '{}/{}'.format(ANYPOINT_APP_URL, str(app['id'])) kwargs = {'files': {'file': zipFile}} resp, code = self.__anypoint_request(*args, **kwargs) if code != 200: raise DeployError( 'App update failed with HTTP code {}: {}'.format( str(code), resp['message'] ) ) <file_sep>-r requirements.txt HTTMock>=1.2.6 <file_sep>import requests from httmock import urlmatch, HTTMock from unittest import TestCase from unittest.mock import patch, Mock, mock_open from mock_responses import * from runtime_mgr_api import * @urlmatch(path='/accounts/login') def login_mock(url, request): return MOCK_LOGIN_RESPONSE @urlmatch(path='/accounts/login') def unauthorized_login_mock(url, request): return MOCK_UNAUTHORIZED_RESPONSE @urlmatch(path='/accounts/api/me') def org_mock(url, request): return MOCK_ORG_RESPONSE @urlmatch(path=r'\/accounts\/api\/organizations\/.*\/environments') def env_mock(url, request): return MOCK_ENV_RESPONSE @urlmatch(path='/hybrid/api/v1/applications') def app_mock(url, request): return MOCK_APP_RESPONSE @urlmatch(path='/hybrid/api/v1/servers') def server_mock(url, request): return MOCK_SERVER_RESPONSE @urlmatch(path='/hybrid/api/v1/serverGroups') def servergroup_mock(url, request): return MOCK_SERVERGROUP_RESPONSE @urlmatch(path='/hybrid/api/v1/clusters') def cluster_mock(url, request): return MOCK_CLUSTER_RESPONSE @urlmatch(path='/hybrid/api/v1/applications') def deploy_mock(url, request): return MOCK_DEPLOY_RESPONSE @urlmatch(path=r'\/hybrid\/api\/v1\/applications\/[0-9]*') def update_mock(url, request): return MOCK_UPDATE_RESPONSE class TestLogin(TestCase): def test_login_sets_header(self): with HTTMock(login_mock), HTTMock(org_mock), HTTMock(env_mock): rma = API('fake_user', 'fake_pass') mock_token = '<PASSWORD>' self.assertEqual( rma.session.headers['Authorization'], 'Bearer {}'.format(mock_token) ) def test_unauthorized_login_raises_exception(self): with HTTMock(unauthorized_login_mock), \ self.assertRaises(AnypointAuthError): rma = API('fake_user', 'fake_pass') class TestOrgs(TestCase): def test_org_refresh_sets_context(self): with HTTMock(login_mock), HTTMock(org_mock), HTTMock(env_mock): rma = API('fake_user', 'fake_pass') mock_org_id = '731ed508-dbc3-4b78-889c-b5e6fc532b0f' self.assertEqual(rma.org_context, mock_org_id) self.assertEqual( rma.session.headers['X-ANYPNT-ORG-ID'], mock_org_id ) class TestEnvs(TestCase): def test_switch_env_sets_context(self): with HTTMock(login_mock), HTTMock(org_mock), HTTMock(env_mock): rma = API('fake_user', 'fake_pass') rma.switch_env('FAKEPROD') mock_env_id = '36f615eb-7c09-45e9-a880-3809099cb7e8' self.assertEqual(rma.env_context, mock_env_id) self.assertEqual( rma.session.headers['X-ANYPNT-ENV-ID'], mock_env_id ) class TestApps(TestCase): def test_get_apps_response_is_not_none(self): with HTTMock(login_mock), HTTMock(org_mock), \ HTTMock(env_mock), HTTMock(app_mock): rma = API('fake_user', 'fake_pass') self.assertIsNotNone(rma.get_apps()) def test_get_apps_with_target_name_filters_results(self): with HTTMock(login_mock), HTTMock(org_mock), \ HTTMock(env_mock), HTTMock(app_mock): rma = API('fake_user', 'fake_pass') apps = rma.get_apps(targetName='fakeserver1') self.assertEqual(len(apps), 1) class TestAppNames(TestCase): def test_app_name_too_long_raises_exception(self): with HTTMock(login_mock), HTTMock(org_mock), HTTMock(env_mock), \ self.assertRaises(DeployError): rma = API('fake_user', 'fake_pass') rma.deploy_app('this-app-name-is-toooooooooooooooooooo-long', None) def test_app_name_too_short_raises_exception(self): with HTTMock(login_mock), HTTMock(org_mock), HTTMock(env_mock), \ self.assertRaises(DeployError): rma = API('fake_user', 'fake_pass') rma.deploy_app('x', None) def test_app_name_starts_with_dash_raises_exception(self): with HTTMock(login_mock), HTTMock(org_mock), HTTMock(env_mock), \ self.assertRaises(DeployError): rma = API('fake_user', 'fake_pass') rma.deploy_app('-fakeapp', None) def test_app_name_ends_with_dash_raises_exception(self): with HTTMock(login_mock), HTTMock(org_mock), HTTMock(env_mock), \ self.assertRaises(DeployError): rma = API('fake_user', 'fake_pass') rma.deploy_app('fakeapp-', None) def test_app_name_has_invalid_chars_raises_exception(self): with HTTMock(login_mock), HTTMock(org_mock), HTTMock(env_mock), \ self.assertRaises(DeployError): rma = API('fake_user', 'fake_pass') rma.deploy_app("#@.$*()+;~:'/%_?,=&!", None) class TestTargets(TestCase): def test_server_response_is_not_none(self): with HTTMock(login_mock), HTTMock(org_mock), \ HTTMock(env_mock), HTTMock(server_mock): rma = API('fake_user', 'fake_pass') self.assertIsNotNone(rma.get_servers()) def test_servergroup_response_is_not_none(self): with HTTMock(login_mock), HTTMock(org_mock), \ HTTMock(env_mock), HTTMock(servergroup_mock): rma = API('fake_user', 'fake_pass') self.assertIsNotNone(rma.get_server_groups()) def test_cluster_response_is_not_none(self): with HTTMock(login_mock), HTTMock(org_mock), \ HTTMock(env_mock), HTTMock(cluster_mock): rma = API('fake_user', 'fake_pass') self.assertIsNotNone(rma.get_clusters()) def test_target_response_is_sum_of_parts(self): with HTTMock(login_mock), HTTMock(org_mock), HTTMock(env_mock), \ HTTMock(server_mock), HTTMock(servergroup_mock), \ HTTMock(cluster_mock): rma = API('fake_user', 'fake_pass') self.assertEqual(len(rma.get_targets()), 3) class TestDeploy(TestCase): def test_deploy_with_targetname_does_not_fail(self): try: with HTTMock(login_mock), HTTMock(org_mock), HTTMock(env_mock), \ HTTMock(server_mock), HTTMock(servergroup_mock), \ HTTMock(cluster_mock), HTTMock(deploy_mock), \ patch('builtins.open', mock_open(read_data='fakedata')) as m: with open('fakepath') as f: rma = API('fake_user', 'fake_pass') rma.deploy_app('new-fake-app', f, targetName='fakeserver1') except DeployError: self.fail("Test encountered DeployError") def test_deploy_with_targetid_does_not_fail(self): try: with HTTMock(login_mock), HTTMock(org_mock), HTTMock(env_mock), \ HTTMock(server_mock), HTTMock(servergroup_mock), \ HTTMock(cluster_mock), HTTMock(deploy_mock), \ patch('builtins.open', mock_open(read_data='fake')) as m: with open('fakepath') as f: rma = API('fake_user', 'fake_pass') rma.deploy_app('new-fake-app', f, targetName='fakeserver1') except DeployError: self.fail("Test encountered DeployError") class TestUpdate(TestCase): def test_update_does_not_fail(self): try: with HTTMock(login_mock), HTTMock(org_mock), HTTMock(env_mock), \ HTTMock(app_mock), HTTMock(update_mock), \ patch('builtins.open', mock_open(read_data=b'fake')) as m: with open('fakepath', 'rb') as f: rma = API('fake_user', 'fake_pass') rma.update_app('fake-app-1', f) except DeployError: self.fail("Test encountered DeployError") def test_update_duplicate_hash_raises_exception(self): with HTTMock(login_mock), HTTMock(org_mock), HTTMock(env_mock), \ HTTMock(app_mock), HTTMock(update_mock), \ patch('builtins.open', mock_open(read_data=b'fake')) as m, \ self.assertRaises(DeployError): with open('fakepath', 'rb') as f: rma = API('fake_user', 'fake_pass') # the mock response includes a hash to match b'fake' # for fake-app-2 rma.update_app('fake-app-2', f) <file_sep>MOCK_LOGIN_RESPONSE = { 'status_code': 200, 'content': { # fake token 'access_token': '<PASSWORD>', 'redirectUrl': '/home/', 'token_type': 'bearer' } } MOCK_UNAUTHORIZED_RESPONSE = { 'status_code': 401, 'content': 'Unauthorized' } MOCK_ORG_RESPONSE = { 'status_code': 200, 'content': { "user": { "id": "2345f29a-6596-4931-bd91-79f25a4ea436", "createdAt": "2017-05-25T14:13:31.886Z", "updatedAt": "2018-10-31T17:07:11.763Z", "organizationId": "731ed508-dbc3-4b78-889c-b5e6fc532b0f", "firstName": "Fake", "lastName": "User", "email": "<EMAIL>", "phoneNumber": "8005555555", "idprovider_id": "mulesoft", "username": "fakeuser", "enabled": True, "deleted": False, "lastLogin": "2018-10-31T17:07:00.000Z", "type": "host", "organizationPreferences": {}, "organization": { "name": "FakeOrg", "id": "731ed508-dbc3-4b78-889c-b5e6fc532b0f", "createdAt": "2017-01-19T16:01:13.523Z", "updatedAt": "2018-10-12T04:32:51.926Z", "ownerId": "2345f29a-6596-4931-bd91-79f25a4ea436", "clientId": "9f2a60ea-bdff-4959-975c-47c8447a3868", "domain": "FakeOrg-2", "idprovider_id": "FakeCompany:FakeOrg.anypoint.mulesoft.com", "isFederated": True, "parentOrganizationIds": [], "subOrganizationIds": [ "68b41362-ea1b-4269-8035-9c12039b58df", "96408f62-1e13-4036-af59-a6188488f103", "2a9da4c0-6552-41e6-852c-1876742e6a9c" ], "tenantOrganizationIds": [], "isMaster": True, "subscription": { "category": "Customer", "type": "Platinum", "expiration": "2019-02-27T16:01:13.522Z" }, "properties": { "identity_management": { "saml": { "issuer": "FakeCompany", "public_key": "-----BEGIN CERTIFICATE-----\\NoCert\\n-----END CERTIFICATE-----", "audience": "FakeOrg.anypoint.mulesoft.com", "claims_mapping": { "group_attribute": "memberOf", "username_attribute": "", "firstname_attribute": "", "lastname_attribute": "", "email_attribute": "" }, "name": "SAML 2.0" }, "type": { "description": "SAML 2.0", "name": "saml" }, "service_provider": { "urls": { "sign_on": "https://fedsso.company.com/fakeuri/saml2sso?SPID=FakeOrg.anypoint.mulesoft.com", "sign_out": "https://fedsso.company.com/signout.html" }, "name": "SAML Service Provider" } } }, "entitlements": { "createEnvironments": True, "globalDeployment": True, "createSubOrgs": True, "hybrid": { "enabled": True }, "hybridInsight": True, "hybridAutoDiscoverProperties": True, "vCoresProduction": { "assigned": 0, "reassigned": 0 }, "vCoresSandbox": { "assigned": 0, "reassigned": 0 }, "vCoresDesign": { "assigned": 17, "reassigned": 0 }, "staticIps": { "assigned": 0, "reassigned": 0 }, "vpcs": { "assigned": 2, "reassigned": 0 }, "vpns": { "assigned": 0, "reassigned": 0 }, "workerLoggingOverride": { "enabled": False }, "mqMessages": { "base": 0, "addOn": 0 }, "mqRequests": { "base": 0, "addOn": 0 }, "objectStoreRequestUnits": { "base": 0, "addOn": 0 }, "objectStoreKeys": { "base": 0, "addOn": 0 }, "mqAdvancedFeatures": { "enabled": False }, "gateways": { "assigned": 0 }, "designCenter": { "apiExample": False, "apiVisual": True, "mozart": True, "api": True }, "partnersProduction": { "assigned": 0 }, "partnersSandbox": { "assigned": 0 }, "loadBalancer": { "assigned": 0, "reassigned": 0 }, "externalIdentity": True, "autoscaling": False, "armAlerts": True, "apis": { "enabled": False }, "apiMonitoring": { "schedules": 5 }, "monitoringCenter": { "productSKU": -1 }, "crowd": { "hideApiManagerDesigner": True, "enableApiDesigner": True, "environments": True }, "cam": { "enabled": False }, "exchange2": { "enabled": False }, "crowdSelfServiceMigration": { "enabled": False }, "kpiDashboard": { "enabled": False }, "pcf": False, "appViz": False, "runtimeFabric": True, "anypointSecurityTokenization": { "enabled": False }, "anypointSecurityEdgePolicies": { "enabled": False }, "messaging": { "assigned": 0 }, "workerClouds": { "assigned": 1, "reassigned": 0 } } }, "properties": { "cs_auth": { "activeOrganizationId": "9a50dd7f-249a-4973-b9b5-7702b60a869c" } }, "memberOfOrganizations": [ { "name": "FakeOrg", "id": "731ed508-dbc3-4b78-889c-b5e6fc532b0f", "createdAt": "2017-01-19T16:01:13.523Z", "updatedAt": "2018-10-12T04:32:51.926Z", "ownerId": "2345f29a-6596-4931-bd91-79f25a4ea436", "clientId": "9f2a60ea-bdff-4959-975c-47c8447a3868", "domain": "FakeOrg-2", "idprovider_id": "FakeCompany:FakeOrg.anypoint.mulesoft.com", "isFederated": True, "parentOrganizationIds": [], "subOrganizationIds": [ "b6c6dbc2-063b-46d4-b282-83c2761c57d0", "cd0a477b-9336-4bee-960f-d872890f7687", "4a810114-0a80-4280-a3c4-91f76ba385f6" ], "tenantOrganizationIds": [], "parentName": None, "parentId": None, "isMaster": True, "subscription": { "category": "Customer", "type": "Platinum", "expiration": "2019-02-27T16:01:13.522Z" } }, { "name": "FakeOrg-BG1", "id": "4a810114-0a80-4280-a3c4-91f76ba385f6", "createdAt": "2018-07-31T15:38:58.986Z", "updatedAt": "2018-10-12T04:32:51.936Z", "ownerId": "0ad20450-9fbe-4801-a1a6-926f725d5a8d", "clientId": "ee75a1ab-d895-42c8-9d6d-f2fa04759194", "domain": None, "idprovider_id": "mulesoft", "isFederated": True, "parentOrganizationIds": [ "731ed508-dbc3-4b78-889c-b5e6fc532b0f" ], "subOrganizationIds": [], "tenantOrganizationIds": [], "parentName": "FakeOrg", "parentId": "731ed508-dbc3-4b78-889c-b5e6fc532b0f", "isMaster": False }, { "name": "FakeOrg-BG2", "id": "b6c6dbc2-063b-46d4-b282-83c2761c57d0", "createdAt": "2017-06-07T19:07:45.819Z", "updatedAt": "2018-10-12T04:32:51.936Z", "ownerId": "2345f29a-6596-4931-bd91-79f25a4ea436", "clientId": "1ba6cdb44f0a48a0b4623673c985bdfe", "domain": None, "idprovider_id": "mulesoft", "isFederated": True, "parentOrganizationIds": [ "731ed508-dbc3-4b78-889c-b5e6fc532b0f" ], "subOrganizationIds": [], "tenantOrganizationIds": [], "parentName": "FakeOrg", "parentId": "731ed508-dbc3-4b78-889c-b5e6fc532b0f", "isMaster": False }, { "name": "FakeOrg-BG3", "id": "cd0a477b-9336-4bee-960f-d872890f7687", "createdAt": "2018-01-25T16:58:36.904Z", "updatedAt": "2018-10-12T04:32:51.936Z", "ownerId": "2345f29a-6596-4931-bd91-79f25a4ea436", "clientId": "2a9d2f1cfaa9471abb59ac205fee0c97", "domain": None, "idprovider_id": "mulesoft", "isFederated": True, "parentOrganizationIds": [ "731ed508-dbc3-4b78-889c-b5e6fc532b0f" ], "subOrganizationIds": [], "tenantOrganizationIds": [], "parentName": "FakeOrg", "parentId": "731ed508-dbc3-4b78-889c-b5e6fc532b0f", "isMaster": False } ], "contributorOfOrganizations": [ { "name": "FakeOrg", "id": "731ed508-dbc3-4b78-889c-b5e6fc532b0f", "createdAt": "2017-01-19T16:01:13.523Z", "updatedAt": "2018-10-12T04:32:51.926Z", "ownerId": "2345f29a-6596-4931-bd91-79f25a4ea436", "clientId": "9f2a60ea-bdff-4959-975c-47c8447a3868", "domain": "FakeOrg-2", "idprovider_id": "FakeCompany:FakeOrg.anypoint.mulesoft.com", "isFederated": True, "parentOrganizationIds": [], "subOrganizationIds": [ "b6c6dbc2-063b-46d4-b282-83c2761c57d0", "cd0a477b-9336-4bee-960f-d872890f7687", "4a810114-0a80-4280-a3c4-91f76ba385f6" ], "tenantOrganizationIds": [], "parentName": None, "parentId": None, "isMaster": True, "subscription": { "category": "Customer", "type": "Platinum", "expiration": "2019-02-27T16:01:13.522Z" } }, { "name": "FakeOrg-BG1", "id": "4a810114-0a80-4280-a3c4-91f76ba385f6", "createdAt": "2018-07-31T15:38:58.986Z", "updatedAt": "2018-10-12T04:32:51.936Z", "ownerId": "<PASSWORD>", "clientId": "ee75a1ab-d895-42c8-9d6d-f2fa04759194", "domain": None, "idprovider_id": "mulesoft", "isFederated": True, "parentOrganizationIds": [ "731ed508-dbc3-4b78-889c-b5e6fc532b0f" ], "subOrganizationIds": [], "tenantOrganizationIds": [], "parentName": "FakeOrg", "parentId": "731ed508-dbc3-4b78-889c-b5e6fc532b0f", "isMaster": False }, { "name": "FakeOrg-BG2", "id": "b6c6dbc2-063b-46d4-b282-83c2761c57d0", "createdAt": "2017-06-07T19:07:45.819Z", "updatedAt": "2018-10-12T04:32:51.936Z", "ownerId": "2345f29a-6596-4931-bd91-79f25a4ea436", "clientId": "1ba6cdb44f0a48a0b4623673c985bdfe", "domain": None, "idprovider_id": "mulesoft", "isFederated": True, "parentOrganizationIds": [ "731ed508-dbc3-4b78-889c-b5e6fc532b0f" ], "subOrganizationIds": [], "tenantOrganizationIds": [], "parentName": "FakeOrg", "parentId": "731ed508-dbc3-4b78-889c-b5e6fc532b0f", "isMaster": False }, { "name": "FakeOrg-BG3", "id": "cd0a477b-9336-4bee-960f-d872890f7687", "createdAt": "2018-01-25T16:58:36.904Z", "updatedAt": "2018-10-12T04:32:51.936Z", "ownerId": "2345f29a-6596-4931-bd91-79f25a4ea436", "clientId": "2a9d2f1cfaa9471abb59ac205fee0c97", "domain": None, "idprovider_id": "mulesoft", "isFederated": True, "parentOrganizationIds": [ "731ed508-dbc3-4b78-889c-b5e6fc532b0f" ], "subOrganizationIds": [], "tenantOrganizationIds": [], "parentName": "FakeOrg", "parentId": "731ed508-dbc3-<PASSWORD>", "isMaster": False } ] }, "access_token": { "access_token": "<PASSWORD>", "expires_in": 3596 } } } MOCK_ENV_RESPONSE = { 'status_code': 200, 'content': { "data": [ { "id": "fc0b75a4-8f17-47b8-b0df-18793f7507ba", "name": "FAKEDEV", "organizationId": "731ed508-dbc3-4b78-889c-b5e6fc532b0f", "isProduction": False, "type": "sandbox", "clientId": "3ea4018a-902f-4682-b5dd-b2915877aef8" }, { "id": "36f615eb-7c09-45e9-a880-3809099cb7e8", "name": "FAKEPROD", "organizationId": "731ed508-dbc3-4b78-889c-b5e6fc532b0f", "isProduction": True, "type": "production", "clientId": "ba493896-be33-49a4-9081-656722d5a149" } ], "total": 2 } } MOCK_APP_RESPONSE = { 'status_code': 200, 'content': { "data": [ { "id": 1234567, "timeCreated": 1539805405470, "timeUpdated": 1539870422168, "name": "fake-app-1", "uptime": 1293834630, "desiredStatus": "STARTED", "lastReportedStatus": "STARTED", "started": True, "serverArtifacts": [ { "id": 1234568, "timeCreated": 1539805405473, "timeUpdated": 1539887034815, "artifactName": "fake-app-1", "artifact": { "id": 1234569, "storageId": 1234560, "name": "fake-app-1", "fileName": "fake-app-1.jar", "fileChecksum": "ae7dc42268f2324723329141cb6268f2", "fileSize": 23573150, "timeUpdated": 1539870422927 }, "deploymentId": 1234567, "serverId": 1000000, "lastReportedStatus": "STARTED", "desiredStatus": "STARTED", "message": "", "discovered": False } ], "artifact": { "id": 1234569, "storageId": 1234560, "name": "fake-app-1", "fileName": "fake-app-1.jar", "fileChecksum": "ae7dc42268f2324723329141cb6268f2", "fileSize": 23573150, "timeUpdated": 1539870422927 }, "target": { "id": 1000000, "timeCreated": 1539804670390, "timeUpdated": 1541176181449, "name": "fakeserver1", "type": "SERVER", "serverType": "GATEWAY", "muleVersion": "4.1.4", "gatewayVersion": "4.1.4", "agentVersion": "2.1.7", "licenseExpirationDate": 1551312000000, "certificateExpirationDate": 1602963070000, "status": "RUNNING", "addresses": [ { "ip": "8.8.8.8", "networkInterface": "eth0" } ], "runtimeInformation": { "jvmInformation": { "runtime": { "name": "Java(TM) SE Runtime Environment", "version": "1.8.0_181-b13" }, "specification": { "vendor": "Oracle Corporation", "name": "Java Platform API Specification", "version": "1.8" } }, "osInformation": { "name": "Linux", "version": "3.10.0-862.14.4.el7.x86_64", "architecture": "amd64" }, "muleLicenseExpirationDate": 1551312000000 } } }, { "id": 7654321, "timeCreated": 1539871651803, "timeUpdated": 1539871651809, "name": "fake-app-2", "uptime": 1293833528, "desiredStatus": "STARTED", "lastReportedStatus": "STARTED", "started": True, "serverArtifacts": [ { "id": 7654322, "timeCreated": 1539871651807, "timeUpdated": 1539887035906, "artifactName": "fake-app-2", "artifact": { "id": 7654323, "storageId": 7654324, "name": "fake-app-2", "fileName": "fake-app-2.jar", "fileChecksum": "c053ecf9ed41df0311b9df13cc6c3b6078d2d3c2", "fileSize": 19914984, "timeUpdated": 1539871652802 }, "deploymentId": 7654321, "serverId": 1000000, "lastReportedStatus": "STARTED", "desiredStatus": "STARTED", "message": "", "discovered": False } ], "artifact": { "id": 7654323, "storageId": 7654324, "name": "fake-app-2", "fileName": "fake-app-2.jar", "fileChecksum": "c053ecf9ed41df0311b9df13cc6c3b6078d2d3c2", "fileSize": 19914984, "timeUpdated": 1539871652802 }, "target": { "id": 1000001, "timeCreated": 1539804670390, "timeUpdated": 1541176181449, "name": "fakeserver2", "type": "SERVER", "serverType": "GATEWAY", "muleVersion": "4.1.4", "gatewayVersion": "4.1.4", "agentVersion": "2.1.7", "licenseExpirationDate": 1551312000000, "certificateExpirationDate": 1602963070000, "status": "RUNNING", "addresses": [ { "ip": "8.8.4.4", "networkInterface": "eth0" } ], "runtimeInformation": { "jvmInformation": { "runtime": { "name": "Java(TM) SE Runtime Environment", "version": "1.8.0_181-b13" }, "specification": { "vendor": "Oracle Corporation", "name": "Java Platform API Specification", "version": "1.8" } }, "osInformation": { "name": "Linux", "version": "3.10.0-862.14.4.el7.x86_64", "architecture": "amd64" }, "muleLicenseExpirationDate": 1551312000000 } } } ] } } MOCK_SERVER_RESPONSE = { 'status_code': 200, 'content': { "data": [ { "id": 1000000, "timeCreated": 1539804670390, "timeUpdated": 1541176181449, "name": "fakeserver1", "type": "SERVER", "serverType": "GATEWAY", "muleVersion": "4.1.4", "gatewayVersion": "4.1.4", "agentVersion": "2.1.7", "licenseExpirationDate": 1551312000000, "certificateExpirationDate": 1602963070000, "status": "RUNNING", "addresses": [ { "ip": "8.8.8.8", "networkInterface": "eth0" } ], "runtimeInformation": { "jvmInformation": { "runtime": { "name": "Java(TM) SE Runtime Environment", "version": "1.8.0_181-b13" }, "specification": { "vendor": "Oracle Corporation", "name": "Java Platform API Specification", "version": "1.8" } }, "osInformation": { "name": "Linux", "version": "3.10.0-862.14.4.el7.x86_64", "architecture": "amd64" }, "muleLicenseExpirationDate": 1551312000000 } } ] } } MOCK_SERVERGROUP_RESPONSE = { 'status_code': 200, 'content': { "data": [ { "id": 123456, "timeCreated": 1541183235771, "timeUpdated": 1541183235771, "name": "fake-group-1", "type": "SERVER_GROUP", "status": "DISCONNECTED", "servers": [ { "id": 123455, "timeCreated": 1519060596284, "timeUpdated": 1541183235773, "name": "fake-server-3", "type": "SERVER", "serverType": "GATEWAY", "muleVersion": "3.9.0", "gatewayVersion": "3.9.0", "agentVersion": "1.9.0", "licenseExpirationDate": 1519452000000, "certificateExpirationDate": 1582132596284, "status": "DISCONNECTED", "serverGroupId": 123456, "serverGroupName": "fake-group-1", "addresses": [ { "ip": "127.0.0.1", "networkInterface": "eth3" } ], "runtimeInformation": { "jvmInformation": { "runtime": { "name": "Java(TM) SE Runtime Environment", "version": "1.8.0_161-b12" }, "specification": { "vendor": "Oracle Corporation", "name": "Java Platform API Specification", "version": "1.8" } }, "osInformation": { "name": "Windows 7", "version": "6.1", "architecture": "x86" }, "muleLicenseExpirationDate": 1519452000000 } } ] } ] } } MOCK_CLUSTER_RESPONSE = { 'status_code': 200, 'content': { "data": [ { "id": 555555, "timeCreated": 1521942106448, "timeUpdated": 1541159115261, "name": "fake-cluster-1", "type": "CLUSTER", "status": "RUNNING", "multicastEnabled": False, "primaryNodeId": 555551, "servers": [ { "id": 555551, "timeCreated": 1521863052021, "timeUpdated": 1541123908530, "name": "fake-server-4", "type": "SERVER", "serverType": "GATEWAY", "muleVersion": "3.9.0", "gatewayVersion": "3.9.0", "agentVersion": "1.9.4", "licenseExpirationDate": 1551312000000, "certificateExpirationDate": 1585021452021, "status": "RUNNING", "addresses": [ { "ip": "10.10.10.10", "networkInterface": "eth0" } ], "clusterId": 555555, "clusterName": "fake-cluster-1", "serverIp": "10.10.10.10", "currentClusteringIp": "10.10.10.10", "currentClusteringPort": 5701, "runtimeInformation": { "jvmInformation": { "runtime": { "name": "Java(TM) SE Runtime Environment", "version": "1.8.0_181-b13" }, "specification": { "vendor": "Oracle Corporation", "name": "Java Platform API Specification", "version": "1.8" } }, "osInformation": { "name": "Linux", "version": "3.10.0-862.14.4.el7.x86_64", "architecture": "amd64" }, "muleLicenseExpirationDate": 1551312000000 } }, { "id": 555552, "timeCreated": 1521940058282, "timeUpdated": 1541159115099, "name": "fake-server-5", "type": "SERVER", "serverType": "GATEWAY", "muleVersion": "3.9.0", "gatewayVersion": "3.9.0", "agentVersion": "1.9.4", "licenseExpirationDate": 1551312000000, "certificateExpirationDate": 1585098458282, "status": "RUNNING", "addresses": [ { "ip": "10.10.10.20", "networkInterface": "eth0" } ], "clusterId": 555555, "clusterName": "fake-cluster-1", "serverIp": "10.10.10.20", "currentClusteringIp": "10.10.10.20", "currentClusteringPort": 5701, "runtimeInformation": { "jvmInformation": { "runtime": { "name": "Java(TM) SE Runtime Environment", "version": "1.8.0_181-b13" }, "specification": { "vendor": "Oracle Corporation", "name": "Java Platform API Specification", "version": "1.8" } }, "osInformation": { "name": "Linux", "version": "3.10.0-862.14.4.el7.x86_64", "architecture": "amd64" }, "muleLicenseExpirationDate": 1551312000000 } } ], "visibilityMap": { "mapNodes": [ { "serverId": 555551, "visibleNodeIds": [ 555551, 555552 ], "unknownNodeIps": [] }, { "serverId": 555552, "visibleNodeIds": [ 555551, 555552 ], "unknownNodeIps": [] } ] } } ] } } MOCK_DEPLOY_RESPONSE = { 'status_code': 202, 'content': { "data": { "id": 684, "artifact": { "id": 1027, "name": "test", "fileName": "test.zip", "fileChecksum": "e98753b28c0fc7f2d01c56682de1387be0faf040", "timeUpdated": 1441221944496 }, "lastReportedStatus": "UNDEPLOYED" } } } MOCK_DEPLOY_FAILED_RESPONSE = { 'status_code': 500, 'content': { "data": {} } } MOCK_UPDATE_RESPONSE = { 'status_code': 200, 'content': { "data": { "id": 684, "artifact": { "id": 1027, "name": "test", "fileName": "test.zip", "fileChecksum": "e98753b28c0fc7f2d01c56682de1387be0faf040", "timeUpdated": 1441221944496 }, "lastReportedStatus": "STARTED" } } } <file_sep>[![Build Status](https://travis-ci.com/adam-j-turner/runtime-mgr-api.svg?branch=master)](https://travis-ci.com/adam-j-turner/runtime-mgr-api) # runtime_mgr_api Python wrapper for MuleSoft Anypoint Runtime Manager API Example usage (deploying an app from local zip file): ``` import runtime_mgr_api import os my_api = runtime_mgr_api.API('my_user','my_pass') my_api.switch_org('MY-ORG') my_api.switch_env('MY-ENV') zipFile = open('C:\muletest\my-app.zip', 'rb') my_api.deploy_app('my-app', zipFile, targetName='my-server-1') ``` <file_sep>import requests from .api import *
a02d3a48031c5fed1d23fc0fc8aec309ede05e31
[ "Markdown", "Python", "Text" ]
8
Python
adam-j-turner/runtime-mgr-api
a10b1034ec6f731eb1eaa82bb090913b815cdf09
c3e6c4a0b2fc23dd58144bdb0e62798f2e86f825
refs/heads/master
<repo_name>debugpoint136/react-metor-kenrogers<file_sep>/README.md # react-metor-kenrogers <file_sep>/ninjatracker/client/components/App/NewNinja/NewNinja.jsx NewNinja = React.createClass({ addNinja(e) { e.preventDefault(); var firstName = $('#first_name').val(); var lastName = $('#last_name').val(); var ninja = { firstName: firstName, lastName: lastName }; Meteor.call('addNinja', ninja, function (error, result) { if (error) { return sAlert.error(error.reason, { effect: 'genie' }); } else { $('#first_name').val(); $('#first_name').val(); return sAlert.success('Ninja successfully created!', { effect: 'genie' }); } }); $('#first_name').val(''); $('#last_name').val(''); }, render() { return ( <div className="container"> <div className="row"> <div className="col-xs-8"> <h1>Add Ninja</h1> <form id="new-ninja-form" onSubmit={this.addNinja}> <div className="form-group"> <label htmlFor="first_name">First Name : </label> <input type="text" id="first_name" name="first_name" className="form-control"/> </div> <div className="form-group"> <label htmlFor="last_name">Last Name : </label> <input type="text" id="last_name" name="last_name" className="form-control"/> </div> <div className="form-group"> <button type="submit" className="btn btn-primary">Add Ninja</button> </div> </form> </div> </div> </div> ) } });
e384f4a963a308a1eacabb5ada2b77d5dbe4a7e1
[ "Markdown", "JavaScript" ]
2
Markdown
debugpoint136/react-metor-kenrogers
df32f4556abc890fc12d477fb3bd02a93e58dba4
8301b07637bf7f4953e4c212fd13fe6cb112381a
refs/heads/master
<file_sep>in this dir to be explained how to recreate labels images conf. pick the necessary files from job-process. ideally: job-input: all the stuff to prepare the input of the cf job job-output: all the stuff to recreate data set conf. from cf output job:prcess: all the stuff to normalize job-output and give stats/files about it <file_sep>''' This program is to combine the features of serveral types It works by concatenate line by line of each features file Note: feature file contains numbers of words per line that are described in the following format word [space] freq1 freq2 freq3 ... @usage: Parameter list is described as following: @param1: (N) number of files to combine @param2, 3, ... (N+1) : files @param (N+2): output @author: <NAME> (2011) ''' import sys if __name__ == "__main__": N = eval(sys.argv[1]) #open the first file and create the hash map sizefeat = 0 F1 = open (sys.argv[2], 'r') hash = {} for line in F1: line = line.strip() sep = line.find(' ', 0) word = line[0:sep] feat = line[sep:] hash[word] = feat if (sizefeat == 0): sizefeat = line.count(' ') F1.close() #combine with next files mark = {} for i in range(3,2 + N): F = open (sys.argv[i], 'r') old_sizefeat = sizefeat mark.clear() for line in F: line = line.strip() if sizefeat == old_sizefeat: sizefeat = sizefeat + line.count(' ') sep = line.find(' ', 0) word = line[0:sep] feat = line[sep:] if word in hash: hash[word] += feat mark[word] = True else: oldfeature = '' for j in range(0, old_sizefeat): oldfeature += ' 0' hash[word] = oldfeature + feat mark[word] = True for wordleft in hash.keys(): if not wordleft in mark: newfeature = '' for j in range(old_sizefeat, sizefeat): newfeature += ' 0' hash[wordleft] += newfeature F.close() #write the output FO = open(sys.argv[N+2], 'w') for word in hash.keys(): FO.write(word) FO.write(hash[word] + '\n') FO.close() <file_sep>#$ -wd /home/gtran/top_n/ #$ -j y #$ -S /bin/bash #$ -m bea #$ -l vf=8G #$ -M <EMAIL> echo "begin" matlab phow_alg_fast_color_1250.m perl tuple_to_link_word_vector.pl typedm.txt.k64.txt word_list_k64 zip word_list_k64.zip word_list_k64/* python mapping.py echo "done" <file_sep>import sys, os, random, shutil images = {} thresh_1 = {} thresh_051 = {} thresh_033 = {} thresh_0 = {} sample_1 = {} sample_051 = {} sample_033 = {} sample_0 = {} def read_report(report_path): global images report_file = open(report_path, 'r') for line in report_file: line = line.strip().split(',') if line[2] == 'true': continue image = line[8] if image in images: tags = images[image] else: tags = {} tag = line[9] confid = line[6] choice = line[5] if choice == 'Yes': tags[tag] = float(confid) elif choice == 'No': tags[tag] = 1 - float(confid) images[image] = tags def make_samples(): global thresh_1 global thresh_051 global thresh_033 global thresh_0 global sample_1 global sample_051 global sample_033 global sample_0 global images for image in images: for tag in images[image]: confid = images[image][tag] if confid == 1: thresh_1[image] = tag elif confid >= 0.51 and confid < 1: thresh_051[image] = tag elif confid >= 0.33 and confid < 0.51: thresh_033[image] = tag elif confid == 0: thresh_0[image] = tag for i in range(30): tag = random.choice(thresh_1.keys()) sample_1[tag] = thresh_1[tag] tag = random.choice(thresh_051.keys()) sample_051[tag] = thresh_051[tag] tag = random.choice(thresh_033.keys()) sample_033[tag] = thresh_033[tag] tag = random.choice(thresh_0.keys()) sample_0[tag] = thresh_0[tag] def write_to_files(images_path, output_path): os.mkdir(output_path + '/sample_1') os.mkdir(output_path + '/sample_1/images') os.mkdir(output_path + '/sample_1/tags') os.mkdir(output_path + '/sample_051-099') os.mkdir(output_path + '/sample_051-099/images') os.mkdir(output_path + '/sample_051-099/tags') os.mkdir(output_path + '/sample_033-050') os.mkdir(output_path + '/sample_033-050/images') os.mkdir(output_path + '/sample_033-050/tags') os.mkdir(output_path + '/sample_0') os.mkdir(output_path + '/sample_0/images') os.mkdir(output_path + '/sample_0/tags') for image in sample_1: image_name = os.path.basename(image) old_image_path = images_path + '/' + image_name new_image_path = output_path + '/sample_1/images/' + image_name new_tag_path = output_path + '/sample_1/tags/' + image_name[:-4] + '.txt' shutil.copy(old_image_path, new_image_path) new_tag_file = open(new_tag_path, 'w') new_tag_file.write(thresh_1[image]) new_tag_file.close() for image in sample_051: image_name = os.path.basename(image) old_image_path = images_path + '/' + image_name new_image_path = output_path + '/sample_051-099/images/' + image_name new_tag_path = output_path + '/sample_051-099/tags/' + image_name[:-4] + '.txt' shutil.copy(old_image_path, new_image_path) new_tag_file = open(new_tag_path, 'w') new_tag_file.write(thresh_051[image]) new_tag_file.close() for image in sample_033: image_name = os.path.basename(image) old_image_path = images_path + '/' + image_name new_image_path = output_path + '/sample_033-050/images/' + image_name new_tag_path = output_path + '/sample_033-050/tags/' + image_name[:-4] + '.txt' shutil.copy(old_image_path, new_image_path) new_tag_file = open(new_tag_path, 'w') new_tag_file.write(thresh_033[image]) new_tag_file.close() for image in sample_0: image_name = os.path.basename(image) old_image_path = images_path + '/' + image_name new_image_path = output_path + '/sample_0/images/' + image_name new_tag_path = output_path + '/sample_0/tags/' + image_name[:-4] + '.txt' shutil.copy(old_image_path, new_image_path) new_tag_file = open(new_tag_path, 'w') new_tag_file.write(thresh_0[image]) new_tag_file.close() if __name__ =="__main__": _report_path = sys.argv[1] _images_path = sys.argv[2] _output_path = sys.argv[3] read_report(_report_path) make_samples() write_to_files(_images_path, _output_path) <file_sep>import sys """ Given two matrices <word feat-1, ... , feat-n>, the first to be filtered retaining only those words contained in the second, it returns that filtered matrix. Usage: @param1: the matrix to be filtered @param2: the matrix to use as filter @param3: output path """ def clean_matrix(matrix_to_filter, filter_list, ou_path): filter_file = open(filter_list, 'r') filter = [] for line in filter_file: line = line.split() word = line[0] if word not in filter: filter.append(word) filter_file.close() matrix_to_filter_file = open(matrix_to_filter, 'r') hash = {} count = 0 for line in matrix_to_filter_file: line = line.strip() sep = line.find(' ', 0) word = line[0:sep] feat = line[sep:] if word in filter: count += 1 hash[word] = feat matrix_to_filter_file.close() filter.sort() ou_file = open(ou_path, 'w') for word in filter: feat = hash[word] ou_file.write(word + ' ' + feat + '\n') ou_file.close() print 'words in filter: ' + str(len(filter)) + '\n' print 'words in ou_file: ' + str(count) if __name__ =="__main__": _matrix_to_filter = sys.argv[1] _filter_list = sys.argv[2] _ou_path = sys.argv[3] clean_matrix(_matrix_to_filter, _filter_list, _ou_path) <file_sep>''' This program is to combine the features of serveral types It works by concatenate line by line of each features file Note: feature file contains numbers of words per line that are described in the following format word [space] freq1 freq2 freq3 ... NOTICE: they have the same number of lines in the same order @usage: Parameter list is described as following: @param 1, 2 input files @param 3: output @author: <NAME> (2011) ''' import sys if __name__ == "__main__": #open the first file and create the hash map sizefeat = 0 F1 = open (sys.argv[1], 'r') F2 = open (sys.argv[2], 'r') FO = open (sys.argv[3], 'w') hash = {} for line in F1: line = line.strip() sep = line.find(' ', 0) word = line[0:sep] line2 = F2.readline() line2 = line2.strip() sep2 = line2.find(' ',0) feat2 = line2[sep2:] word2 = line2[0:sep2] if word != word2: print "different lines in 2 files" exit() FO.write(line + feat2 + '\n') F1.close() F2.close() #combine with next files #write the output FO.close() <file_sep>import sys """ This program retain those words occurring threshold time in the first file (in_path) and ouputs a filtered version of the second file (me_path) using them. Usage: @param1: first file, where we count word occurrences @param2: second file with the word pairs we want to filter @param3: output path """ def filter(in_path, me_path, ou_path): in_file = open(in_path, 'r') counts = {} dic = {} for line in in_file: line = line.split() if len(line) != 0: word = line[0] imag = line[1] if word in counts: count = counts[word] count += 1 counts[word] = count else: count = 1 counts[word] = count in_file.close() me_file = open(me_path, 'r') ou_file = open(ou_path, 'w') for line in me_file: line = line.split() if len(line) != 0: word1 = line[0] word2 = line[1] lits = line[2] cos = line[3] mod = line[4] if int(counts[word2]) >= 5: ou_file.write(word1 + ' ' + word2 + ' ' + lits + ' ' + cos + ' ' + mod + '\n') me_file.close() ou_file.close() if __name__ =="__main__": _in_path = sys.argv[1] _me_path = sys.argv[2] _ou_path = sys.argv[3] filter(_in_path, _me_path, _ou_path) <file_sep>import sys, os color_counts = {} colors = ['black','blue','brown','grey','green','orange','pink','purple','red','white','yellow'] def read_csv(report_path, block_path, out_path): #debug tot_count = 0 print_count = 0 index = {} # 1st file report_file = open(report_path, 'r') first_line = True for line in report_file: if first_line: first_line = False continue line = line.strip().split(',') image = line[8] image = image[+68:] tag = line[9].rstrip() check_color(tag) tot_count += 1 if tag in index: list = index[tag] list.append(image) index[tag] = list else: list = [] list.append(image) index[tag] = list report_file.close() # 2nd file block_file = open(block_path, 'r') first_line = True for line in block_file: if first_line: first_line = False continue line = line.split(',') if line[0] != '\n': image = line[0] image = image[+68:] tag = line[1].rstrip() check_color(tag) tot_count += 1 if tag in index: list = index[tag] list.append(image) index[tag] = list else: list = [] list.append(image) index[tag] = list block_file.close() out_file = open(out_path, 'w') for tag in index: for image in index[tag]: print_count += 1 out_file.write(tag + ' ' + image + '\n') out_file.close() print 'debug: tot_count = ' + str(tot_count) + ' print_count = ' + str(print_count) for color in color_counts: print color + ': ' + str(color_counts[color]) def check_color(tag): global color_counts global colors ctag = tag if ctag == 'gray': ctag = 'grey' if ctag in colors: if ctag in color_counts: print ctag count = color_counts[ctag] count += 1 color_counts[ctag] = count else: count = 1 color_counts[ctag] = count if __name__ =="__main__": _report_path = sys.argv[1] _block_path = sys.argv[2] _out_path = sys.argv[3] read_csv(_report_path, _block_path, _out_path) <file_sep>""" This program is to found a ranked feature list from the several list of features """ import sys featureDic = {} """ Assign all of the features listed in the file to a value @param: fname: file name, each feature is in a line @param: value """ def assign(fname, value): global featureDic F = open(fname, 'r') for line in F: line = line.strip() if not featureDic.has_key(line): featureDic[line] = value F.close() if __name__ =="__main__": assign("featurelist.k4.txt", '1') assign("featurelist.k8.txt", '2') assign("featurelist.k12.txt", '3') assign("featurelist.k16.txt", '4') assign("featurelist.k20.txt", '5') assign("featurelist.k24.txt", '6') assign("featurelist.k28.txt", '7') assign("featurelist.k32.txt", '8') assign("featurelist.k36.txt", '9') assign("featurelist.k40.txt", '10') assign("featurelist.k44.txt", '11') assign("featurelist.k48.txt", '12') assign("featurelist.k52.txt", '13') #print the feature list assigned value Fout = open("52kfeatureValue.txt", 'w') for key, value in featureDic.iteritems(): Fout.write(key + ' ' + value + '\n') Fout.close() <file_sep>""" """ import sys from nltk.corpus import wordnet as wn POS = {'n':'n', 'v':'v', 'j':'a', 'r':'r'} def calc_distance(lemma1, pos1, lemma2, pos2): """ """ global POS synset1 = wn.synsets(lemma1, pos=POS[pos1]) synset2 = wn.synsets(lemma2, pos=POS[pos2]) shortest_distance = 10000 for s1 in synset1: for s2 in synset2: distance = s1.shortest_path_distance(s2) if distance < shortest_distance: shortest_distance = distance return shortest_distance if __name__ == "__main__": if len(sys.argv) < 5: print "\n Usage: python wn_dist.py [word1][pos1][word2][pos2]" sys.exit(1) _lemma1 = sys.argv[1] _pos1 = sys.argv[2] _lemma2 = sys.argv[3] _pos2 = sys.argv[4] print calc_distance(_lemma1, _pos1, _lemma2, _pos2) <file_sep> ''' This program is to normalize the feature vectors of the given matrices. Note: feature file contains numbers of words per line that are described in the following format word [space] freq1 freq2 freq3 ... @usage: Parameter list is described as following: @param1: (N) number of files to normalize @param2, 3, ... (N+1) : files @author: <NAME> (2011) ''' import sys from numpy import * from numpy.linalg import norm if __name__ == "__main__": N = eval(sys.argv[1]) # open each file, create and normalize the vectors for i in range(2, N+2): F = open(sys.argv[i], 'r') d = 0 matrix = {} for line in F: if (d == 0): d = line.count(' ') v = zeros(d, float32) line = line.strip() sep = line.find(' ', 0) word = line[0:sep] v = array(line.split()[1:], dtype=float32) matrix[word] = v/norm(v) F.close() # write the output outfile = sys.argv[i] + '-norm.txt' FO = open(outfile, "w") for word in matrix: FO.write(word + ' ') for feat in matrix[word]: FO.write(str(feat) + ' ') FO.write('\n') FO.close() <file_sep>import sys, fileinput from numpy.linalg import norm from numpy import * from operator import itemgetter from heapq import nlargest bless_words = [] bless_types = [] features = {} cosine_pairs = {} words = {} def read_bless_pairs(pairs_list): global bless_pairs pairs_file = open(pairs_list, 'r') last_word = '' for line in pairs_file: line = line.split() word = line[0] if word == last_word: adj_list = words[word] adj_list[line[3]] = line[2] bless_types.append(line[3]) words[word] = adj_list else: adj_list = {} adj_list[line[3]] = line[2] bless_types.append(line[3]) words[word] = adj_list last_word = word pairs_file.close() def read_feature_list(feature_list): global cosine_pairs global bless_words global cosine_types global features global words feature_file = open(feature_list, 'r') for line in feature_file: line = line.split() word = line[0] if word in words or word in bless_types: features[word] = array(line[1:], dtype=float32) feature_file.close() def compute_cosines(): global words global cosine_pairs for word in features: if word in words: for relata in words[word]: if word in cosine_pairs.keys() and relata in features: word_cosines = cosine_pairs[word] word_cosines[relata] = dot(features[word], features[relata]) / (norm(features[word]) * norm(features[relata])) cosine_pairs[word] = word_cosines elif relata in features: word_cosines = {} word_cosines[relata] = dot(features[word], features[relata]) / (norm(features[word]) * norm(features[relata])) cosine_pairs[word] = word_cosines def get_top(N, output_file): global bless_words global cosine_pairs OFILE = open(output_file, 'w') for word in cosine_pairs: word_cosines = cosine_pairs[word] sorted_list = sorted(word_cosines, key=word_cosines.__getitem__, reverse=True) #topn = nlargest(N, word_cosines.iteritems(), itemgetter(1)) for relata in sorted_list: OFILE.write(word + ' ' + words[word][relata] + ' ' + relata + '\n') OFILE.write('\n') OFILE.close() def get_nearest_neighbors(N, pairs_list, feature_list, output_file): read_bless_pairs(pairs_list) read_feature_list(feature_list) compute_cosines() get_top(N, output_file) if __name__=="__main__": _pairs_list = sys.argv[1] _feature_list = sys.argv[2] _output_file = sys.argv[3] get_nearest_neighbors(5, _pairs_list, _feature_list, _output_file) <file_sep>#$ -wd <labels-dir> #$-q *@compute-0-* #$ -j y #$ -S /bin/bash #$ -m bea #$ -M <account> # This script removes empty files echo "begin" find . -type f -size 0k -exec rm {} \; | awk '{ print $8 }' echo "done" <file_sep>#To compute the topic modelling of imange labels #Note that the before that we have images represented as "bag of visual" words #The program is freesoftware and can be distributed under GNU license #Authors: <NAME> (2011) #Modified: <NAME> (2011) import pycassa, os, glob, re, math import numpy as np from scipy import io import sys ''' imageFeatsPath: the folder where to find the computed image features wordFeatsPath: the folder where to store the final word features tmpDir: a folder where to put temporary files for the coputation imageBlockSize: the number of images in each block of computed image features numDescrs: the number of descriptors for each image ''' #Read the image feature given its key def readFeatures(key, filename): matfile = io.matlab.loadmat(filename) return matfile.get(key) # TODO: # 0. IMPORTANT!!!: GOT TO CHECK IF READLINE READS CORRECTLY FROM THE TMPFILE # 1. Consider to save intermediate files at each iteration to understand how much numbers matter # 2. Split in sub_functions? def assignWordFeats(imagesFeatsPath, wordsFeatsPath, imageBlockSize, numDescrs, toZeros): #def assignWordFeats(imagesFeatsPath, imageBlockSize, numDescrs): fileMap = {} fileList = [] for fname in os.listdir(imagesFeatsPath): if (str.endswith(fname, '.mat')): key, ext = fname.split('.') if (len(key)==20): fileList.append(key) print len(fileList) print "Finish reading file list" pool = pycassa.connect('Featurespace') CFImageInfos = pycassa.ColumnFamily(pool, 'imageInfos') cf_dicStrToIdx = pycassa.ColumnFamily(pool, 'dictionary_strToIdx') cf_dicIdxToStr = pycassa.ColumnFamily(pool, 'dictionary_idxToStr') iter = 0 fileList.sort() wordsFeats = {} totFeats = np.zeros((numDescrs), np.float64) print "Reading the information of images .....\n" imageFeats = 0 for key in fileList: filename = os.path.join(imagesFeatsPath, key + '.mat') print "reading file name : " + filename imagesFeats = readFeatures(key, filename) imageIdx = 0 print iter if (iter >=10): exit() imageIdxMult = iter*imageBlockSize for i in range(len(imagesFeats)): imageIdx = i + imageIdxMult try: imageRow = CFImageInfos.get(str(imageIdx)) #index of the tokens for wordIdx in imageRow: #convert wordID to the real token word = cf_dicIdxToStr.get(str(wordIdx))[str(0)] word = word[0:-1] word = word.replace('\n','') print word if not wordsFeats.has_key(word) and not math.isnan(imagesFeats[i][0]): wordsFeats[word] = imagesFeats[i] elif not wordsFeats.has_key(word) and math.isnan(imagesFeats[i][0]): print 'here' wordsFeats[word] = np.zeros((len(imagesFeats[i])), np.float64) elif not math.isnan(imagesFeats[i][0]): wordsFeats[word] = np.add(wordsFeats[word], imagesFeats[i]) #totFeats = np.add(totFeats, imagesFeats[i]) #print imagesFeats[i] totFeats = np.add(totFeats, imagesFeats[i]) #print 'totFeats[0] before:' #print totFeats[0] except Exception, e: #print 'exception in CFImageInfos.get(str(imageIdx)): ' #print ' imageIdx: ' #print imageIdx x = 1 iter += 1 #del imagesFeats N = np.sum(totFeats) exit() # TODO: change the variable names to that pertaining the formula print "Constructing words (image labels) BOW visual features.....\n" newWordsFeats = {} pcount = 0 for word in wordsFeats: #print 'totFeats[0]:' #print totFeats[0] newWordsFeats[word] = np.zeros((numDescrs), np.float64) pcount +=1 if pcount % 200 == 0: print pcount wordOcc = sum(wordsFeats[word]) if wordOcc != 0: colIdx = 0 for wordFeat in wordsFeats[word]: #print 'wordFeat:' #print wordFeat #print 'totFeats[colIdx]:' #print totFeats[colIdx] if wordFeat != 0.0 and totFeats[colIdx] != 0.0: totFeat = float(wordFeat * N) / float(totFeats[colIdx] * wordOcc) #print 'totFeat:' #print totFeat newWordFeat = float(wordFeat) * float(math.log(totFeat)) #print 'newWordFeat before:' #print newWordFeat if toZeros and newWordFeat < 0.0: newWordsFeats[word][colIdx] = 0.0 else: #print 'newWordFeat after:' #print newWordFeat newWordsFeats[word][colIdx] = newWordFeat colIdx += 1 else: newWordsFeats[word][colIdx] = 0.0 colIdx += 1 else: wordsFeats[word][:] = 0 file = open(wordsFeatsPath, 'w') newWordsFeatsKeys = newWordsFeats.keys() newWordsFeatsKeys.sort() for word in newWordsFeatsKeys: file.write(str(word) + ' ') for wordFeat in newWordsFeats[word]: file.write(str(wordFeat) + ' ') file.write('\n') file.close() #return newWordsFeats if __name__ == "__main__": imagesFeatsPath = "/Volumes/Working/Works/Bolzano/Thesis/vision/experimental/IFFN_500_v1000" wordsFeatsPath = "/Volumes/Working/Works/Bolzano/Thesis/vision/WF/wordfeat_small/oldversion-test-lboff" imageBlockSize = 100 numDescrs = 8000 toZeros = True assignWordFeats(imagesFeatsPath, wordsFeatsPath, imageBlockSize, numDescrs, toZeros) <file_sep>import glob, os, sys """ Given a list <word lemma pos freq>, this code assign the most frequent pos-tag in the given list to each word of each label in the dataset directory Usage: @param1: pos list @param2: dataset directory """ pos_dic = {} pos_freq = {} def read_pos_list(pos_list): global pos_dic global pos_freq pos_file = open(pos_list, "r") for line in pos_file: tokens = line.split() pos_dic[tokens[0]] = tokens[1] + '-' + tokens[2].lower() pos_freq[tokens[0]] = tokens[3] def map_pos(pos_list, dataset_path): global pos_dic global pos_freq pos_file = open(pos_list, "r") read_pos_list(pos_list) os.mkdir(os.path.join(dataset_path, 'pos-tagged')) for file_path in glob.glob(os.path.join(dataset_path, 'labels/*.txt')): Ifile = open(file_path, "r") file_name = os.path.basename(file_path) Ofile = open(os.path.join(dataset_path, 'pos-tagged', file_name), "w") for line in Ifile: tokens = line.split() for token in tokens: if token in pos_freq and pos_freq[token] > 100: Ofile.write(pos_dic[token]) Ofile.write('\n') Ifile.close() Ofile.close() if __name__=='__main__': _pos_list = sys.argv[1] _dataset_path = sys.argv[2] map_pos(_pos_list, _dataset_path) <file_sep> ''' This program is to normalize the feature vectors of the given matrices. Note: feature file contains numbers of words per line that are described in the following format word [space] freq1 freq2 freq3 ... @usage: Parameter list is described as following: @param1: (N) number of files to normalize @param2, 3, ... (N+1) : files @author: <NAME> (2011) ''' import sys from numpy import * from numpy.linalg import norm if __name__ == "__main__": N = eval(sys.argv[1]) # normalize the vectors for each file for i in range(2, N+2): FI = open(sys.argv[i], 'r') outfile = sys.argv[i] + '-norm.txt' FO = open(outfile, "w") for line in F: line = line.strip() sep = line.find(' ', 0) word = line[0:sep] FO.write(word + ' ') for feat in array(line.split()[1:], dtype=float32): FO.write(str(feat) + ' ') FO.write('\n') FI.close() FO.close() <file_sep>import glob, os, sys """ Given a list <word lemma pos freq>, this code assign the most frequent pos-tag in the given list to each word of each label in the dataset directory. Moreover, it ensures that color adj have '-j' tag no matter what and map 'gray' instances to 'grey' (to have only one grey word). Usage: @param1: pos list @param2: dataset directory """ pos_dic = {} pos_freq = {} colors = ['black','blue','brown','grey','green','orange','pink','purple','red','white','yellow'] color_counts = {} def read_pos_list(pos_list): global pos_dic global pos_freq pos_file = open(pos_list, "r") for line in pos_file: tokens = line.split() pos_dic[tokens[0]] = tokens[1] + '-' + tokens[2].lower() pos_freq[tokens[0]] = tokens[3] pos_file.close() def map_pos(pos_list, in_file_path, ou_file_path): global pos_dic global pos_freq global color_counts pos_file = open(pos_list, 'r') read_pos_list(pos_list) in_file = open(in_file_path, 'r') ou_file = open(ou_file_path, 'w') for line in in_file: line = line.split(' ') tag = line[0] image = line[1] #check_color(tag) if tag in pos_freq and pos_freq[tag] > 100: pos_tag = pos_dic[tag] check = pos_tag.lower() if check[:-2] == 'gray': check = 'grey-j' if check[:-2] in colors: check_color(check[:-2]) pos_tag = check[:-2] + '-j' ou_file.write(pos_tag + ' ' + image + '\n') in_file.close() ou_file.close() for color in color_counts: print color + ' ' + str(color_counts[color]) def check_color(tag): global color_counts global colors ctag = tag if ctag in colors: if ctag in color_counts: count = color_counts[ctag] count += 1 color_counts[ctag] = count else: count = 1 color_counts[ctag] = count if __name__=='__main__': _pos_list = sys.argv[1] _in_file_path = sys.argv[2] _ou_file_path = sys.argv[3] map_pos(_pos_list, _in_file_path, _ou_file_path) <file_sep>""" THe program is to construct visual features from VLFEAT output SIFT It uses temple file to store information to avoid overloading memory Usage: @param1: image feature director @param2: word_feature target file @param3: directory of unique labels @param4: size (number of elemements) of the dictionary storing word - features """ #To compute the topic modelling of imange labels #Note that the before that we have images represented as "bag of visual" words import glob, math, os, re, sys import numpy as np import gc from scipy import io label_files = '' num_descrs = -1 labels_dir = '' words_in_dic = 0 MEMORY_LIMIT = 0 words_features_target_file = '' DEBUG = False #Initialization def to_str(value): if (value >0): return "%.10f" %value else: return "%.0f" %value #Store dictionary of words' features to temple file in the target dictionary def store_to_file(words_features): #open the current temple file and write to new file, then rename the file global words_features_target_file TMP_OUT = open ( words_features_target_file + '_wftmpout.txt','w') mark = {} if os.path.exists(words_features_target_file + '_wftmpin.txt'): TMP_IN = open (words_features_target_file+ '_wftmpin.txt','r') update_line = '' for line in TMP_IN: values = line.split() word = values.pop(0) update_line = '' if words_features.has_key(word): if (len(values) != len(words_features[word])): print str(len(values)) + " " + str(len(words_features[word])) print word exit() update_line = word + ' ' for i in range(0,len(words_features[word])): update_line += to_str(words_features[word][i] + float(values[i])) + ' ' TMP_OUT.write(update_line + '\n') mark[word] = True else: TMP_OUT.write(line + '\n') TMP_IN.close() os.remove(words_features_target_file + '_wftmpin.txt') for word in words_features.keys(): if not mark.has_key(word): update_line = word + ' ' for i in range(0, len(words_features[word])): update_line += to_str(words_features[word][i]) + ' ' TMP_OUT.write(update_line + '\n') TMP_OUT.close() #Delete the old temple file and rename the new temple file to wftmpin.txt os.rename(words_features_target_file + '_wftmpout.txt', words_features_target_file + '_wftmpin.txt') def get_label_info(index): global labels_dir file_name = os.path.join(labels_dir, label_files[index]) tmp = [] F = open (file_name, 'r') for token in F: token = token.replace('\n', '') tmp.append(token) F.close() return tmp #Read the image feature given its key def get_image_features(key, filename): matfile = io.matlab.loadmat(filename) return matfile.get(key) def get_words_features(images_features_path, words_features_target_file): global num_descrs global MEMORY_LIMIT file_map = {} file_list = [] for fname in os.listdir(images_features_path): if (str.endswith(fname, '.mat')): key, ext = fname.split('.') if (len(key) == 30): file_list.append(key) print len(file_list) print "Finish reading file list....." iter = 0 file_list.sort() words_features = {} if num_descrs == -1: filename = os.path.join(images_features_path, file_list[0] + '.mat') images_features = get_image_features(file_list[0], filename) num_descrs = len(images_features[0]) images_block_size = len(images_features) totFeats = np.zeros((num_descrs), np.float32) print "Reading the information of images .....\n" words_in_dic = 0 count_null_image = 0 for key in file_list: filename = os.path.join(images_features_path, key + '.mat') print "reading file name : " + filename images_features = get_image_features(key, filename) image_idx = 0 image_idx_mult = iter*images_block_size for i in range(len(images_features)): image_idx = i + image_idx_mult image_row = get_label_info(image_idx); # for word in image_row: if (len(word.split())>1): print "Exists a tag having 2 tokens!!!! - " + word #exit() #word = word.replace(' ','') if not words_features.has_key(word) and not math.isnan(images_features[i][0]): words_features[word] = images_features[i] totFeats = np.add(totFeats, images_features[i]) words_in_dic +=1 elif not words_features.has_key(word) and math.isnan(images_features[i][0]): count_null_image +=1 elif not math.isnan(images_features[i][0]): words_features[word] = np.add(words_features[word], images_features[i]) totFeats = np.add(totFeats, images_features[i]) #endfor """ If the dictionary consume a lot of RAM, we store it to the file Then restore the original state """ if words_in_dic >= MEMORY_LIMIT: store_to_file(words_features) words_in_dic = 0 words_features = {} gc.collect() iter +=1 #endfor #Now print the rest of dictionary words_features to the file store_to_file(words_features) words_features = {} gc.collect() print "Finished reading images infor. - there's total " + str(count_null_image) + " images having NULL feature" N = np.sum(totFeats) print "Constructing words (image labels) BOW visual features.....\n" RAW_WF = open (words_features_target_file + '_wftmpin.txt','r') OFILE = open(words_features_target_file, 'w') progress_count = 0 for line in RAW_WF: values = line.split() word = values.pop(0) update_line = word + ' ' if DEBUG == True: if len(values) != num_descrs: print "DEBUG MODE: different number of features in the raw file" raw_word_features = np.zeros((num_descrs), np.float32) for i in range(0, num_descrs): raw_word_features[i] = float(values[i]) progress_count +=1 if (DEBUG == True) and (progress_count % 500 == 0): print "DEBUG MODE: " + str(progress_count) + " words indexed...." wordOcc = sum(raw_word_features) colIdx = 0 for word_feature in raw_word_features: if wordOcc != 0 and word_feature != 0.0 and totFeats[colIdx] != 0.0: totFeat = float(word_feature * N) / float(totFeats[colIdx] * wordOcc) lmi_score = float(word_feature) * float(math.log(totFeat)) if lmi_score < 0: lmi_score = 0.0 else: lmi_score = 0.0 colIdx +=1 update_line += to_str(lmi_score) + ' ' OFILE.write(update_line + '\n') OFILE.close() RAW_WF.close() os.remove(words_features_target_file + '_wftmpin.txt') def read_label_file(labels_dir): temp = [] for fname in os.listdir(labels_dir): if (len(fname) == 36): temp.append(fname) temp.sort() return temp if __name__ == "__main__": global labels_dir global MEMORY_LIMIT global DEBUG global images_features_path global words_features_target_file global label_files gc.enable() DEBUG = True images_features_path = sys.argv[1] words_features_target_file = sys.argv[2] labels_dir = sys.argv[3] MEMORY_LIMIT = int(sys.argv[4]) label_files = read_label_file(labels_dir) print "Number of label files is " + str(len(label_files)); htags = {} for i in range(0,len(label_files)): tokens = get_label_info(i) for tag in tokens: htags[tag] = True print "Number of tags in labels: " + str(len(htags.keys())) exit() #get_words_features(images_features_path, words_features_target_file) <file_sep>import sys, os """ Given the crowdflower final report, this program returns a inverted index <tag,image> as ouput. Usage: @param1: the final CF report (csv format) @param2: the output directory """ color_counts = {} colors = ['black','blue','brown','grey','green','orange','pink','purple','red','white','yellow'] def read_csv(in_path, ou_path): #debug tot_count = 0 index = {} # 1st file report_file = open(in_path, 'r') first_line = True for line in report_file: if first_line: first_line = False continue line = line.strip().split(',') bool = line[5] conf = float(line[6]) if (bool == 'Yes' and conf >= 1) or (bool == 'No' and conf <= 0) : image = line[8] image = image[+68:] tag = line[9].rstrip() if tag == 'gray' or tag == 'Gray': tag = 'grey' check_color(tag) tot_count += 1 if tag in index: list = index[tag] list.append(image) index[tag] = list else: list = [] list.append(image) index[tag] = list report_file.close() ou_file = open(ou_path, 'w') for tag in index: for image in index[tag]: ou_file.write(tag + ' ' + image + '\n') ou_file.close() for color in color_counts: print color + ': ' + str(color_counts[color]) def check_color(tag): global color_counts global colors ctag = tag if ctag in colors: if ctag in color_counts: count = color_counts[ctag] count += 1 color_counts[ctag] = count else: count = 1 color_counts[ctag] = count if __name__ =="__main__": _in_path = sys.argv[1] _ou_path = sys.argv[2] read_csv(_in_path, _ou_path) <file_sep># Pipeline ## Phase 1 - Initial distinct word list **Input**: distinct word list from text corpus and word list from cleared Flickr dataset **Output**: intersection of two word lists (F) ## Phase 2 - Create word pairs **Input**: word list F **Output**: Cartesian product F x F ## Phase 3 - Filter out word pairs **Input**: Set of word pairs (F x F) **Output**: Filter out the pair that the frequencies of words are less than a threshold (5, 10??) ## Phase 4 - Get final word pairs **Input**: Thres\_word pairs and probably the distribution that we want to test **Output**: Using WordNet (e.g implemented in NLTK) to get the final set ## Phase 5 - Create gold standard **Input**: Final set of word pairs **Output**: Gold standard (e.g for WordSim) <file_sep>#$ -wd /home/elia.bruni/code/sh-filess #$-l vf=8G #$ -j y #$ -S /bin/bash #$ -m bea echo "begin" python2.6 /home/elia.bruni/src/s2m/vsm/cosine_similarity.py /home/elia.bruni/test-set/repo/cleaned-wordsim_similarity_goldstandard.txt /mnt/8tera/test-marco/image-and-text/elia/esp/features/new-feat/canny.txt /mnt/8tera/test-marco/image-and-text/elia/esp/dataset/esp_50k/ESP-ImageSet/eval/only-vision/wordsim/sim.txt echo "done" <file_sep>import glob, os, shutil, sys """ This code create a directory with the images associated with the given labels. Usage: @param1: dataset directory where you have the labels and you want also the images @param2: path to all the images form which to pick the desired ones """ def extract_images(dataset_path, all_images_path): images_path = os.path.join(dataset_path, 'images') os.mkdir(images_path) for label_path in glob.glob(os.path.join(dataset_path, 'labels/*.txt')): label_name = os.path.basename(label_path) image_name = 'im' + label_name[+4:-3] + 'jpg' image_path = os.path.join(images_path, image_name) shutil.copy(os.path.join(all_images_path, image_name), image_path) if __name__ =="__main__": _dataset_path = sys.argv[1] _all_images_path = sys.argv[2] extract_images(_dataset_path, _all_images_path) <file_sep>import sys, os, glob from numpy import * from numpy.linalg import norm """ This program computes and write into the given output directory cosine similarities for all the word pairs of the given input file, with the feature matrices inside the given directory. This version is for literal/ non-literal analysis, therefore also a 'L' for literal and a 'N' for non-literal inside the input file is expected (adj noun L/N). Usage: @param1: feature matrices directory @param2: file with the word pairs and L/N @param3: output file path """ def compute_cosines(matrices_dir, in_path, ou_path): in_file = open(in_path, 'r') word_list = [] pair_dic = {} vote_dic = {} for line in in_file: line = line.split() A = line[0] N = line[1] V = line[2] AN = A+N word_list.append(A) word_list.append(N) if A in pair_dic: in_list = pair_dic[A] in_list.append(N) pair_dic[A] = in_list else: in_list = [] in_list.append(N) pair_dic[A] = in_list vote_dic[AN] = V in_file.close() ou_file = open(ou_path, 'w') for matrix_path in glob.glob(matrices_dir + '/*'): matrix = {} F = open(matrix_path, 'r') matrix_name = os.path.basename(matrix_path) print matrix_name for f_line in F: #print len(f_line) #print f_line word = f_line.split()[0] if word in word_list: v = array(f_line.split()[1:], dtype=float32) matrix[word] = v F.close() for A in pair_dic: #print A v = matrix[A] for N in pair_dic[A]: w = matrix[N] cos = dot(v,w) / (norm(v) * norm(w)) ou_file.write(A + ' ' + N + ' ' + vote_dic[A+N] + ' ' + str(cos) + ' ' + matrix_name + '\n') ou_file.close() if __name__ =="__main__": _matrices_dir = sys.argv[1] _in_path = sys.argv[2] _ou_path = sys.argv[3] compute_cosines(_matrices_dir, _in_path, _ou_path) <file_sep>this is a howto for the EACL paper: 0. code to combine the 2 CF jobs 1. inverted_index_from_file.py (to be readapted to work only with a final result): --> outputs an inverted index file <word image> (needed by marco) 2. pos_map_from_file.py --> add pos to words in the inverted_index. 3. create_labels_from_inverted_index.py --> from the inverted index, all the labels are created 4. common_with_cleaned_labels.py --> from the labels and original images, creates an image directory with only those images for whci a label is provided 3+4. TODO: merge file in 3. and file in 4, to have images and labels dir form inv. index at once 5. words_with_images.py --> ceates 'preprocessed' dir with uuid names 6. features extraction 7. generate_VM.sh --> merge the mat matrices and creates the visual-feature file for each feature extracted 8. normalize_vectors.py --> normalize the feature vectors [v/norm(v)], necessary for concatenation 9. combine_feature.py --> combine the given feature matrices 10. filter_from_list.py (here the first ~700 words as input) --> each resulting matrix has to be filtered, retaining only words for eacl tests 11. filter_from_list.py (here the litnonlit file) 12. compute_cosines.py --> compute the cosines for the given list of words, with all the given matrices 13. filter_thresh.py --> from the ouput in 12, retains just words occurring threshold time in the visual data set 3.0.3 compute_wordsim.sh <file_sep>import glob, os, shutil, sys, random """ This code assigns randomly generated uuid to image-label pairs. The dataset directory must contain one folder called 'original-data', with two subfolders 'images' and 'labels'. Images are in '.jpg' format, labels in '.txt' format. Usage: @param1: dataset directory """ def filter_dataset(dataset_path): preprocessed_path = os.path.join(dataset_path, 'preprocessed') os.mkdir(preprocessed_path) os.mkdir(os.path.join(preprocessed_path, 'labels')) os.mkdir(os.path.join(preprocessed_path, 'images')) words_with_images = {} for file_path in glob.glob(os.path.join(dataset_path, 'original-data/20k-labels/*.txt')): print file_path file = open(file_path, "r") file_name = os.path.basename(file_path) image_name = 'im' + file_name[+4:-4] + '.jpg' image_path = os.path.join(dataset_path, 'original-data/20k-images/', image_name) new_file_name = get_random_string(32); label = new_file_name + '.txt' image = new_file_name + '.jpg' shutil.copy(str(file_path), os.path.join(preprocessed_path,'labels', label)) shutil.copy(str(image_path), os.path.join(preprocessed_path,'images', image)) file.close() def get_random_string(word_len): word = '' for i in range(word_len): word += random.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') return word if __name__ =="__main__": dataset_path = sys.argv[1] filter_dataset(dataset_path) <file_sep>Steps to prepare a crowdflower job (to be translated into a wiki page): 1. Extract randomly n labels from the original label/image data set (e.g. MIR Flickr) ==> add random.sh code to this directory 2. Filter out empty labels ==> remove_empty_labels.sh 3. From the original data set copy all the images correspondent to the survived labels into 'labels' dir ==> find_images.py 4. Create csv file to upload on crowflower website ==> create_csv.py 5. Create some gold standard on the crowdflower website <file_sep>TODO: change names of the output files (not more genetic!!!) <file_sep>''' This program is to compute the effectiveness of text models on semantics similarity measurement Text features are split into pieces of ordered 4k-block-features We compute the measurment by using the top 8k, 12k, 16k....64k features Usage: @param 1: l @param 2: alpha (normally take 0.5) for combination of text and image vectors @param 3: number of block 4k of text features, for example: param3 = 8 means we use 32K text feature to test @param 4: visual features matrix python this_file l alpha number_of_block visual_featurefile where: k is number of 4k-blocks for testing see the __main__ function to indicate the directory where the feature_list, visual_feature ----- ''' import sys import os import numpy as np from numpy import dot from numpy.linalg import norm from numpy.ctypeslib import _num_fromflags """ """ DEBUG = 0 featureDic = {} allfeat = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[], [], [], []] #This function is to read the features of a word into some blocks of features #Each block of feature contains features that have same value def readWord(word): global featureDic top = [{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}] vector = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]] Wfile = open(os.path.join(textFeatDirectory, word), "r") for line in Wfile: feature, score = line.split() blocknum = featureDic[feature] top[blocknum][feature] = float(score) Wfile.close() #Vector found for i in range(0,len(allfeat)): for j in range(0, len(allfeat[i])): if allfeat[i][j] in top[i]: vector[i].append(top[i][allfeat[i][j]]) else: vector[i].append(float(0)) return vector #This program is to read the list of features and their asscociate assigned block def readFeatureList(featurelist): global featureDic global allfeat featureDic = {} Ffeat = open(featurelist, 'r') for line in Ffeat: feature, blocknum = line.split() featureDic[feature] = int(blocknum) -1 allfeat[int(blocknum)-1 ].append(feature) Ffeat.close() printvector(allfeat) def printvector(v): print "number of block " + str(len(v)) print "size: " + str(len(v[0])) + ":" + str(len(v[1])) + ":" + str(len(v[2])) + ":" +str(len(v[3])) + ":" + str(len(v[4])) # TODO: # 0. Split the big function into subfunctions # 1. Consider to insert a choice between output into file or db def cossim(pairList, visualFeatsFile, outputFile): PLFile = open(pairList, "r") PLLine = PLFile.readline() pairsDic = {} words = [] wordsIdxs = [] iter = 0 notFound = 0 while PLLine: pair = PLLine.split() word0 = pair[0] word1 = pair[1] if not word0 in words: words.append(word0) if not word1 in words: words.append(word1) if not pairsDic.has_key(word0): partners = [] partners.append(word1) pairsDic[word0] = partners elif not word1 in pairsDic[word0]: pairsDic[word0].append(word1) PLLine = PLFile.readline() imagesFeats = {} WFFile = open(visualFeatsFile, "r") WFLine = WFFile.readline() while WFLine: values = WFLine.split() # TODO: this correction for mix, got to find a general way word = values.pop(0) numDescrs = len(values) if word in words: #print word wordFeats = np.zeros((numDescrs), np.float64) featIdx = 0 for feat in values: feat = float(feat) wordFeats[featIdx] = feat featIdx += 1 imagesFeats[word] = wordFeats WFLine = WFFile.readline() # Here i populate the list of all the words-feats files wordsFiles = os.listdir(textFeatDirectory) #Open the output file OFile = open(outputFile, 'w') for word0 in pairsDic: if not word0 in wordsFiles or not word0 in imagesFeats: continue vv0 = readWord(word0) v0 = [] for i in range(0, len(vv0)): v0.append(np.array(vv0[i])) image_v0 = imagesFeats[word0] if (norm(image_v0) !=0): image_v0 = image_v0/norm(image_v0) else: continue #If need to weight the text, using this #for blocknum in range(0, len(v0)): # if norm(v0[blocknum]) !=0: # v0[blocknum] = v0[blocknum]/norm(v0[blocknum]) for word1 in pairsDic[word0]: if not word1 in wordsFiles or not word1 in imagesFeats: continue vv1 = readWord(word1) v1 = [] for i in range(0, len(vv1)): v1.append(np.array(vv1[i])) image_v1 = imagesFeats[word1] if (norm(image_v1) !=0): image_v1 = image_v1/norm(image_v1) else: continue #If need to weight the text, using this #for blocknum in range(0, len(v0)): # if norm(v1[blocknum]) >0: # v1[blocknum] = v1[blocknum]/norm(v1[blocknum]) #concatenation #Concat image features and text features #liner method with parameter alpha pairCosine = 0 if (sys.argv[1] == "l"): #Linear combination #Alpha is not important here because we dont concat text with vision alpha = eval(sys.argv[2]) text_v0 = v0[0] text_v1 = v1[0] blocknum = eval(sys.argv[3]) #Number of 4k text blocks if blocknum > len(v0): print "Number of tested blocks is out of index" sys.exit() for bl in range(1,blocknum): text_v0 = np.concatenate((text_v0, v0[bl])) text_v1 = np.concatenate((text_v1, v1[bl])) if (norm(text_v0) >0): text_v0 = text_v0/norm(text_v0) if (norm(text_v1) >0): text_v1 = text_v1/norm(text_v1) concat0 = np.concatenate((alpha * text_v0, (1-alpha) * image_v0)) concat1 = np.concatenate((alpha * text_v1, (1-alpha) * image_v1)) #print norm(image_v0) * norm(image_v1) if (norm(concat0) >0): concat0 = concat0/norm(concat0) if (norm(concat1) >0): concat1 = concat1/norm(concat1) pairCosine = float(dot(concat0,concat1)) #pairCosine = float(dot(text_v0,text_v1)) OFile.write(word0 + ' ' + word1 + ' ' + str(pairCosine)) OFile.write('\n') OFile.close() if __name__=="__main__": global textFeatDirectory print "Reading the feature list" readFeatureList("./featureValue_64k.txt") textFeatDirectory = "./top_n/word_list_k64" global DEBUG if DEBUG == 1: v = readWord("zoo-n") x = [] x.append(np.array(v[0])) x.append(np.array(v[1])) print type(x[1]) printvector(v) sys.exit() _pairList = "./cleaned-wordsim-all.txt" _visualFile = sys.argv[4] _visualFeatFile = "./esp/new-esp-data/vision-matrix/" + _visualFile _outFile = "./WS.vision.only." + sys.argv[3] + "." + _visualFile cossim(_pairList, _visualFeatFile, _outFile) <file_sep>import sys, glob, os, shutil """ This program simply copy to the given output directory only the tags and images within the CF cleaned data Usage: @param1: images directory @param2: labels directory @param3: output directory """ def create_common_data(cleaned_tags_path, not_cleaned_path, ou_path): for label_path in glob.glob(os.path.join(cleaned_tags_path) + '/*'): label_name = os.path.basename(label_path) image_name = 'im' + label_name[+4:-4] + '.jpg' #label_path = not_cleaned_path + '/' + 'labels/' + label_name image_path = not_cleaned_path + '/' + 'images/' + image_name #shutil.copy(label_path, ou_path + '/labels/' + label_name) shutil.copy(image_path, ou_path + '/images/' + image_name) if __name__ =="__main__": _cleaned_tags_path = sys.argv[1] _not_cleaned_path = sys.argv[2] _ou_path = sys.argv[3] create_common_data(_cleaned_tags_path, _not_cleaned_path, _ou_path) <file_sep>import sys """ This program creates a directory containing all the constructed from the given inverted index with lines of the form <tag image>. Usage: @param1: path to the inverted index file @param2: output directory for the labels """ def create_labels_from_inverted_index(inverted_index_path, out_path): index_file = open(inverted_index_path, 'r') index = {} for line in index_file: line = line.split(' ') if line[0] != '\n': tag = line[0] ima = line[1] lab = 'tags' + ima[+2:-5] + '.txt' if lab in index: tags = index[lab] tags.append(tag) index[lab] = tags else: tags = [] tags.append(tag) index[lab] = tags for lab in index: lab_file = open(out_path + '/' + lab, 'w') for tag in index[lab]: lab_file.write(tag + '\n') lab_file.close() index_file.close() if __name__ =="__main__": _inverted_index_path = sys.argv[1] _out_path = sys.argv[2] create_labels_from_inverted_index(_inverted_index_path, _out_path) <file_sep>#$ -wd /home/binhgiang.tran/ #$-l vf=8G #$ -j y #$ -S /bin/bash #$ -m bea #$ -M <EMAIL> echo "begin" python2.6 LBOFF/LBOFF_no_swap.py /mnt/8tera/test-marco/image-and-text/elia/esp/dataset/esp_50k/ESP-ImageSet/vision/features/canny esp/old-esp-data/new-feat/canny.txt esp/old-esp-data/uuid_labels/ 15000 #python2.6 LBOFF_noDB_temple_file.py esp/new-esp-data/feature-100k/v1000_2000k_block1000 visualfeatures/matrix_k2000.txt esp/new-esp-data/labels/uuid_labels 15000 echo "done" <file_sep>import sys, glob, os, re """ This program creates a csv file where each row contains an image and one of its associated tag <"image_path, tag">. An image has to be in 'jpg' format, a label in 'txt' format. Usage: @param1: dataset directory @param2: url base where images and labels have to be located @param3: output directory """ def write_csv(dataset_path, url_path, out_path): info = {} for file_path in glob.glob(os.path.join(dataset_path, 'labels/*')): file = open(file_path, 'r') file_name = os.path.basename(file_path) image_name = file_name[:-4] + ".jpg" if image_name in info: label = info[image_name] else: label = [] for tag in file: # retain a word iff has only alphabetical characters if re.match("^[A-Za-z]*$", tag): label.append(tag) info[image_name] = label data = [] for image in info: for tag in info[image]: image_file_name = url_path + 'images/' + image data.append((str(image_file_name), str(tag))) csv_file = open(out_path, 'w') csv_file.write("Image,Tag" + '\n') for pair in data: csv_file.write(pair[0] + ',' + pair[1] + '\n') csv_file.close() if __name__ =="__main__": _dataset_path = sys.argv[1] _url_path = sys.argv[2] _out_path = sys.argv[3] write_csv(_dataset_path, _url_path, _out_path) <file_sep>#$ -wd /home/binhgiang.tran/top_n/ #$ -j y #$ -S /bin/bash #$ -m bea #$ -M <EMAIL> echo "begin" #perl tuple_to_link_word_vector.pl typedm.txt.k64.txt word_list_k64/ zip word_list_k64.zip word_list_k64/* echo "done" <file_sep>""" """ import sys import re import wn_dist from operator import itemgetter def read_text_file(text_path): """ """ out_res = list() with open(text_path, 'r') as fin: for line in fin.read().split("\n"): if len(line) > 0: out_res.append(line) return out_res def read_image_file(image_path): """ """ out_res = dict() with open(image_path, 'r') as fin: for line in fin.read().split("\n"): if len(line) == 0: continue tmp = re.split("\s+", line) if out_res.has_key(tmp[0]): out_res[tmp[0]].append(tmp[1]) else: out_res[tmp[0]] = [tmp[1]] return out_res def init_word_pair(txt_word, img_word, threshold): """ """ word_list = list() word_pair = set() for word in txt_word: if img_word.has_key(word) and len(img_word[word]) > threshold: word_list.append(word) for w1 in word_list: for w2 in word_list: if w1 != w2 and (w2,w1) not in word_pair: word_pair.add((w1,w2)) return word_pair def calc_wordnet_path(word1, word2): """ """ lemma1 = word1[:word1.rfind('-')] pos1 = word1[word1.rfind('-')+1:] lemma2 = word2[:word2.rfind('-')] pos2 = word2[word2.rfind('-')+1:] return wn_dist.calc_distance(lemma1, pos1, lemma2, pos2) def filter_word_pair(word_pair): """ """ print len(word_pair) score = dict() for wp in word_pair: pair_score = calc_wordnet_path(wp[0], wp[1]) score[wp] = pair_score sorted_wp = sorted(score.iteritems(), key=itemgetter(1), reverse=False) print sorted_wp return word_pair def create_word_pairs(text_path, image_path, out_path, threshold): """ """ txt_word = read_text_file(text_path) img_word = read_image_file(image_path) initial_word_pair = init_word_pair(txt_word, img_word, threshold) filtered_word_pair = filter_word_pair(initial_word_pair) with open(out_path, 'w') as fout: for (w1,w2) in filtered_word_pair: fout.write("%s %s\n" % (w1, w2)) if __name__ == "__main__": if len(sys.argv) < 5: print "\n Usage: python [text_word_file] [image_word_file] [out_file] \ threshold" sys.exit(1) _text_path = sys.argv[1] _image_path = sys.argv[2] _out_path = sys.argv[3] _threshold = int(sys.argv[4]) create_word_pairs(_text_path, _image_path, _out_path, _threshold)
a6c9d8be4fa2505c6b2bd6bb91ab5b62bd022294
[ "Markdown", "Python", "Text", "Shell" ]
34
Text
namkhanhtran/mss
ff33b92f362c5fe23e232837bf74aa827dac3c17
e6c603010f95610c160412149001453c5ff180fd
refs/heads/master
<file_sep>๏ปฟusing System; #if __ANDROID__ using Android.App; #endif namespace Acr.UserDialogs { public static class UserDialogs { #if __ANDROID__ public static void Init(Func<Activity> getActivity) { if (Instance == null) Instance = new UserDialogsImpl(getActivity); } public static void Init(Activity activity) { if (Instance != null) return; var app = Application.Context.ApplicationContext as Application; if (app == null) throw new Exception("Application Context is not an application"); ActivityMonitor.CurrentTopActivity = activity; app.RegisterActivityLifecycleCallbacks(new ActivityMonitor()); Instance = new UserDialogsImpl(() => ActivityMonitor.CurrentTopActivity); } #else public static void Init() { #if __PLATFORM__ if (Instance == null) Instance = new UserDialogsImpl(); #endif } #endif public static IUserDialogs Instance { get; set; } } } <file_sep>using System; using UIKit; namespace Acr.UserDialogs { public class NetworkIndicator : IProgressIndicator { public string Title { get; set; } public int PercentComplete { get; set; } public bool IsDeterministic { get; set; } public bool IsShowing { get { return UIApplication.SharedApplication.NetworkActivityIndicatorVisible; } } public void Show() { UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true; } public void Hide() { UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; } public void Dispose() { this.Hide(); } } }<file_sep>๏ปฟusing System; namespace Acr.UserDialogs { public interface IProgressDialog : IProgressIndicator { string Title { get; set; } bool IsDeterministic { get; set; } void SetCancel(Action onCancel, string cancelText = "Cancel"); } } <file_sep>using System; using System.Linq; using Windows.UI.Xaml.Controls; using WinRTXamlToolkit.Controls; namespace Acr.UserDialogs { public class UserDialogsImpl : AbstractUserDialogs { public override async void Alert(AlertConfig config) { var input = new InputDialog(); await input.ShowAsync(config.Title, config.Message, config.OkText); if (config.OnOk != null) config.OnOk(); } public override async void ActionSheet(ActionSheetConfig config) { var input = new InputDialog { ButtonsPanelOrientation = Orientation.Vertical }; var buttons = config .Options .Select(x => x.Text) .ToArray(); var choice = await input.ShowAsync(config.Title, null, buttons); var opt = config.Options.SingleOrDefault(x => x.Text == choice); if (opt != null && opt.Action != null) opt.Action(); } public override async void Confirm(ConfirmConfig config) { var input = new InputDialog { AcceptButton = config.OkText, CancelButton = config.CancelText }; var choice = await input.ShowAsync(config.Title, config.Message); config.OnConfirm(config.OkText == choice); } public override void Login(LoginConfig config) { throw new NotImplementedException(); } public override async void Prompt(PromptConfig config) { var input = new InputDialog { AcceptButton = config.OkText, CancelButton = config.CancelText, InputText = config.Placeholder }; var result = await input.ShowAsync(config.Title, config.Message); // input // .ShowAsync(title, message) // .ContinueWith(x => { // // TODO: how to get button click for this scenario? // }); } public override void Toast(string message, int timeoutSeconds = 3, Action onClick = null) { // //http://msdn.microsoft.com/en-us/library/windows/apps/hh465391.aspx // // TODO: Windows.UI.Notifications. // //var toast = new ToastPrompt { // // Message = message, // // MillisecondsUntilHidden = timeoutSeconds * 1000 // //}; // //if (onClick != null) { // // toast.Tap += (sender, args) => onClick(); // //} // //toast.Show(); } protected override IProgressDialog CreateDialogInstance() { throw new NotImplementedException(); } protected override IProgressIndicator CreateNetworkIndicator() { return new NetworkIndicator(); } } } <file_sep>using System; using System.Linq; using BigTed; using CoreGraphics; using UIKit; namespace Acr.UserDialogs { public class UserDialogsImpl : AbstractUserDialogs { public override void Alert(AlertConfig config) { UIApplication.SharedApplication.InvokeOnMainThread(() => { if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0)) { var alert = UIAlertController.Create(config.Title ?? String.Empty, config.Message, UIAlertControllerStyle.Alert); alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, x => { if (config.OnOk != null) config.OnOk(); })); this.Present(alert); } else { var dlg = new UIAlertView(config.Title ?? String.Empty, config.Message, null, null, config.OkText); if (config.OnOk != null) dlg.Clicked += (s, e) => config.OnOk(); dlg.Show(); } }); } public override void ActionSheet(ActionSheetConfig config) { if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0)) { var sheet = UIAlertController.Create(config.Title ?? String.Empty, String.Empty, UIAlertControllerStyle.ActionSheet); config.Options.ToList().ForEach(x => sheet.AddAction(UIAlertAction.Create(x.Text, UIAlertActionStyle.Default, y => { if (x.Action != null) x.Action(); })) ); this.Present(sheet); } else { var view = Utils.GetTopView(); var action = new UIActionSheet(config.Title); config.Options.ToList().ForEach(x => action.AddButton(x.Text)); action.Dismissed += (sender, btn) => { if ((int)btn.ButtonIndex > -1 && (int)btn.ButtonIndex < config.Options.Count) config.Options[(int)btn.ButtonIndex].Action(); }; action.ShowInView(view); } } public override void Confirm(ConfirmConfig config) { UIApplication.SharedApplication.InvokeOnMainThread(() => { if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0)) { var dlg = UIAlertController.Create(config.Title ?? String.Empty, config.Message, UIAlertControllerStyle.Alert); dlg.AddAction(UIAlertAction.Create(config.OkText, UIAlertActionStyle.Default, x => config.OnConfirm(true))); dlg.AddAction(UIAlertAction.Create(config.CancelText, UIAlertActionStyle.Default, x => config.OnConfirm(false))); this.Present(dlg); } else { var dlg = new UIAlertView(config.Title ?? String.Empty, config.Message, null, config.CancelText, config.OkText); dlg.Clicked += (s, e) => { var ok = ((int)dlg.CancelButtonIndex != (int)e.ButtonIndex); config.OnConfirm(ok); }; dlg.Show(); } }); } public override void Login(LoginConfig config) { UITextField txtUser = null; UITextField txtPass = null; UIApplication.SharedApplication.InvokeOnMainThread(() => { if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0)) { var dlg = UIAlertController.Create(config.Title ?? String.Empty, config.Message, UIAlertControllerStyle.Alert); dlg.AddAction(UIAlertAction.Create(config.OkText, UIAlertActionStyle.Default, x => config.OnResult(new LoginResult(txtUser.Text, txtPass.Text, true)))); dlg.AddAction(UIAlertAction.Create(config.CancelText, UIAlertActionStyle.Default, x => config.OnResult(new LoginResult(txtUser.Text, txtPass.Text, true)))); dlg.AddTextField(x => { txtUser = x; x.Placeholder = config.LoginPlaceholder; x.Text = config.LoginValue ?? String.Empty; }); dlg.AddTextField(x => { txtPass = x; x.Placeholder = config.PasswordPlaceholder; x.SecureTextEntry = true; }); this.Present(dlg); } else { var dlg = new UIAlertView { AlertViewStyle = UIAlertViewStyle.LoginAndPasswordInput }; txtUser = dlg.GetTextField(0); txtPass = dlg.GetTextField(1); txtUser.Placeholder = config.LoginPlaceholder; txtUser.Text = config.LoginValue ?? String.Empty; txtPass.Placeholder = config.PasswordPlaceholder; dlg.Clicked += (s, e) => { var ok = ((int)dlg.CancelButtonIndex != (int)e.ButtonIndex); config.OnResult(new LoginResult(txtUser.Text, txtPass.Text, ok)); }; dlg.Show(); } }); } public override void Prompt(PromptConfig config) { UIApplication.SharedApplication.InvokeOnMainThread(() => { var result = new PromptResult(); if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0)) { var dlg = UIAlertController.Create(config.Title ?? String.Empty, config.Message, UIAlertControllerStyle.Alert); UITextField txt = null; dlg.AddAction(UIAlertAction.Create(config.OkText, UIAlertActionStyle.Default, x => { result.Ok = true; result.Text = txt.Text.Trim(); config.OnResult(result); })); dlg.AddAction(UIAlertAction.Create(config.CancelText, UIAlertActionStyle.Default, x => { result.Ok = false; result.Text = txt.Text.Trim(); config.OnResult(result); })); dlg.AddTextField(x => { Utils.SetInputType(x, config.InputType); x.Placeholder = config.Placeholder ?? String.Empty; txt = x; }); this.Present(dlg); } else { var isPassword = config.InputType == InputType.Password; var dlg = new UIAlertView(config.Title ?? String.Empty, config.Message, null, config.CancelText, config.OkText) { AlertViewStyle = isPassword ? UIAlertViewStyle.SecureTextInput : UIAlertViewStyle.PlainTextInput }; var txt = dlg.GetTextField(0); Utils.SetInputType(txt, config.InputType); txt.Placeholder = config.Placeholder; dlg.Clicked += (s, e) => { result.Ok = ((int)dlg.CancelButtonIndex != (int)e.ButtonIndex); result.Text = txt.Text.Trim(); config.OnResult(result); }; dlg.Show(); } }); } public override void Toast(string message, int timeoutSeconds = 3, Action onClick = null) { UIApplication.SharedApplication.InvokeOnMainThread(() => { var ms = timeoutSeconds * 1000; BTProgressHUD.ShowToast(message, false, ms); }); } protected override IProgressDialog CreateDialogInstance() { return new ProgressDialog(); } protected virtual void Present(UIAlertController controller) { UIApplication.SharedApplication.InvokeOnMainThread(() => { var top = Utils.GetTopViewController(); var po = controller.PopoverPresentationController; if (po != null) { po.SourceView = top.View; var h = (top.View.Frame.Height / 2) - 400; var v = (top.View.Frame.Width / 2) - 300; po.SourceRect = new CGRect(v, h, 0, 0); po.PermittedArrowDirections = UIPopoverArrowDirection.Any; } top.PresentViewController(controller, true, null); }); } protected override IProgressIndicator CreateNetworkIndicator() { return new NetworkIndicator(); } } } //public override void DateTimePrompt(DateTimePromptConfig config) { // var sheet = new ActionSheetDatePicker { // Title = config.Title, // DoneText = config.OkText // }; // switch (config.SelectionType) { // case DateTimeSelectionType.Date: // sheet.DatePicker.Mode = UIDatePickerMode.Date; // break; // case DateTimeSelectionType.Time: // sheet.DatePicker.Mode = UIDatePickerMode.Time; // break; // case DateTimeSelectionType.DateTime: // sheet.DatePicker.Mode = UIDatePickerMode.DateAndTime; // break; // } // if (config.MinValue != null) // sheet.DatePicker.MinimumDate = config.MinValue.Value; // if (config.MaxValue != null) // sheet.DatePicker.MaximumDate = config.MaxValue.Value; // sheet.DateTimeSelected += (sender, args) => { // // TODO: stop adjusting date/time // config.OnResult(new DateTimePromptResult(sheet.DatePicker.Date)); // }; // var top = Utils.GetTopView(); // sheet.Show(top); // //sheet.DatePicker.MinuteInterval //} //public override void DurationPrompt(DurationPromptConfig config) { // var sheet = new ActionSheetDatePicker { // Title = config.Title, // DoneText = config.OkText // }; // sheet.DatePicker.Mode = UIDatePickerMode.CountDownTimer; // sheet.DateTimeSelected += (sender, args) => config.OnResult(new DurationPromptResult(args.TimeOfDay)); // var top = Utils.GetTopView(); // sheet.Show(top); //}<file_sep>using System; namespace Acr.UserDialogs { public class NetworkIndicator : IProgressDialog { public string Title { get; set; } public int PercentComplete { get; set; } public bool IsDeterministic { get; set; } public bool IsShowing { get { return true; } } public void SetCancel(Action onCancel, string cancelText = "Cancel") {} public void Show() { } public void Hide() { } public void Dispose() { this.Hide(); } } }<file_sep>๏ปฟACR User Dialogs for Xamarin and Windows ========================================= ##User Dialogs Allows for messagebox style dialogs to be called from your shared/PCL code To use, simply reference the nuget package in each of your platform projects. ANDROID USERS: You must call UserDialogs.Init(Activity) ALL OTHERS: UserDialogs.Init() * Action Sheet (multiple choice menu) * Alert * Confirm * Loading * Login * Progress * Prompt * Toast [examples](https://github.com/aritchie/acr-xamarin-forms/blob/master/Samples/Samples/ViewModels/UserDialogViewModel.cs) * Android - Progress/Loading uses Redth's [AndHUD](https://github.com/Redth/AndHUD) * iOS - Progress/Loading uses Nic Wise's [BTProgressHUD](https://github.com/nicwise/BTProgressHUD) * WinPhone - All dialogs by [WPToolkit](http://coding4fun.codeplex.com/) <file_sep>using System; using Android.App; using Android.Views; namespace Acr.UserDialogs { public class NetworkIndicator : IProgressIndicator { private readonly Activity activity; public NetworkIndicator(Activity activity) { this.activity = activity; } private int percentComplete; public int PercentComplete { get { return this.percentComplete; } set { if (this.percentComplete == value) return; if (value > 100) this.percentComplete = 100; else if (value < 0) this.percentComplete = 0; else this.percentComplete = value; ; this.activity.SetProgress(this.percentComplete); } } public bool IsDeterministic { get; set; } public bool IsShowing { get { return true; } } public void Show() { this.activity.RequestWindowFeature(WindowFeatures.Progress); this.activity.RequestWindowFeature(WindowFeatures.IndeterminateProgress); Utils.RequestMainThread(() => { //this.activity.SetProgress(0); //this.activity.SetProgressBarVisibility(true); //this.activity.SetProgressBarIndeterminateVisibility(true); //this.activity.SetProgressBarIndeterminate(true); }); } public void Hide() { } public void Dispose() { this.Hide(); } } } /* public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); requestWindowFeature(Window.FEATURE_PROGRESS); currentURL = BrowserActivity.this.getIntent().getExtras().getString("currentURL"); setContentView(R.layout.browser); setProgressBarIndeterminateVisibility(true); setProgressBarVisibility(true); try { mWebView = (WebView) findViewById(R.id.webview); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.setWebViewClient(new browserActivityClient()); mWebView.setWebChromeClient(new WebChromeClient() { public void onProgressChanged(WebView view, int progress) { setProgress(progress * 100); if(progress == 100) { setProgressBarIndeterminateVisibility(false); setProgressBarVisibility(false); } } }); mWebView.loadUrl(currentURL); } catch (Exception e) { Log.e(getClass().getSimpleName(), "Browser: " + e.getMessage()); Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show(); } */<file_sep>using System; using System.Windows; using Microsoft.Phone.Shell; namespace Acr.UserDialogs { public class NetworkIndicator : IProgressIndicator { private readonly ProgressIndicator progress = new ProgressIndicator(); private int percentComplete; public int PercentComplete { get { return this.percentComplete; } set { if (this.percentComplete == value) return; this.progress.IsIndeterminate = false; if (value > 100) this.percentComplete = 100; else if (value < 0) this.percentComplete = 0; else this.percentComplete = value; this.progress.Value = this.percentComplete; } } public bool IsShowing { get { return this.progress.IsVisible; } private set { this.progress.IsVisible = value; SystemTray.SetProgressIndicator(Deployment.Current, value ? this.progress : null); } } public void Show() { this.IsShowing = true; } public void Hide() { this.IsShowing = false; } public void Dispose() { this.Hide(); } } }<file_sep>using System; using System.Linq; using UIKit; namespace Acr.UserDialogs { public static class Utils { public static UIWindow GetTopWindow() { return UIApplication.SharedApplication .Windows .Reverse() .FirstOrDefault(x => x.WindowLevel == UIWindowLevel.Normal && !x.Hidden ); } public static UIView GetTopView() { return GetTopWindow().Subviews.Last(); } public static UIViewController GetTopViewController() { var root = GetTopWindow().RootViewController; var tabs = root as UITabBarController; if (tabs != null) return tabs.SelectedViewController; var nav = root as UINavigationController; if (nav != null) return nav.VisibleViewController; if (root.PresentedViewController != null) return root.PresentedViewController; return root; } public static void SetInputType(UITextField txt, InputType inputType) { switch (inputType) { case InputType.Email : txt.KeyboardType = UIKeyboardType.EmailAddress; break; case InputType.Number: txt.KeyboardType = UIKeyboardType.NumberPad; break; case InputType.Password: txt.SecureTextEntry = true; break; default : txt.KeyboardType = UIKeyboardType.Default; break; } } } }
1505f17b4b2cc184782b0a9cf815a787736e5631
[ "Markdown", "C#" ]
10
C#
geirsagberg/userdialogs
9a1b96dd254d5afc7917170315596b181cd2f5d8
b2262069078681f23aad7614c5f0ae14ab3200ca
refs/heads/master
<file_sep># --- # title: "EAA_6_run_graph_program" # author: "<EMAIL>" # date: "2019/7/3" # output: html_document # --- #```{r} rm(list = ls()) #``` ## save_persp_pdf_FUN #```{r} save_persp_pdf_FUN <- function( dat_0 = dat_0, plot_name = "bci", theta_set = c(born = 320, clust = 310, diedS = 310, diedL = 310, growth = 320), phi_set = c(born = 30, clust = 30, diedS = 30, diedL = 30, growth = 30), k_set = c(born = 12, clust = 12, diedS = 12, diedL = 12, growth = 5) ) { data_type <- as.character(unique(dat_0[, "data_type"])) p_list <- vector(mode = "list", length = length(data_type)) names(p_list) <- data_type # for(i in data_type) { condition <- switch(EXPR = i, growth = c(1, 5), c(1, 4)) theta <- switch(EXPR = i, born = theta_set[1], clust = theta_set[2], diedL = theta_set[3], diedS = theta_set[4], growth = theta_set[5]) phi <- switch(EXPR = i, born = phi_set[1], clust = phi_set[2], diedL = phi_set[3], diedS = phi_set[4], growth = phi_set[5]) gam_k <- switch(EXPR = i, born = k_set[1], clust = k_set[2], diedL = k_set[3], diedS = k_set[4], growth = k_set[5]) p_j <- vector(mode = "list", length = length(condition)) names(p_j) <- condition for(j in condition) { dat_1 <- dat_1_FUN( dat_0 = dat_0, plot_name = plot_name, data_type = i, condition = j) dat_1[, "annul_dist"] <- as.numeric(as.character(dat_1[, "annul_dist"])) gam_0 <- mgcv::gam( formula = graph_value ~ s(annul_dist, k = gam_k) + s(phyl_dist, k = gam_k), family = gaussian(link = "identity"), data = dat_1) predict_values <- predict_gam_FUN( gam_0 = gam_0, ngrid = 50) main <- sprintf( fmt = "%s, %s, condition %s", plot_name, i, j) # pdf(file = sprintf(fmt = "pdf_save//persp_%s.pdf", main), width = 16 / 2.54, height = 16 / 2.54) par(mar = c(3, 2, 2, 0)) persp_gam_graph_FUN( predict_values = predict_values, theta = theta, phi = phi, main = main, xlab = "Phys distance (m)", ylab = "phylo distance (Ma)", zlab = paste("\n", "z-values", sep = "") ) dev.off() # } } } #``` ## Read R Code #```{r} setwd("F:\\porjects-wangbin\\EAA_pnas") # dir() source("EAA_4_graph_program_gam_ggplot_persp_rgl_20190703_1616.R") #``` ## dat_0 #```{r} setwd("F:\\porjects-wangbin\\EAA_pnas\\EAA_results") load("dat_0_pnas_20190703.save") dat_0 <- dat_0 #``` ## Run "save_persp_pdf_FUN" "bci" #```{r} setwd("F:\\porjects-wangbin\\EAA_pnas") plot_name = "bci" theta_set = c(born = 320, clust = 310, diedS = 310, diedL = 310, growth = 320) phi_set = c(born = 30, clust = 30, diedS = 30, diedL = 30, growth = 30) k_set = c(born = 12, clust = 12, diedS = 12, diedL = 12, growth = 5) # save_persp_pdf_FUN(dat_0, plot_name, theta_set, phi_set, k_set) # #``` <file_sep># --- # title: "EAA_program_gam_ggplot_persp_rgl" # author: "<EMAIL>" # date: "2019_6_27 1543" # output: html_document # --- # devtools::install_github("thomasp85/patchwork") #```{r} dat_1_FUN <- function( dat_0 = dat_0, plot_name = c("bci", "nonggang")[1], data_type = c("clust", "growth", "born", "died", "diedS", "diedL")[1], census_interval = list(NA, 1:5)[[1]], condition = list(NA, 1:5)[[1]], annul_interval = list(NA, 1:5)[[1]]) { if(all(plot_name %in% unique(dat_0[, "plot_name"])) == T) {NULL} else { stop(sprintf(fmt = "'plot_name' must be one of: %s", paste(unique(dat_0[, "plot_name"]), collapse = ", ")))} if(all(data_type %in% unique(dat_0[, "data_type"])) == T) {NULL} else { stop(sprintf(fmt = "'data_type' must be one of: %s", paste(unique(dat_0[, "data_type"]), collapse = ", ")))} dat_1 <- dat_0[ dat_0[, "plot_name"] == plot_name & dat_0[, "data_type"] == data_type, ] if(all(is.na(census_interval)) == T) {NULL} else { index <- census_interval %in% unique(dat_1[, "census_interval"]) if(all(index) == T) { dat_1 <- dat_1[dat_1[, "census_interval"] %in% census_interval, ] } else { stop( sprintf(fmt = "'census_interval' must be NA or a subset of: %s", paste(unique(dat_1[, "census_interval"]), collapse = ", ")))} } if(all(is.na(condition)) == T) {NULL} else { index <- condition %in% unique(dat_1[, "condition"]) if(all(index) == T) { dat_1 <- dat_1[dat_1[, "condition"] %in% condition, ] } else { stop( sprintf(fmt = "'condition' must be NA or a subset of: %s", paste(unique(dat_1[, "condition"]), collapse = ", ")))} } if(all(is.na(annul_interval)) == T) {NULL} else { index <- annul_interval %in% unique(dat_1[, "annul_interval"]) if(all(index) == T) { dat_1 <- dat_1[dat_1[, "annul_interval"] %in% annul_interval, ] } else { stop( sprintf(fmt = "'annul_interval' must be NA or a subset of: %s", paste(unique(dat_1[, "annul_interval"]), collapse = ", ")))} } if(inherits(try(dat_1[, "sd_shuffled"], silent = T), "try-error") == F) { dat_1[, "graph_value"] <- round(x = dat_1[, "relative_value"] / dat_1[, "sd_shuffled"], digits = 3) } else { if(inherits(try(dat_1[, "z_score"], silent = T), "try-error") == F){ dat_1[, "graph_value"] <- round(x = (dat_1[, "value"] / dat_1[, "z_score"]) * 1.96, digits = 3) } else { warning("Have not found dat_1[, 'sd_shuffled'] or dat_1[, 'z_score'].") } } dat_1[is.na(dat_1[, "graph_value"]) == T, "graph_value"] <- 0 dat_1[, "annul_dist"] <- round(x = dat_1[, "annul_dist"], digits = 2) dat_1[, "phyl_dist"] <- round(x = dat_1[, "phyl_dist"] / 2) dat_1[, "plot_name"] <- as.factor(as.character(dat_1[, "plot_name"])) dat_1[, "condition"] <- as.factor(dat_1[, "condition"]) # return dat_1 } #``` #```{r} ggplot_graph_FUN <- function( dat_1 = dat_1_growth, gam_k = c(NA, 7)[2], graph_name = "graph_value") { require(ggplot2) if(is.na(gam_k) == T) { formula <- formula("y ~ s(x)") } else { if(is.numeric(gam_k) == T & gam_k > 0) { formula <- formula("y ~ s(x, k = gam_k)") } else { stop("'gam_k' must be NA or a positive integer.") } } data_type <- as.character(unique(dat_1[, "data_type"])) plot_name <- unique(dat_1[, "plot_name"]) annulus <- unique(dat_1[, "annul_interval"]) dat_1[, "graph_value"] <- dat_1[, graph_name] y_int <- switch( EXPR = graph_name, graph_value = c(-1.96, 0, 1.96), 0) type_txt <- switch( EXPR = data_type, growth = "focal growth", born = "recruitment", clust = "clustering", died = "mortality", diedS = "mortality_S", diedL = "mortality_L") main_title <- sprintf(fmt = "%s, %s", type_txt, plot_name) sub_title <- sprintf(fmt = "annulus = %s, k = %s", annulus, gam_k) # return ggplot(data = dat_1, mapping = aes(phyl_dist, graph_value, colour = condition)) + geom_hline(yintercept = y_int, size = 0.8, color = "darkgoldenrod4") + geom_jitter(size = 1, width = 0, alpha = 2/10) + geom_smooth(method = 'gam', formula = formula, se = TRUE, level = 0.95, size = 2) + scale_colour_brewer(palette = "RdYlBu", direction = -1) + labs(title = main_title, subtitle = sub_title) + theme(axis.title = element_blank(), axis.text = element_text(size = 10), title = element_text(size = 12.5), legend.position = "none") } # ``` ## gam_FUN #```{r } gam_FUN <- function(dat_1){ gam_0 <- try( expr = mgcv::gam( formula = graph_value ~ s(annul_dist) + s(phyl_dist), family = gaussian(link = "identity"), data = dat_1), silent = T) if(inherits(gam_0, "try-error") == F) { cat("\n"); print(gam_0[["formula"]]) # return(gam_0) } else {NULL} for(gam_k in 20:1) { gam_0 <- try( expr = mgcv::gam( formula = graph_value ~ s(annul_dist, k = gam_k) + s(phyl_dist, k = gam_k), family = gaussian(link = "identity"), data = dat_1), silent = T) if(inherits(gam_0, "try-error") == T) {NULL} else { cat("\n") warning(sprintf(fmt = "gam_k was changed to %s.", gam_k)) print( gsub(pattern = "gam_k", replacement = gam_k, x = "graph_value ~ s(annul_dist, k = gam_k) + s(phyl_dist, k = gam_k)") ) # return(gam_0)} } } #``` #```{r} predict_gam_FUN <- function(gam_0 = gam_0, ngrid = 30) { xy_range <- gam_0[["model"]] annul_dist <- xy_range[["annul_dist"]] annul_dist <- as.numeric(as.character(annul_dist)) annul_levels <- seq(from = min(annul_dist), to = max(annul_dist), length.out = ngrid) xy_grid <- expand.grid( annul_dist = annul_levels, phyl_dist = seq(from = min(xy_range[["phyl_dist"]]), to = max(xy_range[["phyl_dist"]]), length.out = ngrid)) xy_grid <- as.data.frame(x = xy_grid) fv <- mgcv::predict.gam( object = gam_0, newdata = xy_grid, se.fit = T, type = "response") # return data.frame( annul_dist = xy_grid[, "annul_dist"], phyl_dist = xy_grid[, "phyl_dist"], fit = fv[["fit"]], fit_se = fv[["se.fit"]], fit_upper = fv[["fit"]] + 1.96 * fv[["se.fit"]], fit_lower = fv[["fit"]] - 1.96 * fv[["se.fit"]], num = 1:nrow(xy_grid) ) } #``` #```{r} persp_gam_graph_FUN <- function( predict_values = predict_values, theta = 45, phi = 45, main = "bci, clustered, smallest focal trees", xlab = "annular distance (m)", ylab = "phylogenetic distance (Ma)", zlab = "z-values") { z_mat <- tapply( X = predict_values[, "fit"], INDEX = predict_values[, c("annul_dist", "phyl_dist")], FUN = mean) col_FUN <- function(z_mat){ ncz <- ncol(z_mat) nrz <- nrow(z_mat) zfacet <- z_mat[-1, -1] + z_mat[-1, -ncz] + z_mat[-nrz, -1] + z_mat[-nrz, -ncz] color <- heat.colors(n = prod(dim(zfacet)), alpha = 0.9) col <- color[as.numeric(as.factor(zfacet))] col[zfacet <= (1.96 * 4) & zfacet >= (-1.96 * 4)] <- "#CCCCCCE6" # col } persp_FUN <- function(){ col <- col_FUN(z_mat) persp( x = as.numeric(rownames(z_mat)), y = as.numeric(colnames(z_mat)), z = z_mat, theta = theta, phi = phi, ticktype = "detailed", main = main, xlab = paste("\n", xlab, sep = ""), ylab = paste("\n", ylab, sep = ""), zlab = zlab, col = col, cex.lab = 1.8, cex.axis = 1.3, cex.main = 2, lwd = 1, border = ggplot2::alpha(colour = "grey", alpha = 0.6)) } #return persp_FUN() } #``` #```{r} z_se_data_FUN <- function(predict_values){ z_se_data <- rbind(predict_values, predict_values) z_se_data[1:nrow(predict_values), "fit"] <- z_se_data[1:nrow(predict_values), "fit_upper"] z_se_data[ nrow(predict_values) + 1:nrow(predict_values), "fit"] <- z_se_data[ nrow(predict_values) + 1:nrow(predict_values), "fit_lower"] z_se_data[, "annul_interval"] <- as.integer(as.factor(z_se_data[, "annul_dist"])) z_se_data[, "phyl_interval"] <- as.integer(as.factor(z_se_data[, "phyl_dist"])) z_se_data <- z_se_data[order(z_se_data[, "num"]), ] # return z_se_data } #``` #```{r} rgl_gam_graph_FUN <- function( predict_values = predict_values, main = "bci, clustered, smallest focal trees", xlab = "annular distance (m)", ylab = "phylogenetic distance (Ma)", zlab = "z-values", axes_type = c(1, 2)[1]) { z_mat <- tapply( X = predict_values[, "fit"], INDEX = predict_values[, c("annul_dist", "phyl_dist")], FUN = mean) col_0 <- heat.colors(n = 100)[20:70] col <- rep(x = col_0, each = (prod(dim(z_mat))/length(col_0)) + 1) col <- col[as.numeric(as.factor(z_mat))] col[z_mat <= 1.96 & z_mat >= -1.96] <- "#4A708BE6" z_se_data <- z_se_data_FUN(predict_values) xi <- z_se_data[, "annul_interval"] t_x <- (max(xi) - min(xi)) / 10 yi <- z_se_data[, "phyl_interval"] t_y <- (max(yi) - min(yi)) / 10 t_z <- (max(z_mat) - min(z_mat)) / 10 require(rgl) open3d() bg3d(color="gray") # persp3d(x = 1:nrow(z_mat) / t_x, y = 1:ncol(z_mat) / t_y, z = z_mat / t_z, line_antialias = T, lwd = 4, color= col, alpha = 0.8, front = "lines", back = "lines", lit = F, add = TRUE) col_1 <- rep(x = col, each = 2) col_2 <- rep(x = c("red", "blue"), times = length(col)) col_2[which(col_1 == "#4A708BE6")] <- "#4A708BE6" segments3d( x = z_se_data[, "annul_interval"] / t_x, y = z_se_data[, "phyl_interval"]/ t_y, z = z_se_data[, "fit"] / t_z, lwd = 3, color = col_2, alpha = 0.6, line_antialias = T) box3d() at_x <- round(seq( from = min(xi), to = max(xi), length.out = 10), 1) xj <- as.numeric(as.character(unique(z_se_data[, "annul_dist"]))) labels_x <- round(seq( from = min(xj), to = max(xj), length.out = 10), 1) at_y <- round(seq( from = min(yi), to = max(yi), length.out = 10)) yj <- as.numeric(as.character(unique(z_se_data[, "phyl_dist"]))) labels_y <- round(seq( from = min(yj), to = max(yj), length.out = 10)) at_z <- round(seq( from = min(z_se_data[, "fit"]), to = max(z_se_data[, "fit"]), length.out = 10)) labels_z <- at_z axes_1_FUN <- function(){ axes3d( edges = 'x--', at = at_x / t_x, labels = labels_x) axes3d( edges = 'y+-', at = at_y / t_y, labels = labels_y) axes3d( edges = 'z--', at = at_z / t_z, labels = labels_z) title3d( main = main, xlab = xlab, ylab = NULL, zlab = zlab) mtext3d(text = ylab, edge = 'y+-', line = 2, at = NULL) } axes_2_FUN <- function(){ axes3d( edges = 'x++', at = at_x / t_x, labels = labels_x) axes3d( edges = 'y-+', at = at_y / t_y, labels = labels_y) axes3d( edges = 'z++', at = at_z / t_z, labels = labels_z) title3d( sub = main, xlab = NULL, ylab = NULL, zlab = NULL) mtext3d(text = xlab, edge = 'x++', line = 2, at = NULL) mtext3d(text = ylab, edge = 'y-+', line = 2, at = NULL) mtext3d(text = zlab, edge = 'z++', line = 2, at = NULL) } if(axes_type == 1) { axes_1_FUN() } else { if(axes_type == 2){ axes_2_FUN() } else { warning("\'axes_type\' must be 1 or 2.") } } userMatrix <- rotate3d( obj = diag(4), angle = pi/4, x = -1, y = 0, z = -1) rgl.viewpoint(userMatrix = userMatrix) } #``` <file_sep># --- # title: "Untitled" # author: "<EMAIL>" # date: "2019/06/27" # output: html_document # editor_options: # chunk_output_type: console # --- #```{r} rm(list = ls()) #``` ## package #```{r} setwd("F:\\porjects-wangbin\\EAA_pnas") require(ggplot2) # devtools::install_github("thomasp85/patchwork") require(patchwork) source("EAA_4_graph_program_gam_ggplot_persp_rgl_20190703_1616.R") #``` # dat_0 #```{r} setwd("F:\\porjects-wangbin\\EAA_pnas\\EAA_results") load(file = "dat_0_pnas_20190703.save") dat_0 <- dat_0 #``` ## patchwork_detailed_values_FUN #```{r} patchwork_detailed_values_FUN <- function( dat_0, plot_name, gam_k = c(born = 5, clust = 5, diedL = 4, diedS = 4, growth = 3)) { # data_types <- unique(dat_0[, "data_type"]) p_j_list <- vector(mode = "list", length = length(data_types)) names(p_j_list) <- data_types for(j in data_types) { k_0 <- switch(EXPR = j, born = gam_k[1], clust = gam_k[2], diedL = gam_k[3], diedS = gam_k[4], growth = gam_k[5]) value_names <- c("real_value", "relative_value", "mean_shuffled", "sd_shuffled", "graph_value") p_i_list <- vector(mode = "list", length = length(value_names)) names(p_i_list) <- value_names for(i in value_names) { condition <- switch(EXPR = j, growth = 0:5, 1:4) dat_1 <- dat_1_FUN( dat_0 = dat_0, plot_name = plot_name, data_type = j, condition = condition, annul_interval = 1) p_i_list[[i]] <- ggplot_graph_FUN( dat_1 = dat_1, gam_k = k_0, graph_name = i) p_i_list[[i]] <- p_i_list[[i]] + annotate("text", label = i, x = 100, y = 0, size = 6, colour = "black") } p_j_list[[j]] <- p_i_list } # return p_j_list } #``` ## graph_rbind_FUN #```{r} require(patchwork) graph_rbind_FUN <- function(p_j_list) { # p_list <- p_j_list[["born"]] p_born <- p_list[["real_value"]] + p_list[["mean_shuffled"]] + p_list[["relative_value"]] + p_list[["sd_shuffled"]] + p_list[["graph_value"]] + plot_layout(ncol = 5) # p_list <- p_j_list[["clust"]] p_clust <- p_list[["real_value"]] + p_list[["mean_shuffled"]] + p_list[["relative_value"]] + p_list[["sd_shuffled"]] + p_list[["graph_value"]] + plot_layout(ncol = 5) # p_list <- p_j_list[["diedS"]] p_diedS <- p_list[["real_value"]] + p_list[["mean_shuffled"]] + p_list[["relative_value"]] + p_list[["sd_shuffled"]] + p_list[["graph_value"]] + plot_layout(ncol = 5) # p_list <- p_j_list[["diedL"]] p_diedL <- p_list[["real_value"]] + p_list[["mean_shuffled"]] + p_list[["relative_value"]] + p_list[["sd_shuffled"]] + p_list[["graph_value"]] + plot_layout(ncol = 5) # p_list <- p_j_list[["growth"]] p_growth <- p_list[["real_value"]] + p_list[["mean_shuffled"]] + p_list[["relative_value"]] + p_list[["sd_shuffled"]] + p_list[["graph_value"]] + plot_layout(ncol = 5) # p_all <- p_born / p_clust / p_diedS / p_diedL / p_growth # return p_all } #``` ## detailed graphs "windriver" #```{r} setwd("F:\\porjects-wangbin\\EAA_pnas") plot_name = "windriver" dat_0 = dat_0 gam_k = c(born = 5, clust = 5, diedL = 4, diedS = 4, growth = 3) # p_j_list <- patchwork_detailed_values_FUN(dat_0, plot_name, gam_k) p_all <- graph_rbind_FUN(p_j_list) filename = sprintf( fmt = "pdf_save//patchwork_detailed_values_%s.pdf", plot_name) ggsave( filename = filename, plot = p_all, device = "pdf", width = 8 * 5, height = 8 * 5, units = "cm") #``` ## detailed graphs "mudumalai" #```{r} setwd("F:\\porjects-wangbin\\EAA_pnas") plot_name = "mudumalai" dat_0 = dat_0 gam_k = c(born = 5, clust = 5, diedL = 4, diedS = 4, growth = 3) # p_j_list <- patchwork_detailed_values_FUN(dat_0, plot_name, gam_k) p_all <- graph_rbind_FUN(p_j_list) filename = sprintf( fmt = "pdf_save//patchwork_detailed_values_%s.pdf", plot_name) ggsave( filename = filename, plot = p_all, device = "pdf", width = 8 * 5, height = 8 * 5, units = "cm") #``` ## detailed graphs wytham #```{r} setwd("F:\\porjects-wangbin\\EAA_pnas") plot_name = "wytham" dat_0 = dat_0 gam_k = c(born = 5, clust = 5, diedL = 4, diedS = 4, growth = 3) # p_j_list <- patchwork_detailed_values_FUN(dat_0, plot_name, gam_k) p_all <- graph_rbind_FUN(p_j_list) filename = sprintf( fmt = "pdf_save//patchwork_detailed_values_%s.pdf", plot_name) ggsave( filename = filename, plot = p_all, device = "pdf", width = 8 * 5, height = 8 * 5, units = "cm") #``` ## detailed graphs gutianshan #```{r} setwd("F:\\porjects-wangbin\\EAA_pnas") plot_name = "gutianshan" dat_0 = dat_0 gam_k = c(born = 6, clust = 6, diedL = 5, diedS = 5, growth = 5) # p_j_list <- patchwork_detailed_values_FUN(dat_0, plot_name, gam_k) p_all <- graph_rbind_FUN(p_j_list) filename = sprintf( fmt = "pdf_save//patchwork_detailed_values_%s.pdf", plot_name) ggsave( filename = filename, plot = p_all, device = "pdf", width = 8 * 5, height = 8 * 5, units = "cm") #``` ## detailed graphs nonggang #```{r} setwd("F:\\porjects-wangbin\\EAA_pnas") plot_name = "nonggang" dat_0 = dat_0 gam_k = c(born = 5, clust = 5, diedL = 4, diedS = 4, growth = 3) # p_j_list <- patchwork_detailed_values_FUN(dat_0, plot_name, gam_k) p_all <- graph_rbind_FUN(p_j_list) filename = sprintf( fmt = "pdf_save//patchwork_detailed_values_%s.pdf", plot_name) ggsave( filename = filename, plot = p_all, device = "pdf", width = 8 * 5, height = 8 * 5, units = "cm") #``` ## detailed graphs heishiding #```{r} setwd("F:\\porjects-wangbin\\EAA_pnas") plot_name = "heishiding" dat_0 = dat_0 gam_k = c(born = 5, clust = 5, diedL = 4, diedS = 4, growth = 3) # p_j_list <- patchwork_detailed_values_FUN(dat_0, plot_name, gam_k) p_all <- graph_rbind_FUN(p_j_list) filename = sprintf( fmt = "pdf_save//patchwork_detailed_values_%s.pdf", plot_name) ggsave( filename = filename, plot = p_all, device = "pdf", width = 8 * 5, height = 8 * 5, units = "cm") #``` ## detailed graphs "bci" #```{r} setwd("F:\\porjects-wangbin\\EAA_pnas") plot_name = "bci" dat_0 = dat_0 gam_k = c(born = 5, clust = 5, diedL = 4, diedS = 4, growth = 3) # p_j_list <- patchwork_detailed_values_FUN(dat_0, plot_name, gam_k) p_all <- graph_rbind_FUN(p_j_list) filename = sprintf( fmt = "pdf_save//patchwork_detailed_values_%s.pdf", plot_name) ggsave( filename = filename, plot = p_all, device = "pdf", width = 8 * 5, height = 8 * 5, units = "cm") #``` ## detailed graphs pasoh #```{r} setwd("F:\\porjects-wangbin\\EAA_pnas") plot_name = "pasoh" dat_0 = dat_0 gam_k = c(born = 5, clust = 5, diedL = 4, diedS = 4, growth = 3) # p_j_list <- patchwork_detailed_values_FUN(dat_0, plot_name, gam_k) p_all <- graph_rbind_FUN(p_j_list) filename = sprintf( fmt = "pdf_save//patchwork_detailed_values_%s.pdf", plot_name) ggsave( filename = filename, plot = p_all, device = "pdf", width = 8 * 5, height = 8 * 5, units = "cm") #``` <file_sep># EAAr An R package for **Equal Area Annulus (EAA) neighborhood analysis method**. ## Introduction The EAA method (Wills, et al. 2016; 2019) combines spatial point-pattern and individual-based neighborhood models. It is capable of refining and extending the research results of traditional neighborhood models at different spatial and phylogenetic distances. This method can be used to examine in detail many of the interactions between ecological factors and evolutionary divergence in forest diversity plots. Most recently we examine data from 16 globally distributed forest dynamics plots (FDPs), using the equal-area-annulus (EAA) method. This method obtains detailed information on interactions between focal trees and trees that occupy concentric equal-area annuli around the focal trees. The interactions affect growth, clustering, recruitment, and mortality, and are consistent with the presence of negative density-dependent effects. Their strength increases smoothly with physical proximity, but fluctuates in a pattern unique to each FDP with increasing phylogenetic proximity. We show how one of these unique patterns, in the temperate Wind River FDP, can provide new information about a known allelopathic interaction. Such species-species interactions, along with convergent and divergent coevolutionary processes that may be uncorrelated with overall phylogenetic separation, contribute to these unique effects. EAA can be used to test Darwinโ€™s prediction that unique patterns of coevolution in different ecosystems can be chiefly traced to interactions among each ecosystemโ€™s unique mix of species. ## Authors <NAME> <<EMAIL>> <NAME> <<EMAIL>> ## Installation ```r devtools::install_github("wangbinzjcc/EAAr") ``` ## Usage Hint: The main function of this package is under test and has not been uploaded, so it is temporarily unavailable. The author is trying to repair it, but the process still needs a few days. Thank you for your attention. ```r library(EAAr) ?EAAr ``` ## References <NAME>., <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, 2016. Persistence of Neighborhood Demographic Influences Over Long Phylogenetic Distances May Help Drive Post-Speciation Adaptation in Tropical Forests. PLOS ONE | DOI: 10.1371/ journal.pone.0156913. <NAME>., <NAME>, et al., 2019. In Forests Worldwide a Treeโ€™s Influence on Neighbors Increases Steadily with Proximity and Idiosyncratically with Phylogenetic Relatedness: Tree Phylogenies Influence World's Forests. <file_sep># --- # title: "all_plots_patchwork_EAA_20190629" # author: "<EMAIL>" # date: "2019/6/29" # output: html_document # --- #```{r} rm(list = ls()) #``` #```{r} require(ggplot2) # devtools::install_github("thomasp85/patchwork") require(patchwork) setwd("F:\\porjects-wangbin\\EAA_pnas") source("EAA_4_graph_program_gam_ggplot_persp_rgl_20190703_1616.R") #``` # dat_0_new #```{r} setwd("F:\\porjects-wangbin\\EAA_pnas\\EAA_results") load(file = "dat_0_pnas_20190703.save") dat_0 <- dat_0 # unique(dat_0[, "plot_name"]) #``` # patchwork_graph_FUN ------------------------- #```{r} patchwork_graph_FUN <- function( dat_0, plot_name, gam_k = c(born = 5, clust = 5, diedL = 4, diedS = 4, growth = 3)) { # data_type <- unique(dat_0[, "data_type"]) p_list <- vector(mode = "list", length = length(data_type)) names(p_list) <- data_type #--- for(i in data_type) { condition <- switch(EXPR = i, growth = 1:5, 1:4) dat_1 <- dat_1_FUN( dat_0 = dat_0, plot_name = plot_name, data_type = i, condition = condition, annul_interval = 1) k_0 <- switch( EXPR = i, born = gam_k[1], clust = gam_k[2], diedS = gam_k[3], diedL = gam_k[4], growth = gam_k[5]) p_list[[i]] <- ggplot_graph_FUN(dat_1 = dat_1, gam_k = k_0) } # return p_list } #``` # print graph "mudumalai" #```{r} require(patchwork) plot_name = "mudumalai" dat_0 = dat_0 gam_k = c(born = 5, clust = 5, diedL = 4, diedS = 4, growth = 4) p_list <- patchwork_graph_FUN(dat_0, plot_name, gam_k) p_mudumalai <- p_list[["born"]] + p_list[["clust"]] + p_list[["diedS"]]+ p_list[["diedL"]] + p_list[["growth"]] + plot_layout(ncol = 5) # print(p_mudumalai) #``` # print graph "windriver" #```{r} require(patchwork) plot_name = "windriver" dat_0 = dat_0 gam_k = c(born = 5, clust = 5, diedL = 4, diedS = 4, growth = 3) p_list <- patchwork_graph_FUN(dat_0, plot_name, gam_k) p_windriver <- p_list[["born"]] + p_list[["clust"]] + p_list[["diedS"]]+ p_list[["diedL"]] + p_list[["growth"]] + plot_layout(ncol = 5) # print(p_windriver) #``` # print graph "wytham" #```{r} require(patchwork) plot_name = "wytham" dat_0 = dat_0 gam_k = c(born = 5, clust = 5, diedL = 4, diedS = 4, growth = 3) p_list <- patchwork_graph_FUN(dat_0, plot_name, gam_k) p_wytham <- p_list[["born"]] + p_list[["clust"]] + p_list[["diedS"]]+ p_list[["diedL"]] + p_list[["growth"]] + plot_layout(ncol = 5) # print(p_wytham) #``` # print graph nonggang #```{r} require(patchwork) plot_name = "nonggang" dat_0 = dat_0 gam_k = c(born = 7, clust = 7, diedL = 5, diedS = 5, growth = 4) p_list <- patchwork_graph_FUN(dat_0, plot_name, gam_k) p_nonggang <- p_list[["born"]] + p_list[["clust"]] + p_list[["diedS"]]+ p_list[["diedL"]] + p_list[["growth"]] + plot_layout(ncol = 5) # print(p_nonggang) #``` # print graph heishiding #```{r} require(patchwork) plot_name = "heishiding" dat_0 = dat_0 gam_k = c(born = 7, clust = 7, diedL = 5, diedS = 5, growth = 5) p_list <- patchwork_graph_FUN(dat_0, plot_name, gam_k) p_heishiding <- p_list[["born"]] + p_list[["clust"]] + p_list[["diedS"]]+ p_list[["diedL"]] + p_list[["growth"]] + plot_layout(ncol = 5) # print(p_heishiding) #``` # print graph pasoh #```{r} require(patchwork) plot_name = "pasoh" dat_0 = dat_0 gam_k = c(born = 7, clust = 7, diedL = 5, diedS = 5, growth = 5) p_list <- patchwork_graph_FUN(dat_0, plot_name, gam_k) p_list[["growth"]] <- p_list[["growth"]] + ylim(-20, 5) p_pasoh <- p_list[["born"]] + p_list[["clust"]] + p_list[["diedS"]]+ p_list[["diedL"]] + p_list[["growth"]] + plot_layout(ncol = 5) # print(p_pasoh) #``` # print graph "bci" #```{r} require(patchwork) plot_name = "bci" dat_0 = dat_0 gam_k = c(born = 7, clust = 7, diedL = 5, diedS = 5, growth = 5) p_list <- patchwork_graph_FUN(dat_0, plot_name, gam_k) p_list[["growth"]] <- p_list[["growth"]] + ylim(-20, 5) p_bci <- p_list[["born"]] + p_list[["clust"]] + p_list[["diedS"]]+ p_list[["diedL"]] + p_list[["growth"]] + plot_layout(ncol = 5) # print(p_bci) #``` # save all graphs #```{r} setwd("F:\\porjects-wangbin\\EAA_pnas") require(patchwork) p_all_plot <- p_mudumalai / p_windriver / p_wytham / p_nonggang / p_heishiding / p_pasoh / p_bci ggsave( filename = "pdf_save//all_plots_patchwork_EAA_graphs.pdf", plot = p_all_plot, device = "pdf", width = 8 * 5, height = 8 * 7, units = "cm") #``` <file_sep># --- # title: "test_EAA_3" # author: "<EMAIL>" # date: "2019/06/03" # output: html_document # editor_options: # chunk_output_type: console # --- ## Package #```{r} require(bigtabulate) require(nlme) #``` ## Data #```{r} setwd("D:\\wangbinzjcc\\EAA_pnas") load("data\\bci.bigarray") # # bci.bigarray <- bci.bigarray[ # bci.bigarray[, "gx"] < 100 & bci.bigarray[, "gy"] < 100, ] # load("data\\bci.pairwise.table.scenario.2") # bci.bigarray[1:20, 1:8] #``` ## Arguments #```{r} replicate_EAA_times = 10; big_array_data = bci.bigarray; census_interval_number = (6-1); pairwise_table_scenario_data = bci.pairwise.table.scenario.2; annulus_size = 25; annulus_number = 20; quantile_number = 20; shuffled_times = 100; min_sample_phyl_interval = 5; plot_name = "bci"; working_directory = getwd(); # census_interval = 1 #``` ## File_save #```{r } file_save <- sprintf( fmt = "EAA_results\\dat_0_%s_a_%s_size_%s_q_%s_EAA_%s.save", plot_name,annulus_number,annulus_size,quantile_number, format(Sys.time(), "%Y%m%d_%H%M%OS")) file_save #``` ### Load main program #```{r} source("EAA_3_main_program_BinWang_2019_0627_1542.R") #``` ### Run main program #```{r} EAA_analysis_results <- EAA_analysis_results_FUN( replicate_EAA_times, big_array_data, census_interval_number, pairwise_table_scenario_data, annulus_size, annulus_number, quantile_number, shuffled_times, min_sample_phyl_interval, plot_name, working_directory) save(EAA_analysis_results, file = file_save) #``` ### Read dat_0 and summary_sp_pairs #```{r} load(file = file_save) dat_0 <- EAA_analysis_results[["EAA_results"]] summary_sp_pairs <- EAA_analysis_results[["summary_sp_pairs"]] #``` <file_sep># --- # title: "The EAA main program" # author: "<EMAIL>" # date: "2019-07-08 0952" # output: html_document # editor_options: # chunk_output_type: console # --- ### --- # single_census_interval_data_add_z_growth_FUN <- # switch(EXPR = z_growth_model, # gls = gls_add_z_growth_FUN, # scale = scale_add_z_growth_FUN) ### !!! #```{r} # install.packages("bigtabulate") # install.packages("nlme") # require(bigtabulate) # require(nlme) #``` #-------------------------------------------------- # "some functions, begin ~ " #```{r} create_directory_FUN <- function(){ gc() dir_name <- paste("big_mat", format(Sys.time(), "%Y_%m%d_%H%M_%OS"), paste(sample(letters, 8), collapse = ""), sep = "_") backingpath <- sprintf(fmt = "%s/%s", getwd(), dir_name) backingfile <- sprintf(fmt = "%s.bin", dir_name) descriptorfile <- sprintf(fmt = "%s.desc", dir_name) dir.create(path = backingpath) # return list(backingpath = backingpath, backingfile = backingfile, descriptorfile = descriptorfile) } #--- as_big_matrix_FUN <- function(x_matrix) { # dir_description <- create_directory_FUN() # return bigmemory::as.big.matrix( x = as.matrix(x_matrix), type = "double", separated = TRUE, backingfile = dir_description[["backingfile"]], backingpath = dir_description[["backingpath"]], descriptorfile = dir_description[["descriptorfile"]], binarydescriptor = FALSE, shared = TRUE) } #--- create_big_matrix_FUN <- function(nrow_0, colnames_0) { dir_description <- create_directory_FUN() # return bigmemory::filebacked.big.matrix( nrow = nrow_0, ncol = length(colnames_0), type = "double", init = NA, dimnames = list(NULL, colnames_0), separated = TRUE, backingfile = dir_description[["backingfile"]], backingpath = dir_description[["backingpath"]], descriptorfile = dir_description[["descriptorfile"]], binarydescriptor = FALSE) } #--- deepcopy_big_matrix_FUN <- function(big_matrix, col_0, row_0) { dir_description <- create_directory_FUN() big_matrix <- bigmemory::deepcopy( x = big_matrix, cols = col_0, rows = row_0, separated = TRUE, backingfile = dir_description[["backingfile"]], backingpath = dir_description[["backingpath"]], descriptorfile = dir_description[["descriptorfile"]], binarydescriptor = FALSE, shared = TRUE) options(bigmemory.allow.dimnames = TRUE) colnames(big_matrix) <- col_0 # return big_matrix } #--- parallel_lapply_FUN <- function( x, fun, varlist, text_to_parse = NA) { num_cpu <- parallel::detectCores() - 1 cl <- parallel::makeCluster(num_cpu) parallel::clusterExport( cl = cl, varlist = varlist, envir = sys.frame(sys.nframe() - 1)) if(is.na(text_to_parse) == T) {NULL} else { parallel::clusterExport( cl = cl, varlist = "text_to_parse", envir = sys.frame(sys.nframe())) parallel::clusterEvalQ( cl = cl, expr = eval(parse(text = text_to_parse))) } parallel_results <- parallel::parLapply( cl = cl, X = x, fun = compiler::cmpfun(fun)) names(parallel_results) <- x parallel::stopCluster(cl) # return parallel_results } #``` #------------------------------------------------------ # "The EAA main program, part 0, begin~" # --- # title: "EAA_part_0_single_census_interval_data_FUN" # author: "<EMAIL>" # date: "2019-05-10" # --- ## single_census_interval_data_FUN #```{r} single_census_interval_data_FUN <- function (big_array_data, census_interval) { big_array_data <- as.data.frame(big_array_data) for (i in 1 : ncol(big_array_data)) { big_array_data[, i] <- as.numeric(as.character(big_array_data[, i]))} index_col_names <- colnames(big_array_data)[ c(1, 2, census_interval + 2, census_interval + 3, 9, 10, census_interval + 10, census_interval + 15, census_interval + 20)] single_census_interval_data <- big_array_data[, index_col_names] colnames(single_census_interval_data) <- c("id_name", "sp_name", "dbh_1", "dbh_2", "gx", "gy", "growth_rate", "z_growth", "biomass_1") ### --- single_census_interval_data[, "z_growth"] <- NA ### !!! dbh_1_test <- single_census_interval_data[single_census_interval_data[, "dbh_1"] > 0, "dbh_1"] if(quantile(x = dbh_1_test, probs = 0.1, na.rm = T) < 10) { single_census_interval_data[, "dbh_1"] <- 10 * single_census_interval_data[, "dbh_1"] single_census_interval_data[, "dbh_2"] <- 10 * single_census_interval_data[, "dbh_2"] } else {NULL} ### --- single_census_interval_data[, "biomass_1"] <- pi * (single_census_interval_data[, "dbh_1"] / 2) ^ 2 ### !!! suppressWarnings( single_census_interval_data[, "growth_rate"] <- (log(single_census_interval_data[, "dbh_2"]) - log(single_census_interval_data[, "dbh_1"])) / 5 ) single_census_interval_data[, "delete"] <- 0L single_census_interval_data[ is.infinite(single_census_interval_data[, "gx"]) | is.infinite(single_census_interval_data[, "gy"]) | is.na(single_census_interval_data[, "gx"]) | is.na(single_census_interval_data[, "gy"]), "delete"] <- 1L single_census_interval_data[ is.na(single_census_interval_data[, "dbh_1"]) | (single_census_interval_data[, "dbh_1"] < 1), "dbh_1"] <- -2 single_census_interval_data[ is.na(single_census_interval_data[, "dbh_2"]) | (single_census_interval_data[, "dbh_2"] < 1), "dbh_2"] <- -2 single_census_interval_data[ single_census_interval_data[, "dbh_1"] <= 0 & single_census_interval_data[, "dbh_2"] <= 0, "delete"] <- 1L single_census_interval_data <- single_census_interval_data[ single_census_interval_data[, "delete"] != 1L, ] single_census_interval_data[single_census_interval_data[, "gx"] == 0, "gx"] <- 0.01 single_census_interval_data[single_census_interval_data[, "gy"] == 0, "gy"] <- 0.01 single_census_interval_data[ single_census_interval_data[, "dbh_1"] > 0 & single_census_interval_data[, "dbh_2"] > 0, "survival_born_diedS_diedL"] <- 1L single_census_interval_data[ single_census_interval_data[, "dbh_1"] <= 0 & single_census_interval_data[, "dbh_2"] > 0, "survival_born_diedS_diedL"] <- 2L dbh_died <- single_census_interval_data[ single_census_interval_data[, "dbh_1"] > 0 & single_census_interval_data[, "dbh_2"] <= 0, "dbh_1"] dbh_died_point <- quantile(x = dbh_died, probs = 0.5, na.rm = T) single_census_interval_data[ single_census_interval_data[, "dbh_1"] > 0 & single_census_interval_data[, "dbh_1"] < dbh_died_point & single_census_interval_data[, "dbh_2"] <= 0, "survival_born_diedS_diedL"] <- 3L single_census_interval_data[ single_census_interval_data[, "dbh_1"] >= dbh_died_point & single_census_interval_data[, "dbh_2"] <= 0, "survival_born_diedS_diedL"] <- 4L colnames_add <- c("is_edge", "gx_square_num", "gy_square_num", "gxy_square_name", paste("square_name", 1:8, sep = "_")) single_census_interval_data[, colnames_add] <- 0 single_census_interval_data <- single_census_interval_data[ order(single_census_interval_data[, "survival_born_diedS_diedL"]), ] single_census_interval_data[, "id_name"] <- 1:nrow(single_census_interval_data) rownames(single_census_interval_data) <- NULL # return as_big_matrix_FUN(x_matrix = single_census_interval_data) } #``` ## single_census_interval_data_add_square_FUN #```{r} single_census_interval_data_add_square_FUN <- function(single_census_interval_data, annulus_number, annulus_size){ # max_r <- (annulus_number * annulus_size / pi) ^ 0.5 #------- single_census_interval_data[, "gx_square_num"] <- as.integer(factor(ceiling( single_census_interval_data[, "gx"] / max_r) * max_r)); gc() single_census_interval_data[, "gy_square_num"] <- as.integer(factor(ceiling( single_census_interval_data[, "gy"] / max_r) * max_r)); gc() single_census_interval_data[, "gxy_square_name"] <- single_census_interval_data[, "gx_square_num"] * 10000L + single_census_interval_data[, "gy_square_num"]; gc() single_census_interval_data[, "square_name_1"] <- single_census_interval_data[, "gx_square_num"] * 10000L + (single_census_interval_data[, "gy_square_num"] + 1L); gc() single_census_interval_data[, "square_name_2"] <- single_census_interval_data[, "gx_square_num"] * 10000L + (single_census_interval_data[, "gy_square_num"] - 1L); gc() single_census_interval_data[, "square_name_3"] <- (single_census_interval_data[, "gx_square_num"] + 1L) * 10000L + single_census_interval_data[, "gy_square_num"]; gc() single_census_interval_data[, "square_name_4"] <- (single_census_interval_data[, "gx_square_num"] + 1L) * 10000L + (single_census_interval_data[, "gy_square_num"] + 1L); gc() single_census_interval_data[, "square_name_5"] <- (single_census_interval_data[, "gx_square_num"] + 1L) * 10000L + (single_census_interval_data[, "gy_square_num"] - 1L); gc() single_census_interval_data[, "square_name_6"] <- (single_census_interval_data[, "gx_square_num"] - 1L) * 10000L + single_census_interval_data[, "gy_square_num"]; gc() single_census_interval_data[, "square_name_7"] <- (single_census_interval_data[, "gx_square_num"] - 1L) * 10000L + (single_census_interval_data[, "gy_square_num"] + 1L); gc() single_census_interval_data[, "square_name_8"] <- (single_census_interval_data[, "gx_square_num"] - 1L) * 10000L + (single_census_interval_data[, "gy_square_num"] - 1L); gc() #------ edge_gx <- max(single_census_interval_data[, "gx"]) - max_r edge_gy <- max(single_census_interval_data[, "gy"]) - max_r index_is_edge <- bigmemory::mwhich( x = single_census_interval_data, cols = c("gx", "gx", "gy", "gy"), vals = list(max_r, edge_gx, max_r, edge_gy), comps = list("lt", "gt", "lt", "gt"), op = "OR") single_census_interval_data[index_is_edge, "is_edge"] <- 1L #return single_census_interval_data } #``` ### gls_add_z_growth_FUN # ```{r} gls_add_z_growth_FUN <- function(single_census_interval_data) { # gls_fun <- function(sp_dat_1) { gls0 <- nlme::gls( model = growth_rate ~ dbh_1 + I(dbh_1^2), data = sp_dat_1, weights = nlme::varExp(form = ~ dbh_1)) res_sd <- attr(resid(gls0), "std") res_value <- as.numeric(resid(gls0)) # res_value / res_sd } # fun_0 <- function(sp_data) { index <- is.na(sp_data[, "growth_rate"]) == F sp_dat_1 <- sp_data[index, ] z_growth <- rep(x = NA, times = nrow(sp_data)) if (nrow(sp_dat_1) >= 5) { ### --- z_try <- try(expr = gls_fun(sp_dat_1), silent = T) ### !!! if (inherits(z_try, "try-error") == F) { z_growth[index] <- z_try} else {NULL} } else {NULL} # z_growth } dat_split <- split( x = as.data.frame(single_census_interval_data[, c("dbh_1", "growth_rate")]), f = single_census_interval_data[, "sp_name"]) value_unsplit <- lapply(X = dat_split, FUN = fun_0) z_growth <- unsplit(value = value_unsplit, f = single_census_interval_data[, "sp_name"]) single_census_interval_data[, "z_growth"] <- z_growth #return single_census_interval_data } # ``` ## scale_add_z_growth_FUN # ```{r} scale_add_z_growth_FUN <- function(single_census_interval_data) { dbh_0 <- single_census_interval_data[ single_census_interval_data[, "survival_born_diedS_diedL"] == 1L, "dbh_1"] size_breakpoints <- quantile(x = dbh_0, probs = (0:11)/11, na.rm = T) ### --- scale_growth_fun <- function(sp_dat_1) { # dbh_1 <- sp_dat_1[, "dbh_1"] group_size <- cut(x = dbh_1, breaks = size_breakpoints, include.lowest = T, right = T) group_size <- as.factor(group_size) numbers <- tapply(X = dbh_1, INDEX = group_size, FUN = length) # growth_rate <- sp_dat_1[, "growth_rate"] group_means <- tapply(X = growth_rate, INDEX = group_size, FUN = mean) group_sds <- tapply(X = growth_rate, INDEX = group_size, FUN = sd) z_growth <- (growth_rate - group_means[group_size]) / group_sds[group_size] # return z_growth } ### !!! # fun_0 <- function(sp_data) { index <- is.na(sp_data[, "growth_rate"]) == F sp_dat_1 <- sp_data[index, ] z_growth <- rep(x = NA, times = nrow(sp_data)) if (nrow(sp_dat_1) >= 5) { ### --- z_try <- try(expr = scale_growth_fun(sp_dat_1), silent = T) ### !!! if (inherits(z_try, "try-error") == F) { z_growth[index] <- z_try} else {NULL} } else {NULL} # z_growth } dat_split <- split( x = as.data.frame(single_census_interval_data[, c("dbh_1", "growth_rate")]), f = single_census_interval_data[, "sp_name"]) value_unsplit <- lapply(X = dat_split, FUN = fun_0) ### --- z_growth <- unsplit(value = value_unsplit, f = single_census_interval_data[, "sp_name"]) single_census_interval_data[, "z_growth"] <- z_growth ### !!! #return single_census_interval_data } # ``` ## EAA_part_0_single_census_interval_data_FUN #```{r} EAA_part_0_single_census_interval_data_FUN <- function( big_array_data, census_interval, annulus_number, annulus_size, z_growth_model) { single_census_interval_data <- single_census_interval_data_FUN(big_array_data, census_interval) single_census_interval_data <- single_census_interval_data_add_square_FUN(single_census_interval_data, annulus_number, annulus_size) ### --- single_census_interval_data_add_z_growth_FUN <- switch(EXPR = z_growth_model, gls = gls_add_z_growth_FUN, scale = scale_add_z_growth_FUN) ### !!! single_census_interval_data <- single_census_interval_data_add_z_growth_FUN(single_census_interval_data) # return single_census_interval_data } #``` #--------------------------------------- # "The EAA main program, part 1, begin~" # --- # title: "EAA_part_1_focal_and_annular_id_pair_data_FUN" # author: "<EMAIL>" # date: "2019-05-10" # --- ## annular_id_names_of_focal_ids_FUN #```{r } annular_id_names_of_focal_ids_FUN <- function (single_census_interval_data, annulus_number, annulus_size) { # annular_ids_in_gxy_squares <- split( x = single_census_interval_data[, "id_name"], f = single_census_interval_data[, "gxy_square_name"]) gxy_square_names <- as.character(names(annular_ids_in_gxy_squares)) # is_survival <- single_census_interval_data[, "survival_born_diedS_diedL"] == 1L gxy_squares_of_focal_ids <- split( x = single_census_interval_data[ is_survival, grep(pattern = "square_name", x = colnames(single_census_interval_data))], f = single_census_interval_data[is_survival, "id_name"]) index_focal_ids <- as.integer(as.character(names(gxy_squares_of_focal_ids))) # gx_0 <- single_census_interval_data[, "gx"] gy_0 <- single_census_interval_data[, "gy"] max_r <- (annulus_number * annulus_size / pi) ^ 0.5 # fun <- function (index_focal_i) { index_gxy_squares <- gxy_square_names %in% gxy_squares_of_focal_ids[[index_focal_i]] annular_ids_of_focal_id <- unlist(x = annular_ids_in_gxy_squares[index_gxy_squares], use.names = FALSE) r <- ((gx_0[annular_ids_of_focal_id] - gx_0[index_focal_i]) ^ 2 + (gy_0[annular_ids_of_focal_id] - gy_0[index_focal_i]) ^ 2) ^ 0.5 # as.integer(annular_ids_of_focal_id[r <= max_r]) } x <- index_focal_ids varlist <- c("annular_ids_in_gxy_squares", "gxy_square_names", "gxy_squares_of_focal_ids", "gx_0", "gy_0", "max_r") annular_id_names_of_focal_ids <- parallel_lapply_FUN(x = x, fun = fun, varlist = varlist) names(annular_id_names_of_focal_ids) <- index_focal_ids # return annular_id_names_of_focal_ids } #``` ## focal_and_annular_id_pairs_FUN #```{r} focal_and_annular_id_pairs_FUN <- function ( annular_id_names_of_focal_ids, single_census_interval_data, annulus_number, annulus_size) { nrow_0 <- length(unlist(x = annular_id_names_of_focal_ids, recursive = TRUE)) colnames_0 <- c("focal_id", "annular_id", "focal_sp", "annular_sp", "annular_biomass", "annul_dist", "annul_interval", "f_gx", "f_gy", "a_gx", "a_gy", "phyl_dist", "phyl_interval", "phyl_dist_integer", "survival_born_diedS_diedL", "delete") focal_and_annular_id_pairs <- create_big_matrix_FUN(nrow_0, colnames_0) # focal_and_annular_id_pairs[, "focal_id"] <- as.integer( rep(x = as.integer(names(annular_id_names_of_focal_ids)), times = sapply(X = annular_id_names_of_focal_ids, FUN = length))); gc() focal_and_annular_id_pairs[, "annular_id"] <- as.integer( unlist(x = annular_id_names_of_focal_ids, use.names = FALSE)); gc() focal_and_annular_id_pairs[, "focal_sp"] <- single_census_interval_data[focal_and_annular_id_pairs[, "focal_id"], "sp_name"]; gc() focal_and_annular_id_pairs[, "annular_sp"] <- single_census_interval_data[focal_and_annular_id_pairs[, "annular_id"], "sp_name"]; gc() focal_and_annular_id_pairs[, "f_gx"] <- single_census_interval_data[focal_and_annular_id_pairs[, "focal_id"], "gx"]; gc() focal_and_annular_id_pairs[, "f_gy"] <- single_census_interval_data[focal_and_annular_id_pairs[, "focal_id"], "gy"]; gc() focal_and_annular_id_pairs[, "a_gx"] <- single_census_interval_data[focal_and_annular_id_pairs[, "annular_id"], "gx"]; gc() focal_and_annular_id_pairs[, "a_gy"] <- single_census_interval_data[focal_and_annular_id_pairs[, "annular_id"], "gy"]; gc() focal_and_annular_id_pairs[, "annul_dist"] <- ((focal_and_annular_id_pairs[, "f_gx"] - focal_and_annular_id_pairs[, "a_gx"]) ^ 2 + (focal_and_annular_id_pairs[, "f_gy"] - focal_and_annular_id_pairs[, "a_gy"]) ^ 2) ^ 0.5; gc() focal_and_annular_id_pairs[, "annular_biomass"] <- single_census_interval_data[ focal_and_annular_id_pairs[, "annular_id"], "biomass_1"]; gc() focal_and_annular_id_pairs[, "annul_interval"] <- as.integer(as.character( cut(x = focal_and_annular_id_pairs[, "annul_dist"], breaks = ((0 : annulus_number) * annulus_size / pi) ^ 0.5, labels = 1 : annulus_number, include.lowest = T, right = T))); gc() focal_and_annular_id_pairs[, "delete"] <- 0 # return focal_and_annular_id_pairs } #``` ## phyl_dists_of_paired_species_FUN #```{r} phyl_dists_of_paired_species_FUN <- function ( pairwise_table_scenario_data, min_sample_phyl_interval) { phyl_dists_of_paired_species <- as.data.frame(pairwise_table_scenario_data) names(phyl_dists_of_paired_species) <- c("focal_sp", "annular_sp", "phyl_dist") phyl_dists_of_paired_species[ phyl_dists_of_paired_species[, "focal_sp"] == phyl_dists_of_paired_species[, "annular_sp"], "phyl_dist"] <- 0L phyl_dists_of_paired_species[, "phyl_dist_integer"] <- as.integer( phyl_dists_of_paired_species[, "phyl_dist"] / min_sample_phyl_interval) * min_sample_phyl_interval phyl_dists_of_paired_species <- phyl_dists_of_paired_species[ sample(x = 1:nrow(phyl_dists_of_paired_species)), ] phyl_dists_of_paired_species <- phyl_dists_of_paired_species[ order(phyl_dists_of_paired_species[, "phyl_dist_integer"]), ] # return phyl_dists_of_paired_species } #``` ## id_pair_data_add_phyl_dist_FUN #```{r} id_pair_data_add_phyl_dist_FUN <- function ( focal_and_annular_id_pairs, single_census_interval_data, phyl_dists_of_paired_species) { index_match <- match( x = paste( as.integer(focal_and_annular_id_pairs[, "focal_sp"]), as.integer(focal_and_annular_id_pairs[, "annular_sp"])), table = paste( as.integer(phyl_dists_of_paired_species[, "focal_sp"]), as.integer(phyl_dists_of_paired_species[, "annular_sp"]))) focal_and_annular_id_pairs[, "phyl_dist"] <- phyl_dists_of_paired_species[index_match, "phyl_dist"] focal_and_annular_id_pairs[, "phyl_dist_integer"] <- phyl_dists_of_paired_species[index_match, "phyl_dist_integer"] focal_and_annular_id_pairs[ is.na(focal_and_annular_id_pairs[, "phyl_dist"]), "delete"] <- 1L # return focal_and_annular_id_pairs } #``` ## id_pair_data_add_phyl_interval_FUN #```{r} id_pair_data_add_phyl_interval_FUN <- function ( id_pair_data_add_phyl_dist, quantile_number) { index_delete <- which(id_pair_data_add_phyl_dist[, "delete"] != 1L) phyl_dist_temp <- id_pair_data_add_phyl_dist[index_delete, "phyl_dist_integer"] phyl_dist_temp <- phyl_dist_temp + round(x = rnorm(n = length(phyl_dist_temp), mean = 0, sd = 0.0001), digits = 10) phyl_dist_break_points <- sort(phyl_dist_temp)[ round(seq(from = 1, to = length(phyl_dist_temp), length.out = (quantile_number + 1)))] id_pair_data_add_phyl_dist[, "phyl_interval"] <- NA id_pair_data_add_phyl_dist[index_delete, "phyl_interval"] <- as.integer(as.character( cut(x = phyl_dist_temp, breaks = phyl_dist_break_points, labels = c(1:quantile_number - 1), include.lowest = T, right = T))) # return id_pair_data_add_phyl_dist } #``` ## id_pair_data_add_survival_state_FUN #```{r} id_pair_data_add_survival_state_FUN <- function ( id_pair_data_add_phyl_interval, single_census_interval_data) { id_pairs <- id_pair_data_add_phyl_interval survival_annular_ids <- single_census_interval_data[ single_census_interval_data[, "survival_born_diedS_diedL"] == 1L, "id_name"] id_pairs[id_pairs[, "annular_id"] %in% survival_annular_ids, "survival_born_diedS_diedL"] <- 1L # born_annular_ids <- single_census_interval_data[single_census_interval_data[, "survival_born_diedS_diedL"] == 2L, "id_name"] id_pairs[id_pairs[, "annular_id"] %in% born_annular_ids, "survival_born_diedS_diedL"] <- 2L # diedS_annular_ids <- single_census_interval_data[single_census_interval_data[, "survival_born_diedS_diedL"] == 3L, "id_name"] id_pairs[id_pairs[, "annular_id"] %in% diedS_annular_ids, "survival_born_diedS_diedL"] <- 3L # diedL_annular_ids <- single_census_interval_data[single_census_interval_data[, "survival_born_diedS_diedL"] == 4L, "id_name"] id_pairs[id_pairs[, "annular_id"] %in% diedL_annular_ids, "survival_born_diedS_diedL"] <- 4L # id_pairs[! (id_pairs[, "focal_id"] %in% survival_annular_ids), "delete"] <- 1L id_pairs[! (id_pairs[, "annular_id"] %in% c(diedS_annular_ids, diedL_annular_ids, born_annular_ids, survival_annular_ids)), "delete"] <- 1L id_pairs[is.na(id_pairs[, "annul_interval"]), "delete"] <- 1L id_pairs[is.na(id_pairs[, "phyl_interval"]), "delete"] <- 1L # return deepcopy_big_matrix_FUN(big_matrix = id_pairs, col_0 = colnames(id_pairs), row_0 = id_pairs[, "delete"] != 1L) } #``` ## unlink_dir_FUN #```{r} unlink_dir_FUN <- function(big_matirx_except) { big_mat_paths <- grep(pattern = "big_mat_[0-9]{4}_.*", x = dir(getwd()), value = T) path_except <- describe(big_matirx_except)@ description[["dirname"]] path_except <- gsub(pattern = ".*/([^/]*)/$", replacement = "\\1", x = path_except) big_mat_paths <- big_mat_paths[!big_mat_paths %in% path_except] gc() lapply(X = big_mat_paths, FUN = unlink, recursive = TRUE, force = TRUE) } #``` ## EAA_part_1_focal_and_annular_id_pair_data_FUN #```{r} EAA_part_1_focal_and_annular_id_pair_data_FUN <- function( single_census_interval_data, annulus_number, annulus_size, pairwise_table_scenario_data, quantile_number, min_sample_phyl_interval) { # part 1 annular_id_names_of_focal_ids <- annular_id_names_of_focal_ids_FUN( single_census_interval_data, annulus_number, annulus_size) focal_and_annular_id_pairs <- focal_and_annular_id_pairs_FUN( annular_id_names_of_focal_ids, single_census_interval_data, annulus_number, annulus_size) phyl_dists_of_paired_species <- phyl_dists_of_paired_species_FUN( pairwise_table_scenario_data, min_sample_phyl_interval) id_pair_data_add_phyl_dist <- id_pair_data_add_phyl_dist_FUN( focal_and_annular_id_pairs, single_census_interval_data, phyl_dists_of_paired_species) id_pair_data_add_phyl_interval <- id_pair_data_add_phyl_interval_FUN( id_pair_data_add_phyl_dist, quantile_number) id_pair_data <- id_pair_data_add_survival_state_FUN( id_pair_data_add_phyl_interval, single_census_interval_data) # unlink_dir_FUN(big_matirx_except = id_pair_data) # return id_pair_data } #``` #------------------------------------------------------ # "The new EAA program, part 2, begin~" # --- # title: "EAA_part_2_all_quantiles_statistics_data_FUN" # author: "<EMAIL>" # date: "2019-05-08" # --- ## full_big_matrix_FUN #```{r} full_big_matrix_FUN <- function (id_pair_data) { levels_expand_grid <- expand.grid( focal_id = sort(unique(id_pair_data[, "focal_id"])), annul_interval = sort(unique(id_pair_data[, "annul_interval"])), phyl_interval = sort(unique(id_pair_data[, "phyl_interval"]))) col_names <- c( "focal_id", "focal_sp", "focal_z_growth", "focal_diameter", "f_gx", "f_gy", "is_edge", "d_1", "d_2", "edge_coef", "is_small_diam", "dbh_interval", "biom_interval", "clust_number", "born_number", "diedS_number", "diedL_number", "annular_biomass", "annul_interval", "annul_dist", "phyl_interval", "phyl_dist") full_big_matrix <- create_big_matrix_FUN( nrow_0 = nrow(levels_expand_grid), colnames_0 = col_names) full_big_matrix[ , c("focal_id", "annul_interval", "phyl_interval")] <- as.matrix(levels_expand_grid[ , c("focal_id", "annul_interval", "phyl_interval")]) # return full_big_matrix } #``` ## biomass_clust_statistic_FUN #```{r} biomass_clust_statistic_FUN <- function ( id_pair_data = id_pair_data) { which_survival <- bigmemory::mwhich( x = id_pair_data, cols = "survival_born_diedS_diedL", vals = 1L, comps = "eq") survival_id_pairs <- deepcopy_big_matrix_FUN( big_matrix = id_pair_data, col_0 = c("focal_id", "annul_interval", "phyl_interval", "annular_biomass"), row_0 = which_survival) X = bigtabulate::bigsplit( x = survival_id_pairs, ccols = c("focal_id", "annul_interval", "phyl_interval"), splitcol="annular_biomass") gc() annular_biomass_statistic <- sapply(X = X, FUN = sum) gc() annular_clust_statistic <- bigtabulate::bigtable( x = survival_id_pairs, ccols = c("focal_id", "annul_interval", "phyl_interval")) gc() names_split_df <- do.call( what = rbind, args = strsplit(x = names(annular_biomass_statistic), split = ":")) biomass_clust_statistic <- data.frame( annular_biomass = as.numeric(annular_biomass_statistic), clust_number = as.integer(annular_clust_statistic), focal_id = as.integer(names_split_df[, 1]), annul_interval = as.integer(names_split_df[, 2]), phyl_interval = as.integer(names_split_df[, 3]), id_INDEX = -2, annul_INDEX = -2, phyl_INDEX = -2) # return as_big_matrix_FUN(x_matrix = biomass_clust_statistic) } #``` ## born_statistic_FUN (hide) #```{r} born_statistic_FUN <- function ( id_pair_data = id_pair_data) { which_born <- bigmemory::mwhich( x = id_pair_data, cols = "survival_born_diedS_diedL", vals = 2L, comps = "eq") born_id_pairs <- deepcopy_big_matrix_FUN( big_matrix = id_pair_data, col_0 = c("focal_id", "annul_interval", "phyl_interval"), row_0 = which_born) annular_born_statistic <- bigtabulate::bigtable( x = born_id_pairs, ccols = c("focal_id", "annul_interval", "phyl_interval")) names(dimnames(annular_born_statistic)) <- c("focal_id", "annul_interval", "phyl_interval") gc() focal_id <- as.integer( dimnames(annular_born_statistic)[["focal_id"]])[ apply(X = annular_born_statistic, MARGIN = 3, FUN = row)] annul_interval <- as.integer( dimnames(annular_born_statistic)[["annul_interval"]])[ apply(X = annular_born_statistic, MARGIN = 3, FUN = col)] phyl_interval <- as.integer( dimnames(annular_born_statistic)[["phyl_interval"]])[ t(apply(X = annular_born_statistic, MARGIN = 1, FUN = col))] born_statistic <- data.frame( born_number = as.integer(annular_born_statistic), focal_id = focal_id, annul_interval = annul_interval, phyl_interval = phyl_interval, id_INDEX = -2, annul_INDEX = -2, phyl_INDEX = -2) # return as_big_matrix_FUN(x_matrix = born_statistic) } #``` ## died_statistic_FUN (hide) #```{r} died_statistic_FUN <- function (id_pair_data, val = c(3, 4)[1]) { which_died <- bigmemory::mwhich( x = id_pair_data, cols = "survival_born_diedS_diedL", vals = val, comps = "eq") died_id_pairs <- deepcopy_big_matrix_FUN( big_matrix = id_pair_data, col_0 = c("focal_id", "annul_interval", "phyl_interval"), row_0 = which_died) annular_died_statistic <- bigtabulate::bigtable( x = died_id_pairs, ccols = c("focal_id", "annul_interval", "phyl_interval")) names(dimnames(annular_died_statistic)) <- c("focal_id", "annul_interval", "phyl_interval") gc() focal_id <- as.integer(dimnames(annular_died_statistic)[["focal_id"]])[ apply(X = annular_died_statistic, MARGIN = 3, FUN = row)] annul_interval <- as.integer(dimnames(annular_died_statistic)[["annul_interval"]])[ apply(X = annular_died_statistic, MARGIN = 3, FUN = col)] phyl_interval <- as.integer(dimnames(annular_died_statistic)[["phyl_interval"]])[ t(apply(X = annular_died_statistic, MARGIN = 1, FUN = col))] died_statistic <- data.frame( died_number = as.integer(annular_died_statistic), focal_id = focal_id, annul_interval = annul_interval, phyl_interval = phyl_interval, id_INDEX = -2, annul_INDEX = -2, phyl_INDEX = -2) if(val == 3) { colnames(died_statistic)[colnames(died_statistic) == "died_number"] <- "diedS_number" } else { if(val == 4) { colnames(died_statistic)[colnames(died_statistic) == "died_number"] <- "diedL_number" } else { print("'val' must be 3 or 4") } } # return as_big_matrix_FUN(x_matrix = died_statistic) } #``` ## assign_value_FUN #```{r} assign_value_FUN <- function( full_big_matrix = full_big_matrix, sub_matrix = biomass_clust_statistic, value_names = c("annular_biomass", "clust_number")) { mpermute(x = full_big_matrix, cols = c("phyl_interval", "annul_interval", "focal_id")) full_big_matrix[, value_names] <- 0L grand_id_levels <- as.integer(sort(unique(full_big_matrix[, "focal_id"]))) grand_annul_levels <- as.integer(sort(unique(full_big_matrix[, "annul_interval"]))) grand_phyl_levels <- as.integer(sort(unique(full_big_matrix[, "phyl_interval"]))) len_id <- length(grand_id_levels) len_annul <- length(grand_annul_levels) len_phyl <- length(grand_phyl_levels) gc() sub_matrix[, "id_INDEX"] <- match( x = as.integer(sub_matrix[, "focal_id"]), table = grand_id_levels) gc() sub_matrix[, "annul_INDEX"] <- match( x = as.integer(sub_matrix[, "annul_interval"]), table = grand_annul_levels) gc() sub_matrix[, "phyl_INDEX"] <- match( x = as.integer(sub_matrix[, "phyl_interval"]), table = grand_phyl_levels) gc() INDEX_matrix <- (sub_matrix[, "phyl_INDEX"] - 1) * (len_annul * len_id) + (sub_matrix[, "annul_INDEX"] - 1) * len_id + sub_matrix[, "id_INDEX"] gc() full_big_matrix[INDEX_matrix, value_names] <- sub_matrix[, value_names] gc() # return full_big_matrix } #``` ## add_biomass_interval_FUN #```{r} add_biomass_interval_FUN <- function(full_big_matrix, small_diameter_point) { # annular_biomasses_temp <- full_big_matrix[, "annular_biomass"] + rnorm(n = nrow(full_big_matrix), mean = 0.001, sd = 0.001) biomass_quantiles <- quantile( x = annular_biomasses_temp[ annular_biomasses_temp >= pi * (small_diameter_point / 2) ^ 2], probs = c(0, 0.2, 0.4, 0.6, 0.8, 1)) biom_interval <- as.character( cut(x = annular_biomasses_temp, breaks = biomass_quantiles, labels = 1:5, include.lowest = T, right = T)) ### --- biom_interval[ annular_biomasses_temp < pi * (small_diameter_point / 2) ^ 2 ] <- 0 ### !!! full_big_matrix[, "biom_interval"] <- biom_interval # return full_big_matrix } #``` ## add_dbh_interval_FUN #```{r} add_dbh_interval_FUN <- function(full_big_matrix) { id_diameters <- full_big_matrix[, "focal_diameter"] + rnorm(n = nrow(full_big_matrix), mean = 0.001, sd = 0.001) diameter_quantiles_2 <- quantile(x = id_diameters, probs = c(0, 0.25, 0.5, 0.75, 1)) dbh_interval <- as.character( cut(x = id_diameters, breaks = diameter_quantiles_2, labels = 1:4, include.lowest = T, right = T)) full_big_matrix[, "dbh_interval"] <- dbh_interval # return full_big_matrix } #``` ## calculate_edge_correction_coefficient_FUN #```{r} calculate_edge_correction_coefficient_FUN <- function( full_big_matrix = full_big_matrix, id_pair_data = id_pair_data, single_census_interval_data = single_census_interval_data){ mean_annul_dist <- tapply( X = id_pair_data[, "annul_dist"], INDEX = id_pair_data[, "annul_interval"], FUN = mean, na.rm = T) full_big_matrix[, "annul_dist"] <- mean_annul_dist[ as.integer(as.factor( full_big_matrix[, "annul_interval"]))] gc() full_big_matrix[, "f_gx"] <- single_census_interval_data[ match(x = full_big_matrix[, "focal_id"], table = single_census_interval_data[, "id_name"]), "gx"] gc() full_big_matrix[, "f_gy"] <- single_census_interval_data[ match(x = full_big_matrix[, "focal_id"], table = single_census_interval_data[, "id_name"]), "gy"] gc() full_big_matrix[, "is_edge"] <- single_census_interval_data[ match(x = full_big_matrix[, "focal_id"], table = single_census_interval_data[, "id_name"]), "is_edge"] gc() #--- full_big_matrix[, "edge_coef"] <- 1 index_1 <- full_big_matrix[, "is_edge"] == 1 gx_max <- max(full_big_matrix[, "f_gx"], na.rm = T) index_2 <- full_big_matrix[index_1, "f_gx"] > c(gx_max / 2) full_big_matrix[index_1, "d_1"][index_2] <- gx_max - full_big_matrix[index_1, "f_gx"][index_2] full_big_matrix[index_1, "d_1"][! index_2] <- full_big_matrix[index_1, "f_gx"][! index_2] gc() # gy_max <- max(full_big_matrix[, "f_gy"], na.rm = T) index_2 <- full_big_matrix[index_1, "f_gy"] > c(gy_max / 2) full_big_matrix[index_1, "d_2"][index_2] <- gy_max - full_big_matrix[index_1, "f_gy"][index_2] full_big_matrix[index_1, "d_2"][! index_2] <- full_big_matrix[index_1, "f_gy"][! index_2] gc() #--- index_3 <- (full_big_matrix[index_1, "d_2"] > full_big_matrix[index_1, "annul_dist"]) & (full_big_matrix[index_1, "d_1"] > full_big_matrix[index_1, "annul_dist"]) full_big_matrix[index_1, "is_edge"][index_3] <- 0 index_4 <- (full_big_matrix[index_1, "d_2"] < full_big_matrix[index_1, "annul_dist"]) & (full_big_matrix[index_1, "d_1"] < full_big_matrix[index_1, "annul_dist"]) full_big_matrix[index_1, "is_edge"][index_4] <- 2 gc() #--- index_1 <- full_big_matrix[, "is_edge"] == 1 index_2 <- full_big_matrix[index_1, "d_1"] > full_big_matrix[index_1, "d_2"] full_big_matrix[index_1, "d_1"][index_2] <- full_big_matrix[index_1, "d_2"][index_2] # x <- full_big_matrix[index_1, "d_1"] / full_big_matrix[index_1, "annul_dist"] alpha <- 2 * pi - 2 * acos(x) arc_length <- alpha * full_big_matrix[index_1, "annul_dist"] circumference <- pi * 2 * full_big_matrix[index_1, "annul_dist"] full_big_matrix[index_1, "edge_coef"] <- arc_length / circumference # index_3 <- full_big_matrix[, "is_edge"] == 2 # In order to avoid over-correction, the smallest correction coefficient is limited to 0.5. full_big_matrix[index_3, "edge_coef"] <- 0.5 gc() # # return full_big_matrix } #``` ## all_quantiles_statistics_data_FUN #```{r} all_quantiles_statistics_data_FUN <- function( full_big_matrix = full_big_matrix, biomass_clust_statistic = biomass_clust_statistic, born_statistic = born_statistic, diedS_statistic = diedS_statistic, diedL_statistic = diedL_statistic, single_census_interval_data = single_census_interval_data, id_pair_data = id_pair_data) { full_big_matrix <- calculate_edge_correction_coefficient_FUN( full_big_matrix = full_big_matrix, id_pair_data = id_pair_data, single_census_interval_data = single_census_interval_data) full_big_matrix <- assign_value_FUN( full_big_matrix = full_big_matrix, sub_matrix = biomass_clust_statistic, value_names = c("annular_biomass", "clust_number")) full_big_matrix <- assign_value_FUN( full_big_matrix = full_big_matrix, sub_matrix = born_statistic, value_names = c("born_number")) full_big_matrix <- assign_value_FUN( full_big_matrix = full_big_matrix, sub_matrix = diedS_statistic, value_names = c("diedS_number")) full_big_matrix <- assign_value_FUN( full_big_matrix = full_big_matrix, sub_matrix = diedL_statistic, value_names = c("diedL_number")) for(i in c("annular_biomass", "clust_number", "born_number", "diedS_number", "diedL_number")) { full_big_matrix[, i] <- full_big_matrix[, i] / full_big_matrix[, "edge_coef"] } gc() full_big_matrix[, "focal_sp"] <- single_census_interval_data[ match(x = full_big_matrix[, "focal_id"], table = single_census_interval_data[, "id_name"]), "sp_name"] full_big_matrix[, "focal_diameter"] <- single_census_interval_data[ match(x = full_big_matrix[, "focal_id"], table = single_census_interval_data[, "id_name"]), "dbh_1"] full_big_matrix[, "focal_z_growth"] <- single_census_interval_data[ match(x = full_big_matrix[, "focal_id"], table = single_census_interval_data[, "id_name"]), "z_growth"] gc() ### --- small_diameter_point <- quantile( x = full_big_matrix[, "focal_diameter"], probs = 0.4) ### !!! full_big_matrix[, "is_small_diam"] <- as.integer( full_big_matrix[, "focal_diameter"] <= small_diameter_point) full_big_matrix <- add_dbh_interval_FUN( full_big_matrix) mean_phyl_dist <- tapply( X = id_pair_data[, "phyl_dist"], INDEX = id_pair_data[, "phyl_interval"], FUN = mean, na.rm = T) full_big_matrix[, "phyl_dist"] <- mean_phyl_dist[ as.integer(as.factor(full_big_matrix[, "phyl_interval"]))] gc() full_big_matrix <- add_biomass_interval_FUN( full_big_matrix, small_diameter_point) gc() # return full_big_matrix } #``` ## EAA_part_2_all_quantiles_statistics_data_FUN_0 #```{r} EAA_part_2_all_quantiles_statistics_data_FUN_0 <- function(id_pair_data_0, single_census_interval_data) { # part 2 full_big_matrix <- full_big_matrix_FUN(id_pair_data_0) biomass_clust_statistic <- biomass_clust_statistic_FUN(id_pair_data_0) born_statistic <- born_statistic_FUN(id_pair_data_0) diedS_statistic <- died_statistic_FUN(id_pair_data_0, val = 3) diedL_statistic <- died_statistic_FUN(id_pair_data_0, val = 4) statistic_data <- all_quantiles_statistics_data_FUN( full_big_matrix, biomass_clust_statistic, born_statistic, diedS_statistic, diedL_statistic, single_census_interval_data, id_pair_data_0) # return statistic_data } #``` # reduce_memory_FUN_0 #```{r } reduce_memory_FUN_0 <- function( id_pair_data, single_census_interval_data, n_break = (1:5)[1]){ # focal_ids <- sort(unique(id_pair_data[, "focal_id"])) len <- length(focal_ids) n_break <- round(n_break) focal_ids_split <- split( x = focal_ids, f = rep( x = 1: n_break, each = ceiling(length(focal_ids)/n_break), length.out = length(focal_ids))) results_list <- lapply( X = focal_ids_split, FUN = function(i){ row_0 <- bigmemory::mwhich( x = id_pair_data, cols = "focal_id", vals = c(min(i), max(i)), comps = c("ge", "le"), op = "AND") id_pair_data_0 <- deepcopy_big_matrix_FUN( big_matrix = id_pair_data, col_0 = colnames(id_pair_data), row_0 = row_0) results <- EAA_part_2_all_quantiles_statistics_data_FUN_0( id_pair_data_0, single_census_interval_data) # bigmemory::describe(results) }) # return results_list } #``` ## EAA_part_2_all_quantiles_statistics_data_FUN #```{r} EAA_part_2_all_quantiles_statistics_data_FUN <- function( id_pair_data, single_census_interval_data, max_matrix_row_limit){ if(max_matrix_row_limit < 1e7) { warning( "'max_matrix_row_limit' should be >= 1e7, ", "which was converted to 1e7.") max_matrix_row_limit = 1e7 } else {NULL} nrow_id_data <- nrow(id_pair_data) n_break <- ceiling(nrow_id_data / max_matrix_row_limit) if(n_break > 5){n_break = 5}else{NULL} results_list <- reduce_memory_FUN_0( id_pair_data, single_census_interval_data, n_break) totalRows <- lapply(X = results_list, FUN = function(list_i){ list_i@description[["totalRows"]]}) nrow_0 <- sum(unlist(totalRows), na.rm = T) colnames_0 <- results_list[[1]]@description[["colNames"]] statistic_data <- create_big_matrix_FUN(nrow_0, colnames_0) # row_cumsum <- c(0, cumsum(totalRows)) for(i in 1:length(totalRows)) { list_i <- results_list[[i]] sub_matrix <- attach.big.matrix(list_i) index_row <- (row_cumsum[i] + 1): row_cumsum[i+1] for(j in colnames(sub_matrix)){ statistic_data[index_row, j] <- sub_matrix[, j] gc() } } unlink_dir_FUN(big_matirx_except = statistic_data) # return statistic_data } #``` # ----------------------------------------- # "EAA main program, part 3, begin~" # --- # title: "EAA_part_3_growth_results_FUN" # author: "<EMAIL>" # date: "2019-05-10" # --- ## as_data_frame_FUN #```{r} as_data_frame_FUN <- function(real_growths_of_all_quant_pairs) { name_length <- sapply(X = real_growths_of_all_quant_pairs, FUN = length) names <- rep(x = names(name_length), times = as.numeric(name_length)) biom_interval <- unlist(lapply( X = real_growths_of_all_quant_pairs, FUN = names), use.names = F) annul_interval <- gsub(pattern = "([0-9]{1,2}):[0-9]{1,2}", replacement = "\\1", x = names) phyl_interval <- gsub(pattern = "[0-9]{1,2}:([0-9]{1,2})", replacement = "\\1", x = names) growth <- unlist(x = real_growths_of_all_quant_pairs, use.names = F) results <- data.frame( annul_interval = as.integer(annul_interval), phyl_interval = as.integer(phyl_interval), biom_interval = as.integer(biom_interval), growth = as.numeric(growth)) expand_levels_FUN <- function(results) { expand_data <- expand.grid( annul_interval = unique(results[, "annul_interval"]), phyl_interval = unique(results[, "phyl_interval"]), biom_interval = unique(results[, "biom_interval"])) if(nrow(results) == nrow(expand_data)) { # results } else { index <- match( x = paste(results[, "annul_interval"], results[, "phyl_interval"], results[, "biom_interval"]), table = paste(expand_data[, "annul_interval"], expand_data[, "phyl_interval"], expand_data[, "biom_interval"])) expand_data[index, "growth"] <- results[, "growth"] # expand_data } } # return expand_levels_FUN(results) } #``` ## calculate_real_growth_FUN #```{r} calculate_real_growth_FUN <- function(col_diam_small = "is_small_diam") { new_data_s <- bigmemory::attach.big.matrix(describe_data) row_0 <- bigmemory::mwhich( x = new_data_s, cols = c("focal_z_growth", col_diam_small), vals = list(NA, 1), comps = list("neq", "eq"), op = "AND") data_temp <- deepcopy_big_matrix_FUN( big_matrix = new_data_s, col_0 = c("focal_z_growth", col_diam_small, "biom_interval", "annul_interval", "phyl_interval"), row_0 = row_0) focal_growth_split <- bigtabulate::bigsplit( x = data_temp, ccols = c("annul_interval", "phyl_interval"), splitcol = c("focal_z_growth")) biom_interval_split <- bigtabulate::bigsplit( x = data_temp, ccols = c("annul_interval", "phyl_interval"), splitcol = c("biom_interval")) x <- names(focal_growth_split) fun <- function(name_i) { tapply(X = focal_growth_split[[name_i]], INDEX = biom_interval_split[[name_i]], FUN = mean, na.rm = T) } real_growths_of_all_quant_pairs <- lapply(X = x, FUN = fun) names(real_growths_of_all_quant_pairs) <- x real_growth_data <- as_data_frame_FUN(real_growths_of_all_quant_pairs) gc() # return real_growth_data } #``` ## sample_within_sp_FUN (hide) #```{r} sample_within_sp_FUN <- function(focal_sp){ index_split <- split(x = 1:length(focal_sp), f = focal_sp) set.seed(seed = NULL) value_split <- lapply( X = index_split, FUN = function(x){ if (length(x) == 1) {x} else {sample(x)}}) index_sample <- unsplit(value = value_split, f = focal_sp) # return index_sample } #``` ## statistic_data_add_shuffled_diams_FUN #```{r} statistic_data_add_shuffled_diams_FUN <- function ( statistic_data, shuffled_times, shuffled_col = "is_small_diam") { big_matrix_add_shuffled <- create_big_matrix_FUN( nrow_0 = nrow(statistic_data), colnames_0 = c(colnames(statistic_data), paste("shuffled", 1:shuffled_times, sep = "_"))) big_matrix_add_shuffled[, colnames(statistic_data)] <- statistic_data[, colnames(statistic_data)] focal_sp <- big_matrix_add_shuffled[, "focal_sp"] gc() # x <- 1:shuffled_times fun <- function(i) { big_matrix_add_shuffled <- bigmemory::attach.big.matrix(describe_data) big_matrix_add_shuffled[, paste("shuffled", i, sep = "_")] <- big_matrix_add_shuffled[sample_within_sp_FUN(focal_sp), shuffled_col] gc() # return NULL } describe_data <- bigmemory::describe(big_matrix_add_shuffled) varlist <- c("describe_data", "sample_within_sp_FUN", "focal_sp", "shuffled_col") text_to_parse <- "require(bigmemory)" parallel_lapply_FUN( x = x, fun = fun, varlist = varlist, text_to_parse = text_to_parse) # return big_matrix_add_shuffled } #``` ## relative_growth_FUN #```{r} relative_growth_FUN <- function(real_growth_data) { dat_0 <- real_growth_data[ real_growth_data[, "biom_interval"] == 0, ] dat_1 <- real_growth_data INDEX <- match( x = paste(dat_1[, "annul_interval"], dat_1[, "phyl_interval"], sep = "_"), table = paste(dat_0[, "annul_interval"], dat_0[, "phyl_interval"], sep = "_")) dat_1[, "growth_0"] <- dat_0[INDEX, "growth"] dat_1[, "relative_value"] <- dat_1[, "growth"] - dat_1[, "growth_0"] # return dat_1[, c("annul_interval", "phyl_interval", "biom_interval", "relative_value")] } #``` ## real_results_add_shuffled_sd_FUN #```{r} real_results_add_shuffled_sd_FUN_1 <- function( results_list) { real_results <- results_list[[1]] growth_results <- real_results # relative_results_list <- lapply( X = results_list, FUN = relative_growth_FUN) shuffled_data <- do.call( what = cbind, args = relative_results_list[-1]) shuffled_data_1 <- shuffled_data[ grep(pattern = "relative_value", x = colnames(shuffled_data))] # growth_results[, "sd_shuffled"] <- apply( X = shuffled_data_1, MARGIN = 1, FUN = sd, na.rm = T) growth_results[, "mean_shuffled"] <- apply( X = shuffled_data_1, MARGIN = 1, FUN = mean, na.rm = T) growth_results[, "relative_value"] <- relative_results_list[[1]][, "relative_value"] colnames(growth_results)[ colnames(growth_results) == "growth"] <- "real_value" # return growth_results } #``` ## EAA_part_3_growth_results_FUN_0 #```{r} EAA_part_3_growth_results_FUN_0 <- function( statistic_data_0, shuffled_times) { new_data_s <- statistic_data_add_shuffled_diams_FUN( statistic_data_0, shuffled_times, shuffled_col = "is_small_diam") x <- c("is_small_diam", grep(pattern = "shuffled", x = colnames(new_data_s), value = T)) fun <- calculate_real_growth_FUN describe_data <- bigmemory::describe(new_data_s) varlist <- c("describe_data", "as_data_frame_FUN", "deepcopy_big_matrix_FUN", "create_directory_FUN") text_to_parse <- "require(bigmemory)" results_list <- parallel_lapply_FUN( x = x, fun = fun, varlist = varlist, text_to_parse = text_to_parse) results <- real_results_add_shuffled_sd_FUN_1(results_list) results[, "data_type"] <- "growth" unlink_dir_FUN(big_matirx_except = statistic_data_0) # return results } #``` ## reduce_memory_consumption_FUN #```{r} reduce_memory_consumption_FUN <- function( FUN_0, statistic_data, shuffled_times, n_running_speed) { annul_levels <- unique(statistic_data[, "annul_interval"]) len <- length(annul_levels) n_running_speed <- round(n_running_speed) warning_txt <- "'n_running_speed' should be >= 1 and <= 'annulus_number', " if(n_running_speed > length(annul_levels)) { warning(warning_txt, sprintf(fmt = "and which has been converted to %s.", len)) n_running_speed <- len } else { if(n_running_speed < 1){ warning(warning_txt, "and which has been converted to 1.") n_running_speed <- 1 } else {NULL} } annul_levels_split <- split( x = annul_levels, f = rep( x = 1:ceiling(length(annul_levels) / n_running_speed), each = n_running_speed, length.out = length(annul_levels))) results_list <- lapply( X = annul_levels_split, FUN = function(i){ row_0 <- bigmemory::mwhich( x = statistic_data, cols = "annul_interval", vals = c(min(i), max(i)), comps = c("ge", "le"), op = "AND") statistic_data_0 <- deepcopy_big_matrix_FUN(big_matrix = statistic_data, col_0 = colnames(statistic_data), row_0 = row_0) results <- FUN_0(statistic_data_0 = statistic_data_0, shuffled_times = shuffled_times) unlink_dir_FUN(big_matirx_except = statistic_data) # results }) results <- do.call(what = rbind, args = results_list) unlink_dir_FUN(big_matirx_except = statistic_data) # return results } #``` ## EAA_part_3_growth_results_FUN #```{r} EAA_part_3_growth_results_FUN <- function( statistic_data, shuffled_times, n_running_speed) { growth_results <- reduce_memory_consumption_FUN( FUN_0 = EAA_part_3_growth_results_FUN_0, statistic_data, shuffled_times, n_running_speed) colnames(growth_results)[ grep(pattern = "biom_interval", x = colnames(growth_results))] <- "condition" # return growth_results } #``` #----------------------------------- # "EAA main program, part 4, begin~" # --- # title: "EAA main program, part 4" # subtitle: "EAA_part_4_born_clust_died_results_FUN" # author: "<EMAIL>" # date: "2019-05-10" # --- ## split_sum_FUN #```{r} list_to_data_frame_FUN <- function(x_split_sum) { names_strsplit <- strsplit(x = names(x_split_sum), split = ":") results <- as.data.frame( do.call(what = rbind, args = names_strsplit)) colnames(results) <- c("annul_interval", "phyl_interval", "dbh_interval") results[, "value"] <- as.numeric(as.character(x_split_sum)) # return results } #---------------------- split_stat_FUN <- function( new_data_s, col_dbh_interval = "dbh_interval", splitcol = "born_number", fun = mean) { x_split <- bigtabulate::bigsplit( x = new_data_s, ccols = c("annul_interval", "phyl_interval", col_dbh_interval), splitcol = splitcol) x_split_stat <- lapply(X = x_split, FUN = fun, na.rm = T) x_split_stat <- list_to_data_frame_FUN(x_split_stat) x_split_stat[, "data_type"] <- strsplit(x = splitcol, split = "_")[[1]][1] # return x_split_stat } #``` ## born_clust_died_rates_FUN #```{r} born_clust_died_rates_FUN <- function(col_dbh_interval = "dbh_interval") { new_data_s <- bigmemory::attach.big.matrix(describe_data) mean_born_abun <- split_stat_FUN( new_data_s, col_dbh_interval = col_dbh_interval, splitcol = "born_number", fun = mean) mean_clust_abun <- split_stat_FUN( new_data_s, col_dbh_interval = col_dbh_interval, splitcol = "clust_number", fun = mean) mean_diedS_abun <- split_stat_FUN( new_data_s, col_dbh_interval = col_dbh_interval, splitcol = "diedS_number", fun = mean) mean_diedL_abun <- split_stat_FUN( new_data_s, col_dbh_interval = col_dbh_interval, splitcol = "diedL_number", fun = mean) mean_diedS_abun[, "value"] <- mean_diedS_abun[, "value"] / (mean_diedS_abun[, "value"] + mean_clust_abun[, "value"]) mean_diedL_abun[, "value"] <- mean_diedL_abun[, "value"] / (mean_diedL_abun[, "value"] + mean_clust_abun[, "value"]) results <- rbind(mean_born_abun, mean_clust_abun, mean_diedS_abun, mean_diedL_abun) # return results } #``` ## real_results_add_shuffled_sd_FUN #```{r} real_results_add_shuffled_sd_FUN_2 <- function( results_list) { real_results <- results_list[[1]] shuffled_data <- do.call(what = cbind, args = results_list[-1]) shuffled_data_1 <- shuffled_data[ grep(pattern = "value", x = colnames(shuffled_data))] real_results[, "sd_shuffled"] <- apply( X = shuffled_data_1, MARGIN = 1, FUN = sd, na.rm = T) real_results[, "mean_shuffled"] <- apply( X = shuffled_data_1, MARGIN = 1, FUN = mean, na.rm = T) real_results[, "relative_value"] <- real_results[, "value"] - real_results[, "mean_shuffled"] colnames(real_results)[ colnames(real_results) == "value"] <- "real_value" # return real_results } #``` ## EAA_part_4_born_clust_died_results_FUN_0 #```{r} EAA_part_4_born_clust_died_results_FUN_0 <- function( statistic_data_0, shuffled_times) { new_data_s <- statistic_data_add_shuffled_diams_FUN( statistic_data_0, shuffled_times, shuffled_col = "dbh_interval") x <- c("dbh_interval", grep(pattern = "shuffled", x = colnames(new_data_s), value = T)) fun <- born_clust_died_rates_FUN describe_data <- bigmemory::describe(new_data_s) varlist <- c( "describe_data", "split_stat_FUN", "list_to_data_frame_FUN") text_to_parse <- "require(bigmemory)" results_list <- parallel_lapply_FUN( x = x, fun = fun, varlist = varlist, text_to_parse = text_to_parse) results <- real_results_add_shuffled_sd_FUN_2(results_list) unlink_dir_FUN(big_matirx_except = statistic_data_0) # return results } #``` ## EAA_part_4_born_clust_died_results_FUN #```{r} EAA_part_4_born_clust_died_results_FUN <- function( statistic_data, shuffled_times, n_running_speed) { born_clust_died_results <- reduce_memory_consumption_FUN( FUN_0 = EAA_part_4_born_clust_died_results_FUN_0, statistic_data, shuffled_times, n_running_speed) colnames(born_clust_died_results)[ grep(pattern = "dbh_interval", x = colnames(born_clust_died_results))] <- "condition" # return born_clust_died_results } #``` #---------------------------- # "EAA main program, part 5, begin~" # --- # title: "summary_sp_pairs_FUN" # author: "<EMAIL>" # date: "2019-05-10" # --- #```{r } table_sp_pairs_annul_1_FUN <- function( id_pair_data, data_type = c("survival", "born", "diedS", "diedL")[1]) { mpermute(x = id_pair_data, cols= c("survival_born_diedS_diedL", "annul_interval")) val <- switch( EXPR = data_type, survival = 1, born = 2, diedS = 3, diedL = 4, stop("'data_type' must be one of 'survival', 'born', 'diedS', 'diedL'.")) which_survival <- mwhich( x = id_pair_data, cols = c("survival_born_diedS_diedL", "annul_interval"), vals = c(val, 1), comps = "eq", op = "AND") survival_id_pairs <- sub.big.matrix( x = id_pair_data, firstRow = min(which_survival), lastRow = max(which_survival)) gc() # return bigtabulate::bigtable( x = survival_id_pairs, ccols = c("focal_sp", "annular_sp", "phyl_interval")) } ### data_frame_top_10_FUN <- function( sp_pairs = sp_pairs){ sp_pairs <- as.array(sp_pairs) index_1_2_row <- apply(X = sp_pairs, MARGIN = 3, FUN = row) index_1_2_col <- apply(X = sp_pairs, MARGIN = 3, FUN = col) index_3 <- col(index_1_2_row) dat_new <- data.frame( focal_sp = dimnames(sp_pairs)[[1]][index_1_2_row], annular_sp = dimnames(sp_pairs)[[2]][index_1_2_col], phyl_interval = dimnames(sp_pairs)[[3]][index_3], abundance = as.integer(sp_pairs), stringsAsFactors = F) dat_split <- split(x = dat_new[, "abundance"], f = dat_new[, "phyl_interval"]) value_unsplit <- lapply(X = dat_split, FUN = function(list_i) { value_limit <- ifelse( test = length(list_i) >= 10, yes = sort(x = list_i, decreasing = T)[10], no = 0) is_top_10 <- list_i > value_limit # is_top_10 }) index_is_top_10 <- unsplit(value = value_unsplit, f = dat_new[, "phyl_interval"]) # return dat_new[index_is_top_10, ] } sp_pairs_df_FUN <- function( id_pair_data, data_type = "survival") { sp_pairs <- table_sp_pairs_annul_1_FUN( id_pair_data, data_type = data_type) sp_pairs_df <- data_frame_top_10_FUN(sp_pairs) sp_pairs_df[, "data_type"] <- data_type # return sp_pairs_df } add_phyl_dist_FUN <- function( summary_sp_pairs, pairwise_table_scenario_data, min_sample_phyl_interval) { phyl_dist_of_sp_pairs_data <- phyl_dists_of_paired_species_FUN( pairwise_table_scenario_data, min_sample_phyl_interval) index_between_phyl_pairs <- match( x = paste( summary_sp_pairs[, "focal_sp"], summary_sp_pairs[, "annular_sp"]), table = paste( phyl_dist_of_sp_pairs_data[, "focal_sp"], phyl_dist_of_sp_pairs_data[, "annular_sp"])) summary_sp_pairs[, "phyl_dist"] <- phyl_dist_of_sp_pairs_data[ index_between_phyl_pairs, "phyl_dist"] rownames(summary_sp_pairs) <- NULL # return summary_sp_pairs[ order(summary_sp_pairs[, "data_type"], summary_sp_pairs[, "phyl_interval"], - summary_sp_pairs[, "abundance"]), ] } ### #``` # summary_sp_pairs_FUN #```{r} # summary_sp_pairs_FUN <- function( id_pair_data, pairwise_table_scenario_data, min_sample_phyl_interval) { sp_pairs_survival <- sp_pairs_df_FUN( id_pair_data, data_type = "survival") sp_pairs_born <- sp_pairs_df_FUN( id_pair_data, data_type = "born") sp_pairs_diedS <- sp_pairs_df_FUN( id_pair_data, data_type = "diedS") sp_pairs_diedL <- sp_pairs_df_FUN( id_pair_data, data_type = "diedL") # summary_sp_pairs <- rbind(sp_pairs_survival, sp_pairs_born, sp_pairs_diedS, sp_pairs_diedL) summary_sp_pairs <- add_phyl_dist_FUN( summary_sp_pairs, pairwise_table_scenario_data, min_sample_phyl_interval) summary_sp_pairs[, "annul_interval"] <- 1 summary_sp_pairs[, "census_interval"] <- NA # return summary_sp_pairs } #``` #---------------------------- # "EAA main program, part 6, begin~" # --- # title: "all_EAA_analysis_results_data_FUN" # author: "<EMAIL>" # date: "2019-05-10" # --- # EAA_results_add_dists_FUN #```{r} EAA_results_add_dists_FUN <- function( EAA_results, id_pair_data) { annul_dist_mean <- tapply( X = id_pair_data[, "annul_dist"], INDEX = id_pair_data[, "annul_interval"], FUN = mean) phyl_dist_mean <- tapply( X = id_pair_data[, "phyl_dist"], INDEX = id_pair_data[, "phyl_interval"], FUN = mean) index_annul <- match( x = as.character(EAA_results[, "annul_interval"]), table = names(annul_dist_mean)) EAA_results[, "annul_dist"] <- round( annul_dist_mean[index_annul], 2) index_phyl <- match( x = as.character(EAA_results[, "phyl_interval"]), table = names(phyl_dist_mean)) EAA_results[, "phyl_dist"] <- round( phyl_dist_mean[index_phyl], 2) # return EAA_results } ### #``` ## EAA_analysis_results_of_single_census_FUN #```{r} EAA_analysis_results_of_single_census_FUN <- function( big_array_data, census_interval, annulus_number, annulus_size, pairwise_table_scenario_data, quantile_number, min_sample_phyl_interval, shuffled_times, max_matrix_row_limit, n_running_speed, z_growth_model) { # single_census_interval_data <- EAA_part_0_single_census_interval_data_FUN( big_array_data, census_interval, annulus_number, annulus_size, z_growth_model) print("( part 0 / part 4 ) ~ ~ EAA analysis begins ~ ~", quote = F) st_0 = Sys.time() max_mem_0 = round(sum(gc()[, ncol(gc())])) dim_single_data = dim(single_census_interval_data) print(paste("Maximum memory allocation", max_mem_0, "Mb"), quote = F) print(paste("Current memory allocation", round(sum(gc()[, 2])), "Mb"), quote = F) print(paste("dim(single_census_interval_data):", paste(dim_single_data, collapse = ", ")), quote = F) print(st_0, quote = F) cat("\n") id_pair_data <- EAA_part_1_focal_and_annular_id_pair_data_FUN( single_census_interval_data, annulus_number, annulus_size, pairwise_table_scenario_data, quantile_number, min_sample_phyl_interval) summary_sp_pairs <- summary_sp_pairs_FUN( id_pair_data, pairwise_table_scenario_data, min_sample_phyl_interval) summary_sp_pairs[, "census_interval"] <- census_interval st_1 = Sys.time() max_mem_1 = round(sum(gc()[, ncol(gc())])) dim_id_pairs = dim(id_pair_data) print("( part 1 / part 4 ) is finished", quote = F) print(paste("Maximum memory allocation", max_mem_1, "Mb"), quote = F) print(paste("Current memory allocation", round(sum(gc()[, 2])), "Mb"), quote = F) print(paste("dim(focal_and_annular_id_pairs):", paste(dim_id_pairs, collapse = ", ")), quote = F) print(st_1, quote = F) cat("\n") statistic_data <- EAA_part_2_all_quantiles_statistics_data_FUN( id_pair_data, single_census_interval_data, max_matrix_row_limit) st_2 = Sys.time() max_mem_2 = round(sum(gc()[, ncol(gc())])) dim_stat_data = dim(statistic_data) print("( part 2 / part 4 ) is finished", quote = F) print(paste("Maximum memory allocation", max_mem_2, "Mb"), quote = F) print(paste("Current memory allocation", round(sum(gc()[, 2])), "Mb"), quote = F) print(paste("dim(all_quantiles_statistic_data):", paste(dim_stat_data, collapse = ", ")), quote = F) print(st_2, quote = F) cat("\n") # growth_results <- EAA_part_3_growth_results_FUN( statistic_data, shuffled_times, n_running_speed) # st_3 = Sys.time() max_mem_3 = round(sum(gc()[, ncol(gc())])) dim_growth_results = dim(growth_results) print("( part 3 / part 4 ) is finished", quote = F) print(paste("Maximum memory allocation", max_mem_3, "Mb"), quote = F) print(paste("Current memory allocation", round(sum(gc()[, 2])), "Mb"), quote = F) print(paste("dim(growth_results):", paste(dim(growth_results), collapse = ", ")), quote = F) print(st_3, quote = F) cat("\n") born_clust_died_results <- EAA_part_4_born_clust_died_results_FUN( statistic_data, shuffled_times, n_running_speed) EAA_results <- rbind(growth_results, born_clust_died_results) EAA_results[, "census_interval"] <- census_interval EAA_results <- EAA_results_add_dists_FUN(EAA_results, id_pair_data) st_4 = Sys.time() max_mem_4 = round(sum(gc()[, ncol(gc())])) dim_born_clust_died_results = dim(born_clust_died_results) print("( part 4 / part 4 ) is finished", quote = F) print(paste("Maximum memory allocation", max_mem_4, "Mb"), quote = F) print(paste("Current memory allocation", round(sum(gc()[, 2])), "Mb"), quote = F) print(paste("dim(born_clust_died_results):", paste(dim_born_clust_died_results, collapse = ", ")), quote = F) print(st_4, quote = F) cat("\n") print("Results list:", quote = F) print(paste("dim(EAA_results):", paste(dim(EAA_results), collapse = ", ")), quote = F) print(paste("dim(summary_sp_pairs):", paste(dim(summary_sp_pairs), collapse = ", ")), quote = F) cat("\n") cat("\n") # detailed_information <- data.frame( code_location = c("part 0", "part 1", "part 2", "part 3", "part 4"), time_current = c(st_0, st_1, st_2, st_3, st_4), time_used = round(c(st_0, st_1, st_2, st_3, st_4) - c(st_0, st_0, st_1, st_2, st_3)), memory_max_allocation = c(max_mem_0, max_mem_1, max_mem_2, max_mem_3, max_mem_4), data_name = c("single_census_interval_data", "id_pair_data", "statistic_data", "growth_results", "born_clust_died_results"), data_nrow = c(dim_single_data[1], dim_id_pairs[1], dim_stat_data[1], dim_growth_results[1], dim_born_clust_died_results[1]), census_interval = census_interval ) rm(list = c("single_census_interval_data", "id_pair_data", "statistic_data", "growth_results", "born_clust_died_results")) gc() # return list(EAA_results = EAA_results, summary_sp_pairs = summary_sp_pairs, detailed_information = detailed_information) } #``` ## EAA_analysis_results_of_all_censuses_FUN #```{r} EAA_analysis_results_of_all_censuses_FUN <- function( big_array_data, census_interval_number, pairwise_table_scenario_data, annulus_size, annulus_number, quantile_number, shuffled_times, min_sample_phyl_interval, max_matrix_row_limit, n_running_speed, z_growth_model) { results_list <- lapply( X = 1: round(census_interval_number), FUN = function(i){ print(paste(" census interval =", i, " ")) print(Sys.time(), quote = F) cat("\n") EAA_analysis_results_of_single_census_FUN( big_array_data, census_interval = i, annulus_number, annulus_size, pairwise_table_scenario_data, quantile_number, min_sample_phyl_interval, shuffled_times, max_matrix_row_limit, n_running_speed, z_growth_model) }) # return results_list } #``` ## results_list_to_data_frame_FUN #```{r} results_list_to_data_frame_FUN <- function( replicated_results_list, data_names = "EAA_results") { results_list <- lapply( X = replicated_results_list, FUN = function(list_i) { args_rbind <- lapply(X = list_i, FUN = function(list_j){ list_j[[data_names]]}) # do.call(what = rbind, args = args_rbind) }) results <- do.call(what = rbind, args = results_list) results[, "replicate_time"] <- rep( x = 1:length(results_list), times = sapply(X = results_list, FUN = nrow)) results[, "plot_name"] <- plot_name #return results } #``` ## EAA_analysis_results_FUN #```{r} EAA_analysis_results_FUN <- function( replicate_EAA_times = 3, big_array_data = nonggang_bigarray, census_interval_number = 1, pairwise_table_scenario_data = nonggang_pairwise_table_scenario_2, annulus_size = 5, annulus_number = 3, quantile_number = 3, shuffled_times = 10, min_sample_phyl_interval = 2, plot_name = plot_name, working_directory = getwd(), max_matrix_row_limit = 2e7, n_running_speed = 5, z_growth_model = c("gls", "scale")[1]){ time_0 <- Sys.time() temp_file_name <- sprintf(fmt = "%s/%s_%s", working_directory, "temp_file", plot_name) if (! dir.exists(paths = temp_file_name)) { dir.create(path = temp_file_name)} else {NULL} setwd(dir = temp_file_name) if (! requireNamespace("bigtabulate", quietly = T)){ install.packages("bigtabulate") } else {NULL} if (! requireNamespace("nlme", quietly = T)){ install.packages("nlme")} else {NULL} require(bigtabulate); require(nlme); require(parallel); require(compiler); replicated_results_list <- lapply( X = 1:replicate_EAA_times, FUN = function(i) { cat("\n") print(x = sprintf(fmt = "Replicated EAA analysis time = %s", i)); cat("\n") EAA_analysis_results_of_all_censuses_FUN( big_array_data, census_interval_number, pairwise_table_scenario_data, annulus_size, annulus_number, quantile_number, shuffled_times, min_sample_phyl_interval, max_matrix_row_limit, n_running_speed, z_growth_model) }) EAA_results <- results_list_to_data_frame_FUN( replicated_results_list, data_names = "EAA_results") EAA_results <- EAA_results[ order(EAA_results[, "data_type"], EAA_results[, "annul_interval"], EAA_results[, "phyl_interval"], EAA_results[, "condition"]), ] summary_sp_pairs <- results_list_to_data_frame_FUN( replicated_results_list, data_names = "summary_sp_pairs") detailed_information <- results_list_to_data_frame_FUN( replicated_results_list, data_names = "detailed_information") time_1 <- Sys.time() # running_information <- list( time_begin = time_0, time_end = time_1, time_running = time_1 - time_0, plot_name = plot_name, data_dim = dim(big_array_data), census_interval_number = census_interval_number, replicate_EAA_times = replicate_EAA_times, annulus_size = annulus_size, annulus_number = annulus_number, quantile_number = quantile_number, shuffled_times = shuffled_times, min_sample_phyl_interval = min_sample_phyl_interval, r_version = sessionInfo()[["R.version"]][["version.string"]], os_Version = sessionInfo()[["running"]], num_cpu = parallel::detectCores(), memory_max_allocation = memory.size(T), memory_current_allocation = memory.size(F), memory_limit = memory.size(NA), gc = gc(), max_matrix_row_limit = max_matrix_row_limit, n_running_speed = n_running_speed, detailed_information = detailed_information ) # rm(list = ls()[! ls() %in% c("EAA_results", "summary_sp_pairs", "running_information", "working_directory", "temp_file_name")]) gc() setwd(dir = working_directory) unlink(x = temp_file_name, recursive = T, force = T) # return list(EAA_results = EAA_results, summary_sp_pairs = summary_sp_pairs, running_information = running_information) } #``` <file_sep># --- # title: "EAA_6_run_graph_program" # author: "<EMAIL>" # date: "2019/7/3" # output: html_document # --- #```{r} rm(list = ls()) #``` ## Read R Code #```{r} setwd("F:\\porjects-wangbin\\EAA_pnas") require(rgl) require(mgcv) source("EAA_4_graph_program_gam_ggplot_persp_rgl_20190703_1616.R") #``` ## dat_0 #```{r} setwd("F:\\porjects-wangbin\\EAA_pnas\\EAA_results") load("dat_0_pnas_20190703.save") dat_0 <- dat_0 #``` # Parameters setting #```{r} setwd("F:\\porjects-wangbin\\EAA_pnas") plot_name = "bci" k_set = c(born = 7, clust = 7, diedS = 7, diedL = 7, growth = 7) #``` # Run "rgl_gam_graph_FUN" #```{r} data_type <- as.character(unique(dat_0[, "data_type"])) for(i in data_type) { condition <- switch(EXPR = i, growth = c(1, 5), c(1, 4)) gam_k <- switch(EXPR = i, born = k_set[1], clust = k_set[2], diedL = k_set[3], diedS = k_set[4], growth = k_set[5]) for(j in condition) { dat_1 <- dat_1_FUN( dat_0 = dat_0, plot_name = plot_name, census_interval = 1, data_type = i, condition = j) dat_1[, "annul_dist"] <- as.numeric(as.character(dat_1[, "annul_dist"])) gam_0 <- mgcv::gam( formula = graph_value ~ s(annul_dist, k = gam_k) + s(phyl_dist, k = gam_k), family = gaussian(link = "identity"), data = dat_1) predict_values <- predict_gam_FUN(gam_0 = gam_0, ngrid = 20) ### main <- sprintf( fmt = "%s, %s, condition %s", plot_name, i, j) require(rgl) rgl_gam_graph_FUN( predict_values = predict_values, main = main, xlab = "Phys distance (m)", ylab = "phylo distance (Ma)", zlab = "z-values", axes_type = c(1, 2)[1]) url <- writeWebGL( filename = sprintf(fmt = "pdf_save//rgl_%s.html", main), width = 900, height = 900) browseURL(url = url) } } #```
0e2b053c601d5c0599dd430164d0b185c19b88a0
[ "Markdown", "R" ]
8
R
wangbinzjcc/EAAr
1bd036453af50d77f9355441291b1b6e0b8de11a
6af940d7929b2217d53785bf5ef57d6cf9096f87
refs/heads/master
<file_sep>### Install `./install.sh` ### Get OSM Data - URL https://s3.amazonaws.com/osm-changesets/ ##### Build osm for whole world `./buildosm.sh 137 148` ##### Build osm file for a specific area You can find all the poly in `boundary` folder `./buildosm.sh 137 148 af.poly` output: **osm.osm.bz2** ##### Build osm file for specific and specifics users Add the users in on file `users` and execute `./buildosm.sh 137 148 af.poly users` The number are the range from replication files: http://planet.osm.org/replication/day/000/001/ - [137](http://planet.osm.org/replication/day/000/001/137.osc.gz) Date : 2015-10-29 00:06 - [142](http://planet.osm.org/replication/day/000/001/142.osc.gz) Date : 2015-10-24 00:06 <file_sep>#!/bin/bash set -x url="http://planet.osm.org/replication/day/000/001/" #url="http://planet.osm.org/redaction-period/day-replicate/000/000/" ##per hour #url="https://s3.amazonaws.com/osm-changesets/hour/000/027/" sed 's/@//g' $4 > temp sed 's/,/,/g' temp > u for i in $(seq $1 $2) do echo ${url}$i.osc.gz if (($i<10)); then curl ${url}00$i.osc.gz -o "$i.osc.gz" fi if (($i<100)) && (($i>=10)); then curl ${url}0$i.osc.gz -o "$i.osc.gz" fi if (($i>=100)); then curl $url$i.osc.gz -o "$i.osc.gz" fi echo "Processing file $i" # if(($i == $1)); then # osmconvert $i.osm --complete-ways -o=main.osm # else # updateosm $i.osm main.osm # fi echo "Process completed $i" done echo "====================== Merge files ======================" # Merge file osmconvert *.osc.gz -o=temp.osm rm *.osc.gz #boundary if [ -n "$3" ]; then echo "====================== Clip for $3 ======================" osmconvert temp.osm -B=$3 --complete-ways -o=b-temp.osm mv b-temp.osm temp.osm fi #users if [ -n "$4" ]; then echo "==================== Proces by users ====================" users=("$(cat u)") IFS="," read -ra STR_ARRAY <<< "$users" for j in "${STR_ARRAY[@]}" do osmfilter temp.osm --keep=@user=$j -o=$j-users.osm done osmconvert *-users.osm -o=osm.osm rm *-users.osm else mv temp.osm osm.osm fi bzip2 osm.osm rm u rm temp.osm rm temp
bd56f44338755ed9026f9296a3b4dcb291a121ea
[ "Markdown", "Shell" ]
2
Markdown
ramyaragupathy/ExtractPoly
538bd69369976f87742e9d5af49aa8b8b953be07
5e9ca7104b960639389b90b11d04a2c8b282f85b
refs/heads/main
<file_sep>import xlrd import xlsxwriter import os from fuzzywuzzy import process from fuzzywuzzy import fuzz import math import re def reduce(dic): new_dic = {} for key,val in dic.items(): if val!=1: new_dic.update({key:dic[key]}) return new_dic def get_size(code): reg = "\d+[\s\`\"]*x\s*\d+[\`\"]*|\d+[\s\`\"]*X\s*\d+[\`\"]*" lst = re.findall(reg,code) if len(lst) == 0: return '' else: lst = lst[0] lst = lst.replace('x', 'X') lst = lst.replace(' ', '') lst = lst.replace('`', '') return lst def get_matches(element, list1, list2): matches = [] if element in list1: for e in list1: if e==element: matches.append(list2[list1.index(e)]) return matches elif element in list2: for e in list2: if e==element: matches.append(list1[list2.index(e)]) return matches else: return matches # filter_1 -> dimensions def filter_1(elem,lst,size1,size2): elem_size = get_size(elem) matching_sizes = [] if elem_size in size1: for s in size1: if s in size2: matching_sizes.append( s ) matches = [] for l in lst: l_size = get_size(l) if l_size in matching_sizes: matches.append( l ) return matches else: #print('No matching sizes in config file.') return 0 # filter_2 -> matching words def filter_2(elem,lst): elem_size = get_size(elem) elem_split = elem.replace(elem_size,'') elem_split = elem_split.split(' ') matches = [] for e in elem_split: for l in lst: ratio = fuzz.partial_ratio(e, l) if (ratio>80) and (l not in matches): matches.append(l) if len(matches)==0: #print('No partial matches found.') return 0 else: return matches # Logic def match(source, target, size1, size2): sources = [] matches = [] del source['NA'] for key,val in source.items(): targ = list( target.keys() ) #print('Working on '+key) options_1 = filter_1(key,targ,size1,size2) options_2 = [] match = [] if options_1!=0: options_2 = filter_2(key,options_1) if options_2!=0: match = process.extract(key, options_2, limit=1) else: match = process.extract(key, options_1, limit=1) else: options_2 = filter_2(key,targ) if options_2!=0: match = process.extract(key, options_2, limit=1) else: match = process.extract(key, targ, limit=1) if len(match)==0: matches.append( 'No matches found.' ) sources.append( key ) else: matches.append( match[0][0] ) sources.append( key ) target = reduce(target) #print('Match is '+str(matches[-1])) print('Matching done.') return sources,matches # Read configuration file def read_conf(filename): size1 = [] size2 = [] path = os.getcwd()+'/'+filename wb = xlrd.open_workbook(path) sheet = wb.sheet_by_index(0) sheet.cell_value(0, 0) for i in range(1, sheet.nrows): size1.append( sheet.cell_value(i, 0) ) size2.append( sheet.cell_value(i, 1) ) print('Conf read complete.') return size1,size2 # write file def write(source, target, sku): workbook = xlsxwriter.Workbook('./Result_v5.xlsx') worksheet = workbook.add_worksheet() bold = workbook.add_format({'bold': True}) worksheet.write(0, 0, "SKU code", bold) worksheet.write(0, 1, "Distributed Item Name", bold) worksheet.write(0, 2, "Company Description", bold) for i in range(0,len(target)): #if source[i] in sku.keys(): worksheet.write(i+1, 0, sku[ target[i] ]) worksheet.write(i+1, 1, source[i]) worksheet.write(i+1, 2, target[i]) workbook.close() print('Result file written.') # Read SKU file comp_desc = {} dist_desc = {} sku = {} path = os.getcwd()+'/SKU Mapping_for_v5.xlsx' wb = xlrd.open_workbook(path) sheet = wb.sheet_by_index(0) sheet.cell_value(0, 0) for i in range(1, sheet.nrows): com = sheet.cell_value(i, 2) comp_desc.update( {com : 0} ) sku.update( {com : sheet.cell_value(i, 1)} ) com = sheet.cell_value(i, 0) dist_desc.update( {com : 0} ) print('File read complete.') print('No. of source(company codes) : '+str(len(comp_desc))) print('No. of targets(distributor codes) : '+str(len(dist_desc))) print('No. of SKUs : '+str(len(sku))) # main program size1,size2 = read_conf('Size Configurations.xlsx') sources,matches = match(comp_desc, dist_desc, size1, size2) write(matches,sources,sku) <file_sep># SKU_Mapping SKU Mapping Tool Library Requirements - fuzzywuzzy==0.17.0 xlrd==1.2.0 XlsxWriter==1.2.2 Code implements below logic: 1. Match sizes 2. Match common words on subset from 1 3. Applies fuzzywuzzy on subset from 2
4df0d832981c2d47f0c8083f1214a78372b5e341
[ "Markdown", "Python" ]
2
Python
rsj-rishabh/SKU_Mapping
76d7a9220f7e0d6066120cd5395dd27c34451c51
4e0d79fe127a3e4e5c59c54d1ad9b4bd05055a8d
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; import { LectureService } from "app/services/lecture.service"; import { Lecture } from "app/models/lecture"; @Component( { selector: 'lectures', templateUrl: './lectures.component.html', styleUrls: ['./lectures.component.css'] } ) export class LecturesComponent implements OnInit { lectures: Lecture[]; constructor( private lectureService: LectureService ) { } ngOnInit() { this.loadLectures() window.scrollTo( 0, 0 ) } loadLectures() { this.lectureService.getLectures() .subscribe( lectures => this.lectures = lectures, //Bind to view err => { // Log errors if any console.log( err ); } ); } } <file_sep>export class UserHistory { constructor( public id: string, public name: string, public surname: string, public registerdate: Date, public email: string, public password: string, public university: string, public phone: string, public congressrole: string, public subjectdescription: string, public contactcomments: string, public confirmation: string, public privileges: string, public summary: string, public abstract: string, public paper_acceptation: string, public payment: string, public payment_accepted: string, public academic_title: string, public academic_status: string, public master: string, public engineer: string, public editor: string, public modified_date: Date ) { } get showStudentOptions(): boolean { return this.academic_status === '1' } get showAcademicTitle(): boolean { return this.academic_status === '2' } get isAcceptationPending(): boolean { if ( 'Y' == this.confirmation || 'N' == this.confirmation ) { return false; } return true; } get isAccepted(): boolean { if ( 'Y' == this.confirmation ) { return true; } return false; } get isRejected(): boolean { if ( 'N' == this.confirmation ) { return true; } return false; } } <file_sep>import { Component, OnInit, Input, OnChanges } from '@angular/core'; import { User } from "app/models/user"; import { UserService } from '../services/user.service'; import { EmitterService } from '../services/emitter.service'; import { LocalDataSource } from "ng2-smart-table/ng2-smart-table"; import { Observable } from "rxjs"; import { DatePipe } from "@angular/common"; import { ActionAdminEnrolmentComponent } from "app/action-admin-enrolment/action-admin-enrolment.component"; import { ActionAdminPaymentComponent } from "app/action-admin-payment/action-admin-payment.component"; import { UserInfoService } from "app/services/user-info.service"; import { UserInfo } from "app/models/user-info"; @Component( { selector: 'enrolments', templateUrl: './enrolments.component.html', styleUrls: ['./enrolments.component.css'] } ) export class EnrolmentsComponent implements OnInit, OnChanges { // Local properties users: User[]; // Input properties @Input() listId: string; @Input() editId: string; source: LocalDataSource; showAllEnabled: boolean; showAcceptedEnabled: boolean; showPendingEnabled: boolean; showSpeakersEnabled: boolean; showRejectedEnabled: boolean; showPaymentPendingEnabled: boolean; showPaymentAcceptedEnabled: boolean; showWorkhopEnabled: boolean; showInvoiceEnabled: boolean; enrolmentsCount: string; userInfo: UserInfo; // Constructor with injected service constructor( private userService: UserService, private userInfoService: UserInfoService ) { } ngOnInit() { // Load enrolments this.source = new LocalDataSource(); this.userService.getUsers().toPromise().then(( data ) => { this.source.load( data ); } ); this.getAllInfo(); this.showAllEnabled = true; window.scrollTo( 0, 0 ) } loadAllEnrolments() { // Get all enrolments this.userService.getUsers() .subscribe( enrolments => this.users = enrolments, //Bind to view err => { // Log errors if any console.log( err ); } ); } ngOnChanges( changes: any ) { // Listen to the 'list'emitted event so as populate the model // with the event payload EmitterService.get( this.listId ).subscribe(( enrolments: User[] ) => { this.loadAllEnrolments() } ); } settings = { columns: { name: { title: 'Imie' }, surname: { title: 'Nazwisko' }, email: { title: 'Email' }, university: { title: 'Uniwersytet' }, registerdate: { title: 'Data zgloszenia', type: 'html', valuePrepareFunction: ( value ) => { var datePipe = new DatePipe( 'pl-PL' ); return datePipe.transform( value, 'dd.MM.yyyy' ); } }, congressrole: { title: 'Rola', type: 'html', valuePrepareFunction: ( value ) => { if ( value === 'U' ) return 'Uczestnik'; if ( value === 'R' ) return 'Referent'; if ( value === 'O' ) return 'Organizator'; return '' }, filterFunction( cell?: any, search?: string ): boolean { if ( search != null ) { if ( "uczestnik".search( search ) > 0 ) { if ( cell === 'U' ) { return true; } return false; } if ( "referent".search( search ) > 0 ) { if ( cell === 'R' ) { return true; } return false; } if ( "organizator".search( search ) > 0 ) { if ( cell === 'U' ) { return true; } return false; } } if ( search === '' ) { return true; } else { return false; } } }, academic_title: { title: 'Tytul', type: 'html', valuePrepareFunction: ( value ) => { if ( value === '1' ) return 'mgr'; if ( value === '2' ) return 'dr'; if ( value === '3' ) return 'dr hab.'; if ( value === '4' ) return 'Prof. (stan.)'; if ( value === '5' ) return 'Prof.'; return '' } }, payment: { title: 'Oplata', type: 'custom', renderComponent: ActionAdminPaymentComponent, valuePrepareFunction: ( cell, row ) => { return row } }, confirmation: { title: 'Akceptacja', type: 'html', valuePrepareFunction: ( value ) => { if ( value === 'Y' ) return 'Tak'; if ( value === 'N' ) return 'Nie'; return 'Oczekuje' } }, action: { title: 'Akcja', type: 'custom', renderComponent: ActionAdminEnrolmentComponent, valuePrepareFunction: ( cell, row ) => { return row } } }, actions: false }; settingsInvoice = { columns: { name: { title: 'Imie' }, surname: { title: 'Nazwisko' }, email: { title: 'Email' }, payment: { title: 'Oplata', type: 'custom', renderComponent: ActionAdminPaymentComponent, valuePrepareFunction: ( cell, row ) => { return row } }, invoice_data: { title: 'Dane do faktury' }, action: { title: 'Akcja', type: 'custom', renderComponent: ActionAdminEnrolmentComponent, valuePrepareFunction: ( cell, row ) => { return row } } }, actions: false }; showAll() { this.userService.getUsers().toPromise().then(( data ) => { this.source.load( data ); } ); this.resetButtons(); this.showAllEnabled = true; this.getAllInfo(); } getAllInfo() { this.userInfoService.getAllUsersInfo().subscribe( data => {this.userInfo = data console.log ('data= ' + data) console.log ('Ilosc= ' + data.count) }, //Bind to view err => { // Log errors if any console.log( err ); } ); } showAcepted() { this.userService.getAcceptedUsers().toPromise().then(( data ) => { this.source.load( data ); } ); this.resetButtons(); this.showAcceptedEnabled = true; this.getAcceptedInfo(); } getAcceptedInfo() { this.userInfoService.getAcceptedUsersInfo().subscribe( data => {this.userInfo = data console.log ('data= ' + data) console.log ('Ilosc= ' + data.count) }, //Bind to view err => { // Log errors if any console.log( err ); } ); } showPending() { this.userService.getPendingUsers().toPromise().then(( data ) => { this.source.load( data ); } ); this.resetButtons(); this.showPendingEnabled = true; this.getPendingInfo(); } getPendingInfo() { this.userInfoService.getPendingUsersInfo().subscribe( data => {this.userInfo = data console.log ('data= ' + data) console.log ('Ilosc= ' + data.count) }, //Bind to view err => { // Log errors if any console.log( err ); } ); } showRejected() { this.userService.getRejectedUsers().toPromise().then(( data ) => { this.source.load( data ); } ); this.resetButtons(); this.showRejectedEnabled = true; this.getRejectedInfo(); } getRejectedInfo() { this.userInfoService.getRejectedUsersInfo().subscribe( data => {this.userInfo = data console.log ('data= ' + data) console.log ('Ilosc= ' + data.count) }, //Bind to view err => { // Log errors if any console.log( err ); } ); } showSpeakers() { this.userService.getSpeakers().toPromise().then(( data ) => { this.source.load( data ); } ); this.resetButtons(); this.showSpeakersEnabled = true; this.getSpeakersInfo(); } getSpeakersInfo() { this.userInfoService.getSpeakersUsersInfo().subscribe( data => {this.userInfo = data console.log ('data= ' + data) console.log ('Ilosc= ' + data.count) }, //Bind to view err => { // Log errors if any console.log( err ); } ); } showPaymentAccepted() { this.userService.getAcceptedPayment().toPromise().then(( data ) => { this.source.load( data ); } ); this.resetButtons(); this.showPaymentAcceptedEnabled = true; this.getPaymentAcceptedInfo(); } getPaymentAcceptedInfo() { this.userInfoService.getPaymentAcceptedUsersInfo().subscribe( data => {this.userInfo = data console.log ('data= ' + data) console.log ('Ilosc= ' + data.count) }, //Bind to view err => { // Log errors if any console.log( err ); } ); } showPaymentPending() { this.userService.getPendingPayment().toPromise().then(( data ) => { this.source.load( data ); } ); this.resetButtons(); this.showPaymentPendingEnabled = true; this.getPaymentPendingInfo(); } getPaymentPendingInfo() { this.userInfoService.getPaymentPendingUsersInfo().subscribe( data => {this.userInfo = data console.log ('data= ' + data) console.log ('Ilosc= ' + data.count) }, //Bind to view err => { // Log errors if any console.log( err ); } ); } showWorkshop() { this.userService.getWorkshop().toPromise().then(( data ) => { this.source.load( data ); } ); this.resetButtons(); this.showWorkhopEnabled = true; this.getWorkshopInfo(); } getWorkshopInfo() { this.userInfoService.getWorkshopUsersInfo().subscribe( data => {this.userInfo = data console.log ('data= ' + data.count) console.log ('Ilosc= ' + data.count) }, //Bind to view err => { // Log errors if any console.log( err ); } ); } showInvoice() { this.userService.getInvoice().toPromise().then(( data ) => { this.source.load( data ); } ); this.resetButtons(); this.showInvoiceEnabled = true; this.getInvoiceInfo(); } getInvoiceInfo() { this.userInfoService.getInvoiceUsersInfo().subscribe( data => {this.userInfo = data console.log ('data= ' + data) console.log ('Ilosc= ' + data.count) }, //Bind to view err => { // Log errors if any console.log( err ); } ); } resetButtons() { this.showAllEnabled = false; this.showAcceptedEnabled = false; this.showPendingEnabled = false; this.showSpeakersEnabled = false; this.showRejectedEnabled = false; this.showPaymentPendingEnabled = false; this.showPaymentAcceptedEnabled = false; this.showWorkhopEnabled = false; this.showInvoiceEnabled = false; } } <file_sep>import { Component, OnInit } from '@angular/core'; import { News } from "app/models/news"; import { NewsService } from '../services/news.service'; import { EmitterService } from '../services/emitter.service'; import { LocalDataSource } from "ng2-smart-table/ng2-smart-table"; import { Router } from "@angular/router"; import { DatePipe } from "@angular/common"; @Component( { selector: 'admin-news', templateUrl: './admin-news.component.html', styleUrls: ['./admin-news.component.css'] } ) export class AdminNewsComponent implements OnInit { news: News[]; source: LocalDataSource; activeNewsView: boolean; constructor( private newsService: NewsService, private router: Router ) { this.source = new LocalDataSource(); this.newsService.getNews().toPromise().then(( data ) => { this.source.load( data ); } ); this.activeNewsView = true; } ngOnInit() { // Load articles // this.loadArticles() } loadNews() { this.newsService.getNews().toPromise().then(( data ) => { this.source.load( data ); } ); } loadDeletedNews() { this.newsService.getDeletedNews().toPromise().then(( data ) => { this.source.load( data ); } ); } //TODO Michal translacja przez serwis settings = { columns: { author: { title: 'Autor' }, title: { title: 'Tytul' }, edited: { title: 'Edytowal' }, editdate: { title: 'Data edycji', type: 'html', valuePrepareFunction: ( value ) => { var datePipe = new DatePipe( 'pl-PL' ); return datePipe.transform( value, 'dd.MM.yyyy' ); } }, //TODO wpasowac w routingAdmin link: { title: 'Akcja', type: 'html', valuePrepareFunction: ( cell, row ) => { return '<a href="/admin-single-news/' + row.id + '">Edytuj</a>' } } }, actions: false }; createNew() { this.router.navigate( ['admin-news-new/'] ); } isShowActive() { return this.activeNewsView; } showDeletedNews() { this.loadDeletedNews(); this.activeNewsView = false; } showActiveNews() { this.loadNews(); this.activeNewsView = true; } } <file_sep>import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http'; import { Article } from '../models/article'; import { ArticleHistory } from "app/models/article-history"; import { Observable } from 'rxjs/Rx'; //Import RxJs required methods import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import { Config } from "app/utils/config"; @Injectable() export class ArticleService { constructor( private http: Http ) { } private articlesUrl = Config.serverAddress + '/articles'; private articleUrl = Config.serverAddress + '/article'; private deletedArticlesUrl = Config.serverAddress + '/deletedArticles'; private deleteArticleUrl = Config.serverAddress + '/deleteArticle'; private activateArticleUrl = Config.serverAddress + '/activateArticle'; private articleHistoryUrl = Config.serverAddress + '/articleHistory'; getArticles(): Observable<Article[]> { // ...using get request return this.http.get( this.articlesUrl ) // ...and calling .json() on the response to return data .map(( res: Response ) => res.json() ) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } getDeletedArticles(): Observable<Article[]> { return this.http.get( this.deletedArticlesUrl ) // ...and calling .json() on the response to return data .map(( res: Response ) => res.json() ) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } //TODO serwer i testy getArticle( id: string ): Observable<any> { let params: URLSearchParams = new URLSearchParams(); params.set( 'id', id ); var options = new RequestOptions( { headers: new Headers( { 'Content-Type': 'application/json' } ) } ); options.search = params; // ...using get request return this.http.get( this.articleUrl, options ) // ...and calling .json() on the response to return data .map(( res: Response ) => res.json() ) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } get(id): Observable<Article> { return this.getArticle(id) .map(data => data.article); } getArticleHistory( id: string ): Observable<ArticleHistory[]> { let params: URLSearchParams = new URLSearchParams(); params.set( 'id', id ); var options = new RequestOptions( { headers: new Headers( { 'Content-Type': 'application/json' } ) } ); options.search = params; // ...using get request return this.http.get( this.articleHistoryUrl, options ) // ...and calling .json() on the response to return data .map(( res: Response ) => res.json() ) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } addArticle( body: Article ): Observable<Article[]> { let headers = new Headers( { 'Content-Type': 'application/json' } ); let options = new RequestOptions( { headers: headers } ); return this.http.post( this.articlesUrl, JSON.stringify( body ), options ) .map(( res: Response ) => res.json() ) // ...and calling .json() on the response to return data .catch(( error: any ) => Observable.throw( error || 'Server error' ) ); //...errors if any } updateArticle( body: Article ): Observable<Article[]> { let headers = new Headers( { 'Content-Type': 'application/json' } ); let options = new RequestOptions( { headers: headers } ); return this.http.put( this.articlesUrl, JSON.stringify( body ), options ) .map(( res: Response ) => res.json() ) // ...and calling .json() on the response to return data .catch(( error: any ) => Observable.throw( error || 'Server error' ) ); //...errors if any } deleteArticle( body: Article ): Observable<Article[]> { let headers = new Headers( { 'Content-Type': 'application/json' } ); let options = new RequestOptions( { headers: headers } ); return this.http.post( this.deleteArticleUrl, JSON.stringify( body ), options ) .map(( res: Response ) => res.json() ) // ...and calling .json() on the response to return data .catch(( error: any ) => Observable.throw( error || 'Server error' ) ); //...errors if any } activateArticle( body: Article ): Observable<Article[]> { let headers = new Headers( { 'Content-Type': 'application/json' } ); let options = new RequestOptions( { headers: headers } ); return this.http.post( this.activateArticleUrl, JSON.stringify( body ), options ) .map(( res: Response ) => res.json() ) // ...and calling .json() on the response to return data .catch(( error: any ) => Observable.throw( error || 'Server error' ) ); //...errors if any } } <file_sep>export class Enrolment { constructor( public id: string, public name: string, public surname: string, public date: Date, public email: string, public university: string ) { } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Article } from "app/models/article"; import { ArticleService } from '../services/article.service'; import { EmitterService } from '../services/emitter.service'; @Component( { selector: 'articles', templateUrl: './articles.component.html', styleUrls: ['./articles.component.css'] } ) export class ArticlesComponent implements OnInit { articles: Article[]; constructor( private articleService: ArticleService ) { } ngOnInit() { // Load articles this.loadArticles() window.scrollTo( 0, 0 ) } loadArticles() { this.articleService.getArticles() .subscribe( articles => this.articles = articles, //Bind to view err => { // Log errors if any console.log( err ); } ); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { AuthenticationService } from '../services/authentication.service'; import { Config } from "app/utils/config"; //todo michal stworzyc login serwis @Component( { selector: 'login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] } ) //https://github.com/auth0-blog/angular2-authentication-sample/tree/master/src/login export class LoginComponent implements OnInit { constructor( private authenticationService: AuthenticationService, public router: Router, public http: Http ) { } private loginUrl = Config.serverAddress + '/login'; //todo michal service z emmiterem login( event, username, password ) { //co to jest? event.preventDefault(); this.authenticationService.login( username, password ); } signup( event ) { event.preventDefault(); this.router.navigate( ['signup'] ); } logout() { this.authenticationService.logout(); } ngOnInit() { } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ContactService } from "app/services/contact.service"; import { ForgotPasswordMessage } from "app/models/forgot-password-message"; import { Message } from "primeng/primeng"; @Component( { selector: 'forgot-password', templateUrl: './forgot-password.component.html', styleUrls: ['./forgot-password.component.css'] } ) export class ForgotPasswordComponent implements OnInit { email: string; msgs: Message[]; forgotForm; emailNotFoundAlert: boolean; passwordSentAlert: boolean; constructor( private contactService: ContactService ) { this.forgotForm = []; this.forgotForm.email = 'input full'; } ngOnInit() { } submitPassword() { this.emailNotFoundAlert = false; this.passwordSentAlert = false; if ( this.validateLoginForm() === true ) { //todo obsluga bledow nie znaleziono, wyslano if ( this.isEmpty( this.email ) ) { } else { var forgotMessage = new ForgotPasswordMessage( this.email ); this.contactService.sendPassword( forgotMessage ).subscribe( response => { this.msgs = []; this.msgs.push( { severity: 'success', summary: 'Email z hasล‚em zostaล‚ dostarczony.', detail: '' } ); this.passwordSentAlert = true; }, err => { this.msgs = []; // Log errors if any this.msgs.push( { severity: 'error', summary: 'Nie znaleziono takiego uลผytkownika.', detail: '' } ); //console.log( err ); console.log( "Email not found" + err ); this.emailNotFoundAlert = true; } ); } } } validateLoginForm() { var result = true; if ( this.isEmpty( this.email ) ) { result = false; this.forgotForm.email = 'input full validationError'; } else { if ( this.validateEmail( this.email ) === true ) { this.forgotForm.email = 'input full'; } else { this.forgotForm.email = 'input full validationError'; result = false; } } return result; } emailNotFoundAlertVisible() { return this.emailNotFoundAlert } passwordSentAlertVisible() { return this.passwordSentAlert } validateEmail( email ) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test( String( email ).toLowerCase() ); } isEmpty( str ) { return ( !str || 0 === str.length ); } } <file_sep>export const LANG_PL_NAME = 'pl'; export const LANG_PL_TRANS = { 'enrolments-list': 'Lista zgล‚oszeล„', 'Clear': 'Usuล„ tekst', 'Print': 'Drukuj', 'Text': 'Treล›ฤ‡', 'Description': 'Opis', 'Save': 'Zapisz', 'Cancel': 'Anuluj', 'Delete': 'Usuล„', 'show-history': 'Pokaลผ historiฤ™', 'Create New': 'Utwรณrz', 'Author': 'Autor', 'Title': 'Tytuล‚', 'First name': 'Imiฤ™', 'Surname': 'Nazwisko', 'E-mail': 'E-mail', 'Enrolment form': 'Formularz zgล‚oszenia', 'Phone': 'Telefon', 'Show deleted articles': 'Pokaลผ usuniฤ™te', 'Show articles': 'Pokaลผ aktywne artykuล‚y', 'News': 'Aktualnoล›ci', 'Articles': 'Artykuล‚y', 'Contact': 'Kontakt', 'ContactMail': 'Kontakt: <a href="mailto:<EMAIL>"><EMAIL></a>', 'Address': 'Dojazd', 'Schedules': 'Harmonogram', 'Events': 'Wydarzenia', 'Log out': 'Wyloguj', 'Welcome': 'Witaj', 'Terms': 'Regulamin', 'Read more': 'Czytaj wiฤ™cej', 'Registration': 'Rejestracja', 'Admin panel': 'Admin', 'Medieval congress': 'VI Kongres Mediewistรณw Polskich', 'Wroclaw University': 'Uniwersytet wrocล‚awski - Wydziaล‚ historii', 'Published:': 'Opublikowano:', 'Categories:': 'Tagi:', 'Modern history': 'Historia najnowsza', 'Congress': 'Kongres', 'logo': 'logo', 'Sponsors': 'Sponsorzy', 'Sign Up': 'Zarejestruj siฤ™', 'Login': 'Zaloguj siฤ™', 'Enter your details': 'Wprowadลบ swoje dane', 'congressDatePlace': 'Wrocล‚aw, 20โ€“22 wrzeล›nia 2018', 'to create an account': 'by utworzyฤ‡ konto', 'Email': 'Email', 'Password': '<PASSWORD>', 'Repeat password': '<PASSWORD>', 'University': 'Afiliacja', 'Remarks': 'Uwagi', 'Capacity': 'W jakim charakterze?', 'Topic': 'Abstrakt', 'Show': 'Pokaลผ', 'Hide': 'Ukryj', 'Click here': 'Kliknij tutaj', 'ForgotPassword': 'Zapomniaล‚eล›/aล› hasล‚a?', 'EnterYourEmail': 'Wprowadลบ swรณj email i hasล‚o', 'to sign in': 'aby zalogowaฤ‡ siฤ™', 'Agree rules info': 'Tworzฤ…c konto akceptujฤ™', 'Send Message': 'Wyล›lij wiadomoล›ฤ‡', 'Name': 'Imiฤ™ i nazwisko', 'Subject': 'Temat', 'Message': 'Wiadomoล›ฤ‡', 'Thank You!': 'Dziฤ™kujemy!', 'EmailSentInfo': 'Twoja wiadomoล›ฤ‡ zostaล‚a wysล‚ana.', 'About the university': 'O uniwersytecie', 'Log in': 'Zaloguj siฤ™', 'Create account': 'Utwรณrz konto', 'Profile photo': 'Zdjฤ™cie uลผytkownika', 'Send for acceptation': 'Wyล›lij do akceptacji', 'Personal data': 'Dane osobiste', 'Degree': 'Tytuล‚ naukowy', 'academic_status': 'Status akademicki', 'engineer': 'inลผ.', 'master': 'mgr', 'Additional Info': 'Dodatkowe', 'Paper': 'Referat', 'Summary': 'Streszczenie', 'Content': 'Abstrakt', 'Mailbox': 'Poczta', 'Recover': 'Przywrรณฤ‡', 'Show all applicants': 'Pokaลผ wszystkich', 'Show accepted': 'Zaakceptowani', 'Show pending requests': 'Oczekujฤ…cy', 'Show rejected': 'Odrzuceni', 'Show speakers': 'Referenci', 'Receivers': 'Odbiorcy', 'Accept': 'Akceptuj', 'Reject': 'Odrzuฤ‡', 'letter-of-intent': 'Komunikat', 'letter-greeting': '<NAME>,', 'letter-1': 'Kongresy Mediewistรณw Polskich stanowiฤ… najwaลผniejsze i najliczniejsze spotkania badaczy ล›redniowiecza w Polsce. Inicjatywฤ™ ich organizacji wysuwa Staล‚y Komitet Mediewistรณw Polskich (SKMP), wspรณล‚pracujฤ…c w realizacji tego zadania z najwaลผniejszymi i najprฤ™ลผniej dziaล‚ajฤ…cymi oล›rodkami akademickimi w kraju, goszczฤ…cymi kolejne spotkania: w Toruniu (2002), w Lublinie (2005), w ลodzi (2008), w Poznaniu (2011) i w Rzeszowie (2015). Obecnie czas na Wrocล‚aw!', 'letter-2': 'Kaลผda z tych imprez zgromadziล‚a i w przyszล‚oล›ci ma gromadziฤ‡ przedstawicieli wielu dyscyplin (m.in. historia, archeologia, historia sztuki, filozofia, filologie), w tym goล›ci zagranicznych, w zaล‚oลผeniu majฤ…c na celu promowanie ich wspรณล‚pracy oraz realizowanie postulatu interdyscyplinarnoล›ci badaล„. Istotne znaczenie ma teลผ obecnoล›ฤ‡ reprezentantรณw nauk ล›cisล‚ych i przyrodniczych wspรณล‚pracujฤ…cych z mediewistami.', 'letter-3': 'W imieniu Organizatorรณw <b>VI Kongresu Mediewistรณw Polskich</b> โ€“ Staล‚ego Komitetu Mediewistรณw Polskich, Uniwersytetu Wrocล‚awskiego, Oล›rodka Badaล„ nad Kulturฤ… Pรณลบnego Antyku i Wczesnego ลšredniowiecza IAE PAN we Wrocล‚awiu โ€“ kierujฤ™ do Paล„stwa serdeczne zaproszenie do wziฤ™cia udziaล‚u w tej zaplanowanej na <b>20โ€“22 wrzeล›nia bieลผฤ…cego roku</b> imprezie. Tematyka obrad zaplanowana zostaล‚a w trzech zasadniczych obszarach:', 'letter-4': '<b>I. ลšredniowieczne fundamenty cywilizacji i kultury europejskiej w kontekล›cie ล›wiatowym</b> (m.in. strategie badaล„ nad ksztaล‚towaniem Europy, znaczenie kontaktรณw miฤ™dzykulturowych w tym procesie, wkล‚ad epoki warunkujฤ…cy ksztaล‚t poszczegรณlnych dziedzin cywilizacji i kultury ล›wiatowej w kolejnych stuleciach aลผ do dziล›);', 'letter-5': '<b>II. Obecnoล›ฤ‡ wiekรณw ล›rednich w dzisiejszej kulturze i ลผyciu spoล‚ecznym </b>(m.in. miejsca pamiฤ™ci, wielkie wydarzenia i rocznice, mediewalizm);', 'letter-6': '<b>III. ลปywotnoล›ฤ‡ badaล„ </b>(m.in. rozwรณj metod badawczych i ich interdyscyplinarnoล›ฤ‡ โ€“ np. cyfryzacja, LIDAR, zastosowanie genetyki; poszerzanie bazy ลบrรณdล‚owej, zwล‚aszcza archeologicznej).', 'letter-7': 'Obrady bฤ™dฤ… miaล‚y po czฤ™ล›ci charakter plenarny, a w wiฤ™kszoล›ci sekcyjny oraz warsztatowy. Sekcje majฤ… charakter autorski, a propozycje ich zorganizowania zgล‚aszane sฤ… zgodnie z tradycjฤ… poprzednich Kongresรณw przez ich kierownikรณw-moderatorรณw, ktรณrzy odpowiadajฤ… teลผ za zaproszenie referentรณw (czas obrad poszczegรณlnych sekcji nie powinien przekraczaฤ‡ 6 godz.). Termin zgล‚aszania propozycji sekcji wraz z wykazem referatรณw w ich ramach upล‚ywa z koล„cem kwietnia br.', 'letter-8': 'W programie wrocล‚awskiego Kongresu zaplanowane sฤ… rรณwnieลผ spotkania warsztatowe (m.in. archeologiczne, kodykologiczne i filmowe), do ktรณrych rekrutacja przeprowadzona zostanie w czerwcu i lipcu br. O ile napล‚ynฤ… odpowiednie zgล‚oszenia, zostanie zorganizowana takลผe sesja posterowa.', 'letter-9': 'Uczestnikom imprezy zapewniony zostanie hotel, wyลผywienie oraz komplet materiaล‚รณw kongresowych, przy czym opล‚ata konferencyjna peล‚na wynosi 300 zล‚, natomiast ulgowa dla doktorantรณw 220 zล‚. W wypadku uczestnikรณw mieszkajฤ…cych we Wrocล‚awiu i niekorzystajฤ…cych z bazy hotelowej opล‚ata wyniesie 123 zล‚ (co pozwoli zapewniฤ‡ posiล‚ki w trakcie obrad i komplet materiaล‚รณw kongresowych).', 'letter-10': 'Fundacja dla Uniwersytetu Wrocล‚awskiego na ลผyczenie opล‚acajฤ…cego wystawi fakturฤ™ potwierdzajฤ…cฤ… wniesienie opล‚aty konferencyjnej. W tym celu prosimy po zalogowaniu o wypeล‚nienie odpowiedniego formularza, ktรณry pojawi siฤ™ niedล‚ugo na stronie, bฤ…dลบ teลผ o kontakt drogฤ… mailowฤ….', 'letter-11': 'Zapytania i propozycje w sprawach organizacyjnych proszฤ™ kierowaฤ‡ na adres mailowy: <a href="mailto:<EMAIL>"><u><EMAIL></u></a>', 'letter-regards': 'Z serdecznym zaproszeniem do Wrocล‚awia, mocฤ… pozdrowieล„ i wyrazami szacunku!', 'letter-author': '<NAME>', 'letter-author-role': 'Przewodniczฤ…cy SKMP', 'letter-date': 'Wrocล‚aw, 20.06.2018', 'letter-contact-1': 'Kontakt w sprawach organizacyjnych:', 'letter-contact-2': 'Prof. dr hab. <NAME>, Instytut Historyczny Uniwersytetu Wrocล‚awskiego, ul. Szewska 49, 50-139 Wrocล‚aw; e-mail: <a href="mailto:<EMAIL>"><u><EMAIL></u></a>', 'noConfirmationInfo': 'Twoje zgล‚oszenie nie zostaล‚o jeszcze zaakceptowane przez organizatora. Niebawem otrzyma Pan/Pani informacjฤ™ mailowฤ….', 'incorrectLoginDataInfo': 'Nieprawidล‚owe dane logowania.', 'Academic title': 'Tytuล‚ naukowy', 'Reset': 'Resetuj zmiany', 'Change password': '<NAME>', 'FooterWelcome': 'Zapraszamy!', 'RegistrationOpen': 'Rejestracja juลผ otwarta!', 'RegistrationClosed' : 'Rejestracja zostaล‚a zamkniฤ™ta', 'LateRegistrationInfo' : 'W celu dopisania do listy uczestnikรณw prosimy kontaktowaฤ‡ siฤ™ bezpoล›rednio z organizatorami.', 'RegistrationTime': 'Na zgล‚oszenia czekamy do 5 wrzeล›nia.', 'enrolment-created-title': 'Dziฤ™kujemy za przesล‚anie zgล‚oszenia.', 'enrolment-created1': 'O akceptacji Paล„stwa wniosku poinformujemy drogฤ… mailowฤ…. Po jej otrzymaniu bฤ™dzie moลผliwe zalogowanie siฤ™ za pomocฤ… zdefiniowanego przez Paล„stwa hasล‚a.', 'TermsTitle': 'Regulamin korzystania z portalu:', 'Terms0-1': 'Akceptacja regulaminu oznacza wyraลผenie zgody na przetwarzanie danych osobowych na potrzeby zjazdu i dziaล‚aล„ organizacyjnych zwiฤ…zanych z wydarzeniem.', 'Terms0-2': 'Rejestracja trwa od 9 kwietnia 2018 r. do 5 wrzeล›nia 2018 r.', 'Terms0': 'W celu uczestnictwa w zjeลบdzie naleลผy:', 'Terms1': 'Utworzyฤ‡ konto na stronie <a href="www.vikmp.pl">www.vikmp.pl</a>', 'Terms2': 'Po otrzymaniu maila aktywujฤ…cego uzupeล‚niฤ‡ wszelkie brakujฤ…ce dane.', 'Terms3': 'Dokonaฤ‡ opล‚aty rejestracyjnej w terminie do 30 sierpnia 2018 r.', 'Send Password': '<PASSWORD>', 'emailNotFoundAlert': 'Nie znaleziono takiego adresu e-mail w bazie danych.', 'emailSentAlert': 'Hasล‚o zostaล‚o wysล‚ane na podany adres email.', 'Commitee': 'Komitet naukowy', 'Presidium': 'Prezydium:', 'PresidiumNames': 'Prof. dr hab. <NAME>, Prof. dr hab. <NAME>, Prof. dr hab. <NAME>', 'CommiteeNames1': 'Prof. dr hab. <NAME>, Prof. dr hab. <NAME>,', 'CommiteeNames2': 'Prof. dr hab. <NAME>, Prof. dr hab. <NAME>, Dr hab. Prof. UWr, <NAME>, ', 'CommiteeNames3': 'Dr hab. Prof. UWr <NAME>, Prof. dr hab. <NAME>, ', 'CommiteeNames4': 'Prof. dr hab. <NAME>, Prof. UWr dr hab. <NAME>,', 'CommiteeNames5': 'Prof. dr hab. <NAME>, Prof. UWr dr.hab. <NAME>,', 'CommiteeNames6': 'Prof. dr hab. <NAME>', 'OrganizersCommitee': 'Komitet organizacyjny', 'OrganizersCommiteeNames1': 'Prof. dr hab. <NAME>, dr hab. Prof. UWr <NAME>, Prof. dr hab. Sล‚awom<NAME>,', 'OrganizersCommiteeNames2': 'dr hab. Prof. UWr <NAME>, dr hab. <NAME>, dr Mirosล‚aw Piwowarczyk,', 'OrganizersCommiteeNames3': 'Prof. dr hab. <NAME> (przewodniczฤ…cy)', 'OrganizersTechnical': 'Zespรณล‚ ds. informacji i rejestracji uczestnikรณw', 'OrganizersTechnicalNames1': 'mgr <NAME> - koordynator ds. Informacji i rejestracji', 'OrganizersTechnicalNames2': 'mgr <NAME> - administrator strony fb kongresu', 'OrganizersTechnicalNames3': 'mgr inลผ. <NAME> - portal internetowy', 'emailRegisteredAlert': 'Istnieje juลผ uลผytkownik o podanym adresie email. Rejestracja nie powiodล‚a siฤ™.', 'requiredFieldsAlert': 'Proszฤ™ uzupeล‚niฤ‡ wszystkie obowiฤ…zkowe (*) pola.', 'saveSuccess': 'Zapis zakoล„czony powodzeniem.', 'passwordChangedAlert': 'Hasล‚o zostaล‚o zmienione.', 'cancelConfirmation': 'Wycofaj', 'Edit': 'Edytuj', 'ShowPaymentAccepted': 'Pล‚atnoล›ฤ‡ przyjฤ™ta', 'ShowPaymentPending': 'Brak opล‚aty', 'SeeYouInWroclaw': 'Do zobaczenia we Wrocล‚awiu!', 'Friends': 'Zaprzyjaลบnione instytucje:', 'Links': 'Linki', 'Institution1': 'Uniwersytet Wrocล‚awski <a href="https://uni.wroc.pl/">https://uni.wroc.pl</a>', 'Institution2': 'Wydziaล‚ nauk Historycznych i Pedagogicznych UWr <a href="http://wnhip.uni.wroc.pl">http://wnhip.uni.wroc.pl</a>', 'Institution3': 'Instytut Historyczny UWr <a href="http://www.hist.uni.wroc.pl/pl/">http://www.hist.uni.wroc.pl/pl/</a>', 'Institution4': 'Instytut Archeologii UWr <a href="https://ww3.archeo.uni.wroc.pl">https://ww3.archeo.uni.wroc.pl</a>', 'Institution5': 'Instytut Archeologii i Etnologii PAN o/Wrocล‚aw <a href="http://arch.pan.wroc.pl/">http://arch.pan.wroc.pl/</a>', 'Institution6': 'Instytut Historii Sztuki <a href="https://uni.wroc.pl/">http://historiasztuki.uni.wroc.pl/</a>', 'EnrolmentAccepted': 'Zaakceptowane', 'EnrolmentRejected': 'Odrzucone', 'EnrolmentWaiting': 'Oczekuje', 'EnrolmentStatus': 'Status uczestnictwa', 'Enrolment': 'Zgล‚oszenie', 'Paid': 'Wpล‚acono', 'Patronage': 'Patronat i mecenat', 'patronage-title': 'Patronat nad wydarzeniem objฤ™li:', 'rektor-title': 'Rektor Uniwersytetu Wrocล‚awskiego', 'rektor-name': 'Je<NAME> prof. dr hab. <NAME>', 'Payment Status': 'Status pล‚atnoล›ci', 'PaymentAccepted': 'Zaakceptowano', 'PaymentWaiting': 'Oczekuje', 'PaymentInfo': 'Opล‚ata konferencyjna', 'paymentInfo-1': 'Opล‚atฤ™ konferencyjnฤ… prosimy wnosiฤ‡ na konto Fundacji dla Uniwersytetu Wrocล‚awskiego nr <b>78 1050 1575 1000 0022 9609 3004</b> z tytuล‚em โ€žVI Kongres Mediewistรณw Polskich. Imiฤ™ Nazwiskoโ€.', 'paymentInfo-2': 'Wysokoล›ฤ‡ opล‚aty:', 'paymentInfo-3': 'Peล‚na โ€“ 300 zล‚', 'paymentInfo-4': 'Ulgowa (dla doktorantรณw) โ€“ 220 zล‚', 'paymentInfo-5': 'โ€žWrocล‚awskaโ€ โ€“ 123 zล‚', 'paymentInfo-6': 'Informacja: Osobom wpล‚acajฤ…cym opล‚atฤ™ normalnฤ… i ulgowฤ… Organizatorzy zapewniajฤ… hotel, posiล‚ki w trakcie obrad oraz komplet materiaล‚รณw konferencyjnych, natomiast w wypadku opล‚aty โ€žwrocล‚awskiejโ€ posiล‚ki w trakcie obrad oraz komplet materiaล‚รณw konferencyjnych. Fundacja dla Uniwersytetu Wrocล‚awskiego na ลผyczenie opล‚acajฤ…cego wystawi fakturฤ™ potwierdzajฤ…cฤ… wniesienie opล‚aty konferencyjnej. W tym celu prosimy po zalogowaniu o wypeล‚nienie odpowiedniego formularza, bฤ…dลบ teลผ o kontakt drogฤ… mailowฤ….', 'registerParticipation' : 'Zaznacz udziaล‚:', 'participateConference' : 'Konferencja', 'participateWorkshop': 'Warsztaty', 'Conference':'Konferencja', 'wantInvoice':'Potrzebna faktura', 'footerUniversity':'Uniwersytet Wrocล‚awski', 'footerInstitute':'Instytut historyczny', 'ShowWorkhopEnrolments' : 'Udziaล‚ w warsztatach', 'noPayment':'Brak opล‚aty', 'Workshops':'Warsztaty', 'workshop1-title':'WARSZTAT KODYKOLOGICZNY: OFERTA nie tylko DLA DOKTORANTร“W!', 'workshop1-content':'<NAME>, <br/> <br/> serdecznie zapraszamy do zgล‚aszania udziaล‚u w warsztacie organizowanym przez Prof. dra hab. <NAME> (Instytut Historyczny UWr) <b>โ€žKodykologia jako narzฤ™dzie w warsztacie historyka-mediewistyโ€</b>', 'workshop1-date':'Planowany termin: 21 wrzeล›nia br., godz. 9.00', 'workshop1-place':'Miejsce: Biblioteka Uniwersytecka, ul. F. Joliot-Curie 12', 'workshop1-contact':'Kontakt w sprawach organizacyjnych: <a href="mailto:<EMAIL>"><u><EMAIL></u></a>, <a href="mailto:<EMAIL>"><u><EMAIL></u></a>', 'workshop2-title':'WARSZTAT FILMOWY: OFERTA nie tylko DLA DOKTORANTร“W!', 'workshop2-content':'<NAME>, <br/> <br/> serdecznie zapraszamy do zgล‚aszania udziaล‚u w warsztacie <b>โ€žHistoryk przed kamerฤ…โ€</b> prowadzonym przez Pana Zdzisล‚awa Cozaca, scenarzystฤ™ i reลผysera, twรณrcฤ™ m.in. cyklu โ€žTajemnice poczฤ…tkรณw Polskiโ€ realizowanego od 2010 r. w koprodukcji z TVP Historia ', 'workshop2-date':'Planowany termin: 22 wrzeล›nia br., godz. 9.00', 'workshop2-contact': 'Kontakt w sprawach organizacyjnych: <a href="mailto:<EMAIL>"><u><EMAIL></u></a>', 'gotoFacebook' : 'Odwiedลบ nas na facebooku', 'PersonsCount' : 'Iloล›ฤ‡ osรณb', 'InvoiceData' : 'Dane do faktury', 'Accomodation' : 'Nocleg', 'AccomodationDate' : 'W dniach', 'Invoice' : 'Faktura', 'Show deleted workshops' : 'Pokaลผ usuniฤ™te', 'Show workshops' : 'Pokaลผ aktywne', 'Place' : 'Miejsce', 'Date' : 'Data', 'meal' : 'Posiล‚ki', 'lactose_intolerance' : 'Nietolerancja laktozy', 'WorkshopChoice' : 'Wybรณr warsztatu', 'SelectedWorkshops' : 'Wybierz warsztaty', 'TitleHeadline' : 'Nagล‚รณwek tytuล‚owy', 'GlutenIntolerance' : 'Nietolerancja glutenu', 'AccomodationInfo1' : 'Organizator zapewnia trzy noclegi (19-22.09) w ramach opล‚aty konferencyjnej.', 'AccomodationInfo2' : 'Moลผliwy jest dodatkowy nocleg 22-23.09, w tej sprawie prosimy o kontakt z <a href="mailto:<EMAIL>"><u><EMAIL></u></a>', 'AccomodationInfo3' : 'Preferencje dot. zakwaterowania w dwuosobowych pokojach prosimy wpisywaฤ‡ w polu "Uwagi".', 'SmookingRoom': 'Pokรณj dla palฤ…cych', 'LeaveComment' : 'Skomentuj:', 'Submit' : 'Wyล›lij', 'Lectures' : 'Program kongresu', 'LecturesS' : 'Sekcje', 'Sections' : 'Sekcje', 'Show deleted lectures' : 'Pokaลผ usuniฤ™te', 'Show lectures' : 'Pokaลผ aktywne', 'Cooperation' : 'Instytucje wspรณล‚organizujฤ…ce', 'Cooperation1' : 'Papieski Wydziaล‚ Teologiczny we Wrocล‚awiu', 'Cooperation2' : 'Biblioteka Uniwersytecka we Wrocล‚awiu', 'MediaPatronage' : 'Patronat medialny', 'MediaPatronage1' : 'TVP Historia', 'LecturesInfo' : 'Informacja', 'LecturesInfo1' : 'Program Kongresu obejmie rรณwnieลผ: 1) wykล‚ady plenarne; 2) zaplanowanฤ… na sobotฤ™ 22 wrzeล›nia br. dyskusjฤ™ panelowฤ… nt. stanu i perspektyw mediewistyki polskiej (moderator: Prof. Dr hab. <NAME>); 3) warsztat otwarty, z czynnym udziaล‚em uczniรณw szkรณล‚ podstawowych, nt. zabaw i zabawek ล›redniowiecznych w edukacji i terapii wspรณล‚czesnej (moderatorka: Prof. Dr hab. <NAME>ฤ…dลบ-Strzelczyk); 4) warsztaty โ€žna zapisyโ€: kodykologiczny (moderator: Dr hab. <NAME> Prof. UWr), filmoznawczy (moderator: <NAME>); archeologiczny nt. nowoczesnych metod badaล„ (moderatorzy: Dr hab. <NAME> Prof. IAE PAN, Dr <NAME>, Dr hab. Piotr Kittel Prof. Uล, mgr <NAME>i).', 'UsersEnrolments' : 'Zapisani', 'Section1' : 'Sekcja 1', 'Section2' : 'Sekcja 2', 'Section3' : 'Sekcja 3', 'Section4' : 'Sekcja 4', 'Section5' : 'Sekcja 5', 'Section6' : 'Sekcja 6', 'Section7' : 'Sekcja 7', 'Section8' : 'Sekcja 8', 'Section9' : 'Sekcja 9', 'Section10' : 'Sekcja 10', 'LecturesPlan' : 'Plan obrad (ramowy)', 'LecturesPlanThursday' : 'Czwartek (20.09.2018)', 'LecturesPlanThursday1' : 'Godz. 9.00-11.00. Otwarcie VI Kongresu Mediewistรณw Polskich', 'LecturesPlanThursday1Place' : 'Gmach Gล‚รณwny UWr,, Pl. Uniwersytecki 1, Oratorium Marianum', 'LecturesPlanThursday1Content1' : 'Powitania', 'LecturesPlanThursday1Content2' : 'Wrฤ™czenie medali LUX ET LAUS', 'LecturesPlanThursday1a' : 'Godz. 10.00โ€“11.00. Sesja plenarna 1 (wykล‚ady)', 'LecturesPlanThursday1Content3' : 'Wykล‚ady (Prof. dr hab. <NAME>, Prof. dr hab. <NAME>)', 'LecturesPlanThursday1Content4' : 'Kawa/herbata', 'LecturesPlanThursday1b' : '11.00โ€“11.30. Kawa/herbata', 'LecturesPlanThursday2' : 'Godz. 11.30โ€“13.45. Sekcje', 'LecturesPlanThursday2Table1' : '<b>Sekcja 1</b><br/> Od โ€žcivitas Shinesgneโ€ do Korony Krรณlestwa Polskiego. Cywilizacyjne i ideowe podstawy ksztaล‚towania polskiej paล„stwowoล›ci w dobie Piastรณw <br/> Cz. 1 <br/> Instytut Historyczny UWr, Szewska 49, Audytorium', 'LecturesPlanThursday2Table2' : '<b>Sekcja 2</b><br/> Ruล› Waregรณw. Archeologia i historia <br/> Cz. 1 <br/> IAE PAN, Wiฤ™zienna 6, sala im. Anny i <NAME>', 'LecturesPlanThursday2Table3' : '<b>Sekcja 3</b><br/> Mediewistyka historyczno-artystyczna wล›rรณd innych dyscyplin naukowych <br/> Cz. 1 <br/> Instytut Historii Sztuki UWr, Szewska 36, sala 309', 'LecturesPlanThursday2Table4' : '<b>Sekcja 4</b><br/> Sympozjon โ€“ Anzelmiaล„ski argument za istnieniem Boga <br/> Instytut Historyczny UWr, Szewska 49, sala 18', 'LecturesPlanThursday2Table5' : '<b>Sekcja 5</b><br/> Islam i jego zaล‚oลผyciel w kulturze europejskiego Wschodu i Zachodu w ล›redniowieczu <br/> Cz. 1 <br/> Instytut Historyczny UWr, Szewska 49, sala 13', 'LecturesPlanThursday2Table6' : '<b>Sekcja 6</b><br/> ลšredniowiecze w nas', 'LecturesPlanThursday2Table7' : '<b>Sekcja 7</b><br/> Hortus medievalis <br/> Sekcja otwarta <br/> Instytut Historyczny UWr, Szewska 49, sala 138', 'LecturesPlanThursday1c' : '13.45โ€“15.00. Obiad', 'LecturesPlanThursday1cDinner' : 'Budynek D Wydziaล‚u Prawa, Administracji i Ekonomii UWr, ul. Uniwersytecka 7-10, Hol Gล‚รณwny', 'Dinner' : 'Obiad', 'LecturesPlanThursday3' : '15.00โ€“18.45. Sekcje', 'LecturesPlanThursday3Table1' : '<b>Sekcja 1</b><br/> Od โ€ž<NAME>โ€ do Korony Krรณlestwa Polskiego. Cywilizacyjne i ideowe podstawy ksztaล‚towania polskiej paล„stwowoล›ci w dobie Piastรณw <br/> Cz. 2 <br/> Instytut Historyczny UWr, Szewska 49, Audytorium', 'LecturesPlanThursday3Table2' : '<b>Sekcja 2</b><br/> Ruล› Waregรณw. Archeologia i historia <br/> Cz. 2 <br/> IAE PAN, Wiฤ™zienna 6, sala im. Anny i <NAME>', 'LecturesPlanThursday3Table3' : '<b>Sekcja 3</b><br/> Mediewistyka historyczno-artystyczna wล›rรณd innych dyscyplin naukowych <br/> Cz. 2 <br/> Instytut Historii Sztuki UWr, Szewska 36, sala 309', 'LecturesPlanThursday3Table4' : '<b>Sekcja 8</b><br/> Historiografia w krฤ™gu kultury pisma w ล›redniowieczu <br/> Instytut Historyczny UWr, Szewska 49, sala 138', 'LecturesPlanThursday3Table5' : '<b>Sekcja 5</b><br/> Islam i jego zaล‚oลผyciel w kulturze europejskiego Wschodu i Zachodu w ล›redniowieczu <br/> Cz. 2 <br/> Instytut Historyczny UWr, Szewska 49, sala 13', 'LecturesPlanThursday3Table6' : '<b>Sekcja 9</b><br/> Demografia Imperium bizantyjskiego <br/> Instytut Historyczny UWr, Szewska 49, sala 13', 'LecturesPlanThursday3Table7' : '<b>Sekcja 10</b><br/> Mediewalizm w kulturze (XVI-XXI w.) <br/> Instytut Historyczny UWr, Szewska 49, sala 240', 'LecturesPlanThursday3Content1' : 'Uwaga: Przerwa na kawฤ™/herbatฤ™ 16.45-17.00. Sekcje mogฤ… zakoล„czyฤ‡ obrady wczeล›niej niลผ o godz. 18.45, stosownie do liczby referatรณw.', 'LecturesPlanThursday4' : 'Godz. 19.00โ€“21.00. Projekcja filmu z cyklu Tajemnice poczฤ…tkรณw Polski (reลผ. Zdzisล‚aw Cozac) i dyskusja z udziaล‚em Reลผysera', 'LecturesPlanThursday4Place' : 'Budynek D Wydziaล‚u Prawa, Administracji i Ekonomii UWr, ul. Uniwersytecka 7-10, sala 2D im. Witolda ลšwidy', 'LecturesPlanThursday1d' : '16.30โ€“17.00 Kawa/herbata (Uwaga: przerwa 15 minut we wskazanym przedziale czasowym)', 'LecturesPlanThursday1dPlace' : 'Instytut Historyczny UWr, Szewska 49, sala 14', 'LecturesPlanFriday' : 'Piฤ…tek (21.09.2018)', 'LecturesPlanFriday1' : 'Godz. 9.00โ€“11.15. Sekcje i warsztaty', 'LecturesPlanFriday1Table1' : '<b>Sekcja 11</b><br/> Od grodu do miasta lokacyjnego na ziemiach polskich w kontekล›cie europejskim (dyskusja panelowa) <br/> Instytut Historyczny UWr, Szewska 49, sala 138 ', 'LecturesPlanFriday1Table2' : '<b>Sekcja 12</b><br/> Rok 1018 (dyskusja panelowa) <br/> Instytut Historyczny UWr, Szewska 49, Audytorium', 'LecturesPlanFriday1Table3' : '<b>Sekcja 13</b><br/> ลšredniowieczne miejsca grzebalne i ich spoล‚eczne uwarunkowania <br/> Instytut Historyczny UWr, Szewska 49, sala 13', 'LecturesPlanFriday1Table4' : '<b>Sekcja 14</b><br/> W cieniu starego cesarstwa: bizantyล„skie Baล‚kany od VII do koล„ca XII wieku <br/> Cz. 1 <br/> IAE PAN, Wiฤ™zienna 6, sala im. Anny i <NAME>', 'LecturesPlanFriday1Table5' : '<b>Sekcja 15</b><br/> Dziedzictwo polsko-ruskie w dziejach Europy ลšrodkowo-Wschodniej <br/> Cz. 1 <br/> Instytut Historyczny UWr, Szewska 49, sala 240', 'LecturesPlanFriday1Table6' : '<b>Sekcja 6</b><br/> ลšredniowiecze w nas (dyskusja panelowa) <br/> Instytut Historyczny UWr, Szewska 49, sala 18 ', 'LecturesPlanFriday1Table7' : '<b>WARSZAT 1</b><br/>Kodykologia jako narzฤ™dzie w warsztacie historyka-mediewisty <br/> Biblioteka UWr, ul. Fryderyka Joliot-Curie 12 (spotkanie o 9.00 przy punkcie informacyjnym)', 'LecturesPlanFriday1Table8' : '<b>WARSZAT 2</b><br/>(otwarty)<br/>Gry i zabawy ล›redniowieczne <br/> Instytut Historyczny UWr, Szewska 49, sala 14', 'LecturesPlanFriday1a' : '11.15โ€“11.45. Kawa/herbata', 'LecturesPlanFriday1aPlace' : 'Budynek D Wydziaล‚u Prawa, Administracji i Ekonomii UWr, ul. Uniwersytecka 7-10, Hol Gล‚รณwny', 'LecturesPlanFriday1Content1' : 'Kawa/herbata', 'LecturesPlanFriday2' : 'Godz. 11.45โ€“14.00. Sesja plenarna 2 (wykล‚ady)', 'LecturesPlanFriday2Place' : 'Budynek D Wydziaล‚u Prawa, Administracji i Ekonomii UWr, ul. Uniwersytecka 7-10, sala 1D im. Unii Europejskiej', 'LecturesPlanFriday2a' : '14.00โ€“15.15. Obiad', 'LecturesPlanFriday2aPlace' : 'Budynek D Wydziaล‚u Prawa, Administracji i Ekonomii UWr, ul. Uniwersytecka 7-10, Hol Gล‚รณwny', 'LecturesPlanFriday2Content1' : '(Prof. dr hab. <NAME>, Prof. dr hab. <NAME>, Prof. dr hab. <NAME>, Prof. dr hab. <NAME>)', 'LecturesPlanFriday2Content2' : 'Obiad', 'LecturesPlanFriday3' : 'Godz. 15.15โ€“19.00. Sekcje i warsztat', 'LecturesPlanFriday3Table1' : '<b>Sekcja 17</b><br/> Ksztaล‚towanie siฤ™ paล„stwa polskiego w perspektywie badaล„ numizmatycznych <br/> Instytut Historyczny UWr, Szewska 49, sala 138', 'LecturesPlanFriday3Table2' : '<b>Sekcja 18</b><br/> ลšredniowieczne struktury osadnicze w perspektywie nowych metod badawczych <br/> Instytut Historyczny UWr, Szewska 49, sala 13', 'LecturesPlanFriday3Table3' : '<b>Sekcja 19</b><br/> Badaฤ‡ ล›redniowiecze w Maล‚opolsce; interdyscyplinarnoล›ฤ‡ โ€“ wieloล›ฤ‡ metod โ€“ zaskakujฤ…ce rezultaty <br/> Instytut Historii Sztuki UWr, ul. Szewska 36, sala 306', 'LecturesPlanFriday3Table4' : '<b>Sekcja 20</b><br/> Biblia w ล›redniowieczu: interpretacja, przekล‚ady na jฤ™zyk polski i ich znaczenie <br/> Instytut Historyczny UWr, Szewska 49, sala 241', 'LecturesPlanFriday3Table5' : '<b>Sekcja 14</b><br/> W cieniu starego cesarstwa: bizantyล„skie Baล‚kany od VII do koล„ca XII wieku <br/> Cz. 2 <br/> IAE PAN, Wiฤ™zienna 6, sala im. Anny i <NAME>', 'LecturesPlanFriday3Table6' : '<b>Sekcja 15</b><br/> Dziedzictwo polsko-ruskie w dziejach Europy ลšrodkowo-Wschodniej <br/> Cz. 2 <br/> Instytut Historyczny UWr, Szewska 49, sala 240', 'LecturesPlanFriday3Table7' : '<b>Sekcja 21</b><br/> Wzajemne postrzeganie Niemcรณw i Polakรณw w ล›redniowieczu โ€“ rola stereotypรณw narodowych w historii i w kulturze <br/> Instytut Historyczny UWr, Szewska 49, sala 18', 'LecturesPlanFriday3Table8' : '<b>Sekcja 16</b><br/> Dziedzictwo Barbaricum w ล›redniowiecznej Europie i jego mitologizacja w historiografii XIX-XXI w. <br/>Cz. 2 <br/> Instytut Historyczny UWr, Szewska 49, Audytorium', 'LecturesPlanFriday3Table9' : '<b>Sekcja 22</b><br/> Konstruowanie wizji epoki ล›redniowiecznej w drugiej poล‚owie XIX i pierwszej poล‚owie XX w. <br/> Instytut Historii Sztuki UWr, Szewska 36, sala 309', 'LecturesPlanFriday3Table10' : '<b>WARSZTAT 3</b><br/>(od godz. 17.15)<br/>Nowoczesne metody w archeologii ล›redniowiecza<br/>Instytut Historyczny UWr, Szewska 49, sala 13', 'LecturesPlanFriday3Content1' : 'Uwaga: Przerwa na kawฤ™/herbatฤ™ 17.00-17.15. Sekcje mogฤ… zakoล„czyฤ‡ obrady wczeล›niej niลผ o godz. 18.45, stosownie do liczby referatรณw.', 'LecturesPlanFriday3a' : '16.45โ€“17.15 Kawa/herbata (Uwaga: przerwa 15 minut we wskazanym przedziale czasowym)', 'LecturesPlanFriday3aPlace' : 'Instytut Historyczny UWr,, Szewska 49, sala 14', 'LecturesPlanFriday4' : 'Godz. 20.00-22.00. Uroczysta kolacja', 'LecturesPlanFriday4Place' : 'Budynek D Wydziaล‚u Prawa, Administracji i Ekonomii UWr, ul. Uniwersytecka 7-10, Hol Gล‚รณwny', 'LecturesPlanSaturday' : 'Sobota (22.09.2018)', 'LecturesPlanSaturday1' : 'Godz. 9.00โ€“11.15. Sekcje i warsztat', 'LecturesPlanSaturday1Table1' : '<b>Sekcja 23</b><br/> Od sfer niebiaล„skich do miast i wsi โ€“ przestrzenie czล‚owieka ล›redniowiecznego (dyskusja panelowa) <br/>Instytut Historyczny UWr, Szewska 49, Audytorium', 'LecturesPlanSaturday1Table2' : '<b>Sekcja 24</b><br/> Latinitas medii aevi โ€“ ลผywy jฤ™zyk martwy, ponadnarodowy standard i wernakularne tendencje <br/> Instytut Historyczny UWr, Szewska 49, sala 241', 'LecturesPlanSaturday1Table3' : '<b>Sekcja 25</b><br/> Adaptacja historii <br/>Instytut Historyczny UWr, Szewska 49, sala 18', 'LecturesPlanSaturday1Table4' : '<b>Sekcja 26</b><br/> Z dziejรณw Skandynawii ล›redniowiecznej: kultura, wล‚adza, spoล‚eczeล„stwo<br/>Instytut Historyczny UWr, Szewska 49, sala 138', 'LecturesPlanSaturday1Table5' : '<b>Sekcja 27</b><br/> Pomorze, Polska i ich sฤ…siedzi w ksztaล‚towaniu cywilizacji europejskiej (do przeล‚omu XII/XIII w.) โ€“ temat rzeka <br/> Instytut Historyczny UWr, Szewska 49, sala 13', 'LecturesPlanSaturday1Table6' : '<b>Sekcja 28</b><br/> Rekonstrukcja historyczna: nauka zabawฤ…, zabawa naukฤ…? (dyskusja panelowa) <br/> Instytut Historyczny UWr, Szewska 49, sala 14', 'LecturesPlanSaturday1Table7' : 'Hortus medievalis Sekcja otwarta <br/> Cz. 2', 'LecturesPlanSaturday1Table8' : '<b>WARSZTAT 4</b><br/> โ€žHistoryk przed kamerฤ…โ€ <br/> Instytut Historyczny UWr, Szewska 49, sala 240', 'LecturesPlanSaturday1a' : '11.15โ€“11.45. Kawa/herbata', 'LecturesPlanSaturday1aPlace' : 'Budynek D Wydziaล‚u Prawa, Administracji i Ekonomii UWr, ul. Uniwersytecka 7-10, Hol Gล‚รณwny', 'LecturesPlanSaturday2a' : '13.30โ€“14.30. Obiad', 'LecturesPlanSaturday2aPlace' : 'Budynek D Wydziaล‚u Prawa, Administracji i Ekonomii UWr, ul. Uniwersytecka 7-10, Hol Gล‚รณwny', 'LecturesPlanSaturday2' : 'Godz. 11.45โ€“13.30. Sesja plenarna 3 (wykล‚ady)', 'LecturesPlanSaturday2Content1' : 'Budynek D Wydziaล‚u Prawa, Administracji i Ekonomii UWr, ul. Uniwersytecka 7-10, sala 1D im. Unii Europejskiej', 'LecturesPlanSaturday2Content2' : 'Obiad', 'LecturesPlanSaturday3' : '14.30โ€“16.00. Sesja plenarna 4 (dyskusja panelowa)', 'LecturesPlanSaturday3Content1' : 'Gmach Gล‚รณwny UWr,, Pl. Uniwersytecki 1, Oratorium Marianum', 'LecturesPlanSaturday3a' : '16.00โ€“16.30. Zakoล„czenie VI Kongresu Mediewistรณw Polskich', 'LecturesPlanSaturday3aPlace' : 'Gmach Gล‚รณwny UWr,, Pl. Uniwersytecki 1, Oratorium Marianum', 'LecturesPlanSaturday4' : '16.00-16.30. Zakoล„czenie kongresu', 'LecturesPlanSaturday4Table1' : '<b>Uwaga:</b> powyลผszy plan obrad ma charakter roboczy i mogฤ… nastฤ…piฤ‡ w nim pewne korekty (zwล‚aszcza w tytuล‚ach sekcji). Organizatorzy sekcji wymienieni sฤ… na: www.vikmp.pl, tam teลผ w najbliลผszych dniach zamieszczony zostanie szczegรณล‚owy program obrad.', 'DownloadLecturesPlan' : 'Pobierz ramowy plan obrad', 'DownloadProgram' : 'Pobierz program kongresu', 'PatronagePresident' : 'Prezydent miasta <br /> <NAME>', 'papa-rektor-title' : 'Rektor Papieskiego Wydziaล‚u Teologicznego we Wrocล‚awiu', 'papa-rektor-name' : 'Jego Magnificencja ks. prof. dr hab. <NAME>', 'patronsandorganizers' : 'Patroni i organizatorzy', 'marszalek-title' : 'Marszaล‚ek Wojewรณdztwa Dolnoล›lฤ…skiego', 'marszalek-name' : '<NAME>', 'president-title' : 'Prezydent miasta Wrocล‚awia', 'president-name' : '<NAME>', 'pan-rektor-title' : 'Dyrektor Instytutu Archeologii i Etnologii PAN', 'pan-rektor-name' : 'Prof. dr hab. <NAME>', 'Help' : 'Wsparcie', 'HistoriaAetas' : 'Media aetas historia viva!', 'MinInfo' : 'Organizacja VI Kongresu Mediewistรณw Polskich - zadanie finansowane w ramach umowy 511/P-DUNdem/2018 <br /> ze ล›rodkรณw Ministra Nauki i Szkolnictwa Wyลผszego <br /> przeznaczonych na dziaล‚alnoล›ฤ‡ upowszechniajฤ…cฤ… naukฤ™' }; <file_sep>import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http'; import { User } from '../models/user'; import { Observable } from 'rxjs/Rx'; import { UserInfo } from "app/models/user-info"; import { Config } from "app/utils/config"; @Injectable() export class UserInfoService { private allUsersInfoUrl = Config.serverAddress + '/allUsersInfo'; private acceptedUsersInfoUrl = Config.serverAddress + '/acceptedUsersInfoUrl'; private pendingUsersInfoUrl = Config.serverAddress + '/pendingUsersInfoUrl'; private rejectedUsersInfoUrl = Config.serverAddress + '/rejectedUsersInfoUrl'; private speakersUsersInfoUrl = Config.serverAddress + '/speakersUsersInfoUrl'; private paymentAcceptedUsersInfoUrl = Config.serverAddress + '/paymentAcceptedUsersInfoUrl'; private paymentPendingUsersInfoUrl = Config.serverAddress + '/paymentPendingUsersInfoUrl'; private workshopUsersInfoUrl = Config.serverAddress + '/workshopUsersInfoUrl'; private invoiceUsersInfoUrl = Config.serverAddress + '/invoiceUsersInfoUrl'; constructor( private http: Http ) { } getAllUsersInfo(): Observable<UserInfo> { // ...using get request return this.http.get( this.allUsersInfoUrl ) // ...and calling .json() on the response to return data .map(( res: Response ) => { let userInfo = res.json(); return userInfo; }) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } getAcceptedUsersInfo(): Observable<UserInfo> { // ...using get request return this.http.get( this.acceptedUsersInfoUrl ) // ...and calling .json() on the response to return data .map(( res: Response ) => { let userInfo = res.json(); return userInfo; }) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } getPendingUsersInfo(): Observable<UserInfo> { // ...using get request return this.http.get( this.pendingUsersInfoUrl ) // ...and calling .json() on the response to return data .map(( res: Response ) => { let userInfo = res.json(); return userInfo; }) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } getRejectedUsersInfo(): Observable<UserInfo> { // ...using get request return this.http.get( this.rejectedUsersInfoUrl ) // ...and calling .json() on the response to return data .map(( res: Response ) => { let userInfo = res.json(); return userInfo; }) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } getSpeakersUsersInfo(): Observable<UserInfo> { // ...using get request return this.http.get( this.speakersUsersInfoUrl ) // ...and calling .json() on the response to return data .map(( res: Response ) => { let userInfo = res.json(); return userInfo; }) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } getPaymentAcceptedUsersInfo(): Observable<UserInfo> { // ...using get request return this.http.get( this.paymentAcceptedUsersInfoUrl ) // ...and calling .json() on the response to return data .map(( res: Response ) => { let userInfo = res.json(); return userInfo; }) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } getPaymentPendingUsersInfo(): Observable<UserInfo> { // ...using get request return this.http.get( this.paymentPendingUsersInfoUrl ) // ...and calling .json() on the response to return data .map(( res: Response ) => { let userInfo = res.json(); return userInfo; }) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } getWorkshopUsersInfo(): Observable<UserInfo> { // ...using get request return this.http.get( this.workshopUsersInfoUrl ) // ...and calling .json() on the response to return data .map(( res: Response ) => { let userInfo = res.json(); return userInfo; }) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } getInvoiceUsersInfo(): Observable<UserInfo> { // ...using get request return this.http.get( this.invoiceUsersInfoUrl ) // ...and calling .json() on the response to return data .map(( res: Response ) => { let userInfo = res.json(); return userInfo; }) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } }<file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { AdminMailboxComponent } from './admin-mailbox.component'; describe('AdminMailboxComponent', () => { let component: AdminMailboxComponent; let fixture: ComponentFixture<AdminMailboxComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ AdminMailboxComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(AdminMailboxComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should be created', () => { expect(component).toBeTruthy(); }); }); <file_sep>import { Injectable, } from '@angular/core'; import { ActivatedRouteSnapshot, Resolve, Router, RouterStateSnapshot } from '@angular/router'; import { Observable } from 'rxjs/Rx'; import { Schedule } from "app/models/schedule"; @Injectable() export class ScheduleNewResolver implements Resolve<Schedule> { constructor( private router: Router, ) { } resolve( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable<Schedule> { console.log('wywolano schedule new resolver') return Observable.create( observer => { observer.next( new Schedule( '', '' ) ); observer.complete(); } ); } }<file_sep>import { TestBed, inject } from '@angular/core/testing'; import { CommentNewsService } from './comment-news.service'; describe('CommentNewsService', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [CommentNewsService] }); }); it('should be created', inject([CommentNewsService], (service: CommentNewsService) => { expect(service).toBeTruthy(); })); }); <file_sep>export class WorkshopUser { constructor( public fk_user: string, public fk_workshop: string ) { } }<file_sep>import { Component, OnInit } from '@angular/core'; import { Config } from "app/utils/config"; @Component({ selector: 'app-header', templateUrl: './header.component.html', styleUrls: ['./header.component.css'] }) //http://cssreset.com/creating-fixed-headers-with-css/ export class HeaderComponent implements OnInit { constructor() { } ngOnInit() { } isAdmin() { let admintoken = localStorage.getItem( 'admintoken' ); return ( admintoken ); } isShowMap() { return Config.isShowMap(); } isShowLinks() { return Config.isShowLinks(); } isShowNews() { return Config.isShowNews(); } isShowArticles() { return Config.isShowArticles(); } } <file_sep>import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http'; //Import RxJs required methods import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import { Observable } from 'rxjs/Rx'; import { Config } from "app/utils/config"; import { Lecture } from "app/models/lecture"; @Injectable() export class LectureService { constructor( private http: Http ) { } private lecturesUrl = Config.serverAddress + '/lectures'; private lectureUrl = Config.serverAddress + '/lecture'; private deletedLecturesUrl = Config.serverAddress + '/deletedLectures'; private deleteLectureUrl = Config.serverAddress + '/deleteLecture'; private activateLectureUrl = Config.serverAddress + '/activateLecture'; getLectures(): Observable<Lecture[]> { // ...using get request return this.http.get( this.lecturesUrl ) // ...and calling .json() on the response to return data .map(( res: Response ) => res.json() ) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } getDeletedLectures(): Observable<Lecture[]> { return this.http.get( this.deletedLecturesUrl ) // ...and calling .json() on the response to return data .map(( res: Response ) => res.json() ) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } //TODO serwer i testy getLecture( id: string ): Observable<any> { let params: URLSearchParams = new URLSearchParams(); params.set( 'id', id ); var options = new RequestOptions( { headers: new Headers( { 'Content-Type': 'application/json' } ) } ); options.search = params; // ...using get request return this.http.get( this.lectureUrl, options ) // ...and calling .json() on the response to return data .map(( res: Response ) => res.json() ) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } get(id): Observable<Lecture> { return this.getLecture(id) .map(data => data.article); } addLecture( body: Lecture ): Observable<Lecture[]> { let headers = new Headers( { 'Content-Type': 'application/json' } ); let options = new RequestOptions( { headers: headers } ); return this.http.post( this.lectureUrl, JSON.stringify( body ), options ) .map(( res: Response ) => res.json() ) // ...and calling .json() on the response to return data .catch(( error: any ) => Observable.throw( error || 'Server error' ) ); //...errors if any } updateLecture( body: Lecture ): Observable<Lecture[]> { let headers = new Headers( { 'Content-Type': 'application/json' } ); let options = new RequestOptions( { headers: headers } ); return this.http.put( this.lectureUrl, JSON.stringify( body ), options ) .map(( res: Response ) => res.json() ) // ...and calling .json() on the response to return data .catch(( error: any ) => Observable.throw( error || 'Server error' ) ); //...errors if any } deleteLecture( body: Lecture ): Observable<Lecture[]> { let headers = new Headers( { 'Content-Type': 'application/json' } ); let options = new RequestOptions( { headers: headers } ); return this.http.post( this.deleteLectureUrl, JSON.stringify( body ), options ) .map(( res: Response ) => res.json() ) // ...and calling .json() on the response to return data .catch(( error: any ) => Observable.throw( error || 'Server error' ) ); //...errors if any } activateLecture( body: Lecture ): Observable<Lecture[]> { let headers = new Headers( { 'Content-Type': 'application/json' } ); let options = new RequestOptions( { headers: headers } ); return this.http.post( this.activateLectureUrl, JSON.stringify( body ), options ) .map(( res: Response ) => res.json() ) // ...and calling .json() on the response to return data .catch(( error: any ) => Observable.throw( error || 'Server error' ) ); //...errors if any } } <file_sep>export const LANG_DE_NAME = 'de'; export const LANG_DE_TRANS = { 'enrolments-list': 'Anmeldungsliste', 'Clear': '---' };<file_sep>import { Component, OnInit } from '@angular/core'; import { News } from "app/models/news"; import { ActivatedRoute, Router } from "@angular/router"; import { ConfirmationService, MenuItem } from "primeng/primeng"; import { Message } from "primeng/components/common/api"; import { NewsService } from "app/services/news.service"; import { NewsHistory } from "app/models/news-history"; @Component( { selector: 'admin-single-news', templateUrl: './admin-single-news.component.html', styleUrls: ['./admin-single-news.component.css'] } ) //todo wlasciwa nawigacja //todo co jak nie znajdzie news? export class AdminSingleNewsComponent implements OnInit { text: string; news: News; newsHistory: NewsHistory[]; msgs: Message[] = []; navigationItems: MenuItem[]; constructor( private route: ActivatedRoute, private router: Router, private newsService: NewsService, private confirmationService: ConfirmationService ) { } ngOnInit() { this.route.data.subscribe( ( data: { news: News } ) => { if ( data.news ) { this.news = data.news; } else { //TODO Michal error and redirect } } ); this.navigationItems = []; this.navigationItems.push( { label: 'Admin' } ); this.navigationItems.push( { label: 'Artykuly' } ); this.navigationItems.push( { label: 'Sekcja XV wiek' } ); this.navigationItems.push( { label: 'O bitwie pod Grunwaldem', url: 'https://en.wikipedia.org/wiki/Lionel_Messi' } ); } saveNew() { //todo get from localStorage.getItem( 'token' ) this.news.fk_editor = '1'; this.newsService.addNews( this.news ).subscribe( articles => { // Emit list event // //navigate // EmitterService.get( this.listId ).emit( enrolments ); // Empty model this.navigateBack(); }, err => { // Log errors if any console.log( err ); } ); //TODO Michal tymczasowo bo nie ma odpowiedzi this.navigateBack(); } save() { //todo get from localStorage.getItem( 'token' ) this.news.fk_editor = '1'; this.newsService.updateNews( this.news ).subscribe( articles => { // Emit list event // //navigate // EmitterService.get( this.listId ).emit( enrolments ); // Empty model this.navigateBack(); }, err => { // Log errors if any console.log( err ); } ); //TODO odpowiedz i bledy //TODO Michal tymczasowo bo nie ma odpowiedzi this.navigateBack(); } cancel() { this.navigateBack(); } isNew() { return ( !this.news.id || 0 === this.news.id.length ); } isDeleted() { return 'D' === this.news.status } getNewsHistory() { this.newsService.getNewsHistory( this.news.id ) .subscribe( n => this.newsHistory = n, //Bind to view err => { // Log errors if any console.log( err ); } ); } confirmDelete() { this.confirmationService.confirm( { message: 'Do you want to delete this record?', header: 'Delete Confirmation', icon: 'fa fa-trash', accept: () => { this.msgs = [{ severity: 'info', summary: 'Confirmed', detail: 'Record deleted' }]; this.deleteNews(); }, reject: () => { this.msgs = [{ severity: 'info', summary: 'Rejected', detail: 'You have rejected' }]; } } ); } deleteNews() { this.newsService.deleteNews( this.news ).subscribe( articles => { // Emit list event // //navigate // EmitterService.get( this.listId ).emit( enrolments ); // Empty model this.navigateBack(); }, err => { // Log errors if any console.log( err ); } ); } activateNews() { this.newsService.activateNews( this.news ).subscribe( articles => { // Emit list event // //navigate // EmitterService.get( this.listId ).emit( enrolments ); // Empty model this.navigateBack(); }, err => { // Log errors if any console.log( err ); } ); } navigateBack() { this.router.navigate(['/admin', {outlets: {adminRouting: ['admin-news']}}]) } } <file_sep>import { Component, OnInit, Input } from '@angular/core'; import { ActivatedRoute, Router } from "@angular/router"; import { Lecture } from "app/models/lecture"; @Component( { selector: 'lecture', templateUrl: './lecture.component.html', styleUrls: ['./lecture.component.css'] } ) export class LectureComponent implements OnInit { @Input() lecture: Lecture; constructor( private route: ActivatedRoute, private router: Router ) { } ngOnInit() { window.scrollTo( 0, 0 ) } } <file_sep>import { Component, OnInit, Input } from '@angular/core'; import { ArticleHistory } from "app/models/article-history"; @Component( { selector: 'admin-article-history', templateUrl: './admin-article-history.component.html', styleUrls: ['./admin-article-history.component.css'] } ) export class AdminArticleHistoryComponent implements OnInit { @Input() articlesHistory: ArticleHistory[]; constructor() { } ngOnInit() { } } <file_sep>import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { ContactMessage } from "app/models/contact-message"; import { Observable } from 'rxjs/Rx'; //Import RxJs required methods import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import { ForgotPasswordMessage } from "app/models/forgot-password-message"; import { Config } from "app/utils/config"; @Injectable() export class ContactService { constructor( private http: Http ) { } private contactUrl = Config.serverAddress + '/contactMessage'; private contactsUrl = Config.serverAddress + '/adminMessages'; private forgotPasswordUrl = Config.serverAddress + '/forgotPassword'; addMessage( body: ContactMessage ): any { let headers = new Headers( { 'Content-Type': 'application/json' } ); let options = new RequestOptions( { headers: headers } ); return this.http.post( this.contactUrl, JSON.stringify( body ), options ) .map(( res: Response ) => { return true; }) .catch(( error: any ) => Observable.throw( error || 'Server error' ) ); //...errors if any } sendAdminMessages( body: ContactMessage ): any { let headers = new Headers( { 'Content-Type': 'application/json' } ); let options = new RequestOptions( { headers: headers } ); return this.http.post( this.contactsUrl, JSON.stringify( body ), options ) .map(( res: Response ) => { return true; }) .catch(( error: any ) => Observable.throw( error || 'Server error' ) ); //...errors if any } sendPassword( body: ForgotPasswordMessage ): any { let headers = new Headers( { 'Content-Type': 'application/json' } ); let options = new RequestOptions( { headers: headers } ); return this.http.post( this.forgotPasswordUrl, JSON.stringify( body ), options ) .map(( res: Response ) => { return true; }) .catch(( error: any ) => Observable.throw( error || 'Server error' ) ); //...errors if any } } <file_sep>import { TestBed, inject } from '@angular/core/testing'; import { UserService } from './user.service'; describe( 'UserServiceService', () => { beforeEach(() => { TestBed.configureTestingModule( { providers: [UserService] } ); } ); it( 'should be created', inject( [UserService], ( service: UserService ) => { expect( service ).toBeTruthy(); } ) ); } ); <file_sep>import { Component, OnInit } from '@angular/core'; import { Article } from "app/models/article"; import { ArticleService } from '../services/article.service'; import { EmitterService } from '../services/emitter.service'; import { LocalDataSource } from "ng2-smart-table/ng2-smart-table"; import { Router } from "@angular/router"; import { AdminTableButtonComponent } from "app/admin-table-button/admin-table-button.component"; import { DatePipe } from "@angular/common"; @Component( { selector: 'admin-articles', templateUrl: './admin-articles.component.html', styleUrls: ['./admin-articles.component.css'] } ) //https://akveo.github.io/ng2-smart-table export class AdminArticlesComponent implements OnInit { articles: Article[]; source: LocalDataSource; activeArticleView: boolean; constructor( private articleService: ArticleService, private router: Router ) { this.source = new LocalDataSource(); this.articleService.getArticles().toPromise().then(( data ) => { this.source.load( data ); } ); this.activeArticleView = true; } ngOnInit() { // Load articles // this.loadArticles() } loadArticles() { this.articleService.getArticles().toPromise().then(( data ) => { this.source.load( data ); } ); } loadDeletedArticles() { this.articleService.getDeletedArticles().toPromise().then(( data ) => { this.source.load( data ); } ); } //TODO Michal translacja przez serwis settings = { columns: { author: { title: 'Autor' }, title: { title: 'Tytul' }, edited: { title: 'Edytowal' }, editdate: { title: 'Data edycji', type: 'html', valuePrepareFunction: ( value ) => { var datePipe = new DatePipe( 'pl-PL' ); return datePipe.transform( value, 'dd.MM.yyyy' ); } }, //TODO wpasowac w routingAdmin admin/(adminRouting:admin-articles) //return '<a href="/admin-article/' + row.id + '">Edytuj</a>' link: { title: 'Akcja', type: 'html', valuePrepareFunction: ( cell, row ) => { return '<a href="/admin-article/' + row.id + '">Edytuj</a>' } }, // button: { // title: 'Button', // type: 'custom', // renderComponent: AdminTableButtonComponent, // onComponentInitFunction(instance) { // instance.save.subscribe(row => { // alert(`${row.name} saved!`) // }); // } // } }, actions: false }; createNew() { this.router.navigate( ['admin-article-new/'] ); } isShowActive() { return this.activeArticleView; } showDeletedArticles() { this.loadDeletedArticles(); this.activeArticleView = false; } showActiveArticles() { this.loadArticles(); this.activeArticleView = true; } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { Article } from "app/models/article"; import { Comment } from "app/models/comment"; import { CommentService } from "app/services/comment.service"; @Component( { selector: 'app-article', templateUrl: './article.component.html', styleUrls: ['./article.component.css'] } ) //Nawigacja: https://github.com/gothinkster/angular-realworld-example-app/blob/master/src/app/editor/editor.component.ts //Layout: https://startbootstrap.com/template-overviews/blog-post/ export class ArticleComponent implements OnInit { article: Article; comments: Comment[]; comment = new Comment( '', null, '', '', '', '', null, '', '', '' ); userid: string; constructor( private route: ActivatedRoute, private router: Router, private commentService: CommentService ) { } ngOnInit() { this.route.data.subscribe( ( data: { article: Article } ) => { if ( data.article ) { this.article = data.article; } else { //TODO Michal error and redirect } } ); if ( this.article.id ) { //TODO w zaleznosci od uzytkownika this.loadAllComments(); } } loadAllComments() { this.commentService.getAllComments( this.article.id ) .subscribe( c => this.comments = c, //Bind to view err => { // Log errors if any console.log( err ); } ); } loadConfirmedComments() { this.commentService.getConfirmedComments( this.article.id ) .subscribe( c => this.comments = c, //Bind to view err => { // Log errors if any console.log( err ); } ); } addNewComment() { //todo get from localStorage.getItem( 'token' ) //rozroznienie na tworzenie parent comment i comment this.comment.fk_user = this.userid; this.comment.fk_post = this.article.id; //todo if uprawnienia //todo admin user ma od razu zatwierdzony post this.commentService.addParentCommentAdminUser( this.comment ).subscribe( c => this.comments = c //todo dymek? , err => { // Log errors if any console.log( err ); } ); this.comment = new Comment( '', null, '', '', '', '', null, '', '', '' ); } isLogged() { this.userid = localStorage.getItem( 'userid' ); return ( this.userid ); } } <file_sep>import { Component, OnInit, Input } from '@angular/core'; import { Person } from './person'; import { Enrolment } from '../models/enrolment' import { EnrolmentService } from '../services/enrolment.service'; import { Observable } from 'rxjs/Rx'; import { EmitterService } from "app/services/emitter.service"; import { AutoCompleteModule } from 'primeng/primeng'; import { University } from "../models/university"; import { UniversityService } from "app/services/university.service"; @Component( { selector: 'application-form', templateUrl: './application-form.component.html', styleUrls: ['./application-form.component.css'] } ) //https://www.primefaces.org/primeng/#/autocomplete export class ApplicationFormComponent implements OnInit { ngOnInit(): void { } @Input() listId: string; @Input() editId: string; universities: University[]; constructor( private enrolmentService: EnrolmentService, private universityService: UniversityService ) { } submitted = false; enrolment = new Enrolment( '', '', '', null, '', '' ); submitEnrolment() { this.enrolment.date = new Date(); this.enrolmentService.addEnrolment( this.enrolment ).subscribe( response => { if ( response.text() === 'OK' ) { - console.log( 'udalo sie ' + response.text()); // this.submitted = true; // - this.router.navigate( ['admin'] ); } }, err => { // Log errors if any console.log( err ); } ); } newEnrolment() { this.enrolment = new Enrolment( '', '', '', null, '', '' ); this.submitted = false; } //TODO Michal usun to val1: string; abstrakt: string; text: string; results: string[]; loadUniversities() { // Get all enrolments this.universityService.getUniversities( this.enrolment.university ) .subscribe( universities => this.universities = universities, //Bind to view err => { // Log errors if any console.log( err ); } ); console.log( this.universities ); } search( event ) { // EmitterService.get( this.listId ).subscribe(( universities: University[] ) => { this.loadUniversities() } ); this.loadUniversities(); //todo dziala wolno, jakby co drugi znak if ( this.universities ) { this.results = this.universities.map( function( uni ) { return uni.name; } ) } ; } } <file_sep>import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http'; import { University } from '../models/university'; import { Observable } from 'rxjs/Rx'; //Import RxJs required methods import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import { Config } from "app/utils/config"; @Injectable() export class UniversityService { constructor( private http: Http ) { } private universitiesUrl = Config.serverAddress + '/universities'; getUniversities( university: string ): Observable<University[]> { let params: URLSearchParams = new URLSearchParams(); params.set( 'university', university ); var options = new RequestOptions({headers: new Headers({'Content-Type': 'application/json'})}); options.search = params; // ...using get request return this.http.get( this.universitiesUrl, options) // ...and calling .json() on the response to return data .map(( res: Response ) => res.json() ) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } } <file_sep>export class Config { public static serverAddress = 'http://172.16.58.3:3000'; //public static serverAddress = 'http://localhost:3000'; public static isShowLangs() { return false; } public static isShowArticles() { return true; } public static isShowNews() { return true; } public static isShowSchedule() { return false; } public static isShowMap() { return false; } public static isShowLinks() { return false; } public static isShowWorkshops() { return true; } public static isShowLectures() { return true; } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from "@angular/router"; import { ConfirmationService } from "primeng/primeng"; import { EventService } from "app/services/event.service"; import { LocalDataSource } from "ng2-smart-table/ng2-smart-table"; import { Event } from "app/models/event"; import { Message } from "primeng/components/common/api"; @Component( { selector: 'admin-event', templateUrl: './admin-event.component.html', styleUrls: ['./admin-event.component.css'], providers: [ConfirmationService] } ) export class AdminEventComponent implements OnInit { event: Event; msgs: Message[] = []; constructor( private route: ActivatedRoute, private router: Router, private eventService: EventService, private confirmationService: ConfirmationService ) { } ngOnInit() { this.route.data.subscribe( ( data: { event: Event } ) => { if ( data.event ) { this.event = data.event; } else { //TODO Michal error and redirect } } ); } saveNew() { this.eventService.addEvent( this.event ).subscribe( schedules => { // Emit list event // //navigate // EmitterService.get( this.listId ).emit( enrolments ); // Empty model this.router.navigate( ['admin-events'] ); }, err => { // Log errors if any console.log( err ); } ); this.router.navigate( ['admin-events'] ); } save() { this.eventService.updateEvent( this.event ).subscribe( articles => { // Emit list event // //navigate // EmitterService.get( this.listId ).emit( enrolments ); // Empty model this.router.navigate( ['admin-events'] ); }, err => { // Log errors if any console.log( err ); } ); //TODO odpowiedz i bledy this.router.navigate( ['admin-events'] ); } cancel() { this.router.navigate( ['admin-events'] ); } isNew() { return ( !this.event.id || 0 === this.event.id.length ); } confirmDelete() { this.confirmationService.confirm( { message: 'Do you want to delete this record?', header: 'Delete Confirmation', icon: 'fa fa-trash', accept: () => { this.msgs = [{ severity: 'info', summary: 'Confirmed', detail: 'Record deleted' }]; this.deleteEvent(); }, reject: () => { this.msgs = [{ severity: 'info', summary: 'Rejected', detail: 'You have rejected' }]; } } ); } deleteEvent() { this.eventService.deleteEvent( this.event ).subscribe( events => { // Emit list event // //navigate // EmitterService.get( this.listId ).emit( enrolments ); // Empty model this.router.navigate( ['admin-events'] ); }, err => { // Log errors if any console.log( err ); } ); } //todo opracowac przejscie z parametrem navigateBack() { this.router.navigate(['/admin', {outlets: {adminRouting: ['admin-schedule']}}]) } } <file_sep>import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http'; import { News } from '../models/news'; import { NewsHistory } from "app/models/news-history"; import { Observable } from 'rxjs/Rx'; //Import RxJs required methods import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import { Config } from "app/utils/config"; @Injectable() export class NewsService { constructor( private http: Http ) { } private allNewsUrl = Config.serverAddress + '/allnews'; private newsUrl = Config.serverAddress + '/news'; private deletedNewsUrl = Config.serverAddress + '/deletedNews'; private deleteNewsUrl = Config.serverAddress + '/deleteNews'; private activateNewsUrl = Config.serverAddress + '/activateNews'; private newsHistoryUrl = Config.serverAddress + '/newsHistory'; getNews(): Observable<News[]> { // ...using get request return this.http.get( this.allNewsUrl ) // ...and calling .json() on the response to return data .map(( res: Response ) => res.json() ) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } getDeletedNews(): Observable<News[]> { return this.http.get( this.deletedNewsUrl ) // ...and calling .json() on the response to return data .map(( res: Response ) => res.json() ) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } //TODO serwer i testy getSingleNews( id: string ): Observable<any> { let params: URLSearchParams = new URLSearchParams(); params.set( 'id', id ); var options = new RequestOptions( { headers: new Headers( { 'Content-Type': 'application/json' } ) } ); options.search = params; // ...using get request return this.http.get( this.newsUrl, options ) // ...and calling .json() on the response to return data .map(( res: Response ) => res.json() ) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } get(id): Observable<News> { return this.getSingleNews(id) .map(data => data.news); } getNewsHistory( id: string ): Observable<NewsHistory[]> { let params: URLSearchParams = new URLSearchParams(); params.set( 'id', id ); var options = new RequestOptions( { headers: new Headers( { 'Content-Type': 'application/json' } ) } ); options.search = params; // ...using get request return this.http.get( this.newsHistoryUrl, options ) // ...and calling .json() on the response to return data .map(( res: Response ) => res.json() ) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } addNews( body: News ): Observable<News[]> { let headers = new Headers( { 'Content-Type': 'application/json' } ); let options = new RequestOptions( { headers: headers } ); return this.http.post( this.newsUrl, JSON.stringify( body ), options ) .map(( res: Response ) => res.json() ) // ...and calling .json() on the response to return data .catch(( error: any ) => Observable.throw( error || 'Server error' ) ); //...errors if any } updateNews( body: News ): Observable<News[]> { let headers = new Headers( { 'Content-Type': 'application/json' } ); let options = new RequestOptions( { headers: headers } ); return this.http.put( this.newsUrl, JSON.stringify( body ), options ) .map(( res: Response ) => res.json() ) // ...and calling .json() on the response to return data .catch(( error: any ) => Observable.throw( error || 'Server error' ) ); //...errors if any } deleteNews( body: News ): Observable<News[]> { let headers = new Headers( { 'Content-Type': 'application/json' } ); let options = new RequestOptions( { headers: headers } ); return this.http.post( this.deleteNewsUrl, JSON.stringify( body ), options ) .map(( res: Response ) => res.json() ) // ...and calling .json() on the response to return data .catch(( error: any ) => Observable.throw( error || 'Server error' ) ); //...errors if any } activateNews( body: News ): Observable<News[]> { let headers = new Headers( { 'Content-Type': 'application/json' } ); let options = new RequestOptions( { headers: headers } ); return this.http.post( this.activateNewsUrl, JSON.stringify( body ), options ) .map(( res: Response ) => res.json() ) // ...and calling .json() on the response to return data .catch(( error: any ) => Observable.throw( error || 'Server error' ) ); //...errors if any } } <file_sep>import { Injectable, } from '@angular/core'; import { ActivatedRouteSnapshot, Resolve, Router, RouterStateSnapshot } from '@angular/router'; import { Observable } from 'rxjs/Rx'; import { News } from "app/models/news"; @Injectable() export class NewsNewResolver implements Resolve<News> { constructor( private router: Router, ) { } resolve( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable<News> { //todo michal status return Observable.create( observer => { observer.next( new News( '', '', '', '', '', 'A' ) ); observer.complete(); } ); } }<file_sep>import { Component, OnInit, Input } from '@angular/core'; import { ActivatedRoute, Router } from "@angular/router"; import { Workshop } from "app/models/workshop"; @Component( { selector: 'workshop', templateUrl: './workshop.component.html', styleUrls: ['./workshop.component.css'] } ) export class WorkshopComponent implements OnInit { @Input() workshop: Workshop; constructor( private route: ActivatedRoute, private router: Router ) { } ngOnInit() { window.scrollTo( 0, 0 ) } } <file_sep>import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http'; import { Event } from '../models/event'; import { Observable } from 'rxjs/Rx'; //Import RxJs required methods import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import { Config } from "app/utils/config"; @Injectable() export class EventService { constructor( private http: Http ) { } private eventsUrl = Config.serverAddress + '/events'; private eventUrl = Config.serverAddress + '/event'; private deleteEventUrl = Config.serverAddress + '/deleteEvent'; getEvents( id: string ): Observable<Event[]> { let params: URLSearchParams = new URLSearchParams(); params.set( 'id', id ); var options = new RequestOptions( { headers: new Headers( { 'Content-Type': 'application/json' } ) } ); options.search = params; return this.http.get( this.eventsUrl, options ) .map(( res: Response ) => res.json() ) .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } getEvent( id: string ): Observable<any> { let params: URLSearchParams = new URLSearchParams(); params.set( 'id', id ); var options = new RequestOptions( { headers: new Headers( { 'Content-Type': 'application/json' } ) } ); options.search = params; // ...using get request return this.http.get( this.eventUrl, options ) .map(( res: Response ) => res.json() ) .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } get( id ): Observable<Event> { return this.getEvent( id ) .map( data => data.event ); } addEvent( body: Event ): Observable<Event[]> { let headers = new Headers( { 'Content-Type': 'application/json' } ); let options = new RequestOptions( { headers: headers } ); return this.http.post( this.eventUrl, JSON.stringify( body ), options ) .map(( res: Response ) => res.json() ) // ...and calling .json() on the response to return data .catch(( error: any ) => Observable.throw( error || 'Server error' ) ); //...errors if any } updateEvent( body: Event ): Observable<Event[]> { let headers = new Headers( { 'Content-Type': 'application/json' } ); let options = new RequestOptions( { headers: headers } ); return this.http.put( this.eventUrl, JSON.stringify( body ), options ) .map(( res: Response ) => res.json() ) // ...and calling .json() on the response to return data .catch(( error: any ) => Observable.throw( error || 'Server error' ) ); //...errors if any } deleteEvent( body: Event ): Observable<Event[]> { let headers = new Headers( { 'Content-Type': 'application/json' } ); let options = new RequestOptions( { headers: headers } ); return this.http.post( this.deleteEventUrl, JSON.stringify( body ), options ) .map(( res: Response ) => res.json() ) // ...and calling .json() on the response to return data .catch(( error: any ) => Observable.throw( error || 'Server error' ) ); //...errors if any } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Article } from "app/models/article"; import { ActivatedRoute, Router } from "@angular/router"; import { ConfirmationService, MenuItem } from "primeng/primeng"; import { Message } from "primeng/components/common/api"; import { ArticleService } from "app/services/article.service"; import { ArticleHistory } from "app/models/article-history"; @Component( { selector: 'admin-article', templateUrl: './admin-article.component.html', styleUrls: ['./admin-article.component.css'], providers: [ConfirmationService] } ) //TODO pomyslny response export class AdminArticleComponent implements OnInit { text: string; article: Article; articlesHistory: ArticleHistory[]; msgs: Message[] = []; navigationItems: MenuItem[]; constructor( private route: ActivatedRoute, private router: Router, private articleService: ArticleService, private confirmationService: ConfirmationService ) { } ngOnInit() { this.route.data.subscribe( ( data: { article: Article } ) => { if ( data.article ) { this.article = data.article; } else { //TODO Michal error and redirect } } ); this.navigationItems = []; this.navigationItems.push( { label: 'Admin' } ); this.navigationItems.push( { label: 'Artykuly' } ); this.navigationItems.push( { label: 'Sekcja XV wiek' } ); this.navigationItems.push( { label: 'O bitwie pod Grunwaldem', url: 'https://en.wikipedia.org/wiki/Lionel_Messi' } ); } saveNew() { //todo get from localStorage.getItem( 'token' ) this.article.fk_editor = '1'; this.articleService.addArticle( this.article ).subscribe( articles => { // Emit list event // //navigate // EmitterService.get( this.listId ).emit( enrolments ); // Empty model this.navigateBack(); }, err => { // Log errors if any console.log( err ); } ); //TODO Michal tymczasowo bo nie ma odpowiedzi this.navigateBack(); } save() { //TODO get from localStorage.getItem( 'token' ) this.article.fk_editor = '1'; this.articleService.updateArticle( this.article ).subscribe( articles => { // Emit list event // //navigate // EmitterService.get( this.listId ).emit( enrolments ); // Empty model this.navigateBack(); }, err => { // Log errors if any console.log( err ); } ); //TODO Michal tymczasowo bo nie ma odpowiedzi this.navigateBack(); } cancel() { this.navigateBack(); } isNew() { return ( !this.article.id || 0 === this.article.id.length ); } isDeleted() { return 'D' === this.article.status } getArticlesHistory() { this.articleService.getArticleHistory( this.article.id ) .subscribe( articles => this.articlesHistory = articles, //Bind to view err => { // Log errors if any console.log( err ); } ); } confirmDelete() { this.confirmationService.confirm( { message: 'Do you want to delete this record?', header: 'Delete Confirmation', icon: 'fa fa-trash', accept: () => { this.msgs = [{ severity: 'info', summary: 'Confirmed', detail: 'Record deleted' }]; this.deleteArticle(); }, reject: () => { this.msgs = [{ severity: 'info', summary: 'Rejected', detail: 'You have rejected' }]; } } ); } deleteArticle() { this.articleService.deleteArticle( this.article ).subscribe( articles => { // Emit list event // //navigate // EmitterService.get( this.listId ).emit( enrolments ); // Empty model this.navigateBack(); }, err => { // Log errors if any console.log( err ); } ); } activateArticle() { this.articleService.activateArticle( this.article ).subscribe( articles => { // Emit list event // //navigate // EmitterService.get( this.listId ).emit( enrolments ); // Empty model this.navigateBack(); }, err => { // Log errors if any console.log( err ); } ); } navigateBack() { this.router.navigate(['/admin', {outlets: {adminRouting: ['admin-articles']}}]) } } <file_sep>import { Component, OnInit, Input } from '@angular/core'; import { User } from "app/models/user"; import { UserService } from "app/services/user.service"; import { ConfirmationService } from "primeng/primeng"; import { Message } from "primeng/components/common/api"; @Component( { selector: 'action-admin-enrolment', templateUrl: './action-admin-enrolment.component.html', styleUrls: ['./action-admin-enrolment.component.css'], providers: [ConfirmationService] } ) export class ActionAdminEnrolmentComponent implements OnInit { msgs: Message[] = []; @Input() value: User; constructor( private userService: UserService, private confirmationService: ConfirmationService ) { } ngOnInit() { } example() { alert( this.value.name ); } isAcceptationPending() { if ( 'Y' == this.value.confirmation || 'N' == this.value.confirmation ) { return false; } return true; } isAccepted() { if ( 'Y' == this.value.confirmation ) { return true; } return false; } isRejected() { if ( 'N' == this.value.confirmation ) { return true; } return false; } accept() { //TODO refresh lub dymek this.userService.acceptUser( this.value ).subscribe( response => { if ( response.text() === 'OK' ) { - console.log( 'udalo sie accepted ' + response.text() ); // this.value.confirmation = 'Y' } }, err => { // Log errors if any console.log( err ); } ); } confirmReject() { this.confirmationService.confirm( { message: 'Czy na pewno chcesz odrzucic zgloszenie?', header: 'Potwierdz odrzucenie', icon: 'fa fa-trash', accept: () => { this.msgs = [{ severity: 'info', summary: 'Confirmed', detail: 'Record deleted' }]; this.reject(); }, reject: () => { this.msgs = [{ severity: 'info', summary: 'Rejected', detail: 'You have rejected' }]; } } ); } reject() { //TODO refresh lub dymek this.userService.rejectUser( this.value ).subscribe( response => { if ( response.text() === 'OK' ) { - console.log( 'udalo sie rejected ' + response.text() ); this.value.confirmation = 'N' // } }, err => { // Log errors if any console.log( err ); } ); } } <file_sep>export function isLoggedin() { return ( !!localStorage.getItem( 'userid' ) ) && ( !!localStorage.getItem( 'username' ) ); }<file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { AdminEnrolmentHistoryComponent } from './admin-enrolment-history.component'; describe('AdminEnrolmentHistoryComponent', () => { let component: AdminEnrolmentHistoryComponent; let fixture: ComponentFixture<AdminEnrolmentHistoryComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ AdminEnrolmentHistoryComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(AdminEnrolmentHistoryComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should be created', () => { expect(component).toBeTruthy(); }); }); <file_sep>import { Component, OnInit } from '@angular/core'; import { News } from "app/models/news"; import { NewsService } from "app/services/news.service"; @Component( { selector: 'news', templateUrl: './news.component.html', styleUrls: ['./news.component.css'] } ) export class NewsComponent implements OnInit { //The time to show the next photo private NextPhotoInterval: number = 2000; //Looping or not private noLoopSlides: boolean = false; //Photos private slides: Array<any> = []; news: News[]; constructor(private newsService: NewsService) { this.addNewSlide(); } private addNewSlide() { // this.slides.push( // { image: '/assets/cars/car1.jpg', text: 'BMW 1', description: 'Pierwszy samochodzik' }, // { image: '/assets/cars/car2.jpg', text: 'BMW 2', description: 'Drugi samochodzik' }, // { image: '/assets/cars/car3.jpg', text: 'BMW 3', description: 'Trzeci samochodzik' }, // { image: '/assets/cars/car4.jpg', text: 'BMW 4', description: 'Czwarty samochodzik' }, // { image: '/assets/cars/car5.jpg', text: 'BMW 5', description: 'Inny opis, inny temat' }, // { image: '/assets/cars/car6.jpg', text: 'BMW 6', description: 'Opis, naglowek' } // ); } private removeLastSlide() { this.slides.pop(); } ngOnInit() { this.loadNews() window.scrollTo( 0, 0 ) } loadNews() { this.newsService.getNews() .subscribe( n => this.news = n, //Bind to view err => { // Log errors if any console.log( err ); } ); } } <file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { AdminLectureComponent } from './admin-lecture.component'; describe('AdminLectureComponent', () => { let component: AdminLectureComponent; let fixture: ComponentFixture<AdminLectureComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ AdminLectureComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(AdminLectureComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should be created', () => { expect(component).toBeTruthy(); }); }); <file_sep>import { Component, OnInit } from '@angular/core'; import { Message, SelectItem } from "primeng/primeng"; import { RequestOptions, Http, Headers } from "@angular/http"; import { Observable } from "rxjs/Observable"; import { ImageService } from "app/services/image.service"; import { UserService } from "app/services/user.service"; import { User } from "app/models/user"; import { Router } from "@angular/router"; import { AuthenticationService } from "app/services/authentication.service"; import { UniversityService } from "app/services/university.service"; import { University } from "app/models/university"; import { WorkshopsUserService } from "app/services/workshops-user.service"; import { WorkshopUser } from "app/models/workshop-user"; import { WorkshopService } from "app/services/workshop.service"; import { Workshop } from "app/models/workshop"; @Component( { selector: 'user-profile', templateUrl: './user-profile.component.html', styleUrls: ['./user-profile.component.css'] } ) export class UserProfileComponent implements OnInit { private html: any; private userId: string; private imageLoaded: boolean; user = new User( '', '', '', null, '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', null, null, '', '', '', '' ); selectedCongressRole: string; selectedAcademicTitle: string; selectedAcademicStatus: string; selectedParticipation: string[] = []; selectedMeal: string; types: SelectItem[]; academicTitles: SelectItem[]; academicStatuses: SelectItem[]; participationOptions: SelectItem[]; mealOptions: SelectItem[]; universities: University[]; results: string[]; password1: string; password2: string; userForm; requiredFieldsAlert: boolean; saveSuccessAlert: boolean; passwordChangedAlert: boolean; rangeDates: Date[]; minDate = new Date( 2018, 8, 19, 0, 10, 0, 0 ); maxDate = new Date( 2018, 8, 23, 0, 10, 0, 0 ); defaultDate = new Date( 2018, 8, 19, 0, 10, 0, 0 ); pl: any; workshopsUsers: WorkshopUser[]; workshops: Workshop[]; selectedWorkshops: WorkshopUser[]; workshopsOptions: SelectItem[]; kodykologiczny: boolean; constructor( private imageService: ImageService, private userService: UserService, private universityService: UniversityService, private authenticationService: AuthenticationService, private workshopsUserService: WorkshopsUserService, private workshopService: WorkshopService, public router: Router ) { this.userId = this.userService.getLoggedUserId(); this.types = []; this.types.push( { label: 'Uczestnik', value: 'Uczestnik' } ); this.types.push( { label: 'Referent', value: 'Referent' } ); this.types.push( { label: 'Organizator', value: 'Organizator' } ); this.academicTitles = []; this.academicTitles.push( { label: 'mgr', value: '1' } ); this.academicTitles.push( { label: 'dr', value: '2' } ); this.academicTitles.push( { label: 'dr hab.', value: '3' } ); this.academicTitles.push( { label: 'Profesor (stanowisko)', value: '4' } ); this.academicTitles.push( { label: 'Profesor (tytuล‚)', value: '5' } ); this.academicStatuses = []; this.academicStatuses.push( { label: 'Student/Doktorant', value: '1' } ); this.academicStatuses.push( { label: 'Pracownik naukowy', value: '2' } ); this.participationOptions = []; this.participationOptions.push( { label: 'Konferencja', value: '1' } ); this.participationOptions.push( { label: 'Warsztaty', value: '2' } ); this.mealOptions = []; this.mealOptions.push( { label: 'Standard', value: '1' } ); this.mealOptions.push( { label: 'Wegetariaล„skie', value: '2' } ); this.mealOptions.push( { label: 'Wegaล„skie', value: '3' } ); this.userForm = []; this.userForm.name = 'form-control'; this.userForm.surname = 'form-control'; this.userForm.email = 'form-control'; this.userForm.password1 = '<PASSWORD>'; this.userForm.password2 = '<PASSWORD>'; this.userForm.participation = 'col-md-11'; this.pl = { firstDayOfWeek: 1, dayNames: ["Niedziela", "Poniedziaล‚ek", "Wtorek", "ลšroda", "Czwartek", "Piฤ…tek", "Sobota"], dayNamesShort: ["Nie", "Pn", "Wt", "ลšr", "Czw", "Pi", "So"], dayNamesMin: ["Nie", "Pn", "Wt", "ลšr", "Czw", "Pi", "So"], monthNames: ["styczeล„", "luty", "marzec", "kwiecieล„", "maj", "czerwiec", "lipiec", "sierpieล„", "wrzesieล„", "paลบdziernik", "listopad", "grudzieล„"], monthNamesShort: ["sty", "lu", "mar", "kw", "maj", "cze", "lip", "sie", "wrz", "paลบ", "lis", "gru"], today: 'Dzisiaj', clear: 'Reset' } } ngOnInit() { if ( this.userId ) { this.html = this.imageService.getUserImage( this.userId ); this.imageLoaded = true; } this.userService.get( this.userId ).subscribe( u => { this.user = u; if ( this.user ) { this.selectAcademicStatus( this.user ); this.selectAcademicTitle( this.user ); this.selectCongressRole( this.user ); this.selectParticipation(); this.selectMeal(); this.selectAccommodation() this.selectBooleans() } }, //Bind to view err => { // Log errors if any console.log( err ); } ); this.preloadWorkshopsForUser(); window.scrollTo( 0, 0 ) } preloadWorkshopsForUser() { console.log('preload'); if ( this.userId ) { this.workshopsUserService.getWorkshopsForUser( this.userId ) .subscribe( results => { this.workshopsUsers = results; for ( var i = 0; i < this.workshopsUsers.length; i++ ) { if ('3' === this.workshopsUsers[i].fk_workshop) { this.kodykologiczny = true; } } this.loadWorkshops() this.loadWorkshopsUser(); }) } } loadWorkshops() { this.workshopService.getWorkshops() .subscribe( workshops => { this.workshops = workshops this.setWorkshopItems() }, //Bind to view err => { // Log errors if any console.log( err ); } ); } setWorkshopItems() { this.workshopsOptions = []; this.selectedWorkshops = []; if ( this.workshops ) { for ( var i = 0; i < this.workshops.length; i++ ) { let name = this.workshops[i].title; let id = this.workshops[i].id; if (this.workshops && '3' == this.workshops[i].id) { if (this.kodykologiczny === true) { this.workshopsOptions.push( { label: this.workshops[i].title, value: { fk_user: this.userId, fk_workshop: this.workshops[i].id } } ); } } else { this.workshopsOptions.push( { label: this.workshops[i].title, value: { fk_user: this.userId, fk_workshop: this.workshops[i].id } } ); } } } } loadWorkshopsUser() { if ( this.userId ) { this.workshopsUserService.getWorkshopsForUser( this.userId ) .subscribe( results => { this.workshopsUsers = results this.workshopsOptions.map(( item ) => { for ( var i = 0; i < this.workshopsUsers.length; i++ ) { if ( this.workshopsUsers[i].fk_workshop == item.value.fk_workshop ) { this.selectedWorkshops.push( item.value ) } } } ); //this.selectWorkshops() }, //Bind to view err => { // Log errors if any console.log( err ); } ); } } msgs: Message[]; uploadedFiles: File[] = []; onUpload( event ) { for ( let file of event.files ) { this.uploadedFiles.push( file ); } this.msgs = []; this.msgs.push( { severity: 'success', summary: 'File Uploaded', detail: '' } ); } logout() { this.authenticationService.logout(); this.router.navigate( ['welcome'] ); } search( event ) { // EmitterService.get( this.listId ).subscribe(( universities: University[] ) => { this.loadUniversities() } ); this.loadUniversities(); //todo dziala wolno, jakby co drugi znak if ( this.universities ) { this.results = this.universities.map( function( uni ) { return uni.name; } ) } ; } loadUniversities() { // Get all enrolments this.universityService.getUniversities( this.user.university ) .subscribe( universities => this.universities = universities, //Bind to view err => { // Log errors if any console.log( err ); } ); console.log( this.universities ); } get userData() { return this.user; } save() { this.requiredFieldsAlert = false; this.saveSuccessAlert = false; this.passwordChangedAlert = false; if ( this.validateUserForm() ) { this.user.fk_editor = this.user.id; this.setAcademicTitle(); this.setAcademicStatus(); this.setCongressRole(); this.setParticipation(); this.setMeal(); this.setAccommodation(); this.workshopsUserService.deleteWorkshopUser( new WorkshopUser( this.userId, '' ) ).subscribe( users => { }, err => { // Log errors if any console.log( err ); } ); for ( var i = 0; i < this.selectedWorkshops.length; i++ ) { this.workshopsUserService.addWorkshopUser( new WorkshopUser( this.userId, this.selectedWorkshops[i].fk_workshop ) ).subscribe( users => { }, err => { // Log errors if any console.log( err ); } ); } console.log( 'saving this.user.accommodation_from=' + this.user.accommodation_from ); console.log( 'saving this.user.accommodation_to=' + this.user.accommodation_to ); this.userService.updateUser( this.user ).subscribe( users => { // Emit list event // //navigate // EmitterService.get( this.listId ).emit( enrolments ); // Empty model //TODO Info this.msgs = []; this.msgs.push( { severity: 'success', summary: 'Zapis zakonczony powodzeniem.', detail: '' } ); this.saveSuccessAlert = true; window.scrollTo( 0, 0 ) }, err => { // Log errors if any console.log( err ); //TODO <NAME> wlasciwy komunikat o errorze this.requiredFieldsAlert = false; } ); } else { this.requiredFieldsAlert = true; this.msgs = []; this.msgs.push( { severity: 'error', summary: 'Proszฤ™ uzupeล‚nic wszystkie obowiฤ…zkowe (*) pola.', detail: '' } ); } } selectAcademicTitle( user: User ) { this.selectedAcademicTitle = this.user.academic_title; } selectAcademicStatus( user ) { this.selectedAcademicStatus = this.user.academic_status; } selectCongressRole( user: User ) { if ( this.user.congressrole === 'U' ) { this.selectedCongressRole = 'Uczestnik' } if ( this.user.congressrole === 'R' ) { this.selectedCongressRole = 'Referent' } if ( this.user.congressrole === 'O' ) { this.selectedCongressRole = 'Organizator' } } selectParticipation() { if ( this.user.participation === '1' ) { this.selectedParticipation[0] = '1' } if ( this.user.participation === '2' ) { this.selectedParticipation[0] = '2' } if ( this.user.participation === '3' ) { this.selectedParticipation[0] = '1' this.selectedParticipation[1] = '2' } } selectMeal() { this.selectedMeal = this.user.meal; } selectAccommodation() { console.log( 'this.user.accommodation_from=' + this.user.accommodation_from ); console.log( 'this.user.accommodation_to=' + this.user.accommodation_to ); if ( this.user.accommodation_from ) { this.user.accommodation_from = new Date( this.user.accommodation_from ) } if ( this.user.accommodation_to ) { this.user.accommodation_to = new Date( this.user.accommodation_to ) } } selectBooleans() { if ( this.user.accommodation === '0' ) { this.user.accommodation = null } if ( this.user.engineer === '0' ) { this.user.engineer = null } if ( this.user.invoice === '0' ) { this.user.invoice = null } if ( this.user.lactose_intolerance === '0' ) { this.user.lactose_intolerance = null } if ( this.user.master === '0' ) { this.user.master = null } if ( this.user.gluten_intolerance === '0' ) { this.user.gluten_intolerance = null } if ( this.user.smooking_room === '0' ) { this.user.smooking_room = null } } setAcademicTitle() { if ( this.selectedAcademicTitle === '1' ) { this.user.academic_title = '1' } if ( this.selectedAcademicTitle === '2' ) { this.user.academic_title = '2' } if ( this.selectedAcademicTitle === '3' ) { this.user.academic_title = '3' } if ( this.selectedAcademicTitle === '4' ) { this.user.academic_title = '4' } if ( this.selectedAcademicTitle === '5' ) { this.user.academic_title = '5' } } setAcademicStatus() { if ( this.selectedAcademicStatus === '1' ) { this.user.academic_status = '1' } if ( this.selectedAcademicStatus === '2' ) { this.user.academic_status = '2' } } setParticipation() { if ( this.selectedParticipation ) { if ( this.selectedParticipation.length === 2 ) { this.user.participation = '3'; } else { if ( this.selectedParticipation[0] === '1' ) { this.user.participation = '1'; } if ( this.selectedParticipation[0] === '2' ) { this.user.participation = '2'; } } } } setMeal() { if ( this.selectedMeal ) { if ( this.selectedMeal === '1' ) { this.user.meal = '1' } if ( this.selectedMeal === '2' ) { this.user.meal = '2' } if ( this.selectedMeal === '3' ) { this.user.meal = '3' } } } setAccommodation() { if ( this.user.accommodation_from ) { this.user.accommodation_from = new Date( this.user.accommodation_from.getTime() + ( 2 * 3600 * 1000 ) ) } if ( this.user.accommodation_to ) { this.user.accommodation_to = new Date( this.user.accommodation_to.getTime() + ( 2 * 3600 * 1000 ) ) } } showAcademicTitle() { return this.selectedAcademicStatus === '2' } showInvoiceData() { return this.user.invoice === '1' || this.user.invoice } showAccomodation() { return this.user.accommodation === '1' || this.user.accommodation } showStudentOptions() { return this.selectedAcademicStatus === '1' } showWorkshops() { if ( this.user ) { if ( this.selectedParticipation.length === 2 ) { return true; } if ( this.selectedParticipation[0] === '2' ) { return true; } } } setCongressRole() { if ( this.selectedCongressRole === 'Uczestnik' ) { this.user.congressrole = 'U' } if ( this.selectedCongressRole === 'Referent' ) { this.user.congressrole = 'R' } if ( this.selectedCongressRole === 'Organizator' ) { this.user.congressrole = 'O' } } resetChanges() { this.requiredFieldsAlert = false; this.saveSuccessAlert = false; this.passwordChangedAlert = false; if ( this.userId ) { this.html = this.imageService.getUserImage( this.userId ); this.imageLoaded = true; } this.userService.get( this.userId ).subscribe( u => this.user = u, //Bind to view err => { // Log errors if any console.log( err ); } ); if ( this.user ) { this.selectAcademicStatus( this.user ); this.selectAcademicTitle( this.user ); this.selectCongressRole( this.user ); this.selectParticipation(); this.selectMeal(); this.selectAccommodation() this.selectBooleans() } this.loadWorkshops() this.loadWorkshopsUser(); this.userForm = []; this.userForm.name = 'form-control'; this.userForm.surname = 'form-control'; this.userForm.email = 'form-control'; this.userForm.password1 = '<PASSWORD>'; this.userForm.password2 = '<PASSWORD>'; this.password1 = <PASSWORD>; this.password2 = <PASSWORD>; this.userForm.participation = 'col-md-11'; } validateUserForm() { var result = true; if ( this.isEmpty( this.user.name ) ) { result = false; this.userForm.name = 'form-control validationError'; } else { this.userForm.name = 'form-control'; } if ( this.isEmpty( this.user.surname ) ) { result = false; this.userForm.surname = 'form-control validationError'; } else { this.userForm.surname = 'form-control'; } if ( this.isEmpty( this.user.email ) ) { result = false; this.userForm.email = 'form-control validationError'; } else { this.userForm.email = 'form-control'; } if ( this.isEmpty( this.selectedParticipation ) ) { result = false; this.userForm.participation = 'col-md-11 validationError'; } else { this.userForm.participation = 'col-md-11'; } return result; } changePassword() { this.requiredFieldsAlert = false; this.saveSuccessAlert = false; this.passwordChangedAlert = false; if ( this.validatePasswordForm() ) { this.user.fk_editor = this.user.id; this.user.password = <PASSWORD>; this.userService.updatePassword( this.user ).subscribe( users => { this.msgs = []; this.msgs.push( { severity: 'success', summary: 'Haslo zmienione.', detail: '' } ); this.passwordChangedAlert = true; window.scrollTo( 0, 0 ) }, err => { // Log errors if any console.log( err ); //TODO Michal blad this.requiredFieldsAlert = true; this.msgs = []; this.msgs.push( { severity: 'error', summary: 'Proszฤ™ uzupeล‚nic wszystkie obowiฤ…zkowe (*) pola.', detail: '' } ); window.scrollTo( 0, 0 ) } ); } else { this.requiredFieldsAlert = true; this.msgs = []; this.msgs.push( { severity: 'error', summary: 'Proszฤ™ uzupeล‚nic wszystkie obowiฤ…zkowe (*) pola.', detail: '' } ); } } validatePasswordForm() { var result = true; if ( this.isEmpty( this.password1 ) ) { result = false; this.userForm.password1 = 'form-control validationError'; } else { this.userForm.password1 = 'form-control'; } if ( this.isEmpty( this.password2 ) ) { result = false; this.userForm.password2 = 'form-control validationError'; } else { this.userForm.password2 = 'form-control'; } if ( this.password1 != this.password2 ) { result = false; this.userForm.password1 = 'form-control validationError'; this.userForm.password2 = 'form-control validationError'; } return result; } requiredFieldsAlertVisible() { return this.requiredFieldsAlert } saveSuccessAlertVisible() { return this.saveSuccessAlert } passwordChangedAlertVisible() { return this.passwordChangedAlert } isEmpty( str ) { return ( !str || 0 === str.length ); } } <file_sep>import { Injectable, } from '@angular/core'; import { ActivatedRouteSnapshot, Resolve, Router, RouterStateSnapshot } from '@angular/router'; import { Observable } from 'rxjs/Rx'; import { Article } from "app/models/article"; @Injectable() export class ArticleNewResolver implements Resolve<Article> { constructor( private router: Router, ) { } resolve( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable<Article> { return Observable.create( observer => { observer.next( new Article( '', '', '', '', '', 'A' ) ); observer.complete(); } ); } }<file_sep>( function( $ ) { $( document ).ready(function() { $('#cssmenu li.has-sub>a').on('click', function(){ $(this).removeAttr('href'); var element = $(this).parent('li'); if (element.hasClass('open')) { element.removeClass('open'); element.find('li').removeClass('open'); element.find('ul').slideUp(); } else { element.addClass('open'); element.children('ul').slideDown(); element.siblings('li').children('ul').slideUp(); element.siblings('li').removeClass('open'); element.siblings('li').find('li').removeClass('open'); element.siblings('li').find('ul').slideUp(); } }); }); } )( jQuery ); //SMOOTH PAGE SCROLL $(function() { $('a[href*=#]:not([href=#])').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); if (target.length) { $('html,body').animate({ scrollTop: target.offset().top }, 1000); return false; } } }); }); /* * //OWL CAROSEL TESTIMONIAL $('.owl-carousel').owlCarousel({ loop:true, margin:10, nav:false, dots:true, dotsEach:true, responsive:{ 0:{ items:1 }, 600:{ items:1 }, 1000:{ items:1 } } }) */ $(document).ready( function() { $("html").niceScroll({ cursorcolor:"#f74d65", scrollspeed :"100", cursorborder:"1px solid #f74d65", horizrailenabled: "false", cursorborderradius: "0px" }); } ); new WOW().init(); /*Preloader*/ //<![CDATA[ $(window).load(function() { // makes sure the whole site is loaded $('#status').fadeOut(); // will first fade out the loading animation $('#preloader').delay(350).fadeOut('slow'); // will fade out the white DIV that covers the website. $('body').delay(350).css({'overflow':'visible'}); }) //]]> <file_sep>import { Component, OnInit } from '@angular/core'; import { LocalDataSource } from "ng2-smart-table/ng2-smart-table"; import { Router } from "@angular/router"; import { ScheduleService } from "app/services/schedule.service"; @Component( { selector: 'admin-schedules', templateUrl: './admin-schedules.component.html', styleUrls: ['./admin-schedules.component.css'] } ) export class AdminSchedulesComponent implements OnInit { source: LocalDataSource; constructor( private router: Router, private scheduleService: ScheduleService ) { this.source = new LocalDataSource(); this.scheduleService.getSchedules().toPromise().then(( data ) => { this.source.load( data ); } ); } ngOnInit() { } //TODO Michal translacja przez serwis settings = { columns: { title: { title: 'Blok wydarzen' }, action: { title: 'Akcja', type: 'html', valuePrepareFunction: ( cell, row ) => { return '<a href="/admin-schedule/' + row.id + '">Edytuj</a>' } } }, actions: false }; createNew() { this.router.navigate(['/admin-schedule-new', {outlets: 'adminRouting'}]); // this.router.navigate( ['admin-schedule-new/'] ); } } <file_sep>import { Component, ViewEncapsulation, Input, Output, OnChanges, ElementRef, EventEmitter } from '@angular/core'; @Component( { selector: 'print', templateUrl: './print.component.html', styleUrls: ['./print.component.css'] } ) //TODO Michal testy dla chrome i innych przegladarek export class PrintComponent implements OnChanges { @Input( 'section' ) section: string; @Output() sectionChange = new EventEmitter<any>(); constructor( private ele: ElementRef ) { if ( this.section === undefined ) this.section = ''; } ngOnChanges( changes ) { if ( changes.section && changes.section.currentValue !== undefined && changes.section.currentValue !== '' ) { } } afterPrint() { console.log( "after print" ); this.ele.nativeElement.children[0].innerHTML = ''; this.sectionChange.emit( '' ); this.section = ''; } printDiv() { this.section = 'printSection' console.log('Section=' + this.section) if ( this.section && this.section != undefined && this.section != '' ) { var printContents = document.getElementById( this.section ).innerHTML; var originalContents = document.body.innerHTML; if ( window ) { if ( navigator.userAgent.toLowerCase().indexOf( 'chrome' ) > -1 ) { var popup = window.open( '', '_blank', 'width=600,height=600,scrollbars=no,menubar=no,toolbar=no,' + 'location=no,status=no,titlebar=no' ); popup.window.focus(); popup.document.write( '<!DOCTYPE html><html><head> ' + '<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.css" ' + 'media="screen,print">' + '<link rel="stylesheet" href="style.css" media="screen,print">' + '</head><body onload="window.print()"><div class="reward-body">' + printContents + '</div></html>' ); popup.onbeforeunload = function( event ) { popup.close(); return '.\n'; }; popup.onabort = function( event ) { popup.document.close(); popup.close(); } } else { var popup = window.open( '', '_blank', 'width=800,height=600' ); popup.document.open(); popup.document.write( '<html><head></head><body onload="window.print()">' + printContents + '</html>' ); popup.document.close(); } popup.document.close(); } return true; } } fetchStylesheets() { var output: string = ''; for ( var i = 0; i < document.styleSheets.length; i++ ) { output = output + ' <link rel="stylesheet" type="text/css" href="' + window.document.styleSheets[0].href + '" /> '; } return output; } fetchscriptSheets() { var output: string = ''; for ( var i = 0; i < document.scripts.length; i++ ) { output = output + ' <script type="text/javascript" src="' + window.document.scripts[0].src + '" /> '; } return output; } }<file_sep>import { Injectable, } from '@angular/core'; import { ActivatedRouteSnapshot, Resolve, Router, RouterStateSnapshot } from '@angular/router'; import { Observable } from 'rxjs/Rx'; import { EventService } from "app/services/event.service"; import { Event } from "app/models/event"; @Injectable() export class EventResolver implements Resolve<Event> { constructor( private eventService: EventService, private router: Router, ) {} resolve( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable<Event> { return this.eventService.getEvent(route.params['id']) .catch((err) => this.router.navigateByUrl('/')); } }<file_sep>import { Component, OnInit } from '@angular/core'; @Component( { selector: 'app-text-editor', templateUrl: './text-editor.component.html', styleUrls: ['./text-editor.component.css'] } ) export class TextEditorComponent implements OnInit { constructor() { } content = "<p> this is custom directive </p>"; content_two = "<p> this is ng-ckeditor directive </p>"; articleText = "To jest tresc."; ngOnInit(){ window['CKEDITOR']['replace']( 'editor1' ); } } <file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'letter-of-intent', templateUrl: './letter-of-intent.component.html', styleUrls: ['./letter-of-intent.component.css'] }) export class LetterOfIntentComponent implements OnInit { constructor() { } ngOnInit() { window.scrollTo(0, 0) } } <file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { EnrolmentCreatedComponent } from './enrolment-created.component'; describe('EnrolmentCreatedComponent', () => { let component: EnrolmentCreatedComponent; let fixture: ComponentFixture<EnrolmentCreatedComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ EnrolmentCreatedComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(EnrolmentCreatedComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should be created', () => { expect(component).toBeTruthy(); }); }); <file_sep>import { Component, OnInit } from '@angular/core'; import { Article } from "app/models/article"; import { ActivatedRoute, Router } from "@angular/router"; import { ConfirmationService, MenuItem } from "primeng/primeng"; import { Message } from "primeng/components/common/api"; import { LectureService } from "app/services/lecture.service"; import { Lecture } from "app/models/lecture"; @Component( { selector: 'admin-lecture', templateUrl: './admin-lecture.component.html', styleUrls: ['./admin-lecture.component.css'], providers: [ConfirmationService] } ) export class AdminLectureComponent implements OnInit { text: string; lecture: Lecture; // articlesHistory: ArticleHistory[]; msgs: Message[] = []; navigationItems: MenuItem[]; requiredFieldsAlert: boolean; saveSuccessAlert: boolean; constructor(private route: ActivatedRoute, private router: Router, private lectureService: LectureService, private confirmationService: ConfirmationService) { } ngOnInit() { window.scrollTo(0, 0) this.route.data.subscribe( ( data: { lecture: Lecture } ) => { if ( data.lecture ) { this.lecture = data.lecture; } else { //TODO Michal error and redirect } } ); } saveNew() { //todo get from localStorage.getItem( 'token' ) this.lecture.fk_editor = '1'; this.lectureService.addLecture( this.lecture ).subscribe( lectures => { // Emit list event // //navigate // EmitterService.get( this.listId ).emit( enrolments ); // Empty model this.navigateBack(); }, err => { // Log errors if any console.log( err ); } ); //TODO Michal tymczasowo bo nie ma odpowiedzi this.navigateBack(); } save() { //TODO get from localStorage.getItem( 'token' ) this.requiredFieldsAlert = false; this.saveSuccessAlert = false; if (this.validate()) { this.lecture.fk_editor = localStorage.getItem( 'userid' ) this.lectureService.updateLecture( this.lecture ).subscribe( lectures => { // Emit list event // //navigate // EmitterService.get( this.listId ).emit( enrolments ); // Empty model this.msgs = []; this.msgs.push( { severity: 'success', summary: 'Zapis zakonczony powodzeniem.', detail: '' } ); this.saveSuccessAlert = true; window.scrollTo( 0, 0 ) }, err => { // Log errors if any console.log( err ); this.requiredFieldsAlert = false; } ); } else { this.requiredFieldsAlert = true; this.msgs = []; this.msgs.push( { severity: 'error', summary: 'Proszฤ™ uzupeล‚nic wszystkie obowiฤ…zkowe (*) pola.', detail: '' } ); } } cancel() { this.navigateBack(); } isNew() { return ( !this.lecture.id || 0 === this.lecture.id.length ); } isDeleted() { return 'D' === this.lecture.status } // getArticlesHistory() { // this.articleService.getArticleHistory( this.article.id ) // .subscribe( // articles => this.articlesHistory = articles, //Bind to view // err => { // // Log errors if any // console.log( err ); // } ); // } confirmDelete() { this.confirmationService.confirm( { message: 'Do you want to delete this record?', header: 'Delete Confirmation', icon: 'fa fa-trash', accept: () => { this.msgs = [{ severity: 'info', summary: 'Confirmed', detail: 'Record deleted' }]; this.deleteLecture(); }, reject: () => { this.msgs = [{ severity: 'info', summary: 'Rejected', detail: 'You have rejected' }]; } } ); } deleteLecture() { this.lectureService.deleteLecture( this.lecture ).subscribe( lectures => { // Emit list event // //navigate // EmitterService.get( this.listId ).emit( enrolments ); // Empty model this.navigateBack(); }, err => { // Log errors if any console.log( err ); } ); this.navigateBack(); } activateLecture() { this.lectureService.activateLecture( this.lecture ).subscribe( lectures => { // Emit list event // //navigate // EmitterService.get( this.listId ).emit( enrolments ); // Empty model this.navigateBack(); }, err => { // Log errors if any console.log( err ); } ); } navigateBack() { this.router.navigate(['/admin', {outlets: {adminRouting: ['admin-lectures']}}]) } validate() { var result = true; if ( this.isEmpty( this.lecture.title ) ) { result = false; // this.userForm..password1 = '<PASSWORD>'; } else { // this.userForm.password1 = '<PASSWORD>'; } return result; } isEmpty( str ) { return ( !str || 0 === str.length ); } requiredFieldsAlertVisible() { return this.requiredFieldsAlert } saveSuccessAlertVisible() { return this.saveSuccessAlert } } <file_sep>import { Component, OnInit } from '@angular/core'; import { AuthenticationService } from "app/services/authentication.service"; import { Router } from "@angular/router"; @Component( { selector: 'user-logged', templateUrl: './user-logged.component.html', styleUrls: ['./user-logged.component.css'] } ) export class UserLoggedComponent implements OnInit { private username: string; constructor(private authenticationService: AuthenticationService, public router: Router) { } ngOnInit() { this.username = localStorage.getItem( 'username' ); } isLogged() { this.username = localStorage.getItem( 'username' ); return ( this.username ); } logout() { this.authenticationService.logout(); this.router.navigate( ['welcome'] ); } } <file_sep>import { Injectable, } from '@angular/core'; import { ActivatedRouteSnapshot, Resolve, Router, RouterStateSnapshot } from '@angular/router'; import { Observable } from 'rxjs/Rx'; import { ScheduleService } from "app/services/schedule.service"; import { Schedule } from "app/models/schedule"; @Injectable() export class ScheduleResolver implements Resolve<Schedule> { constructor( private scheduleService: ScheduleService, private router: Router, ) {} resolve( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable<Schedule> { console.log('wywolano schedule resolver') return this.scheduleService.getSchedule(route.params['id']) .catch((err) => this.router.navigateByUrl('/')); } } <file_sep>import { Injectable, Sanitizer } from '@angular/core'; import { Http, Response, Headers, RequestOptions, URLSearchParams, ResponseContentType } from '@angular/http'; import { DomSanitizer } from '@angular/platform-browser'; import { Observable } from 'rxjs/Rx'; //Import RxJs required methods import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import { Config } from "app/utils/config"; @Injectable() export class ImageService { private imageUrl = Config.serverAddress + '/profileimage'; constructor( private http: Http, private sanitizer: DomSanitizer ) { } getUserImage(id) { return this.sanitizer.bypassSecurityTrustResourceUrl(this.imageUrl + "?id=" + id) } } <file_sep>import { TestBed, inject } from '@angular/core/testing'; import { WorkshopResolver } from './workshop-resolver.service'; describe('WorkshopResolverService', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [WorkshopResolver] }); }); it('should be created', inject([WorkshopResolver], (service: WorkshopResolver) => { expect(service).toBeTruthy(); })); }); <file_sep>export class ArticleHistory { constructor( public author: string, public title: string, public content: string, public headline: string, public editor: string, public modified_date: Date ) { } }<file_sep>import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http'; //Import RxJs required methods import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import { Observable } from 'rxjs/Rx'; import { Config } from "app/utils/config"; import { WorkshopUser } from "app/models/workshop-user"; import { User } from "app/models/user"; @Injectable() export class WorkshopsUserService { private allWorkshops = Config.serverAddress + '/allWorkshops'; private insertWorkshop = Config.serverAddress + '/insertWorkshop'; private deleteWorkshops = Config.serverAddress + '/deleteWorkshops'; private forUser = Config.serverAddress + '/forUser'; private forWorkshop = Config.serverAddress + '/forWorkshop'; constructor( private http: Http ) { } getWorkshops(): Observable<WorkshopUser[]> { // ...using get request return this.http.get( this.allWorkshops ) // ...and calling .json() on the response to return data .map(( res: Response ) => res.json() ) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } getWorkshopsForUser( id: string ): Observable<WorkshopUser[]> { let params: URLSearchParams = new URLSearchParams(); params.set( 'fk_user', id ); var options = new RequestOptions( { headers: new Headers( { 'Content-Type': 'application/json' } ) } ); options.search = params; // ...using get request return this.http.get( this.forUser, options ) // ...and calling .json() on the response to return data .map(( res: Response ) => res.json() ) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } addWorkshopUser( body: WorkshopUser ): Observable<WorkshopUser[]> { let headers = new Headers( { 'Content-Type': 'application/json' } ); let options = new RequestOptions( { headers: headers } ); return this.http.post( this.insertWorkshop, JSON.stringify( body ), options ) .map(( res: Response ) => res.json() ) // ...and calling .json() on the response to return data .catch(( error: any ) => Observable.throw( error || 'Server error' ) ); //...errors if any } deleteWorkshopUser( body: WorkshopUser ): Observable<WorkshopUser[]> { let headers = new Headers( { 'Content-Type': 'application/json' } ); let options = new RequestOptions( { headers: headers } ); return this.http.post( this.deleteWorkshops, JSON.stringify( body ), options ) .map(( res: Response ) => res.json() ) // ...and calling .json() on the response to return data .catch(( error: any ) => Observable.throw( error || 'Server error' ) ); //...errors if any } getUsersForWorkshop( id: string ): Observable<User[]> { let params: URLSearchParams = new URLSearchParams(); params.set( 'fk_workshop', id ); var options = new RequestOptions( { headers: new Headers( { 'Content-Type': 'application/json' } ) } ); options.search = params; // ...using get request return this.http.get( this.forWorkshop, options ) // ...and calling .json() on the response to return data .map(( res: Response ) => res.json() ) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } } <file_sep>import { TestBed, inject } from '@angular/core/testing'; import { WorkshopNewResolver } from './workshop-new-resolver.service'; describe('WorkshopNewResolverService', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [WorkshopNewResolver] }); }); it('should be created', inject([WorkshopNewResolver], (service: WorkshopNewResolver) => { expect(service).toBeTruthy(); })); }); <file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { News } from "app/models/news"; import { Comment } from "app/models/comment"; import { CommentNewsService } from "app/services/comment-news.service"; @Component( { selector: 'news-single', templateUrl: './news-single.component.html', styleUrls: ['./news-single.component.css'] } ) export class NewsSingleComponent implements OnInit { article: News; comments: Comment[]; comment = new Comment( '', null, '', '', '', '', null, '', '', '' ); userid: string; constructor( private route: ActivatedRoute, private router: Router, private commentService: CommentNewsService ) { } ngOnInit() { this.route.data.subscribe( ( data: { news: News } ) => { if ( data.news ) { this.article = data.news; } else { //TODO Michal error and redirect } } ); if ( this.article.id ) { //TODO w zaleznosci od uzytkownika this.loadAllComments(); } window.scrollTo( 0, 0 ) } loadAllComments() { this.commentService.getAllComments( this.article.id ) .subscribe( c => this.comments = c, //Bind to view err => { // Log errors if any console.log( err ); } ); } loadConfirmedComments() { this.commentService.getConfirmedComments( this.article.id ) .subscribe( c => this.comments = c, //Bind to view err => { // Log errors if any console.log( err ); } ); } addNewComment() { //todo get from localStorage.getItem( 'token' ) //rozroznienie na tworzenie parent comment i comment this.comment.fk_user = this.userid; this.comment.fk_post = this.article.id; //todo if uprawnienia //todo admin user ma od razu zatwierdzony post this.commentService.addParentCommentAdminUser( this.comment ).subscribe( c => this.comments = c //todo dymek? , err => { // Log errors if any console.log( err ); } ); this.comment = new Comment( '', null, '', '', '', '', null, '', '', '' ); } isLogged() { this.userid = localStorage.getItem( 'userid' ); return ( this.userid ); } } <file_sep>import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http'; import { User } from '../models/user'; import { Observable } from 'rxjs/Rx'; import { UserHistory } from "app/models/user-history"; import { Config } from "app/utils/config"; @Injectable() export class UserService { private usersUrl = Config.serverAddress + '/users'; private userUrl = Config.serverAddress + '/user'; private acceptedUsersUrl = Config.serverAddress + '/acceptedUsers'; private pendingUsersUrl = Config.serverAddress + '/pendingUsers'; private rejectedUsersUrl = Config.serverAddress + '/rejectedUsers'; private speakersUrl = Config.serverAddress + '/speakers'; private acceptUserUrl = Config.serverAddress + '/acceptUser'; private rejectUserUrl = Config.serverAddress + '/rejectUser'; private acceptPaymentUrl = Config.serverAddress + '/acceptPayment'; private rejectPaymentUrl = Config.serverAddress + '/rejectPayment'; private acceptedPaymentUrl = Config.serverAddress + '/acceptedPayment'; private pendingPaymentUrl = Config.serverAddress + '/pendingPayment'; private workshopUrl = Config.serverAddress + '/workshopUsers'; private invoiceUrl = Config.serverAddress + '/invoiceUsers'; private userPasswordUrl = Config.serverAddress + '/userPassword'; //TODO private userHistoryUrl = Config.serverAddress + '/userHistory'; constructor( private http: Http ) { } addUser( body: User ): any { let headers = new Headers( { 'Content-Type': 'application/json' } ); let options = new RequestOptions( { headers: headers } ); return this.http.post(this.usersUrl, JSON.stringify(body), options); } getUsers(): Observable<User[]> { // ...using get request return this.http.get( this.usersUrl ) // ...and calling .json() on the response to return data .map(( res: Response ) => res.json() ) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } getAcceptedUsers(): Observable<User[]> { // ...using get request return this.http.get( this.acceptedUsersUrl ) // ...and calling .json() on the response to return data .map(( res: Response ) => res.json() ) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } getPendingUsers(): Observable<User[]> { // ...using get request return this.http.get( this.pendingUsersUrl ) // ...and calling .json() on the response to return data .map(( res: Response ) => res.json() ) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } getRejectedUsers(): Observable<User[]> { // ...using get request return this.http.get( this.rejectedUsersUrl ) // ...and calling .json() on the response to return data .map(( res: Response ) => res.json() ) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } getSpeakers(): Observable<User[]> { // ...using get request return this.http.get( this.speakersUrl ) // ...and calling .json() on the response to return data .map(( res: Response ) => res.json() ) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } getLoggedUserId() { return localStorage.getItem( 'userid' ); } getUser( id: string ): Observable<User> { let params: URLSearchParams = new URLSearchParams(); params.set( 'id', id ); var options = new RequestOptions( { headers: new Headers( { 'Content-Type': 'application/json' } ) } ); options.search = params; // ...using get request return this.http.get( this.userUrl, options ) // ...and calling .json() on the response to return data .map(( res: Response ) => res.json() ) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } updateUser( body: User ): Observable<User[]> { let headers = new Headers( { 'Content-Type': 'application/json' } ); let options = new RequestOptions( { headers: headers } ); return this.http.put( this.usersUrl, JSON.stringify( body ), options ) .map(( res: Response ) => res.json() ) // ...and calling .json() on the response to return data .catch(( error: any ) => Observable.throw( error || 'Server error' ) ); //...errors if any } updatePassword ( body: User ): Observable<User[]> { let headers = new Headers( { 'Content-Type': 'application/json' } ); let options = new RequestOptions( { headers: headers } ); return this.http.put( this.userPasswordUrl, JSON.stringify( body ), options ) .map(( res: Response ) => res.json() ) // ...and calling .json() on the response to return data .catch(( error: any ) => Observable.throw( error || 'Server error' ) ); //...errors if any } get(id: string): Observable<User> { return this.getUser(id) .map(data => data); } acceptUser( body: User ): any { let headers = new Headers( { 'Content-Type': 'application/json' } ); let options = new RequestOptions( { headers: headers } ); return this.http.post(this.acceptUserUrl, JSON.stringify(body), options); } rejectUser( body: User ): any { let headers = new Headers( { 'Content-Type': 'application/json' } ); let options = new RequestOptions( { headers: headers } ); return this.http.post(this.rejectUserUrl, JSON.stringify(body), options); } acceptPayment( body: User ): any { let headers = new Headers( { 'Content-Type': 'application/json' } ); let options = new RequestOptions( { headers: headers } ); return this.http.post(this.acceptPaymentUrl, JSON.stringify(body), options); } rejectPayment( body: User ): any { let headers = new Headers( { 'Content-Type': 'application/json' } ); let options = new RequestOptions( { headers: headers } ); return this.http.post(this.rejectPaymentUrl, JSON.stringify(body), options); } getAcceptedPayment(): Observable<User[]> { // ...using get request return this.http.get( this.acceptedPaymentUrl ) // ...and calling .json() on the response to return data .map(( res: Response ) => res.json() ) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } getPendingPayment(): Observable<User[]> { // ...using get request return this.http.get( this.pendingPaymentUrl ) // ...and calling .json() on the response to return data .map(( res: Response ) => res.json() ) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } getWorkshop(): Observable<User[]> { // ...using get request return this.http.get( this.workshopUrl ) // ...and calling .json() on the response to return data .map(( res: Response ) => res.json() ) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } getInvoice(): Observable<User[]> { // ...using get request return this.http.get( this.invoiceUrl ) // ...and calling .json() on the response to return data .map(( res: Response ) => res.json() ) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } getUserHistory( id: string ): Observable<UserHistory[]> { let params: URLSearchParams = new URLSearchParams(); params.set( 'id', id ); var options = new RequestOptions( { headers: new Headers( { 'Content-Type': 'application/json' } ) } ); options.search = params; // ...using get request return this.http.get( this.userHistoryUrl, options ) // ...and calling .json() on the response to return data .map(( res: Response ) => res.json() ) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } } <file_sep>export class Comment { constructor( public parentcomment: string, public parentdate: Date, public parentid: string, public parentusername: string, public parentconfirmed: string, public comment: string, public date: Date, public id: string, public username: string, public confirmed: string ) { } public fk_user: string; public fk_post: string; }<file_sep>export const LANG_EN_NAME = 'en'; export const LANG_EN_TRANS = { 'enrolments-list': 'Enrolments list', 'Clear': 'Clear', 'Print': 'Print', 'Text': 'Text', 'Description': 'Description', 'Save': 'Save', 'Cancel': 'Cancel', 'Delete': 'Delete', 'show-history': 'Show history', 'Create New': 'Create New', 'Author': 'Author', 'Title': 'Title', 'First name': 'First name', 'Surname': 'Surname', 'E-mail': 'E-mail', 'Enrolment form': 'Enrolment form', 'Phone': 'Phone', 'Show deleted articles': 'Show deleted articles', 'Show articles': 'Show active articles', 'News': 'News', 'Articles': 'Articles', 'Contact': 'Contact', 'ContactMail' : 'Contact: <a href="mailto:<EMAIL>"><EMAIL></a>', 'Address': 'Address', 'Schedules': 'Schedules', 'Events': 'Events', 'Log out': 'Log out', 'Welcome': 'Welcome', 'Terms': 'Terms & Privacy', 'Read more': 'Read more', 'Registration': 'Registration', 'Admin panel': 'Admin panel', 'Medieval congress': '6th Polish Medieval Congress', 'Wroclaw University': 'Wroclaw University - Faculty of history', 'Published:': 'Published:', 'Categories:': 'Categories:', 'Modern history': 'Modern history', 'Congress': 'Congress', 'logo': 'logo', 'Sponsors': 'Sponsors', 'Sign Up': 'Sign Up', 'Login': 'Login', 'Enter your details': 'Enter your personal details', 'congressDatePlace': 'Wrocล‚aw, 20โ€“22 wrzeล›nia 2018', 'to create an account': 'to create an account', 'Email': 'Email', 'Password': '<PASSWORD>', 'Repeat password': '<PASSWORD>', 'University': 'University', 'Remarks': 'Remarks', 'Capacity': 'In what capacity?', 'Topic': 'Topic', 'Show': 'Show', 'Hide': 'Hide', 'Click here': 'Click here', 'ForgotPassword': 'Forgot your password?', 'EnterYourEmail': 'Enter your email and password', 'to sign in': 'to sign in', 'Agree rules info': 'By creating an account you agree to our', 'Send Message': 'Send Message', 'Name': 'Name', 'Subject': 'Subject', 'Message': 'Message', 'Thank You!': 'Thank You!', 'EmailSentInfo': 'Your email has been delivered.', 'About the university': 'About the university', 'Submit': 'Submit', 'Leave a comment:': 'Leave a comment:', 'Log in': 'Zaloguj siฤ™', 'Create account': 'Create account', 'Profile photo': 'Profile photo', 'Send for acceptation': 'Send for acceptation', 'Personal data': 'Personal data', 'Degree': 'Degree', 'academic_status': 'Academic status', 'engineer' : 'engineer', 'master' : 'master', 'Additional Info': 'Additional Info', 'Paper': 'Paper', 'Summary': 'Summary', 'Content': 'Content', 'Mailbox': 'Mailbox', 'Recover': 'Recover', 'Show all applicants': 'Show all applicants', 'Show accepted': 'Show accepted', 'Show rejected': 'Show rejected', 'Show pending requests': 'Pending', 'Show speakers': 'Show speakers', 'Receivers': 'Receivers', 'Accept': 'Accept', 'Reject': 'Reject', 'letter-of-intent': 'Announcement', 'noConfirmationInfo': 'Your enrolment is not confirmed yet. Please wait for the admin confirmation. You will receive it soon by email.', 'incorrectLoginDataInfo' : 'Incorrect login data.', 'Academic title' : 'Academic title', 'Reset' : 'Reset changes', 'Change password' : '<PASSWORD>', 'FooterWelcome': 'Welcome!', 'RegistrationOpen' : 'The registration is already open!', 'RegistrationTime': 'We wait for your enrolment until 10th july.', 'enrolment-created-title' : 'Thank you for your enrolment.', 'enrolment-created1' : 'TODO', 'TermsTitle': 'Terms:', 'Terms0-1': 'Akceptacja regulaminu oznacza wyraลผenie zgody na udostฤ™pnienie swoich danych na potrzeby zjazdu i dziaล‚aล„ promocyjnych zwiฤ…zanych z wydarzeniem.', 'Terms0-2': 'Rejestracja trwa od 09 kwietnia 2018 r. do 10 lipca 2018 r.', 'Terms0': 'W celu uczestnictwa w zjeลบdzie naleลผy:', 'Terms1': 'Utworzyฤ‡ konto na stronie <a href="www.vikmp.pl">www.vikmp.pl</a>', 'Terms2': 'Po otrzymaniu maila aktywujฤ…cego uzupeล‚niฤ‡ wszelkie brakujฤ…ce dane.', 'Terms3': 'Dokonaฤ‡ opล‚aty rejestracyjnej ktรณrej wysokoล›ฤ‡ zostanie oraz nr konta do wpล‚aty zostanie ustalona do dnia 15 maja. Okres zbierania wpล‚at koล„czy siฤ™ w dniu zamkniฤ™cia rejestracji tj. 10 lipca 2018 r.', 'Send Password' : 'Send Password', 'emailNotFoundAlert' : 'User with such email not found.', 'emailSentAlert' : 'The password sent.', 'Commitee' : 'Komitet naukowy', 'Presidium' : 'Prezydium:', 'PresidiumNames' : 'Prof. dr hab. <NAME>, Prof. dr hab. <NAME>, Prof. dr hab. <NAME>', 'CommiteeNames1' : 'Prof. dr hab. <NAME>, Prof. dr hab. <NAME>,', 'CommiteeNames2' : 'Prof. dr hab. <NAME>, Prof. dr hab. <NAME>, Dr hab. Prof. UWr, <NAME>, ', 'CommiteeNames3' : 'Dr hab. Prof. UWr <NAME>, Prof. dr hab. <NAME>, ', 'CommiteeNames4' : 'Prof. dr hab. <NAME>, Prof. UWr dr hab. <NAME>,', 'CommiteeNames5' : 'Prof. dr hab. <NAME>, Prof. UWr dr.hab. <NAME>,', 'CommiteeNames6' : 'Prof. dr hab. <NAME>', 'OrganizersCommitee' : 'Komitet organizacyjny', 'OrganizersCommiteeNames1' : 'Prof. dr hab. <NAME>, Dr hab. Prof. UWr <NAME>,', 'OrganizersCommiteeNames2' : 'Prof. dr hab. <NAME>, Dr hab. Prof. UWr <NAME>,', 'OrganizersCommiteeNames3' : 'Prof. dr hab. <NAME> (przewodniczฤ…cy)', 'emailRegisteredAlert' : 'There is already an user with given email. The registration has failed.', 'requiredFieldsAlert' : 'Please enter all required (*) fields.', 'saveSuccess' : 'Changes saved.', 'passwordChangedAlert' : 'The password is changed.', 'cancelConfirmation' : 'Cancel confirmation', 'Edit' : 'Edit', 'ShowPaymentAccepted' : 'Payment accepted', 'ShowPaymentPending' : 'No payment', 'SeeYouInWroclaw' :'See you in Wrocล‚aw!', 'Friends' : 'Friendly institutions:', 'Links' : 'Links', 'Institution1' : 'Uniwersytet Wrocล‚awski <a href="https://uni.wroc.pl/">https://uni.wroc.pl</a>', 'Institution2' : 'Wydziaล‚ nauk Historycznych i Pedagogicznych UWr <a href="http://wnhip.uni.wroc.pl">http://wnhip.uni.wroc.pl</a>', 'Institution3' : 'Instytut Historyczny UWr <a href="http://www.hist.uni.wroc.pl/pl/">http://www.hist.uni.wroc.pl/pl/</a>', 'Institution4' : 'Instytut Archeologii UWr <a href="https://ww3.archeo.uni.wroc.pl">https://ww3.archeo.uni.wroc.pl</a>', 'Institution5' : 'Instytut Archeologii i Etnologii PAN o/Wrocล‚aw <a href="http://arch.pan.wroc.pl/">http://arch.pan.wroc.pl/</a>', 'Institution6' : 'Instytut Historii Sztuki <a href="https://uni.wroc.pl/">http://historiasztuki.uni.wroc.pl/</a>', 'EnrolmentAccepted' : 'Accepted', 'EnrolmentRejected' : 'Rejected', 'EnrolmentWaiting' : 'Pending', 'EnrolmentStatus' : 'Enrolment status', 'Enrolment' : 'Enrolment', 'Paid' : 'Paid', 'Patronage' : 'Patronage', 'patronage-title' : 'Patronage:', 'rektor-title' : 'Rector of Uniwersity of Wrocล‚aw', 'rektor-name' : 'Prof. dr hab. <NAME>', 'Payment Status' : 'Payment status', 'PaymentAccepted' : 'Accepted', 'PaymentWaiting' : 'Pending', 'Conference':'Conference', 'wantInvoice':'The invoice is needed', 'footerUniversity':'Uniwersystet Wrocล‚awski', 'footerInstitute':'Instytut historyczny', 'ShowWorkhopEnrolments' : 'Workshops', 'noPayment':'No', 'Workshops':'Workshops', 'Invoice' : 'Invoice', 'Show deleted workshops' : 'Show deleted workshops', 'Show workshops' : 'Show workshops', 'Place' : 'Place', 'LeaveComment' : 'Leave a comment:' };<file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'patronage', templateUrl: './patronage.component.html', styleUrls: ['./patronage.component.css'] }) export class PatronageComponent implements OnInit { constructor() { } ngOnInit() { } } <file_sep>import { Injectable } from '@angular/core'; import { CanActivate } from '@angular/router'; import { AuthenticationService } from '../services/authentication.service'; import { isLoggedin } from '../services/is-loggedin'; //TODO user obiekt @Injectable() export class CanActivateUserGuard { constructor() { } canActivate() { return ( !!localStorage.getItem( 'userid' ) ) && ( !!localStorage.getItem( 'username' ) ); } } <file_sep>import { Component, OnDestroy, Input } from '@angular/core'; //Importt the Image interface import { Image } from './image.interface'; import { SlideComponent } from "app/slide/slide.component"; export enum Direction { UNKNOWN, NEXT, PREV } @Component( { selector: 'carousel', templateUrl: './carousel.component.html', styleUrls: ['./carousel.component.css'] } ) //Carousel Component itself export class CarouselComponent implements OnDestroy { @Input() public noWrap: boolean; @Input() public noPause: boolean; @Input() public noTransition: boolean; public text: string; @Input() public get interval(): number { return this._interval; } public set interval( value: number ) { this._interval = value; this.restartTimer(); } private slides: Array<SlideComponent> = []; private currentInterval: any; private isPlaying: boolean; private destroyed: boolean = false; private currentSlide: SlideComponent; private _interval: number; public ngOnDestroy() { this.destroyed = true; } public select( nextSlide: SlideComponent, direction: Direction = Direction.UNKNOWN ) { let nextIndex = nextSlide.index; if ( direction === Direction.UNKNOWN ) { direction = nextIndex > this.getCurrentIndex() ? Direction.NEXT : Direction.PREV; } // Prevent this user-triggered transition from occurring if there is already one in progress if ( nextSlide && nextSlide !== this.currentSlide ) { this.goNext( nextSlide, direction ); } } private goNext( slide: SlideComponent, direction: Direction ) { if ( this.destroyed ) { return; } slide.direction = direction; slide.active = true; if ( this.currentSlide ) { this.currentSlide.direction = direction; this.currentSlide.active = false; } this.currentSlide = slide; // every time you change slides, reset the timer this.restartTimer(); } private getSlideByIndex( index: number ) { let len = this.slides.length; for ( let i = 0; i < len; ++i ) { if ( this.slides[i].index === index ) { return this.slides[i]; } } } private getCurrentIndex() { return !this.currentSlide ? 0 : this.currentSlide.index; } private next() { let newIndex = ( this.getCurrentIndex() + 1 ) % this.slides.length; if ( newIndex === 0 && this.noWrap ) { this.pause(); return; } return this.select( this.getSlideByIndex( newIndex ), Direction.NEXT ); } private prev() { let newIndex = this.getCurrentIndex() - 1 < 0 ? this.slides.length - 1 : this.getCurrentIndex() - 1; if ( this.noWrap && newIndex === this.slides.length - 1 ) { this.pause(); return; } return this.select( this.getSlideByIndex( newIndex ), Direction.PREV ); } private restartTimer() { this.resetTimer(); let interval = +this.interval; if ( !isNaN( interval ) && interval > 0 ) { this.currentInterval = setInterval(() => { let nInterval = +this.interval; if ( this.isPlaying && !isNaN( this.interval ) && nInterval > 0 && this.slides.length ) { this.next(); } else { this.pause(); } }, interval ); } } private resetTimer() { if ( this.currentInterval ) { clearInterval( this.currentInterval ); this.currentInterval = null; } } public play() { if ( !this.isPlaying ) { this.isPlaying = true; this.restartTimer(); } } public pause() { if ( !this.noPause ) { this.isPlaying = false; this.resetTimer(); } } public addSlide( slide: SlideComponent ) { slide.index = this.slides.length; this.slides.push( slide ); if ( this.slides.length === 1 || slide.active ) { this.select( this.slides[this.slides.length - 1] ); if ( this.slides.length === 1 ) { this.play(); } } else { slide.active = false; } } public removeSlide( slide: SlideComponent ) { this.slides.splice( slide.index, 1 ); if ( this.slides.length === 0 ) { this.currentSlide = null; return; } for ( let i = 0; i < this.slides.length; i++ ) { this.slides[i].index = i; } } //images data to be bound to the template public images = IMAGES; } //IMAGES array implementing Image interface var IMAGES: Image[] = [ { "title": "Patton", "url": "http://wolna-polska.pl/wp-content/uploads/2014/12/a28.jpg", "description": "<NAME> Junior (ur. 11 listopada 1885 w San Gabriel, zm. 21 grudnia 1945 w Heidelbergu w Niemczech) โ€“ amerykaล„ski generaล‚ okresu II wojny ล›wiatowej.Byล‚ postaciฤ… bardzo kontrowersyjnฤ…, budziล‚ skrajne uczucia zarรณwno u swoich podwล‚adnych, jak i u przeล‚oลผonych. Wล›rรณd swoich ลผoล‚nierzy znany byล‚ jako Old blood and guts. Znakomity kawalerzysta i szermierz (napisaล‚ m.in. instrukcjฤ™ szermierczฤ… dla kawalerii amerykaล„skiej), namiฤ™tnie grywaล‚ w polo. Opowiadaล‚ o swoich bardzo realistycznych wizjach wczeล›niejszych wcieleล„. Wierzyล‚ w reinkarnacjฤ™, uwaลผaล‚ siฤ™ m.in. za wcielenie kartagiล„skiego ลผoล‚nierza, rzymskiego legionisty, napoleoล„skiego generaล‚a i wielu innych postaci." }, { "title": "Eisenhower", "url": "https://fthmb.tqn.com/-iPOZ5lTnUG6Y9dHryCI8lUGHDI=/768x0/filters:no_upscale()/about/dd-eisenhower-large-56a61ba75f9b58b7d0dff3c1.jpg", "description": "ps. Ike (ur. 14 paลบdziernika 1890 w Denison, zm. 28 marca 1969 w Waszyngtonie) โ€“ amerykaล„ski dowรณdca wojskowy, generaล‚ armii United States Army, uczestnik II wojny ล›wiatowej, Naczelny Dowรณdca Alianckich Ekspedycyjnych Siล‚ Zbrojnych (1943โ€“1945), polityk, 34. prezydent Stanรณw Zjednoczonych (1953โ€“1961)." }, { "title": "Anders", "url": "https://ocdn.eu/pulscms-transforms/1/lHbktkpTURBXy8zYjdmNTgxMGQzMmQ3NTgwOTJmYjU5ODgzMjA2NjljOC5qcGeSlQMAzQS1zROwzQsTkwXNAyDNAcI", "description": "(ur. 11 sierpnia 1892 w Bล‚oniu, zm. 12 maja 1970 w Londynie) โ€“ generaล‚ dywizji Polskich Siล‚ Zbrojnych, Naczelny Wรณdz Polskich Siล‚ Zbrojnych w latach 1944โ€“1945 i 1946โ€“1954[potrzebny przypis], nastฤ™pca prezydenta RP na uchodลบstwie w latach 1950โ€“1954, w 1954 mianowany przez wล‚adze emigracyjne generaล‚em broni." }, { "title": "Sosabowski", "url": "http://77.spds.w.interiowo.pl/sosabowski/2.jpg", "description": "<NAME> (ur. 8 maja 1892 w Stanisล‚awowie, zm. 25 wrzeล›nia 1967 w Londynie) โ€“ dziaล‚acz niepodlegล‚oล›ciowy, czล‚onek ruchu strzeleckiego i skautingu, uczestnik I wojny ล›wiatowej w szeregach armii austro-wฤ™gierskiej, puล‚kownik dyplomowany piechoty Wojska Polskiego, 15 czerwca 1944 roku mianowany generaล‚em brygady, organizator i dowรณdca 1 Samodzielnej Brygady Spadochronowej, z ktรณrฤ… walczyล‚ w bitwie o Arnhem." }, { "title": "Rommel", "url": "https://artofwar.pl/wp-content/uploads/photo-gallery/Erwin_Rommel3.jpeg", "description": "<NAME> byล‚ najmล‚odszym niemieckim feldmarszaล‚kiem (Generalfeldmarschall) podczas II wojny ล›wiatowej. Dowodziล‚ Afrika Korps โ€“ niemieckim korpusem ekspedycyjnym w Afryce. Dziฤ™ki swoim znakomitym posuniฤ™ciom i taktyce szybkiego przemieszczania wojsk staล‚ siฤ™ ลผywฤ… legendฤ… wล›rรณd ลผoล‚nierzy niemieckich, ale przede wszystkim wล›rรณd aliantรณw. Ze wzglฤ™du na przebiegล‚oล›ฤ‡ nazwany Lisem Pustyni (niem. Wรผstenfuchs). Pod koniec wojny (1944) zostaล‚ skierowany do Francji jako dowรณdca Grupy Armii B, z zadaniem poprawienia umocnieล„ w Normandii, w obliczu spodziewanej alianckiej inwazji. Miaล‚ syna, ktรณry przeลผyล‚ wojnฤ™." } ];<file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'enrolment-created', templateUrl: './enrolment-created.component.html', styleUrls: ['./enrolment-created.component.css'] }) export class EnrolmentCreatedComponent implements OnInit { constructor() { } ngOnInit() { } } <file_sep>import { Component, OnInit } from '@angular/core'; import { TranslateService } from "app/translations/translate.service"; import { Config } from "app/utils/config"; @Component( { selector: 'languages', templateUrl: './languages.component.html', styleUrls: ['./languages.component.css'] } ) //https://scotch.io/tutorials/simple-language-translation-in-angular-2-part-1 export class LanguagesComponent implements OnInit { public supportedLanguages: any[]; constructor( private _translate: TranslateService ) { } ngOnInit() { // standing data this.supportedLanguages = [ { display: 'Polski', value: 'pl', flag: 'pl' }, { display: 'English', value: 'en', flag: 'gb' }, { display: 'Deutsch', value: 'de', flag: 'de' } ]; // set current langage this.selectLang( 'pl' ); } isCurrentLang( lang: string ) { // check if the selected lang is current lang return lang === this._translate.currentLang; } selectLang( lang: string ) { // set current lang; this._translate.use( lang ); } isShowLangs() { return Config.isShowLangs(); } } <file_sep>import { Injectable } from '@angular/core'; import { CanActivate } from '@angular/router'; import { AuthenticationService } from '../services/authentication.service'; import { isLoggedin } from '../services/is-loggedin'; //TODO user obiekt with admin priv @Injectable() export class CanActivateAdminGuard { constructor() { } canActivate() { return !!localStorage.getItem( 'admintoken' ); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { LocalDataSource } from "ng2-smart-table/ng2-smart-table"; import { Workshop } from "app/models/workshop"; import { WorkshopService } from "app/services/workshop.service"; import { Router } from "@angular/router"; import { DatePipe } from "@angular/common"; @Component( { selector: 'admin-workshops', templateUrl: './admin-workshops.component.html', styleUrls: ['./admin-workshops.component.css'] } ) export class AdminWorkshopsComponent implements OnInit { workshops: Workshop[]; source: LocalDataSource; activeWorkshopView: boolean; constructor( private workshopService: WorkshopService, private router: Router ) { this.source = new LocalDataSource(); this.workshopService.getWorkshops().toPromise().then(( data ) => { this.source.load( data ); } ); this.activeWorkshopView = true; } ngOnInit() { window.scrollTo( 0, 0 ) } loadWorkshops() { this.workshopService.getWorkshops().toPromise().then(( data ) => { this.source.load( data ); } ); } loadDeletedWorkshops() { this.workshopService.getDeletedWorkshops().toPromise().then(( data ) => { this.source.load( data ); } ); } settings = { columns: { title: { title: 'Tytul' }, author: { title: 'Autor' }, date: { title: 'Data' }, //TODO wpasowac w routingAdmin admin/(adminRouting:admin-articles) //return '<a href="/admin-article/' + row.id + '">Edytuj</a>' link: { title: 'Akcja', type: 'html', valuePrepareFunction: ( cell, row ) => { return '<a href="/admin-workshop/' + row.id + '">Edytuj</a>' } }, // button: { // title: 'Button', // type: 'custom', // renderComponent: AdminTableButtonComponent, // onComponentInitFunction(instance) { // instance.save.subscribe(row => { // alert(`${row.name} saved!`) // }); // } // } }, actions: false }; createNew() { this.router.navigate( ['admin-workshop-new/'] ); } isShowActive() { return this.activeWorkshopView; } showDeletedWorkshops() { this.loadDeletedWorkshops(); this.activeWorkshopView = false; } showActiveWorkshops() { this.loadWorkshops(); this.activeWorkshopView = true; } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Article } from "app/models/article"; import { ActivatedRoute, Router } from "@angular/router"; import { ConfirmationService, MenuItem } from "primeng/primeng"; import { Message } from "primeng/components/common/api"; import { WorkshopService } from "app/services/workshop.service"; import { Workshop } from "app/models/workshop"; import { ActionAdminEnrolmentComponent } from "app/action-admin-enrolment/action-admin-enrolment.component"; import { ActionAdminPaymentComponent } from "app/action-admin-payment/action-admin-payment.component"; import { DatePipe } from "@angular/common"; import { WorkshopsUserService } from "app/services/workshops-user.service"; import { LocalDataSource } from "ng2-smart-table/ng2-smart-table"; @Component( { selector: 'admin-workshop', templateUrl: './admin-workshop.component.html', styleUrls: ['./admin-workshop.component.css'], providers: [ConfirmationService] } ) export class AdminWorkshopComponent implements OnInit { text: string; workshop: Workshop; // articlesHistory: ArticleHistory[]; msgs: Message[] = []; navigationItems: MenuItem[]; requiredFieldsAlert: boolean; saveSuccessAlert: boolean; source: LocalDataSource; constructor( private route: ActivatedRoute, private router: Router, private workshopService: WorkshopService, private worskhopsUserService: WorkshopsUserService, private confirmationService: ConfirmationService ) { } ngOnInit() { window.scrollTo( 0, 0 ) this.route.data.subscribe( ( data: { workshop: Workshop } ) => { if ( data.workshop ) { this.workshop = data.workshop; } else { //TODO Michal error and redirect } } ); this.source = new LocalDataSource(); if ( this.workshop ) { this.worskhopsUserService.getUsersForWorkshop( this.workshop.id ).toPromise().then(( data ) => { this.source.load( data ); } ); } } saveNew() { //todo get from localStorage.getItem( 'token' ) this.workshop.fk_editor = '1'; this.workshopService.addWorkshop( this.workshop ).subscribe( workshops => { // Emit list event // //navigate // EmitterService.get( this.listId ).emit( enrolments ); // Empty model this.navigateBack(); }, err => { // Log errors if any console.log( err ); } ); //TODO <NAME>czasowo bo nie ma odpowiedzi this.navigateBack(); } save() { //TODO get from localStorage.getItem( 'token' ) this.requiredFieldsAlert = false; this.saveSuccessAlert = false; if ( this.validate() ) { this.workshop.fk_editor = localStorage.getItem( 'userid' ) this.workshopService.updateWorkshop( this.workshop ).subscribe( workshops => { // Emit list event // //navigate // EmitterService.get( this.listId ).emit( enrolments ); // Empty model this.msgs = []; this.msgs.push( { severity: 'success', summary: 'Zapis zakonczony powodzeniem.', detail: '' } ); this.saveSuccessAlert = true; window.scrollTo( 0, 0 ) }, err => { // Log errors if any console.log( err ); this.requiredFieldsAlert = false; } ); } else { this.requiredFieldsAlert = true; this.msgs = []; this.msgs.push( { severity: 'error', summary: 'Proszฤ™ uzupeล‚nic wszystkie obowiฤ…zkowe (*) pola.', detail: '' } ); } } cancel() { this.navigateBack(); } isNew() { return ( !this.workshop.id || 0 === this.workshop.id.length ); } isDeleted() { return 'D' === this.workshop.status } // getArticlesHistory() { // this.articleService.getArticleHistory( this.article.id ) // .subscribe( // articles => this.articlesHistory = articles, //Bind to view // err => { // // Log errors if any // console.log( err ); // } ); // } confirmDelete() { this.confirmationService.confirm( { message: 'Do you want to delete this record?', header: 'Delete Confirmation', icon: 'fa fa-trash', accept: () => { this.msgs = [{ severity: 'info', summary: 'Confirmed', detail: 'Record deleted' }]; this.deleteWorkshop(); }, reject: () => { this.msgs = [{ severity: 'info', summary: 'Rejected', detail: 'You have rejected' }]; } } ); } deleteWorkshop() { this.workshopService.deleteWorkshop( this.workshop ).subscribe( articles => { // Emit list event // //navigate // EmitterService.get( this.listId ).emit( enrolments ); // Empty model this.navigateBack(); }, err => { // Log errors if any console.log( err ); } ); this.navigateBack(); } activateWorkshop() { this.workshopService.activateWorkshop( this.workshop ).subscribe( workshops => { // Emit list event // //navigate // EmitterService.get( this.listId ).emit( enrolments ); // Empty model this.navigateBack(); }, err => { // Log errors if any console.log( err ); } ); } navigateBack() { this.router.navigate( ['/admin', { outlets: { adminRouting: ['admin-workshops'] } }] ) } validate() { var result = true; if ( this.isEmpty( this.workshop.title ) ) { result = false; // this.userForm..password1 = '<PASSWORD>'; } else { // this.userForm.password1 = '<PASSWORD>'; } return result; } isEmpty( str ) { return ( !str || 0 === str.length ); } requiredFieldsAlertVisible() { return this.requiredFieldsAlert } saveSuccessAlertVisible() { return this.saveSuccessAlert } settings = { columns: { name: { title: 'Imie' }, surname: { title: 'Nazwisko' }, email: { title: 'Email' }, university: { title: 'Uniwersytet' }, congressrole: { title: 'Rola', type: 'html', valuePrepareFunction: ( value ) => { if ( value === 'U' ) return 'Uczestnik'; if ( value === 'R' ) return 'Referent'; if ( value === 'O' ) return 'Organizator'; return '' }, filterFunction( cell?: any, search?: string ): boolean { if ( search != null ) { if ( "uczestnik".search( search ) > 0 ) { if ( cell === 'U' ) { return true; } return false; } if ( "referent".search( search ) > 0 ) { if ( cell === 'R' ) { return true; } return false; } if ( "organizator".search( search ) > 0 ) { if ( cell === 'U' ) { return true; } return false; } } if ( search === '' ) { return true; } else { return false; } } }, academic_title: { title: 'Tytul', type: 'html', valuePrepareFunction: ( value ) => { if ( value === '1' ) return 'mgr'; if ( value === '2' ) return 'dr'; if ( value === '3' ) return 'dr hab.'; if ( value === '4' ) return 'Prof. (stan.)'; if ( value === '5' ) return 'Prof.'; return '' } }, payment: { title: 'Oplata', type: 'custom', renderComponent: ActionAdminPaymentComponent, valuePrepareFunction: ( cell, row ) => { return row } }, action: { title: 'Akcja', type: 'custom', renderComponent: ActionAdminEnrolmentComponent, valuePrepareFunction: ( cell, row ) => { return row } } }, actions: false }; } <file_sep>import { OpaqueToken } from '@angular/core'; //import translations import { LANG_EN_NAME, LANG_EN_TRANS } from './lang-en'; import { LANG_DE_NAME, LANG_DE_TRANS } from './lang-de' import { LANG_PL_NAME, LANG_PL_TRANS } from './lang-pl' //translation token export const TRANSLATIONS = new OpaqueToken( 'translations' ); // Fix: Error encountered resolving symbol values statically //https://github.com/angular/angular/issues/13983 // //all translations export const dictionary = { 'en': LANG_EN_TRANS, 'de': LANG_DE_TRANS, 'pl': LANG_PL_TRANS, } //providers export const TRANSLATION_PROVIDERS = [ { provide: TRANSLATIONS, useValue: dictionary },];<file_sep>import { Injectable, } from '@angular/core'; import { ActivatedRouteSnapshot, Resolve, Router, RouterStateSnapshot } from '@angular/router'; import { Observable } from 'rxjs/Rx'; import { Workshop } from "app/models/workshop"; import { WorkshopService } from "app/services/workshop.service"; @Injectable() export class WorkshopResolver implements Resolve<Workshop> { constructor( private workshopService: WorkshopService, private router: Router, ) {} resolve( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable<Workshop> { return this.workshopService.getWorkshop(route.params['id']) .catch((err) => this.router.navigateByUrl('/')); } }<file_sep>import { Component, OnInit } from '@angular/core'; import { WorkshopService } from "app/services/workshop.service"; import { Workshop } from "app/models/workshop"; @Component( { selector: 'workshops', templateUrl: './workshops.component.html', styleUrls: ['./workshops.component.css'] } ) export class WorkshopsComponent implements OnInit { workshops: Workshop[]; constructor( private workshopService: WorkshopService ) { } ngOnInit() { this.loadWorkshops() window.scrollTo( 0, 0 ) } loadWorkshops() { this.workshopService.getWorkshops() .subscribe( workshops => this.workshops = workshops, //Bind to view err => { // Log errors if any console.log( err ); } ); } } <file_sep>import { Component, OnInit, Input } from '@angular/core'; import { User } from "app/models/user"; import { UserService } from "app/services/user.service"; import { ConfirmationService } from "primeng/primeng"; import { Message } from "primeng/components/common/api"; @Component( { selector: 'action-admin-payment', templateUrl: './action-admin-payment.component.html', styleUrls: ['./action-admin-payment.component.css'], providers: [ConfirmationService] } ) export class ActionAdminPaymentComponent implements OnInit { msgs: Message[] = []; @Input() value: User; constructor( private userService: UserService, private confirmationService: ConfirmationService ) { } ngOnInit() { } isPaymentAccepted() { if ( 'Y' == this.value.payment_accepted ) { return true; } return false; } isPaymentAcceptationPending() { if ( 'Y' == this.value.payment_accepted ) { return false; } return true; } acceptPayment() { //TODO refresh lub dymek this.userService.acceptPayment( this.value ).subscribe( response => { if ( response.text() === 'OK' ) { - console.log( 'udalo sie accepted ' + response.text() ); // this.value.payment_accepted = 'Y' } }, err => { // Log errors if any console.log( err ); } ); } confirmPaymentReject() { this.confirmationService.confirm( { message: 'Czy na pewno chcesz anulowac status platnosci?', header: 'Potwierdz odrzucenie', icon: 'fa fa-trash', accept: () => { this.msgs = [{ severity: 'info', summary: 'Confirmed', detail: 'Status anulowany' }]; this.rejectPayment(); }, reject: () => { this.msgs = [{ severity: 'info', summary: 'Rejected', detail: 'Anulowano' }]; } } ); } rejectPayment() { //TODO refresh lub dymek this.userService.rejectPayment( this.value ).subscribe( response => { if ( response.text() === 'OK' ) { - console.log( 'udalo sie rejected ' + response.text() ); this.value.payment_accepted = 'N' // } }, err => { // Log errors if any console.log( err ); } ); } } <file_sep>import { Injectable, } from '@angular/core'; import { ActivatedRouteSnapshot, Resolve, Router, RouterStateSnapshot } from '@angular/router'; import { Observable } from 'rxjs/Rx'; import { Lecture } from "app/models/lecture"; @Injectable() export class LectureNewResolver implements Resolve<Lecture> { constructor( private router: Router, ) { } resolve( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable<Lecture> { return Observable.create( observer => { observer.next( new Lecture( '', '', '', '', '', '', '', '', 'A' ) ); observer.complete(); } ); } } <file_sep>import { ModuleWithProviders } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { AppComponent } from './app.component'; import { EnrolmentsComponent } from './enrolments/enrolments.component'; import { ApplicationFormComponent } from './application-form/application-form.component'; import { LoginComponent } from './login/login.component'; import { TextEditorComponent } from './text-editor/text-editor.component'; import { AdminComponent } from "app/admin/admin.component"; import { MapComponent } from "app/map/map.component"; import { NewsComponent } from "app/news/news.component"; import { ArticleComponent } from "app/article/article.component"; import { ArticleResolver } from './services/article-resolver.service'; import { AdminArticleComponent } from "app/admin-article/admin-article.component"; import { ArticleNewResolver } from "app/services/article-new-resolver.service"; import { LoginRegisterComponent } from "app/login-register/login-register.component"; import { CanActivateAdminGuard } from "app/services/can-activate-admin-guard"; import { UserLoggedComponent } from "app/user-logged/user-logged.component"; import { CanActivateUserGuard } from "app/services/can-activate-user-guard"; import { UserProfileComponent } from "app/user-profile/user-profile.component"; import { ContactComponent } from "app/contact/contact.component"; import { AdminArticlesComponent } from "app/admin-articles/admin-articles.component"; import { AdminNewsComponent } from "app/admin-news/admin-news.component"; import { ScheduleComponent } from "app/schedule/schedule.component"; import { AdminSchedulesComponent } from "app/admin-schedules/admin-schedules.component"; import { ScheduleResolver } from "app/services/schedule-resolver.service"; import { AdminScheduleComponent } from "app/admin-schedule/admin-schedule.component"; import { ScheduleNewResolver } from "app/services/schedule-new-resolver.service"; import { AdminEventComponent } from "app/admin-event/admin-event.component"; import { EventResolver } from "app/services/event-resolver.service"; import { EventNewResolver } from "app/services/event-new-resolver.service"; import { NewsNewResolver } from "app/services/news-new-resolver.service"; import { NewsResolver } from "app/services/news-resolver.service"; import { AdminSingleNewsComponent } from "app/admin-single-news/admin-single-news.component"; import { NewsSingleComponent } from "app/news-single/news-single.component"; import { ArticlesComponent } from "app/articles/articles.component"; import { TermsComponent } from "app/terms/terms.component"; import { ForgotPasswordComponent } from "app/forgot-password/forgot-password.component"; import { SponsorsComponent } from "app/sponsors/sponsors.component"; import { AdminEnrolmentComponent } from "app/admin-enrolment/admin-enrolment.component"; import { UserResolver } from "app/services/user-resolver.service"; import { EnrolmentCreatedComponent } from "app/enrolment-created/enrolment-created.component"; import { AdminMailboxComponent } from "app/admin-mailbox/admin-mailbox.component"; import { LetterOfIntentComponent } from "app/letter-of-intent/letter-of-intent.component"; import { WelcomePageComponent } from "app/welcome-page/welcome-page.component"; import { LinksComponent } from "app/links/links.component"; import { PatronageComponent } from "app/patronage/patronage.component"; import { PaymentInfoComponent } from "app/payment-info/payment-info.component"; import { WorkshopsComponent } from "app/workshops/workshops.component"; import { AdminWorkshopsComponent } from "app/admin-workshops/admin-workshops.component"; import { AdminWorkshopComponent } from "app/admin-workshop/admin-workshop.component"; import { WorkshopNewResolver } from "app/services/workshop-new-resolver.service"; import { WorkshopResolver } from "app/services/workshop-resolver.service"; import { AdminLecturesComponent } from "app/admin-lectures/admin-lectures.component"; import { LectureNewResolver } from "app/services/lecture-new-resolver.service"; import { AdminLectureComponent } from "app/admin-lecture/admin-lecture.component"; import { LectureResolver } from "app/services/lecture-resolver.service"; import { LecturesComponent } from "app/lectures/lectures.component"; import { SectionsComponent } from "app/sections/sections.component"; export const router: Routes = [ { path: '', component: WelcomePageComponent }, { path: 'enrolments', component: EnrolmentsComponent }, { path: 'application-form', component: ApplicationFormComponent }, { path: 'login', component: LoginComponent }, { path: 'login-register', component: LoginRegisterComponent }, { path: 'map', component: MapComponent }, { path: 'terms', component: TermsComponent }, { path: 'welcome/terms', component: TermsComponent }, { path: 'login-register/terms', component: TermsComponent }, { path: 'news', component: NewsComponent }, { path: 'welcome', component: WelcomePageComponent }, { path: 'admin', component: AdminComponent, canActivate: [ CanActivateAdminGuard ], //dodac guard children: [ { path: '', component: EnrolmentsComponent, outlet: 'adminRouting' }, { path: 'admin-workshops', component: AdminWorkshopsComponent, outlet: 'adminRouting' }, { path: 'admin-lectures', component: AdminLecturesComponent, outlet: 'adminRouting' }, { path: 'admin-mailbox', component: AdminMailboxComponent, outlet: 'adminRouting' }, { path: 'admin-news', component: AdminNewsComponent, outlet: 'adminRouting' }, { path: 'admin-schedules', component: AdminSchedulesComponent, outlet: 'adminRouting' }, { path: 'enrolments', component: EnrolmentsComponent, outlet: 'adminRouting' }, { path: 'admin-article/:id', component: AdminArticleComponent, resolve: { article: ArticleResolver }, canActivate: [ CanActivateAdminGuard ], }, { path: 'admin-schedule/:id', component: AdminScheduleComponent, resolve: { schedule: ScheduleResolver }, canActivate: [ CanActivateAdminGuard ], }, { path: 'admin-schedule-new', component: AdminScheduleComponent, resolve: { schedule: ScheduleNewResolver }, canActivate: [ CanActivateAdminGuard ], outlet: 'adminRouting' }, ] }, { path: 'article/:id', component: ArticleComponent, resolve: { article: ArticleResolver }, }, { path: 'admin-user/:id', component: AdminEnrolmentComponent, resolve: { user: UserResolver }, canActivate: [ CanActivateAdminGuard ], }, { path: 'news/:id', component: NewsSingleComponent, resolve: { news: NewsResolver }, }, { path: 'admin-article/:id', component: AdminArticleComponent, resolve: { article: ArticleResolver }, canActivate: [ CanActivateAdminGuard ], }, { path: 'admin-single-news/:id', component: AdminSingleNewsComponent, resolve: { news: NewsResolver }, canActivate: [ CanActivateAdminGuard ], }, { path: 'admin-schedule/:id', component: AdminScheduleComponent, resolve: { schedule: ScheduleResolver }, canActivate: [ CanActivateAdminGuard ], }, { path: 'admin-event/:id', component: AdminEventComponent, resolve: { event: EventResolver }, canActivate: [ CanActivateAdminGuard ], }, { path: 'admin-article-new', component: AdminArticleComponent, resolve: { article: ArticleNewResolver }, canActivate: [ CanActivateAdminGuard ], }, { path: 'admin-schedule-new', component: AdminScheduleComponent, resolve: { schedule: ScheduleNewResolver }, canActivate: [ CanActivateAdminGuard ], }, { path: 'admin-event-new', component: AdminEventComponent, resolve: { event: EventNewResolver }, canActivate: [ CanActivateAdminGuard ], }, { path: 'admin-news-new', component: AdminSingleNewsComponent, resolve: { news: NewsNewResolver }, canActivate: [ CanActivateAdminGuard ], }, { path: 'user-profile', component: UserProfileComponent, resolve: { article: ArticleNewResolver }, canActivate: [ CanActivateUserGuard ], }, { path: 'admin-workshop-new', component: AdminWorkshopComponent, resolve: { workshop: WorkshopNewResolver }, canActivate: [ CanActivateAdminGuard ], }, { path: 'admin-lecture-new', component: AdminLectureComponent, resolve: { lecture: LectureNewResolver }, canActivate: [ CanActivateAdminGuard ], }, { path: 'admin-workshop/:id', component: AdminWorkshopComponent, resolve: { workshop: WorkshopResolver }, canActivate: [ CanActivateAdminGuard ], }, { path: 'admin-lecture/:id', component: AdminLectureComponent, resolve: { lecture: LectureResolver }, canActivate: [ CanActivateAdminGuard ], }, { path: 'articles', component: ArticlesComponent }, { path: 'schedules', component: ScheduleComponent }, { path: 'contact', component: ContactComponent }, { path: 'links', component: LinksComponent }, { path: 'login-register/forgot-password', component: ForgotPasswordComponent }, { path: 'welcome/forgot-password', component: ForgotPasswordComponent }, { path: 'forgot-password', component: ForgotPasswordComponent }, { path: 'sponsors', component: SponsorsComponent }, { path: 'login-register/enrolment-created', component: EnrolmentCreatedComponent }, { path: 'enrolment-created', component: EnrolmentCreatedComponent }, { path: 'letter-of-intent', component: LetterOfIntentComponent }, { path: 'workshops', component: WorkshopsComponent }, { path: 'lectures', component: LecturesComponent }, { path: 'sections', component: SectionsComponent }, { path: 'patronage', component: PatronageComponent }, { path: 'paymentInfo', component: PaymentInfoComponent } ]; export const routes: ModuleWithProviders = RouterModule.forRoot( router );<file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { AgmCoreModule } from '@agm/core'; import { Ng2SmartTableModule } from 'ng2-smart-table'; //PrimeNG import { AutoCompleteModule } from 'primeng/primeng'; import { EditorModule } from 'primeng/primeng'; import { ButtonModule } from 'primeng/primeng'; import { ArticleComponent } from './article/article.component'; import { InputMaskModule } from 'primeng/primeng'; import { RadioButtonModule } from 'primeng/primeng'; import { InputTextModule } from 'primeng/primeng'; import { TabViewModule } from 'primeng/primeng'; import { ConfirmDialogModule, ConfirmationService } from 'primeng/primeng'; import { BreadcrumbModule } from 'primeng/primeng'; import { AccordionModule } from 'primeng/primeng'; import { ArticleNewResolver } from "app/services/article-new-resolver.service"; import { LoginRegisterComponent } from './login-register/login-register.component'; import { SelectButtonModule } from 'primeng/primeng'; import { FileUploadModule } from 'primeng/primeng'; import { GrowlModule } from 'primeng/primeng'; import { CarouselModule } from 'primeng/primeng'; import { CalendarModule } from 'primeng/primeng'; import { MultiSelectModule } from 'primeng/primeng'; import {CheckboxModule} from 'primeng/primeng'; import { EnrolmentService } from './services/enrolment.service'; import { ArticleService } from './services/article.service'; import { AuthenticationService } from './services/authentication.service'; import { UniversityService } from './services/university.service'; import { ArticleResolver } from './services/article-resolver.service'; import { ContactService } from "app/services/contact.service"; import { CommentService } from './services/comment.service'; import { ImageService } from './services/image.service'; import { NewsService } from './services/news.service'; import { WorkshopService } from './services/workshop.service'; import {UserInfoService} from './services/user-info.service'; import {WorkshopsUserService} from './services/workshops-user.service'; //internationalization import { TranslateService } from "app/translations/translate.service"; import { TRANSLATION_PROVIDERS } from "app/translations/translations"; import { TranslatePipe } from "app/translations/translate.pipe"; import { LanguagesComponent } from './languages/languages.component'; //guards import { CanActivateAdminGuard } from "app/services/can-activate-admin-guard"; import { CanActivateUserGuard } from "app/services/can-activate-user-guard"; import { routes } from './app.router'; import { LoginComponent } from './login/login.component'; import { TextEditorComponent } from './text-editor/text-editor.component'; import { AdminComponent } from './admin/admin.component'; import { MapComponent } from './map/map.component'; import { NewsComponent } from './news/news.component'; import { ArticlesComponent } from './articles/articles.component'; import { ArticleBoxComponent } from './article-box/article-box.component'; import { FooterComponent } from './footer/footer.component'; import { HeaderComponent } from './header/header.component'; import { AdminArticlesComponent } from './admin-articles/admin-articles.component'; import { PrintComponent } from './print/print.component'; import { AdminArticleComponent } from './admin-article/admin-article.component'; import { AdminArticleHistoryComponent } from './admin-article-history/admin-article-history.component'; import { UserLoggedComponent } from './user-logged/user-logged.component'; import { UserProfileComponent } from './user-profile/user-profile.component'; import { AppComponent } from './app.component'; import { ApplicationFormComponent } from './application-form/application-form.component'; import { CarouselComponent } from './carousel/carousel.component'; import { MenuComponent } from './menu/menu.component'; import { EnrolmentsComponent } from './enrolments/enrolments.component'; import { UserService } from "app/services/user.service"; import { SlideComponent } from './slide/slide.component'; import { ContactComponent } from './contact/contact.component'; import { AdminMenuComponent } from './admin-menu/admin-menu.component'; import { CommentBoxComponent } from './comment-box/comment-box.component'; import { SchedulesComponent } from './schedules/schedules.component'; import { AdminSchedulesComponent } from './admin-schedules/admin-schedules.component'; import { ScheduleComponent } from './schedule/schedule.component'; import { AdminScheduleComponent } from './admin-schedule/admin-schedule.component'; import { AdminEventComponent } from './admin-event/admin-event.component'; import { ScheduleResolver } from "app/services/schedule-resolver.service"; import { ScheduleNewResolver } from "app/services/schedule-new-resolver.service"; import { NewsResolver } from "app/services/news-resolver.service"; import { NewsNewResolver } from "app/services/news-new-resolver.service"; import { ScheduleService } from "app/services/schedule.service"; import { EventService } from "app/services/event.service"; import { EventResolver } from "app/services/event-resolver.service"; import { EventNewResolver } from "app/services/event-new-resolver.service"; import { AdminNewsComponent } from './admin-news/admin-news.component'; import { AdminSingleNewsComponent } from './admin-single-news/admin-single-news.component'; import { NewsBoxComponent } from './news-box/news-box.component'; import { NewsSingleComponent } from './news-single/news-single.component'; import { CommentNewsService } from "app/services/comment-news.service"; import { AdminTableButtonComponent } from './admin-table-button/admin-table-button.component'; import { TermsComponent } from './terms/terms.component'; import { ForgotPasswordComponent } from './forgot-password/forgot-password.component'; import { SponsorsComponent } from './sponsors/sponsors.component'; import { AdminEnrolmentComponent } from './admin-enrolment/admin-enrolment.component'; import { EnrolmentCreatedComponent } from './enrolment-created/enrolment-created.component'; import { UserResolver } from "app/services/user-resolver.service"; import { AdminMailboxComponent } from './admin-mailbox/admin-mailbox.component'; import { LetterOfIntentComponent } from './letter-of-intent/letter-of-intent.component'; import { ActionAdminEnrolmentComponent } from './action-admin-enrolment/action-admin-enrolment.component'; import { WelcomePageComponent } from './welcome-page/welcome-page.component'; import { Footer2Component } from './footer2/footer2.component'; import { RegistrationInfoComponent } from './registration-info/registration-info.component'; import { OrganizersComponent } from './organizers/organizers.component'; import { LogoComponent } from './logo/logo.component'; import { AdminEnrolmentHistoryComponent } from './admin-enrolment-history/admin-enrolment-history.component'; import { LinksComponent } from './links/links.component'; import { PatronageComponent } from './patronage/patronage.component'; import { PaymentInfoComponent } from './payment-info/payment-info.component'; import { ActionAdminPaymentComponent } from './action-admin-payment/action-admin-payment.component'; import { WorkshopsComponent } from './workshops/workshops.component'; import { AdminWorkshopsComponent } from './admin-workshops/admin-workshops.component'; import { WorkshopResolver } from "app/services/workshop-resolver.service"; import { WorkshopNewResolver } from "app/services/workshop-new-resolver.service"; import { AdminWorkshopComponent } from './admin-workshop/admin-workshop.component'; import { WorkshopComponent } from './workshop/workshop.component'; import { AdminLecturesComponent } from './admin-lectures/admin-lectures.component'; import { AdminLectureComponent } from './admin-lecture/admin-lecture.component'; import { LecturesComponent } from './lectures/lectures.component'; import { LectureComponent } from './lecture/lecture.component'; import { LectureService } from "app/services/lecture.service"; import { LectureResolver } from "app/services/lecture-resolver.service"; import { LectureNewResolver } from "app/services/lecture-new-resolver.service"; import { SectionsComponent } from './sections/sections.component'; @NgModule( { declarations: [ AppComponent, ApplicationFormComponent, CarouselComponent, MenuComponent, EnrolmentsComponent, LoginComponent, TextEditorComponent, AdminComponent, MapComponent, NewsComponent, ArticlesComponent, ArticleBoxComponent, FooterComponent, HeaderComponent, TranslatePipe, LanguagesComponent, AdminArticlesComponent, ArticleComponent, PrintComponent, AdminArticleComponent, AdminArticleHistoryComponent, LoginRegisterComponent, UserLoggedComponent, UserProfileComponent, SlideComponent, ContactComponent, AdminMenuComponent, CommentBoxComponent, SchedulesComponent, AdminSchedulesComponent, ScheduleComponent, AdminScheduleComponent, AdminEventComponent, AdminNewsComponent, AdminSingleNewsComponent, NewsBoxComponent, NewsSingleComponent, AdminTableButtonComponent, TermsComponent, ForgotPasswordComponent, SponsorsComponent, AdminEnrolmentComponent, EnrolmentCreatedComponent, AdminMailboxComponent, LetterOfIntentComponent, ActionAdminEnrolmentComponent, WelcomePageComponent, Footer2Component, RegistrationInfoComponent, OrganizersComponent, LogoComponent, AdminEnrolmentHistoryComponent, LinksComponent, PatronageComponent, PaymentInfoComponent, ActionAdminPaymentComponent, WorkshopsComponent, AdminWorkshopsComponent, AdminWorkshopComponent, WorkshopComponent, AdminLecturesComponent, AdminLectureComponent, LecturesComponent, LectureComponent, SectionsComponent ], imports: [ BrowserModule, FormsModule, HttpModule, routes, AgmCoreModule.forRoot( { apiKey: '<KEY>' } ), AutoCompleteModule, EditorModule, ButtonModule, InputMaskModule, RadioButtonModule, InputTextModule, TabViewModule, Ng2SmartTableModule, ConfirmDialogModule, BreadcrumbModule, AccordionModule, SelectButtonModule, FileUploadModule, GrowlModule, CarouselModule, CalendarModule, MultiSelectModule, CheckboxModule ], providers: [EnrolmentService, ArticleService, AuthenticationService, UniversityService, UserService, CanActivateAdminGuard, CanActivateUserGuard, TRANSLATION_PROVIDERS, TranslateService, ArticleResolver, ArticleNewResolver, ScheduleResolver, ScheduleNewResolver, EventResolver, EventNewResolver, WorkshopResolver, WorkshopNewResolver, ConfirmationService, ImageService, NewsService, WorkshopService, WorkshopsUserService, NewsResolver, NewsNewResolver, LectureService, LectureResolver, LectureNewResolver, ContactService, CommentService, CommentNewsService, ScheduleService, EventService, UserResolver, UserInfoService], entryComponents: [ActionAdminEnrolmentComponent, ActionAdminPaymentComponent], bootstrap: [AppComponent], } ) export class AppModule { } <file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'menu', templateUrl: './menu.component.html', styleUrls: ['./menu.component.css'] }) //http://cssmenumaker.com/menu/modern-accordion-menu# export class MenuComponent implements OnInit { constructor() { } ngOnInit() { } isAdmin() { let admintoken = localStorage.getItem( 'admintoken' ); return ( admintoken ); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { LocalDataSource } from "ng2-smart-table/ng2-smart-table"; import { Lecture } from "app/models/lecture"; import { LectureService } from "app/services/lecture.service"; import { Router } from "@angular/router"; import { DatePipe } from "@angular/common"; @Component( { selector: 'admin-lectures', templateUrl: './admin-lectures.component.html', styleUrls: ['./admin-lectures.component.css'] } ) export class AdminLecturesComponent implements OnInit { lectures: Lecture[]; source: LocalDataSource; activeLectureView: boolean; constructor( private lectureService: LectureService, private router: Router ) { this.source = new LocalDataSource(); this.lectureService.getLectures().toPromise().then(( data ) => { this.source.load( data ); } ); this.activeLectureView = true; } ngOnInit() { window.scrollTo( 0, 0 ) } loadLectures() { this.lectureService.getLectures().toPromise().then(( data ) => { this.source.load( data ); } ); } loadDeletedLectures() { this.lectureService.getDeletedLectures().toPromise().then(( data ) => { this.source.load( data ); } ); } settings = { columns: { title: { title: 'Tytul' }, author: { title: 'Autor' }, date: { title: 'Data' }, //TODO wpasowac w routingAdmin admin/(adminRouting:admin-articles) //return '<a href="/admin-article/' + row.id + '">Edytuj</a>' link: { title: 'Akcja', type: 'html', valuePrepareFunction: ( cell, row ) => { return '<a href="/admin-lecture/' + row.id + '">Edytuj</a>' } }, // button: { // title: 'Button', // type: 'custom', // renderComponent: AdminTableButtonComponent, // onComponentInitFunction(instance) { // instance.save.subscribe(row => { // alert(`${row.name} saved!`) // }); // } // } }, actions: false }; createNew() { this.router.navigate( ['admin-lecture-new/'] ); } isShowActive() { return this.activeLectureView; } showDeletedLectures() { this.loadDeletedLectures(); this.activeLectureView = false; } showActiveLectures() { this.loadLectures(); this.activeLectureView = true; } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Config } from "app/utils/config"; @Component({ selector: 'admin-menu', templateUrl: './admin-menu.component.html', styleUrls: ['./admin-menu.component.css'] }) export class AdminMenuComponent implements OnInit { constructor() { } ngOnInit() { } isShowArticles() { return Config.isShowArticles(); } isShowNews() { return Config.isShowNews(); } isShowSchedules() { return Config.isShowSchedule(); } isShowWorkshops() { return Config.isShowWorkshops(); } isShowLectures() { return Config.isShowLectures(); } } <file_sep>import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http'; import { Comment } from '../models/comment'; import { Observable } from 'rxjs/Rx'; //Import RxJs required methods import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import { Config } from "app/utils/config"; @Injectable() export class CommentService { constructor( private http: Http ) { } private allCommentsUrl = Config.serverAddress + '/allArticleComments'; private confirmedCommentsUrl = Config.serverAddress + '/confirmedArticleComments'; getAllComments( id: string ): Observable<Comment[]> { let params: URLSearchParams = new URLSearchParams(); params.set( 'id', id ); var options = new RequestOptions( { headers: new Headers( { 'Content-Type': 'application/json' } ) } ); options.search = params; return this.http.get( this.allCommentsUrl, options ) .map(( res: Response ) => res.json() ) .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } getConfirmedComments( id: string ): Observable<Comment[]> { let params: URLSearchParams = new URLSearchParams(); params.set( 'id', id ); var options = new RequestOptions( { headers: new Headers( { 'Content-Type': 'application/json' } ) } ); options.search = params; return this.http.get( this.confirmedCommentsUrl, options ) .map(( res: Response ) => res.json() ) .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } addParentCommentConfirmedUser( body: Comment ): Observable<Comment[]> { let headers = new Headers( { 'Content-Type': 'application/json' } ); let options = new RequestOptions( { headers: headers } ); return this.http.post( this.confirmedCommentsUrl, JSON.stringify( body ), options ) .map(( res: Response ) => res.json() ) // ...and calling .json() on the response to return data .catch(( error: any ) => Observable.throw( error || 'Server error' ) ); //...errors if any } addParentCommentAdminUser( body: Comment ): Observable<Comment[]> { let headers = new Headers( { 'Content-Type': 'application/json' } ); let options = new RequestOptions( { headers: headers } ); return this.http.post( this.allCommentsUrl, JSON.stringify( body ), options ) .map(( res: Response ) => res.json() ) // ...and calling .json() on the response to return data .catch(( error: any ) => Observable.throw( error || 'Server error' ) ); //...errors if any } } <file_sep>import { Component, OnInit, Input } from '@angular/core'; import { UserHistory } from "app/models/user-history"; import { SelectItem } from "primeng/primeng"; @Component( { selector: 'admin-enrolment-history', templateUrl: './admin-enrolment-history.component.html', styleUrls: ['./admin-enrolment-history.component.css'] } ) export class AdminEnrolmentHistoryComponent implements OnInit { @Input() userHistory:UserHistory[]; types: SelectItem[]; academicTitles: SelectItem[]; academicStatuses: SelectItem[]; constructor() { this.types = []; this.types.push( { label: 'Uczestnik', value: 'Uczestnik' } ); this.types.push( { label: 'Referent', value: 'Referent' } ); this.types.push( { label: 'Organizator', value: 'Organizator' } ); this.academicTitles = []; this.academicTitles.push( { label: 'mgr', value: '1' } ); this.academicTitles.push( { label: 'dr', value: '2' } ); this.academicTitles.push( { label: 'dr hab.', value: '3' } ); this.academicTitles.push( { label: 'Profesor (stanowisko)', value: '4' } ); this.academicTitles.push( { label: 'Profesor (tytuล‚)', value: '5' } ); this.academicStatuses = []; this.academicStatuses.push( { label: 'Student/Doktorant', value: '1' } ); this.academicStatuses.push( { label: 'Pracownik naukowy', value: '2' } ); } ngOnInit() { } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from "@angular/router"; import { ScheduleService } from "app/services/schedule.service"; import { ConfirmationService } from "primeng/primeng"; import { EventService } from "app/services/event.service"; import { LocalDataSource } from "ng2-smart-table/ng2-smart-table"; import { Schedule } from "app/models/schedule"; import { Message } from "primeng/components/common/api"; @Component( { selector: 'admin-schedule', templateUrl: './admin-schedule.component.html', styleUrls: ['./admin-schedule.component.css'], providers: [ConfirmationService] } ) //todo nie dziala save export class AdminScheduleComponent implements OnInit { events: Event[]; source: LocalDataSource; schedule: Schedule; msgs: Message[] = []; constructor( private route: ActivatedRoute, private router: Router, private scheduleService: ScheduleService, private eventService: EventService, private confirmationService: ConfirmationService ) { } ngOnInit() { this.route.data.subscribe( ( data: { schedule: Schedule } ) => { if ( data.schedule ) { this.schedule = data.schedule; } else { //TODO Michal error and redirect } } ); this.source = new LocalDataSource(); this.eventService.getEvents(this.schedule.id).toPromise().then(( data ) => { this.source.load( data ); } ); } settings = { columns: { from_date: { title: 'Od' }, to_date: { title: 'Do' }, title: { title: 'Wydarzenie' }, description: { title: 'Opis' }, action: { title: 'Akcja', type: 'html', valuePrepareFunction: ( cell, row ) => { return '<a href="/event-schedule/' + row.id + '">Edytuj</a>' } } }, actions: false }; saveNew() { this.scheduleService.addSchedule( this.schedule ).subscribe( schedules => { // Emit list event // //navigate // EmitterService.get( this.listId ).emit( enrolments ); // Empty model this.navigateBack(); }, err => { // Log errors if any console.log( err ); } ); this.router.navigate( ['admin-schedules'] ); } save() { this.scheduleService.updateSchedule( this.schedule ).subscribe( articles => { // Emit list event // //navigate // EmitterService.get( this.listId ).emit( enrolments ); // Empty model this.navigateBack(); }, err => { // Log errors if any console.log( err ); } ); } cancel() { this.navigateBack(); } isNew() { return ( !this.schedule.id || 0 === this.schedule.id.length ); } confirmDelete() { this.confirmationService.confirm( { message: 'Do you want to delete this record?', header: 'Delete Confirmation', icon: 'fa fa-trash', accept: () => { this.msgs = [{ severity: 'info', summary: 'Confirmed', detail: 'Record deleted' }]; this.deleteSchedule(); }, reject: () => { this.msgs = [{ severity: 'info', summary: 'Rejected', detail: 'You have rejected' }]; } } ); } deleteSchedule() { this.scheduleService.deleteSchedule( this.schedule ).subscribe( articles => { // Emit list event // //navigate // EmitterService.get( this.listId ).emit( enrolments ); // Empty model this.navigateBack(); }, err => { // Log errors if any console.log( err ); } ); } createNew() { //todo nie dziala this.router.navigate(['/admin', {outlets: {adminRouting: ['admin-event-new']}}]) } navigateBack() { this.router.navigate(['/admin', {outlets: {adminRouting: ['admin-schedules']}}]) } } <file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { AdminLecturesComponent } from './admin-lectures.component'; describe('AdminLecturesComponent', () => { let component: AdminLecturesComponent; let fixture: ComponentFixture<AdminLecturesComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ AdminLecturesComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(AdminLecturesComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should be created', () => { expect(component).toBeTruthy(); }); }); <file_sep>export class Article { constructor( public id: string, public author: string, public title: string, public content: string, public headline: string, public status: string ) { } public fk_editor: string }<file_sep>import { Component, OnInit, OnDestroy, Input, HostBinding } from '@angular/core'; import { Direction, CarouselComponent } from "app/carousel/carousel.component"; @Component( { selector: 'slide', templateUrl: './slide.component.html', styleUrls: ['./slide.component.css'] } ) export class SlideComponent implements OnInit, OnDestroy { @Input() public index: number; @Input() public direction: Direction; @HostBinding( 'class.active' ) @Input() public active: boolean; @HostBinding( 'class.item' ) @HostBinding( 'class.carousel-item' ) private addClass: boolean = true; @Input() public description: string; constructor( private carousel: CarouselComponent ) { } public ngOnInit() { this.carousel.addSlide( this ); } public ngOnDestroy() { this.carousel.removeSlide( this ); } } <file_sep>export class User { constructor( public id: string, public name: string, public surname: string, public registerdate: Date, public email: string, public password: string, public university: string, public phone: string, public congressrole: string, public subjectdescription: string, public contactcomments: string, public confirmation: string, public privileges: string, public summary: string, public abstract: string, public paper_acceptation: string, public payment: string, public payment_accepted: string, public academic_title: string, public academic_status: string, public master: string, public engineer: string, public participation: string, public invoice: string, public invoice_data: string, public accommodation: string, public accommodation_from: Date, public accommodation_to: Date, public meal: string, public lactose_intolerance: string, public gluten_intolerance: string, public smooking_room: string ) { } public fk_editor: string }<file_sep>import { TestBed, inject } from '@angular/core/testing'; import { LectureResolver } from './lecture-resolver.service'; describe('LectureResolverService', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [LectureResolver] }); }); it('should be created', inject([LectureResolver], (service: LectureResolver) => { expect(service).toBeTruthy(); })); }); <file_sep>import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { Enrolment } from '../models/enrolment'; import { Observable } from 'rxjs/Rx'; //Import RxJs required methods import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import { Config } from "app/utils/config"; @Injectable() export class EnrolmentService { // Resolve HTTP using the constructor constructor( private http: Http ) { } // private instance variable to hold base url private enrolmentsUrl = Config.serverAddress + '/enrolments'; getEnrolments(): Observable<Enrolment[]> { // ...using get request return this.http.get( this.enrolmentsUrl ) // ...and calling .json() on the response to return data .map(( res: Response ) => res.json() ) //...errors if any .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); } // Add a new enrolment addEnrolment( body: Enrolment ): any { let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this.http.post(this.enrolmentsUrl, JSON.stringify(body), options); //...errors if any // // return this.http.post( this.enrolmentsUrl, body, options ) // ...using post request // .map(( res: Response ) => res.json() ) // ...and calling .json() on the response to return data // .catch(( error: any ) => Observable.throw( error || 'Server error' ) ); //...errors if any } // Update a enrolment updateEnrolment( body: Object ): Observable<Enrolment[]> { let bodyString = JSON.stringify( body ); // Stringify payload let headers = new Headers( { 'Content-Type': 'application/json' } ); // ... Set content type to JSON let options = new RequestOptions( { headers: headers } ); // Create a request option return this.http.put( `${this.enrolmentsUrl}/${body['id']}`, body, options ) // ...using put request .map(( res: Response ) => res.json() ) // ...and calling .json() on the response to return data .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); //...errors if any } // Delete a enrolment removeEnrolment( id: string ): Observable<Enrolment[]> { return this.http.delete( `${this.enrolmentsUrl}/${id}` ) // ...using put request .map(( res: Response ) => res.json() ) // ...and calling .json() on the response to return data .catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ) ); //...errors if any } } <file_sep>import { Component, OnInit } from '@angular/core'; import { SelectItem } from "primeng/primeng"; import { UniversityService } from "app/services/university.service"; import { University } from "app/models/university"; import { Enrolment } from "app/models/enrolment"; import { User } from "app/models/user"; import { UserService } from "app/services/user.service"; import { EmitterService } from "app/services/emitter.service"; import { AuthenticationService } from "app/services/authentication.service"; import { Router } from "@angular/router"; @Component( { selector: 'login-register', templateUrl: './login-register.component.html', styleUrls: ['./login-register.component.css'] } ) export class LoginRegisterComponent implements OnInit { loginTabVisible: boolean; speakerPartsVisible: boolean; incorrectLoginDataAlert: boolean; noLoginRightsAlert: boolean; emailRegisteredAlert: boolean; types: SelectItem[]; selectedType: string; universities: University[]; results: string[]; submitted = false; passwordType: string; user = new User( '', '', '', null, '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', null, null, '', '', '', '' ); repeatPassword: string; //TODO dodac walidacje termsAcceptation: boolean; loginForm; registerForm; //logowanie: loginEmail: string; password: string; selectedAcademicTitle: string; selectedAcademicStatus: string; selectedParticipation: string[] = []; academicTitles: SelectItem[]; academicStatuses: SelectItem[]; participationOptions: SelectItem[]; constructor( private userService: UserService, private universityService: UniversityService, private authenticationService: AuthenticationService, public router: Router ) { this.loginTabVisible = false; this.speakerPartsVisible = false; this.types = []; this.types.push( { label: 'Uczestnik', value: 'Uczestnik' } ); this.types.push( { label: 'Referent', value: 'Referent' } ); this.types.push( { label: 'Organizator', value: 'Organizator' } ); this.selectedType = 'Uczestnik'; this.passwordType = '<PASSWORD>' this.loginForm = []; this.loginForm.email = 'input full'; this.loginForm.password = '<PASSWORD>'; this.registerForm = []; this.registerForm.email = 'input full'; this.registerForm.password = '<PASSWORD>'; this.registerForm.repeatPassword = 'input string optional'; this.registerForm.username = 'input string optional'; this.registerForm.usersurname = 'input string optional'; this.registerForm.terms = 'simform__actions-sidetext'; this.registerForm.university = 'input string optional'; this.registerForm.academicStatus = 'input full'; this.registerForm.academicTitle = 'input full'; this.registerForm.participation = 'input full'; this.academicTitles = []; this.academicTitles.push( { label: 'mgr', value: '1' } ); this.academicTitles.push( { label: 'dr', value: '2' } ); this.academicTitles.push( { label: 'dr hab.', value: '3' } ); this.academicTitles.push( { label: 'Profesor (stanowisko)', value: '4' } ); this.academicTitles.push( { label: 'Profesor (tytuล‚)', value: '5' } ); this.academicStatuses = []; this.academicStatuses.push( { label: 'Student/Doktorant', value: '1' } ); this.academicStatuses.push( { label: 'Pracownik naukowy', value: '2' } ); this.participationOptions = []; this.participationOptions.push( { label: 'Konferencja', value: '1' } ); this.participationOptions.push( { label: 'Warsztaty', value: '2' } ); } ngOnInit() { if (this.isAdmin()) { this.loginTabVisible = false } else { this.loginTabVisible = true } } changeToLogin() { this.loginTabVisible = true; } changeToRegister() { this.loginTabVisible = false; } isAdmin() { let admintoken = localStorage.getItem( 'admintoken' ); return ( admintoken ); } isSpeakerPartsVisible() { return false; //return this.selectedType === 'Referent'; } //TODO koniecznie jakas odpowiedz serwera //automatyczny login??? registerUser() { this.emailRegisteredAlert = false; if ( this.validateRegisterForm() === true ) { this.user.registerdate = new Date(); this.user.congressrole = this.selectedType.charAt( 0 ) this.setAcademicTitle(); this.setAcademicStatus(); this.setParticipation(); this.userService.addUser( this.user ).subscribe( response => { if ( response.text() === 'OK' ) { - console.log( 'udalo sie haha ' + response.text() ); // this.submitted = true; this.router.navigate( ['enrolment-created'] ); } }, err => { // Log errors if any console.log( err ); if ( err.status === 401 ) { console.log( "401 Istnieje juz uzytkownik o podanym adresie email." ); this.emailRegisteredAlert = true; } } ); } } validateRegisterForm() { var result = true; if ( this.isEmpty( this.user.email ) ) { result = false; this.registerForm.email = 'input full validationError'; } else { if ( this.validateEmail( this.user.email ) === true ) { this.registerForm.email = 'input full'; } else { this.registerForm.email = 'input full validationError'; result = false; } } if ( this.isEmpty( this.user.password ) ) { result = false; this.registerForm.password = 'input string optional validationError'; } else { this.registerForm.password = 'input string optional'; } if ( this.isEmpty( this.repeatPassword ) ) { result = false; this.registerForm.repeatPassword = 'input string optional validationError'; } else { this.registerForm.repeatPassword = 'input string optional'; } if ( this.repeatPassword != this.user.password ) { result = false; this.registerForm.repeatPassword = 'input string optional validationError'; this.registerForm.password = 'input string optional validation<PASSWORD>'; } if ( this.isEmpty( this.user.name ) ) { result = false; this.registerForm.username = 'input string optional validationError'; } else { this.registerForm.username = 'input string optional'; } if ( this.isEmpty( this.user.surname ) ) { result = false; this.registerForm.usersurname = 'input string optional validationError'; } else { this.registerForm.usersurname = 'input string optional'; } if ( this.isEmpty( this.user.university ) ) { result = false; this.registerForm.university = 'input string optional validationError'; } else { this.registerForm.university = 'input string optional'; } if ( this.termsAcceptation != true ) { result = false; this.registerForm.terms = 'simform__actions-sidetext validationError'; } else { this.registerForm.terms = 'simform__actions-sidetext'; } if ( this.isEmpty( this.selectedAcademicStatus ) ) { result = false; this.registerForm.academicStatus = 'input full validationError'; } else { this.registerForm.academicStatus = 'input full'; if ( this.selectedAcademicStatus === '2' ) { if ( this.isEmpty( this.selectedAcademicTitle ) ) { result = false; this.registerForm.academicTitle = 'input full validationError'; } else { this.registerForm.academicTitle = 'input full'; } } } // if ( this.isEmpty( this.selectedParticipation ) ) { // result = false; // this.registerForm.participation = 'input full validationError'; // } else { // this.registerForm.participation = 'input full'; // } return result; } validateLoginForm() { var result = true; if ( this.isEmpty( this.loginEmail ) ) { result = false; this.loginForm.email = 'input full validationError'; } else { if ( this.validateEmail( this.loginEmail ) === true ) { this.loginForm.email = 'input full'; } else { this.loginForm.email = 'input full validationError'; result = false; } } if ( this.isEmpty( this.password ) ) { result = false; this.loginForm.password = '<PASSWORD>'; } else { this.loginForm.password = '<PASSWORD>'; } return result; } loadUniversities() { // Get all enrolments this.universityService.getUniversities( this.user.university ) .subscribe( universities => this.universities = universities, //Bind to view err => { // Log errors if any console.log( err ); } ); console.log( this.universities ); } search( event ) { // EmitterService.get( this.listId ).subscribe(( universities: University[] ) => { this.loadUniversities() } ); this.loadUniversities(); //todo dziala wolno, jakby co drugi znak if ( this.universities ) { this.results = this.universities.map( function( uni ) { return uni.name; } ) } ; } //TODO do porzadnej poprawy login() { this.incorrectLoginDataAlert = false; this.noLoginRightsAlert = false; if ( this.validateLoginForm() === true ) { this.authenticationService.login( this.loginEmail, this.password ).subscribe( u => { this.user = u; this.navigateUser( this.user.id ) } , //Bind to view err => { // Log errors if any console.log( "Error na poziomie authenticationService.getUser=" + err ); if ( err.status === 400 ) { console.log( "400 User not found" + err ); this.incorrectLoginDataAlert = true; } if ( err.status === 401 ) { console.log( "401 User not confirmed" + err ); this.noLoginRightsAlert = true; } } ); } } logout() { this.authenticationService.logout(); } showPassword() { this.passwordType = 'text' } hidePassword() { this.passwordType = '<PASSWORD>' } isPasswordVisible() { return 'text' === this.passwordType } isPasswordHidden() { return '<PASSWORD>' === this.passwordType } validateEmail( email ) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test( String( email ).toLowerCase() ); } isEmpty( str ) { return ( !str || 0 === str.length ); } incorrectLoginDataAlertVisible() { return this.incorrectLoginDataAlert; } noLoginRightsAlertVisible() { return this.noLoginRightsAlert; } emailRegisteredAlertVisible() { return this.emailRegisteredAlert; } navigateUser( id ) { this.router.navigate( ['user-profile/'] ); } showAcademicTitle() { return this.selectedAcademicStatus === '2' } showStudentOptions() { return this.selectedAcademicStatus === '1' } setAcademicTitle() { if ( this.selectedAcademicTitle === '1' ) { this.user.academic_title = '1' } if ( this.selectedAcademicTitle === '2' ) { this.user.academic_title = '2' } if ( this.selectedAcademicTitle === '3' ) { this.user.academic_title = '3' } if ( this.selectedAcademicTitle === '4' ) { this.user.academic_title = '4' } if ( this.selectedAcademicTitle === '5' ) { this.user.academic_title = '5' } } setAcademicStatus() { if ( this.selectedAcademicStatus === '1' ) { this.user.academic_status = '1' } if ( this.selectedAcademicStatus === '2' ) { this.user.academic_status = '2' } } setParticipation() { if (this.selectedParticipation ) { if ( this.selectedParticipation.length === 2 ) { this.user.participation = '3'; } else { if (this.selectedParticipation[0] === '1') { this.user.participation = '1'; } if (this.selectedParticipation[0] === '2') { this.user.participation = '2'; } } } } } <file_sep>export class UserInfo { constructor( public count: string ) { } }<file_sep>import { Component, OnInit } from '@angular/core'; import { ContactMessage } from "app/models/contact-message"; import { ContactService } from "app/services/contact.service"; import { Message } from "primeng/primeng"; import { SelectItem } from 'primeng/primeng'; import { UserService } from "app/services/user.service"; import { User } from "app/models/user"; interface Address { name: string, code: string } @Component( { selector: 'admin-mailbox', templateUrl: './admin-mailbox.component.html', styleUrls: ['./admin-mailbox.component.css'] } ) // css: https://www.sanwebe.com/2014/08/css-html-forms-designs/comment-page-1#comments export class AdminMailboxComponent implements OnInit { contactMessage = new ContactMessage( '', '', '', '', null ); msgs: Message[]; submitted = false; selectedAddresses: Address[]; users: User[]; addressees: SelectItem[]; showAllEnabled: boolean; showAcceptedEnabled: boolean; showNotAcceptedEnabled: boolean; showSpeakersEnabled: boolean; showPaymentPendingEnabled: boolean; showPaymentAcceptedEnabled: boolean; constructor( private contactService: ContactService, private userService: UserService ) { } ngOnInit() { this.showAll(); } submitMessage() { this.contactMessage.date = new Date(); this.contactMessage.email = '' this.contactMessage.email = this.contactMessage.email.replace( /\n/g, "<br />" ); for ( var i = 0; i < this.selectedAddresses.length; i++ ) { if ( this.isEmpty( this.contactMessage.email ) ) { this.contactMessage.email = this.selectedAddresses[i].code; } else { this.contactMessage.email = this.contactMessage.email + ', ' + this.selectedAddresses[i].code; } } console.log( 'Wysylam do ' + this.contactMessage.email ); this.contactService.sendAdminMessages( this.contactMessage ).subscribe( response => { this.msgs = []; this.msgs.push( { severity: 'success', summary: 'Email dostarczony.', detail: '' } ); this.submitted = true; }, err => { // Log errors if any this.msgs.push( { severity: 'error', summary: 'Nie udalo sie=' + err, detail: '' } ); console.log( err ); } ); } showAll() { this.userService.getUsers() .subscribe( allUsers => { this.users = allUsers; this.setItems(); }, err => { console.log( err ); } ); this.setItems(); this.resetButtons(); this.showAllEnabled = true; } showAcepted() { this.userService.getAcceptedUsers() .subscribe( acceptedUsers => { this.users = acceptedUsers; this.setItems(); }, err => { console.log( err ); } ); this.setItems(); this.resetButtons(); this.showAcceptedEnabled = true; } showNotAccepted() { this.userService.getPendingUsers() .subscribe( notAcceptedUsers => { this.users = notAcceptedUsers; this.setItems(); }, err => { console.log( err ); } ); this.setItems(); this.resetButtons(); this.showNotAcceptedEnabled = true; } showPaymentAccepted() { this.userService.getAcceptedPayment() .subscribe( acceptedPaymentUsers => { this.users = acceptedPaymentUsers; this.setItems(); }, err => { console.log( err ); } ); this.setItems(); this.resetButtons(); this.showPaymentAcceptedEnabled = true; } showPaymentPending() { this.userService.getPendingPayment() .subscribe( pendingPaymentUsers => { this.users = pendingPaymentUsers; this.setItems(); }, err => { console.log( err ); } ); this.setItems(); this.resetButtons(); this.showPaymentPendingEnabled = true; } showSpeakers() { this.userService.getSpeakers() .subscribe( speakers => { this.users = speakers; this.setItems(); }, err => { console.log( err ); } ); this.setItems(); this.resetButtons(); this.showSpeakersEnabled = true; } setItems() { this.addressees = []; this.selectedAddresses = []; if ( this.users ) { for ( var i = 0; i < this.users.length; i++ ) { let name = this.users[i].name + ' ' + this.users[i].surname; this.addressees.push( { label: name, value: { id: i + 1, name: name, code: this.users[i].email } } ); } } this.addressees.sort(); } isEmpty( str ) { return ( !str || 0 === str.length ); } resetButtons() { this.showAllEnabled = false; this.showAcceptedEnabled = false; this.showNotAcceptedEnabled = false; this.showSpeakersEnabled = false; this.showPaymentPendingEnabled = false; this.showPaymentAcceptedEnabled = false; } } <file_sep>import { Injectable, } from '@angular/core'; import { ActivatedRouteSnapshot, Resolve, Router, RouterStateSnapshot } from '@angular/router'; import { Observable } from 'rxjs/Rx'; import { ArticleService } from "app/services/article.service"; import { Article } from "app/models/article"; @Injectable() export class ArticleResolver implements Resolve<Article> { constructor( private articleService: ArticleService, private router: Router, ) {} resolve( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable<Article> { return this.articleService.getArticle(route.params['id']) .catch((err) => this.router.navigateByUrl('/')); } }<file_sep>import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Http, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http'; import { Router } from '@angular/router'; import { User } from 'app/models/user'; import { Config } from "app/utils/config"; @Injectable() export class AuthenticationService { token: string; constructor( private http: Http, public router: Router ) { this.token = localStorage.getItem( 'token' ); } private loginUrl = Config.serverAddress + '/login'; user: User; users: User[]; login( username: string, password: string ): Observable<User> { let body = JSON.stringify( { username, password } ); let headers = new Headers( { 'Content-Type': 'application/json' } ); let options = new RequestOptions( { headers: headers } ); return this.http.post( this.loginUrl, { username, password }, options ) .map(( res: Response ) => { let user = res.json(); console.log('Response=' + JSON.stringify(user)) if (user) { // zaloguj uzytkownika localStorage.setItem('userid', user.id) localStorage.setItem('username', user.name) console.log('Dobrze') if (user.privileges === 'A') { //zaloguj admina localStorage.setItem('admintoken', JSON.stringify(user)) console.log('Bardzo dobrze') } } else { console.log('Niedobrze') } return user; } ) // ...and calling .json() on the response to return data .catch(( error: any ) => Observable.throw( error || 'Server error' ) ); //...errors if any } //TODO Michal get jest potrzebny? logout() { /* * If we had a login api, we would have done something like this return this.http.get(this.config.serverUrl + '/auth/logout', { headers: new Headers({ 'x-security-token': this.token }) }) .map((res : any) => { this.token = undefined; localStorage.removeItem('token'); }); */ this.token = undefined; localStorage.removeItem( 'userid' ); localStorage.removeItem( 'username' ); localStorage.removeItem( 'admintoken' ); return Observable.of( true ); } } <file_sep>import { Component, OnInit, ElementRef } from '@angular/core'; import { ContactService } from "app/services/contact.service"; import { ContactMessage } from "app/models/contact-message"; import { Message } from "primeng/primeng"; @Component( { selector: 'contact', templateUrl: './contact.component.html', styleUrls: ['./contact.component.css'] } ) //todo dymek potwierdzajacy, message z pelnym html z textarea export class ContactComponent implements OnInit { contactMessage = new ContactMessage( '', '', '', '', null ); msgs: Message[]; submitted = false; constructor( private contactService: ContactService ) { } ngOnInit() { window.scrollTo(0, 0) } submitMessage() { this.contactMessage.message = 'Wiadomosc z formularza kontaktowego od ' + this.contactMessage.name + ' ' + this.contactMessage.email + '\n\n' + this.contactMessage.message this.contactMessage.date = new Date(); this.contactService.addMessage( this.contactMessage ).subscribe( res => { this.msgs = []; this.msgs.push( { severity: 'success', summary: 'Email dostarczony.', detail: '' } ); this.submitted = true; }, err => { // Log errors if any console.log( err ); } ); } }
13d84ef6fec78f38205545a4c24c7d1f75d0447b
[ "JavaScript", "TypeScript" ]
93
TypeScript
michail1988/MedievalPortal
44493c723c10e16e56d968d982ad179765086cd8
2292c7c8ddd8c17da41801666a8d2623070936f7
refs/heads/master
<repo_name>riexinsa/php-simple-web-api<file_sep>/src/AAuthentification.php <?php /* * (c) <NAME> <<EMAIL>> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PHPWebAPI; abstract class AAuthentification { // return values: // string => error description // array => (header entry as string => token as string) => ok token returned // instance is an instance of TableProcessor protected abstract function login($instance); // false on error // true on success // instance is an instance of TableProcessor protected abstract function checkToken($instance); } ?><file_sep>/src/ADataBase.php <?php /* * (c) <NAME> <<EMAIL>> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PHPWebAPI; abstract class ADataBase { protected abstract function sql($sql); protected abstract function lastID(); protected abstract function getConnection(); } <file_sep>/README.md # php-web-api A little framework to easily create a web api with PHP. <file_sep>/src/AVisitor.php <?php /* * (c) <NAME> <<EMAIL>> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PHPWebAPI; /* Abstract base class for a implementation of visiting all elements of an given collection */ abstract class AVisitor { /* Abstract method, this method will be invoked for any element in given collection. */ protected abstract function visit($instance, &$element, $context); /* Using this method the root elements of the given collection ($elements) will be visited by calling the above defined abtract method. remark: The elements and element parameter are passed by reference and therefore may be changed in the called methods! */ public function visitElements($instance, &$elements) { foreach($elements as &$element) $this->visit($instance, $element); } } ?><file_sep>/src/APIController.php <?php /* * (c) <NAME> <<EMAIL>> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PHPWebAPI; class APIController { private static $instance = null; // table for response request pairs private $requestTable = array(); // authentification class private $auth = null; private $noCheckFor = array(); // data base link private $db = null; // request if not PATH_INFO private $request = null; // base URL private $baseURI = ""; // the actual informations private $input = ""; private $headers = ""; private $pathElements = ""; private $table = ""; private $method = ""; // options requests private $fullfillAllOptionsRequests = false; public static function getInstance() { if(self::$instance == null) self::$instance = new APIController(); return self::$instance; } private function __construct() { } /******************************************************************************************************************* registration methods *******************************************************************************************************************/ // fct must return an array containing: // array( "http_response_code" => ..., "content" => ...) // if content is a string it will be handled as error and mangled into array("error" => content) before returning // otherwise it will be returned as it is. public function addRequestProcessing($table, $requestType, $fct, $requestpattern, $visitor = null) { if($visitor != null && !is_a($visitor, "PHPWebAPI\AVisitor")) throw new \Exception("Wrong type of visitor! AVisitor expected."); if($requestpattern != null) $rp = explode("/", trim($requestpattern, "/")); else $rp = array(); $this->requestTable[$table][$requestType] = array("fct" => $fct, "rp" => $rp, "vis" => $visitor); } public function setAuthentification($auth, $route = "login", $method = "POST") { if(is_a($auth, "PHPWebAPI\AAuthentification")) { $this->auth = $auth; array_push($this->noCheckFor, $route); $this->addRequestProcessing ( $route, $method, function($instance) use($auth) { $res = $auth->login($instance); if(is_string($res)) return $this->httpResponse(401, json_encode(array("error" => $res))); return $this->httpResponse(200, null, $res); }, "" ); } else throw new \Exception("Wrong type for authentification! AAuthentification expected."); } public function registerDataBaseHandler($db) { //print($db); if(is_a($db, "PHPWebAPI\ADataBase")) $this->db = $db; else { throw new \Exception("Wrong type of database! DataBase expected."); } } public function httpResponse($code, $content, $headers = array()) { return array("http_response_code" => $code, "content" => $content, "headers" => $headers); } public function fillPlaceHolders($where, $with = null) { if($with == null) $vars = $this->pathElements; else $vars = $with; $result = preg_replace_callback("/\{\{([a-z0-9_]+)((\[[0-9]+\])*)\}\}/i", function($matches) use ($vars) { $name = $matches[1]; $res = $vars[$name]; if($matches[2] != null) { preg_match_all("/(\[([0-9])+\])/", $matches[2], $m); for($i=0;$i<sizeof($m[2]);$i++) $res = $res[$m[2][$i]]; return $res; } else return $res; }, $where); return $result; } private function createSQLSetter() { $link = $this->db->getConnection(); $columns = preg_replace('/[^a-z0-9_]+/i','',array_keys($this->input)); $values = array_map(function ($value) use ($link) { if ($value===null) return null; return mysqli_real_escape_string($link,(string)$value); },array_values($this->input)); $set = ''; for ($i=0;$i<count($columns);$i++) { $set.=($i>0?',':'').'`'.$columns[$i].'`='; $set.=($values[$i]===null?'NULL':'"'.$values[$i].'"'); } return $set; } public function transformResults(&$results) { $visitor = $this->requestTable[$this->table][$this->method]["vis"]; if($visitor == null) return; $visitor->visitElements($this, $results); } private function executeRequest($request) { $subArray = $this->requestTable[$this->table]; $fct = $subArray[$this->method]["fct"]; $rp = $subArray[$this->method]["rp"]; // values from the path $this->pathElements = array(); foreach($rp as $val) $this->pathElements[$val] = array_shift($request); if(is_string($fct)) { $this->pathElements["set"] = $this->createSQLSetter($this->input); $sql = self::fillPlaceHolders($fct); $res = $this->db->sql($sql); $this->transformResults($res); return $this->httpResponse(200, json_encode($res)); } else { return $fct($this); } } /******************************************************************************************************************* setters and getters *******************************************************************************************************************/ public function getCurrentInput() { return $this->input; } public function getCurrentPathElements() { return $this->pathElements; } public function getCurrentHeaders() { return $this->headers; } public function getDataBase() { return $this->db; } public function getCurrentTable() { return $this->table; } public function getCurrentMethod() { return $this->method; } public function setBaseURI($baseURI) { $this->baseURI = $baseURI; } public function fullfillAllOptionsRequests($value) { $this->fullfillAllOptionsRequests = $value; } public function addUnCheckedEndPoint($name) { array_push($this->noCheckFor, $name); } /******************************************************************************************************************* login handlers *******************************************************************************************************************/ private function checkToken($headers) { if($this->auth == null) return true; return $this->auth->checkToken($headers); } public function setMethod($method) { $this->method = $method; } public function setRequest($request) { $this->request = $request; } /******************************************************************************************************************* run method to do it all ;) *******************************************************************************************************************/ public function run() { if($this->method == "") $this->method = $_SERVER["REQUEST_METHOD"]; if($this->fullfillAllOptionsRequests && $this->method == "OPTIONS") { http_response_code(200); return; } $pathInfo = ""; if($this->request != null) $pathInfo = trim($this->request, "/"); else $pathInfo = trim($_SERVER["PATH_INFO"], "/"); $request = explode("/", $pathInfo); $this->input = json_decode(file_get_contents('php://input'),true); $this->headers = getallheaders(); $this->table = preg_replace('/[^a-z0-9_]+/i','',array_shift($request)); if(!in_array($this->table, $this->noCheckFor)) { if(!$this->checkToken($this)) { http_response_code(403); echo json_encode(array("error" => "authorization failed")); return; } } if(!array_key_exists($this->table, $this->requestTable) || !(array_key_exists($this->method, $this->requestTable[$this->table]))) { http_response_code(404); echo json_encode(array("error" => "unknown route [$this->method] $this->table")); return; } $res = $this->executeRequest($request); foreach($res["headers"] as $key => $value) { header("$key: $value"); } if(!array_key_exists("Content-Type", $res["headers"])) header("Content-Type: application/json"); http_response_code($res["http_response_code"]); print $res["content"]; } } ?><file_sep>/src/LinkVisitor.php <?php /* * (c) <NAME> <<EMAIL>> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PHPWebAPI; use PHPWebAPI\AVisitor as AVisitor; class LinkVisitor extends AVisitor { private $links = array(); private $debug = false; private function __construct(){} public static function create() { return new LinkVisitor(); } private function write($string) { if($this->debug) { if(is_array($string)) print_r($string); else print($string); } } protected function addLink(&$to, $rel, $href, $method = "GET", $type = "application/json") { $toAdd = array(); $toAdd["rel"] = $rel; $toAdd["href"] = $href; $toAdd["method"] = $method; $toAdd["type"] = $type; array_push($to, $toAdd); } public function addLinkReference($transformPath, $rel, $href, $method = "GET", $type = "application/json", $dependency = null) { if(array_key_exists($transformPath, $this->links)) $toPushIn = $this->links[$transformPath]; else $toPushIn = array(); array_push($toPushIn, array( "rel" => $rel, "href" => $href, "method" => $method, "type" => $type, "dep" => $dependency )); $this->links[$transformPath] = $toPushIn; return $this; } private function visitElement($instance, $path, &$element, $links) { $this->write("******************************************* visitElement - path\n"); $this->write($path); $this->write("******************************************* visitElement - element\n"); $this->write($element); $this->write("******************************************* visitElement - first\n"); $first = array_shift($path); $this->write("$first\n"); if($first == "") { $this->write("go into element itself\n"); $this->visit($instance, $element, $links); } else { if($first == "*") { $this->write("exec for each \n"); foreach($element as &$ele) $this->visit($instance, $ele, $links); } else { $this->write("go deeper into element \n"); if(array_key_exists($first, $element)) $this->visitElement($instance, $path, $element[$first], $links); } } } public function visitElements($instance, &$elements) { $this->write("~~~~~~~~~~~~~~~~~~~~~~~~~~~ visitElements\n"); $this->write($elements); foreach($this->links as $path => $links_for_path) { $pathParts = explode("/", trim($path, "/")); $this->write($pathParts); $this->visitElement($instance, $pathParts, $elements, $links_for_path); } } public function visit($instance, &$element, $links_for_path) { $this->write("\n---------------before---------------------\n"); $this->write($element); $this->write("\n---------------before---------------------\n"); if(array_key_exists("_links", $element)) $links = $element["_links"]; else $links = array(); foreach($links_for_path as $link) { $add = true; $dep = $link["dep"]; if($dep != null) { if(is_string($dep)) { if(!array_key_exists($dep, $element) || $element[$dep] == null) $add = false; } else $add = $dep($element); } if($add) { $this->addLink( $links, $link["rel"], $instance->fillPlaceHolders($link["href"], $element), $link["method"], $link["type"]); } } if(is_array($element) && array_key_exists(0, $element)) $element = array("_embedded" => $element); if(sizeof($links) != 0) $element["_links"] = $links; $this->write("\n---------------after---------------------\n"); $this->write($element); $this->write("\n---------------after---------------------\n"); } } ?>
23f2af3fa8d63becdb9ce34dc57876b2848da871
[ "Markdown", "PHP" ]
6
PHP
riexinsa/php-simple-web-api
1957bb6ff72c3322177903c3af2fb4ca230800e4
c326c47979303dc3994cd8083e553998b31baa61
refs/heads/master
<repo_name>Oddert/stock-market-tracker<file_sep>/public/js/indexCopy.js var socket = io.connect(); var localData = []; $.getJSON("https://api.iextrading.com/1.0/stock/aapl/chart/1d", function (data) { localData = data; renderGraph(); setInterval(function () { console.log("============ RE RENDERING GRAPH ===============") renderGraph(); }, 15000) }); socket.on('message', message => console.log(message)); socket.on('tester', message => { // console.log("New massage from local host: ", message) var relativeDate = moment().tz('America/New_York').format(); relativeDate = relativeDate.slice(relativeDate.length-14, relativeDate.length-9); // console.log(relativeDate); var parsed = JSON.parse(message); if (parsed.symbol == 'AAPL') { var newEntry = { minute: relativeDate, close: parsed.lastSalePrice } console.log("ADDING: ", newEntry); localData.push(newEntry); } // localData.push(message); }); socket.on('add', (message) => { console.log('Subscribing to: ', message); }); function add() { console.log("Broadcasting: add, appl"); socket.emit('add', 'aapl'); } socket.on('disconnect', () => console.log('Disconnected.')); function dateString(minute) { return (new Date().toDateString()) + " " + minute + ":00" } function renderGraph() { d3.selectAll('h1').style('text-decoration', 'underline'); d3.selectAll('.root').selectAll('*').remove(); var canvasHeight = 500, canvasWidth = 960, graphHeight = 400, graphWidth = 800; var canvas = d3.selectAll('.root') .append('svg') .attr('width', canvasWidth) .attr('height', canvasHeight) .style('border', '1px solid black'); var graph = canvas.append('g') .attr('transform', 'translate(' + ((canvasWidth-graphWidth)/2) + ',' + ((canvasHeight-graphHeight)/1.5) + ')') .style('border', '1px solid red'); var minDateParse = new Date(moment.tz('America/New_York').format().slice(0,11) + '09:30:00'); var maxDateParse = new Date(moment.tz('America/New_York').format().slice(0,11) + '16:00:00'); var minStockParse = localData.reduce(function (acc, each) { return acc < each.close ? acc : each.close; }); var maxStockParse = localData.reduce(function (acc, each) { if (each.close === undefined || acc > each.close) { return acc; } else { return each.close; } }, 0); // console.log(typeof minDateParse, minDateParse); // console.log(minStockParse); // console.log(typeof maxDateParse, maxDateParse); // console.log(maxStockParse); //need new max min stock val - var timeScale = d3.scaleTime() .domain([minDateParse, maxDateParse]) .range([0, graphWidth]); var valueScale = d3.scaleLinear() .domain([minStockParse, maxStockParse]) .range([graphHeight, 0]); var prevClose = 0; var line = d3.line() .x(function (d) { // console.log(d.minute) var timeP = new Date(dateString(d.minute)); return timeScale(timeP) }) .y(function (d) { if (d.close) { prevClose = d.close; return valueScale(d.close) } else { return valueScale(prevClose) } }); graph.append('path') .datum(localData) .attr('class', 'line') .attr('d', line) .attr('transform', 'translate(' + 0 + ',' + 0 + ')') .style("stroke", "black") .style("stroke-width", "1px") .style("fill", "none"); var axisLeftConst = d3.axisLeft(valueScale) .ticks(10); var axisLeft = graph.append('g') .call(axisLeftConst) .attr('transform', 'translate(0, 0)'); var axisBottomConst = d3.axisBottom(timeScale) .ticks(10); var axisBottom = graph.append('g') .call(axisBottomConst) .attr('transform', 'translate(0,' + graphHeight + ')'); var crossHairHor = canvas.append('line') .attr('x1', 0) .attr('y1', 50) .attr('x2', canvasWidth) .attr('y2', 50) .style('stroke', 'red') .style('stroke-width', '1px'); var crossHairVer = canvas.append('line') .attr('x1', 50) .attr('y1', 0) .attr('x2', 50) .attr('y2', canvasHeight) .style('stroke', 'red') .style('stroke-width', '1px'); canvas.on('mouseover', function (d) { var xPos = d3.mouse(this)[0]; var yPos = d3.mouse(this)[1]; crossHairHor.attr('y1', yPos) .attr('y2', yPos) crossHairVer.attr('x1', xPos) .attr('x2', xPos) }) .on('mousemove', function (d) { var xPos = d3.mouse(this)[0]; var yPos = d3.mouse(this)[1]; crossHairHor.attr('y1', yPos) .attr('y2', yPos) crossHairVer.attr('x1', xPos) .attr('x2', xPos) }) //time scale should be fixed //stock amount needs calculated //time can be eg 4mins uptime, back data for 12 hours? //since day open? // x scale show form -6hrs, + 6hrs // y scale show from -10%, + 10% } // =========== LAST end point ========== var lastSample = { "symbol": "FB", "sector": "softwareservices", "securityType": "commonstock", "bidPrice": 184.8000, "bidSize": 200, "askPrice": 184.8500, "askSize": 100, "lastUpdated": 1526923279796, "lastSalePrice": 184.8600, "lastSaleSize": 100, "lastSaleTime": 1526923159070, "volume": 107154, "marketPercent": 0.01668, "seq": 21488 }; var lastMulti = [ {"symbol":"FB","sector":"softwareservices","securityType":"commonstock","bidPrice":180.2400,"bidSize":100,"askPrice":184.9000,"askSize":100,"lastUpdated":1526926267516,"lastSalePrice":184.8250,"lastSaleSize":700,"lastSaleTime":1526926204574,"volume":121847,"marketPercent":0.01734,"seq":25276}, {"symbol":"FB","sector":"softwareservices","securityType":"commonstock","bidPrice":180.2400,"bidSize":100,"askPrice":184.9100,"askSize":100,"lastUpdated":1526926267601,"lastSalePrice":184.8250,"lastSaleSize":700,"lastSaleTime":1526926204574,"volume":121847,"marketPercent":0.01734,"seq":25277}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7500,"bidSize":200,"askPrice":10.7600,"askSize":400,"lastUpdated":1526926264779,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273777,"volume":243505,"marketPercent":0.01516,"seq":11719}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7500,"bidSize":200,"askPrice":10.7600,"askSize":400,"lastUpdated":1526926264779,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273777,"volume":243605,"marketPercent":0.01517,"seq":11720}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":200,"askPrice":10.7600,"askSize":400,"lastUpdated":1526926273777,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273777,"volume":243605,"marketPercent":0.01517,"seq":11721}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":200,"askPrice":10.7600,"askSize":500,"lastUpdated":1526926273778,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273777,"volume":243605,"marketPercent":0.01517,"seq":11722}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":200,"askPrice":10.7600,"askSize":600,"lastUpdated":1526926273778,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273777,"volume":243605,"marketPercent":0.01516,"seq":11723}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":200,"askPrice":10.7600,"askSize":600,"lastUpdated":1526926273778,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273778,"volume":243705,"marketPercent":0.01516,"seq":11724}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":200,"askPrice":10.7500,"askSize":1000,"lastUpdated":1526926273778,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273778,"volume":243705,"marketPercent":0.01515,"seq":11725}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":100,"askPrice":10.7500,"askSize":1000,"lastUpdated":1526926273778,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273778,"volume":243705,"marketPercent":0.01515,"seq":11726}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":100,"askPrice":10.7600,"askSize":500,"lastUpdated":1526926273797,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273778,"volume":243705,"marketPercent":0.01514,"seq":11727}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":100,"askPrice":10.7600,"askSize":600,"lastUpdated":1526926273812,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273778,"volume":243705,"marketPercent":0.01514,"seq":11728}, {"symbol":"FB","sector":"softwareservices","securityType":"commonstock","bidPrice":180.2400,"bidSize":100,"askPrice":185.0000,"askSize":110,"lastUpdated":1526926273901,"lastSalePrice":184.8250,"lastSaleSize":700,"lastSaleTime":1526926204574,"volume":121847,"marketPercent":0.01734,"seq":25278}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":200,"askPrice":10.7600,"askSize":600,"lastUpdated":1526926273978,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273778,"volume":243705,"marketPercent":0.01514,"seq":11729}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":200,"askPrice":10.7600,"askSize":500,"lastUpdated":1526926274219,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273778,"volume":243705,"marketPercent":0.01514,"seq":11730}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":200,"askPrice":10.7600,"askSize":400,"lastUpdated":1526926274697,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273778,"volume":243705,"marketPercent":0.01514,"seq":11731}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":200,"askPrice":10.7600,"askSize":300,"lastUpdated":1526926274697,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273778,"volume":243705,"marketPercent":0.01514,"seq":11732}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":200,"askPrice":10.7600,"askSize":200,"lastUpdated":1526926274697,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273778,"volume":243705,"marketPercent":0.01514,"seq":11733}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":200,"askPrice":10.7500,"askSize":300,"lastUpdated":1526926274698,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273778,"volume":243705,"marketPercent":0.01514,"seq":11734}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":200,"askPrice":10.7500,"askSize":400,"lastUpdated":1526926274698,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273778,"volume":243705,"marketPercent":0.01514,"seq":11735}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":200,"askPrice":10.7500,"askSize":500,"lastUpdated":1526926274698,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273778,"volume":243705,"marketPercent":0.01514,"seq":11736}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":100,"askPrice":10.7500,"askSize":500,"lastUpdated":1526926276959,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273778,"volume":243705,"marketPercent":0.01514,"seq":11737}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7300,"bidSize":700,"askPrice":10.7500,"askSize":500,"lastUpdated":1526926278797,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273778,"volume":243705,"marketPercent":0.01514,"seq":11738}, {"symbol":"FB","sector":"softwareservices","securityType":"commonstock","bidPrice":184.8600,"bidSize":100,"askPrice":185.0000,"askSize":110,"lastUpdated":1526926279932,"lastSalePrice":184.8250,"lastSaleSize":700,"lastSaleTime":1526926204574,"volume":121847,"marketPercent":0.01734,"seq":25279}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7300,"bidSize":700,"askPrice":10.7500,"askSize":500,"lastUpdated":1526926278797,"lastSalePrice":10.7450,"lastSaleSize":100,"lastSaleTime":1526926280602,"volume":243805,"marketPercent":0.01515,"seq":11739}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7300,"bidSize":700,"askPrice":10.7500,"askSize":600,"lastUpdated":1526926280615,"lastSalePrice":10.7450,"lastSaleSize":100,"lastSaleTime":1526926280602,"volume":243805,"marketPercent":0.01514,"seq":11740}, {"symbol":"FB","sector":"softwareservices","securityType":"commonstock","bidPrice":180.2400,"bidSize":100,"askPrice":185.0000,"askSize":110,"lastUpdated":1526926287962,"lastSalePrice":184.8250,"lastSaleSize":700,"lastSaleTime":1526926204574,"volume":121847,"marketPercent":0.01733,"seq":25280}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7300,"bidSize":700,"askPrice":10.7500,"askSize":600,"lastUpdated":1526926280615,"lastSalePrice":10.7450,"lastSaleSize":100,"lastSaleTime":1526926288173,"volume":243905,"marketPercent":0.01515,"seq":11741}, {"symbol":"FB","sector":"softwareservices","securityType":"commonstock","bidPrice":180.2400,"bidSize":100,"askPrice":184.9000,"askSize":100,"lastUpdated":1526926288209,"lastSalePrice":184.8250,"lastSaleSize":700,"lastSaleTime":1526926204574,"volume":121847,"marketPercent":0.01733,"seq":25281}, {"symbol":"FB","sector":"softwareservices","securityType":"commonstock","bidPrice":180.2400,"bidSize":100,"askPrice":184.9100,"askSize":100,"lastUpdated":1526926288601,"lastSalePrice":184.8250,"lastSaleSize":700,"lastSaleTime":1526926204574,"volume":121847,"marketPercent":0.01733,"seq":25282} ]; <file_sep>/models/sublist.js var mongoose = require('mongoose'); var SublistSchema = new mongoose.Schema({ list: [ String ] }); module.exports = mongoose.model('StockMarketSublist', SublistSchema); <file_sep>/public/js/index.js var socket = io.connect(); var localData = {}; var sublist = []; var currentCode = '1d'; var allTimeCodes = ['1d', '1m', '3m', '6m', '1y', '2y', '5y']; // var upTime = 0; // setInterval(() => { // upTime ++; // $('.dispTimer').html(upTime); // }, 1000) function populateData(subCode) { console.log("Populating data...", subCode); var allDone = false; allTimeCodes.forEach(function (eachTime, index) { console.log("Populating ", eachTime); if (!localData.hasOwnProperty(subCode)) { console.log(subCode, " is not found, adding it now.."); localData[subCode] = {} } var url = "https://api.iextrading.com/1.0/stock/" + subCode + "/chart/" + eachTime; $.getJSON(url, function (jsonData) { console.log("JSON call for " + subCode + " at " + eachTime + " complete, data: ", jsonData); if (!localData[subCode].hasOwnProperty('data')) { localData[subCode].data = {} } localData[subCode].data[eachTime] = jsonData; if (eachTime == '1d') { localData[subCode].data['1d'].forEach(function (each, index) { each.date = moment.tz('America/New_York').format().slice(0,11) + each.minute; }); } console.log(localData); if (eachTime == allTimeCodes[allTimeCodes.length-1]) { console.log(eachTime, ' was the last time code, initialising render cycle...'); intiateRenderCycle(); allDone = true; } }) }) if (allDone === true) { console.log("APPARENTLY EVERYTHING IS FINISHED< THIS IS WHERE WE WOULD DO THE FIRST RENDER"); } else { console.log("........ more to go........."); } } // socket.on('message', message => console.log(message)); socket.on('tester', message => { // console.log("New massage from local host: ", message) var momentDate = moment().tz('America/New_York').format(); var relativeDate = momentDate.slice(0, momentDate.length-9); var nycDate = momentDate.slice(0, momentDate.length-6); var parsed = JSON.parse(message); var symbol = parsed.symbol.toLowerCase(); if (!localData.hasOwnProperty(symbol)) { console.log('localData does not have property: ' + symbol); localData[symbol] = {} } if (!localData[symbol].hasOwnProperty('live')) { console.log('localData[' + symbol + '] does not have live property, adding it now...'); localData[symbol].live = [] } // console.log(localData); parsed.date = relativeDate; parsed.close = parsed.lastSalePrice ? parsed.lastSalePrice : localData[symbol].live[localData[symbol].live.length-1].close; localData[symbol].live.push(parsed); console.log('ln70, newdata') }); function intiateRenderCycle() { clearInterval(renderTimer); console.log("==================================== INITIAL GRAPH RENDER ======================================="); renderGraph(); var renderTimer = setInterval(function () { console.log(new Date().toString(), "============ RE RENDERING GRAPH ===============") renderGraph(); }, 60000) } socket.on('sublist', message => { console.log('new sublist from server! ', message); console.log(message.split(',')); sublist = message.split(','); sublist.forEach(each => populateData(each)); setTimeout(function () { intiateRenderCycle(); }, 3000) }); socket.on('add', (message) => { console.log('Subscribing to: ', message); addSource(message); }); function internalAdd() { var newStock = $('#newStockForm').val(); $('#newStockForm').val(''); console.log("GOING TO ADD: ", newStock); addSource(newStock); socket.emit('add', newStock); } function addSource(code) { code = code.toLowerCase(); console.log('Adding source: ', code); if (localData.hasOwnProperty(code)) { console.log('Data already stored, removing it...'); localData[code] = {}; } if (!sublist.includes(code)) { sublist.push(code); } populateData(code); setTimeout(function () { renderGraph(); }, 2000) } socket.on('remove', data => { console.log('Instruction recieved; Remove: ', data); removeItem(data); }); function internalRemove (code) { removeItem(code); socket.emit('remove', code); } function removeItem(code) { var newSublist = sublist.filter(each => each != code); console.log('removed: ', code, ', sublist now: ', newSublist); sublist = newSublist; renderGraph(); } socket.on('disconnect', () => console.log('Disconnected.')); function testadd() { console.log('adding goog'); socket.emit('add', 'goog'); } function testCode(code) { currentCode = code; renderGraph(); } //min and max times are fixed //---------------------------- var colors = ['#F34F43', '#57B459', '#2F9DF4', '#FEC516', '#A235B6', '#119D92', '#826053', '#F0286C', '#6A8692', '#495CBB', '#FEED48', '#6E45BB', '#FE9F11', '#92C657', '#12AEF4', '#CFDE45', '#0AC1D7']; // Red Green Blue Amber Purple Teal Brown Pink Blue Gray Indego Yellow Deep Purple Orange Lime Green Light Blue Lime Cyan function renderGraph(timeScale) { timeScale = currentCode; // d3.selectAll('h1').style('text-decoration', 'line-through'); d3.selectAll('.root').selectAll('*').remove(); d3.selectAll('.removeButtons').selectAll('*').remove(); var canvasHeight = $(window).height() - 20, canvasWidth = $(window).width() - 20, graphHeight = 300, graphWidth = 800; var canvas = d3.select('.root') .append('svg') .attr('width', canvasWidth) .attr('height', canvasHeight) .style('border', '1px solid black'); var graph = canvas.append('g') .attr('width', graphWidth) .attr('height', 'graphHeight') .attr('transform', 'translate(' + ((canvasWidth-graphWidth)/2) + ',' + ((canvasHeight-graphHeight)/2) + ')') // object -> symbol -> data -> timecode -> [{},{},{}] // -> timecode -> [{},{},{}] // -> timecode -> [{},{},{}] // // -> live -> [{},{},{}] var rawMomentDate = moment().tz('America/New_York'); var momentDate = moment().tz('America/New_York').format(); // "2018-05-25T17:01:08-04:00" var nycDate = momentDate.slice(0, momentDate.length-6); // "2018-05-25T17:01:08" var minDate = new Date(moment.tz('America/New_York').format().slice(0,11) + '09:30:00'); function numToString(num) { num = num.toString(); if (num.length > 1) { return num } else { return '0' + num; } } var objMinDates = { '1d': new Date(moment.tz('America/New_York').format().slice(0,11) + '09:30:00'), '1m': moment().tz('America/New_York').subtract(1, 'month'), '3m': moment().tz('America/New_York').subtract(3, 'month'), '6m': moment().tz('America/New_York').subtract(6, 'month'), '1y': moment().tz('America/New_York').subtract(1, 'year'), '2y': moment().tz('America/New_York').subtract(2, 'year'), '5y': moment().tz('America/New_York').subtract(5, 'year') } minDate = objMinDates[timeScale]; var maxDate = new Date(moment.tz('America/New_York').format().slice(0,11) + '16:00:00'); var allMinClose = []; var allMaxClose = []; //get all min/max times sublist.forEach(function (symbol, index) { //say each = 'aapl' var concatData = localData[symbol].data[timeScale].concat(localData[symbol].live); var minClose = concatData.reduce(function (acc, each) { if (each && each.close) { return acc < each.close ? acc : each.close; } else { return acc } }); var maxClose = concatData.reduce(function (acc, each) { if (each && each.close) { return acc > each.close ? acc : each.close; } else { return acc; } }, 0); allMinClose.push(minClose); allMaxClose.push(maxClose); console.log(symbol); console.log(minClose, maxClose); }); var minClose = d3.min(allMinClose); var maxClose = d3.max(allMaxClose); console.log('Over all min and max stocks: '); console.log(minClose, maxClose); var dateScale = d3.scaleTime() .domain([minDate, maxDate]) .range([0, graphWidth]); var closeScale = d3.scaleLinear() .domain([minClose, maxClose]) .range([graphHeight, 0]); var axisLeftConst = d3.axisLeft(closeScale) .ticks(10); var axisBottomConst = d3.axisBottom(dateScale) .ticks(10); var axisLeft = graph.append('g') .call(axisLeftConst); var axisBottom = graph.append('g') .call(axisBottomConst) .attr('transform', 'translate(0,' + (graphHeight) + ')'); // sublist = ['aapl']; sublist.forEach(function (each, index) { var item = localData[each]; if (!item.live) {item.live = []} console.log('PRE CONCAT', item.data[timeScale], item.live) var concatData = item.data[timeScale].concat(item.live); console.log('POST CONCAT: ', concatData); var sampleItemSnap = { data: { '1d': [], '3y': [] }, live: [] } var pickColor = colors[index > colors.length ? Math.floor(Math.random()*17) : index]; console.log('COLOR PICKED: ', each, ' ', pickColor); var prevClose = minClose; var prevDate = minDate; var line = d3.line() .x(function (d) { if (d && d.date) { var timeCalc = new Date(d.date); prevDate = new Date(d.date); // console.log("DATE: ", d.date, " translates to: ", dateScale(new Date(d.date))) return dateScale(timeCalc); } else { // console.log("DATE: ", "defaulting onto: ", prevDate, dateScale(prevDate)); return dateScale(prevDate); } }) .y(function (d) { if (d && d.close) { prevClose = d.close; // console.log("STOCK: ", d.close, " translates to: ", closeScale(d.close)); return closeScale(d.close); } else { // console.log("STOCK: ", "defaulting onto: ", prevClose, closeScale(prevClose)); return closeScale(prevClose) } }); graph.append('path') .datum(concatData) .attr('class', 'line ' + each) .attr('d', line) .on('mouseover', function (d) { }) .on('mouseout', function (d) { // d3.select(this).style('stroke', null); }); var stockCard = d3.select('.removeButtons') .append('div') .attr('class', 'stockCard'); var stockText = stockCard.append('p') .text(each.toUpperCase() + ' '); var button = stockCard.append('button'); button.append('i').attr('class', 'fa fa-times') button.attr('class', 'removeButton') .attr('id', each) .attr('onClick', 'internalRemove("' + each + '")') stockCard.on('mouseover', function () { d3.select(this).style('background-color', pickColor); d3.select('.line.' + each).style('stroke', pickColor) .style('stroke-width', '1.5px'); }) .on('mouseout', function () { d3.select(this).style('background-color', null); d3.select('.line.' + each).style('stroke', null) .style('stroke-width', null); }) }); var crossHairHor = canvas.append('line') .attr('x1', 0) .attr('y1', 50) .attr('x2', canvasWidth) .attr('y2', 50) .style('stroke', 'red') .style('stroke-width', '1px'); var crossHairVer = canvas.append('line') .attr('x1', 50) .attr('y1', 0) .attr('x2', 50) .attr('y2', canvasHeight) .style('stroke', 'red') .style('stroke-width', '1px'); canvas.on('mouseover', function (d) { var xPos = d3.mouse(this)[0]; var yPos = d3.mouse(this)[1]; crossHairHor.attr('y1', yPos) .attr('y2', yPos) crossHairVer.attr('x1', xPos) .attr('x2', xPos) }) .on('mousemove', function (d) { // console.log('-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-=-='); var xPos = d3.mouse(this)[0]; var yPos = d3.mouse(this)[1]; crossHairHor.attr('y1', yPos) .attr('y2', yPos) crossHairVer.attr('x1', xPos) .attr('x2', xPos) // var xPos = d3.mouse(this)[0]; // var scaledPos = dateScale.invert(xPos).toTimeString(); // console.log('Scaled Position: ', typeof scaledPos, scaledPos); // var sampleData = localData['aapl'].data['1d']; // // var bisectDate = d3.bisector(function (d) { // var arrDate = new Date(d.date).toTimeString(); // console.log('Return: ', typeof arrDate, arrDate); // console.log(arrDate, scaledPos); // console.log(arrDate == scaledPos); // return arrDate; // }).right // // console.log('Bisect: ', typeof bisectDate(sampleData, scaledPos), bisectDate(sampleData, scaledPos, 1, 5) ); }) //time scale should be fixed //stock amount needs calculated //time can be eg 4mins uptime, back data for 12 hours? //since day open? // x scale show form -6hrs, + 6hrs // y scale show from -10%, + 10% } // =========== LAST end point ========== var lastSample = { "symbol": "FB", "sector": "softwareservices", "securityType": "commonstock", "bidPrice": 184.8000, "bidSize": 200, "askPrice": 184.8500, "askSize": 100, "lastUpdated": 1526923279796, "lastSalePrice": 184.8600, "lastSaleSize": 100, "lastSaleTime": 1526923159070, "volume": 107154, "marketPercent": 0.01668, "seq": 21488 }; var lastMulti = [ {"symbol":"FB","sector":"softwareservices","securityType":"commonstock","bidPrice":180.2400,"bidSize":100,"askPrice":184.9000,"askSize":100,"lastUpdated":1526926267516,"lastSalePrice":184.8250,"lastSaleSize":700,"lastSaleTime":1526926204574,"volume":121847,"marketPercent":0.01734,"seq":25276}, {"symbol":"FB","sector":"softwareservices","securityType":"commonstock","bidPrice":180.2400,"bidSize":100,"askPrice":184.9100,"askSize":100,"lastUpdated":1526926267601,"lastSalePrice":184.8250,"lastSaleSize":700,"lastSaleTime":1526926204574,"volume":121847,"marketPercent":0.01734,"seq":25277}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7500,"bidSize":200,"askPrice":10.7600,"askSize":400,"lastUpdated":1526926264779,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273777,"volume":243505,"marketPercent":0.01516,"seq":11719}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7500,"bidSize":200,"askPrice":10.7600,"askSize":400,"lastUpdated":1526926264779,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273777,"volume":243605,"marketPercent":0.01517,"seq":11720}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":200,"askPrice":10.7600,"askSize":400,"lastUpdated":1526926273777,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273777,"volume":243605,"marketPercent":0.01517,"seq":11721}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":200,"askPrice":10.7600,"askSize":500,"lastUpdated":1526926273778,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273777,"volume":243605,"marketPercent":0.01517,"seq":11722}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":200,"askPrice":10.7600,"askSize":600,"lastUpdated":1526926273778,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273777,"volume":243605,"marketPercent":0.01516,"seq":11723}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":200,"askPrice":10.7600,"askSize":600,"lastUpdated":1526926273778,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273778,"volume":243705,"marketPercent":0.01516,"seq":11724}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":200,"askPrice":10.7500,"askSize":1000,"lastUpdated":1526926273778,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273778,"volume":243705,"marketPercent":0.01515,"seq":11725}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":100,"askPrice":10.7500,"askSize":1000,"lastUpdated":1526926273778,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273778,"volume":243705,"marketPercent":0.01515,"seq":11726}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":100,"askPrice":10.7600,"askSize":500,"lastUpdated":1526926273797,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273778,"volume":243705,"marketPercent":0.01514,"seq":11727}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":100,"askPrice":10.7600,"askSize":600,"lastUpdated":1526926273812,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273778,"volume":243705,"marketPercent":0.01514,"seq":11728}, {"symbol":"FB","sector":"softwareservices","securityType":"commonstock","bidPrice":180.2400,"bidSize":100,"askPrice":185.0000,"askSize":110,"lastUpdated":1526926273901,"lastSalePrice":184.8250,"lastSaleSize":700,"lastSaleTime":1526926204574,"volume":121847,"marketPercent":0.01734,"seq":25278}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":200,"askPrice":10.7600,"askSize":600,"lastUpdated":1526926273978,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273778,"volume":243705,"marketPercent":0.01514,"seq":11729}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":200,"askPrice":10.7600,"askSize":500,"lastUpdated":1526926274219,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273778,"volume":243705,"marketPercent":0.01514,"seq":11730}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":200,"askPrice":10.7600,"askSize":400,"lastUpdated":1526926274697,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273778,"volume":243705,"marketPercent":0.01514,"seq":11731}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":200,"askPrice":10.7600,"askSize":300,"lastUpdated":1526926274697,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273778,"volume":243705,"marketPercent":0.01514,"seq":11732}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":200,"askPrice":10.7600,"askSize":200,"lastUpdated":1526926274697,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273778,"volume":243705,"marketPercent":0.01514,"seq":11733}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":200,"askPrice":10.7500,"askSize":300,"lastUpdated":1526926274698,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273778,"volume":243705,"marketPercent":0.01514,"seq":11734}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":200,"askPrice":10.7500,"askSize":400,"lastUpdated":1526926274698,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273778,"volume":243705,"marketPercent":0.01514,"seq":11735}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":200,"askPrice":10.7500,"askSize":500,"lastUpdated":1526926274698,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273778,"volume":243705,"marketPercent":0.01514,"seq":11736}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7400,"bidSize":100,"askPrice":10.7500,"askSize":500,"lastUpdated":1526926276959,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273778,"volume":243705,"marketPercent":0.01514,"seq":11737}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7300,"bidSize":700,"askPrice":10.7500,"askSize":500,"lastUpdated":1526926278797,"lastSalePrice":10.7500,"lastSaleSize":100,"lastSaleTime":1526926273778,"volume":243705,"marketPercent":0.01514,"seq":11738}, {"symbol":"FB","sector":"softwareservices","securityType":"commonstock","bidPrice":184.8600,"bidSize":100,"askPrice":185.0000,"askSize":110,"lastUpdated":1526926279932,"lastSalePrice":184.8250,"lastSaleSize":700,"lastSaleTime":1526926204574,"volume":121847,"marketPercent":0.01734,"seq":25279}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7300,"bidSize":700,"askPrice":10.7500,"askSize":500,"lastUpdated":1526926278797,"lastSalePrice":10.7450,"lastSaleSize":100,"lastSaleTime":1526926280602,"volume":243805,"marketPercent":0.01515,"seq":11739}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7300,"bidSize":700,"askPrice":10.7500,"askSize":600,"lastUpdated":1526926280615,"lastSalePrice":10.7450,"lastSaleSize":100,"lastSaleTime":1526926280602,"volume":243805,"marketPercent":0.01514,"seq":11740}, {"symbol":"FB","sector":"softwareservices","securityType":"commonstock","bidPrice":180.2400,"bidSize":100,"askPrice":185.0000,"askSize":110,"lastUpdated":1526926287962,"lastSalePrice":184.8250,"lastSaleSize":700,"lastSaleTime":1526926204574,"volume":121847,"marketPercent":0.01733,"seq":25280}, {"symbol":"SNAP","sector":"softwareservices","securityType":"commonstock","bidPrice":10.7300,"bidSize":700,"askPrice":10.7500,"askSize":600,"lastUpdated":1526926280615,"lastSalePrice":10.7450,"lastSaleSize":100,"lastSaleTime":1526926288173,"volume":243905,"marketPercent":0.01515,"seq":11741}, {"symbol":"FB","sector":"softwareservices","securityType":"commonstock","bidPrice":180.2400,"bidSize":100,"askPrice":184.9000,"askSize":100,"lastUpdated":1526926288209,"lastSalePrice":184.8250,"lastSaleSize":700,"lastSaleTime":1526926204574,"volume":121847,"marketPercent":0.01733,"seq":25281}, {"symbol":"FB","sector":"softwareservices","securityType":"commonstock","bidPrice":180.2400,"bidSize":100,"askPrice":184.9100,"askSize":100,"lastUpdated":1526926288601,"lastSalePrice":184.8250,"lastSaleSize":700,"lastSaleTime":1526926204574,"volume":121847,"marketPercent":0.01733,"seq":25282} ]; <file_sep>/app.js require('dotenv').config() var express = require('express'), app = express(), bodyParser = require('body-parser'), ejs = require('ejs'), socketServer = require('socket.io'), socketClient = require('socket.io-client'), moment = require('moment-timezone'), mongoose = require('mongoose'), cors = require('cors') var Sublist = require('./models/sublist'); app.use(cors()) app.set('view engine', 'ejs'); app.use(bodyParser.urlencoded({extended: true})); app.use(express.static(__dirname + '/public')); mongoose.connect(process.env.DATABASE); app.get('/', function (req, res) { res.render('index'); }); app.get('/copy', function (req, res) { res.render('indexCopy'); }); app.get('/example', function (req, res) { res.render('example'); }); app.get('/basic', function (req, res) { res.render('basicline'); }); const PORT = process.env.PORT || 3000 var server = app.listen(PORT, function () { console.log("Server initialised on port " + PORT); }); var socket = socketClient.connect('https://ws-api.iextrading.com/1.0/tops'); // socket.on('message', message => console.log({message})); socket.on('connect', () => { socket.emit('subscribe', 'fb,aapl'); // socket.emit('unsubscribe', 'agi+'); }); socket.on('disconnect', () => console.log('Disconnected.')); var localio = socketServer(server); var sublist = ['fb', 'aapl']; function getList() { console.log('Get list called'); Sublist.find({}, function (err, foundList) { if (err) { console.error(err); } else { if (foundList[0] && Array.isArray(foundList[0].list)) sublist = foundList[0].list; else sublist = [] console.log("Sublist updated to: ", sublist); } }); } getList(); function updateList() { Sublist.remove({}, function (err) { if (err) { console.error(err); } else { Sublist.create({list: sublist}, function (err, createdList) { console.log('(80) Sublist Updated'); console.log(createdList); }); } }); } //on server start -get list from db //on add, overwrite list on db //on remove overwrite list on db localio.sockets.on('connection', function (localsocket) { console.log("New Connection"); console.log('Broadcasting sublist: ', sublist); localsocket.emit('sublist', sublist.join()); socket.on('message', data => { // console.log("Data recieved from IEX, broadcasting to clients"); localsocket.broadcast.emit('tester', data); }); localsocket.on('add', data => { if (!sublist.includes(data)) { sublist.push(data) } socket.emit('subscribe', data); console.log("(104) Sublist changed to add item: ", sublist); console.log("(105) Broadcasting ", data); localsocket.broadcast.emit('add', data); updateList(); }); localsocket.on('remove', data => { sublist = sublist.filter(each => each != data); socket.emit('unsubscribe', data); console.log("(113) Sublist changed to remove item: ", sublist); console.log("(114) Removing item: ", data); localsocket.broadcast.emit('remove', data); updateList(); }) } ); <file_sep>/public/js/basicline.js $(document).ready(function () { d3.selectAll('h1').style('color', 'pink'); console.log('what') var canvasHeight = $(window).height() - 20, canvasWidth = $(window).width() - 20; var graphHeight = 300, graphWidth = 600; var canvas = d3.select('.root') .append('svg') .attr('width', canvasWidth) .attr('height', canvasHeight) .style('border', '1px solid black'); var graph = canvas.append('g') .attr('width', graphWidth) .attr('height', graphHeight) .attr('transform', 'translate(' + ((canvasWidth-graphWidth)/2) + ',' + ((canvasHeight-graphHeight)/2) + ')'); var data = [ {position: 1, value: 20}, {position: 6, value: 197}, {position: 4, value: 244}, {position: 5, value: 289}, {position: 8, value: 487}, {position: 3, value: 491}, {position: 7, value: 528}, {position: 2, value: 835}, {position: 9, value: 974} ] var newData = [ {position: 6, value: 83}, {position: 7, value: 135}, {position: 2, value: 246}, {position: 1, value: 445}, {position: 5, value: 450}, {position: 2, value: 580}, {position: 9, value: 699}, {position: 2, value: 782}, {position: 3, value: 923} ] var dataConcat = [ [ {position: 1, value: 20}, {position: 6, value: 197}, {position: 4, value: 244}, {position: 5, value: 289}, {position: 8, value: 487}, {position: 3, value: 491}, {position: 7, value: 528}, {position: 2, value: 835}, {position: 9, value: 974} ], [ {position: 6, value: 83}, {position: 7, value: 135}, {position: 2, value: 246}, {position: 1, value: 445}, {position: 5, value: 450}, {position: 2, value: 580}, {position: 9, value: 699}, {position: 2, value: 782}, {position: 3, value: 923} ] ] var posScale = d3.scaleLinear() .domain([1,9]) .range([graphHeight, 0]); var valScale = d3.scaleLinear() .domain([1,999]) .range([0, graphWidth]); var line = d3.line() .x(d => valScale(d.value)) .y(d => posScale(d.position)); //=============== render lines together =================== var colors = ["#c1392b", "#27ae61", "#297fb8", "#f39c11", "#8d44ad", "#16a086", "#d25400", "#bec3c7", "#e84c3d", "#2dcc70", "#3598db", "#f1c40f", "#9a59b5", "#1bbc9b", "#e67f22", "#95a5a5"]; dataConcat.forEach(function (each, index) { graph.append('path') .datum(each) .attr('class', 'line') .attr('d', line) .attr('transform', 'translate(' + 0 + ',' + 0 + ')') .style("stroke", d => colors[index]) .style("stroke-width", "1px") .style("fill", "none"); }) //=============== render lines individually ================ // var firstLine = graph.append('path') // .datum(data) // .attr('class', 'line') // .attr('d', line) // // .attr('transform', 'translate(' + 0 + ',' + 0 + ')') // .style("stroke", "black") // .style("stroke-width", "1px") // .style("fill", "none"); // // // var secondLine = graph.append('path') // .datum(newData) // .attr('class', 'line') // .attr('d', line) // // .attr('transform', 'translate(' + 0 + ',' + 0 + ')') // .style("stroke", "red") // .style("stroke-width", "1px") // .style("fill", "none"); var posAxisConst = d3.axisLeft(posScale) .ticks(10); var posAxis = graph.append('g') .call(posAxisConst); var valAxisConst = d3.axisBottom(valScale) .ticks(9); var valAxis = graph.append('g') .call(valAxisConst) .attr('transform', 'translate(0, ' + graphHeight + ')'); }); <file_sep>/README.md # Realtime Stock Market Tracker > NOTE: this project is currently broken oweing to an API update. A fix is currently being worked on. A data visualisation application to display historical and live stock data for subscribed (selected) stocks. Subscription data is shared in realtime with all other users. Node / express app using socket.io, built with MongoDB / Mongoose for data persistance Stock data provided by [IEX Trading](https://iextrading.com/) # Live Demo [https://crimson-bandana.glitch.me/](https://crimson-bandana.glitch.me/) # Installation ``` $ git clone https://github.com/Oddert/stock-market-tracker.git $ cd stock-market-tracker $ npm i ``` ### For development ``` $ npm run dev ``` ### For a production build ``` $ npm start ``` ## Scripts | script | command | action |--------|------------------------------------------------|------------------------------------------------| | start | node app.js | runs the server | | dev | nodemon app.js | runs the server with auto restart |
621ec9452faa49b4538a11686fa1219625c03257
[ "JavaScript", "Markdown" ]
6
JavaScript
Oddert/stock-market-tracker
fd0c433853300388e2f55a40a0a82406826522e1
fe89aea2b7641c2fc6aa3c4950868fde0ef14fe4
refs/heads/main
<file_sep><?php require "header.php";?> <section> <div class="container"> <div class="user singin-bx" id="singin"> <div class="img-bx"><img src="img/pexels-cottonbro-3585074.jpg" alt="Login"></div> <div class="form-bx"> <form action="login.php" method="post"> <h2>sign in</h2> <input type="email" placeholder="email" name="mail"> <input type="<PASSWORD>" placeholder="<PASSWORD>" name="<PASSWORD>"> <input type="submit" value="Login" name="send"> <p class="singup">don't have an account ? <a href="#singup" onclick="toggleFrom();">sing up.</a></p> </form> </div> </div> <div class="user singup-bx" id="singup"> <div class="form-bx"> <form action="register.php" method="post"> <h2>creat an account</h2> <input type="text" placeholder="<NAME>" name="name"> <input type="email" placeholder="Email" name="mail"> <input type="<PASSWORD>" placeholder="<PASSWORD>" name="<PASSWORD>"> <input type="submit" value="Sing Up" name="send"> <p class="singup">already have an account ? <a href="#singin" onclick="toggleFrom();">sign in.</a></p> </form> </div> <div class="img-bx"><img src="img/pexels-cottonbro-4629633.jpg" alt="Sing"></div> </div> </div> </section> <?php require "footer.php"; ?><file_sep><?php ob_start(); session_start(); $email = trim(filter_var($_POST['mail'],FILTER_SANITIZE_EMAIL)); $password = filter_var($_POST['password'],FILTER_SANITIZE_STRING); $email = htmlspecialchars($email); $password = htmlspecialchars($password); $send = $_POST['send']; if (isset($send)){ $data = file_get_contents('data.json'); $json = json_decode($data, true); foreach($json as $js ){ if($js['email'] == $email && $js['password'] == $password){ $_SESSION['email']= $email; header("location: welcome.php"); }else { echo "sorry this info is not correct'"; } } } <file_sep><?php session_start(); if(isset($_SESSION['email'])){ header("location: welcome.php"); } ?> <!DOCTYPE html> <html lang="en"> <head> <!-- !important Meta --> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- !Style Files CSS --> <link rel="icon" href="img/App data-bro.svg"> <link rel="stylesheet" href="css/master.css"> <!-- !Google Font --> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap" rel="stylesheet"> <title>Login & Sing Up</title> </head> <body><file_sep><?php $send = $_POST['send']; if (isset($send)){ $name = trim(filter_var($_POST['name'],FILTER_SANITIZE_STRING)); $password = filter_var($_POST['password'],FILTER_SANITIZE_STRING); $email = trim(filter_var($_POST['mail'],FILTER_SANITIZE_STRING)); $name = htmlspecialchars($name); $password = htmlspecialchars($password); $email = htmlspecialchars($email); $data = file_get_contents("data.json"); $json= json_decode($data, true); if (empty($json)){ $json_add = array( "name"=> $name, "email" => $email, "password" => $<PASSWORD>); $content = json_encode($json_add,JSON_PRETTY_PRINT); file_put_contents('data.json',"[$content]"); echo "success create account"; }else{ $json= json_decode($data, true); foreach ($json as $data) { if ( $email == $data['email']) { echo "sorry this account is used"; }else{ $json_add = array("name"=> $name,"email" => $email,"password" => $<PASSWORD>); array_push($json,$json_add); file_put_contents('data.json', json_encode($json,JSON_PRETTY_PRINT)); echo "success create Account"; } } } } <file_sep># login-system-with-json login system using json file with save your session
bcfc281fb6a5e50cca2e71e91432ecea9851912f
[ "Markdown", "PHP" ]
5
PHP
y0usefalsaadany/login-system-with-json
e70d969c4b92e1b0fc4eb60d7f6d9da6229dd2cb
0db9b4ba45f9900f63c2c79c7c095485bf58c9ee
refs/heads/master
<file_sep>export default function Http404(props) { return ( <h2>404</h2> ); }
31c38e42f152a1a7bb22867a52804d29ab404e65
[ "JavaScript" ]
1
JavaScript
caseydriscoll/react-dc-dot-com
d3c720b06a9f0d575f02e56c47ebb5b8f66cb338
1125ad40bb35d5f868dbb4ebac1a39a1d0d26f40
refs/heads/main
<file_sep>const express = require('express'); const app = express(); const { userTable, db } = require('./model/User'); const {adminTable} = require('./model/admin'); const {userController} = require('./controller/userController'); const{adminController}=require('./controller/adminController'); // app.get("/",(req, res)=>res.status(200).send("hey i m on")) app.use(express.json()) userController(app); adminController(app); // app.get("/", async function (req, res) { // const data = await userTable.findAll({}); // res.send(data); // }); app.listen(1698, console.log("Server is Running....."));<file_sep>const { adminTable } = require('../model/admin'); function adminController(app) { app.get("/admin", async function (req, res) { const data = await adminTable.findAll({}); res.send(data); }); app.post("/admin", async function (req, res) { const { body } = req; const { name, technology } = body; const add = await adminTable.create({ id: id, name, technology, }); res.send(add); }); app.put("/admin/:id", async function (req, res) { const { id } = req.params; const user = await adminTable.findOne({ id }); const { body } = req; const { name, technology } = body; user.name = name ? name : user.name; user.technology = technology ? technology : user.technology; await user.save(); res.status(200); }); } module.exports = { adminController, }<file_sep>const { json } = require('sequelize/types'); const { userTable, db } = require('../model/User'); const md5 = require('md5'); function userController(app) { app.get("/", async function (req, res) { const data = await userTable.findAll({}); res.status(200).send(data); }); app.post("/", async function (req, res) { const { body } = req; const { id, name, password, technology } = body; const add = userTable.create({ id: id, name, password, technology, }); // const {password: <PASSWORD>, ...userWithNoPass}=json.parse( // JSON.stringify(add) // ); res.send(add); }); app.delete("/:id", async function (req, res) { const { id } = req.params; const delval = await userTable.findOne({ id }); const deleted = await delval.destroy(); res.send({ deleted }); }) } module.exports = { userController, };<file_sep>const {Sequelize} = require('sequelize'); const db =new Sequelize({ dialect: "postgres", host: "localhost", port: 5432, username: "postgres", password: "<PASSWORD>", database: "samdb", }); const adminTable = db.define("admin",{ id:{ type:Sequelize.INTEGER, allowNull:false, primaryKey:true, }, name:{ type:Sequelize.STRING, allowNull:false, }, technology:{ type:Sequelize.STRING, allowNull:false, }, }, {logging:false, createdAt:false, updatedAt:false} ); db.authenticate().then(()=>console.log("database authenticate.....")); db.sync({alter:true}).then(()=>console.log("alter alos true.....")); module.exports={adminTable,}<file_sep>var express = require("express"); var app = express(); var db = require("./index.js"); const { sequelize }=require("./index.js"); app.use(express.json()); app.use(express.urlencoded()); app.get("/get",async function(_, response){ let dat=await sequelize.nodeDB.findAll({}); console.log(dat); response.status(201).send(dat); }); db.init().then().catch(); app.listen(3000,()=>console.log(`Server is Running...`)); // var userData =[ // {'name':"shivam", 'id':1}, // {'name':"prince", 'id':2}, // {'name':"ameer", 'id':3}, // {'name':"dev",'id':4} // ]; // app.get('/',(request, response)=>{ // response.status(200).send(userData); // // console.log(request); // }) // app.post('/data',(request, response)=> // { // userData.push(request.body); // response.status(201).send(userData); // }); // app.put('/put/:id',(request, response)=>{ // const user = books.find(c=> c.id === parseInt(req.params.id)); // user.name=request.body.name; // response.send(userData); // }); // app.delete('/del/:id',(request, response)=>{ // let id=request.params; // console.log(id); // let arr=userData.filter((_,index)=>id!=index); // console.log(arr); // }); // var a=["shivam","rai","GET"]; // app.use(bodyParser.json()); // app.get("/", (req, res) => { // res.status(200).send(a); // }); // app.post("/",(req,res)=>{ // // function s(res){ // // for(let v in res){ // // res[v]; // // } // // } // res.status(201).send(); // }); // app.listen(3000,()=>console.log("shivamrai")); // const bodyParser = require('body-parser'); // app.use(bodyParser.json()); // var XMLHttpRequest = require("XMLHttprequest").XMLHttpRequest; // var http = new XMLHttpRequest(); // // var http = new XMLHttpRequest(); // var url="https://reqres.in/api/unknown"; // http.open('GET',url); // http.send(); // http.onreadydtatechange=(e)=>{ // console.log(Http.responseText); // } // app.post('/dogs', function(req, res) { // var dog = req.body; // console.log(dog); // dogsArr.push(dog); // res.send("Dog added!"); // }); // app.listen(3000, () => { // console.log("Server running on port 3000"); // });
07667dc3ce8d727af17c564c828d5bb9e1b6da47
[ "JavaScript" ]
5
JavaScript
shivamrai83/node
8b4e1858dcdb4719bcc9c2c65f8f101e437f3f3d
06029703226ddabd96480ebe938ea1eb3397ea56
refs/heads/master
<file_sep>๊ณค์ถฉ์Œ์‹ ํ™๋ณด ํ”„๋กœ์ ํŠธ(์›น ๊ฐœ๋ฐœ) -------- _____ ###์„œ๋ก  **ํ–ฅ**ํ›„ 50๋…„ ์ด๋‚ด ์ธ๊ตฌ๋Š” ํญ๋ฐœ์ ์ธ ์ฆ๊ฐ€๋ฅผ ํ•  ๊ฒƒ์œผ๋กœ ์˜ˆ๊ฒฌ๋˜๊ณ  ์žˆ๋‹ค. ์ด์—๋”ฐ๋ผ ์‹๋Ÿ‰๋ถ€์กฑ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•ด ๋งŽ์€ ๋Œ€์•ˆ๋“ค์ด ์ œ์‹œ๋˜๊ณ ์žˆ๋‹ค. ๊ณผ๊ฑฐ ์ธ๊ตฌ์ฆ๊ฐ€๋Š” ๋…น์ƒ‰ํ˜๋ช…์œผ๋กœ ์ธํ•˜์—ฌ ๋ฌด์‚ฌํžˆ ๊ณ ๋น„๋ฅผ ๋„˜๊ฒผ์ง€๋งŒ, ๋†์ž‘์ธ๋“ค๊ณผ ๋†์ž‘์ง€๋Š” ๊ฐˆ์ˆ˜๋ก ๊ฐ์†Œํ•˜๊ณ ์žˆ๋‹ค. ๋˜ํ•œ, ์ค‘์‚ฐ์ธต์˜ ์ฆ๊ฐ€๋กœ ์‚ฌ์น˜์ž์›์˜ ์†Œ๋น„๋Š” ๊ณ„์† ๋Š˜์–ด๋‚˜๊ณ  ์žˆ๋‹ค. ๋ณธ ํ”„๋กœ์ ํŠธ์—์„œ๋Š” ์ œ 3์ฐจ ๋…น์ƒ‰ํ˜๋ช…์˜ ์ฃผ์ธ๊ณต์€ ๊ณค์ถฉ์ด ๋  ๊ฒƒ์œผ๋กœ ๋ณด๊ณ ์˜ˆ๊ฒฌํ•˜๊ณ , ์ด์— ๋”ฐ๋ฅธ ํ™๋ณด ์›น ์ œ์ž‘์„ ๋ชฉํ‘œ๋กœ ํ•˜๊ณ ์žˆ๋‹ค. ๊ณค์ถฉ์„ ์‹๋Ÿ‰์œผ๋กœ ์‚ฌ์šฉ ํ•˜๋Š”๋ฐ์—๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์ด์ ์ด ์žˆ๋‹ค. * ๋ฉ”ํƒ„๊ฐ€์Šค ๊ฐ์†Œ(์ถ•์‚ฐ๋ฌผ ์ƒ์‚ฐ ๊ฐ์†Œ์— ๋”ฐ๋ฅธ ๋ฉ”ํƒ„๊ฐ€์Šค ๊ฐ์†Œ) * ๋†์ž‘์ง€ ๊ฐ์†Œ(๊ณค์ถฉ์˜ ๊ตฐ์ง‘์„ ์ด๋ฃจ๋Š” ํŠน์„ฑ์œผ๋กœ ์ธํ•˜์—ฌ) * ์ƒˆ๋กœ์šด ๋ถ€๊ฐ€๊ฐ€์น˜ ์ฐฝ์ถœ ---------- ###๋ณธ๋ก  **๋‹ค**์Œ๊ณผ ๊ฐ™์€ ์ปจํ…์ธ ๋ฅผ ๊ฐ€์ง„๋‹ค. 1. edible insects DB ์ œ๊ณต 2. ์‚ฌ์šฉ์ž ์ฐธ์—ฌ ๊ฒŒ์‹œํŒ 3. ๊ณค์ถฉ ์Œ์‹ ๋ฐฐํ‹€ 4. ๋ง›์ง‘ ์†Œ๊ฐœ 5. ๋ ˆ๋ฒจ ์—… ๊ธฐ๋Šฅ **edible insects DB** ์ „ ์„ธ๊ณ„์˜ 1900์—ฌ์ข…์˜ ๋จน์„ ์ˆ˜ ์žˆ๋Š” ๊ณค์ถฉ์— ๋Œ€ํ•œ DB๋ฅผ ์ œ๊ณตํ•œ๋‹ค. ๊ณค์ถฉ ์„œ์‹์ง€, ๋จน์„์ˆ˜ ์žˆ๋Š” ๋ถ€์œ„๋“ฑ์˜ ์ •๋ณด๋ฅผ ์ œ๊ณตํ•œ๋‹ค. DB์ •๋ ฌ๊ธฐ๋Šฅ, Search ๊ธฐ๋Šฅ, Filtering ๊ธฐ๋Šฅ์œผ๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ์‰ฝ๊ฒŒ ์ฐพ์„ ์ˆ˜ ์žˆ๊ฒŒ ํ•จ. **์‚ฌ์šฉ์ž ์ฐธ์—ฌ ๊ฒŒ์‹œํŒ** ์‚ฌ์šฉ์ž์˜ ์ฐธ์—ฌ๋ฅผ ์œ ๋„ํ•˜๊ธฐ ์œ„ํ•œ ์ฐธ์—ฌ ๊ฒŒ์‹œํŒ์œผ๋กœ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๊ฒŒ์‹œํŒ๋“ค๋กœ ๊ตฌ์„ฑ๋˜ ์žˆ๋‹ค. 1. ๊ณค์ถฉ ์Œ์‹ ๋ ˆ์‹œํ”ผ 2. ๋ฏธ๋””์–ด ๊ฒŒ์‹œํŒ 3. ์ถ”์ฒœ ๊ฒŒ์‹œํŒ **๊ณค์ถฉ ์Œ์‹ ๋ ˆ์‹œํ”ผ** ๊ณค์ถฉ ์Œ์‹์˜ ๋ ˆ์‹œํ”ผ๋ฅผ ๊ณต์œ ํ•˜๋Š” ๊ฒŒ์‹œํŒ์ด๋‹ค. ์‚ฌ์šฉ์ž๋Š” ๋„์›€์ด ๋˜๋Š” ๊ฒŒ์‹œ๊ธ€์— ์ถ”์ฒœ์„ ํ•  ์ˆ˜ ์žˆ์œผ๋ฉฐ, ์ผ์ •์ˆ˜ ์ด์ƒ์˜ ์ถ”์ฒœ์„ ๋ฐ›์€ ๊ฒŒ์‹œ๊ธ€์€ ์ถ”์ฒœ ๊ฒŒ์‹œํŒ์œผ๋กœ ์˜ด๊ฒจ์ง„๋‹ค. **๋ฏธ๋””์–ด ๊ฒŒ์‹œํŒ** ๊ณค์ถฉ ์Œ์‹ ํ™๋ณด๋ฅผ ์œ„ํ•œ ๊ฐ์ข… ๊ฒŒ์‹œ๊ธ€์„ ์˜ฌ๋ฆฌ๋Š” ๊ณต๊ฐ„์ด๋‹ค. ํ•ด์™ธ ๋‰ด์Šค๋ฒˆ์—ญ, ํ™๋ณด ๋™์˜์ƒ๋“ฑ์„ ๊ณต์œ ํ•œ๋‹ค. ์ผ์ • ์ˆ˜ ์ด์ƒ์˜ ์ถ”์ฒœ์ˆ˜๋ฅผ ๋ฐ›์œผ๋ฉด ๊ฒŒ์‹œ๊ธ€์ด ์ถ”์ฒœ๊ฒŒ์‹œํŒ์œผ๋กœ ์ž๋™์œผ๋กœ ์˜ด๊ฒจ์ง„๋‹ค. **๊ณค์ถฉ ์Œ์‹ ๋ฐฐํ‹€** ์ € ๋งˆ๋‹ค์˜ ๊ณค์ถฉ ์Œ์‹์œผ๋กœ ์ฐธ๊ฐ€๋ฅผ ํ•˜์—ฌ ์„ธ๊ณ„ ์ผ๋ฏธ์˜ ๊ณค์ถฉ ์š”๋ฆฌ์™•์„ ์„ ๋ฐœํ•˜๋Š” ๊ณต๊ฐ„์ด๋‹ค. ํ† ๋„ˆ๋จผํŠธ ํ˜•์‹์ด๋ฉฐ, ์ฐธ๊ฐ€์ž๋“ค์€ ์‹ ์ฒญ์„ ํ•˜๊ณ  ๋‚œ ํ›„์— ์ฐธ๊ฐ€ ํ•  ์ˆ˜ ์žˆ๋‹ค. ์ถ”์ฒœ์ˆ˜๋กœ ๋Œ€ํšŒ์˜ ์Šน์ž๊ฐ€ ๊ฒฐ์ •๋‚œ๋‹ค. **๋ง›์ง‘ ์†Œ๊ฐœ** ๊ณค์ถฉ์— ๊ด€ํ•œ ๋ง›์ง‘์„ ์†Œ๊ฐœํ•ด์ค€๋Š” ์ปจํ…์ธ . **๋ ˆ๋ฒจ์—… ๊ธฐ๋Šฅ** ์‚ฌ์šฉ์ž์˜ ์ฐธ์—ฌ๋ฅผ ์œ ๋„ํ•˜๊ธฐ ์œ„ํ•œ ๋ ˆ๋ฒจ์—… ์ปจํ…์ธ . ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๊ฒฝ์šฐ์— ๊ฒฝํ—˜์น˜๋ฅผ ์–ป๋Š”๋‹ค. 1. ๋กœ๊ทธ์ธ ๊ฒฝํ—˜์น˜ 2. ๊ฒŒ์‹œํŒ ํ™œ๋™ ๊ฒฝํ—˜์น˜(๋ง๊ธ€, ์ถ”์ฒœ์ˆ˜, ๊ฒŒ์‹œ) ๋ ˆ๋ฒจ์—…์˜ ๋‹จ๊ณ„๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค. ์ดˆ๋ณด์ถฉ-> ์ค‘์ˆ˜์ถฉ->๊ณ ์ˆ˜์ถฉ->์ถฉ์™• ์ถฉ์™•์€ ๋ง›์ง‘์„ ์†Œ๊ฐœํ•  ์ˆ˜ ์žˆ๋Š” ๋ง‰๊ฐ•ํ•œ ๊ถŒ๋ ฅ์„ ๊ฐ€์งˆ ์ˆ˜ ์žˆ๊ณ , ๊ฐ ๋ ˆ๋ฒจ๋ณ„๋กœ ์•„์ด์ฝ˜์ด ๋‹ฌ๋ผ์ ธ ์‚ฌ์šฉ์ž์˜ ๋ ˆ๋ฒจ์—… ์š•๊ตฌ ์ž๊ทนํ•œ๋‹ค. ________________ ๊ฒฐ๋ก  ---- ๋ฏธ๋ž˜ ์‹๋Ÿ‰ ์ž์›์ธ ๊ณค์ถฉ์„ ํ™๋ณดํ•˜๋Š” ์›น ํŽ˜์ด์ง€๋ฅผ ์ œ์ž‘ํ•จ์œผ๋กœ์จ ๊ณค์ถฉ์Œ์‹์— ๋Œ€ํ•œ ์ธ์‹๋ณ€ํ™”๋ฅผ ๊ธฐ๋Œ€ํ•œ๋‹ค. ![enter image description here](http://club.koreadaily.com/pds_update/img_20120421200156.jpg) <file_sep>**๋ชฉ์ฐจ** 1. ๊ฐœ์š”------------------------------------------------------------------------------------------- p.2 1. ์š”์•ฝ---------------------------------------------------------------------------------- p.2 2. ํ•„์š”์„ฑ-------------------------------------------------------------------------------- p.2 3. ์ข…๋ž˜ ๊ธฐ์ˆ -----------------------------------------------------------------------------p.3 4. ๋ฌธ์ œ ํ•ด๊ฒฐ ์ˆ˜๋‹จ---------------------------------------------------------------------- p.3 5. ๊ธฐ๋Œ€ํšจ๊ณผ------------------------------------------------------------------------------p.3 2. ์š”๊ตฌ์‚ฌํ•ญ ์ •์˜---------------------------------------------------------------------------------p.3 1. ์‚ฌ์šฉ์ž ์š”๊ตฌ์‚ฌํ•ญ ์ •์˜--------------------------------------------------------------- p.3 2. ์‹œ์Šคํ…œ ์š”๊ตฌ์‚ฌํ•ญ ์ •์˜----------------------------------------------------------------p.3 3. ์‹œ์Šคํ…œ ์ƒ์„ธ ์„ค๊ณ„------------------------------------------------------------------------------p.4 1. ์‹œ์Šคํ…œ ๊ตฌ์กฐ---------------------------------------------------------------------------p.4 2. ๊ณค์ถฉ ์Œ์‹ DB-------------------------------------------------------------------------p.5 1. ๊ฐœ์š”----------------------------------------------------------------------p.5 2. ํ๋ฆ„๋„-------------------------------------------------------------------p.6 3. ์ธํ„ฐํŽ˜์ด์Šค--------------------------------------------------------------p.6 3. ๋ฏธ๋””์–ด ๊ฒŒ์‹œํŒ------------------------------------------------------------------------p.10 1. ๊ฐœ์š” ๋ฐ ํ๋ฆ„๋„---------------------------------------------------------p.10 2. ์ธํ„ฐํŽ˜์ด์Šค--------------------------------------------------------------p.11 4. ๋ง›์ง‘ ์†Œ๊ฐœ-----------------------------------------------------------------------------p.14 1. ๊ฐœ์š”---------------------------------------------------------------------p.14 2. ๊ฐ ๋ ˆ๋ฒจ ๋ณ„ ์š”๊ตฌ์‚ฌํ•ญ ๋ฐ ๊ธฐ๋Šฅ-----------------------------------------p.14 3. ๊ฒฝํ—˜์น˜ ํš๋“ ๊ฒฝ๋กœ------------------------------------------------------p.14 5. ์ฒœํ•˜์ œ์ผ ๊ณค์ถฉ ์Œ์‹ ๋Œ€ํšŒ-----------------------------------------------------------p.15 1. ๊ฐœ์š”---------------------------------------------------------------------p.15 2. ์ธํ„ฐํŽ˜์ด์Šค-------------------------------------------------------------p.15 4. ํ‰๊ฐ€ ๋ฐ ๊ณ„ํš---------------------------------------------------------------------------------p.18 1. ํ‰๊ฐ€ ๋„๊ตฌ ๋ฐ ๋ฒ”์œ„------------------------------------------------------------------p.18 2. ์„ค๋ฌธ ์กฐ์‚ฌ----------------------------------------------------------------------------p.18 3. Windows ์‹œ์Šคํ…œ ์„ฑ๋Šฅ ๋ชจ๋‹ˆํ„ฐ๋ง ๋„๊ตฌ---------------------------------------------p.18 4. Wave tool----------------------------------------------------------------------------p.21 5. ๊ธฐ๋Œ€ํšจ๊ณผ์˜ ํƒ€๋‹น์„ฑ ๋ฐ ํ•œ๊ณ„์ -------------------------------------------------------p.23 1. ๊ธฐ๋Œ€ํšจ๊ณผ์˜ ํƒ€๋‹น์„ฑ------------------------------------------------------p.23 2. ๊ธฐ๋Œ€ํšจ๊ณผ์˜ ํ•œ๊ณ„์ ------------------------------------------------------p.23 **๊ฐœ์š”** **1.1 ์š”์•ฝ** edible insects์— ๋Œ€ํ•œ ํ™๋ณด ์›น ์‚ฌ์ดํŠธ ๊ตฌ์ถ• ๊ณผ์ œ๋Š” ์ตœ์ข… ์‚ฌ์šฉ์ž์ธ ์š”๋ฆฌ ์ „๋ฌธ๊ฐ€๋“ค ๋ฐ ์ผ๋ฐ˜์ธ๋“ค์˜ ์ •๋ณด ๊ต๋ฅ˜์™€ ์ •๋ณด ์ทจ๋“์„ ์œ„ํ•œ ํ”Œ๋žซํผ์ด ๋˜๋Š” ์›น ํŽ˜์ด์ง€ ์ œ์ž‘. **1.2 ํ•„์š”์„ฑ** ![](media/image1.gif) 2050๋…„๊นŒ์ง€ ์„ธ๊ณ„ ์ธ๊ตฌ ์˜ˆ์ƒ์น˜๋Š” 90์–ต์ด๋‹ค. ์ด๋“ค์„ ๋ชจ๋‘ ๋จน์ด๊ธฐ ์œ„ํ•ด์„  ์‹๋Ÿ‰์ƒ์‚ฐ์ด ๊ณฑ์ ˆ๋กœ ๋Š˜์–ด์•ผ ํ•œ๋‹ค๋Š” ํ†ต๊ณ„๊ฐ€ ๋‚˜์˜จ๋‹ค. ์ง€๊ธˆ๋„ 10์–ต๋ช…์˜ ์‚ฌ๋žŒ๋“ค์ด ์‹๋Ÿ‰ ๋ถ€์กฑ ๋ฌธ์ œ๋กœ ๊ตถ์ฃผ๋ฆฌ๊ณ  ์žˆ๋Š” ์ƒํ™ฉ์ด๋‹ค. ์†Œ๊ณ ๊ธฐ 1kg์„ ์ƒ์‚ฐํ•˜๊ธฐ ์œ„ํ•ด ํ•„์š”ํ•œ ๊ณก๋ฌผ์˜ ์–‘์ด 10kg์ด๋‹ค. ๋ผ์ง€๊ณ ๊ธฐ 1kg์„ ์–ป๊ธฐ ์œ„ํ•ด์„  5kg์˜ ๊ณก๋ฌผ์ด ํ•„์š”ํ•˜๋‹ค. ๊ทธ๋Ÿฌ๋‚˜ ๊ณค์ถฉ ๊ณ ๊ธฐ๋ฅผ ์–ป๊ธฐ ์œ„ํ•ด์„  ๋‹จ์ง€ 1.7kg์˜ ๊ณก๋ฌผ์ด ํ•„์š”ํ•  ๋ฟ์ด๋‹ค. ์ด๊ฒƒ์ด ๋ฏธ๋ž˜ ์‹๋Ÿ‰ ์ž์›์œผ๋กœ์„œ ๊ณค์ถฉ์„ ๋จน์–ด์•ผ ํ•  ์ฃผ์š”ํ•œ ์ด์œ ์ด๋‹ค. ๊ฒŒ๋‹ค๊ฐ€ ์˜จ์‹คํšจ๊ณผ์˜ ์ฃผ๋ฒ”์ธ ์ „์„ธ๊ณ„ ๋ฉ”ํƒ„ ๋ฐฐ์ถœ๋Ÿ‰์˜ 37%๊ฐ€ ๊ฐ€์ถ•(domestic animals)์—์„œ ๋ฐœ์ƒํ•œ๋‹ค. ๋ฐ˜๋ฉด ๊ณค์ถฉ์˜ CO2 ๋ฐฐ์ถœ๋Ÿ‰์€ ๊ทนํžˆ ๋“œ๋ฌผ๋‹ค. ์†Œ๊ณ ๊ธฐ์—” 50%์˜ ๋‹จ๋ฐฑ์งˆ์ด ์žˆ์œผ๋ฉฐ ๊ทธ ์™ธ์˜ ์ง€๋ฐฉ์งˆ ๋“ฑ์œผ๋กœ ์ด๋ฃจ์–ด์ง„ ๊ณ ์ง€๋ฐฉ ์‹ํ’ˆ์ด๋‹ค. ๋ฐ˜๋ฉด ๊ณค์ถฉ ๊ณ ๊ธฐ๋Š” ๋‹จ๋ฐฑ์งˆ์ด ๋Œ€๋ถ€๋ถ„์ด๋‹ค. ๋”๋ถˆ์–ด ๋น„ํƒ€๋ฏผ, ์ฒ ๋ถ„, ์•„์—ฐ ๋“ฑ์ด ํ’๋ถ€ํ•˜๋‹ค. ์‚ฌ๋žŒ๋“ค์˜ ํŽธ๊ฒฌ๊ณผ๋Š” ๋‹ฌ๋ฆฌ ๊ณค์ถฉ์€ ์ธ์ฒด์— ์น˜๋ช…์ ์ธ ๋ณ‘์›๊ท ์„ ๊ฐ–๊ณ  ์žˆ์ง€ ์•Š์•„ ์†Œ, ๊ฐœ, ๋ผ์ง€๋ณด๋‹ค๋„ ๋œ ํ•ด๋กญ๋‹ค๊ณ  ํ•œ๋‹ค. ์ธ๊ฐ„์ด ์„ญ์ทจ ๊ฐ€๋Šฅํ•œ ๊ณค์ถฉ์˜ ์ข…๋ฅ˜๋Š” 1900์ข…์ด๋‹ค. ๊ทธ๋Ÿฌ๋‚˜ ๊ณค์ถฉ์„ ๋จน๋Š” ๋‚˜๋ผ๋Š” ์•„์‹œ์•„์™€ ์•„ํ”„๋ฆฌ์นด ์ง€์—ญ์— ๊ตญํ•œ๋˜์–ด ์žˆ์œผ๋ฉฐ ์ƒ๋Œ€์ ์œผ๋กœ ์œ ๋Ÿฝ๊ณผ ๋ฉ•์‹œ์ฝ”๋ฅผ ์ œ์™ธํ•œ ์•„๋ฉ”๋ฆฌ์นด ๋Œ€๋ฅ™, ์•„์‹œ์•„ ์ง€์—ญ ์ค‘ ํ•œ๊ตญ๊ณผ ๋Ÿฌ์‹œ์•„ ์ง€์—ญ์€ ์˜ˆ์™ธ์ ์œผ๋กœ ๊ณค์ถฉ ์†Œ๋น„๊ฐ€ ๋‚ฎ๋‹ค. ๊ณค์ถฉ์— ๋Œ€ํ•œ ๋ง‰์—ฐํ•œ ์ธ์‹ ์ด๋ฅผ ํ…Œ๋ฉด ๋ง›์ด ์—†์„ ๊ฒƒ์ด๋ผ๋Š” ์ธ์‹์ด ์ง€๋ฐฐ์ ์ด๊ธฐ ๋•Œ๋ฌธ์œผ๋กœ ๋ณด์ธ๋‹ค. ๊ทธ๋Ÿฌ๋‚˜ ๊ณค์ถฉ์ด ๋ง›์ด ์—†๋‹ค๋Š” ๊ฒƒ์€ ์‹ค์ œ๋กœ๋Š” ๋งž์ง€ ์•Š์œผ๋ฉฐ ๊ณค์ถฉ์— ๋Œ€ํ•œ ์š”๋ฆฌ๋ฒ•์กฐ์ฐจ๋„ ์—†๋‹ค๋Š” ๊ฒƒ์€ ์‚ฌ๋žŒ๋“ค์—๊ฒŒ ๊ณค์ถฉ์ด ์‹๋Ÿ‰์œผ๋กœ์„œ ๋ณด์ด๊ธฐ์— ๋”์šฑ ์–ด๋ ต๊ฒŒ ๋งŒ๋“ ๋‹ค. ์ฐจ์„ธ๋Œ€ ๋ฏธ๋ž˜ ์‹๋Ÿ‰์œผ๋กœ์จ ๊ณค์ถฉ์„ ํ™œ์šฉํ•˜๊ธฐ ์œ„ํ•œ ์š”๋ฆฌ๋ฒ•์„ ์š”๋ฆฌ ๊ด€๋ จ ์ „๋ฌธ๊ฐ€๋“ค์ด ๊ณค์ถฉ์ด๋ผ๋Š” ์ƒ‰๋‹ค๋ฅธ ์žฌ๋ฃŒ์— ๋Œ€ํ•œ ๊ด€์‹ฌ์„ ๊ฐ€์งˆ ์ˆ˜ ์žˆ๊ฒŒ ํ•  ํ•„์š”๊ฐ€ ์žˆ๋‹ค. ๊ตญ์™ธ์—์„  ์ด๋ฏธ ๊ณค์ถฉ์— ๋Œ€ํ•œ ์ •๋ณด๋ฅผ ์ œ๊ณตํ•˜๋ฉฐ ํ™๋ณด๋ฅผ ํ•˜๋Š” ์›น ์‚ฌ์ดํŠธ๊ฐ€ ์žˆ์ง€๋งŒ, ๊ตญ๋‚ด์—” ์ „๋ฌดํ•œ ์ƒํƒœ๋‹ค. **1.3 ์ข…๋ž˜๊ธฐ์ˆ ** ๊ตญ์™ธ์—์„œ๋Š” ๊ณค์ถฉ ์Œ์‹์ด ์ด๋ฏธ ์‹๋Ÿ‰ ๋Œ€์•ˆ์œผ๋กœ ๊ฐ๊ด‘์„ ๋ฐ›๊ณ  ์žˆ๊ณ  ํ˜„์žฌ ํ™œ๋ฐœํ•œ ์ •๋ณด๊ต๋ฅ˜๊ฐ€ ์ด๋ฃจ์–ด ์ง€๊ณ  ์žˆ๋‹ค. Girl meets bug([*https://edibug.wordpress.com/*](https://edibug.wordpress.com/))์—์„œ๋Š” ๋ธ”๋กœ๊ทธ ํ˜•์‹์˜ ์›น ํŽ˜์ด์ง€๋กœ ๊ฐœ์ธ์ด ๋งŒ๋“  ๊ณค์ถฉ ์š”๋ฆฌ๋‚˜ ๊ด€๋ จ ๊ธฐ์‚ฌ๋“ค์„ ํฌ์ŠคํŠธ ํ•œ๋‹ค. ์ƒ๊ธฐ ์›น ํŽ˜์ด์ง€์˜ ๋ฌธ์ œ์ ์€ ๋ธ”๋กœ๊ทธ ํ˜•์‹์˜ ์›น ํŽ˜์ด์ง€๋กœ ์ผ ๋ฐฉํ–ฅ ์ ์ธ ์ •๋ณด์ œ๊ณต๊ณผ ์‚ฌ์šฉ์ž ์ฐธ์—ฌ๋„๊ฐ€ ๋‚ฎ๋‹ค๋Š” ๊ฒƒ์ด๋‹ค. ๋”ฐ๋ผ์„œ ์ง„์ •ํ•œ ๊ณค์ถฉ ์ •๋ณด ๊ตํ™˜์˜ ํ”Œ๋žซํผ์œผ๋กœ ์‚ฌ์šฉ๋˜๊ธฐ์—” ๋งŽ์€ ๋ถ€์กฑํ•จ์ด ์žˆ์–ด ๋ณด์ธ๋‹ค. ๊ตญ์™ธ ๋น„์˜๋ฆฌ๋‹จ์ฒด์ธ fao([*http://www.fao.org/forestry/edibleinsects/en/*](http://www.fao.org/forestry/edibleinsects/en/))์—์„œ๋„ ๋จน์„ ์ˆ˜ ์žˆ๋Š” ๊ณค์ถฉ์— ๋Œ€ํ•œ ์ˆ˜์ค€ ๋†’์€ ์ •๋ณด๋ฅผ ์ œ๊ณตํ•˜๊ณ  ์žˆ๋‹ค. 1900์—ฌ์ข…์˜ ๋จน์„ ์ˆ˜ ์žˆ๋Š” ๊ณค์ถฉ DB์ œ๊ณต๊ณผ ๊ด€๋ จ ๊ธฐ์‚ฌ๋ฅผ ์ œ๊ณตํ•œ๋‹ค. ํ•˜์ง€๋งŒ ์ƒ๊ธฐ ์›น ํŽ˜์ด์ง€ fao ๋˜ํ•œ, ์ผ ๋ฐฉํ–ฅ ์ ์ธ ์ •๋ณด ์ œ๊ณต์œผ๋กœ ์‚ฌ์šฉ์ž์˜ ์ฐธ์—ฌ๋„๊ฐ€ ๋งค์šฐ ๋‚ฎ์€ ์‹ค์ •์ด๋‹ค. ๋ฌด์—‡๋ณด๋‹ค๋„, ์˜๋ฌธ ํŽ˜์ด์ง€๋กœ ํ•œ๊ตญ ์‚ฌ์šฉ์ž๋“ค์ด ์ด์šฉํ•˜๊ธฐ์—๋Š” ๋งค์šฐ ํž˜๋“ค ๊ฒƒ์œผ๋กœ ์ƒ๊ฐํ•œ๋‹ค. **1.4 ๋ฌธ์ œ ํ•ด๊ฒฐ ์ˆ˜๋‹จ** ์ƒ๊ธฐ์— ์ œ์‹œ๋œ ์ข…๋ž˜๊ธฐ์ˆ ์˜ ๋ฌธ์ œ์ ์„ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•ด ์‚ฌ์šฉ์ž๊ฐ€ ์ •๋ณด ์ œ๊ณต์ž๊ฐ€ ๋˜๋Š” ๊ณค์ถฉ ์š”๋ฆฌ ํ™๋ณด ๋ฐ ์ •๋ณด๊ต๋ฅ˜๋ฅผ ์œ„ํ•œ ํ”Œ๋žซํผ์ด ๋˜๋Š” ์›น ํŽ˜์ด์ง€๋ฅผ ์ œ๊ณตํ•œ๋‹ค. **1.5 ๊ธฐ๋Œ€ ํšจ๊ณผ** ๋ณธ ์‹œ์Šคํ…œ ๊ฒฐ๊ณผ๋กœ ์‚ฌ์šฉ์ž๋Š” ์ •๋ณด ์ด์šฉ์ž๊ฐ€ ๋˜๋Š” ๋™์‹œ์— ์ •๋ณด ์ œ๊ณต์ž๊ฐ€ ๋˜๊ณ  ๋งŽ์€ ์ปจํ…์ธ ๋ฅผ ์ œ๊ณตํ•˜์—ฌ ๋งŽ์€ ์‚ฌ์šฉ์ž๋“ค์„ ๋Œ์–ด ๋“ค์ผ ์ˆ˜ ์žˆ์„ ๊ฒƒ์œผ๋กœ ์˜ˆ์ƒ๋˜๋ฉฐ, ๊ณค์ถฉ ์Œ์‹์— ๋Œ€ํ•œ ์ •๋ณด๊ต๋ฅ˜์™€ ํ™๋ณด์— ๋งŽ์€ ํšจ๊ณผ๋ฅผ ์–ป์„ ์ˆ˜ ์žˆ์„ ๊ฒƒ์œผ๋กœ ์ƒ๊ฐํ•œ๋‹ค. **์š”๊ตฌ์‚ฌํ•ญ ์ •์˜** **2.1 ์‚ฌ์šฉ์ž ์š”๊ตฌ์‚ฌํ•ญ ์ •์˜** ๋ฒˆํ˜ธ ๋‚ด์šฉ ์ค‘์š”๋„ ------ ---------------------------------------------------------- -------- 1 ํ•œ๊ตญ์–ด๋กœ ์ œ๊ณต๋˜๋Š” ์›น ์‚ฌ์ดํŠธ์ด์–ด์•ผ ํ•œ๋‹ค. ์ƒ 2 ์‚ฌ์šฉ์ž์—๊ฒŒ ์›ํ•˜๋Š” ๊ฐ€์žฅ ์ตœ์‹  ์ •๋ณด๊ฐ€ ์‰ฝ๊ฒŒ ๋…ธ์ถœ๋˜์–ด์•ผ ํ•œ๋‹ค. ์ค‘ 3 ๊ณค์ถฉ ์Œ์‹๋“ค์˜ ๋‹ค์–‘ํ•œ ์ •๋ณด๊ฐ€ ์ œ๊ณต๋˜์–ด์•ผ ํ•œ๋‹ค. ์ค‘ 4 ๊ณค์ถฉ ์Œ์‹์˜ ๋‹ค์–‘ํ•œ ๋ง›์ง‘๋“ค์ด ์†Œ๊ฐœ ๋˜์–ด์•ผ ํ•œ๋‹ค. ์ƒ 5 ํ™œ๋ฐœํ•œ ํ™œ๋™์— ๋Œ€ํ•œ ๋ณด์ƒ์ด ์žˆ์–ด์•ผ ํ•œ๋‹ค. ์ƒ 6 ๋‹ค๋ฅธ ์‚ฌ์šฉ์ž๋“ค๊ณผ ํ™œ๋ฐœํ•œ ๊ต๋ฅ˜๊ฐ€ ์ด๋ฃจ์–ด ์ ธ์•ผ ํ•œ๋‹ค. ์ƒ 7 ๋จน์„ ์ˆ˜ ์žˆ๋Š” ๊ณค์ถฉ์— ๋Œ€ํ•œ DB๊ฐ€ ์ œ๊ณต๋˜์–ด์•ผ ํ•œ๋‹ค. ์ƒ **2.2 ์‹œ์Šคํ…œ ์š”๊ตฌ์‚ฌํ•ญ ์ •์˜** ๋ฒˆํ˜ธ ๋‚ด์šฉ ์ค‘์š”๋„ ------ ------------------------------------------------------------------------------------------------------------ -------- 1 ์›น ํŽ˜์ด์ง€๋Š” ํ•œ๊ตญ์–ด๋กœ ์ œ๊ณตํ•œ๋‹ค. ์ƒ 2 ์‚ฌ์šฉ์ž๊ฐ€ ์›ํ•˜๋Š” ์ตœ์‹  ์ •๋ณด๋ฅผ ์ œ๊ณตํ•  ์ˆ˜ ์žˆ๋„๋ก ์ถ”์ฒœ ์ˆ˜๊ฐ€ ๋†’์€ ๊ฒŒ์‹œ๋ฌผ์€ ์ถ”์ฒœ ๊ฒŒ์‹œํŒ์œผ๋กœ ์ด๋™์‹œ์ผœ ์žฌ ๊ฐœ์‹œํ•œ๋‹ค. ์ค‘ 3 ๊ณค์ถฉ์Œ์‹๋“ค์˜ ๋‹ค์–‘ํ•œ ์ •๋ณด๊ฐ€ ์ œ๊ณต๋  ์ˆ˜ ์žˆ๋„๋ก ๊ด€๋ จ ๋‰ด์Šค๋“ค์„ ๋ฒˆ์—ญํ•œ ๊ฒŒ์‹œํŒ์„ ์ œ๊ณตํ•œ๋‹ค. ์ค‘ 4 ๊ณค์ถฉ ์Œ์‹์˜ ๋‹ค์–‘ํ•œ ๋ง›์ง‘๋“ค์ด ์†Œ๊ฐœ๋  ์ˆ˜ ์žˆ๋„๋ก ๋ง›์ง‘ ์†Œ๊ฐœ ๊ฒŒ์‹œํŒ์„ ์ œ๊ณตํ•œ๋‹ค. ์ƒ 5 ํ™œ๋ฐœํ•œ ํ™œ๋™์— ๋Œ€ํ•œ ๋ณด์ƒ์œผ๋กœ ๋ ˆ๋ฒจ ์ฒด๊ณ„๋ฅผ ์ œ๊ณตํ•œ๋‹ค. ์ƒ 6 ๋‹ค๋ฅธ ์‚ฌ์šฉ์ž๋“ค๊ณผ ํ™œ๋ฐœํ•œ ๊ต๋ฅ˜๋ฅผ ์œ„ํ•˜์—ฌ ๊ณค์ถฉ ์š”๋ฆฌ ๋Œ€ํšŒ๋ฅผ ๊ฐœ์ตœํ•œ๋‹ค. ์ƒ 7 ๋‹ค๋ฅธ ์‚ฌ์šฉ์ž๋“ค๊ณผ ํ™œ๋ฐœํ•œ ๊ต๋ฅ˜๋ฅผ ์œ„ํ•˜์—ฌ ๊ฒŒ์‹œ๊ธ€์— ๋ง๊ธ€์„ ๋‹ฌ ์ˆ˜ ์žˆ๊ฒŒ ํ•œ๋‹ค. ์ƒ 8. ๋จน์„ ์ˆ˜ ์žˆ๋Š” ๊ณค์ถฉ์˜ DB๋ฅผ ์ œ๊ณตํ•˜๋Š” ํŽ˜์ด์ง€๋ฅผ ์ œ์ž‘ํ•œ๋‹ค. ์ƒ **์‹œ์Šคํ…œ ์ƒ์„ธ ์„ค๊ณ„** **3.1์‹œ์Šคํ…œ ๊ตฌ์กฐ** Figure 1์‹œ์Šคํ…œ ๊ตฌ์กฐ๋„ ๊ณค์ถฉ ์Œ์‹ ํ™๋ณด๋ฅผ ๋ฐ ์ •๋ณด๊ต๋ฅ˜๋ฅผ ์œ„ํ•œ ํ”Œ๋žซํผ์„ ์ œ๊ณตํ•˜๋Š” ์›น ํŽ˜์ด์ง€๋Š” ์ด 5๊ฐœ์˜ ๋ชจ๋“ˆ๋กœ ๊ตฌ์„ฑ๋˜์–ด ์žˆ์œผ๋ฉฐ ๊ฐ๊ฐ์˜ ๋ชจ๋“ˆ์€ ์„œ๋กœ ๋‹ค๋ฅธ ์ปจํŠธ๋กค๋Ÿฌ์˜ ์ œ์–ด๋ฅผ ๋ฐ›๋Š”๋‹ค. ๊ณค์ถฉ ์Œ์‹ ๋ฐฐํ‹€ ๋ชจ๋“ˆ์€ ์‚ฌ์šฉ์ž๋“ค์ด ์„œ๋กœ์˜ ๊ณค์ถฉ ๋ ˆ์‹œํ”ผ๋ฅผ ๊ฒŒ์‹œํ•˜์—ฌ ์ถ”์ฒœ ์ˆ˜๋กœ ๋Œ€๊ฒฐ์„ ํ•˜๋Š” ์ผ์ข…์˜ ๊ฒŒ์‹œํŒ์ด๋‹ค. ๊ณค์ถฉ ์Œ์‹ ๋ชจ๋“ˆ์€ 1900์—ฌ๊ฐœ์˜ ๋จน์„ ์ˆ˜ ์žˆ๋Š” ๊ณค์ถฉ์— ๋Œ€ํ•œ ๋ฐ์ดํ„ฐ๋ฅผ ์ œ๊ณตํ•œ๋‹ค. ๋ฏธ๋””์–ด ๊ฒŒ์‹œํŒ์€ ์‚ฌ์šฉ์ž๋“ค์ด ๊ด€๋ จ ๋‰ด์Šค์™€ ๋™์˜์ƒ ๋“ฑ์„ ๊ฒŒ์‹œํ•˜๋ฉฐ ์ •๋ณด๋ฅผ ๊ต๋ฅ˜ํ•˜๋Š” ๋ชจ๋“ˆ์ด๋‹ค. ๋ง›์ง‘ ์†Œ๊ฐœ ๋ชจ๋“ˆ์€ ๊ณค์ถฉ ์Œ์‹์˜ ๋ง›์ง‘์„ ์†Œ๊ฐœํ•˜๋Š” ํŽ˜์ด์ง€์ด๋‹ค. ์„œ๋ฒ„ ๋ชจ๋“ˆ์€ ์‚ฌ์šฉ์ž๋“ค์˜ ๋ ˆ๋ฒจ ๋“ฑ๊ณผ ๊ฐ™์€ ์‚ฌ์šฉ์ž์˜ ์ •๋ณด๋ฅผ ๊ด€๋ฆฌํ•˜๋Š” ๋ชจ๋“ˆ๊ณผ ๊ฒŒ์‹œํŒ์˜ ๊ธ€ ์ •๋ณด ๋“ฑ์˜ ๋ฐ์ดํ„ฐ๋ฅผ ๊ด€๋ฆฌํ•˜๋Š” ๊ฒŒ์‹œํŒ ๋ฐ์ดํ„ฐ ๊ด€๋ฆฌ ๋ชจ๋“ˆ๋กœ ๊ตฌ์„ฑ๋œ ๋ชจ๋“ˆ์ด๋‹ค. **3.2 ๊ณค์ถฉ DB** ๊ณค์ถฉ DB๋Š” 1900๊ฐœ์˜ ๋จน์„ ์ˆ˜ ์žˆ๋Š” ๊ณค์ถฉ๋“ค์— ๋Œ€ํ•œ ๋ฐ์ดํ„ฐ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ œ๊ณตํ•˜๋Š” ๋ชจ๋“ˆ์ด๋‹ค. ๊ณค์ถฉ ์ข…๋ฅ˜๋ณ„ ์ด๋ฆ„ ๋ณ„, ์„œ์‹ ์ง€์—ญ ๋ณ„๋กœ ํ•„ํ„ฐ ๋ง ํ•˜๊ณ  ๊ฒ€์ƒ‰ํ•˜๋Š” ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•˜๊ณ  ํด๋ฆญํ•˜๋ฉด ์ƒ์„ธ ์ •๋ณด๋ฅผ ์—ด๋žŒ ํ•  ์ˆ˜ ์žˆ๋‹ค. ์ƒ์„ธ ์ •๋ณด์—๋Š” ๊ณค์ถฉ์˜ ์ข…, ์†, ๊ณผ, ์„œ์‹ ์ง€์—ญ, ์ด๋ฆ„, description, ๋น„๊ณ , ์ƒ ๊ทธ๋ฆฌ๊ณ  ์ด๋ฏธ์ง€ ๋“ฑ์˜ ์ •๋ณด๋ฅผ ์ œ๊ณตํ•œ๋‹ค. ๋ ˆ์‹œํ”ผ๊ฐ€ ์กด์žฌํ•˜๋Š” ๊ณค์ถฉ์ด๋ผ๋ฉด ๋งํฌ ์ฃผ์†Œ๋ฅผ ํ•˜์ด๋ผ์ดํŠธ ํ•˜์—ฌ ๋” ๋งŽ์€ ์กฐํšŒ์ˆ˜๋ฅผ ์˜ฌ์˜ฌ ์ˆ˜ ์žˆ๋Š” ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•œ๋‹ค. **3.2.1 ๊ฐœ์š”** ๊ณค์ถฉ DB์˜ ๋ชจ๋“ˆ์€ ์•„๋ž˜์™€ ๊ฐ™์€ ๊ตฌ์กฐ๋ฅผ ๊ฐ€์ง„๋‹ค. **Figure 2๊ณค์ถฉ DB ๊ตฌ์กฐ** ------------------------ -------------------------------------------------------------- ------ ๊ธฐ๋Šฅ ๊ธฐ๋Šฅ ๋‚ด์šฉ ๋น„๊ณ  SQL ์„œ๋ฒ„ 1900์—ฌ์ข…์˜ ๊ณค์ถฉ์— ๋Œ€ํ•œ ์ •๋ณด๋ฅผ ์ €์žฅํ•˜๊ณ  ์žˆ๋Š” DB ์„œ๋ฒ„ SQL-&gt;Json converter ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ํŒŒ์ผ์„ Json ํŒŒ์ผ๋กœ ์ปจ๋ฒ„ํŒ… ํ•ด์ฃผ๋Š” ๊ธฐ๋Šฅ ๊ณค์ถฉ ํ•„ํ„ฐ๋ง, ๊ฒ€์ƒ‰ ๊ณค์ถฉ์„ ๊ฐ ๋ถ€๋ถ„๋ณ„๋กœ ํ•„ํ„ฐ๋ง, ์ด๋ฆ„์ด๋‚˜ ์„œ์‹์ง€๋ณ„๋กœ ๊ฒ€์ƒ‰ํ•˜๋Š” ๊ธฐ๋Šฅ ๊ณค์ถฉ ๋ฆฌ์ŠคํŠธ ๊ณค์ถฉ ์ •๋ณด์— ๋Œ€ํ•œ ์š”์•ฝ์„ ๋ฆฌ์ŠคํŠธ๋กœ ์ œ๊ณต ๊ณค์ถฉ ์ƒ์„ธ ๋””์Šคํฌ๋ฆฝ์…˜ ๊ณค์ถฉ์— ๋Œ€ํ•œ ์ƒ์„ธ ์ •๋ณด ์ œ๊ณต ๋‹ค๋ฅธ ๋ชจ๋“ˆ๋กœ ๋ผ์šฐํŒ… ํ˜„์žฌ ๋ชจ๋“ˆ์—์„œ ๋‹ค๋ฅธ ๋ชจ๋“ˆ๋กœ ์ด๋™ํ•˜๋Š” ๋ผ์šฐํŒ… ๊ธฐ๋Šฅ ------------------------ -------------------------------------------------------------- ------ **3.2.2 ํ๋ฆ„๋„** **Figure 3 ๊ณค์ถฉ DB ํ๋ฆ„๋„** - SQL ์„œ๋ฒ„๋Š” ์š”์ฒญ์— ๋Œ€ํ•œ ์‘๋‹ต์œผ๋กœ DB ํŒŒ์ผ์„ ์ „์†กํ•œ๋‹ค. - DB-&gt; Json converter๋Š” ์ด ํŒŒ์ผ์„ JSON ํŒŒ์ผํ˜•์‹์œผ๋กœ ๋‹ค์‹œ ์ž‘์„ฑํ•œ ํ›„ ์›น์— ์ถœ๋ ฅํ•œ๋‹ค. - ์‚ฌ์šฉ์ž์—๊ฒŒ ๋ฐ์ดํ„ฐ๋ฅผ ์ถœ๋ ฅํ•œ ํ›„ ์ž…๋ ฅ์„ ๋ฐ›๋Š”๋‹ค. - ๊ณค์ถฉ์ด๋ฆ„์— ์—ฐ๊ฒฐ๋œ Link๋ฅผ ๋ˆ„๋ฅด๋ฉด ๊ณค์ถฉ ์ƒ์„ธ ๋””์Šคํฌ๋ฆฝ์…˜ ํŽ˜์ด์ง€๋กœ ๋„˜์–ด๊ฐ„ ํ›„ ๋ฐ์ดํ„ฐ๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค. - ๋‹ค๋ฅธ ๋ชจ๋“ˆ์˜ Url์„ ํด๋ฆญํ•˜๋ฉด ๋‹ค๋ฅธ ํŽ˜์ด์ง€๋กœ ๋„˜์–ด๊ฐ€ ๊ทธ ๋ชจ๋“ˆ์˜ ์ œ์–ด๋ฅผ ๋ฐ›๋Š”๋‹ค. **3.2.3 ์ธํ„ฐํŽ˜์ด์Šค** - Get\_insects\_db\_sumarry() a. ํ•จ์ˆ˜ ์ •์˜ > Def Get\_insects\_db\_sumarry (); a. ์„ค๋ช… > ์„œ๋ฒ„์— ๊ณค์ถฉ DB list๋ฅผ ์š”์ฒญํ•˜๋Š” ํ•จ์ˆ˜. a. ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฉ”ํƒ€ ---------------- ---- ----- ------------- Parameter Name IN OUT Description ---------------- ---- ----- ------------- a. ๋ฐ˜ํ™˜ ํƒ€์ž… ---------------------- -------------------------------------------------------------------------- Type Name Description Summary\_of\_insects ๊ฒŒ์‹œํŒ ๋ฆฌ์ŠคํŠธ์— ๋„์šธ ๊ณค์ถฉ์˜ ์š”์•ฝ ์ •๋ณด๋ฅผ ํฌํ•จํ•œ ํŒŒ์ผ(๊ณค์ถฉ์˜ ์ด๋ฆ„, ์„œ์‹์ง€) ---------------------- -------------------------------------------------------------------------- - Convert\_to\_json() a. ํ•จ์ˆ˜ ์ •์˜ > Def Conver\_to\_json(raw\_db\_file) a. ์„ค๋ช… > ์„œ๋ฒ„์—์„œ ๋ณด๋‚ด์˜จ DB๋ฅผ json ํŒŒ์ผ๋กœ ๋ณ€ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜ a. ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฉ”ํƒ€ ---------------- ---- ----- ------------------------------------------------------------------ Parameter Name IN OUT Description raw\_db\_file Y ์„œ๋ฒ„์—์„œ ๋ณด๋‚ด์˜จ ๋ฐ์ดํ„ฐ ํŒŒ์ผ. ๊ฐ€๊ณต๋˜์ง€ ์•Š์•˜์Œ. โ€˜.sqlโ€™ํŒŒ์ผ ํ™•์žฅ์ž. ---------------- ---- ----- ------------------------------------------------------------------ a. ๋ฐ˜ํ™˜ ํƒ€์ž… ------------ -------------------------------------------------- Type Name Description Json\_list ํ•จ์ˆ˜์˜ ๊ฒฐ๊ณผ๋กœ โ€œ.jsonโ€ํŒŒ์ผ ํ™•์žฅ ์ž๋กœ ๊ฐ€๊ณต๋œ ํŒŒ์ผ. ------------ -------------------------------------------------- - Print\_data() a. ํ•จ์ˆ˜ ์ •์˜ > Def print\_data(Json\_list) a. ์„ค๋ช… > Json ํŒŒ์ผ์„ ์‹œ๊ฐ์ ์œผ๋กœ ์ถœ๋ ฅํ•˜๊ธฐ ์œ„ํ•œ ํ•จ์ˆ˜. ๋ฐ์ดํ„ฐ๋ฅผ ์˜ˆ์˜๊ฒŒ ์ถœ๋ ฅํ•œ๋‹ค. a. ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฉ”ํƒ€ ---------------- ---- ----- ------------------- Parameter Name IN OUT Description Json\_list Y ๊ณค์ถฉ DB Json ํŒŒ์ผ ---------------- ---- ----- ------------------- a. ๋ฐ˜ํ™˜ ํƒ€์ž… ----------- ----------------------------- Type Name Description Error Error๋ฐœ์ƒ์‹œ ์—๋Ÿฌ๋ฉ”์‹œ์ง€ ์ถœ๋ ฅ ----------- ----------------------------- - Route\_Url() a. ํ•จ์ˆ˜ ์ •์˜ > Def route\_url(url) a. ์„ค๋ช… > ์‚ฌ์šฉ์ž ์ž…๋ ฅ์— ๋”ฐ๋ฅธ ๋ผ์šฐํŒ… ๊ธฐ๋Šฅ ์ œ๊ณต. ์ƒ์„ธ ๋””์Šคํฌ๋ฆฝ์…˜์ด๋‚˜ ๋‹ค๋ฅธ ๋ชจ๋“ˆ๋กœ > ๋ผ์šฐํŒ…๊ธฐ๋Šฅ ์ œ๊ณต. a. ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฉ”ํƒ€ ---------------- ---- ----- ------------------------- Parameter Name IN OUT Description url Y ๋ผ์šฐํŒ… ํ•˜๊ณ ์ž ํ•˜๋Š” ๊ฒฝ๋กœ ---------------- ---- ----- ------------------------- a. ๋ฐ˜ํ™˜ ํƒ€์ž… ----------- ----------------------------- Type Name Description Error Error๋ฐœ์ƒ์‹œ ์—๋Ÿฌ๋ฉ”์‹œ์ง€ ์ถœ๋ ฅ ----------- ----------------------------- - Get\_insects\_db\_detail() a. ํ•จ์ˆ˜ ์ •์˜ > Def Get\_insects\_db\_detail (index) a. ์„ค๋ช… > ๊ณค์ถฉ ๋ฐ์ดํ„ฐ ๋ฒ ์ด์Šค ์š”์ฒญ a. ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฉ”ํƒ€ ---------------- ---- ----- ------------------------------ Parameter Name IN OUT Description index Y ๋ผ์šฐํŒ… ํ•˜๊ณ ์ž ํ•˜๋Š” ๊ฒฝ๋กœ(url) ---------------- ---- ----- ------------------------------ a. ๋ฐ˜ํ™˜ ํƒ€์ž… -------------------------- ------------------------------------------------------- Type Name Description Error Error๋ฐœ์ƒ์‹œ ์—๋Ÿฌ๋ฉ”์‹œ์ง€ ์ถœ๋ ฅ Description\_of\_insects ๊ณค์ถฉ์˜ ์ƒ์„ธ์ •๋ณด(๊ณค์ถฉ์˜ ์ด๋ฆ„, ์„œ์‹์ง€, ์š”๋ฆฌ๋ฒ•, ์‚ฌ์ง„ ์™ธ) -------------------------- ------------------------------------------------------- - Route\_to\_other\_modules() a. ํ•จ์ˆ˜ ์ •์˜ > Def Route\_to\_other\_modules (url) a. ์„ค๋ช… > ๋‹ค๋ฅธ ๋ชจ๋“ˆ๋กœ ๋ผ์šฐํŒ… ํ•˜๋Š” ํ•จ์ˆ˜ a. ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฉ”ํƒ€ ---------------- ---- ----- ------------------------------------------------- Parameter Name IN OUT Description url Y ๋ผ์šฐํŒ… ํ•˜๊ณ ์ž ํ•˜๋Š” ๊ฒฝ๋กœ(module์ด๋ฆ„;ํŽ˜์ด์ง€ ์ด๋ฆ„) ---------------- ---- ----- ------------------------------------------------- a. ๋ฐ˜ํ™˜ ํƒ€์ž… ----------- --------------------------------------------- Type Name Description Error Error๋ฐœ์ƒ์‹œ ์—๋Ÿฌ๋ฉ”์‹œ์ง€ ์ถœ๋ ฅ, 404ํŽ˜์ด์ง€ ์ถœ๋ ฅ ----------- --------------------------------------------- **3.3 ๋ฏธ๋””์–ด ๊ฒŒ์‹œํŒ** ๋ฏธ๋””์–ด ๊ฒŒ์‹œํŒ์€ ๊ณค์ถฉ์˜ ๋ ˆ์‹œํ”ผ๋‚˜ ๊ฐ์ข… ์ด์Šˆ๋“ค์— ๋Œ€ํ•œ ์ •๋ณด๊ต๋ฅ˜๋ฅผ ๋ชฉ์ ์œผ๋กœ ํ•˜๋Š” ์ผ์ข…์˜ ๊ฒŒ์‹œํŒ์ด๋‹ค. ๋กœ๊ทธ์ธํ•œ ์‚ฌ์šฉ์ž๋Š” ๊ธ€์„ ๊ฒŒ์‹œํ•  ์ˆ˜ ์žˆ์œผ๋ฉฐ, ์ž์‹ ์˜ ๊ธ€์„ ์ˆ˜์ • ๋ฐ ์‚ญ์ œํ•  ์ˆ˜ ์žˆ๋‹ค. ๋˜ํ•œ ํƒ€์ธ์˜ ๊ธ€์„ ์ถ”์ฒœํ•  ์ˆ˜ ์žˆ๋Š” ๊ธฐ๋Šฅ์ด ์žˆ๋‹ค. ์ถ”์ฒœ์ˆ˜๊ฐ€ ๋†’์€ ๊ธ€์€ ์ถ”์ฒœ๊ฒŒ์‹œํŒ์œผ๋กœ ์˜ฎ๊ฒจ์ง„๋‹ค. ๋ฏธ๋””์–ด๊ฒŒ์‹œํŒ์€ ๋ ˆ์‹œํ”ผ ๊ฒŒ์‹œํŒ๊ณผ, ๋‰ด์Šค ๋ฐ ๋™์˜์ƒ ๊ฒŒ์‹œํŒ์œผ๋กœ ๊ตฌ์„ฑ๋˜์–ด ์žˆ๋‹ค. ๊ฒŒ์‹œํŒ์€ ๋ˆ„๊ตฌ๋‚˜ ์ ‘๊ทผ ํ•  ์ˆ˜ ์žˆ๋‹ค. **3.3.1 ๊ฐœ์š” ๋ฐ ํ๋ฆ„** **Figure 4 ๋ฏธ๋””์–ด ๊ฒŒ์‹œํŒ ๊ตฌ์กฐ ๋ฐ ๋ฐ์ดํ„ฐ ํ๋ฆ„** - ๊ฒŒ์‹œ๊ธ€ ๋ฐ์ดํ„ฐ๋ฅผ ์š”์ฒญ(get\_board\_summary()) ๋ฐ›์€ DB ์„œ๋ฒ„๋Š” ๊ฒŒ์‹œํŒ ์ •๋ณด์— ๋Œ€ํ•œ ๋ฐ์ดํ„ฐ(๊ธ€๋ฒˆํ˜ธ, ์กฐํšŒ์ˆ˜, ์ œ๋ชฉ, ์ž‘์„ฑ์ž, ์ถ”์ฒœ์ˆ˜)๋ฅผ ์ „์†กํ•œ๋‹ค. - SQL -&gt; Json ํŒŒ์ผ ์ปจ๋ฒ„ํ„ฐ๋Š” DBํŒŒ์ผ์„ JsonํŒŒ์ผ๋กœ ์ปจ๋ฒ„ํŒ…(conver\_to\_json()) ํ•œ๋‹ค. - ๊ฒŒ์‹œ๊ธ€ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ถœ๋ ฅํ•œ ํ›„(Print\_data()) ์‚ฌ์šฉ์ž ์ž…๋ ฅ์„ ๋ฐ›์•„ ๋‹ค์Œ ํ–‰๋™์„ ๋Œ€๊ธฐํ•œ๋‹ค. - ๊ฒŒ์‹œ๊ธ€ ๋ฆฌ์ŠคํŠธ๋ฅผ ํด๋ฆญ(get\_board\_detail(index))ํ•˜๋ฉด ๊ฒŒ์‹œ๊ธ€์— ๋Œ€ํ•œ ์ƒ์„ธ ๋””์Šคํฌ๋ฆฝ์…˜์„ ์ถœ๋ ฅํ•œ๋‹ค. ๋งŒ์•ฝ ํ˜„์žฌ ์‚ฌ์šฉ์ž์™€ ๊ฒŒ์‹œ์ž๊ฐ€ ๋™์ผํ•˜๋ฉด edit()๊ณผ delet()ํ•จ์ˆ˜๋ฅผ ์‹คํ–‰ํ•˜๋Š” ๊ถŒํ•œ์„ ๋ถ€์—ฌํ•œ๋‹ค. - Edit()์„ ์‹คํ–‰ํ•˜๋ฉด ๋ฐ์ดํ„ฐ๋ฅผ ์ˆ˜์ •ํ•  ์ˆ˜ ์žˆ์œผ๋ฉฐ ์ˆ˜์ •ํ•œ ๋ฐ์ดํ„ฐ๋Š” DB์— ๋ณด๋‚ด์ง€๋ฉฐ ์ดํ›„ ๊ฒŒ์‹œ๊ธ€ ์ƒ์„ธ ๋””์Šคํฌ๋ฆฝ์…˜์œผ๋กœ ๋ผ์šฐํŒ…ํ•œ๋‹ค. - Delete()๋ฅผ ์‹คํ–‰ํ•˜๋ฉด ๋ฐ์ดํ„ฐ๋ฅผ ์‚ญ์ œํ•˜๊ณ  DB์— ๋ฐ˜์˜ ํ›„ ๊ฒŒ์‹œ๊ธ€ ๋ฆฌ์ŠคํŠธ๋กœ ๋ผ์šฐํŒ…ํ•œ๋‹ค. - ๋กœ๊ทธ์ธํ•œ ์‚ฌ์šฉ์ž๋Š” ๊ธ€์„ ์“ธ ์ˆ˜ ์žˆ๋‹ค. - ๋‹ค๋ฅธ ๋ชจ๋“ˆ๋กœ ๋ผ์šฐํŒ…(route\_to\_other\_modues(url))์„ ํ•˜๋ฉด ํ•ด๋‹น ๋ชจ๋“ˆ๋กœ ์ด๋™ํ•˜๊ณ , ํ•ด๋‹น ๋ชจ๋“ˆ์˜ ์ œ์–ด๋ฅผ ๋ฐ›๊ฒŒ ๋œ๋‹ค. **3.3.2 ์ธํ„ฐํŽ˜์ด์Šค** - Get\_board\_summary() a. Def get\_board\_summary() b. ์„ค๋ช… > DB์„œ๋ฒ„์— ๊ฒŒ์‹œํŒ ๋ฆฌ์ŠคํŠธ์— ์ •๋ณด๋ฅผ ์š”์ฒญํ•˜๋Š” ํ•จ์ˆ˜(๊ธ€๋ฒˆํ˜ธ, ์ œ๋ชฉ, ๊ธ€์“ด์ด, > ์ถ”์ฒœ์ˆ˜, ๋‚ ์งœ) a. ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฉ”ํƒ€ ---------------- ---- ----- ------------- Parameter Name IN OUT Description ---------------- ---- ----- ------------- a. ๋ฐ˜ํ™˜ ํƒ€์ž… ---------------- ---------------------------------------------------------------------------------------- Type Name Description Board\_summary ํ™•์žฅ์ž๊ฐ€ โ€œ.SQLโ€์ธ ํŒŒ์ผ์ด๋ฉฐ, ๊ธ€๋ฒˆํ˜ธ, ์ œ๋ชฉ, ๊ธ€์“ด์ด, ์ถ”์ฒœ์ˆ˜ ๋ฐ ๋‚ ์งœ ์ •๋ณด๋ฅผ ํฌํ•จํ•˜๊ณ  ์žˆ๋‹ค. ---------------- ---------------------------------------------------------------------------------------- - Get\_board\_detail(i) a. Def get\_board\_detail(index) b. ์„ค๋ช… > DB ์„œ๋ฒ„์— ์š”์ฒญํ•œ index์— (๊ธ€ ๋ฒˆํ˜ธ) ๋Œ€์‘ํ•˜๋Š” ์ƒ์„ธ ๋””์Šคํฌ๋ฆฝ์…˜์„ ์š”์ฒญํ•˜๋Š” > ํ•จ์ˆ˜.(๊ธ€๋ฒˆํ˜ธ, ์ œ๋ชฉ, ๊ธ€์“ด์ด, ์ถ”์ฒœ์ˆ˜, ๋‚ ์งœ, ๋ณธ๋ฌธ) a. ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฉ”ํƒ€ ---------------- ---- ----- --------------------------------------------------------------------------------- Parameter Name IN OUT Description Index Y ์ƒ์„ธํžˆ ์—ด๋žŒํ•˜๊ณ ์ž ํ•˜๋Š” ๊ธ€๋ฒˆํ˜ธ. ์ฆ‰, DB์˜ ๊ธฐ๋ณธํ‚ค์— ๋Œ€์‘ํ•˜๋Š” ๋ชจ๋“  ๋‚ด์šฉ์„ ์š”์ฒญํ•œ๋‹ค. ---------------- ---- ----- --------------------------------------------------------------------------------- a. ๋ฐ˜ํ™˜ ํƒ€์ž… --------------- ---------------------------------------------------------------------------------------------- Type Name Description Board\_detail ํ™•์žฅ์ž๊ฐ€ โ€œ.SQLโ€์ธ ํŒŒ์ผ์ด๋ฉฐ, ๊ธ€๋ฒˆํ˜ธ, ์ œ๋ชฉ, ๊ธ€์“ด์ด, ์ถ”์ฒœ์ˆ˜, ๋‚ ์งœ ๋ฐ ๋ณธ๋ฌธ ์ •๋ณด๋ฅผ ํฌํ•จํ•˜๊ณ  ์žˆ๋‹ค. --------------- ---------------------------------------------------------------------------------------------- - Convert\_to\_json() a. Def convert\_to\_json(raw\_db\_file) b. ์„ค๋ช… > ์„œ๋ฒ„์—์„œ ๋ฐ›์•„์˜จ DB๋ฅผ JsonํŒŒ์ผ๋กœ ๋ณ€ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜ a. ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฉ”ํƒ€ ---------------- ---- ----- ----------------------------------------- Parameter Name IN OUT Description raw\_db\_file Y Json ํŒŒ์ผ๋กœ ๋ณ€ํ™˜ํ•  ๊ฐ€๊ณต๋˜์ง€ ์•Š์€ DBํŒŒ์ผ ---------------- ---- ----- ----------------------------------------- a. ๋ฐ˜ํ™˜ ํƒ€์ž… ------------ ---------------------------------------------- Type Name Description Json\_list ๋ณ€ํ™˜๋œ Json ํŒŒ์ผ. ์ด๋•Œ ํ™•์žฅ์ž๋Š” โ€œ.jsonโ€์ด๋‹ค. ------------ ---------------------------------------------- - Print\_board\_list() a. Def print\_board\_list(Json\_list) b. ์„ค๋ช… > ๊ฒŒ์‹œํŒ ์ •๋ณด๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ํ•จ์ˆ˜. ์ œ๋ชฉ, ์ž‘์„ฑ์ž, ๋‚ ์งœ, ๊ธ€ ๋ฒˆํ˜ธ๋ฅผ ์ถœ๋ ฅ a. ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฉ”ํƒ€ ---------------- ---- ----- ----------------------------------------------------------------------------------------------- Parameter Name IN OUT Description Json\_list Y ๊ฒŒ์‹œํŒ ๋ฆฌ์ŠคํŠธ ์ •๋ณด์— ๋Œ€ํ•œ JsonํŒŒ์ผ. ๊ธ€์ œ๋ชฉ, ์ถ”์ฒœ์ˆ˜, ๋ฒˆํ˜ธ, ์ž‘์„ฑ์ž ์ •๋ณด๋ฅผ ํฌํ•จํ•˜๊ณ  ์žˆ๋Š” ๊ตฌ์กฐ์ฒด. ---------------- ---- ----- ----------------------------------------------------------------------------------------------- a. ๋ฐ˜ํ™˜ ํƒ€์ž… ----------- ------------------------------------------------- Type Name Description error Error๊ฒ€์ถœ์‹œ error message ์ถœ๋ ฅ. 404 ํŽ˜์ด์ง€ ์ถœ๋ ฅ ----------- ------------------------------------------------- - Print board\_detail() a. Def print\_board\_detail(json\_list) b. ์„ค๋ช… > ๋ณด๊ณ ์ž ํ•˜๋Š” ๊ธ€์„ ์–‘์‹์— ๋งž์ถ”์–ด ์˜ˆ์˜๊ฒŒ ์ถœ๋ ฅํ•˜๋Š” ํ•จ์ˆ˜. a. ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฉ”ํƒ€ ---------------- ---- ----- ----------------------------------------------------------------------------------------------------- Parameter Name IN OUT Description Json\_list Y ๊ฒŒ์‹œํŒ ์ƒ์„ธ ์ •๋ณด์— ๋Œ€ํ•œ JsonํŒŒ์ผ. ๊ธ€์ œ๋ชฉ, ์ถ”์ฒœ์ˆ˜, ๋ฒˆํ˜ธ, ์ž‘์„ฑ์ž ๋ฐ ๋ณธ๋ฌธ ์ •๋ณด๋ฅผ ํฌํ•จํ•˜๊ณ  ์žˆ๋Š” ๊ตฌ์กฐ์ฒด. ---------------- ---- ----- ----------------------------------------------------------------------------------------------------- a. ๋ฐ˜ํ™˜ ํƒ€์ž… ----------- ------------------------------------------------- Type Name Description error Error๊ฒ€์ถœ์‹œ error message ์ถœ๋ ฅ. 404 ํŽ˜์ด์ง€ ์ถœ๋ ฅ ----------- ------------------------------------------------- - Route\_to\_other\_modules() a. Def Route\_to\_other\_modules (url) b. ์„ค๋ช… > ๋‹ค๋ฅธ ๋ชจ๋“ˆ๋กœ ๋ผ์šฐํŒ… ํ•˜๋Š” ๊ธฐ๋Šฅ์„ ๊ฐ€์ง„ ํ•จ์ˆ˜.. a. ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฉ”ํƒ€ ---------------- ---- ----- ------------------- Parameter Name IN OUT Description url Y ๋ผ์šฐํŒ… ํ•  url์ฃผ์†Œ ---------------- ---- ----- ------------------- a. ๋ฐ˜ํ™˜ ํƒ€์ž… ----------- ------------------------------------------------ Type Name Description error Error๊ฒ€์ถœ์‹œ error message ์ถœ๋ ฅ. 404ํŽ˜์ด์ง€ ์ถœ๋ ฅ ----------- ------------------------------------------------ - Board\_write() a. Def board\_write() b. ์„ค๋ช… > ๊ฒŒ์‹œํŒ์— ๊ธ€์„ ์˜ฌ๋ฆฌ๋Š” ํ•จ์ˆ˜. ๊ฒŒ์‹œํŒ์— ๊ธ€ ์ž‘์„ฑ์€ ํšŒ์›๋งŒ ํ•  ์ˆ˜ ์žˆ๋‹ค. > ํ•จ์ˆ˜์˜ ๊ฒฐ๊ณผ๋กœ DB์„œ๋ฒ„์— ์ƒˆ๋กœ์šด ์ •๋ณด๋ฅผ ์—…๋ฐ์ดํŠธํ•œ๋‹ค. a. ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฉ”ํƒ€ ---------------- ---- ----- ------------- Parameter Name IN OUT Description ---------------- ---- ----- ------------- a. ๋ฐ˜ํ™˜ ํƒ€์ž… ----------- ------------------------------------------------ Type Name Description error Error๊ฒ€์ถœ์‹œ error message ์ถœ๋ ฅ, 404ํŽ˜์ด์ง€ ์ถœ๋ ฅ ----------- ------------------------------------------------ - Edit\_board() a. Def edit\_board(user\_info) b. ์„ค๋ช… > ๊ฒŒ์‹œ๊ธ€์„ ์ˆ˜์ •ํ•  ์ˆ˜ ์žˆ๋Š” ๊ธฐ๋Šฅ. ๊ธ€์˜ ์ˆ˜์ •์€ ๊ธ€์˜ ์ž‘์„ฑ์ž์™€ ํ˜„์žฌ ๋กœ๊ทธ์ธํ•œ > ์‚ฌ์šฉ์ž๊ฐ€ ์ผ์น˜ํ•  ๋•Œ๋งŒ ํ•จ์ˆ˜๋ฅผ ์‹คํ–‰ ํ•  ์ˆ˜ ์žˆ๋‹ค. a. ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฉ”ํƒ€ ---------------- ---- ----- --------------------------------------------------------------------- Parameter Name IN OUT Description User\_info Y ํ˜„์žฌ ์ ‘์†ํ•œ ์œ ์ €์— ๊ด€ํ•œ ์ •๋ณด. ์ˆ˜์ •ํ•  ๊ถŒํ•œ์ด ์žˆ๋Š”์ง€ ์—†๋Š”์ง€ ํŒ๋ณ„ํ•œ๋‹ค. ---------------- ---- ----- --------------------------------------------------------------------- a. ๋ฐ˜ํ™˜ ํƒ€์ž… ----------- ------------------------------------------- Type Name Description error Error๊ฒ€์ถœ์‹œ error message ์ถœ๋ ฅ, 404ํŽ˜์ด์ง€ ----------- ------------------------------------------- **3.4 ๋ง›์ง‘ ์†Œ๊ฐœ** ๊ณค์ถฉ ์Œ์‹ ๋ง› ์ง‘์„ ์†Œ๊ฐœํ•  ์ˆ˜ ์žˆ๋Š” ๋ชจ๋“ˆ์ด๋‹ค. ์ด ๋ชจ๋“ˆ์€ ๋ง› ์ง‘์— ์ •๋ณด์— ๋Œ€ํ•œ ์ผ์ข…์˜ ๊ฒŒ์‹œํŒ์œผ๋กœ ๋ณผ ์ˆ˜ ์žˆ์œผ๋ฉฐ, ๊ธ€์„ ๊ฒŒ์‹œํ•  ์ˆ˜ ์žˆ๋Š” ์ฃผ์ฒด๋Š” ๊ณ  ๋ ˆ๋ฒจ ์œ ์ €์ด๋‹ค. ๋ณธ ๋ชจ๋“ˆ์€ 2.2์ ˆ์ธ ๋ฏธ๋””์–ด ๊ฒŒ์‹œํŒ๊ณผ ๋™์ผํ•œ ๊ตฌ์กฐ์ด๊ธฐ ๋•Œ๋ฌธ์— ๊ตฌ์กฐ๋Š” ์ƒ๋žตํ•˜๊ณ , ๋ ˆ๋ฒจ ์—… ์ฒด๊ณ„์— ๋Œ€ํ•ด์„œ ์„ค๋ช…ํ•  ๊ฒƒ์ด๋‹ค. **3.4.1 ๊ฐœ์š”** ๋‹ค์Œ ๊ทธ๋ฆผ์€ ๋ณธ ์›น์‚ฌ์ดํŠธ์˜ ๋ ˆ๋ฒจ ์—… ์ฒด๊ณ„์ด๋‹ค. ์ด 4๊ฐœ์˜ ๋‹จ๊ณ„๋กœ ๋‚˜๋‰˜๋ฉฐ, ๋กœ๊ทธ์ธ ํšŸ์ˆ˜ ๋ฐ ๊ฒŒ์‹œ ๊ธ€ ๊ฐœ์ˆ˜, ์ถ”์ฒœ ๊ฐœ์ˆ˜ ๋“ฑ ํ™œ๋™ ์ ์ˆ˜๋ฅผ ์˜ฌ๋ ค ๊ฒฝํ—˜์น˜๋ฅผ ์–ป๊ฒŒ ๋œ๋‹ค. ์‚ฌ์šฉ์ž์˜ ์ž๋ฐœ์ ์ธ ์ฐธ์—ฌ๋ฅผ ์œ„ํ•œ ์ผ์ข…์˜ ๋„๊ตฌ์ด๋‹ค. **Figure 5 ์›น์‚ฌ์ดํŠธ ๋ ˆ๋ฒจ์—… ์ฒด๊ณ„** **3.4.2 ๊ฐ ๋ ˆ๋ฒจ ๋ณ„ ์š”๊ตฌ์‚ฌํ•ญ ๋ฐ ๊ธฐ๋Šฅ.** -------- ----------------------------------------------------------------------- -------------------------- ------ ๋ ˆ๋ฒจ ๊ธฐ๋Šฅ ๋‚ด์šฉ ์š”๊ตฌ ์‚ฌํ•ญ ๋น„๊ณ  ์ดˆ๋ณด์ถฉ ์• ๋ฒŒ๋ ˆ ์•„์ด์ฝ˜ ๊ฐ€์ž… ์ค‘์ˆ˜์ถฉ ๋ฒˆ๋ฐ๊ธฐ ์•„์ด์ฝ˜ ํ™œ๋™ ๊ฒฝํ—˜์น˜ 100์  ํš๋“ ๊ณ ์ˆ˜์ถฉ ๋‚˜๋น„ ์•„์ด์ฝ˜ ํ™œ๋™ ๊ฒฝํ—˜์น˜ 1000์  ํš๋“ ์ถฉ์™• ํ—ค๋ผํด๋ ˆ์Šค ์•„์ด์ฝ˜, ๊ฒŒ์‹œ ๊ธ€์— ํ•˜์ด๋ผ์ดํŒ…, ๋ง›์ง‘ ์†Œ๊ฐœ๊ฒŒ์‹œํŒ ๊ธ€ ๊ฒŒ์‹œ ๊ฐ€๋Šฅ ํ™œ๋™ ๊ฒฝํ—˜์น˜ 10000์  ํš๋“ -------- ----------------------------------------------------------------------- -------------------------- ------ **3.4.3 ๊ฒฝํ—˜์น˜ ํš๋“ ๊ฒฝ๋กœ** - ๋กœ๊ทธ์ธ์‹œ 3์  ํš๋“. 1์ผ 1ํšŒ - ๊ฒŒ์‹œํŒ์— ๊ธ€ ๋“ฑ๋ก ์‹œ 3์  ํš๋“. 1์ผ 3ํšŒ - ๋Œ“๊ธ€ ์ž‘์„ฑ์‹œ 1์  ํš๋“. 1์ผ 10ํšŒ. - ์ถ”์ฒœ ๋ฐ›์„ ์‹œ 1์  ํš๋“. - ๊ธฐํƒ€. ์ด๋ฒคํŠธ ์ฐธ์—ฌ์‹œ ์ ์ˆ˜ ๋ถ€์—ฌ. **3.5์ฒœํ•˜์ œ์ผ ๊ณค์ถฉ์Œ์‹ ๋Œ€ํšŒ** ์ฒœํ•˜์ œ์ผ ๊ณค์ถฉ์Œ์‹ ๋Œ€ํšŒ๋Š” ์‚ฌ์šฉ์ž์˜ ์ฐธ์—ฌ๋ฅผ ์œ ๋„ํ•˜๋ฉฐ, ๊ณค์ถฉ ์Œ์‹์— ๊ด€ํ•œ ํ™œ๋ฐœํ•œ ์ •๋ณด๊ต๋ฅ˜๋ฅผ ์ด‰์ง„์‹œํ‚ค๊ธฐ ์œ„ํ•œ ๋ชจ๋“ˆ์ด๋‹ค. ์ฐธ๊ฐ€์ž๋Š” ์‚ฌ์ „์— ๋“ฑ๋ก์„ ๋ฐ›์œผ๋ฉฐ ๋“ฑ๋กํ•œ ์‚ฌ์šฉ์ž๋Š” ๊ฐ์ž์˜ ๋ ˆ์‹œํ”ผ๋ฅผ ๋“ฑ๋กํ•˜๊ณ  ์„œ๋กœ ๊ฒจ๋ฃฌ๋‹ค. ์Šน์ž๋Š” ์ถ”์ฒœ์ˆ˜๋ฅผ ๋งŽ์ด ๋ฐ›์€ ์œ ์ €๊ฐ€ ์Šน๋ฆฌํ•œ๋‹ค. 1์œ„๋ถ€ํ„ฐ 3์œ„๊นŒ์ง€ ์ˆ˜์ƒ์ž๋ฅผ ๋ฝ‘๋Š”๋‹ค. ์ด ๋ชจ๋“ˆ์— ๋“ค์–ด์˜ค๊ฒŒ ๋˜๋ฉด, ํ˜„์žฌ ์ถ”์ฒœ์ˆ˜๊ฐ€ ๋งŽ์€ ์ˆœ์„œ๋Œ€๋กœ 1๋“ฑ๋ถ€ํ„ฐ 3์œ„๊นŒ์ง€๋ฅผ ์Šคํฌ๋ฆฐ์—์„œ ๋ณผ ์ˆ˜ ์žˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ๊ทธ ์•„๋ž˜ ๋ ˆ์‹œํ”ผ๋ฅผ ๋ณผ ์ˆ˜ ์žˆ๋Š” ๊ฒŒ์‹œํŒ์ด ์žˆ๋‹ค. ๋กœ๊ทธ์ธ ํ•œ ์œ ์ €๋Š” ์ถ”์ฒœ์„ ํ•  ์ˆ˜ ์žˆ๋‹ค. ์ค‘๋ณต ์ถ”์ฒœ์€ ๋ถˆ๊ฐ€๋Šฅ ํ•˜๋‹ค. **3.5.1 ๊ฐœ์š”** ์•„๋ž˜ ๊ทธ๋ฆผ์€ ํ˜„์žฌ ํŽ˜์ด์ง€์— ๋“ค์–ด์™”์„ ์‹œ ์ฒ˜์Œ์œผ๋กœ ๋ณด์—ฌ์ง€๋Š” ํ™”๋ฉด์ด๋‹ค. ![](media/image7.png) Figure 6 ๊ณค์ถฉ ์Œ์‹ ๋Œ€ํšŒ ๋ฉ”์ธ **3.5.2 ์ธํ„ฐํŽ˜์ด์Šค** - Get\_ranking\_board() a. Def get\_ranking\_board() b. ํ•จ์ˆ˜ ์ •์˜ > DB ์„œ๋ฒ„์—์„œ ๋žญํ‚น๋ณด๋“œ์— ์‚ฌ์šฉํ•  ๋ฐ์ดํ„ฐ๋ฅผ ์š”์ฒญํ•˜๋Š” ํ•จ์ˆ˜. ๋Œ€ํšŒ ์ฐธ๊ฐ€์ž๋“ค์˜ > ๊ธ€ ์ •๋ณด๋ฅผ ์š”์ฒญ(์ˆœ์œ„, ์ด๋ฆ„, ์ œ๋ชฉ, ์ถ”์ฒœ์ˆ˜)์ •๋ณด๋ฅผ ํฌํ•จํ•˜๋Š” ๋ฐ์ดํ„ฐ๋ฅผ > ๋ฐ˜ํ™˜ํ•œ๋‹ค. a. ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฉ”ํƒ€ ---------------- ---- ----- ------------- Parameter Name IN OUT Description ---------------- ---- ----- ------------- a. ๋ฐ˜ํ™˜ ํƒ€์ž… ------------------ ------------------------------------------------------------------------------------------------------------- Type Name Description Ranking\_summary ์š”๋ฆฌ ๋Œ€ํšŒ ๋ฉ”์ธํŽ˜์ด์ง€์˜ ๊ฒŒ์‹œํŒ์— ์ถœ๋ ฅํ•  ์ฐธ๊ฐ€์ž๋“ค์˜ ๊ธ€ ์ •๋ณด์— ๊ด€ํ•œ ๊ตฌ์กฐ์ฒด(์ˆœ์œ„, ์ด๋ฆ„, ์ œ๋ชฉ, ์ถ”์ฒœ์ˆ˜)์ •๋ณด ํฌํ•จ. ------------------ ------------------------------------------------------------------------------------------------------------- - Convert\_to\_Json() a. Def convert\_to\_json(raw\_db\_file) b. ํ•จ์ˆ˜ ์ •์˜ > ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์—์„œ ๊ฑด๋‚ด ์ค€ ํŒŒ์ผ์„ JsonํŒŒ์ผ๋กœ ๋ณ€ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜. a. ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฉ”ํƒ€ ---------------- ---- ----- ------------------------------------------ Parameter Name IN OUT Description raw\_db\_file Y JsonํŒŒ์ผ๋กœ ๊ฐ€๊ณตํ•  ํ™•์žฅ์ž๊ฐ€ โ€œ.SQLโ€์ธ ํŒŒ์ผ ---------------- ---- ----- ------------------------------------------ a. ๋ฐ˜ํ™˜ ํƒ€์ž… ------------ ------------------------------- Type Name Description Json\_list ํŒŒ์ผ ํ™•์žฅ์ž๊ฐ€ โ€œ.jsonโ€์ธ ํŒŒ์ผ. ------------ ------------------------------- - Print\_ranking\_board() a. Def print\_ranking\_board(Json\_list) b. ํ•จ์ˆ˜ ์ •์˜ > ์ ์ˆ˜ํŒ์— 1๋“ฑ๋ถ€ํ„ฐ 3๋“ฑ๊นŒ์ง€ ์ถœ๋ ฅํ•˜๋Š” ํ•จ์ˆ˜ a. ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฉ”ํƒ€ ---------------- ---- ----- -------------------------------------------------------------------- Parameter Name IN OUT Description Json\_list Y ๋žญํ‚น ๋ณด๋“œ์— ์ถœ๋ ฅํ•  3์ธ์— ๋Œ€ํ•œ ์ •๋ณด(์ด๋ฆ„). ํ™•์žฅ์ž๋Š” โ€œ.jsonโ€์ธ ํŒŒ์ผ. ---------------- ---- ----- -------------------------------------------------------------------- a. ๋ฐ˜ํ™˜ ํƒ€์ž… ----------- -------------------------------- Type Name Description Error Error ๋ฐœ์ƒ์‹œ error message์ถœ๋ ฅ ----------- -------------------------------- - print\_recipe\_detail() a. def print\_recipe\_lists(recipe\_detail) b. ํ•จ์ˆ˜ ์ •์˜ > ๋ณด๊ณ ์ž ํ•˜๋Š” ์ฐธ๊ฐ€์ž์˜ ๋ ˆ์‹œํ”ผ๋ฅผ ์–‘์‹์— ๋งž์ถ”์–ด ์˜ˆ์˜๊ฒŒ ์ถœ๋ ฅํ•˜๋Š” ํ•จ์ˆ˜. a. ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฉ”ํƒ€ ---------------- ---- ----- ---------------------------------------------------------------------------------------------------- Parameter Name IN OUT Description Recipe\_detail Y ์ถœ๋ ฅํ•  ๋ ˆ์‹œํ”ผ์˜ ์ •๋ณด(์ด๋ฆ„, ์ œ๋ชฉ, ๋ณธ๋ฌธ, ์ถ”์ฒœ์ˆ˜, ๊ธ€๋ฒˆํ˜ธ)์— ๊ด€ํ•œ ๊ตฌ์กฐ์ฒด. ํ™•์žฅ์ž๊ฐ€ โ€œ.jsonโ€์ธ ํŒŒ์ผ์ด๋‹ค. ---------------- ---- ----- ---------------------------------------------------------------------------------------------------- a. ๋ฐ˜ํ™˜ ํƒ€์ž… ----------- ------------------------------------------------ Type Name Description Error Error ๋ฐœ์ƒ์‹œ error message์ถœ๋ ฅ. 404ํŽ˜์ด์ง€ ์ถœ๋ ฅ ----------- ------------------------------------------------ - Route\_other\_modules(url) a. Def route\_other\_modules(url) b. ํ•จ์ˆ˜ ์ •์˜ > ๋‹ค๋ฅธ ๋ชจ๋“ˆ๋กœ ๋ผ์šฐํŒ… ํ•˜๋Š” ํ•จ์ˆ˜. a. ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฉ”ํƒ€ ---------------- ---- ----- ------------------------------- Parameter Name IN OUT Description url Y ๋ผ์šฐํŒ… ํ•˜๊ณ ์ž ํ•˜๋Š” ๋ชจ๋“ˆ์˜ url ---------------- ---- ----- ------------------------------- a. ๋ฐ˜ํ™˜ ํƒ€์ž… ----------- ------------------------------------------------ Type Name Description Error Error ๋ฐœ์ƒ์‹œ error message์ถœ๋ ฅ. 404ํŽ˜์ด์ง€ ์ถœ๋ ฅ ----------- ------------------------------------------------ - <span id="h.gjdgxs" class="anchor"></span>recommand(index) a. Def recommend(index) b. ํ•จ์ˆ˜ ์ •์˜ > ํด๋ฆญ ์‹œ ์ถ”์ฒœ์ˆ˜๋ฅผ ์˜ฌ๋ฆฌ๊ณ  DB ์„œ๋ฒ„์— ๋ฐ˜์˜ํ•˜๋Š” ํ•จ์ˆ˜. a. ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฉ”ํƒ€ ---------------- ---- ----- -------------- Parameter Name IN OUT Description Index Y ํ˜„์žฌ ๊ธ€ ๋ฒˆํ˜ธ ---------------- ---- ----- -------------- a. ๋ฐ˜ํ™˜ ํƒ€์ž… ----------- ------------------------------------------------ Type Name Description Error Error ๋ฐœ์ƒ์‹œ error message์ถœ๋ ฅ. 404ํŽ˜์ด์ง€ ์ถœ๋ ฅ ----------- ------------------------------------------------ **ํ‰๊ฐ€ ๋ฐ ํ‰๊ฐ€ ๊ณ„ํš** **4.1 ํ‰๊ฐ€ ๋„๊ตฌ ๋ฐ ๋ฒ”์œ„** ๋ณธ ์‹œ์Šคํ…œ์˜ ํ‰๊ฐ€๋ฅผ ์œ„ํ•˜์—ฌ ์„ธ ๊ฐ€์ง€ ํ‰๊ฐ€ ์ง€ํ‘œ๋ฅผ ์ด์šฉํ•  ๊ณ„ํš์ด๋‹ค. ์ฒซ ๋ฒˆ์งธ๋Š” ์„ค๋ฌธ์กฐ์‚ฌ๋ฅผ ์‹ค์‹œํ•˜์—ฌ ์„œ๋น„์Šค์˜ ๋งŒ์กฑ๋„ ๋ฐ ๊ฐœ์„ ์  ์กฐ์‚ฌ. ๋‘ ๋ฒˆ์งธ๋Š” Windows์˜ ์‹œ์Šคํ…œ ์„ฑ๋Šฅ ๋ชจ๋‹ˆํ„ฐ๋ง ์„œ๋น„์Šค ๋„๊ตฌ๋ฅผ ์ด์šฉํ•˜์—ฌ ๊ฐ ๋‚ ์งœ ๋ณ„, ํŽ˜์ด์ง€ ๋ ˆ์ด์•„์›ƒ ๋“ฑ์˜ ํ•ญ๋ชฉ์œผ๋กœ ํ‰๊ฐ€๋ฅผ ์‹ค์‹œ, ๋งˆ์ง€๋ง‰์œผ๋กœ wave๋ผ๋Š” ํˆด์„ ์ด์šฉ, ์›น ์ ‘๊ทผ์„ฑ์˜ ํƒ€๋‹น์„ฑ์„ ์กฐ์‚ฌํ•  ๊ฒƒ์ด๋‹ค. **4.2. ์„ค๋ฌธ ์กฐ์‚ฌ** ์„ค๋ฌธ์กฐ์‚ฌ ์ˆ˜ํ–‰ ํ›„ ์„ค๋ฌธ์กฐ์‚ฌ ๊ฒฐ๊ณผ์™€ ํ•จ๊ป˜ ์ ‘์†์ž์ˆ˜ ์ธก์ •์„ ํ†ตํ•ด ๊ฒฐ๊ณผ๋ฌผ์„ ๊ทธ๋ž˜ํ”„๋กœ ์‚ฐ์ •ํ•  ๊ณ„ํš์ด๋‹ค. ์•„๋ž˜๋Š” ์„ค๋ฌธ์กฐ์‚ฌ ํ•ญ๋ชฉ์ด๋‹ค. Q. ์šฐ๋ฆฌ ์‚ฌ์ดํŠธ๋ฅผ ์‚ฌ์šฉํ•ด ๋ณธ ํ›„ ๊ณค์ถฉ์— ๋Œ€ํ•œ ์ธ์‹์ด ๊ฐœ์„ ๋˜์—ˆ์Šต๋‹ˆ๊นŒ? (1\~10์ ) --&gt; ๋ณธ๋ž˜ ๋ชฉ์ ์— ๋Œ€ํ•œ ๋‹ฌ์„ฑ ์—ฌ๋ถ€๋ฅผ ์•Œ๊ธฐ ์œ„ํ•ด Q. ์šฐ๋ฆฌ ์‚ฌ์ดํŠธ์—์„œ ๊ณค์ถฉ์— ๋Œ€ํ•œ ์ •๋ณด๋ฅผ ๊ฒ€์ƒ‰ํ•˜๊ธฐ์— ํŽธ๋ฆฌํ•˜์‹ญ๋‹ˆ๊นŒ? (1\~10์ ) --&gt; ์‚ฌ์šฉ์ž์—๊ฒŒ ์ œ๊ณตํ•ด์ฃผ๊ณ ์ž ํ•˜๋Š” ๋ฉ”์ธ ๊ธฐ๋Šฅ์ด ์ œ๋Œ€๋กœ ์ž‘๋™ํ•˜๋Š”์ง€ ๋ณด๊ธฐ ์œ„ํ•ด Q. ์šฐ๋ฆฌ ์‚ฌ์ดํŠธ์˜ ์ธํ„ฐํŽ˜์ด์Šค์— ๋Œ€ํ•œ ํŽธ์˜์„ฑ ์ •๋„๋ฅผ ์ ์ˆ˜๋กœ ๋งค๊ธด๋‹ค๋ฉด ๋ช‡ ์  ์ •๋„๋ฅผ ์ฃผ์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (1\~10์ ) --&gt; UI์šฉ ์งˆ๋ฌธ Q. ํ˜„์žฌ ์‚ฌ์šฉ ์ค‘์ธ ๋ธŒ๋ผ์šฐ์ €์˜ ์ข…๋ฅ˜๋Š” ๋ฌด์—‡์ž…๋‹ˆ๊นŒ? (ํฌ๋กฌ,IE,์Šค์œ™,ํŒŒ์ด์–ดํญ์Šค,๊ธฐํƒ€) --&gt; ๋ธŒ๋ผ์šฐ์ € ์ง€์› ์—ฌ๋ถ€ ๊ฒฐ์ •์— ๋„์›€์ด ๋จ Q. ๋ชจ๋ฐ”์ผ๋กœ ๋ณธ ์›น ํŽ˜์ด์ง€์— ์ ‘์†ํ–ˆ์„ ๋•Œ์— ๋Œ€ํ•œ ํŽธ์˜์„ฑ ์ •๋„๋ฅผ ์ ์ˆ˜๋กœ ๋งค๊ธด๋‹ค๋ฉด ๋ช‡ ์  ์ •๋„๋ฅผ ์ฃผ์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (1\~10์ ) --&gt; ๋ฐ˜์‘ํ˜• ์›น ํŽ˜์ด์ง€ ๊ตฌ์„ฑ ์—ฌ๋ถ€ ๊ฒฐ์ •์— ๋„์›€์ด ๋จ Q. \[์žฅ์• ์ธ์šฉ\] ๋ณธ ์›น ํŽ˜์ด์ง€๋ฅผ ์ด์šฉํ•˜๊ธฐ์— ํŽธ๋ฆฌํ•œ ์ •๋„๋ฅผ ์ ์ˆ˜๋กœ ๋งค๊ฒจ์ฃผ์‹ญ์‹œ์˜ค. (1\~10์ ) --&gt; ์›น ์ ‘๊ทผ์„ฑ ํ‘œ์ค€ ์ค€์ˆ˜ ๋Œ€ํ•œ ์‹ค์ œ ์‚ฌ์šฉ์ž ์ฒด๊ฐ ๋ฐ˜์‘ **4.2 windows ์‹œ์Šคํ…œ ์„ฑ๋Šฅ ๋ชจ๋‹ˆํ„ฐ๋ง** Windows ์‹œ์Šคํ…œ ์„ฑ๋Šฅ ๋ชจ๋‹ˆํ„ฐ๋ง ๋„๊ตฌ๋ฅผ ์ด์šฉํ•˜์—ฌ ์•„๋ž˜์˜ ํ•ญ๋ชฉ์„ ๊ฒ€์‚ฌํ•œ๋‹ค. - ์ธํ„ฐํŽ˜์ด์Šค๋ณ„ ์ ‘์†์ž์ˆ˜(ํ•œ ๋‹ฌ) - ํŽ˜์ด์ง€ ๋ ˆ์ด์•„์›ƒ ๋ณ„ ์ ‘์†์ž์ˆ˜(ํ•œ ๋‹ฌ) - ์ง€์› ๊ฐ€๋Šฅํ•œ ๋ธŒ๋ผ์šฐ์ €์˜ ๋ฒ”์œ„์— ๋”ฐ๋ฅธ ์ ‘์†์ž์ˆ˜ - ๋ฐ˜์‘ ํ˜• ์›น ์ง€์› ๊ฐ€๋Šฅ ์—ฌ๋ถ€์— ๋”ฐ๋ฅธ ์ ‘์†์ž์ˆ˜ ์›น ์„œ๋ฒ„ ๋ฆฌ์†Œ์Šค ํŒŒ์•…์„ ์œ„ํ•˜์—ฌ ์„ฑ๋Šฅ ๋ชจ๋‹ˆํ„ฐ๋ง์„ ์‚ฌ์šฉ, ์ˆ˜ํ–‰ ๊ฒฐ๊ณผ๋Š” ์•„๋ž˜์™€ ๊ฐ™๋‹ค. ์‚ฌ์ง„ ์ถ”๊ฐ€(์„ฑ๋Šฅ๋ชจ๋‹ˆํ„ฐ๋ง1\~) ![](media/image8.png)![](media/image9.png)![](media/image10.png)![](media/image11.png)![](media/image12.png)![](media/image13.png) ์ ‘์†์ž์ˆ˜ ์ถ”์ •์น˜ ![](media/image14.png) ์‹œ๊ฐ„๋Œ€๋ณ„ ์ ‘์†์ž์ˆ˜ ![](media/image15.jpeg) ํ–ฅํ›„ ์ ‘์†์ž์ˆ˜ ์ถ”์ • ![](media/image16.png) **4.3 Wave ํˆด** ์›น์˜ ์ ‘๊ทผ์„ฑ์„ ํ‰๊ฐ€ํ•˜๊ธฐ ์œ„ํ•œ ๋„๊ตฌ๋กœ waveํˆด์„ ์ด์šฉํ•œ๋‹ค. waveํˆด์„ ์ด์šฉํ•˜์—ฌ ๋‹ค์Œ์˜ ํ•ญ๋ชฉ๋“ค์„ ๊ฒ€์‚ฌํ•  ์˜ˆ์ •์ด๋‹ค. - ๋Œ€์ฒดํ…์ŠคํŠธ ์ œ๊ณต - ์ œ๋ชฉ์ œ๊ณต - ๊ธฐ๋ณธ์–ธ์–ด ๋ช…์‹œ - ์‚ฌ์šฉ์ž ์š”๊ตฌ์— ๋”ฐ๋ฅธ ์ƒˆ์ฐฝ ์—ด๊ธฐ - ๋ ˆ์ด๋ธ” ์ œ๊ณต - ๋งˆํฌ์—… ์˜ค๋ฅ˜ ๋ฐฉ์ง€ ![](media/image17.PNG) ์›น ์ ‘๊ทผ์„ฑ ์—ฐ๊ตฌ์†Œ์—์„œ ์ˆ˜ํ–‰ํ•œ ์›น ์ ‘๊ทผ์„ฑ ์ž๋™ ์ ๊ฒ€ ๋ณด๊ณ ์„œ ![](media/image18.PNG) **4.4 ๊ธฐ๋Œ€ํšจ๊ณผ์˜ ํƒ€๋‹น์„ฑ ๋ฐ ํ•œ๊ณ„์ ** **4.4.1 ๊ธฐ๋Œ€ ํšจ๊ณผ์˜ ํƒ€๋‹น์„ฑ** ์›น ํŽ˜์ด์ง€์˜ ์ด์šฉ์„ฑ ์ธก๋ฉด์—์„œ๋Š” (์žฅ์• ์ธ๋“ค๋„ ์›ํ•˜๋Š” ์ •๋ณด๋ฅผ ์–ป์„ ์ˆ˜ ์žˆ์„ ์ •๋„์˜ ์›น ์ ‘๊ทผ์„ฑ ํ‘œ์ค€์„ ๋งŒ์กฑํ•˜๋ฉฐ, ์„ค๋ฌธ์กฐ์‚ฌ๊ฒฐ๊ณผ ๋“ฑ์— ์˜ํ•ด) ์‚ฌ๋žŒ๋“ค์ด ํฐ ๋ถˆํŽธ์„ ๋А๋ผ์ง€ ์•Š๋Š”๋‹ค๊ณ  ํ•  ์ˆ˜ ์žˆ์œผ๋ฉฐ ํ™๋ณด์ ์ธ ์ธก๋ฉด์—์„œ๋„ ํŽ˜์ด์ง€๋กœ ์ ‘์†ํ•˜๋Š” active ์‚ฌ์šฉ์ž ์ˆ˜๊ฐ€ ๋งŽ๋‹ค๋Š” ๊ฒƒ๊ณผ ํ•œ๊ตญ์–ด๋กœ ์ง€์›๋˜๋Š” ๊ณค์ถฉ ์Œ์‹ ์›น ์‚ฌ์ดํŠธ๋กœ๋Š” ์ตœ์ดˆ๋ผ๋Š” ์ ์—์„œ ๋‹น์ดˆ ์›ํ–ˆ๋˜ ํ™๋ณด ํšจ๊ณผ๋ฅผ ๋‹ฌ์„ฑํ•  ๊ฒƒ์œผ๋กœ ์ƒ๊ฐ๋œ๋‹ค. **4.4.2 ์•„์ด๋””์–ด์™€ ๊ธฐ๋Œ€๋˜๋Š” ํšจ๊ณผ์˜ ํ•œ๊ณ„์ ** ๋‹จ์ˆœํžˆ ํŽ˜์ด์ง€๋ฅผ ๊ธฐ์ˆ ์ ์œผ๋กœ ์ž˜ ๊ตฌํ˜„ํ•˜๋Š” ๊ฒƒ๊ณผ๋Š” ๋ณ„๊ฐœ๋กœ ๋งˆ์ผ€ํŒ…์  ์š”์†Œ๊ฐ€ ๋ฐ˜๋“œ์‹œ ๋“ค์–ด๊ฐ€์•ผ ์ •๋ง๋กœ ์›ํ•˜๋Š” ๋ชฉ์ ์ธ โ€˜๊ณค์ถฉ์— ๋Œ€ํ•œ ์ธ์‹ ๊ฐœ์„ ์„ ์œ„ํ•œ ํ™๋ณดโ€™์— ๊ธฐ์—ฌํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ์œผ๋กœ ๋ณด์ธ๋‹ค. ์ฆ‰ ๋””์ง€ํ„ธ๋งˆ์ผ€ํŒ…๊ณผ์˜ ๊ฒฐํ•ฉ์˜ ํ•„์š”์„ฑ์ด ์ œ๊ธฐ๋จ. ํ–ฅํ›„ SNS์™€์˜ ์—ฐ๋™ ๊ธฐ๋Šฅ ๋“ฑ์„ ์ถ”๊ฐ€ํ•˜์—ฌ ๋ณด์™„ํ•  ์ˆ˜ ์žˆ๋‹ค. <file_sep>๊ณค์ถฉ ์Œ์‹ ํ™๋ณด ๋ฐ ์ •๋ณด ๊ต๋ฅ˜๋ฅผ ์œ„ํ•œ ์›น ํŽ˜์ด์ง€ ์ œ์ž‘ =================== ์ตœ์ข… ๋ณด๊ณ ์„œ ------------- Korea Tech ์ปดํ“จํ„ฐ์‹œ์Šคํ…œ๊ธฐ์ดˆ์„ค๊ณ„ 14์กฐ(์ž„์„์˜, ๊ถŒ๋„ํ˜•) ---------- ๊ฐœ์š” ------------- edible insects์— ๋Œ€ํ•œ ํ™๋ณด ์›น ์‚ฌ์ดํŠธ ๊ตฌ์ถ• ๊ณผ์ œ๋Š” ์ตœ์ข… ์‚ฌ์šฉ์ž์ธ ์š”๋ฆฌ ์ „๋ฌธ๊ฐ€๋“ค ๋ฐ ์ผ๋ฐ˜์ธ๋“ค์˜ ์ •๋ณด ๊ต๋ฅ˜์™€ ์ •๋ณด ์ทจ๋“์„ ์œ„ํ•œ ํ”Œ๋žซํผ์ด ๋˜๋Š” ์›น ํŽ˜์ด์ง€ ์ œ์ž‘ #### <i class="icon-file"></i> ํ•„์š”์„ฑ > - 2050๋…„๊นŒ์ง€ ์„ธ๊ณ„ ์ธ๊ตฌ ์˜ˆ์ƒ์น˜๋Š” 90์–ต์ด๋‹ค. ์ด๋“ค์„ ๋ชจ๋‘ ๋จน์ด๊ธฐ ์œ„ํ•ด์„  ์‹๋Ÿ‰์ƒ์‚ฐ์ด ๊ณฑ์ ˆ๋กœ ๋Š˜์–ด์•ผ ํ•œ๋‹ค๋Š” ํ†ต๊ณ„๊ฐ€ ๋‚˜์˜จ๋‹ค. ์ง€๊ธˆ๋„ 10์–ต๋ช…์˜ ์‚ฌ๋žŒ๋“ค์ด ์‹๋Ÿ‰ ๋ถ€์กฑ ๋ฌธ์ œ๋กœ ๊ตถ์ฃผ๋ฆฌ๊ณ  ์žˆ๋Š” ์ƒํ™ฉ์ด๋‹ค. > - ์†Œ๊ณ ๊ธฐ 1kg์„ ์ƒ์‚ฐํ•˜๊ธฐ ์œ„ํ•ด ํ•„์š”ํ•œ ๊ณก๋ฌผ์˜ ์–‘์ด 10kg์ด๋‹ค. ๋ผ์ง€๊ณ ๊ธฐ 1kg์„ ์–ป๊ธฐ ์œ„ํ•ด์„  5kg์˜ ๊ณก๋ฌผ์ด ํ•„์š”ํ•˜๋‹ค. ๊ทธ๋Ÿฌ๋‚˜ ๊ณค์ถฉ ๊ณ ๊ธฐ๋ฅผ ์–ป๊ธฐ ์œ„ํ•ด์„  ๋‹จ์ง€ 1.7kg์˜ ๊ณก๋ฌผ์ด ํ•„์š”ํ•  ๋ฟ์ด๋‹ค. ์ด๊ฒƒ์ด ๋ฏธ๋ž˜ ์‹๋Ÿ‰ ์ž์›์œผ๋กœ์„œ ๊ณค์ถฉ์„ ๋จน์–ด์•ผ ํ•  ์ฃผ์š”ํ•œ ์ด์œ ์ด๋‹ค. ๊ฒŒ๋‹ค๊ฐ€ ์˜จ์‹คํšจ๊ณผ์˜ ์ฃผ๋ฒ”์ธ ์ „์„ธ๊ณ„ ๋ฉ”ํƒ„ ๋ฐฐ์ถœ๋Ÿ‰์˜ 37%๊ฐ€ ๊ฐ€์ถ•(domestic animals)์—์„œ ๋ฐœ์ƒํ•œ๋‹ค. ๋ฐ˜๋ฉด ๊ณค์ถฉ์˜ CO2 ๋ฐฐ์ถœ๋Ÿ‰์€ ๊ทนํžˆ ๋“œ๋ฌผ๋‹ค. ์†Œ๊ณ ๊ธฐ์—” 50%์˜ ๋‹จ๋ฐฑ์งˆ์ด ์žˆ์œผ๋ฉฐ ๊ทธ ์™ธ์˜ ์ง€๋ฐฉ์งˆ ๋“ฑ์œผ๋กœ ์ด๋ฃจ์–ด์ง„ ๊ณ ์ง€๋ฐฉ ์‹ํ’ˆ์ด๋‹ค. ๋ฐ˜๋ฉด ๊ณค์ถฉ ๊ณ ๊ธฐ๋Š” ๋‹จ๋ฐฑ์งˆ์ด ๋Œ€๋ถ€๋ถ„์ด๋‹ค. ๋”๋ถˆ์–ด ๋น„ํƒ€๋ฏผ, ์ฒ ๋ถ„, ์•„์—ฐ ๋“ฑ์ด ํ’๋ถ€ํ•˜๋‹ค. ์‚ฌ๋žŒ๋“ค์˜ ํŽธ๊ฒฌ๊ณผ๋Š” ๋‹ฌ๋ฆฌ ๊ณค์ถฉ์€ ์ธ์ฒด์— ์น˜๋ช…์ ์ธ ๋ณ‘์›๊ท ์„ ๊ฐ–๊ณ  ์žˆ์ง€ ์•Š์•„ ์†Œ, ๊ฐœ, ๋ผ์ง€๋ณด๋‹ค๋„ ๋œ ํ•ด๋กญ๋‹ค๊ณ  ํ•œ๋‹ค. ์ธ๊ฐ„์ด ์„ญ์ทจ ๊ฐ€๋Šฅํ•œ ๊ณค์ถฉ์˜ ์ข…๋ฅ˜๋Š” 1900์ข…์ด๋‹ค. ๊ทธ๋Ÿฌ๋‚˜ ๊ณค์ถฉ์„ ๋จน๋Š” ๋‚˜๋ผ๋Š” ์•„์‹œ์•„์™€ ์•„ํ”„๋ฆฌ์นด ์ง€์—ญ์— ๊ตญํ•œ๋˜์–ด ์žˆ์œผ๋ฉฐ ์ƒ๋Œ€์ ์œผ๋กœ ์œ ๋Ÿฝ๊ณผ ๋ฉ•์‹œ์ฝ”๋ฅผ ์ œ์™ธํ•œ ์•„๋ฉ”๋ฆฌ์นด ๋Œ€๋ฅ™, ์•„์‹œ์•„ ์ง€์—ญ ์ค‘ ํ•œ๊ตญ๊ณผ ๋Ÿฌ์‹œ์•„ ์ง€์—ญ์€ ์˜ˆ์™ธ์ ์œผ๋กœ ๊ณค์ถฉ ์†Œ๋น„๊ฐ€ ๋‚ฎ๋‹ค. ๊ณค์ถฉ์— ๋Œ€ํ•œ ๋ง‰์—ฐํ•œ ์ธ์‹ ์ด๋ฅผ ํ…Œ๋ฉด ๋ง›์ด ์—†์„ ๊ฒƒ์ด๋ผ๋Š” ์ธ์‹์ด ์ง€๋ฐฐ์ ์ด๊ธฐ ๋•Œ๋ฌธ์œผ๋กœ ๋ณด์ธ๋‹ค. ๊ทธ๋Ÿฌ๋‚˜ ๊ณค์ถฉ์ด ๋ง›์ด ์—†๋‹ค๋Š” ๊ฒƒ์€ ์‹ค์ œ๋กœ๋Š” ๋งž์ง€ ์•Š์œผ๋ฉฐ ๊ณค์ถฉ์— ๋Œ€ํ•œ ์š”๋ฆฌ๋ฒ•์กฐ์ฐจ๋„ ์—†๋‹ค๋Š” ๊ฒƒ์€ ์‚ฌ๋žŒ๋“ค์—๊ฒŒ ๊ณค์ถฉ์ด ์‹๋Ÿ‰์œผ๋กœ์„œ ๋ณด์ด๊ธฐ์— ๋”์šฑ ์–ด๋ ต๊ฒŒ ๋งŒ๋“ ๋‹ค. ์ฐจ์„ธ๋Œ€ ๋ฏธ๋ž˜ ์‹๋Ÿ‰์œผ๋กœ์จ ๊ณค์ถฉ์„ ํ™œ์šฉํ•˜๊ธฐ ์œ„ํ•œ ์š”๋ฆฌ๋ฒ•์„ ์š”๋ฆฌ ๊ด€๋ จ ์ „๋ฌธ๊ฐ€๋“ค์ด ๊ณค์ถฉ์ด๋ผ๋Š” ์ƒ‰๋‹ค๋ฅธ ์žฌ๋ฃŒ์— ๋Œ€ํ•œ ๊ด€์‹ฌ์„ ๊ฐ€์งˆ ์ˆ˜ ์žˆ๊ฒŒ ํ•  ํ•„์š”๊ฐ€ ์žˆ๋‹ค. > - ๊ตญ์™ธ์—์„  ์ด๋ฏธ ๊ณค์ถฉ์— ๋Œ€ํ•œ ์ •๋ณด๋ฅผ ์ œ๊ณตํ•˜๋ฉฐ ํ™๋ณด๋ฅผ ํ•˜๋Š” ์›น ์‚ฌ์ดํŠธ๊ฐ€ ์žˆ์ง€๋งŒ, ๊ตญ๋‚ด์—” ์ „๋ฌดํ•œ ์ƒํƒœ๋‹ค. #### <i class="icon-file"></i> ์ข…๋ž˜๊ธฐ์ˆ  > - ๊ตญ์™ธ์—์„œ๋Š” ๊ณค์ถฉ ์Œ์‹์ด ์ด๋ฏธ ์‹๋Ÿ‰ ๋Œ€์•ˆ์œผ๋กœ ๊ฐ๊ด‘์„ ๋ฐ›๊ณ  ์žˆ๊ณ  ํ˜„์žฌ ํ™œ๋ฐœํ•œ ์ •๋ณด๊ต๋ฅ˜๊ฐ€ ์ด๋ฃจ์–ด ์ง€๊ณ  ์žˆ๋‹ค. > - Girl meets bug(https://edibug.wordpress.com/)์—์„œ๋Š” ๋ธ”๋กœ๊ทธ ํ˜•์‹์˜ ์›น ํŽ˜์ด์ง€๋กœ ๊ฐœ์ธ์ด ๋งŒ๋“  ๊ณค์ถฉ ์š”๋ฆฌ๋‚˜ ๊ด€๋ จ ๊ธฐ์‚ฌ๋“ค์„ ํฌ์ŠคํŠธ ํ•œ๋‹ค. ์ƒ๊ธฐ ์›น ํŽ˜์ด์ง€์˜ ๋ฌธ์ œ์ ์€ ๋ธ”๋กœ๊ทธ ํ˜•์‹์˜ ์›น ํŽ˜์ด์ง€๋กœ ์ผ ๋ฐฉํ–ฅ ์ ์ธ ์ •๋ณด์ œ๊ณต๊ณผ ์‚ฌ์šฉ์ž ์ฐธ์—ฌ๋„๊ฐ€ ๋‚ฎ๋‹ค๋Š” ๊ฒƒ์ด๋‹ค. ๋”ฐ๋ผ์„œ ์ง„์ •ํ•œ ๊ณค์ถฉ ์ •๋ณด ๊ตํ™˜์˜ ํ”Œ๋žซํผ์œผ๋กœ ์‚ฌ์šฉ๋˜๊ธฐ์—” ๋งŽ์€ ๋ถ€์กฑํ•จ์ด ์žˆ์–ด ๋ณด์ธ๋‹ค. > - ๊ตญ์™ธ ๋น„์˜๋ฆฌ๋‹จ์ฒด์ธ fao(http://www.fao.org/forestry/edibleinsects/en/)์—์„œ๋„ ๋จน์„ ์ˆ˜ ์žˆ๋Š” ๊ณค์ถฉ์— ๋Œ€ํ•œ ์ˆ˜์ค€ ๋†’์€ ์ •๋ณด๋ฅผ ์ œ๊ณตํ•˜๊ณ  ์žˆ๋‹ค. 1900์—ฌ์ข…์˜ ๋จน์„ ์ˆ˜ ์žˆ๋Š” ๊ณค์ถฉ DB์ œ๊ณต๊ณผ ๊ด€๋ จ ๊ธฐ์‚ฌ๋ฅผ ์ œ๊ณตํ•œ๋‹ค. ํ•˜์ง€๋งŒ ์ƒ๊ธฐ ์›น ํŽ˜์ด์ง€ fao ๋˜ํ•œ, ์ผ ๋ฐฉํ–ฅ ์ ์ธ ์ •๋ณด ์ œ๊ณต์œผ๋กœ ์‚ฌ์šฉ์ž์˜ ์ฐธ์—ฌ๋„๊ฐ€ ๋งค์šฐ ๋‚ฎ์€ ์‹ค์ •์ด๋‹ค. ๋ฌด์—‡๋ณด๋‹ค๋„, ์˜๋ฌธ ํŽ˜์ด์ง€๋กœ ํ•œ๊ตญ ์‚ฌ์šฉ์ž๋“ค์ด ์ด์šฉํ•˜๊ธฐ์—๋Š” ๋งค์šฐ ํž˜๋“ค ๊ฒƒ์œผ๋กœ ์ƒ๊ฐํ•œ๋‹ค. #### <i class="icon-file"></i> ๋ฌธ์ œ ํ•ด๊ฒฐ ์ˆ˜๋‹จ > - ์ƒ๊ธฐ์— ์ œ์‹œ๋œ ์ข…๋ž˜๊ธฐ์ˆ ์˜ ๋ฌธ์ œ์ ์„ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•ด ์‚ฌ์šฉ์ž๊ฐ€ ์ •๋ณด ์ œ๊ณต์ž๊ฐ€ ๋˜๋Š” ๊ณค์ถฉ ์š”๋ฆฌ ํ™๋ณด ๋ฐ ์ •๋ณด๊ต๋ฅ˜๋ฅผ ์œ„ํ•œ ํ”Œ๋žซํผ์ด ๋˜๋Š” ์›น ํŽ˜์ด์ง€๋ฅผ ์ œ๊ณตํ•œ๋‹ค. #### <i class="icon-file"></i> ๊ธฐ๋Œ€ ํšจ๊ณผ > - ๋ณธ ์‹œ์Šคํ…œ ๊ฒฐ๊ณผ๋กœ ์‚ฌ์šฉ์ž๋Š” ์ •๋ณด ์ด์šฉ์ž๊ฐ€ ๋˜๋Š” ๋™์‹œ์— ์ •๋ณด ์ œ๊ณต์ž๊ฐ€ ๋˜๊ณ  ๋งŽ์€ ์ปจํ…์ธ ๋ฅผ ์ œ๊ณตํ•˜์—ฌ ๋งŽ์€ ์‚ฌ์šฉ์ž๋“ค์„ ๋Œ์–ด ๋“ค์ผ ์ˆ˜ ์žˆ์„ ๊ฒƒ์œผ๋กœ ์˜ˆ์ƒ๋˜๋ฉฐ, ๊ณค์ถฉ ์Œ์‹์— ๋Œ€ํ•œ ์ •๋ณด๊ต๋ฅ˜์™€ ํ™๋ณด์— ๋งŽ์€ ํšจ๊ณผ๋ฅผ ์–ป์„ ์ˆ˜ ์žˆ์„ ๊ฒƒ์œผ๋กœ ์ƒ๊ฐํ•œ๋‹ค. ---------- ์š”๊ตฌ์‚ฌํ•ญ ์ •์˜ ------------- #### <i class="icon-file"></i> ์‚ฌ์šฉ์ž ์š”๊ตฌ์‚ฌํ•ญ ์ •์˜ > - ํ•œ๊ตญ์–ด๋กœ ์ œ๊ณต๋˜๋Š” ์›น ์‚ฌ์ดํŠธ์ด์–ด์•ผ ํ•œ๋‹ค. > - ์‚ฌ์šฉ์ž์—๊ฒŒ ์›ํ•˜๋Š” ๊ฐ€์žฅ ์ตœ์‹  ์ •๋ณด๊ฐ€ ์‰ฝ๊ฒŒ ๋…ธ์ถœ๋˜์–ด์•ผ ํ•œ๋‹ค. > - ๊ณค์ถฉ ์Œ์‹๋“ค์˜ ๋‹ค์–‘ํ•œ ์ •๋ณด๊ฐ€ ์ œ๊ณต๋˜์–ด์•ผ ํ•œ๋‹ค. > - ๊ณค์ถฉ ์Œ์‹์˜ ๋‹ค์–‘ํ•œ ๋ง›์ง‘๋“ค์ด ์†Œ๊ฐœ ๋˜์–ด์•ผ ํ•œ๋‹ค. > - ํ™œ๋ฐœํ•œ ํ™œ๋™์— ๋Œ€ํ•œ ๋ณด์ƒ์ด ์žˆ์–ด์•ผ ํ•œ๋‹ค. > - ๋‹ค๋ฅธ ์‚ฌ์šฉ์ž๋“ค๊ณผ ํ™œ๋ฐœํ•œ ๊ต๋ฅ˜๊ฐ€ ์ด๋ฃจ์–ด ์ ธ์•ผ ํ•œ๋‹ค. > - ๋จน์„ ์ˆ˜ ์žˆ๋Š” ๊ณค์ถฉ์— ๋Œ€ํ•œ DB๊ฐ€ ์ œ๊ณต๋˜์–ด์•ผ ํ•œ๋‹ค. #### <i class="icon-file"></i> ์‹œ์Šคํ…œ ์š”๊ตฌ์‚ฌํ•ญ ์ •์˜ > - ์›น ํŽ˜์ด์ง€๋Š” ํ•œ๊ตญ์–ด๋กœ ์ œ๊ณตํ•œ๋‹ค. > - ์‚ฌ์šฉ์ž๊ฐ€ ์›ํ•˜๋Š” ์ตœ์‹  ์ •๋ณด๋ฅผ ์ œ๊ณตํ•  ์ˆ˜ ์žˆ๋„๋ก ์ถ”์ฒœ ์ˆ˜๊ฐ€ ๋†’์€ ๊ฒŒ์‹œ๋ฌผ์€ ์ถ”์ฒœ ๊ฒŒ์‹œํŒ์œผ๋กœ ์ด๋™์‹œ์ผœ ์žฌ ๊ฐœ์‹œํ•œ๋‹ค. > - ๊ณค์ถฉ์Œ์‹๋“ค์˜ ๋‹ค์–‘ํ•œ ์ •๋ณด๊ฐ€ ์ œ๊ณต๋  ์ˆ˜ ์žˆ๋„๋ก ๊ด€๋ จ ๋‰ด์Šค๋“ค์„ ๋ฒˆ์—ญํ•œ ๊ฒŒ์‹œํŒ์„ ์ œ๊ณตํ•œ๋‹ค. > - ๊ณค์ถฉ ์Œ์‹์˜ ๋‹ค์–‘ํ•œ ๋ง›์ง‘๋“ค์ด ์†Œ๊ฐœ๋  ์ˆ˜ ์žˆ๋„๋ก ๋ง›์ง‘ ์†Œ๊ฐœ ๊ฒŒ์‹œํŒ์„ ์ œ๊ณตํ•œ๋‹ค. > - ํ™œ๋ฐœํ•œ ํ™œ๋™์— ๋Œ€ํ•œ ๋ณด์ƒ์œผ๋กœ ๋ ˆ๋ฒจ ์ฒด๊ณ„๋ฅผ ์ œ๊ณตํ•œ๋‹ค. > - ๋‹ค๋ฅธ ์‚ฌ์šฉ์ž๋“ค๊ณผ ํ™œ๋ฐœํ•œ ๊ต๋ฅ˜๋ฅผ ์œ„ํ•˜์—ฌ ๊ณค์ถฉ ์š”๋ฆฌ ๋Œ€ํšŒ๋ฅผ ๊ฐœ์ตœํ•œ๋‹ค. > - ๋‹ค๋ฅธ ์‚ฌ์šฉ์ž๋“ค๊ณผ ํ™œ๋ฐœํ•œ ๊ต๋ฅ˜๋ฅผ ์œ„ํ•˜์—ฌ ๊ฒŒ์‹œ๊ธ€์— ๋ง๊ธ€์„ ๋‹ฌ ์ˆ˜ ์žˆ๊ฒŒ ํ•œ๋‹ค. > - ๋จน์„ ์ˆ˜ ์žˆ๋Š” ๊ณค์ถฉ์˜ DB๋ฅผ ์ œ๊ณตํ•˜๋Š” ํŽ˜์ด์ง€๋ฅผ ์ œ์ž‘ํ•œ๋‹ค. ---------- ์‹œ์Šคํ…œ ์ƒ์„ธ ์„ค๊ณ„ ------------- #### <i class="icon-file"></i> ์‹œ์Šคํ…œ ๊ตฌ์กฐ ![ํ…์ŠคํŠธ](http://1.bp.blogspot.com/-XVHBaLBHBNA/Vmq_AUyCp8I/AAAAAAAAESg/cWqF_l6lEuQ/s1600/0.PNG) >- ๊ณค์ถฉ ์Œ์‹ ํ™๋ณด๋ฅผ ๋ฐ ์ •๋ณด๊ต๋ฅ˜๋ฅผ ์œ„ํ•œ ํ”Œ๋žซํผ์„ ์ œ๊ณตํ•˜๋Š” ์›น ํŽ˜์ด์ง€๋Š” ์ด 5๊ฐœ์˜ ๋ชจ๋“ˆ๋กœ ๊ตฌ์„ฑ๋˜์–ด ์žˆ์œผ๋ฉฐ ๊ฐ๊ฐ์˜ ๋ชจ๋“ˆ์€ ์„œ๋กœ ๋‹ค๋ฅธ ์ปจํŠธ๋กค๋Ÿฌ์˜ ์ œ์–ด๋ฅผ ๋ฐ›๋Š”๋‹ค. ๊ณค์ถฉ ์Œ์‹ ๋ฐฐํ‹€ ๋ชจ๋“ˆ์€ ์‚ฌ์šฉ์ž๋“ค์ด ์„œ๋กœ์˜ ๊ณค์ถฉ ๋ ˆ์‹œํ”ผ๋ฅผ ๊ฒŒ์‹œํ•˜์—ฌ ์ถ”์ฒœ ์ˆ˜๋กœ ๋Œ€๊ฒฐ์„ ํ•˜๋Š” ์ผ์ข…์˜ ๊ฒŒ์‹œํŒ์ด๋‹ค. ๊ณค์ถฉ ์Œ์‹ ๋ชจ๋“ˆ์€ 1900์—ฌ๊ฐœ์˜ ๋จน์„ ์ˆ˜ ์žˆ๋Š” ๊ณค์ถฉ์— ๋Œ€ํ•œ ๋ฐ์ดํ„ฐ๋ฅผ ์ œ๊ณตํ•œ๋‹ค. ๋ฏธ๋””์–ด ๊ฒŒ์‹œํŒ์€ ์‚ฌ์šฉ์ž๋“ค์ด ๊ด€๋ จ ๋‰ด์Šค์™€ ๋™์˜์ƒ ๋“ฑ์„ ๊ฒŒ์‹œํ•˜๋ฉฐ ์ •๋ณด๋ฅผ ๊ต๋ฅ˜ํ•˜๋Š” ๋ชจ๋“ˆ์ด๋‹ค. ๋ง›์ง‘ ์†Œ๊ฐœ ๋ชจ๋“ˆ์€ ๊ณค์ถฉ ์Œ์‹์˜ ๋ง›์ง‘์„ ์†Œ๊ฐœํ•˜๋Š” ํŽ˜์ด์ง€์ด๋‹ค. ์„œ๋ฒ„ ๋ชจ๋“ˆ์€ ์‚ฌ์šฉ์ž๋“ค์˜ ๋ ˆ๋ฒจ ๋“ฑ๊ณผ ๊ฐ™์€ ์‚ฌ์šฉ์ž์˜ ์ •๋ณด๋ฅผ ๊ด€๋ฆฌํ•˜๋Š” ๋ชจ๋“ˆ๊ณผ ๊ฒŒ์‹œํŒ์˜ ๊ธ€ ์ •๋ณด ๋“ฑ์˜ ๋ฐ์ดํ„ฐ๋ฅผ ๊ด€๋ฆฌํ•˜๋Š” ๊ฒŒ์‹œํŒ ๋ฐ์ดํ„ฐ ๊ด€๋ฆฌ ๋ชจ๋“ˆ๋กœ ๊ตฌ์„ฑ๋œ ๋ชจ๋“ˆ์ด๋‹ค. #### <i class="icon-file"></i> ๊ณค์ถฉ DB ๊ณค์ถฉ DB๋Š” 1900๊ฐœ์˜ ๋จน์„ ์ˆ˜ ์žˆ๋Š” ๊ณค์ถฉ๋“ค์— ๋Œ€ํ•œ ๋ฐ์ดํ„ฐ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ œ๊ณตํ•˜๋Š” ๋ชจ๋“ˆ์ด๋‹ค. ๊ณค์ถฉ ์ข…๋ฅ˜๋ณ„ ์ด๋ฆ„ ๋ณ„, ์„œ์‹ ์ง€์—ญ ๋ณ„๋กœ ํ•„ํ„ฐ ๋ง ํ•˜๊ณ  ๊ฒ€์ƒ‰ํ•˜๋Š” ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•˜๊ณ  ํด๋ฆญํ•˜๋ฉด ์ƒ์„ธ ์ •๋ณด๋ฅผ ์—ด๋žŒ ํ•  ์ˆ˜ ์žˆ๋‹ค. ์ƒ์„ธ ์ •๋ณด์—๋Š” ๊ณค์ถฉ์˜ ์ข…, ์†, ๊ณผ, ์„œ์‹ ์ง€์—ญ, ์ด๋ฆ„, description, ๋น„๊ณ , ์ƒ ๊ทธ๋ฆฌ๊ณ  ์ด๋ฏธ์ง€ ๋“ฑ์˜ ์ •๋ณด๋ฅผ ์ œ๊ณตํ•œ๋‹ค. ๋ ˆ์‹œํ”ผ๊ฐ€ ์กด์žฌํ•˜๋Š” ๊ณค์ถฉ์ด๋ผ๋ฉด ๋งํฌ ์ฃผ์†Œ๋ฅผ ํ•˜์ด๋ผ์ดํŠธ ํ•˜์—ฌ ๋” ๋งŽ์€ ์กฐํšŒ์ˆ˜๋ฅผ ์˜ฌ์˜ฌ ์ˆ˜ ์žˆ๋Š” ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•œ๋‹ค. > **๊ฐœ์š”:** > >- ๊ณค์ถฉ DB์˜ ๋ชจ๋“ˆ์€ ์•„๋ž˜์™€ ๊ฐ™์€ ๊ตฌ์กฐ๋ฅผ ๊ฐ€์ง„๋‹ค. > **Figure 2๊ณค์ถฉ DB ๊ตฌ์กฐ:** ![ํ…์ŠคํŠธ](http://2.bp.blogspot.com/-K4yr31d0YzA/VmrBiA3PZfI/AAAAAAAAESs/aQHJEN1XD-U/s1600/1.PNG) > **ํ๋ฆ„๋„:** ![ํ…์ŠคํŠธ](http://2.bp.blogspot.com/-Sqhn37uTxUE/Vmq-rYgyd7I/AAAAAAAAERQ/SOxdE1kbJrc/s1600/2.PNG) > - SQL ์„œ๋ฒ„๋Š” ์š”์ฒญ์— ๋Œ€ํ•œ ์‘๋‹ต์œผ๋กœ DB ํŒŒ์ผ์„ ์ „์†กํ•œ๋‹ค. > - DB-> Json converter๋Š” ์ด ํŒŒ์ผ์„ JSON ํŒŒ์ผํ˜•์‹์œผ๋กœ ๋‹ค์‹œ ์ž‘์„ฑํ•œ ํ›„ ์›น์— ์ถœ๋ ฅํ•œ๋‹ค. > - ์‚ฌ์šฉ์ž์—๊ฒŒ ๋ฐ์ดํ„ฐ๋ฅผ ์ถœ๋ ฅํ•œ ํ›„ ์ž…๋ ฅ์„ ๋ฐ›๋Š”๋‹ค. > - ๊ณค์ถฉ์ด๋ฆ„์— ์—ฐ๊ฒฐ๋œ Link๋ฅผ ๋ˆ„๋ฅด๋ฉด ๊ณค์ถฉ ์ƒ์„ธ ๋””์Šคํฌ๋ฆฝ์…˜ ํŽ˜์ด์ง€๋กœ ๋„˜์–ด๊ฐ„ ํ›„ ๋ฐ์ดํ„ฐ๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค. > - ๋‹ค๋ฅธ ๋ชจ๋“ˆ์˜ Url์„ ํด๋ฆญํ•˜๋ฉด ๋‹ค๋ฅธ ํŽ˜์ด์ง€๋กœ ๋„˜์–ด๊ฐ€ ๊ทธ ๋ชจ๋“ˆ์˜ ์ œ์–ด๋ฅผ ๋ฐ›๋Š”๋‹ค. **์ธํ„ฐํŽ˜์ด์Šค:** Get_insects_db_sumarry() >- ํ•จ์ˆ˜ ์ •์˜ Def Get_insects_db_sumarry (); >- ์„ค๋ช… ์„œ๋ฒ„์— ๊ณค์ถฉ DB list๋ฅผ ์š”์ฒญํ•˜๋Š” ํ•จ์ˆ˜ >- ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฏธํ„ฐ ![ํ…์ŠคํŠธ](http://1.bp.blogspot.com/-LuGZ2WBk5Wg/VmrBkxp1szI/AAAAAAAAET8/MLVut7qwwvo/s1600/2.PNG) >- ๋ฐ˜ํ™˜ํƒ€์ž… ![ํ…์ŠคํŠธ](http://2.bp.blogspot.com/-izuRr1Uuc7o/VmrBnhzyWWI/AAAAAAAAEU0/YHRfxb1TXJA/s1600/3.PNG) Convert_to_json() >- ํ•จ์ˆ˜ ์ •์˜ Def Conver_to_json(raw_db_file) >- ์„ค๋ช… ์„œ๋ฒ„์—์„œ ๋ณด๋‚ด์˜จ DB๋ฅผ json ํŒŒ์ผ๋กœ ๋ณ€ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜ >- ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฏธํ„ฐ ![ํ…์ŠคํŠธ](http://3.bp.blogspot.com/-DzsoOvyDY4c/VmrBqIdeFVI/AAAAAAAAEV8/l488lTCs61A/s1600/4.PNG) >- ๋ฐ˜ํ™˜ํƒ€์ž… ![ํ…์ŠคํŠธ](http://4.bp.blogspot.com/-0bpFWreEhDk/VmrBrKy7ZCI/AAAAAAAAEWg/hNzAezI9VHw/s1600/5.PNG) Print_data() >- ํ•จ์ˆ˜ ์ •์˜ Def print_data(Json_list) >- ์„ค๋ช… Json ํŒŒ์ผ์„ ์‹œ๊ฐ์ ์œผ๋กœ ์ถœ๋ ฅํ•˜๊ธฐ ์œ„ํ•œ ํ•จ์ˆ˜. ๋ฐ์ดํ„ฐ๋ฅผ ์˜ˆ์˜๊ฒŒ ์ถœ๋ ฅํ•œ๋‹ค. >- ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฏธํ„ฐ ![ํ…์ŠคํŠธ](http://1.bp.blogspot.com/-LVY0KwIqn84/VmrBrXqugZI/AAAAAAAAEWk/_kYH9ivodfY/s1600/6.PNG) >- ๋ฐ˜ํ™˜ํƒ€์ž… ![ํ…์ŠคํŠธ](http://3.bp.blogspot.com/-zZ4UICXGDns/VmrBrYE3y5I/AAAAAAAAEWo/mx-CB5uH4c0/s1600/7.PNG) Route_Url() >- ํ•จ์ˆ˜ ์ •์˜ Def route_url(url) >- ์„ค๋ช… ์‚ฌ์šฉ์ž ์ž…๋ ฅ์— ๋”ฐ๋ฅธ ๋ผ์šฐํŒ… ๊ธฐ๋Šฅ ์ œ๊ณต. ์ƒ์„ธ ๋””์Šคํฌ๋ฆฝ์…˜์ด๋‚˜ ๋‹ค๋ฅธ ๋ชจ๋“ˆ๋กœ ๋ผ์šฐํŒ…๊ธฐ๋Šฅ ์ œ๊ณต >- ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฏธํ„ฐ ![ํ…์ŠคํŠธ](http://1.bp.blogspot.com/-JA14m_9tOP8/VmrBrrnGWcI/AAAAAAAAEWw/wOXSjKkdn8E/s1600/8.PNG) >- ๋ฐ˜ํ™˜ํƒ€์ž… ![ํ…์ŠคํŠธ](http://1.bp.blogspot.com/-9Sz1fIJmjB8/VmrBr_aSOWI/AAAAAAAAEW0/nOrDL8snCT8/s1600/9.PNG) Get_insects_db_detail() >- ํ•จ์ˆ˜ ์ •์˜ Def Get_insects_db_detail (index) >- ์„ค๋ช… ๊ณค์ถฉ ๋ฐ์ดํ„ฐ ๋ฒ ์ด์Šค ์š”์ฒญ >- ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฏธํ„ฐ ![ํ…์ŠคํŠธ](http://1.bp.blogspot.com/-OIk34UG242U/VmrBiCeSxJI/AAAAAAAAES0/RpWbusssdlQ/s1600/10.PNG) >- ๋ฐ˜ํ™˜ํƒ€์ž… ![ํ…์ŠคํŠธ](http://4.bp.blogspot.com/-XCkYmatyT4c/VmrBiL4FmSI/AAAAAAAAESw/zdTIeK8Hs_o/s1600/11.PNG) Route_to_other_modules() >- ํ•จ์ˆ˜ ์ •์˜ Def Route_to_other_modules (url) >- ์„ค๋ช… ๋‹ค๋ฅธ ๋ชจ๋“ˆ๋กœ ๋ผ์šฐํŒ… ํ•˜๋Š” ํ•จ์ˆ˜ >- ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฏธํ„ฐ ![ํ…์ŠคํŠธ](http://1.bp.blogspot.com/-0XaXYlcuQ2o/VmrBiskGs-I/AAAAAAAAES4/Q9kgTyrqg_Q/s1600/12.PNG) >- ๋ฐ˜ํ™˜ํƒ€์ž… ![ํ…์ŠคํŠธ](http://4.bp.blogspot.com/-2jpZcbs5R7U/VmrBi-_kRPI/AAAAAAAAES8/yTT3ElGgtto/s1600/13.PNG) #### <i class="icon-file"></i> ๋ฏธ๋””์–ด ๊ฒŒ์‹œํŒ ๋ฏธ๋””์–ด ๊ฒŒ์‹œํŒ์€ ๊ณค์ถฉ์˜ ๋ ˆ์‹œํ”ผ๋‚˜ ๊ฐ์ข… ์ด์Šˆ๋“ค์— ๋Œ€ํ•œ ์ •๋ณด๊ต๋ฅ˜๋ฅผ ๋ชฉ์ ์œผ๋กœ ํ•˜๋Š” ์ผ์ข…์˜ ๊ฒŒ์‹œํŒ์ด๋‹ค. ๋กœ๊ทธ์ธํ•œ ์‚ฌ์šฉ์ž๋Š” ๊ธ€์„ ๊ฒŒ์‹œํ•  ์ˆ˜ ์žˆ์œผ๋ฉฐ, ์ž์‹ ์˜ ๊ธ€์„ ์ˆ˜์ • ๋ฐ ์‚ญ์ œํ•  ์ˆ˜ ์žˆ๋‹ค. ๋˜ํ•œ ํƒ€์ธ์˜ ๊ธ€์„ ์ถ”์ฒœํ•  ์ˆ˜ ์žˆ๋Š” ๊ธฐ๋Šฅ์ด ์žˆ๋‹ค. ์ถ”์ฒœ์ˆ˜๊ฐ€ ๋†’์€ ๊ธ€์€ ์ถ”์ฒœ๊ฒŒ์‹œํŒ์œผ๋กœ ์˜ฎ๊ฒจ์ง„๋‹ค. ๋ฏธ๋””์–ด๊ฒŒ์‹œํŒ์€ ๋ ˆ์‹œํ”ผ ๊ฒŒ์‹œํŒ๊ณผ, ๋‰ด์Šค ๋ฐ ๋™์˜์ƒ ๊ฒŒ์‹œํŒ์œผ๋กœ ๊ตฌ์„ฑ๋˜์–ด ์žˆ๋‹ค. ๊ฒŒ์‹œํŒ์€ ๋ˆ„๊ตฌ๋‚˜ ์ ‘๊ทผ ํ•  ์ˆ˜ ์žˆ๋‹ค. > **๊ฐœ์š” ๋ฐ ํ๋ฆ„:** > > **Figure 4 ๋ฏธ๋””์–ด ๊ฒŒ์‹œํŒ ๊ตฌ์กฐ ๋ฐ ๋ฐ์ดํ„ฐ ํ๋ฆ„** ![ํ…์ŠคํŠธ](http://3.bp.blogspot.com/-KhfvVZtgFRw/Vmq-rT1imBI/AAAAAAAAERU/c1K0l5l-NP4/s1600/3.PNG) > - ๊ฒŒ์‹œ๊ธ€ ๋ฐ์ดํ„ฐ๋ฅผ ์š”์ฒญ(get_board_summary()) ๋ฐ›์€ DB ์„œ๋ฒ„๋Š” ๊ฒŒ์‹œํŒ ์ •๋ณด์— ๋Œ€ํ•œ ๋ฐ์ดํ„ฐ(๊ธ€๋ฒˆํ˜ธ, ์กฐํšŒ์ˆ˜, ์ œ๋ชฉ, ์ž‘์„ฑ์ž, ์ถ”์ฒœ์ˆ˜)๋ฅผ ์ „์†กํ•œ๋‹ค. > - SQL -> Json ํŒŒ์ผ ์ปจ๋ฒ„ํ„ฐ๋Š” DBํŒŒ์ผ์„ JsonํŒŒ์ผ๋กœ ์ปจ๋ฒ„ํŒ…(conver_to_json()) ํ•œ๋‹ค. ๊ฒŒ์‹œ๊ธ€ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ถœ๋ ฅํ•œ ํ›„(Print_data()) ์‚ฌ์šฉ์ž ์ž…๋ ฅ์„ ๋ฐ›์•„ ๋‹ค์Œ ํ–‰๋™์„ ๋Œ€๊ธฐํ•œ๋‹ค. > - ๊ฒŒ์‹œ๊ธ€ ๋ฆฌ์ŠคํŠธ๋ฅผ ํด๋ฆญ(get_board_detail(index))ํ•˜๋ฉด ๊ฒŒ์‹œ๊ธ€์— ๋Œ€ํ•œ ์ƒ์„ธ ๋””์Šคํฌ๋ฆฝ์…˜์„ ์ถœ๋ ฅํ•œ๋‹ค. ๋งŒ์•ฝ ํ˜„์žฌ ์‚ฌ์šฉ์ž์™€ ๊ฒŒ์‹œ์ž๊ฐ€ ๋™์ผํ•˜๋ฉด edit()๊ณผ delet()ํ•จ์ˆ˜๋ฅผ ์‹คํ–‰ํ•˜๋Š” ๊ถŒํ•œ์„ ๋ถ€์—ฌํ•œ๋‹ค. > - Edit()์„ ์‹คํ–‰ํ•˜๋ฉด ๋ฐ์ดํ„ฐ๋ฅผ ์ˆ˜์ •ํ•  ์ˆ˜ ์žˆ์œผ๋ฉฐ ์ˆ˜์ •ํ•œ ๋ฐ์ดํ„ฐ๋Š” DB์— ๋ณด๋‚ด์ง€๋ฉฐ ์ดํ›„ ๊ฒŒ์‹œ๊ธ€ ์ƒ์„ธ ๋””์Šคํฌ๋ฆฝ์…˜์œผ๋กœ ๋ผ์šฐํŒ…ํ•œ๋‹ค. > - Delete()๋ฅผ ์‹คํ–‰ํ•˜๋ฉด ๋ฐ์ดํ„ฐ๋ฅผ ์‚ญ์ œํ•˜๊ณ  DB์— ๋ฐ˜์˜ ํ›„ ๊ฒŒ์‹œ๊ธ€ ๋ฆฌ์ŠคํŠธ๋กœ ๋ผ์šฐํŒ…ํ•œ๋‹ค. ๋กœ๊ทธ์ธํ•œ ์‚ฌ์šฉ์ž๋Š” ๊ธ€์„ ์“ธ ์ˆ˜ ์žˆ๋‹ค. > - ๋‹ค๋ฅธ ๋ชจ๋“ˆ๋กœ ๋ผ์šฐํŒ…(route_to_other_modues(url))์„ ํ•˜๋ฉด ํ•ด๋‹น ๋ชจ๋“ˆ๋กœ ์ด๋™ํ•˜๊ณ , ํ•ด๋‹น ๋ชจ๋“ˆ์˜ ์ œ์–ด๋ฅผ ๋ฐ›๊ฒŒ ๋œ๋‹ค. **์ธํ„ฐํŽ˜์ด์Šค:** Get_board_summary() >- ํ•จ์ˆ˜ ์ •์˜ Def get_board_summary() >- ์„ค๋ช… DB์„œ๋ฒ„์— ๊ฒŒ์‹œํŒ ๋ฆฌ์ŠคํŠธ์— ์ •๋ณด๋ฅผ ์š”์ฒญํ•˜๋Š” ํ•จ์ˆ˜(๊ธ€๋ฒˆํ˜ธ, ์ œ๋ชฉ, ๊ธ€์“ด์ด, ์ถ”์ฒœ์ˆ˜, ๋‚ ์งœ) >- ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฏธํ„ฐ ![ํ…์ŠคํŠธ](http://3.bp.blogspot.com/-hhAAvZkW5hE/VmrBjehRo4I/AAAAAAAAETQ/qmmNSFsKla0/s1600/14.PNG) >- ๋ฐ˜ํ™˜ํƒ€์ž… ![ํ…์ŠคํŠธ](http://1.bp.blogspot.com/-r-brWCgosZI/VmrBjhtYa_I/AAAAAAAAETI/tTk7_GI7vIU/s1600/15.PNG) Get_board_detail(i) >- ํ•จ์ˆ˜ ์ •์˜ Def get_board_detail(index) >- ์„ค๋ช… DB ์„œ๋ฒ„์— ์š”์ฒญํ•œ index์— (๊ธ€ ๋ฒˆํ˜ธ) ๋Œ€์‘ํ•˜๋Š” ์ƒ์„ธ ๋””์Šคํฌ๋ฆฝ์…˜์„ ์š”์ฒญํ•˜๋Š” ํ•จ์ˆ˜.(๊ธ€๋ฒˆํ˜ธ, ์ œ๋ชฉ, ๊ธ€์“ด์ด, ์ถ”์ฒœ์ˆ˜, ๋‚ ์งœ, ๋ณธ๋ฌธ) >- ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฏธํ„ฐ ![ํ…์ŠคํŠธ](http://1.bp.blogspot.com/-UZtepv1aBHg/VmrBjkLw_EI/AAAAAAAAETM/q5kTTpqj7vM/s1600/16.PNG) >- ๋ฐ˜ํ™˜ํƒ€์ž… ![ํ…์ŠคํŠธ](http://4.bp.blogspot.com/-x77d0RaiUTg/VmrBkG_LGAI/AAAAAAAAETg/dhYPzXrJtlA/s1600/17.PNG) Convert_to_json() >- ํ•จ์ˆ˜ ์ •์˜ Def convert_to_json(raw_db_file) >- ์„ค๋ช… ์„œ๋ฒ„์—์„œ ๋ฐ›์•„์˜จ DB๋ฅผ JsonํŒŒ์ผ๋กœ ๋ณ€ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜ >- ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฏธํ„ฐ ![ํ…์ŠคํŠธ](http://4.bp.blogspot.com/-Pkpl90Jr48U/VmrBkHxlNdI/AAAAAAAAETc/DMwHJbru_CE/s1600/18.PNG) >- ๋ฐ˜ํ™˜ํƒ€์ž… ![ํ…์ŠคํŠธ](http://2.bp.blogspot.com/-JEymJHQohE8/VmrBkaN8d_I/AAAAAAAAETo/toPWCtlkMhs/s1600/19.PNG) Print_board_list() >- ํ•จ์ˆ˜ ์ •์˜ Def print_board_list(Json_list) >- ์„ค๋ช… ๊ฒŒ์‹œํŒ ์ •๋ณด๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ํ•จ์ˆ˜. ์ œ๋ชฉ, ์ž‘์„ฑ์ž, ๋‚ ์งœ, ๊ธ€ ๋ฒˆํ˜ธ๋ฅผ ์ถœ๋ ฅ >- ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฏธํ„ฐ ![ํ…์ŠคํŠธ](http://1.bp.blogspot.com/-DheRtks2HDk/VmrBlJCjGeI/AAAAAAAAETs/D6IBKniVMls/s1600/20.PNG) >- ๋ฐ˜ํ™˜ํƒ€์ž… ![ํ…์ŠคํŠธ](http://1.bp.blogspot.com/-aC9CrtmYv8U/VmrBlPs4_-I/AAAAAAAAET4/-mZ7J5b4I6s/s1600/21.PNG) Print board_detail() >- ํ•จ์ˆ˜ ์ •์˜ Def print_board_detail(json_list) >- ์„ค๋ช… ๋ณด๊ณ ์ž ํ•˜๋Š” ๊ธ€์„ ์–‘์‹์— ๋งž์ถ”์–ด ์˜ˆ์˜๊ฒŒ ์ถœ๋ ฅํ•˜๋Š” ํ•จ์ˆ˜ >- ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฏธํ„ฐ ![ํ…์ŠคํŠธ](http://4.bp.blogspot.com/-fftwV21Ewxo/VmrBlpfKM0I/AAAAAAAAEUA/Rz794h4Lx4c/s1600/22.PNG) >- ๋ฐ˜ํ™˜ํƒ€์ž… ![ํ…์ŠคํŠธ](http://2.bp.blogspot.com/-8avz-W-4Tfw/VmrBmFdomII/AAAAAAAAEUU/tmUgcScl6Ek/s1600/23.PNG) Route_to_other_modules() >- ํ•จ์ˆ˜ ์ •์˜ Def Route_to_other_modules (url) >- ์„ค๋ช… ๋‹ค๋ฅธ ๋ชจ๋“ˆ๋กœ ๋ผ์šฐํŒ… ํ•˜๋Š” ๊ธฐ๋Šฅ์„ ๊ฐ€์ง„ ํ•จ์ˆ˜.. >- ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฏธํ„ฐ ![ํ…์ŠคํŠธ](http://4.bp.blogspot.com/-pChGEOTG2-g/VmrBl1oJuVI/AAAAAAAAEUQ/BNUiCvrm_2k/s1600/24.PNG) >- ๋ฐ˜ํ™˜ํƒ€์ž… ![ํ…์ŠคํŠธ](http://1.bp.blogspot.com/-DsU81PyPN3I/VmrBmE-_0hI/AAAAAAAAEVA/5ZIAlnFihq0/s1600/25.PNG) Board_write() >- ํ•จ์ˆ˜ ์ •์˜ Def board_write() >- ์„ค๋ช… ๊ฒŒ์‹œํŒ์— ๊ธ€์„ ์˜ฌ๋ฆฌ๋Š” ํ•จ์ˆ˜. ๊ฒŒ์‹œํŒ์— ๊ธ€ ์ž‘์„ฑ์€ ํšŒ์›๋งŒ ํ•  ์ˆ˜ ์žˆ๋‹ค. ํ•จ์ˆ˜์˜ ๊ฒฐ๊ณผ๋กœ DB์„œ๋ฒ„์— ์ƒˆ๋กœ์šด ์ •๋ณด๋ฅผ ์—…๋ฐ์ดํŠธํ•œ๋‹ค. >- ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฏธํ„ฐ ![ํ…์ŠคํŠธ](http://4.bp.blogspot.com/-dCANsMuAKKw/VmrBmdlAEfI/AAAAAAAAEUY/GwfDSkQ1twI/s1600/26.PNG) >- ๋ฐ˜ํ™˜ํƒ€์ž… ![ํ…์ŠคํŠธ](http://3.bp.blogspot.com/-F2_R1wOcIOI/VmrBmkAupOI/AAAAAAAAEUc/kuJ8AywN1XY/s1600/27.PNG) Edit_board() >- ํ•จ์ˆ˜ ์ •์˜ Def edit_board(user_info) >- ์„ค๋ช… ๊ฒŒ์‹œ๊ธ€์„ ์ˆ˜์ •ํ•  ์ˆ˜ ์žˆ๋Š” ๊ธฐ๋Šฅ. ๊ธ€์˜ ์ˆ˜์ •์€ ๊ธ€์˜ ์ž‘์„ฑ์ž์™€ ํ˜„์žฌ ๋กœ๊ทธ์ธํ•œ ์‚ฌ์šฉ์ž๊ฐ€ ์ผ์น˜ํ•  ๋•Œ๋งŒ ํ•จ์ˆ˜๋ฅผ ์‹คํ–‰ ํ•  ์ˆ˜ ์žˆ๋‹ค. >- ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฏธํ„ฐ ![ํ…์ŠคํŠธ](http://2.bp.blogspot.com/-yzKedNLA5cc/VmrBnK6UOcI/AAAAAAAAEUs/80BeMpCzDL4/s1600/28.PNG) >- ๋ฐ˜ํ™˜ํƒ€์ž… ![ํ…์ŠคํŠธ](http://4.bp.blogspot.com/-qCxi9qB1-mk/VmrBnDgNf3I/AAAAAAAAEUo/9IMQkRuKkaM/s1600/29.PNG) #### <i class="icon-file"></i> ๋ง›์ง‘ ์†Œ๊ฐœ ๊ณค์ถฉ ์Œ์‹ ๋ง› ์ง‘์„ ์†Œ๊ฐœํ•  ์ˆ˜ ์žˆ๋Š” ๋ชจ๋“ˆ์ด๋‹ค. ์ด ๋ชจ๋“ˆ์€ ๋ง› ์ง‘์— ์ •๋ณด์— ๋Œ€ํ•œ ์ผ์ข…์˜ ๊ฒŒ์‹œํŒ์œผ๋กœ ๋ณผ ์ˆ˜ ์žˆ์œผ๋ฉฐ, ๊ธ€์„ ๊ฒŒ์‹œํ•  ์ˆ˜ ์žˆ๋Š” ์ฃผ์ฒด๋Š” ๊ณ  ๋ ˆ๋ฒจ ์œ ์ €์ด๋‹ค. ๋ณธ ๋ชจ๋“ˆ์€ 2.2์ ˆ์ธ ๋ฏธ๋””์–ด ๊ฒŒ์‹œํŒ๊ณผ ๋™์ผํ•œ ๊ตฌ์กฐ์ด๊ธฐ ๋•Œ๋ฌธ์— ๊ตฌ์กฐ๋Š” ์ƒ๋žตํ•˜๊ณ , ๋ ˆ๋ฒจ ์—… ์ฒด๊ณ„์— ๋Œ€ํ•ด์„œ ์„ค๋ช…ํ•  ๊ฒƒ์ด๋‹ค. > **๊ฐœ์š”:** > > ๋‹ค์Œ ๊ทธ๋ฆผ์€ ๋ณธ ์›น์‚ฌ์ดํŠธ์˜ ๋ ˆ๋ฒจ ์—… ์ฒด๊ณ„์ด๋‹ค. ์ด 4๊ฐœ์˜ ๋‹จ๊ณ„๋กœ ๋‚˜๋‰˜๋ฉฐ, ๋กœ๊ทธ์ธ ํšŸ์ˆ˜ ๋ฐ ๊ฒŒ์‹œ ๊ธ€ ๊ฐœ์ˆ˜, ์ถ”์ฒœ ๊ฐœ์ˆ˜ ๋“ฑ ํ™œ๋™ ์ ์ˆ˜๋ฅผ ์˜ฌ๋ ค ๊ฒฝํ—˜์น˜๋ฅผ ์–ป๊ฒŒ ๋œ๋‹ค. ์‚ฌ์šฉ์ž์˜ ์ž๋ฐœ์ ์ธ ์ฐธ์—ฌ๋ฅผ ์œ„ํ•œ ์ผ์ข…์˜ ๋„๊ตฌ์ด๋‹ค. > > **Figure 5 ์›น์‚ฌ์ดํŠธ ๋ ˆ๋ฒจ์—… ์ฒด๊ณ„** ![ํ…์ŠคํŠธ](http://3.bp.blogspot.com/-i25gfOT7Nk8/Vmq-rwrqEPI/AAAAAAAAERc/2YA6lMOVs5k/s1600/4.PNG) > > **๊ฐ ๋ ˆ๋ฒจ ๋ณ„ ์š”๊ตฌ์‚ฌํ•ญ ๋ฐ ๊ธฐ๋Šฅ** ![ํ…์ŠคํŠธ](http://1.bp.blogspot.com/-HQdg1t7NJxM/VmrBnshavDI/AAAAAAAAEU8/heiVarUdRAE/s1600/30.PNG) > **๊ฒฝํ—˜์น˜ ํš๋“ ๊ฒฝ๋กœ** > > - ๋กœ๊ทธ์ธ์‹œ 3์  ํš๋“. 1์ผ 1ํšŒ > - ๊ฒŒ์‹œํŒ์— ๊ธ€ ๋“ฑ๋ก ์‹œ 3์  ํš๋“. 1์ผ 3ํšŒ > - ๋Œ“๊ธ€ ์ž‘์„ฑ์‹œ 1์  ํš๋“. 1์ผ 10ํšŒ > - ์ถ”์ฒœ ๋ฐ›์„ ์‹œ 1์  ํš๋“ > - ๊ธฐํƒ€. ์ด๋ฒคํŠธ ์ฐธ์—ฌ์‹œ ์ ์ˆ˜ ๋ถ€์—ฌ #### <i class="icon-file"></i> ์ฒœํ•˜์ œ์ผ ๊ณค์ถฉ์Œ์‹ ๋Œ€ํšŒ ์ฒœํ•˜์ œ์ผ ๊ณค์ถฉ์Œ์‹ ๋Œ€ํšŒ๋Š” ์‚ฌ์šฉ์ž์˜ ์ฐธ์—ฌ๋ฅผ ์œ ๋„ํ•˜๋ฉฐ, ๊ณค์ถฉ ์Œ์‹์— ๊ด€ํ•œ ํ™œ๋ฐœํ•œ ์ •๋ณด๊ต๋ฅ˜๋ฅผ ์ด‰์ง„์‹œํ‚ค๊ธฐ ์œ„ํ•œ ๋ชจ๋“ˆ์ด๋‹ค. ์ฐธ๊ฐ€์ž๋Š” ์‚ฌ์ „์— ๋“ฑ๋ก์„ ๋ฐ›์œผ๋ฉฐ ๋“ฑ๋กํ•œ ์‚ฌ์šฉ์ž๋Š” ๊ฐ์ž์˜ ๋ ˆ์‹œํ”ผ๋ฅผ ๋“ฑ๋กํ•˜๊ณ  ์„œ๋กœ ๊ฒจ๋ฃฌ๋‹ค. ์Šน์ž๋Š” ์ถ”์ฒœ์ˆ˜๋ฅผ ๋งŽ์ด ๋ฐ›์€ ์œ ์ €๊ฐ€ ์Šน๋ฆฌํ•œ๋‹ค. 1์œ„๋ถ€ํ„ฐ 3์œ„๊นŒ์ง€ ์ˆ˜์ƒ์ž๋ฅผ ๋ฝ‘๋Š”๋‹ค. ์ด ๋ชจ๋“ˆ์— ๋“ค์–ด์˜ค๊ฒŒ ๋˜๋ฉด, ํ˜„์žฌ ์ถ”์ฒœ์ˆ˜๊ฐ€ ๋งŽ์€ ์ˆœ์„œ๋Œ€๋กœ 1๋“ฑ๋ถ€ํ„ฐ 3์œ„๊นŒ์ง€๋ฅผ ์Šคํฌ๋ฆฐ์—์„œ ๋ณผ ์ˆ˜ ์žˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ๊ทธ ์•„๋ž˜ ๋ ˆ์‹œํ”ผ๋ฅผ ๋ณผ ์ˆ˜ ์žˆ๋Š” ๊ฒŒ์‹œํŒ์ด ์žˆ๋‹ค. ๋กœ๊ทธ์ธ ํ•œ ์œ ์ €๋Š” ์ถ”์ฒœ์„ ํ•  ์ˆ˜ ์žˆ๋‹ค. ์ค‘๋ณต ์ถ”์ฒœ์€ ๋ถˆ๊ฐ€๋Šฅ ํ•˜๋‹ค. > **๊ฐœ์š”:** > > ์•„๋ž˜ ๊ทธ๋ฆผ์€ ํ˜„์žฌ ํŽ˜์ด์ง€์— ๋“ค์–ด์™”์„ ์‹œ ์ฒ˜์Œ์œผ๋กœ ๋ณด์—ฌ์ง€๋Š” ํ™”๋ฉด์ด๋‹ค. > > **Figure 6 ๊ณค์ถฉ ์Œ์‹ ๋Œ€ํšŒ ๋ฉ”์ธ** ![ํ…์ŠคํŠธ](http://1.bp.blogspot.com/-6uvo8o8Dahg/Vmq-r4_OwTI/AAAAAAAAERk/9Alt0ngWqr0/s1600/5.PNG) **์ธํ„ฐํŽ˜์ด์Šค:** Get_ranking_board() >- ํ•จ์ˆ˜ ์ •์˜ Def get_ranking_board() >- ์„ค๋ช… DB ์„œ๋ฒ„์—์„œ ๋žญํ‚น๋ณด๋“œ์— ์‚ฌ์šฉํ•  ๋ฐ์ดํ„ฐ๋ฅผ ์š”์ฒญํ•˜๋Š” ํ•จ์ˆ˜. ๋Œ€ํšŒ ์ฐธ๊ฐ€์ž๋“ค์˜ ๊ธ€ ์ •๋ณด๋ฅผ ์š”์ฒญ(์ˆœ์œ„, ์ด๋ฆ„, ์ œ๋ชฉ, ์ถ”์ฒœ์ˆ˜)์ •๋ณด๋ฅผ ํฌํ•จํ•˜๋Š” ๋ฐ์ดํ„ฐ๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค. >- ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฏธํ„ฐ ![ํ…์ŠคํŠธ](http://1.bp.blogspot.com/-052zl0w_Slk/VmrBoffI6CI/AAAAAAAAEVI/fW_WuSv0vu8/s1600/31.PNG) >- ๋ฐ˜ํ™˜ํƒ€์ž… ![ํ…์ŠคํŠธ](http://2.bp.blogspot.com/-xbTrGcG-3wk/VmrBotl8o4I/AAAAAAAAEVM/B3vcPlh-iG0/s1600/32.PNG) Convert_to_Json() >- ํ•จ์ˆ˜ ์ •์˜ Def convert_to_json(raw_db_file) >- ์„ค๋ช… ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์—์„œ ๊ฑด๋‚ด ์ค€ ํŒŒ์ผ์„ JsonํŒŒ์ผ๋กœ ๋ณ€ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜ >- ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฏธํ„ฐ ![ํ…์ŠคํŠธ](http://1.bp.blogspot.com/-YnYvvGFWkpw/VmrBoqb3kwI/AAAAAAAAEVU/_pwFxK6cJTo/s1600/33.PNG) >- ๋ฐ˜ํ™˜ํƒ€์ž… ![ํ…์ŠคํŠธ](http://1.bp.blogspot.com/-LGBf6hPiwqk/VmrBo_92uCI/AAAAAAAAEVQ/NxH8oJfd8Sg/s1600/34.PNG) Print_ranking_board() >- ํ•จ์ˆ˜ ์ •์˜ Def print_ranking_board(Json_list) >- ์„ค๋ช… ์ ์ˆ˜ํŒ์— 1๋“ฑ๋ถ€ํ„ฐ 3๋“ฑ๊นŒ์ง€ ์ถœ๋ ฅํ•˜๋Š” ํ•จ์ˆ˜ >- ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฏธํ„ฐ ![ํ…์ŠคํŠธ](http://1.bp.blogspot.com/-gDYrid0Bz9o/VmrBpPBFv8I/AAAAAAAAEVc/Hk3DzmtcSeE/s1600/35.PNG) >- ๋ฐ˜ํ™˜ํƒ€์ž… ![ํ…์ŠคํŠธ](http://4.bp.blogspot.com/-pLwRNINked8/VmrBpXV8RgI/AAAAAAAAEVg/FbqGK19lcPg/s1600/36.PNG) print_recipe_detail() >- ํ•จ์ˆ˜ ์ •์˜ def print_recipe_lists(recipe_detail) >- ์„ค๋ช… ๋ณด๊ณ ์ž ํ•˜๋Š” ์ฐธ๊ฐ€์ž์˜ ๋ ˆ์‹œํ”ผ๋ฅผ ์–‘์‹์— ๋งž์ถ”์–ด ์˜ˆ์˜๊ฒŒ ์ถœ๋ ฅํ•˜๋Š” ํ•จ์ˆ˜. >- ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฏธํ„ฐ ![ํ…์ŠคํŠธ](http://4.bp.blogspot.com/-ssHwdHtoVQ4/VmrBpa8s4EI/AAAAAAAAEVo/LZL5Bw1CGQA/s1600/37.PNG) >- ๋ฐ˜ํ™˜ํƒ€์ž… ![ํ…์ŠคํŠธ](http://1.bp.blogspot.com/-podkkYZBfjw/VmrBpmjvPuI/AAAAAAAAEWA/Zh4AUolk6m8/s1600/38.PNG) Route_other_modules(url) >- ํ•จ์ˆ˜ ์ •์˜ Def route_other_modules(url) >- ์„ค๋ช… ๋ณด๊ณ ์ž ํ•˜๋Š” ์ฐธ๊ฐ€์ž์˜ ๋ ˆ์‹œํ”ผ๋ฅผ ์–‘์‹์— ๋งž์ถ”์–ด ์˜ˆ์˜๊ฒŒ ์ถœ๋ ฅํ•˜๋Š” ํ•จ์ˆ˜ >- ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฏธํ„ฐ ![ํ…์ŠคํŠธ](http://2.bp.blogspot.com/-ys_L6pVOuyY/VmrBp3YUtDI/AAAAAAAAEV4/gvnAzwQY2JE/s1600/39.PNG) >- ๋ฐ˜ํ™˜ํƒ€์ž… ![ํ…์ŠคํŠธ](http://2.bp.blogspot.com/-wwZzbdPkfnw/VmrBqp9axNI/AAAAAAAAEWM/as5lGtw8yLU/s1600/40.PNG) recommand(index) >- ํ•จ์ˆ˜ ์ •์˜ Def recommend(index) >- ์„ค๋ช… ํด๋ฆญ ์‹œ ์ถ”์ฒœ์ˆ˜๋ฅผ ์˜ฌ๋ฆฌ๊ณ  DB ์„œ๋ฒ„์— ๋ฐ˜์˜ํ•˜๋Š” ํ•จ์ˆ˜ >- ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฏธํ„ฐ ![ํ…์ŠคํŠธ](http://4.bp.blogspot.com/-1gYtBT0Pp7s/VmrBqhpHqbI/AAAAAAAAEWU/nQYiNJu9bZQ/s1600/41.PNG) >- ๋ฐ˜ํ™˜ํƒ€์ž… ![ํ…์ŠคํŠธ](http://4.bp.blogspot.com/-KPBYNqfFIHU/VmrBqg-ZF4I/AAAAAAAAEWQ/y7L0pen0yqo/s1600/42.PNG) ---------- ํ‰๊ฐ€ ๋ฐ ํ‰๊ฐ€ ๊ณ„ํš ------------- #### <i class="icon-file"></i> ํ‰๊ฐ€ ๋„๊ตฌ ๋ฐ ๋ฒ”์œ„ ๋ณธ ์‹œ์Šคํ…œ์˜ ํ‰๊ฐ€๋ฅผ ์œ„ํ•˜์—ฌ ์„ธ ๊ฐ€์ง€ ํ‰๊ฐ€ ์ง€ํ‘œ๋ฅผ ์ด์šฉํ•  ๊ณ„ํš์ด๋‹ค. ์ฒซ ๋ฒˆ์งธ๋Š” ์„ค๋ฌธ์กฐ์‚ฌ๋ฅผ ์‹ค์‹œํ•˜์—ฌ ์„œ๋น„์Šค์˜ ๋งŒ์กฑ๋„ ๋ฐ ๊ฐœ์„ ์  ์กฐ์‚ฌ. ๋‘ ๋ฒˆ์งธ๋Š” Windows์˜ ์‹œ์Šคํ…œ ์„ฑ๋Šฅ ๋ชจ๋‹ˆํ„ฐ๋ง ์„œ๋น„์Šค ๋„๊ตฌ๋ฅผ ์ด์šฉํ•˜์—ฌ ๊ฐ ๋‚ ์งœ ๋ณ„, ํŽ˜์ด์ง€ ๋ ˆ์ด์•„์›ƒ ๋“ฑ์˜ ํ•ญ๋ชฉ์œผ๋กœ ํ‰๊ฐ€๋ฅผ ์‹ค์‹œ, ๋งˆ์ง€๋ง‰์œผ๋กœ wave๋ผ๋Š” ํˆด์„ ์ด์šฉ, ์›น ์ ‘๊ทผ์„ฑ์˜ ํƒ€๋‹น์„ฑ์„ ์กฐ์‚ฌํ•  ๊ฒƒ์ด๋‹ค. #### <i class="icon-file"></i> ์„ค๋ฌธ ์กฐ์‚ฌ ์„ค๋ฌธ์กฐ์‚ฌ ์ˆ˜ํ–‰ ํ›„ ์„ค๋ฌธ์กฐ์‚ฌ ๊ฒฐ๊ณผ์™€ ํ•จ๊ป˜ ์ ‘์†์ž์ˆ˜ ์ธก์ •์„ ํ†ตํ•ด ๊ฒฐ๊ณผ๋ฌผ์„ ๊ทธ๋ž˜ํ”„๋กœ ์‚ฐ์ •ํ•  ๊ณ„ํš์ด๋‹ค. ์•„๋ž˜๋Š” ์„ค๋ฌธ์กฐ์‚ฌ ํ•ญ๋ชฉ์ด๋‹ค. > - Q. ์šฐ๋ฆฌ ์‚ฌ์ดํŠธ๋ฅผ ์‚ฌ์šฉํ•ด ๋ณธ ํ›„ ๊ณค์ถฉ์— ๋Œ€ํ•œ ์ธ์‹์ด ๊ฐœ์„ ๋˜์—ˆ์Šต๋‹ˆ๊นŒ? (1~10์ ) --> ๋ณธ๋ž˜ ๋ชฉ์ ์— ๋Œ€ํ•œ ๋‹ฌ์„ฑ ์—ฌ๋ถ€๋ฅผ ์•Œ๊ธฐ ์œ„ํ•ด > - Q. ์šฐ๋ฆฌ ์‚ฌ์ดํŠธ์—์„œ ๊ณค์ถฉ์— ๋Œ€ํ•œ ์ •๋ณด๋ฅผ ๊ฒ€์ƒ‰ํ•˜๊ธฐ์— ํŽธ๋ฆฌํ•˜์‹ญ๋‹ˆ๊นŒ? (1~10์ ) --> ์‚ฌ์šฉ์ž์—๊ฒŒ ์ œ๊ณตํ•ด์ฃผ๊ณ ์ž ํ•˜๋Š” ๋ฉ”์ธ ๊ธฐ๋Šฅ์ด ์ œ๋Œ€๋กœ ์ž‘๋™ํ•˜๋Š”์ง€ ๋ณด๊ธฐ ์œ„ํ•ด > - Q. ์šฐ๋ฆฌ ์‚ฌ์ดํŠธ์˜ ์ธํ„ฐํŽ˜์ด์Šค์— ๋Œ€ํ•œ ํŽธ์˜์„ฑ ์ •๋„๋ฅผ ์ ์ˆ˜๋กœ ๋งค๊ธด๋‹ค๋ฉด ๋ช‡ ์  ์ •๋„๋ฅผ ์ฃผ์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (1~10์ ) --> UI์šฉ ์งˆ๋ฌธ > - Q. ํ˜„์žฌ ์‚ฌ์šฉ ์ค‘์ธ ๋ธŒ๋ผ์šฐ์ €์˜ ์ข…๋ฅ˜๋Š” ๋ฌด์—‡์ž…๋‹ˆ๊นŒ? (ํฌ๋กฌ,IE,์Šค์œ™,ํŒŒ์ด์–ดํญ์Šค,๊ธฐํƒ€) --> ๋ธŒ๋ผ์šฐ์ € ์ง€์› ์—ฌ๋ถ€ ๊ฒฐ์ •์— ๋„์›€์ด ๋จ > - Q. ๋ชจ๋ฐ”์ผ๋กœ ๋ณธ ์›น ํŽ˜์ด์ง€์— ์ ‘์†ํ–ˆ์„ ๋•Œ์— ๋Œ€ํ•œ ํŽธ์˜์„ฑ ์ •๋„๋ฅผ ์ ์ˆ˜๋กœ ๋งค๊ธด๋‹ค๋ฉด ๋ช‡ ์  ์ •๋„๋ฅผ ์ฃผ์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (1~10์ ) --> ๋ฐ˜์‘ํ˜• ์›น ํŽ˜์ด์ง€ ๊ตฌ์„ฑ ์—ฌ๋ถ€ ๊ฒฐ์ •์— ๋„์›€์ด ๋จ > - Q. [์žฅ์• ์ธ์šฉ] ๋ณธ ์›น ํŽ˜์ด์ง€๋ฅผ ์ด์šฉํ•˜๊ธฐ์— ํŽธ๋ฆฌํ•œ ์ •๋„๋ฅผ ์ ์ˆ˜๋กœ ๋งค๊ฒจ์ฃผ์‹ญ์‹œ์˜ค. (1~10์ ) --> ์›น ์ ‘๊ทผ์„ฑ ํ‘œ์ค€ ์ค€์ˆ˜ ๋Œ€ํ•œ ์‹ค์ œ ์‚ฌ์šฉ์ž ์ฒด๊ฐ ๋ฐ˜์‘ #### <i class="icon-file"></i> windows ์‹œ์Šคํ…œ ์„ฑ๋Šฅ ๋ชจ๋‹ˆํ„ฐ๋ง Windows ์‹œ์Šคํ…œ ์„ฑ๋Šฅ ๋ชจ๋‹ˆํ„ฐ๋ง ๋„๊ตฌ๋ฅผ ์ด์šฉํ•˜์—ฌ ์•„๋ž˜์˜ ํ•ญ๋ชฉ์„ ๊ฒ€์‚ฌํ•œ๋‹ค. > - ์ธํ„ฐํŽ˜์ด์Šค๋ณ„ ์ ‘์†์ž์ˆ˜(ํ•œ ๋‹ฌ) > - ํŽ˜์ด์ง€ ๋ ˆ์ด์•„์›ƒ ๋ณ„ ์ ‘์†์ž์ˆ˜(ํ•œ ๋‹ฌ) > - ์ง€์› ๊ฐ€๋Šฅํ•œ ๋ธŒ๋ผ์šฐ์ €์˜ ๋ฒ”์œ„์— ๋”ฐ๋ฅธ ์ ‘์†์ž์ˆ˜ > - ๋ฐ˜์‘ ํ˜• ์›น ์ง€์› ๊ฐ€๋Šฅ ์—ฌ๋ถ€์— ๋”ฐ๋ฅธ ์ ‘์†์ž์ˆ˜ > - ์›น ์„œ๋ฒ„ ๋ฆฌ์†Œ์Šค ํŒŒ์•…์„ ์œ„ํ•˜์—ฌ ์„ฑ๋Šฅ ๋ชจ๋‹ˆํ„ฐ๋ง์„ ์‚ฌ์šฉ, ์ˆ˜ํ–‰ ๊ฒฐ๊ณผ๋Š” ์•„๋ž˜์™€ ๊ฐ™๋‹ค. ์„ฑ๋Šฅ๋ชจ๋‹ˆํ„ฐ๋ง1 ![ํ…์ŠคํŠธ](http://3.bp.blogspot.com/-pkgZ9_ng0II/Vmq-saQfklI/AAAAAAAAER4/qEvPl0MlEBI/s1600/7.PNG) ์ ‘์†์ž์ˆ˜ ์ถ”์ •์น˜ ![ํ…์ŠคํŠธ](http://1.bp.blogspot.com/-iK5OSDv9QGs/Vmq-suviB_I/AAAAAAAAER0/3NFygXtAENU/s1600/8.png) ์‹œ๊ฐ„๋Œ€๋ณ„ ์ ‘์†์ž์ˆ˜ ![ํ…์ŠคํŠธ](http://4.bp.blogspot.com/-b-xqGYme9j8/Vmq-tEZwhII/AAAAAAAAESA/yIXz4SkZNhM/s1600/9.jpg) ํ–ฅํ›„ ์ ‘์†์ž์ˆ˜ ์ถ”์ • ![ํ…์ŠคํŠธ](http://4.bp.blogspot.com/-pplOjHJjJ_s/Vmq-q6IbZpI/AAAAAAAAERE/P2iWh8HPWmY/s1600/10.png) #### <i class="icon-file"></i> Wave ํˆด ์›น์˜ ์ ‘๊ทผ์„ฑ์„ ํ‰๊ฐ€ํ•˜๊ธฐ ์œ„ํ•œ ๋„๊ตฌ๋กœ waveํˆด์„ ์ด์šฉํ•œ๋‹ค. waveํˆด์„ ์ด์šฉํ•˜์—ฌ ๋‹ค์Œ์˜ ํ•ญ๋ชฉ๋“ค์„ ๊ฒ€์‚ฌํ•  ์˜ˆ์ •์ด๋‹ค. > - ๋Œ€์ฒดํ…์ŠคํŠธ ์ œ๊ณต - ์ œ๋ชฉ์ œ๊ณต - ๊ธฐ๋ณธ์–ธ์–ด ๋ช…์‹œ - ์‚ฌ์šฉ์ž ์š”๊ตฌ์— ๋”ฐ๋ฅธ ์ƒˆ์ฐฝ ์—ด๊ธฐ - ๋ ˆ์ด๋ธ” ์ œ๊ณต - ๋งˆํฌ์—… ์˜ค๋ฅ˜ ๋ฐฉ์ง€ ![ํ…์ŠคํŠธ](http://1.bp.blogspot.com/-H2Kl_lwlqAw/Vmq-q2JxRNI/AAAAAAAAERI/FIS_f2bBebE/s1600/11.png) ์›น ์ ‘๊ทผ์„ฑ ์—ฐ๊ตฌ์†Œ์—์„œ ์ˆ˜ํ–‰ํ•œ ์›น ์ ‘๊ทผ์„ฑ ์ž๋™ ์ ๊ฒ€ ๋ณด๊ณ ์„œ ![ํ…์ŠคํŠธ](http://1.bp.blogspot.com/-yoJTi1mZdjQ/Vmq-rFn002I/AAAAAAAAERM/3MboiUZKgSk/s1600/12.png) #### <i class="icon-file"></i> ๊ธฐ๋Œ€ํšจ๊ณผ์˜ ํƒ€๋‹น์„ฑ ๋ฐ ํ•œ๊ณ„์  > **๊ธฐ๋Œ€ ํšจ๊ณผ์˜ ํƒ€๋‹น์„ฑ** ์›น ํŽ˜์ด์ง€์˜ ์ด์šฉ์„ฑ ์ธก๋ฉด์—์„œ๋Š” (์žฅ์• ์ธ๋“ค๋„ ์›ํ•˜๋Š” ์ •๋ณด๋ฅผ ์–ป์„ ์ˆ˜ ์žˆ์„ ์ •๋„์˜ ์›น ์ ‘๊ทผ์„ฑ ํ‘œ์ค€์„ ๋งŒ์กฑํ•˜๋ฉฐ, ์„ค๋ฌธ์กฐ์‚ฌ๊ฒฐ๊ณผ ๋“ฑ์— ์˜ํ•ด) ์‚ฌ๋žŒ๋“ค์ด ํฐ ๋ถˆํŽธ์„ ๋А๋ผ์ง€ ์•Š๋Š”๋‹ค๊ณ  ํ•  ์ˆ˜ ์žˆ์œผ๋ฉฐ ํ™๋ณด์ ์ธ ์ธก๋ฉด์—์„œ๋„ ํŽ˜์ด์ง€๋กœ ์ ‘์†ํ•˜๋Š” active ์‚ฌ์šฉ์ž ์ˆ˜๊ฐ€ ๋งŽ๋‹ค๋Š” ๊ฒƒ๊ณผ ํ•œ๊ตญ์–ด๋กœ ์ง€์›๋˜๋Š” ๊ณค์ถฉ ์Œ์‹ ์›น ์‚ฌ์ดํŠธ๋กœ๋Š” ์ตœ์ดˆ๋ผ๋Š” ์ ์—์„œ ๋‹น์ดˆ ์›ํ–ˆ๋˜ ํ™๋ณด ํšจ๊ณผ๋ฅผ ๋‹ฌ์„ฑํ•  ๊ฒƒ์œผ๋กœ ์ƒ๊ฐ๋œ๋‹ค. > **์•„์ด๋””์–ด์™€ ๊ธฐ๋Œ€๋˜๋Š” ํšจ๊ณผ์˜ ํ•œ๊ณ„์ ** ๋‹จ์ˆœํžˆ ํŽ˜์ด์ง€๋ฅผ ๊ธฐ์ˆ ์ ์œผ๋กœ ์ž˜ ๊ตฌํ˜„ํ•˜๋Š” ๊ฒƒ๊ณผ๋Š” ๋ณ„๊ฐœ๋กœ ๋งˆ์ผ€ํŒ…์  ์š”์†Œ๊ฐ€ ๋ฐ˜๋“œ์‹œ ๋“ค์–ด๊ฐ€์•ผ ์ •๋ง๋กœ ์›ํ•˜๋Š” ๋ชฉ์ ์ธ โ€˜๊ณค์ถฉ์— ๋Œ€ํ•œ ์ธ์‹ ๊ฐœ์„ ์„ ์œ„ํ•œ ํ™๋ณดโ€™์— ๊ธฐ์—ฌํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ์œผ๋กœ ๋ณด์ธ๋‹ค. ์ฆ‰ ๋””์ง€ํ„ธ๋งˆ์ผ€ํŒ…๊ณผ์˜ ๊ฒฐํ•ฉ์˜ ํ•„์š”์„ฑ์ด ์ œ๊ธฐ๋จ. ํ–ฅํ›„ SNS์™€์˜ ์—ฐ๋™ ๊ธฐ๋Šฅ ๋“ฑ์„ ์ถ”๊ฐ€ํ•˜์—ฌ ๋ณด์™„ํ•  ์ˆ˜ ์žˆ๋‹ค.<file_sep>๋ฌด์ •์ „ ๋ฐฐํ„ฐ๋ฆฌ ๊ต์ฒด ๊ธฐ์ˆ (์ผ€์ด์Šค์— ๊ด€ํ•˜์—ฌ...) -------- _____ ###์„œ๋ก  **๋ฐฐ**ํ„ฐ๋ฆฌ๋ฅผ ๊ต์ฒดํ•  ๋•Œ, ์ „์›์ด ๊บผ์ง€๋Š” ๋ถˆํŽธํ•จ์„ ํ•ด์†Œํ•˜๊ณ  ์‹œ์Šคํ…œ ์žฌ๋ถ€ํŒ… ์‹œ์— ์ „๋ ฅ ์†Œ๋ชจ(์ „์ฒด ๋ฐฐํ„ฐ๋ฆฌ ์šฉ๋Ÿ‰์˜ 2~5%)๋ฅผ ๋ฐฉ์ง€ํ•˜๊ธฐ ์œ„ํ•œ ๊ธฐ์ˆ ์ด๋‹ค. ์ƒ๊ธฐ ์•„์ด๋””์–ด๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์ด์ ์ด ์˜ˆ์ƒ๋œ๋‹ค. * ์ค‘์š”ํ•œ ์ „ํ™”, ๊ฒŒ์ž„ ์‹œ ๋ฌด์ •์ „ ๋ฐฐํ„ฐ๋ฆฌ ๊ต์ฒด. * ์žฌ๋ถ€ํŒ…์— ์†Œ๋ชจ๋˜๋Š” ์ „๋ ฅ ๋ฐฉ์ง€. * ์‹œ์Šคํ…œ์˜ ์žฌ๋ถ€ํŒ…์„ ๋ฐฉ์ง€ํ•จ์œผ๋กœ์จ 10์ดˆ๊ฐ€๋Ÿ‰์˜ ์‹œ๊ฐ„ ์ ˆ์•ฝ. ---------- ###๋ณธ๋ก  **๋‹ค**์Œ๊ณผ ๊ฐ™์€ ๊ตฌ์กฐ๋ฅผ ๊ฐ€์ง„๋‹ค. ![enter image description here](https://lh3.googleusercontent.com/-klSzLVMmpG4/Vjl9AwfTFoI/AAAAAAAAANo/h1scNULlZdc/w346-h213/%25EC%2595%2584%25EC%259D%25B4%25EB%2594%2594%25EC%2596%25B4_%25EA%25B0%259C%25EC%259A%2594%25EB%258F%2584.png) ๋ณด์กฐ ๋ฐฐํ„ฐ๋ฆฌ๊ฐ€ ๋‚ด์žฅ๋œ ํœด๋Œ€ํฐ ์ผ€์ด์Šค ์ƒ์—์„œ ๋ฐฐํ„ฐ๋ฆฌ๋ฅผ ๊ต์ฒดํ•จ์œผ๋กœ์จ, ๋ฌด์ •์ „ ๋ฐฐํ„ฐ๋ฆฌ ๊ต์ฒด๋ฅผ ํ•  ์ˆ˜ ์žˆ๋‹ค. ์ผ€์ด์Šค ์ƒ์—๋Š” ์Šค์œ„์น˜๊ฐ€ ์žˆ์–ด, ํƒˆ์ฐฉ์ด ํ™•์ธ๋˜๋ฉด ๋ณด์กฐ๋ฐฐํ„ฐ๋ฆฌ๋กœ ์Šค๋งˆํŠธํฐ์„ ๊ตฌ๋™ํ•œ๋‹ค. ๋ณด์กฐ๋ฐฐํ„ฐ๋ฆฌ๋Š” ๋™์ž‘ํ•˜์ง€ ์•Š์„ ๋•Œ ์ฃผ ๋ฐฐํ„ฐ๋ฆฌ๋ฅผ ํ†ตํ•ด ์ถฉ์ „์ด ๋œ๋‹ค. _____ ###๊ธฐํƒ€ ----------------------- ###๊ฒฐ๋ก  **์Šค**๋งˆํŠธํฐ์˜ ๋‚ด๋ถ€ ํšŒ๋กœ๋ฅผ ์žฌ๊ตฌ์„ฑํ•˜๊ฑฐ๋‚˜ ์™ธ๊ด€์„ ํ•ด์น˜์ง€ ์•Š์œผ๋ฉด์„œ, ๋ฐฐํ„ฐ๋ฆฌ๋ฅผ ๊ต์ฒดํ•  ์ˆ˜ ์žˆ์–ด ๋งค์šฐ ํŽธ๋ฆฌํ•  ๊ฒƒ์œผ๋กœ ์˜ˆ์ƒ๋œ๋‹ค. ___________ ###๊ด€๋ จ ํŠนํ—ˆ 1. 20-2013-0003519 (2013.05.06.)/๊ฑฐ์ ˆ 2. 10-2012-0055315 (2012.05.24) 3. 10-2014-0015500 (2014.02.11.) 4. 10-2013-0145163 (2013.11.27.) /๊ฑฐ์ ˆ 5. 10-2010-0128751 (2010.12.15.)/๊ฑฐ์ ˆ 6. 10-2013-0083649 (2013.07.16.) 7. 10-2012-0052376 (2012.05.17.) 8. 10-2012-0114009 (2012.10.15.) 9. 10-2014-0128812 (2014.09.26.) 10. 10-2011-0060163 (2011.06.21.) _____________ ###์ฐจ๋ณ„์„ฑ ๋‚ด๋ถ€ํšŒ๋กœ์˜ ์žฌ๊ตฌ์„ฑ ์—†์ด ๊ธฐ์กด์˜ ์Šค๋งˆํŠธํฐ์„ ๊ทธ๋Œ€๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์œผ๋ฉฐ, ์™ธ๊ด€์„ ํ•ด์น˜์ง€ ์•Š๋Š”๋‹ค.<file_sep>'use strict'; /* App Controllers */ var memoryGameApp = angular.module('memoryGameApp', []); memoryGameApp.factory('game', function() { var tileNames = ['8-ball', 'kronos', 'baked-potato', 'dinosaur', 'rocket', 'skinny-unicorn', 'that-guy', 'zeppelin']; return new Game(tileNames); }); memoryGameApp.controller('GameCtrl',function GameCtrl($scope, game, $timeout) { $scope.game = game; $scope.counter = 0; $scope.onTimeout = function(){ $scope.counter++; mytimeout = $timeout($scope.onTimeout,1000); } var mytimeout = $timeout($scope.onTimeout,1000); $scope.check = function(a){ if (a == 0) { $timeout.cancel(mytimeout); }; } }); //usages: //- in the repeater as: <mg-card tile="tile"></mg-card> //- card currently being matched as: <mg-card tile="game.firstPick"></mg-card><file_sep>app.controller('MainController', ['$scope', function($scope) { $scope.today = new Date(); $scope.appetizers = [ { name: 'Caprese', description: 'Mozzarella, tomatoes, basil, balsmaic glaze.', price: 4.95 }, { name: '<NAME>', description: 'Served with marinara sauce.', price: 3.95 }, { name: 'Bruschetta', description: 'Grilled bread garlic', price: 4.95 } ]; $scope.mains = [ { name: 'bread', description: 'Best thing ever', price: 3.99 }, { name: 'shushi', description: 'Best thing ever', price: 12.99 }, { name: 'stake', description: 'Best thing ever', price: 8.99 } ]; $scope.extras = [ { name: 'Coke', description: 'Best thing ever', price: 0.99 }, { name: 'vita 500', description: 'Best thing ever', price: 0.99 }, { name: 'water', description: 'Best thing ever', price: 0.99 } ]; }]);
4c7f611c280d9fe36287052cb6d2780d4c4118b0
[ "Markdown", "JavaScript" ]
6
Markdown
LimEulYoung/git_cowork
5c4c84a26abc794f7a890a866ca0b0c6333cedc5
e627d5d1872efae09c044c1220b7140c0beaf955
refs/heads/master
<file_sep>#!/bin/bash mkdir ~/Desktop/Screenshots defaults write com.apple.menuextra.battery ShowPercent -string "YES" defaults write com.apple.menuextra.battery ShowTime -string "YES" ######################################## # Screen Setings # ######################################### # Screen locking defaults write com.apple.screensaver askForPassword -int 1 defaults write com.apple.screensaver askForPasswordDelay -int 0 # Screenshots defaults write com.apple.screencapture location -string "${HOME}/Desktop/Screenshots" defaults write com.apple.screencapture type -string "jpg" ############################################## # Finder # ############################################## # Show HDDs and Removeable drives on Desktop defaults write com.apple.finder ShowExternalHardDriversOnDesktop -bool true defaults write com.apple.finder ShowHardDrivesOnDesktop -bool true defaults write com.apple.finder ShowRemoveableMediaOnDesktop -bool true # Dock and Dashboard defaults write com.apple.dock mouse-over-hilite-stack -bool true # Set icon size defaults write com.apple.dock tilesize -int 36 # indicator lights defaults write com.apple.dock show-process-indicator -bool true # Automatically hide the dock defaults write com.apple.dock autohide -bool true # Turn on Firewall defaults write /Library/Preferences/com.apple.alf globalstate -int 1<file_sep>#/bin/bash # Start up script for ansible echo =========================== echo "| Mac Setup Started |" echo =========================== echo "Enter the preferred IDE (Eclipse or Intellij): " read IDE echo $IDE # Base line packages if ! [[ -e ~/.ssh/id_rsa ]]; then echo "creating ssh key" ssh-keygen -t rsa -b 4096 -C "<EMAIL>" -N '' ssh-add -K ~/.ssh/id_rsa echo "Add public key to github" pbcopy < ~/.ssh/id_rsa.pub read -p "Press enter to continue." else echo "Key already created" fi xcode-select --install sudo easy_install pip sudo pip install cryptography sudo easy_install ansible sudo pip install ansible-vault ansible-vault encrypt ~/.ssh/id_rsa # creating temp directory for instal installDir="/tmp/setupmac" sshkeyDir = "/Users/"$(whoami)"/Desktop" mkdir $installDir mkdir $sshkeyDir echo "Cloning git repo." git clone -b development https://github.com/smoloney/macsetup.git $installDir if [! $installDir ]; then echo "Failed to find mac setup files." echo "Git clone failed." exit 1 else cd $installDir ansible-playbook -i ./hosts playbook.yml --verbose --extra-vars "ide=$IDE" fi echo "Cleaning up from install." rm -rf $installDir # ~/.ssh/id_rsa ~/.ssh/id_rsa.pub echo "All done! Enjoy your new mac." exit 0<file_sep>todo: fix adding ssh key for github get repos to clone install java and setup config settings
813216f807bfa30c77c34572ed5823358dcd0e15
[ "Text", "Shell" ]
3
Shell
smoloney/macsetup
80a3a1d4ae93da795e228c5a76a6918050e066b2
5798a3be238fb091ab1e7e3179a461a56a0ea567