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>package com.example.studentportal; import android.os.Parcel; import android.os.Parcelable; /** * Dit object bevat een url en een titel */ public class Portal implements Parcelable { private String url; private String titel; public Portal(String url, String titel) { this.url = url; this.titel = titel; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getTitel() { return titel; } public void setTitel(String titel) { this.titel = titel; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.url); dest.writeString(this.titel); } protected Portal(Parcel in) { this.url = in.readString(); this.titel = in.readString(); } public static final Parcelable.Creator<Portal> CREATOR = new Parcelable.Creator<Portal>() { @Override public Portal createFromParcel(Parcel source) { return new Portal(source); } @Override public Portal[] newArray(int size) { return new Portal[size]; } }; }
4a52dee2924c2f752a1c39e1c315e11a40dc3952
[ "Java" ]
1
Java
DyonJacobs/Week3
ede8b89e1132550a6a9e0c91accc30e086a5bf55
ac7ba861f8a87e73a1ec9ca6ba8f7b5b3b0101c8
refs/heads/main
<repo_name>gianlucapes/webapiFuAgency<file_sep>/WebApiFuAgency/Helpers/AppMapper.cs using AutoMapper; using Employee.Entity; using Employee.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebApiFuAgency.Helpers { public class AppMapper : Profile { public AppMapper() { CreateMap<Impiegato, ImpiegatoModel>().ReverseMap(); CreateMap<Dipartimenti, Dipartimenti>().ReverseMap(); } } } <file_sep>/Employee/Repository/IAccountRepository.cs using Employee.Models; using Microsoft.AspNetCore.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Employee.Repository { public interface IAccountRepository { public Task<IdentityResult> SingUp(SignUpModel signUpModel); public Task<String> LoginAsync(SigninModel signinModel); } } <file_sep>/Employee/Entity/Dipartimenti.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Employee.Entity { public class Dipartimenti { [Key] public int GeoCode { get; set; } public string Nome { get; set; } public string Luogo { get; set; } public string Descrizione { get; set; } public string ImmagineDipartimento { get; set; } public Impiegato Leader {get;set;} } } <file_sep>/Employee/Data/RolmexContext.cs using Employee.Entity; using Employee.Models; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Text; namespace Employee.Data { public class RolmexContext : IdentityDbContext<ApplicationUser> { public RolmexContext(DbContextOptions<RolmexContext> option) : base(option) { } public DbSet<Impiegato> Impiegato { get; set; } public DbSet<Dipartimenti> Dipartimenti { get; set; } } } <file_sep>/Employee/Entity/Impiegato.cs using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace Employee.Entity { public class Impiegato { [Key] public int EntrepriseId { get; set; } public string Nome { get; set; } public string Cognome { get; set; } public string Qualifica { get; set; } public string Telefono { get; set; } public int RakingPoints { get; set; } public string ImmagineProfilo { get; set; } public int Dipartimento { get; set; } } } <file_sep>/WebApiFuAgency/Controllers/AccountController.cs using Employee.Models; using Employee.Repository; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebApiFuAgency.Controllers { [Route("api/[controller]")] [ApiController] public class AccountController : ControllerBase { private readonly IAccountRepository accountRepository; public AccountController(IAccountRepository _accountRepository) { this.accountRepository = _accountRepository; } [HttpPost("signUp")] public async Task<IActionResult> SignUp([FromBody] SignUpModel signUpModel) { var result = await accountRepository.SingUp(signUpModel); if(result.Succeeded) { return Ok(); } return Unauthorized(result.Errors); } [HttpPost("login")] public async Task<IActionResult> Login([FromBody] SigninModel signinModel) { var result = await accountRepository.LoginAsync(signinModel); if (String.IsNullOrEmpty(result)) { return Unauthorized("Email o password errati"); } return Ok(result); } } } <file_sep>/WebApiFuAgency/Controllers/ImpiegiatiController.cs using Employee.Models; using Employee.Repository; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.JsonPatch; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebApiFuAgency.Controllers { [Route("api/[controller]/[action]")] [ApiController] [Authorize] public class ImpiegiatiController : ControllerBase { private readonly IImpiegatiRepository _impiegatiRepository; public ImpiegiatiController(IImpiegatiRepository impiegatiRepository) { _impiegatiRepository = impiegatiRepository; } [HttpGet("")] public async Task<IActionResult> GetAllImpiegati() { var impiegati = await _impiegatiRepository.GetAllImpiegati(); return Ok(impiegati); } [HttpGet("{entrId}")] public async Task<IActionResult> GetImpiegatoByEntrId([FromRoute] int entrId) { var impiegato = await _impiegatiRepository.GetImpiegatoByEntrId(entrId); if (impiegato != null) return Ok(impiegato); else return Ok("Non è stato trovato nessun impiegato"); } [HttpPost("")] public async Task<IActionResult> AddImpiegato([FromBody] ImpiegatoModel impiegatoModel) { var entrId = await _impiegatiRepository.AddImpiegato(impiegatoModel); return CreatedAtAction(nameof(GetImpiegatoByEntrId), new { entrId = entrId , controller = "Impiegiati" } , entrId); } [HttpPatch("{entrId}")] public async Task<IActionResult> UpdateImpiegato([FromRoute] int entrId,[FromBody] JsonPatchDocument impiegatoModel) { await _impiegatiRepository.UpdateImpiegato(entrId, impiegatoModel); return Ok(entrId); } [HttpDelete("{entrId}")] public async Task<IActionResult> UpdateImpiegato([FromRoute] int entrId) { await _impiegatiRepository.DeleteImpiegato(entrId); return Ok(entrId); } } } <file_sep>/Employee/Repository/impl/ImpiegatiRepository.cs using AutoMapper; using Employee.Data; using Employee.Entity; using Employee.Models; using Microsoft.AspNetCore.JsonPatch; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Employee.Repository { public class ImpiegatiRepository : IImpiegatiRepository { private readonly RolmexContext _rolmexContext; private readonly IMapper _mapper; public ImpiegatiRepository(RolmexContext rolmexContext, IMapper mapper) { this._rolmexContext = rolmexContext; this._mapper = mapper; } public async Task<int> AddImpiegato(ImpiegatoModel impiegato) { var _impiegato = new Impiegato() { Nome = impiegato.Nome, Cognome = impiegato.Cognome, Qualifica= impiegato.Qualifica, RakingPoints = impiegato.RackingPoints, ImmagineProfilo = impiegato.ImmagineProfilo, Telefono = impiegato.Telefono, Dipartimento = impiegato.Dipartimento }; _rolmexContext.Impiegato.Add(_impiegato); await _rolmexContext.SaveChangesAsync(); return impiegato.EntrepriseId; } public async Task DeleteImpiegato(int EntrPrs) { var impiegato = new Impiegato() { EntrepriseId = EntrPrs}; _rolmexContext.Remove(impiegato); await _rolmexContext.SaveChangesAsync(); } public async Task<List<ImpiegatoModel>> GetAllImpiegati() { var records = await _rolmexContext.Impiegato.ToListAsync(); return _mapper.Map<List<ImpiegatoModel>>(records); } public async Task<ImpiegatoModel> GetImpiegatoByEntrId(int entrId) { var impiegato = await _rolmexContext.Impiegato.FindAsync(entrId); return _mapper.Map<ImpiegatoModel>(impiegato); } public async Task UpdateAllImpiegato(int entrId, ImpiegatoModel impiegatoModel) { var _impiegato = new Impiegato() { EntrepriseId = entrId, Nome = impiegatoModel.Nome, Cognome = impiegatoModel.Cognome, Qualifica = impiegatoModel.Qualifica, RakingPoints = impiegatoModel.RackingPoints, Telefono = impiegatoModel.Telefono }; _rolmexContext.Impiegato.Update(_impiegato); await _rolmexContext.SaveChangesAsync(); } public async Task UpdateImpiegato(int entrId, JsonPatchDocument impiegatoModel) { var impiegato = await _rolmexContext.Impiegato.FindAsync(entrId); if(impiegato != null) { impiegatoModel.ApplyTo(impiegato); await _rolmexContext.SaveChangesAsync(); } } } } <file_sep>/Employee/Models/ImpiegatoModel.cs using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Text; using System.ComponentModel.DataAnnotations; using Employee.Entity; namespace Employee.Models { public class ImpiegatoModel { [Required] public int EntrepriseId { get; set; } [Required] public string Nome { get; set; } [Required] public string Cognome { get; set; } [Required] public string Qualifica { get; set; } public string Telefono { get; set; } public string ImmagineProfilo { get; set; } [Required] public int RackingPoints { get; set; } public int Dipartimento { get; set; } } } <file_sep>/Employee/Models/DipartimentoModel.cs using Employee.Entity; using System; using System.Collections.Generic; using System.Text; namespace Employee.Models { public class DipartimentoModel { public int GeoCode { get; set; } public string Nome { get; set; } public string Luogo { get; set; } public string Descrizione { get; set; } public string ImmagineDipartimento { get; set; } public Impiegato Leader { get; set; } } } <file_sep>/Employee/Repository/IImpiegatiRepository.cs using Employee.Models; using Microsoft.AspNetCore.JsonPatch; using System.Collections.Generic; using System.Threading.Tasks; namespace Employee.Repository { public interface IImpiegatiRepository { public Task<List<ImpiegatoModel>> GetAllImpiegati(); public Task<ImpiegatoModel> GetImpiegatoByEntrId(int entrId); public Task<int> AddImpiegato(ImpiegatoModel impiegato); public Task UpdateAllImpiegato(int entrId, ImpiegatoModel impiegatoModel); public Task UpdateImpiegato(int entrId, JsonPatchDocument impiegatoModel); public Task DeleteImpiegato(int EntrPrs); } }<file_sep>/WebApiFuAgency/Controllers/DipartimentiController.cs using Employee.Models; using Employee.Repository; using Employee.Repository.impl; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebApiFuAgency.Controllers { [Route("api/[controller]/[action]")] [ApiController] public class DipartimentiController : ControllerBase { private readonly IDipartimentiRepository _dipartimentiRepository; public DipartimentiController(IDipartimentiRepository dipartimentiRepository) { this._dipartimentiRepository = dipartimentiRepository; } [HttpPost("")] public async Task<IActionResult> AddDipartimenti([FromBody]DipartimentoModel dipartimentiModel) { await _dipartimentiRepository.AddDipartimento(dipartimentiModel); return Ok(dipartimentiModel.Nome); } [HttpGet("")] public async Task<IActionResult> GetAllDipartimenti() { var dipartimenti = await _dipartimentiRepository.GetAllDipartimenti(); return Ok(dipartimenti); } [HttpGet("{geoCode}")] public async Task<IActionResult> GetDipartimentoByGeoCode([FromRoute]int geoCode) { var dipartimento = await _dipartimentiRepository.GetDipartimentiByGeoCode(geoCode); return Ok(dipartimento); } [HttpGet("{luogo}")] public async Task<IActionResult> GetDipartimentoLuogo([FromRoute] string luogo) { var dipartimento = await _dipartimentiRepository.GetDipartimentiByLuogo(luogo); return Ok(dipartimento); } } } <file_sep>/WebApiFuAgency/Migrations/20210417201338_InitialCreate.cs using Microsoft.EntityFrameworkCore.Migrations; namespace WebApiFuAgency.Migrations { public partial class InitialCreate : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Impiegato", columns: table => new { EntrepriseId = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Nome = table.Column<string>(type: "nvarchar(max)", nullable: true), Cognome = table.Column<string>(type: "nvarchar(max)", nullable: true), Qualifica = table.Column<string>(type: "nvarchar(max)", nullable: true), Telefono = table.Column<string>(type: "nvarchar(max)", nullable: true), RakingPoints = table.Column<int>(type: "int", nullable: false), ImmagineProfilo = table.Column<string>(type: "nvarchar(max)", nullable: true), Dipartimento = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Impiegato", x => x.EntrepriseId); }); migrationBuilder.CreateTable( name: "Dipartimenti", columns: table => new { GeoCode = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Nome = table.Column<string>(type: "nvarchar(max)", nullable: true), Luogo = table.Column<string>(type: "nvarchar(max)", nullable: true), Descrizione = table.Column<string>(type: "nvarchar(max)", nullable: true), ImmagineDipartimento = table.Column<string>(type: "nvarchar(max)", nullable: true), LeaderEntrepriseId = table.Column<int>(type: "int", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Dipartimenti", x => x.GeoCode); table.ForeignKey( name: "FK_Dipartimenti_Impiegato_LeaderEntrepriseId", column: x => x.LeaderEntrepriseId, principalTable: "Impiegato", principalColumn: "EntrepriseId", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateIndex( name: "IX_Dipartimenti_LeaderEntrepriseId", table: "Dipartimenti", column: "LeaderEntrepriseId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Dipartimenti"); migrationBuilder.DropTable( name: "Impiegato"); } } } <file_sep>/Employee/Repository/IDipartimentiRepository.cs using Employee.Entity; using Employee.Models; using Microsoft.AspNetCore.JsonPatch; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Employee.Repository { public interface IDipartimentiRepository { public Task<List<DipartimentoModel>> GetDipartimentiByGeoCode(int geoCode); public Task<List<DipartimentoModel>> GetDipartimentiByNome(string nome); public Task<List<DipartimentoModel>> GetDipartimentiByLuogo(string luogo); public Task<List<DipartimentoModel>> GetAllDipartimenti(); public Task AddDipartimento(DipartimentoModel dipartimentiModel); public Task UpdateDipartimento(int geoCode, JsonPatchDocument dipartimentiModel); public Task DeleteImpiegato(int geoCode); } } <file_sep>/Employee/Repository/impl/DipartimentiRepository.cs using Employee.Data; using Employee.Entity; using Employee.Models; using Microsoft.AspNetCore.JsonPatch; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Employee.Repository.impl { public class DipartimentiRepository : IDipartimentiRepository { private readonly RolmexContext _rolmexContext; public DipartimentiRepository(RolmexContext rolmexContext) { this._rolmexContext = rolmexContext; } public async Task AddDipartimento(DipartimentoModel dipartimentiModel) { var dipartimento = new Dipartimenti() { GeoCode = dipartimentiModel.GeoCode, Nome = dipartimentiModel.Nome, Luogo = dipartimentiModel.Luogo, Descrizione = dipartimentiModel.Luogo, ImmagineDipartimento = dipartimentiModel.ImmagineDipartimento, Leader = dipartimentiModel.Leader }; await _rolmexContext.Dipartimenti.AddAsync(dipartimento); _rolmexContext.SaveChanges(); } public async Task DeleteImpiegato(int geoCode) { var dipartimento = new Dipartimenti() { GeoCode = geoCode }; _rolmexContext.Dipartimenti.Remove(dipartimento); await _rolmexContext.SaveChangesAsync(); } public async Task<List<DipartimentoModel>> GetAllDipartimenti() { var records = await _rolmexContext.Dipartimenti.Select(x => new DipartimentoModel() { GeoCode = x.GeoCode, Nome = x.Nome, Luogo = x.Luogo, Descrizione = x.Descrizione, ImmagineDipartimento = x.ImmagineDipartimento, Leader=x.Leader }).ToListAsync(); return records; } public async Task<List<DipartimentoModel>> GetDipartimentiByGeoCode(int geoCode) { var records = await _rolmexContext.Dipartimenti.Where(x => x.GeoCode == geoCode).Select(x => new DipartimentoModel() { GeoCode = x.GeoCode, Nome = x.Nome, Luogo = x.Luogo, Descrizione = x.Descrizione, ImmagineDipartimento = x.ImmagineDipartimento, Leader = x.Leader }).ToListAsync(); return records; } public async Task<List<DipartimentoModel>> GetDipartimentiByLuogo(string luogo) { var records = await _rolmexContext.Dipartimenti.Where(x => x.Luogo == luogo).Select(x => new DipartimentoModel() { GeoCode = x.GeoCode, Nome = x.Nome, Luogo = x.Luogo, Descrizione = x.Descrizione, ImmagineDipartimento = x.ImmagineDipartimento, Leader = x.Leader }).ToListAsync(); return records; } public async Task<List<DipartimentoModel>> GetDipartimentiByNome(string nome) { var records = await _rolmexContext.Dipartimenti.Where(x => x.Nome == nome).Select(x => new DipartimentoModel() { GeoCode = x.GeoCode, Nome = x.Nome, Luogo = x.Luogo, Descrizione = x.Descrizione, ImmagineDipartimento = x.ImmagineDipartimento, Leader = x.Leader }).ToListAsync(); return records; } public Task UpdateDipartimento(int geoCode, JsonPatchDocument dipartimentiModel) { throw new NotImplementedException(); } } } <file_sep>/WebApiFuAgency/Program.cs using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; using System; namespace WebApiFuAgency { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults( webHost => { webHost.UseStartup<Startup>(); }); } }
f20bdac676c00974d7403c92841c8f285d31d9cf
[ "C#" ]
16
C#
gianlucapes/webapiFuAgency
a25cafb55e1206c2c108b6d7ee7c1f042e0f80bf
4656802bbcb17b405044271c9b1d316a0471f06c
refs/heads/master
<repo_name>TensyTeam/Hedera-platform<file_sep>/app/sys_feedback_delete.py from flask import session, request, render_template, redirect from app import app, LINK from requests import post import json @app.route('/sys_feedback_delete') def sys_feedback_delete(): ip = request.remote_addr id = int(request.args.get('id')) req = json.loads(post(LINK, json={ 'method': 'feedback.delete', 'token': session['token'], 'ip': ip, 'id': id, }).text) id -= id != 0 if not req['error']: return redirect(LINK + 'admin') ## + str(id) else: return render_template('message.html', cont=req['message'])<file_sep>/app/space.py from flask import render_template, session, request, Markup, redirect from app import app, LINK, get_preview, PLATFORM_WALLET from requests import post from json import loads import re @app.route('/space/<int:id>') @app.route('/space/<int:id>/') def space(id): ip = request.remote_addr user = loads(post(LINK, json={'method': 'users.get', 'ip': ip, 'id': session['id']}).text)['user'] if 'id' in session else {'id': 0, 'admin': 2} url = 'space/%d' % id if 'token' in session: req = loads(post(LINK, json={ 'method': 'study.get', 'token': session['token'], 'ip': ip, 'id': id, }).text) if req['error']: return render_template('message.html', cont=req['message']) finished = req['finished'] req = req['study'] req['theory'] = Markup(req['theory']) if req['teacher']: for i in range(len(req['messages'])): req['messages'][i]['cont'] = Markup(req['messages'][i]['cont']) return render_template('space.html', title = 'Theory', description = re.sub(r'\<[^>]*\>', '', req['ladder_name'] + '\n' + req['step_name'] + '\n' + req['step_cont']), tags = ['theory'] + req['tags'], url = url, user = user, LINK = LINK, preview = get_preview, PLATFORM_WALLET = PLATFORM_WALLET, id = id, student = req['student'], teacher = req['teacher'], ladder = req['ladder_name'], step = req['step_name'], ladder_id = req['ladder'], step_id = req['step'], theory = req['theory'], cont = Markup(req['step_cont']), messages = req['messages'] if req['teacher'] else [], status = req['status'], price = req['price'], wallet = req['wallet'], finished = finished, ) else: return redirect(LINK + 'login?url=' + url)<file_sep>/app/api.py from flask import request from app import app, LINK, IP_CLIENT, PLATFORM_WALLET, CONTRACT_ADDRESS, TOPIC_LESSON_STARTED, TOPIC_LESSON_PREPARED import time import base64 from mongodb import * from re import findall, match, search from hashlib import md5 from json import dumps, loads from random import randint from os import listdir, remove import requests # Socket.IO from threading import Lock from flask_socketio import SocketIO, emit async_mode = None socketio = SocketIO(app, async_mode=async_mode) thread = None thread_lock = Lock() generate = lambda length=32: ''.join(['1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM'[randint(0, 61)] for _ in range(length)]) def max_image(url): x = listdir(url) k = 0 for i in x: j = findall(r'\d+', i) if len(j) and int(j[0]) > k: k = int(j[0]) return k+1 def load_image(url, data, adr=None, format='jpg', type='base64'): if type == 'base64': data = base64.b64decode(data) if adr: id = adr for i in listdir(url): if search(r'^' + str(id) + '\.', i): remove(url + '/' + i) else: id = max_image(url) with open('%s/%s.%s' % (url, str(id), format), 'wb') as file: file.write(data) return id def errors(x, filters): for i in filters: if i[0] in x: # Неправильный тип данных if type(x[i[0]]) != i[2] or (type(x[i[0]]) == list and any(type(j) != i[3] for j in x[i[0]])): mes = 'Invalid data type: %s (required %s' % (i[0], str(i[2])) if i[2] == list: mes += ' - %s' % str(i[3]) mes += ')' return dumps({'error': 4, 'message': mes}) # Не все поля заполнены elif i[1]: return dumps({'error': 3, 'message': 'Not all required fields are filled in: %s' % i[0]}) def reimg(s, type='steps', id1=0, id2=0): i = 1 k = 0 while True: x = search(r'<img ', s[k:]) if x: st = list(x.span()) st[1] = st[0] + s[k+st[0]:].index('>') vs = '' if 'src="' in s[k+st[0]:k+st[1]]: adr = '%d-%d' % (id2, i) if id1: adr = str(id1) + '-' + adr if search(r'image/.*;', s[k+st[0]:k+st[1]]) and 'base64,' in s[k+st[0]:k+st[1]]: start = k + st[0] + s[k+st[0]:].index('base64,') + 7 stop = start + s[start:].index('"') b64 = s[start:stop] form = search(r'image/.*;', s[k+st[0]:start]).group(0)[6:-1] load_image('app/static/load/' + type, b64, adr, form) vs = '<img src="' + '/static/load/' + type + '/' + adr + '.' + form + '">' # s = s[:k+s[k:].index('src="')+5] + '/static/load/' + type + '/' + adr + '.' + form + s[stop:] else: start = k + search(r'src=".*', s[k:]).span()[0] + 5 stop = start + s[start:].index('"') href = s[start:stop] if href[:7] == '/static': href = LINK + href[1:] if href[:4] == 'http': b64 = str(base64.b64encode(requests.get(href).content))[2:-1] form = href.split('.')[-1] if 'latex' in form: form = 'png' load_image('app/static/load/' + type, b64, adr, form) vs = '<img src="' + '/static/load/' + type + '/' + adr + '.' + form + '">' if vs: s = s[:k+st[0]] + vs + s[k+st[1]+1:] k += st[0] + len(vs) i += 1 else: k += st[1] else: break return s def get_user(id): if id: req = db['users'].find_one({'id': id}, {'id': True, 'login': True, 'name': True, 'surname': True, '_id': False}) else: req = 0 return req # type_transactions = ( # 'Unknown transaction', # 'Send', # 'Registration', # 'Lesson', # ) @app.route('/', methods=['POST']) def process(): x = request.json # print(x) if 'method' not in x: return dumps({'error': 2, 'message': 'Wrong method'}) # Убираем лишние отступы for i in x: if type(x[i]) == str: x[i] = x[i].strip() # Определение пользователя if 'token' in x: user_id = db['tokens'].find_one({'token': x['token']}, {'id': True, '_id': False})['id'] if user_id: user = db['users'].find_one({'id': user_id}) else: return dumps({'error': 5, 'message': 'Invalid token'}) else: user = { 'id': 0, 'admin': 2, } timestamp = time.time() req = { 'time': timestamp, 'user': user['id'], 'admin': user['admin'], 'request': x, } ip = request.remote_addr if 'ip' in x and ip == IP_CLIENT: req['ip'] = x['ip'] else: req['ip'] = ip db['actions'].insert(req) try: # Регистрация if x['method'] == 'profile.reg': # Не все поля заполнены mes = errors(x, ( ('login', True, str), ('pass', True, str), ('mail', True, str), ('name', False, str), ('surname', False, str), )) if mes: return mes x['login'] = x['login'].lower() # Логин уже зарегистрирован if len(list(db['users'].find({'login': x['login']}, {'_id': True}))): return dumps({'error': 6, 'message': 'This login already exists'}) # Недопустимый логин if not 3 <= len(x['login']) <= 10 or len(findall('[^a-z0-9]', x['login'])) or not len(findall('[a-z]', x['login'])): return dumps({'error': 7, 'message': 'Wrong login: length must be more than 3 and less than 10 characters, consist only of digits and at least a few latin letters'}) # Почта уже зарегистрирована if len(list(db['users'].find({'mail': x['mail']}, {'_id': True}))): return dumps({'error': 8, 'message': 'This mail already exsists'}) # Недопустимый пароль if not 6 <= len(x['pass']) <= 40 or len(findall('[^a-zA-z0-9!@#$%^&*()-_+=;:,./?\|`~\[\]{}]', x['pass'])) or not len(findall('[a-zA-Z]', x['pass'])) or not len(findall('[0-9]', x['pass'])): return dumps({'error': 9, 'message': 'Invalid password: the length must be from 6 to 40 characters, consist of mandatory digits, characters:! @, #, $, %, ^, &, *, (, ), -, _, +, =, ;, :, ,, ., /, ?, |, `, ~, [, ], {, } and necessarily Latin letters'}) # Недопустимая почта if match('.+@.+\..+', x['mail']) == None: return dumps({'error': 10, 'message': 'Invalid mail'}) # Недопустимое имя if 'name' in x and not x['name'].isalpha(): return dumps({'error': 11, 'message': 'Invalid name'}) # Недопустимая фамилия if 'surname' in x and not x['surname'].isalpha(): return dumps({'error': 12, 'message': 'Invalid surname'}) try: id = db['users'].find({}, {'id': True, '_id': False}).sort('id', -1)[0]['id'] + 1 except: id = 1 db['users'].insert({ 'id': id, 'login': x['login'], 'password': md5(bytes(x['pass'], 'utf-8')).hexdigest(), 'mail': x['mail'], 'name': x['name'].title() if 'name' in x else None, 'surname': x['surname'].title() if 'surname' in x else None, 'description': '', 'rating': 0, 'admin': 3, 'ladders': {}, 'steps': [], 'balance': 1000, # }) token = generate() db['tokens'].insert({ 'token': token, 'id': id, 'time': timestamp, }) return dumps({'error': 0, 'id': id, 'token': token}) # Авторизация elif x['method'] == 'profile.auth': mes = errors(x, ( ('login', True, str), ('pass', True, str), )) if mes: return mes x['login'] = x['login'].lower() # Неправильный логин if not len(list(db['users'].find({'login': x['login']}, {'_id': True}))): return dumps({'error': 6, 'message': 'Login does not exist'}) password = md5(bytes(x['pass'], 'utf-<PASSWORD>() req = db['users'].find_one({'login': x['login'], 'password': <PASSWORD>}, {'id': True, '_id': False}) # Неправильный пароль if not req: return dumps({'error': 7, 'message': 'Invalid password'}) token = generate() db['tokens'].insert({'token': token, 'id': req['id'], 'time': timestamp}) return dumps({'error': 0, 'id': req['id'], 'token': token}) # Изменение личной информации elif x['method'] == 'profile.edit': mes = errors(x, ( ('token', True, str), ('name', False, str), ('surname', False, str), ('description', False, str), ('photo', False, str), )) if mes: return mes if 'name' in x: # Недопустимое имя if not x['name'].isalpha(): return dumps({'error': 6, 'message': 'Invalid name'}) user['name'] = x['name'].title() if 'surname' in x: # Недопустимая фамилия if not x['surname'].isalpha(): return dumps({'error': 7, 'message': 'Invalid surname'}) user['surname'] = x['surname'].title() if 'description' in x: user['description'] = x['description'] db['users'].save(user) if 'photo' in x: try: load_image('app/static/load/users', x['photo'], user['id']) # Ошибка загрузки фотографии except: return dumps({'error': 8, 'message': 'Error uploading photo'}) return dumps({'error': 0}) # Закрытие сессии elif x['method'] == 'profile.exit': mes = errors(x, ( ('token', True, str), )) if mes: return mes req = db['tokens'].find_one({'token': x['token']}, {'_id': True}) db['tokens'].remove(req['_id']) return dumps({'error': 0}) # Добавление ледера elif x['method'] == 'ladders.add': mes = errors(x, ( ('token', True, str), ('name', True, str), ('description', True, str), ('tags', True, list, str), # ('category', True, int), ('preview', False, str), )) if mes: return mes try: id = db['ladders'].find({}, {'id': True, '_id': False}).sort('id', -1)[0]['id'] + 1 except: id = 1 query = { 'id': id, 'user': user['id'], 'time': timestamp, 'status': 1, 'view': [], 'like': [], 'dislike': [], 'comment': [], 'steps': [{ 'id': 0, 'name': 'You have read and agreed to Honor code?', 'cont': '<a href="/codex">Link to Honor code</a>', 'options': ['Yes', 'No', 'Don\'t understand'], 'answers': [1,], 'theory': '<a href="/codex">Link to Honor code</a>', 'user': user['id'], 'view': [], 'complete': [], 'comment': [], 'status': 3, 'total': 0, },], } for i in ('name', 'tags', 'description'): # , 'category' if i in x: query[i] = x[i] db['ladders'].insert(query) if 'preview' in x: try: load_image('app/static/load/ladders', x['preview'], id, x['file'].split('.')[-1] if 'file' in x else None) # Ошибка загрузки изображения except: return dumps({'error': 6, 'message': 'Error uploading image'}) return dumps({'error': 0, 'id': id}) # Изменение ледера elif x['method'] == 'ladders.edit': mes = errors(x, ( ('token', True, str), ('id', True, int), ('name', False, str), ('description', False, str), ('tags', False, list, str), ('preview', False, str), )) if mes: return mes query = db['ladders'].find_one({'id': x['id']}) # Неправильный ледер if not query: return dumps({'error': 6, 'message': 'Ladder does not exsist'}) # Нет прав на редактирование if user['admin'] < 5: return dumps({'error': 7, 'message': 'No access rights'}) for i in ('name', 'description', 'tags'): # 'category' if i in x: query[i] = x[i] query['status'] = 3 if user['admin'] >= 5 else 2 db['ladders'].save(query) if 'preview' in x: try: load_image('app/static/load/ladders', x['preview'], x['id'], x['file'].split('.')[-1] if 'file' in x else None) # Ошибка загрузки изображения except: return dumps({'error': 8, 'message': 'Error uploading image'}) return dumps({'error': 0}) # Список ледеров # сделать выборку полей elif x['method'] == 'ladders.gets': mes = errors(x, ( ('count', False, int), ('category', False, int) )) if mes: return mes count = x['count'] if 'count' in x else None category = None # if 'category' in x: # category = [x['category'],] # for i in db['categories'].find({'parent': x['category']}, {'id': True, '_id': False}): # category.append(i['id']) # category = {'category': {'$in': category}} ladders = list(db['ladders'].find(category, {'_id': False, 'id': True, 'name': True, 'steps.complete': True})) for i in range(len(ladders)): ladders[i]['complete'] = sum(len(j['complete']) for j in ladders[i]['steps']) ladders.sort(key=lambda i: i['complete'], reverse=-1) for i in range(len(ladders)): del ladders[i]['steps'] del ladders[i]['complete'] # ! Преобразовать поле просмотров return dumps({'error': 0, 'ladders': ladders}) # Получение ледера elif x['method'] == 'ladders.get': mes = errors(x, ( ('token', False, str), ('id', True, int), )) if mes: return mes ladder = db['ladders'].find_one({'id': x['id']}) # Неправильный ледер if not ladder: return dumps({'error': 6, 'message': 'Ladder does not exsist'}) ladder['view'].append(user['id']) db['ladders'].save(ladder) s = str(x['id']) step_id = -1 step_num = -1 if user['admin'] >= 3: if s in user['ladders']: j = user['ladders'][s] for i, el in enumerate(ladder['steps']): if ((user['admin'] >= 5 and el['status']) or el['status'] >= 3) and el['id'] not in j: step_id = el['id'] step_num = i break else: for i, el in enumerate(ladder['steps']): if (user['admin'] >= 5 and el['status']) or el['status'] >= 3: step_id = el['id'] step_num = i break user['ladders'][s] = [] db['users'].save(user) else: for i, el in enumerate(ladder['steps']): if el['status'] >= 3: step_id = el['id'] step_num = i break view = set(ladder['view']) user_top = [] for i in view: filter_db = {'_id': False, 'ladders': True, 'name': True, 'surname': True, 'login': True} users = db['users'].find_one({'id': i, 'admin': {'$gte': 3}}, filter_db) if not users: continue steps = [j['id'] for j in ladder['steps']] kol = len(set(users['ladders'][s]) & set(steps)) # При ошибке: обнулить view ladder user_info = { 'id': i, 'name': users['name'], 'surname': users['surname'], 'login': users['login'], 'complete': kol, } user_top.append((kol, user_info)) user_top = [i[1] for i in sorted(user_top, key=lambda y: y[0], reverse=True)] for i in range(len(ladder['steps'])): ladder['steps'][i]['price'] = (20 + i) * 10 # ! del ladder['_id'] del ladder['view'] del ladder['time'] del ladder['user'] for i in range(len(ladder['steps'])): for j in ('answers', 'view', 'cont', 'options', 'comment', 'user', 'theory'): del ladder['steps'][i][j] i = 0 while i < len(ladder['steps']): if not ladder['steps'][i]['status']: del ladder['steps'][i] else: i += 1 def get_step(j): for i, el in enumerate(ladder['steps']): if el['id'] == j: return { 'id': j, 'name': el['name'], 'num': i, } return None user_steps = [] if 'token' in x: for i in user['ladders'][str(x['id'])]: s = get_step(i) if s: user_steps.append(s) user_steps.sort(key=lambda i: i['num'], reverse=-1) req = { 'error': 0, 'ladder': ladder, 'step': step_id, 'num': step_num, 'experts': user_top, 'steps': user_steps } return dumps(req) # Добавление степа # добавлять по id # менять местами elif x['method'] == 'step.add': mes = errors(x, ( ('token', True, str), ('id', False, int), ('after', False, bool), ('ladder', True, int), ('name', True, str), ('options', True, list, str), ('answers', False, list, int), ('cont', False, str), ('theory', True, str), )) if mes: return mes ladder = db['ladders'].find_one({'id': x['ladder']}) # Неправильный ледер if not ladder: return dumps({'error': 6, 'message': 'Wrong id of ladder'}) try: step_all = [i['id'] for i in ladder['steps']] step_id = max(step_all) + 1 except: step_all = [] step_id = 0 if 'id' in x: if x['id'] not in step_all: return dumps({'error': 7, 'message': 'Wrong id of step'}) else: x['id'] = step_all[-1] x['after'] = True if x['theory'] and 'answers' in x: if user['admin'] >= 5: status = 3 else: status = 2 else: status = 1 step = { 'id': step_id, 'name': x['name'], 'options': [i.strip() for i in x['options']], 'answers': x['answers'] if 'answers' in x else [], 'user': user['id'], 'view': [], 'comment': [], 'status': status, 'cont': reimg(x['cont'], 'steps', x['ladder'], step_id) if 'cont' in x else '', 'theory': reimg(x['theory'], 'theory', x['ladder'], step_id), 'complete': [], } after = x['after'] if 'after' in x else False if 'id' in x and x['id'] in step_all and not (after and step_all.index(x['id']) == (len(step_all) - 1)): step_num = step_all.index(x['id']) + after ladder['steps'] = ladder['steps'][:step_num+after] + [step] + ladder['steps'][step_num+after:] else: step_num = len(step_all) ladder['steps'].append(step) db['ladders'].save(ladder) return dumps({'error': 0, 'id': step_id, 'num': step_num}) # Изменение степа elif x['method'] == 'step.edit': mes = errors(x, ( ('token', True, str), ('ladder', True, int), ('step', True, int), ('name', False, str), ('options', False, list, str), ('answers', False, list, int), ('cont', False, str), ('theory', False, str), ('id', False, int), ('after', False, bool), )) if mes: return mes ladder = db['ladders'].find_one({'id': x['ladder']}) # Неправильный ледер if not ladder: return dumps({'error': 6, 'message': 'Wrong id of ladder'}) try: step_all = [i['id'] for i in ladder['steps']] except: step_all = [] # Неправильный степ if x['step'] not in step_all: return dumps({'error': 7, 'message': 'Wrong id of step'}) step_num = step_all.index(x['step']) # Нет прав на редактирование if user['admin'] < 5 and user['id'] != ladder['steps'][step_num]['user']: return dumps({'error': 8, 'message': 'No access rights'}) for i in ('name', 'options', 'answers', 'cont', 'theory'): if i in x: if type(x[i]) == list and type(x[i][0]) == str: x[i] = [j.strip() for j in x[i]] if i == 'cont': x[i] = reimg(x[i], 'steps', x['ladder'], x['step']) elif i == 'theory': x[i] = reimg(x[i], 'theory', x['ladder'], x['step']) ladder['steps'][step_num][i] = x[i] ladder['steps'][step_num]['status'] = 2 if user['admin'] < 5 else 3 if 'id' in x: if x['id'] not in step_all: return dumps({'error': 9, 'message': 'Wrong id of step'}) step = ladder['steps'][step_num] del ladder['steps'][step_num] del step_all[step_num] after = x['after'] if 'after' in x else False if x['id'] in step_all and not (after and step_all.index(x['id']) == (len(step_all) - 1)): step_num = step_all.index(x['id']) + after ladder['steps'] = ladder['steps'][:step_num+after] + [step] + ladder['steps'][step_num+after:] else: step_num = len(step_all) ladder['steps'].append(step) db['ladders'].save(ladder) return dumps({'error': 0, 'num': step_num}) # Удаление степа elif x['method'] == 'step.delete': mes = errors(x, ( ('token', True, str), ('ladder', True, int), ('step', True, int), )) if mes: return mes ladder = db['ladders'].find_one({'id': x['ladder']}) # Неправильный ледер if not ladder: return dumps({'error': 6, 'message': 'Wrong id of ladder'}) try: step_all = [i['id'] for i in ladder['steps']] except: step_all = [] # Неправильный степ if x['step'] not in step_all: return dumps({'error': 7, 'message': 'Wrong id of step'}) step_num = step_all.index(x['step']) # Нет прав на удаление if user['admin'] < 6: return dumps({'error': 8, 'message': 'No access rights'}) # del ladder['steps'][step_num] ladder['steps'][step_num]['status'] = 0 db['ladders'].save(ladder) # Куда перекинуть после удаления step_next = -1 if len(ladder['steps']) > step_num + 1: for e in ladder['steps'][step_num+1:]: if user['admin'] >= 5 or e['status'] >= 3: step_next = e['id'] break step_num -= step_num != 0 return dumps({'error': 0, 'num': step_num, 'step': step_next}) # Получение степа elif x['method'] == 'step.get': mes = errors(x, ( ('token', True, str), ('ladder', True, int), ('step', True, int), )) if mes: return mes ladder = db['ladders'].find_one({'id': x['ladder']}) # Неправильный ледер if not ladder: return dumps({'error': 6, 'message': 'Ladder does not exsist'}) try: step_all = [j['id'] for j in ladder['steps']] step_available = [j['id'] for j in ladder['steps'] if (user['admin'] >= 6 and j['status']) or j['status'] >= 3] except: step_all = [] step_available = [] # Неправильный степ if x['step'] not in step_all: return dumps({'error': 7, 'message': 'Step does not exsist'}) step_num = step_all.index(x['step']) step_num_available = step_available.index(x['step']) s = str(x['ladder']) if s not in user['ladders']: user['ladders'][s] = [] db['users'].save(user) # Степ недоступен try: step_user = max(step_available.index(i) for i in user['ladders'][s] if i in step_available) except: step_user = 0 for i, el in enumerate(ladder['steps']): if (user['admin'] >= 5 and el['status']) or el['status'] >= 3: step_user = i break if (user['admin'] < 7 and step_num_available > step_user + 1 and ladder['steps'][step_num]['user'] != user['id']) or (user['admin'] < 5 and ladder['steps'][step_num]['status'] < 3 and ladder['steps'][step_num]['user'] != user['id']): return dumps({'error': 8, 'message': 'You are not yet available this step'}) ladder['steps'][step_num]['view'].append(user['id']) db['ladders'].save(ladder) if ladder['steps'][step_num]['user'] != user['id'] and user['admin'] <= 3: del ladder['steps'][step_num]['answers'] author = get_user(ladder['steps'][step_num]['user']) step = ladder['steps'][step_num] step['next'] = None for i, el in enumerate(ladder['steps']): # ! обрезать if ((user['admin'] >= 5 and el['status']) or el['status'] >= 3) and i > step_num: step['next'] = { 'id': el['id'], 'name': el['name'], } step['prev'] = None for i, el in enumerate(ladder['steps']): # ! обрезать if ((user['admin'] >= 5 and el['status']) or el['status'] >= 3) and i < step_num: step['prev'] = { 'id': el['id'], 'name': el['name'], } del step['view'] spaces = list(db['study'].find({'student': user['id'], 'ladder': x['ladder'], 'step': x['step'], 'teacher': {'$ne': 0}}, {'_id': False, 'id': True, 'teacher': True})) for i in range(len(spaces)): users = db['users'].find_one({'id': spaces[i]['teacher']}, {'_id': False, 'name': True, 'surname': True, 'login': True}) for j in ('name', 'surname', 'login'): spaces[i][j] = users[j] res = { 'error': 0, 'step': step, 'num': step_num, 'name': ladder['name'], 'tags': ladder['tags'], 'author': author, 'complete': True if x['step'] in user['ladders'][str(x['ladder'])] else False, 'spaces': spaces, } return dumps(res) # Список степов elif x['method'] == 'step.gets': mes = errors(x, ( ('token', False, str), ('ladder', True, int), )) if mes: return mes filter_db = {'steps.name': True, 'steps.id': True, '_id': False, 'steps.status': True} # status = 1 if user['admin'] >= 5 else 3 # 'status': {'$gte': status} ladder = db['ladders'].find_one({'id': x['ladder']}, filter_db) # Неправильный ледер if not ladder: return dumps({'error': 6, 'message': 'Ladder does not exsist'}) try: step_list = [[j['id'], j['name']] for j in ladder['steps'] if j['status'] >= 1] except: step_list = [] return dumps({'error': 0, 'steps': step_list}) # Проверка ответов elif x['method'] == 'step.check': mes = errors(x, ( ('token', True, str), ('ladder', True, int), ('step', True, int), ('answers', True, list, int), )) if mes: return mes ladder = db['ladders'].find_one({'id': x['ladder']}) # Неправильный ледер if not ladder: return dumps({'error': 6, 'message': 'Ladder does not exsist'}) # status = 3 if user['admin'] < 5 else 1 # Неподтверждённые степы обычным пользователям не отображаются # if j['status'] >= status try: step_all = [j['id'] for j in ladder['steps']] step_available = [j['id'] for j in ladder['steps'] if (user['admin'] >= 6 and j['status']) or j['status'] >= 3] except: step_all = [] step_available = [] # Неправильный степ if x['step'] not in step_available: return dumps({'error': 7, 'message': 'Step does not exsist'}) step_num = step_all.index(x['step']) step_num_available = step_available.index(x['step']) # Нет прав на проверку ответов if user['admin'] < 3: return dumps({'error': 8, 'message': 'No access rights'}) # Ледер недоступен s = str(x['ladder']) if s not in user['ladders']: dumps({'error': 9, 'message': 'You are not yet available this ladder'}) # Степ недоступен try: step_user = max(step_available.index(i) for i in user['ladders'][s] if i in step_available) except: step_user = 0 for i, el in enumerate(ladder['steps']): if (user['admin'] >= 5 and el['status']) or el['status'] >= 3: step_user = i break if (user['admin'] < 7 and step_num_available > step_user + 1 and ladder['steps'][step_num]['user'] != user['id']) or (user['admin'] < 5 and ladder['steps'][step_num]['status'] < 3 and ladder['steps'][step_num]['user'] != user['id']): return dumps({'error': 10, 'message': 'You are not yet available this step'}) suc = set(x['answers']) == set(ladder['steps'][step_num]['answers']) if suc: if x['step'] not in user['ladders'][s]: # Обновить информацию пользователя ladder['steps'][step_num]['complete'].append(user['id']) db['ladders'].save(ladder) user['ladders'][s].append(x['step']) # Добавить в список для обучения step = { 'ladder': x['ladder'], 'step': x['step'], 'price': (20 + x['step']) * 10, # ! } user['steps'].append(step) db['users'].save(user) # Обновить список степов для поиска онлайн учителя users = db['online'].find_one({'id': user['id']}) if users: users['steps'].append(step) # Следующий степ step_next = -1 for u, e in enumerate(ladder['steps']): if e['id'] not in user['ladders'][s] and e['status'] >= 3: step_next = e['id'] break # if step_next == -1: # if step_num < len(step_all): # step_next = step_all[step_num] return dumps({'error': 0, 'correct': suc, 'step': step_next if suc else x['step']}) # Список учителей elif x['method'] == 'study.gets': mes = errors(x, ( ('token', True, str), ('ladder', True, int), ('step', True, int), )) if mes: return mes ladder = db['ladders'].find_one({'id': x['ladder']}, {'_id': False, 'steps.id': True}) # Неправильный ледер if not ladder: return dumps({'error': 6, 'message': 'Ladder does not exsist'}) try: step_all = [j['id'] for j in ladder['steps']] except: step_all = [] # Неправильный степ if x['step'] not in step_all: return dumps({'error': 7, 'message': 'Step does not exsist'}) step_num = step_all.index(x['step']) # Нет прав на обучение if user['admin'] < 3: return dumps({'error': 8, 'message': 'No access rights'}) # Удалить предыдущие сеансы for i in db['teachers'].find({'user': user['id']}): socketio.emit('remove', { 'ladder': i['ladder'], 'step': i['step'], 'user': i['user'], }, namespace='/study') db['teachers'].remove(i['_id']) filter_db = {'_id': False, 'user': True, 'price': True} users = list(db['teachers'].find({'ladder': x['ladder'], 'step': x['step']}, filter_db)) for i, el in enumerate(users): filter_db = {'_id': False, 'id': True, 'name': True, 'surname': True, 'login': True} req = db['users'].find_one({'id': el['user']}, filter_db) for j in req: users[i][j] = req[j] users[i]['rating'] = 0 # # Список пользователей онлайн ladder_str = str(x['ladder']) online = [] for i in db['online'].find({'user': {'$ne': user['id']}, 'steps': {'$elemMatch': {'ladder': x['ladder'], 'step': x['step']}}}, {'_id': False, 'user': True, 'steps': True}): req = {'user': i['user']} for j in i['steps']: if j['ladder'] == x['ladder'] and j['step'] == x['step']: req['price'] = j['price'] online.append(req) for i, el in enumerate(online): filter_db = {'_id': False, 'id': True, 'name': True, 'surname': True, 'login': True} req = db['users'].find_one({'id': el['user']}, filter_db) for j in req: online[i][j] = req[j] online[i]['price'] = el['price'] online[i]['rating'] = 0 # req = { 'error': 0, 'bot': { 'price': (20 + step_num) * 10, # }, 'teachers': [], 'users': users, 'online': online, } return dumps(req) # Начало обучения elif x['method'] == 'study.start': mes = errors(x, ( ('token', True, str), ('ladder', True, int), ('step', True, int), ('teacher', True, int), )) if mes: return mes filter_db = {'_id': False, 'steps.id': True, 'steps.user': True} ladder = db['ladders'].find_one({'id': x['ladder']}, filter_db) # Неправильный ледер if not ladder: return dumps({'error': 6, 'message': 'Ladder does not exsist'}) try: step_all = [j['id'] for j in ladder['steps']] except: step_all = [] # Неправильный степ if x['step'] not in step_all: return dumps({'error': 7, 'message': 'Step does not exsist'}) step_num = step_all.index(x['step']) # Нет прав на обучение if user['admin'] < 3: return dumps({'error': 8, 'message': 'No access rights'}) # Нельзя учить самого себя if user['id'] == x['teacher']: return dumps({'error': 9, 'message': 'You can not teach yourself!'}) try: id = db['study'].find({}, {'_id': False, 'id': True}).sort('id', -1)[0]['id'] + 1 except: id = 1 request_user = False if x['teacher']: users = db['teachers'].find_one({'user': x['teacher'], 'ladder': x['ladder'], 'step': x['step']}, {'_id': False, 'price': True}) # Если пользователь ожидает ученика if users: price = users['price'] else: # Онлайн пользователь condition_db = { 'user': x['teacher'], 'steps': { '$elemMatch': { 'ladder': x['ladder'], 'step': x['step'], } } } filter_db = {'_id': False, 'steps': True} users = db['online'].find_one(condition_db, filter_db) # Запрос онлайн пользователю if users: for i in users['steps']: if i['ladder'] == x['ladder'] and i['step'] == x['step']: price = i['price'] request_user = True # Учитель не найден else: return dumps({'error': 10, 'message': 'Teacher is not available!'}) else: price = (20 + x['step']) * 10 # if price > user['balance']: return dumps({'error': 11, 'message': 'Not enough tokens!'}) if not x['teacher']: user['balance'] -= price db['users'].save(user) # db['study'].insert_one({ 'id': id, 'teacher': x['teacher'], 'student': user['id'], 'ladder': x['ladder'], 'step': x['step'], 'price': price, 'time': timestamp, 'status': 0 if x['teacher'] else 17, 'messages': [], }) author_wallet = db['users'].find_one({'id': ladder['steps'][step_num]['user']}, {'_id': False, 'public': True})['public'] # ! переделать на общее пространство сайта if x['teacher']: if request_user: socketio.emit('teacher', { 'teacher': x['teacher'], 'id': id, 'user': user['id'], 'ladder': x['ladder'], 'step': x['step'], 'price': price, }, namespace='/main') else: socketio.emit('study', { 'teacher': x['teacher'], 'id': id, 'user': user['id'], 'ladder': x['ladder'], 'step': x['step'], 'price': price, 'wallet_student': user['public'], 'wallet_author': author_wallet, 'wallet_platform': PLATFORM_WALLET, }, namespace='/teach') return dumps({'error': 0, 'id': id}) # Конец обучения elif x['method'] == 'study.stop': mes = errors(x, ( ('token', True, str), ('id', True, int), ('status', True, int), )) if mes: return mes study = db['study'].find_one({'id': x['id']}) if not study: return dumps({'error': 6, 'message': 'Training session does not exsist'}) if x['status'] == 0: study['status'] = 2 elif x['status'] == 1: study['status'] = 3 else: return dumps({'error': 7, 'message': 'Invalid training status'}) db['study'].save(study) return dumps({'error': 0, 'ladder': study['ladder'], 'step': study['step']}) # Получение пространства обучения elif x['method'] == 'study.get': mes = errors(x, ( ('token', True, str), ('id', True, int), )) if mes: return mes study = db['study'].find_one({'id': x['id']}) if not study: return dumps({'error': 6, 'message': 'Training session does not exsist'}) if user['id'] != study['student'] and user['id'] != study['teacher'] and user['admin'] < 6: return dumps({'error': 7, 'message': 'No access rights'}) # Учитель подтвердил начало обучения if user['id'] == study['teacher'] and study['status'] == 0: study['status'] = 1 # study['height'] = loads(requests.get('https://testnet.qtum.org/insight-api/sync').text)['blockChainHeight'] db['study'].save(study) # Удалить объявления об обучении for i in db['teachers'].find({'user': study['teacher']}): socketio.emit('remove', { 'ladder': i['ladder'], 'step': i['step'], 'user': i['user'], }, namespace='/study') db['teachers'].remove(i['_id']) wallet_teacher = db['users'].find_one({'id': study['teacher']}, {'_id': False, 'public': True})['public'] socketio.emit('accept', { 'id': x['id'], 'teacher': wallet_teacher, 'price': study['price'], }, namespace='/space') filter_db = { '_id': False, 'name': True, 'tags': True, 'steps.id': True, 'steps.name': True, 'steps.cont': True, 'steps.theory': True } ladder = db['ladders'].find_one({'id': study['ladder']}, filter_db) step_all = [j['id'] for j in ladder['steps']] step_num = step_all.index(study['step']) step = ladder['steps'][step_num] study['step_name'] = step['name'] study['step_cont'] = step['cont'] study['theory'] = step['theory'] study['ladder_name'] = ladder['name'] study['tags'] = ladder['tags'] filter_db = {'_id': False, 'name': True, 'surname': True, 'login': True, 'id': True} users = db['users'].find_one({'id': study['student']}, filter_db) study['student'] = users if study['teacher']: study['wallet'] = db['users'].find_one({'id': study['teacher']}, {'_id': False, 'public': True})['public'] else: study['wallet'] = PLATFORM_WALLET if study['teacher']: filter_db = {'_id': False, 'name': True, 'surname': True, 'login': True, 'id': True} users = db['users'].find_one({'id': study['teacher']}, filter_db) study['teacher'] = users del study['_id'] finished = study['status'] not in (0, 1, 14, 17, 18, 19) return dumps({'error': 0, 'study': study, 'finished': finished}) # Начало обучения elif x['method'] == 'teach.start': mes = errors(x, ( ('token', True, str), ('steps', True, list, dict), )) if mes: return mes filter_db = {'_id': False, 'id': True, 'steps.id': True} ladder_list = {str(i['id']): [j['id'] for j in i['steps']] for i in db['ladders'].find({}, filter_db)} for i in x['steps']: lad = str(i['ladder']) if type(i['ladder']) != int or lad not in ladder_list: return dumps({'error': 6, 'message': 'Invalid ladder: ' + lad}) if type(i['step']) != int or i['step'] not in ladder_list[lad]: return dumps({'error': 7, 'message': 'Invalid step: ' + str(i['step']) + ' in ladder: ' + lad}) if i['step'] not in user['ladders'][lad]: return dumps({'error': 8, 'message': 'Can not teach step: ' + str(i['step']) + ' in ladder: ' + lad}) # if type(i['price']) != int or i['price'] < 0: # return dumps({'error': 9, 'message': 'Invalid count of tokens'}) user['steps'] = x['steps'] db['users'].save(user) url = '/static/load/users/' img = url + '0.png' for i in listdir('app' + url): if search(r'^' + str(user['id']) + '\.', i): img = url + i for i in db['teachers'].find({'user': user['id']}): socketio.emit('remove', { 'ladder': i['ladder'], 'step': i['step'], 'user': i['user'], }, namespace='/study') db['teachers'].remove(i['_id']) for i in x['steps']: socketio.emit('add', { 'ladder': i['ladder'], 'step': i['step'], 'user': user['id'], 'photo': img, 'name': user['name'], 'login': user['login'], 'rating': 0, 'tokens': i['price'], }, namespace='/study') db['teachers'].insert_one({ 'user': user['id'], 'ladder': i['ladder'], 'step': i['step'], 'price': i['price'], 'time': timestamp, }) return dumps({'error': 0}) # Получение пользователя elif x['method'] == 'users.get': mes = errors(x, ( ('token', False, str), ('id', True, int), )) if mes: return mes users = db['users'].find_one({'id': x['id']}, {'_id': False, 'password': False}) # Неправильный пользователь if not users: return dumps({'error': 6, 'message': 'User does not exsist'}) if users['admin'] < 3 and user['admin'] < 6: return dumps({'error': 7, 'message': 'The user is blocked'}) for i in users['ladders']: filter_db = {'_id': False, 'steps.id': True, 'steps.status': True, 'name': True} ladder = db['ladders'].find_one({'id': int(i)}, filter_db) step_all_published = [j['id'] for j in ladder['steps'] if j['status'] >= 3] j = 0 while j < len(users['ladders'][i]): if users['ladders'][i][j] not in step_all_published: del users['ladders'][i][j] else: j += 1 users['ladders'][i] = { 'name': ladder['name'], 'steps': users['ladders'][i], 'complete': len(set(users['ladders'][i]) & set(step_all_published)), 'all': len(step_all_published) } return dumps({'error': 0, 'user': users}) # Блокировка пользователя elif x['method'] == 'users.block': mes = errors(x, ( ('token', True, str), ('id', True, int), )) if mes: return mes users = db['users'].find_one({'id': x['id']}) # Неправильный пользователь if not users: return dumps({'error': 6, 'message': 'User does not exsist'}) # Нет прав на блокировку if user['admin'] < 6 or users['admin'] > user['admin']: return dumps({'error': 7, 'message': 'No access rights'}) users['admin'] = 1 db['users'].save(users) return dumps({'error': 0}) # Список пользователей elif x['method'] == 'members.gets': mes = errors(x, ( ('token', False, str), ('count', False, int), ('sort', False, int), )) if mes: return mes count = x['count'] if 'count' in x else None filter_db = {'_id': False, 'id': True, 'login': True, 'name': True, 'surname': True} # rating if 'sort' in x: users = db['users'].find({'admin': {'$gte': 2}}, filter_db).sort('rating.' + str(x['sort']), -1) else: users = db['users'].find({'admin': {'$gte': 2}}, filter_db) return dumps({'error': 0, 'users': [i for i in users[:count]]}) # Добавление новостей elif x['method'] == 'news.add': mes = errors(x, ( ('token', True, str), ('name', True, str), ('description', True, str), ('cont', True, str), ('preview', True, str), )) if mes: return mes try: id = db['news'].find({}, {'id': True, '_id': False}).sort('id', -1)[0]['id'] + 1 except: id = 1 # Нет прав на создание новости if user['admin'] < 6: return dumps({'error': 6, 'message': 'No access rights'}) query = { 'id': id, 'name': x['name'], 'description': x['description'], 'cont': reimg(x['cont'], 'news', 0, id), 'user': user['id'], 'time': timestamp, 'view': [], 'like': [], 'dislike': [], 'comment': [], } db['news'].insert(query) if 'preview' in x: try: load_image('app/static/load/news', x['preview'], id, x['file'].split('.')[-1] if 'file' in x else None) # Ошибка загрузки изображения except: return dumps({'error': 7, 'message': 'Error uploading image'}) return dumps({'error': 0, 'id': id}) # Изменение новостей elif x['method'] == 'news.edit': mes = errors(x, ( ('token', True, str), ('id', True, int), ('name', False, str), ('description', False, str), ('cont', False, str), ('preview', False, str), )) if mes: return mes query = db['news'].find_one({'id': x['id']}) # Неправильная новость if not query: return dumps({'error': 6, 'message': 'News does not exsist'}) # Нет прав на редактирование if user['admin'] < 6: return dumps({'error': 7, 'message': 'No access rights'}) for i in ('name', 'description'): if i in x: query[i] = x[i] if 'cont' in x: query['cont'] = reimg(x['cont']) db['news'].save(query) if 'preview' in x: try: load_image('app/static/load/news', x['preview'], x['id'], x['file'].split('.')[-1] if 'file' in x else None) # Ошибка загрузки изображения except: return dumps({'error': 8, 'message': 'Error uploading image'}) return dumps({'error': 0}) # Список новостей elif x['method'] == 'news.gets': mes = errors(x, ( ('token', False, str), ('count', False, int), )) if mes: return mes count = x['count'] if 'count' in x else None filter_db = {'_id': False, 'name': True, 'id': True} news = list(db['news'].find({}, filter_db).sort('time', -1)) return dumps({'error': 0, 'news': news}) # Получение новости elif x['method'] == 'news.get': mes = errors(x, ( ('token', False, str), ('id', True, int), )) if mes: return mes req = db['news'].find_one({'id': x['id']}) req['view'].append(user['id']) db['news'].save(req) # Неправильная новость if not req: return dumps({'error': 6, 'message': 'News does not exsist'}) # del req['_id'] del req['view'] del req['user'] return dumps({'error': 0, 'news': req}) # Удаление новости elif x['method'] == 'news.delete': mes = errors(x, ( ('token', True, str), ('id', True, int), )) if mes: return mes # Нет прав на удаление if user['admin'] < 6: return dumps({'error': 6, 'message': 'No access rights'}) news = db['news'].find_one({'id': x['id']}, {'_id': True}) # Неправильная новость if not news: return dumps({'error': 7, 'message': 'Wrong id of news'}) db['news'].remove(news['_id']) return dumps({'error': 0}) # Добавление ошибок и предложений elif x['method'] == 'feedback.add': mes = errors(x, ( ('token', False, str), ('name', True, str), ('cont', True, str), )) if mes: return mes try: id = db['feedback'].find({}, {'_id': False, 'id': True}).sort('id', -1)[0]['id'] + 1 except: id = 1 query = { 'id': id, 'name': x['name'], 'cont': reimg(x['cont'], 'feedbacks', 0, id), 'user': user['id'], 'time': timestamp, 'success': 0, } db['feedback'].insert(query) return dumps({'error': 0, 'id': id}) # Список ошибок и предложений elif x['method'] == 'feedback.gets': mes = errors(x, ( ('token', False, str), ('count', False, int), )) if mes: return mes # Нет прав на просмотр отзывов if user['admin'] < 4: return dumps({'error': 6, 'message': 'No access rights'}) count = x['count'] if 'count' in x else None news = list(db['feedback'].find({}, {'_id': False}).sort('time', -1)[0:count]) for i in range(len(news)): news[i]['user'] = get_user(news[i]['user']) return dumps({'error': 0, 'feedback': news}) # Удаление ошибок и предложений elif x['method'] == 'feedback.delete': mes = errors(x, ( ('token', True, str), ('id', True, int), )) if mes: return mes feedback = db['feedback'].find_one({'id': x['id']}, {'_id': True}) # Неправильный отзыв if not feedback: return dumps({'error': 6, 'message': 'Wrong id of ladder'}) # Нет прав на удаление отзыва if user['admin'] < 5: return dumps({'error': 7, 'message': 'No access rights'}) db['feedback'].remove(feedback['_id']) return dumps({'error': 0}) # Поиск elif x['method'] == 'search': mes = errors(x, ( ('token', False, str), ('cont', True, str), )) if mes: return mes # Пустой запрос if not x['cont']: return dumps({'error': 6, 'message': 'Empty request'}) # Новости news = [] for i in db['news'].find({}, {'_id': False, 'name': True, 'description': True, 'cont': True, 'comment': True, 'id': True}): if any(x['cont'] in j.lower() for j in (i['name'], i['description'], i['cont'])) or any(x['cont'] in j.lower() for j in i['comment']): news.append(i) # Пользователи users = [] for i in db['users'].find({}, {'_id': False, 'name': True, 'surname': True, 'mail': True, 'description': True, 'id': True, 'login': True}): if any(x['cont'] in j.lower() for j in (i['name'], i['surname'], i['mail'], i['description'], i['login'])): users.append(i) # Ледеры ladders = [] for i in db['ladders'].find({}, {'_id': False, 'name': True, 'description': True, 'comment': True, 'tags': True, 'id': True, 'steps.complete': True}): if any(x['cont'] in j.lower() for j in (i['name'], i['description'])) or any(x['cont'] in j.lower() for j in i['tags']) or any(x['cont'] in j.lower() for j in i['comment']): ladders.append(i) if len(ladders): print(ladders) for i in range(len(ladders)): ladders[i]['complete'] = sum(len(j['complete']) for j in ladders[i]['steps']) ladders.sort(key=lambda i: i['complete'], reverse=-1) for i in range(len(ladders)): del ladders[i]['steps'] del ladders[i]['complete'] # Степы steps = [] filter_db = { '_id': False, 'id': True, 'steps.name': True, 'steps.cont': True, 'steps.theory': True, 'steps.options': True, 'steps.id': True, 'steps.comment': True, } status = 3 if user['admin'] < 5 else 1 for i in db['ladders'].find({'status': {'$gte': status}}, filter_db): for j in i['steps']: if any(x['cont'] in u.lower() for u in (j['name'], j['cont'], j['theory'])) or any(x['cont'] in u.lower() for u in j['comment']) or any(x['cont'] in u.lower() for u in j['options']): j['ladder'] = i['id'] steps.append(j) res = { 'error': 0, 'news': news, 'users': users, 'ladders': ladders, 'steps': steps, 'comments': [], } return dumps(res) # Добавить сообщение elif x['method'] == 'space.add': mes = errors(x, ( ('token', False, str), ('id', True, int), ('cont', True, str), )) if mes: return mes study = db['study'].find_one({'id': x['id']}) if not study: return dumps({'error': 6, 'message': 'Training session does not exsist'}) if not x['cont']: return dumps({'error': 7, 'message': 'Empty message'}) if len(study['messages']): id = study['messages'][-1]['id'] + 1 else: id = 1 out = study['student'] == user['id'] x['cont'] = reimg(x['cont'], 'spaces', x['id'], id) study['messages'].append({ 'id': id, 'out': out, 'cont': x['cont'], 'time': timestamp, }) db['study'].save(study) socketio.emit('message', { 'session': x['id'], 'id': id, 'out': out, 'cont': x['cont'], 'time': timestamp, }, namespace='/space') return dumps({'error': 0}) # Получение категорий # elif x['method'] == 'categories.gets': # categories = [] # for i in db['categories'].find().sort('priority', -1): #{"$unwind": "$Applicants"} # # print('!!!', i) # # time.sleep(2) # del i['_id'] # categories.append(i) # return dumps(categories) # db['categories'].insert({ # 'id': 1, # 'parent': 0, # 'name': 'Раздел 1', # 'url': 'art', # 'priority': 50, # 'plus': 'ladder', # }) else: return dumps({'error': 2, 'message': 'Wrong method'}) # Серверная ошибка except Exception as e: print(e) return dumps({'error': 1, 'message': 'Server error'}) @socketio.on('connect', namespace='/teach') def test_connect(): emit('my_response', {'data': 'Connected', 'count': 0}) @socketio.on('wait', namespace='/teach') def wait_teach(mes): for i in db['teachers'].find({'user': mes['id']}): i['time'] = time.time() db['teachers'].save(i) # Убрать в общее пространство @socketio.on('cancel', namespace='/teach') def cancel_teach(mes): study = db['study'].find_one({'id': mes['id']}) study['status'] = 5 db['study'].save(study) socketio.emit('cancel', { 'id': mes['id'], }, namespace='/space') @socketio.on('cancel', namespace='/main') def cancel_teach(mes): study = db['study'].find_one({'id': mes['id']}) study['status'] = 5 db['study'].save(study) socketio.emit('cancel', { 'id': mes['id'], }, namespace='/space') @socketio.on('stop_yes', namespace='/space') def stop_yes(mes): # study = db['study'].find_one({'id': mes['id']}) users = db['users'].find_one({'id': study['teacher']}) users['balance'] += int(study['price'] * 0.9) db['users'].save(users) ladder = db['ladders'].find_one({'id': study['ladder']}) steps_all = [i['id'] for i in ladder['steps']] step_num = steps_all.index(study['step']) users = db['users'].find_one({'id': ladder['steps'][step_num]['user']}) users['balance'] += int(study['price'] * 0.03) db['users'].save(users) ladder['steps'][step_num]['total'] += int(study['price'] * 0.03) db['ladders'].save(ladder) # socketio.emit('stop_yes', { 'id': mes['id'], }, namespace='/space') @socketio.on('stop_no', namespace='/space') def stop_no(mes): socketio.emit('stop_no', { 'id': mes['id'], }, namespace='/space') @socketio.on('student_accept', namespace='/space') def student_accept(mes): study = db['study'].find_one({'id': mes['id']}) study['status'] = 19 # 14 db['study'].save(study) # users = db['users'].find_one({'id': study['student']}) users['balance'] -= study['price'] db['users'].save(users) # socketio.emit('accept_to_teacher', { 'id': mes['id'], }, namespace='/space') @socketio.on('student_cancel', namespace='/space') def student_cancel(mes): study = db['study'].find_one({'id': mes['id']}) study['status'] = 15 db['study'].save(study) socketio.emit('cancel_to_teacher', { 'id': mes['id'], }, namespace='/space') @socketio.on('public', namespace='/reg') def reg_private(mes): user_id = db['tokens'].find_one({'token': mes['token']})['id'] users = db['users'].find_one({'id': user_id}) users['public'] = mes['key'] db['users'].save(users) @socketio.on('password', namespace='/auth') def check_password(mes): users = db['users'].find_one({'id': mes['id'], 'password': mes['cont']}) res = True if users else False socketio.emit('result', { 'id': mes['id'], 'cont': res, }, namespace='/auth') @socketio.on('online', namespace='/main') def online_users(mes): global thread with thread_lock: if thread is None: thread = socketio.start_background_task(target=background_thread) x = db['online'].find_one({'user': mes['id']}) if x: x['time'] = time.time() db['online'].save(x) else: y = db['users'].find_one({'id': mes['id']}, {'_id': False, 'steps': True}) x = { 'user': mes['id'], 'time': time.time(), 'steps': y['steps'], } db['online'].insert_one(x) socketio.emit('user_add', { 'id': mes['id'], }, namespace='/study') if __name__ == '__main__': socketio.run(app, debug=True) def background_thread(): while True: timestamp = time.time() # Удалять старые объявления об обучении for i in db['teachers'].find(): if timestamp - i['time'] > 60: socketio.emit('remove', { 'ladder': i['ladder'], 'step': i['step'], 'user': i['user'], }, namespace='/study') db['teachers'].remove(i['_id']) # Ученик не подтвердил вовремя начало урока for i in db['study'].find({'status': 1}): if timestamp - i['time'] > 60: socketio.emit('student_cancel', { 'id': i['id'], }, namespace='/study') i['status'] = 16 db['study'].save(i) # Если учитель не открыл вовремя урок for i in db['study'].find({'status': 0}): if timestamp - i['time'] > 60: i['status'] = 11 db['study'].save(i) for j in db['teachers'].find({'user': i['teacher']}): socketio.emit('remove', { 'ladder': j['ladder'], 'step': j['step'], 'user': j['user'], }, namespace='/study') db['teachers'].remove(j['_id']) socketio.emit('timeout', { 'id': i['id'], }, namespace='/space') socketio.emit('timeout', { 'id': i['teacher'], }, namespace='/teach') # Если долго не было сообщений for i in db['study'].find({'status': {'$in': (14, 18, 19)}}): # 5 минут от пользователей if len(i['messages']): if timestamp - i['messages'][-1]['time'] > 300: i['status'] = 7 if i['messages'][-1]['out'] else 6 db['study'].save(i) socketio.emit('time', { 'id': i['id'], }, namespace='/space') else: if timestamp - i['time'] > 300: i['status'] = 13 db['study'].save(i) socketio.emit('time', { 'id': i['id'], }, namespace='/space') # 25 минут с начала урока if timestamp - i['time'] > 1500: i['status'] = 12 db['study'].save(i) socketio.emit('time', { 'id': i['id'], }, namespace='/space') # Ожидание транзакций # for i in db['study'].find({'status': 14}): # url = 'http://172.16.58.3:3000/searchlogs/%s/latest/%s/%s' % (i['height'], CONTRACT_ADDRESS, TOPIC_LESSON_PREPARED) # print('!!!', url) # x = loads(requests.get(url).text) # wallet = db['users'].find_one({'id': i['teacher']})['public'] # if len(x['data']): # req = { # 'id': i['id'], # 'teacher': wallet, # 'price': i['price'], # } # socketio.emit('transaction_teacher', req, namespace='/space') # i['status'] = 18 # db['study'].save(i) # for i in db['study'].find({'status': 18}): # url = 'http://172.16.58.3:3000/searchlogs/%s/latest/%s/%s' % (i['height'], CONTRACT_ADDRESS, TOPIC_LESSON_STARTED) # print('!!!', url) # x = loads(requests.get(url).text) # if len(x['data']): # req = { # 'id': i['id'], # } # socketio.emit('transaction_student', req, namespace='/space') # i['status'] = 19 # db['study'].save(i) # Удаление онлайн пользователей for i in db['online'].find({'time': {'$lt': timestamp - 15}}): socketio.emit('user_remove', { 'id': i['user'], }, namespace='/study') db['online'].remove(i['_id']) time.sleep(15)<file_sep>/app/sys_study_stop.py from flask import session, request, render_template, redirect from app import app, LINK from requests import post import json @app.route('/sys_study_stop/<int:id>') @app.route('/sys_study_stop/<int:id>/') def sys_study_stop(id): ip = request.remote_addr status = int(request.args.get('status')) req = { 'method': 'study.stop', 'token': session['token'], 'ip': ip, 'id': id, 'status': status, } req = json.loads(post(LINK, json=req).text) if req['error']: return render_template('message.html', cont=req['message']) return redirect(LINK + 'ladder/' + str(req['ladder']) + '/question/' + str(req['step']))<file_sep>/app/index.py from flask import render_template, session, request from app import app, LINK, get_preview from requests import post from json import loads @app.route('/', methods=['GET']) @app.route('/index') @app.route('/index/') def index(): ip = request.remote_addr user = loads(post(LINK, json={'method': 'users.get', 'ip': ip, 'id': session['id']}).text)['user'] if 'id' in session else {'id': 0, 'admin': 2} return render_template('index.html', title = 'Main', description = '', tags = ['main page', 'tensegrity'], url = 'index', # categories = loads(post(LINK, json={'method': 'categories.gets'}).text), user = user, LINK = LINK, without_menu = True, )<file_sep>/app/login.py from flask import render_template, session, request from app import app, LINK from requests import post from json import loads @app.route('/login') @app.route('/login/') def login(): ip = request.remote_addr user = loads(post(LINK, json={'method': 'users.get', 'ip': ip, 'id': session['id']}).text)['user'] if 'id' in session else {'id': 0, 'admin': 2} redirect = request.args.get('url') return render_template('login.html', title = 'Account', description = 'Sign Up / Log In', tags = ['Sign Up', 'Log In'], url = 'login?url=' + redirect, user = user, LINK = LINK, without_menu = True, redirect = redirect, )<file_sep>/app/sys_step_check.py from flask import session, request, render_template, redirect from app import app, LINK from requests import post import json @app.route('/sys_step_check', methods=['POST']) def sys_step_check(): ip = request.remote_addr x = request.form ladder = request.args.get('ladder') id = request.args.get('step') if 'token' not in session: return redirect(LINK + 'login?url=ladder/' + ladder + '/question/' + id) req = { 'method': 'step.check', 'token': session['token'], 'ip': ip, 'ladder': int(ladder), 'step': int(id), 'answers': [int(i) for i in x if x[i] == '1'], } correct = json.loads(post(LINK, json=req).text) if correct['error']: return render_template('message.html', cont=correct['message']) if correct['correct']: return redirect(LINK + 'ladder/' + ladder + '/question/' + str(correct['step'])) else: return redirect(LINK + 'ladder/' + ladder + '/study/' + id + '/?error=1')<file_sep>/app/wait.py from flask import session, request, render_template, redirect from app import app, LINK from requests import post from json import loads @app.route('/wait', methods=['POST']) def wait(): ip = request.remote_addr user = loads(post(LINK, json={'method': 'users.get', 'ip': ip, 'id': session['id']}).text)['user'] if 'id' in session else {'id': 0, 'admin': 2} if 'token' in session: x = request.form # По степу получать, добавить цену step_list = [] for i in x: if '-' in i: y = i.split('-') step_list.append({ 'ladder': int(y[0]), 'step': int(y[1]), 'price': int(x[y[0] + 'price' + y[1]]), }) req = { 'method': 'teach.start', 'token': session['token'], 'ip': ip, 'steps': step_list, } req = loads(post(LINK, json=req).text) if not req['error']: return render_template('wait.html', title = 'Wait', description = 'wait', tags = ['wait'], url = 'wait', user = user, LINK = LINK, ) else: return render_template('message.html', cont=req['message']) else: return redirect(LINK + 'login?url=teach')<file_sep>/app/feedback.py from flask import render_template, session, redirect, request from app import app, LINK from requests import post from json import loads @app.route('/feedback') @app.route('/feedback/') def feedback(): ip = request.remote_addr user = loads(post(LINK, json={'method': 'users.get', 'ip': ip, 'id': session['id']}).text)['user'] if 'id' in session else {'id': 0, 'admin': 2} link = request.args.get('url') return render_template('feedback.html', title = 'Feedback', description = 'Feedback & troubles', tags = ['feedback', 'troubles'], url = 'feedback', user = user, LINK = LINK, link = link, )<file_sep>/app/sys_step_delete.py from flask import session, request, render_template, redirect from app import app, LINK from requests import post import json @app.route('/sys_step_delete') def sys_step_delete(): ip = request.remote_addr id = request.args.get('ladder') step = int(request.args.get('step')) num = request.args.get('num') req = { 'method': 'step.delete', 'token': session['token'], 'ip': ip, 'ladder': int(id), 'step': step, } req = json.loads(post(LINK, json=req).text) if not req['error']: if num: return redirect(LINK + 'ladder/' + id + '/?edit=1#' + str(req['num'])) else: return redirect(LINK + 'ladder/' + id + '/question/' + str(req['step'])) else: return render_template('message.html', cont=req['message'])<file_sep>/app/sys_news_edit.py from flask import session, request, render_template, redirect from app import app, LINK from requests import post import re, json, base64 @app.route('/sys_news_edit', methods=['POST']) def sys_news_edit(): ip = request.remote_addr x = request.form id = request.args.get('id') req = { 'method': 'news.edit', 'token': session['token'], 'ip': ip, 'id': int(id), 'name': x['name'], 'description': x['description'].replace('\r', '').replace('\n', '<br>'), 'cont': x['cont'], } if 'preview' in request.files: y = request.files['preview'].stream.read() y = str(base64.b64encode(y))[2:-1] req['preview'] = y req['file'] = request.files['preview'].filename req = json.loads(post(LINK, json=req).text) if not req['error']: return redirect(LINK + 'news/' + id) else: return render_template('message.html', cont=req['message'])<file_sep>/app/ladder.py from flask import render_template, session, request, Markup, redirect from app import app, LINK, get_preview from requests import post from json import loads import markdown import re @app.route('/ladder/<int:id>') @app.route('/ladder/<int:id>/') def ladder(id): ip = request.remote_addr user = loads(post(LINK, json={'method': 'users.get', 'ip': ip, 'id': session['id']}).text)['user'] if 'id' in session else {'id': 0, 'admin': 2} edit = request.args.get('edit') url = 'ladder/%d' % id if edit: url += '?edit=1' if edit and 'token' not in session: return redirect(LINK + 'login?url=' + url) req = { 'method': 'ladders.get', 'ip': ip, 'id': id, } if 'token' in session: req['token'] = session['token'] req = loads(post(LINK, json=req).text) if req['error']: return render_template('message.html', cont=req['message']) ladder = req['ladder'] if not edit: ladder['description'] = Markup(markdown.markdown(ladder['description'])) else: ladder['description'] = ladder['description'].replace('<br>', '\r\n') req2 = { 'method': 'step.gets', 'ip': ip, 'ladder': id, } if 'token' in session: req2['token'] = session['token'] steps = loads(post(LINK, json=req2).text) return render_template('ladder_edit.html' if edit and user['admin'] >= 5 else 'ladder.html', title = ladder['name'], description = re.sub(r'\<[^>]*\>', '', ladder['description']), tags = ladder['tags'], url = url, user = user, LINK = LINK, preview = get_preview, enumerate = enumerate, str = str, ladder = ladder, step = req['step'], num = req['num'], experts = req['experts'], steps = steps['steps'], user_steps = req['steps'], )<file_sep>/app/sys_sign_out.py from flask import session, request #redirect from app import app, LINK from requests import post @app.route('/sys_sign_out') def out(): ip = request.remote_addr if 'token' in session: req ={ 'cm': 'profile.exit', 'token': session['token'], 'ip': ip, } post(LINK, json=req) session.pop('token', None) session.pop('id', None) return '<script>document.location.href = document.referrer</script>' #redirect(request.url, code=302)<file_sep>/app/sys_feedback.py from flask import session, request, render_template, redirect from app import app, LINK, CAPTCHA from requests import post import re, json, base64 @app.route('/sys_feedback', methods=['POST']) def sys_feedback(): ip = request.remote_addr x = request.form req = { 'secret': CAPTCHA, 'response': x['g-recaptcha-response'], 'remoteip': request.remote_addr, } y = post('https://www.google.com/recaptcha/api/siteverify', params=req).text if not json.loads(y)['success']: return render_template('message.html', cont='Wrong captcha!') req = { 'method': 'feedback.add', 'ip': ip, 'name': x['name'], 'cont': x['cont'], } if 'token' in session: req['token'] = session['token'] req = json.loads(post(LINK, json=req).text) if not req['error']: return redirect(LINK + '/' + request.args.get('url')) else: return render_template('message.html', cont=req['message'])<file_sep>/app/ladders.py from flask import render_template, session, request from app import app, LINK, get_preview from requests import post from json import loads @app.route('/ladder') @app.route('/ladder/') @app.route('/ladders') @app.route('/ladders/') @app.route('/ladders/<sub>') def ladders(sub=''): ip = request.remote_addr user = loads(post(LINK, json={'method': 'users.get', 'ip': ip, 'id': session['id']}).text)['user'] if 'id' in session else {'id': 0, 'admin': 2} title = 'Ladders' #change with category tags = ['ladders', 'courses'] req = { 'method': 'ladders.gets', 'ip': ip, # 'category': subcategory if subcategory else category, } if 'token' in session: req['token'] = session['token'] ladders = loads(post(LINK, json=req).text)['ladders'] return render_template('ladders.html', title = title, description = '', tags = tags, url = 'ladders/' + sub, user = user, LINK = LINK, preview = get_preview, ladders = ladders, )<file_sep>/app/news_add.py from flask import render_template, session, redirect, request from app import app, LINK from requests import post from json import loads @app.route('/admin/news/add') @app.route('/admin/news/add/') def news_add(): ip = request.remote_addr user = loads(post(LINK, json={'method': 'users.get', 'ip': ip, 'id': session['id']}).text)['user'] if 'id' in session else {'id': 0, 'admin': 2} url = 'admin/news/add' if user['admin'] < 6: return render_template('message.html', cont='No access rights') return render_template('news_add.html', title = 'Add news', description = 'Add news', tags = ['admin', 'add news'], url = url, user = user, LINK = LINK, )<file_sep>/app/step_add.py from flask import render_template, session, redirect, request from app import app, LINK from requests import post from json import loads @app.route('/admin/add/step/<int:ladder>/<int:step>') @app.route('/admin/add/step/<int:ladder>/<int:step>/') @app.route('/admin/add/step/<int:ladder>') @app.route('/admin/add/step/<int:ladder>/') def step_add(ladder, step=None): ip = request.remote_addr user = loads(post(LINK, json={'method': 'users.get', 'ip': ip, 'id': session['id']}).text)['user'] if 'id' in session else {'id': 0, 'admin': 2} url = 'admin/add/step/%d%s' % (ladder, '' if step == None else ('/' + str(step))) after = True if request.args.get('after') else False if 'token' in session: steps = loads(post(LINK, json={ 'method': 'step.gets', 'token': session['token'], 'ip': ip, 'ladder': ladder, }).text) return render_template('step_add.html', title = 'Add step', description = 'Admin panel: add step', tags = ['admin panel', 'add step'], url = url, user = user, LINK = LINK, ladder = ladder, step = step, after = after, steps = steps['steps'], ) else: return redirect(LINK + 'login?url=' + url)<file_sep>/app/search.py from flask import session, request, render_template, redirect from app import app, LINK, get_preview from requests import post from json import loads @app.route('/search', methods=['POST']) @app.route('/search/<cont>') @app.route('/search/<cont>/') def search(cont=''): ip = request.remote_addr user = loads(post(LINK, json={'method': 'users.get', 'ip': ip, 'id': session['id']}).text)['user'] if 'id' in session else {'id': 0, 'admin': 2} if not cont: cont = request.form['search'] return redirect(LINK + 'search/' + cont) if not cont: return render_template('message.html', cont='Здесь страница с поиском') req = { 'method': 'search', 'ip': ip, 'cont': cont, } if 'token' in session: req['token'] = session['token'] req = loads(post(LINK, json=req).text) if not req['error']: return render_template('search.html', title = 'Search', description = 'Search', tags = ['search'], url = 'search/' + cont, user = user, LINK = LINK, preview = get_preview, news = req['news'], users = req['users'], ladders = req['ladders'], steps = req['steps'], comments = req['comments'], ) else: return render_template('message.html', cont=req['message'])<file_sep>/app/news.py from flask import render_template, session, request, Markup, redirect from app import app, LINK, get_preview from requests import post from json import loads import markdown import re from time import strftime, gmtime def time(x): return strftime('%d.%m.%Y %H:%M:%S', gmtime(x)) @app.route('/news/<int:id>') @app.route('/news/<int:id>/') def news(id): ip = request.remote_addr user = loads(post(LINK, json={'method': 'users.get', 'ip': ip, 'id': session['id']}).text)['user'] if 'id' in session else {'id': 0, 'admin': 2} edit = request.args.get('edit') url = 'news/%d' % id if edit: url += '?edit=1' if edit and 'token' not in session: return redirect(LINK + 'login?url=' + url) req = { 'method': 'news.get', 'ip': ip, 'id': id, } if 'token' in session: req['token'] = session['token'] new = loads(post(LINK, json=req).text)['news'] if not edit: new = dict(new) new['description'] = Markup(markdown.markdown(new['description'])) new['cont'] = Markup(new['cont']) else: new['description'] = new['description'].replace('<br>', '\r\n') return render_template('news_edit.html' if edit else 'news.html', title = new['name'], description = re.sub(r'\<[^>]*\>', '', new['description']), tags = ['news'], url = url, user = user, LINK = LINK, preview = get_preview, time = time, news = new, )<file_sep>/app/members.py from flask import render_template, session, request from app import app, LINK, get_preview from requests import post from json import loads @app.route('/user') @app.route('/user/') @app.route('/users') @app.route('/users/') @app.route('/members') @app.route('/members/') def members(): ip = request.remote_addr user = loads(post(LINK, json={'method': 'users.get', 'ip': ip, 'id': session['id']}).text)['user'] if 'id' in session else {'id': 0, 'admin': 2} req = { 'method': 'members.gets', 'ip': ip, } if 'token' in session: req['token'] = session['token'] members = loads(post(LINK, json=req).text)['users'] return render_template('members.html', title = 'Members', description = 'Users, members', tags = ['users', 'members'], url = 'members', user = user, LINK = LINK, preview = get_preview, members = members, )<file_sep>/app/study.py from flask import render_template, session, redirect, request from app import app, LINK, get_preview from requests import post from json import loads @app.route('/ladder/<int:ladder>/study/<int:step>') @app.route('/ladder/<int:ladder>/study/<int:step>/') def study(ladder, step): ip = request.remote_addr user = loads(post(LINK, json={'method': 'users.get', 'ip': ip, 'id': session['id']}).text)['user'] if 'id' in session else {'id': 0, 'admin': 2} if 'token' in session: req = loads(post(LINK, json={ 'method': 'study.gets', 'token': session['token'], 'ip': ip, 'ladder': ladder, 'step': step, }).text) if req['error']: return render_template('message.html', cont=req['message']) return render_template('study.html', title = 'Study', description = '', tags = ['study', 'ladder'], url = 'ladder/%d/study/%d' % (ladder, step), user = user, LINK = LINK, preview = get_preview, ladder = ladder, step = step, bot = req['bot'], # Markup(markdown.markdown(loads(post(LINK, json={'method': 'step.get', 'ladder': ladder, 'step': step}).text)['step']['theory'])), teachers = req['teachers'], users = req['users'], online = req['online'], error = request.args.get('error'), ) else: return redirect(LINK + 'login?url=ladder/%d/study/%d' % (ladder, step))<file_sep>/app/sys_sign_in.py from flask import session, request, render_template from app import app, LINK, get_url from requests import post import json @app.route('/sys_sign_in', methods=['POST']) def signin(): ip = request.remote_addr x = request.form if not all([i in x for i in ('login', 'pass')]): return render_template('message.html', cont='3') req = { 'method': 'profile.auth', 'ip': ip, 'login': x['login'], 'pass': x['pass'], } req = json.loads(post(LINK, json=req).text) if not req['error']: session['token'] = req['token'] session['id'] = req['id'] return get_url(request.args.get('url')) # get_url('token/?url=' + request.args.get('url')) else: return render_template('message.html', cont=req['message'])<file_sep>/app/admin.py from flask import render_template, session, Markup, request from app import app, LINK from requests import post from json import loads @app.route('/admin') @app.route('/admin/') def admin(): ip = request.remote_addr user = loads(post(LINK, json={'method': 'users.get', 'ip': ip, 'id': session['id']}).text)['user'] if 'id' in session else {'id': 0, 'admin': 2} if user['admin'] < 4: return render_template('message.html', cont='No access rights') req = { 'method': 'feedback.gets', 'token': session['token'], 'ip': ip, } feedback = loads(post(LINK, json=req).text) for i in range(len(feedback['feedback'])): feedback['feedback'][i]['cont'] = Markup(feedback['feedback'][i]['cont']) return render_template('admin.html', title = 'Admin', description = 'Admin', tags = ['admin'], url = 'admin', user = user, LINK = LINK, feedback = feedback['feedback'], )<file_sep>/app/sys_step_edit.py from flask import session, request, render_template, redirect from app import app, LINK from requests import post import json @app.route('/sys_step_edit', methods=['POST']) def sys_step_edit(): ip = request.remote_addr x = request.form ladder = request.args.get('ladder') step = request.args.get('step') req = { 'method': 'step.edit', 'token': session['token'], 'ip': ip, 'ladder': int(ladder), 'step': int(step), 'name': x['name'], 'cont': x['cont'], 'options': [i.replace('\r', '').replace('\n', '<br>') for i in x['options'].split(';') if i], } step_list = json.loads(post(LINK, json={ 'method': 'step.gets', 'token': session['token'], 'ip': ip, 'ladder': int(ladder), }).text)['steps'] if 'after' in x: if x['after'] != '-1': req['id'] = int(x['after']) req['after'] = True else: req['id'] = step_list[0][0] req['after'] = False elif 'before' in x: if x['before'] != '-1': req['id'] = int(x['before']) req['after'] = False else: req['id'] = step_list[-1][0] req['after'] = True req = json.loads(post(LINK, json=req).text) if not req['error']: return redirect(LINK + 'admin/edit/step/' + ladder + '/' + step) else: return render_template('message.html', cont=req['message'])<file_sep>/README.md # Tensy For Hedera global hackathon [tensy.org](http://tensy.org/) <file_sep>/app/user.py from flask import render_template, session, Markup, request from app import app, LINK, get_preview from requests import post from json import loads import markdown @app.route('/user/<int:id>') @app.route('/user/<int:id>/') def user(id): ip = request.remote_addr user = loads(post(LINK, json={'method': 'users.get', 'ip': ip, 'id': session['id']}).text)['user'] if 'id' in session else {'id': 0, 'admin': 2} req = { 'method': 'users.get', 'ip': ip, 'id': id, } if 'token' in session: req['token'] = session['token'] users = loads(post(LINK, json=req).text) if users['error']: return render_template('message.html', cont=users['message']) users = users['user'] users['description'] = Markup(markdown.markdown(users['description'])) return render_template('user.html', title = '', description = '', tags = [], url = 'user/%d' % id, user = user, LINK = LINK, preview = get_preview, round = round, users = users, )<file_sep>/app/ladder_add.py from flask import render_template, session, redirect, request from app import app, LINK from requests import post from json import loads @app.route('/admin/add/ladder') @app.route('/admin/add/ladder/') def add_ladder(): ip = request.remote_addr user = loads(post(LINK, json={'method': 'users.get', 'ip': ip, 'id': session['id']}).text)['user'] if 'id' in session else {'id': 0, 'admin': 2} url = 'admin/add/ladder' if 'token' in session: return render_template('ladder_add.html', title = 'Add ladder', description = 'Admin panel: add ladder', tags = ['admin panel', 'add ladder'], url = url, user = user, LINK = LINK, ) else: return redirect(LINK + 'login?url=' + url)<file_sep>/app/sys_user_block.py from flask import session, request, redirect, render_template from app import app, LINK from requests import post import json @app.route('/sys_user_block/<int:id>') @app.route('/sys_user_block/<int:id>/') def sys_user_block(id): ip = request.remote_addr if 'token' not in session: return redirect(LINK + 'login?url=user/' + str(id)) req = json.loads(post(LINK, json={ 'method': 'users.block', 'token': session['token'], 'ip': ip, 'id': id, }).text) if req['error']: return render_template('message.html', cont=req['message']) return redirect(LINK + 'members')<file_sep>/app/__init__.py from flask import Flask, redirect import os import re from params import * app = Flask(__name__) app.config.from_object('config') def get_url(url, rep='competions'): if not url: url = rep if url == 'index': url = '' return redirect(LINK + url) def get_preview(url, num=0): url = '/static/load/' + url + '/' for i in os.listdir('app' + url): if re.search(r'^' + str(num) + '\.', i): return url + i return url + '0.png' from app import api from app import index from app import admin from app import news from app import news_add from app import search from app import login from app import cabinet from app import wallet from app import password from app import token from app import codex from app import feedback from app import about from app import news_all from app import errors from app import sys_sign_up from app import sys_sign_in from app import sys_sign_out from app import sys_profile_edit from app import sys_ladder_add from app import sys_ladder_edit from app import sys_step_add from app import sys_step_edit from app import sys_step_more from app import sys_step_delete from app import sys_step_check from app import sys_feedback from app import sys_feedback_delete from app import sys_news_add from app import sys_news_edit from app import sys_news_delete from app import sys_study from app import sys_space from app import sys_study_stop from app import sys_user_block from app import user from app import members from app import ladder from app import ladders from app import ladder_add from app import step from app import step_add from app import step_edit from app import study from app import step_end from app import teach from app import wait from app import space<file_sep>/app/sys_step_more.py from flask import session, request, render_template, redirect from app import app, LINK from requests import post import json @app.route('/sys_step_more', methods=['POST']) def sys_step_more(): ip = request.remote_addr x = request.form ladder = request.args.get('ladder') step = request.args.get('step') req = { 'method': 'step.edit', 'token': session['token'], 'ip': ip, 'ladder': int(ladder), 'step': int(step), 'theory': x['theory'], 'answers': [int(i) for i in x if x[i] == '1'], } req = json.loads(post(LINK, json=req).text) if not req['error']: href = request.args.get('href') if href: return redirect(LINK + 'ladder/' + ladder + '/?edit=1#' + step) else: return redirect(LINK + 'ladder/' + ladder + '/question/' + step) else: return render_template('message.html', cont=req['message'])<file_sep>/app/sys_sign_up.py from flask import session, request, render_template, redirect from app import app, LINK, CAPTCHA from requests import post import json @app.route('/sys_sign_up', methods=['POST']) def signup(): ip = request.remote_addr x = request.form req = { 'secret': CAPTCHA, 'response': x['g-recaptcha-response'], 'remoteip': request.remote_addr, } y = post('https://www.google.com/recaptcha/api/siteverify', params=req).text if not json.loads(y)['success']: return render_template('message.html', cont='Wrong captcha!') if not all([i in x for i in ('login', 'pass', 'name', 'surname', 'mail')]): return render_template('message.html', cont='3') req = { 'method': 'profile.reg', 'ip': ip, 'login': x['login'], 'pass': x['pass'], 'mail': x['mail'], 'name': x['name'], 'surname': x['surname'], } req = json.loads(post(LINK, json=req).text) if not req['error']: session['token'] = req['token'] session['id'] = req['id'] return redirect(LINK + 'cabinet?url=' + request.args.get('url')) else: return render_template('message.html', cont=req['message'])<file_sep>/app/sys_news_delete.py from flask import session, request, render_template, redirect from app import app, LINK from requests import post import json @app.route('/sys_news_delete') def sys_news_delete(): ip = request.remote_addr id = request.args.get('id') req = json.loads(post(LINK, json={ 'method': 'news.delete', 'token': session['token'], 'ip': ip, 'id': int(id), }).text) if not req['error']: return redirect(LINK) else: return render_template('message.html', cont=req['message'])<file_sep>/app/teach.py from flask import render_template, session, request, redirect from app import app, LINK from requests import post from json import loads @app.route('/teach') @app.route('/teach/') def teach(): ip = request.remote_addr user = loads(post(LINK, json={'method': 'users.get', 'ip': ip, 'id': session['id']}).text)['user'] if 'id' in session else {'id': 0, 'admin': 2} if 'token' in session: not_empty = False for ladder in user['ladders']: req = loads(post(LINK, json={'method': 'ladders.get', 'ip': ip, 'id': int(ladder), 'token': session['token']}).text)['ladder'] for step in range(len(user['ladders'][ladder]['steps'])): id = user['ladders'][ladder]['steps'][step] name = '' price = 0 checked = False not_empty = True for i in req['steps']: if i['id'] == id: name = i['name'] price = i['price'] for i in user['steps']: if i['ladder'] == int(ladder) and i['step'] == id: checked = True price = i['price'] user['ladders'][ladder]['steps'][step] = { 'id': id, 'name': name, 'price': price, 'checked': checked, } return render_template('teach.html', title = 'Teach', description = 'teach', tags = ['teach'], url = 'teach', user = user, LINK = LINK, error = request.args.get('error'), not_empty = not_empty, ) else: return redirect(LINK + 'login?url=teach')<file_sep>/app/sys_study.py from flask import render_template, session, request, Markup, redirect from app import app, LINK from requests import post from json import loads @app.route('/sys_study') @app.route('/sys_study/') def sys_study(): ip = request.remote_addr if 'token' in session: req = loads(post(LINK, json={ 'method': 'study.start', 'token': session['token'], 'ip': ip, 'ladder': int(request.args.get('ladder')), 'step': int(request.args.get('step')), 'teacher': int(request.args.get('user')), }).text) if req['error']: return render_template('message.html', cont=req['message']) src = LINK + 'space/' + str(req['id']) return redirect(src) else: return redirect(LINK + 'login?url=' + url)<file_sep>/requirements.txt certifi==2018.4.16 chardet==3.0.4 click==6.7 Flask==1.0.2 Flask-SocketIO==3.0.1 idna==2.7 itsdangerous==0.24 Jinja2==2.10 Markdown==2.6.11 MarkupSafe==1.0 pymongo==3.7.1 python-engineio==2.2.0 python-socketio==2.0.0 requests==2.19.1 six==1.11.0 urllib3==1.23 uWSGI==2.0.17.1 Werkzeug==0.14.1 <file_sep>/app/cabinet.py from flask import render_template, session, request, redirect from app import app, LINK, get_preview from requests import post from json import loads @app.route('/cabinet') @app.route('/cabinet/') def cabinet(): ip = request.remote_addr user = loads(post(LINK, json={'method': 'users.get', 'ip': ip, 'id': session['id']}).text)['user'] if 'id' in session else {'id': 0, 'admin': 2} x = request.args.get('url') if 'token' in session: user['description'] = user['description'].replace('<br>', '\r\n') return render_template('cabinet.html', title = 'Profile', description = 'Profile, personal area, settings, account', tags = ['profile', 'personal area', 'settings', 'account'], url = 'cabinet', user = user, LINK = LINK, preview = get_preview, loc = x if x else 'cabinet', token = session['token'], ) else: return redirect(LINK + 'login?url=cabinet')<file_sep>/app/step_end.py from flask import render_template, session, redirect, request from app import app, LINK from requests import post from json import loads @app.route('/ladder/<int:ladder>/question/-1') @app.route('/ladder/<int:ladder>/question/-1/') def step_end(ladder): ip = request.remote_addr user = loads(post(LINK, json={'method': 'users.get', 'ip': ip, 'id': session['id']}).text)['user'] if 'id' in session else {'id': 0, 'admin': 2} if 'token' not in session: return redirect(LINK + 'login?url=ladder/' + str(ladder)) url = 'ladder/%d/question/-1' % ladder return render_template('step_end.html', title = 'End of the ladder', description = 'End of the ladder', tags = ['end', 'ladder'], url = url, user = user, LINK = LINK, ladder = ladder, )<file_sep>/app/step_edit.py from flask import render_template, session, redirect, request from app import app, LINK from requests import post from json import loads @app.route('/admin/edit/step/<int:ladder>/<int:step>') @app.route('/admin/edit/step/<int:ladder>/<int:step>/') def step_edit(ladder, step): ip = request.remote_addr user = loads(post(LINK, json={'method': 'users.get', 'ip': ip, 'id': session['id']}).text)['user'] if 'id' in session else {'id': 0, 'admin': 2} url = 'admin/edit/step/%d/%d' % (ladder, step) type = request.args.get('type') type = type and type == 'add' href = request.args.get('href') if 'token' not in session: return redirect(LINK + 'login?url=' + url) req = { 'method': 'step.get', 'token': session['token'], 'ip': ip, 'ladder': ladder, 'step': step, } res = loads(post(LINK, json=req).text) return render_template('step_more.html', title = 'Edit step', description = 'Admin panel: edit step', tags = ['admin panel', 'edit step'], url = url, user = user, LINK = LINK, enumerate = enumerate, ladder = ladder, id = step, type = type, href = href, step = res['step'], author = res['author'], ) <file_sep>/app/codex.py from flask import render_template, session, request from app import app, LINK from requests import post from json import loads @app.route('/codex') @app.route('/codex/') def codex(): ip = request.remote_addr user = loads(post(LINK, json={'method': 'users.get', 'ip': ip, 'id': session['id']}).text)['user'] if 'id' in session else {'id': 0, 'admin': 2} return render_template('codex.html', title = 'Codex', description = 'Codex', tags = ['codex', 'honor code'], url = 'codex', user = user, LINK = LINK, )<file_sep>/app/templates/news_all.html {% extends "main.html" %} {% block cont %} {% from 'list_note.html' import list_note %} {% from 'list_user.html' import list_user %} <div class="u-info" onclick="change();">↑ Tap on the logo ↑</div> <h2 class="u-title">News</h2> <div class="u-notes"> {% for i in news %}<a href="/news/{{ i.id }}"><div><div class="u-img" style="background-image: url({{ preview('news', i.id) }}");"></div><div class="u-text">{{ i.name }}</div></div></a>{% endfor %} </div> {% endblock %}<file_sep>/app/wallet.py from flask import render_template, session, request, redirect from app import app, LINK, get_preview from requests import post from json import loads from time import strftime, gmtime def time(x): return strftime('%d.%m.%Y %H:%M:%S', gmtime(x)) @app.route('/wallet') @app.route('/wallet/') def wallet(): ip = request.remote_addr user = loads(post(LINK, json={'method': 'users.get', 'ip': ip, 'id': session['id']}).text)['user'] if 'id' in session else {'id': 0, 'admin': 2} if 'token' in session: return render_template('wallet.html', title = 'Wallet', description = 'Wallet, tokens, transaction history', tags = ['wallet', 'tokens', 'transaction history'], url = 'wallet', user = user, LINK = LINK, preview = get_preview, time = time, ) else: return redirect(LINK + 'login?url=wallet')<file_sep>/app/step.py from flask import render_template, session, request, Markup, redirect from app import app, LINK, get_preview from requests import post from json import loads import markdown import re @app.route('/ladder/<int:ladder>/question/<int:step>') @app.route('/ladder/<int:ladder>/question/<int:step>/') def step(ladder, step): ip = request.remote_addr user = loads(post(LINK, json={'method': 'users.get', 'ip': ip, 'id': session['id']}).text)['user'] if 'id' in session else {'id': 0, 'admin': 2} if 'token' not in session: return redirect(LINK + 'login?url=ladder/' + str(ladder)) edit = request.args.get('edit') url = 'ladder/%d/question/%d' % (ladder, step) if edit: url += '?edit=1' req = loads(post(LINK, json={ 'method': 'step.get', 'token': session['token'], 'ip': ip, 'ladder': ladder, 'step': step, }).text) print(req) if req['error'] in (8,): return redirect(LINK + 'ladder/' + str(ladder)) if edit and user['admin'] < 5 and user['id'] != req['step']['user']: return redirect(LINK + url) if 'step' not in req: return render_template('message.html', cont='Страница не существует!') if not edit: req['step']['cont'] = Markup(req['step']['cont']) req['step']['theory'] = Markup(req['step']['theory']) for i in range(len(req['step']['options'])): req['step']['options'][i] = Markup(markdown.markdown(req['step']['options'][i])) else: for i in range(len(req['step']['options'])): req['step']['options'][i] = req['step']['options'][i].replace('<br>', '\r\n') steps = loads(post(LINK, json={ 'method': 'step.gets', 'token': session['token'], 'ip': ip, 'ladder': ladder, }).text) return render_template('step_edit.html' if edit and (user['id'] == req['step']['user'] or user['admin'] >= 5) else 'step.html', title = req['step']['name'], description = re.sub(r'\<[^>]*\>', '', req['step']['cont']) + '\n' + '; '.join([re.sub(r'\<[^>]*\>', '', i) for i in req['step']['options']]), tags = req['tags'], url = url, user = user, LINK = LINK, preview = get_preview, enumerate = enumerate, str = str, step = req['step'], steps = steps['steps'], ladder = ladder, id = step, author = req['author'], complete = req['complete'], spaces = req['spaces'], )<file_sep>/app/sys_space.py from flask import session, request from app import app, LINK from requests import post import json @app.route('/sys_space', methods=['POST']) def sys_space(): ip = request.remote_addr x = request.form id = request.args.get('id') req = { 'method': 'space.add', 'token': session['token'], 'ip': ip, 'id': int(id), 'cont': x['cont'], } json.loads(post(LINK, json=req).text) return ''<file_sep>/app/password.py from flask import session, request, render_template, redirect from app import app, LINK from requests import post import json @app.route('/password') @app.route('/password/') def password(): ip = request.remote_addr user = json.loads(post(LINK, json={'method': 'users.get', 'ip': ip, 'id': session['id']}).text)['user'] if 'id' in session else {'id': 0, 'admin': 2} url = 'token' if 'token' in session: return render_template('password.html', title = 'Authorization', description = '', tags = ['authorization', 'password'], url = url, user = user, LINK = LINK, without_menu = True, link = request.args.get('url') ) else: return redirect(LINK + 'login?url=' + request.args.get('url'))
29f97049688a918064257744dc3732e953eea3ab
[ "Markdown", "Python", "Text", "HTML" ]
44
Python
TensyTeam/Hedera-platform
ae52881406d32f5dfd0453294b0ceb89c9f43bc3
9c29f2d8c09aa44149d4b6949ff1c84c33db5fdd
refs/heads/master
<file_sep>package com.example.myfirstapp; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.InputType; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.EditText; public class MainActivity extends AppCompatActivity { public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE"; public final static String ABOUT_MESSAGE = "com.example.myfirstapp.ABOUT"; private String m_Text = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.reset: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Title"); // Set up the input final EditText input = new EditText(this); // Specify the type of input expected; this, for example, sets the input as a password, and will mask the text input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); builder.setView(input); // Set up the buttons builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { m_Text = input.getText().toString(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); case R.id.about: Intent intent = new Intent(this, AboutActivity.class); String message = getString(R.string.aboutMessage); intent.putExtra(ABOUT_MESSAGE, message); startActivity(intent); return true; default: return super.onOptionsItemSelected(item); } } /** Called when the user clicks the Send button */ public void sendMessage(View view) { Intent intent = new Intent(this, DisplayMessageActivity.class); EditText editText = (EditText) findViewById(R.id.edit_message); String message = editText.getText().toString(); intent.putExtra(EXTRA_MESSAGE, message); startActivity(intent); } }
47cc39e0b223025383a35442d9429b107bae831d
[ "Java" ]
1
Java
mtrzepka/test
1b335b9f2befd78ad76104477c4e934df8434e12
c74d517558a1fe72e794e50f41ab6f010d6e61e0
refs/heads/master
<file_sep># privescbykernel Just adjust the pid to u to root in the source file and compile it. <file_sep>#include <linux/module.h> #include <linux/kernel.h> // #include <linux/sched.h> #include <linux/sched/task.h> #include <linux/init.h> #include <linux/cred.h> const int target_pid = 22577; // <<-- CHANGE ME TO DESIRED PID TO PRIVESC /** * Performs a DFS on a given task's children. * * @void */ void DFS(struct task_struct *task) { struct task_struct *child; struct list_head *list; // printk("name: %s, pid: [%d], state: %li UID:%d\n", task->comm, task->pid, task->state, task->cred->uid.val); if (task->pid == target_pid) { printk("pid %d found, PRIVESC TIME!", target_pid); int* uid = &(task->cred->uid.val); int* euid = &(task->cred->euid.val); int* gid = &(task->cred->gid.val); int* egid = &(task->cred->egid.val); *uid = 0; *euid = 0; *gid = 0; *egid = 0; } list_for_each(list, &task->children) { child = list_entry(list, struct task_struct, sibling); DFS(child); } } /** * This function is called when the module is loaded. * * @return 0 upon success */ int task_lister_init(void) { printk(KERN_INFO "Loading Task Privesc Module...\n"); DFS(&init_task); return 0; } /** * This function is called when the module is removed. * * @void */ void task_lister_exit(void) { printk(KERN_INFO "Removing Task Privesc Module...\n"); } // Macros for registering module entry and exit points. module_init(task_lister_init); module_exit(task_lister_exit);
c64bf8db385668f423ff839f654298830647facc
[ "Markdown", "C" ]
2
Markdown
warsocket/privescbykernel
b593425c5068dfd1e56388b964d69284e4826d3f
57d270906b80929cb9596a27e11658697a237cc5
refs/heads/master
<file_sep>/** * Created by Administrator on 2020/4/8 0008. */ ; $(".yiJiUl>li>p").click(function () { var thisHeight = parseInt($(this).next().css("height")) $(".sanJiUl").css("height","0px"); $(".erJiUl").css("height","0px"); if (thisHeight==0){ $(this).next().css("height","auto"); }else { $(this).next().css("height","0"); } }) $(".erJiUl>li>p").click(function () { var thisHeight = parseInt($(this).next().css("height")) $(".sanJiUl").css("height","0px"); if (thisHeight==0){ $(this).next().css("height","auto"); }else { $(this).next().css("height","0"); } })
232e015bc40433eeb01a261ab74831a89484965e
[ "JavaScript" ]
1
JavaScript
qyyl/jsStudayErJieDuan
bb41d4bb62e006a7b2c1c41e7ad9e1011048f939
f36ab08c51d2fdb678d962bbf7080bcbc28b435f
refs/heads/master
<repo_name>matlus/AsyncDemoNetCore<file_sep>/AsyncDemoNetCore/Movie.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AsyncDemoNetCore { public sealed class Movie { public string Title { get; set; } public int Year { get; set; } public string ImageUrl { get; set; } public string Category { get; set; } } } <file_sep>/AsyncDemoNetCore/MovieServiceGateway.cs using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace AsyncDemoNetCore { public static class MovieServiceGateway { private static readonly string[] sources = { "https://matlusstorage.blob.core.windows.net/membervideos/action.json", "https://matlusstorage.blob.core.windows.net/membervideos/drama.json", "https://matlusstorage.blob.core.windows.net/membervideos/thriller.json", "https://matlusstorage.blob.core.windows.net/membervideos/scifi.json", }; public static IEnumerable<IEnumerable<Movie>> DownloadData() { var allMovies = new List<IEnumerable<Movie>>(); foreach (var url in sources) { allMovies.Add(DownloadMovies(url)); } return allMovies; } public static Task<IEnumerable<Movie>[]> DownloadDataAsync(HttpClient httpClient) { var allMoviesTasks = new List<Task<IEnumerable<Movie>>>(); foreach (var url in sources) { allMoviesTasks.Add(DownloadMoviesAsync(httpClient, url)); } return Task.WhenAll(allMoviesTasks); } public static IEnumerable<IEnumerable<Movie>> DownloadDataParallel() { var allMovies = new List<IEnumerable<Movie>>(); Parallel.ForEach(sources, url => { allMovies.Add(DownloadMovies(url)); }); return allMovies; } private static IEnumerable<Movie> DownloadMovies(string url) { using (var httpClient = new HttpClient()) { var httpResponseMessage = httpClient.GetAsync(url).GetAwaiter().GetResult(); httpResponseMessage.EnsureSuccessStatusCode(); return httpResponseMessage.Content.ReadAsAsync<IEnumerable<Movie>>().GetAwaiter().GetResult(); } } private static async Task<IEnumerable<Movie>> DownloadMoviesAsync(HttpClient httpClient, string url) { var httpResponseMessage = await httpClient.GetAsync(url); httpResponseMessage.EnsureSuccessStatusCode(); return await httpResponseMessage.Content.ReadAsAsync<IEnumerable<Movie>>(); } } } <file_sep>/AsyncDemoNetCore/Startup.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; namespace AsyncDemoNetCore { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddHttpClient("MovieServiceHttpClient"); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.Run(async (httpContext) => { var httpClientFactory = app.ApplicationServices.GetService<IHttpClientFactory>(); var httpClient = httpClientFactory.CreateClient("MovieServiceHttpClient"); if (httpContext.Request.Path == "/Home/ASync") { var allMovies = await MovieServiceGateway.DownloadDataAsync(httpClient); using (var streamWriter = new StreamWriter(httpContext.Response.Body)) using (var jsonTextWriter = new JsonTextWriter(streamWriter)) { var jsonSerializer = new JsonSerializer(); jsonSerializer.Serialize(jsonTextWriter, allMovies); await streamWriter.FlushAsync(); } } else { await httpContext.Response.WriteAsync("Nothing to return"); } }); } } }
9c55ba915d4a3520896b97076963fafe80842461
[ "C#" ]
3
C#
matlus/AsyncDemoNetCore
710162932bfa037b491bbcd04322dc0e0d2fd308
9405bc784f01dbfd1c523d1079c6ef57d9ec5533
refs/heads/master
<file_sep><?php session_start(); include 'includes/functions.php'; $intest = ""; if(isset($_POST['submit'])) { if(!$_POST['username'] || $_POST['username'] == "") { $intest = '<p align="center"><font color="#000000">Please enter a eMail-Address</font></p>'; } elseif(!$_POST['password'] || $_POST['password'] == "") { $intest = '<p align="center"><font color="#000000">Please enter a Password</font></p>'; } else { connectmass(); $isuser = $_POST['username']; $ispass = $_POST['password']; $hash = sha1("$isuser$ispass"); $query = mysql_query("SELECT * FROM accounts WHERE name = '".$_POST['username']."'"); $result = mysql_fetch_array($query) or die($intest = '<p align="center">Sorry, the Account is not exist!<br /><a href="login.php">back</a></p>'); if($hash != $result['password']) { $intest = '<p align="center"><font color="#000000">Sorry, the Password is fail!</font></p>'; } else { $user = $_POST['username']; $_SESSION['user'] = $user; $_SESSION['style'] = $_POST['style']; echo '<meta http-equiv="refresh" content="1; URL=index.php">'; $intest = '<p align="center"><font color="#000000">LogIn successfully! :-)</p>'; } } } echo' <p align="center"><b><u><font size="6">Interface Overlay<br> Admin Security</font></u></b></p> <hr> <p align="center">&nbsp;</p> <form action="'.$PHP_SELF.'" method="post"><br> <div align="center"> <table border="0" cellpadding="2"> <tr> <td width="180">User:</td> <td><input type="text" name="username" size="24" class="input"'; if($_POST['username'] != "" ) {echo ' value="'.$_POST['username'].'"';} echo'></td> </tr> <tr> <td>Password:</td> <td height="0" valign="top"><input type="<PASSWORD>" name="password" size="24" class="input"></td> </tr> <tr> <td colspan="2"><p align="center">'.$intest.'</td> </tr> <tr> <td align="center" colspan="2"> <table border="0" width="100%"> <tr> <td width="50%" align="center"> <p> <input type="submit" name="submit" value="Login" class="button"></td> <td width="50%" align="center"><p><a href="http://the-open-cave.net"><input type="button" name="quit" value="Quit" class="button"></a></td> </tr> </table> </td> </tr> </table> </div> </form> '; ?> <file_sep><?php connectmoul(); $msgav = 0; if (configis('moulserver') == 1) { $ergmoul = pg_query('SELECT * FROM vault."Nodes" WHERE "String64_1" = \''.configis('msgtitel').'\' ORDER BY "ModifyTime" DESC'); } elseif (configis('moulserver') == 2) { $ergmoul = pg_query("SELECT * FROM textnote WHERE title = '".configis('msgtitel')."' ORDER BY modifytime DESC"); } connectalcugs(); $ergalcugs = mysql_query("SELECT * FROM vault WHERE str_1 = '".configis('msgtitel')."'".connectalcugs()." ORDER BY mod_time DESC"); echo '<p align="center"><u><b><font size="4" face="<NAME>">Public Message</font></b></u></p> <p align="center"><font size="2">If you create a new textnode with the title "'.configis('msgtitel').'" in your game, the message will appear directly here.</font></p> <div align="center"> <table cellspacing="1" border="1" width="100%"> <tr> <td align="center"><b><font size="4">From</font></b></td> <td width="80" align="center"><b><font size="4">Time</font></b></td> <td align="center"><b><font size="4">Text</font></b></td> </tr>'; if ((pg_num_rows($ergmoul) > 0) or (mysql_num_rows($ergalcugs) > 0)) { $msgwho = array(); $msgtime = array(); $msgowner = array(); $msgtext = array(); while($rowmoul = pg_fetch_object($ergmoul)) { if (configis('moulserver') == 1) { $idxis = pg_fetch_object(pg_query('SELECT * FROM vault."NodeRefs" WHERE "ChildIdx" = '.$rowmoul->idx.'')); $frageplayer = 'SELECT * FROM auth."Players" WHERE "PlayerIdx" = '.$idxis->OwnerIdx.''; $modtimeold = date('Y-m-d H:i:s',$rowmoul->ModifyTime); $modtime = $rowmoul->ModifyTime; $text = $rowmoul->Text_1; } elseif (configis('moulserver') == 2) { $frageplayer = "SELECT * FROM playerinfo WHERE creatorid = '".$rowmoul->creatorid."'"; $modtimeold = $rowmoul->modifytime; $modtime = strtotime($rowmoul->modifytime); $text = $rowmoul->value; } if ($modtimeold > date('Y-m-d H:i:s', strtotime('-'.configis('msgold').''))) { $ergplayer = pg_query($frageplayer); while($row2 = pg_fetch_object($ergplayer)) { if (configis('moulserver') == 1) { $name = $row2->PlayerName; } elseif (configis('moulserver') == 2) { $name = $row2->name; } array_push($msgwho, "MOUL"); array_push($msgtime, substr($modtime, 0, 10)); array_push($msgowner, $name); array_push($msgtext, $text); } } } while($rowalcugs = mysql_fetch_object($ergalcugs)) { if (date('Y-m-d H:i:s',$rowalcugs->mod_time) > date('Y-m-d H:i:s', strtotime('-'.configis('msgold').''))) { connectalcugs(); $frageplayer = "SELECT * FROM vault WHERE idx = '".$rowalcugs->owner."'"; $ergplayer = mysql_query($frageplayer); while($row2 = mysql_fetch_object($ergplayer)) { array_push($msgwho, "tPots"); array_push($msgtime, substr($rowalcugs->mod_time, 0, 10)); array_push($msgowner, $row2->lstr_1); array_push($msgtext, $rowalcugs->blob_1); } } } array_multisort($msgtime, SORT_DESC, $msgwho, $msgowner, $msgtext); for ($x=0; $x < configis('msgmax'); $x++) { if ($msgwho[$x] != "") { $msgav = 1; echo ' <tr> <td align="left">'.$msgowner[$x].'<br><font size="2">('.$msgwho[$x].')</font></td> <td align="center">'.date('Y-m-d',$msgtime[$x]).'<br>'.date('H:i:s',$msgtime[$x]).'</td> <td align="left">'.$msgtext[$x].'</td> </tr>'; } } if ($msgav == 0) { echo '<tr><td align="center" colspan="3">Messages to old for Displaying</td></tr>'; } } else { echo '<tr><td align="center" colspan="3">No Messages</td></tr>'; } echo '</table></div>'; ?><file_sep><?php $ergebnis = mysql_query("SELECT * FROM event"); echo ' <div align="center"> <u><b><font size="7">TOC-Event<br> </font><i><font size="7">List of Participants</font></i></b></u><hr>'; echo ' <p align="center">Please click on the button to sign up for the event and log in with your TOC MOUL account + password.</p> <p align="center"><a href="event"><input type="button" value="Sign up" name="su"></a></p> '; echo '<table border="1" cellpadding="3" cellspacing="1"> <tr> <td><b>Number #</b></td> <td><b>Name</b></td> <td><b>Team (Color)</b></td> <td><b>Join Time</b></td> </tr>'; if(mysql_num_rows($ergebnis) > 0) { $num = 1; while ($row = mysql_fetch_object($ergebnis)) { echo ' <tr> <td>'.$num.'</td> <td>'.$row->name.'</td> <td>'.$row->color.'</td> <td>'.$row->creattime.'</td> </tr> '; $num ++; } echo ' </table> </div> '; } else { echo ' <td colspan="4"><p align="center"><i><b><font color="#FF0000" size="4">No Player in the list</font></b></i></td> '; } ?><file_sep><?php $gtime = time(); $kMST = 25200; $kOneHour = 3600; $kOneDay = 86400; $dtime = $gtime - $kMST; #$utime = time($dtime); ## check for daylight savings time in New Mexico and adjust if ( date('n') >= 4 && date('n') < 11 ) { $dstStart = mktime(2,0,0,4,1,date("Y")); $dstStartsun = strtotime("sunday",mktime(2,0,0,4,1,date("Y"))); $dstStartsec = $dstStartsun - $dstStart; $dstStartinsec = ceil($dstStartsec/(60*60*24)); // find first Sunday after 4/1 (first sunday of April) $days_to_go_sunday_april = 7 - $dstStartinsec; if ($days_to_go_sunday_april == 7) $days_to_go_sunday_april = 0; $dstStartSecs = $dstStart + $days_to_go_sunday_april * $kOneDay; $dstEnd = mktime(1,0,0,10,25,date("Y")); $dstEndsun = strtotime("sunday",mktime(1,0,0,10,25,date("Y"))); $dstEndsec = $dstStartsun - $dstStart; $dstEndinsec = ceil($dstStartsec/(60*60*24)); // find first sunday after 10/25 (last sunday of Oct.) $days_to_go_sunday_okt = 7 - $dstEndinsec; if ($days_to_go_sunday_okt == 7) $days_to_go_sunday_okt = 0; $dstEndSecs = $dstEnd + $days_to_go_sunday_okt * $kOneDay; if ( $dtime > $dstStartSecs && $dtime < $dstEndSecs ) // add hour for daylight savings time $dtime += $kOneHour; } $dtime = $dtime; $dnitime = gmdate('H:i',$dtime); $dnidate = date('Y.m.d',$dtime); echo '<p align="center">'.$dnitime.'<br>'.$dnidate.'</p>'; ?><file_sep><?php $time = date("H:i:s"); $date = date("M d, Y"); echo '<p align="center">'.$time.'<br>'.$date.'</p>'; ?><file_sep><?php if ($displayset == "moul") { if (configis('moulserver') == 1) { $players = pg_query('SELECT * FROM vault."Nodes" WHERE "NodeType" = 23'); $mtime = 'ModifyTime'; $newgeb = pg_query('SELECT * FROM auth."Players" ORDER BY "idx" DESC'); $erghood = pg_query('SELECT * FROM vault."Nodes" WHERE "String64_2" = \'Neighborhood\' ORDER BY "CreateTime" DESC'); $name = 'PlayerName'; } elseif (configis('moulserver') == 2) { $players = pg_query("SELECT modifytime FROM playerinfo"); $mtime = 'modifytime'; $newgeb = pg_query("SELECT * FROM player ORDER BY nodeid DESC"); $erghood = pg_query("SELECT * FROM ageinfo WHERE string64_2 = 'Neighborhood' ORDER BY createtime DESC"); $name = 'name'; } } elseif ($displayset == "tpots") { connectalcugs(); $players = mysql_query("SELECT * FROM vault WHERE type = 23"); $mtime = 'mod_time'; $newgeb = mysql_query("SELECT * FROM vault WHERE type = 23 ORDER BY idx DESC"); $name = 'lstr_1'; } $today = 0; $yesterday = 0; $week = 0; $month = 0; $year = 0; $weekdays = array( date('Y-m-d', strtotime(date('o-\\WW-1'))), date('Y-m-d', strtotime(date('o-\\WW-2'))), date('Y-m-d', strtotime(date('o-\\WW-3'))), date('Y-m-d', strtotime(date('o-\\WW-4'))), date('Y-m-d', strtotime(date('o-\\WW-5'))), date('Y-m-d', strtotime(date('o-\\WW-6'))), date('Y-m-d', strtotime(date('o-\\WW-7'))) ); $todayis = date("Y-m-d"); $yesterdayis = date("Y-m-d", strtotime('- 1 day')); $weekis = $weekdays; $monthis = date("Y-m"); $yearis = date("Y"); #### Today if ($displayset == "moul") { $playersdateis = pg_fetch_object; $row = pg_fetch_object($newgeb); } elseif ($displayset == "tpots") { $playersdateis = mysql_fetch_object; $row = mysql_fetch_object($newgeb); } while($playersdate = $playersdateis($players)) { if ($displayset == "moul") { if (configis('moulserver') == 1) { $playersonlydate = date("Y-m-d", $playersdate->$mtime); } elseif (configis('moulserver') == 2) { $playersonlydate = substr($playersdate->$mtime, 0, 10); } } else { $playersonlydate = date("Y-m-d", $playersdate->$mtime); } if ($todayis == $playersonlydate) { $today ++; } #### Yesterday if ($yesterdayis == $playersonlydate) { $yesterday ++; } #### This Week if (in_array(substr($playersonlydate, 0, 10), $weekdays)) { $week ++; } #### This Month if ($monthis == substr($playersonlydate, 0, 7)) { $month ++; } #### This Year if ($yearis == substr($playersonlydate, 0, 4)) { $year ++; } } echo ' <table border="0" width="100%"> <tr> <td> <p align="center"> <u><b><font face="<NAME>">Online Players<br>Statistics</font></b></u></p> <div align="center"> <table border="0" width="100%"> <tr> <td width="110">Today:</td> <td align="right"><b>'.$today.'</b></td> </tr> <tr> <td>Yesterday:</td> <td align="right"><b>'.$yesterday.'</b></td> </tr> <tr> <td>This Week:</td> <td align="right"><b>'.$week.'</b></td> </tr> <tr> <td>This Month:</td> <td align="right"><b>'.$month.'</b></td> </tr> <tr> <td>This Year:</td> <td align="right"><b>'.$year.'</b></td> </tr> <tr> <td>Newest Member:</td> <td align="right"><b>'.$row->$name.'</b></td> </tr>'; if ($displayset == "moul") { echo ' <tr> <td>Newest Hood:</td> <td align="right"> '; $hood = pg_fetch_object($erghood); if (configis('moulserver') == 1) { if($hood->Int32_1 == 0) { echo '<b>'.$hood->Text_1.'</b>'; } else { echo '<b>'.$hood->String64_4.'('.$hood->Int32_1.')</b>'; } } elseif (configis('moulserver') == 2) { if($hood->int32_1 == 0) { echo '<b>'.$hood->text_1.'</b>'; } else { echo '<b>'.$hood->string64_4.'('.$hood->int32_1.')</b>'; } } echo '</td> </tr>'; } echo ' </table> </div></td> </tr> </table> '; ?><file_sep><?php function connectmass() { include 'config/config.php'; $dbmysql = mysql_connect($massalcugshost, $massalcugsuser, $massalcugspassword); mysql_select_db($massdb); } function connectmoul() { include 'config/config.php'; $dbpg = pg_connect('host='.$moulhost.' port='.$moulport.' dbname='.$mouldb.' user='.$mouluser.' password='.$<PASSWORD>.''); } function connectalcugs() { include 'config/config.php'; $dbmysql2 = mysql_connect($massalcugshost, $massalcugsuser, $massalcugspassword); mysql_select_db ($alcugsdb); } function serveronmoul($ip) { if (! $sock = @fsockopen($ip, 14617, $num, $error, 1)) { return false; } else { return true; fclose($sock); } } function serveron($pid) { $cmd = "ps -e | grep -w ".$pid.""; exec($cmd, $output, $result); if(count($output) >= 1){ return true; } return false; } function configis($name) { connectmass(); $frag = mysql_query("SELECT * FROM config WHERE name = '".$name."'"); $erg = mysql_fetch_object($frag); return $erg->params; } function onoffind($name) { require ('../config/config.php'); if ($name == "moulonoff") { $check = $moulonoff; } elseif ($name == "tpotsonoff") { $check = $tpotsonoff; } if ($check == 1) { return "checked"; } else { return ""; } } ?><file_sep><?php $serverison = 0; if ($displayset == "moul") { $serverisonmax = 1; if (serveronmoul($_SERVER['SERVER_NAME']) == 1) { $serverison ++; } } elseif ($displayset == "tpots") { $serverisonmax = 4; if (serveron(alcugs_auth) == 1) { $serverison ++; } if (serveron(alcugs_lobby) == 1) { $serverison ++; } if (serveron(alcugs_tracking) == 1) { $serverison ++; } if (serveron(alcugs_vault) == 1) { $serverison ++; } } if ($serverison == 0) { echo '<p align="center"><font size="4">'.strtoupper($displayset).': <img src="img/online/red.gif" border="0" alt="Login" align="top" width="20" height="20" /></font></p>'; } elseif ($serverison == $serverisonmax) { echo '<p align="center"><font size="4">'.strtoupper($displayset).': <img src="img/online/green.gif" border="0" alt="Login2" align="top" width="20" height="20" /></font></p>'; } ?><file_sep><?php ######### Global Setting ## Dont change $displayinsertnames = array ( "DELETE" => "---DELETE---", "reload" => "-Side reloader-", "serveron" => "Server Online Indicator", "time" => "Server Date & Time", "dnitime" => "DNI/KI Date & Time", "online" => "Members Online - only Members", "online-full" => "Members Online - Full", "statistics" => "Server Statistics", "msg" => "Public Messages", "msg-all" => "Public Messages - All Servers", "event" => "Event list", "event-ko" => "Event K.O. list"); ?><file_sep>var gap_v = 15; var gap_h = 7; var oldgap; function replace_node(node, node1, node2, binding) { var div = document.getElementById(node); var div1 = document.getElementById(node1); var div2 = document.getElementById(node2); var binding = document.getElementById(binding); div.style.visibility="visible"; div1.style.visibility="visible"; div2.style.visibility="visible"; binding.style.visibility="visible"; if (!div2) { oldgap_tmp = oldgap; } else { oldgap_tmp = ( div2.offsetTop - div.offsetTop ) - div.offsetHeight; oldgap = oldgap_tmp; } div1.style.top = ( div.offsetHeight + (oldgap_tmp/2) ) - ( div1.offsetHeight/2 ) + div.offsetTop; div1.style.left = div.offsetLeft + div.offsetWidth + (2*gap_h); if (div2) { binding.style.top = div.offsetTop + (div.offsetHeight/2); binding.style.left = div.offsetLeft + div.offsetWidth + gap_h - (binding.offsetWidth/2); binding.style.height = div2.offsetTop - div.offsetTop; } } function replace_node_v(node, node1) { var div = document.getElementById(node); var div1 = document.getElementById(node1); var f = div.offsetHeight + gap_v; div1.style.top = div.offsetTop + f; div1.style.left = div.offsetLeft; } <file_sep><?php $ftext = "<?php ############## # MASS & Alcugs database connections \$massalcugshost = '".$_POST['massalcugshost']."'; \$massalcugsuser = '".$_POST['massalcugsuser']."'; \$massalcugspassword = '".$_POST['massalcugspassword']."'; \$massdb = '".$_POST['massdb']."'; \$alcugsdb = '".$_POST['alcugsdb']."'; ############## # MOUL database connections \$moulhost = '".$_POST['moulhost']."'; \$moulport = '".$_POST['moulport']."'; \$mouluser = '".$_POST['mouluser']."'; \$moulpassword = '".$_POST['moulpassword']."'; \$mouldb = '".$_POST['mouldb']."'; ?>"; ?><file_sep><?php echo ' <script src="includes/scripts/event-ko.js" type="text/javascript"></script> <div style="position: absolute; margin: 5px 5px 5px 5px;"> '; connectmass(); $playername = array(); $playercolor = array(); $ergebnis = mysql_query("SELECT * FROM event_ko"); $players = mysql_num_rows($ergebnis); $maxteams = $players; $hoehe = $maxteams-1; $teamnum = 1; $breite = log($maxteams,10)/log(2,10); function eintrag($zeile,$potenz) { for ($i=0;$i<=$zeile;$i++) { $beginn = bcpow(2,$potenz); $resume = $beginn*2; $zeileis = $beginn+($resume*$i); if ($zeile == $zeileis) { break; } } return $zeileis; } $round = array(1 => "round1win", "round2win", "round3win", "round4win", "round5win"); $nameround = array(1 => 0, 0, 0, 0, 0, 0, 0); $tableround = array(1 => array(0 => 0), array(0 => 0), array(0 => 0), array(0 => 0), array(0 => 0), array(0 => 0), array(0 => 0)); $tableroundbreak = array(1 => array(0 => 0), array(0 => 0), array(0 => 0), array(0 => 0), array(0 => 0), array(0 => 0), array(0 => 0)); $scripts = array(); $scriptnum = array(); for ($zeile=1;$zeile<=$hoehe;$zeile++) { for ($spalte=1;$spalte<=$breite;$spalte++) { $potenz = $spalte-1; $isidnumtable = $zeile+($spalte*100); $isidnumtablebreak = $zeile+($spalte*1000); array_push($tableround[$spalte], $isidnumtable); array_push($tableroundbreak[$spalte], $isidnumtablebreak); if ( $zeile == eintrag($zeile,$potenz)) { if ($spalte != 1) { echo ' <div style="visibility: hidden; z-index: 101; position: absolute;" id="'.$isidnumtablebreak.'"> <table cellpadding="0" cellspacing="0" border="0" style="height: 100%;"> <tr> <td height="1"><img src="img/event/binding_end.gif" border="0" alt="" height="1"></td> </tr> <tr style="background-image: url(img/event/binding_spacer.gif);"> <td><img src="img/event/binding_mid.gif" border="0" alt="" height="1"></td> </tr> <tr> <td height="1"><img src="img/event/binding_end.gif" border="0" alt="" height="1"></td> </tr> </table> </div> '; } echo '<div class="node" style="visibility: hidden; z-index: 100; position:absolute;background-color: #EFEFEF; border: 1px solid #999999; width: 115px; height: auto;" id="'.$isidnumtable.'"> '; echo '<table cellpadding="0" cellspacing="1" border="0" class="node" style="width: 115px;">'; for ($print=1;$print<=2;$print++) { if ($potenz == 0) { $erg = mysql_query("SELECT name,color FROM event_ko"); print '<tr><td bgcolor="'.mysql_result($erg, $nameround[$potenz], 1).'">'.mysql_result($erg, $nameround[$potenz]).'</td></tr>'; $nameround[$potenz] ++; } elseif ($potenz > 0) { $roundis = $round[$potenz]; $erg = mysql_query("SELECT name,color FROM event_ko WHERE ".$roundis." = true"); if(mysql_num_rows($erg) > 0) { if (mysql_result($erg, $nameround[$potenz]) == "") { print "<tr><td>WAITING...</td></tr>"; } else { print '<tr><td bgcolor="'.mysql_result($erg, $nameround[$potenz], 1).'">'.mysql_result($erg, $nameround[$potenz]).'</td></tr>'; $nameround[$potenz] ++; } } else { print "<tr><td>----</td></tr>"; } } } echo '</table>'; echo '</div> '; } } } for ($zeile=1;$zeile<=$hoehe;$zeile++) { for ($spalte=1;$spalte<=$breite;$spalte++) { $potenz = $spalte-1; if ( $zeile == eintrag($zeile,$potenz)) { $beginn = bcpow(2,$potenz); $resume = $beginn*2; $zeileis = $beginn/2; if ($potenz == 0) { $numvor = $zeile-$resume; $oldistableid = $tableround[$spalte][$numvor]; $scriptis = '<script type="text/javascript">setTimeout("replace_node_v(\''.$oldistableid.'\',\''.$tableround[$spalte][$zeile].'\')",100);</script>'; } elseif ($potenz > 0) { $is = $zeile+$zeileis; $numvor = $zeile-$zeileis; $oldistableid = $tableround[$potenz][$numvor]; $scriptis = '<script type="text/javascript">setTimeout("replace_node(\''.$oldistableid.'\',\''.$tableround[$spalte][$zeile].'\',\''.$tableround[$potenz][$is].'\',\''.$tableroundbreak[$spalte][$zeile].'\')",200);</script>'; } array_push($scripts, $scriptis); $scriptnumis = $oldistableid; array_push($scriptnum, $scriptnumis); } } } array_multisort($scripts, $scriptnum); for ($zeile=1;$zeile<=count($scripts);$zeile++) { list($key, $val) = each($scripts); echo ''.$val.' '; } #print_r ($tableround); ?><file_sep><?php session_start(); if($_SESSION['eventuser'] == "") { header("location:login.php"); die; } function connectmass() { include '../config/config.php'; $dbmysql = mysql_connect($massalcugshost, $massalcugsuser, $massalcugspassword); mysql_select_db($massdb); } function connectmoul() { include '../config/config.php'; $dbpg = pg_connect('host='.$moulhost.' port='.$moulport.' dbname='.$mouldb.' user='.$mouluser.' password='.$<PASSWORD>.''); } echo ' <body text="#FFFFFF" bgcolor="#000000">'; connectmass(); connectmoul(); if(isset($_POST['submit'])) { $eventavatar = $_POST['eventavatar']; $eventcolor = $_POST['eventcolor']; $table = "event"; $isuserfrag = "SELECT * FROM accounts WHERE name = '".$_SESSION['eventuser']."'"; $isuser = pg_query($isuserfrag); $isuserrow = pg_fetch_object($isuser); $isavatarfrag = "SELECT * FROM ".$table." WHERE moulid = '".$isuserrow->id."'"; $isavatar = mysql_query($isavatarfrag); if (mysql_num_rows($isavatar) == 0) { $inserttpots = "INSERT INTO ".$table." values ('', '".$isuserrow->id."', '".$eventavatar."', '".$eventcolor."', now())"; mysql_query($inserttpots) or die (mysql_error()); echo '<p align="center">Your entry was added.</p>'; } else { $updatetpots = "UPDATE ".$table." SET name = '".$eventavatar."', color = '".$eventcolor."' WHERE moulid = '".$isuserrow->id."'"; mysql_query($updatetpots) or die (mysql_error()); echo '<p align="center">Your entry was updated.</p>'; } echo '<meta http-equiv="refresh" content="5; URL=http://mass.the-open-cave.net/display.php?wall-event-moul">'; session_destroy(); } else { echo ' <div align="center"> <u><b><font size="7">TOC-Event<br> </font><i><font size="7">Registration form</font></i></b></u><hr> <p>Please select an avatar for playing</p> <p>&nbsp;</p> </div> <form method="POST" action="'.$PHP_SELF.'"> <div align="center"> <table border="0"> <tr> <td>Name:</td> <td><select size="1" name="eventavatar">'; $ergebnis = pg_query("SELECT * FROM accounts WHERE name = '".$_SESSION['eventuser']."'"); while($row = pg_fetch_object($ergebnis)) { $abfragespieler = "SELECT * FROM player WHERE creatoracctid = '".$row->id."' ORDER BY nodeid"; $spieler = pg_query($abfragespieler); if(pg_num_rows($spieler) > 0) { while($avatar = pg_fetch_object($spieler)) { $onavatarfrag = "SELECT * FROM event WHERE moulid = '".$row->id."' AND name = '".$avatar->name."'"; $onavatar = mysql_query($onavatarfrag); if (mysql_num_rows($onavatar) != 0) { echo ' <option selected>'.$avatar->name.'</option> '; } else { echo ' <option>'.$avatar->name.'</option> '; } } } } echo ' </select> </td> </tr> <tr> <td>Color:</td> <td><select size="1" name="eventcolor"> <option selected>no preference</option> <option>violet</option> <option>yellow</option> </select> </td> </tr> </table> </div> <p align="center"> <input type="submit" value="Submit" name="submit"></p> </form> '.$row->id.' '; } ?> <file_sep><?php require ('functions.php'); include ('sort.php'); ?><file_sep><?php session_start(); ?> <html> <head> <title>TOC-MOUL Interface - LogOut</title> <link href="style.css" rel="stylesheet" type="text/css" media="screen" /> </head> <body background="../img/interface/interface-nexus-back.jpg"> <?php $user = $_SESSION['user']; if(session_destroy()) { echo '<p align="center"><font size="4"><br><br>Bye bye '.$user.'<br> <br>Successfully<br>Logged out!<br><br> <a href="login.php">Back to Login</font></a></p>'; }else{ echo '<p align="center">When logging off, unfortunately, an error occurred! <br /><br />Please close your browser window.'; } ?> </body> </html><file_sep><?php echo '<p align="center"><u><font size="7">MASS<br> Installation</font></u></p> <hr>'; if ($_SERVER["QUERY_STRING"] == '') { header('Location: ?State=CHECK&CHECK=1'); } if ($_GET['State'] == 'CHECK') { if ($_GET['CHECK'] == 1) { chdir('../config'); $filename = ''.getcwd().'/config.php'; if (file_exists($filename)) { header('Location: ?State=ERROR&ERROR=1'); } else { header('Location: ?State=1'); } } elseif ($_GET['CHECK'] == 2) { chdir('../config'); $filename = ''.getcwd().'/config.php'; if (substr(sprintf('%o', fileperms(getcwd())), -3) == 777) { header('Location: ?State=2'); } else { header('Location: ?State=ERROR&ERROR=2'); } } } if ($_GET['State'] == 'ERROR') { if ($_GET['ERROR'] == 1) { echo ' <p align="center"><u><b><font style="font-size: 50pt" color="#FF0000">ERROR</font></b></u></p> <p align="center">A MASS installation is already in place. Delete the config.php in config folder.</p> '; } elseif ($_GET['ERROR'] == 2) { echo ' <p align="center"><u><b><font style="font-size: 50pt" color="#FF0000">ERROR</font></b></u></p> <p align="center">The "config" folder is not writable, please set it to chmod 777.</p> '; } } if ($_GET['State'] == 1) { echo ' <p align="center">Welcome to Mass Installation</p> <p align="center">&nbsp;</p> <p align="center"><a href="?State=CHECK&CHECK=2"><input type="button" value="begin with the installation" name="begin"></a></p> '; } elseif ($_GET['State'] == 2) { echo '<p align="center">&nbsp;</p> <table border="0" width="100%"> <tr> <td width="25%" align="center" valign="top">&nbsp;</td> <td width="75%"><form method="POST" action="?State=3"> <div align="center"> <table border="1" style="border-collapse: collapse"> <tr> <td width="150"> <p align="center"><u><b>MASS<br> (and Alcugs)</b></u></td> </tr> <tr> <td>&nbsp;</td> </tr> <tr> <td>Serveradress:<br> <input type="text" name="massalcugshost" size="20" value="localhost"></td> </tr> <tr> <td>User:<br> <input type="text" name="massalcugsuser" size="20"></td> </tr> <tr> <td>Password:<br> <input type="text" name="massalcugspassword" size="20"></td> </tr> <tr> <td><b>MASS</b> Database Name:<br> <input type="text" name="massdb" size="20"></td> </tr> <tr> <td><b>Alcugs</b> Database Name:<br> <input type="text" name="alcugsdb" size="20"></td> </tr> </table> </div><hr width="200"> <div align="center"> <table border="1" style="border-collapse: collapse"> <tr> <td width="150"> <p align="center"><u><b>MOUL</b></u></td> </tr> <tr> <td>&nbsp;</td> </tr> <tr> <td>Serveradress:<br> <input type="text" name="moulhost" size="20" value="localhost"></td> </tr> <tr> <td>Port:<br> <input type="text" name="moulport" size="20" value="5432"></td> </tr> <tr> <td>User:<br> <input type="text" name="mouluser" size="20"></td> </tr> <tr> <td>Password:<br> <input type="text" name="moulpassword" size="20"></td> </tr> <tr> <td>Database Name:<br> <input type="text" name="mouldb" size="20"></td> </tr> </table> </div> <p align="center"><input type="reset" value="Reset" name="Reset"> <input type="submit" value="Submit" name="Submit"></p> </form> </td> </tr> </table> '; } elseif ($_GET['State'] == 3) { echo '<p align="center">Information to be written!</p>'; chdir('../config'); $filename = ''.getcwd().'/config.php'; if (file_exists($filename)) { echo '<meta http-equiv="refresh" content="0; URL=?State=ERROR&ERROR=1">'; } else { include 'include/ftext.php'; $handle = @fopen($filename, "x+"); if ($handle) { @fwrite ($handle, $ftext); @fclose ($handle); include 'include/sql.php'; } else { header('Location: ?State=ERROR&ERROR=2'); } } chmod($filename, 0777); echo '<meta http-equiv="refresh" content="0; URL=?State=4">'; } elseif ($_GET['State'] == 4) { echo ' <p align="center">Information has been described.</p> <p align="center">Please delete the &quot;install&quot; folder to continue</p> <p align="center">&nbsp;</p> <p align="center"><a href="../">continue</a></p>'; } ?><file_sep><?php if (configis('moulserver') == 1) { $abfrage = 'SELECT * FROM vault."Nodes" WHERE "NodeType" = 23 AND "Int32_1" = 1 ORDER BY "String64_1", "IString64_1"'; } elseif (configis('moulserver') == 2) { $abfrage = "SELECT * FROM playerinfo WHERE online = 1 ORDER BY string64_1, name"; } $ergebnis = pg_query($abfrage); $isonavatargroupnum = 0; $isonavatargroup = 0; if(pg_num_rows($ergebnis) > 0) { echo '<p align="center">'; $avafrag = mysql_query("SELECT * FROM groups WHERE category = '".$displayset."'"); if(mysql_num_rows($avafrag) > 0) { while ($rowava = mysql_fetch_object($avafrag)) { $avafound = preg_split("/[\s]*[,][\s]*/", $rowava->avatar); $ergebnis2 = pg_query($abfrage); while($row2 = pg_fetch_object($ergebnis2)) { if (configis('moulserver') == 1) {$name = $row2->IString64_1;} elseif (configis('moulserver') == 2) {$name = $row2->name;} if(in_array($name, $avafound)) { $isonavatargroup ++; } } if ($isonavatargroup > 0) { $groupfrag = mysql_query("SELECT * FROM groups WHERE category = '".$displayset."' AND num = '".$rowava->num."'"); $rowgroup = mysql_fetch_object($groupfrag); echo '<font color="'.$rowgroup->color.'">'.$rowgroup->name.'</font> '; } } } echo '</p> <div align="center"> <table cellspacing="1" border="2"> <tr> <td width="150" align="center"><b><font size="4">Name</font></b></td>'; if ($querystring == "online-full") { echo ' <td width="50" align="center"><b><font size="4">KI #</font></b></td> <td width="200" align="center"><b><font size="4">Age</font></b></td>'; } echo ' </tr>'; while($row = pg_fetch_object($ergebnis)) { if (configis('moulserver') == 1) { $name = $row->IString64_1; $ageis = $row->String64_1; $ki = $row->CreatorIdx; } elseif (configis('moulserver') == 2) { $name = $row->name; $ageis = $row->string64_1; $ki = $row->ki; } switch($ageis) { case "Personal": $agename = "Relto"; break; case "Garrison": $agename = "Gahreesen"; break; case "Gira": $agename = "<NAME>"; break; case "GreatZero": $agename = "Great Zero"; break; case "city": $agename = "Ae´gura"; break; case "Ercana": $agename = "Er'cana"; break; case "ErcanaCitySilo": $agename = "Er'cana City Silo"; break; case "PelletBahroCave": $agename = "Pellet Bahro Cave"; break; default: $agename = $ageis; break; } echo '<tr>'; if(mysql_num_rows($avafrag) > 0) { $isonavatargrouplist = 0; $avafrag2 = mysql_query("SELECT * FROM groups WHERE category = '".$displayset."'"); while ($rowava2 = mysql_fetch_object($avafrag2)) { for ($i = 1; $i <= mysql_num_rows($avafrag2); $i++) { $avafound2 = preg_split("/[\s]*[,][\s]*/", $rowava2->avatar); if(in_array($name, $avafound2)) { $isonavatargrouplist ++; $num = $rowava2->num; } } } if ($isonavatargrouplist > 0) { $groupfrag2 = mysql_query("SELECT * FROM groups WHERE category = '".$displayset."' AND num = '".$num."'"); $rowgroup2 = mysql_fetch_object($groupfrag2); echo '<td width="150" align="left"><font color="'.$rowgroup2->color.'">'; if ($rowgroup2->pic != "") { $picpath = 'img/group/'; echo '<img border="0" src="'.$picpath.''.$rowgroup2->pic.'" width="20" height="20" align="top">'; } echo ''.$name.'</font></td>'; } else { echo '<td width="150" align="left">'.$name.'</td>'; } } else { echo '<td width="150" align="left">'.$name.'</td>'; } if ($querystring == "online-full") { echo '<td width="50" align="right">'.$ki.'</td>'; if($row->string64_1 == 'Hood') { $fragmem = "SELECT * FROM ageinfo A, playerinfo P WHERE P.ki = ".$ki." AND A.uuid_1 = P.uuid_1 AND A.string64_3 = 'Hood'"; $ergmem = pg_query($fragmem); while($hood = pg_fetch_object($ergmem)) echo '<td width="200" align="left">'.$hood->text_1.'</td></tr>'; } elseif($row->string64_1 == 'Bevin') { $fragmem = "SELECT * FROM ageinfo A, playerinfo P WHERE P.ki = ".$ki." AND A.uuid_1 = P.uuid_1 AND A.string64_3 = 'Bevin'"; $ergmem = pg_query($fragmem); while($bevin = pg_fetch_object($ergmem)) echo '<td width="200" align="left">'.$bevin->string64_4.'('.$bevin->int32_1.')</td></tr>'; } else { echo '<td width="200" align="left">'.$agename.'</td></tr>'; } } } echo '</table> </div>'; } else { echo ' <div align="center"> <table cellspacing="1" border="2"> <tr> <td width="150" align="center"><b><font size="4">Name</font></b></td>'; if ($querystring == "online-full") { echo ' <td width="50" align="center"><b><font size="4">KI #</font></b></td> <td width="150" align="center"><b><font size="4">Age</font></b></td>'; $colspan = 3; } else { $colspan = 1; } echo ' </tr> <tr> <td align="center" colspan="'.$colspan.'"><i><b><font color="#FF0000"><u>All Players Offline</u></font></b></i></td> </tr> </table> </div> '; } ?><file_sep><?php session_start(); if($_SESSION['user'] == "") { header("location:login.php"); die; } require ('includes/functions.php'); include ('ddl-list.php'); echo ' <div align="center"> <p align="center"><b><u><font size="6">MASS<br> Admin Security</font></u></b></p> <hr> <table border="1" width="95%"> <tr> <td width="250" align="center" valign="top"><b><font size="5"><a href="?">Home</a></font></b><hr> <p><a href="?Set=Accounts">Accounts</a></p> <p><a href="?Set=General">General Settings</a></p> <p><a href="?Set=Modul">Modul Settings</a><br> <a href="?Set=Display">Display Settings</a></p> <p><a href="?Set=Group">Group Settings</a></p> <hr> <p><a href="logout.php">LOGOUT</a></td> <td align="center" valign="top"> '; connectmass(); ?> <html> <script type="text/javascript"> function showonlyone(thechosenone) { var newboxes = document.getElementsByTagName("div"); for(var x=0; x<newboxes.length; x++) { name = newboxes[x].getAttribute("name"); if (name == 'newboxes') { if (newboxes[x].id == thechosenone) { newboxes[x].style.display = 'block'; } else { newboxes[x].style.display = 'none'; } } } } </script> </html> <?php if ($_GET['Set'] == 'Accounts') { echo ' <p align="center"><b><font size="7">Accounts</font></b></p> <hr> <div align="center"> <table border="1" width="95%"> <tr> <td align="center" width="100">Account<br> No.</td> <td align="center" width="50%">Account</td> <td align="center" width="50%">Password</td> </tr>'; sqlaccounts('accounts'); echo ' <tr><form method="POST" action="'.$_SERVER['PATH_INFO'].'?'.$_SERVER["QUERY_STRING"].'&action=NEW&SAVE"> <td align="center" width="50">new</td> <td align="center"><input type="text" name="AccNewName" size="20"></td> <td align="center"> <table border="0" width="100%"> <tr> <td width="100%"><input type="text" name="AccNewPW" size="20"></td> <td><p align="right"><input type="submit" value="New Account" name="newaccount"></td> </tr> </table> </td> </form></tr> </table> </div>'; if (isset($_GET['SAVE'])) { $name = ""; $pw = ""; if ($_GET['action'] == "NEW") { $name = $_POST["AccNewName"]; $pw = $_POST["AccNewPW"]; } elseif ($_GET['action'] == "CHANGE") { if ($_GET['CHANGE'] != "") { $post = $_GET['CHANGE']; $pw = $_POST[''.$post.'']; } } accountset($name, $pw); header('Location: ?Set=Accounts'); } } ?> <?php if ($_GET['Set'] == 'General') { echo ' <p align="center"><u><b><font size="5">General Settings</font></b></u></p> <div align="center"><FORM name="moulserver" action="'.$_SERVER['PATH_INFO'].'?'.$_SERVER["QUERY_STRING"].'&SAVE" method="POST" > <table border="1" width="90%"> <tr> <td align="center" width="50%"> <u><b>MOUL-Server:</b></u> <p><input type="radio" name="moulserver" value="1" '.moulserver(dirtsand).'>dirtsand <input type="radio" name="moulserver" value="2" '.moulserver(moss).'>moss</p> </td> <td align="center" width="50%"><u><b>Side-reload time (sec): </b></u> <p><input type="text" name="reload" value="'.settingsquery(reload).'" size="3"></p></td> </tr> <tr> <td align="center" width="50%"> <table border="1" width="100%"> <tr> <td colspan="3"> <p align="center"><u><b>Public Message</b></u></td> </tr> <tr> <td width="33%" align="center">Headertext for Public<br> <input type="text" name="msgtitel" value="'.settingsquery(msgtitel).'" size="10"></td> <td width="33%" align="center">Max. messages<br> <input type="text" name="msgmax" value="'.settingsquery(msgmax).'" size="3"></td> <td width="33%" align="center">Max. old Message<br> <input type="text" name="msgold" value="'.settingsquery(msgold).'" size="10"></td> </tr> </table> </td> <td align="center" width="50%">&nbsp;</td> </tr> </table> <p><input type="submit" value="SAVE" name="Submit"></p> </form></div>'; if (isset($_GET['SAVE'])) { generalset(); echo '<meta http-equiv="refresh" content="0; URL=index.php?Set=General">'; } } ?> <?php if ($_GET['Set'] == 'Modul') { echo ' <p align="center"><u><b><font size="5">Modul Settings</font></b></u></p> <hr> <table border="1" width="100%"> <tr> <td align="center" width="50%"> MOUL</td> <td align="center" width="50%"> TPOTS</td> </tr> <tr> <td align="center" width="50%"> <table border="1" width="100%">'; addmodul("moul"); echo ' </table> <p><a href="'.$_SERVER['PATH_INFO'].'?'.$_SERVER["QUERY_STRING"].'&action=NEW&NEW=moul&SAVE"><input type="submit" value="New MOUL Modul" name="newmoulmodul"></a></td> <td align="center" width="50%"> <table border="1" width="100%">'; addmodul("tpots"); echo ' </table> <p><a href="'.$_SERVER['PATH_INFO'].'?'.$_SERVER["QUERY_STRING"].'&action=NEW&NEW=tpots&SAVE"><input type="submit" value="New TPOTS Modul" name="newtpotsmodul"></a></td> </tr> </table> '; if (isset($_GET['SAVE'])) { if ($_GET['action'] == "RENAME") { if ($_GET['RENAME'] != "") { $num = substr($_GET['RENAME'], -1); $post = $_GET['RENAME']; $name = $_POST[''.$post.'']; } } elseif ($_GET['action'] == "BCOLOR") { if ($_GET['BCOLOR'] != "") { $num = substr($_GET['BCOLOR'], -1); $post = $_GET['BCOLOR']; $name = $_POST[''.$post.'']; } } elseif ($_GET['action'] == "FCOLOR") { if ($_GET['FCOLOR'] != "") { $num = substr($_GET['FCOLOR'], -1); $post = $_GET['FCOLOR']; $name = $_POST[''.$post.'']; } } elseif ($_GET['action'] == "AVATAR") { if ($_GET['AVATAR'] != "") { $num = substr($_GET['AVATAR'], -1); $post = $_GET['AVATAR']; $name = $_POST[''.$post.'']; } } modulvar($name); echo '<meta http-equiv="refresh" content="0; URL=index.php?Set=Modul">'; } } ?> <?php if ($_GET['Set'] == 'Display') { echo ' <body onload="fillCategory();"> <FORM name="drop_list" action="'.$_SERVER['PATH_INFO'].'?'.$_SERVER["QUERY_STRING"].'&SAVE" method="POST"> <p align="center"><u><font size="5"><b>Display Settings</font></b></u></p> <hr> <table border="0" width="100%"> <tr> <td align="center" width="50%">&nbsp; <table border="1" width="100%"> <tr> <td width="25%">Display</td> <td width="25%">Position</td> <td>Select</td> </tr> <tr> <td width="25%"> <select size="10" name="displayinsertdisplay" id="displayinsertdisplay" onChange="array_position();">'.list_array_display().'</select> </td> <td width="25%"> <select size="10" name="displayinsertposition" onChange="array_select();">'.list_array_position().'<option value="">Select a Display</option></select> </td> <td> <select size="10" name="displayinsertselect">'.list_array_select().'<option value="">Select a Display</option></select> </td> </tr> </table> <p align="center"><input type="submit" value="SAVE" name="Submit"></p> </td> </tr> </table> </form> </body>'; if (isset($_GET["SAVE"])) { $display = $_POST["displayinsertdisplay"]; $position = $_POST["displayinsertposition"]; $select = $_POST["displayinsertselect"]; DSEND($display, $position, $select); echo '<meta http-equiv="refresh" content="0; URL=index.php?Set=Display">'; } } ?> <?php if ($_GET['Set'] == 'Group') { echo ' <p align="center"><u><b><font size="5">Modul Settings</font></b></u></p> <hr> <table border="1" width="100%"> <tr> <td align="center" width="50%"> MOUL</td> <td align="center" width="50%"> TPOTS</td> </tr> <tr> <td align="center" width="50%"> <table border="1" width="100%">'; group_list("moul"); echo ' </table> <p><a href="'.$_SERVER['PATH_INFO'].'?'.$_SERVER["QUERY_STRING"].'&action=NEW&NEW=moul&SAVE"><input type="submit" value="New MOUL Group" name="newmoulgroup"></a></td> <td align="center" width="50%"> <table border="1" width="100%">'; group_list("tpots"); echo ' </table> <p><a href="'.$_SERVER['PATH_INFO'].'?'.$_SERVER["QUERY_STRING"].'&action=NEW&NEW=tpots&SAVE"><input type="submit" value="New TPOTS Group" name="newtpotsgroup"></a></td> </tr> </table>'; if (isset($_GET['SAVE'])) { if ($_GET['action'] == "RENAME") { if ($_GET['RENAME'] != "") { $post = $_GET['RENAME']; $name = $_POST[''.$post.'']; } } elseif ($_GET['action'] == "PIC") { if ($_GET['PIC'] != "") { $post = $_GET['PIC']; $name = $_POST[''.$post.'']; } } elseif ($_GET['action'] == "COLOR") { if ($_GET['COLOR'] != "") { $post = $_GET['COLOR']; $name = $_POST[''.$post.'']; } } elseif ($_GET['action'] == "AVATAR") { if ($_GET['AVATAR'] != "") { $post = $_GET['AVATAR']; $name = $_POST[''.$post.'']; } } modulvar($name); echo '<meta http-equiv="refresh" content="0; URL=index.php?Set=Group">'; } } ?> <?php echo '</td> </tr> </table> </div>'; ?> <file_sep><?php session_start(); function connectmoul() { include '../config/config.php'; $dbpg = pg_connect('host='.$moulhost.' port='.$moulport.' dbname='.$mouldb.' user='.$mouluser.' password='.$mo<PASSWORD>.''); } connectmoul(); $passhash = '../set/compute_auth_hash'; $intest = ""; if(isset($_POST['submit'])) { if(!$_POST['username'] || $_POST['username'] == "") { $intest = '<p align="center"><font color="#000000">Please enter a eMail-Address</font></p>'; } elseif(!$_POST['password'] || $_POST['password'] == "") { $intest = '<p align="center"><font color="#000000">Please enter a Password</font></p>'; } else { if (preg_match("/@/", $_POST['username'])) { $isuser = $_POST['username']; $ispass = $_POST['password']; $hash = exec("$passhash $isuser $ispass"); } else { $hash = sha1($_POST['password']); } $query = pg_query("SELECT * FROM accounts WHERE name = '".strtolower($_POST['username'])."'"); $result = pg_fetch_array($query) or die($intest = '<p align="center">Sorry, the eMail-Address is not exist!<br /><a href="login.php">back</a></p>'); $avafrag = pg_num_rows(pg_query("SELECT * FROM player WHERE creatoracctid = '".$result['id']."'")); if($hash != $result['hash']) { $intest = '<p align="center">Sorry, your password is wrong!</p>'; } elseif ($result['banned'] == "t") { $intest = '<p align="center">Sorry, your Account is not Activatet or BANNED!<br /><br>Please notify a ADMIN or a MOD in the Forum</p>'; } elseif ($avafrag == 0) { $intest = '<p align="center">Her Account, has no Avatars.<br /><br /><br /><b><font face="<NAME>">ACCESS DENIED</font></p>'; } else { $user = $result['name']; $_SESSION['eventuser'] = $user; echo '<meta http-equiv="refresh" content="1; URL=index.php">'; $intest = '<p align="center">LogIn successfully! :-)</p>'; } } } echo' <body text="#FFFFFF" bgcolor="#000000"> <form action="'.$PHP_SELF.'" method="post"><br> <div align="center"> <u><b><font size="7">TOC-Event<br> </font><i><font size="7">Registration form</font></i></b></u><p>&nbsp;</p> <table border="0"> <tr> <td>Name:</td> <td> <input type="text" name="username" size="24" class="input"'; if($_POST['username'] != "" ) {echo ' value="'.$_POST['username'].'"';} echo'></td> </tr> <tr> <td>Password:</td> <td> <input type="<PASSWORD>" name="password" size="24" class="input"></td> </tr> <tr> <td colspan="2"> <table border="0" width="100%"> <tr> <td width="50%" align="center"><p><input type="submit" name="submit" value="Login" class="button"></td> <td width="50%" align="center"><p><a href="http://the-open-cave.net"><input type="button" name="quit" value="Quit" class="button"></a></td> </tr> </table> </td> </tr> </table> </div> </form> <br><br><p align="center">'.$intest.'</p> '; ?> <file_sep><?php $db = mysql_connect($_POST['massalcugshost'], $_POST['massalcugsuser'], $_POST['massalcugspassword']); $database = ($_POST['massdb']); $tabel = array( 1 => "CREATE DATABASE ".$database."", 2 => "CREATE TABLE `accounts` ( `num` int(11) NOT NULL, `name` varchar(20) NOT NULL, `password` varchar(40) NOT NULL, PRIMARY KEY (`num`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 ROW_FORMAT=DYNAMIC;", 3 => "CREATE TABLE `config` ( `num` int(11) NOT NULL, `name` varchar(20) NOT NULL, `params` varchar(20) NOT NULL, PRIMARY KEY (`num`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1;", 4 => "CREATE TABLE `displays` ( `num` int(11) NOT NULL, `display` int(11) NOT NULL, `position` int(11) NOT NULL, `sel` text NOT NULL, PRIMARY KEY (`num`), KEY `num` (`num`) ) ENGINE=MyISAM AUTO_INCREMENT=19 DEFAULT CHARSET=latin1;", 5 => "CREATE TABLE `groups` ( `num` int(11) NOT NULL AUTO_INCREMENT, `category` varchar(20) NOT NULL, `pic` varchar(20) DEFAULT NULL, `name` varchar(20) NOT NULL, `color` varchar(20) NOT NULL, `avatar` text NOT NULL, PRIMARY KEY (`num`) ) ENGINE=MyISAM AUTO_INCREMENT=10 DEFAULT CHARSET=latin1;", 6 => "CREATE TABLE `modul` ( `num` int(11) NOT NULL AUTO_INCREMENT, `type` varchar(20) NOT NULL, `name` varchar(20) NOT NULL, `backcolor` varchar(20) NOT NULL, `fontcolor` varchar(20) NOT NULL, PRIMARY KEY (`num`) ) ENGINE=MyISAM AUTO_INCREMENT=19 DEFAULT CHARSET=latin1;", 7 => "INSERT INTO accounts values ('0', 'admin', '<PASSWORD>58f827fa78eef7197b8ee606c99b2e6')", 8 => "INSERT INTO config values ('1', 'moulserver', '1')", 9 => "INSERT INTO config values ('2', 'reload', '30')"); for($x=1; $x <= sizeof($tabel); $x++) { mysql_select_db($database); $sql = mysql_query($tabel[$x]) or die ('<meta http-equiv="refresh" content="0"; URL=?State=ERROR&ERROR=3">'); } ?><file_sep><html> <?php function list_array_display() { $category = "displayinsertdisplay"; echo '<script type="text/javascript"> function fillCategory(){'; $frag = mysql_query("SELECT * FROM modul"); while($row = mysql_fetch_object($frag)) { $displayname = ''.$row->num.''; if ($row->name != '') { $displayname = ''.$row->num.' - '.$row->name.''; } $inhalt .= 'addOption(document.drop_list.'.$category.', '.$row->num.', "'.$displayname.'");' ; } echo ''.$inhalt.'}</script>'; } ############### function list_array_position() { include ('includes/modulesset.php'); $selectname = "displayinsertselect"; $firsttabel = "displayinsertdisplay"; $posiname = "displayinsertposition"; echo '<script type="text/javascript"> function array_position(){ removeAllOptions(document.drop_list.'.$posiname.') removeAllOptions(document.drop_list.'.$selectname.') addOption(document.drop_list.'.$selectname.', "", "Select a Position");;'; $frag = mysql_query("SELECT * FROM modul"); while($row = mysql_fetch_object($frag)) { $inhalt .= 'if(document.drop_list.'.$firsttabel.'.value == "'.$row->num.'"){' ; $posimax = mysql_num_rows(mysql_query("SELECT * FROM displays WHERE display = '".$row->num."' ORDER BY position DESC")); $posimax ++; for($t=1; $t <= $posimax; $t++) { $posionis = mysql_fetch_object(mysql_query("SELECT * FROM displays WHERE display = '".$row->num."' AND position = ".$t."")); $getname = ''.$displayinsertnames[$posionis->sel].''; if ($getname == "") { $getname = "NOT SETTET"; } $inhalt .= 'addOption(document.drop_list.'.$posiname.', '.$t.', "'.$t.' - '.$getname.'");' ; } $inhalt .= '}'; } echo ''.$inhalt.'}</script>'; } ############## function list_array_select() { include ('includes/modulesset.php'); $selectname = "displayinsertselect"; $posiname = "displayinsertposition"; echo '<script type="text/javascript"> function array_select(){ removeAllOptions(document.drop_list.'.$selectname.');'; $frag = mysql_query("SELECT * FROM modul"); $row = mysql_fetch_object($frag); $posimax = mysql_num_rows(mysql_query("SELECT * FROM displays ORDER BY position DESC")); $posimax ++; for($x=1; $x <= $posimax; $x++) { $inhalt .= 'if(document.drop_list.'.$posiname.'.value == "'.$x.'"){' ; for($t=1; $t <= count($displayinsertnames); $t++) { list($key, $val) = each($displayinsertnames); $inhalt .= 'addOption(document.drop_list.'.$selectname.', "'.$key.'", "'.$val.'");' ; } reset($displayinsertnames); $inhalt .= '}'; } echo ''.$inhalt.'}</script>'; } echo ' <script type="text/javascript"> function removeAllOptions(selectbox) { var i; for(i=selectbox.options.length-1;i>=0;i--) { //selectbox.options.remove(i); selectbox.remove(i); } } function addOption(selectbox, value, text ) { var optn = document.createElement("OPTION"); optn.text = text; optn.value = value; selectbox.options.add(optn); } '; ?> </script> </html><file_sep><?php $frag = mysql_query("SELECT * FROM config WHERE name = 'reload'"); $erg = mysql_fetch_object($frag); echo '<meta http-equiv="refresh" content="'.$erg->params.';">'; ?><file_sep><?php connectalcugs(); $abplayer = "SELECT * FROM vault WHERE int_1 = 1 AND type = 23"; $ergebnis = mysql_query($abplayer); $isonavatargroup = 0; connectmass(); if(mysql_num_rows($ergebnis) > 0) { echo '<p align="center">'; $avafrag = mysql_query("SELECT * FROM groups WHERE category = '".$displayset."'"); if(mysql_num_rows($avafrag) > 0) { while ($rowava = mysql_fetch_object($avafrag)) { $avafound = preg_split("/[\s]*[,][\s]*/", $rowava->avatar); connectalcugs(); $ergebnis2 = mysql_query($abplayer); while($row2 = mysql_fetch_object($ergebnis2)) { if(in_array($row2->lstr_1, $avafound)) { $isonavatargroup ++; } } if ($isonavatargroup > 0) { connectmass(); $groupfrag = mysql_query("SELECT * FROM groups WHERE category = '".$displayset."' AND num = '".$rowava->num."'"); $rowgroup = mysql_fetch_object($groupfrag); echo '<font color="'.$rowgroup->color.'">'.$rowgroup->name.'</font> '; } } } echo '</p> <div align="center"> <table cellspacing="1" border="2"> <tr> <td width="150" align="center"><b><font size="4">Name</font></b></td>'; if ($querystring == "online-full") { echo ' <td width="50" align="center"><b><font size="4">KI #</font></b></td> <td width="150" align="center"><b><font size="4">Age</font></b></td>'; } echo ' </tr>'; while($row = mysql_fetch_object($ergebnis)) { switch($row->str_1) { case "Personal": $agename = "Relto"; break; case "Garrison": $agename = "Gahreesen"; break; case "Gira": $agename = "<NAME>"; break; case "GreatZero": $agename = "Great Zero"; break; case "city": $agename = "Ae´gura"; break; case "Ercana": $agename = "Er'cana"; break; case "ErcanaCitySilo": $agename = "Er'cana City Silo"; break; case "PelletBahroCave": $agename = "<NAME>"; break; default: $agename = $row->str_1; break; } echo '<tr>'; if(mysql_num_rows($avafrag) > 0) { connectmass(); $isonavatargrouplist = 0; $avafrag2 = mysql_query("SELECT * FROM groups WHERE category = '".$displayset."'"); while ($rowava2 = mysql_fetch_object($avafrag2)) { for ($i = 1; $i <= mysql_num_rows($avafrag2); $i++) { $avafound2 = preg_split("/[\s]*[,][\s]*/", $rowava2->avatar); if(in_array($row->lstr_1, $avafound2)) { $isonavatargrouplist ++; $num = $rowava2->num; } } } if ($isonavatargrouplist > 0) { $groupfrag2 = mysql_query("SELECT * FROM groups WHERE category = '".$displayset."' AND num = '".$num."'"); $rowgroup2 = mysql_fetch_object($groupfrag2); echo '<td width="150" align="left"><font color="'.$rowgroup2->color.'">'; if ($rowgroup2->pic != "") { $picpath = 'img/group/'; echo '<img border="0" src="'.$picpath.''.$rowgroup2->pic.'" width="20" height="20" align="top">'; } echo ''.$row->lstr_1.'</font></td>'; } else { echo '<td width="150" align="left">'.$row->lstr_1.'</td>'; } } else { echo '<td width="150" align="left">'.$row->lstr_1.'</td>'; } if ($querystring == "online-full") { echo '<td width="50" align="right">'.$row->owner.'</td>'; echo '<td width="150" align="left">'.$agename.'</td></tr>'; } } echo '</table> </div>'; } else { echo ' <div align="center"> <table cellspacing="1" border="2"> <tr> <td width="150" align="center"><b><font size="4">Name</font></b></td>'; if ($querystring == "online-full") { echo ' <td width="50" align="center"><b><font size="4">KI #</font></b></td> <td width="150" align="center"><b><font size="4">Age</font></b></td>'; $colspan = 3; } else { $colspan = 1; } echo ' </tr> <tr> <td align="center" colspan="'.$colspan.'"><i><b><font color="#FF0000"><u>All Players Offline</u></font></b></i></td> </tr> </table> </div> '; } ?><file_sep><?php connectmass(); $iam = $_SERVER["QUERY_STRING"]; if (is_numeric($iam) == TRUE) { $tosort = mysql_fetch_object(mysql_query("SELECT * FROM modul WHERE num = '".$_SERVER["QUERY_STRING"]."'")); $zahlsort = mysql_fetch_object(mysql_query("SELECT * FROM displays WHERE display = '".$_SERVER["QUERY_STRING"]."' ORDER BY position DESC")); $coloris = mysql_fetch_object(mysql_query("SELECT * FROM modul WHERE num = '".$_SERVER["QUERY_STRING"]."'")); } else { $tosort = mysql_fetch_object(mysql_query("SELECT * FROM modul WHERE name = '".$_SERVER["QUERY_STRING"]."'")); $zahlsort = mysql_fetch_object(mysql_query("SELECT * FROM displays WHERE display = '".$tosort->num."' ORDER BY position DESC")); $coloris = mysql_fetch_object(mysql_query("SELECT * FROM modul WHERE name = '".$_SERVER["QUERY_STRING"]."'")); } $modulpath = 'includes/module/'; echo '<body bgcolor="'.$coloris->backcolor.'" text="'.$coloris->fontcolor.'">'; for ($a = 1; $a <= $zahlsort->position; $a++) { connectmass(); $fragsort2 = mysql_query("SELECT * FROM displays WHERE display = '".$tosort->num."' AND position = '".$a."'"); $rowsort = mysql_fetch_object($fragsort2); $querystring = $rowsort->sel; if (($querystring == "online") or ($querystring == "online-full")) { $querystringres = 'online-'.$displayset.''; } elseif ($querystring == "msg") { $querystringres = 'msg-'.$displayset.''; } elseif ($querystring == "") { $querystringres = 'clear'; } else { $querystringres = ''.$rowsort->sel.''; } include ''.$modulpath.''.$querystringres.'.php'; } echo '</body>'; mysql_close(); if ($displayset == "moul") { pg_close(); } ?><file_sep><?php include ('set/functions.php'); connectmass(); $iam = $_SERVER["QUERY_STRING"]; if (is_numeric($iam) == TRUE) { $fragdisplay = mysql_query("SELECT * FROM modul WHERE num = '".$_SERVER["QUERY_STRING"]."'"); $rowdis = mysql_fetch_object($fragdisplay); } else { $fragdisplay = mysql_query("SELECT * FROM modul WHERE name = '".$_SERVER["QUERY_STRING"]."'"); $rowdis = mysql_fetch_object($fragdisplay); } if ($rowdis->type == "moul") { connectmoul(); $displayset = "moul"; } elseif ($rowdis->type == "tpots") { connectalcugs(); $displayset = "tpots"; } include ('set/sort.php'); ?><file_sep><?php ###################### ###################### function connectmass() { include '../config/config.php'; $db = mysql_connect($massalcugshost, $massalcugsuser, $massalcugspassword); mysql_select_db ($massdb); } function available($table, $from) { $frag = mysql_query("SELECT * FROM ".$table." ORDER BY num DESC"); $erg = mysql_fetch_object($frag); if ($erg->num == 0) { return 1; } else { for($x=1; $x-1 <= $erg->num; $x++) { $frag2 = mysql_query("SELECT * FROM ".$table." WHERE ".$from." = '".$x."'"); $erg2 = mysql_num_rows($frag2); if ($erg2 == 0) { return $x; break; } } } } function settingsquery($name) { $frag = mysql_query("SELECT * FROM config WHERE name = '".$name."'"); $erg = mysql_fetch_object($frag); return $erg->params; } function generalset() { for ($x=1; $x < count($_POST); $x++) { list($key, $val) = each($_POST); $frag = mysql_query("SELECT * FROM config WHERE name = '".$key."'"); if (mysql_num_rows($frag) == 0) { $insert = "INSERT INTO config values (".available('config', 'num').", '".$key."', '".$val."')"; mysql_query($insert); } else { $update = "UPDATE config SET params = '".$val."' WHERE name = '".$key."'"; mysql_query($update); } } } function sqlaccounts($table) { $frag = mysql_query("SELECT * FROM ".$table." ORDER BY num ASC"); $tohood = newboxes0001; $header = myHeader0001; while($row = mysql_fetch_object($frag)) { $accdelete = "accdelete".$row->num.""; $accnum = "accnum".$row->num.""; $accname = "accname".$row->num.""; $accpass = "accpass".$row->num.""; echo ' <tr> <td align="center"><input type="text" name="T1" size="1" value="'.$row->num.'" disabled></td> <td align="center">'.$row->name.'</td> <td align="center"> <table border="0" width="100%"> <tr> <td width="33%" align="center">&nbsp;</td> <td width="33%" align="center"><a id="'.$header.'" href="javascript:showonlyone('; echo"'".$tohood."'"; echo');" ><input type="button" value="Show"></a><div name="newboxes" id="'.$tohood.'" style="display: none"> <form method="POST" action="'.$_SERVER['PATH_INFO'].'?'.$_SERVER["QUERY_STRING"].'&action=CHANGE&CHANGE='.$accpass.'&SAVE"><input type="text" name="'.$accpass.'" value="'.$row->password.'" size="50"></div></td> <td width="33%" align="center"> <div name="newboxes" id="'.$tohood.'" style="display: none"><input type="submit" value="Change" name="B2"></form></div>'; if ($row->num != 0) { echo '<form method="POST" action="'.$_SERVER['PATH_INFO'].'?'.$_SERVER["QUERY_STRING"].'&action=DELETE&DELETE='.$accdelete.'&SAVE"><input type="submit" value="DELETE" name="B1"></form>'; } echo'</td> </tr> </table> </td> </tr>'; $tohood ++; $header ++; } } function accountset($name, $pw) { $table = "accounts"; $pwis = sha1(''.$name.''.$pw.''); $insert = "INSERT INTO ".$table." values (".available(''.$table.'', 'num').", '".$name."', '".$pwis."')"; if ($_GET['action'] == "DELETE") { $num = substr($_GET['DELETE'], -1); $delete = "DELETE FROM ".$table." WHERE num = '".$num."'"; mysql_query($delete) or die (mysql_error()); } elseif ($_GET['action'] == "CHANGE") { if ($_GET['CHANGE'] != "") { $num = substr($_GET['CHANGE'], -1); $sel = mysql_fetch_object(mysql_query("SELECT * FROM ".$table." WHERE num = '".$num."'")); $name = $sel->name; $pwis = sha1(''.$name.''.$pw.''); $update = "UPDATE ".$table." SET password = '".$pwis."' WHERE num = '".$num."'"; mysql_query($update) or die (mysql_error()); } } elseif ($_GET['action'] == "NEW") { mysql_query($insert) or die (mysql_error()); } } function serveron($pid) { $cmd = "ps -e | grep -w ".$pid.""; exec($cmd, $output, $result); if(count($output) >= 1){ return true; } return false; } function moulserver($name) { $frag = mysql_query("SELECT * FROM config WHERE name = 'moulserver'"); $erg = mysql_fetch_object($frag); if ($name == "dirtsand") { if ($erg->params == 1) { return "checked"; } else { return ""; } } elseif ($name == "moss") { if ($erg->params == 2) { return "checked"; } else { return ""; } } } ###################### ###################### function DSEND($display, $position, $select) { $fragpos = mysql_query("SELECT * FROM displays WHERE display = '".$display."' AND position = '".$position."'"); if(mysql_num_rows($fragpos) > 0) { $selrow = mysql_fetch_object($fragpos); if ($select == "DELETE") { $update = "DELETE FROM displays WHERE display = '".$display."' AND position = '".$position."'"; mysql_query($update) or die (mysql_error()); } else { if ($selrow->select != $select) { $update = "UPDATE displays SET sel = '".$select."' WHERE display = '".$display."' AND position = '".$position."'"; mysql_query($update) or die (mysql_error()); } } } else { if(($select != "DELETE") or ($select != "")) { mysql_query("INSERT INTO displays values (".available('displays', 'num').", '$display', '$position', '$select')") or die (mysql_error()); } } } function group_list($game) { echo ' <tr> <td width="25%">Group No.</td> <td width="25%">Group Pic:</td> <td width="25%">Group Name:</td> <td width="25%">Group Color:</td> <td width="25%">Group Avatars:</td> </tr>'; $frag = mysql_query("SELECT * FROM groups WHERE category = '".$game."' ORDER BY num ASC"); while($rows = mysql_fetch_object($frag)) { $picpath = '../img/group/'; $groupdelete = "groupdelete".$rows->num.""; $groupnum = "groupnum".$rows->num.""; $groupname = "groupname".$rows->num.""; $grouppic = "grouppic".$rows->num.""; $groupcolor = "groupcolor".$rows->num.""; $groupavatar = "groupavatar".$rows->num.""; echo ' <tr> <td> <table border="0" width="100%"> <tr> <td align="center"><input type="text" name="'.$groupnum.'" size="2" value="'.$rows->num.'" disabled></td> </tr> <tr> <td align="center"><a href="'.$_SERVER['PATH_INFO'].'?'.$_SERVER["QUERY_STRING"].'&action=DELETE&DELETE='.$groupdelete.'&SAVE"><input type="submit" value="DELETE" name="'.$groupdelete.'"></a></td> </tr> </table> </td> <td> <table border="0" width="100%"> <tr> <td align="center">'; if ($rows->pic != ""){ echo'<p><img border="0" src="'.$picpath.''.$rows->pic.'" width="20" height="20"></p>'; } echo'</td> </tr> <tr><form method="POST" action="'.$_SERVER['PATH_INFO'].'?'.$_SERVER["QUERY_STRING"].'&action=PIC&PIC='.$grouppic.'&SAVE"> <td align="center"><input type="text" name="'.$grouppic.'" size="10" value="'.$rows->pic.'"></td> </tr> <tr> <td align="center"><input type="submit" value="Change Pic" name="B2"></td> </form></tr> </table> </td> <td> <table border="0" width="100%"> <tr><form method="POST" action="'.$_SERVER['PATH_INFO'].'?'.$_SERVER["QUERY_STRING"].'&action=RENAME&RENAME='.$groupname.'&SAVE"> <td align="center"><input type="text" name="'.$groupname.'" size="10" value="'.$rows->name.'"></td> </tr> <tr> <td align="center"><input type="submit" value="Change Name" name="B2"></td> </form></tr> </table> </td> <td> <table border="0" width="100%"> <tr><form method="POST" action="'.$_SERVER['PATH_INFO'].'?'.$_SERVER["QUERY_STRING"].'&action=COLOR&COLOR='.$groupcolor.'&SAVE"> <td align="center"><p><font color="'.$rows->color.'">TEST</font></p></td> </tr> <tr> <td align="center" bgcolor="'.$rows->color.'"><input type="text" name="'.$groupcolor.'" size="5" value="'.$rows->color.'"></td> </tr> <tr> <td align="center"><input type="submit" value="Change Color" name="B3"></td> </form></tr> </table> </td> <td> <table border="0" width="100%"> <tr><form method="POST" action="'.$_SERVER['PATH_INFO'].'?'.$_SERVER["QUERY_STRING"].'&action=AVATAR&AVATAR='.$groupavatar.'&SAVE"> <td align="center"><textarea rows="5" name="'.$groupavatar.'" cols="30">'.$rows->avatar.'</textarea></td> </tr> <tr> <td align="center"><input type="submit" value="SAVE" name="T1"></a></td> </form></tr> </table> </td> </tr> '; } } function addmodul($game) { echo ' <tr> <td width="25%">Modul No.</td> <td width="25%">Backcolor</td> <td width="25%">Fontcolor</td> <td width="25%">Name</td> </tr>'; $fragdis = mysql_query("SELECT * FROM modul WHERE type = '".$game."' ORDER BY num ASC"); if(mysql_num_rows($fragdis) > 0) { while($row = mysql_fetch_object($fragdis)) { $moduldelete = "moduldelete".$row->num.""; $modulnum = "modulnum".$row->num.""; $modulname = "modulname".$row->num.""; $modulbackcolor = "modulbackcolor".$row->num.""; $modulfontcolor = "modulfontcolor".$row->num.""; echo ' <tr> <td width="25%"> <table border="0" width="100%"> <tr> <td align="center"><input type="text" name="'.$modulnum.'" size="2" value="'.$row->num.'" disabled></td> </tr> <tr> <td align="center"><a href="'.$_SERVER['PATH_INFO'].'?'.$_SERVER["QUERY_STRING"].'&action=DELETE&DELETE='.$moduldelete.'&SAVE"><input type="submit" value="DELETE" name="'.$moduldelete.'"></a></td> </tr> </table> </td> <td width="25%"> <table border="0" width="100%"> <tr><form method="POST" action="'.$_SERVER['PATH_INFO'].'?'.$_SERVER["QUERY_STRING"].'&action=BCOLOR&BCOLOR='.$modulbackcolor.'&SAVE"> <td align="center"><p><font color="'.$row->fontcolor.'"><span style="background-color: '.$row->backcolor.'">TEST</span></font></p></td> </tr> <tr> <td align="center" bgcolor="'.$row->backcolor.'"><input type="text" name="'.$modulbackcolor.'" size="5" value="'.$row->backcolor.'"></td> </tr> <tr> <td align="center"><input type="submit" value="Change Backcolor" name="B1"></td> </form></tr> </table> </td> <td width="25%"> <table border="0" width="100%"> <tr><form method="POST" action="'.$_SERVER['PATH_INFO'].'?'.$_SERVER["QUERY_STRING"].'&action=FCOLOR&FCOLOR='.$modulfontcolor.'&SAVE"> <td align="center"><p><font color="'.$row->fontcolor.'"><span style="background-color: '.$row->backcolor.'">TEST</span></font></p></td> </tr> <tr> <td align="center" bgcolor="'.$row->fontcolor.'"><input type="text" name="'.$modulfontcolor.'" size="5" value="'.$row->fontcolor.'"></td> </tr> <tr> <td align="center"><input type="submit" value="Change Fontcolor" name="B2"></td> </form></tr> </table> </td> <td width="25%"> <table border="0" width="100%"> <tr><form method="POST" action="'.$_SERVER['PATH_INFO'].'?'.$_SERVER["QUERY_STRING"].'&action=RENAME&RENAME='.$modulname.'&SAVE"> <td align="center"><input type="text" name="'.$modulname.'" size="10" value="'.$row->name.'"></td> </tr> <tr> <td align="center"><input type="submit" value="Change Name" name="B3"></td> </form></tr> </table> </td> </tr> '; } } else { echo '<tr><td colspan="4"><p align="center">No Display available</p></td></tr>'; } } function modulvar($change) { if ($_GET['Set'] == "Modul") { $table = "modul"; $insertmoul = "INSERT INTO ".$table." values (".available(''.$table.'', 'num').", 'moul', 'newmoul".$table."', 'white', 'black')"; $inserttpots = "INSERT INTO ".$table." values (".available(''.$table.'', 'num').", 'tpots', 'newtpots".$table."', 'white', 'black')"; } elseif ($_GET['Set'] == "Group") { $table = "groups"; $insertmoul = "INSERT INTO ".$table." values (".available(''.$table.'', 'num').", 'moul', '', 'newmoul".$table."', 'black', 'example, system, Avatar')"; $inserttpots = "INSERT INTO ".$table." values (".available(''.$table.'', 'num').", 'tpots', '', 'newtpots".$table."', 'black', 'example, system, Avatar')"; } if ($_GET['action'] == "DELETE") { $num = substr($_GET['DELETE'], 11); $delete = "DELETE FROM ".$table." WHERE num = '".$num."'"; mysql_query($delete) or die (mysql_error()); $whodelete = substr($_GET['DELETE'], 11); if ($whodelete == 'moduldelete') { $delete2 = "DELETE FROM displays WHERE display = '".$num."'"; mysql_query($delete2) or die (mysql_error()); } } elseif ($_GET['action'] == "RENAME") { if ($_GET['RENAME'] != "") { $num = substr($_GET['RENAME'], 9); $update = "UPDATE ".$table." SET name = '".$change."' WHERE num = '".$num."'"; mysql_query($update) or die (mysql_error()); } } elseif ($_GET['action'] == "PIC") { if ($_GET['PIC'] != "") { $num = substr($_GET['PIC'], 8); $update = "UPDATE ".$table." SET pic = '".$change."' WHERE num = '".$num."'"; mysql_query($update) or die (mysql_error()); } } elseif ($_GET['action'] == "COLOR") { if ($_GET['COLOR'] != "") { $num = substr($_GET['COLOR'], 10); $update = "UPDATE ".$table." SET color = '".$change."' WHERE num = '".$num."'"; mysql_query($update) or die (mysql_error()); } } elseif ($_GET['action'] == "BCOLOR") { if ($_GET['BCOLOR'] != "") { $num = substr($_GET['BCOLOR'], 14); $update = "UPDATE ".$table." SET backcolor = '".$change."' WHERE num = '".$num."'"; mysql_query($update) or die (mysql_error()); } } elseif ($_GET['action'] == "FCOLOR") { if ($_GET['FCOLOR'] != "") { $num = substr($_GET['FCOLOR'], 14); $update = "UPDATE ".$table." SET fontcolor = '".$change."' WHERE num = '".$num."'"; mysql_query($update) or die (mysql_error()); } } elseif ($_GET['action'] == "AVATAR") { if ($_GET['AVATAR'] != "") { $num = substr($_GET['AVATAR'], 11); $update = "UPDATE ".$table." SET avatar = '".$change."' WHERE num = '".$num."'"; mysql_query($update) or die (mysql_error()); } } elseif ($_GET['action'] == "NEW") { if ($_GET['NEW'] == "moul") { mysql_query($insertmoul) or die (mysql_error()); } elseif ($_GET['NEW'] == "tpots") { mysql_query($inserttpots) or die (mysql_error()); } } } ?>
529ae50f3cb32c239d6f88c663e3f2d01246776d
[ "JavaScript", "PHP" ]
26
PHP
Filtik/MASS
261a11d587ef200ac849fce57d555d882f0336e6
dc6f9a820fb2969ed39453c9348ce1540ee38831
refs/heads/master
<repo_name>svanellewee/pg_timesheet<file_sep>/make_schema.py import sys from jinja2 import Environment, PackageLoader, select_autoescape env = Environment(loader=PackageLoader('timesheet', 'templates')) schema_name = sys.argv[1] schema = env.get_template("schema.sql") print(schema.render(schema_name=schema_name)) <file_sep>/uploader.py import yaml import dropbox from dropbox.files import WriteMode from dropbox.exceptions import ApiError, AuthError import sys import os # Uploads contents of LOCALFILE to Dropbox def backup(dbx, local_file, target_path): with open(local_file, 'rb') as f: # We use WriteMode=overwrite to make sure that the settings in the file # are changed on upload print("Uploading " + local_file + " to Dropbox as " + target_path + "...") try: dbx.files_upload(f.read(), target_path, mode=WriteMode('overwrite')) except ApiError as err: # This checks for the specific error where a user doesn't have # enough Dropbox space quota to upload this file if (err.error.is_path() and err.error.get_path().error.is_insufficient_space()): sys.exit("ERROR: Cannot back up; insufficient space.") elif err.user_message_text: print(err.user_message_text) sys.exit() else: print(err) sys.exit() def list_files(dbx, target_path, max_revisions=30): results = dbx.files_list_revisions(target_path, limit=max_revisions) for entry in results.entries: print(entry) def main(): with open(".credentials.yml") as config_file: config = yaml.load(config_file.read()) token = config['upload']['token'] target_path = config['upload']['target_path'] dbx = dropbox.Dropbox(token) try: print(dbx.users_get_current_account()) except AuthError as err: sys.exit("ERROR: Invalid token {}".format(err)) local_file_path = sys.argv[1] file_name = os.path.basename(local_file_path) target = os.path.join(target_path, file_name) backup(dbx, local_file_path, target) list_files(dbx, target) if __name__ == "__main__": main() <file_sep>/mailer.py import yaml from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart import smtplib from os.path import basename from email.mime.text import MIMEText from email.utils import COMMASPACE, formatdate def send_mail(username, password, recipient, subject, body, files=None): assert isinstance(recipient, list) gmail_user = username gmail_pwd = <PASSWORD> msg = MIMEMultipart() msg['From'] = username msg['To'] = COMMASPACE.join(recipient) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText(body)) for f in files or []: with open(f, "rb") as fil: part = MIMEApplication( fil.read(), Name=basename(f) ) part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f) msg.attach(part) smtp = smtplib.SMTP_SSL("smtp.gmail.com", 465) smtp.ehlo() smtp.login(gmail_user, gmail_pwd) smtp.sendmail(gmail_user, recipient, msg.as_string()) smtp.close() import random import sys import datetime print(sys.argv) with open(".credentials.yml") as config_file: config = yaml.load(config_file.read()) username, password, recipient = config['email']['username'], config['email']['password'], config['email']['recipients'][0] subject = "Time sheet at: "+datetime.datetime.now().isoformat() send_mail(username, password, config['email']['recipients'], "Today's timesheet", random.choice(["Timesheet for today {}".format(subject), "Today's timesheet {}".format(subject),]), sys.argv[1:]) <file_sep>/setup.py # insert setup code here <file_sep>/Makefile VIRTUALENV_DIR=timesheet_venv PIP=$(VIRTUALENV_DIR)/bin/pip PYTHON=$(VIRTUALENV_DIR)/bin/python DCOMPOSE=docker-compose DCOMPOSE_PGRES_DIR=./postgres_timesheet_data $(VIRTUALENV_DIR): pyvenv $(VIRTUALENV_DIR) $(PIP) install -U pip clean: docker-stop rm -fr $(VIRTUALENV_DIR) rm -fr $(DCOMPOSE_PGRES_DIR) depends: $(VIRTUALENV_DIR) $(PIP) install aiopg aiohttp PyYAML docker-compose jinja2 dropbox DOCKER_IP?=127.0.0.1 # 192.168.99.100 docker machine? DOCKER_POSTGRES_PORT=54320 # as per docker-compose file docker-start: depends $(DCOMPOSE) pull && \ $(DCOMPOSE) up -d docker-stop: $(DCOMPOSE) kill && \ $(DCOMPOSE) rm -f PSQL=psql -h $(DOCKER_IP) -p $(DOCKER_POSTGRES_PORT) # INITDB=initdb -h $(DOCKER_IP) -p $(DOCKER_POSTGRES_PORT) # CREATEDB=createdb -h $(DOCKER_IP) -p $(DOCKER_POSTGRES_PORT) # Postgres cli should use docker incantation actually... POSTGRES?=/home/stephan/applications/postgres9.6.2/ PG_RESTORE=$(POSTGRES)/bin/pg_restore -U timesheet -h $(DOCKER_IP) -p $(DOCKER_POSTGRES_PORT) PG_DUMP=$(POSTGRES)/bin/pg_dump -U timesheet -h $(DOCKER_IP) -p $(DOCKER_POSTGRES_PORT) PG_RESTORE=pg_restore -U timesheet -h $(DOCKER_IP) -p $(DOCKER_POSTGRES_PORT) #PG_DUMP=pg_dump -U timesheet -h $(DOCKER_IP) -p $(DOCKER_POSTGRES_PORT) --force destroydb: $(PSQL) -U postgres -c "DROP DATABASE IF EXISTS timesheet;" $(PSQL) -U postgres -c "DROP USER IF EXISTS timesheet;" createdb: $(PSQL) -U postgres -c "CREATE DATABASE timesheet;" $(PSQL) -U postgres -c "CREATE USER timesheet PASSWORD '<PASSWORD>';" $(PSQL) -U postgres -c "GRANT ALL ON DATABASE timesheet TO timesheet;" resetdb: destroydb createdb schema: $(PYTHON) make_schema.py $(PROJECT) | $(PSQL) -U timesheet -f - restore: resetdb $(PG_RESTORE) -C -d timesheet "$(BACKUP)" psql: $(PSQL) -U timesheet NEW_TIMESHEET=$(shell date +'%y.%m.%d_%H:%M:%S').sql backup: $(PG_DUMP) -Fc timesheet > $(NEW_TIMESHEET) $(PYTHON) uploader.py $(NEW_TIMESHEET) $(PYTHON) mailer.py $(NEW_TIMESHEET) clockin: @echo "Clock-in: $(REASON) $(PROJECT)" @$(PSQL) -U timesheet -c "SELECT $(PROJECT).clockin('$(REASON)');" clockout: @echo "Clock-in: $(REASON) $(PROJECT)" @$(PSQL) -U timesheet -c "SELECT $(PROJECT).clockout('$(REASON)');" note: @echo "adding note: $(REASON) $(PROJECT)" @$(PSQL) -U timesheet -c "SELECT $(PROJECT).add_note('$(REASON)');" all-tasks-complete: @$(PSQL) -U timesheet -c "SELECT * FROM $(PROJECT).all_completed_tasks;" all-tasks: @$(PSQL) -U timesheet -c "SELECT * FROM $(PROJECT).all_tasks;" today: @echo "How today looks like:" @$(PSQL) -U timesheet -c "SELECT * FROM $(PROJECT).today;" <file_sep>/timesheet/server.py import aiopg import asyncio from aiohttp import web loop = asyncio.get_event_loop() app = web.Application(loop=loop) async def get_today(): conn = await aiopg.connect(database='timesheet', host='127.0.0.1') cur = await conn.cursor() await cur.execute("SELECT * FROM timesheet.today") retval = [] async for elem in cur: return elem async def start_day(request): return web.Response(text='{}', content_type='application/json') async def index(request): values = await get_today() for value in values: print("..",values) return web.Response(text='{"Hello": "World"}"', content_type='application/json') app.router.add_get("/", index) web.run_app(app, host='127.0.0.1', port=8088)
cb8211f61b65b6b2add5545a598a5ca60a301bd0
[ "Python", "Makefile" ]
6
Python
svanellewee/pg_timesheet
12c8bff4e13c53fe035671c3b7ae60f6bab1a132
33250e769581c3b32d1fab74834f7e1e59064b31
refs/heads/master
<repo_name>BruceMcl/venues<file_sep>/database.php <?php // The SQL to uninstall this tool $DATABASE_UNINSTALL = array( "drop table if exists {$CFG->dbprefix}booking", "drop table if exists {$CFG->dbprefix}venue" ); // The SQL to create the tables if they don't exist $DATABASE_INSTALL = array( array( "{$CFG->dbprefix}venue", "create table {$CFG->dbprefix}venue ( link_id INTEGER NOT NULL, user_id INTEGER NOT NULL, venue_id TEXT NOT NULL, added_on DATETIME NOT NULL, CONSTRAINT `{$CFG->dbprefix}venue_ibfk_1` FOREIGN KEY (`link_id`) REFERENCES `{$CFG->dbprefix}lti_link` (`link_id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `{$CFG->dbprefix}venue_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `{$CFG->dbprefix}lti_user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE, UNIQUE(link_id, user_id, venue_id) ) ENGINE = InnoDB DEFAULT CHARSET=utf8"), array( "{$CFG->dbprefix}booking", "create table {$CFG->dbprefix}booking ( link_id INTEGER NOT NULL, user_id INTEGER NOT NULL, venue_id TEXT NOT NULL, booking_Date INTEGER NOT NULL, CONSTRAINT `{$CFG->dbprefix}booking_ibfk_1` FOREIGN KEY (`link_id`) REFERENCES `{$CFG->dbprefix}lti_link` (`link_id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `{$CFG->dbprefix}booking_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `{$CFG->dbprefix}lti_user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE, UNIQUE(link_id, user_id) ) ENGINE = InnoDB DEFAULT CHARSET=utf8")); <file_sep>/register.php <?php $REGISTER_LTI2 = array( "name" => "Venue Booking Tool", "FontAwesome" => "fa-server", "short_name" => "Room Tool", "description" => "This is a simple venue booking tool that allows the booking of a venue." ); <file_sep>/index.php <?php require_once "../config.php"; // The Tsugi PHP API Documentation is available at: // http://do1.dr-chuck.com/tsugi/phpdoc/ use \Tsugi\Core\LTIX; use \Tsugi\Core\Settings; use \Tsugi\Util\Net; // No parameter means we require CONTEXT, USER, and LINK $LAUNCHSESSION = LTIX::session_start(); $LAUNCH = LTIX::requireData(); // Handle Post Data $p = $CFG->dbprefix; if (isset($_POST['createVenue'])) { $PDOX->queryDie("INSERT INTO {$p}venue (link_id, user_id, venue_id, added_on) VALUES ( :LI, :UI, :venue_id, :added_on )", array( ':LI' => $LINK->id, ':UI' => $USER->id, ':venue_id' => $_POST['txtVenue'], ':added_on' =>$_POST['txtDate'] ) ); return; } if (isset($_POST['addBooking'])) { return; } // Render view $OUTPUT->header(); $OUTPUT->bodyStart(); $OUTPUT->topNav(); $OUTPUT->welcomeUserCourse(); $OUTPUT->flashMessages(); echo("<!-- Classic single-file version of the tool -->\n"); // We could use the settings form - but we will keep this simple //Body content here: //include(addVenue.php); //include(makeBooking.php); echo("Add new venue"); echo("<table> <form method='post'> <tr> <td>Venue:</td> <td>Date:</td> </tr> <tr> <td><input type='text' required name='txtVenue' id='txtVenue' /></td> <td><input type='text' required name='txtDate' id='txtDate' /></td> </tr> <tr> <td> <input type='submit' name='createVenue' id='createVenue' value='Go'> </td> </tr> </form> </table>"); $OUTPUT->footer();
ab3334cba09fdc3d927c3e35bd1af9438bcfe01d
[ "PHP" ]
3
PHP
BruceMcl/venues
c386d19b0dc27512da84650c04d9e787c7e7c954
8a94b9dbadeadacb1ff89c156d02a597986170b1
refs/heads/master
<file_sep>setwd("~/great lakes/Facebook_metrics") fb <- read.csv("dataset_Facebook.csv", header = TRUE) View(fb) ?read.csv fb <- read.csv("dataset_Facebook.csv", header = TRUE, sep = ";") require(dplyr) Select<- head(select(fb, Category:Paid)) View(Select) View(fb) str(fb) fb$Post.Hour v <- fb[,2] View(v) u <- fb[1:10,2] View(u) str(fb) #dataframe$columnname = as.numeric/factor(dataframe$columnname) fb$comment <- as.numeric(fb$comment) # merge authors <- data.frame( ## I(*) : use character columns of names to get sensible sort order surname = I(c("Tukey", "Venables", "Tierney", "Ripley", "McNeil")), nationality = c("US", "Australia", "US", "UK", "Australia"), deceased = c("yes", rep("no", 4))) authorN <- within(authors, { name <- surname; rm(surname) }) books <- data.frame( name = I(c("Tukey", "Venables", "Tierney", "Ripley", "Ripley", "McNeil", "R Core")), title = c("Exploratory Data Analysis", "Modern Applied Statistics ...", "LISP-STAT", "Spatial Statistics", "Stochastic Simulation", "Interactive Data Analysis", "An Introduction to R"), other.author = c(NA, "Ripley", NA, NA, NA, NA, "<NAME>")) m1 <- merge(authors, books, by.x = "surname", by.y = "name") m2 <- merge(books, authors, by.x = "name", by.y = "surname") ?merge View(fb) fb <- read.csv("dataset_Facebook.csv", header = TRUE, sep = ";") View(fb) # with funciton a = mean(fb$Lifetime.Post.Total.Reach + fb$Page.total.likes + fb$Lifetime.Post.Total.Impressions) a # using with(), we can clean this up: b = with(fb, mean(Lifetime.Post.Total.Reach + Page.total.likes + Lifetime.Post.Total.Impressions)) b library(dplyr) ?subset reach <- subset(fb,select=c(Lifetime.Post.Total.Reach,Page.total.likes)) View(reach) str(fb) ?select reach1 <- select(fb,Lifetime.Post.reach.by.people.who.like.your.Page,comment ) View(reach1) #ends_with() = Select columns that end with a character string #contains() = Select columns that contain a character string #matches() = Select columns that match a regular expression #one_of() = Select columns names that are from a group of names ?filter reach3 <- filter(fb, Category == 2) View(reach3) reach4 <- filter(fb, Category == 2, Post.Month == 12) View(reach4) ?arrange reach5 <- arrange(fb,Post.Month) View(reach5) ?rename fb <- rename(fb, month = Post.Month) View(fb)<file_sep># source- https://archive.ics.uci.edu/ml/machine-learning-databases/water-treatment/ water <- read.delim("water-treatment.data.txt", header=FALSE, sep = ",") water <- read.delim("water-treatment.data.txt", header=FALSE, sep = ",",na.strings=c("?"," ","NA")) View(water) colnames(water) <- c( "Q-E", "ZN-E", "PH-E", "DBO-E", "DQO-E", "SS-E", "SSV-E", "SED-E", "COND-E", "PH-P", "DBO-P", "SS-P", "SSV-P", "SED-P", "COND-P", "PH-D", "DBO-D", "DQO-D", "SS-D", "SSV-D", "SED-D", "COND-D", "PH-S", "DBO-S", "DQO-S", "SS-S", "SSV-S", "SED-S", "COND-S", "RD-DBO-P", "RD-SS-P", "RD-SED-P", "RD-DBO-S", "RD-DQO-S", "RD-DBO-G", "RD-DQO-G", "RD-SS-G", "RD-SED-G", "percent" ) # print total number of NAs in the data sum(is.na(water)) # print the columns with NAs in the data colnames(water)[colSums(is.na(water)) > 0] str(water) library(Amelia) missmap(water) water[is.na(water)] <- 50 ## scale func.watertion standardizes the values scaled.water <- scale(water) scaled.water <- scale(water[,-1]) View(scaled.water) # Identifying the optimal number of clusters library(NbClust) ?NbClust set.seed(100) nc.water <- NbClust(water[,-1], distance = "euclidean", method="kmeans") table(nc.water$Best.n[1,]) barplot(table(nc.water$Best.n[1,]), xlab="Numer of Clusters", ylab="Number of Criteria", main="Number of Clusters Chosen by 26 Criteria") ?kmeans kwater = kmeans(x=scaled.water, centers = 3, nstart = 10) kwater ## plotting the clusters ##install.packages("fpc") library(fpc) plotcluster(scaled.water, kwater$cluster) library(cluster) ?clusplot clusplot(scaled.water, kwater$cluster, color=TRUE, shade=TRUE, labels=2, lines=1) #add a new column Cluster and assign values of clusters to individual data points water$Clusters <- kwater$cluster View(water) aggr = aggregate(water[,-1],list(water$Clusters),mean) profile.updated <- data.frame( Cluster=aggr[,1], Freq=as.vector(table(water$Clusters)), aggr[,-1]) View(profile.updated) <file_sep>setwd("~/machine learning with R") library(car) library(ggplot2) library(tabplot) library(corrplot) library(scatterplot3d) library(dplyr) library(devtools) install_github("mtennekes/tabplot") # source-https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/ ?read.delim auto.mpg <- read.delim("auto-mpg.data.txt", header = FALSE,sep = "") View(auto.mpg) colnames(auto.mpg) <- c("mpg","cylinders","displacement","horsepower","weight","acceleration","model year","origin","car name") View(auto.mpg) str(auto.mpg) auto.mpg$`car name` <- as.factor(auto.mpg$`car name`) auto.mpg$horsepower <- as.factor(auto.mpg$horsepower) summary(auto.mpg) # area of interest = mpg is influenced displacement of the car # area of interest = dependent variable # displacement = independent variable hist(auto.mpg$mpg) hist(auto.mpg$displacement) tableplot(auto.mpg[,-9]) pairs(auto.mpg) ggplot(data = auto.mpg,aes(y=auto.mpg$weight, x=auto.mpg$mpg)) +geom_boxplot(aes(col=mpg))+labs(title="Boxplot of weight & mpg") plot(auto.mpg$weight, auto.mpg$mpg) plot(auto.mpg$mpg,auto.mpg$weight) mod <- lm(formula = mpg ~ weight, data = auto.mpg) summary(mod) # value of r-squared should be close to 1 to represent good variance # we have got over 0.6 so it is good but not good enough lmplot<-ggplot(data = auto.mpg, aes(x=weight, y=mpg)) + geom_point() lmplot<- lmplot + geom_smooth(method ="lm", col="red") lmplot + geom_smooth() # visualize residuals & fitted line ?plot plot(mod, which = 1, pch=16) # multiple linear regression plot(auto.mpg, col="blue") mod1 <- lm(formula = mpg ~ weight + displacement + acceleration, data = auto.mpg) summary(mod1) new.auto <- auto.mpg[,1:5] head(new.auto) str(new.auto) new.auto$horsepower <- as.numeric(new.auto$horsepower) new.auto$cylinders <- as.numeric(new.auto$cylinders) str(new.auto) cor.plot <- cor(as.matrix(new.auto)) corrplot(cor.plot) # not comfortable with colors & need numbers, use method = "number" corrplot(cor.plot, method = "number") #mod.multi <- lm(formula = cylinders ~ displacement + weight, data = new.auto) summary(mod) plot(mod1, pch=16, which=1) new.3dplot <- select(new.auto,cylinders,displacement,weight) head(new.3dplot) scatterplot3d(new.3dplot) <file_sep># source - https://archive.ics.uci.edu/ml/machine-learning-databases/nursery/ nursery <- read.delim("nursery.data.txt", sep = ",", header = FALSE) colnames(nursery) <- c( "parents", "has_nurs", "form", "children", "housing", "finance", "social", "health", "class" ) str(nursery) summary(nursery) sum(is.na(nursery)) set.seed(100) nursery$random <- runif (nrow(nursery), 0, 1) trainingData <- nursery[which(nursery$random <= 0.8),] testData <- nursery[which(nursery$random > 0.8),] c (nrow(trainingData), nrow(testData)) print(table(nursery$class)) print(table(nursery$parents)) print(table(nursery$children)) library(e1071) naive.classfier=naiveBayes(class~., data=nursery) print(naive.classfier) # scoring trainingData$predict.class <- predict(naive.classfier, trainingData, type="class") with(trainingData, table(class, predict.class)) library(caret) confusionMatrix(with(trainingData, table(class, predict.class))) testData$predict.class <- predict(naive.classfier, testData, type="class") confusionMatrix(with(testData, table(class, predict.class))) library(naivebayes) new.lib=naive_bayes(class~.,usekernel=T, data=trainingData) print(new.lib) <file_sep># https://archive.ics.uci.edu/ml/machine-learning-databases/glass/glass.names glass.data<- read.delim("glass.data.txt", sep = ",") View(glass.data) colnames(glass.data) <- c( "Id", "RI", "Na.Sodium", "Magnesium", "Aluminum", "Silicon", "Potassium", "Calcium", "Barium", "Iron", "Type.glass" ) View(glass.data) str(glass.data) summary(glass.data) sum(is.na(glass.data)) set.seed(100) glass.data$random <- runif (nrow(glass.data), 0, 1) trainingData <- glass.data[which(glass.data$random <= 0.8),] testData <- glass.data[which(glass.data$random > 0.8),] c (nrow(trainingData), nrow(testData)) normalize <- function(x){ return ((x-min(x))/(max(x)-min(x))) } train.norm <- as.data.frame(lapply(trainingData[,-11], normalize)) test.norm <- as.data.frame(lapply(trainingData[,-11], normalize)) # str(trainingData) output <- trainingData$Type.glass test.output <- testData$Type.glass library(class) model1<- knn(train=train.norm, test=test.norm, cl=output, k=16) k16 <- 100* sum(output == model1) /NROW(output) k16 table(model1, trainingData[,11]) library(caret) confusionMatrix(table(model2, trainingData[,11])) model2<- knn(train=train.norm, test=test.norm, cl=output, k=3) k3 <- 100* sum(output == model2) /NROW(output) k3 model1 plot(model1) <file_sep> library(neuralnet) library(data.table) library(scales) library(caret) # data source- https://archive.ics.uci.edu/ml/machine-learning-databases/adult/ ?read.delim # impute na instead of ? # can't impute NA directly if it is present in factors income.orig <- read.delim("adult-data.txt", header = FALSE, sep = ",", na.strings=c(""," "," ?","NA")) # name the columns colnames(income.orig) <- c( "age", "workclass", "final.weight", "education", "education.num", "marital-status", "occupation", "relationship", "race", "sex", "capital.gain", "capital.loss", "hours.per.week", "country", "final.class" ) View(income.orig) #structure of data str(income.orig) # print total number of NAs in the data sum(is.na(income.orig)) # print the columns with NAs in the data colnames(income.orig)[colSums(is.na(income.orig)) > 0] summary(income.orig) #install.packages("mice") library(mice) # displays a table with NA md.pattern(income.orig) #verify number of NAs sum(is.na(income.orig$workclass)) sum(is.na(income.orig$country)) sum(is.na(income.orig$occupation)) summary(income.orig) #library-Hmisc, mice are good choice for handling NAs # create library(forcats) workclass.new<- fct_explicit_na(income.orig$workclass, na_level = " None") income.orig$workclass.new <- workclass.new country.new<- fct_explicit_na(income.orig$country, na_level = " None") income.orig$country.new <- country.new occupation.new<- fct_explicit_na(income.orig$occupation, na_level = " None") income.orig$occupation.new <- occupation.new str(income.orig) summary(income.orig) occ.matrix <- model.matrix(~ occupation.new - 1, data = income.orig) income.orig <- data.frame(income.orig, occ.matrix) library(plyr) library(dplyr) str(income.orig) income.orig$final.class <- revalue(income.orig$final.class, c(" >50K"="1")) income.orig$final.class <- revalue(income.orig$final.class, c(" <=50K"="0")) # training & test datasets set.seed(100) income.orig$random <- runif (nrow(income.orig), 0, 1) trainingData <- income.orig [which(income.orig$random <= 0.8),] testData <- income.orig [which(income.orig$random > 0.8),] c (nrow(trainingData), nrow(testData)) ?"neuralnet" # neuralnet only works with quantitative variables, #you need to convert factors to binary ("dummy") variables, with the model.matrix str(trainingData) ?neuralnet nn1 <- neuralnet(formula = as.numeric(final.class) ~ occupation.new.Adm.clerical + occupation.new.Armed.Forces + occupation.new.Craft.repair + occupation.new.Exec.managerial +occupation.new.Farming.fishing +occupation.new.Handlers.cleaners+occupation.new.Machine.op.inspct+occupation.new.Other.service +occupation.new.Priv.house.serv+age , data = trainingData, hidden = c(5,2), err.fct = "sse", linear.output = FALSE, lifesign = "full", lifesign.step = 10, threshold = 0.01, stepmax = 2000 ) plot (nn1) nn1$result.matrix ## Assigning the Probabilities to Dev Sample trainingData$Prob = nn1$net.result[[1]] View(trainingData) ## The distribution of the estimated probabilities quantile(trainingData$Prob, c(0,1,5,10,25,50,75,90,95,98,99,100)/100) boxplot(trainingData$Prob) ## Rebuilding the model by Scaling the Independent Variables str(income.orig) ## build the neural net model by scaling the variables scaled.data <- subset(income.orig, select = c( "occupation.new.Adm.clerical" , "occupation.new.Armed.Forces" , "occupation.new.Craft.repair" , "occupation.new.Exec.managerial" ,"occupation.new.Farming.fishing" ,"occupation.new.Priv.house.serv","age") ) nn.devscaled <- scale(scaled.data) # add final class column to it nn.devscaled <- cbind(income.orig[15],nn.devscaled) View(nn.devscaled) # to decide number of neurons, take square root of total variables # err.fct is error function=loss function # linear output = false because this is a classification problem nn2 <- neuralnet(formula =as.numeric(final.class)~ occupation.new.Adm.clerical+occupation.new.Armed.Forces +age, data = nn.devscaled, hidden =c(9,3), err.fct = "sse", linear.output = FALSE, lifesign = "full", lifesign.step = 10, threshold = 0.05, stepmax = 2000, ) weights1 <- nn2$weights weights1 plot(nn2) ## Assigning the Probabilities to training nn.devscaled$Prob2= nn2$net.result[[1]] ## The distribution of the estimated probabilities quantile(nn.devscaled$Prob, c(0,1,5,10,25,50,75,90,95,99,100)/100) hist(nn.devscaled$Prob) ## Assgining 0 / 1 class based on certain threshold nn.devscaled$Class = ifelse(nn.devscaled$Prob>0.21,1,0) with( nn.devscaled, table(final.class, as.factor(Class))) # classification error - 1845/14000 - 0.1317857143 ## We can use the confusionMatrix function of the caret package ##install.packages("caret") ## Other Model Performance Measures library(ROCR) class(nn.dev) pred <- prediction(nn.devscaled$Prob, nn.devscaled$final.class) perf <- performance(pred, "tpr", "fpr") plot(perf) KS <- max(attr(perf, 'y.values')[[1]]-attr(perf, 'x.values')[[1]]) auc <- performance(pred,"auc"); auc <- as.numeric(auc@y.values) library(ineq) gini = ineq(nn.devscaled$Prob, type="Gini") auc KS gini <file_sep>require(dplyr) library() fb <- read.csv("dataset_Facebook.csv", header = TRUE, sep = ";") View(fb) a <- fb$Post.Hour #basic command a v <- fb[,3] v u <- fb[1:10,2:6] class(u) View(u) z <- fb$Page.total.likes z a = mean(fb$Lifetime.Post.Total.Reach + fb$Page.total.likes + fb$Lifetime.Post.Total.Impressions) a b = with(fb, mean(Lifetime.Post.Total.Reach + Page.total.likes + Lifetime.Post.Total.Impressions)) b View(fb) str(fb) library(dplyr) ?select Select <- select(fb, Category:Paid) View(Select) str(fb) Filter <- filter(fb, Lifetime.Post.Total.Reach > 3000) ?arrange arranged <- arrange(Filter, Lifetime.Post.Total.Reach) View(arranged) ?sort #try this function ?mutate View(arranged) str(arranged) ?mutate arranged %>% mutate( comment.square = comment ^ 2, likeo = like + 2 ) View(arranged) arranged <- arranged %>% mutate( comment.square = comment ^ 2, likeo = like + 2, ) str(fb) #dataframe$columnname = as.numeric/factor(dataframe$columnname) fb$comment <- as.numeric(fb$comment) fb$Category <- as.factor(fb$Category) View(fb) fb <- read.csv("dataset_Facebook.csv", header = TRUE, sep = ";") View(fb) # with funciton a = mean(fb$Lifetime.Post.Total.Reach + fb$Page.total.likes + fb$Lifetime.Post.Total.Impressions) a # using with(), we can clean this up: b = with(fb, mean(Lifetime.Post.Total.Reach + Page.total.likes + Lifetime.Post.Total.Impressions)) b ?subset reach <- subset(fb,select=c(Lifetime.Post.Total.Reach,Page.total.likes)) View(reach) str(fb) ?select reach1 <- select(fb,Lifetime.Post.reach.by.people.who.like.your.Page,comment) View(reach1) #ends_with() = Select columns that end with a character string #contains() = Select columns that contain a character string #matches() = Select columns that match a regular expression #one_of() = Select columns names that are from a group of names ?filter reach3 <- filter(fb, Category == 2) View(reach3) reach4 <- filter(fb, Category == 2, Post.Month == 12) View(reach4) ?arrange reach5 <- arrange(fb,Post.Month) View(reach5) library(xlsx) LA2017_candidate <- read.xlsx("LA 2017.xls", sheetIndex = 1) LA2017_candidatebye <- read.xlsx("LA 2017.xls", sheetIndex = 3) ?merge plxsell <- merge(LA2017_candidate, LA2017_candidatebye, all.x = TRUE, all.y = TRUE) View(plxsell) <file_sep> # data source- https://archive.ics.uci.edu/ml/machine-learning-databases/arrhythmia/ # PCA only works with numerical column ?read.delim ca.arry <- read.delim("arrhythmia.data.txt", header = FALSE, sep = ",") View(ca.arry) # impute na instead of ? # can't impute NA directly if it is present in factors ca.arry <- read.delim("arrhythmia.data.txt", header = FALSE, sep = ",", na.strings=c("?"," ","NA")) View(ca.arry) str(ca.arry) summary(ca.arry) pairs(ca.arry, gap = 0, pch = 21) library(corpcor) corrmatrix<-cor(ca.arry) # print the names of the column with 0 colnames(ca.arry)[colSums(is.na(ca.arry)) > 0] ca.arry.updated <- ca.arry[, -c(11:15)] str(ca.arry.updated) ?cor corrmatrix<- cor(ca.arry.updated, use = "complete.obs") ca.zero <- subset(ca.arry.updated, select=colSums(ca.arry.updated) > 0) View(ca.zero) corrmatrix<- cor(ca.zero, use = "complete.obs") corrmatrix library(corrplot) corrplot(corrmatrix) ?princomp pc <- princomp(ca.zero, cor = TRUE, scores = TRUE) summary(pc) plot(pc) plot(pc, type="l") attributes(pc) pc$loadings pc$scores lo.model <- glm(V2 ~ pc$scores[,1]+pc$scores[,2], data=ca.zero, family=binomial("logit")) summary(lo.model) library(pls) #pcr() function is similar to that for lm() ?pcr pcr.m <- pcr(V2~pc$scores[,1]+pc$scores[,2], data = ca.zero, scale = TRUE, validation = "CV") pcr.m2 <- pcr(V2~., data = ca.arry, scale = TRUE, validation = "CV") summary(pcr.m) validationplot(pcr.m) <file_sep>## loading the library library(rattle) library(RColorBrewer) library(ggplot2) library(data.table) library(scales) library(ROCR) library(ineq) library(tabplot) library(xlsx) # data source- https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/ b.cancer <- read.delim("breast-cancer-wisconsin.data.txt", sep = ",", header = FALSE) View(b.cancer) colnames(b.cancer) <- c( "code", "Clump.Thickness", "Uniformity.of.Cell.Size", "Uniformity.of.Cell.Shape", "Marginal.Adhesion", "Single.Epithelial.Cell.Size", "Bare.Nuclei", "Bland.Chromatin", "Normal.Nucleoli", "Mitoses", "Class" ) #structure of data str(b.cancer) # print total number of NAs in the data sum(is.na(b.cancer)) summary(b.cancer) # wrong way in this case #bank.data$default <- as.numeric(bank.data$default) # right way # one hot encoding #library(modelr) #dummy.data<- model.matrix(~default, data = bank.data) # # dummy.data<- model_matrix(b.cancer,~ default-1) # # bankdata.updated <- cbind(b.cancer,dummy.data) library(plyr) library(dplyr) # data exploration #ggplot(data = election.dev,aes(y=election.dev$BALANCE, x=election.dev$OCCUPATION)) +geom_boxplot(aes(col=OCCUPATION))+labs(title="Boxplot of Balance for all occupation types") #ggplot(data = election.dev,aes(y=election.dev$BALANCE, x=election.dev$AGE_BKT)) +geom_boxplot(aes(col=AGE_BKT))+labs(title="Boxplot of Balance for age brackets types") # g <- ggplot(election.dev, aes(election.dev$HOLDING_PERIOD)) # g + geom_bar() # g + geom_bar(aes(weight = election.dev$HOLDING_PERIOD)) # g + geom_bar() # # g <- ggplot(election.dev, aes(election.dev$AGE)) # g + geom_bar() # g + geom_bar(aes(weight = election.dev$AGE)) # g + geom_bar() # g <- ggplot(election.dev, aes(election.dev$TARGET)) # g + geom_bar() # g + geom_bar(aes(weight = election.dev$TARGET)) # g + geom_bar(aes(fill = '#A4A4A4',, color="darkred")) # # sctplot<-ggplot(data = election.dev, aes(x=AGE, y=BALANCE)) + geom_point() # # sctplot<- sctplot + geom_smooth(method ="lm", col="red") # # sctplot + geom_smooth(col="green") set.seed(100) b.cancer$random <- runif (nrow(b.cancer), 0, 1) trainingData <- b.cancer [which(b.cancer$random <= 0.8),] testData <- b.cancer [which(b.cancer$random > 0.8),] c (nrow(trainingData), nrow(testData)) library(rpart) library(rpart.plot) #cart ?rpart.control r.ctrl = rpart.control(minsplit=50, minbucket = 10, cp = 0.02, xval = 10) m1 <- rpart(formula = Class ~ ., data = b.cancer, method = "class", control = r.ctrl) m1 #node), split, n, loss, yval, (yprob) # node) represent the node number # split= name of variable/attributes used for split # n =of data elements in this node # loss = presence of untarget elements in this stage # yval= label assigned to a node # yprob = displays proportion of 0 and 1 class fancyRpartPlot(m1, uniform=TRUE, cex=0.4) ## to find how the tree performs printcp(m1) # cp indicates the classification error #nsplit displays the split node at which classification error is encountered # rel error column display that classification keeps going down as number of splits goes up # xerror indicates cross validation error, if there is overfitting error will go up so we need to find the lowest value and use that # as cp value for pruning the ree plotcp(m1) #pruning ptree<- prune(m1, cp= 0.16,"CP") printcp(ptree) fancyRpartPlot(ptree, uniform=TRUE, main="Pruned Classification Tree") # scoring trainingData$predict.class <- predict(ptree, trainingData, type="class") trainingData$predict.score <- predict(ptree, trainingData, type="prob") # predict.score.1 columns give probability of record being 1 # predict.score.0 columns give probability of record being 0 head(trainingData) View(trainingData) pred <- prediction(trainingData$predict.score[,2],(trainingData$Class)) perf <- performance(pred, "tpr", "fpr") KS <- max(attr(perf, 'y.values')[[1]]-attr(perf, 'x.values')[[1]]) # KS value of 40 or above good but we should target higher value KS auc <- performance(pred,"auc"); auc auc <- as.numeric(auc@y.values) # gini is computed on probability column gini = ineq(trainingData$predict.score[,2], type="Gini") plot(perf) #classification error with(trainingData, table(Class, predict.class)) #Mis-Classification Error = 31+11/ 332+31+11+181 = 0.07567568 (7.5%) auc KS gini # Holdout sample nrow(testData) ## Scoring Holdout sample testData$predict.class <- predict(ptree, testData, type="class") testData$predict.score <- predict(ptree, testData, type="prob") View(testData) pred <- prediction(testData$predict.score[,2], testData$Class) perf <- performance(pred, "tpr", "fpr") KS <- max(attr(perf, 'y.values')[[1]]-attr(perf, 'x.values')[[1]]) auc <- performance(pred,"auc"); auc <- as.numeric(auc@y.values) gini = ineq(testData$predict.score[,2], type="Gini") with(testData, table(Class, predict.class)) #classification error- 13+2/71+13+2+48 =0.1119403 (11.19%) auc KS gini # library("randomForest") # churn.rf = randomForest(churn ~ ., data = trainset, importance = T) <file_sep>#setwd("") #https://www.kaggle.com/c/titanic/data titanicd <- read.csv("train_titanic.csv") View(titanicd) #in order to treat the blank string as NA, one can specify that na.strings equals either "NA" or an empty string titanicdna <- read.csv("train_titanic.csv", na.strings = c("NA", "")) View(titanicdna) str(titanicdna) ?summary summary(titanicdna) #The is.na function is used to denote which index of the attribute contains the NA value. #Here, we apply it to the Age attribute first: is.na(titanicdna$Age) # The is.na function indicates the missing value of the Age attribute. #To get a general number of how many missing values there are, you can perform a sum to calculate this sum(is.na(titanicdna$Age)) str(titanicdna) 177/891 # total percentage of missing values #To calculate the percentage of missing values, #one method adopted is to count the number of missing values against nonmissing values: sum(is.na(titanicdna$Age) == TRUE) / length(titanicdna$Age) summary(titanicdna) #To get a percentage of the missing value of the attributes, #you can use sapply to calculate the percentage of all the attributes: ?sapply # stop this video and write similar code for other variables from line # 19 to 37. # na.rm is used to ignore the NA and otherwise, it will throw NA as result instead of mean # na.omit() from dplyr is useful when you want to drop NA values titanicdna$Embarked <- as.factor(titanicdna$Embarked) class(titanicdna$Embarked) mnAge <- mean(titanicdna$Age, na.rm = TRUE) mnAge View(titanicdna) library(dplyr) ?mutate Ageupdated <- mutate(titanicdna,Ageupdated = ifelse(is.na(Age), mnAge,Age)) View(Ageupdated) View(titanicdna) sum(is.na(titanicdna$Embarked)) # C = Cherbourg, Q = Queenstown, S = Southampton Embarkedupdated <- mutate(titanicdna,Embarkedupdated = ifelse(is.na(Embarked), "S",Embarked)) sum(is.na(titanicdna$Embarkedupdated)) <file_sep>library(tidyverse) library(ggplot2) library(readr) library(maps) library(viridis) ## get the COVID-19 data datacov <- read_csv("code/day_5/time_series_covid19_deaths_global.csv") ## get the world map world <- map_data("world") # cutoffs based on the number of cases mybreaks <- c(1, 20, 100, 1000, 50000) ggplot() + geom_polygon(data = world, aes(x=long, y = lat, group = group), fill="grey", alpha=0.3) + geom_point(data=datacov, aes(x=Long, y=Lat, size=`3/3/20`, color=`3/3/20`),stroke=F, alpha=0.7) + scale_size_continuous(name="Cases", trans="log", range=c(1,7),breaks=mybreaks, labels = c("1-19", "20-99", "100-999", "1,000-49,999", "50,000+")) + # scale_alpha_continuous(name="Cases", trans="log", range=c(0.1, 0.9),breaks=mybreaks) + scale_color_viridis_c(option="inferno",name="Cases", trans="log",breaks=mybreaks, labels = c("1-19", "20-99", "100-999", "1,000-49,999", "50,000+")) + theme_void() + guides( colour = guide_legend()) + labs(caption = "Data Repository provided by Johns Hopkins CSSE. Visualization by DataScience+ ") + theme( legend.position = "bottom", text = element_text(color = "#22211d"), plot.background = element_rect(fill = "#ffffff", color = NA), panel.background = element_rect(fill = "#ffffff", color = NA), legend.background = element_rect(fill = "#ffffff", color = NA) ) <file_sep># Data Types # #Data can be of different types. Commonly # #vector #matrix #data.frame library(xlsx) a <- 20 class(a) ?read.table ?read.csv golf <- read.csv('DEV_SAMPLE.csv') View(golf) ?head head(golf) class(golf) ?class new.matrix <- as.matrix(golf) class(new.matrix) new.matrix new.vector <- as.vector(golf$Balance) class(new.vector) ?str() str(golf) #Numeric: refers to any number or numeric value #Ex: 1.2, 4.5, 26 it even includes decimals a1 <- 25 class(a1) #Integer: refers to any number without a fractional part #Ex: 1, 2, 3, etc. a2 <- as.integer(a1) class(a2) #Character: refers to textual data #Ex: learning, education a3 <- "Batman" a4 <- '<NAME>' class(a4) #Logical: refers to any values which is either TRUE or FALSE #Ex: If x=10, y=20 then x>y is FALSE x <- TRUE class(x) #Factor: refers to data in categories #Ex: city, gender #List: ordered collection, can be created with function list() o.list <- list(fname="Bruce", lname="Wayen", age="50") ?list class(o.list) o.list <file_sep>setwd("E:/Machine learning with R-Akhilendra/Section 11") # source-https://archive.ics.uci.edu/ml/machine-learning-databases/heart-disease/ heart.dis <- read.delim("processed.cleveland.data.txt", sep = ",") View(heart.dis) colnames(heart.dis) <- c( "age", "sex", "cp", "rbp", "chol", "fbs", "recg", "max hr", "angina", "oldpeak", "slope", "# of major vessels", "thal", "output" ) View(heart.dis) str(heart.dis) <file_sep># logistic regression is part of glm (generalized linear model) # data source- https://archive.ics.uci.edu/ml/machine-learning-databases/adult/ ?read.delim income.orig <- read.delim("adult-data.txt", header = FALSE, sep = ",") View(income.orig) # impute na instead of ? # can't impute NA directly if it is present in factors income.orig <- read.delim("adult-data.txt", header = FALSE, sep = ",", na.strings=c(""," "," ?","NA")) # name the columns colnames(income.orig) <- c( "age", "workclass", "final.weight", "education", "education.num", "marital-status", "occupation", "relationship", "race", "sex", "capital.gain", "capital.loss", "hours.per.week", "country", "final.class" ) View(income.orig) #structure of data str(income.orig) # print total number of NAs in the data sum(is.na(income.orig)) # print the columns with NAs in the data colnames(income.orig)[colSums(is.na(income.orig)) > 0] summary(income.orig) #install.packages("mice") library(mice) # displays a table with NA md.pattern(income.orig) #verify number of NAs sum(is.na(income.orig$workclass)) sum(is.na(income.orig$country)) sum(is.na(income.orig$occupation)) summary(income.orig) #library-Hmisc, mice are good choice for handling NAs # create library(forcats) workclass.new<- fct_explicit_na(income.orig$workclass, na_level = " None") income.orig$workclass.new <- workclass.new country.new<- fct_explicit_na(income.orig$country, na_level = " None") income.orig$country.new <- country.new occupation.new<- fct_explicit_na(income.orig$occupation, na_level = " None") income.orig$occupation.new <- occupation.new # dependent variable = final class library(ggplot2) # final weight for all occupation types ggplot(data = income.orig,aes(y=income.orig$final.weight, x=income.orig$occupation.new)) +geom_boxplot(aes(col=occupation.new))+labs(title="Boxplot of Weights for all occupation types") #final weight for all education types ggplot(data = income.orig,aes(y=income.orig$final.weight, x=income.orig$education)) +geom_boxplot(aes(col=education))+labs(title="Boxplot of Weights for all education types") #Histogram for relationship g <- ggplot(income.orig, aes(income.orig$relationship)) g + geom_bar() g + geom_bar(aes(weight = income.orig$relationship)) g + geom_bar() #Histogram to represent gender distribution g <- ggplot(income.orig, aes(income.orig$sex)) g + geom_bar() g + geom_bar(aes(weight = income.orig$sex)) g + geom_bar(aes(fill = '#A4A4A4',, color="darkred")) # list=false to ensure that resultant is not in the form of a list # replacing less than and more than 50000 with 0 and 1 # always select random values/rows for training and test datasets library(plyr) library(dplyr) str(income.orig) income.orig$final.class <- revalue(income.orig$final.class, c(" >50K"="1")) income.orig$final.class <- revalue(income.orig$final.class, c(" <=50K"="0")) ?mutate View(income.orig) # create data partition- create a vector library(caret) set.seed(101) # income_sampling <- createDataPartition(income.orig$final.class, p = 0.80, list = FALSE) # class(income_sampling) # class(income.orig) # # View(income_sampling) # # income.train <- income.orig[income_sampling,] # View(income.train) # # class(income.train) # # income.trainlabels <- income.orig$final.class[income_sampling] # # then same for test dataset # # one more way of random selection for training & test income.orig$random <- runif (nrow(income.orig), 0, 1) View(income.orig) # training & test datasets set.seed(100) trainingData <- income.orig [which(income.orig$random <= 0.8),] testData <- income.orig [which(income.orig$random > 0.8),] c (nrow(trainingData), nrow(testData)) View(trainingData) # when you use only 1 variable like age, you will be doing univariate logistic analysis # we are using multiple variables to mimic real world scenario, therefore it is multivariate logistic analysis # run logistic regression using glm function # glm with family binomial is used to run binomial logistic regression # binomial logistic regression is used when the outcome can have only 2 values like yes or no, true or false # multinomial logistic regression is used when outcome can be more than 2 different classes like type a, type b, type c etc. # lower aic indicates better model # AIC = akaike information criterion ?glm income.model <- glm(final.class~ sex+age+workclass+final.weight+education+occupation+country, data=trainingData, family=binomial("logit")) str(trainingData) trainingData$final.weight <- as.numeric(trainingData$final.weight) trainingData$age <- as.numeric(trainingData$age) trainingData$workclass <- as.factor(trainingData$workclass) trainingData$education <- as.factor(trainingData$education) trainingData$final.class <- as.numeric(trainingData$final.class) # higher z value is good # deviance residual should be closer to 0 # postive and higher estimate value indicate higher significance # Number of Fisher Scoring iterations indicates how quickly our model converged summary(income.model) # calculate p value by multiplying corresponding z value # set lower.tail to F if z value is positive pnorm(-5.735 , lower.tail = T) * 2 # final weight, country doesn't look very significant income.model2 <- glm(final.class~ sex+age+workclass+education+occupation, data=trainingData, family=binomial("logit")) # higher z value is good summary(income.model2) plot(income.model2) ?predict # predict <- predict(income.model2, type = 'response') # # trainingData$prediction <- predict income.woNA <- na.omit(trainingData) prediction <- predict(income.model, type = 'response') income.woNA$prediction <- prediction View(income.woNA) # we can update prediction column to use 0 & 1 if the probability is less than 0.5 or greater than 0.5 respectively # but we will create a new column for this purpose instead of updating prediction column income.woNA$prediction.updated <- ifelse(prediction>0.5,1, 0) # confusion matrix with(income.woNA, table(final.class, prediction.updated)) # total obs 16923+1277+3497+2525 #incorrect obs 1277+3494 #classification error in percentage 4771/24222 * 100 income.test <- na.omit(testData) test.prediction <- predict(income.model, income.test, type='response') income.test$predicted <- test.prediction income.test$prediction.updated <- ifelse(test.prediction>0.5,1, 0) View(income.test) with(income.test, table(final.class, prediction.updated)) a <- 4158+296+847+639 b <- 296+847 b/a * 100 # roc curve-Receiver operating characteristic # it is used for evaluating performance # tpr vs fpr # tpr = senstivity & recall # library(ROCR) ROCRpred <- prediction(test.prediction, income.test$final.class) ROCRperf <- performance(ROCRpred, 'tpr','fpr') plot(ROCRperf) <file_sep>library(dplyr) library(ggplot2) library(readxl) library(psych) library(car) library(foreign) library(nlme) library(onewaytests) library(tabplot) library(MASS) library(rcompanion) library(WRS2) library(devtools) plxsell <- read.csv("PL_X_SELL.csv") class(plxsell) View(plxsell) str(plxsell) summary(plxsell) #using tableplot from tabplot to visualize entire dataset tableplot(plxsell) #visualization with boxplot ggplot(data = plxsell,aes(y=plxsell$Balance, x=plxsell$Occupation)) +geom_boxplot(aes(col=Occupation))+labs(title="Boxplot of Balance for all occupation types") # Normality Test #select subset with 5000 rows fivethd <- plxsell[1:5000,] #fivethd$Occupation<-factor(fivethd$Occupation,labels = c("PROF","SAL","SELF-EMP","SENP")) ?cat cat("Normality p-values by Factor place: ") for(i in unique(factor(fivethd$Occupation))){ cat(shapiro.test(fivethd[fivethd$Occupation==i, ]$Balance)$p.value," ") } #test for normality- normality assumption is not violated # null hypothesis, balance is not influenced by occupation #alternative hypothesis, balance is influenced by occupation # p value is less than 0.05, therefore we reject null hypothesis # Test of homogenity # Levene's & bartlett tests are used to test if samples have equal variances. #Equal variances across samples is called homogeneity of variance leveneTest(plxsell$Balance ~ plxsell$Occupation, data = plxsell) bartlett.test(plxsell$Balance ~ plxsell$Occupation) # ANOVA Model anova_Model <- aov(plxsell$Balance ~ plxsell$Occupation, data = plxsell) summary(anova_Model) # Tukey Test is a post-hoc test based #ANOVA test can tell us if the output is significant, it won't tell us where is the difference #we use Tukey's HSD to find out which specific groups's means are different. tukey_HSD <- TukeyHSD(anova_Model) tukey_HSD plot(tukey_HSD) # Two way anova #plxsell$Occupation<-factor(plxsell$Occupation,labels = c("PROF","SAL","SELF-EMP","SENP")) #plxsell$Gender<-factor(plxsell$Gender,labels = c("Male","Female","Org")) ?tapply tapply(plxsell$Balance,list(plxsell$Occupation,plxsell$Gender), mean) tapply(plxsell$Balance,list(plxsell$Occupation,plxsell$Gender), sd) #interaction plot displays the levels of one variable on the X axis and #has a separate line for the means of each level of the other variable. #The Y axis is the dependent variable. # itshows that the effect of variable is different for different variables # interaction plot interaction.plot(plxsell$Gender,plxsell$Occupation,plxsell$Balance) #barlett test leveneTest(plxsell$Balance ~ plxsell$Occupation*plxsell$Gender) anova2<-aov(Balance~Occupation+Gender+Occupation:Gender,data = plxsell) summary(anova2) tukey_HSD2 <- TukeyHSD(anova2) tukey_HSD plot(tukey_HSD2) <file_sep># first difference between bar plots & histograms is that there is gap between bars in barplots #whereras there is no gap in histogram # both use bars but bar plot or graph is used for comparision of variables #whereas histograms are used for displaying frequencies # if i need to compare male and female variables, #i will use bar plots and #if i neeed to display the numerical distribution of a quantity, #i will use histogram likes sales on monthly basis #setwd("/Users/me.wolf/programming/r/r_workshop") Titanicdata <- read.csv("train_titanic.csv", header = TRUE) summary(Titanicdata) str(Titanicdata) library(Amelia) missmap(Titanicdata, main="Missing values") fb <- read.csv("dataset_Facebook.csv", header = TRUE, sep = ";") missmap(fb, main="Missing Values") fbdata <- read.csv("dataset_Facebook.csv", header = TRUE, sep = ";") #Bar charts are the most common data visualization for categorical data but also used for numerical variables ?barplot fbdata$Type <- as.factor(fb$Type) barplot(fbdata) str(fbdata) barplot(fbdata$like, main = "Bar plot for likes", col = "red") barplot(Titanicdata$Age) hist(fbdata$like) hist(as.numeric(Titanicdata$like)) str(Titanicdata) hist(Titanicdata$Age) View(Titanicdata) barplot(fbdata$like, main = "Bar plot for likes", horiz=TRUE, col = "red") barplot(fbdata$Post.Month, main = "Bar plot for likes", horiz=TRUE, col = "red") ?barplot #heat.colors(12 View(fbdata) # hist(), barplot(), plot() plot(Titanicdata$Age) plot(fbdata$Lifetime.Post.Consumptions, type = "s") plot(fbdata$Lifetime.Post.Consumptions,xlim = c(0,1000), ylim = c(0, 5000)) plot(fbdata$Page.total.likes) ?plot plot(density(fbdata$Page.total.likes)) #The plot()function is a generic function. If we put two numeric variables inside this function, #it produces a scatter. On the other hand, if we use one numeric variable and another factor variable, #then it produces a boxplot of the numeric variable for each unique value of the factor variable. #type is a factor plot(Lifetime.Post.Consumptions ~ Type, data = fbdata) plot(Lifetime.Post.Total.Reach ~ Lifetime.Post.Total.Impressions , data = fbdata, main="Relationship between car Reach & Impressions", col= "red") str(fbdata) ?plot data("mtcars") #inbuilt datasets heatmap(as.matrix(mtcars), Rowv = NA, Colv = NA, col= heat.colors(4, alpha=1)) # dark line represent the median # the bottom and top edges represent the first & third quartiles # length of the box is equal to the interquartile range (IQR, which is the difference between first and third quartiles boxplot(fbdata$Page.total.likes) str(fbdata) #pair #pairs() command makes a matrix of scatter plots, where all the variables in the specified dataset are plotted against each other. #The variable names, displayed in the diagonal running across from the top-left corner to the bottom-right corner, #are the key to reading the graph. For example, the scatter plot in the first row and second column shows the relationship #between variable on the y axis and on the x axis. head(mtcars) pairs(mtcars) pairs(mtcars[,2:6]) # create multiple graphs # c(2,3) mean 2 rows and 3 columns # this is particularly useful if you want to show some kind of comparsion like price movement of different stocks in a time # or summary of a dataset with multiple graphs par(mfrow=c(2,3)) #4,8 # install rcolorbrewer library(RColorBrewer) display.brewer.all() infy <- read.csv("infy.csv", header = TRUE) head(infy) str(infy) tcs <- read.csv("tcs.csv", header = TRUE) head(tcs) wipro <- read.csv("wipro.csv", header = TRUE) plot(Average.Price~Open.Price,data=infy,type="l",main="Percentage change in GDP",ylab="") mtext(side=4,at=infy$Open.Price[infy$Open.Price],text="Open Price") lines(infy$Average.Price~infy$High.Price,col=pal[2],lwd=2) mtext(side=4,at=infy$High.Price[length(infy$High.Price)],text="High price", col=pal[2],line=0.3,las=2) lines(infy$Average.Price~infy$Low.Price,col=pal[3],lwd=2) mtext(side=4,at=infy$Low.Price[length(infy$Low.Price)],text="Low price", col=pal[3],line=0.3,las=2) # map- not very common usage but good to know library(maps) map() ?map map("france") map("usa", fill=TRUE, col=heat.colors(256)) #library(rgdal) #library(RgoogleMaps) library(ggplot2) # ggplot2 comes with commands- qplot & ggplot #geom_point(): This will create a scatter plot #geom_line(): This will create a line chart #geom_bar(): This will create a bar chart #geom_boxplot(): This will create a box plot #geom_text(): This will write certain text inside the plot area ?qplot data("iris") qplot(Sepal.Length, Sepal.Width, data=iris, colour = Species) library(xlsx) lung = read.xlsx("LungCap_Dataset.xls", sheetIndex = 1, header = TRUE) lung$Gender <- as.factor(lung$Gender) qplot(lung$Age..years.,lung$Height.inches.,data = lung,shape=as.factor(Gender)) str(lung) ggplot(data = lung, aes(x=Age..years., y=Height.inches.)) + geom_bar(stat = "identity",position = "dodge",colour= "blue", fill = "gray") sctplot<-ggplot(data = lung, aes(x=Age..years., y=Height.inches.)) + geom_point() sctplot<- sctplot + geom_smooth(method ="lm", col="red") sctplot + geom_smooth(col="green") str(lung) ?ggplot ggplot(data= lung, aes(x=Smoke, y=LungCap.cc., fill=Age..years.)) + geom_bar(stat="identity",position="dodge") ggplot(data= lung, aes(x=Smoke, y=LungCap.cc.)) + geom_bar(stat="identity",position="dodge") ggplot(data= lung, aes(x=Smoke, y=LungCap.cc., fill=Age..years.)) + geom_bar(stat="identity",position="dodge")+coord_flip() ggplot(data=lung,aes(x=Age..years.))+geom_density() ggplot(data=lung,aes(y=LungCap.cc.,x=Gender))+geom_boxplot() CTDF.dev <- read.csv("DEV_SAMPLE.csv", header = TRUE) head(CTDF.dev) str(CTDF.dev) ggplot(data = CTDF.dev,aes(y=CTDF.dev$Balance, x=CTDF.dev$Occupation)) +geom_boxplot(aes(col=Occupation))+labs(title="Boxplot of Balance for all occupation types") data("iris") head(iris) library(lattice) xyplot(Sepal.Length~Sepal.Width, data=iris, groups=Species) # first 3 variables are numeric and Species is factor, it is grouping based on Species barchart(Sepal.Length+Sepal.Width+Petal.Length~Species,data=iris) barchart(Sepal.Length+Sepal.Width+Petal.Length~Species,data=iris, auto.key=list(column=3)) barchart(Sepal.Length+Sepal.Width+Petal.Length~Species,data=iris, stack=TRUE) Titanicdata <- read.csv("train_titanic.csv", header = TRUE) View(Titanicdata) str(Titanicdata) barchart(Age~Survived|Sex,data=Titanicdata) ?barchart histogram(~Age|Sex,data=Titanicdata) histogram(~Age|Sex+Survived,data=Titanicdata) densityplot(~Age|Sex,data=Titanicdata) bwplot(~Age|Sex+Survived,data=Titanicdata) bwplot(~Age,data=Titanicdata) library(scatterplot3d) scatterplot3d(x=iris$Sepal.Length,y=iris$Sepal.Width,z=iris$Species) ?scatterplot3d scatterplot3d(x=iris$Sepal.Length,y=iris$Sepal.Width,z=iris$Species, pch = 16) scatterplot3d(x=iris$Sepal.Length,y=iris$Sepal.Width,z=iris$Species, pch = 16, highlight.3d=TRUE,col.axis="blue", col.grid="lightblue") <file_sep># What is an operator? # # it is a symbol that is used to assign values or run commands. Operators are used in all programming languages like = sign or <> signs # # Types of Operators # # # Arithmetic # Relational # Logical # Assignment # Miscellaneous # # # # Arithmetic Operators # # + 2 + 2 # - 3-2 # * 2 * 2 # / 10 /2 # # %% - Give the remainder of the first vector with the second %% 11%%2 # # %/% - The result of division of first vector with second 11%/%2 # # ^ first vector raised to the exponent of second vector 2 ^ 3 # # Relational Operators # # # > greater than . 4 > 5 # < less than 4 < 5 # == is equal to , please only = will be used as assignment operator 4==5 4==4 # <= less than or equal to 4 <= 5 # >= greater than or equal to 4 >= 5 # != NOT equal to 4 != 5 # # d <- 4 e <- 5 # not a very useful if else block, but just for demonstration purpose on how # ! - NOT operator, it can be used with equal sign for "NOT Equal" purpose. d != e d != 5 #Assignment Operators # These operators are used to assign values to vectorsdataframes/matrix/variables/objects. # <- f <- 123 # <<- f <<- 123 # = f = 123 # # -> ef -> 123 # # # Others # # : Colon operator, used to create the series of numbers in sequence for a vector. nb <- rnorm(1:50) nb # Few others # | - Vertical bar or pipe operator, #it is an Element wise Logical OR operator. #it gives an output TRUE if one of the elements is TRUE or one of the condition passes. # & operator for element wise operation similar to OR # The logical operator && and || considers only the first element of the vectors and give a vector of single element as output. # # && Logical AND operator. #Takes first element of both the vectors and gives the TRUE only if both are TRUE. # || Logical OR operator. #Takes first element of both the vectors and gives the TRUE if one of them is TRUE. <file_sep> # source-https://archive.ics.uci.edu/ml/machine-learning-databases/heart-disease/ heart.dis <- read.delim("processed.cleveland.data.txt", sep = ",") View(heart.dis) colnames(heart.dis) <- c( "age", "sex", "cp", "rbp", "chol", "fbs", "recg", "max.hr", "angina", "oldpeak", "slope", "major.vessels", "thal", "output" ) View(heart.dis) str(heart.dis) summary(heart.dis) sum(is.na(heart.dis)) set.seed(100) heart.dis$random <- runif (nrow(heart.dis), 0, 1) trainingData <- heart.dis [which(heart.dis$random <= 0.8),] testData <- heart.dis [which(heart.dis$random > 0.8),] c (nrow(trainingData), nrow(testData)) library(randomForest) #ntree = number of forest #mtry = number of variables to be used for each forest/node # nodesize = similar to minbucket(terminal node) # importance= which variable is more important than others random.heart <- randomForest(as.factor(output) ~ ., data = trainingData, ntree=50, mtry = 3, nodesize = 10, importance=TRUE) # OOB = out of bag # we have 50 trees which mean that there are 50 models. All obs won't be there in each model # missing values are called out of bag # out of bag values are used as testing set by model # model will use these OOBs to predict class of these obs. # OOB is the mean prediction error on each training sample using out of bag value print(random.heart) # plot to tell us optimum number of trees plot(random.heart, main="") legend("topright", c("OOB", "1", "2","3", "4"), text.col=1:6, lty=1:3, col=1:3) title(main="Error Rates Random Forest") # same information in table format random.heart$err.rate ## List the importance of the variables. importantvariables <- round(randomForest::importance(random.heart), 2) importantvariables[order(importantvariables[,3], decreasing=TRUE),] # variable with highest meandecreasegini is the best variable-max.hr ?tuneRF ## Tuning Random Forest-used for finding optimum value of mtry ?tuneRF tune.forest <- tuneRF(x = trainingData, y=as.factor(trainingData$output), mtryStart = 3, ntreeTry=50, trace=TRUE, plot = TRUE, doBest = TRUE, improve = TRUE, nodesize = 10, importance=TRUE) tune.forest$importance #predict trainingData$predict.class <- predict(tune.forest, trainingData, type="class") trainingData$predict.score <- predict(tune.forest, trainingData, type="prob") View(trainingData) sum(trainingData$output) / nrow(trainingData) # KS,AUC, gini cannot be calculated in this case because output variable is not binary ## Classification Error with(trainingData, table(output, predict.class)) library(class) ?knn # add predict class for test data set model1<- knn(train=trainingData, test=trainingData, cl=trainingData[,14], k=16) model1 <file_sep>#1. Reading CSV files with R read.csv() ?read.csv fb <- read.csv("dataset_Facebook.csv", header = TRUE, sep = ";") View(fb) #read.csv(file, header = TRUE, sep = ",", quote = "\"", # dec = ".", fill = TRUE, comment.char = "", ...) #read.csv2 is used in countries that use a comma as decimal point and a semicolon as field separator. read.csv2() #additional function- for reading csv and other formats like copy paste #data.table package #separator is automatically recognized fread() #2. Reading xls files with R library(xlsx) ?read.xlsx() lc <- read.xlsx("LungCap_Dataset.xls", sheetIndex = 1) View(lc) str(lc) #3. Reading txt files with R ?read.delim() read.delim() #read.table is similar to .csv and can be used to read csv files read.table() #4. read xml library(XML) ?xmlParse() # read json library(rjson) ?fromJSON #foreign package to read octave, SAS, SPSS and other formats library(foreign) <file_sep># function_name <- function(arguments1, arguments2, so on) { # Function body # } # # Function Name − Name of the function,whenever you want to ues a function, you call it by using the name # # Arguments − placeholder variables which are used in function # # Function Body − function body contains the code for all the statements or actions # # Return Value − it is the last statement in function body # Create a function to print squares of numbers in sequence. new.function <- function(a) { for(i in 1:a) { b <- i^2 print(b) } } # Call the function new.function supplying 6 as an argument. new.function(6) decile <- function(x){ deciles <- vector(length=10) for (i in seq(0.1,1,.1)){ deciles[i*10] <- quantile(x, i, na.rm=T) } return ( ifelse(x<deciles[1], 1, ifelse(x<deciles[2], 2, ifelse(x<deciles[3], 3, ifelse(x<deciles[4], 4, ifelse(x<deciles[5], 5, ifelse(x<deciles[6], 6, ifelse(x<deciles[7], 7, ifelse(x<deciles[8], 8, ifelse(x<deciles[9], 9, 10 )))))))))) } <file_sep># you can use <- or = to create variables or objects in R # int a1 <- 100 a12 = 101 # floating number a2 <- 100.5 class(a2) new.a2 <- as.integer(a2) class(new.a2) # string or character a3 <- "hello" # if you use quotes, it becomes string even if you include number in it a4 <- "100" # To print, either write the variable or use print command a1 print("Hi Hello") a2 # when using print with variable, you don't need to use quotes print(a3) print(a4) # when using print with numbers, you don't need to use quotes print(4) # when using print with string, you need to use quotes print("this is a string") # all the variables are saved as objects & displayed in right hand top section # use ? before any function to get more information on that. # you won't be creating these simple variables though # you will be creating different data types in R for machine learning. There are 4 types of atomic vector # These data types are; #Vectors #Matrices #Data Frames #Lists #Arrays #Factors # let's start with vector # use C() function to create vectors # C() stand for concatenate # create vectors ?c v1 <- c(1,2,3) v2 <- c(4,5,6) # you can directly perform calculations in R on these vectors c1 <- v1 * v2 c1 c2 <- v1 + v2 c2 # logical vector b = c(TRUE, FALSE, TRUE ) #list x = list( v1, c1, v2, 100) x class(x) #Let's create a list containing a vector, a matrix, and a list. new.list <- list(c("Sachin","Saurav","Rahul"), matrix(c(28000,25000,220000,100,500,800), nrow = 2), list("x",12.3)) print(new.list) #manipulation #Give names to the elements in the list. names(new.list) <- c("Names", "Numbers", "Random") ?name print(new.list) #Access the first element of the list. print(new.list[1]) print(new.list[3]) #Add an element at the end of the list. new.list[4] <- "New Player" print(new.list[4]) #Remove the element. new.list[3] <- NULL # Print the 4th Element. print(new.list[3]) #Update the 3rd Element. new.list[3] <- "updated element" print(new.list[3]) #How to Merge Lists in R Programming language? #Merge the two lists. two.list <- c(x,new.list) print(two.list) # R Predefined Lists # Lists for letters and month names are predefined: # letters # # A matrix is a two-dimensional vector (fixed size, all cell types the same). # # array is a vector with one or more dimensions. #An array with two dimensions is same as a matrix. #An array with three or more dimensions is an n-dimensional array. # # A data frame is called a table in most languages. Each column holds the same type, and the columns can have header names. # # Arrays # Create two vectors of different lengths. v1.new <- c(2,9,3) v2.new <- c(10,11,12,13) # create a array with these vectors new.arr <- array(c(v1.new,v2.new), dim = c(3,3,4)) print(new.arr) #naming columns income.orig <- read.delim("adult-data.txt", header = FALSE, sep = ",", na.strings=c(""," "," ?","NA")) ?colnames # name the columns colnames(income.orig) <- c( "age", "workclass", "final.weight", "education", "education.num", "marital-status", "occupation", "relationship", "race", "sex", "capital.gain", "capital.loss", "hours.per.week", "country", "final.class" ) View(income.orig) new.vector <- income.orig[120:3000,5] View(new.vector) income.orig$education.num <- NULL View(income.orig) income.orig$edu.new <- 125 str(income.orig) income.orig$edu.new <- as.integer(income.orig$edu.new) <file_sep>for (v in c(1:5)) { print(v) } for (v in c(1:5)) { if(v <= 3) print(v) else( print("i m done") ) } a <- c(1:5) for (v in a) { if(v <= 2) print(v) else( print("i m done") ) } b <- c(1:10) for (v in b) { if(v <= 5) print(v) else( print("i m done") ) } setwd("") # set working directory library(corpcor) library(GPArotation) library(psych) library(ggplot2) library(ggfortify) library(nFactors) library(dplyr) library(expm) library(Hmisc) iplbatting <- read.csv("batting_bowling_ipl_bat.csv", header = TRUE) View(iplbatting) for (v in iplbatting$Runs) { print(v) } r <- iplbatting[6,] r r <- 500 while (r!=495){ print("this is my") } rt <- 1 while (rt < 6){ print(rt) rt = rt+1 }
af47150c6b43edd6ad61a69813fa8828f2b0d084
[ "R" ]
22
R
mahoretushar/r_workshop
d24364b0f217af949479d2361a28bc4e808f9777
016ffaa038e2a5ab68f0fd9ed2a84d0857bfc6a6
refs/heads/main
<repo_name>Akramjon1995/Stocks<file_sep>/src/components/Header.js import React from 'react'; import { Navbar } from 'react-bootstrap'; const Header = () => { return ( <Navbar className="mb-5" expand="lg" variant="secondary" bg="secondary"> <div className="px-4"> <Navbar.Brand className="text-white" href="#">Navbar</Navbar.Brand> </div> </Navbar> ); }; export default Header;<file_sep>/src/components/SearchInput.jsx import React from 'react'; const SearchInput = ({onSearch}) => { const handleInputChange = (e) => { onSearch(e.target.value) } return ( <div className="text-center px-4"> <input type="text" className="form-control mb-5 w-75" placeholder="Enter Symbol" onChange={handleInputChange} /> </div> ); }; export default SearchInput;<file_sep>/src/components/StockList.jsx import React from 'react'; import SingleStock from './SingleStock'; const StockList = ({ stocks }) => { const allStocks = stocks.map((stock) => { return ( <SingleStock key={stock.id} stock={stock} /> ) }) return ( <div className="px-4 d-flex flex-wrap"> {allStocks} </div> ); }; export default StockList;<file_sep>/src/App.js import 'bootstrap/dist/css/bootstrap.css' import { useState } from 'react'; import {BrowserRouter as Router} from 'react-router-dom' import Header from './components/Header'; import SearchInput from './components/SearchInput'; import StockList from './components/StockList' import {Stocks} from './Resources' function App() { const [data] = useState(Stocks) const [filteredData, setFilteredData] = useState(Stocks) const Search = (text) => { const filteredStokcs = data.filter((stock) => { return stock.ticker.toLowerCase().includes(text.toLowerCase()) }) setFilteredData(filteredStokcs) } return ( <Router className="container-fluid"> <Header /> <SearchInput onSearch = {Search} /> <StockList stocks={filteredData} /> </Router> ); } export default App; <file_sep>/src/components/SingleStock.js import React from 'react'; import { Card } from 'react-bootstrap'; import './style.css' const SingleStoke = ({stock}) => { return ( <Card className="card me-4" style={{ width: '18rem', marginBottom: '16px' }}> <Card.Body> <Card.Title>{stock.company}</Card.Title> <Card.Subtitle className="mb-2 text-muted">{stock.ticker}</Card.Subtitle> <Card.Text> Last price: {stock.data.currentSharePrice} </Card.Text> <Card.Text> Volume: {stock.data.tradingVolume} </Card.Text> <Card.Text> Highest: {stock.data.highest} </Card.Text> <Card.Text> Lowest: {stock.data.lowest} </Card.Text> </Card.Body> </Card> ); }; export default SingleStoke;<file_sep>/src/Resources.jsx export const Stocks = [ { id: 1, company: "Microsoft", ticker: "MSFT", data: { currentSharePrice: 567, tradingVolume: 345, highest: 2244, lowest: 233 } }, { id: 2, company: "Apple", ticker: "GOOG", data: { currentSharePrice: 500, tradingVolume: 395, highest: 2304, lowest: 450 } }, { id: 3, company: "Spotify", ticker: "DEFG", data: { currentSharePrice: 700, tradingVolume: 510, highest: 1500, lowest: 330 } }, { id: 4, company: "Amazon", ticker: "JKLMN", data: { currentSharePrice: 800, tradingVolume: 480, highest: 1200, lowest: 310 } }, { id: 5, company: "Facebook", ticker: "QWERT", data: { currentSharePrice: 1950, tradingVolume: 1440, highest: 3500, lowest: 1200 } } ]
a2671012e453b33331d507fae9c06d4655fea1bd
[ "JavaScript" ]
6
JavaScript
Akramjon1995/Stocks
71ff8117108b789e58094217a3f3d15aa0de0465
c291798645a941e54183d20cd1005a3e4269da36
refs/heads/master
<file_sep>import pygame from random import randint pygame.init() screen_size = 800 block_size = 40 update_snake = 0 blocks_amount = int(screen_size / block_size) screen = pygame.display.set_mode((screen_size, screen_size)) pygame.display.set_caption("SnakeGame") def rand_pos(): return [randint(0, blocks_amount - 1), randint(0, blocks_amount - 1)] class Manager: def __init__(self): self.is_running = True self.current_food = Food() self.current_snake = Snake() self.score = 0 self.my_font = pygame.font.SysFont('Comic Sans MS', 30) self.text_surface = self.my_font.render(f'Score: {self.score}', True, (255, 0, 0)) def check_collision(self): if self.current_food.pos in self.current_snake.pos: self.current_snake.need_grow = True self.current_food.pos = rand_pos() self.score += 1 self.text_surface = self.my_font.render(f'Score: {self.score}', True, (255, 0, 0)) while self.current_food.pos in self.current_snake.pos: self.current_food.pos = rand_pos() if self.current_snake.is_bumped(): self.my_font = pygame.font.SysFont('Comic Sans MS', 60) self.text_surface = self.my_font.render(f'WASTED! score: {self.score}', True, (255, 0, 0)) self.is_running = False class Background: def __init__(self): self.green1 = (146, 239, 162) self.green2 = (128, 208, 119) def draw(self): for rows in range(blocks_amount): for columns in range(blocks_amount): if (columns + rows) % 2 == 0: color = self.green1 else: color = self.green2 pygame.draw.rect(screen, color, [columns * block_size, rows * block_size, block_size, block_size]) class Food: def __init__(self): self.pos = [int(blocks_amount / 2) - 1, int(blocks_amount / 2) - 1] self.RED = (195, 40, 40) def draw(self): pygame.draw.rect(screen, self.RED, [self.pos[0] * block_size, self.pos[1] * block_size, block_size, block_size]) class Snake: def __init__(self): self.color = (30, 100, 20) self.pos = [[int(blocks_amount / 2), int(blocks_amount / 2)], [int(blocks_amount / 2), int(blocks_amount / 2) + 1], [int(blocks_amount / 2), int(blocks_amount / 2) + 2], [int(blocks_amount / 2), int(blocks_amount / 2) + 3]] self.direct = [0, -1] self.size = 4 self.need_grow = False def draw(self): for current in self.pos: pygame.draw.rect(screen, self.color, [current[0] * block_size, current[1] * block_size, block_size, block_size]) def move(self): new_pos = list() new_pos.append([self.pos[0][0] + self.direct[0], self.pos[0][1] + self.direct[1]]) if not self.need_grow: for current in self.pos[:-1]: new_pos.append(current) else: self.need_grow = False for current in self.pos: new_pos.append(current) for current in new_pos: if current[0] == blocks_amount: current[0] = 0 if current[1] == blocks_amount: current[1] = 0 if current[0] == -1: current[0] = blocks_amount - 1 if current[1] == -1: current[1] = blocks_amount - 1 self.pos = new_pos def is_bumped(self): for current in self.pos: flag = 0 for i in self.pos: if i == current: flag += 1 if flag > 1: return True return False def check_win(mng: Manager): if mng.score == blocks_amount * blocks_amount - 4: mng.is_running = False manager.text_surface = manager.my_font.render(f'WINNER! score: {manager.score}', True, (255, 0, 0)) manager = Manager() bg = Background() # main loop while True: bg.draw() screen.blit(manager.text_surface, (0, 0)) check_win(manager) if manager.is_running: manager.current_food.draw() manager.current_snake.draw() if update_snake > 99: update_snake = 0 manager.current_snake.move() else: manager.current_snake.draw() manager.check_collision() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_w and manager.current_snake.direct != [0, 1]: manager.current_snake.direct = [0, -1] elif event.key == pygame.K_a and manager.current_snake.direct != [1, 0]: manager.current_snake.direct = [-1, 0] elif event.key == pygame.K_s and manager.current_snake.direct != [0, -1]: manager.current_snake.direct = [0, 1] elif event.key == pygame.K_d and manager.current_snake.direct != [-1, 0]: manager.current_snake.direct = [1, 0] pygame.display.update() update_snake += 0.6<file_sep>import pygame from random import randint window_size = (1400, 800) pygame.init() screen = pygame.display.set_mode(window_size) pygame.display.set_caption("CircleDrop") ball_list = list() class Ball: def __init__(self, pos): self.pos_x = pos[0] self.pos_y = pos[1] self.radius = randint(10, 100) self.color = (randint(0, 255), randint(0, 255), randint(0, 255)) self.speed = 0 self.acceleration = 0.00005 * self.radius def draw_ball(self): pygame.draw.circle(screen, self.color, (self.pos_x, self.pos_y), self.radius) def fall_ball(self): if self.pos_y < window_size[1] - self.radius: self.pos_y += self.speed self.speed += self.acceleration else: if self.speed < 0.1 and self.radius > 0: self.radius -= 1 self.pos_y = window_size[1] - self.radius self.speed *= -1 self.speed /= 1.3 self.pos_y += self.speed self.speed += self.acceleration def draw_balls(): for element in ball_list: if element.radius == 0: ball_list.remove(element) else: element.draw_ball() def fall_balls(): for element in ball_list: element.fall_ball() while True: screen.fill((0, 0, 0)) for event in pygame.event.get(): if event.type == pygame.QUIT: quit() if event.type == pygame.MOUSEBUTTONDOWN: ball = Ball(pygame.mouse.get_pos()) ball_list.append(ball) draw_balls() fall_balls() pygame.display.update()
73ff8af88c4b7fafeca778b7910682061e2c7467
[ "Python" ]
2
Python
MrSemyon12/MyGames
15a0a2ac2ae1e7d3de5e77c1ff46bb4fe4a94fe5
fd05c9dc54f70736a39351923ad9e2210653f96f
refs/heads/master
<file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- # discription: common # author: dreampuf import cgi, os, logging, sys, string, random import datetime import urllib import wsgiref.handlers from google.appengine.api import memcache from google.appengine.ext import deferred from google.appengine.ext.webapp import util from google.appengine.api import urlfetch from django.utils import simplejson as json from django.dispatch import dispatcher from config import config import que #from config import CURPATH import tenjin tenjin.gae.init() from tenjin.helpers import * from gaesession import SessionMiddleware, get_current_session from model import User from model import Category from model import Post from model import PostSignals pjoin = os.path.join tplengine = tenjin.Engine(path=[pjoin("static", "views"), pjoin("static", "views", "iphonsta")], preprocess=True) tplengine_cache_store = tenjin.gae.helpers.fragment_cache.store tplengine_cache_prefix = tenjin.gae.helpers.fragment_cache.prefix logger = logging.getLogger() logger.setLevel(logging.DEBUG) tenjin.logger = logger COOKIE_KEY = "0883ba4c4fd211e0a727485b39b890e1" #this is your code def session_middleware(app): from google.appengine.ext.appstats import recording #for developing app = SessionMiddleware(app, cookie_key=COOKIE_KEY) app = recording.appstats_wsgi_middleware(app) return app def attach_event(func, signal): dispatcher.connect(func, signal=signal) def rPost_tpl_content(post, *args, **kw): tplengine_cache_store.set("%spost:content:%s" % (tplengine_cache_prefix, post.key().id()), format_content(post.content, post.format), config.POST_CACHE_TIME ) attach_event(rPost_tpl_content, PostSignals.Modify) def format_content(content, format="html"): if format == "html": return content elif format == "rest": try: from docutils.core import publish_parts except ImportError, ex: sys.path.insert(0, pjoin(config.CURPATH, "lib")) from docutils.core import publish_parts doc = publish_parts(content ,writer_name='html', settings_overrides= {"file_insertion_enabled": 0, "raw_enabled": 0, "_disable_config": 1, }) return doc["body"] elif format == "markdown": try: from markdown import markdown except ImportError, ex: sys.path.insert(0, pjoin(config.CURPATH, "lib")) from markdown import markdown return markdown(content, output_format="html4") elif format == "bbcode": try: from postmarkup import render_bbcode except ImportError, ex: sys.path.insert(0, pjoin(config.CURPATH, "lib")) from postmarkup import render_bbcode return render_bbcode(content, encoding=config.CHARSET, paragraphs=True) def randstr(start=5, end=10, case=string.lowercase): return "".join([random.choice(case) for i in xrange(random.randint(start, end))]) def soddy(): soddy = User.get_by_key_name("<EMAIL>") if not soddy: soddy = User(key_name="<EMAIL>", nickname=u"米落", password="123") soddy.put() return soddy def genid(n): while True: yield n n += 1 def gender_url(url, filter_func=lambda url: Post.get_by_path(url)): p = filter_func(url) if not p: return url genter = genid(1) if url.find("/") != -1: if url.split("/")[-1].find(".") != -1: ori, ext = url[:url.rfind(".")], url[url.rfind("."):] else: ori, ext = url[:url.rfind("/")], url[url.rfind("/"):] elif url.find(".") != -1: ori, ext = url[:url.rfind(".")], url[url.rfind("."):] else: ori, ext = url, "" while(filter_func(url)): url = "%s%d%s" % (ori, genter.next(), ext) return url url_mapper = { "%category%": lambda p: p.category.title, "%year%": lambda p: p.date_created.year, "%month%": lambda p: p.date_created.month, "%day%": lambda p: p.date_created.day, "%title%": lambda p: p.title, "%url%": lambda p: p.url, "%author%": lambda p: p.author.nickname, } def realurl(post): url = config.POST_URL for key, val in url_mapper.items(): if url.find(key) != -1: url = url.replace(key, str(val(post))) return gender_url(url) ZERO_TIME_DELTA = datetime.timedelta(0) class LocalTimezone(datetime.tzinfo): def utcoffset(self, dt): return datetime.timedelta(hours=Config.localtimezone) def dst(self, dt): return ZERO_TIME_DELTA LOCAL_TIMEZONE = LocalTimezone() class UTC(datetime.tzinfo): def utcoffset(self, dt): return ZERO_TIME_DELTA def dst(self, dt): return ZERO_TIME_DELTA UTC = UTC() def FormatTime(dt, format=config.DATETIME_FORMAT): if dt: return dt.strftime(format.encode("utf-8")) def ParserTime(dtstr, format="%Y/%m/%d %H:%M:%S"): return datetime.datetime.strptime(dtstr, format) def ParserLocalTimeToUTC(dtstr, format="%Y/%m/%d %H:%M:%S"): return ParserTime(dtstr, format).replace(tzinfo=LOCAL_TIMEZONE).astimezone(UTC) \ .replace(tzinfo=None) #fix in Google Engine App def LocalToUTC(dt): if dt.tzinfo: dt.replace(tzinfo=None) return dt.replace(tzinfo=LOCAL_TIMEZONE).astimezone(UTC) def UTCtoLocal(dt): if dt.tzinfo: dt.replace(tzinfo=None) return dt.replace(tzinfo=UTC).astimezone(LOCAL_TIMEZONE) \ .replace(tzinfo=None) #fix in Google Engine App ISO_TIME_FORMAT = '%Y-%m-%dT%H:%M:%SZ' def urlrequest(url, data=None, method=urlfetch.GET, headers=None): if data: data = urllib.urlencode(data) if headers is None: headers = {} return urlfetch.fetch(url=url, payload=data, method=method, headers=headers).content def sitemap_time_format(dt): if dt.tzinfo: dt = dt.astimezone(UTC) return dt.strftime('%Y-%m-%dT%H:%M:%S+00:00') def ISO_FORMAT(dt): logging.info(repr(dt)) if dt.tzinfo: return UTCtoLocal(dt).strftime(ISO_TIME_FORMAT) else: return dt.strftime(ISO_TIME_FORMAT) def iso_time_now(): return datetime.utcnow().strftime() class BaseHandler(que.RequestHandler): def __init__(self, request, response, default_status=405): #response.header["charset"] = config.CHARSET response.set_content_type() super(BaseHandler, self).__init__(request, response, default_status) def render(self, tplname, context=None, globals=None, layout=False): context = context or {} context["request"] = self.request context["config"] = config self.write(tplengine.render(tplname, context, globals, layout)) def jsonout(self, obj): self.set_content_type("json") self.write(json.dumps(obj)) manage_categories = [ { "url" : config.BLOG_ADMIN_PATH + "post/new/", "title": u"添加文章" }, { "url" : config.BLOG_ADMIN_PATH + "post/", "title" : u"文章管理" }, { "url" : config.BLOG_ADMIN_PATH + "reply/", "title" : u"评论" }, { "url" : config.BLOG_ADMIN_PATH + "config/", "title" : u"站点配置" }, ] manage_pages = [ { "url" : config.BLOG_ADMIN_PATH + "logout/", "title" : u"登出" }, ] class AdminHandler(BaseHandler): def __init__(self, request, response, default_status=405): self.session = get_current_session() #self.session["curr_ukey"] = "<EMAIL>" #soddy() super(AdminHandler, self).__init__(request, response, default_status=405) def before(self, *args, **kw): if not self.session.get("curr_ukey"): self.redirect(config.BLOG_ADMIN_PATH + "login/") return super(AdminHandler, self).before(*args, **kw) def render(self, tplname, context=None, globals=None, layout=False): context = context or {} context["categories_title"] = u"管理" context["pages_title"] = u"其他" context["categories"] = manage_categories context["pages"] = manage_pages super(AdminHandler, self).render(tplname, context, globals, layout) def curr_ukey(self): return self.request.session.get("curr_ukey", None) class BlogHandler(BaseHandler): def render(self, tplname, context=None, globals=None, layout=False): context = context or {} #context["categories_title"] = u"分类" #context["pages_title"] = u"其他" context["categories"] = Category.get_categories() super(BlogHandler, self).render(tplname, context, globals, layout) <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- # discription: model # author: dreampuf import logging import traceback import cPickle as pickle from hashlib import md5 from google.appengine.ext import db from google.appengine.ext import deferred from google.appengine.ext.db import Model run_in_transaction = db.run_in_transaction Rollback = db.Rollback Key = db.Key from django.dispatch import dispatcher from cache import memcache def sendsignal(signal=dispatcher.Any, *arg, **kw): dispatcher.send(signal=signal, *arg, **kw) def with_transaction(func): def wapper(*arg, **kw): with_transaction = kw.pop("with_transaction", True) if with_transaction: return db.run_in_transaction(wapper, with_transaction=False, *arg, **kw) return func(*arg, **kw) return wapper def memcached(key, cache_time=0, key_suffix_calc_func=None, namespace=None): def wrap(func): def cached_func(*args, **kw): key_with_suffix = key if key_suffix_calc_func: key_suffix = key_suffix_calc_func(*args, **kw) if key_suffix is not None: key_with_suffix = '%s:%s' % (key, key_suffix) value = memcache.get(key_with_suffix, namespace) if value is None: value = func(*args, **kw) try: memcache.set(key_with_suffix, value, cache_time, namespace) except: pass return value return cached_func return wrap TABLE_COUNT_TAG_PRE = "tablecount" _settingcache = {} class Setting(Model): name=db.StringProperty() value=db.TextProperty() @classmethod def get(cls,name,default=None, useMemoryCache=True): global _settingcache if useMemoryCache and _settingcache.has_key(name) : return _settingcache[name] else: n = memcache.get("setting.%s" % name) if n != None: if useMemoryCache: _settingcache[name] = n return n try: opt=Setting.get_by_key_name(name) result = pickle.loads(str(opt.value)) if isinstance(result, unicode): result = result.encode("utf-8") if useMemoryCache: _settingcache[name] = result memcache.set("setting.%s" % name, result, 0) return result except: return default @classmethod def set(cls,name,value, useMemoryCache=True): if useMemoryCache: global _settingcache _settingcache[name] = value memcache.set("setting.%s" % name, value, 0) opt = Setting.get_or_insert(name) opt.name = name opt.value = pickle.dumps(value) opt.put() @classmethod def remove(cls,name): global _settingcache if _settingcache.has_key(name): del _settingcache[name] memcache.delete("setting.%s" % name, 0) opt= Setting.get_by_key_name(name) if opt: opt.delete() class _ConfigProperty(object): def __init__(self, name, default=None, useMemoryCache=True): self.name = "config_%s" % name self.default= default self.usememorycache = useMemoryCache #def __getattr__(self, attrname): # real = Setting.get(self.name, self.default, self.usermemorycache) # return real.__getattr__(attrname) def __get__(self, instance, klass): return Setting.get(self.name, self.default, self.usememorycache) def __set__(self, instance, value): Setting.set(self.name, value, self.usememorycache) def __str__(self): return Setting.get(self.name, self.default, self.usememorycache) class _Pager(object): def __init__(self, data, count, index, last): self.data = data self.count = count self.index = index self.prev = index - 1 self.next = (index + 1 > last) and 0 or (index + 1) self.last = last def __repr__(self): return "<_Pager: count:%s, index:%s, prev:%s, next:%s, last:%s, Entry_Type:%s >" % (self.count, self.index, self.prev, self.next, self.last, self.data[0].__class__.__name__) def func2str(func): fcode = func.func_code return md5("%s%s" % (fcode.co_code, fcode.co_consts)).hexdigest() class BaseModel(Model): _lastQuery = None def put(self, **kw): if not self.is_saved(): tname = "%s_%s" % (TABLE_COUNT_TAG_PRE, self.__class__.__name__ , ) tval = Setting.get(tname, useMemoryCache=False) if tval == None: tval = self.__class__.total() Setting.set(tname, tval + 1, False) super(BaseModel, self).put(**kw) def delete(self, **kw): if self.is_saved(): tname = "%s_%s" % (TABLE_COUNT_TAG_PRE, self.__class__.__name__) tval = Setting.get(tname, useMemoryCache=False) if tval == None: tval = self.__class__.all().count(None) Setting.set(tname, tval - 1, False) super(BaseModel, self).delete(**kw) @classmethod def puts(cls, entrys): tname = "%s_%s" % (TABLE_COUNT_TAG_PRE, cls.__name__) Setting.set(tname, cls.total() + len(entrys), False) db.put(entrys) @classmethod def deletes(cls, vals): tname = "%s_%s" % (TABLE_COUNT_TAG_PRE, cls.__name__) Setting.set(tname, cls.total() - len(vals), False) db.delete(vals) @classmethod def fetch_page(cls, p, plen = 20, func=None, realtime_count=False): total = cls.total(func, realtime_count=realtime_count) n = total / plen if total % plen != 0: n = n + 1 #logging.info(n) if p < 0 or p > n: p = 1 offset = (p - 1) * plen query = cls.all() #cls._lastQuery if cls._lastQuery else cls.all() results = query.fetch(plen, offset) if func is None else func(query).fetch(plen, offset) cls._lastQuery = query return _Pager(results, total, p, n) @classmethod def cursorfetch(cls, cursor, plen = 20, func=None): query = cls.all() #cls._lastQuery if cls._lastQuery else cls.all() query = func(query) if func else query ls = query.with_cursor(cursor).fetch(plen) cls._lastQuery = query return ls, query.cursor() #@classmethod #def cursor(cls): # if cls._lastQuery: # return cls._lastQuery.cursor() # return None @classmethod def total(cls, func=None, realtime_count=False): if realtime_count: return func(cls.all()).count(None) if func else cls.all().count(None) if func: tname = "%s_%s::%s" % (TABLE_COUNT_TAG_PRE, cls.__name__, func2str(func)) else: tname = "%s_%s" % (TABLE_COUNT_TAG_PRE, cls.__name__) tval = Setting.get(tname, useMemoryCache=False) if tval == None: logging.info("calc the %s total count" % cls.__name__) tval = func(cls.all()).count(None) if func else cls.all().count(None) Setting.set(tname, tval, False) return tval @classmethod def refresh_total(cls, func=None): if func: tname = "%s_%s::%s" % (TABLE_COUNT_TAG_PRE, cls.__name__, func2str(func)) else: tname = "%s_%s" % (TABLE_COUNT_TAG_PRE, cls.__name__) tval = cls.all().count(None) Setting.set(tname, tval, False) def toBlob(val): return db.Blob(val) def toLink(val): return db.Link(val) def toEmail(val): return db.Email(val) class User(BaseModel): nickname = db.StringProperty(required=True) password = db.StringProperty(indexed=False) date_created = db.DateTimeProperty(auto_now_add=True) lastip = db.StringProperty(indexed=False) lastlogin = db.DateTimeProperty() #email = db.EmailProperty() #key_name as email @classmethod def check(cls, email, password): try: user = cls.get_by_key_name(email) if user and password and user.password == md5(password).<PASSWORD>(): return user return None except: logging.info(traceback.format_exc()) return None @classmethod def by_email(cls, email): return User.get_by_key_name(email) class Category(BaseModel): ishidden = db.BooleanProperty(default=False) title = db.StringProperty() description = db.StringProperty(indexed=False) order = db.IntegerProperty(default=0) belong = db.SelfReferenceProperty(collection_name="children") #url = db.StringProperty() #key_name as url @classmethod def get_all(cls): return cls.all().order("order") @classmethod def get_categories(cls): cates = cls.get_all() return [{"url": "/category/%s/"%i.key().name(), "title": i.title } for i in cates] @classmethod @with_transaction def new(cls, url, title, description, order=0, belong=None, with_transaction=True): c = cls(key_name=url, title=title, description=description, order=order, belong=belong) return db.put(c) @classmethod def id(cls, cid): return cls.get_by_id(cid) @classmethod def keyname(cls, ckey): return cls.get_by_key_name(ckey) # cls.incr_counter("%s_%s" % (TABLE_COUNT_TAG_PRE, cls.__name__)) class Tag(BaseModel): # key_name as title count = db.IntegerProperty(default=1) @property def posts(self): return Post.all().filter("tags =", self.key().name()) @classmethod def Incr(cls, tag): t = cls.get_by_key_name(tag) if not t: t = cls(key_name=tag) t.put() else: t.count = t.count + 1 t.put() @classmethod def Decr(cls, tag): t = cls.get_by_key_name(tag) if t: if t.count == 1: db.delete(t) else: t.count = t.count - 1 db.put(t) class PostStatus(object): NORMAL = 0 HIDDEN = 1 TOP = 2 PAGE = 3 class PostFormat(object): PLAIN = "html" #like HTML, txt MARKDOWN = "markdown" #markdown RST = "rest" #ReStructuredText UBB = "bbcode" #UBB class PostSignals(object): New = "Post.New" Modify = "Post.Modify" class Post(BaseModel): """ url 只是存在一个可能的别名,实际匹配时则直接匹配realurl """ #key_name=realurl, 因为realurl存在修改的可能而key_name无法修改;可能需要key_id数字索引;realurl需要存储之后才能获得; status = db.IntegerProperty(default=PostStatus.NORMAL) enablecomment = db.BooleanProperty(default=True) format = db.StringProperty(default=PostFormat.PLAIN, indexed=False) # 解析格式 realurl = db.StringProperty(default="") category = db.ReferenceProperty(Category, collection_name="posts") author = db.ReferenceProperty(User, collection_name="posts") title = db.StringProperty() date_created = db.DateTimeProperty(auto_now_add=True) date_modify = db.DateTimeProperty(auto_now_add=True) url = db.StringProperty() keyword = db.StringListProperty() content = db.TextProperty() views = db.IntegerProperty(default=0) tags = db.StringListProperty() @classmethod @with_transaction def new(cls, title, category_keyname, author_keyname, url, keyword, tags, content, status=PostStatus.NORMAL, format=PostFormat.PLAIN, enablecomment=True): c = Key.from_path("Category", category_keyname) a = Key.from_path("User", author_keyname) p = cls(title=title, category=c, author=a, url=url, keyword=keyword, tags=tags, content=content, format=format, enablecomment=enablecomment ) deferred.defer(sendsignal, signal=PostSignals.New, post=p) return db.put(p) @classmethod @with_transaction def modify(cls, post_id, title, category_keyname, author_keyname, url, keyword, tags, content, status=PostStatus.NORMAL, format=PostFormat.PLAIN, enablecomment=True): p = cls.id(post_id) #cur_tags = set(tags) #old_tags = set(p.tags) #for i in old_tags^(cur_tags&old_tags): # Tag.Decr(i) #for i in cur_tags^(cur_tags&old_tags): # Tag.Incr(i) c = Key.from_path("Category", category_keyname) a = Key.from_path("User", author_keyname) p.title=title p.category=c p.author=a p.url=url p.keyword=keyword p.tags=tags p.content=content p.format=format p.enablecomment=enablecomment deferred.defer(sendsignal, signal=PostSignals.Modify, post=p) return db.put(p) @classmethod def id(cls, pids): return Post.get_by_id(pids) @classmethod def get_by_path(cls, path, keys_only=False): return Post.all(keys_only=keys_only).filter("realurl =", path).get() @classmethod def get_feed_post(cls, feed_count=20): return Post.all().filter("status =", PostStatus.NORMAL).order("-date_created").fetch(feed_count) class CommentType(object): COMMENT = "comment" TRACKBACK = "trackback" PINGBACK = "pingback" class CommentSignals(object): New = "Comment.New" class Comment(BaseModel): commenttype = db.StringProperty(default=CommentType.COMMENT) belong = db.ReferenceProperty(Post, collection_name="comments") re = db.SelfReferenceProperty(collection_name="children") content = db.TextProperty() date_created = db.DateTimeProperty(auto_now_add=True) nickname = db.StringProperty() ip = db.StringProperty() website = db.LinkProperty() email = db.EmailProperty() hascheck = db.BooleanProperty(default=True) @classmethod @with_transaction def new(cls, belong, nickname, email, re=None, ip=None, website=None, content=None, hascheck=True, commenttype=CommentType.COMMENT): #belong = Post.id(belong) email = toEmail(email) if re: re = cls.id(re) if website: website = toLink(website) c = cls(parent=belong, belong=belong, nickname=nickname, #author.nickname if author else nickname, email=email,#author.key().name() if author else email, re=re, ip=ip or "", website=website or None, content=content or "", hascheck=hascheck, commenttype=commenttype ) deferred.defer(sendsignal, signal=CommentSignals.New, comment=c) return db.put(c) @classmethod def id(cls, comment_ids): return cls.get_by_id(comment_ids) @classmethod def by_post(cls, post, plen=50, cursor=None): return cls.cursorfetch(cursor, plen=plen, func=lambda x: x.filter("belong =", post)) class Attachment(BaseModel): beuse = db.ReferenceProperty(Post, collection_name="attachments") belong = db.ReferenceProperty(User, collection_name="attachments") filename = db.StringProperty() filetype = db.StringProperty() filesize = db.IntegerProperty(default=0) content = db.BlobProperty() date_created = db.DateTimeProperty(auto_now_add=True) def setfiletype(self, filename): self.filetype = os.path.splitext(filename)[1][1:] class Plugin(BaseModel): enable = db.BooleanProperty(default=False) pluginguid = db.StringProperty() pluginname = db.StringProperty() plugintype = db.StringProperty() plugindescription = db.StringProperty() pluginauthor = db.StringProperty() pluginurl = db.LinkProperty() pluginsize = db.IntegerProperty(default=0) plugindata = db.BlobProperty() <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- # discription: admin_views # author: dreampuf import re import logging from google.appengine.api import memcache from google.appengine.api import urlfetch from config import config from common import BlogHandler, AdminHandler, randstr, json, realurl, attach_event, urlrequest from model import run_in_transaction, Rollback, Category, Post, PostSignals, Tag, User class LoginHandler(AdminHandler): def before(self): pass def get(self): self.render("login.html", {"page_name": u"管理员登录", }) def post(self): pdict = self.POST username = pdict.get("username") password = pdict.get("<PASSWORD>") user = User.check(username, password) if user: self.session["curr_ukey"] = username user.lastip = self.request.client_ip self.redirect(config.BLOG_ADMIN_PATH) else: self.render("login.html", {"page_name": u"管理员登录", "username": username, "erros": u"错误的管理员账户或密码", }) class LogoutHandler(AdminHandler): def get(self): del self.session["curr_ukey"] self.redirect(config.BLOG_ADMIN_PATH + "login/") class AdminIndexHandler(AdminHandler): def get(self): self.render("admin_page.html", { "page_name": u"站点管理", "page_title": u"基本信息", }) class AdminCategoryHandler(AdminHandler): def post(self): pdict = self.request.POST action = pdict.get("action", "") if action == "new": try: Category.new(pdict.get("category.url", randstr()), pdict.get("category.title"), pdict.get("category.discription") ) Category.refresh_total() except Rollback, ex: self.jsonout(ex) else: self.jsonout("ok") ADMINPOSTFILTER = lambda x:x.order("-date_created") def rtotal_AdminPost(*arg, **kw): Post.refresh_total(func=ADMINPOSTFILTER) attach_event(func=rtotal_AdminPost, signal=PostSignals.New) class AdminPostHandler(AdminHandler): def get(self): p = self.GET.get("p") p = int(p) if p and p.isdigit() else 1 pager = Post.fetch_page(p, func=ADMINPOSTFILTER) context = {"page_name": u"文章管理", "page_title": u"文章管理", "pager": pager } self.render("admin_post.html", context) class AdminModifyPostHandler(AdminHandler): def get(self, post_id): p = Post.get_by_id(int(post_id)) if post_id.isdigit() else None if not p: self.redirect(config.BLOG_ADMIN_PATH + "post/") return context = {"page_name": u"编辑文章", "page_title": u"编辑文章", "all_category": Category.get_all(), "post.title": p.title, "post.category": p.category.key().name(), "post.url": p.url, "post.tags": ",".join(p.tags), "post.keyword": ",".join(p.keyword), "post.content": p.content, "post.format": p.format } self.render("admin_post_editor.html", context) def post(self, post_id): logging.info(self.request.environ) post_id = int(post_id) p = Post.id(post_id) if not p: self.redirect(config.BLOG_ADMIN_PATH + "post/") return pdict = self.request.POST cur_tags = set(pdict.get("post.tags").split(",")) old_tags = set(p.tags) for i in old_tags^(cur_tags&old_tags): Tag.Decr(i) for i in cur_tags^(cur_tags&old_tags): Tag.Incr(i) tags = list(cur_tags) try: old_realurl = p.realurl pkey = Post.modify(post_id=post_id, title=pdict.get("post.title"), category_keyname=pdict.get("post.category").decode(config.CHARSET).encode("utf-8"), author_keyname=self.session.get("curr_ukey").decode(config.CHARSET).encode("utf-8"), url=pdict.get("post.url"), keyword=pdict.get("post.keyword").split(","), tags=pdict.get("post.tags").split(","),#tags, content=pdict.get("post.content"), format=pdict.get("post.format") ) p = Post.id(pkey.id()) if p.realurl != old_realurl: p.realurl = realurl(p) p.put() except Exception, ex: logging.info(ex) context = {} context.update(self.request.POST) context["errors_msg"] = ex context["page_name"] = u"修改文章" context["page_title"] = u"修改文章" context["all_category"] = Category.get_all() self.render("admin_post_editor.html", context) else: self.redirect(config.BLOG_ADMIN_PATH + "post/") class AdminAddPostHandler(AdminHandler): def get(self): editor = self.GET.get("editor") if editor and editor in config.EDITOR_TYPE : config.POST_EDITOR = editor context = {} # config.POST_EDITOR = "" editor = config.POST_EDITOR if not editor.strip(): #首次编辑, 选择编辑器 context["page_name"] = u"编辑器选择" context["page_title"] = u"首次编辑文章,请选择你所喜爱的文本编辑" context["first"] = True else: context["page_name"] = u"添加文章" context["page_title"] = u"添加文章" context["all_category"] = Category.get_all() self.render("admin_post_editor.html", context) def post(self): pdict = self.request.POST try: #def new(cls, title, category_keyname, author_keyname, url, keyword, tags, content, status=PostStatus.NORMAL, format=PostFormat.PLAIN, enablecomment=True): tags = pdict.get("post.tags").split(",") for i in tags: Tag.Incr(i) pkey = Post.new(title=pdict.get("post.title"), category_keyname=pdict.get("post.category").decode(config.CHARSET).encode("utf-8"), author_keyname=self.session.get("curr_ukey").decode(config.CHARSET).encode("utf-8"), url=pdict.get("post.url"), keyword=pdict.get("post.keyword").split(","), tags=tags, content=pdict.get("post.content"), format=pdict.get("post.format") ) p = Post.id(pkey.id()) p.realurl = realurl(p) Post.put(p) Post.refresh_total() except Exception, ex: context = {} context.update(self.request.POST) context["errors_msg"] = ex context["page_name"] = u"添加文章" context["page_title"] = u"添加文章" context["all_category"] = Category.get_all() self.render("admin_post_editor.html", context) else: self.redirect(config.BLOG_ADMIN_PATH + "post/") class AdminConfigHandler(AdminHandler): def get(self): context = {"page_title": u"站点设置", } self.render("admin_config.html", context) def post(self): post_editor = self.request.POST.get("POSTEDITOR")#pop("POST_EDITOR") if post_editor in config.EDITOR_TYPE: config.POST_EDITOR = post_editor for key, val in self.request.POST.items(): try: if isinstance(getattr(config, key), list): if val.find("\n") != -1: setattr(config, key, val.split("\n")) else: setattr(config, key, [val]) else: setattr(config, key, val) pass except AttributeError, ex: continue self.redirect(".") class AdminUtilHandler(AdminHandler): def post(self, action): if action == "cross_domain": post_data = dict([(k, v.encode("utf-8")) for k, v in self.POST.copy().items()]) data = urlrequest(self.POST.pop("url"), post_data, urlfetch.POST).decode("utf-8") split_start = data.find(u"关键词:<br>") + 16 #data = data[split_start: # data.find("</FONT>", split_start)] #self.write(data) #return result = re.findall(u"([^</>\s]+?)\:.+<br", data[split_start : data.find(u"</FONT>", split_start)]) self.jsonout(result) return class AdminCronHandler(AdminHandler): def get(self, instruct=None): if instruct == "view_counter": view = memcache.get("views") if view != None: for path,v in view.items(): post = Post.get_by_path(path) if post: post.views += v post.put() memcache.delete("views", namespace="Front") <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- # discription: admin_url # author: dreampuf import sys, os, logging CURPATH = os.path.join(os.path.abspath(os.path.dirname(__file__))) sys.path.insert(0, os.path.join(CURPATH, "lib")) from google.appengine.ext.webapp import util from config import config from admin_views import LoginHandler from admin_views import LogoutHandler from admin_views import AdminIndexHandler from admin_views import AdminAddPostHandler from admin_views import AdminConfigHandler from admin_views import AdminCategoryHandler from admin_views import AdminPostHandler from admin_views import AdminModifyPostHandler from admin_views import AdminCronHandler from admin_views import AdminUtilHandler import que from common import session_middleware def main(): BLOG_ADMIN_PATH = config.BLOG_ADMIN_PATH application = que.WSGIApplication([ (BLOG_ADMIN_PATH + "post/", AdminPostHandler), (BLOG_ADMIN_PATH + "post/new/", AdminAddPostHandler), (BLOG_ADMIN_PATH + "post/(?P<post_id>\d+)/", AdminModifyPostHandler), (BLOG_ADMIN_PATH + "login/", LoginHandler), (BLOG_ADMIN_PATH + "logout/", LogoutHandler), (BLOG_ADMIN_PATH + "config/", AdminConfigHandler), (BLOG_ADMIN_PATH + "category/", AdminCategoryHandler), (BLOG_ADMIN_PATH + "cron/(?P<instruct>\w+)/", AdminCronHandler), (BLOG_ADMIN_PATH + "util/(?P<action>[^/]+)/", AdminUtilHandler), (BLOG_ADMIN_PATH, AdminIndexHandler) ]) util.run_wsgi_app(session_middleware(application)) if __name__ == '__main__': main() <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- # discription: blog_views # author: dreampuf import os, sys, logging, traceback, urllib CURPATH = os.path.join(os.path.abspath(os.path.dirname(__file__))) sys.path.insert(0, os.path.join(CURPATH, "lib")) from google.appengine.api import memcache from django.dispatch import dispatcher from config import config from model import Post from model import PostStatus from model import PostSignals from model import Key from model import User from model import Comment from model import CommentSignals from model import Rollback from common import BlogHandler, attach_event INDEXPOSTFILTER = lambda x:x.filter("status =", PostStatus.NORMAL).order("-date_created") def rtotal_Index(*args, **kw): Post.refresh_total(func=INDEXPOSTFILTER) attach_event(func=rtotal_Index, signal=PostSignals.New) class IndexHandler(BlogHandler): def get(self): p = self.GET.get("p") p = int(p) if p and p.isdigit() else 1 pager = Post.fetch_page(p, func=INDEXPOSTFILTER) context = {"pager": pager} self.render("index.html", context) class CategoryHandler(BlogHandler): def get(self, category_key_name): p = self.GET.get("p") p = int(p) if p and p.isdigit() else 1 cate = Key.from_path("Category", category_key_name) if not cate: #TODO 404 pass pager = Post.fetch_page(p, func=lambda x:x.filter("category =", cate).filter("status =", PostStatus.NORMAL).order("-date_created"), realtime_count=True) context = {"pager": pager} self.render("index.html", context) class CommentHandler(BlogHandler): def post(self, post_id): post_id = int(post_id) post = Post.id(post_id) if not post: #TODO 404 return pdict = self.request.POST nickname = pdict.get("author") email = pdict.get("email") website = pdict.get("url") comment = pdict.get("comment") logging.info(website) #def new(cls, belong, nickname, email, author=None, re=None, ip=None, website=None, hascheck=True, commenttype=CommentType.COMMENT): try: c = Comment.new(belong=post, nickname=nickname, email=email, website=website, content=comment, ip=self.request.client_ip) except Exception, ex: logging.info(traceback.format_exc()) self.redirect("%s/%s" % (config.BASEURL, post.realurl)) def view_counter(handler): def view_handler(self, path): url = urllib.unquote(path) view = memcache.get("views") if view == None: view = {} if not url in view: view[url] = 0 view[url] += 1 memcache.set("views", view) return handler(self, path) return view_handler VIEWCOMMENTFILTER = lambda x: x.filter("hascheck =", True).order("date_created") if config.COMMENT_NEEDLOGINED else x.order("date_created") def rtotal_Comment(*args, **kw): Comment.refresh_total(func=VIEWCOMMENTFILTER) attach_event(func=rtotal_Comment, signal=CommentSignals.New) class ViewHandler(BlogHandler): # 大苦逼处理类 @view_counter def get(self, path): gdict = self.GET path = urllib.unquote(path) if path == config.FEED_SRC: #FEED self.set_content_type("atom") posts = Post.get_feed_post(config.FEED_NUMBER) self.render("feed.xml", {"posts": posts }) return post = Post.get_by_path(path) if post: p = gdict.get("p", None) p = int(p) if p and p.isdigit() else 1 def post_comment_filter(query): query = query.filter("belong =", post) if config.COMMENT_NEEDLOGINED: query = query.filter("hashcheck =", True) query = query.order("date_created") return query post_comments = Comment.fetch_page(p, config.COMMENT_PAGE_COUNT, func=post_comment_filter, realtime_count=True) context = {"post": post, "post_comments": post_comments, } self.render("single.html", context) return #self.render("single.html", {}) <file_sep>#! /usr/bin/env python # -*- coding: utf-8 -*- # discription: cache # author: dreampuf import time from datetime import datetime from google.appengine.api import memcache as gmemcache class BaseCache(object): def __init__(self, timeout=0): try: timeout = int(timeout) except (ValueError, TypeError): timeout = 0 self.default_timeout = timeout def get(self, key, default=None): raise NotImplementedError def set(self, key, value, timeout=None): raise NotImplementedError def delete(self, key): raise NotImplementedError def incr(self, key, timeout=None): val = self.get(key) if val: val = val + 1 self.set(key, val, timeout) def decr(self, key, timeout=None): val = self.get(key) if val: val = val - 1 self.set(key, val, timeout) def get_many(self, keys): d = {} for k in keys: val = self.get(k) if val is not None: d[k] = val return d def has_key(self, key): return self.get(key) is not None def __contains__(self, key): return self.has_key(key) def dict_cmp(x, y): return 1 if x[1] > y[1] else \ 0 if x[1] == y[1] else \ -1 class LocalCache(BaseCache): def __init__(self, cull_frequency=3, max_entrys=300, *args, **kw): self._cache = {} self._expire = {} self._cull_frequency = cull_frequency self._delete_count = max_entrys/cull_frequency self.max_entrys = max_entrys super(LocalCache, self).__init__(*args, **kw) def get(self, key, default=None): if self._expire.has_key(key): if time.time() > self._expire[key]: self.delete(key) return default return self._cache.get(key, default) else: return default def set(self, key, val, timeout=None): self._cull() timeout = self.default_timeout if timeout is None else timeout self._cache[key] = val self._expire[key] = time.time() + timeout def delete(self, key): #if self._cache.has_key(kddey): # del self._cache[key] self._expire.pop(key, None) self._cache.pop(key, None) def has_key(self, key): exp = self._expire.get(key, None) if exp is None: return False elif exp > time.time(): return True self._expire.pop(key, None) self._cache.pop(key,None) def _cull(self): clen = len(self._cache) if clen > self.max_entrys: if self._cull_frequency in (0, 1): self._cache.clear() self._expire.clear() else: sorted_list = sorted(self._expire.items(), dict_cmp) for i in xrange(self._delete_count): self._cache.pop(sorted_list[i][0], None) self._expire.pop(sorted_list[i][0], None) locache = LocalCache(timeout=300) class MemCache(BaseCache): default_namespace = None def __init__(self, default_namespace=None, *args, **kw): self.namespace = default_namespace if not default_namespace is None else MemCache.default_namespace super(MemCache, self).__init__(self, *args, **kw) def get(self, key, default=None, namespace=None): namespace = self.namespace if namespace is None else namespace ret = gmemcache.get(key, namespace=namespace) if ret is None: return default return ret def get_multi(self, keys, key_prefix="", namespace=None): namespace = self.namespace if namespace is None else namespace return gmemcache.get_multi(keys, key_prefix, namespace) def set(self, key, val, timeout=None, namespace=None): namespace = self.namespace if namespace is None else namespace timeout = self.default_timeout if timeout is None else timeout return gmemcache.set(key, val, timeout, namespace=namespace) def set_multi(self, mapping, timeout=None, key_prefix="", namespace=None): namespace = self.namespace if namespace is None else namespace timeout = self.default_timeout if timeout is None else timeout return gmemcache.set_multi(mapping, timeout, key_prefix, namespace=namespace) def delete(self, key, namespace=None): namespace = self.namespace if namespace is None else namespace return gmemcache.delete(key, namespace=namespace) def delete_multi(self, keys, key_prefix="", namespace=None): namespace = self.namespace if namespace is None else namespace return gmemcache.delete_multi(keys, key_prefix=key_prefix, namespace=namespace) def get_many(self, keys, namespace=None): return self.get_multi(keys, namespace=namespace) def incr(self, key, delta=1, namespace=None, initial_value=None): namespace = self.namespace if namespace is None else namespace return gmemcache.incr(key, delta, namespace, initial_value) def decr(self, key, delta=1, namespace=None, initial_value=None): namespace = self.namespace if namespace is None else namespace return gmemcache.decr(key, delta, namespace, initial_value) memcache = MemCache() class CacheProperty(object): def __init__(self, fget): self.fget = fget self.__doc__ = fget.__doc__ def __get__(self, obj, objtype=None): obj.__dict__[self.fget.__name__] = prop = self.fget(obj) return prop <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- # discription: test_for template lib # author: dreampuf import sys, os, unittest, logging, time map(sys.stdout.write, sys.path) import tenjin #import Template, Engine, gae import tenjin.gae; tenjin.gae.init() from tenjin.helpers import escape, to_str #from common import tplengin, escape, to_str class Template_Test(unittest.TestCase): def setUp(self): self.tpl = """ I'm is a mem tpl. hello #{ name } """ def test_tenjinMemLoader(self): a = tenjin.Template(filename="afn", input=self.tpl) engine = tenjin.Engine(cache=tenjin.MemoryCacheStorage(), preprocess=True) engine.add_template(a) logging.info(engine.render("afn", {"name": "Dreampuf"})) <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- # discription: template # author: dreampuf import sys, os, logging CURPATH = os.path.join(os.path.abspath(os.path.dirname(__file__))) #sys.path.insert(0, os.path.join(CURPATH, "lib")) from google.appengine.ext.webapp import util from config import config import que class aHandler(que.RequestHandler): def get(self, filename): #TODO 凑合 #logging.info(filename) if filename.endswith("js"): self.set_content_type("text/javascript") elif filename.endswith("css"): self.set_content_type("text/css") self.response.header["Cache-Control"] = "public, max-age=10800" tplpath = os.path.join( "..", "static", "views", "iphonsta") try: fs = open(os.path.join(tplpath, filename)) self.write(fs.read()) fs.close() except: pass def main(): tpl_path = "%stemplate/%s/(.*)" % (config.BLOG_PATH , config.TEMPLATE ) application = que.WSGIApplication([ (tpl_path, aHandler), ]) util.run_wsgi_app(application) if __name__ == '__main__': main() <file_sep>#! /usr/bin/env python # -*- coding: utf-8 -*- # discription: WSGI # author: dreampuf """ que modified from keakon's yui. original author: keakon<mailto:<EMAIL>> """ import re import time import logging import cStringIO as StringIO from datetime import datetime, timedelta from hashlib import md5 from urlparse import urljoin, urlunsplit from google.appengine.ext import webapp from webob.multidict import MultiDict from cache import memcache, locache, CacheProperty HTTP_STATUS = { 100: 'Continue', 101: 'Switching Protocols', 102: 'Processing', 200: 'OK', 201: 'Created', 202: 'Accepted', 203: 'Non-Authoritative Information', 204: 'No Content', 205: 'Reset Content', 206: 'Partial Content', 207: 'Multi-Status', 300: 'Multiple Choices', 301: 'Moved Permanently', 302: 'Moved Temporarily', 303: 'See Other', 304: 'Not Modified', 305: 'Use Proxy', 307: 'Temporary Redirect', 400: 'Bad Request', 401: 'Unauthorized', 402: 'Payment Required', 403: 'Forbidden', 404: 'Not Found', 405: 'Method Not Allowed', 406: 'Not Acceptable', 407: 'Proxy Authentication Required', 408: 'Request Time-out', 409: 'Conflict', 410: 'Gone', 411: 'Length Required', 412: 'Precondition Failed', 413: 'Request Entity Too Large', 414: 'Request-URI Too Large', 415: 'Unsupported Media Type', 416: 'Requested range not satisfiable', 417: 'Expectation Failed', 422: 'Unprocessable Entity', 423: 'Locked', 424: 'Failed Dependency', 500: 'Internal Server Error', 501: 'Not Implemented', 502: 'Bad Gateway', 503: 'Service Unavailable', 504: 'Gateway Time-out', 505: 'HTTP Version not supported', 507: 'Insufficient Storage', } class Request(webapp.Request): """ a wapper with webapp.Request """ __SPIDER_PATTERN = re.compile('(bot|crawl|spider|slurp|sohu-search|lycos|robozilla)', re.I) @CacheProperty def is_spider(self): return self.__SPIDER_PATTERN.search(self.user_agent) is not None @CacheProperty def is_system(self): return self.remote_addr[:2] == '0.' @CacheProperty def ua_details(self): ''' parse browser, platform, os and vendor from user agent. 从user agent解析浏览器、平台、操作系统和产商信息。 @rtype: string @return: tuple of browser, platform, os and vendor browser, platform, os, vendor组成的元组 ''' user_agent = self.user_agent os = '' browser = '' platform = '' vendor = '' if user_agent: if 'iPhone' in user_agent: os = 'iOS' platform = 'iPhone' vendor = 'Apple' elif 'iPad' in user_agent: os = 'iOS' platform = 'iPad' vendor = 'Apple' elif 'iPod' in user_agent: os = 'iOS' platform = 'iPod' vendor = 'Apple' elif 'Android' in user_agent: os = platform = 'Android' elif 'BlackBerry' in user_agent: os = 'BlackBerry OS' platform = 'BlackBerry' vendor = 'RIM' elif 'Palm' in user_agent: os = 'PalmOS' platform = 'Palm' elif 'Windows Phone' in user_agent: os = platform = 'Windows Mobile' elif 'PSP' in user_agent: platform = 'PSP' vendor = 'Sony' elif 'Kindle' in user_agent: os = 'Linux' platform = 'Kindle' elif 'Nintendo' in user_agent or 'Nitro' in user_agent: platform = 'Wii' vendor = 'Nintendo' if not os: if 'Windows' in user_agent: if 'Windows NT 6.1' in user_agent: os = 'Windows 7' elif 'Windows NT 5.1' in user_agent: os = 'Windows XP' elif 'Windows NT 6.0' in user_agent: os = 'Windows Vista' elif 'Windows NT 5.2' in user_agent: os = 'Windows Server 2003' elif 'Windows NT 5.0' in user_agent: os = 'Windows 2000' elif 'Windows CE' in user_agent: os = 'Windows CE' else: os = 'Windows' elif 'Macintosh' in user_agent or 'Mac OS' in user_agent: os = 'Mac OS' elif 'Linux' in user_agent: os = 'Linux' elif 'FreeBSD' in user_agent: os = 'FreeBSD' elif 'OpenBSD' in user_agent: os = 'OpenBSD' elif 'Solaris' in user_agent: os = 'Solaris' elif 'Symbian' in user_agent or 'SymbOS' in user_agent: if 'Series60' in user_agent: os = 'SymbianOS Series60' elif 'Series40' in user_agent: os = 'SymbianOS Series40' else: os = 'SymbianOS' if not browser: if 'MSIE' in user_agent: browser = 'Internet Explorer' elif 'Firefox' in user_agent: browser = 'Firefox' elif 'Chrome' in user_agent: browser = 'Chrome' elif 'Safari' in user_agent: if 'Mobile' in user_agent: browser = 'Mobile Safari' self.is_mobile = True else: browser = 'Safari' elif 'Opera Mini' in user_agent: browser = 'Opera Mini' self.is_mobile = True elif 'Opera Mobi' in user_agent: browser = 'Opera Mobile' self.is_mobile = True elif 'Opera' in user_agent: browser = 'Opera' elif 'UCWEB' in user_agent: browser = 'UCWEB' self.is_mobile = True elif 'IEMobile' in user_agent: browser = 'IEMobile' self.is_mobile = True if not vendor: if 'Nokia' in user_agent: vendor = 'Nokia' elif 'motorola' in user_agent: vendor = 'Motorola' elif 'Sony' in user_agent: vendor = 'Sony' elif 'samsung' in user_agent.lower(): vendor = 'Samsung' return browser, platform, os, vendor @CacheProperty def is_mobile(self): environ = self.environ if 'HTTP_X_WAP_PROFILE' in environ or 'HTTP_PROFILE' in environ or 'X-OperaMini-Features' in environ or\ self.first_match(('application/vnd.wap.xhtml+xml', 'text/vnd.wap.wml'), ''): return True user_agent = self.user_agent if user_agent: user_agent_lower = user_agent.lower() if 'phone' in user_agent_lower or 'mobi' in user_agent_lower or 'wap' in user_agent_lower: return True browser, platform, os, vendor = self.ua_details if platform or vendor: return True @CacheProperty def client_ip(self): environ = self.environ ip = environ.get('HTTP_X_REAL_IP', '') # if using nginx reverse proxy if ip: return ip ip = environ.get('HTTP_CLIENT_IP', '') if ip: return ip ip = environ.get('HTTP_X_FORWARDED_FOR', '') if ip: return ip return environ.get('REMOTE_ADDR', 'unknown') def first_match(self, mime_types, fallback='text/html'): accept = self.accept.best_matches() for mime_type in mime_types: if mime_type in accept: return mime_type return fallback class ResponseHeader(object): def __init__(self, header=None, cookie=()): cookie = [('Set-Cookie', value) for value in cookie] _header = {} if header: for name, value in header.iteritems(): if value is not None: name = self._valid_name(name) if name != 'Set-Cookie': _header[name] = value else: cookie.append(('Set-Cookie', value)) self.__header = _header self.__cookie = cookie def __getitem__(self, name): name = self._valid_name(name) if name != 'Set-Cookie': return self.__header.get(name, None) else: return [cookie[1] for cookie in self.__cookie] or None def __setitem__(self, name, value): name = self._valid_name(name) if name != 'Set-Cookie': if value is not None: self.__header[name] = value else: self.__header.pop(name, None) else: if value is not None: self.__cookie = [('Set-Cookie', value)] else: self.__cookie = [] def __delitem__(self, name): name = self._valid_name(name) if name != 'Set-Cookie': self.__header.pop(name, None) else: self.__cookie = [] def __contains__(self, name): name = self._valid_name(name) if name != 'Set-Cookie': return name in self.__header else: return self.__cookie != [] def setdefault(self, name, default_value): name = self._valid_name(name) if name != 'Set-Cookie': if default_value is not None: return self.__header.setdefault(name, default_value) else: return self.__header.get(name, None) else: if self.__cookie != []: return [cookie[1] for cookie in self.__cookie] elif default_value is not None: self.__cookie = [('Set-Cookie', default_value)] return [default_value] else: return None def pop(self, name, default_value=None): name = self._valid_name(name) if name != 'Set-Cookie': return self.__header.pop(name, default_value) else: if self.__cookie != []: cookie = [cookie[1] for cookie in self.__cookie] self.__cookie = [] return cookie else: return None def add_cookie(self, name, value, expires=None, path=None, domain=None, secure=False, httponly=False): cookie = ['%s=%s' % (name, value)] if expires is not None: if isinstance(expires, int): cookie.append((datetime.utcnow() + timedelta(seconds=expires)).strftime('expires=%a, %d-%b-%Y %H:%M:%S GMT')) elif isinstance(expires, datetime): cookie.append(expires.strftime('expires=%a, %d-%b-%Y %H:%M:%S GMT')) else: cookie.append('expires=' + expires) if path: cookie.append('path=' + path) if domain: cookie.append('domain=' + domain) if secure: cookie.append('secure') if httponly: cookie.append('HttpOnly') self.__cookie.append(('Set-Cookie', '; '.join(cookie))) def get_cookies(self): return self.__cookie[:] def clear_cookies(self): self.__cookie = [] def items(self): return self.__header.items() + self.__cookie def clear(self): self.__header = {} self.__cookie = [] def __len__(self): return len(self.__header) + len(self.__cookie) @staticmethod def _valid_name(name): name = name.title() if name == 'Etag': return 'ETag' if name == 'X-Xss-Protection': return 'X-XSS-Protection' if name == 'Www-Authenticate': return 'WWW-Authenticate' if name == 'Content-Md5': return 'Content-MD5' return name class Response(object): def __init__(self, start_response): self._start_response = start_response # set default HTTP status to 200 OK # 将默认的HTTP状态码设为200 OK self.status = 200 self.header = ResponseHeader() # the string buffer for output content # 存储输出内容的字符串缓冲区 self.out = StringIO.StringIO() def set_content_type(self, mime_type='text/html', charset='UTF-8'): if mime_type != 'text/html': if mime_type == 'xhtml': mime_type = self.handler.request.first_match(('application/xhtml+xml',), 'text/html') elif mime_type == 'wap': mime_type = 'text/vnd.wap.wml' elif mime_type == 'wap2': mime_type = self.handler.request.first_match(('application/vnd.wap.xhtml+xml', 'application/xhtml+xml'), 'text/html') elif mime_type == 'json': mime_type = 'application/json' elif mime_type == 'atom': mime_type = 'application/atom+xml' charset = '' elif mime_type == 'rss': mime_type = 'application/rss+xml' charset = '' self.header['Content-Type'] = '%s; charset=%s' % (mime_type, charset) if charset else mime_type def set_cache(self, seconds, is_privacy=None): if seconds <= 0: self.header['Cache-Control'] = self.header['Pragma'] = 'no-cache' # fix localhost test for IE 6 # for performance reason, you can remove next line in production server # 在本地开发服务器上用IE 6测试会出现bug # 如果是在生产服务器上使用的话,可以去掉下面这行代码,减小header的体积 # 详情可见:http://www.keakon.cn/bbs/thread-1976-1-1.html self.header['Expires'] = 'Fri, 01 Jan 1990 00:00:00 GMT' else: if is_privacy: privacy = 'public, ' elif is_privacy is None: privacy = '' else: privacy = 'private, ' self.header['Cache-Control'] = '%smax-age=%s' % (privacy, seconds) def write(self, obj, encoding='utf-8'): if isinstance(obj, str): self.out.write(obj) elif isinstance(obj, unicode): self.out.write(obj.encode(encoding)) else: self.out.write(str(obj)) def get_status(self): return '%d %s' % (self.status, HTTP_STATUS[self.status]) def clear(self): self.out.seek(0) self.out.truncate(0) def send(self): write = self._start_response(self.get_status(), self.header.items()) body = self.out.getvalue() if body: write(body) class RequestHandler(object): def __init__(self, request, response, default_status=405): self.request = request self.response = response self.__default_status = default_status self.update_shortcut() def update_shortcut(self): request = self.request response = self.response response.handler = self self.header = response.header self.write = response.write self.clear = response.clear self.set_content_type = response.set_content_type self.set_cache = response.set_cache self.GET = request.GET self.POST = request.POST self.HEADER = request.headers def get(self, *args, **kw): self.not_allowed() def head(self, *args, **kw): self.get(*args, **kw) post = options = put = delete = trace = get def before(self, *args, **kw): pass def after(self, *args, **kw): pass def set_status(self, code): self.response.status = code def error(self, code): self.set_status(code) self.clear() def redirect(self, url, status=302): # if status not in (301, 302, 303, 307) or (status in (303, 307) and self.request.environ['SERVER_PROTOCOL'] == 'HTTP/1.0'): # status = 302 self.set_status(status) logging.info(self.request.environ) if 'HTTP_ORIGIN' in self.request.environ: self.header['Location'] = urljoin(self.request.environ['HTTP_ORIGIN'], url) else: self.header['Location'] = urljoin(self.request.url, url) self.clear() def not_allowed(self): status = self.__default_status self.error(status) if status == 405: allow = [method.upper() for method in ('get', 'post', 'head', 'options', 'put', 'delete', 'trace') # has been overriden, so must has been implemented # 已被覆盖,所以必然已被实现 if getattr(self.__class__, method) != getattr(RequestHandler, method)] self.header['Allow'] = ', '.join(allow) def handle_exception(self, exception): logging.error(exception) self.error(500) raise class HtmlRequestHandler(RequestHandler): def before(self, *args, **kw): self.response.set_content_type() class WSGIApplication(object): def __init__(self, url_mapping, default_response_class=Response, quote_path=True): self.quote_path = quote_path url_mapping_keys = [] url_mappings = {} for handler_tuple in url_mapping: regexp = handler_tuple[0] handler = handler_tuple[1] if not regexp or not handler: continue response_class = handler_tuple[2] if len(handler_tuple) > 2 else default_response_class if regexp[0] != '^': regexp = '^' + regexp if regexp[-1] != '$': regexp += '$' compiled = re.compile(regexp) url_mappings[compiled] = (handler, response_class) url_mapping_keys.append(compiled) self.__url_mapping_keys = url_mapping_keys self.__url_mappings = url_mappings def __call__(self, environ, start_response): request = Request(environ) request_path = request.path if self.quote_path else request.path_info groups = () groupdict = {} for regexp in self.__url_mapping_keys: handler, response_class = self.__url_mappings[regexp] match = regexp.match(request_path) if match: response = response_class(start_response) if not callable(handler): # delay binding for url_path and handler_class string # 推迟绑定URL路径和处理类字符串 try: mod_name, class_name = handler.rsplit('.', 1) mod = __import__(mod_name) handler = getattr(mod, class_name) self.__url_mappings[regexp] = handler, response_class except Exception, e: logging.error('Please check your URL mapping, you probably point this path "%s" to an undefined handler "%s". \n%s', request_path, handler, format_exc()) response, handler = self.handle_not_found(request, start_response) self.__url_mappings[regexp] = handler, response.__class__ break handler = handler(request, response) groupdict = match.groupdict() if not groupdict: groups = match.groups() break else: response, handler = self.handle_not_found(request, start_response) try: handler.before(*groups, **groupdict) method = request.method if method == 'GET': handler.get(*groups, **groupdict) elif method == 'POST': handler.post(*groups, **groupdict) elif method == "HEAD": handler.head(*groups, **groupdict) elif method == "OPTIONS": handler.options(*groups, **groupdict) elif method == "PUT": handler.put(*groups, **groupdict) elif method == "DELETE": handler.delete(*groups, **groupdict) elif method == "TRACE": handler.trace(*groups, **groupdict) else: getattr(handler, method.lower())(*groups, **groupdict) handler.after(*groups, **groupdict) except Exception, e: handler.handle_exception(e) handler.response.send() return [] def handle_not_found(self, request, start_response): response = Response(start_response) return response, RequestHandler(request, response, 404) @property def url_mapping(self): return self.__url_mappings <file_sep>#! /usr/bin/env python # -*- coding: utf-8 -*- # discription: test_lib # author: dreampuf import os, unittest, logging, time from cache import LocalCache, MemCache, CacheProperty from docutils.core import publish_parts from google.appengine.api import urlfetch from lib import config from common import gender_url class CacheTest(unittest.TestCase): def test_locache(self): acache = LocalCache(timeout=5) self.assertEquals(None, acache.get("key")) acache.set("key", "value") self.assertEquals("value", acache.get("key")) time.sleep(5) self.assertEquals(None, acache.get("key")) acache.set("akey", "avalue", timeout=2) self.assertEquals("avalue", acache.get("akey")) time.sleep(2) self.assertEquals(None, acache.get("akey")) acache = LocalCache(timeout=300) for i in xrange(500): acache.set("%03d" % i, "%03d") end = start = -1 for i in xrange(500, 0, -1): if acache.get("%03d" % i): end = i break for i in xrange(500): if acache.get("%03d" % i): start = i break self.assertTrue((end-start) < 300) def test_memcache(self): amcache = MemCache() bmcache = MemCache(default_namespace="b") val = time.time() amcache.set("key", val) self.assertNotEquals(amcache.get("key"), bmcache.get("key")) self.assertEquals(None, bmcache.get("key")) def test_cacheproperty(self): class aClass(object): @CacheProperty def a(self): return time.time() a = aClass() self.assertEquals(a.a, a.a) self.assertTrue(a.__dict__.has_key("a")) class DocutilsTest(unittest.TestCase): def setUp(self): self.override_setting={ 'file_insertion_enabled':0, 'raw_enabled':0, '_disable_config':1, } self.doc = """ =========== 你好周杰伦 =========== :author:Dreampuf :date:2011-02-14 01:38:34 谢谢 --------- #. verynice #. yeah 是的吗? ======= ""很明显是的"" """ def testRST2HTML(self): dd = publish_parts(self.doc,writer_name='html',settings_overrides=self.override_setting) #logging.info(dd.keys()) #logging.info(dd["body"]) self.assertTrue(dd["body"].find(u"<h1>谢谢</h1>") != -1) self.assertTrue(dd["body"].find(u"<h2>是的吗?</h2>") != -1) class ConfigTest(unittest.TestCase): def setUp(self): pass def test_config(self): self.assertTrue(not config.CURPATH is None) #logging.info(config.CURPATH) class CommonTest(unittest.TestCase): def setUp(self): pass def test_gender_url(self): self.assertEquals("s", gender_url("s", filter_func=lambda x: x not in ("s"))) self.assertEquals("s/s/s2.html", gender_url("s/s/s.html", filter_func=lambda x: x in ("s/s/s.html", "s/s/s1.html"))) self.assertEquals("g3.html", gender_url("g.html", filter_func=lambda x: x in ("g.html", "g1.html", "g2.html"))) self.assertEquals("xxxx2", gender_url("xxxx", filter_func=lambda x: x in ("xxxx", "xxxx1"))) class AppEngineAPITest(unittest.TestCase): def test_urlfetch(self): #response = urlfetch.fetch('http://www.google.com') #self.assertEquals(15, response.content.find('<html>')) #logging.info(response.content) pass <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- # discription: blog # author: dreampuf import sys, os, logging CURPATH = os.path.join(os.path.abspath(os.path.dirname(__file__))) sys.path.insert(0, os.path.join(CURPATH, "lib")) from google.appengine.api import memcache from google.appengine.ext.webapp import util import que from common import BlogHandler from blog_views import IndexHandler from blog_views import CategoryHandler from blog_views import ViewHandler from blog_views import CommentHandler def main(): application = que.WSGIApplication([("^/$", IndexHandler), ("^/category/(?P<category_key_name>.*)/$", CategoryHandler), ("^/comment/(?P<post_id>\d*)/$", CommentHandler), ("^/(?P<path>.*)$", ViewHandler) ]) util.run_wsgi_app(application) if __name__ == '__main__': main() <file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head profile="http://gmpg.org/xfn/11"> <title>{% if title %}{{ title }} | {% endif %}{{ blog_title }}</title> <link rel="shortcut icon" href="{{ baseurl }}/images/favicon.ico" /> {% for type, src in head_link %}{% if type == "css" %}<link rel="stylesheet" href="{{ baseurl }}{{ src }}" type="text/css" media="screen, projection" id="cssfile" /> {% else %}<script type="text/javascript" src="{{ baseurl }}{{ src }}"></script>{% endif %}{% endfor %} <style type="text/css"> #wrap{ margin:0 auto; padding:0; width:100%; background:url(/images/adminside-bg.gif) repeat-y left #f8f8f8;} #main{width: 100%; } #maincontent{ float:right; margin:0 0 0 -171px; padding:0; display:inline;width: 100%; } #maincontent .forFlow{ margin:0 0 0 171px; float: none; width: auto; } #sidebar{ float:left; margin:10px; padding:0; width:150px; display:inline; } </style> </head> <body> <div id="wrap"> <div id="header"> <div id="header-left"> <h1><a href="{{ baseurl }}/">{{ blog_title }}</a></h1> <div class="description">{{ blog_subtitle }}</div> </div> <div id="header-right"> <div class="layout"> </div> <div id="menu"> <li class="{% if is_home %}current_page_item{%else%}page_item{%endif%}"><a href="{{ baseurl }}/" title="{{ blog_title }}">首页</a></li> </div> </div> </div> <div id="main"> <div id="maincontent"><div class="forFlow"> {% block maincontent -%}{%- endblock %} </div></div> <div id="sidebar"> <ul id="sidebarul"> {% for i in sitebar %} <li class="widget widget_categories"> <h3 class="widgettitle">{{ i }}</h3> <ul> {% for j in sitebar[i] %} <li><a href="{{ baseurl }}{{ j[1] }}">{{ j[0] }}</a></li> {% endfor %} </ul> </li> {% endfor %} </ul> </div> </div> <div id="footer"> <div id="footer-wp"></div> <div id="footer-link"><p>Blog Engine <a rel="nofollow" href="http://www.macgoo.com" target="_blank">Banana</a> </p> {{ blog_footer }} </div> </div> </div> </body> </html><file_sep>#! /usr/bin/env python # -*- coding: utf-8 -*- # discription: test_lib # author: dreampuf import os, unittest, logging, time import string, random from google.appengine.ext import db from lib.model import BaseModel ## Test for BaseModel ####### class TempTable(BaseModel): tkey = db.IntegerProperty(default=0) value = db.StringProperty() create = db.DateTimeProperty(auto_now_add=True) class BaseModelTest(unittest.TestCase): def setUp(self): db.delete(TempTable.all().fetch(500)) #init data ls = [] for i in xrange(500): ls.append(TempTable(tkey=i, value=random.choice(string.lowercase))) db.put(ls) def dearDown(self): db.delete(TempTable.all().fetch(500)) logging.info("被执行拉") def testFetch(self): index = 1 ls = TempTable.fetch_page(index, 20) for n, i in enumerate(ls.data): self.assertEquals(i.tkey, n) ls, cursor = TempTable.cursorfetch(None) nls, ncursor = TempTable.cursorfetch(cursor, plen=500) nnls, nncursor = TempTable.cursorfetch(ncursor, plen=500) self.assertEquals(TempTable.fetch_page(10).data[0].tkey, 180) def testPut(self): befor = TempTable.total() i = TempTable(tkey=9527, value=random.choice(string.lowercase)) i.put() self.assertEquals(befor + 1, TempTable.total()) def testDelete(self): befor = TempTable.total() i = TempTable.fetch_page(1, 1) i.data[0].delete() self.assertEquals(befor - 1, TempTable.total()) <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- # discription: config # author: dreampuf import os, sys import logging from cache import memcache from model import _ConfigProperty class CommentStatus(object): DISENABLE = 0 ENABLE = 1 USERONLY = 2 NEEDCHECK = 4 class config(object): VERSION = 2.0 CURPATH = os.path.join(os.path.split(os.path.abspath(__file__))[0], "..") CHARSET = "utf-8" LANGUAGE = "zh-CN" APPID = os.environ["APPLICATION_ID"] OWNER = _ConfigProperty("OWNER", "<EMAIL>") BLOG_PATH = "/" BLOG_ADMIN_PATH = "/admin/" DOMAIN = "huangxin.im"#_ConfigProperty("DOMAIN", os.environ['HTTP_HOST']) #站点域名 TEMPLATE = _ConfigProperty("TEMPLATE", "iphonsta") POST_EDITOR = _ConfigProperty("POST_EDITOR", "") EDITOR_TYPE = ("html", "rest", "markdown", "bbcode") BASEURL = "http://%s" % (DOMAIN) ADMINURL = "%s%s" % (BASEURL, BLOG_ADMIN_PATH) TEMPLATEURL = "%s/template/%s" % (BASEURL, TEMPLATE) LOCAL_TIMEZONE = _ConfigProperty("LOCAL_TIMEZONE", 8) #时区 TITLE = _ConfigProperty("TITLE", "bana") #站点名称 SUBTITLE = _ConfigProperty("SUBTITLE", "an other blog") #站点简介 ENABLE_COMMENT = _ConfigProperty("ENABLE_COMMENT", True) #允许回复 COMMENT_NEEDLOGINED = _ConfigProperty("COMMENT_NEEDLOGINED", False) #回复需登录 DESCRIPTION = _ConfigProperty("DESCRIPTION", "this descript in feed") #FEED中的描述 DATE_FORMAT = _ConfigProperty("DATE_FORMAT", "%Y-%m-%d") DATETIME_FORMAT = _ConfigProperty("DATETIME_FORMAT", "%Y-%m-%d %H:%M:%S") DATEMINUTE_FORMAT = _ConfigProperty("DATEMINUTE_FORMAT", "%Y-%m-%d %H:%M") FEED_SRC = _ConfigProperty("FEED_SRC", "feed/") FEED_URL = "%s/%s" % ( BASEURL, FEED_SRC) FEED_NUMBER = _ConfigProperty("DIGIT_FEED_NUMBER_", 20) FEED_SUMMARY = _ConfigProperty("FEED_SUMMARY", False) FEED_COMMENT_COUNT = _ConfigProperty("FEED_COMMENT_COUNT", 5) HUB_SRC = _ConfigProperty("HUB_SRC", ["http://pubsubhubbub.appspot.com/"]) XML_RPC_ENDPOINT = _ConfigProperty("HUB_SRC", ['http://blogsearch.google.com/ping/RPC2', 'http://rpc.pingomatic.com/', 'http://ping.baidu.com/ping/RPC2']) INDEX_POST_COUNT = _ConfigProperty("INDEX_POST_COUNT", 10) INDEX_SUMMARY = _ConfigProperty("INDEX_SUMMARY", True) POST_PAGE_COUNT = _ConfigProperty("POST_PAGE_COUNT", 10) COMMENT_PAGE_COUNT = _ConfigProperty("COMMENT_PAGE_COUNT", 10) LAST_COMMENT_COUNT = _ConfigProperty("LAST_COMMENT_COUNT", 20) LAST_COMMENT_LENGTH = _ConfigProperty("LAST_COMMENT_LENGTH", 20) POST_CACHE_TIME = _ConfigProperty("POST_CACHE_TIME", 600) FEED_CACHE_TIME = _ConfigProperty("FEED_CACHE_TIME", 600) SITEMAP_CACHE_TIME = _ConfigProperty("SITEMAP_CACHE_TIME", 600) FOOTER_HTML = _ConfigProperty("FOOTER_HTML", "") HEAD_LINK = _ConfigProperty("HEAD_LINK", ["/js/common.js"]) POST_URL = _ConfigProperty("POST_URL", "%year%/%month%/%url%.html") COMMENT_STATUS = _ConfigProperty("COMMENT_STATUS", CommentStatus.ENABLE) RECAPTCHA_PUBLIC_KEY = _ConfigProperty("RECAPTCHA_PUBLIC_KEY","<KEY>") RECAPTCHA_PRIVATE_KEY = _ConfigProperty("RECAPTCHA_PRIVATE_KEY", "<KEY>") GOOGLE_ANALYTICS_ID = _ConfigProperty("GOOGLE_ANALYTICS_ID", "") config = config()
8f1aae9b3cf4b13b4897f7b101abc5fc4407e135
[ "Python", "HTML" ]
14
Python
dreampuf/bana
c08949803e2bc1e379b235a0901ab0683d4acb38
9db81bf77611a54b83fbd7cfa95393d81897a7ab
refs/heads/master
<file_sep>The Ceejay iOS app is your all-in-one application to contact and avail of the services by Ceejay, one of the famous technicians in Greenhills Shopping Center in San Juan City, Metro Manila, Philippines. FEATURES: * Ceejay's Facebook page for a one-click update on everything happening to Ceejay and his services, even on his personal life * Location of his shops in Greenhills Shopping Center and in Malolos City * Driving directions option to Ceejay's shops from user's current location * Sharing options to promote the app to popular social media sites and email * List of services that Ceejay offers to his clients or customers * Contact page to personally get in touch with Ceejay via phone, text and email Download the app now in the AppStore at http://www.appstore.com/ceejay. <file_sep>// // Constants.h // Ceejay // // Created by <NAME> on 10/18/12. // Copyright (c) 2012 <NAME>. All rights reserved. // #ifndef Ceejay_Constants_h #define Ceejay_Constants_h // Images #define kCeejayPhoto [UIImage imageNamed:@"ceejay_appicon@2x.png"] #define kBackgroundImage [UIImage imageNamed:@"cj_navbar_iPhone.png"] #define kNameBannerImage [UIImage imageNamed:@"cj_name_iPhone.png"] #define kCircleButtonImage [UIImage imageNamed:@"cj_circle_iPhone.png"] #define kTopButtonImage [UIImage imageNamed:@"1.png"] #define kUpperRightButtonImage [UIImage imageNamed:@"2.png"] #define kLowerRightButtonImage [UIImage imageNamed:@"3.png"] #define kLowerLeftButtonImage [UIImage imageNamed:@"4.png"] #define kUpperLeftButtonImage [UIImage imageNamed:@"5.png"] // Links #define kCeejayFacebookLink @"http://www.facebook.com/ceejay.spaxx" #define kCeejayAppleServicesFacebookLink @"https://www.facebook.com/CeeJayAppleServices" #define kCeejayLink [NSURL URLWithString:@"https://itunes.apple.com/us/app/ceejay/id590361528?ls=1&mt=8"] #define kWebPageLink1 @"http://sndeep.info/en" #define kWebPageLink2 @"http://iphonefrom.com/" #define kWebPageLink3 @"http://mofodox.me/jbstats" #define kWebPageLink4 @"http://s-url.ro/" // Coordinates #define kZoomLocationLatitude 14.735706 #define kZoomLocationLongitude 120.954666 #define kGreenhillsLatitude 14.602407 #define kGreenhillsLongitude 121.050536 #define kMalolosLatitude 14.856213 #define kMalolosLongitude 120.81167 #define kMaunladLatitude 14.842856 #define kMaunladLongitude 120.812855 // Annotations #define kGreenhillsMapTitle @"Greenhills Shop" #define kGreenhillsMapSubtitle @"2/F Greenhills Shopping Center beside EO Optical" #define kMalolosMapTitle @"Malolos - iPrint Shop" #define kMalolosSubtitle @"iPrint Catmon Road Malolos City, Bulacan" #define kMaunladTitle @"Malolos - Maunlad Mall Shop" #define kMaunladSubtitle @"Maunlad Mall Malolos City, Bulacan" // Sharing #define kPhone @"tel:09152127000" #define kTextMessage @"Ceejay, I used your iOS app to send you a message and I need your help." #define kPhoneNumber @"09152127000" #define kMailSubject @"Ceejay, HELP!" #define kEmailAddress @"<EMAIL>" #define kEmailMessage @"Ceejay, I used your iOS app to send you an email and I need your help!" #define kShareMessage @"Check out this free Ceejay iOS app from the AppStore!" // Errors #define kErrorFacebookMessage @"You can't post to Facebook right now, make sure your device has an internet connection and you have your Facebook account setup on your device." #define kErrorTwitterMessage @"You can't send a tweet right now, make sure your device has an internet connection and you have at least one Twitter account setup on your device." #define kErrorMessage @"Your device doesn't support the composer sheet" #define kErrorLocationServices @"Please turn ON Location Services for Ceejay in Settings." // Alerts & Action Sheets #define kOK @"OK" #define kError @"Error" #define kSorry @"Sorry" #define kLogin @"Login" #define kCancel @"Cancel" #define kLogout @"Logout" #define kDismiss @"Dismiss" #define kBlank @"" #define kAboutTitle @"About The Developer" #define kAboutMessage @"Appsaint by <NAME>\n\nEmail: <EMAIL>\nTwitter: @appsaint_ph" #define kLocationSelectorActionSheetTitle @"Shop Selector" #define kGreenhillsShop @"Greenhills" #define kMalolosShop @"Malolos - iPrint" #define kMaunladShop @"Malolos - Maunlad Mall" #define kPageSelectorActionSheetTitle @"Web Page Selector" #define kCeejayOcampo @"Ceejay Ocampo" #define kCeejayAppleServices @"Ceejay Apple Services" #define kWebPage1 @"SNDeepInfo" #define kWebPage2 @"iPhoneFrom" #define kWebPage3 @"JBStats" #define kWebPage4 @"IMEI" #define kPhoneCallErrorTitle @"Cannot Make Phone Call" #define kPhoneCallErrorMessage @"Making a phone call is not available." // Miscellaneous #define kFourInchDevice [UIScreen mainScreen].bounds.size.height == 568 #define kMapTitle @"Map" #define kSatelliteTitle @"Satellite" #endif
06776798a253f9133e4ea21bdf6929969d87be9e
[ "Markdown", "C" ]
2
Markdown
jaytrixz/Ceejay
7e8f7446647849d33da2ddc80c6ec4feaddc9912
05d38f5b5226fbf6f7c82048e5e5e636be551517
refs/heads/master
<repo_name>dmydry/constants<file_sep>/source/date.js "use strict"; import moment from "moment-config-trejgun"; export const timeZone = "Pacific/Chatham"; // +12:45, the most fucked up time zone export const date = new Date(); export const testDate = moment(date).tz(timeZone).startOf("hour").toDate(); export const startDate = moment(testDate).add(0, "h").toDate(); export const endDate = moment(testDate).add(1, "h").toDate(); export const untilDate = moment(testDate).add(14, "d").add(0, "h").toDate(); export const daysRunning = [0, 1, 2, 3, 4, 5, 6]; export const ISO_8601 = "YYYY-MM-DD\\THH:mm:ss\\Z"; export const googleFormat = "YYYYMMDD\\THHmmss\\Z"; export const dateFormat = "MMM-DD-YYYY"; export const timeFormat = "h:mm a";
7d9e1e05d12a48cbfc240eb0bd3f8a6e9e5d00df
[ "JavaScript" ]
1
JavaScript
dmydry/constants
480a66ad08315c27dc82272eb08e1d4316100f5d
0cee1c20e85ab9772f17b37e30fd9b3842085446
refs/heads/master
<repo_name>future4code/Cristiane-Rocha<file_sep>/semana10/astro-x/src/components/DetailsTrip/DetailsTripPrivate.js import React,{useEffect,useState} from 'react' import {useRequestApiWidthHeaders} from '../API/Api' import {useHistory,useParams} from 'react-router-dom' import {ItemsDetails,CandItem,TitleContent,ButtonDiv,DetailsDiv,ButtonAprove,ButtonRight,NameItem,CanditateItem,CandidatesDiv,TitleColumn,TitleContentTrips,Text} from '../../assets/styles/Styles' import axios from 'axios' const DetailsTrip = () => { const pathParams = useParams() const myTripsDetails = useRequestApiWidthHeaders(`https://us-central1-labenu-apis.cloudfunctions.net/labeX/cristiane-rocha/trip/${pathParams.id}`) const token = localStorage.getItem('token') const history = useHistory() const mostrar = () => { console.log(myTripsDetails.candidates) } const logout = () => { localStorage.removeItem('token') history.push('/login') } const aproveCandidate = (id) => { const body = {"approve": true} axios.put(`https://us-central1-labenu-apis.cloudfunctions.net/labeX/cristiane-rocha/trips/${pathParams.id}/candidates/${id}/decide`,body,{ headers: { auth:token } }) .then((res) => { alert("Candidato Aprovado !") }) .catch((err) => { console.log(err.message) }) } const candidates = myTripsDetails && myTripsDetails.candidates const deleteTrip = () => { axios.delete(`https://us-central1-labenu-apis.cloudfunctions.net/labeX/cristiane-rocha/trips/${pathParams.id}`) .then((res) => { alert("Viagem apagada!") history.push('/trips/listPrivate') }) .catch((err) => { console.log(err) }) } return( <div> <TitleContent>Viagem para {myTripsDetails.name}</TitleContent> <ItemsDetails> <DetailsDiv> <p>Destino:</p> <h3>{myTripsDetails.planet}</h3> </DetailsDiv> <DetailsDiv> <p>Data da Partida:</p> <h3>{myTripsDetails.date}</h3> </DetailsDiv> <DetailsDiv> <p>Duração:</p> <h3>{myTripsDetails.durationInDays} dias</h3> </DetailsDiv> </ItemsDetails> <div> <div> <TitleContentTrips><div><ButtonRight red onClick={logout}>sair</ButtonRight><ButtonRight onClick={deleteTrip}><i class="fas fa-trash-alt"></i> Apagar Viagem</ButtonRight></div> Candidatos ↴</TitleContentTrips> </div> <div> {candidates != undefined ? candidates.map((cand) => { return ( <CandidatesDiv key={cand.id}> <CanditateItem> <NameItem>Nome: </NameItem> <CandItem>{cand.name}</CandItem> </CanditateItem> <CanditateItem> <NameItem>Profissão: </NameItem> <CandItem>{cand.profession}</CandItem> </CanditateItem> <CanditateItem> <NameItem>Idade: </NameItem> <CandItem>{cand.age}</CandItem> </CanditateItem> <CanditateItem> <NameItem>País: </NameItem> <CandItem>{cand.country}</CandItem> </CanditateItem> <CanditateItem> <NameItem>Porque deveria ir: </NameItem> <CandItem>{cand.applicationText}</CandItem> </CanditateItem> <ButtonDiv> <ButtonAprove onClick={() => aproveCandidate(cand.id)} >Aprovar</ButtonAprove> </ButtonDiv> </CandidatesDiv> ) }) : ''} </div> </div> </div> ) } export default DetailsTrip<file_sep>/semana5/insta4/src/components/PopupCompartilhar/PopupCompartilhar.js import React from 'react' import './PopupCompartilhar.css' import Whatsapp from '../../img/whatsapp.svg' import Instagram from '../../img/instagram.svg' import Twitter from '../../img/twitter.svg' export function PopupCompartilhar(props){ return <div className={props.display}> <img src={Whatsapp} onClick={props.onClickWhats}/> <img src={Instagram} onClick={props.onClickInsta}/> <img src={Twitter} onClick={props.onClickTwitter}/> </div> }<file_sep>/semana9/astromatch/src/components/Container/Container.js import React, {useState,useEffect} from 'react' import NavBar from '../NavBar/NavBar' import Person from '../Person/Person' import FooterContainer from '../FooterContainer/FooterContainer' import IsMatch from '../IsMatch/IsMatch' import {FooterMach} from '../FooterContainer/FooterContainer' import Matchs from '../Matchs/Matchs' import Styled from 'styled-components' import axios from 'axios' //Infos API const urlAPI = 'https://us-central1-missao-newton.cloudfunctions.net/astroMatch/:cristiane-rocha/person' const urlAPIMatch = 'https://us-central1-missao-newton.cloudfunctions.net/astroMatch/cristiane-rocha/choose-person' const urlApiShowMatchs = 'https://us-central1-missao-newton.cloudfunctions.net/astroMatch/cristiane-rocha/matches' const urlApiClear = 'https://us-central1-missao-newton.cloudfunctions.net/astroMatch/cristiane-rocha/clear' const headers = { headers:{ aluno:'cristiane-rocha' } } const MainContainer = Styled.section` width:360px; height:auto; display:flex; flex-direction:column; justify-content:space-between; align-items:center; margin:10px auto; border:1px solid #ddd; border-radius:4px; box-shadow:2px 2px 5px #ccc; position:relative; `; //Componente function Container(){ //States const [pessoa,setPessoa] = useState('') const [showMatch,setShowMatch] = useState(false) const [matchs,setMatchs] = useState([]) const [matchOk,setMatchOk] = useState(false) const [show,setShow] = useState(false) useEffect(() => { mostraPessoa() },[]) //Passa pra próxima pessoa const mostraPessoa = () => { axios.get(urlAPI,headers).then((res) => { setPessoa(res.data.profile) setMatchOk(false) }).catch((err) => { console.log("Erro -> ",err) }) setMatchOk(false) } //Da Match const escolhePessoa = (id) => { const body = { id: id, choice: true } axios.post(urlAPIMatch,body,headers).then((res) => { if(res.data.isMatch === true){ setMatchOk(true) }else{ mostraPessoa() } }).catch((err) => { console.log("Erro -> ",err) }) } //Mostra Matchs const exibeMatch = () => { setShowMatch(true) axios.get(urlApiShowMatchs,headers).then((res) => { setMatchs(res.data.matches) if(res.data.matches.length > 0){ setShow(true) } }).catch((err) => { console.log("Erro -> ",err) }) setMatchOk(false) } //Fecha matchs const hiddenMatch = () => { setShowMatch(false) } let match = <Person pessoa={pessoa}/> let footer = <FooterContainer mostraPessoa={mostraPessoa} escolhePessoa={escolhePessoa} pessoaId={pessoa.id} /> if(showMatch === true){ match = <Matchs matchs={matchs} show={show} hiddenMatch={hiddenMatch}/> footer = <FooterMach/> } //Apagar matchs const clearMatchs = () => { axios.put(urlApiClear,headers).then((res) => { setMatchs([]) setShow(false) }).catch((err) => { console.log("Erro -> ",err) }) } let deuMatch = '' if(matchOk === true){ deuMatch = <IsMatch mostraPessoa={mostraPessoa} exibeMatch={exibeMatch} /> } return( <MainContainer> <NavBar exibeMatch={exibeMatch} hiddenMatch={hiddenMatch} showMatch={showMatch} clearMatchs={clearMatchs} /> {deuMatch} {match} {footer} </MainContainer> ) } export default Container<file_sep>/semana10/astro-x/src/components/Forms/FormCreateTrip.js import React,{useState} from 'react' import {Formulario,ButtonRight,Label,Input,Textarea} from '../../assets/styles/Styles' import {useForm} from '../hooks/useForm' import axios from 'axios' import {useHistory} from 'react-router-dom' const FormCreateTrip = (props) => { const [form,onChange] = useForm({name:'',planet:'',date:'',durationInDays:'',description:''}) const history = useHistory() const createTrip = (event) => { const body = { name: form.name, planet: form.planet, date: form.date, description: form.description, durationInDays: form.durationInDays } const header = { headers: { auth: localStorage.getItem('token') } } axios.post('https://us-central1-labenu-apis.cloudfunctions.net/labeX/cristiane-rocha/trips',body,header) .then((res) => { alert("Viagem Criada com sucesso !") history.push('/trips/listPrivate') }) .catch((err) => { console.log(err.message) }) event.preventDefault() } return( <Formulario onSubmit={createTrip}> <Label>Nome: </Label> <Input value={form.name} name={'name'} onChange={onChange} type="text"/> <Label>Destino: </Label> <Input value={form.planet} name={'planet'} onChange={onChange} type="text"/> <Label>Data: </Label> <Input value={form.date} name={'date'} onChange={onChange} type="date"/> <Label>Duração em dias: </Label> <Input value={form.durationInDays} name={'durationInDays'} onChange={onChange} type="number"/> <Label>Descrição: </Label> <Textarea value={form.description} name={'description'} onChange={onChange}></Textarea> <ButtonRight>Criar</ButtonRight> </Formulario> ) } export default FormCreateTrip<file_sep>/semana7/labeusers/labe-users/src/components/Usuarios/DetalheUsuario.js import React from 'react' import Styled from 'styled-components' import {DivDetalhes} from '../Usuarios/Estilos/StyleDetalhesUsuario' import {H3Detalhes} from '../Usuarios/Estilos/StyleDetalhesUsuario' import {DetalhesItem} from '../Usuarios/Estilos/StyleDetalhesUsuario' import {PDetalhes} from '../Usuarios/Estilos/StyleDetalhesUsuario' import {InputDetalhes} from '../Usuarios/Estilos/StyleDetalhesUsuario' import {SpanDetalhes} from '../Usuarios/Estilos/StyleDetalhesUsuario' import {ButtonDetalhesSair} from '../Usuarios/Estilos/StyleDetalhesUsuario' import {ButtonDetalhesDelete} from '../Usuarios/Estilos/StyleDetalhesUsuario' import {ButtonsDetalhes} from '../Usuarios/Estilos/StyleDetalhesUsuario' import {ButtonsEditarSalvar} from '../Usuarios/Estilos/StyleDetalhesUsuario' import {SpanEditar} from '../Usuarios/Estilos/StyleDetalhesUsuario' import {BotaoSalvar} from '../Usuarios/Estilos/StyleDetalhesUsuario' import {BotaoCancelar} from '../Usuarios/Estilos/StyleDetalhesUsuario' class DetalheUsuario extends React.Component{ render(){ let botaoEditarSalvar = '' let nomeUsuario = '' let emailUsuario = '' let cancelarEditar = '' if(this.props.usuarioEditar === false){ botaoEditarSalvar = <BotaoSalvar onClick={this.props.editarUsuario}> Editar </BotaoSalvar> nomeUsuario = <SpanDetalhes>{this.props.nomeDoUsuario}</SpanDetalhes> emailUsuario = <SpanDetalhes>{this.props.emailDoUsuario}</SpanDetalhes> }else{ botaoEditarSalvar = <BotaoSalvar onClick={this.props.salvarUsuario}> Salvar </BotaoSalvar> cancelarEditar = <BotaoCancelar onClick={this.props.cancelarEditar}> Cancelar </BotaoCancelar> nomeUsuario = <InputDetalhes value={this.props.nomeDoUsuario} onChange={this.props.mudarNome} /> emailUsuario = <InputDetalhes value={this.props.emailDoUsuario} onChange={this.props.mudarEmail} /> } return( <DivDetalhes> <H3Detalhes>Detalhes do Usuário </H3Detalhes> <PDetalhes> <DetalhesItem>Nome: </DetalhesItem> {nomeUsuario} </PDetalhes> <PDetalhes> <DetalhesItem>Email: </DetalhesItem> {emailUsuario} </PDetalhes> <ButtonsEditarSalvar> {cancelarEditar} {botaoEditarSalvar} </ButtonsEditarSalvar> <ButtonsDetalhes> <ButtonDetalhesDelete onClick={this.props.botaoDeletar}>Deletar Usuário </ButtonDetalhesDelete> <ButtonDetalhesSair onClick={this.props.fecharDetalhes}> Voltar </ButtonDetalhesSair> </ButtonsDetalhes> </DivDetalhes> ) } } export default DetalheUsuario<file_sep>/semana6/form-cris/src/Components/FimFormulario.js import React from 'react' import styled from "styled-components" const FimForm = styled.div` display:flex; justify-content:center; align-items:center; flex-direction:column; `; export class FimFormulario extends React.Component { render(){ return( <FimForm> <h1>O formulário Acabou!</h1> <p>Muito obrigado por participar! Entraremos em contato</p> </FimForm> ) } }<file_sep>/semana7/labefy/labefy/src/components/AddTracks/AddTracks.js import React from 'react' class AddTracks extends React.Component{ render(){ let exibeAddMusica = '' if(this.props.adcionaTracks === true){ exibeAddMusica = <div><input onChange={this.props.alteraNome} value={this.props.nomeMusica} placeholder="Nome da Musica"/><input onChange={this.props.alteraArtista} value={this.props.artistaMusica} placeholder="Nome do Artista ou Banda"/><input onChange={this.props.alteraUrl} value={this.props.urlMusica} placeholder="URL da Musica"/><button onClick={this.props.salvaMusica}>Salvar</button></div> } return( <div> {exibeAddMusica} </div> ) } } export default AddTracks<file_sep>/semana7/labeusers/labe-users/src/components/Usuarios/Busca.js import React from 'react' import Styled from 'styled-components' const CampoBusca = Styled.div` width:50%; height:60px; margin:10px auto; display:flex; justify-content:center; align-items:center; `; const InputBusca = Styled.input` width:calc(50% - 10px); height:30px; background:transparent; color:#888; border:1px solid #888; border-radius:10px; font-size:18px; margin-right:10px; padding-left:10px; &:focus{ outline:none; } `; const ButtonBusca = Styled.button` background: #888; color:#fff; width:20%; height:35px; font-size:18px; font-weight:700; border:1px solid #888; border-radius:10px; cursor:pointer; &:focus{ outline:none; } &:hover{ background:#889; } `; class Busca extends React.Component{ render(){ return( <CampoBusca> <InputBusca onChange={this.props.inputControladoBusca} placeholder="Buscar por nome" value={this.props.nomeABuscar}/> <ButtonBusca onClick={this.props.buscaNome} >Buscar</ButtonBusca> </CampoBusca> ) } } export default Busca <file_sep>/semana5/labedin/src/App.js import React from 'react'; import './App.css'; import CardGrande from './components/CardGrande/CardGrande'; import ImagemButton from './components/ImagemButton/ImagemButton'; import CardPequeno from './components/CardPequeno/CardPequeno' function App() { return ( <div className="App"> <div className="page-section-container"> <h2>Dados pessoais</h2> <CardGrande imagem="https://scontent.fjoi3-1.fna.fbcdn.net/v/t1.0-9/67095152_2107283966240583_2905899199444811776_o.jpg?_nc_cat=101&_nc_sid=174925&_nc_ohc=9c3qPCmR5bIAX8hSmjc&_nc_ht=scontent.fjoi3-1.fna&oh=5d99ea389f1eef3522fabf837c570d12&oe=5FAE9271" nome="<NAME>" descricao="Me chamo Cristiane <NAME>, moro em Rio Negrinho SC, sou mãe e esposa, e Desenvolvedora Full Stack em formação. Possuo conhecimento em HTML e CSS, e como linguagem de programação, Javascript e PHP." /> <ImagemButton imagem="https://image.flaticon.com/icons/png/512/117/117472.png" texto="Ver mais" /> </div> <div className="page-section-container"> <CardPequeno image="https://ecommercedesucesso.com.br/wp-content/uploads/2018/02/Como-criar-um-email-personalizado-2.png" adress="<EMAIL>" option="Email: " /> <CardPequeno image="https://www.compass.adm.br/wp-content/uploads/2017/07/endereco-fiscal.png" adress="Rua das Hortencias,121,Industrial Norte, Rio Negrinho SC" option="Endereço: " /> </div> <h2>Alguns projetos que participei ou desenvolvi!</h2> <div className="page-section-container"> <CardGrande imagem="https://image.freepik.com/vetores-gratis/campanha-de-icone-de-cartao-bancario-de-credito-de-debito-transacao-sem-dinheiro-para-o-modelo-de-pouso-de-pagina-inicial-do-site-web-com-estilo-cartoon_197170-398.jpg" nome="Site Cashless Transation" descricao="Esta imagem eu retirei da internet para usar de exemplo na construção deste layout" /> <CardGrande imagem="https://expressodelivery.com.br/assets/img/aplicativo-pizzaria-delivery.png" nome="Express Delivery App" descricao="Esta imagem eu retirei da internet para usar de exemplo na construção deste layout" /> <CardGrande imagem="https://www.jivochat.com.br/blog/assets/images/compressed/blog2/modelos-de-sites/image_10-modelos-de-sites-futurio.jpg" nome="Site Futurio" descricao="Esta imagem eu retirei da internet para usar de exemplo na construção deste layout" /> </div> <div className="page-section-container"> <h2>Experiências profissionais</h2> <CardGrande imagem="https://s3.amazonaws.com/future4.com.br/static/headf4-c492117ca2373dc85ca81bf715b3dc2a.png" nome="Labenu" descricao="Formando desenvolvedores para o mercado de trabalho!" /> <CardGrande imagem="https://imagens.canaltech.com.br/empresas/4418.400.jpg" nome="NASA" descricao="Apontando defeitos." /> </div> <div className="page-section-container"> <h2>Minhas redes sociais</h2> <ImagemButton imagem="https://d2v9ipibika81v.cloudfront.net/uploads/sites/261/2017/01/facebook-logo-3.png" texto="Facebook" /> <ImagemButton imagem="https://logodownload.org/wp-content/uploads/2014/09/twitter-logo-1-1.png" texto="Twitter" /> </div> </div> ); } export default App; <file_sep>/semana3/blackjack/desafio.js /** * EXEMPLO DE UTILIZAÇÃO DA 'comprarCarta' * * const carta = comprarCarta(); // Sorteia uma carta. Por exemplo, o rei de ouros console.log(carta.texto) // imprime o texto da carta. Exemplo: "K♦️" (indica "K" de ouros) console.log(carta.valor) // imprime o valor da carta (um número). Exemplo: 10 (dado que "K" vale 10) * * * */ console.log("Bem vindo ao jogo de Blackjack!") const conf = confirm( "Quer iniciar uma nova rodada?") if(conf){ //Cartas do usuário let cartasUsuario = [] cartasUsuario[0] = comprarCarta() cartasUsuario[1] = comprarCarta() //Sorteia a carta novamente se forem dois ases while((cartasUsuario[0].valor === 11) && (cartasUsuario[1] === 11)){ cartasUsuario[0] = comprarCarta() cartasUsuario[1] = comprarCarta() } //Soma os pontos iniciais do Usuario let pontosUsuario = cartasUsuario[0].valor + cartasUsuario[1].valor //Cartas do Computador let cartasComputador = [] cartasComputador[0] = comprarCarta() cartasComputador[1] = comprarCarta() //Sorteia a carta novamente se forem dois ases while((cartasComputador[0].valor === 11) && (cartasComputador[1] === 11)){ cartasComputador[0] = comprarCarta() cartasComputador[1] = comprarCarta() } //Soma os pontos iniciais do computador let pontosComputador = cartasComputador[0].valor + cartasComputador[1].valor //Array para armazenar os textos das cartas let textoCartaUsuario = [] textoCartaUsuario.push(cartasUsuario[0].texto) textoCartaUsuario.push(cartasUsuario[1].texto) let textoCartaComputador = [] textoCartaComputador.push(cartasComputador[0].texto) textoCartaComputador.push(cartasComputador[1].texto) //Pergunta se deseja comprar outra carta let comprar = confirm(`Suas cartas são ${textoCartaUsuario}. A carta revelada do computador é ${textoCartaComputador[0]}.Deseja comprar mais uma carta?`) //Variaveis para contagens nos while let indice = 1 let indice2 = 1 //Loop para compra das cartas do Usuario while((comprar) && (pontosUsuario <= 21)){ indice ++ cartasUsuario[indice] = comprarCarta() textoCartaUsuario.push(cartasUsuario[indice].texto) comprar = confirm(`Suas cartas são ${textoCartaUsuario}. A carta revelada do computador é ${cartasComputador[0].texto}.Deseja comprar mais uma carta?`) pontosUsuario = pontosUsuario + cartasUsuario[indice].valor } //Verificação dos pontos if((pontosUsuario>21) && (pontosComputador<=21)){ alert(`Suas cartas são ${textoCartaUsuario}. Sua pontuação é ${pontosUsuario}. As cartas do computador são ${textoCartaComputador}.A pontuação do computador é ${pontosComputador} !! O computador ganhou !! `) }else if((pontosUsuario<=21) && (pontosComputador<=21) ){ while(pontosComputador<=pontosUsuario){ indice2 ++ cartasComputador[indice2] = comprarCarta() textoCartaComputador.push(cartasComputador[indice2].texto) alert("Cartas do Computador" + textoCartaComputador) pontosComputador = pontosComputador + cartasComputador[indice2].valor } //Se o computador Ganhar if((pontosComputador>pontosUsuario)&&(pontosComputador<=21)){ alert(`Suas cartas são ${textoCartaUsuario}. Sua pontuação é ${pontosUsuario}. As cartas do computador são ${textoCartaComputador}.A pontuação do computador é ${pontosComputador} !! O computador ganhou !! `) //Se o usuario ganhar }else if(((pontosComputador<pontosUsuario)&&(pontosComputador<=21))||(pontosComputador>21)){ alert(`Suas cartas são ${textoCartaUsuario}. Sua pontuação é ${pontosUsuario}. As cartas do computador são ${textoCartaComputador}.A pontuação do computador é ${pontosComputador} !! Você ganhou !! `) } }else{ alert(`Suas cartas são ${textoCartaUsuario}. Sua pontuação é ${pontosUsuario}. As cartas do computador são ${textoCartaComputador}.A pontuação do computador é ${pontosComputador} !! O jogo acabou e ninguém ganhou !! `) } }<file_sep>/semana5/labedin/src/components/CardPequeno/CardPequeno.js import React from 'react'; import './CardPequeno.css' function CardPequeno(props){ return( <div className="littlecard-container"> <div> <img src={ props.image }/> <p><span>{props.option}</span>{props.adress}</p> </div> </div> ) } export default CardPequeno;<file_sep>/semana7/labeusers/labe-users/src/components/Usuarios/Estilos/StyleUsuario.js import React from 'react' import Styled from 'styled-components' import UsuarioImg from '../../../img/usuarios.jpg' export const UsuarioDiv = Styled.div` width: 100vw; height:100vh; background-image: url(${UsuarioImg}); background-size:cover; background-repeat:no-repeat; display:flex; flex-direction: column; justify-content:flex-start; align-items:center `; export const UsuarioTabela = Styled.div` width:90%; height:auto; display:block; position:relative; `; export const UsuarioHead = Styled.div` width:100%; height:40px; display:flex; justify-content:space-around; align-items:center; position:relative; `; export const UsuarioHeadCol1 = Styled.div` background:#888; border: 1px solid #888; text-transform:uppercase; color: #fff; width:calc(68% - 20px); height:100%; display:flex; align-items:center; padding: 0 10px; justify-content:space-between; `; export const UsuarioHeadCol2 = Styled.div` background:#888; border: 1px solid #888; text-transform:uppercase; color: #fff; width:28%; height:100%; display:flex; align-items:center; justify-content:center; `; export const UsuarioTbody = Styled.div` width:100%; `; export const UsuarioTr = Styled.div` width:100%; height:40px; display:flex; justify-content:space-around; align-items:center; position:relative; `; export const UsuarioTh1 = Styled.div` border: 1px solid #888; text-transform:uppercase; color: #888; width:calc(68% - 20px); height:100%; display:flex; align-items:center; justify-content:space-between; padding: 0 10px; background:#fff; `; export const UsuarioTh2 = Styled.div` border: 1px solid #888; text-transform:uppercase; color: #888; width:28%; height:100%; display:flex; align-items:center; justify-content:center; background:#fff; `; export const UsuarioDeleteButton = Styled.button` background:transparent; border:none; text-transform:uppercase; color:red; font-size:25px; cursor:pointer; &:focus{ outline:none; } &:hover{ color:orange; } `; export const UsuarioH2 = Styled.h2` color: #888; text-transform:uppercase; text-align:center; padding:20px 0; font-size:30px; `; export const UsuariosCenter = Styled.div` background:#ffffff90; margin-top:20px; box-shadow: 2px 2px 5px #888; width:70%; display:flex; flex-direction:column; justify-content:center; align-items:center; padding-bottom:30px; `; export const UsuarioSpan = Styled.span` color: #2aaa7e; font-weight:700; font-size:20px; cursor:pointer; text-align:center; &:hover{ color:#17efa4; } `; export const ButtonVoltar = Styled.button` background-color: #17efa4; color: #fff; text-transform:uppercase; font-weight:800; height:40px; border-radius:10px; border:none; width:35%; margin: 10px auto; display:block; cursor:pointer; transition: .3s ease-in-out; &:hover{ background:#2aaa7e; transition: .3s ease-in-out; } &:focus{ outline:none; } `; <file_sep>/semana7/labefy/labefy/src/components/AddPlaylist/AddPlaylist.js import React from 'react' import {TitleAdd,DivAdd,InputAdd,InputsDiv,DivAviso} from './StyleAdd' import {Button} from '@material-ui/core' class AddPlaylist extends React.Component{ render(){ let addPlay = '' if(this.props.openAddPlaylists === true){ addPlay = <InputsDiv> <InputAdd placeholder='Digite o nome da sua playlist' value={this.props.playlistCriada} onChange={this.props.onChangeCriaPlaylist}/> <Button color='primary' variant='contained' onClick={this.props.addPlaylist}>Salvar</Button> </InputsDiv> }else{ addPlay = <DivAviso> <h3>Playlist salva com sucesso !</h3> <Button color='primary' variant='contained' onClick={this.props.addMais}>Adcionar Mais </Button> </DivAviso> } return( <DivAdd> <TitleAdd>Adcione Playlists a sua conta </TitleAdd> {addPlay} </DivAdd> ) } } export default AddPlaylist<file_sep>/semana4/funcoes-de-array/index.js let arrDespesas = [] imprimirDespesas(arrDespesas) imprimirExtrato() // PRIMEIRO function imprimirDespesas(despesas){ let divDespesas = document.getElementById('despesas') divDespesas.innerHTML = '<p><ul>Despesas Detalhadas</ul></p>' // IMPLEMENTAÇÃO despesas.forEach((despesa) => { divDespesas.innerHTML += `<li>Valor: ${despesa.valor} | Tipo: ${despesa.tipo} | Descrição: ${despesa.descricao}</li>` }) } //FIM DA IMPLEMENTAÇÃO // SEGUNDO function imprimirExtrato(){ let divExtrato = document.getElementById('extrato') let gastoTotal = 0 let gastoAlimentacao = 0 let gastoUtilidades = 0 let gastoViagem = 0 // IMPLEMENTAÇÃO arrDespesas.forEach((desp) => { if(desp.tipo === "alimentação"){ gastoAlimentacao += desp.valor }else if(desp.tipo === "utilidades"){ gastoUtilidades += desp.valor }else if(desp.tipo === "viagem"){ gastoViagem += desp.valor } }) //Desafio 03 gastoTotal = arrDespesas.reduce(function(soma, desp){ return soma + desp.valor; }, 0); // FIM DA IMPLEMENTAÇÃO divExtrato.innerHTML = `<p>Extrato: Gasto Total: R$${gastoTotal} | Alimentação: R$${gastoAlimentacao} | Utilidades: R$${gastoUtilidades} | Viagem: R$${gastoViagem}</p>` } function limparFiltros() { document.getElementById('tipoFiltro').value = "" document.getElementById('valorFiltroMin').value = "" document.getElementById('valorFiltroMax').value = "" } function adicionarDespesa(){ let valorCdt = document.getElementById('valorCadastro') let tipoCtd = document.getElementById('tipoCadastro') let descricaoCtd = document.getElementById('descricaoCadastro') if(validarValor(valorCdt) && validarTipo(tipoCtd) && validarDescricao(descricaoCtd)){ let novaDespesa = { valor: Number(valorCdt.value), tipo: tipoCtd.value, descricao: descricaoCtd.value, } arrDespesas.push(novaDespesa) valorCdt.value = "" tipoCtd.value = "" descricaoCtd.value = "" limparFiltros() imprimirDespesas(arrDespesas) imprimirExtrato(arrDespesas) } else { alert("`Faltou algum valor ou algum valor é um número negativo`") } } // TERCEIRO function filtrarDespesas(){ let tipoFiltro = document.getElementById('tipoFiltro').value let valorMin = Number(document.getElementById('valorFiltroMin').value) let valorMax = Number(document.getElementById('valorFiltroMax').value) //Desafio 01 if(((tipoFiltro != "") && (valorMin != "") && (valorMax != "")) && (valorMin < valorMax) && ((valorMin > 0) && (valorMax > 0)) ){ let despesasFiltradas = arrDespesas.filter((desp) => { if(desp.tipo === tipoFiltro && desp.valor >= valorMin && desp.valor <= valorMax){ return true } return false }) imprimirDespesas(despesasFiltradas) }else { alert("`Faltou algum valor, ou o valor mínimo que você digitou é maior que o maximo digitad ou algum valor é um número negativo`") } } // FunÇoes que fazem validaÇoes dos inputs de criaÇao de despesas // NÃO SE PREOCUPEM EM ENTENDER ESSAS FUNÇÕES function validarValor(valor){ if(valor.value.length > 0 && parseInt(valor.value) > 0){ return true } return false } function validarTipo(tipo){ if(tipo.value !== ""){ return true } return false } function validarDescricao(texto){ if(texto.value.replace(/ /g,"").length !== 0){ return true } return false } //Desafio 02 function organiza(){ arrDespesas.sort(function(a, b) { return a.valor - b.valor; }); let divDespesas = document.getElementById('despesas') divDespesas.innerHTML = '<p><ul>Despesas Detalhadas</ul></p>' let ordermMaior = arrDespesas.reverse() ordermMaior.forEach((despesa) => { divDespesas.innerHTML += `<li>Valor: ${despesa.valor} | Tipo: ${despesa.tipo} | Descrição: ${despesa.descricao}</li>` }) }<file_sep>/semana6/form-cris/src/App.js import React from 'react'; import logo from './logo.svg'; import './App.css'; import {InicioFormulario} from './Components/InicioFormulario' function App() { return ( <InicioFormulario/> ); } export default App; <file_sep>/semana7/labefy/labefy/src/components/Main/Main.js import React from 'react'; import AddPlaylist from '../AddPlaylist/AddPlaylist' import axios from 'axios' import ListaDePlaylists from '../ListaDePlaylists/ListaDePlaylists' import AddTracks from '../AddTracks/AddTracks' import DetalhesMusica from '../DetalhesMusica/DetalhesMusica' import AppBar from '../AppBar/AppBar' const urlApi = "https://us-central1-labenu-apis.cloudfunctions.net/labefy/playlists" const apiConfig = { headers:{ Authorization:'<PASSWORD>', } } class Main extends React.Component{ state = { playlistCriada: '', playlistsCriadas:[], adcionaTracks:false, nomeMusica:'', artistaMusica:'', urlMusica:'', musicaSalva:'', idMusica:'', detalhesDaMusica:[], openAddPlaylist:false, openViewPlaylist:false, openAddPlaylists:true } //onChange cria playlist onChangeCriaPlaylist = (event) => { this.setState({playlistCriada:event.target.value}) } //Adciona Playlist addPlaylist = () => { let body = { name: this.state.playlistCriada } axios.post(urlApi,body,apiConfig).then((resposta) => { console.log(resposta.data) this.setState({openAddPlaylists:false,playlistCriada:''}) }).catch((error) => { console.log(error) }) } //Exibe Playlists componentDidMount = () => { axios.get(urlApi,apiConfig).then((resposta) => { console.log(resposta.data) this.setState({playlistsCriadas:resposta.data.result.list}) }).catch((error) => { console.log(error) }) } //Deleta Playlist deletePlaylist = (id) => { if(window.confirm("Tem certeza que deseja apagar esta playlist? ")){ axios.delete (`${urlApi}/${id}`,{ headers:{ Authorization:'cri<PASSWORD>', playlistId:id } }).then((resposta) => { console.log(resposta.data) }).catch((error) => { console.log(error) }) } } //Abrir detalhes de cada playlist detalhesPlaylist = (id) => { axios.get (`${urlApi}/${id}/tracks`,{ headers:{ Authorization:'cri<PASSWORD>', playlistId:id } }).then((resposta) => { this.setState({detalhesDaMusica:resposta.data.result.tracks}) console.log(resposta.data.result.tracks) this.setState({idMusica:id}) }).catch((error) => { console.log(error) }) console.log(this.state.detalhesDaMusica) } //Atualiza Playlist apos alterações componentDidUpdate = (id) => { axios.get(urlApi,apiConfig).then((resposta) => { this.setState({playlistsCriadas:resposta.data.result.list,detalhesDaMusica:this.state.detalhesDaMusica}) }).catch((error) => { console.log(error) }) } //Adcionar musica a uma playlist addMusicasPlaylist = (id) => { this.setState({ adcionaTracks:!this.state.adcionaTracks, idMusica:id }) } //Onchange inputs adciona Musica alteraNome = (event) => { this.setState({nomeMusica:event.target.value}) } alteraArtista = (event) => { this.setState({artistaMusica:event.target.value}) } alteraUrl = (event) => { this.setState({urlMusica:event.target.value}) } //Salva Musica salvaMusica = () => { const body = { name: this.state.nomeMusica, artist: this.state.artistaMusica, url: this.state.urlMusica } axios.post (`${urlApi}/${this.state.idMusica}/tracks`,body,{ headers:{ Authorization:'cristiane-rocha-dumont', playlistId:this.state.idMusica } }).then((resposta) => { alert('Musica Salva com sucesso !') this.setState({adcionaTracks:false}) console.log(resposta.data) }).catch((error) => { console.log(error) }) } deletarMusica = (id) => { axios.delete(`https://us-central1-labenu-apis.cloudfunctions.net/labefy/playlists/${this.state.idMusica}/tracks/${id}`,{ headers:{ Authorization:'cristiane-rocha-dumont', trackId:id, playlistId:this.state.idMusica, } }).then((resposta) => { this.setState({detalhesDaMusica:this.state.detalhesDaMusica}) console.log(resposta.data) }).catch((error) => { console.log(error) console.log(this.state.idMusica) }) } //Abrir Paginas openAddPlaylist = () => { this.setState({openAddPlaylist:true,openViewPlaylist:false}) } openViewPlaylist = () => { console.log("Aqui") this.setState({openViewPlaylist:true,openAddPlaylist:false}) } //Adcionar mais Playlist addMais = () => { this.setState({openAddPlaylists:true}) } render(){ let addPlays = '' let viewPlays = '' if(this.state.openAddPlaylist === true){ addPlays = <AddPlaylist playlistCriada={this.state.playlistCriada} onChangeCriaPlaylist={this.onChangeCriaPlaylist} addPlaylist={this.addPlaylist} openAddPlaylists={this.state.openAddPlaylists} openViewPlaylist={this.openViewPlaylist} addMais={this.addMais} /> } if(this.state.openViewPlaylist === true){ viewPlays = <ListaDePlaylists exibePlaylists={this.state.playlistsCriadas} deletePlaylist={this.deletePlaylist} detalhesPlaylist={this.detalhesPlaylist} addMusicasPlaylist={this.addMusicasPlaylist} /> } return ( <div> <AppBar openViewPlaylist={this.openViewPlaylist} openAddPlaylist={this.openAddPlaylist} /> {addPlays} <DetalhesMusica nome={this.state.detalhesDaMusica.name} artista={this.state.detalhesDaMusica.artist} url={this.state.detalhesDaMusica.url} detalhesDaMusica={this.state.detalhesDaMusica} playlistsCriadas={this.state.playlistsCriadas} deletarMusica={this.deletarMusica} /> <AddTracks adcionaTracks={this.state.adcionaTracks} alteraNome={this.alteraNome} alteraArtista={this.alteraArtista} alteraUrl={this.alteraUrl} salvaMusica={this.salvaMusica} /> {viewPlays} </div> ); } } export default Main;<file_sep>/semana6/form-cris/src/Components/ComSuperior.js import React from 'react' import styled from "styled-components" const FormularioDois = styled.div` display:flex; justify-content:center; align-items:center; flex-direction:column; `; const LabelForm = styled.label` display:block; `; export class ComSuperior extends React.Component { render(){ return( <FormularioDois> <h1>Etapa 2 - Informações do ensino Superior</h1> <div> <LabelForm>Qual é curso? </LabelForm> <input/> <LabelForm>Qual unidade de ensino? </LabelForm> <input/> </div> </FormularioDois> ) } }<file_sep>/semana9/astromatch/src/components/Matchs/Matchs.js import React from 'react' import Styled, {keyframes} from 'styled-components' const DivMatchs = Styled.div` width:95%; display:flex; justify-content:space-around; align-items:center; height:120px; box-shadow: 2px 2px 5px #ccc; margin:10px auto; background: rgb(108,72,157); background: linear-gradient(90deg, rgba(108,72,157,1) 0%, rgba(136,94,193,1) 51%, rgba(161,121,216,1) 100%); border-radius:10px; box-shadow:2px 2px 5px #ddd; `; const Div = Styled.div` width:95%; display:flex; flex-direction:column; justify-content:center; align-items:center; height:auto; box-shadow: 2px 2px 5px #ccc; margin:10px auto; background: rgb(108,72,157); background: linear-gradient(90deg, rgba(108,72,157,1) 0%, rgba(136,94,193,1) 51%, rgba(161,121,216,1) 100%); border-radius:10px; box-shadow:2px 2px 5px #ddd; padding:25px 0; `; const DivImg = Styled.div` width:100px; height:100px; overflow:hidden; position:relative; border-radius:50%; margin-left:10px; `; const ImgMatch = Styled.img` width:180%; height:auto; margin-left:50%; transform:translateX(-50%); `; const DivInfo = Styled.div` display:flex; flex-direction:column; justify-content:center; align-items:center; width:70%; height:95%; `; const H2Info = Styled.h2` text-transform:uppercase; color:#fff; `; const PDiv = Styled.p` color:#ddd; font-size:16px; font-weight:600; padding:10px; `; const Button1 = Styled.button` background:#ef436e; border-radius:5px; border:none; outline:none; color:#fff; padding:10px 15px; &:hover{ background:#ef436e95; } cursor:pointer; text-transform:uppercase; font-weight:600; `; function Matchs(props){ let listaDeMatchs = '' if(props.show === true){ listaDeMatchs = props.matchs.map((mat) => { return ( <DivMatchs key={mat.id}> <DivImg > <ImgMatch src={mat.photo} alt={mat.name}/> </DivImg> <DivInfo> <H2Info>{mat.name}</H2Info> </DivInfo> </DivMatchs> ) }) }else{ listaDeMatchs = <Div><H2Info>Sem Matches?</H2Info><PDiv>Continue navegando e encontre sua alma gêmea</PDiv><Button1 onClick={props.hiddenMatch}>Encontrar minha alma gêmea</Button1></Div> } return( <div> {listaDeMatchs} </div> ) } export default Matchs<file_sep>/semana10/astro-x/src/components/SideColumn/SideColumn.js import React from 'react' import {ContainerColumn,ContentColumn,ImageColumn,TitleColumn,TitleAstroX} from '../../assets/styles/Styles' export default function SideColumn(){ return( <ContainerColumn> <TitleAstroX>AstroX</TitleAstroX> <div> <TitleColumn>Parceiros</TitleColumn> <ImageColumn src="https://picsum.photos/300/300"/> <ImageColumn src="https://picsum.photos/300/300"/> </div> </ContainerColumn> ) }<file_sep>/semana7/labefy/labefy/src/App.js import logo from './logo.svg'; import './App.css'; import React from 'react'; import Main from './components/Main/Main' import {Button,ThemeProvider,createMuiTheme} from '@material-ui/core'; class App extends React.Component{ theme = createMuiTheme({ palette: { primary: { main: '#ed174d', }, secondary: { main: '#fff', }, }, }); render(){ return ( <ThemeProvider theme={this.theme}> <Main/> </ThemeProvider> ); } } export default App; <file_sep>/semana7/labefy/labefy/src/components/ListaDePlaylists/ListaDePlaylists.js import React from 'react' import {Button,ThemeProvider,createMuiTheme} from '@material-ui/core'; import {ItemLista,TitlePlaylist,PlayLists,TitleList,Buttons} from './StyleLista' class ListaDePlaylists extends React.Component{ render(){ let playlistsExibida = this.props.exibePlaylists.map((playlist) => { return ( <ItemLista key={playlist.id}> <TitlePlaylist>{playlist.name}</TitlePlaylist> <Buttons> <Button variant='contained' color='primary' onClick={() => this.props.deletePlaylist(playlist.id)}> Apagar </Button> <Button variant='contained' color='secondary' onClick={() => this.props.detalhesPlaylist(playlist.id)}> Ver </Button> <Button variant='contained' onClick={() => this.props.addMusicasPlaylist(playlist.id)}> Add </Button> </Buttons> </ItemLista> ) }) return( <ThemeProvider theme={this.theme}> <TitleList>Ouça as Sua PlayLists </TitleList> <PlayLists> {playlistsExibida} </PlayLists> </ThemeProvider> ) } } export default ListaDePlaylists<file_sep>/semana10/astro-x/src/components/Forms/FormApplyToTrip.js import React,{useState} from 'react' import {Formulario,Label,Input,Textarea,ButtonRight} from '../../assets/styles/Styles' import {useForm} from '../hooks/useForm' import {useHistory,useParams} from 'react-router-dom' import axios from 'axios' const FormCreateTrip = (props) => { const history = useHistory() const pathParams = useParams() const [form,onChange] = useForm({name:'',age:'', profession: '', country: '',applicationText:'' }) const applyToTrip = (event) => { const body = { name: form.name, age: form.age, applicationText: form.applicationText, profession: form.profession, country: form.country } axios.post(`https://us-central1-labenu-apis.cloudfunctions.net/labeX/cristiane-rocha/trips/${pathParams.id}/apply`,body) .then((res) => { alert("Você foi inscrito, aguarde aprovação !") history.push('/trips/list') }) .catch((err) => { console.log(err) }) event.preventDefault(); } return( <Formulario onSubmit={applyToTrip}> <Label>Seu Nome: </Label> <Input name={"name"} value={form.name} onChange={onChange} type="text"/> <Label>Sua Idade: </Label> <Input name={"age"} value={form.age} onChange={onChange} type="number"/> <Label>Profissão: </Label> <Input name={"profession"} value={form.profession} onChange={onChange} type="text"/> <Label>País: </Label> <Input name={"country"} value={form.country} onChange={onChange} type="text"/> <Label>Porque você merece ir? </Label> <Textarea name={"applicationText"} value={form.applicationText} onChange={onChange}></Textarea> <ButtonRight>Inscrever-se</ButtonRight> </Formulario> ) } export default FormCreateTrip<file_sep>/semana10/astro-x/src/components/Forms/Forms.js import React,{useState} from 'react' import {Formulario,Label,Input,ButtonRight} from '../../assets/styles/Styles' import axios from 'axios' import {useHistory} from 'react-router-dom' import {useForm} from '../hooks/useForm' const Forms = (props) => { const [form,onChange] = useForm({password:'',email:''}) const history = useHistory() const handleSubmit = (event) => { const body = { "email": form.email, "password": <PASSWORD> } axios.post(`https://us-central1-labenu-apis.cloudfunctions.net/labeX/cristiane-rocha/login`,body).then((res) => { localStorage.setItem('token',res.data.token) history.push('/trips/listPrivate') }).catch((err) => { console.log(err) }) event.preventDefault(); } return( <Formulario onSubmit={handleSubmit}> <Label>Email: </Label> <Input onChange={onChange} value={form.email} name={"email"} type="email"/> <Label>Senha: </Label> <Input onChange={onChange} value={form.password} name={"password"} type="password"/> <ButtonRight>Login</ButtonRight> </Formulario> ) } export default Forms<file_sep>/semana6/form-cris/src/Components/InicioFormulario.js import React from 'react' import styled from "styled-components" import {DadosGerais} from './DadosGerais' import {ComSuperior} from './ComSuperior' import {SemSuperior} from './SemSuperior' import {FimFormulario} from './FimFormulario' let tiraBotao = false const ButtonProxima = styled.button` display:${props => { if(props.show){ return "block" }else{ return "none" } }}; margin: 20px auto; `; export class InicioFormulario extends React.Component{ state = { paginaAtual: 0, showButton: true } proximaPagina = () => { this.setState({paginaAtual: this.state.paginaAtual + 1}) if(this.state.paginaAtual === 2){ this.setState({showButton:false}) } } render() { let inicia = () => { if(this.state.paginaAtual === 0){ return ( <DadosGerais/> ) }else if(this.state.paginaAtual === 1){ return ( <ComSuperior/> ) }else if(this.state.paginaAtual === 2){ return( <SemSuperior/> ) }else if(this.state.paginaAtual === 3){ return( <FimFormulario/> ) } } return( <div> {inicia()} <ButtonProxima show={this.state.showButton} onClick={this.proximaPagina}>Próxima Etapa</ButtonProxima> </div> ) } }<file_sep>/semana4/objetos/blog/script.js //Array com todas as postagens const posts = [] //função ligada ao botão, que adciona itens ao objeto post e o post ao array posts function adcionaAoObjeto(){ let tituloPost = document.querySelector("#titulo-post") let autorPost = document.querySelector("#autor-post") let conteudoPost = document.querySelector("#conteudo-post") let thumbPost = document.querySelector("#thumb-post") //Chama a função que verifica o link da imagem trataImagem(thumbPost,tituloPost,autorPost,conteudoPost) } //Tratamento do Link da Imagem function trataImagem(imagem,titulo,autor,conteudo){ if(imagem.value.includes("http") || imagem.value.includes("https") ){ //objeto para cada Post const post = { titulo:titulo.value, autor:autor.value, conteudo:conteudo.value, imagem:imagem.value } //adciona o objeto ao array posts.push(post) //chama função que armazena os dados em local storage armazenaPosts(posts) /*//chama função que adciona os posts no documento adcionaPosts(imagem,titulo,autor,conteudo)*/ //função limpa os campos limpaCampos(titulo,autor,conteudo,imagem) }else{ alert("Por favor verifique os campos, o valor inserido em 'Endereço da sua Imagem::' não é um endereço válido") //Limpa os campo imagem antes de retornar imagem.value = "" return } } function limpaCampos(imagem,titulo,autor,conteudo){ //Limpa os campos após inculir no documento titulo.value = "" autor.value = "" imagem.value = "" conteudo.value = "" } let postagensNoLocalStorage = 'Postagens' //Função que armazena o array de posts no local storage function armazenaPosts(posts){ const postsArray = JSON.stringify(posts) localStorage.setItem(postagensNoLocalStorage, postsArray); //Chama função que cria um Popup perguntando se deve continuar adcionando ou vizualizar postagens popupVizualizacao(posts) /*//função que abre a nova página passaValor()*/ } //Função que abre o popup de vizualização let i = 0; function popupVizualizacao(posts){ const sectionPopup = document.querySelector("#popup-section").style.display = 'flex' const popup = document.querySelector("#popup") popup.innerHTML += `<h2 class="titulo-popup">${posts[i].titulo}</h2><h4 class="autor-popup">${posts[i].autor}<h4><img class='imagem-popup' src='${posts[i].imagem}'><p class="conteudo-popup">${posts[i].conteudo}</p>` i++ } //Função do botão continuar Postando function postarMais(){ const sectionPopup = document.querySelector("#popup-section").style.display = 'none' } //Função do botão Salvar function salvarPostagens(){ passaValor() } //Envia os dados para outra página function passaValor(){ window.location = "posts.html" } //adciona os posts no documento function adcionaPostsNaPagina(){ const postagens = JSON.parse(localStorage.getItem('Postagens')); const containerPost = document.querySelector("#container-de-posts") for(let i=0;i<postagens.length;i++){ containerPost.innerHTML += `<h2 class="titulo">${postagens[i].titulo}</h2><h4 class="autor">${postagens[i].autor}<h4><img class='imagem' src='${postagens[i].imagem}'><p class="conteudo">${postagens[i].conteudo}</p>` } } <file_sep>/semana7/labefy/labefy/src/components/ListaDePlaylists/StyleLista.js import React from 'react' import Styled from 'styled-components' export const ItemLista = Styled.p` height:50px; width:90%; margin:0 auto; display:flex; justify-content:space-between; align-items:center; border-bottom:1px solid #ccc; `; export const TitlePlaylist = Styled.h2` text-transform:uppercase; font-weight:800; color:#2d302f; font-size:18px; `; export const PlayLists = Styled.div` width:90%; margin:0 auto; display:grid; grid-template-columns: auto; `; export const TitleList = Styled.h1` text-transform:uppercase; text-align:center; font-weight:800; color:#ed174d; font-size:22px; padding:20px 5px; border-bottom: 1px solid #ed174d; margin:0 10px 20px 10px; `; export const Buttons = Styled.div` display:flex; justify-content:space-between; width:38%; `;<file_sep>/semana10/astro-x/src/screens/ListTripsPage/ListTripsPage.js import React from 'react' import SideColumnPrivate from '../../components/SideColumn/SideColumnPrivate' import {Container,DivDetailsTrip,TitleItem,TextItem,Icon,ItemDetailsTrip,IconItem,TitleContent,ContentHome,FeatureTrip,TitleContentTrips,ItemsTrips,ItemTrips,Planet,ButtonSeeMore} from '../../assets/styles/Styles' import {useHistory} from 'react-router-dom' import {useRequestApi} from '../../components/API/Api' import Header from '../../components/Header/Header' export default function ListTripsPage(){ const myTrips = useRequestApi('https://us-central1-labenu-apis.cloudfunctions.net/labeX/cristiane-rocha/trips') const history = useHistory() const goToApplyToTripPage = (id,name) => { history.push(`/trips/apllyToTrip/${id}/${name}`) } return( <Container> <SideColumnPrivate/> <ContentHome> <Header/> <FeatureTrip> <TitleContent white>Se aventure nas galaxias!</TitleContent> </FeatureTrip> <div> <TitleContentTrips>Viagens Disponiveis </TitleContentTrips> <ItemsTrips> {myTrips.map((trip,ind,trips) => { return ( <ItemTrips key={trip.id}> <Planet>{trip.planet}</Planet> <DivDetailsTrip> <ItemDetailsTrip><Icon><i class="fas fa-calendar-alt"></i></Icon><IconItem><p>Data de partida: </p><h4>{trip.date}</h4></IconItem></ItemDetailsTrip> <ItemDetailsTrip><Icon><i class="fas fa-hourglass-half"></i></Icon><IconItem><p>Duração em dias: </p><h4>{trip.durationInDays}</h4></IconItem></ItemDetailsTrip> </DivDetailsTrip> <TitleItem>{trip.name}</TitleItem> <TextItem>{trip.description}</TextItem> <ButtonSeeMore grey onClick={() => goToApplyToTripPage(trip.id,trip.name)}>Inscrever-se</ButtonSeeMore> </ItemTrips> ) })} </ItemsTrips> </div> </ContentHome> </Container> ) }<file_sep>/semana4/planner/index.js let textoTarefa = document.getElementById('tarefa') let semana = document.querySelectorAll('.semana div') //Seleciona dia da semana function alteraOpcao(){ let selectDias = document.getElementById("dias-semana") let opcaoDia = selectDias.options[selectDias.selectedIndex].value return opcaoDia } //Função criar tarefa function criarTarefa(){ if(textoTarefa.value === ""){ alert("Você precisa digitar uma tarefa para poder incluir!") return }else{ switch(alteraOpcao()){ case "domingo": semana[0].innerHTML += `<li class="item-lista" onclick="riscaTarefa(this)">${textoTarefa.value}</li>` break; case "segunda": semana[1].innerHTML += `<li class="item-lista" onclick="riscaTarefa(this)">${textoTarefa.value}</li>` break; case "terca": semana[2].innerHTML += `<li class="item-lista" onclick="riscaTarefa(this)">${textoTarefa.value}</li>` break; case "quarta": semana[3].innerHTML += `<li class="item-lista" onclick="riscaTarefa(this)">${textoTarefa.value}</li>` break; case "quinta": semana[4].innerHTML += `<li class="item-lista" onclick="riscaTarefa(this)">${textoTarefa.value}</li>` break; case "sexta": semana[5].innerHTML += `<li class="item-lista" onclick="riscaTarefa(this)">${textoTarefa.value}</li>` break; case "sabado": semana[6].innerHTML += `<li class="item-lista">${textoTarefa.value}</li>` break; } textoTarefa.value = "" } } function riscaTarefa(element){ element.style = "text-decoration: line-through;color:red;" } function limparTarefas(){ for(let i=0;i<semana.length;i++){ semana[i].innerHTML = ""; } } <file_sep>/semana3/condicionais/src/index.js /*****************git checkout -b semana3-aula11***********************/ //Exercicio 01 /* * ```jsx const respostaDoUsuario = prompt("Digite o número que você quer testar") const numero = Number(respostaDoUsuario) if(numero % 2 === 0) { console.log("Passou no teste.") } else { console.log("Não passou no teste.") } ``` * Resposta: Este prgrama colhe um numero do usuário e verifica se o resto da divisão de por 2, se for 0 mostra a mensagem "Passou no teste.", caso contrário mostra a mensagem "Não passou no teste." * */ //Exercicio 02 /* * let fruta = prompt("Escolha uma fruta") let preco switch (fruta) { case "Laranja": preco = 3.5 break; case "Maçã": preco = 2.25 break; case "Uva": preco = 0.30 break; case "Pêra": preco = 5.5 break; // BREAK PARA O ITEM c. default: preco = 5 break; } /* console.log("O preço da fruta ", fruta, " é ", "R$ ", preco) * Resposta: a) Este programa recebe do usuario uma fruta, no swicth é feito a verificação dependendo da fruta escolhida, em cada casa é passado um valor, no final imprime a mensagem dizendo valor da fruta escolhida. b) Se a fruta escolhida for maçã, imprime a mensagem "O preço da fruta maça é 2.25" c) Se a fruta escolhida for pera e não houver o break do defout, a mensagem impressa será "O preço da fruta maça é 5" * */ //Exercicio 03 /* * const numero = Number(prompt("Digite o primeiro número.")) if(numero > 0) { console.log("Esse número passou no teste") let mensagem = "Essa mensagem é secreta!!!" } console.log(mensagem) * Resposta: a) A primeira linha esta recebendo um numero do usuário, convertendo ele para o tipo number e armazenando na consatante "numero". b) Se o usuário digitar o numero 10, a mensagem impressa será "Esse numero passou no teste", caso seja -10 a mensagem será um erro. c) Sim haverá erro no console, pois a variavel mensagem esta no escopo do if, onde o programa não entrou por ser um numero menor que 0. * */ /***********************Exercícios de escrita de código*****************************/ //Exercicio 04 const age = Number(prompt("Digite a sua idade: ")) if(age>= 18){ console.log("Você pode dirigir!") }else{ const weit = 18 - age console.log("Você não pode dirigir") console.log(`Aguarde ${weit} anos para poder dirigir, você ainda é menor de idade!`)//resolvi fazer uma frecurinha aqui :) } //Exercicio 05 const hour = prompt("Qual seu turno de estudos, digite M para matutino, V para verpertino e N para noturno: ") if(hour.toUpperCase() === "M"){ console.log("Bom Dia!") }else if(hour.toUpperCase() === "V"){ console.log("Boa Tarde!") }else if(hour.toUpperCase() === "N"){ console.log("Boa noite!") }else{ console.log("Valor digitado invalido, por favor escolha entre M,V ou N, reinicie o navegador.")//Resolvi tratar o erro, porque se não qualquer outro valor digitado iria cair em Boa noite! } //Exercicio 06 const momen = prompt("Qual seu turno de estudos, digite M para matutino, V para verpertino e N para noturno: ") let maius = momen.toUpperCase() switch (maius) { case "M": console.log("Bom Dia!") break; case "V": console.log("Boa Tarde!") break; case "N": console.log("Boa noite!") break; default: console.log("Valor digitado invalido, por favor escolha entre M,V ou N, reinicie o navegador.") break; } //Exercicio 07 const style = prompt("Qual o gênero do filme? ") const value = Number(prompt("Qual o valor do ingresso? ")) if((style.toUpperCase()==="FANTASIA") && (value<=15)){ console.log("Bom Filme !") }else{ console.log("Escolha outro filme!") } /*************************Desafios***********************/ //Desafio 01 const styleDois = prompt("Qual o gênero do filme? ") const valueDois = Number(prompt("Qual o valor do ingresso? ")) if((styleDois.toUpperCase()==="FANTASIA") && (valueDois<=15)){ let snack = prompt("Qual snack deseja comprar para acompanhar o filme: ") console.log(`Bom filme ! e com ${snack}`) }else{ console.log("Escolha outro filme!") } //Deaafio 02 const nome = prompt("Digite seu nome: ") const tipo = prompt("Escolha o tipo de jogo (IN para internacional e DO para domestico):") const etapa = prompt("Escolha a etapa do jogo (SF para semi-final, DT para decisão do terceiro lugar e FI para final)") const cat = Number(prompt("Escolha a categoria ( entre 1 e 4): ")) const qtd = prompt("Deseja comprar quantos ingressos? ") let tj = "" let ej = "" let vj = "" console.log("---Dados da compra--- ") console.log(`Nome do cliente: ${nome} `) if(tipo.toUpperCase()==="DO"){ tj = "Nacional" if(etapa.toUpperCase()==="SF"){ ej = "Semifinal"; switch (cat){ case 1: vj = 1320.00 break; case 2: vj = 880.00 break; case 3: vj = 550.00 break; case 4: vj = 220.00 break; } }else if(etapa.toUpperCase()==="DT"){ ej = "Decisão do terceiro lugar"; switch (cat){ case 1: vj = 660.00 break; case 2: vj = 440.00 break; case 3: vj = 330.00 break; case 4: vj = 170.00 break; } }else if(etapa.toUpperCase()==="FI"){ ej = "Final"; switch (cat){ case 1: vj = 1980.00 break; case 2: vj = 1320.00 break; case 3: vj = 880.00 break; case 4: vj = 330.00 break; } } }else if(tipo.toUpperCase()==="IN"){ tj = "Internacional" if(etapa.toUpperCase()==="SF"){ ej = "Semifinal"; switch (cat){ case 1: vj = 1320.00 break; case 2: vj = 880.00 break; case 3: vj = 550.00 break; case 4: vj = 220.00 break; } }else if(etapa.toUpperCase()==="DT"){ ej = "Decisão do terceiro lugar"; switch (cat){ case 1: vj = 660.00 break; case 2: vj = 440.00 break; case 3: vj = 330.00 break; case 4: vj = 170.00 break; } }else if(etapa.toUpperCase()==="FI"){ ej = "Final"; switch (cat){ case 1: vj = 1980.00 break; case 2: vj = 1320.00 break; case 3: vj = 880.00 break; case 4: vj = 330.00 break; } } }else{ console.log("Por favor digite as opçoes corretamente!")//tratamento de erro } console.log(`Tipo do jogo: ${tj}`) console.log(`Etapa do jogo: ${ej}`) console.log(`Categoria do jogo:${cat}`) console.log(`Quantidade de ingressos a ser impressos: ${qtd}`) console.log("---Valores--- ") let preco = qtd * vj if(tipo.toUpperCase()==="DO"){ console.log(`Valor do ingresso: R$ ${vj}`) console.log(`Valor total: R$ ${preco}`) }else if(tipo.toUpperCase()==="IN"){ console.log(`Valor do ingresso: $ ${vj}`) console.log(`Valor total: $ ${preco}`) }<file_sep>/semana10/astro-x/src/components/Header/Header.js import React from 'react' import {useHistory} from 'react-router-dom' import {MenuItem,Menu,MenuDiv} from '../../assets/styles/Styles' import HomeSvg from '../../assets/img/HomeSvg' import IconBack from '../../assets/img/IconBack' const Header = () => { const history = useHistory() const goPageHome = () => { history.push('/') } const goBack = () => { history.goBack() } return ( <Menu> <MenuDiv><MenuItem onClick={goBack}><IconBack/></MenuItem></MenuDiv> <MenuDiv><MenuItem onClick={goPageHome}><HomeSvg/></MenuItem></MenuDiv> </Menu> ) } export default Header<file_sep>/semana7/labeusers/labe-users/src/components/Header/Header.js import React from 'react' import Styled from 'styled-components' const CadastroButtonPage = Styled.button` background:transparent; border:none; color:#2aaa7e; text-transform:uppercase; font-weight: 800; cursor:pointer; &:hover{ color: #17efa4; } &:before{ content:"⤿"; font-size:16px; padding-right:5px; } &:focus{ outline:none; } `; const UsuarioButtonPage = Styled.button` margin: 20px 0; background:transparent; border:none; color:#2aaa7e; text-transform:uppercase; font-weight: 800; cursor:pointer; &:hover{ color: #17efa4; } &:before{ content:"+"; font-size:16px; padding-right:5px; } &:focus{ outline:none; } `; const LabeusersHeader = Styled.header` width:100%; display:flex; justify-content:space-around; padding: 10px; `; const LabeusersH1 = Styled.h1` color: #6c489d; text-transform:uppercase; text-align:center; font-size:30px; `; class Header extends React.Component{ render(){ return( <LabeusersHeader> <UsuarioButtonPage onClick={this.props.abrirPaginaCadastro} > Cadastrar Usuários </UsuarioButtonPage> <LabeusersH1>Cadastramento de Usuarios</LabeusersH1> <CadastroButtonPage onClick={this.props.abrirPaginaUsuarios}> Exibir Usuários Cadastrados </CadastroButtonPage> </LabeusersHeader> ) } } export default Header<file_sep>/semana3/blackjack/nossoJogo.js /** * EXEMPLO DE UTILIZAÇÃO DA 'comprarCarta' * * const carta = comprarCarta(); // Sorteia uma carta. Por exemplo, o rei de ouros console.log(carta.texto) // imprime o texto da carta. Exemplo: "K♦️" (indica "K" de ouros) console.log(carta.valor) // imprime o valor da carta (um número). Exemplo: 10 (dado que "K" vale 10) * * * */ /* console.log("Bem vindo ao jogo de Blackjack!") const conf = confirm( "Quer iniciar uma nova rodada?") if(conf){ //Cartas do usuário let usuarioCartaUm = comprarCarta() let usuarioCartaDois = comprarCarta() let pontosUsuario = usuarioCartaUm.valor + usuarioCartaDois.valor console.log(`Usuário - cartas: ${usuarioCartaUm.texto} ${usuarioCartaDois.texto} - pontuação ${pontosUsuario}`) //Cartas do Computador let computadorCartaUm = comprarCarta() let computadorCartaDois = comprarCarta() let pontosComputador = computadorCartaUm.valor + computadorCartaDois.valor console.log(`Computador - cartas: ${computadorCartaUm.texto} ${computadorCartaDois.texto} - pontuação ${pontosComputador}`) //Encontrando o vencedor if(pontosUsuario>pontosComputador){ console.log("O usuário ganhou!") }else if(pontosComputador>pontosUsuario){ console.log("O computador ganhou!") }else{ console.log("Empate!") } }else{ console.log("O jogo acabou") }*/<file_sep>/semana9/astromatch/src/components/IsMatch/IsMatch.js import React from 'react' import Styled from 'styled-components' import Heart from '../../img/heart.svg' const DivIsMatch = Styled.div` width:95%; height:60vh; position:absolute; top:50%; left:50%; transform:translate(-50%,-50%); border-radius:10px; box-shadow:2px 2px 5px #ccc; color:#fff; display:flex; justify-content:center; flex-direction:column; align-items:center; z-index:99999; background: linear-gradient(90deg, rgba(108,72,157,1) 0%, rgba(136,94,193,1) 51%, rgba(161,121,216,1) 100%); `; const Buttons = Styled.div` width:90%; margin:10px auto; display:flex; justify-content:space-around; align-items:center; `; const Button1 = Styled.button` background:#ef436e; border-radius:5px; border:none; outline:none; color:#fff; padding:10px 15px; &:hover{ background:#ef436e95; } cursor:pointer; text-transform:uppercase; font-weight:600; `; const Button2 = Styled.button` background:#2aaa7e; border-radius:5px; border:none; outline:none; color:#fff; padding:10px 15px; &:hover{ background:#2aaa7e95; } cursor:pointer; text-transform:uppercase; font-weight:600; font-size:12px; `; const H1 = Styled.h1` background:url(${Heart}) no-repeat; background-size:contain; width:200px; height:200px; display:flex; align-items:center; justify-content:center; text-transform:uppercase; font-size:25px; `; function IsMatch(props){ return ( <DivIsMatch> <H1>Deu Match </H1> <Buttons> <Button1 onClick={props.exibeMatch}>Ver Matchs </Button1> <Button2 onClick={props.mostraPessoa}> Continuar Navegando </Button2> </Buttons> </DivIsMatch> ) } export default IsMatch<file_sep>/semana3/operadores/src/index.js /************ **Exercícios de interpretação de código** ****************/ //Exercicio 01 /* * * Imprime: false false true tipo booleano * * */ //Exercicio 02 /* * * Imprime: indefinido (undefined) null 11 3 Imprime o array inteito ([3,4,5,6,7,8,9,10,11,12,13]) Imprime a posição 6 do array (9) * * */ /********************** **Exercícios de escrita de código** *******************/ /*//Exercicio 01 let yourAge = prompt("Qual a sua idade?") let gAge = prompt("Qual a idade da sua melhor amiga?") let bAge = prompt("Qual a idade do seu melhor amigo?") console.log("A sua idade é maior que a do seu melhor amigo?", yourAge > bAge) console.log("A diferença da idade de vocês é: ", yourAge - bAge) //Exercicio 02 let pair = prompt("Digite um numero par:") console.log(parseInt(pair) % 2) */ /*Se for impar imprime o resto da divisão, se for par, imprime 0*/ //Exercicio 03 /*let listaDeTarefas = [] let tarefa1 = prompt("Digite uma tarefa") listaDeTarefas.push(tarefa1) let tarefa2 = prompt("Digite mais uma tarefa") listaDeTarefas.push(tarefa2) let tarefa3 = prompt("Digite outra tarefa") listaDeTarefas.push(tarefa3) console.log(listaDeTarefas) */ //Exercicio 04 /*let name = prompt("Digite seu nome: ") let email = prompt("Digite seu email: ") console.log(`O e-mail ${email} foi cadastrado com sucesso. Seja bem-vinda(o), ${name}!`) */ /********************* Desafio *************************/ //Desafio 01 /* var fahrenheit = 77 var Kelvin = (fahrenheit - 32)*5/9 + 273.15 console.log(Kelvin + "°K") var celsius = 80 var fahrenheit = celsius*9/5 + 32 console.log(fahrenheit + "°F") celsius = 30 fahrenheit = celsius*9/5 + 32 Kelvin = (fahrenheit - 32)*5/9 + 273.15 console.log(fahrenheit + "°F " + Kelvin + "°K") celsius = prompt("Digite graus em celsius, para converter para Fahrenheit e Kelvin: ") fahrenheit = celsius*9/5 + 32 Kelvin = (fahrenheit - 32)*5/9 + 273.15 console.log(fahrenheit + "°F " + Kelvin + "°K") */ //Desafio 02 /*let cons = 280 let value = cons * 0.05 console.log("Valor: ", value) console.log("Valor a pagar com desconto de 15%: ", (15 * value) / 100) */ //Desafio 03 let lb = 20 * 2.2046 console.log(`20lb equivalem a ${lb} kg`) let oz = 10.5 / 35.274 console.log(`10.5oz equivalem a ${oz} kg`) let mi = 100 / 0.00062137 console.log(`100mi equivalem a ${mi} m`) let ft = 50 / 3.2808 console.log(`50ft equivalem a ${mi} m`) let gal = (103.56 * 473176473) / 125000000 console.log(`103,56gal equivalem a ${gal} l`) let xic = 450 * 0.24 console.log(`450xic equivalem a ${xic} l`) let conv = prompt("Escolha um valor em xicaras para converter em litros: ") xic = conv * 0.24 console.log(`${conv}xic equivalem a ${xic} l`)<file_sep>/semana9/astromatch/src/components/Person/Person.js import React,{useState,useEffect} from 'react' import Styled,{keyframes} from 'styled-components' import FooterContainer from '../FooterContainer/FooterContainer' import axios from 'axios' import Carregando from '../../img/carregando.gif' //Estilos const ImagePessoa = Styled.img` width:100%; height:auto; `; const ConPessoa = Styled.div` display:flex; flex-direction:column; align-items:center; justify-content:center; width:95%; margin:0 auto; height: calc(100vh - 130px); position:relative; padding:20px 0; `; const DivImg = Styled.div` overflow:hidden; border-radius:10px; box-shadow:2px 2px 5px #ddd; `; const DivInfo = Styled.div` `; const H2Info = Styled.h2` color:#6c489d; text-transform:uppercase; `; const PInfo = Styled.p` `; //Componente function Person(props){ return( <ConPessoa> <DivImg> {props.pessoa.photo ? <ImagePessoa src={props.pessoa.photo} alt={props.pessoa.nome}/> : <ImagePessoa src={Carregando}/> } </DivImg> <DivInfo> <H2Info>{props.pessoa.name}</H2Info> <PInfo>{props.pessoa.bio}</PInfo> </DivInfo> </ConPessoa> ) } export default Person<file_sep>/semana7/labefy/labefy/src/components/AddPlaylist/StyleAdd.js import React from 'react' import Styled from 'styled-components' export const TitleAdd = Styled.h1` text-transform:uppercase; text-align:center; font-weight:800; color:#ed174d; font-size:22px; padding:20px 5px; border-bottom: 1px solid #ed174d; margin:0 10px 20px 10px; width:90%; `; export const DivAdd = Styled.div` width:90vw; margin:0 auto; height:90vh; display:flex; justify-content:center; align-items:center; flex-direction:column; `; export const InputAdd = Styled.input` width:80%; padding: 6px 16px; font-size: 0.875rem; box-sizing: border-box; font-family: "Roboto", "Helvetica", "Arial", sans-serif; font-weight: 500; line-height: 1.75; border-radius: 4px; letter-spacing: 0.02857em; text-transform: uppercase; border: 1px solid #ed174d; margin:0 10px; box-shadow: 0px 3px 1px -2px rgba(0,0,0,0.2), 0px 2px 2px 0px rgba(0,0,0,0.14), 0px 1px 5px 0px rgba(0,0,0,0.12); &:focus{ outline:none; } `; export const InputsDiv = Styled.div` width:90%; margin:0 auto; display:flex; justify-content:center; align-items:center; `; export const DivAviso = Styled.div` width:90%; padding: 6px 16px; font-size: 0.875rem; box-sizing: border-box; font-family: "Roboto", "Helvetica", "Arial", sans-serif; font-weight: 500; line-height: 1.75; border-radius: 4px; letter-spacing: 0.02857em; text-transform: uppercase; border: 1px solid #ed174d; margin:0 10px; box-shadow: 0px 3px 1px -2px rgba(0,0,0,0.2), 0px 2px 2px 0px rgba(0,0,0,0.14), 0px 1px 5px 0px rgba(0,0,0,0.12); text-align:center; `;<file_sep>/semana10/astro-x/src/components/hooks/useForm.js import React,{useState} from 'react' export const useForm = (initialValue) => { const [form,setForm] = useState(initialValue) const onChange = (event) => { const {name,value} = event.target setForm({...form,[name]: value}) } return [form,onChange] }<file_sep>/semana7/labeusers/labe-users/src/components/Usuarios/Estilos/StyleDetalhesUsuario.js import React from 'react' import Styled from 'styled-components' export const DivDetalhes = Styled.div` background:#ddd; top:50%; left:50%; transform:translate(-50%,-50%); box-shadow: 2px 2px 5px #888; width:75%; height:70%; display:grid; grid-template-columns:1fr; justify-content:center; align-items:center; position:absolute; z-index:9999; `; export const H3Detalhes = Styled.h3` color:#6c489d; text-transform:uppercase; font-weight:700; `; export const DetalhesItem = Styled.span` color:#000; font-weight:700; text-transform:uppercase; margin: 0 20px 0 0; `; export const PDetalhes = Styled.p` display:flex; justify-content:space-between; align-items:center; width:80%; height:50px; margin:0 auto; padding:0 10px; border-bottom:1px solid #888; `; export const InputDetalhes = Styled.input` display:block; height:40px; width:100%; text-align:center; border:1px solid #3f3f3f ; background:none; font-family:arial; font-size:18px; color:#3f3f3f; &:focus{ outline:none; } `; export const SpanDetalhes = Styled.span` text-align:center; text-transform:uppercase; font-family:arial; font-size:18px; color:#3f3f3f; width:100%; display:block; `; export const ButtonDetalhesSair = Styled.button` background-color: #17efa4; color: #fff; text-transform:uppercase; font-weight:800; height:40px; border-radius:10px; border:none; width:35%; margin: 10px auto; display:block; cursor:pointer; transition: .3s ease-in-out; &:hover{ background:#2aaa7e; transition: .3s ease-in-out; } &:focus{ outline:none; } `; export const ButtonDetalhesDelete = Styled.button` background-color: red; color: #fff; text-transform:uppercase; font-weight:800; height:40px; border-radius:10px; border:none; width:35%; margin: 10px auto; display:block; cursor:pointer; transition: .3s ease-in-out; &:hover{ background:#ed174d; transition: .3s ease-in-out; } &:focus{ outline:none; } `; export const ButtonsDetalhes = Styled.div` display:flex; justify-content:space-between; align-items:center; `; export const ButtonsEditarSalvar = Styled.div` display:grid; grid-templat-columns: 1fr 1fr; justify-content:space-between; align-items:center; width:90%; margin:10px auto; `; export const SpanEditar = Styled.span` padding:5px 10px; background: #2aaa7e; color:#fff; border-radius:5px; cursor:pointer; &:hover{ background:#17efa4; } `; export const BotaoSalvar = Styled.button` padding:5px 10px; color:#fff; background:#2aaa7e; border-radius:3px; border:none; margin-right:10%; grid-column:2; cursor:pointer; &:hover{ background:#17efa4; } &:focus{ outline:none; } `; export const BotaoCancelar = Styled.button` padding:5px 10px; color:#fff; background:#1e1e1e; border-radius:3px; border:none; margin-right:10%; grid-column:1; cursor:pointer; &:hover{ background:#3f3f3f; } &:focus{ outline:none; } `; <file_sep>/semana10/astro-x/src/screens/LoginPage/LoginPage.js import React,{useState} from 'react' import Form from '../../components/Forms/Forms' import {Container,ButtonRight,ContentForms,TitleContentTrips} from '../../assets/styles/Styles' import SideColumnPrivate from '../../components/SideColumn/SideColumnPrivate' import Header from '../../components/Header/Header' const LoginPage = () => { return( <Container> <SideColumnPrivate/> <Header/> <ContentForms> <TitleContentTrips>Faça Login na sua Dashboard </TitleContentTrips> <Form/> </ContentForms> </Container> ) } export default LoginPage<file_sep>/semana10/astro-x/src/screens/ListTripsPrivatePage/ListTripPrivatePage.js import React from 'react' import SideColumnPrivate from '../../components/SideColumn/SideColumnPrivate' import {Container,ItemDetailsTrip,DivDetailsTrip,IconItem,Icon,TitleContent,TextItem,TitleItem,ContentHome,ButtonRight,FeatureTrip,TitleContentTrips,ItemsTrips,ItemTrips,Planet,ButtonSeeMore} from '../../assets/styles/Styles' import {useHistory} from 'react-router-dom' import {useRequestApi} from '../../components/API/Api' import Header from '../../components/Header/Header' export default function ListTripsPage(){ const myTrips = useRequestApi('https://us-central1-labenu-apis.cloudfunctions.net/labeX/cristiane-rocha/trips') const history = useHistory() const goToTtipDetailsPage = (id) => { history.push(`/trips/detailsPrivate/${id}`) } const logout = () => { localStorage.removeItem('token') history.push('/login') } const goToCreateTripPage = () => { history.push('/trips/create') } return( <Container> <SideColumnPrivate/> <ContentHome> <Header/> <FeatureTrip> <TitleContent>Administre Viagens e Candidatos</TitleContent> </FeatureTrip> <div> <TitleContentTrips><div><ButtonRight red onClick={logout}>sair</ButtonRight> <ButtonRight onClick={goToCreateTripPage}>Adcionar Viagem</ButtonRight> </div> Viagens ↴</TitleContentTrips> <ItemsTrips> {myTrips.map((trip) => { return ( <ItemTrips key={trip.id}> <Planet>{trip.planet}</Planet> <DivDetailsTrip> <ItemDetailsTrip><Icon><i class="fas fa-calendar-alt"></i></Icon><IconItem><p>Data de partida: </p><h4>{trip.date}</h4></IconItem></ItemDetailsTrip> <ItemDetailsTrip><Icon><i class="fas fa-hourglass-half"></i></Icon><IconItem><p>Duração em dias: </p><h4>{trip.durationInDays}</h4></IconItem></ItemDetailsTrip> </DivDetailsTrip> <TitleItem>{trip.name}</TitleItem> <TextItem>{trip.description}</TextItem> <ButtonSeeMore onClick={() => goToTtipDetailsPage(trip.id)}>Administrar</ButtonSeeMore> </ItemTrips> ) })} </ItemsTrips> </div> </ContentHome> </Container> ) }<file_sep>/semana4/lista-de-exercicios/script.js //Exercícios de interpretação de código /* * Exercicio 01 Resposta: No console será impresso uma variavel que recebe um função que ao ser chamada passa o valor 100 como parametro. A função pede ao usuário para digitar o valor da cotação do Dolar que retorna uma string com R$ + o valor passado por parametro vezes o valor da cotação digitado pelo usuário, e essa string que é impressa no console. * Exercicio 02 Resposta: É impresso no console duas constantes que recebem a mesma função com parametros diferentes, esta função atribui a variavel valorAposInvestimento o valor passado por parametro vezes um valor especifico para cada tipo de investimento, e retorna essa variavel. Como estas duas duas constantes passam a função os respectivos parametros: Açoes, 150 e Tesouro direto , 200, sendo o primeiro parametro o tipo de investimento e o segundo o valor do investimento, os valores impressos no console serão: 165 e TIPO DE INVESTIMENTO INFORMADO INCORRETO, pois Tesouro direto não esta sendo tratado na função e cai em defout do switch. * Exercicio 03 Resposta: Neste programa são criados 3 arrays, um de numero povoado com 14 numeros e os outros dois vazios. Em um loop for of adciona os numeros da primeira variavel, dividindo eles em pares e impares, jogando os pares em um dos arrays vazios e impares em outro. No fim é impresso no console a mensagem : | Quantidade total de números: 14 |(Que é o tamanho do primeiro array). Seguido de duas outras mensagens com o tamanho dos outros arrays : | 6 | (Tamanho do array de pares) | 8 | (Tamanho do array de impares) * Exercicio 04 Resposta: É criado um array com varios numeros, e duas variaveis numero1 que recebe o valor Infinity, e numero2 que recebe o valor 0, logo em seguida abre-se um loop for of, que se o numero da vez for menor que numero1 , a variavel numero1 recebe esse numero, o primeiro numero é 25, menor que infinito, logo a variavel numero1 recebe 25, não é uma atribuição somatoria e sim uma substituição, assim passando por todos os valores comparando com o valor da vez, a variavel numero1 recebe por fim -10 que é o menor numero, a mesma coisa acontece no segundo if do mesmo loop que faz a comparação inversa, no caso verifica se é maior, 25 o primeiro valor é maior que zero a sua atual atribuição,varrendo todo o array a variavel numero2 recebe o valor 1590 que é o maior valor do array, sendo impresso no console esses valores: -10 e 1590. * */ //Exercícios de Lógica de Programação //Exercicio 01 /*Pode se interar em uma lista com forEach, filter, map, for of e for*/ //Exemplo let lista = [5,36,21,0,25,99,56,21,44,23,85,10,9,25,15,46,82] //Modifica todos os valores da lista de numeros menores que 50 para 0 e imprime no console lista.forEach((item,indice,array)=>{ if(item < 50){ array[indice] = item - item } }) console.log(lista) //Imprime no console uma mensagem com um array de todos os itens do array listaStrings que tem a letra o. let listaStrings = ["Dado","Pincel","Lapis","Tabuleiro","Caneta","Peças","Jogadores"] const comALetraO = listaStrings.filter((item)=>{ return item.includes("o") }) console.log("Os items que tem a letra o são", comALetraO) //Imprime no console um array que contem os mesmos numeros do array lista 2, porém com todos os numeros pares com seus valores dobrados. let lista2 = [0,6,25,32,14,25,6,9,12,36,52,91,63,41,85,42,12] let numerosParesDobrados = lista2.map((item)=>{ if(item % 2 === 0){ return item * 2 }else{ return item } }) console.log(numerosParesDobrados) //Exercicio 02 /* * Respostas: a) false b) false c) true d) true e) true * */ //Exercicio 03 /* * Resposta: Detectei algumas falhas no código do meu amig, começando pela variavel quantidadeDeNumerosPares que não esta recebendo nenhum valor, o que gerara um erro de undefined, em seguida no while é necessário que a variavel i seja incrementada, pois senão teremos um loop infinto parado no numero 0. * */ //Exercicio 04 let numero1 = Number(prompt("Digite um numero: ")) let numero2 = Number(prompt("Digite outro numero: ")) function verificaNumeroMaior(a,b){ if(a > b){ return a }else{ return b } } function verificaDivisao(a,b){ if(a % b === 0){ return a + " é divisivel por " + b }else{ return a + " não é divisivel por " + b } } function diferencaNumeros(a,b){ if(a > b){ return a - b }else{ return b - a } } console.log("ENTRADA") console.log(numero1 + " e " + numero2) console.log("O maior é: " + verificaNumeroMaior(numero1,numero2) ) console.log(verificaDivisao(numero1,numero2)) console.log(verificaDivisao(numero2,numero1)) console.log("A diferença entre eles é: " + diferencaNumeros(numero1,numero2)) // Exercicio 05 function verificaSegundo(array){ let menor = Infinity let maior = 0 let indiceMaior = 0 let indiceMenor = 0 let maiorValor = 0 let menorValor = Infinity array.forEach((item,ind)=>{ if(item>maior){ maior = item indiceMaior = ind }else if(item<menor){ menor = item indiceMenor = ind } }) console.log(maior,menor) array.splice(indiceMaior, 1); array.splice(indiceMenor, 1); array.forEach((item,ind)=>{ if(item>maiorValor){ maiorValor = item indiceMaior = ind }else if(item<menorValor){ menorValor = item indiceMenor = ind } }) console.log(maiorValor,menorValor) } let arrayNumeros = [56,32,23,210,365,2,14,32,39,25,21,36,198,215,125,12,36,10,32] verificaSegundo(arrayNumeros) //Exercicio 2 const alertFuture4 = () => { alert("Hello Future4") } alertFuture4() //Exercícios de Objetos //Exercicio 01 /* * Resposta: Objetos são como objetos na vida real, que tem suas utilidades e caracteristicas, usamos objetos para armazenar e ultilizar dados, como por exemplo dados de um cadastro. * */ //Exercicio 02 function criaRetangulo(lado1,lado2){ let retangulo = { largura: lado1, altura: lado2, perimetro: 2 * (lado1 + lado2), area: (lado1 * lado2) } return retangulo } console.log(criaRetangulo(52,35)) //Exercicio 03 //título, ano, diretor e atores/atrizes (lista com pelo menos 2 atores/atrizes) //Venha assistir ao filme NOME DO FILME, de ANO, dirigido por DIRETOR e estrelado por ATOR 1, ATRIZ 2, ATOR n let meuFilmeFavorito = { titulo:"The Notebook (Diário de uma paixão)", ano: 2004, diretor: "<NAME>", atores:["<NAME>","<NAME>","<NAME>","<NAME>","<NAME>"] } document.write(`Venha assistir ao filme ${meuFilmeFavorito.titulo}, de ${meuFilmeFavorito.ano}, dirigido por ${meuFilmeFavorito.diretor} e estrelado por ${meuFilmeFavorito.atores}`) console.log((`Venha assistir ao filme ${meuFilmeFavorito.titulo}, de ${meuFilmeFavorito.ano}, dirigido por ${meuFilmeFavorito.diretor} e estrelado por ${meuFilmeFavorito.atores}`)) //Exercicio 04 //nome, idade, email e endereco let pessoa = { nome: "<NAME>", idade: 25, email:"<EMAIL>", endereco: "Rua da casa dela, numero 00, Bairro: logo ali" } function anonimizarPessoa(object){ let pessoaAnonima = { ...object, nome: "ANONIMO" } return pessoaAnonima } console.log(anonimizarPessoa(pessoa)) //Exercícios de Funções de array //exercicio 01 let pessoas = [ { nome: "Pedro", idade: 20 }, { nome: "João", idade: 10 }, { nome: "Paula", idade: 12 }, { nome: "Artur", idade: 89 } ] function retornaAdultos(array){ let soAdultos = array.filter((pessoa)=>{ return pessoa.idade >= 20 }) return soAdultos } function retornaCriancas(array){ let soCriancas = array.filter((pessoa)=>{ return pessoa.idade < 20 }) return soCriancas } console.log(retornaCriancas(pessoas)) console.log(retornaAdultos(pessoas)) // Exercicio 02 const array = [1, 2, 3, 4, 5, 6] //a) function multiplicaPorDois(array){ let multiplicado = array.map((item)=>{ return item * 2 }) return multiplicado } console.log(multiplicaPorDois(array)) //b) function multiplicaPorTresToString(array){ let porTresString = array.map((item)=>{ return String(item * 3) }) return porTresString } console.log(multiplicaPorTresToString(array)) //c) function parOuImpar(array){ let parImpar = array.map((item)=>{ if(item % 2 === 0){ return `${item} é par` }else{ return `${item} é impar` } }) return parImpar } console.log(parOuImpar(array)) //Exercicio 03 const pessoas2 = [ { nome: "Paula", idade: 12, altura: 1.8}, { nome: "João", idade: 20, altura: 1.3}, { nome: "Pedro", idade: 15, altura: 1.9}, { nome: "Luciano", idade: 22, altura: 1.8}, { nome: "Artur", idade: 10, altura: 1.2}, { nome: "Soter", idade: 70, altura: 1.9} ] //a) function ePermitido(array){ let podeEntrar = array.filter((pessoa)=>{ if((pessoa.altura >= 1.5) && (pessoa.idade >14) && (pessoa.idade < 60)){ return pessoa } }) return podeEntrar } console.log(ePermitido(pessoas2)) //b) function naoEPermitido(array){ let naoPodeEntrar = array.filter((pessoa)=>{ if((pessoa.altura < 1.5) || (pessoa.idade <=14) || (pessoa.idade >= 60)){ return pessoa } }) return naoPodeEntrar } console.log(naoEPermitido(pessoas2)) //Exercicio 04 const consultas = [ { nome: "João", genero: "masculino", cancelada: true, dataDaConsulta: "01/10/2019" }, { nome: "Pedro", genero: "masculino", cancelada: false, dataDaConsulta: "02/10/2019" }, { nome: "Paula", genero: "feminino", cancelada: true, dataDaConsulta: "03/11/2019" }, { nome: "Márcia", genero: "feminino", cancelada: false, dataDaConsulta: "04/11/2019" } ] let genero = ""; let lembrar = ""; function emailCancelado(array){ let consultasCanceladas = [] let consultasNaoCanceladas = [] array.forEach((consulta)=>{ if(consulta.cancelada){ if(consulta.genero === "masculino"){ genero = "Sr" }else{ genero = "Sra" } consultasCanceladas.push(`Olá, ${ genero } ${ consulta.nome }. Infelizmente, sua consulta marcada para o dia ${ consulta.dataDaConsulta} foi cancelada. Se quiser, pode entrar em contato conosco para remarcá-la `) }else{ if(consulta.genero === "masculino"){ genero = "Sr" lembrar = "-lo" }else{ genero = "Sra" lembrar = "-la" } consultasNaoCanceladas.push(`Olá, ${genero} ${ consulta.nome}. Estamos enviando esta mensagem para lembrá${ lembrar } da sua consulta no dia ${ consulta.dataDaConsulta }. Por favor, acuse o recebimento deste e-mail. `) } }) let emailsConsulta = `Emails para consultas canceladas: ${consultasCanceladas} Emails para consultas não canceladas: ${consultasNaoCanceladas}` return emailsConsulta } console.log(emailCancelado(consultas))<file_sep>/semana10/astro-x/src/components/SideColumn/SideColumnPrivate.js import React from 'react' import {ContainerColumn,TitleAstroXVertical} from '../../assets/styles/Styles' export default function SideColumnPrivate(){ return( <ContainerColumn> <TitleAstroXVertical>AstroX</TitleAstroXVertical> </ContainerColumn> ) }<file_sep>/semana7/labeusers/labe-users/src/components/Cadastro/Cadastro.js import React from 'react' import axios from 'axios' import Styled from 'styled-components' import CadastroImg from '../../img/cadastro.jpg' const CadastroDiv = Styled.div` width: 100vw; height:100vh; background-image: url(${CadastroImg}); background-size:cover; display:flex; flex-direction: column; justify-content:space-between; align-items:center `; const CadastroInputs = Styled.div` width:60%; height:60%; display:flex; background:#ffffff90; flex-direction: column; margin-top:20px; box-shadow: 2px 2px 5px #888; `; const CadastroInnput = Styled.input` width:70%; text-align:left; color: #888; height:40px; margin: 10px auto; border-radius:10px; font-size:20px; border: 1px solid #888; padding-left:10px; &:focus{ outline:none; } `; const CadastroButton = Styled.button` background-color: #17efa4; color: #fff; text-transform:uppercase; font-weight:800; height:40px; border-radius:10px; border:none; width:35%; margin: 10px auto; display:block; cursor:pointer; transition: .3s ease-in-out; &:hover{ background:#2aaa7e; transition: .3s ease-in-out; } &:focus{ outline:none; } `; const CadastroH2 = Styled.h2` color: #888; padding:10px; text-transform:uppercase; text-align:center; font-size:30px; `; class Cadastro extends React.Component{ state = { UsuarioCadastrado:'', EmailCadastrado:'', UsuariosCadastrados:[] } //função onchange para input controlado do nome recebeNome = (event) => { this.setState({UsuarioCadastrado: event.target.value}) } //função onchange para input controlado do email recebeEmail = (event) => { this.setState({EmailCadastrado: event.target.value}) } //função onclick para cadastrar usuario cadastrarUsuario = () =>{ const body = { name: this.state.UsuarioCadastrado, email: this.state.EmailCadastrado } //Enviando dados para Api Labeuser axios.post("https://us-central1-labenu-apis.cloudfunctions.net/labenusers/users",body,{ headers: { Authorization: "cristiane-da-rocha-dumont" } }).then((resposta) => { alert("Usuário Cadastrado com Sucesso !") this.setState({ UsuarioCadastrado:'', EmailCadastrado: '' }) }).catch((error) => { alert("Houve algum erro ao cadastrar, verifique os dados digitados !") console.log("Este Erro aqui",error) }) } render(){ return( <CadastroDiv> <CadastroInputs> <CadastroH2>Cadastrar Usuários</CadastroH2> <CadastroInnput type="text" placeholder='Digite seu Nome' value={this.state.UsuarioCadastrado} onChange={this.recebeNome}/> <CadastroInnput type="email" placeholder='Digite seu Email' value={this.state.EmailCadastrado} onChange={this.recebeEmail} /> <CadastroButton onClick={this.cadastrarUsuario}> Salvar </CadastroButton> </CadastroInputs> </CadastroDiv> ) } } export default Cadastro<file_sep>/semana5/insta4/src/App.js import React from 'react'; import './App.css'; import Post from './components/Post/Post'; class App extends React.Component { render() { return ( <div className={'app-container'}> <Post nomeUsuario={'Paulinha'} fotoUsuario={'https://picsum.photos/50/50'} fotoPost={'https://picsum.photos/200/150'} /> <Post nomeUsuario={'<NAME>'} fotoUsuario={'https://scontent.fjoi3-1.fna.fbcdn.net/v/t1.0-9/80407078_2223426441293001_5431775968802897920_o.jpg?_nc_cat=108&_nc_sid=8bfeb9&_nc_ohc=A5_FkjNHUikAX8eMd-h&_nc_ht=scontent.fjoi3-1.fna&oh=fc1db5d153701299dd656e79f05918a8&oe=5FAE9FEB'} fotoPost={'https://lirp-cdn.multiscreensite.com/d37044ac/dms3rep/multi/opt/Card%C3%A1pio+2019+%282%29-640w.jpeg'} /> <Post nomeUsuario={'Vinicius'} fotoUsuario={'https://scontent.fjoi3-1.fna.fbcdn.net/v/t1.0-9/64641064_2086076521694661_3279682330540638208_n.jpg?_nc_cat=107&_nc_sid=ad2b24&_nc_ohc=kdcXwE5YTFUAX-CtKLE&_nc_ht=scontent.fjoi3-1.fna&oh=670e41905e6e6005514d9a5ee0dd2b5f&oe=5FADA649'} fotoPost={'https://www.melhoresdestinos.com.br/wp-content/uploads/2020/06/melhores-praias-brasil.jpg'} /> </div> ); } } export default App;
235096d899067f09e7926022dacd54f15ea1b884
[ "JavaScript" ]
44
JavaScript
future4code/Cristiane-Rocha
0734b90666e1dab10862f19b009ab9458ac29b1e
b2761cab66acbe011085fc5482d271a3626cc4aa
refs/heads/master
<repo_name>jmpatnoe/ear<file_sep>/server.py #!/usr/bin/env python3 import asyncio import websockets server = None GLOBAL_DISPATCHER = {} SYSTEM_DISPATCHER = {} def global_method(fn): GLOBAL_DISPATCHER[fn.__name__] = fn return fn def system_method(fn): SYSTEM_DISPATCHER[fn.__name__] = fn return fn def error(message, data=None): e = {"error": message} if data is not None: e['data'] = data return json.dumps(e) class Server(object): def __init__(self, logger): self.logger = logger self.systems = {} self.logger.info('Server created') def create(self, driver): system = System(driver, self.logger) system.driver = driver.index system.init() self.systems[system.id] = system return system def destroy(self, system): if system.id in self.systems: del system @global_method async def create_system(req, socket): driver_id = req.get("driver", None) driver = get_driver(driver_id) if not driver: await socket.send(error("Unknown driver", driver_id)) else: system = server.create(driver) await socket.send(json.dumps({ "system": system.id })) @global_method async def list_drivers(req, socket): s = fmod.System() drivers = [] num_drivers = s.num_drivers for i in range(num_drivers): d = s.get_driver_info(i) driver = Driver(i, d) drivers.append(driver.json_obj()) await socket.send(json.dumps(drivers)) @system_method async def get_usage(system, req, socket): await socket.send(json.dumps(system.usage())) def main(argv): parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('--sum', dest='accumulate', action='store_const', const=sum, default=max, help='sum the integers (default: find the max)') args = parser.parse_args() #print(args) logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger('ear') server = Server(logger) logging.getLogger('websockets.server').setLevel(logging.ERROR) async def server_socket(socket, path): async for message in socket: message = message.strip() try: req = json.loads(message) method = req.get('method', None) if method in GLOBAL_DISPATCHER: await GLOBAL_DISPATCHER[method](req, socket) elif method in SYSTEM_DISPATCHER: if 'system' not in req: await socket.send(error("Missing system id")) else: system = server.systems.get(req['system'], None) if not system: await socket.send(error("Unknown system", req['system'])) else: await SYSTEM_DISPATCHER[method](system, req, socket) else: await socket.send(error("Unknown method", method)) except json.decoder.JSONDecodeError: await socket.send(error("JSON payload required")) websocket_server = websockets.serve(server_socket, "localhost", 8765) try: asyncio.get_event_loop().run_until_complete(websocket_server) asyncio.get_event_loop().run_forever() except KeyboardInterrupt as e: pass return 0 if __name__ == "__main__": sys.exit(main(sys.argv)) <file_sep>/mixer.py #!/usr/bin/env python3 import logging import uuid default_logger = logging.getLogger('ear.mixer') class Bus(object): pass class InputBus(object): pass class OutputBus(object): def __init__(self, logger=default_logger): self.logger = logger self.logger.info('OutputBus created') class SpeakerBus(OutputBus): def __init__(self, index, attrs, logger=default_logger): super(OutputBus).__init__() self.index = index self.attrs = attrs self.id = uuid.uuid5(uuid.NAMESPACE_DNS, 'ear.drivers.' + str(self.attrs.guid.data1)) self.logger = logger self.logger.info('SpeakerBus created', self) def __eq__(self, rhs): return self.id == rhs.id def __str__(self): return json.dumps(self.obj()) def __repr__(self): return self.__str__() def obj(self): return { 'id': str(self.id), 'name': self.attrs.name.decode("utf-8") , 'rate': self.attrs.system_rate, 'mode': self.attrs.speaker_mode, 'channels': self.attrs.speaker_mode_channels } class System(object): def __init__(self, num_speakers, logger=default_logger): self.num_speakers = num_speakers self.logger = logger self.logger('Creating system with {} channels'.format(num_speakers)) self.fmod = fmod.System() self.output = None format = self.fmod.software_format format.raw_speakers = num_speakers format.speaker_mode = fmod.enums.SPEAKERMODE.RAW.value self.fmod.software_format = format self.speaker_busses = [] num_drivers = self.fmod.num_drivers for i in range(num_drivers): d = self.fmod.get_driver_info(i) self.speaker_busses.append(SpeakerBus(i, d)) self.logger('System created') def release(self): self.logger('Releasing system') self.fmod.release() def set_output(self, speaker_bus): if not isinstance(speaker_bus, SpeakerBus): raise ValueError("SpeakerBus not provided") self.logger.info('Setting output bus to {}'.format(speaker_bus)) self.output = speaker_bus self.fmod.driver = speaker_bus.index def init(self): self.fmod.init() if __name__ == "__main__": import sys sys.exit(main(sys.argv)) <file_sep>/ear.py #!/usr/bin/env python3 import argparse import json import logging import pyfmodex as fmod import sys import time import uuid default_logger = logging.getLogger('ear') class Matrix(object): def __init__(self, inputs, outputs, assign=0): self.inputs = inputs self.outputs = outputs self.matrix = [[assign for x in range(inputs)] for y in range(outputs)] def fill(self, matrix): if len(matrix) != self.inputs: raise Exception("Inputs length does not match matrix") for input in range(self.inputs): if len(matrix[input]) != self.outputs: raise Exception("Outputs length does not match matrix") self.matrix = matrix def flatten(self): return [y for x in self.matrix for y in x] def set_input_vector(self, input, outputs): if len(outputs) != self.outputs: raise Exception("Outputs length does not match expected") self.matrix[input] = outputs def set_input(self, input, output, value): self.matrix[input][output] = value def get_input_vector(self, input): return self.matrix[input] def set_output_vector(self, output, inputs): if len(inputs) != self.inputs: raise Exception("Inputs length does not match expected") for i in range(self.inputs): self.matrix[i][output] = inputs[i] def set_output(self, output, input, value): self.matrix[input][output] = value def get_output_vector(self, output): inputs = [] for i in range(self.inputs): inputs.append(self.matrix[i][output]) return inputs class Driver(object): def __init__(self, index, fmod_driver): self.index = index self.fmod_driver = fmod_driver self.id = uuid.uuid5(uuid.NAMESPACE_DNS, 'ear.drivers.' + str(self.fmod_driver.guid.data1)) def __eq__(self, rhs): return self.id == rhs.id def __str__(self): return json.dumps(self.obj()) def __repr__(self): return self.__str__() def obj(self): return { 'id': str(self.id), 'name': self.fmod_driver.name.decode("utf-8") , 'rate': self.fmod_driver.system_rate, 'mode': self.fmod_driver.speaker_mode, 'channels': self.fmod_driver.speaker_mode_channels } class Speaker(object): def __init__(self, index): self.index = index self.name = None self.volume = 0 class SpeakerGroup(object): def __init__(self, router, speakers): self.router = router self.speakers = speakers self.mix_recipes = {} def play(file): sound = self.router.fmod_system.create_sound(file) format = sound.format channels = format.channels channel_group = self.router.fmod_system.create_channel_group("test") sound.add_group(channel_group) self.router.output.add_group(channel_group) matrix = Matrix(channels, router.num_speakers, 1) channel_group.set_mix_matrix(matrix.flatten()) sound.play() class Zone(object): def __init__(self, group, name): self.group = group self.name = name self.children = [] def add_zone(self, zone): if zone in self.children: raise Exception("Zone already has child " + zone) self.children.append(zone) def remove_zone(self, zone): if zone not in self.children: raise Exception("Zone does not have child " + zone) self.children.remove(zone) class ChannelZone(object): def __init__(self, channel, zone): self.channel = channel self.zone = zone self.volume = 1 class Channel(object): def __init__(self, router): self.id = uuid.uuidv4() self.router = router self.output = self.router.fmod_system.create_channel_group() self.zones = [] def _update_mix(self): """Recompute output mix matrix based on currently attached zones""" mix = [0 for i in range(self.router.num_speakers * self.router.num_speakers)] self.output.set_mix_matrix(mix, self.router.num_speakers, self.router.num_speakers) def attach_zone(self, zone): for cz in self.zones: if cz.zone is zone: return cz cz = ChannelZone(self, zone) self.zones.append(cz) return cz def detach_zone(self, cz): self.zones.remove(cz) def play(file): sound = self.system.create_sound(file) sound.channel_group = self.output #speakers = group.get_speakers() class Router(object): def __init__(self, num_speakers, logger=default_logger): self.num_speakers = num_speakers self.speakers = SpeakerGroup([Speaker(i) for i in range(num_speakers)]) self.logger = logger self.running = False self.fmod_system = fmod.System() self.output = None format = self.fmod_system.software_format format.raw_speakers = num_speakers format.speaker_mode = fmod.enums.SPEAKERMODE.RAW.value self.fmod_system.software_format = format #self.update_driver_cache() def _update_volume(self): mix_matrix = [0 for i in range(self.num_speakers * self.num_speakers)] for index, speaker in enumerate(self.speakers.speakers): mix_matrix[index][index] = speaker.volume self.output.set_mix_matrix(mix_matrix, self.num_speakers, self.num_speakers) def play(self, file, group): sound = self.fmod_system.create_sound(file) sound.channel_group = self.output speakers = group.get_speakers() mix = [0 for i in range(self.num_speakers * self.num_speakers)] def get_all_drivers(self): drivers = [] num_drivers = self.fmod_system.num_drivers for i in range(num_drivers): d = self.fmod_system.get_driver_info(i) drivers.append(Driver(i, d)) return drivers def get_driver_from_index(self, index): return Driver(index, self.fmod_system.get_driver_info(index)) def get_index_from_driver(self, driver): num_drivers = self.fmod_system.num_drivers for i in range(num_drivers): d = Driver(i, self.fmod_system.get_driver_info(i)) if d == driver: return i return None def get_driver(self): """ Return current driver object configured in Mixer """ print("driver_index", self.fmod_system.driver) return self.get_driver_from_index(self.fmod_system.driver) def set_driver(self, driver): self.fmod_system.driver = driver.get_index() def get_speaker(index): return self.speakers.get_speaker(index) def start(self): if self.running: raise Exception("Mixer already running") self.fmod_system.init() if self.output is None: self.output = self.fmod_system.create_channel_group("main_mix") self._update_volume() self.running = True def stop(self): if not self.running: raise Exception("Mixer is not running") self.fmod_system.close() self.running = False def usage(self): cpu_usage = self.fmod_system.cpu_usage return { 'dsp': usage.dsp, 'stream': usage.stream, 'geometry': usage.geometry, 'update': usage.update, 'total': usage.total } def main(argv): parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('--sum', dest='accumulate', action='store_const', const=sum, default=max, help='sum the integers (default: find the max)') args = parser.parse_args() #print(args) logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', level=logging.INFO) logger = default_logger if __name__ == "__main__": sys.exit(main(sys.argv)) <file_sep>/poc.py #!/usr/bin/env python3 import pyfmodex as fmod import os import sys import time def main(argv): system = fmod.System() num_drivers = system.num_drivers for i in range(num_drivers): d = system.get_driver_info(i) vals = {} for key in d.keys(): vals[key] = d[key] print("driver", vals) system.init() sounds = [] for root, dirs, files in os.walk('./media'): for f in files: file = os.path.join(root, f) sound = system.create_sound(file, fmod.flags.MODE.ACCURATETIME) format = sound.format attrs = { 'type': format.type, 'channels': format.channels, 'format': format.format, 'length': sound.get_length(fmod.flags.TIMEUNIT.MS) } print(len(sounds), ':', file, attrs) sounds.append({ 'sound': sound, 'attrs': attrs }) master_group = system.master_channel_group sound_group = system.create_channel_group('sound') left_group = system.create_channel_group('left') right_group = system.create_channel_group('right') left_group.add_group(sound_group, True) left_group.set_mix_matrix([0, 1, 0, 0], 2, 2) #right_group.add_group(sound_group, True) #right_group.set_mix_matrix([0, 0, 1, 0], 2, 2) #left_group.volume = .3 #right_group.volume = .3 parent = sound_group.parent_group print('parent name', parent.name) print('parent is master', parent is master_group) s = sounds[1]['sound'] channel = s.play(sound_group) while channel.is_playing: time.sleep(0) return 0 if __name__ == "__main__": sys.exit(main(sys.argv)) <file_sep>/test.py import unittest import ear class TestMatrix(unittest.TestCase): def test_matrix(self): matrix = ear.Matrix(2, 3, None) self.assertEqual([None, None, None, None, None, None], matrix.flatten()) matrix.fill([ [1, 2, 3], [4, 5, 6] ]) self.assertEqual([1, 2, 3], matrix.get_input_vector(0)) self.assertEqual(6, len(matrix.flatten())) self.assertEqual([1, 2, 3, 4, 5, 6], matrix.flatten()) matrix.set_output_vector(0, [7, 8]) self.assertEqual([7, 2, 3, 8, 5, 6], matrix.flatten()) if __name__ == '__main__': unittest.main()
8eac6c7296c23915c10f3ca30fdcfdd7ff7be15e
[ "Python" ]
5
Python
jmpatnoe/ear
e1eb2904abc57de573907ad47e883b245143a90e
bf46f2eec4a5c7c7715b8f3bf9db8865a40abecf
refs/heads/main
<repo_name>chrisleggett/k8s-banking-demo<file_sep>/server-profiles/pingdirectory/pd.profile/server-root/pre-setup/webapps/privacy-dashboard/assets/example.config.js /* * This file can be used to override any environment vars from compile time. * * To use: * $ cp example.config.js config.js * $ vi config.js * * And customize for your deployment environment. * */ (function(window) { window.RuntimeConfig = {}; /* * The https host and port for your PingDirectory, * where the privacy dashboard will find the consent API. * Set this URL if you are deploying the privacy * dashboard to a different webserver. Don't forget to * fix the CORS policy on your PingDirectory consent API too. */ // window.RuntimeConfig.PD_HOST_PORT = "https://pd.example.com:8443"; /* * If you are deploying this app on your PingDirectory, * like in the `webapps` directory, * use this value instead. */ // window.RuntimeConfig.PD_HOST_PORT = window.location.origin; /* * The https URL where the privacy dashboard will redirect for login. */ // window.RuntimeConfig.OAUTH2_AUTHORIZATION_URL = "https://pf.example.com:9031/as/authorization.oauth2"; /* * The client id the privacy dashboard will use to identify itself to the authorization server. */ // window.RuntimeConfig.OAUTH2_CLIENT_ID = "privacy-dashboard"; /* * The list of scopes to request from the authorization server. * Override this value if your fine-grained consent templates * require authorizations for other API calls. * * For example, add `accounts` to the space-delimited list * if you intend to demo the open-banking-account-request consent, * while will need authorization to list the user's bank * accounts for explicit authorization. */ // window.RuntimeConfig.OAUTH2_SCOPES = "urn:pingdirectory:consent"; /* * Other configuration options are available or required depending on the * fine-grained consents you want to support. */ // window.RuntimeConfig.OPEN_BANKING_ACCOUNTS_URL = "https://example.com/api/open-banking/v1/accounts"; })(window); <file_sep>/server-profiles/README.md # Overview This directory contains server profiles for PingDirectory and PingDataGovernance to make it easier to demonstrate the capabilities of these products. # What Do You Get? PingDirectory will be configured with: * 1000 sample users of the `user.#` convention * 1000 other users of a `json.user.#` convention * * A small number of patients under `ou=patients,dc=example,dc=com` * A small number of companies and their users under `ou=customers,dc=example,dc=com` * For each company, a group of admins at `cn=COMPANY Admins,ou=COMPANY,ou=customers,dc=example,dc=com` * A base entry for groups at `ou=groups,dc=example,dc=com` * Delegated Admin (version 4.4) at path `/delegator` ** * Delegated Admin Resource Types for users, patients, customer users, companies, admin groups, and groups * Delegated Admin Rights for `user.0` to do anything and everything to all resource types * Delegated Admin Rights for each group of `cn=COMPANY Admins` to do anything and everything their customer users * Two consent definitions `share-call-history` and `share-health-treatment-plan` * Consent API with unprivileged/user OAuth scope `urn:pingdirectory:consent` * Consent API service account (i.e. basic auth) `Consent Admin` (password `<PASSWORD>`) * Privacy Dashboard at path `/privacy-dashboard` ** * Privacy Dashboard supports fine-grained consent for `share-call-history` and `share-health-treatment-plan` * Mock Access Token Validator with Identity Mapper that matches the `sub` claim to `uid` attribute * JWT Validator with Identity Mapper that matches the `email` claim to `mail` attribute * PingFederate Validator and Identity Mapper that matches the `email` claim to `mail` attribute PingDataGovernance will be configured with: * API Gateway endpoints mapping various `/open-banking/v2.0` API to [the mock ASPSP's](https://github.com/babbtx/mock-simple-aspsp) `/OpenBanking/v2` * SCIM pass-through to sample users in PingDirectory * Mock Access Token Validator with Token Resource Lookup Method that matches the `sub` claim to SCIM `uid` attribute * JWT Validator with Token Resource Lookup Method that matches the `email` claim to the SCIM `mail` attribute Policy Admin GUI will be configured with: * Demo authentication * Demo policies for and Trust Framework for enforcing consent-authorized access to `/open-banking/v2.0/accounts` \* "JSON users" have a `telephoneJson` multivalued JSON attribute.<br> \** Delegated Admin and the Privacy Dashboard require PingFederate and/or PingOne for login. More information below.<br> # Configuration These server profiles are more easily configured through the Docker [project](https://gitlab.corp.pingidentity.com/davidbabbitt/pingdata-lab-docker) or the Ansible [project](https://gitlab.corp.pingidentity.com/davidbabbitt/pingdata-lab-ansible) that consume them. Most noteably, this project does not contain an OAuth server, even though they depend on one for Delegated Admin and the Privacy Dashboard. You can use my PingFederate (you may need to ask me for help) or your own PingFederate or PingOne. Those projects will supply values for the following server profile variables: * `PING_LOCAL_HOST_NAME` - hostname for each server instance * `CN_ROOT_PASSWORD` - administrator password * `PD_LDAP_PORT` - port for LDAP connections to PingDirectory * `PD_LDAPS_PORT` - port for LDAPS connections to PingDirectory * `PD_HTTP_PORT` - port for HTTP connections to PingDirectory * `PD_HTTPS_PORT` - port for HTTPS connections to PingDirectory * `PDG_LDAP_PORT` - port for LDAP (management API) of PingDataGovernance * `PDG_LDAPS_PORT` - port for LDAPS (management API) of PingDataGovernance * `PDG_HTTPS_PORT` - port for HTTPS connections to PingDataGovernance * `PAP_HTTPS_PORT` - port for HTTPS connections to PingDataGovernance Policy Admin GUI * `PD_INTERNAL_HOSTNAME` - hostname that the other servers use to talk to PingDirectory * `PAP_INTERNAL_HOSTNAME` - hostname that the other servers use to talk to PingDataGovernance-PAP * `PF_EXTERNAL_HOSTNAME` - hostname for PingFederate, used by Delegated Admin * `PF_HTTPS_PORT` - runtime https port for PingFederate, used by Delegated Admin * `OAUTH2_SERVER_BASE_URL` - OAuth server base URL, like https://pf.example.com * `OAUTH2_JWKS_URL` - JWKS endpoint for *OAuth* (not OIDC) * `OAUTH2_AUTHORIZATION_URL` - OAuth login URL, used by Delegated Admin and Privacy Dashboard * `PRIVACY_DASHBOARD_CLIENT_ID` - Client identifier configured in the OAuth server for the Privacy Dashboard * `OPEN_BANKING_BASE_URL` - Base URL for the mock ASPSP, like `https://babbtx-aspsp.herokuapp.com`<file_sep>/server-profiles/pingdirectory/pd.profile/server-root/pre-setup/webapps/privacy-dashboard/assets/config.js /* * This file can be used to override any environment vars from compile time. * * To use: * $ cp example.config.js config.js * $ vi config.js * * And customize for your deployment environment. * */ (function(window) { window.RuntimeConfig = {}; /* * If you are deploying this app on your PingDirectory, * like in the `webapps` directory, * use this value instead. */ window.RuntimeConfig.PD_HOST_PORT = window.location.origin; /* * The https URL where the privacy dashboard will redirect for login. */ window.RuntimeConfig.OAUTH2_AUTHORIZATION_URL = "${OAUTH2_AUTHORIZATION_URL}"; /* * The client id the privacy dashboard will use to identify itself to the authorization server. */ window.RuntimeConfig.OAUTH2_CLIENT_ID = "${PRIVACY_DASHBOARD_CLIENT_ID}"; /* * URL for mock bank API */ window.RuntimeConfig.OPEN_BANKING_ACCOUNTS_URL = "${OPEN_BANKING_ACCOUNTS_URL}"; })(window); <file_sep>/server-profiles/pingdatagovernance/server-root/pre-setup/webapps/delegator/app/precache-manifest.80fd044951242aebcd111756118c5402.js self.__precacheManifest = (self.__precacheManifest || []).concat([ { "revision": "b7fc7c6e1527aee6d344339a6f337686", "url": "/delegator/index.html" }, { "revision": "deadd0f73b0fe20b3a08", "url": "/delegator/static/css/2.2f3537af.chunk.css" }, { "revision": "9ddec5a2d66118ccc255", "url": "/delegator/static/css/main.40608eb6.chunk.css" }, { "revision": "deadd0f73b0fe20b3a08", "url": "/delegator/static/js/2.8b252563.chunk.js" }, { "revision": "9ddec5a2d66118ccc255", "url": "/delegator/static/js/main.d4a4089b.chunk.js" }, { "revision": "e5c7974aca8fd5d70837", "url": "/delegator/static/js/runtime~main.88cd2ac6.js" }, { "revision": "69d0f1119ae0049bba32415feeba5e7c", "url": "/delegator/static/media/flags.69d0f111.png" }, { "revision": "4728d3c7e389a3a1a6fea7afa0009ca4", "url": "/delegator/static/media/iconfont.4728d3c7.woff2" }, { "revision": "b2abb4387fd9601c2d64e03ddbdac963", "url": "/delegator/static/media/iconfont.b2abb438.svg" }, { "revision": "c575329d4b24516b75ca55d7e1598bdc", "url": "/delegator/static/media/iconfont.c575329d.woff" }, { "revision": "dfcfae2b22feea2d05249b2715714729", "url": "/delegator/static/media/iconfont.dfcfae2b.ttf" }, { "revision": "84eed5a2e1bca9ec0cb30ef528bfef03", "url": "/delegator/static/media/logo-pingaccess.84eed5a2.svg" }, { "revision": "4e46725f4880790f72fd3ec9115f335f", "url": "/delegator/static/media/logo-pingfed.4e46725f.svg" }, { "revision": "6dfdd48cc3ede60aac855e494912b7e2", "url": "/delegator/static/media/logo-pingone.6dfdd48c.svg" }, { "revision": "16f2287c8cb5754063c75b3ee4d4bcf7", "url": "/delegator/static/media/logo-uilibrary.16f2287c.svg" } ]);
5bfa1b801b533c1648067db2268ad5abd3144d8d
[ "JavaScript", "Markdown" ]
4
JavaScript
chrisleggett/k8s-banking-demo
34a21c4f93f4986c0f2e4bd90f644351c1e44916
1a8a7ebd9d0a6cef1bd20df825d7a2d829abc519
refs/heads/master
<repo_name>MiguelDeLaRosa90/Desarrollo_Interfaces<file_sep>/src/Tema5/Progreso.java package Tema5; import javax.swing.JProgressBar; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public class Progreso extends JProgressBar implements ChangeListener{ public Progreso() { // TODO Auto-generated constructor stub addChangeListener(this); } @Override public void stateChanged(ChangeEvent arg0) { // TODO Auto-generated method stub System.out.println("texto para enrique: "+this.getValue()); } } <file_sep>/src/tema3/TresEnRaya.java package tema3; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import java.awt.GridLayout; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class TresEnRaya extends JFrame { private JPanel contentPane; private int turno = 0; private boolean estado_juego = true; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { TresEnRaya frame = new TresEnRaya(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public TresEnRaya() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JPanel panel = new JPanel(); panel.setBounds(5, 5, 419, 201); contentPane.add(panel); panel.setLayout(new GridLayout(3, 3, 0, 0)); Btn3inrow btn1 = new Btn3inrow(); btn1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { turno++; if (turno%2==0) { btn1.activate(1); }else { btn1.activate(2); } } }); panel.add(btn1); Btn3inrow btn2 = new Btn3inrow(); btn2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { turno++; if (turno%2==0) { btn2.activate(1); }else { btn2.activate(2); } } }); panel.add(btn2); Btn3inrow btn3 = new Btn3inrow(); btn3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { turno++; if (turno%2==0) { btn3.activate(1); }else { btn3.activate(2); } } }); panel.add(btn3); Btn3inrow btn4 = new Btn3inrow(); btn4.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { turno++; if (turno%2==0) { btn4.activate(1); }else { btn4.activate(2); } } }); panel.add(btn4); Btn3inrow btn5 = new Btn3inrow(); btn5.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { turno++; if (turno%2==0) { btn5.activate(1); }else { btn5.activate(2); } } }); panel.add(btn5); Btn3inrow btn6 = new Btn3inrow(); btn6.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { turno++; if (turno%2==0) { btn6.activate(1); }else { btn6.activate(2); } } }); panel.add(btn6); Btn3inrow btn7 = new Btn3inrow(); btn7.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { turno++; if (turno%2==0) { btn7.activate(1); }else { btn7.activate(2); } } }); panel.add(btn7); Btn3inrow btn8 = new Btn3inrow(); btn8.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { turno++; if (turno%2==0) { btn8.activate(1); }else { btn8.activate(2); } } }); panel.add(btn8); Btn3inrow btn9 = new Btn3inrow(); btn9.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { turno++; if (turno%2==0) { btn9.activate(1); }else { btn9.activate(2); } } }); panel.add(btn9); JPanel panel_1 = new JPanel(); panel_1.setBounds(5, 211, 419, 39); contentPane.add(panel_1); panel_1.setLayout(new GridLayout(1, 2, 0, 0)); JButton btnNueva = new JButton("NUEVA PARTIDA"); btnNueva.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { btn1.clear(); btn2.clear(); btn3.clear(); btn4.clear(); btn5.clear(); btn6.clear(); btn7.clear(); btn8.clear(); btn9.clear(); } }); panel_1.add(btnNueva); JButton btnPause = new JButton("PAUSEEEE"); btnPause.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (estado_juego) { //bloquear todos los botones btn1.setEnabled(true); estado_juego = false; }else { if (btn1.getStatus()>0) btn1.setEnabled(false); estado_juego = true; } } }); panel_1.add(btnPause); } } <file_sep>/src/tema1/InterfazCalculadora.java package tema1; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JTextField; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JButton; import javax.swing.JPanel; import java.awt.GridLayout; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JTextArea; import javax.swing.JScrollPane; public class InterfazCalculadora { private JFrame frame; private JTextField textOper; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { InterfazCalculadora window = new InterfazCalculadora(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public InterfazCalculadora() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.setBounds(100, 100, 450, 420); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); textOper = new JTextField(); textOper.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); textOper.setBounds(10, 124, 414, 20); frame.getContentPane().add(textOper); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(20, 30, 404, 83); frame.getContentPane().add(scrollPane); JTextArea textLog = new JTextArea(); scrollPane.setViewportView(textLog); JLabel lblLog = new JLabel("Log:"); lblLog.setBounds(21, 11, 46, 14); frame.getContentPane().add(lblLog); JPanel panel = new JPanel(); panel.setBounds(27, 155, 272, 215); frame.getContentPane().add(panel); panel.setLayout(new GridLayout(0, 3, 0, 0)); JButton boton7 = new JButton("7"); boton7.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String texto_old = textOper.getText(); texto_old = texto_old.concat("7"); textOper.setText(texto_old); } }); panel.add(boton7); JButton boton8 = new JButton("8"); boton8.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String texto_old = textOper.getText(); texto_old = texto_old.concat("8"); textOper.setText(texto_old); } }); panel.add(boton8); JButton boton9 = new JButton("9"); boton9.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String texto_old = textOper.getText(); texto_old = texto_old.concat("9"); textOper.setText(texto_old); } }); panel.add(boton9); JButton boton4 = new JButton("4"); boton4.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String texto_old = textOper.getText(); texto_old = texto_old.concat("4"); textOper.setText(texto_old); } }); panel.add(boton4); JButton boton5 = new JButton("5"); boton5.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String texto_old = textOper.getText(); texto_old = texto_old.concat("5"); textOper.setText(texto_old); } }); panel.add(boton5); JButton boton6 = new JButton("6"); boton6.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String texto_old = textOper.getText(); texto_old = texto_old.concat("6"); textOper.setText(texto_old); } }); panel.add(boton6); JButton boton1 = new JButton("1"); boton1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String texto_old = textOper.getText(); texto_old = texto_old.concat("1"); textOper.setText(texto_old); } }); panel.add(boton1); JButton boton2 = new JButton("2"); boton2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String texto_old = textOper.getText(); texto_old = texto_old.concat("2"); textOper.setText(texto_old); } }); panel.add(boton2); JButton boton3 = new JButton("3"); boton3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String texto_old = textOper.getText(); texto_old = texto_old.concat("3"); textOper.setText(texto_old); } }); panel.add(boton3); JButton btnNewButton_11 = new JButton(""); panel.add(btnNewButton_11); JButton boton0 = new JButton("0"); boton0.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String texto_old = textOper.getText(); texto_old = texto_old.concat("0"); textOper.setText(texto_old); } }); panel.add(boton0); JButton btnNewButton_3 = new JButton(""); panel.add(btnNewButton_3); JPanel panel_1 = new JPanel(); panel_1.setBounds(331, 155, 93, 215); frame.getContentPane().add(panel_1); panel_1.setLayout(new GridLayout(0, 1, 0, 0)); JButton botonAC = new JButton("AC"); botonAC.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String texto_old = textOper.getText(); texto_old = texto_old.concat("6"); textOper.setText(""); JOptionPane.showMessageDialog(panel, "Borrado","texto en ventana",JOptionPane.ERROR_MESSAGE); } }); panel_1.add(botonAC); JButton botonDEL = new JButton("DEL"); botonDEL.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String texto_old = textOper.getText(); texto_old = texto_old.concat("6"); textOper.setText(""); } }); panel_1.add(botonDEL); JButton botonDIV = new JButton("/"); botonDIV.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String texto_old = textOper.getText(); texto_old = texto_old.concat("/"); textOper.setText(texto_old); } }); panel_1.add(botonDIV); JButton botonMULT = new JButton("*"); botonMULT.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String texto_old = textOper.getText(); texto_old = texto_old.concat("*"); textOper.setText(texto_old); } }); panel_1.add(botonMULT); JButton botonRESTA = new JButton("-"); botonRESTA.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String texto_old = textOper.getText(); texto_old = texto_old.concat("-"); textOper.setText(texto_old); } }); panel_1.add(botonRESTA); JButton botonSUMA = new JButton("+"); botonSUMA.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String texto_old = textOper.getText(); texto_old = texto_old.concat("+"); textOper.setText(texto_old); } }); panel_1.add(botonSUMA); JButton botonIGUAL = new JButton("="); botonIGUAL.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String texto_old = textOper.getText(); texto_old = texto_old.concat("="); textLog.append(textOper.getText()+ "\r\n"); textOper.setText(""); } }); panel_1.add(botonIGUAL); } } <file_sep>/src/Tema6/testCalculadora.java package Tema6; import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class testCalculadora { Calculadora calc; @BeforeClass public static void beforeClass() { System.out.println("beforeClass"); } @org.junit.AfterClass public static void AfterClass() { System.out.println("afterClass"); } @Before public void before() { System.out.println("before"); calc = new Calculadora(); } @After public void after() { System.out.println("After"); } @Test public void TestSumar() { System.out.println("Sumar"); int num1 = 2; int num2 = 3; int expected = 5; int sumar = calc.sumar(num1, num2); assertEquals(expected, sumar); } @Test public void TestResta() { System.out.println("Restar"); int num1 = 2; int num2 = 3; int expected = -1; int restar = calc.resta(num1, num2); assertEquals(expected, restar); } @Test public void TestDividir() { System.out.println("dividir"); double num1 = 4; double num2 = 2; double expected = 2; double division = calc.dividir(num1, num2); System.out.println("division"+division); assertEquals(expected, division, 0.001); } } <file_sep>/src/Tema7/InterfazCliente.java package Tema7; import java.awt.EventQueue; import javax.swing.JFrame; import java.awt.SystemColor; import java.awt.Color; import javax.swing.JPanel; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.JButton; import javax.swing.JTextArea; import javax.swing.UIManager; import javax.swing.JList; import javax.swing.JOptionPane; import java.awt.event.ActionListener; import java.net.InetAddress; import java.net.UnknownHostException; import java.awt.event.ActionEvent; public class InterfazCliente { private JFrame frame; private JTextField textFieldClient_nick; private JTextField textFieldClient_IP; private JLabel lblClientip; private JTextField textFieldPuerto; private JTextField textFieldIP; public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { InterfazCliente window = new InterfazCliente(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } public InterfazCliente() { initialize(); } private void initialize() { frame = new JFrame(); frame.getContentPane().setBackground(new Color(153, 204, 255)); frame.setBackground(new Color(176, 196, 222)); frame.setBounds(100, 100, 498, 450); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); JPanel panel = new JPanel(); panel.setBackground(SystemColor.controlShadow); panel.setBounds(10, 11, 304, 95); frame.getContentPane().add(panel); panel.setLayout(null); JLabel lblClientnick = new JLabel("Client_nick"); lblClientnick.setBounds(10, 11, 71, 14); panel.add(lblClientnick); textFieldClient_nick = new JTextField(); textFieldClient_nick.setBounds(86, 8, 129, 20); panel.add(textFieldClient_nick); textFieldClient_nick.setColumns(10); lblClientip = new JLabel("Client_IP"); lblClientip.setBounds(10, 36, 66, 14); panel.add(lblClientip); textFieldClient_IP = new JTextField(); textFieldClient_IP.setBounds(86, 36, 129, 20); panel.add(textFieldClient_IP); textFieldClient_IP.setColumns(10); JButton btnLogin = new JButton("Login"); btnLogin.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(!textFieldClient_nick.getText().equals("")) { String contrasenia = JOptionPane.showInputDialog(frame, "Introduce la contraseña"); if(contrasenia.equals("12345")) { try { textFieldClient_IP.setText(InetAddress.getLocalHost().getHostAddress()); } catch (UnknownHostException e) { e.printStackTrace(); } } else { JOptionPane.showMessageDialog(frame, "Contraseña inválida", "Error",JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "Introduce un usuario en client_nick"); } } }); btnLogin.setBounds(225, 11, 69, 45); panel.add(btnLogin); JLabel lblPuerto = new JLabel("Puerto"); lblPuerto.setBounds(10, 70, 46, 14); panel.add(lblPuerto); textFieldPuerto = new JTextField(); textFieldPuerto.setText("5555"); textFieldPuerto.setBounds(52, 67, 86, 20); panel.add(textFieldPuerto); textFieldPuerto.setColumns(10); JLabel lblIp = new JLabel("IP"); lblIp.setBounds(156, 70, 23, 14); panel.add(lblIp); textFieldIP = new JTextField(); textFieldIP.setBounds(178, 67, 116, 20); panel.add(textFieldIP); textFieldIP.setColumns(10); JTextArea textArea = new JTextArea(); textArea.setBounds(10, 117, 304, 174); frame.getContentPane().add(textArea); JTextArea textArea_1 = new JTextArea(); textArea_1.setBounds(10, 303, 304, 44); frame.getContentPane().add(textArea_1); JButton btnEnviar = new JButton("Enviar"); btnEnviar.setBounds(225, 368, 89, 32); frame.getContentPane().add(btnEnviar); JButton btnLimpiar = new JButton("Limpiar"); btnLimpiar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textFieldClient_nick.setText(""); textFieldClient_IP.setText(""); textFieldIP.setText(""); } }); btnLimpiar.setBounds(126, 368, 89, 32); frame.getContentPane().add(btnLimpiar); JLabel lblConectados = new JLabel("Conectados"); lblConectados.setBounds(370, 11, 78, 14); frame.getContentPane().add(lblConectados); JList list = new JList(); list.setBounds(324, 36, 148, 364); frame.getContentPane().add(list); } }
fc87958529ef47c96a69d6b8a349f42a8ad9bac4
[ "Java" ]
5
Java
MiguelDeLaRosa90/Desarrollo_Interfaces
d04c1828744bdad355ed71b888302459e4e74ebf
e51a6b87ba55c1cf1c694f920af278472f4ef090
refs/heads/master
<file_sep>using UnityEngine; using System.Collections; using UnityEngine.UI; public class Interact : MonoBehaviour { public string interactButton; public float interactDistance = 3f; public LayerMask interactLayer; public Image interactIcon; public bool isInteracting; void Start () { if (interactIcon != null) { interactIcon.enabled = false; } } void Update () { Ray ray = new Ray(transform.position, transform.forward); RaycastHit hit; if (Physics.Raycast(ray, out hit, interactDistance)) { if (isInteracting == false) { if (interactIcon != null) { interactIcon.enabled = true; } if (Input.GetButtonDown(interactButton)) { if (hit.collider.CompareTag("Door1")) { hit.collider.GetComponent<Door>().ChangeDoorState(); } else if (hit.collider.CompareTag("Key")) { hit.collider.GetComponent<Key>().UnlockDoor(); } else if (hit.collider.CompareTag("Door2")) { hit.collider.GetComponent<Door2>().ChangeDoorState(); } else if (hit.collider.CompareTag("Note")) { hit.collider.GetComponent<Note>().ShowNoteImage(); } } } } } } <file_sep>using UnityEngine; using System.Collections; public class ChangeAmbienceTrigger : MonoBehaviour { public AudioClip hallway; private ChangeAmbience theAM; void Start () { theAM = FindObjectOfType<ChangeAmbience>(); } void OnTriggerEnter(Collider other) { if (other.CompareTag("Player")) { if (hallway != null) { theAM.ChangeMusic(hallway); } } } void Update () { } } <file_sep>using UnityEngine; using System.Collections; public class Key : MonoBehaviour { public Door myDoor; public AudioClip keyPickUpNoise; public AudioSource audioSource; void Start() { audioSource = GetComponent<AudioSource>(); } public void UnlockDoor() { myDoor.isLocked = false; audioSource.PlayOneShot(keyPickUpNoise); StartCoroutine("WaitForSelfDestruct"); } IEnumerator WaitForSelfDestruct() { yield return new WaitForSeconds(keyPickUpNoise.length); Destroy(gameObject); } } <file_sep>using UnityEngine; using System.Collections; public class ChangeAmbience : MonoBehaviour { public AudioSource colliderMusic; void Start () { } public void ChangeMusic(AudioClip music) { colliderMusic.Stop(); colliderMusic.clip = music; colliderMusic.Play(); } } <file_sep>using UnityEngine; using System.Collections; public class Flashlight : MonoBehaviour { // Use this for initialization public Light flashLight; public AudioSource audioSource; public AudioClip soundFlashLightToggle; private bool isActive = true; void Start () { } // Update is called once per frame void Update () { if (Input.GetKeyDown(KeyCode.Mouse1)) { if (isActive == false) { flashLight.enabled = true; isActive = true; audioSource.PlayOneShot(soundFlashLightToggle); } else if (isActive == true) { flashLight.enabled = false; isActive = false; audioSource.PlayOneShot(soundFlashLightToggle); } } } }
892f80afed53b899434df0ba7c5f236e6b773fb2
[ "C#" ]
5
C#
sldghamr/hallway
33cfad67bb17e81216c9b6f0dc5f97e408eb33fb
c0164dded525a9f1c8a4f96e9efb85c831a93ecb
refs/heads/master
<file_sep>#include "Vertex.h" using namespace std; Vertex::Vertex() { m_key = 0; m_size = 0; m_pEHead = NULL; m_pNext = NULL; } Vertex::Vertex(int key) { m_key = key; m_size = 0; m_pEHead = NULL; m_pNext = NULL; } Vertex::~Vertex() { } void Vertex::SetNext(Vertex* pNext) {//set next vertex m_pNext = pNext; } int Vertex::GetKey() const {//return ket of vertex return m_key; } Vertex* Vertex::GetNext() const {//return next vertex return m_pNext; } int Vertex::Size() const {//return edge size of vertex return m_size; } void Vertex::AddSize() {//size = size + 1 m_size = m_size + 1; } void Vertex::AddEdge(int edgeKey, int weight) {//add edge in vertex Edge* A = m_pEHead; if (A == NULL) {//if edge is empty m_pEHead = new Edge(edgeKey, weight); return; } else { while (A->GetNext()) {//else A = A->GetNext(); } Edge * n_p = new Edge(edgeKey, weight); A->SetNext(n_p); } m_size++; return; } Edge* Vertex::GetHeadOfEdge() const {//return head edge return m_pEHead; } void Vertex::Clear() {//delete all of edge in vertex Edge *B = m_pEHead; Edge *C; while (B) { C = B; B = B->GetNext(); delete C; } }<file_sep>#include "Graph.h" #include<utility> #include<iostream> #include<fstream> #include<cstring> using namespace std; class Manager { public: AVLTree * avl;//value declare Graph * gp;//value declare char * cmd;//value declare int iter;//value declare char * two;//value declare char * three;//value declare char * four;//value declare int num;//value declare int zzzz;//value declare AVLNode * prin;//value declare public: Manager(); ~Manager(); ofstream flog;//value declare ifstream fin;//value declare void run(const char * command);//fucntion declare bool LOAD();//fucntion declare bool INSERT();//fucntion declare bool PRINT_AVL();//fucntion declare bool SEARCH_AVL();//fucntion declare bool DELETE_AVL();//fucntion declare bool BUILD_GP();//fucntion declare bool PRINT_GP();//fucntion declare bool BUILD_MST();//fucntion declare bool PRINT_MST();//fucntion declare void EXIT();//fucntion declare AVLNode * si;//value declare AVLNode * inorder_s(AVLNode * a);//fucntion declare void printErrorCode(int n, const char * cmdname);//fucntion declare void printSuccessCode(const char * cmdname);//fucntion declare }; <file_sep> // MFCApplication1View.h : CMFCApplication1View 클래스의 인터페이스 // #pragma once class CMFCApplication1View : public CView { protected: // serialization에서만 만들어집니다. CMFCApplication1View(); DECLARE_DYNCREATE(CMFCApplication1View) // 특성입니다. public: CMFCApplication1Doc* GetDocument() const; // 작업입니다. public: // 재정의입니다. public: virtual void OnDraw(CDC* pDC); // 이 뷰를 그리기 위해 재정의되었습니다. virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: virtual BOOL OnPreparePrinting(CPrintInfo* pInfo); virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo); // 구현입니다. public: virtual ~CMFCApplication1View(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // 생성된 메시지 맵 함수 protected: DECLARE_MESSAGE_MAP() public: afx_msg void OnPaint();//큐브그림 출력 afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);//kyboard 입력 처리 //마우스 입력 이벤트 afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnLButtonUp(UINT nFlags, CPoint point); //메뉴 리소스 이벤트 afx_msg void OnClr();//출력메뉴-색상 On afx_msg void OnClrNum();//출력메뉴-색생 Off afx_msg void Log_On();//기록메뉴- 기록 on afx_msg void Log_Off();//기록메뉴- 기록 Off bool Color_On_flag;//0: color off , 1: color on bool Save_rotation_flag;//1이면 회전 기록 bool Save_move_flag;//1이면 회전기록 int Turn_count;//턴의 횟수 bool m_bDragFlag_toR;//오른쪽으로 드래그 시작여부 (true: ok, false: no) bool m_bDragFlag_toL;//왼쪽으로 시작여부 (true: ok, false: no) int org_x, org_y;//드래그 시 처음 좌표 int new_x, new_y;//드래그 시 마지막 좌표 CFile outFile;//log 파일을 처리하기 위한 CFile }; #ifndef _DEBUG // MFCApplication1View.cpp의 디버그 버전 inline CMFCApplication1Doc* CMFCApplication1View::GetDocument() const { return reinterpret_cast<CMFCApplication1Doc*>(m_pDocument); } #endif <file_sep>#include <iostream> using namespace std; int main() { int two_d_array[2][3] = {//make array {1,2,3},//input {4,5,6} }; int* a = 0, * b = 0, * c = 0, * d = 0, * e, * f, (*g)[3], * h, * i, * j;//declare a = &two_d_array[0][0];//address of [0][0]==1 b = &two_d_array[1][0];//address of [1][0]==4 c = &two_d_array[0][1];//address of [0][1]==2 d = &two_d_array[0][2];//address of [0][2]==3 h = a;//h->a->1 i = a;//i->a->1 j = c;//j->c->2 e = two_d_array[0];//e->1,2,3 f = two_d_array[1];//f->4,5,6 g = two_d_array;//g->1,2,3,4,5,6 cout << "First Condition" << endl; cout << "a:" << *a << endl;//print cout << "b:" << *b << endl; cout << "c:" << *c << endl; cout << "d:" << *d << endl; cout << "h:" << *h << endl; cout << "i:" << *i << endl; cout << "j:" << *j << endl << endl; cout << "Second Condition" << endl; cout << "1-a:" << a << endl;//print cout << "1-h:" << h << endl; cout << "1-i:" << i << endl; cout << "2-c:" << c << endl; cout << "2-j:" << j << endl; cout << "3-d:" << d << endl; cout << "4-b:" << b << endl; cout << "5-?:" << b + 1 << endl;//shift 4bit cout << "6-?:" << b + 2 << endl << endl;//shift 8 bit cout << "Third Condition" << endl; cout << "e:" << e[0] <<" "<<e[1] << " " <<e[2]<<endl; cout << "f:" << f[0] << " " <<f[1] << " " <<f[2]<<endl; cout << "g:"; for(int z =0; z<2;z++) for (int x = 0; x < 3; x++) { cout << g[z][x]<< " "; } cout << endl; }<file_sep>#pragma once #include "pch.h" class Block { private: int m_number, b_x, b_y;//각 블럭의 숫자와 좌표x,y //Block의 사방의 블락을 가리키는 포인터 Block* p_Up; Block* p_Down; Block* p_Left; Block* p_Right; public: Block(); ~Block(); //data handle int getNum(); int getX(); int getY(); void setNum(int new_num); void setX(int newx); void setY(int newy); //link handle void setUp(Block* NewNode); void setDown(Block* NewNode); void setRight(Block* NewNode); void setLeft(Block* NewNode); Block* getUp(); Block* getDown(); Block* getRight(); Block* getLeft(); }; <file_sep>#pragma once #include <iostream> using namespace std; class Node { public: Node* nextNode;//declare Node* preNode;//declare string name;//declare string professor;//declare int grade=0;//declare int position = 0;//declare }; class List { private: Node* head = new Node();//declare Node* tail = new Node();//declare public: List() { head = nullptr;//declare tail = nullptr;//declare } ~List() { } void insert_beginning(Node* newNode);//declare void insert_last(Node* newNode);//declare bool insert_position(Node* newNode,int posi);//declare void Display();//declare void reposition();//declare int maxposition();//declare bool delete_lecture(string u_name);//declare bool search_lecture(string u_name);//declare void update_lecture(Node* newNode,string u_name);//declare bool serch_lec(string u_name);//declare bool search_pro(string u_name);//declare bool search_grade(int g);//declare void sort_ascending();//declare void reverse();//declare void delete_lecture2(string u_name);//declare };<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <iostream> using namespace std; class ThreeSixNine {//declare class public: char TSN[3] = { NULL, }; int number = 0; void print369(int number);//print369 func }; void ThreeSixNine::print369(int number) { for (int a = 1; a <= number; a++) {//1 ~num _itoa(a, TSN, 10);//num to char int cnt = 0; for (int b = 0; b < 3; b++) {//if number is 3 or 6 or 9 if (TSN[b] == '3' || TSN[b] == '6' || TSN[b] == '9') cnt++;//get count } if (cnt == 1) {//if count is 1 cout << '!' << " "; } else if (cnt == 2) {//count is 2 cout << "!!" << " "; } else {//else print num cout << a << " "; } if (a % 10 == 0)//cout endl each 10 cout << endl; } } int main() { int num = 0; ThreeSixNine game; cout << "input your number" << endl; cin >> num; game.print369(num);//print cout << endl; return 0; } <file_sep>#include "SoccerPlayerData.h" #include <iostream> class TreeNode { friend class BinarySearchTree; friend class TransferWindowManager; private: SoccerPlayerData m_data; TreeNode* m_left; TreeNode* m_right; public: TreeNode() :m_left(NULL), m_right(NULL) {}// function declaer ~TreeNode() { }// function declaer TreeNode(SoccerPlayerData & data, TreeNode* left = NULL, TreeNode* right = NULL)// function declaer { //make player this->m_data = data; this->m_left = left; this->m_right = right; } friend std::ostream& operator<<(std::ostream& os, const TreeNode* node)//inorder { if (node != NULL) {//code to print in-order traversal of a binary search tree os << node->m_left; os << node->m_data << std::endl; os << node->m_right; } return os; } }; <file_sep>#include "TreeNode.h" #include <iostream> #include <cstring> #include <string> class BinarySearchTree { friend class TransferWindowManager; private: TreeNode * m_root; //root public: BinarySearchTree() { m_root = NULL; } //root is NULL BinarySearchTree(SoccerPlayerData& data); //funtion declaer ~BinarySearchTree();//funtion declaer void insert(SoccerPlayerData& data);//funtion declaer void insert_arr(SoccerPlayerData & data);//funtion declaer void deletion(int ability); ////funtion declaer ability = key void Clear(TreeNode * root);//funtion declaer friend std::ostream& operator<<(std::ostream& os, const BinarySearchTree& tree)//inorder { while (tree.m_root != NULL)//while root is NULL { // code to print in-order traversal of a binary search tree os << tree.m_root; return os; } } }; <file_sep>#include "CityData.h" #include <iostream> #include <stack> using namespace std; class AVLNode { private: CityData * pCityData; // CityData Pointer ���� ���� AVLNode * pLeft; // AVL Left Pointer ���� AVLNode * pRight; // AVL Right Pointer ������ int mBF; // Balance Factor �뷱�� ���� public: AVLNode(); ~AVLNode(); int u; int v; CityData * data1; CityData * data2; int wei; CityData * GetCityData(); // Get CityData Pointer AVLNode * GetLeft(); // Get AVL Left Pointer AVLNode * GetRight(); // Get AVL Right Pointer int GetmBF(); // Get Balance Factor bool operator <(AVLNode &AVLNode) {//operator node return this->pCityData->Getname() < AVLNode.GetCityData()->Getname(); } void SetCityData(CityData * node); // Set CityData Pointer void SetLeft(AVLNode * node); // Set AVL Left Pointer void SetRight(AVLNode * node); // Set AVL Right Pointer void SetmBF(int n); // Set Balance Factor }; <file_sep># define _CRT_SECURE_NO_WARNINGS #pragma warning(disable:4996) #include "Manager.h" #include <stdlib.h> #include <iostream> #include <fstream> #include <cstring> using namespace std; Manager::Manager() { flog.open("log.txt", ios::app); flog.setf(ios::fixed); avl = new AVLTree(&flog); gp = new Graph(&flog); iter = 0; cmd = NULL; } Manager::~Manager() { flog.close(); } void Manager::run(const char * command) { fin.open(command);//open text cmd = new char[40];//value declare while (!fin.eof()) { //whille until read text file is null iter = iter + 1; //iter num fin.getline(cmd, 40);//get command char * one = strtok(cmd, " "); //get one and strto two = strtok(NULL, " "); //two strtok three = strtok(NULL, " "); four = strtok(NULL, " "); if (!strcmp(one, "LOAD")) { if (LOAD() == true) { //if LOAD printSuccessCode("LOAD");//print success code } else { printErrorCode(100, "LOAD");//print error code } } else if (!strcmp(one, "INSERT")) { if (INSERT() == true) { //print success code printSuccessCode("INSERT");//print success code } else {//print error code printErrorCode(200, "INSERT"); } } else if (!strcmp(one, "PRINT_AVL")) { flog << "==> command " << iter << ") " << "PRINT_AVL" << endl; if (PRINT_AVL() == true)//print success code {//if command is print AVL flog << "Success" << endl;//if command is success print success code } else { printErrorCode(300, "PRINT_AVL"); } } else if (!strcmp(one, "SEARCH_AVL")) {//if command is SEARCH_AVL flog << "==> command " << iter << ") " << "SEARCH_AVL " << two << endl; if (SEARCH_AVL() == false) //if fucntion is false { flog << "==> command " << iter << ") " << "SEARCH_AVL" << endl; flog << "Error code: " << "500" << endl; //print error code } } else if (!strcmp(one, "DELETE_AVL")) {//if command is DELETE_AVL flog << "==> command " << iter << ") " << "DELETE_AVL " << two << endl; if (DELETE_AVL() == true) { //if delete success print Success flog << "Success" << endl; } else { //false print error code printErrorCode(400, "DELETE_AVL"); } } else if (!strcmp(one, "BUILD_GP")) {//if command is BUILD_GP if (BUILD_GP() == true) {//if fucntion success printSuccessCode("BUILD_GP"); //print success code } else { //if print errot code printErrorCode(600, "BUILD_GP"); } } else if (!strcmp(one, "PRINT_GP")) {//if command is print_GP flog << "==> command " << iter << ") " << "PRINT_GP " << endl; if (PRINT_GP() == false)//if fucntion is false { printErrorCode(700, "PRINT_GP"); //print error code } } else if (!strcmp(one, "BUILD_MST")) { flog << "==> command " << iter << ") " << "BUILD_MST " << endl; if (BUILD_MST() == true) {//BUILD_MST() is true flog << "Success" << endl; } else { printErrorCode(800, "BUILD_MST"); } } else if (!strcmp(one, "PRINT_MST")) { flog << "==> command " << iter << ") " << "PRINT_MST " << endl; if (PRINT_MST() == false) { //print MST printErrorCode(900, "PRINT_MST"); } } else if (!strcmp(one, "EXIT")) { flog << "==> command " << iter << ") " << "EXIT " << endl; flog << "Success" << endl; EXIT(); } else { printErrorCode(0, "Unknown"); } } fin.close(); return; } bool Manager::LOAD() { string line; //string line ifstream in("city_list.txt"); //open citylist if (in.fail()) return false; if (avl->Getroot() != NULL)//if avl is NULL return false; while (getline(in, line)) { char buff[100] = { 0 };//vlaue int num1 = 0; CityData * data; memset(buff, 0, sizeof(buff));//make reset strncpy(buff, line.c_str(),sizeof(buff)-1);//copy in to arry if (strlen(buff) == 0) break; char * city_num = strtok(buff, "\t");//strtok num char * city_name = strtok(NULL, "\t");//strtok name char * coun_name = strtok(NULL, "\t");//strtok name num1 = atoi(city_num); data = new CityData; data->SetLocationId(num1);//set data data->Setname(city_name);//set data data->Setcountry(coun_name);//set data AVLNode * gp_node = new AVLNode();//make node gp_node->SetCityData(data); //set data avl->Insert(data); //insert data gp->insert_gp(gp_node, zzzz);//insert data zzzz++; } in.close(); return true; } bool Manager::INSERT() {//insert fucntion int num2 = atoi(two); CityData * data = new CityData; data->SetLocationId(num2); data->Setname(three); data->Setcountry(four); AVLNode * gp_node = new AVLNode(); gp_node->SetCityData(data); avl->Insert(data); gp->insert_gp(gp_node, zzzz); zzzz++; return true; } bool Manager::PRINT_AVL() {//print_avl AVLNode * node = avl->Getroot(); if (node) { avl->Print(node); //call fucntion return true; } else { return false; } } bool Manager::SEARCH_AVL() { num = atoi(two); if (num == 0) return false; AVLNode * ml = avl->Getroot();//get root AVLNode * temp = inorder_s(ml); if (temp == NULL) { return false; } else { flog << "("; flog << temp->GetCityData()->GetLocationId(); flog << ", "; flog << temp->GetCityData()->Getname(); flog << ", "; flog << temp->GetCityData()->Getcountry(); flog << ")"; flog << endl; } return true; } bool Manager::DELETE_AVL() {//delete AVL num = atoi(two); avl->Delete(num); return true; } bool Manager::BUILD_GP() {//build gp if (gp->Build(avl) == true) return true; else return false; } bool Manager::PRINT_GP() {//print gp if (gp == NULL) return false; gp->Print_GP(); return true; } bool Manager::BUILD_MST() { //build mst gp->Kruskal(); return true; } bool Manager::PRINT_MST() {//print mst gp->Print_MST(); return true; } void Manager::EXIT() { exit(1); } AVLNode * Manager::inorder_s(AVLNode * a) {//inorder if(a!=NULL) { if(a->GetLeft()) { inorder_s(a->GetLeft()); } if (a->GetCityData()->GetLocationId() == num) { si = a; } if(a->GetRight()) { inorder_s(a->GetRight()); } } else return NULL; return si; } void Manager::printErrorCode(int n, const char * cmdname) {//ERROR CODE PRINNT FUNCTION flog << "==> command " << iter << ") " << cmdname << endl; flog << "Error code: " << n << endl; } void Manager::printSuccessCode(const char * cmdname) {//SUCCESS CODE PRINNT FUNCTION flog << "==> command " << iter << ") " << cmdname << endl; flog << "Success" << endl; } <file_sep>#include <iostream> using namespace std; char map[3][3];//declare int x = 0, y = 0;//declare char end() { for (int a = 0; a < 3; a++) { for (int b = 0; b < 3; b++) { if (map[a][b] == map[a][b + 1] && b == 0) {//if row same char than make winner if (map[a][b + 1] == map[a][b + 2]) {//row winner return map[a][b];//return winner } } if (map[a][b] == map[a + 1][b] && a == 0) {//if col same char(O or X) then return winner if (map[a + 1][b] == map[a + 2][b]) {//col winner return map[a][b];//return winner } } if (map[a][b] == map[a + 1][b + 1] && a == 0 && b == 0) {//if Hanoi same char(O or X) then return winnier if (map[a + 1][b + 1] == map[a + 2][b + 2]) {//Hanoi winner(left ro right) return map[a][b];//return winner } } if (a == 0 && b == 2 && map[a][b] == map[a + 1][b - 1]) {//if Hanoi same char(O or X) then return winnier if (map[a + 1][b - 1] == map[a + 2][b - 2]) {//Hanoi winner (right to left) return map[a][b];//return winner } } else continue; } } } void player1() {//player 1 func cout << "[Play 1] Enter your location [x y] : "; cin >> x >> y;//get x y map[y][x] = 'O';//map [y][x] to 0 x = 0; y = 0;//reset } void player2() { cout << "[Play 2] Enter your location [x y] : "; cin >> x >> y; map[y][x] = 'X'; x = 0; y = 0; } void print() { cout << " X 0 1 2"; cout << endl;//print cout << "Y --- --- ---"; cout << endl; } void print_0() { for (int a = 0; a < 3; a++) { cout << a << " "; for (int b = 0; b < 3; b++) {//print map cout << "|"; if (map[a][b] != NULL) {//if map[a][b] is not null cout << " " << map[a][b] << " ";//print } else {//else cout << " ";//print hole } if (b == 2) {//print edge cout << "|"; cout << endl; cout << " --- --- ---"; } } cout << endl; } } int main() { bool cnt = true; while (1) {//while until occur winner or there is no space to put O or X char winner; int count = 0; print();//print print_0();//print O or X if (cnt == true) {//if cnt is true player1();//player1's turn cnt = false;//player 1 is done, cnt turn false } else if (cnt == false) {//if cnt is false player2();//turn to player 2 cnt = true;//turn to true player1 } winner = end(); if (winner == 'O') {//is winner is player 1 print(); print_0(); cout << "Winner is [Player 1] " << endl; break; } else if (winner == 'X') {//winner is player2 print(); print_0(); cout << "Winner is [Player 2]" << endl; break; } for (int a = 0; a < 3; a++) { for (int b = 0; b < 3; b++) {//check count if (map[a][b] != NULL) count++; } } if (count == 9) {//if count is 9 there is no space to put O or X print(); print_0(); cout << "Draw";//print Draw break; } } }<file_sep>//{{NO_DEPENDENCIES}} // Microsoft Visual C++에서 생성한 포함 파일입니다. // MFCApplication1.rc에서 사용되고 있습니다. // #define IDD_ABOUTBOX 100 #define IDP_OLE_INIT_FAILED 100 #define IDR_MAINFRAME 128 #define IDR_MFCApplication1TYPE 130 #define ID_WINDOW_MANAGER 131 #define ID_32771 32771 #define ID_32772 32772 #define ID_32773 32773 #define ID_32774 32774 #define Print_Clr 32775 #define Print_CLR_NUM 32776 #define Save_ROT 32777 #define ID_32778 32778 #define Save_MOV 32779 #define ID_32780 32780 #define ID_32781 32781 #define ID_32782 32782 #define ID_32783 32783 #define SAVE_ROT_ON 32784 #define SAVE_ROT_OFF 32785 #define SAVE_MOV_ON 32786 #define SAVE_MOV_OFF 32787 #define ID_32788 32788 #define ID_32789 32789 #define ID_32790 32790 #define ID_L_GF 32791 #define ID_GF_SDFDSFDF 32792 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 311 #define _APS_NEXT_COMMAND_VALUE 32793 #define _APS_NEXT_CONTROL_VALUE 1000 #define _APS_NEXT_SYMED_VALUE 310 #endif #endif <file_sep>#include "BinarySearchTree.h" #include <iostream> #include <string> class TransferWindowManager { //friend class BinarySearchTree; private: int m_budget; BinarySearchTree fwBST; BinarySearchTree mfBST; BinarySearchTree dfBST; BinarySearchTree gkBST; int fw_c; int mf_c; int df_c; int gk_c; BinarySearchTree fw_arr[20]; BinarySearchTree mf_arr[20]; BinarySearchTree df_arr[20]; BinarySearchTree gk_arr[20]; public: struct SoccerTeam //struct { SoccerPlayerData fw; SoccerPlayerData mf; SoccerPlayerData df; SoccerPlayerData gk; int sum_transfer_fee; //sum fee is int int sum_ability; SoccerTeam(); // function declaer SoccerTeam(SoccerPlayerData fw, SoccerPlayerData mf, SoccerPlayerData df, SoccerPlayerData gk);// function declaer friend std::ostream& operator<<(std::ostream& os, const SoccerTeam& team);// function declaer }; TransferWindowManager(std::string file_dir, int budget);// function declaer friend std::ostream& operator<<(std::ostream& os, const TransferWindowManager& manager);// print by position const SoccerTeam getBestTeam();// function declaer }; <file_sep>#define _CRT_SECURE_NO_WARNINGS #include "List.h" #include <iostream> using namespace std; void List::add(Node* newnode) { Node* new_node = new Node; new_node = newnode; if (head->nextNode == nullptr) {//if head next is null Node* cate_node1 = new Node;//make node cate_node1->cate = newnode->cate;//set head->nextNode = cate_node1;//set row++; } Node* tmp = head->nextNode;//set if (cate_search(new_node->cate) == true) {//if cate is exist while (1) { if (tmp->cate == new_node->cate) break; tmp = tmp->downNode; } } else { Node* cate_node = new Node; cate_node->cate = newnode->cate; while (1) {//no cate if (tmp->downNode == nullptr) { break; } tmp = tmp->downNode; } tmp->downNode = cate_node; row++; tmp = tmp->downNode; } Node* pp = sort_ro(new_node);//sort new_node->nextNode = nullptr; if (pp->nextNode != nullptr) {//if pp-> next is null Node* tt; tt = pp->nextNode;//tt is pp's next pp->nextNode = new_node; new_node->nextNode = tt; col++; } else {//pp next is not null pp->nextNode = new_node; col++; } count++; } bool List::cate_search(string cate) { if (head->nextNode->cate == cate) return true;//if head next is cate else { Node* tmp = head->nextNode; while (tmp->downNode != nullptr) {//if tmp is cate tmp = tmp->downNode; if (tmp->cate == cate) {//if tmp is cate return true; } } } return false; } bool List::menu_search(Node* mu) { Node* tmp = head; if (tmp->nextNode == nullptr) return false;//no cate than false tmp = tmp->nextNode; while (1) { if (tmp->cate == mu->cate) break;//if tmp cate is find cate break if (tmp->downNode == nullptr) return false; tmp = tmp->downNode; } while (1) { if (tmp->menu == mu->menu) return true;//is find menu if (tmp->nextNode == nullptr) return false; tmp = tmp->nextNode; } } void List::remove() { Node* temp; Node* rwo = head->nextNode; Node* p = rwo->downNode; while (1) {//delete if(rwo->downNode !=nullptr) p = rwo->downNode; else { p = nullptr; } while (rwo!=nullptr) {//if row is no null temp = rwo; rwo = rwo->nextNode; temp->nextNode = nullptr; temp = nullptr; delete temp;//delete } rwo = p; if (rwo == nullptr && p == nullptr) break; } Node* ab = head->nextNode; Node* temp1;//temp while (ab!=nullptr) {//if ab is nu null temp1 = ab; ab = ab->downNode; temp1->nextNode = nullptr; temp1 = nullptr; delete temp1;//delete } head->nextNode = nullptr; head = nullptr; delete head; } Node* List::sort_ro(Node* new_node) {//sort Node* temp = head;//set Node* new_n = new Node;//set new_n = new_node;//set int new_price = new_node->price;//set if (temp->nextNode == nullptr) return nullptr; else temp = temp->nextNode;//set while (1) {//if temp cate and new cate is same if (temp->cate == new_n->cate) break;//find node temp = temp->downNode;//set } while (1) { if (temp->nextNode == nullptr) return temp; else { if (temp->nextNode->price < new_n->price) {//if temp price is smaller than new price temp = temp->nextNode; } else if (temp->nextNode->price > new_n->price) {//temp is bigger than new price return temp; } else { while (1) { if (temp->nextNode == nullptr) return temp; const char* a; a = temp->nextNode->menu.c_str(); const char* b; b = new_n->menu.c_str(); if (strcmp(a, b) > 0) return temp; else if (strcmp(a, b) < 0) {//if price is same compare char temp = temp->nextNode; if (temp->nextNode == nullptr) return temp; if (temp->nextNode->price > new_n->price) return temp; } } } } } } bool List::print() {//print if (head->nextNode == nullptr) return false; else { Node* temp = head->nextNode;//set Node* cat = head->nextNode;//set while (1) { cout << endl; cout << "========== " << cat->cate << " ==========" << endl << endl; while (1) { if (temp->nextNode == nullptr) break; temp = temp->nextNode; cout << temp->menu << " " << temp->price << endl;//print temp node } cout << endl; if (cat->downNode == nullptr) break; else { cat = cat->downNode; temp = cat; } } } return true; } bool List::search_cate(string cate) {//search cate Node* tmp = head; char o_temp[100] = { NULL, };//set char n_temp[100] = { NULL, };//set strcpy(o_temp, cate.c_str());//set if (tmp->nextNode == nullptr) return false; else { tmp = tmp->nextNode; while (1) { if (_stricmp(strcpy(n_temp, tmp->cate.c_str()), o_temp) == 0) break;//cmp temp and n temp if (tmp->downNode == nullptr) return false; tmp = tmp->downNode; } cout << tmp->cate << endl;//print while (1) { if (tmp->nextNode == nullptr) break; tmp = tmp->nextNode; cout << tmp->menu << " " << tmp->price << endl;//print } } cout << endl; return true; } bool List::search_menu(string menu) { Node* tmp = head; Node* pp = head; char o_temp[100] = { NULL, }; char n_temp[100] = { NULL, }; strcpy(o_temp, menu.c_str()); if (tmp->nextNode == nullptr) return false; else { tmp = tmp->nextNode; pp = head->nextNode; while (1) { while (1) { if (_stricmp(strcpy(n_temp, tmp->menu.c_str()), o_temp) == 0) {//if find menu cout << tmp->menu << " " << tmp->price;//print cout << endl; cout << endl; return true; } if (tmp->nextNode == nullptr) break; tmp = tmp->nextNode; } if (pp->downNode == nullptr) return false; pp = pp->downNode; tmp = pp; } } cout << endl; return true; } bool List::delete_menu(string menu) { Node* tmp = head;//set Node* pp = head;//set Node* p = head;//set char o_temp[100] = { NULL, };//set char n_temp[100] = { NULL, };//set strcpy(o_temp, menu.c_str());//set if (tmp->nextNode == nullptr) return false; else { tmp = tmp->nextNode;//set pp = head->nextNode;//set while (1) { while (1) { if (_stricmp(strcpy(n_temp, tmp->menu.c_str()), o_temp) == 0) {//if n_temp and 0_temp is same if (tmp->nextNode == nullptr) { p->nextNode = nullptr; count--; col--; delete(tmp);//delete } else {//no same p->nextNode = tmp->nextNode; count--; col--; delete tmp;//delete } cout << "Delete Success!" << endl; cout << endl; return true; } if (tmp->nextNode == nullptr) break; p = tmp; tmp = tmp->nextNode; } if (pp->downNode == nullptr) return false; pp = pp->downNode; tmp = pp; p = pp; } } cout << endl; return true; } <file_sep>#include <iostream> using namespace std; int my_strlen(char* str); char* my_strstr(char* str, char* strSearch, char* strChange) { int str_len = 0;//declare str_len = my_strlen(str);//get length int search_len = 0;//declare search_len = my_strlen(strSearch);//get length int strChange_len = 0; strChange_len = my_strlen(strChange); int array[100] = { -1, };//declare int array_count = 0; char* answer = new char[100];//declare for (int set = 0; set < 100; set++) {//reset answer[set] = NULL; } for (int a = 0; a < str_len; a++) {//find first match char int count = 1; int count_1 = 0; if (str[a] == strSearch[0]) {//if same while (count < search_len) {//find string until search length if (str[a+count] == strSearch[count]) {//if same count++; if (count == search_len) {//if count is same with search length array[array_count] = a; array_count++; break;//break } } else {//no math count_1++; } if (count_1 == search_len) break; } } } if (array[0] == -1) return 0;//if there is no search string else { int a = 0; while (1) {//put string in answer answer[a] = str[a];//until find sting a++; if (a == array[0]) break; } for (int b =0,c = a; b < strChange_len; b++, c++) {//put chnage string answer[c] = strChange[b]; a++; } int z =array[0] + search_len; for (z; z < str_len; z++) {//put last string answer[a + 1] = str[z]; a++; } return answer; } } int my_strlen(char* str) {//get lenth of str int a = 0; for (a = 0; *str; str++, a++); return a; } int main() { int strlen = 0;//declare char* str1 = new char[100]; char* strChange1 = new char[100]; char* strSearch1 = new char[100]; char* result = new char[100];//declare for (int a = 0; a < 100; a++) str1[a] = NULL;//set to NULL for (int a = 0; a < 100; a++) strSearch1[a] = NULL; for (int a = 0; a < 100; a++) strChange1[a] = NULL; cout << "원본 문자열을 입력하세요." << endl; cin.getline(str1, 100); cout << endl; cout << "변경 전 문자열을 입력하세요." << endl; cin.getline(strSearch1, 100); cout << endl; cout << "변경 후 문자열을 입력하세요." << endl; cin.getline(strChange1, 100); cout << endl; result = my_strstr(str1, strSearch1, strChange1);//my_strstr func cout << "변경 된 결과는 다음과 같습니다." << endl<<endl; if (result == 0) {//if no search string cout << "일치하는 문자열이 없습니다."; } else {//change string output cout << "변경된 문자열: " << endl; for (int a = 0; a < 100; a++) { if (result[a] != NULL) cout << result[a]; } } return 0; }<file_sep> // MFCApplication1View.cpp : CMFCApplication1View 클래스의 구현 // #include "pch.h" #ifndef SHARED_HANDLERS #include "MFCApplication1.h" #endif #include "MFCApplication1Doc.h" #include "MFCApplication1View.h" #pragma warning (disable:4996) #ifdef _DEBUG #define new DEBUG_NEW #endif // CMFCApplication1View IMPLEMENT_DYNCREATE(CMFCApplication1View, CView) BEGIN_MESSAGE_MAP(CMFCApplication1View, CView) // print commmand ON_COMMAND(ID_FILE_PRINT, &CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, &CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, &CView::OnFilePrintPreview) ON_WM_PAINT() ON_WM_KEYDOWN() ON_WM_LBUTTONDOWN() ON_WM_MOUSEMOVE() ON_WM_LBUTTONUP() ON_COMMAND(Print_Clr, &CMFCApplication1View::OnClr) ON_COMMAND(Print_CLR_NUM, &CMFCApplication1View::OnClrNum) ON_COMMAND(ID_32789, &CMFCApplication1View::Log_On) ON_COMMAND(ID_32790, &CMFCApplication1View::Log_Off) END_MESSAGE_MAP() Board m_board; CMFCApplication1View::CMFCApplication1View() { this->m_bDragFlag_toR = 0; this->m_bDragFlag_toL = 0; Color_On_flag = 1;//0: color off , 1: color on Save_rotation_flag = 0;//if 1 save move Save_move_flag = 0;//if 1 save move Turn_count = 0;//if 1 save move outFile.Open(_T("log.txt"), CFile::modeCreate | CFile::modeWrite);//write file open } CMFCApplication1View::~CMFCApplication1View() { outFile.Close();//file close } BOOL CMFCApplication1View::PreCreateWindow(CREATESTRUCT& cs) { // TODO: CREATESTRUCT cs를 수정하여 여기에서 // Window 클래스 또는 스타일을 수정합니다. // return CView::PreCreateWindow(cs); } // CMFCApplication1View 그리기 void CMFCApplication1View::OnDraw(CDC* /*pDC*/) { CMFCApplication1Doc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; // TODO: 여기에 원시 데이터에 대한 그리기 코드를 추가합니다. } // CMFCApplication1View 인쇄 BOOL CMFCApplication1View::OnPreparePrinting(CPrintInfo* pInfo) { // 기본적인 준비 return DoPreparePrinting(pInfo); } void CMFCApplication1View::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: 인쇄하기 전에 추가 초기화 작업을 추가합니다. } void CMFCApplication1View::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: 인쇄 후 정리 작업을 추가합니다. } // CMFCApplication1View 진단 #ifdef _DEBUG void CMFCApplication1View::AssertValid() const { CView::AssertValid(); } void CMFCApplication1View::Dump(CDumpContext& dc) const { CView::Dump(dc); } CMFCApplication1Doc* CMFCApplication1View::GetDocument() const // 디버그되지 않은 버전은 인라인으로 지정됩니다. { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CMFCApplication1Doc))); return (CMFCApplication1Doc*)m_pDocument; } #endif //_DEBUG // CMFCApplication1View 메시지 처리기 void CMFCApplication1View::OnPaint() { Invalidate(FALSE);//수정된 부분을 다시 그려준다. CPaintDC dc(this); // device context for painting // TODO: 여기에 메시지 처리기 코드를 추가합니다. // 그리기 메시지에 대해서는 CView::OnPaint()을(를) 호출하지 마십시오. CPen NewPen(PS_SOLID, 1, RGB(0, 0, 0));//펜 - 기본두께 2 , 기본 색상 검정 CPen* pOldPen = dc.SelectObject(&NewPen);//다른팬을 들고 원래팬은 저장한다. //CBrush NewBrush(RGB(0, 0, 0)); //CBrush* pOldBrush = dc.SelectObject(&NewBrush); Block* pCur; int size = 64;//하나의 사각형의 size //기본 시작점 (10,10)으로부터 변의 길이가 64인 정사각형 int init_coordinate_x_1 = 10; int init_coordinate_y_1 = 10; int init_coordinate_x_2 = 10 + size; int init_coordinate_y_2 = 10 + size; CBrush NewBrush(RGB(255, 255, 255));//초기 Brush //각 색깔 정의 CBrush Yellow_2(RGB(255, 255, 0)); CBrush Orange_4(RGB(255, 127, 0)); CBrush Green_8(RGB(0, 255, 0)); CBrush Blue_16(RGB(0, 0, 255)); CBrush Gray_32(RGB(166, 166, 166)); CBrush Pink_64(RGB(255, 0, 255)); CBrush Cyan_128(RGB(0, 255, 255)); CBrush Purple_256(RGB(128, 0, 128)); CBrush Violet_512(RGB(112, 48, 160)); CBrush Brown_1024(RGB(207, 110, 54)); CBrush Red_2048(RGB(255, 0, 0)); CBrush* pOldBrush = dc.SelectObject(&NewBrush);//기존 pen은 저장 //(0,0)부터 (3,3)까지 for (int j = 0; j < 4; j++) { for (int i = 0; i < 4; i++) { pCur = m_board.getBlock_x_y(i, j); if (Color_On_flag == 1)//색상 출력시 { //숫자에 따라 사각형의 내부에 색을 할당한다. switch (pCur->getNum()) { case 0: dc.SelectObject(&NewBrush); break; case 2: dc.SelectObject(&Yellow_2); break; case 4: dc.SelectObject(&Orange_4); break; case 8: dc.SelectObject(&Green_8); break; case 16: dc.SelectObject(&Blue_16); break; case 32: dc.SelectObject(&Gray_32); break; case 64: dc.SelectObject(&Pink_64); break; case 128: dc.SelectObject(&Cyan_128); break; case 256: dc.SelectObject(&Purple_256); break; case 512: dc.SelectObject(&Violet_512); break; case 1024: dc.SelectObject(&Brown_1024); break; case 2048: dc.SelectObject(&Red_2048); break; } } //사각형 board를 출력해준다. dc.Rectangle(init_coordinate_x_1 + i * size, init_coordinate_y_1 + (j * size), init_coordinate_x_2 + (i * size), init_coordinate_y_2 + (j * size)); //dc.SetBkColor(TRANSPARENT);//배경 투명으로 //사각형 내부에 숫자를 출력한다. if (pCur->getNum() == 0);//0이면 출력을 안한다. else if (pCur->getNum() == 2) dc.DrawText(_T("2"), CRect(init_coordinate_x_1 + i * size, init_coordinate_y_1 + (j * size), init_coordinate_x_2 + (i * size), init_coordinate_y_2 + (j * size)), DT_CENTER | DT_SINGLELINE | DT_VCENTER); else if (pCur->getNum() == 4) dc.DrawText(_T("4"), CRect(init_coordinate_x_1 + i * size, init_coordinate_y_1 + (j * size), init_coordinate_x_2 + (i * size), init_coordinate_y_2 + (j * size)), DT_CENTER | DT_SINGLELINE | DT_VCENTER); else if (pCur->getNum() == 8) dc.DrawText(_T("8"), CRect(init_coordinate_x_1 + i * size, init_coordinate_y_1 + (j * size), init_coordinate_x_2 + (i * size), init_coordinate_y_2 + (j * size)), DT_CENTER | DT_SINGLELINE | DT_VCENTER); else if (pCur->getNum() == 16) dc.DrawText(_T("16"), CRect(init_coordinate_x_1 + i * size, init_coordinate_y_1 + (j * size), init_coordinate_x_2 + (i * size), init_coordinate_y_2 + (j * size)), DT_CENTER | DT_SINGLELINE | DT_VCENTER); else if (pCur->getNum() == 32) dc.DrawText(_T("32"), CRect(init_coordinate_x_1 + i * size, init_coordinate_y_1 + (j * size), init_coordinate_x_2 + (i * size), init_coordinate_y_2 + (j * size)), DT_CENTER | DT_SINGLELINE | DT_VCENTER); else if (pCur->getNum() == 64) dc.DrawText(_T("64"), CRect(init_coordinate_x_1 + i * size, init_coordinate_y_1 + (j * size), init_coordinate_x_2 + (i * size), init_coordinate_y_2 + (j * size)), DT_CENTER | DT_SINGLELINE | DT_VCENTER); else if (pCur->getNum() == 128) dc.DrawText(_T("128"), CRect(init_coordinate_x_1 + i * size, init_coordinate_y_1 + (j * size), init_coordinate_x_2 + (i * size), init_coordinate_y_2 + (j * size)), DT_CENTER | DT_SINGLELINE | DT_VCENTER); else if (pCur->getNum() == 256) dc.DrawText(_T("256"), CRect(init_coordinate_x_1 + i * size, init_coordinate_y_1 + (j * size), init_coordinate_x_2 + (i * size), init_coordinate_y_2 + (j * size)), DT_CENTER | DT_SINGLELINE | DT_VCENTER); else if (pCur->getNum() == 512) dc.DrawText(_T("512"), CRect(init_coordinate_x_1 + i * size, init_coordinate_y_1 + (j * size), init_coordinate_x_2 + (i * size), init_coordinate_y_2 + (j * size)), DT_CENTER | DT_SINGLELINE | DT_VCENTER); else if (pCur->getNum() == 1024) dc.DrawText(_T("1024"), CRect(init_coordinate_x_1 + i * size, init_coordinate_y_1 + (j * size), init_coordinate_x_2 + (i * size), init_coordinate_y_2 + (j * size)), DT_CENTER | DT_SINGLELINE | DT_VCENTER); else if (pCur->getNum() == 2048) dc.DrawText(_T("2048"), CRect(init_coordinate_x_1 + i * size, init_coordinate_y_1 + (j * size), init_coordinate_x_2 + (i * size), init_coordinate_y_2 + (j * size)), DT_CENTER | DT_SINGLELINE | DT_VCENTER); } } //로그파일 기록상태를 표시 if (Save_rotation_flag == 1 && Save_move_flag == 1) { dc.DrawText(_T("log file (0)"), CRect(10, 290, 250, 400), 0); } else if (Save_rotation_flag == 0 && Save_move_flag == 0) { dc.DrawText(_T("log file (x)"), CRect(10, 290, 250, 400), 0); } //색상 출력 상태를 표시 if (Color_On_flag == 0) { dc.DrawText(_T("no color"), CRect(10, 330, 250, 400), 0); } else if (Color_On_flag == 1) { dc.DrawText(_T("yes color"), CRect(10, 330, 250, 400), 0); } //다시 옛날 팬으로 되돌려놓는다. dc.SelectObject(pOldPen); dc.SelectObject(pOldPen); } void CMFCApplication1View::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) { int input_err = 0; switch (nChar)//키 입력 { case VK_LEFT://왼쪽방향 입력시 if (m_board.Left() != 0)//왼쪽으로 갈수 있는지 검사 -> 왼쪽에 블럭이 있다면 { m_board.Put_random_num2();//턴을 바꾼다. Turn_count++;//턴의 count를 1 증가시킨다. if (Save_move_flag == 1)//log파일저장 flag가 On이면 m_board.printBoard(Turn_count, outFile, 1);//log파일 저장 } break; /////////////////////////각 방향마다 기능은 동일//////////////////////// case VK_RIGHT://오른쪽방향 입력시 if (m_board.Right() != 0) { m_board.Put_random_num2(); Turn_count++; if (Save_move_flag == 1) m_board.printBoard(Turn_count, outFile, 2); } break; case VK_DOWN://아래방향 입력시 if (m_board.Down() != 0) { m_board.Put_random_num2(); Turn_count++; if (Save_move_flag == 1) m_board.printBoard(Turn_count, outFile, 3); } break; case VK_UP://위방향 입력시 if (m_board.Up() != 0) { m_board.Put_random_num2(); Turn_count++; if (Save_move_flag == 1) m_board.printBoard(Turn_count, outFile, 4); } break; } OnPaint();//이동후 다시 그려준다. CView::OnKeyDown(nChar, nRepCnt, nFlags); } //마우스이벤트 처리 _ 눌렀을 때 void CMFCApplication1View::OnLButtonDown(UINT nFlags, CPoint point) { //마우스 포인터가 board 내부에 찍혔을 때만 유효 if (point.x >= 10 && point.x <= 10 + 64 * 4 && point.y >= 10 && point.y <= 10 + 64 * 4) { org_x = point.x; org_y = point.y; } SetCapture(); ReleaseCapture(); CView::OnLButtonDown(nFlags, point); } void CMFCApplication1View::OnMouseMove(UINT nFlags, CPoint point) { // TODO: 여기에 메시지 처리기 코드를 추가 및/또는 기본값을 호출합니다. if (m_bDragFlag_toR) { } else if (m_bDragFlag_toL) { } else ReleaseCapture(); CView::OnMouseMove(nFlags, point); } //마우스이벤트 처리 _ 땠을 때 void CMFCApplication1View::OnLButtonUp(UINT nFlags, CPoint point) { //땐 좌표를 저장 new_x = point.x; new_y = point.y; //땐 좌표와 처음 좌표가 board 내부일 때만 if (new_x >= 10 && new_x <= 10 + 64 * 4 && new_y >= 10 && new_y <= 10 + 64 * 4 && org_x >= 10 && org_x <= 10 + 64 * 4 && org_y >= 10 && org_y <= 10 + 64 * 4 ) { if ((new_x - org_x) > 0)//드래그 앤 드롭 → { m_board.rotation_time();//시계방향으로 rotate Turn_count++;//turn 증가 if (Save_rotation_flag == 1)//log 파일 save flag on일 때 { m_board.printBoard(Turn_count, outFile, 5);//현재상태를 로그파일로 print } RedrawWindow();//window를 다시 그린다. } else//드래그 앤 드롭 ← { m_board.rotation_reverse_time();//반시계방향으로 rotate Turn_count++;//turn 증가 if (Save_rotation_flag == 1)//log 파일 save flag on일 때 { m_board.printBoard(Turn_count, outFile, 6);//현재상태를 로그파일로 print } RedrawWindow(); } } //커서 위치 변수 초기화 org_x = 0; org_y = 0; new_x = 0; new_y = 0; CView::OnLButtonUp(nFlags, point); } void CMFCApplication1View::OnClr()//출력메뉴 이벤트 : 색상을 삭제. { Color_On_flag = 0; OnPaint();//다시 그려준다. } void CMFCApplication1View::OnClrNum()//출력메뉴 이벤트 :색상을 추가. { Color_On_flag = 1; OnPaint();//다시 그려준다. } void CMFCApplication1View::Log_On() { //log 파일 flag On Save_move_flag = 1;//이동 Save_rotation_flag = 1;//로테이션 OnPaint();//다시 그려준다. } void CMFCApplication1View::Log_Off() { //log 파일 flag Off Save_move_flag = 0;//이동 Save_rotation_flag = 0;//로테이션 OnPaint();//다시 그려준다. } <file_sep>#ifndef GRAPH_H #define GRAPH_H #include "Vertex.h" #include "Edge.h" using namespace std; #include <fstream> #include <vector> #include <iostream> //using namespace std; #define IN_FINITY 999999 #define visited true #define unvisited false class Graph { private: // the head pointer for the linked list of the vertics Vertex * m_pVHead; // the number of the vertics int m_vSize; public: /// constructor Graph(); /// destructor ~Graph(); /// <summary> /// add vertex with vertexNum at the end of the linked list for the vertics /// </summary> /// /// <param name="vertexKey"> /// the key for the vertex /// </param> Vertex*GetpVHead(); void AddVertex(int vertexKey); /// <summary> /// add edge from the vertex which the number is startVertexKey to the vertex which the number is endVertexKey /// [startVertexKey] ---weight---> [endVertexKey] /// </summary> /// /// <param name="startVertexKey"> /// the start vertex key of the edge /// </param> /// <param name="endVertexKey"> /// the end vertex key of the edge /// </param> /// <param name="weight"> /// the weight of the edge /// </param> void AddEdge(int startVertexKey, int endVertexKey, int weight); /// <summary> /// get the vertex which the key is vertexNum /// </summary> /// /// <param name="key"> /// the key of the vertex to find /// </param> /// /// <returns> /// the vertex which the key is vertexNum /// </returns> Vertex* FindVertex(int key); /// <summary> /// get the number of the vertics /// </summary> /// /// <returns> /// the number of the vertics /// </returns> int Size() const; /// <summary> /// memory free for the vertics /// </summary> void SetSize(int size); /// memory free for the vertics void Clear(); /// <summary> /// print out the graph as matrix form /// </summary> /// /// <param name="fout"> /// file stream for the result log /// </param> void Print(std::ofstream& fout); /// <summary> /// check whether the graph has negative edge or not. /// </summary> /// /// <returns> /// true if the graph has negative edge. /// false otherwise. /// </returns> bool IsNegativeEdge(); /// <summary> /// </summary> /// /// <param name="startVertexKey"> /// the start vertex key /// </param> /// <param name="endVertexKey"> /// the end vertex key /// </param> /// /// <returns> /// the key list of the vertics which are included in the path /// last element should be the total cost /// </returns> /// <summary> /// find the shortest path from startVertexKey to endVertexKey with Dijkstra using std::set /// </summary> /// /// <param name="startVertexKey"> /// the start vertex key /// </param> /// <param name="endVertexKey"> /// the end vertex key /// </param> /// /// <returns> /// the key list of the vertics which are included in the shortest path<para/> /// the last element should be the total cost<para/> /// for the special case, it would be others /// </returns> std::vector<int> FindShortestPathDijkstraUsingSet(int startVertexKey, int endVertexKey); /// <summary> /// find the shortest path from startVertexKey to endVertexKey with Dijkstra using MinHeap /// </summary> /// /// <param name="startVertexKey"> /// the start vertex key /// </param> /// <param name="endVertexKey"> /// the end vertex key /// </param> /// /// <returns> /// the key list of the vertics which are included in the shortest path<para/> /// the last element should be the total cost<para/> /// for the special case, it would be others /// </returns> std::vector<int> FindShortestPathDijkstraUsingMinHeap(int startVertexKey, int endVertexKey); /// <summary> /// find the shortest path from startVertexKey to endVertexKey with Bellman-Ford /// </summary> /// /// <param name="startVertexKey"> /// the start vertex key /// </param> /// <param name="endVertexKey"> /// the end vertex key /// </param> /// /// <returns> /// the key list of the vertics which are included in the shortest path /// last element should be the total cost /// </returns> std::vector<int> FindShortestPathBellmanFord(int startVertexKey, int endVertexKey); std::vector<vector<int>>FindShortestPathFloyd(); bool checkvisittable(int arr[]) { for (int i = 0; i < m_vSize; i++) { if (arr[i] == 0) return false; } return true; } }; #endif <file_sep>#include <string> #include <iostream> class SoccerPlayerData { friend class TreeNode; //friend class friend class BinarySearchTree; friend class TransferWindowManager; private: std::string m_name; //name std::string m_position;//position int m_transfer_fee;// fee int m_ability;//ability public: SoccerPlayerData() { } //function declaer SoccerPlayerData(std::string name, std::string position, int transfer_fee, int ability) // function declaer : m_name(name), m_position(position), m_transfer_fee(transfer_fee), m_ability(ability) { } friend std::ostream& operator<<(std::ostream& os, const SoccerPlayerData& node) {//visit os << "(node.m_name: " << node.m_name << "), " //print << "(node.m_position: " << node.m_position << "), " << "(node.m_transfer_fee: " << node.m_transfer_fee << "), " << "(node.m_ability: " << node.m_ability << ")"; return os; } }; <file_sep>#include "Graph.h" #include "Stack.h" #include "MinHeap.h" #include <set> #include <algorithm> #include <string.h> Graph::Graph() { m_pVHead = NULL; m_vSize = 0; // TODO: implement } Graph::~Graph() { // TODO: implement } void Graph::AddVertex(int vertexKey) {//add vertex Vertex* A = m_pVHead; Vertex* vx = new Vertex(vertexKey); if (A == NULL) {//if head vertex is empty m_pVHead = vx; return; } while (A->GetNext()) {//else A = A->GetNext(); } A->SetNext(vx); return; } void Graph::AddEdge(int startVertexKey, int endVertexKey, int weight) // Add Edge in Graph Linked List { Vertex*pCur = m_pVHead; if (m_pVHead == NULL) // Head not exist return; while (pCur) { if (startVertexKey == pCur->GetKey()) { pCur->AddEdge(endVertexKey, weight); // Add Edge in Vertex class return; } pCur = pCur->GetNext(); } } Vertex* Graph::FindVertex(int key) { Vertex*pCur = m_pVHead; while (pCur) { if (pCur->GetKey() == key) return pCur; pCur = pCur->GetNext(); } return NULL; } void Graph::SetSize(int size) { m_vSize = size; } int Graph::Size() const // return Size function { return m_vSize; } void Graph::Clear() {//delete all of graph Vertex* A = m_pVHead; Vertex* B; while (A) { B = A; A = A->GetNext(); B->Clear(); delete B; //delete vertex } } void Graph::Print(std::ofstream& fout) {//print graph ifstream fin; fin.open("mapdata.txt"); char* Z = new char[100]; fin.getline(Z, 100); fout << "===== PRINT ===== " << endl; while (fin.getline(Z, 100)) {//print all of graph fout << Z << endl; } fout << "=================" << endl; delete[] Z; } bool Graph::IsNegativeEdge() {//check -Weight of all of Edge Vertex* A = m_pVHead; Edge* B = NULL; while (A) { B = A->GetHeadOfEdge(); while (B) { if (B->GetWeight() < 0) return true; //exist -Weight B = B->GetNext(); } A = A->GetNext(); } return false; //Not exist -Weight } std::vector<int> Graph::FindShortestPathDijkstraUsingSet(int startVertexKey, int endVertexKey) {//Find Shortest Path using Dijkstra wite Set vector<int> v; set<int, less<int>> s; //declare set Vertex* P = FindVertex(startVertexKey); //find start vertex Vertex* Q; Edge* E; int a; int* dis = new int[m_vSize]; int* visit = new int[m_vSize]; int* path = new int[m_vSize]; //make table for (a = 0; a < m_vSize; a++) { dis[a] = 11111111; visit[a] = 0; path[a] = -1; //initializing } dis[startVertexKey] = 0; while (1) { E = P->GetHeadOfEdge(); visit[P->GetKey()] = 1; while (E) { if (dis[E->GetKey()] > E->GetWeight() + dis[P->GetKey()]) {//if need update distance if (s.find(dis[E->GetKey()]) != s.end()) {//if exist distance in set s.erase(dis[E->GetKey()]); //erase index in set v.push_back(dis[P->GetKey()] + E->GetWeight());//push new distance } dis[E->GetKey()] = E->GetWeight() + dis[P->GetKey()];//update path[E->GetKey()] = P->GetKey(); if (visit[E->GetKey()] == 0) v.push_back(dis[E->GetKey()]); } E = E->GetNext(); } s.insert(v.begin(), v.end()); //insert vector in set int g = 0; if (s.size() != 0) g = *s.begin(); //find shortest path for (a = 0; a < m_vSize; a++) { if (dis[a] == g) { s.erase(g); //erase break; } } P = FindVertex(a); v.clear(); if (checkvisittable(visit) == true || (s.size() == 0 && visit[endVertexKey] == 1)) break; //if visit table is all true or set size = 0 and visited endvertex } v.push_back(dis[endVertexKey]); //push total distance in vector v.push_back(endVertexKey); //push path while (endVertexKey != startVertexKey) {//push path P = FindVertex(path[endVertexKey]); endVertexKey = P->GetKey(); v.push_back(endVertexKey); } delete[] dis, visit, path; return v; } std::vector<int> Graph::FindShortestPathDijkstraUsingMinHeap(int startVertexKey, int endVertexKey) { MinHeap<int, int>* mh = new MinHeap<int, int>;//distance, vertex int *dist = new int[m_vSize]; memset(dist, 127, m_vSize * sizeof(int)); int *path = new int[m_vSize]; memset(path, -1, m_vSize * sizeof(int)); vector<int> route; mh->Push(0, startVertexKey);//insert distance and vertex dist[startVertexKey] = 0;//change distance while (mh->IsEmpty() != 1)//until mh is empty { pair<int, int> pick = mh->Top();//pull mh's begin Edge * e = FindVertex(pick.second)->GetHeadOfEdge(); while (e) { if (dist[e->GetKey()] > e->GetWeight() + pick.first)//appear shorter path { dist[e->GetKey()] = e->GetWeight() + pick.first;//change distance if (mh->Get(e->GetKey()).second != -1)//find vertex in mh mh->DecKey(e->GetKey(), dist[e->GetKey()]);//change distance in mh else mh->Push(dist[e->GetKey()], e->GetKey());//insert new distance and vertex path[e->GetKey()] = pick.second;//update path } e = e->GetNext(); } mh->Pop(); } int prev = endVertexKey; while (1)//find path to the end vertex from the start vertex { route.push_back(prev); if (prev == startVertexKey) break; prev = path[prev]; } reverse(route.begin(), route.end());//reverse route route.push_back(dist[endVertexKey]);//insert distance return route; } std::vector<int> Graph::FindShortestPathBellmanFord(int startVertexKey, int endVertexKey) { vector<int> v; Vertex* pCur = m_pVHead; Edge* E; int a; int* dis = new int[m_vSize]; int* dis2 = new int[m_vSize]; int* path = new int[m_vSize];//make table for (a = 0; a < m_vSize; a++) { dis[a] = 11111111; dis2[a] = 11111111; path[a] = -1; //initialing } dis[startVertexKey] = 0; dis2[startVertexKey] = 0; //it will use find -weight int count = 0; int count2 = 0; while (count != m_vSize - 1) {//doing size*size-1 while (count2 != m_vSize) {//doing size if (dis[pCur->GetKey()] != 11111111) {//if distance is infinity, dont need visit E = pCur->GetHeadOfEdge(); while (E) { if (dis[E->GetKey()] > dis[pCur->GetKey()] + E->GetWeight()) {//if need update dis[E->GetKey()] = dis[pCur->GetKey()] + E->GetWeight(); dis2[E->GetKey()] = dis2[pCur->GetKey()] + E->GetWeight(); path[E->GetKey()] = pCur->GetKey(); } E = E->GetNext(); } } count2++;//count2 += 1 pCur = pCur->GetNext(); } count2 = 0; count++; //count += 1 pCur = m_pVHead; } pCur = m_pVHead; count = 0; count2 = 0; //find -weight, use only distance table 2 //same process while (count != m_vSize - 1) { while (count2 != m_vSize) { if (dis2[pCur->GetKey()] != 11111111) { E = pCur->GetHeadOfEdge(); while (E) { if (dis2[E->GetKey()] > dis2[pCur->GetKey()] + E->GetWeight()) { dis2[E->GetKey()] = dis2[pCur->GetKey()] + E->GetWeight(); path[E->GetKey()] = pCur->GetKey(); } E = E->GetNext(); } } count2++; pCur = pCur->GetNext(); } count2 = 0; count++; pCur = m_pVHead; } //find -weight, if dis != dis2 (update more), graph have - weight for (int j = 0; j < m_vSize; j++) { if (dis[j] != dis2[j]) { v.clear();//clear vector return v; //if exist -weight return 0 vector } } v.push_back(dis[endVertexKey]); //push total distance while (endVertexKey != -1) {//push path v.push_back(endVertexKey); endVertexKey = path[endVertexKey]; } return v; delete[] dis, dis2, path; } Vertex*Graph::GetpVHead() { return m_pVHead; } vector<vector<int>> Graph::FindShortestPathFloyd() { Vertex* walker = m_pVHead; // set Vwalker is first vertex vector<vector<int>> dist; for (int i = 0; i < m_vSize; i++) // i -> Vertex key { vector<int> v; Edge*pCur = walker->GetHeadOfEdge(); for (int j = 0; j < m_vSize; j++) { if (pCur != NULL) { if (pCur->GetKey() == j) { v.push_back(pCur->GetWeight()); pCur = pCur->GetNext(); } else v.push_back(1000); } else v.push_back(1000); } dist.push_back(v); walker = walker->GetNext(); } for (int k = 0; k < m_vSize; k++) { for (int i = 0; i < m_vSize; i++) { for (int j = 0; j < m_vSize; j++) { if (dist[i][k] + dist[k][j] < dist[i][j]) dist[i][j] = dist[i][k] + dist[k][j]; } } } for (int i = 0; i < m_vSize; i++) dist[i][i] = 0; return dist; } <file_sep>#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <fstream> #include <time.h> #include <conio.h> #include <cmath> using namespace std; ifstream read;//declare ofstream write;//declare int all_char(char a[256]) {//count all char of string int count = 0; for (int b = 0; b < 256; b++) { if (a[b] != NULL) count++;//if char is not NULL count ++ else break; } return count;//return count } int collec_char(char a[256], char b[256]) {//find collect char int count = 0; for (int c = 0; c < 256; c++) { if (a[c] == NULL || b[c] == NULL) break;//if string is end break; if (a[c] == b[c]) count++;//if same count++ } return count;//return } int main() { time_t start = NULL;//set start time time_t end = NULL;//set end time read.open("source.txt");//open text write.open("result.txt");//open text to write char text[256] = { NULL, }; char arr[256] = { NULL, }; int text_count = 0; double speed = 0; double collect = 0; int leng = 0; write << "KW Typing verification Program" << endl; if (read.is_open()) {//if text is open while (!read.eof()) { //read while sting is not end cout << "KW Typing verification Program" << endl; cout << "정확도 : " << collect * 100 << " "; cout << "속도(타자/s) : " << speed << endl << endl; write << "정확도 : " << collect * 100 << " "; write << "속도(타자/s) : " << speed << endl << endl; read.getline(arr, 256);//get line of string cout << "문장 : " << arr << endl; write << arr << endl;//write in result.txt cout << "입력 : "; while (_kbhit()) {//if input is occr } start = time(NULL);//start time cin.getline(text, 256, '\n');//cin getline end = time(NULL);//end time system("cls");//make reset od command text_count = all_char(text);//count all char of string collect = collec_char(text, arr);//find collect char leng = all_char(arr);//get length collect = collect / (double)leng; speed = text_count / ((double)end - (double)start); speed = round(speed * 10) / 10.0; } } cout << "KW Typing verification Program" << endl; cout << "정확도 : " << collect * 100 << " " << "속도(타자/s) : " << speed << endl << endl; write << "정확도 : " << collect * 100 << " " << "속도(타자/s) : " << speed << endl << endl; read.close(); write.close(); }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <fstream> using namespace std; int main() { char line[1500];//declare arr char* str[1500];//declare arr int num[1500];//declare num arr ifstream read;//ifstream read.open("ciphertext.txt");//open the text file read.getline(line, 1500);// get line size 1500 cout << "ciphertext: " << line; cout << endl; char* token = strtok(line, " "); //tok by " " int cnt = 0; while (token) {//while token is not null str[cnt] = token; // put token str[cnt] token = strtok(NULL, " ");// token by " " again cnt++; //count up } for (int b = 0; b < cnt; b++) { num[b] = strtol(str[b], NULL, 16);//print num to hexadecimal } for (int a = 0; a <= 127; a++) { cout << "key(" << a << "): ";//print key for (int b = 0; b < cnt; b++) { char temp = NULL; if ((num[b] + a) > 127) {//if num is lagger than 127 temp = (num[b] + a )- 128;// make reset and shift a } else { // else put hex int temp and shift temp = num[b] + a; } cout << temp<<" ";//print } cout << endl; } }<file_sep>#include "Edge.h" Edge::Edge() { m_key = 0; m_weight = 0; m_pNext = NULL; } Edge::Edge(int key, int weight) { m_key = key; m_weight = weight; m_pNext = NULL; } void Edge::SetNext(Edge* pNext) {//set next edge m_pNext = pNext; } int Edge::GetKey() const {//return key of edge return m_key; } int Edge::GetWeight() const {//return weight of edge return m_weight; } Edge* Edge::GetNext() const {//return next edge return m_pNext; }<file_sep>#include "AVLTree.h" #include <iostream> #include <fstream>// header file declare #include <map> #include <vector> using namespace std; class Graph { public: map<int,CityData*> * mList; // mList[from vetex] = map<to vertex, weigth> CityData * * vertex; // vetex[index] = CityData * int size; // AVLTree size int mstMatrix; // MST AVLNode * gp_arry[30];//value declare AVLNode * MST_arry[30];//value declare ofstream * flog;//value declare int swei;//value declare int arr[100];//value declare int parent[100];//value declare int num[100];//value declare int cc;//value declare struct edge//struct edge { public: int u; //(u,v) int v;//(u,v) CityData * data1;//value declare CityData * data2;//value declare int wei; bool operator <(edge &edge) { //set operation to use sort return this->wei < edge.wei;//if wei is smaller than edge's wei return edge.we } }; vector<edge> kru_tree;//value declare vector<edge> R_tree;//value declare public: Graph(ofstream * flog);//value declare ~Graph();//value declare bool Build(AVLTree * root); void Print_GP(); void Print_MST(); bool Kruskal(); int make_set(int parent[],int a); int union_set(int parent[],int x, int y); int find(int parent[],int x,int y); void insert_gp(AVLNode * tree,int zzzz); }; <file_sep>#include <iostream> #include <vector> #include <cstdlib> #include <time.h> #define MAX_SIZE 16382 using namespace std; int main() { int row=0,col=0;//decalre std::cout << "Enter the row: "; cin >> row;//get row std::cout << "Enter the column: "; cin >> col;//get col std::cout << "Origin Matrix >>> "; std::cout << endl; srand((unsigned int)time(NULL));//to not overlapping int** arr; arr = new int* [row]; for (int i = 0; i < row; i++) arr[i] = new int[col]; int dup[1000];//check dulicate for (int i = 0; i < 1000; i++) dup[i] = 0;//reset to 0 dup[0] = -1; // [0] set to -1 if (1 <= row && col <= 100) {//row and col is 1 to 100 for (int a = 0; a < row; a++) { for (int b = 0; b < col; b++) { int num = rand() % (col*row);//get num 0 to col*row -1 if (dup[num] != num) {//if no duplicate dup[num] = num;// put num arr[a][b] = num;//put num } else {//if duplicate while (1) { num = rand() % (col * row);//get new random number if (dup[num] != num) {//check duplicate dup[num] = num; arr[a][b] = num; break;//if no dup than break; } } } } } for (int a = 0; a < row; a++) { for (int b = 0; b < col; b++) {//print std::cout << arr[a][b]; std::cout << " "; } std::cout << endl; } std::cout << endl; std::cout << "Transpose Matrix >>> "; std::cout << endl; for (int a = 0; a < col; a++) { for (int b = 0; b < row; b++) {//print row is col, col is row std::cout << arr[b][a]; std::cout << " "; } std::cout << endl; } } }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <cstdlib> #include <time.h> using namespace std; int main() { int r_num[5] = { -1 ,};//declare int temp = 0;//declare char my_num[5] = {NULL,};//declare int game = 0;//declare srand((unsigned int)time(NULL));//get diffrent num each compile for (int a = 0; a < 4; a++) { again:; temp = rand() % 10;//get random num for (int b = 0; b < 4; b++) { if (temp == r_num[b])//if num is same as prior num goto again; //get random num again } r_num[a] = temp;// no duplicate num put num in arr } cout << "Random numbers: " << endl; while (1) { if (game == 10) {//if game is 10 cout << "Lose" << endl; break; } game++; int hit = 0; int blow = 0; cout << "Your number: "; scanf("%s", my_num);//get num for (int a = 0; a < 4; a++) { if (r_num[a] == my_num[a] - '0')//my num is char so -0 to make int hit++;//if num is just fit, pluzs hit else { for (int b = 0; b < 4; b++) { if (r_num[a] == my_num[b]- '0') {//if num is fit but no same place blow++;//blow ++ } } } if (hit == 4) {//if hit is 4 cout << ">>" << "HIT: " << hit << "," <<"BLOW: "<<blow<< endl; cout << "Win";//win break; } } if (hit == 4) break; cout << ">>" << "HIT: " << hit << "," <<"BLOW: "<<blow<< endl; } }<file_sep>#include "Manager.h" #include <cstring> #include <iostream> #include<algorithm> using namespace std; Manager::~Manager() { if (fout.is_open()) fout.close(); } void Manager::Run(const char* filepath) { enum Result result; fout.open(RESULT_LOG_PATH); // TODO: implement ifstream fin; fin.open(filepath); if (fin.fail()) { fout << "====== SYSTEM ======" << endl; fout << "CommandFileNotExist" << endl; fout << "=====================" << endl; fout << "=====================" << endl; PrintError(CommandFileNotExist); fout << "=====================" << endl; return; } char * str = new char[200]; char * token = new char[100]; while (fin.getline(str, 200)) { token = strtok(str, " "); if (!strcmp(token, "LOAD")) { token = strtok(NULL, " "); fout << "===== LOAD =====" << endl; if (Load(token) == LoadFileNotExist) { fout << "LoadFileNotExist" << endl; fout << "=================" << endl; fout << "=================" << endl; PrintError(LoadFileNotExist); //error fout << "=================" << endl; } else { fout << "Success" << endl; fout << "=================" << endl; fout << endl; fout << "=================" << endl; PrintError(Success); fout << "=================" << endl; fout << endl; } } else if (!strcmp(token, "PRINT")) { if (Print() == GraphNotExist)//if graph is not exist PrintError(GraphNotExist); else fout << endl; fout << "=================" << endl; PrintError(Success); fout << "=================" << endl; fout << endl; } else if (!strcmp(token, "DIJKSTRAMIN")) {//DIJKSTRAMIN fout << "===== DIJKSTRAMIN =====" << endl; token = strtok(NULL, " "); if (token == NULL) {//if Vertex inserted is insufficient fout << "VertexKeyNotExist" << endl; fout << "=================" << endl; fout << endl; fout << "=================" << endl; PrintError(VertexKeyNotExist); fout << "=================" << endl; continue; } int start = atoi(token); token = strtok(NULL, "\n"); if (token == NULL) {//if Vertex inserted is insufficient fout << "VertexKeyNotExist" << endl; fout << "=================" << endl; fout << endl; fout << "=================" << endl; PrintError(VertexKeyNotExist); fout << "=================" << endl; continue; } int end = atoi(token); result = FindShortestPathDijkstraUsingMinHeap(start, end); //Find Dijkstra using set fout << endl << "=================" << endl; PrintError(result); fout << "=================" << endl; fout << endl; } else if (!strcmp(token, "DIJKSTRA")) {//DIJKSTRA fout << "===== DIJKSTRA =====" << endl; token = strtok(NULL, " "); if (token == NULL) {//if Vertex inserted is insufficient fout << "VertexKeyNotExist" << endl; fout << "=================" << endl; fout << endl; fout << "=================" << endl; PrintError(VertexKeyNotExist); fout << "=================" << endl; continue; } int start = atoi(token); token = strtok(NULL, "\n"); if (token == NULL) {//if Vertex inserted is insufficient fout << "VertexKeyNotExist" << endl; fout << "=================" << endl; fout << endl; fout << "=================" << endl; PrintError(VertexKeyNotExist); fout << "=================" << endl; continue; } int end = atoi(token); result = FindShortestPathDijkstraUsingSet(start, end); //Find Dijkstra using set fout << endl << "=================" << endl; fout << endl << "=================" << endl; PrintError(result); fout << "=================" << endl; fout << endl; } else if (!strcmp(token, "BELLMANFORD")) {//BELLMANFORD fout << "===== BELLMANFORD =====" << endl; token = strtok(NULL, " "); if (token == NULL) {//if Vertex inserted is insufficient fout << "VertexKeyNotExist" << endl; fout << "=================" << endl; fout << endl; fout << "=================" << endl; PrintError(VertexKeyNotExist); fout << "=================" << endl; continue; } int start = atoi(token); token = strtok(NULL, "\n"); if (token == NULL) {//if Vertex inserted is insufficient fout << "VertexKeyNotExist" << endl; fout << "=================" << endl; fout << endl; fout << "=================" << endl; PrintError(VertexKeyNotExist); fout << "=================" << endl; continue; } int end = atoi(token); result = FindShortestPathBellmanFord(start, end); //Find BellmanFord fout << endl << "=================" << endl; PrintError(result); fout << "=================" << endl; fout << endl; } else if (!strcmp(token, "FLOYD")) { fout << "===== FLOYD =====" << endl; if (FindShortestPathFloyd() == VertexKeyNotExist) { fout << "VertexKeyNotExist" << endl; fout << "=================" << endl; fout << endl; fout << "=================" << endl; PrintError(VertexKeyNotExist); fout << "=================" << endl; continue; } else fout << "=================" << endl; PrintError(Success); fout << "=================" << endl; } else {//NonDefinedCommand fout << endl<< "===== " << token << " =====" << endl; fout << "NonDefinedCommand" << endl; fout << "=================" << endl; fout << endl << "=================" << endl; PrintError(NonDefinedCommand); fout << "=================" << endl; fout << endl; } } } void Manager::PrintError(Result result) { fout << "Error code: " << result << std::endl; } /// <summary> /// make a graph /// </summary> /// /// <param name="filepath"> /// the filepath to read to make the graph /// </param> /// /// <returns> /// Result::Success if load is successful. /// Result::LoadFileNotExist if file is not exist. /// </returns> Result Manager::Load(const char* filepath) { ifstream fin; fin.open(filepath); //file open if (fin.fail()) return LoadFileNotExist; char* str = new char[200]; char*token = NULL; fin.getline(str, 200); token = strtok(str, " "); int size = atoi(token); m_graph.SetSize(size); for (int a = 0; a < size; a++) { fin.getline(str, 200); token = strtok(str, " "); m_graph.AddVertex(a); for (int b = 0; b < size; b++) { if (atoi(token) != 0) m_graph.AddEdge(a, b, atoi(token)); token = strtok(NULL, " "); } } fin.close(); return Success; // TODO: implement } /// <summary> /// print out the graph as matrix form /// </summary> /// /// <returns> /// Result::Success if the printing is successful /// Result::GraphNotExist if there is no graph /// </returns> Result Manager::Print() { if (m_graph.Size() == 0) return GraphNotExist; else { m_graph.Print(fout); return Success; } // TODO: implement } /// <summary> /// </summary> /// /// <param name="startVertexKey"> /// the start vertex key /// </param> /// <param name="endVertexKey"> /// the end vertex key /// </param> /// /// <returns> /// Result::InvalidVertexKey or Result::GraphNotExist or Result::InvalidAlgorithm if an exception has occurred. /// Result::Success otherwise. /// </returns> /// <summary> /// find the shortest path from startVertexKey to endVertexKey with Dijkstra using std::set /// </summary> /// /// <param name="startVertexKey"> /// the start vertex key /// </param> /// <param name="endVertexKey"> /// the end vertex key /// </param> /// /// <returns> /// Result::InvalidVertexKey or Result::GraphNotExist or Result::InvalidAlgorithm if an exception has occurred. /// Result::Success otherwise. /// </returns> Result Manager::FindShortestPathDijkstraUsingSet(int startVertexKey, int endVertexKey) { if (m_graph.Size() == 0) {//if graph is not exist fout << "GraphNotExist"; return GraphNotExist; } if (m_graph.FindVertex(startVertexKey) == NULL || m_graph.FindVertex(endVertexKey) == NULL)//üũ {//if Vertex is not exist fout << "InvalidVertexKey"; return InvalidVertexKey; } if (m_graph.IsNegativeEdge() == true) {//if graph had -Weight fout << "InvalidAlgorithm"; return InvalidAlgorithm; } vector<int> v; v = m_graph.FindShortestPathDijkstraUsingSet(startVertexKey, endVertexKey); //Find dijkstra using set fout << "shortest path: "; for (int i = 1; i < v.size(); i++) {//print result vector fout << v[v.size()-i] << " "; } fout << endl; fout << "sorted nodes: "; int temp = v[0]; v[0] = v[v.size() - 1]; v[v.size() - 1] = temp; int z = v[v.size() - 1]; v.pop_back(); sort(v.begin(), v.end()); for (int b = 0; b < v.size(); b++) {//print result vector fout << v[b] << " "; } fout << endl; fout << "path length: "; fout << z; return Success; // TODO: implement } /// <summary> /// find the shortest path from startVertexKey to endVertexKey with Dijkstra using MinHeap /// </summary> /// /// <param name="startVertexKey"> /// the start vertex key /// </param> /// <param name="endVertexKey"> /// the end vertex key /// </param> /// /// <returns> /// Result::InvalidVertexKey or Result::GraphNotExist or Result::InvalidAlgorithm if an exception has occurred. /// Result::Success otherwise. /// </returns> Result Manager::FindShortestPathDijkstraUsingMinHeap(int startVertexKey, int endVertexKey) { Result result; if (m_graph.Size() == 0)// graph not exist error result = GraphNotExist; else if (!m_graph.FindVertex(startVertexKey) || !m_graph.FindVertex(endVertexKey))// vertex having the startvertexkey or vertex having the endvertexkey not exist error result = InvalidVertexKey; else if (m_graph.IsNegativeEdge() == 1)// Nagative weight in the graph exist error result = InvalidAlgorithm; else { vector<int> v = m_graph.FindShortestPathDijkstraUsingMinHeap(startVertexKey, endVertexKey);// find path MIN algorithm fout << "shortest path: "; for (int i = 1; i < v.size(); i++) {//print result vector fout << v[i-1] << " "; } fout << endl; fout << "sorted nodes: "; for (int i = 1; i < v.size(); i++) {//print result vector fout << v[i - 1] << " "; } int z = v[v.size() - 1]; fout << endl; fout << "path length: "; fout << z; fout << endl << "=================" << endl; result = Success; //return result;//success } return result; // TODO: implement } /// <summary> /// find the shortest path from startVertexKey to endVertexKey with Bellman-Ford /// </summary> /// /// <param name="startVertexKey"> /// the start vertex key /// </param> /// <param name="endVertexKey"> /// the end vertex key /// </param> /// /// <returns> /// Result::InvalidVertexKey or Result::GraphNotExist or Result::NegativeCycleDetected if exception has occurred. /// Result::Success otherwise. /// </returns> Result Manager::FindShortestPathBellmanFord(int startVertexKey, int endVertexKey) { vector<int> vt; if (m_graph.Size() == 0)// graph not exist error return GraphNotExist; if (m_graph.FindVertex(startVertexKey) == NULL || m_graph.FindVertex(endVertexKey) == NULL)// vertex having the startvertexkey or vertex having the endvertexkey not exist error return InvalidVertexKey; vt = m_graph.FindShortestPathBellmanFord(startVertexKey, endVertexKey);// find path BELLMAN algorithm if (vt.size() == 0) // Size of vector means to exist negative weight in the graph return NegativeCycleDetected; fout << "shortest path: "; for (int a = 1; a < vt.size(); a++)// print out path { fout << vt[vt.size() - a ] << " "; } int temp = vt[0]; vt[0] = vt[vt.size() - 1]; vt[vt.size() - 1] = temp; int z = vt[vt.size() - 1]; fout << endl; fout << "sorted nodes: "; vt.pop_back(); sort(vt.begin(), vt.end()); for (int b = 0; b < vt.size(); b++) {//print result vector fout << vt[b] << " "; } fout << endl; fout << "path length: "; fout << z; fout << endl << "================" << endl; return Success; // TODO: implement } Result Manager::FindShortestPathFloyd() { vector<vector<int>> mv; if (m_graph.GetpVHead() == NULL) // if m_graph is not exist { return GraphNotExist; // return error } mv = m_graph.FindShortestPathFloyd(); // call PRINT function in m_graph if (mv.size() == 0) return NegativeCycleDetected; for (int i = 0; i < mv.size(); i++) { for (int j = 0; j < mv.size(); j++) { fout << mv[i][j] << " "; } fout << endl; } fout << "================" << endl; fout << endl; return Success; // return success } <file_sep>#define _CRT_SECURE_NO_WARNINGS #pragma once #include <fstream> #include "List.h" #include <iostream> #include <string> #include <cstring> using namespace std; void print_menu(); int main() { int user_input = 0; List list; cout << "**********************************" << endl; cout << "S T A R T" << endl; cout << "**********************************" << endl; while (user_input != 12) { user_input = 0; print_menu(); cin >> user_input; cout << endl; if (user_input == 1) {//insert begin cout << "<Insert lecture at beginning>" << endl; string user_name;//set string user_professor;//set string user_grade;//set char grade_temp[10]; cout << "->Enter the lecture name: "; cin.ignore(100, '\n'); getline(cin, user_name); cout << "->Enter the lecture professor: "; getline(cin, user_professor); cout << "->Enter the lecture grade: "; getline(cin, user_grade); cout << "----------------------------------------" << endl << endl; strcpy(grade_temp, user_grade.c_str()); Node* newnode = new Node; newnode->name = user_name;//set newnode->professor = user_professor;//set newnode->grade = atoi(grade_temp);//set list.insert_beginning(newnode);//insert } else if (user_input == 2) {//insert last cout << "<Insert lecture at last>" << endl; string user_name;//set string user_professor;//set string user_grade;//set char grade_temp[10];//set cout << "->Enter the lecture name: "; cin.ignore(100, '\n'); getline(cin, user_name); cout << "->Enter the lecture professor: "; getline(cin, user_professor); cout << "->Enter the lecture grade: "; getline(cin, user_grade); cout << "----------------------------------------" << endl << endl; strcpy(grade_temp, user_grade.c_str()); Node* newnode = new Node;//make node newnode->name = user_name;//set newnode->professor = user_professor;//set newnode->grade = atoi(grade_temp);//set list.insert_last(newnode);//insert last } else if (user_input == 3) {//insert position tryAgain: int user_po = 0; cout << "<Insert lecture at position>" << endl; cout << "->Enter the position of lecture insert :"; cin >> user_po;//set if (user_po <= 0 || user_po > list.maxposition() + 1) goto tryAgain;//if position is wrong goto again string user_name;//set string user_professor;//set string user_grade;//set char grade_temp[10]; cout << "->Enter the lecture name: "; cin.ignore(100, '\n'); getline(cin, user_name); cout << "->Enter the lecture professor: "; getline(cin, user_professor); cout << "->Enter the lecture grade: "; getline(cin, user_grade); cout << "----------------------------------------" << endl << endl; strcpy(grade_temp, user_grade.c_str()); Node* newnode = new Node;//set newnode->name = user_name;//set newnode->professor = user_professor;//set newnode->grade = atoi(grade_temp);//set if (list.insert_position(newnode, user_po) == false)//insert continue; } else if (user_input == 4) { string user_name;//set cout << "<Delete lecture>" << endl; cout << "Enter the lecture of Delete: "; cin.ignore(100, '\n'); getline(cin, user_name);//set if (list.delete_lecture(user_name) == false) {//delete cout << "No lecture to delete" << endl; continue; } } else if (user_input == 5) { string user_name;//set cout << "<Update lecture>" << endl; cout << "->Enter the lecture name: "; cin.ignore(100, '\n');//set getline(cin, user_name);//set if (list.search_lecture(user_name) == false) {//serch lecture cout << "No information to update" << endl; cout << "--------------------------------" << endl; } else { string user_name1;//set string user_professor;//set string user_grade;//set char grade_temp[10]; cout << "->Enter the new lecture name: "; getline(cin, user_name1); cout << "->Enter the new lecture professor: "; getline(cin, user_professor); cout << "->Enter the new lecture grade: "; getline(cin, user_grade); cout << "----------------------------------------" << endl << endl; strcpy(grade_temp, user_grade.c_str());//set Node* newnode = new Node;//set newnode->name = user_name1;//set newnode->professor = user_professor;//set newnode->grade = atoi(grade_temp);//set list.update_lecture(newnode, user_name);//update } } else if (user_input == 6) { string user_name; cout << "<Search lecture>" << endl; cout << "->Enter the lecture name you want to search: "; cin.ignore(100, '\n'); getline(cin, user_name); if (list.serch_lec(user_name) == false) {//search lecture cout << "No lecture you found" << endl << endl; cout << "-----------------------------------" << endl; } } else if (user_input == 7) { string user_name; cout << "<Search professor>" << endl; cout << "->Enter the professor name you want to search: "; cin.ignore(100, '\n'); getline(cin, user_name); if (list.search_pro(user_name) == false) {//search professor cout << "No professor you find" << endl; cout << "-----------------------------------" << endl; } else cout << "-----------------------------------" << endl; } else if (user_input == 8) { string user_name; char grade_temp[10]; cout << "<Search grade>" << endl; cout << "->Enter the grade you want to search: "; cin.ignore(100, '\n'); getline(cin, user_name); strcpy(grade_temp, user_name.c_str()); int user_grade = atoi(grade_temp); if (list.search_grade(user_grade) == false) {//search grade cout << "No grade you find" << endl; cout << "-----------------------------------" << endl; } else { cout << "-----------------------------------" << endl; } } else if (user_input == 9) {//sort ascending cout << "<Sort by grade in ascending order>" << endl; cout << "-----------------------------------" << endl; list.sort_ascending(); } else if (user_input == 10) {//print list.Display(); cout << "-------------------------------------" << endl; } else if (user_input == 11) {//reverse list.reverse(); cout << "<Reverse lecture list>" << endl; cout << "**The product list has been reversed**" << endl; cout << "-----------------------------------" << endl; } else if (user_input == 12) {//exit exit(0); } else { exit(0); } user_input = 0; } } void print_menu() { cout << "1.Insert lecture at beginning" << endl; cout << "2.Insert lecture at last" << endl; cout << "3.Insert lecture at position" << endl; cout << "4.Delete lecture" << endl; cout << "5.Update lecture " << endl; cout << "6.Search lecture" << endl; cout << "7.Search professor" << endl; cout << "8.Search grade " << endl; cout << "9.Sort by grade In ascending order " << endl; cout << "10.Display lecture list " << endl; cout << "11.Reverse lecture list" << endl; cout << "12.Exit" << endl; cout << "Input Number : "; } <file_sep>#include "Board.h" #include <iostream> #include <vector> #include <cstdlib> #include <ctime> using namespace std; MyBlock::MyBlock() { this->m_pLeft = nullptr;//delcare and reset this->m_pRight = nullptr;//delcare and reset this->m_pup = nullptr;//delcare and reset this->m_pDown = nullptr;//delcare and reset this->m_number = 0;//delcare and reset this->m_x = 0;//delcare and reset this->m_y = 0;//delcare and reset } MyBlock::MyBlock(int num, int x, int y) { this->m_pLeft = nullptr;//delcare and reset this->m_pRight = nullptr;//delcare and reset this->m_pup = nullptr;//delcare and reset this->m_pDown = nullptr;//delcare and reset this->m_number = num;//delcare and reset this->m_x = x;//delcare and reset this->m_y = y;//delcare and reset } MyBlock::~MyBlock() { } void MyBlock::SetLeft(MyBlock* Left) {//set this->m_pLeft = Left; } void MyBlock::SetRight(MyBlock* Right) {//set this->m_pRight = Right; } void MyBlock::SetUp(MyBlock* Up) {//set this->m_pup = Up; } void MyBlock::SetDown(MyBlock* Down) {//set this->m_pDown = Down; } void MyBlock::SetNum(int num) {//set this->m_number = num; } void MyBlock::Set_x(int x) {//set this->m_x = x; } void MyBlock::Set_y(int y) {//set this->m_y = y; } MyBlock* MyBlock::GetLeft() {//get return this->m_pLeft; } MyBlock* MyBlock::GetRight() {//get return this->m_pRight; } MyBlock* MyBlock::GetUp() {//get return this->m_pup; } MyBlock* MyBlock::GetDown() {//get return this->m_pDown; } int MyBlock::GetNum() {//get return this->m_number; } int MyBlock::Get_x() {//get return this->m_x; } int MyBlock::Get_y() {//get return this->m_y; } MyBoard::MyBoard() { this->m_pHead = nullptr; } MyBoard::~MyBoard() { } void MyBoard::print_board() { if (m_pHead == nullptr) return; MyBlock* cur = m_pHead; MyBlock* temp = m_pHead; cout << endl; cout << "[Board]" << endl; for (int a = 0; a < 4; a++) { cout << "[ "; for (int b = 0; b < 4; b++) { if (cur->GetNum() == 0) {//if node num is 0 cout << "- "; } else {//node is none 0 cout << cur->GetNum() << " "; } if (cur->GetRight() == nullptr) continue; cur = cur->GetRight(); } cout << "]" << endl; if (temp->GetDown() == nullptr) break; temp = temp->GetDown(); cur = temp; } } void MyBoard::make_board(MyBlock* node) { if (m_pHead == nullptr) {//if head is null m_pHead = node; return; } MyBlock* cur = m_pHead; if (node->Get_y() == 0) {//if y is 0 while (1) { if (cur->GetDown() == nullptr) break; cur = cur->GetDown(); } cur->SetDown(node);//set node->SetUp(cur);//set return; } else {//y is no 0 while (1) { if (cur->GetDown() == nullptr) break; cur = cur->GetDown(); } for (int a = 0; a < 3; a++) { if (cur->GetRight() == nullptr) { cur->SetRight(node);//set node->SetLeft(cur);//set return; } cur = cur->GetRight(); } } } void MyBoard::connect() { MyBlock* cur = m_pHead;//declare MyBlock* temp = m_pHead->GetDown(); int a = 0; while (1) { int b = 0; a++; while (1) { b++; if (temp->GetUp() == nullptr) {//if temp up is null temp->SetUp(cur);//set cur->SetDown(temp);//set } if (b == 4) break; temp = temp->GetRight();//temp go right cur = cur->GetRight();//cur go right } if (a == 3) break; cur = cur->GetDown()->GetLeft()->GetLeft()->GetLeft();//set temp = cur->GetDown();//set } } bool MyBoard::putnum() { srand((unsigned int)time(NULL));//srand num vector<int>arr_x; vector<int>arr_y; if (m_pHead == nullptr) return false; MyBlock* cur = m_pHead;//delcare MyBlock* temp = m_pHead;//declare for (int a = 0; a < 4; a++) { for (int b = 0; b < 4; b++) { if (cur->GetNum() == 0) {//if cur num is empty arr_x.push_back(cur->Get_x()); arr_y.push_back(cur->Get_y()); } if (cur->GetRight() == nullptr) continue; cur = cur->GetRight(); } if (temp->GetDown() == nullptr) break; temp = temp->GetDown(); cur = temp; } if (arr_x.size() == 0)//if no empty place return false; int v_size = arr_x.size();//node's count int num = rand() % v_size;//num is random num to count of node cur = m_pHead; temp = m_pHead; for (int a = 0; a < 4; a++) { for (int b = 0; b < 4; b++) { if (cur->Get_x() == arr_x[num] && cur->Get_y() == arr_y[num]) {//if find num cur->SetNum(2);//add 2 return true; } if (cur->GetRight() == nullptr) continue; cur = cur->GetRight(); } if (temp->GetDown() == nullptr) break; temp = temp->GetDown(); cur = temp; } return false; } bool MyBoard::copy(MyBoard board, MyBoard temp_board) {//copy if (m_pHead == nullptr) return false; MyBlock* cur = board.m_pHead;//declare MyBlock* temp = board.m_pHead;//declare MyBlock* cur1 = temp_board.m_pHead;//declare MyBlock* temp1 = temp_board.m_pHead;//declare for (int a = 0; a < 4; a++) { for (int b = 0; b < 4; b++) { cur1->SetNum(cur->GetNum());//copy if (cur->GetRight() == nullptr) continue; cur = cur->GetRight(); cur1 = cur1->GetRight(); } if (temp->GetDown() == nullptr) break; temp = temp->GetDown(); temp1 = temp1->GetDown(); cur = temp; cur1 = temp1; } return true; } bool MyBoard::check(MyBoard board, MyBoard temp_board) { int a = temp_board.up();//line 1 copy(board,temp_board); int b = temp_board.down();//line 2 copy(board, temp_board); int c = temp_board.right();//line 3 copy(board, temp_board); int d = temp_board.left();//line 4 copy(board, temp_board); if(a+b+c+d ==0)//if no move return false; } bool MyBoard::win() { if (m_pHead == nullptr) return false; MyBlock* cur = m_pHead; MyBlock* temp = m_pHead; for (int a = 0; a < 4; a++) { for (int b = 0; b < 4; b++) { if (cur->GetNum() == 2048) return true;//if node is 2048 return ture if (cur->GetRight() == nullptr) continue; cur = cur->GetRight(); } if (temp->GetDown() == nullptr) break; temp = temp->GetDown(); cur = temp; } return false;//no 2048 node } bool MyBoard::up() { MyBlock* temp = m_pHead; int a = up(temp);//line 1 temp = temp->GetRight(); int b = up(temp);//line 2 temp = temp->GetRight(); int c = up(temp);//line 3 temp = temp->GetRight(); int d = up(temp);//line 4 if (a + b + c + d > 0)//if move return true; else return false;//if no move } int MyBoard::up(MyBlock* node) { MyBlock* cur = node->GetDown(); MyBlock* cur_pre = node; int a = 0; int count = 0; while (1) { int move = 0; while (1) { if (cur->GetNum() != 0) {//there is num not 0 if (cur->GetNum() == cur_pre->GetNum()) {//same with pre node if (move >= 2 && count >=3) {//if move more 2 and count 3 move = 0; break; } cur_pre->SetNum(cur_pre->GetNum() * 2);//merge cur->SetNum(0);//set count++; break; } else if (cur_pre->GetNum() == 0) {//pre node is 0 cur_pre->SetNum(cur->GetNum()); cur->SetNum(0); count++; } else if (cur_pre->GetNum() != cur->GetNum()) {//no same pre break; } } else {//cur node is 0 break; } if (cur_pre == node) { break; } else { if (move >= 2) { move = 0; break; } cur = cur->GetUp(); cur_pre = cur_pre->GetUp(); move++; } } a++; cur = node->GetDown(); cur_pre = node; if (a == 1) {//if roof is 1 cur_pre = cur; cur = cur->GetDown(); } else if (a == 2) {//if roof is 2 cur_pre = cur_pre->GetDown()->GetDown(); cur = cur->GetDown()->GetDown(); } else break; } return count; } bool MyBoard::down() { MyBlock* temp = m_pHead->GetDown()->GetDown()->GetDown(); int a = down(temp);//line 1 temp = temp->GetRight(); int b = down(temp);//line 2 temp = temp->GetRight(); int c = down(temp);//line 3 temp = temp->GetRight(); int d = down(temp);//line 4 if (a + b + c + d > 0) return true; else return false; } int MyBoard::down(MyBlock* node) { MyBlock* cur = node->GetUp(); MyBlock* cur_pre = node; int a = 0; int count = 0; while (1) { int move = 0; while (1) { if (cur->GetNum() != 0) {//if cur is no 0 if (cur->GetNum() == cur_pre->GetNum()) {//same with prenode if (move >= 2 && count >= 3) { move = 0; break; } cur_pre->SetNum(cur_pre->GetNum() * 2); cur->SetNum(0); count++; break; } else if (cur_pre->GetNum() == 0) {//pre is 0 cur_pre->SetNum(cur->GetNum()); cur->SetNum(0); count++; } else if (cur_pre->GetNum() != cur->GetNum()) {//no same with pre node break; } } else {//cur is 0 break; } if (cur_pre == node) { break; } else { if (move >= 2) { move = 0; break; } cur = cur->GetDown(); cur_pre = cur_pre->GetDown(); move++; } } a++; cur = node->GetUp(); cur_pre = node; if (a == 1) {//roof is 1 cur_pre = cur; cur = cur->GetUp(); } else if (a == 2) {//roof is 2 cur_pre = cur_pre->GetUp()->GetUp(); cur = cur->GetUp()->GetUp(); } else//else break; break; } return count; } bool MyBoard::left() { MyBlock* temp = m_pHead; int a =left(temp);//line 1 temp = temp->GetDown(); int b =left(temp);//line 2 temp = temp->GetDown(); int c =left(temp);//line 3 temp = temp->GetDown(); int d =left(temp);//line 4 if (a + b + c + d > 0) return true; else return false; } int MyBoard::left(MyBlock* node) { MyBlock* cur = node->GetRight(); MyBlock* cur_pre = cur->GetLeft(); MyBlock* temp = node; int a = 0; int count = 0; while (1) { int move = 0; while (1) { if (cur->GetNum() != 0) {//cur is no 0 if (cur_pre->GetNum() == cur->GetNum()) {//same with pre node if (move >= 2 && count >= 3) { move = 0; break; } cur_pre->SetNum(cur_pre->GetNum() * 2); cur->SetNum(0); count++; break; } else if (cur_pre->GetNum() == 0) {//if pre node is 0 cur_pre->SetNum(cur->GetNum()); cur->SetNum(0); count++; } else if (cur_pre->GetNum() != cur->GetNum()) {//no same with pre node break; } } else { break; } if (cur_pre == node) { break; } else { if (move >= 2) { move = 0; break; } cur = cur->GetLeft(); cur_pre = cur_pre->GetLeft(); move++; } } a++; cur = node->GetRight(); cur_pre = node; if (a == 1) {//roof is 1 if (cur->GetRight() == nullptr) break; cur_pre = cur; cur = cur->GetRight(); } else if (a == 2) {//roof is 2 if (cur->GetRight() == nullptr) break; cur_pre = cur_pre->GetRight()->GetRight(); cur = cur->GetRight()->GetRight(); } else break; } return count; } bool MyBoard::right() { MyBlock* temp = m_pHead->GetRight()->GetRight()->GetRight(); int a = right(temp);//line 1 temp = temp->GetDown(); int b = right(temp);//line 2 temp = temp->GetDown(); int c = right(temp);//line 3 temp = temp->GetDown(); int d = right(temp);//line 4 if (a + b + c + d > 0) return true; else return false; } int MyBoard::right(MyBlock* node) { MyBlock* cur = node->GetLeft(); MyBlock* cur_pre = cur->GetRight(); MyBlock* temp = node; int a = 0; int count = 0; while (1) { int move = 0; while (1) { if (cur->GetNum() != 0) {//cur is no 0 if (cur_pre->GetNum() == cur->GetNum()) {//same with pre node if (move >= 2 && count >= 3) { move = 0; break; } cur_pre->SetNum(cur_pre->GetNum() * 2); cur->SetNum(0); count++; break; } else if (cur_pre->GetNum() == 0) {//pre node is 0 cur_pre->SetNum(cur->GetNum()); cur->SetNum(0); count++; } else if (cur_pre->GetNum() != cur->GetNum()) {//no same with pre node break; } } else {//cur is 0 break; } if (cur_pre == node) { break; } else { if (move >= 2) { move = 0; break; } cur = cur->GetRight(); cur_pre = cur_pre->GetRight(); move++; } } a++; cur = node->GetLeft(); cur_pre = node; if (a == 1) {//roof is 1 if (cur->GetLeft() == nullptr) break; cur_pre = cur; cur = cur->GetLeft(); } else if (a == 2) {//roof is 2 if (cur->GetLeft() == nullptr) break; cur_pre = cur_pre->GetLeft()->GetLeft(); cur = cur->GetLeft()->GetLeft(); } else break; } return count; } <file_sep>#include "Board.h" #include <iostream> using namespace std; void print_menu(); int main() { MyBoard m_Board;//declare MyBoard temp_board;//declare for (int a = 0; a < 4; a++) { for (int b = 0; b < 4; b++) {//make map and insert node MyBlock* newNode = new MyBlock(0, a, b); m_Board.make_board(newNode); } } for (int a = 0; a < 4; a++) { for (int b = 0; b < 4; b++) {//make map and insert node MyBlock* newNode = new MyBlock(0, a, b); temp_board.make_board(newNode); } } m_Board.connect();//connect node temp_board.connect();//connect node int user_input = 0; m_Board.putnum();//put random num cout << "[Start]" << endl; while (1) { m_Board.print_board();//print temp_board.copy(m_Board,temp_board);//copy board to temp if (temp_board.check(m_Board, temp_board) == false) {//check rose cout << "Lose!!" << endl; cout << "[program exit]" << endl; return 0; } if (m_Board.win() == true) {//check win cout << "Win!!" << endl; cout << "[program exit]" << endl; return 0; } cout << endl; print_menu();//print menu cin >> user_input; if (user_input == 1) {//if 1 up if (m_Board.up() == true) { m_Board.putnum();//put random num } else { continue; } } else if (user_input == 2) { if (m_Board.down() == true) {//if 2 down m_Board.putnum(); } else { continue; } } else if (user_input == 3) { if (m_Board.left() == true) {//if 3 left m_Board.putnum(); } else { continue; } } else if (user_input == 4) {//if 4 right if (m_Board.right() == true) { m_Board.putnum(); } else { continue; } } else if (user_input == -1) {//if -1 return cout << endl; cout << "[program exit]"; return 0; } user_input = 0; } } void print_menu() { cout << "[Menu]" << endl; cout << "1.Up 2,Down 3.Left 4.Right" << endl; cout << "Input >> "; } <file_sep>#include "pch.h" #include "Board.h" #include<iostream> #include <time.h> #include <fstream> #pragma warning (disable:4996) using namespace std; Board::Board() { Block* pnew;//declare Block* cur = Block_Header;//declare Block* pCol = Block_Header;//declare for (int i = 0; i < 4 * 4; i++) { //declare pnew = new Block(); pnew->setNum(0); pnew->setX(i % 4); pnew->setY(i / 4); if (Block_Header == NULL) { Block_Header = pnew; cur = Block_Header; } else { cur->setRight(pnew); pnew->setLeft(cur); cur = cur->getRight(); } } cur = Block_Header; pCol = Block_Header; Block* temp = Block_Header; for (int j = 0; j < 4; j++) { cur = cur->getRight(); }//cur는 다음 행의 첫번째 노드를 가리킴 for (int i = 0; i < 4 - 1; i++) { //전 행의 모든 노드들과 연결시킨다. for (int j = 0; j < 4; j++) { cur->setUp(temp); temp->setDown(cur); temp = temp->getRight(); cur = cur->getRight(); } } cur = Block_Header; //일차원 배열에서 다음 행으로 넘어가는 노드들의 연결을 해제 for (int i = 0; i < 4 * 4; i++) { if (i % 4 == 0 && i != 0) { cur->getLeft()->setRight(NULL); cur->setLeft(NULL); } cur = cur->getRight(); } //board setting 시, 초기 turn change Put_random_num2();//turn 변경 -> 랜덤으로 2 추가 Put_random_num2(); } Board::~Board() { //(0,0)부터 (3,3)까지 for (int i = 3; i >= 0; i--) { for (int j = 3; j >= 0; j--) { delete getBlock_x_y(i, j); } } } //매 turn이 바뀔 때마다 비어있는 랜덤의 block에 number 2를 할당 bool Board::Put_random_num2() { if (Check_block() == 0) return 0; Block* temp = 0; int x = 0, y = 0; srand((unsigned)time(NULL)); while (1) { // random : 0 ~ 3 y = rand() % 4; x = rand() % 4; temp = getBlock_x_y(x, y);//좌표의 노드를 탐색 if (temp != NULL && temp->getNum() == 0)//탐색한 노드의 number가 0일 때만 { //check[x][y] = 1; temp->setNum(2);//number을 2로 설정 return true;//성공시 true 반환 } } } //비어있는 Block이 있을 경우 return 1 , 모든 Block이 꽉차있을경우 return 0; bool Board::Check_block() { Block* cur = Block_Header;//옆으로 탐색하는 노드 Block* pDown = Block_Header;//밑으로 내려가는 노드 while (pDown) { while (cur)//옆으로 탐색 { //만약 좌표에 해당하는 노드면 해당 노드를 반환 if (cur->getNum() == 0) { return 1; } cur = cur->getRight(); } pDown = pDown->getDown();//밑으로 내려간다. cur = pDown;//밑으로 내려간 노드부터 다시 옆으로 탐색 } return 0; } //(x,y) 좌표에 해당하는 노드를 반환함. Block* Board::getBlock_x_y(int x, int y) { Block* pResult = Block_Header; for (int i = 0; i < x; i++)//x축이동 { pResult = pResult->getRight(); } for (int j = 0; j < y; j++)//y축이동 { pResult = pResult->getDown(); } return pResult;//(x,y)에 해당하는 노드 } Block* Board::getHead() { return Block_Header; } //시계방향으로 rotation void Board::rotation_time() { int temp = 0; temp = getBlock_x_y(3, 0)->getNum();//(3,0)부터 시작. getBlock_x_y(3, 0)->setNum(getBlock_x_y(0, 0)->getNum()); getBlock_x_y(0, 0)->setNum(getBlock_x_y(0, 3)->getNum()); getBlock_x_y(0, 3)->setNum(getBlock_x_y(3, 3)->getNum()); getBlock_x_y(3, 3)->setNum(temp);//한바퀴의 마지막 temp = getBlock_x_y(3, 1)->getNum();//(3,1)부터 시작. getBlock_x_y(3, 1)->setNum(getBlock_x_y(1, 0)->getNum()); getBlock_x_y(1, 0)->setNum(getBlock_x_y(0, 2)->getNum()); getBlock_x_y(0, 2)->setNum(getBlock_x_y(2, 3)->getNum()); getBlock_x_y(2, 3)->setNum(temp); // 한바퀴의 마지막 temp = getBlock_x_y(3, 2)->getNum();//(3,2)부터 시작. getBlock_x_y(3, 2)->setNum(getBlock_x_y(2, 0)->getNum()); getBlock_x_y(2, 0)->setNum(getBlock_x_y(0, 1)->getNum()); getBlock_x_y(0, 1)->setNum(getBlock_x_y(1, 3)->getNum()); getBlock_x_y(1, 3)->setNum(temp); // 한바퀴의 마지막 temp = getBlock_x_y(2, 1)->getNum();//(2,1)부터 시작. getBlock_x_y(2, 1)->setNum(getBlock_x_y(1, 1)->getNum()); getBlock_x_y(1, 1)->setNum(getBlock_x_y(1, 2)->getNum()); getBlock_x_y(1, 2)->setNum(getBlock_x_y(2, 2)->getNum()); getBlock_x_y(2, 2)->setNum(temp);// 한바퀴의 마지막 } //반시계방향 rotation void Board::rotation_reverse_time() { int temp = 0; temp = getBlock_x_y(3, 0)->getNum();//(3,0)부터 시작. getBlock_x_y(3, 0)->setNum(getBlock_x_y(3, 3)->getNum()); getBlock_x_y(3, 3)->setNum(getBlock_x_y(0, 3)->getNum()); getBlock_x_y(0, 3)->setNum(getBlock_x_y(0, 0)->getNum()); getBlock_x_y(0, 0)->setNum(temp);//한바퀴의 마지막 temp = getBlock_x_y(3, 1)->getNum();//(3,1)부터 시작. getBlock_x_y(3, 1)->setNum(getBlock_x_y(2, 3)->getNum()); getBlock_x_y(2, 3)->setNum(getBlock_x_y(0, 2)->getNum()); getBlock_x_y(0, 2)->setNum(getBlock_x_y(1, 0)->getNum()); getBlock_x_y(1, 0)->setNum(temp);//한바퀴의 마지막 temp = getBlock_x_y(3, 2)->getNum();//(3,2)부터 시작. getBlock_x_y(3, 2)->setNum(getBlock_x_y(1, 3)->getNum()); getBlock_x_y(1, 3)->setNum(getBlock_x_y(0, 1)->getNum()); getBlock_x_y(0, 1)->setNum(getBlock_x_y(2, 0)->getNum()); getBlock_x_y(2, 0)->setNum(temp);//한바퀴의 마지막 temp = getBlock_x_y(2, 1)->getNum();//(2,1)부터 시작. getBlock_x_y(2, 1)->setNum(getBlock_x_y(2, 2)->getNum()); getBlock_x_y(2, 2)->setNum(getBlock_x_y(1, 2)->getNum()); getBlock_x_y(1, 2)->setNum(getBlock_x_y(1, 1)->getNum()); getBlock_x_y(1, 1)->setNum(temp);//한바퀴의 마지막 } //Board를 파일로 출력하는 함수 void Board::printBoard(int count, CFile& outFile, int menu) { Block* cur = Block_Header; Block* pDown = Block_Header; //temp를 버퍼처럼 사용 char temp[30] = { 0 };//모든 문자열들을 temp에 저장하여 사용 //count를 출력 itoa(count, temp, 10); outFile.Write(temp, strlen(temp)); memset(temp, 0, 30); if (menu == 1)//Key Left { strcpy(temp, ". Key Left\r\n"); outFile.Write(temp, strlen(temp)); memset(temp, 0, 30); } else if (menu == 2)//Key Right { strcpy(temp, ". Key Right\r\n"); outFile.Write(temp, strlen(temp)); memset(temp, 0, 30); } else if (menu == 3)//Key Down { strcpy(temp, ". Key Down\r\n"); outFile.Write(temp, strlen(temp)); memset(temp, 0, 30); } else if (menu == 4)//Key Up { strcpy(temp, ". Key Up\r\n"); outFile.Write(temp, strlen(temp)); memset(temp, 0, 30); } else if (menu == 6)//Mouse_Right_to_Left { strcpy(temp, ". Mouse_Right_to_Left\r\n"); outFile.Write(temp, strlen(temp)); memset(temp, 0, 30); } else if (menu == 5)//Mouse_Left_to_Right { strcpy(temp, ". Mouse_Left_to_Right\r\n"); outFile.Write(temp, strlen(temp)); memset(temp, 0, 30); } //result를 출력 strcpy(temp, "[result]\r\n"); outFile.Write(temp, strlen(temp)); memset(temp, 0, 30); while (pDown)//밑으로 탐색 { while (cur)//옆으로 탐색 { if (cur->getNum() == 0)//0이면 공백을 출력해준다. { strcpy(temp, " "); outFile.Write(temp, strlen(temp)); memset(temp, 0, 30); } else//0이 아닌 숫자면 해당숫자를 출력한다. { itoa(cur->getNum(), temp, 10); outFile.Write(temp, strlen(temp)); memset(temp, 0, 30); strcpy(temp, " "); outFile.Write(temp, strlen(temp)); memset(temp, 0, 30); memset(temp, 0, 30); } cur = cur->getRight();//오른쪽으로 넘어간다. } strcpy(temp, "\r\n"); outFile.Write(temp, strlen(temp)); memset(temp, 0, 30); pDown = pDown->getDown();//밑으로 내려간다. cur = pDown;//밑으로 내려간 노드부터 다시 옆으로 탐색 } strcpy(temp, "\r\n"); outFile.Write(temp, strlen(temp)); outFile.Write(temp, strlen(temp)); memset(temp, 0, 30); } //2048이 있으면 return 1;, 없으면 return 0;, bool Board::Check_win() { Block* cur = Block_Header; Block* pDown = Block_Header; while (pDown) { while (cur)//옆으로 탐색 { if (cur->getNum() == 2048) return 1; cur = cur->getRight(); } pDown = pDown->getDown();//밑으로 내려간다. cur = pDown;//밑으로 내려간 노드부터 다시 옆으로 탐색 } return 0; } //실패시 return 1, 실패가 아니고 더 진행가능하면 return 0; bool Board::Check_fail() { Block* cur = Block_Header; Block* pDown = Block_Header; while (pDown)//밑으로 탐색 { while (cur)//옆으로 탐색 { if (cur->getNum() == 0)//블럭의 숫자가 0이면 더 진행가능 : 실패가 아님 -> return 0 { return 0; } else//인접 블럭에 같은 숫자들이 있는지 확인 : 하나라도 있으면 실패가 아니다. -> return 0 { if (cur->getUp()) { if (cur->getNum() == cur->getUp()->getNum()) return 0; } if (cur->getDown()) { if (cur->getNum() == cur->getDown()->getNum()) return 0; } if (cur->getRight()) { if (cur->getNum() == cur->getRight()->getNum()) return 0; } if (cur->getLeft()) { if (cur->getNum() == cur->getLeft()->getNum()) return 0; } } cur = cur->getRight(); } pDown = pDown->getDown();//밑으로 내려간다. cur = pDown;//밑으로 내려간 노드부터 다시 옆으로 탐색 } return 1;//위 과정을 거치는 동안 0이 반환이 안된다면 실패가 맞다고 판단 -> return 1 } //숫자들을 하나도 밀지 않을 경우 return 0; 하나라도 밀경우 return 1; //Up() 이외에 Down(), Right(), Left() 함수들도 모두 같은 방식. bool Board::Up() { Block* cur = 0; bool perform = 0; //STAGE 1 :0이상의 숫자들을 위쪽으로 몰아넣기 for (int x = 0; x <= 3; x++) { for (int i = 0; i < 3; i++) { for (int y = 0; y < 3; y++) { cur = getBlock_x_y(x, y);//좌표에 해당하는 블럭을 얻는다. if (cur->getNum() == 0)//number가 0인 블럭이면 { swap(cur, 'd');//cur을 아래쪽 블럭과 swap if (cur->getUp()->getNum() != 0)//swap한 노드의 number가 0이 아닌수 이면 perform = 1;//수행 여부(한번이라도 유효한 수행이 된 경우 1을 저장) //유효한 수행이란 0이아닌값과 노드 swap되는 경우 } } } } //STAGE 2 : 같은숫자 더하기 for (int x = 0; x <= 3; x++) { for (int y = 0; y < 3; y++)//위쪽에서 밑쪽으로 진행 { cur = getBlock_x_y(x, y); //cur의 아래쪽 블럭이 존재하고 cur과 cur의 아래쪽 블럭의 숫자가 같을 때 if (cur->getDown() && cur->getNum() == cur->getDown()->getNum() && cur->getNum() != 0) { //cur의 블럭으로 숫자를 더해줌 cur->setNum(cur->getNum() + cur->getDown()->getNum()); cur->getDown()->setNum(0); perform = 1; } else continue; } } //STAGE 3 : 다시 위쪽으로 몰아넣기 for (int x = 0; x <= 3; x++) { for (int i = 0; i < 3; i++) { for (int y = 0; y < 3; y++) { cur = getBlock_x_y(x, y);//좌표에 해당하는 블럭을 얻는다. if (cur->getNum() == 0)//number가 0인 블럭이면 { swap(cur, 'd');//아래쪽 블럭과 swap if (cur->getUp()->getNum() != 0) perform = 1; } } } } return perform; } bool Board::Down() { Block* cur = 0; bool perform = 0; //Stage 1 for (int x = 3; x >= 0; x--) { for (int i = 0; i < 3; i++) { for (int y = 3; y > 0; y--)//밑쪽에서 위쪽으로 진행 { cur = getBlock_x_y(x, y); if (cur->getNum() == 0) { swap(cur, 'u');//위쪽 블럭과 swap if (cur->getDown()->getNum() != 0) perform = 1; } } } } //Stage 2 for (int x = 0; x <= 3; x++) { for (int y = 3; y > 0; y--) { cur = getBlock_x_y(x, y); //cur의 위쪽 블럭이 존재하고 cur과 cur의 위쪽 블럭의 숫자가 같을 때 if (cur->getUp() && cur->getNum() == cur->getUp()->getNum() && cur->getNum() != 0) { //cur의 블럭으로 숫자를 더해줌 cur->setNum(cur->getNum() + cur->getUp()->getNum()); cur->getUp()->setNum(0); perform = 1; } else continue; } } //Stage 3 for (int x = 3; x >= 0; x--) { for (int i = 0; i < 3; i++) { for (int y = 3; y > 0; y--) { cur = getBlock_x_y(x, y); if (cur->getNum() == 0) { swap(cur, 'u');//위쪽 블럭과 swap if (cur->getDown()->getNum() != 0) perform = 1; } } } } return perform; } bool Board::Left() { Block* cur = 0; bool perform = 0; //Stage 1 for (int y = 0; y <= 3; y++) { for (int i = 0; i < 3; i++) { for (int x = 0; x < 3; x++)//왼쪽에서 오른쪽으로 진행 { cur = getBlock_x_y(x, y);//좌표에 해당하는 블럭을 얻는다. if (cur->getNum() == 0)//number가 0인 블럭이면 { swap(cur, 'r');//오른쪽 블럭과 swap if (cur->getLeft()->getNum() != 0) perform = 1; } } } } //Stage 2 for (int y = 0; y <= 3; y++) { for (int x = 0; x < 3; x++) { cur = getBlock_x_y(x, y); //cur의 오른쪽 블럭이 존재하고 cur과 cur의 오른쪽 블럭의 숫자가 같을 때 if (cur->getRight() && cur->getNum() == cur->getRight()->getNum() && cur->getNum() != 0) { //cur의 블럭으로 숫자를 더해줌 cur->setNum(cur->getNum() + cur->getRight()->getNum()); cur->getRight()->setNum(0); perform = 1; } else continue; } } //Stage 3 for (int y = 0; y <= 3; y++) { for (int i = 0; i < 3; i++) { for (int x = 0; x < 3; x++) { cur = getBlock_x_y(x, y); if (cur->getNum() == 0) { swap(cur, 'r');//오른쪽 블럭과 swap if (cur->getLeft()->getNum() != 0) perform = 1; } } } } return perform; } bool Board::Right() { Block* cur = 0; bool perform = 0; //Stage 1 for (int y = 0; y <= 3; y++) { for (int i = 0; i < 3; i++) { for (int x = 3; x > 0; x--)//오른쪽에서 왼쪽으로 진행 { cur = getBlock_x_y(x, y);//좌표에 해당하는 블럭을 얻는다. if (cur->getNum() == 0)//number가 0인 블럭이면 { swap(cur, 'l');//왼쪽 노드와 swap if (cur->getRight()->getNum() != 0) perform = 1; } } } } //Stage 2 for (int y = 0; y <= 3; y++) { for (int x = 3; x > 0; x--) { cur = getBlock_x_y(x, y); //cur의 왼쪽 블럭이 존재하고 cur과 cur의 왼쪽 블럭의 숫자가 같을 때 if (cur->getLeft() && cur->getNum() == cur->getLeft()->getNum() && cur->getNum() != 0) { //cur의 왼쪽 블럭으로 숫자를 더해줌 cur->setNum(cur->getNum() + cur->getLeft()->getNum()); cur->getLeft()->setNum(0); perform = 1; } else continue; } } //Stage 3 for (int y = 0; y <= 3; y++) { for (int i = 0; i < 3; i++) { for (int x = 3; x > 0; x--)//오른쪽에서 왼쪽으로 진행 { cur = getBlock_x_y(x, y); if (cur->getNum() == 0) { swap(cur, 'l');//아래쪽 블럭과 swap if (cur->getRight()->getNum() != 0) perform = 1; } } } } return perform; } void Board::swap(Block* pTB, char d) { Block* s = 0;//(switch_Block) 스위치 될 노드 int temp_x = 0, temp_y = 0; //방향에 따른 노드 포인터 설정 if (d == 'u') { s = pTB->getUp(); } else if (d == 'd') { s = pTB->getDown(); } else if (d == 'l') { s = pTB->getLeft(); } else if (d == 'r') { s = pTB->getRight(); } else { cout << "\ncheck_move_able() : error unknown value '" << d << "'" << endl;//잘못된 방향입력 시. 프로그램 종료 exit(2); } //좌표값 바꾸기 temp_x = s->getX(); temp_y = s->getY(); s->setX(pTB->getX()); s->setY(pTB->getY()); pTB->setX(temp_x); pTB->setY(temp_y); if (pTB->getX() == 0 && pTB->getY() == 0) Block_Header = pTB; else if (s->getX() == 0 && s->getY() == 0) Block_Header = s; //좌표 설정 완료/// //switch 될 노드와 Zero노드의 인접 노드들. Block* s_Left = s->getLeft(); Block* s_Right = s->getRight(); Block* s_Up = s->getUp(); Block* s_Down = s->getDown(); Block* z_Left = pTB->getLeft(); Block* z_Right = pTB->getRight(); Block* z_Down = pTB->getDown(); Block* z_Up = pTB->getUp(); // u , d , l , r 방향에 따른 노드 swap if (d == 'u') { //상하 경우에 따른 swap if (s_Up == NULL && z_Down == NULL)//위 아래가 막혔을 때 { s->setUp(pTB); pTB->setDown(s); s->setDown(NULL); pTB->setUp(NULL); } else if (s_Up == NULL)//위가 막혔을 때 { pTB->setDown(s); s->setUp(pTB); s->setDown(z_Down); z_Down->setUp(s); pTB->setUp(NULL); } else if (z_Down == NULL)//밑이 막혔을 때 { pTB->setDown(s); s->setUp(pTB); pTB->setUp(s_Up); s_Up->setDown(pTB); s->setDown(NULL); } else//중간에 껴있을 때 { pTB->setDown(s); s->setUp(pTB); s_Up->setDown(pTB); pTB->setUp(s_Up); s->setDown(z_Down); z_Down->setUp(s); } //좌우 인접노드 링크 갱신 //s에 인접한노드 갱신 if (s_Right) { s_Right->setLeft(pTB); pTB->setRight(s_Right); } if (s_Left) { s_Left->setRight(pTB); pTB->setLeft(s_Left); } //zero 노드에 인접한 노드 갱신 if (z_Right) { z_Right->setLeft(s); s->setRight(z_Right); } if (z_Left) { z_Left->setRight(s); s->setLeft(z_Left); } } else if (d == 'd') { //상하 경우에 따른 swap if (s_Down == NULL && z_Up == NULL)//위아래가 다 NULL일 때 { s->setDown(pTB); pTB->setUp(s); s->setUp(NULL); pTB->setDown(NULL); } else if (z_Up == NULL)//zero의 위가 NULL일 때 { pTB->setUp(s); s->setDown(pTB); pTB->setDown(s_Down); s_Down->setUp(pTB); s->setUp(NULL); } else if (s_Down == NULL)//switch 노드의 밑이 NULL일 때 { pTB->setUp(s); s->setDown(pTB); s->setUp(z_Up); z_Up->setDown(s); pTB->setDown(NULL); } else//중간에 껴있을 때 { pTB->setUp(s); s->setDown(pTB); z_Up->setDown(s); s->setUp(z_Up); pTB->setDown(s_Down); s_Down->setUp(pTB); } //좌우 인접노드 링크 갱신 //s에 인접한노드 갱신 if (s_Right) { s_Right->setLeft(pTB); pTB->setRight(s_Right); } if (s_Left) { s_Left->setRight(pTB); pTB->setLeft(s_Left); } //zero 노드에 인접한 노드 갱신 if (z_Right) { z_Right->setLeft(s); s->setRight(z_Right); } if (z_Left) { z_Left->setRight(s); s->setLeft(z_Left); } } else if (d == 'l') { //좌우 경우에 따른 swap if (s_Left == NULL && z_Right == NULL) { s->setLeft(pTB); pTB->setRight(s); s->setRight(NULL); pTB->setLeft(NULL); } else if (z_Right == NULL)//zero 노드의 오른쪽이 NULL일 때 { pTB->setRight(s); s->setLeft(pTB); pTB->setLeft(s_Left); s_Left->setRight(pTB); s->setRight(NULL); } else if (s_Left == NULL)//switch 노드의 왼쪽이 NULL일 떄 { pTB->setRight(s); s->setLeft(pTB); s->setRight(z_Right); z_Right->setLeft(s); pTB->setLeft(NULL); } else//중간에 껴있을 때 { pTB->setRight(s); s->setLeft(pTB); s->setRight(z_Right); z_Right->setLeft(s); pTB->setLeft(s_Left); s_Left->setRight(pTB); } //좌우 인접노드 링크 갱신 //s에 인접한노드 갱신 if (s_Down) { s_Down->setUp(pTB); pTB->setDown(s_Down); } if (s_Up) { s_Up->setDown(pTB); pTB->setUp(s_Up); } //zero 노드에 인접한 노드 갱신 if (z_Down) { z_Down->setUp(s); s->setDown(z_Down); } if (z_Up) { z_Up->setDown(s); s->setUp(z_Up); } } else if (d == 'r') { //좌우 경우에 따른 swap if (s_Right == NULL && z_Left == NULL) { s->setRight(pTB); pTB->setLeft(s); s->setLeft(NULL); pTB->setRight(NULL); } else if (s_Right == NULL)//s 노드의 오른쪽이 NULL일 때 { pTB->setLeft(s); s->setRight(pTB); z_Left->setRight(s); s->setLeft(z_Left); pTB->setRight(NULL); } else if (z_Left == NULL)//switch 노드의 왼쪽이 NULL일 떄 { pTB->setLeft(s); s->setRight(pTB); s_Right->setLeft(pTB); pTB->setRight(s_Right); s->setLeft(NULL); } else//중간에 껴있을 때 { pTB->setLeft(s); s->setRight(pTB); z_Left->setRight(s); s->setLeft(z_Left); pTB->setRight(s_Right); s_Right->setLeft(pTB); } //좌우 인접노드 링크 갱신 //s에 인접한노드 갱신 if (s_Down) { s_Down->setUp(pTB); pTB->setDown(s_Down); } if (s_Up) { s_Up->setDown(pTB); pTB->setUp(s_Up); } //zero 노드에 인접한 노드 갱신 if (z_Down) { z_Down->setUp(s); s->setDown(z_Down); } if (z_Up) { z_Up->setDown(s); s->setUp(z_Up); } } else { cout << "check_move_able() : error unknown value " << d << endl; } } <file_sep>#include "Graph.h" #include <map> #include <cstdlib> #include <iostream> #include <algorithm> Graph::Graph(ofstream * flog) { this->flog=flog; //get flog } Graph::~Graph() { } bool Graph::Build(AVLTree * root) { int a = 0; //value declare int weight = 0;//value declare while (gp_arry[size] != NULL) { //while gp arry is null a++; //count size++; //count } this->vertex = new CityData*[size + 1]; //reset this->mList = new map<int, CityData*>[size + 1]; //reset AVLNode * temp = new AVLNode(); //make new node for (int i = 0; i < size - 1; i++) { for (int j = i + 1; j < size; j++) { if (strncmp(gp_arry[i]->GetCityData()->Getname(), gp_arry[j]->GetCityData()->Getname(),sizeof(gp_arry[i]->GetCityData()->Getname())) > 0) { //if index i 's name si bigger than gp_arry's name temp = gp_arry[i]; //swap gp_arry[i] = gp_arry[j]; //swap gp_arry[j] = temp; //swap } } } for (int x = 0; x < a; x++) { { vertex[x] = gp_arry[x]->GetCityData(); //insert data into vertex } } for (int v = 0; v < size; v++) { for (int x = 0; x < a; x++) { mList[v].insert(make_pair(x, vertex[x])); //insert into mList } } return true; } void Graph::Print_GP() { //print gp int weight = 0;//value declare for (int a = 0; a < size; a++) { for (int b = 0; b < size; b++) {//weight is mlist's local- next local 's abs weight = abs(mList[a][a]->GetLocationId() - mList[a][b]->GetLocationId()); *flog << weight << " "; } *flog << endl; } } void Graph::Print_MST() { for (int a = 0; a < R_tree.size(); a++) {//print r_tree's data *flog<< "("<<R_tree[a].data1->Getname()<<", "; *flog << R_tree[a].data2->Getname()<<"), "; *flog<< R_tree[a].wei << endl; } *flog << "Total: " << mstMatrix << endl; } bool Graph::Kruskal() { edge ege[30][30] = { 0 };//edge's ege[30][30] value declare for (int a = 0; a < size; a++) for (int b = 0; b < size; b++) { ege[a][b].u = a;//insert value ege[a][b].v = b; //insert value ege[a][b].data1 = mList[a][a]; //insert data1 ege[a][b].data2 = mList[a][b]; //insert data2 ege[a][b].wei = abs(mList[a][a]->GetLocationId() - mList[a][b]->GetLocationId()); //insert weight if (ege[a][b].wei == 0) { //if wei is 0 break; break; } kru_tree.push_back((edge(ege[a][b])));//insert edge node into vector } sort(kru_tree.begin(), kru_tree.end());//sort it int parent[60];//value declare for (int i = 0; i < 60; i++) parent[i] = i; //set root value for (int i = 0; i < kru_tree.size(); i++) if (!find(parent, kru_tree[i].u, kru_tree[i].v)) { //if find union mstMatrix += kru_tree[i].wei; //get weight of kru_tree R_tree.push_back((edge(kru_tree[i]))); //insert in vector too union_set(parent, kru_tree[i].u, kru_tree[i].v);//union_set } return true; } int Graph::make_set(int parent[], int a) {//make ser if (parent[a] == a) //if parent [] is a return return a; return make_set(parent, parent[a]);//recursivly call fucntion } int Graph::union_set(int parent[],int x, int y) { //union_set x = make_set(parent, x);//make set parent and x y = make_set(parent, y);//make set parent and y if (x < y) { parent[y] = x; return x; } else { parent[x] = y; return y; } } int Graph::find(int parent[],int x,int y) { x = make_set(parent, x);//call make_set fucntion y = make_set(parent, y); if (x == y) { return 1; } else { return 0; } } void Graph::insert_gp(AVLNode * tree,int zzzz) { //insert gp arry if (gp_arry[0] == NULL) { //if arry is null gp_arry[0] = tree;//set root } else { gp_arry[zzzz] = tree; } return; } <file_sep>#include <iostream> using namespace std; int main() { int x1 = 0, y1 = 0;//declare int x2 = 0, y2 = 0;//declare int x3 = 0, y3 = 0;//declare cout << "P1: "; cin >> x1 >> y1;//get P1 point cout << "P2: "; cin >> x2 >> y2;//get P2 point cout << "P3: "; cin >> x3 >> y3;//get P3 point cout << endl; int mul; mul = x1 * y2 + x2 * y3 + x3 * y1;//mul is p1x * p2y + p2x * p3y + p3x * p1y mul = mul - x1 * y3 - x2 * y1 - x3 * y2;//if (p1x * p2y + p2x * p3y + p3x * p1y) -reverse mul is new mul if (mul < 0 )//if mul is negative cout << "Clockwise";// print clock wise else if (mul > 0)//if mul is pisitive cout << "Counter-Clockwise";//print counter clock wise else// else mean mul is 0 cout << "Straight";// print straight }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include "List.h" #include <vector> void List::insert_beginning(Node* newNode) { Node* n = new Node;//set n = newNode; if (head == nullptr) {//head is null head = n; tail = n; n->position = 1; } else if (tail == head) {//one node Node* temp = head; head = n; tail = temp; head->nextNode = tail; head->preNode = tail; tail->nextNode = head; tail->preNode = head; head->position = 1; tail->position = 2; } else {//else Node* temp = head; head = n; n->nextNode = temp; n->preNode = tail; temp->preNode = n; tail->nextNode = n; reposition(); } } void List::insert_last(Node* newNode) { Node* n = new Node;//set n = newNode; if (head == nullptr) {//head is null head = n; tail = n; n->position = 1; } else if (tail == head) {//head is tail Node* temp = tail; head = temp; tail = n; head->nextNode = tail; head->preNode = tail; tail->nextNode = head; tail->preNode = head; head->position = 1; tail->position = 2; } else {//head is no null and lot node Node* temp = tail; tail = n; temp->nextNode = n; n->nextNode = head; n->preNode = temp; head->preNode = n; reposition(); } } bool List::insert_position(Node* newNode, int posi) { Node* n = new Node;//set n = newNode; if (head == nullptr && posi == 1) {//head is null head = n; tail = n; n->position = 1; return true; } else if (posi == 1) {//position is 1 insert begin insert_beginning(n); return true; } else if (posi == tail->position + 1) {//insert last insert_last(n); return true; } else {//insert position Node* temp = head; while (1) { if (temp == nullptr) break; else temp = temp->nextNode; if (temp->position == posi) break; } Node* temp_pre = temp->preNode; n->nextNode = temp; temp->preNode = n; temp_pre->nextNode = n; n->preNode = temp_pre; reposition(); return true; } } void List::Display() { cout << "<Display lecture list>" << endl; Node* temp = head; if (temp == nullptr) return; while (1) { cout << "lecture name: " << temp->name << endl; cout << "lecture professor: " << temp->professor << endl; cout << "lecture grade: " << temp->grade << endl; if (temp->nextNode == nullptr || temp == tail) break; temp = temp->nextNode; } } void List::reposition() { if (head == nullptr) return; if (head->nextNode == nullptr) { head->position = 1; return; } Node* temp = head;//set int p = 2; head->position = 1; while (1) { temp = temp->nextNode; temp->position = p++; if (temp == tail) break; } } int List::maxposition() { if (head == nullptr) return 0; Node* temp = head; while (1) { if (temp->nextNode == nullptr) break; temp = temp->nextNode; if (temp == tail) break; } return temp->position; } bool List::delete_lecture(string u_name) { if (head == nullptr)//head is null return false; Node* temp = head; string temp_name; int temp_posi; while (1) { if (temp->name == u_name) {//name is umane temp_name = temp->name; temp_posi = temp->position; break; } if (temp->nextNode == nullptr) return false; if (temp == tail) return false; temp = temp->nextNode; } if (temp == head && temp->nextNode == nullptr) {//temp is head and next is null free(head); head = nullptr; delete head; } else if (temp == head) {//temp is head if (temp->nextNode == tail) {//next is tial head = tail; tail->nextNode = nullptr; tail->preNode = nullptr; head->nextNode = nullptr; head->preNode = nullptr; free(temp); temp = nullptr; delete temp; } else {//esles head = temp->nextNode; tail->nextNode = head; head->preNode = tail; free(temp); temp = nullptr; delete temp; } } else if (temp == tail) {//temp is tail if (temp->preNode == head) {//pre is head tail = head; tail->nextNode = nullptr; tail->preNode = nullptr; head->nextNode = nullptr; head->preNode = nullptr; free(temp); temp = nullptr; delete temp;//delete } else {//esle tail = temp->preNode; tail->nextNode = head; head->preNode = tail; free(temp); temp = nullptr; delete temp; } } else {//else temp->preNode->nextNode = temp->nextNode; temp->nextNode->preNode = temp->preNode; free(temp); temp = nullptr; delete temp; } reposition(); cout << "**" << temp_name << " has been deleted from position " << temp_posi << "**" << endl; cout << "------------------------------------------" << endl; return true; } bool List::search_lecture(string u_name) { if (head == nullptr) return false; Node* temp = head; while (1) { if (temp->name == u_name) return true; if (temp->nextNode == nullptr) break; if (temp == tail) break; temp = temp->nextNode; } return false; } void List::update_lecture(Node* newNode, string u_name) { if (head == nullptr) return; Node* temp = head; while (1) { if (temp->name == u_name) break; temp = temp->nextNode; } temp->name = newNode->name; temp->professor = newNode->professor; temp->grade = newNode->grade; } bool List::serch_lec(string u_name) {//serch if (head == nullptr)//head is null return false; Node* temp = head; while (1) { if (temp->name == u_name) break; if (temp->nextNode == nullptr) return false; if (temp == tail) return false; temp = temp->nextNode; } cout << "*At position " << temp->position << "*" << endl; cout << "lecture name: " << temp->name << endl; cout << "lecture professor: " << temp->professor << endl; cout << "lecture grade: " << temp->grade << endl; cout << "-----------------------------------" << endl << endl; return true; } bool List::search_pro(string u_name) { if (head == nullptr)//head is null return false; Node* temp = head;//set int count = 0; while (1) { if (temp->professor == u_name) { cout << "*At position " << temp->position << "*" << endl; cout << "lecture name: " << temp->name << endl; cout << "lecture professor: " << temp->professor << endl; cout << "lecture grade: " << temp->grade << endl << endl; count++; } if (temp->nextNode == nullptr && count == 0) return false; else if (temp->nextNode == nullptr) break; if (temp == tail && count == 0) return false; else if (temp == tail) break; temp = temp->nextNode; } return true; } bool List::search_grade(int g) { if (head == nullptr) return false;//head is null Node* temp = head; int count = 0; while (1) { if (temp->grade == g) { cout << "*At position " << temp->position << "*" << endl; cout << "lecture name: " << temp->name << endl; cout << "lecture professor: " << temp->professor << endl; cout << "lecture grade: " << temp->grade << endl << endl; count++; } if (temp->nextNode == nullptr && count == 0) return false; else if (temp->nextNode == nullptr) break; if (temp == tail && count == 0) return false; else if (temp == tail) break; temp = temp->nextNode; } return true; } void List::sort_ascending() { vector<string> v1; vector<string> v2; vector<int> v3; if (head == nullptr) return; Node* temp = head; if (temp->nextNode == nullptr) return; else { while (1) { if (temp == tail) break; Node* temp1 = temp->nextNode; while (1) { if (temp->grade > temp1->grade) { temp = temp1; } else if (temp->grade == temp1->grade) { char a[100];//set char b[100];//set strcpy(a, temp->name.c_str());//set strcpy(b, temp1->name.c_str());//set if (strcmp(a, b) > 0) {//a is bigger than b temp = temp1; } } if (temp1 == tail) {//set v1.push_back(temp->name);//set v2.push_back(temp->professor);//set v3.push_back(temp->grade);//set delete_lecture2(temp->name);//delete ndde break; } temp1 = temp1->nextNode; } temp = head; if (temp == tail) {//temp is tail v1.push_back(temp->name);//set v2.push_back(temp->professor);//set v3.push_back(temp->grade);//set delete_lecture2(temp->name);//delete break; } } for (int a = 0; a < v1.size(); a++) { Node* N = new Node; N->name = v1[a];//set N->professor = v2[a];//set N->grade = v3[a];//set insert_last(N);//set insert last } } } void List::reverse() { if (head == nullptr)//head is null return; if (head->nextNode == nullptr) return; int count = maxposition(); Node* temp = head; int a = 1; while ( a<count) {// a < coutn temp = temp->nextNode; a++; } Node* cur; while (1) {//temp is head break cur = temp->preNode; temp->preNode->nextNode = nullptr; temp->preNode = nullptr; temp->nextNode = cur; temp = cur; if (temp == head) break; } tail->preNode = head; head->nextNode = tail; Node* swap = head; head = tail; tail = swap; Node* z = head; while (1) {//z is tail z->nextNode->preNode = z; z = z->nextNode; if (z == tail) break; } reposition(); } void List::delete_lecture2(string u_name) {//delelete with no print if (head == nullptr) return; Node* temp = head; string temp_name; int temp_posi; while (1) { if (temp->name == u_name) { temp_name = temp->name; temp_posi = temp->position; break; } if (temp->nextNode == nullptr) return; if (temp == tail) return; temp = temp->nextNode; } if (temp == head && temp->nextNode == nullptr) { free(head); head = nullptr; delete head; } else if (temp == head) { if (temp->nextNode == tail) { head = tail; tail->nextNode = nullptr; tail->preNode = nullptr; head->nextNode = nullptr; head->preNode = nullptr; free(temp); temp = nullptr; delete temp; } else { head = temp->nextNode; tail->nextNode = head; head->preNode = tail; free(temp); temp = nullptr; delete temp; } } else if (temp == tail) { if (temp->preNode == head) { tail = head; tail->nextNode = nullptr; tail->preNode = nullptr; head->nextNode = nullptr; head->preNode = nullptr; free(temp); temp = nullptr; delete temp; } else { tail = temp->preNode; tail->nextNode = head; head->preNode = tail; free(temp); temp = nullptr; delete temp; } } else { temp->preNode->nextNode = temp->nextNode; temp->nextNode->preNode = temp->preNode; free(temp); temp = nullptr; delete temp; } reposition(); } <file_sep>#include <iostream> using namespace std; class Node { public: string cate;//declare string menu;//declare int price;//declare Node* nextNode;//declare Node* downNode;//declare }; class List { private: int count=0;//declare int row=0;//declare int col=0;//declare Node* head = new Node();//declare public: List() { head->nextNode = nullptr; count = 0;//declare } ~List() { remove(); } void add(Node * newnode);//declare bool cate_search(string cate);//declare bool menu_search(Node * mu); //declare void remove(); //declare Node* sort_ro(Node* new_node);//declare bool print();//declare bool search_cate(string cate);//declare bool search_menu(string menu);//declare bool delete_menu(string menu);//declare };<file_sep>#define _CRT_SECURE_NO_WARNINGS #include "TransferWindowManager.h" #include <fstream> #include <iostream> #include <string> #include <cstring> using namespace std; TransferWindowManager::SoccerTeam::SoccerTeam() { } TransferWindowManager::SoccerTeam::SoccerTeam(SoccerPlayerData fw, SoccerPlayerData mf, SoccerPlayerData df, SoccerPlayerData gk) { //this point best team's position and sum fee,ablility this->fw = fw; this->mf = mf; this->df = df; this->gk = gk; this->sum_transfer_fee = fw.m_transfer_fee + mf.m_transfer_fee + df.m_transfer_fee + gk.m_transfer_fee; this->sum_ability = fw.m_ability + mf.m_ability + df.m_ability + gk.m_ability; } std::ostream& operator<<(std::ostream& os, const TransferWindowManager::SoccerTeam& team) { // prnt best team os << team.fw << std::endl; os << team.mf << std::endl; os << team.df << std::endl; os << team.gk << std::endl; os << "sum_transfer_fee " << team.sum_transfer_fee << std::endl; os << "sum_ability " << team.sum_ability << std::endl; return os; } TransferWindowManager::TransferWindowManager(std::string file_dir, int budget) { fw_c = 0;//declear count gk_c = 0; mf_c = 0; df_c = 0; m_budget = budget; std::ifstream in(file_dir); //read file std::string line; //get line by string char str_buf[100]; string str_name; string str_position; while (std::getline(in, line)) //read while text is end { strcpy(str_buf, line.c_str()); char * name_ = strtok(str_buf,",");//tok by name char * position_ = strtok(NULL ,","); //position char * pay_ = strtok(NULL, ","); //fee char * abli_ = strtok(NULL, "\t"); //ablility str_name = string(name_); //change name to string str_position = string(position_); //change position to position int int_pay = atoi(pay_); //change char fee int int_abli = atoi(abli_); //change ablility to char SoccerPlayerData * player_data = new SoccerPlayerData(str_name, str_position, int_pay, int_abli);// make player node TreeNode * player = new TreeNode(*player_data, NULL, NULL);//insert if (str_position == " Forward") //if fw { fwBST.insert(*player_data); //insert fw_arr[fw_c].insert_arr(*player_data); fw_c++; } else if (str_position == " Goalkeeper") //if gk { gkBST.insert(*player_data); //insert gk_arr[gk_c].insert_arr(*player_data); gk_c++; } else if (str_position == " Midfielder")//if mf { mfBST.insert(*player_data); //insert mf_arr[mf_c].insert_arr(*player_data); mf_c++; } else if (str_position == " Defender") //if df { dfBST.insert(*player_data); //insert df_arr[df_c].insert_arr(*player_data); df_c++; } } } std::ostream& operator<<(std::ostream& os, const TransferWindowManager& manager)//print all player by position { os << "********Forward List********" << std::endl; os << manager.fwBST;//print bst os << "****************************" << std::endl; os << "********Midflder List********" << std::endl; os << manager.mfBST; os << "*****************************" << std::endl; os << "********Defender List********" << std::endl; os << manager.dfBST; os << "*****************************" << std::endl; os << "********Goalkeeper List********" << std::endl; os << manager.gkBST; os << "*******************************" << std::endl; return os; } const TransferWindowManager::SoccerTeam TransferWindowManager:: getBestTeam() {//make bestteam SoccerTeam best_team;//make team best_team.sum_ability = 0;//reset best_team.sum_transfer_fee = 0; best_team.fw.m_ability = 0; best_team.mf.m_ability = 0; best_team.df.m_ability = 0; best_team.gk.m_ability = 0; for (int z = 0; z < fw_c; z++) //for all fw's player { for (int x = 0; x < mf_c; x++) //for all mf's player { for (int y = 0; y < df_c; y++) //for all df's player { for (int w = 0; w < gk_c; w++) //for all gk's player { if (fw_arr[z].m_root->m_data.m_transfer_fee + mf_arr[x].m_root->m_data.m_transfer_fee + df_arr[y].m_root->m_data.m_transfer_fee + gk_arr[w].m_root->m_data.m_transfer_fee <= m_budget) {// if team's sum fee is rower or same with budget if (best_team.fw.m_ability == 0 && best_team.mf.m_ability == 0 && best_team.df.m_ability == 0 && best_team.gk.m_ability == 0) {//reset best_team.fw = fw_arr[z].m_root->m_data; best_team.mf = mf_arr[x].m_root->m_data; best_team.df = df_arr[y].m_root->m_data; best_team.gk = gk_arr[w].m_root->m_data; best_team.sum_ability = best_team.df.m_ability + best_team.fw.m_ability + best_team.gk.m_ability + best_team.mf.m_ability; } if (best_team.sum_ability <= fw_arr[z].m_root->m_data.m_ability + mf_arr[x].m_root->m_data.m_ability + df_arr[y].m_root->m_data.m_ability + gk_arr[w].m_root->m_data.m_ability) { //if sum abli is rower than team's sum abli if (best_team.sum_ability == fw_arr[z].m_root->m_data.m_ability + mf_arr[x].m_root->m_data.m_ability + df_arr[y].m_root->m_data.m_ability + gk_arr[w].m_root->m_data.m_ability) {//is sum abli and team sum abli is same if (fw_arr[z].m_root->m_data.m_transfer_fee + mf_arr[x].m_root->m_data.m_transfer_fee + df_arr[y].m_root->m_data.m_transfer_fee + gk_arr[w].m_root->m_data.m_transfer_fee < best_team.fw.m_transfer_fee + best_team.df.m_transfer_fee + best_team.mf.m_transfer_fee + best_team.gk.m_transfer_fee) { //sum fee is cheper than best_team best_team.fw = fw_arr[z].m_root->m_data; best_team.mf = mf_arr[x].m_root->m_data; best_team.df = df_arr[y].m_root->m_data; best_team.gk = gk_arr[w].m_root->m_data; best_team.sum_ability = best_team.df.m_ability + best_team.fw.m_ability + best_team.gk.m_ability + best_team.mf.m_ability; //insert data. } } else { // insert data best_team.fw = fw_arr[z].m_root->m_data; best_team.mf = mf_arr[x].m_root->m_data; best_team.df = df_arr[y].m_root->m_data; best_team.gk = gk_arr[w].m_root->m_data; best_team.sum_ability = best_team.df.m_ability + best_team.fw.m_ability + best_team.gk.m_ability + best_team.mf.m_ability; } } } } } } } best_team.sum_transfer_fee = best_team.df.m_transfer_fee + best_team.fw.m_transfer_fee + best_team.gk.m_transfer_fee + best_team.mf.m_transfer_fee; fwBST.deletion(best_team.fw.m_ability);// delete player mfBST.deletion(best_team.mf.m_ability);// delete player dfBST.deletion(best_team.df.m_ability);// delete player gkBST.deletion(best_team.gk.m_ability);// delete player return best_team; //return } #include <iostream> #include <cstdio> #include <algorithm> using namespace std; // 노드 구조체를 정의합니다. struct nodeAVL { int data; struct nodeAVL *left; struct nodeAVL *right; } *root; // 클래스를 정의합니다. class classAVL { public: // 노드의 높이를 반환합니다. int height(nodeAVL *); // 균형인수(높이의 차이)를 반환합니다. int diff(nodeAVL *); // RR 회전 함수입니다. nodeAVL *rr(nodeAVL *); // LL 회전 함수입니다. nodeAVL *ll(nodeAVL *); // LR 회전 함수입니다. nodeAVL *lr(nodeAVL *); // RL 회전 함수입니다. nodeAVL *rl(nodeAVL *); // 트리의 균형을 맞추는 함수입니다. nodeAVL *balance(nodeAVL *); // AVL 트리에 새로운 원소를 삽입합니다. nodeAVL *insert(nodeAVL *, int); // 현재의 AVL 트리 내용을 보여주는 함수입니다. void display(nodeAVL *, int); // AVL 트리를 중위 순회합니다. void inorder(nodeAVL *); // AVL 트리를 전위 순회합니다. void preorder(nodeAVL *); // AVL 트리를 후위 순회합니다. void postorder(nodeAVL *); // classAVL의 생성자입니다. classAVL() { root = NULL; } }; int main(void) { int choice, item; classAVL AVL; while (1) { cout << "\n----------------------------" << endl; cout << " C++로 구현한 AVL 트리" << endl; cout << "----------------------------" << endl; cout << "1. 원소를 삽입할래요." << endl; cout << "2. AVL 트리를 보여주세요." << endl; cout << "3. 중위 순회를 하고싶어요." << endl; cout << "4. 전위 순회를 하고싶어요." << endl; cout << "5. 후위 순회를 하고싶어요." << endl; cout << "6. 프로그램을 종료할래요." << endl; cout << "당신의 선택을 입력하세요 : "; cin >> choice; switch (choice) { case 1: cout << "삽입할 정수를 입력하세요 : "; cin >> item; root = AVL.insert(root, item); case 2: if (root == NULL) { cout << "현재 트리가 비었습니다." << endl; continue; } cout << "[ AVL 트리 출력 ]" << endl; AVL.display(root, 1); break; case 3: cout << "[ 중위 순회 ]" << endl; AVL.inorder(root); cout << endl; break; case 4: cout << "[ 전위 순회 ]" << endl; AVL.preorder(root); cout << endl; break; case 5: cout << "[ 후위 순회 ]" << endl; AVL.postorder(root); cout << endl; break; case 6: exit(1); break; default: cout << "잘못된 입력입니다." << endl; } } return 0; } // AVL 트리의 높이를 출력합니다. int classAVL::height(nodeAVL* temp) { int h = 0; if (temp != NULL) { // 재귀적으로 왼쪽 혹은 오른쪽으로 검색합니다. int left = height(temp->left); int right = height(temp->right); int maxHeight = max(left, right); h = maxHeight + 1; } return h; } // 균형인수(높이의 차이)를 반환합니다. int classAVL::diff(nodeAVL* temp) { // 왼쪽 자식의 높이와 오른쪽 자식의 높이 차이를 반환합니다. int left = height(temp->left); int right = height(temp->right); int factor = left - right; return factor; } // RR 회전 함수입니다. nodeAVL *classAVL::rr(nodeAVL* parent) { // 말이 회전이지 그냥 부모 노드의 오른쪽 자식노드와 데이터를 교환하는 것입니다. nodeAVL *temp; temp = parent->right; parent->right = temp->left; temp->left = parent; return temp; } // ll 회전 함수입니다. nodeAVL *classAVL::ll(nodeAVL* parent) { // RR 회전과 반대입니다. nodeAVL *temp; temp = parent->left; parent->left = temp->right; temp->right = parent; return temp; } // LR 회전 함수입니다. nodeAVL *classAVL::lr(nodeAVL* parent) { // LR 회전은 왼쪽 자식을 기준으로 RR, 본인을 기준으로 LL회전합니다. nodeAVL * temp; temp = parent->left; parent->left = rr(temp); return ll(parent); } // RL 회전 함수입니다. nodeAVL *classAVL::rl(nodeAVL* parent) { // LR 회전과 반대입니다. nodeAVL * temp; temp = parent->right; parent->right = ll(temp); return rr(parent); } // AVL 트리의 균형을 맞추는 함수입니다. nodeAVL *classAVL::balance(nodeAVL *temp) { int factor = diff(temp); // 왼쪽 서브트리쪽으로 삽입이 되어 균형이 깨진 경우입니다. if (factor > 1) { // 그 왼쪽 자식노드에 문제가 발생했습니다. if (diff(temp->left) > 0) { temp = ll(temp); } // 그 오른쪽 자식 노드에 문제가 발생했습니다. else { temp = lr(temp); } } else if (factor < -1) { if (diff(temp->right) > 0) { temp = rl(temp); } else { temp = rr(temp); } } return temp; } // 트리에 원소를 삽입하는 함수입니다. nodeAVL * classAVL::insert(nodeAVL *root, int value) { // 현재 트리가 비었을 때 if (root == NULL) { root = new nodeAVL; root->data = value; root->left = NULL; root->right = NULL; return root; } else if (value < root->data) { root->left = insert(root->left, value); root = balance(root); } // 크거나 같은 경우 오른쪽 서브트리에 삽입합니다. else if (value >= root->data) { root->right = insert(root->right, value); root = balance(root); } return root; } void classAVL::display(nodeAVL * ptr, int level) { int i; // 현재 트리가 비어있지 않은 경우입니다. if (ptr != NULL) { display(ptr->right, level + 1); printf("\n"); // 현재 루트 노드인 경우입니다. if (ptr == root) { cout << "Root -> "; } // i가 현레벨보다 낮고 루트가 아닌 경우일 때까지 입니다. for (i = 0; i < level && ptr != root; i++) { cout << " "; } // 자신의 위치에 데이터를 출력합니다. cout << ptr->data; // 왼쪽 노드도 출력해줍니다. display(ptr->left, level + 1); } } /* 트리를 순회하는 세 가지 함수입니다. */ void classAVL::inorder(nodeAVL *tree) { if (tree == NULL) return; inorder(tree->left); cout << tree->data << " "; inorder(tree->right); } void classAVL::preorder(nodeAVL *tree) { if (tree == NULL) return; cout << tree->data << " "; inorder(tree->left); inorder(tree->right); } void classAVL::postorder(nodeAVL *tree) { if (tree == NULL) return; inorder(tree->left); inorder(tree->right); cout << tree->data << " "; }<file_sep> # 2048 MFC ## Introduction 2048 게임은 16개의 사각 블록으로 구성된 4x4 보드에서 하는 퍼즐 게임이다. 이 게임의 목표는 2의 블록을 움직여 2048을 만드는 것이다. 게임을 하는 동안 블록을 움직일 수 없을 때 게임은 끝난다. 이 프로젝트의 목표는 두가지로 MFC를 이용한 디스플레이 4x4 보드는 16개의 블록을 가진 모델 다이어그램을 사용하는 것이 하나이고 키보드와 마우스 입력에 따라 4x4 보드를 조작하여 2048 게임인 프로그램을 작성하는 것이 나머지 하나이다. 세부 메뉴 선택에 따라 프로그램은 보드위에 숫자나 숫자, 색상을 표현할 수 있어야 하며 키보드와 마우스 입력을 기록하는 로그 파일을 생성할 수 있어야 한다. 프로그램을 시작할 때 보드의 임의의 위치에 2번 블록이 생성되고 게임이 시작된다. 플레이어는 마우스나 키보드를 사용하여 보드를 회전하거나 블록을 이동할 수 있으며 프로그램은 플레이어가 수행한 마우스나 키보드 작동 기록을 로그 파일로 저장할 수 있다. 플레이어의 선택에 따라 프로그램은 번호나 색상을 보드에 표시할 수 있다. 키보드 입력에 의한 보드의 움직임은 위, 아래, 좌, 우 4가지 방향에 따라 보드의 블록을 이동시켜 게임을 실행할 수 있다. 키보드 input에 따르면 게임에 사용되는 블록은 해당 방향의 가장자리에 위치한 빈 블록으로 이동한다. 블록의 이동이 완료되면 빈 블록 중 하나에서 숫자 2가 생성된다. 보드는 16개의 블록으로 구성되어 있으며 각 블록에는 1개의 번호가 있다. 한 블록은 위, 아래, 왼쪽, 오른쪽으로 표시할 수 있는 4개의 포인터가 있다. 4x4 보드로 구성된 16개 블록의 다이어그램의 Block_Header는 왼쪽 상부 블록을 가리킨다. 각 블록은 4개의 포인터를 사용하여 각 블록을 기준으로 위, 아래, 왼쪽, 오른쪽으로 위치한 블록을 가리킨다. 포인터가 NULL값을 가진 포인터를 가리키는 위치에 블록이 없는 경우 혹은 블록에 값이 없으면 블록 값이 0으로 설정된다. <file_sep>#pragma once class MyBlock { private: int m_number, m_x, m_y;//declare MyBlock* m_pup;//declare MyBlock* m_pDown;//declare MyBlock* m_pLeft;//declare MyBlock* m_pRight;//declare public: MyBlock();//declare MyBlock(int num, int x, int y);//declare ~MyBlock();//declare void SetLeft(MyBlock *Left);//set void SetRight(MyBlock* Right);//set void SetUp(MyBlock* Up);//set void SetDown(MyBlock* Down);//set void SetNum(int num);//set void Set_x(int x);//set void Set_y(int y);//set MyBlock* GetLeft();//get MyBlock* GetRight();//get MyBlock* GetUp();//get MyBlock* GetDown();//get int GetNum();//get int Get_x();//get int Get_y();//get }; class MyBoard { private: MyBlock* m_pHead;//declare public: MyBoard(); ~MyBoard(); bool up();//declare int up(MyBlock* node);//declare bool down();//declare int down(MyBlock* node);//declare bool left();//declare int left(MyBlock * node);//declare bool right();//declare int right(MyBlock* node);//declare void print_board();//declare void make_board(MyBlock * node);//declare void connect();//declare bool putnum();//declare bool copy(MyBoard board,MyBoard temp_board);//declare bool check(MyBoard board, MyBoard temp_board);//declare bool win();//declare }; <file_sep>#pragma once #include "BSTNode.h" class Queue { private: BSTNode* Head;//set int size;//set public: Queue(); ~Queue(); bool IsEmpty();//set bool Push(BSTNode* Node);//set void Pop();//set BSTNode* Front();//set void Inorder(BSTNode* now);//set void Postorder(BSTNode* now);//set void Preorder(BSTNode* now);//set };<file_sep>#include <iostream> using namespace std; char map[2500][2500];//declare int space(int num, int num1, int count) { count++;//count if (num1 /3 == num)//if num1/3 is num mean num is 3, no more get small return 0; else {//else if (count==1) {// if function is first for (int a = 0; a < num; a++) { for (int b = 0; b < num; b++) { if (a % 3 == 1 && b % 3 == 1) {//make hole that 3x3 map[a][b] = ' '; } } } } else {//upto second func for (int a = 0; a < num; a++) { for (int b = 0; b < num; b++) { if (a > num1 / 3 - 1 && b > num1 / 3 - 1 && a < num1 - num1 / 3 && b < num1 - num1 / 3) {//make hole in the middle, range to range map[a][b] = ' '; } else {//make nxn map[a][b] = map[a % num1][b % num1]; } } } } space(num, num1 * 3,count); // call recursion func } } int main() { int n = 0;//declare cout << "Enter the power of 3:";//print cin >> n;//input n num for (int a = 0; a < n; a++) { for (int b = 0; b < n; b++) {//make map which all the map is $ map[a][b] = '$'; } } space(n,3,0);//make hole for (int a = 0; a < n; a++) { for (int b = 0; b < n; b++) {//print map cout << map[a][b]; } cout << endl; } }<file_sep>#include <iostream> #include <vector> #include <string> using namespace std; int N = 0; unsigned int cnt = 0; vector <char> v; void input_bit(); void func_g(); void input_N()//get input { cout << "Input N:"; cin >> N; input_bit();//get bit input } void input_bit() {//get bit input string bit; cout << "Input Bitstream:"; cin >> bit; int bitsize = bit.size(); for (int a = 0; a < bitsize; a++) {//input the bit v.push_back(bit.back()); bit.pop_back(); } func_g();//reverse } void func_f() {//reversal for (vector<int>::size_type a = 0; a < v.size(); a++) {//for 0 to maxbit if (v[a] == '0') {//if 0 change to 1 v[a] = '1'; } else if(v[a] == '1') {//if 1 change to 0 v[a] = '0'; } } } void func_g() {//reverse the bit int c, i, j; for (i = 0, j = v.size() - 1; i < j; i++, j--) { c = v[i];//c is temp v[i] = v[j]; //swap v[j] = c;//relocation } } void add_bit(int a) { if (a % 2 == 0) {// if a is even v.push_back('0'); //add 0 } else if (a == 1 || a % 2 == 1) {//if a is odd num v.push_back('1');//add 1 } } void count() {//demical num cnt = 0; vector<int>::size_type num = 0; int mul = 1; while (num <v.size()) { if (num == 33) break; if (v[v.size()-1-num] == '1') {//if bit is 1 cnt += mul; //add } mul *= 2;//squared num num++; } } int main() { input_N();//get input string output; for (int a = 1; a <= N; a++) { func_g();//reverse func g func_f();// reversal func func f add_bit(a);//add bit 1 cout << a << ": "; for (vector<int>::size_type b = 0; b < v.size(); b++) {//print bit cout << v[b]; } cout << endl; count(); cout << cnt;//print demical num cout << endl; } }<file_sep>#include <iostream> #include "TransferWindowManager.h" using namespace std; int main(int argc, char** argv) { TransferWindowManager transfer_window_manager(argv[1], atoi(argv[2]));//read argv[1](text) set budget(argv[2]) insert player's by position cout << transfer_window_manager << endl; //and print TransferWindowManager::SoccerTeam team = transfer_window_manager.getBestTeam(); // make best team cout << "Best Players" << endl; cout << team << endl; //print best team and delete best team cout << "-----" << endl; cout << "The Transfer window close" << endl; cout << transfer_window_manager << endl; // print all team return 0; } <file_sep># Assignment 1-1 1번 문제는 도형에 관한 별 찍기($) 프로그램이다. 사용자로부터 입력을 받고(입력은 3의 거듭제 곱으로 1부터 7까지 입력이 가능하다.) 프로그램의 문자는 ‘$’ 사용하여 출력한다. 형태는 3의 1승의 정사각형 모양으로 중간은 구멍이 있는 형태이다. 1 부터 입력 받은 숫자 까지 반복하여 출력하는 형태인데 그 크기가 커질수록 이전에 승수의 모양을 합쳐서 만든 모습이다. 중간은 예외없이 항상 구멍이 뚫려 있다 # Assignment 1-2 2번 문제는 에라토스테네스의 체를 이용하여 모든 소수를 찾는 프로그램을 구현하는 것이다. 사 용자로부터 인풋을 받아 2부터 인풋 사이에 있는 모든 소수를 찾는다. 1은 소수가 아니므로 제외 한다. 이 문제는 5단계의 스텝이 존재한다. 1. N 이하의 모든 소수를 찾으려면 2에서 N사이의 모든 정수를 먼저 만든다. 2. 가장 작은 소수 즉 p=2부터 시작한다. 3. N보다 작은 p의 모든 배수를 표시한다. 4. P의 배수 계산이 끝났으면 그 다음 소수의 배수를 계산한다. 5. P<=루트n까지 반복한다. # Assignment 1-3 3번 문제는 사용자로부터 bit stream을 input으로 받는다. 그 후 다음과 같은 함수를 거치게 된다. S0=사용자로부터 받은 bit stream Sn = f(g(Sn-1))+1 → n is odd = f(g(Sn-1))+0 → n is even 식을 설명하자면 bit를 먼저 1011→1101와 같이 MSB와 LSB기준으로 자리를 바꿔주는 것이 G함 수이다. g함수를 거치고 1011 → 0100과 같이 0은 1로 1은 0으로 값을 반전시켜주는 것이 f함수이 다. 그 후 만약 n이 홀수 일 경우 1을 맨 처음 bit에 넣어 bit수를 늘려주고 짝수일 경우 0을 넣 어준다. 마지막으로 단계가 끝나는 시점의 bit를 10진수로 표현한다. 여기서 만약 overflow가 일어 나게 되면 제일 큰 숫자를 출력한다. # Assignment 1-4 4번 문제는 input으로 받은 문자열을 소문자 혹은 대문자를 대문자 혹은 소문자로 변환하고 앞뒤 의 위치를 바꿔주는 프로그램이다. 여기서 C과 C++의 표준 라이브러리 함수를 사용하지 않고 즉 문자열 유형의 함수를 사용하지 않고 프로그램을 진행한다. # Assignment 1-5 5번의 문제는 사용자로부터 행렬을 입력 받고 그 크기에 해당하는 Matrix판을 만들어 random한 숫자들로 채운다. 이 숫자들은 중복이 되지 않고 값이 0부터 Matrix의 크기 보다 1작은 수만큼 값이 채워져야 한다. 입력 받은 행은 1보다 같거나 커야 하고 열은 100보다 같거나 작아야 한다. 그리고 행과 열을 바꿔서 출력한다. # Assignment 1-6 6번 문제는 C++언어를 이용하여 tic-tac-toe게임을 구현하는 것이다. 이 게임은 두 사람이서 번갈 아 가며 3x3 표에 O와 X를 표시하여 가로, 세로, 대각선으로 동일한 모양이 나오게 되면 해당하 는 player는 승리를 하는 프로그램이다. 만약 판이 꽉 찼는 경우에도 승자가 나오지 않게 되면 Draw를 출력해준다. # Assignment 1-7 2차원 데카르트 좌표에 3개의 점(P1,P2,P3)를 사용자로부터 입력 받아 P1→P2→P3으로 가는 방향 을 시계, 반시계, 직선으로 나눠 출력하는 프로그램이다. P1,P2,P3를 연결하는 선은 겹치지 않는다 만약 두 벡터 u = (m1,m2,m3) v =(n1,n2,n3)이 있다고 했을 때 u X v = (m2n3-m3n2,m3n1- m1n3,m1n2-m2n1)이다. 이렇게 두 벡터의 외적을 구하고 m3과 n3이 0인 것을 고려하여 다음 식 을 얻을 수 있다. u X v = (0,0, m1n2-m2n1) 이로서 m1n2 – m2n1의 부호에 따라서 점 P1,P2,P3의 방향을 구할 수 있다. 오른손 법칙에 의하여 D = m1n2 -m2n1가 D>0 반시계 방향, D = 0 직선, D<0 시계 방향을 구하였다. # Assignment 1-8 8번 문제는 시저 암호를 이용하여 주어진 txt를 해독하는 프로그램이다. 일반 텍스트의 각 문자가 특정 숫자만큼 shift되는 암호 유형이다. 예를 들어 A를 3만큼 shift한다 면 A, B, C, D 즉 A에서부터 오른쪽에 3번째에 있는 알파벳인 D가 출력이 된다. 엘리스는 텍스트 에 16진수로 저장된 시저 암호를 사용하여 Bob에게 암호를 보냈지만 아스키 문자로 변환하여 시 저 암호를 통해 일반 텍스트를 찾아야한다. 하지만 엘리스는 shift되는 수를 알려주지 않았기 때 문에 0부터 127까지 모두 shift하면서 엘리스의 평문을 얻는 프로그램이다. # Assignment 1-9 9번 문제는 전화 요금제에서 월별 전화 요금을 계산하는 프로그램이다. 표에 표시된 것처럼 월 기본 요금, 기본 제공 문자, 기본제공 음성통화, 추가 요금이 다른 4가지 유형의 요금제가 있을 경우 사용자로부터 요금제 유형, 사용한 문자 량, 통화한 음성통화 시간을 입력 받아 기본요금과 지불해야하는 추가 요금의 총을 구하는 프로그램이다. # Assignment 1-10 10번은 Hit & blow 라는 게임을 구현하는 것이다. 게임이 시작되면 프로그램은 겹치지 않고 0에 서 9사이의 4개의 난수를 설정한다. 이때 이 숫자는 표시되지 않는다. 그 후 매 턴마다 숫자를 추 측하고 입력할 때마다 힌트가 표시된다. 난수와 입력한 숫자가 같은 위치에 같은 숫자가 있다면 Hit을 표시하고 같은 숫자지만 다른 위치에 있다면 blow를 표시한다. 기회는 10번이며 그 안에 정확한 숫자를 입력하면 Win을 출력한다. # Assignment 2-1 2-1은 주어진 파일(source.txt)를 사용하여 각 줄을 input으로 넣어 사용자로 하여금 각 줄을 print 하는 프로그램을 작성하는 것이다. 이때 프로그램에 입력할 때 정확도와 속도를 표시해야 한다. 속도: 모든 문자/경과 시간 프로그램에 문자를 입력하면 시간 측정이 시작되고 ENTER를 입력하면 종료된다. 종료됨과 동시 에 새로운 시간 측정이 시작된다. 결과는 result.txt에 저장한다. 정확도: 올바른 문자/원문 길이 화면은 문자를 입력하고 초기화 되며 그 후 이전 입력 확인 결과를 인쇄한다. 처음에는 정확도가 0이고 속도도 0이다. 역시 결과는 result.txt에 저장한다. 입력 받을 text와 입력할 text를 연다. 한 문장을 읽으면 바로 사용자로 입력을 받는데 사용자가 입력을 시작할 때 측정하는 방법을 찾다가 키보드로부터 입력이 있으면 반응하는 함수를 찾았다. 이부분이 제일 고민이 였던 부분이다. 그리고 time을 cin함수 위 아래로 시작과 끝을 정해 시간을 측정하였다. 그리고 system함수로 화면 초기화를 하였다. 문장은 공백까지 포함하기 위하여 cin.getline을 이용하였고 문장의 char 수를 count 해주는 함수를 따로 빼고 원문과 비교하는 함수 도 따로 밖으로 빼서 사용하였다. # Assignment 2-2 2-2문제는 포인터 변수를 사용하여 다른 변수의 주소를 나타내고 주어진 양식 대로 출력하는 프 로그램이다. 조건은 1부터 6까지 값을 가진 2x3배열이있다. 변수는 a,b,c,d,e,f,g,h,i,j가 존재한다. 1) a,b,c,d,h,i,j를 순서대로 값을 출력한다. 2) 포인터를 사용하여 1~6값을 가리키는 변수의 주소를 인쇄한다. 3) 포인터 e, f, g의 값을 순서대로 출력한다. 1번 조건인 a,b,c,d,h,I,j를 출력 한 결과 값이다. A는 1을 가리키고 있고 i와 h는 1을 가리키고 있 는 a를 가리키고 있다. C는 2, d는 3, b는 4를 가리키고 있으며 j는 c를 가리키고 있는 것을 알 수 있다. 2번 조건은 각 숫자들에 대한 주소 값들을 출력하는 조건이다. 3번은 e,f,g 즉 값이 하나가 아닌 3개 6개를 출력하는 것을 확인 하였다. # Assignment 2-3 2-3번 문제는 사용자로부터 x와 y의 값을 입력 받아 2차원 배열을 생성하고 시계방향으로 소용돌 이 모양으로 숫자가 증가되는 꼴의 배열을 출력한다. # Assignment 2-4 2-4문제는 strstr함수의 기능을 구현하는 것이다. strstr함수는 strSearch로 표시된 문자열이 포인터 변수 str로 표시된 문자열에 포함이 됐는지 찾는 것이다. 그러나 이번의 문제는 예를 들어, str은 oh sad day! 이고 strSearch는 sad, strChange는 happy라고 가정했을 때 str은 Oh happy day! 되는 것이다. 즉 str은 원문이고 strSearch는 찾는 문자, strChange는 교체할 문자라고 정의할 수 있다. 각각의 크기는 100이고 string에 관련된 함수는 일체 쓰지 않는 조건으로 프로그램을 작성한다. 또한 찾는 문자가 없는 NULL일 경우도 고려해준다. 원본 문자열을 입력 받는다. 변경 전 문자열은 sad가 되고 변경 후 문자열은 Happy가 된다. 그리 고 sad자리에 변경된 문자열인 Happy가 자리하고 있는 것을 확인하였다. 변경 전 문자열이 aaa로 원본 문자열에 존재하지 않는 경우 즉 NULL경우도 고려해준 모습이다. # Assignment 2-5 2-5번 문제는 환자 정보의 클래스를 구현하는 프로그램이다. 환자의 개인 정보를 저장하는 PatientInfo class를 구현한다. class에는 환자의 이름, 주소, 등록번호, 전화번호를 저장하는 private 변수가 있다. 화면에 4명의 데이터를 입력 받고 모든 변수 값을 출력하는 프로그램을 만든다. 환자의 정보를 담을 class를 선언해준다. Private 부분에 변수들을 선언하고 public엔 함수들을 선 언하였다. get과 set의 함수들이다. Class의 생성자 부분을 초기화 해주고 main에서 4명의 환자를 만들고 값을 입력 받는다. 입력을 받는 것과 동시에 set함수로 값들을 넣어준다. 4명 환자들의 정 보를 모두 넣어 줬으면 get함수로 출력을 해준다. # Assignment 2-6 369 게임 프로그램 class로 작성하는 프로그램이다. 규칙은 다음과 같다. 1. Class 이름은 ThreeSixNine이다. 2. Value는 1부터 300까지 들어 갈 수있다. 3. 3, 6, 9가 들어가면 !를 출력하고 아닌 경우에는 숫자를 출력한다. 4. 10개마다 라인 교체를 한다 main함수는 주어진 상태이고 class 이름은 ThreeSixNine으로 하였다. 수행할 print369의 함수는 1 부터 사용자의 입력까지 이중의 for문을 돌면서 369의 여부를 판단해준다. 숫자를 char로 바꿔주 면서 3,6,9와 같을 때 카운트가 올라가고 올라간 카운트만큼 “!!”를 출력하게 된다. 문제의 예시처 럼 10단위로 줄을 바꾸어 주었다. # Assignment 2-7 두개의 클래스 Pharmacist, Buyer를 작성하고 마스크를 구입하는 프로그램을 만든다. 사용자와 대화 형식으로 프로그램이 진행이 되고 메뉴는 다음과 같다. 0. 프로그램 종료 1. 마스크 재고 물어보기 2. 마스크 가격 물어보기 3. 마스크 구매하기 4. 내 마스크 개수 확인하기 5. 내 지갑 확인하기 사용자로부터 0을 입력 받으면 그대로 프로그램은 종료된다. 1,2,4,5번을 입력 받으면 클래스로부 터 각각의 값을 가져와 인쇄해준다. 3번을 입력 받으면 다시 한번 구매할 마스크의 수량을 묻고 입력을 받는다. 만약 사용자의 돈이나 마스크의 재고가 부족하다면 에러 매세지를 출력한다. 혹은 마스크의 재고가 부족하고 돈이 부족 할 시 그에 맞는 에러 매세지를 출력한다. 1을 입력하여 마스크 개수를 확인하고 2를 입력하여 마스크의 가격, 4를 입력하여 나의 마스크 개수를 확인하고 5를 눌러 나의 잔액을 확인한다. 3을 입력하여 마스크 구매하고 구매할 수량을 입력한다. 1을 눌러 마스크의 재고가 바뀐 것을 확인하고 4를 입력하여 나의 마스크 개수가 2개 된 것을 확인한다. 마지막으로 나의 잔액이 바뀐 것을 확인하고 0을 눌러 프로그램을 종료한다. 계속 하여 나올 메뉴판은 따로 함수로 빼서 사용했다. 구매자와 판매자의 class를 만들고 반복문 을 돌면서 프로그램이 진행된다. 조건문으로 사용자의 입력이 0일 때 프로그램 종료, 1,2,4,5일 때 class로부터 값을 가져와 출력을 해주었다. 만약 사용자가 3을 입력하여 마스크를 구매 할 시 구 매할 마스크의 수량을 다시 입력 받아 에러매세지 출력 여부를 판단해주고 에러가 아닐 시 구매 할 마스크 만큼 재고와 지갑의 돈을 업데이트 해주었다. # Assignment 2-8 Class와 상속을 사용하여 입력된 문자열로 환율을 계산하는 프로그램을 작성한다. 환율은 다음과 같다. KRW:USD = 1200: 1 KRW:JPY = 1100:100 KRW:EUR = 1300:1 KRW:CNY = 170:1 사용자로부터 받는 input의 양식은 [가격] 환전받을 나라 to 환전 후 나라가 된다. 클래스는 총 6개가 존재하고 Exchange 클래스는 슈퍼 클래스가 되고 다른 클래스들은 하위 클래 스들이다. 교환된 값은 소수점 첫째 자리에서 반올림한다. 각 나라마다 class를 만들고 슈퍼 클래스인 exchange class도 만들었다. 반복문을 돌면서 사용자의 대답이 Y이거나 y일 때 진행했다. 사용자로부터 환전할 돈과 나라들의 이름을 잘라 값들을 비교해주었다. 환전 전의 나라를 비교하여 일치하는 클래스의 함수로 들어가 환전 후의 나라와 환율을 계산하여 환전 후의 돈을 출력하는 식으로 진행하였다. 만약 n이 입력 으로 들어가면 프로그램을 종료한다. cin으로 값을 입력 받을 때 cin을 비워줘야 다음 환율을 계산 하는데 cin이 비워지지 않아서 애를 먹었다. 결국 cin.ignore()함수를 사용하여 문제를 해결 하였다. # Assignment 3-1 Linked list를 이용하여 카페 메뉴를 관리하는 프로그램을 구현한다. 프로그램은 카페 메 뉴 정보를 저장하고 카테고리 별로 메뉴를 저장하는 ‘input.txt’에서 읽으며 카테고리가 저장된다. 카테고리 노드, 메뉴 및 가격이 메뉴 노드에 저장된다. 이 프로그램은 LOAD, PRINT, INSERT, SEARCH, DELETE의 기능을 수행한다. 삽입은 가격을 기준으로 오름 차순으로 정렬이 된다. 만약 같다면 알파벳 순서대로 삽입한다. 이때 대문자와 소문자는 구별하지 않고 입력 값의 변수가 부족하면 저장되지 않고 에러 메시지를 출력한다. 노드 자체의 속성을 변경하는 것이 아닌 노드 자체를 변경해야 한다. 사용자가 입력할 수 있는 번호판을 먼저 만든다. 1번이 입력되면 텍스트 파일을 읽어와 탭을 기준 으로 잘라 하나의 노드에 정보를 저장한다. 입력이 되지 않은 정보가 있는지 확인하고 있다면 에 러를 출력하고 없다면 삽입을 진행한다. 2를 선택하면 모든 노드를 출력하게 한다. 3을 입력하면 수동으로 메뉴를 추가할 수 있다. 4를 입력하면 검색하는 기능으로 카테고리를 찾아 카테고리에 맞는 데이터들을 출력해준다. 5를 입력하면 찾고 싶은 메뉴를 찾게 해준다. 6은 삭제를 해주는 함 수로 입력을 받고 그에 맞는 정보를 삭제 후 다시 연결해준다. 7을 입력하면 프로그램을 종료한다. 1번은 single linked list로 처음 head로 이뤄진다. 옆에는 각 카테고리마다 연결 리스트가 존재하 며 각 리스트의 첫번째는 연결이 되어있다. 이번 프로젝트에서 비교적 쉬운 편에 속하였다 # Assignment 3-2 Circular Doubly Linked list를 사용하여 강의 목록 관리 프로그램을 작성 및 관리한다. 관리되는 강 의의 특성은 강의의 이름, 교수 및 학년이며 이 프로그램의 관리 기능은 다음과 같다. ✓ Insert lecture at beginning ✓ Insert lecture at last ✓ Insert lecture at position ✓ Delete lecture ✓ Update lecture ✓ Search lecture ✓ Search professor ✓ Search grade ✓ Sort by grade in ascending order ✓ Display lecture list ✓ Reverse lecture list 강의 관리 프로그램은 클라스를 기반으로 구현한다. 또한 같은 등급의 강의가 있으면 이름 별로 정렬하고 중복 강의는 없다고 한다. 종료 기능 할때까지 메뉴는 반복적으로 인쇄되며 노드의 속 성 값이 아닌 노드 자체를 변경해야한다. 함수 3 즉 포지션 별로 삽입을 수행할 땐 다시 입력하 도록 예외 처리를 한다. Circular Doubly Linked list를 사용하여 전체적인 프로그램을 구현하였다. 1번을 입력 받으면 맨 처 음에 입력을 한다. 즉 head가 되게 구현해준다. 2번을 입력하면 맨 마지막에 입력하는 것으로 tail 이 되게 해준다. 3번을 입력하면 원하는 포지션에 넣을 수 있는데 만약 전체 포지션의 범위를 벗 어나면 에러를 출력해준다. 만약 tail의 다음인 tail+1에 추가할 수 있도록 해주었다. 4를 입력하면 리스트를 돌며 원하는 강의를 지우고 5를 입력하면 강의를 업데이트한다. 6을 입력하면 강의를 검 색하고 7은 강의 중 교수님이 맡은 강의는 전부 출력해준다. 8은 검색할 학년이 있는 강의를 전부 출력해주고 10번은 전체 강의를 출력해준다. 9번은 오름차순으로 정렬하는 것인데 만약 학년이 같다면 강의의 이름의 크기를 비교하여 오름차순으로 정렬해준다. 11번은 역으로 노드를 바꾸는 것인데 속성을 바꾸는 것이 아니고 노드 자체를 움직였다. 맨 마지막 노드와 그 앞의 노드의 연 결을 끊고 끊은 노드를 기준으로 맨 뒤에 삽입하게 하고 다시 연결해 주었다. # Assignment 3-3 먼저 크기와 숫자를 입력하고 숫자 순서대로 BST를 구현한다. 큐를 사용하여 BST의 inorder, postorder, preorder를 출력한다. 큐에는 push, pop, front 및 isEmpty 함수가 포함되어야 하며 큐는 라이브러리가 아닌 구현해야한다. 겹치는 숫자는 없다고 가정하며 모든 숫자를 양의 정수로만 입 력한다. 사용자로부터 입력할 숫자의 개수와 숫자를 입력 받은 후 출력의 방식을 선택하여 각각 맞는 출 력을 해주었다. 큐를 직접 구현해야 하는 것이 번거로웠다. BST를 구현하는 과제로 데이터구조때 배웠던 것을 생각하여 구현하였다. 또한 큐와 각 순회를 출 력하는 것 또한 이전에 배운 것을 토대로 구현하였다. # Assignment 3-5 2048게임은 4*4의 판을 기준으로 진행되며 16개의 블록으로 구성된 보드에서 실행된다. 한 블록 에서는 숫자 값과 좌표 값이 있다. 2048게임은 MyBlock 클래스와 Myboard 클래스를 사용하여 구현되며 Mybolck의 첫 번째 멤버 변수는 각 블록의 숫자값을 나타내는 변수이고 두번 째 및 세번쨰 멤버 변수는 x,y 좌표 값을 저 장하는 변수다. Myblock 클래스는 4개의 Myblock 포인터가 있고 각 블록의 위 아래 왼쪽 및 오 른쪽이 블록에 대한 포인터이다. Head는 0,0으로 사용자의 입력에 따라 작동하는 up, down, left, right의 네 가지 멤버 함수가 있다. 프로그램이 실행되면 보드가 생성이 되고 각 블록의 좌표값이 초기화 된다. 각 블록의 숫자는 각 객체의 멤버 변수에서 임의로 생성 및 초기화된다. 게임의 룰은 각 턴이 시작되기 전에 임의의 위치에서 빈 블록에 숫자 2를 생성한다. 동작을 사용 자로부터 입력받고 입력에 따라 함수가 실행된다. 각 기능에서 모든 블록은 입력 방향의 끝에 있 는 블록으로 이동된다. 만약 동일한 값을 가진 두 블록이 만나면 수는 합쳐진다. 빈 블록이 없고 더 이상 블록을 추가할 수 없는 경우 게임은 진다. 2048을 만들면 win을 출력하고 프로그램을 종 료한다. <file_sep>#include <iostream> using namespace std; #pragma once class PatientInfo { private: char* name = nullptr;//declare private char* address = nullptr; int registration_number = 0; int phone_number = 0; public: PatientInfo(char* name, char* address, int registration_number, int phone_number); ~PatientInfo();//declare public char* getName();//get func char* getAddress(); int get_R_Number(); int get_P_Number(); void SetName(char* n);//set func void SetAddress(char* a); void Set_R_Number(int r); void Set_P_Number(int p); }; PatientInfo::PatientInfo(char* name, char* address, int registration_number, int phone_number) { name = new char[50];//patientInfo address = new char[50]; registration_number = 0; phone_number = 0; } PatientInfo::~PatientInfo() { } char* PatientInfo::getName() { return name;//get name } char* PatientInfo::getAddress() { return address; } int PatientInfo::get_R_Number() { return registration_number; } int PatientInfo::get_P_Number() { return phone_number; } void PatientInfo::SetName(char* n) { name = n; } void PatientInfo::SetAddress(char* a) { address = a; } void PatientInfo::Set_R_Number(int r) { registration_number = r; } void PatientInfo::Set_P_Number(int p) { phone_number = p; } int main() { char* n = new char[50];//declare char* a = new char[50]; int r = 0; int p = 0; char* n1 = new char[50]; char* a1 = new char[50]; int r1 = 0; int p1 = 0; char* n2 = new char[50]; char* a2 = new char[50]; int r2 = 0; int p2 = 0; char* n3 = new char[50]; char* a3 = new char[50]; int r3 = 0; int p3 = 0; PatientInfo Info = PatientInfo(n, a, r, p);//declare infos PatientInfo Info1 = PatientInfo(n1, a1, r1, p1); PatientInfo Info2 = PatientInfo(n2, a2, r2, p2); PatientInfo Info3 = PatientInfo(n3, a3, r3, p3); cout << "NAME: ";//get name cin >> n; Info.SetName(n);//set name cout << "Address: ";//get address cin >> a; Info.SetAddress(a);//set address cout << "Registration Number: ";//get R_num cin >> r; Info.Set_R_Number(r);//set R_NUM cout << "Phone Number: ";//get phone num cin >> p; Info.Set_P_Number(p);//set phone num cout << endl; cout << "NAME: "; cin >> n1; Info1.SetName(n1); cout << "Address: "; cin >> a1; Info1.SetAddress(a1); cout << "Registration Number: "; cin >> r1; Info1.Set_R_Number(r1); cout << "Phone Number: "; cin >> p1; Info1.Set_P_Number(p1); cout << endl; cout << "NAME: "; cin >> n2; Info2.SetName(n2); cout << "Address: "; cin >> a2; Info2.SetAddress(a2); cout << "Registration Number: "; cin >> r2; Info2.Set_R_Number(r2); cout << "Phone Number: "; cin >> p2; Info2.Set_P_Number(p2); cout << endl; cout << "NAME: "; cin >> n3; Info3.SetName(n3); cout << "Address: "; cin >> a3; Info3.SetAddress(a3); cout << "Registration Number: "; cin >> r3; Info3.Set_R_Number(r3); cout << "Phone Number: "; cin >> p3; Info3.Set_P_Number(p3); cout << endl; cout << Info.getName() << endl;//print name cout << Info.getAddress() << endl;//print address cout << Info.get_R_Number() << endl;//print R_num cout << Info.get_P_Number() << endl;//print phone num cout << endl; cout << Info1.getName() << endl; cout << Info1.getAddress() << endl; cout << Info1.get_R_Number() << endl; cout << Info1.get_P_Number() << endl; cout << endl; cout << Info2.getName() << endl; cout << Info2.getAddress() << endl; cout << Info2.get_R_Number() << endl; cout << Info2.get_P_Number() << endl; cout << endl; cout << Info3.getName() << endl; cout << Info3.getAddress() << endl; cout << Info3.get_R_Number() << endl; cout << Info3.get_P_Number() << endl; cout << endl; return 0; }<file_sep> ## Project_01 ### 축구 구단 관리 프로그램 ## Project_02 ### 여행 일정 관리 프로그램 ## Project_03 ### 섬 그래프를 이용하여 최단 경로 찾기 프로그램 <file_sep># 여행 일정 관리 프로그램 ## 1. Instroduction 이번 프로젝트는 여행 일정 관리 시스템으로 사용자가 등록한 지역 및 도시 정보를 이용하여 도시간의 이동 거리가 최소가 되도록 여행 일정을 설계 해주는 프로젝트이다. 본 프로젝트는 지정된 자료구조와 그래프를 활용하여 여행 일정 관리 시스템을 구축한다. 도 시 정보는 도시의 이름을 기준으로 하여 AVL tree에 저장하고 Graph를 이용하여 최단 거리를 가지는 여행 일정 그래프를 설계한다. AVL tree는 전체 정보 출력 즉 프린트 기능과 저장된 특정 정보를 삭제 및 검색하는 기능을 제공한다. Graph는 AVL tree에 저장된 도시 정보를 이 용하여 최단 이동 거리 그래프를 MST(minimum spanning tree)를 구축하고 karuskal 알고리즘 을 이용하여 구현한다. ## 2. . Algorithm ### 2.1 LOAD() LOAD 명령어는 여행 일정 관리 시스템에 도시들의 정보를 불러오는 명령어이다. 도시 정보 가 저장 되어있는 city_list 텍스트 파일을 읽어 AVL tree를 구현하다. 또한 범위가 맞지 않는 도시 위치 정보의 입력, 영어가 아닌 도시 및 나라이름이 들어오는 경우는 없다고 가정한다. 중복된 위치 정보를 입력하는 경우 위치 정보/ 도시이름/ 나라이름 개의 데이터 중 하나라도 입력하지 않은 경우는 없다고 가정하며 텍스트 파일이 없고 트리가 이미 구성되어 있는 경우 log파일에 에러코드 100을 출력한다.Load 함수는 먼저 line을 string 형태로 받아서 city list텍스트 파일을 연후 만약 열지못하면 false를 반환한다. 만약 avl트리의 루트가 비어있지 않아도 false를 반환한다. 반복문을 통해 한 줄 씩 읽으며 strtok로 탭을 기준으로 잘라준다. 잘라준 글자를 city num/ city name/ coun name에 넣어준다. 그리고 데이터 노드를 만들어서 데이터를 저장해주고 노드를 만들어서 avl 트리에 삽입해준다. 삽입 함수는 2) INSERT 함수와 같다. ### 2.2 INSERT() INSERT 명령어는 존재하는 AVL tree에 새로운 도시를 입력하는 명령어로 예외처리는 없다고 가정하며 이미 구축된 AVL tree가 없는 경우 log 파일에 에러코드 200을 출력한다. 맨 처음으로 만약 루트가 없다면 들어온 노드를 루트로 지정해준다. Insert 함수는 인자가 city data형태로서 반복문을 돌면서 위치에 맞는 곳에 삽입을 하게 된다. 맨 처음은 bf가 0이 아닐 경우는 양쪽 자식이 같은 높이를 가지고 있는 형태이거나 리프 노 드일 경우로 만약 0이 아니면 인자로 받은 노드의 이름과 p 값의 이름과 비교 후 삽입해준 다. 이런 식으로 루트를 타고 계속해서 노드의 이름과 비교 후 들어온 노드가 있는 값보다 작다 면 왼쪽으로 크다면 오른쪽으로 가게 끔 자리를 배치해준다. 트리의 밸런스가 무너졌는지 확인한다. D==1은 밸런스가 무너졌다면 밸런싱을 해주는 코드다. 맨 처음엔 LL의 경우로서 밸런스가 맞지 않는 경우로 왼쪽->왼쪽으로 치우쳐져 있는 형태다. 각 노드에 데이터를 삽입 후 서 브 트리에 b의 값을 넣어준다. else경우엔 LR의 경우이고 왼쪽으로 그리고 오른쪽으로 치우 쳐져 있는 형태다. 루트를 기준으로 왼쪽의 서브트리의 높이가 더 높다. C의 bf를 받아서 case문으로 bf가 0일경우,1일경우,-1일경우 분류해준다. 그리고 c가 서브트리의 새로운 루트 가 되며 코드가 끝이 난다. 다음은 RR의 경우로 만약 b의 bf가 -1이면 각 노드에 데이터를 삽입하고 서브트리 루트에b의 값을 삽입해준다. 이경우는 오른쪽->오른쪽으로 치우쳐져 있는 형태로 루트 기준으로 오른쪽 서브트리의 높이가 더 높을 경우다. Else의 경우엔 RL의 경우로 오른쪽->왼쪽으로 기울어져 있는 경우다. C의 bf를 구한 후 0,-1,1,의 경우를 고려하여 case문을 수행한다. 그 리고 RR과RL이 끝나고 c의 bf를 0으로 맞춰주고 코드가 끝난다. ### 2.3 PRINT_AVL() PRINT_AVL 명령어는 AVL tree를 탐색하여 저장되어 있는 모든 정보를 출력하는 명령어로 log 텍스트 파일에 도시 이름의 오름차순으로 출력한다. 만약 AVL tree에 저장돼 있는 정보가 없 을 경우 log파일에 에러코드 300을 출력하다. 프린트 함수의 경우 스택을 이용한 inorder를 구현하여 출력해주었다. 먼저 스택을 선언하고 a를 루트로 잡는다. 만약 a가 NULL이면 에러코드를 호출한다. 반복문을 돌면서 루트의 왼쪽 값들을 push로 스택에 넣어준다. 그후 만약 스택이 비어있으면 반복문을 종료하고 아니면 a의 값에 스택에 들어간 가장 마지막 값을 넣어주고 출력해준다. 이 작업을 다하고 a는 오른쪽으로 더 이상 오른쪽이 없을 때지 움직이며 스택에 넣고 이 작업을 반복하여 출력한다. ### 2.4 DELETE_AVL() DELETE_AVL 명령어는 AVL tree를 탐색하여 저장돼 있는 모든 정보 중에 입력 받은 도시 위 치정보를 가지고 있는 노드를 삭제하며 도시 정보를 삭제한 후 AVL tree는 다시 밸런싱 돼야 한다. AVL tree에 해당 도시 위치 정보가 없을 경우, log.txt에 에러 코드 400을 출력한다. 삭제의 경우 전체적인 알고리즘은 우선 반복문을 돌면서 트리의 노드들의 값과 인자로 받은 노드의 값과 비교 후 삭제할 노드를 찾고 지워준 후 BST처럼 자식과 부모를 이어준다. 만약 삭제 후 트리의 밸런싱이 맞지 않으면 밸런싱을 해준다. 먼저 위 코드는 트리를 돌면서 삭제 할 노드를 찾는 과정이다. 삭제를 완료하고 다시 트리의 루트를 호출하여 루트의 bf를 구하였을 때 만약 1보다 크거나 -1보다 작다면 밸런스가 무너진 것으로 각각 맞는 타입의 함수를 호출해준다. (LL,LR,RR,RL) 그 리고 반환한 노드를 트리의 루트 노드로 삽입해준다. 맨위에서부터 RR/ LL / LR / RL 타입이다. RR과 LL은 좌 혹은 우로 트리를 돌린 후에 루트를 반 환하지만 RL과 LR은 트리를 돌리고 RR 혹은 LL을 다시 호출하여 재정리를 해준 뒤 값을 반 환한다. ### 2.5 SEARCH_AVL() SEARCH_AVL 명령어는 입력 받은 도시의 위치정보를 가진 도시 정보의 데이터를 검색하는 명령어로 해당 도시 위치 정보를 가진 노드를 AVL tree에서 검색 하여 도시정보를 log 텍스 트 파일에 출력한다. 다른 예외처리는 없다고 가정하며 입력은 숫자 형태이다 만약 입력한 정보의 데이터가 존재하지 않거나 위치 정보를 입력하지 않은 경우 log에 에러코드 500을 출 력한다. 다음은 노드를 검색하는 코드이다. 먼저 전역변수로 선언한 num에 명령어에서 잘라온 두 번 째 인자를 atoi로 숫자로 변환하여 넣는다. 만약 인자가 없다면 에러코드를 호출한다. 그리고 인오더로 트리를 돌면서 하나하나 씩 값을 비교하고 인자의 값과 일치하는 노드를 찾아 출력 해준다. ### 2.6 BULID_GP() BUILD_GP 명령어는 AVL tree에 저장 되어있는 도시 정보들을 이용하여 완전 연결 gragp로 만들고 이미 만들어진 그래프가 있는 경우 지우고 다시 생성한다. 도시 정보들의 그래프 노 드 번호는 도시 이름의 오름 차순으로 설정한다. 만약 AVL tree에 도시 정보가 없는 경우 log 텍스트 파일에 에러코드 600을 출력한다. 따로 만들어둔 gp_arry에 노드들을 넣고 temp를 만들어 name기준으로 비교한 후 오름차순으로 삽입한다. 그리고 vertex와 mList에 각각 데이터를 넣어준다. ### 2.7 PRINT_GP() PRINT_GP 명령어는 그래프를 탐색하여 저장 되어있는 모든 정보를 출력하는 명령어로 log 텍스트 파일 그래프 연결 형태를 행렬 형식으로 출력한다. 이떄 행과 열 번호는 노드 번호의 오름차순이다. 만약 그래프에 저장되어 있는 정보가 없는 경우, log텍스트 파일에 에러코드 700을 출력한다. mList에 값을 넣고 이중 포문을 돌면서 노드끼리의 차를 abs로 절대값을 씌워 선언해 둔 weight 변수에 넣고 출력한다 ### 2.8 BUILD_MST() BUILD_MST 명령어는 존재하는 그래프의 정보를 이용하여 최적의 간선 가중치로 모든 노드 가 연결 되어있는 tree를 생성한다. 이때 생성하는 알고리즘은 kruskal을 사용하며 이미 만들 어진 mst가 있는 경우 지우고 다시 생성한다. 만약 그래프에 저장되어 있는 정보가 없는 경 우 log 텍스트 파일에 에러코드 800을 출력한다. 다음은 본인이 따로 선언한 sturct의 헤더파일의 코드이다. edge라는 구조체를 만들어 안에 u,v는 각각의 정점이 될 변수이고 data1은 u의 데이터 data2는 v의 데이터이다 그리고 wei는 두 데이터의 가중치다 operator는 나중에 wei를(가중치) 기준으로 sort를 해주기 위해 선언해 주었다. 구조체의 변수를 선언하고 각각 변수에 노드들의 정보를 넣는다. 그후 vector 형태인 kru_tree 에도 값을 넣고 가중치를 기준으로 정렬해준다. 그리고 부모 배열에 부모가 될 벨류를 넣고 find함수를 호출하여 이 노드들이 0이 아니면 조건에 해당되어 mst의 간선 및 정점으로 채택 되어 MST의 결과값을 넣는 벡터형태인 r_tree에 넣는다. 다음은 find의 코드다. 처음에 부모의 값과 두 정점의 숫자를 인자로 받아 make_set해준다. 만약 x와 y가 같으면 1 로 반환하고 아니면 0으로 반환한다. 부모 배열에 a를 비교하여 맞으면 a를 반환한다. 그리고 재귀적으로 이 값을 호출하여 간선 들이 싸이클을 이루지 않는 정점이 나올 때 까지 찾는다. 다음은 합치는 부분인다. 만약 x와 y를 set해서 y가 더 크면 x를 집어넣어 합쳐주고 아니면 x 에 y를 넣어 합쳐준다. ### 2.9 PRINT_MST() PIRINT_MST 명령어는 MST를 탐색하여 저장되어 있는 모든 정보를 출력하는 명령어로 log 텍스트 파일에 도시 정보 노드의 연결 순서대로 출력한 뒤 최종 간선들의 합을 출력한다. 만 약 MST에 저장되어 있는 정보가 없을 경우, log 텍스트 파일에 에러코드 900을 출력한다. 구현한 MST의 값들을 출력해주는 함수로 채택된 간선들의 집합인 백터 형태의 R_tree의 값 들을 출력해준다. 그리고 가중치들의 합들도 출력해준다. ### 2.10 EXIT() EXIT 명령어는 프로그램을 종료하는 명령어로 이 명령어가 들어오면 모든 작업을 멈추고 프 로그램을 종료한다. ## 3. RESULT 맨처음에 LOAD를 하고 트리를 구현한 후 다시 한번 LOAD 를 불러 값이 들어갔는지 확인한후 AVL 트리를 출력 한다. 그 후 값을 추가하고 검색, 삭제 를 거친 후 다시 한번 PRINT해준다. 이 노드들로 그래프를 만들고 출력 후 MST를 빌드 하고 출력하는 것으로 시험했다. MAKE를 해주고 프로그램을 수행하면 정상적으로 실행되고 log.txt가 생긴 것을 환인 할 수 있다. 맨 처음 LOAD는 성공하고 두 번째 LOAD는 이미 트리가 존재하기 때문에 에러코드가 발생 한다. 그리고 AVL트리를 출력 된 모습이고 insert 값인 7423,Damm,korea를 넣고 2132의 위 치 노드를 가진 도쿄 노드를 찾아 출력한다. 그리고 2132를 지우고 다시 AVL을 출력하였을 때 도쿄는 없고 7423,Damm,korea가 들어간 것을 확인 할 수 있다. 그리고 그래프를 빌드하 는 것에 성공하고 프린트 했을 때 행과 열이 같은 값으로 가지는 것을 알 수 있고 방향성이 없는 그래프의 특징인 대각선으로 0값을 갖는 것을 확인 할 수 있다. 그리고 MST를 빌드하고 출력한 결과이다. 모든 간선들이 들어 간 모습이고 도시들의 가중치 또한 더한 값이 잘 출력된 모습이다. ## 4. Consideration 이번 프로젝트는 1차 과제 보다 난이도가 높았다. 먼저 AVL의 밸런스를 맞춰주는 것이 난이 도가 있었고 RR,LLRL,LR의 개념을 확실하게 잡지 않는다면 이번 프로젝트를 수행 할 수 없었 을 것이다. 처음에 RR이 오른쪽으로 회전하는 것인 줄 알고 인터넷에서 공부하던 중 많은 의 문이 달렸고 코드 구현에도 어려움이 있었지만 제대로 개념을 잡고 코드를 수행하니 수월하 게 하였다. 삽입은 강의자료대로 하였지만 삭제는 BST의 삭제처럼 하고 그 뒤에 밸런싱 해주 는 함수를 따로 만들어서 하였다. 이렇게 할 줄 알았으면 삽입도 이렇게 할 걸 그랬다…그리 고 그래프와 kruskal알고리즘도 어렵지 않았지만 linux에서 돌아가지 않아 정말 애를 많이 먹 었다. 디버깅을 하여도 원인 모르는 에러가 자꾸 뜨지만 비쥬얼 스튜디오에선 정상적으로 동 작하였고 정말 예민한 프로그램인 것 같다. 코드를 고치는 와중에 아예 방향성을 잃어버려 부랴부랴 다시 구현한 함수도 있었다. 여러모로 힘든 프로젝트였다. 그리고 이번에 구조체의 operation을 선언하여 정렬하는 부분도 새롭게 배웠고 간단하게나마 벡터도 활용하였다. 다양 한 함수를 사용하여 뿌듯하다. <file_sep>//#pragma once #ifndef RESULT_H #define RESULT_H enum Result { Success = 0, CommandFileNotExist = 100, LoadFileNotExist = 101, VertexKeyNotExist = 200, InvalidVertexKey = 201, GraphNotExist = 202, InvalidAlgorithm = 203, NegativeCycleDetected = 204, NonDefinedCommand = 300, }; #endif <file_sep>#include "AVLTree.h" #include <algorithm> #include <queue> #include <cstring> #include <iostream> #include <stack> AVLTree::AVLTree(ofstream * flog) { this->flog=flog; //get flog } AVLTree::~AVLTree() { } AVLNode * AVLTree::Getroot() { return root; //return root } void AVLTree::Setroot(AVLNode * node) { root = node; //root is node } bool AVLTree::Insert(CityData * node) { //insert if (root == NULL) { //if root is NULL root = new AVLNode; //make new node root->SetCityData(node); } else { //else while(1) //while {//already exist root //Locate insertion point for id AVLNode *a = root, *pa = NULL, //pa is null *p = this->root, // p is this root *pp = NULL, // pp get NULL *rootSub = NULL; //root sub while(p!=NULL) //while p is not null { if(p->GetmBF() != 0){a =p;pa =pp;} // get bf of p is not 0 a is p , pa is pp if (strncmp(node->Getname(), p->GetCityData()->Getname(),sizeof(node->Getname())) < 0) { // if node name is smaller than p's name pp = p; // pp is p p = p->GetLeft(); // p go left } else if (strncmp(node->Getname(), p->GetCityData()->Getname(),sizeof(node->Getname()))> 0) { // if node name is bigger than p's name pp = p; //pp is p p = p->GetRight(); // p get right } else { // else delete node; //delete node return false; // return false } } AVLNode * y = new AVLNode; //make new node y->SetCityData(node); //set citydata y->SetLeft(NULL); y->SetRight(NULL); if (strncmp(node->Getname(), pp->GetCityData()->Getname(),sizeof(node->Getname())) < 0) //if node name is smaller than pp'sname pp->SetLeft(y); //pp go left else //else pp->SetRight(y); //pp set y int d; AVLNode *b,*c; if (strncmp(node->Getname(), a->GetCityData()->Getname(),sizeof(node->Getname())) > 0) { // if node's name is bigger than a's name p = a->GetRight(); //p is a's left b = p; // b is p d = -1; // d is -1 } else { // p = a->GetLeft(); //p is a's left b = p; //b is p d =1; // diff is 1 } while(p!=y) { //while until p is not y if(strncmp(node->Getname(),p->GetCityData()->Getname(),sizeof(node->Getname()))>0) { //if nod's name is bigger than p's name p->SetmBF(-1); //p's bf is -1 p=p->GetRight(); //p is p's right } else {//else p->SetmBF(1); //p 's bf is 1 p=p->GetLeft(); //p is p's left } } if(a->GetmBF()==0|| a->GetmBF()+d==0) { // id a's bf is 0 or a's bf+d is 0 a->SetmBF(a->GetmBF()+d); //a's bf is a's left's bf+d break; } if(d ==1 ) { //if d ==1 if(b->GetmBF()==1) { //b's bf is 1 type ll a->SetLeft(b->GetRight()); //a left is b's right b->SetRight(a); //b set right a a->SetmBF(0); //set a's bf 0 b->SetmBF(0); //set b mf rootSub = b; //roootxub is b } else { //else typr lr c = b->GetRight(); // c is b's right b->SetRight(c->GetLeft()); //set b right is c's left a->SetLeft(c->GetRight()); //set a left is c's right c->SetLeft(b); //c set left b c->SetRight(a); switch (c->GetmBF()) { case 0: b->SetmBF(0); a->SetmBF(0); break; case 1: a->SetmBF(-1); b->SetmBF(0); break; case -1: b->SetmBF(1); a->SetmBF(0); break; } c->SetmBF(0); rootSub =c; } } else { if (b->GetmBF() == -1) {//rotation type RR a->SetRight(b->GetLeft()); b->SetLeft(a); a->SetmBF(0); b->SetmBF(0); rootSub = b;//b is the new root of the subtree } else {//rotation type RL c = b->GetLeft(); b->SetLeft(c->GetRight()); a->SetRight(c->GetLeft()); c->SetRight(b); c->SetLeft(a); switch (c->GetmBF()) { case 0: b->SetmBF(0); a->SetmBF(0); break; case 1: b->SetmBF(-1); a->SetmBF(0); break; case -1: a->SetmBF(1); b->SetmBF(0); break; } c->SetmBF(0); rootSub = c;//c is the new root of the subtree }//end of RL } if (pa == NULL) root = rootSub; //finish while and if pa is nULL root ;s rootsub else if (a == pa->GetLeft()) pa->SetLeft(rootSub); //else id a is pa'sleft pa left is rootsub else pa->SetRight(rootSub); //else pa set right is root sub break; } } return true; } CityData * AVLTree::Delete(int num) { AVLNode * del = new AVLNode(); //Setroot(del); del = root; num2 = num; AVLNode * num_node = new AVLNode(); num_node = inorder_tree(del); if (num_node == NULL) return NULL; AVLNode * prev = NULL; AVLNode * pw = NULL; AVLNode * prev_w = NULL; AVLNode * wa = NULL; if (Getroot() == NULL) { //if root is NULL return 0; //return 0; } while (del) { //while del is exist if (strncmp(num_node->GetCityData()->Getname(),del->GetCityData()->Getname(),sizeof(num_node->GetCityData()->Getname()))==0) break;//if num_node's name is del's name is same prev = del; if (strncmp(num_node->GetCityData()->Getname(),del->GetCityData()->Getname(),sizeof(num_node->GetCityData()->Getname()))>0) del = del->GetRight();//or bigger else del = del->GetLeft(); } //only root node if (del == Getroot() && del->GetLeft() == NULL && del->GetRight() == NULL) { Setroot(NULL); //root is null delete prev; //delete prev } else if (del->GetLeft() == 0 && del->GetRight() == 0) {//no child if (prev == NULL) return 0; if (prev->GetLeft() == del) { //if prev left is del prev->SetLeft(NULL); //set prev's left is null delete del; //delete del } else { //else prev->SetRight(NULL); //prev set right is null delete del; //delete del } } else if(del->GetLeft() == NULL || del->GetRight() == NULL) //else if del go lfet is NULL or del right is null {// 1child if (del->GetLeft() == NULL && del->GetRight() != NULL) {//(right) if (prev == NULL) //if prev is null Setroot(del->GetRight()); //set root del get right else if (prev->GetLeft() == del) //else if prev get left is del prev->SetLeft(del->GetRight()); //prev set left is del's right else //else prev->SetRight(del->GetRight()); //prev right is del's right delete del; //delete del } else if (del->GetLeft() != NULL && del->GetRight() == NULL) {//left if (prev == NULL) //if prev is null Setroot(del->GetLeft()); //set root else if (prev->GetLeft() == del) //else if prev left is del prev->SetLeft(del->GetLeft()); //prev set left is del's left else prev->SetRight(del->GetLeft()); //prev set right is del's left delete del; //delete del } } else { //else if del node has two child AVLNode *prevprev = del; AVLNode * prev = prevprev->GetLeft(); while (prev->GetRight() != NULL) {//while prev 's right is not null prevprev = prev; //pp is p prev = prev->GetRight(); //p is p'sright } if (prev->GetLeft() != NULL) {//if prev get left is not null if (prevprev->GetLeft() == prev) //if pp left is prev prevprev->SetLeft(prev->GetLeft()); //pp left is p's left else //else prevprev->SetRight(prev->GetLeft()); //pp set right is p's left } else { //else if (prevprev->GetLeft() == prev) prevprev->SetLeft(NULL); //pp's left is null else prevprev->SetRight(NULL); //pp's right is null } if (del == Getroot()) {//if dell is root Setroot(prev); //root = prev; } del->SetCityData(prev->GetCityData());//del get data is prev's data del = prev; //del is prev delete del; //delete del del = NULL; } AVLNode * p = Getroot(); p->SetmBF(diff(Getroot())); if (p->GetmBF() > 1) {//ll, lr if (diff(Getroot()->GetLeft()) > 0) {//ll Setroot(ll(p)); } else {//lr Setroot(lr(p)); } } else if (p->GetmBF() < -1) {//rr, rl if (diff(Getroot()->GetRight()) > 0) {//rl Setroot(rl(p)); } else {//rr Setroot(rr(p)); } } } bool AVLTree::Print(AVLNode * root) { stack<AVLNode*> T = *new stack<AVLNode*>; AVLNode* a = root;//make stack if (a == NULL) return false; //if a is null return false while (1) { while (a) { //while a is not null T.push(a); //stack insert a a = a->GetLeft(); //a is a'sleft } if (T.empty()) break; //if t is empty than break a = T.top(); //a is top of stack T.pop(); //delete *flog << "(" << a->GetCityData()->GetLocationId() << ", " << a->GetCityData()->Getname() << ", " << a->GetCityData()->Getcountry() << ")" << endl; a = a->GetRight();//a is a's right } return true; } int AVLTree::height(AVLNode * temp) { int h = 0; if (temp != NULL) { //reculsivly call fucntion int left = height(temp->GetLeft()); //go left int right = height(temp->GetRight()); //go right int max_h = max(left, right); //max left or right h = max_h + 1; //h is max+1 } return h; } int AVLTree::diff(AVLNode * temp) { //make diff int left = height(temp->GetLeft()); int right = height(temp->GetRight()); int factor = left - right; return factor; } AVLNode * AVLTree::rr(AVLNode * parent) { //rr fuction AVLNode * temp; temp = parent->GetRight(); parent->SetRight(temp->GetLeft()); temp->SetLeft(parent); return temp; } AVLNode * AVLTree::ll(AVLNode * parent) { //ll type AVLNode * temp; temp = parent->GetLeft(); parent->SetLeft(temp->GetRight()); temp->SetRight(parent); return temp; } AVLNode * AVLTree::lr(AVLNode * parent) { // lr type AVLNode * temp; temp = parent->GetLeft(); parent->SetLeft(rr(temp)); return ll(parent); } AVLNode * AVLTree::rl(AVLNode * parent) { //rl type AVLNode * temp; temp = parent->GetRight(); parent->SetRight(ll(temp)); return rr(parent); } AVLNode * AVLTree::inorder_tree(AVLNode * tree) { //inorder tree if (tree) { inorder_tree(tree->GetLeft()); if (tree->GetCityData()->GetLocationId() == num2) { sa = tree; } inorder_tree(tree->GetRight()); } return sa; } <file_sep>#include <iostream> #pragma warning(disable : 6386) using namespace std; int main() {//declare int x, y; int arr[10][10] = { 0, }; cout << "Please input 2D array size: "; cin >> x >> y; if (x < 1 || x > 10 || y < 1 || y > 10) return 0; //get x and y int i = 1;//declare int x1 = 0, y1 = 0; int N = x; int xx = 0, yy = 0; int x_count=x; int y_count=y; while (N >0) {//cycle num is bigger than 0 for (int a = y-y_count; a < y; a++) {//left to right columm arr[yy][xx++] = i++; } N--;//cycle -- xx--; yy++; x_count--; if (N == 0) break; for (int a = x-x_count; a < x; a++) {// up to down row arr[yy++][xx] = i++; } yy--; xx--; y_count--; for (int a = y - y_count; a < y; a++) {//right to lfet columm arr[yy][xx--] = i++; } xx++; N--; yy--; x_count--; if (N == 0) break; for (int a = x - x_count; a < x; a++) {//down to up row arr[yy--][xx] = i++; } xx = ++x1; yy = ++y1; y_count--; } for (int a = 0; a < x; a++) {//print numbers for (int b = 0; b < y; b++) { cout << arr[a][b] << " "; } cout << endl; } }<file_sep>#include "AVLNode.h" AVLNode::AVLNode() { } AVLNode::~AVLNode() { } CityData * AVLNode::GetCityData() { return pCityData; //return city data } AVLNode * AVLNode::GetLeft() { if(pLeft ==NULL) { //if left is NULL return 0; //return 0 } else { //else return pLeft; //return left } } AVLNode * AVLNode::GetRight() { if(pRight == NULL) { return 0; } else { return pRight;//rerturn right } } int AVLNode::GetmBF() { return mBF; } void AVLNode::SetCityData(CityData * node) { pCityData = node; //city data is node } void AVLNode::SetLeft(AVLNode * node) { pLeft = node; //left is node } void AVLNode::SetRight(AVLNode * node) { pRight = node; //right is node } void AVLNode::SetmBF(int n) { mBF = n; } <file_sep>#include "AVLNode.h" #include <iostream> #include <fstream>// header file declare using namespace std; class AVLTree { public: AVLNode * root; // AVLTree Root ofstream * flog; public: AVLTree(ofstream * flog); //fucntion declare ~AVLTree();//fucntion declare AVLNode * sa;//fucntion declare int num2;//fucntion declare AVLNode * Getroot();//fucntion declare void Setroot(AVLNode * node);//fucntion declare bool Insert(CityData * node);//fucntion declare CityData * Delete(int num);//fucntion declare CityData * Search(int num);//fucntion declare bool Print(AVLNode* root);//fucntion declare int height(AVLNode * temp);//fucntion declare int diff(AVLNode * temp);//fucntion declare AVLNode * rr(AVLNode * parent);//fucntion declare AVLNode * ll(AVLNode * parent);//fucntion declare AVLNode * lr(AVLNode * parent);//fucntion declare AVLNode * rl(AVLNode * parent);//fucntion declare AVLNode * balance(AVLNode * temp);//fucntion declare AVLNode * inorder_tree(AVLNode * tree);//fucntion declare }; <file_sep>#include "Queue.h" #include <iostream> Queue::Queue() { this->Head = nullptr;//head is null this->size = 0;//size is 0 } Queue::~Queue() { } bool Queue::IsEmpty() { if (size == 0)//set return true; } bool Queue::Push(BSTNode* Node) { if (size == 0) { this->Head = Node;//set size++; return true;//set } BSTNode* parent = nullptr;//set BSTNode* current = this->Head;//set while (current != nullptr) {//current is no null parent = current; if (Node->GetData() < parent->GetData()) {//node data is smaller than parent current = current->GetLeft(); } else {//else current = current->GetRight(); } } if (Node->GetData() < parent->GetData()) {//node data is smaller than paret parent->SetLeft(Node); } else { parent->SetRight(Node); } size++; return true; } void Queue::Pop() { } BSTNode* Queue::Front() { if (size != 0) { return this->Head; } } void Queue::Inorder(BSTNode* now) { if (now != nullptr) { //inorder this->Inorder(now->GetLeft()); std::cout << now->GetData() << " "; this->Inorder(now->GetRight()); } } void Queue::Postorder(BSTNode* now) { if (now != nullptr) { //preorder this->Postorder(now->GetLeft()); this->Postorder(now->GetRight()); std::cout << now->GetData() << " "; } } void Queue::Preorder(BSTNode* now) { if (now != nullptr) {//preorder std::cout << now->GetData() << " "; this->Preorder(now->GetLeft()); this->Preorder(now->GetRight()); } } <file_sep>#define _CRT_SECURE_NO_WARNINGS #include "BinarySearchTree.h" //#include "SoccerPlayerData.h" #include <iostream> using namespace std; BinarySearchTree::BinarySearchTree(SoccerPlayerData & data) { } BinarySearchTree::~BinarySearchTree() { Clear(m_root);//delete memoty } void BinarySearchTree::insert_arr(SoccerPlayerData & data) {// insert arr TreeNode * player_arr = new TreeNode(data, NULL, NULL);//make node TreeNode * p_arr = m_root; //m_root TreeNode * pp_arr = NULL; // reset if (p_arr == NULL) //if p_arr is NULL { m_root = player_arr; //root is node return; } else { while (p_arr) //while until p_arr is not NULL { pp_arr = p_arr; p_arr = p_arr->m_right; //p_arr is p_arr right } pp_arr->m_right = player_arr; //insert pp_arr right is plyer_arr } } void BinarySearchTree::insert(SoccerPlayerData & data) {//insert Binary search Tree TreeNode * player = new TreeNode(data, NULL, NULL);// make new Node TreeNode * p = m_root; //reset TreeNode * pp = NULL; //reset if (p == NULL) {// if root is NULL return m_root = player; return; } else //else { while (p) //while until p is Not NULL { pp = p; if (data.m_ability < p->m_data.m_ability) p = p->m_left;//if new data abli is smaller than predata go left else if (data.m_ability > p->m_data.m_ability) //or big go right p = p->m_right; } if (data.m_ability < pp->m_data.m_ability) pp->m_left = player; //make line with tree else pp->m_right = player; //make contact with tree } } void BinarySearchTree::deletion(int ability) {// delete TreeNode * p = m_root, *pp = NULL; while (p && ability != p->m_data.m_ability)//find delete node { pp = p; if (ability < p->m_data.m_ability) p = p->m_left; //if node is small go left else p = p->m_right; //else go right } if (p == NULL)//if p is NULL return; //return if (p == m_root && p->m_left == NULL && p->m_right == NULL)//if only root { m_root = NULL; delete p; } else if (p->m_left == NULL && p->m_right == NULL)//if Node is leaf { if (pp == NULL) return; // if no node return else if (pp->m_left == p) { //if node's parent's left child pp->m_left = NULL; delete p; } else { pp->m_right = NULL; //if right child delete p; } } else if (p->m_left == NULL && p->m_right!=NULL)//if only 1 child (right) { if (pp == NULL)//pp is NULL m_root = p->m_right; // root go right else if (pp->m_left == p) //else go left { pp->m_left = p->m_right; // parent's left is node's right } else pp->m_right = p->m_right; //else delete p; } else if (p->m_left != NULL && p->m_right == NULL)//if only 1child(left) { if (pp == NULL) // pp is NULL m_root = p->m_left; // root go left else if (pp->m_left == p) //else go left pp->m_left = p->m_left; else pp->m_right = p->m_left; // else delete p; // delete } else//node has two child { TreeNode *prevprev = p;//maximum node's parent node TreeNode * prev = prevprev->m_left;//maximum node while (prev->m_right != NULL) {//find biggest node in left child prevprev = prev; //prevprev is pp prev = prev->m_right; // } if (prev->m_left != NULL) {//if there are bigegst node in left child //if delete node is maximum node if (prevprev->m_left == prev) prevprev->m_left = prev->m_left; else prevprev->m_right = prev->m_left; } else {// if delete node is root if (prevprev->m_left == prev) prevprev->m_left = NULL; else//else prevprev->m_right = NULL;//put node } if(p==m_root) { m_root = prev; } p->m_data = prev->m_data; //put data p = prev; //p is prev delete p; // delete p = NULL; // p is NULL } } void BinarySearchTree::Clear(TreeNode * root) {// delete memory by inorder function TreeNode * cur = root; if (cur) { Clear(cur->m_left); Clear(cur->m_right); delete cur; //delete it } } <file_sep>#include "pch.h" #include "Block.h" Block::Block() { } Block::~Block() { } int Block::getNum() { return m_number; } int Block::getX() { return b_x; } int Block::getY() { return b_y; } void Block::setNum(int new_num) { m_number = new_num; } void Block::setX(int newx) { b_x = newx; } void Block::setY(int newy) { b_y = newy; } void Block::setUp(Block* NewNode) { p_Up = NewNode; } void Block::setDown(Block* NewNode) { p_Down = NewNode; } void Block::setRight(Block* NewNode) { p_Right = NewNode; } void Block::setLeft(Block* NewNode) { p_Left = NewNode; } Block* Block::getUp() { return p_Up; } Block* Block::getDown() { return p_Down; } Block* Block::getRight() { return p_Right; } Block* Block::getLeft() { return p_Left; } <file_sep>#include "CityData.h" #include <cstring> #pragma warning(disable:4996) CityData::CityData() { LocationId = 0;//value declare name = new char[50]; //value declare country = new char[50]; //value declare } CityData::~CityData() { } int CityData::GetLocationId() { return LocationId; //return location } char * CityData::Getname() { return name; // return name } char * CityData::Getcountry() { return country; //return contry } void CityData::SetLocationId(int LocationId) { this ->LocationId = LocationId; } void CityData::Setname(char * name) { strncpy(this->name,name,sizeof(name)-1); } void CityData::Setcountry(char * country) { strncpy(this->country,country,sizeof(country)-1); } <file_sep># 섬 그래프를 이용하여 최단 경로 찾기 프로그램 ## 1. Introduction 이번 프로젝트는 섬 그래프를 이용하여 최단 경로 찾기 프로그램을 구현합니다. 이 프로그램은 섬을 연결하는 섬에 대한 정보가 저장되어 있는 mapdata텍스트 파일을 통 하여 그래프를 구성합 니다. 이 그래프를 기반으로 하여 Dijkstra, Bellman-ford 알고리즘을 이용해 섬의 경로와 거리를 구합니다. 섬 그래프 정보는 방향성과 가중치 모두 가지고 있고 Matrix 형태로 저장 되어있습니다. 만약 가중치가 음수일 경우 Dijkstra는 에러를 출력하고, Bellman-Ford에서는 음수 사이클이 발생 한 경우 에러, 음수 사이클이 발생하지 않았을 때 최단 경로와 거리를 구합니다. FLOYD에서는 음 수 사이클이 발생한 경우 헤러, 음수 사이클이 발생하지 않았을 경우 최단 경로 행렬을 구합니다. 프로그램 동작은 명령어 파일에서 요청하는 명령에 따라 각각의 기능을 수행하고 그 결과를 로그 파일에 저장합니다. Dijkstra는 start vertex와 end vertex를 입력을 받아 경로와 거리를 구합니다. 경로를 구하는 방법 으로는 STL set을 사용하고, 결과로 찾은 최단 경로를 다시 순회하여 start vertex부터 end vertex 순으로 경로를 구합니다. Dijkstra with min heap 방법으로는 Dijkstra와 알고리즘은 동일하지만 STL set을 쓰는 대신에 min heap을 사용하여 구현을 합니다. Bellman-Ford는 start vertex와 end vertex를 입력을 받아 최단 경로와 거리를 구합니다. 거리의 가 중치 weght가 음수인 경우에도 동작을 하며, 음수 weight에 사이클이 발생한 경우에는 알맞은 에 러를 출력합니다. Floyd는 명령어 인자 없이 모든 쌍에 대하여 최단 경로 행렬을 구합니다. 거리의 가중 치 weght 가 음수인 경우에도 동작을 하며, 음수 weight에 사이클이 발생한 경우에는 알맞은 에러를 출력 합니다. ## 2. Algorithm ### 2.1 LOAD 프로그램에 섬 Mapdata의 정보를 기반으로 하여 그래프를 형성합니다, 위의 그림처럼 Matrix의 형태로 그래프의 정보를 관리합니다. 만약 LOAD 할 텍스트 파일이 없거나 읽을 수 없을 경우, 에러코드를 출력하고 오류 코드 101를 출력합니다. 또한 하나의 커맨드 파 일에서 LOAD가 2번 이상 성공하는 경우는 고려하지 않습니다 섬을 이어주는 경로의 데이터 정보가 존재하는 텍스트파일의 파일명인 filepath를 불러 와 ifstream형의 변수로 선언을 해주고 fin.open()함수를 사용하여 파일을 열어줍니다. 만약 파일이 제 대로 열리지 않았을 경우 에러 코드를 출력해주고 함수를 종료합니다 벡터에 값을 저장할 때, n x n의 행렬을 가집니다 벡터의 개수는 n개이며, 각각의 벡 터에 존재하 는 edge의 개수도 n개로 나타낼 수 있습니다. 따라서 맨 처음 for문을 이용하여 n번 만큼 반복을 하며, 현재의 i를 vertex의 값으로 지정하여 추가해줍니다. 그 후 첫번째 값을 edge로 넣어준 후, n-1번 for문을 이용하여 해당 vector에 edge값을 n개 만큼 넣어 줍니다. 반복문이 종료하게 되면 success를 return해주며 함수를 종료합니다. ### 2.2 PRINT 섬 정보 데이터를 읽어 섬 정보를 출력하는 명령어입니다. Matrix 형태로 섬 정보를 출력 합니다. 섬 정보 데이터가 존재하지 않을 경우엔 로그파일에 오류코드 202를 출력합니다. 함수 실행 시 m_graph의 size 가 비어 있다면, 즉 아무 값도 들어가 있지 않는 상황이라면 알맞 은 에러코드를 출력하고 함수를 return하여 종료를 합니다. graph 클래스 내에서 print 함수로 넘어가줍니다. 벡터 vertex를 m_pVhead 로 지정해준 후, while문을 돌려 벡터 안에 들어있는 값인 edge들을 모두 출력을 해줍니다. While문 안에서 또다 른 for문을 돌리면서, 들어온 값의 key값과 비교하여 edge숫자 전의 edge들에 값에 대해서는 0을 출력해 주도록 합니다. 하나의 edge를 출력을 해주었다면, edge = edge -> GetNext()를 이용하여 다음 edge 로 넘어가도록 해줍니다. vector = vector -> GetNext() 함수를 이용하여 벡터를 이동시 킵니다. 이렇게 모든 벡터들을 거쳐가면서 출력을 마치면 반복문이 종료가 되고 함수를 종료를 시켜줍니다. ### 2.3 DIJKSTRA ```C++ else if(DIJKSTRA) find start key, end key if(inserted vertex is insufficient) error : VertexKeyNotExist FindShortestPathDijkstraUsingSet(start,end) print error ``` mapdata를 기반으로 하여 시작점과 끝점의 최단경로와 거리를 찾는 알고리즘. STL set을 이용하여 구현하였습니다. set을 이용하여 최단 Distance를 구분하여 최단거리와 경로를 찾아내고, 시작점과 끝점의 Distance를 반환하여 출력합니다. 마찬가지로 LOAD 가 된 데 이터가 없을 경우 에러를 출력하며, 명령어 인자가 부족한 경우에는 VertexKeyNotExist, 인자로 입력한 Vertex 가 존재하지 않는 경우에는 InvalidVertexKey, 맵 데이터 중 음수의 Weight 가 존재하는 경우에는 InvalidAlgorithm을 출력하며, 에러없이 정상적인 구동을 완료하면 에러코드는 0입니다 함수 실행 시 세 가지의 경우의 수에 따라 예외 처리를 해줍니다. 첫 번째, m_graph의 size 가 비 어 있다면, 즉 아무 값도 들어가 있지 않는 상황입니다. 두 번째, 입력 받은 시작 vertex 와 마지 막 vertex 값들이 m_graph 안에 있는지 FindVertex()함수를 확인 해 줌으로써 하나라도 NULL 값 을 가지고 있는 경우, 해당 vertex가 그래프 존재하지 않는 상황입니다. 세 번째로 IsNegativeEdge()의 함수가 true를 반환을 한다면, 그래프 안에 음수가 존재하는 상황입니다. 다음 세 가지의 경우를 예외처리를 해주어 알맞은 result값을 return하여 함수를 종료합니다. graph 클래스 내에서 FindPathDijkstrausingset 함수로 넘어갑니다. 그 후 사용할 변수들 중, 거리 를 저장할 dist 값들을 전부 IN_FINITY, 방문 여부를 확인하는 visited 값들을 전부 unvisited, 마지 막으로 경로를 저장할 path값들을 전부 -1로 초기화를 해줍니다. while문을 이용하여 반복문을 실 행시켜 주고, key 값이 end vertex의 key값과 동일할 경우 반복문을 종료하도록 if 문을 이용하여 반복문을 벗어날 수 있도록 설정을 하였습니다. Vertex를 key 값에 해당하는 vertex, 해당 key 값 의 visit 값을 visited, edge를 vertex의 head 로 지정을 해줍니다. While 문 조건에 edge를 넣어 edge 가 next 로 이동하면서 방문을 기록하는 visit 배열안에 순서가 unvisited 로 되어 있을 시, 이때의 edge를 거쳐서 가는 거리와 key 값에 해당하는 vertex 로 바로 가는 거리를 if 문을 이용 하여 비교를 한 다음, 더 작은 값을 dist 안에 정보를 update를 해줍니다. 반복문을 벗어나게 된 다면 stack 안에 있는 맨 첫번째의 second 값을 stack에서 꺼내 다음 key 값으로 지정을 해주고, stack의 맨 첫번째 값을 erase 해주어 그 값을 지워주게 됩니다. 그 후에 endvertex의 path를 따 라가다 보면 경로를 알 수 있으므로, 거꾸로 찾아가는 방식으로 vector에 Vertex값들을 넣어주며, 마지막으로 endVertex까지 오는 최단거리 값을 추가해주고 함수를 종료합니다 ### 2.4 DIJKSTRAMIN ```C++ else if(DIJKSTRAMIN) find start key, end key if(inserted vertex is insufficient) error : VertexKeyNotExist FindShortestPathDijkstraUsingMinHeap(start,end) print error ``` DIJKSTRAMIN의 경우 flowchart 에서도 볼 수 있듯이, DIJKSTRA 와 같은 알고리즘을 사용한다는 점을 알 수 있습니다. 초반에 세 가지에 대하여 예외 처리를 해주고, vertex 와 edge를 while 문 을 통하여 바꿔 주면서 최단 거리를 비교하며 정보들을 업데이트를 해주며 최단거리를 구해줍니 다. Min Heap을 사용한다는 점에서 DIJKSTRA와 다르다는 것을 알 수 있습니다 ### 2.5 BELLMANFORD ```C++ Else if(BELLMANFORD) if(Graph is not exist) error : GraphNotExist if(Vertex is not exist(start or end) error : InvalidVertexKey if(Graph have – Weight) error : InvalidAlgorithm p = Head vertex count = 0, count2 = 0, dis(arr), dis2(arr) while(count != graph size-1) while(count2 != graph size) if(dis of p != infinity) while(visit all of edge of p) if( need update distance of edge) 14 update dis,dis2 count2++ p = next vertex count2 = 0 count++ p = Head vertex doing again only use dis if(dis != dis2) return empty vector //error else push total distance push path return vector(include path and total distance) ``` 함수 실행 시 세 가지의 경우의 수에 따라 예외 처리를 해줍니다. 첫 번째, m_graph의 size 가 비 어 있다면, 즉 아무 값도 들어가 있지 않는 상황입니다. 두 번째, 입력 받은 시작 vertex 와 마지 막 vertex 값들이 m_graph 안에 있는지 FindVertex()함수를 확인해 줌으로써 하나라도 NULL 값을 가지고 있는 경우, 해당 vertex 가 그래프 존재하지 않는 상황입니다. 세 번째, 음수 사이클이 존 재하는 상황입니다. 다음 세 가지의 경우를 예외처리를 해주어 알맞은 result값을 return 하여 함 수를 종료합니다. graph 클래스 내에서 FindPath 함수로 넘어가줍니다. 그 후 사용할 변수들 중, 거리를 저장할 dist 값들을 전부 IN_FINITY, 경로를 저장할 path 값들을 전부 -1 로 초기화를 해줍니다. for 문을 사용하여 m_vSize 만큼 반복을 하도록 설정을 합니다. While 문 조건에 vertex를 넣어 vertex 가 next 로 이동하면서 vertex 값이 존재하는 경우에 반복문을 실행하도록 합니다. key 값에 해당하 는 vertex, 해당 key 값의 visit 값을 visited, edge를 vertex의 head 로 지정을 해줍니다. While 문 조건에 edge를 넣어 edge 가 next 로 이동하면서 방문을 기록하는 visit 배열안에 순서가 unvisited 로 되어 있을 시, 이때의 edge를 거쳐서 가는 거리와 key 값에 해당하는 vertex 로 바 로 가는 거리를 if문을 이용하여 비교를 한 다음, 더 작은 값을 dist 안에 정보를 update를 해줍니 다. 업데이트를 마친 후, 한번 더 위와 같은 while 문 2 개를 사용, 조건을 vertex, edge를 넣어주어 한번 더 탐색을 해줍니다. 만약 음수 사이클이 존재를 할 경우 새로운 업데이트가 다시 생기기 때문입니다. 업데이트를 한번 더 해줄 경우, v 값 맨 앞에 IN_FINITY 값을 넣어주어 음수 사이클 이 존재함을 확인을 하도록 합니다. 그 후에 endvertex의 path를 따라가다 보면 경로를 알 수 있으므로, 거꾸로 찾아가는 방식으로 vector에 Vertex 값들을 넣어주며, 마지막으로 endVertex까지 오는 최단거리 값을 추가해주고 함 수를 종료합니다. ### 2.6 FLOYD 함수 실행 시 m_graph의 size 가 비어 있다면, 즉 아무 값도 들어가 있지 않는 상황이라면 알맞 은 에러코드를 출력하고 함수를 return하여 종료를 시켜줍니다. 기존에 Manager 가 가지고 있던 graph의 정보를 새로운 벡터 vetor<vector<int>형에 저장을 해 줍니다. 이는 while 문을 2 개 사용하여 vector를 이동하고 해당하는 벡터에 있는 edge 들을 while 문을 이용하여 next 로 이동하면서 graph의 정보를 벡터로 그래도 가져오게 됩니다. <file_sep>#include <iostream> #include <vector> #include <cmath> using namespace std; vector <int> v; vector <int> v1; int N = 0; void input() {//get input cout << "Enter the n: "; cin >> N; } void map(vector<int>& v) {// make map that 1to n for (int a = 1; a <= N; a++) { v.push_back(a); } } void find(vector<int>& v) { for (int a = 2; a < N; a++) {//1is not prime for (int b = 2; b <= a; b++) {//1is not prime if (a % b == 0) { //if a division b no remainder if (a / b != 1) {//if a division b no remainder and a/b is not a 1 means no prime break; } v1.push_back(a);//else push primes } } } } int main() { input();//get input map(v);//mapping find(v);//find primes int count = 0; for (int a = 0; a < v1.size(); a++) {//print primes cout << v1[a] << " "; count++; } cout << endl; cout <<"The number of Prime numbers:" <<count; return 0; } <file_sep>#pragma once class BSTNode { private: BSTNode* pLeft;//set BSTNode* pRight;//set BSTNode* pNext;//set int data;//set public: BSTNode();//set BSTNode(int Data);//set ~BSTNode();//set void SetLeft(BSTNode* Left);//set void SetRight(BSTNode* Right);//set void SetNext(BSTNode* Next);//set void SetData(int Data);//set BSTNode* GetLeft();//set BSTNode* GetRight();//set BSTNode* GetNext();//set int GetData();//set };<file_sep>#ifndef MIN_HEAP_H #define MIN_HEAP_H #include <utility> #include <vector> using namespace std; template<typename TKey, typename TValue> class MinHeap { private: // array for the elements which should be heap-sorted std::vector<std::pair<TKey, TValue>> m_vec; public: MinHeap() { m_vec.push_back(std::make_pair(-1, -1)); } /// <summary> /// insert key-value pair /// </summary> /// /// <param name="key"> /// the key that is used for sorting /// </param> /// /// <param name="value"> /// the value that is managed in this heap /// </param> void Push(TKey key, TValue value); /// <summary> /// remove the minimum element /// </summary> void Pop(); /// <summary> /// get the minimum element /// </summary> /// /// <returns> /// the minimum element /// </returns> std::pair<TKey, TValue> Top(); /// <summary> /// get the key-value pair which the value is the same as the target /// </summary> /// /// <returns> /// the key-value pair which the value is the same as the target /// </returns> std::pair<TKey, TValue> Get(TValue target); /// <summary> /// check whether this heap is empty or not /// </summary> /// /// <returns> /// true if this heap is empty /// </returns> bool IsEmpty(); /// <summary> /// change the key of the node which the value is the target.<para/> /// In general, the newKey should be smaller than the old key.<para/> /// </summary> /// /// <parma name="target"> /// the target to change the key /// </param> /// /// <param name="newKey"> /// new key for the target /// </param> void DecKey(TValue target, TKey newKey); private: /// <summary> /// heap-sort, heapify.<para/> /// this function can be called recursively /// </summary> void Heapify(int index); }; #endif template<typename TKey, typename TValue> void MinHeap<TKey, TValue>::Push(TKey key, TValue value) {//insert index if (IsEmpty()) {//if heap is empty m_vec.push_back(make_pair(key, value)); return; } //else m_vec.push_back(make_pair(key, value)); Heapify(1); //sorting } template<typename TKey, typename TValue> void MinHeap<TKey, TValue>::Pop() {//delete top index if (IsEmpty()) return; Heapify(-1); } template<typename TKey, typename TValue> bool MinHeap<TKey, TValue>::IsEmpty() {//heap is empty? if (m_vec.size() != 1) return false; else return true; } template<typename TKey, typename TValue> std::pair<TKey, TValue> MinHeap<TKey, TValue>::Top() {//return top index return m_vec[1]; } template<typename TKey, typename TValue> std::pair<TKey, TValue> MinHeap<TKey, TValue>::Get(TValue target) {//find index in heap for (int i = 0; i < m_vec.size(); i++) { if (target == m_vec.at(i).second) { return m_vec[i]; } } return m_vec[0]; // not exist = cant found } template<typename TKey, typename TValue> void MinHeap<TKey, TValue>::DecKey(TValue target, TKey newKey) { int i; for (i = 0; i < m_vec.size(); i++) { if (target == m_vec.at(i).second) { m_vec.at(i).first = newKey; // change distance of select key } } pair<TKey, TValue> p = m_vec[i - 1]; // new key and new value int c = i - 1; while (c != 1 && m_vec[c / 2].first>m_vec[i - 1].first) // find insertion location { m_vec[c].first = m_vec[c / 2].first; m_vec[c].second = m_vec[c / 2].second; c /= 2; } // insert new key and new value m_vec[c].first = p.first; m_vec[c].second = p.second; return; } template<typename TKey, typename TValue> void MinHeap<TKey, TValue>::Heapify(int index) {//heap - sorting if (index == 1) {//Push case pair<TKey, TValue> p = m_vec[m_vec.size() - 1]; int a = m_vec.size() - 1; while (a != 1 && m_vec[a / 2].first>m_vec.back().first) // push Sorting { m_vec[a].first = m_vec[a / 2].first; m_vec[a].second = m_vec[a / 2].second; a /= 2; } m_vec[a].first = p.first; // push insert m_vec[a].second = p.second; } else if (index == -1) {//Pop case int a = 1; int b = 2; pair<TKey, TValue> p = m_vec[m_vec.size() - 1]; while (b <= m_vec.size() - 1) // pop sorting { if (b<m_vec.size() - 1 && m_vec[b].first > m_vec[b + 1].first) b++; if (p.first <= m_vec[b].first) break; m_vec[a].first = m_vec[b].first; m_vec[a].second = m_vec[b].second; a = b; b *= 2; } m_vec[a].first = p.first; // pop insert m_vec[a].second = p.second; m_vec.resize(m_vec.size() - 1); } } //#pragma once <file_sep># DS ## Project_01 ### 축구 구단 관리 프로그램 ## Project_02 ### 여행 일정 관리 프로그램 ## Project_03 ### 섬 그래프를 이용하여 최단 경로 찾기 프로그램 # OOP ## 과제 1-1 ~ 3-5 ## 프로젝트 ### 2048 MFC <file_sep>#pragma once #include "pch.h" #include "Block.h" class Board { private: Block* Block_Header; public: Board(); ~Board(); bool Up(); bool Down(); bool Left(); bool Right(); bool Put_random_num2();//declare bool Check_block();//declare void printBoard(int count, CFile& outfile, int menu);//declare Block* getBlock_x_y(int x, int y);//declare void swap(Block* pPivot, char d);//declare bool Check_win();//win check bool Check_fail();//fail check Block* getHead();//헤드를 반환 //rotation - 시계방향 또는 반시계방향 void rotation_time(); void rotation_reverse_time(); };<file_sep>축구 구단 관리 프로그램 ============= ## 1. Introduction 프로젝트는 BST(Binary Search Tree)를 이용하여 축구 구단 관리 프로그램을 구현하는 프로젝트다. 감독의 입장으로서 선수 명단(ShootForLog.txt)으로 구단주에게 받은돈으로 가장 강력한 팀을 꾸릴 수 있도록 한다. 선수 명단에 저장된 선수에 대한 정보는각 선수의 이름(name), 포지션(position), 이적료(fee), 능력치(ability)로 구성 되어있다. 이름은 영문으로 저장되어 있으며 포지션의 종류는 forward(공격수), Midfielder(미드필더), Defender(수비수), Goalkeeper(골키퍼)로 총 4개의 포지션이 있고 이적료는 정수의 값으로 저장을 받는다. 또한 같은 포지션 내에 이적료가 같은 선수는 존재하지 않으며 이적료 와 능력치는 비례하지 않는다. 능력치의 범위는 1~99이며 같은 포지션내에서 능력치가 서로 같은 선수는 존재 하지 않는다. 본프로젝트의 핵심 요소는 BST의 기능을 구현하며 Best_team을 만드는 것에 있다고 생각 한다. Bestteam은 4명의 선수로 구성 되어있고 공격수 1명, 미드필더 1명, 수비수 1명, 골 키퍼 1명으로 각 포지션별로 한 명을 뽑는다. 뽑은 선수들의 이적료 합은 구단주가 준 돈 (m_budget)보다 작거나 같아야 하며 능력치의 합이 가장 높은 team이 bestteam이 된다. 만약 능력치의 합이 가장 높은 두 개 이상의 팀이 존재 한다면 이적료의 합이 가장 적은 팀이 best_team이 된다. ## 2. Algorithm ### 2.1 Set up 프로그램 실행 시 두개의 입력이 존재하는데 처음은 ShootForLog.txt로서 선수의 명단을 불러오고 두 번째는 구단주에게 받은 돈의 액수(억)이다. 여기서 두 번째 입력 즉 구단주 에게 받은 돈은 최소 1664억 이상이다. 프로그램 실행 시 선수 명단을 읽고 선수들의 정보를 포지션에 따라 4개의 BST에 저장 하도록 한다. 각 BST의 루트는 선수 명단에 데이터 순으로 처음 나타나는 포지션에 해당 하는 선수가 해당 포지션 별 BST의 루트 노드가 된다. 먼저 텍스트 파일을 읽어서 각 포지션별로 insert를 해준다. 움직여야할 노드를 만들어주고 그 노드의 부모노드까지 같이 만들어 준다.만약 루트가 NULL이면 즉 데이터가 없으면 루트에 플레이어를 넣고 리턴한다. 루트 노드가 비어있지 않으면 들어가야할 노드의 위치를 탐색하는 while문을 만들어 준다. 만약 insert 하는 데이터의 값이 현재 p가 있는 위치보다 작으면 왼쪽으로 가고 크면 오른 쪽으로 가게 하는 트리의 습성을 이용한다. 위치를 찾고 리프노드를 찾으면 리프노드보다 작으면 왼쪽에 데이터를 넣어주고 크면 오른쪽에 데이터를 넣어준다. ### 2.2 Print Players 데이터를 저장 후 데이터를 inorder방식으로 순회하며 선수 목록을 출력한다. 출력 순서는 fw, mf, df, gk이다. ```C++ if(node != NULL) { os << node->m_left; os << node->m_data << std::endl; os << node-> m_right; } ``` 맨 처음 operation 부분. 먼저 루트가 널일때까지 루트를 넣어서 재귀적으로 도는 함 수다.노드가 맨 왼쪽으로 이동을 한 뒤 그 다음 출력부분을 실행 해주고 왼쪽 노드가 없으 면 오른쪽 노드로 가는 방식이다. ### 2.3 Search the Best Team & Delete best team player 각 포지션 별로 선수 한 명을 선별하며 현재 보유한 재산으로 구매 가능한 가장 강력 한 팀을 찾아낸다. 탐색이 끝나면 포지션 별로 가장 강력한 팀의 존재하는 선수들의 정보를 제거한다. 이 후 가장 강력한 팀을 출력하고 포지션 별로 선수 목록을 출력한 다. 여기서 선수 목록은 정보가 제거 된 후이다. BST로부터 선수를 제거할 때 제거될 노드가 left 서브트리와 right 서브트리를 같는 경우 left서브트리 내에서 가장 큰 능력치를 갖는 노드를 찾고 해당 노드를 제거될 노 드에 위치시키도록 한다. 각 포지션별로 한 명씩 돌아가면서 만들 수 있는 모든 조합을 만들면서 비교하는 알 고리즘으로 첫 번째 if 문에는 각배열을 돌면서 선수의 이적료 합이 구단주에게 받은 돈 (m_budget)보다 작아야 다음 조건으로 갈 수 있다.두 번째 if 문에는 능력치의 비교를 한다. 첫 번째 조건을 만족한 팀의 능력치의 합이 기존에 있던 sum_ability보다 크거나 같으면 다음 if으로 넘어 간다. 능력치가 같을 경우일 때를 먼저 고려해주었다.만약 능력치가 같더라도 더 낮은 이적료를 가진 팀이 더욱 강력한 팀이기에 비교를 해주고 다음 조건으로 넘어간다. 능력치가 같고 더 낮은 이적료를 가진 팀이 있다면 best팀의 선수들을 현재의 선수들로 바꿔준다. 만약 두 번째 능력치가 같지 않고 더 크다면 같을 때를 고려하지 않고 바로 best팀의 선수들을 현재의 선수들로 바꿔준다. ## 3. Result Screen Make로 실행파일(run)을 만들어 준 뒤 첫번째 인자 즉 argv[1]에는 선수 명단인 ShootForLog.txt를 넣어주고 두 번째 인자(argv[2])에는 감독에게 받은 이적료를 넣어 줬다. 맨 처음 출력은 공격수, 미드필더, 수비수, 골키퍼 순으로 inorder순회로 출력해준다. 능력치 기준으로 노드가 생성이 됐기 때문에 작은 능력치부터 큰 능력치로 오름차 순 출력이 된 것을 확인할 수 있다. 다음으로 출력 된 것은 best team의 선수 명단이다. 역시 공격수, 미드필더, 수비수, 골키 퍼 순으로 출력이 되었고 4400의 인자를 주었을 때 프로젝트 제안서와 같은 결과를 얻은 것을 확인할 수 있다. 마지막 출력 부분은 베스트팀에 있는 선수들이 모두 삭제가 된 후의 선수 명단이다. 공격 수에서 Messi의 정보가 빠지고 미드 필더에서 Kang in의 정보가 수비수에선 Alves의 정보 가 빠진 것을 확인할 수 있다. 골키퍼에는 단 한 명의 골키퍼 밖에 존재하지 않았기 때문 에 Jeong Sung-Ryong이 빠진 후 다른 정보가 없는 것을 확인할 수 있다. ## 4. Consideration 이번 프로젝트를 진행하면서 BST를 구현하는 것에는 크게 어려움이 없었으나, operation 을 이용하는 것은 처음이라 애를 먹은 기억이 있다. 하지만 이것저것 하다 보니 얼떨결에 됐고 그것을 기반으로 수행할 수 있었다. 그리고 operation에 대한 개념도 찾아보면서 공 부가 되었다. 또 한가지 애를 먹었던 점은 best_team을 만드는 것 이였다. 처음엔 가성비 를 따지는 건지 너무 어렵게 생각했던 나머지 생각이 잘 나지 않았고 제안서를 몇 번이 나 다시 읽은 결과 그저 조건만 만족하면 되겠구나 생각이 났다 이 부분이 제일 오래 걸 렸다. 마지막으로 BST의 삭제부분은 아직도 헷갈리는 부분이 있다. 개념은 어렵지 않지만 신경 써줘야 하는 부분도 많고 경우의 수도 몇 가지가 있기 때문이다. 전체적으로 코드를 구현하기보다 메모리 해제나 초기화, 사소하지만 중요한 것 들에서 애를 먹었다. <file_sep>#include <iostream> using namespace std; int main() { cout << "Enter the string : "; char str[100] = { NULL, }; cin.getline(str, 100, '\n');//get string for (int a = 0; a<100; a++) { if (str[a] == NULL) continue;//if no text continue; else if (str[a] >= 65 && str[a] <= 90) {//or if stra[a] is capital letter str[a] += 32; //plus 32 to make small letter } else if (str[a] >= 97 && str[a] <= 122) {//if str[a] is small letter str[a] -= 32; //minus 32 to make capital letter } } int a, b; char c; for (a = 0,b=strlen(str)-1; a<b; a++,b--) { if (str[a] != NULL) {//if str[a] is not a null c = str[a];//temp str[a] = str[b];//swap str[b] = c;//relocation } } cout << "Result : "; cout << str;//print }<file_sep>//#pragma once #ifndef STACK_H #define STACK_H #ifndef NULL #define NULL 0 #endif template <typename T> class Stack { private: class StackNode { public: T Data; StackNode* pNext; StackNode(T data) : Data(data), pNext(NULL) {} }; private: // the head pointer of the stack StackNode * m_pTop; public: Stack(); ~Stack(); /// <summary> /// push the data into this stack /// </summary> /// /// <param name="data"> /// a data to push into this stack /// </param> void Push(T data); /// <summary> /// pop(remove) the last-in data from this stack /// </summary> void Pop(); /// <summary> /// get the last-in data of this stack /// </summary> /// /// <returns> /// the last-in data of this stack /// </returns> T Top(); /// <summary> /// check whether this stack is empty or not. /// </summary> /// /// <returns> /// true if this stack is empty. /// false otherwise. /// </returns> bool IsEmpty(); }; #endif // stack class constructor template <class T> Stack<T>::Stack() { m_pTop = NULL; } // stack class destructor template <class T> Stack<T>::~Stack() { StackNode*cur = NULL; StackNode*prev_cur = NULL; while (m_pTop) // all stack node memory free { prev_cur = m_pTop; cur = m_pTop; while (cur->pNext) { prev_cur = cur; cur = cur->pNext; } prev_cur->pNext = NULL; if (cur == m_pTop) { delete cur; m_pTop = NULL; return; } delete cur; } } /// push the data into this stack template <class T> void Stack<T>::Push(T data) { StackNode*prev_top = m_pTop; StackNode*cur = new StackNode(data); if (prev_top == NULL) // empty stack { m_pTop = cur; return; } cur->pNext = m_pTop; m_pTop = cur; } /// pop(remove) the last-in data from this stack template <class T> void Stack<T>::Pop() { StackNode*prev_top = m_pTop; if (IsEmpty()) // empty stack return; if (prev_top->pNext == NULL) // There is only one stack node on the stack { delete prev_top; m_pTop = NULL; return; } m_pTop = prev_top->pNext; delete prev_top; return; } /// check whether this stack is empty or not. template <class T> bool Stack<T>::IsEmpty() { if (m_pTop == NULL) return true; else return false; } /// get the last-in data of this stack template <class T> T Stack<T>::Top() { return m_pTop->Data; } <file_sep>#include <iostream> using namespace std; class Pharmacist {//declare class public: int mask = 5; int price = 1000; }; class Buyer {//declare class public: int num = 0; int money = 3000; int mask_num = 0; int buy_mask_num = 0; }; void menu() {//print menu cout << " 0. 프로그램 종료" << endl; cout << " 1. 마스크 재고 물어보기" << endl; cout << " 2. 마스크 가격 물어보기" << endl; cout << " 3. 마스크 구매하기" << endl; cout << " 4. 내 마스크 갯수 확인하기" << endl; cout << " 5. 내 지갑 확인하기" << endl; } int main() { Buyer costomer; Pharmacist sales; while (1) { menu();//print menu cin >> costomer.num;//get num of menu if (costomer.num == 0) break; else if (costomer.num == 1) {//if num is 1 cout << " 남은 마스크 갯수: " << sales.mask << "개" << endl; cout << endl; } else if (costomer.num == 2) {//if num is 2 cout << " 마스크 가격: " << sales.price << "원" << endl; cout << endl; } else if (costomer.num == 3) {//if num is 3 cout << " 몇 개를 구매하시겠습니까?" << endl; cin >> costomer.buy_mask_num;//get num of mask if (sales.mask - costomer.buy_mask_num < 0 && costomer.money - costomer.buy_mask_num * sales.price < 0) {//if number of mask is larger than left mask and not enough money cout << " 마스크 재고와 잔액 모두 부족합니다." << endl; cout << endl; } else if (sales.mask - costomer.buy_mask_num < 0) {//if mask no mask cout << " 마스크 재고가 부족합니다." << endl; cout << endl; } else if (costomer.money - costomer.buy_mask_num * sales.price < 0) {//no money cout << " 잔액이 부족합니다." << endl; cout << endl; } else {//costomer buy the mask cout << " " << costomer.buy_mask_num << "개를 구매 완료." << endl; cout << endl; sales.mask = sales.mask - costomer.buy_mask_num;//update mask num costomer.money = costomer.money - costomer.buy_mask_num * sales.price;//update money of left costomer.mask_num += costomer.buy_mask_num;//update mask num } } else if (costomer.num == 4) {//if num is 4 cout << " 내 마스크 갯수: " << costomer.mask_num << "개" << endl; cout << endl; } else if (costomer.num == 5) {//if num is 5 cout << " 내 잔액: " << costomer.money << "원" << endl; cout << endl; } } return 0; } <file_sep>#include "BSTNode.h" BSTNode::BSTNode() { this->pLeft = nullptr;//set this->pRight = nullptr;//set this->pNext = nullptr;//set this->data = 0;//set } BSTNode::BSTNode(int Data) { this->pLeft = nullptr;//set this->pRight = nullptr;//set this->pNext = nullptr;//set this->data = Data;//set } BSTNode::~BSTNode() { } void BSTNode::SetLeft(BSTNode* Left) { this->pLeft = Left;//set } void BSTNode::SetRight(BSTNode* Right) { this->pRight = Right;//set } void BSTNode::SetNext(BSTNode* Next) { this->pNext = Next; }//set void BSTNode::SetData(int Data) { this->data = Data;//set } BSTNode* BSTNode::GetLeft() { return this->pLeft;//set } BSTNode* BSTNode::GetRight() {//set return this->pRight; } BSTNode* BSTNode::GetNext() {//set return this->pNext; } int BSTNode::GetData() {//set return this->data; }<file_sep>#include <iostream> using namespace std; int main() { char type;//declare int text=0;//declare int call=0;//declare int extra_text=0;//declare int extra_call=0;//declare int fee = 0;//declare cout << "Which type: "; cin >> type;//get type cout << "Text: "; cin >> text;//get text cout << "CALL : "; cin >> call;// get call cout << "=========" << endl;; cout << "Result" << endl;; if (type == 'A') {//if type is A if (text - 100 > 0) {//if used text is more than 100 extra_text = (text - 100) * 20;//count extra text fee } else {//smaller than 100 extra_text = 0;//no extra fee of text } if (call - 60 > 0) {//if used call is more than 60 extra_call = (call - 60) * 180;//count textra call fee } else {//smaller than 60 extra_call = 0;//no extra fee of call } fee = 10000;//basic fee is 10000 } else if (type == 'B') {//if type is B if (text - 150 > 0) {//if used text is more than 150 extra_text = (text - 150) * 15;//count extra text fee } else { extra_text = 0;//no extra fee of text } if (call - 90 > 0) {//if used call is more than 90 extra_call = (call - 90) * 150;//count textra call fee } else { extra_call = 0;//no extra fee of call } fee = 15000;//basic fee is 15000 } else if (type == 'C') { if (text - 200 > 0) {//if used text is more than 100 extra_text = (text - 200) * 10;//count extra text fee } else { extra_text = 0;//no extra fee of text } if (call - 120 > 0) {//if used call is more than 120 extra_call = (call - 120) * 60;//count textra call fee } else { extra_call = 0;//no extra fee of call } fee = 20000;//basic fee is 20000 } else if (type == 'D') { if (text - 250 > 0) {//if used text is more than 100 extra_text = (text - 250) * 5;//count extra text fee } else { extra_text = 0;//no extra fee of text } if (call - 150 > 0) {//if used call is more than 150 extra_call = (call - 150) * 30;//no extra fee of call } else { extra_call = 0;//no extra fee of call } fee = 25000;//basic fee is 25000 } cout << "Extra text: " << extra_text << endl; cout << "Extra call: " << extra_call << endl; cout << "Total: " << extra_text + extra_call+fee;//get total fee extra call,text and basic fee }<file_sep>#include <iostream> #include "BSTNode.h" #include "Queue.h" #include <vector> using namespace std; void print_menu() { cout << "1. Preorder" << endl; cout << "2. Inorder" << endl; cout << "3. Postorder" << endl; cout << "4. Exit" << endl; cout << "Select Number : "; } int main(void) { vector<int> input;//set Queue* q = new Queue;//set int size = 0;//set int n_input = 0;//set cout << "Enter Input Size: "; cin >> size; cout << "Enter a number: "; for (int i = 0; i < size; i++) { cin >> n_input; input.push_back(n_input);//insert } for (int i = 0; i < input.size(); i++) { BSTNode* newNode = new BSTNode(input[i]);//set q->Push(newNode);//push } while (1) { int user_input = 0; print_menu(); cin >> user_input; cout << endl; if (user_input == 1) { cout << "Preorder : "; q->Preorder(q->Front());//preorder cout << endl<<endl; } else if (user_input == 2) { cout << "Inorder : "; q->Inorder(q->Front());//inorder cout << endl<<endl; } else if (user_input == 3) { cout << "Postorder : "; q->Postorder(q->Front());//front cout << endl<<endl; } else if (user_input == 4) { cout << endl; cout << "End of Program." << endl; break; } } return 0; }<file_sep>#define _CRT_SECURE_NO_WARNINGS #pragma once #include <fstream> #include "List.h" #include <iostream> #include <string> #include <cstring> using namespace std; void print_menu(); int main() { int user_input = 0; List list; while (user_input != 7) { //while until input is 7 print_menu();//print menu cin >> user_input; cout << endl; if (user_input == 1) {//LOAD string dir = "input.txt"; ifstream in(dir); string line; char buf[100]; string cate2; string menu2; while (getline(in, line)) { strcpy(buf, line.c_str()); char* cate1 = strtok(buf, "\t");//get cate char* menu1 = strtok(NULL,"\t");//get menu char* price = strtok(NULL, "\t");//get price if (strcmp(cate1,"CATEGORY")==0) { continue; } if (cate1 == NULL) {//is cate is null error cout <<menu1<< " invalid input!" << endl<<endl; continue; } else if (menu1 == NULL) {//menu and price is null cout << cate1<< " invalid input!" << endl << endl; continue; } else if (price == NULL) {//price is null cout << menu1 << " invalid input!" << endl << endl; continue; } cate2 = string(cate1);//set menu2 = string(menu1);//set int pri = atoi(price);//set Node* n_node = new Node;//make node n_node->cate = cate2;//set n_node->menu = menu2;//set n_node->price = pri;//set if (list.menu_search(n_node) == true) {//if menu is exist cout << menu2 << " already exists!" << endl << endl; continue; } list.add(n_node);//insert } cout << "LOAD Success!" << endl << endl; } else if (user_input == 2) {//PRINT if (list.print() == false) {//if print is false cout << "The data does not exist!" << endl; cout << endl; user_input = 0; continue; } } else if (user_input == 3) {//INSERT string user_txt; cout << "Enter Category, Menu and Price : " ; cin.ignore(100, '\n'); getline(cin, user_txt); char buf[100];//declare string cate2;//declare string menu2;//declare strcpy(buf, user_txt.c_str());//set char* cate1 = strtok(buf, " ");//get cate char* menu1 = strtok(NULL, " ");//get menu char* price = strtok(NULL, " ");//get price if (cate1 == NULL || price == NULL) {//cate and price is null cout << cate1 << " invalid input!" << endl << endl; continue; } cate2 = string(cate1);//set menu2 = string(menu1);//set int pri = atoi(price);//set Node* n_node = new Node;//set n_node->cate = cate2;//set n_node->menu = menu2;//set n_node->price = pri;//set if (list.menu_search(n_node) == true) {//exist cout << menu2 << " already exists!" << endl << endl; continue; } list.add(n_node); cout << "Insert Success!" << endl << endl; user_input = 0; } else if (user_input == 4) {//Category SEARCH string user_txt; cout << "Enter Category which you want to find : "; cin.ignore(100, '\n'); getline(cin, user_txt); if (list.search_cate(user_txt) == false) {//if search is false cout << "No search data" << endl << endl; continue; } } else if (user_input == 5) {//Menu SEARCH string user_txt; cout << "Enter Menu which you want to find : "; cin.ignore(100, '\n'); getline(cin, user_txt); if (list.search_menu(user_txt) == false) {//if search is false cout << "No search data" << endl << endl; continue; } } else if (user_input == 6) {//DELETE string user_txt; cout << "Enter Menu which you want to delete : "; cin.ignore(100, '\n'); getline(cin, user_txt); if (list.delete_menu(user_txt) == false) {//if search is false cout << "No search data" << endl << endl; continue; } } else if (user_input == 7) {//End of Program! cout << endl << "End of Program." << endl; exit(0); } else { exit(0); } user_input = 0; } } void print_menu() { cout << "1.LOAD" << endl; cout << "2.PRINT" << endl; cout << "3.INSERT" << endl; cout << "4.Category SEARCH" << endl; cout << "5.Menu SEARCH" << endl; cout << "6.DELETE" << endl; cout << "7.End of Program!" << endl; cout << "Select Number : "; } <file_sep>#define _CRT_SECURE_NO_WARNINGS #pragma warning(disable : 4244) #include <iostream> #include <string> #include <cmath> using namespace std; class Exchange {//declare super class public://declare public index double before_m = 0; double after_m = 0; char before_c[50] = {NULL,}; char after_c[50] = {NULL,}; char answer = 'Y'; int KRW = 1; int USD = 1200; int JPY = 11; int EUR = 1300; int CNY = 170; Exchange() { } ~Exchange() { } }; class ToKRW : public Exchange { public: int before_KRW(char a[50],double b) {//defore KRW func strcpy(after_c, a); before_m = b; if (strcmp(after_c, "USD") == 0) {//if after country is USD after_m = before_m /USD; } else if (strcmp(after_c, "JPY") == 0) {//if after country is JPY after_m = before_m /JPY; } else if (strcmp(after_c, "EUR") == 0) {//if after country is EUR after_m = before_m / EUR; } else if (strcmp(after_c, "CNY") == 0) {//if after country is CNY after_m = before_m /CNY; } return round(after_m); } }; class ToUSD : public Exchange { public: int before_USD(char a[50], double b) { strcpy(after_c, a); before_m = b; if (strcmp(after_c, "KRW") == 0) {//if after country is KRW after_m = before_m * 1200;//before_m *(USD/KRW) } else if (strcmp(after_c, "JPY") == 0) {//if after country is JPY after_m = before_m * 109.091;//before_m *(USD/JPY) } else if (strcmp(after_c, "EUR") == 0) {//if after country is EUR after_m = before_m * 0.923;//before_m *(USD/EUR) } else if (strcmp(after_c, "CNY") == 0) {//if after country is CNY after_m = before_m * 7.059;//before_m *(USD/CNY) } return round(after_m); } }; class ToJPY : public Exchange { public: int before_JPY(char a[50], double b) { strcpy(after_c, a); before_m = b; if (strcmp(after_c, "USD") == 0) {//if after country is USD after_m = before_m * 0.009; } else if (strcmp(after_c, "KRW") == 0) {//if after country is KRW after_m = before_m * 11; } else if (strcmp(after_c, "EUR") == 0) {//if after country is EUR after_m = before_m * 0.008; } else if (strcmp(after_c, "CNY") == 0) {//if after country is CNY after_m = before_m / 0.064; } return round(after_m); } }; class ToEUR : public Exchange { public: int before_EUR(char a[50], double b) { strcpy(after_c, a); before_m = b; if (strcmp(after_c, "USD") == 0) {//if after country is USD after_m = before_m * 1.083; } else if (strcmp(after_c, "JPY") == 0) {//if after country is JPY after_m = before_m / 118.182; } else if (strcmp(after_c, "KRW") == 0) {//if after country is KRW after_m = before_m * 1300; } else if (strcmp(after_c, "CNY") == 0) {//if after country is CNY after_m = before_m * 7.647; } return round(after_m); } }; class ToCNY : public Exchange { public: int before_CNY(char a[50], double b) { strcpy(after_c, a); before_m = b; if (strcmp(after_c, "USD") == 0) {//if after country is USD after_m = before_m / 0.142; } else if (strcmp(after_c, "JPY") == 0) {//if after country is JPY after_m = before_m / 15.455; } else if (strcmp(after_c, "EUR") == 0) {//if after country is EUR after_m = before_m / 0.131; } else if (strcmp(after_c, "KRW") == 0) {//if after country is KRW after_m = before_m * 170; } return round(after_m); } }; int main() { Exchange money; ToKRW KRW; ToUSD USD; ToJPY JPY; ToEUR EUR; ToCNY CNY; int after =0; while (money.answer=='Y'|| money.answer == 'y')//while until user input is y { char want[50]; char* temp[4] = {NULL,}; int cnt = 0; cout << "”ŚCurrency Converter”Ś" << endl; cout << "e.g. [Price] KRW to USD" << endl; cout << endl; cin.getline(want, 50);//get input char* tmp = strtok(want, " "); while (tmp != NULL) {//tok price, before country, after country temp[cnt] = tmp; tmp = strtok(NULL, " "); cnt++; } strcpy(money.after_c,temp[3]); money.before_m=atoi(temp[0]); if (strcmp(money.after_c, "KRW")==0 || strcmp(money.after_c, "USD") == 0 || strcmp(money.after_c, "JPY") == 0 || strcmp(money.after_c, "EUR") == 0 || strcmp(money.after_c, "CNY") == 0) {//if after country is KRW, USD,EUR,CNY,JPY if (strcmp(temp[1], "KRW") == 0) {//if before country is KRW after = KRW.before_KRW(money.after_c, money.before_m); } else if (strcmp(temp[1], "USD") == 0) {//if before country is USD after = USD.before_USD(money.after_c, money.before_m); } else if (strcmp(temp[1], "JPY") == 0) {//if before country is JPY after = JPY.before_JPY(money.after_c, money.before_m); } else if (strcmp(temp[1], "EUR") == 0) {//if before country is EUR after = EUR.before_EUR(money.after_c, money.before_m); } else if (strcmp(temp[1], "CNY") == 0) {//if before country is CNY after = CNY.before_CNY(money.after_c, money.before_m); } else {//no country like that cout << "Input error"; break; } } else {//no country like that cout << "Input error"; break; } cout << after <<" "<<temp[3]<<endl; cout << endl; cout << "Would you like to continue? (Y/N)" << endl; cin >> money.answer;//get answer cin.ignore();//reset cin if (money.answer == 'N' || money.answer == 'n') {//if answer is N or n cout << "Bye!"; break; } } }
d367e7ceb45fbf9f7525f361dc3f935a336b89a8
[ "Markdown", "C", "C++" ]
70
C++
edoll1843/sophomoreProject
a29c56622eb78e6e57e0fb7267dec14dff63b8c8
36ce93ba7525d46f6991fb31d05ebc36742853ce
refs/heads/main
<repo_name>davesavedaday/Computational-Psychology-2021-<file_sep>/README.md # Computational-Model-for-BRAT Here, we compare 4 different models for the Balloon Risk Aversion Task (BRAT), a variation of the Balloon Analog Risk Task (BART). All the models were fitted through both hierarchal Bayesian Inference and Maximum Likelihood Estimation. Files related to MLE are located in the MLE folder. All the fitted samples in either rds or RData format can be found in a link in the presentation explaining reproducibility. Model 2 showed to be best model out of the four. <file_sep>/brat_Bayes.R # rm(list=ls()) # graphics.off() library(rstan) library(bayesplot) library(loo) options(mc.cores = parallel::detectCores()) dat = read.table("export_brat_time1(n=20).txt", header = T) dat_shortened = read.table("export_brat_time1(n=2).txt", header = T) allSubjs <- unique(dat_shortened$Subject) N <- length(allSubjs) T <- table(dat_shortened$Subject)[1] numPars <- 5 Tsubj <- numeric() for(i in 1:N) { Tsubj = c(Tsubj, table(dat_shortened$Subject)[i]) } dataList <- list( N = N, T = T, I = 128, Tsubj = Tsubj, pumps = matrix(nrow = N, dat_shortened$pumped), explosion = matrix(nrow = N, dat_shortened$explosion) ) fit_1 = stan("brat_model1.stan", data = dataList, pars = c("mu_pr", "phi_pr", "eta_pr", "gam_pr", "tau_pr"), include = FALSE, iter = 3000, warmup = 1000, chains=4, cores=4, seed = "1000") fit_2 = stan("brat_model2.stan", data = dataList, pars = c("mu_pr", "phi_pr", "eta_pr", "gam_pr", "tau_pr"), include = FALSE, iter = 3000, warmup = 1000, chains=4, cores=4, seed = "1000") fit_3 = stan("brat_model3.stan", data = dataList, pars = c("mu_pr", "phi_pr", "eta_pr", "gam_pr", "tau_pr"), include = FALSE, iter = 3000, warmup = 1000, chains=4, cores=4, seed = "1000") fit_4 = stan("brat_model4.stan", data = dataList, pars = c("mu_pr", "phi_pr", "eta_pr", "gam_pr", "tau_pr"), include = FALSE, iter = 3000, warmup = 1000, chains=4, cores=4, seed = "1000") loo1 <- loo(fit_1, save_psis = TRUE) loo2 <- loo(fit_2, save_psis = TRUE) loo3 <- loo(fit_3, save_psis = TRUE) loo4 <- loo(fit_4, save_psis = TRUE)<file_sep>/Parameter Recovery/simul_data_model2.R # rm(list=ls()) rtnorm <- function(n, mean, sd, a = -Inf, b = Inf){ qnorm(runif(n, pnorm(a, mean, sd), pnorm(b, mean, sd)), mean, sd) } softmax <- function(par){ n.par <- length(par) par1 <- sort(par, decreasing = TRUE) Lk <- par1[1] for (k in 1:(n.par-1)) { Lk <- max(par1[k+1], Lk) + log1p(exp(-abs(par1[k+1] - Lk))) } val <- exp(par - Lk) return(val) } set.seed(1000) num_subjs <- 50 num_trials <- 100 I <- 128 simul_pars = data.frame(phi_pos = rtnorm(num_subjs, 0.999, 0.05, a = 0, b = 1), eta_pos = rtnorm(num_subjs, 0.99, 0.15, a = 0), gam_pos = rtnorm(num_subjs, 0.02, 0.10, a = 0, b = 2), tau_pos = rtnorm(num_subjs, 0.5, 0.34, a = 0), subjID = 1:num_subjs) all_data <- NULL for( i in 1:num_subjs) { phi_pos <- simul_pars$phi_pos[i] eta_pos <- simul_pars$eta_pos[i] gam_pos <- simul_pars$gam_pos[i] tau_pos <- simul_pars$tau_pos[i] break_point = rtnorm(1, 64, 30, a = 0, b = I) n_succ = 0 n_total = 0 p = phi_pos tmp_data = data.frame(subjID = NULL, trial = NULL, pumped=NULL, explosion=NULL) curUtil <- rep(0, I) for( t in 1:num_trials) { p = (phi_pos + eta_pos * (n_total - n_succ )) / (1+ eta_pos * n_total) for(l in 1:I) { curUtil[l] =(1 - p^l) * (I - l)^gam_pos } deflation = sample(1:I, size = 1, replace = TRUE, prob = softmax(curUtil * tau_pos)) break_val = rnorm(1, mean = 64, sd = 20) if(I - deflation > break_val) { explosion = 1 } else { explosion = 0 n_succ = n_succ + deflation } n_total = n_total + deflation tmp_data[t, "subjID"] = i tmp_data[t, "trial"] = t tmp_data[t, "pumped"] = deflation tmp_data[t, "explosion"] = explosion } all_data = rbind(all_data, tmp_data) } write.table(all_data, file = "simul_data_model2.txt", row.names = FALSE, col.names = TRUE, sep = "\t") <file_sep>/brat_different_hyp.R rm(list=ls()) graphics.off() library(rstan) library(bayesplot) library(loo) options(mc.cores = parallel::detectCores()) dat = read.table("export_brat_time1(n=20).txt", header = T) dat_shortened = read.table("export_brat_time1(n=2).txt", header = T) allSubjs <- unique(dat$Subject) N <- length(allSubjs) T <- table(dat$Subject)[1] numPars <- 5 Tsubj <- numeric() for(i in 1:N) { Tsubj = c(Tsubj, table(dat$Subject)[i]) } dataList <- list( N = N, T = T, I = 128, Tsubj = Tsubj, pumps = matrix(nrow = N, dat$pumped), explosion = matrix(nrow = N, dat$explosion) ) fit_modified = stan("brat_model2(modified).stan", data = dataList, iter = 3000, warmup = 1000, chains =4, cores=4, seed = "1000") fit_no_indiv = stan("brat_model2(no_indiv).stan",data = dataList, iter = 3000, warmup = 1000, chains=4, cores=4, seed = "1000" ) fit_no_hier = stan("brat_model2(no_hier).stan", data= dataList, iter = 3000, warmup = 1000, chains=4, cores=4, seed = "1000") fit_hier = readRDS("fit_2.rds") <file_sep>/Parameter Recovery/simul_data_model2(no_indiv).R # rm(list=ls()) rtnorm <- function(n, mean, sd, a = -Inf, b = Inf){ qnorm(runif(n, pnorm(a, mean, sd), pnorm(b, mean, sd)), mean, sd) } softmax <- function(par){ n.par <- length(par) par1 <- sort(par, decreasing = TRUE) Lk <- par1[1] for (k in 1:(n.par-1)) { Lk <- max(par1[k+1], Lk) + log1p(exp(-abs(par1[k+1] - Lk))) } val <- exp(par - Lk) return(val) } set.seed(1000) num_subjs <- 10 num_trials <- 30 I <- 128 simul_pars = data.frame(subjID = 1:num_subjs) all_data <- NULL for( i in 1:num_subjs) { phi = 0.9965212 eta = 2.226753e-06 gam = 0.7808239 tau = 0.9526595 break_point = rtnorm(1, 64, 30, a = 0, b = I) n_succ = 0 n_total = 0 p = phi tmp_data = data.frame(subjID = NULL, trial = NULL, pumped=NULL, explosion=NULL) curUtil <- rep(0, I) for( t in 1:num_trials) { p = (phi + eta * (n_total - n_succ )) / (1+ eta * n_total) for(l in 1:I) { curUtil[l] =(1 - p^l) * (I - l)^gam } deflation = sample(1:I, size = 1, replace = TRUE, prob = softmax(curUtil * tau)) break_val = rnorm(1, mean = 64, sd = 20) if(I - deflation > break_val) { explosion = 1 } else { explosion = 0 n_succ = n_succ + deflation } n_total = n_total + deflation tmp_data[t, "subjID"] = i tmp_data[t, "trial"] = t tmp_data[t, "pumped"] = deflation tmp_data[t, "explosion"] = explosion } all_data = rbind(all_data, tmp_data) } write.table(all_data, file = "simul_data_model2(no_indiv).txt", row.names = FALSE, col.names = TRUE, sep = "\t") <file_sep>/MLE/MLE_model_function.R softmax <- function(par){ n.par <- length(par) par1 <- sort(par, decreasing = TRUE) Lk <- par1[1] for (k in 1:(n.par-1)) { Lk <- max(par1[k+1], Lk) + log1p(exp(-abs(par1[k+1] - Lk))) } val <- exp(par - Lk) return(val) } N = 20 T = 30 I = 128 mle_model1 <-function(param, data) { pump <- data[,3] explosion <- data[,7] sum_minusLL = 0 n_succ = 0 n_total = 0 p = param[1] curUtil = rep(0,I) for(t in 1:T) { p = 1- (param[1] + param[2] * (n_total - n_succ)) / (1+ param[2] * n_total) for(l in 1:I) { curUtil[l] = (1-p)^(I-l) * (I-l)^param[3] } prob = softmax(curUtil)[pump[t]] #Softmax function already normalized the value. prob = prob * 0.9998 + 0.0001 sum_minusLL = sum_minusLL -log(prob) } sum_minusLL } mle_model2 <-function(param, data) { pump <- data[,3] explosion <- data[,7] sum_minusLL = 0 n_succ = 0 n_total = 0 p = param[1] curUtil = rep(0,I) for(t in 1:T) { p = (param[1] + param[2] * n_succ) / (1+ param[2] * n_total) for(l in 1:I) { curUtil[l] = (1-p^l) * (I-l)^param[3] } prob = softmax(curUtil)[pump[t]] #Softmax function already normalized the value. prob = prob * 0.9998 + 0.0001 sum_minusLL = sum_minusLL -log(prob) } sum_minusLL } mle_model3 <-function(param, data) { pump <- data[,3] explosion <- data[,7] sum_minusLL = 0 n_succ = 0 n_total = 0 p = param[1] curUtil = rep(0,I) for(t in 1:T) { p = 1- (param[1] + param[2] * n_succ) / (1+ param[2] * n_total) for(l in 1:I) { curUtil[l] = -(1-p)^(I-l) * l^param[3] - (1-(1-p)^(I-l))* I^param[3] } prob = softmax(curUtil)[pump[t]] #Softmax function already normalized the value. prob = prob * 0.9998 + 0.0001 sum_minusLL = sum_minusLL -log(prob) } sum_minusLL } mle_model4 <-function(param, data) { pump <- data[,3] explosion <- data[,7] sum_minusLL = 0 n_succ = 0 n_total = 0 p = param[1] curUtil = rep(0,I) for(t in 1:T) { p = (param[1] + param[2] * n_succ) / (1 + param[2] * n_total) for(l in 1:I) { curUtil[l] = -(1-p^l) * l^param[3] - p^l * I^param[3] } prob = softmax(curUtil)[pump[t]] #Softmax function already normalized the value. prob = prob * 0.9998 + 0.0001 sum_minusLL = sum_minusLL -log(prob) } sum_minusLL } <file_sep>/Parameter Recovery/brat_recovery_model2.R # rm(list=ls()) # graphics.off() library(rstan) library(bayesplot) library(loo) options(mc.cores = parallel::detectCores()) sim_model2 = read.table("simul_data_model2.txt", header = T) allSubjs <- unique(sim_model2$subjID) N <- length(allSubjs) T <- table(sim_model2$subjID)[1] Tsubj <- numeric() for(i in 1:N) { Tsubj = c(Tsubj, table(sim_model2$subjID)[i]) } dataList <- list( N = N, T = T, I = 128, Tsubj = Tsubj, pumps = matrix(nrow = N, sim_model2$pumped), explosion = matrix(nrow = N, sim_model2$explosion) ) fit_2 = stan("brat_model2.stan", data = dataList, pars = c("mu_pr", "phi_pr", "eta_pr", "gam_pr", "tau_pr"), include = FALSE, iter = 2000, warmup = 1000, chains=2, cores=2, seed = "1000") parameters <- rstan::extract(fit_2) phi_mean = apply(parameters$phi, 2, mean) phi_sd = apply(parameters$phi, 2, sd) plot(simul_pars$phi_pos, phi_mean, xlim=c(0,1), ylim=c(0,1)); abline(0,1) arrows(x0=simul_pars$phi_pos, y0= phi_mean - phi_sd, y1= phi_mean + phi_sd, length=0.02, angle=90, code=3) eta_mean = apply(parameters$eta, 2, mean) eta_sd = apply(parameters$eta, 2, sd) plot(simul_pars$eta_pos, eta_mean, xlim=c(0,2), ylim=c(0,2)); abline(0,1) arrows(x0=simul_pars$eta_pos, y0= eta_mean - eta_sd, y1= phi_mean + eta_sd, length=0.02, angle=90, code=3) gam_mean = apply(parameters$gam, 2, mean) gam_sd = apply(parameters$gam, 2, sd) plot(simul_pars$gam_pos, gam_mean, xlim=c(0,0.3), ylim=c(0,0.3)); abline(0,1) arrows(x0=simul_pars$gam_pos, y0= gam_mean - gam_sd, y1= gam_mean + gam_sd, length=0.02, angle=90, code=3) tau_mean = apply(parameters$tau, 2, mean) tau_sd = apply(parameters$tau, 2, sd) plot(simul_pars$tau_pos, tau_mean, xlim=c(0,4), ylim=c(0,4)); abline(0,1) arrows(x0=simul_pars$tau_pos, y0= tau_mean - tau_sd, y1= tau_mean + tau_sd, length=0.02, angle=90, code=3) <file_sep>/MLE/MLE_Parm_Estm.R rm(list=ls()) graphics.off() source("MLE_model_function.R") dat = read.table("export_brat_time1(n=20).txt", header = T) allSubjs <- unique(dat$Subject) param_init <- runif(4) param_low <- c(0,0,0,0); param_up <- c(1,10,2,10) mle_model1_fit <- optim(param_init, mle_model1, method="L-BFGS-B", lower=param_low, upper=param_up, data=subset(dat, dat$Subject == 100)) mle_model2_fit <- optim(param_init, mle_model2, method="L-BFGS-B", lower=param_low, upper=param_up, data=subset(dat, dat$Subject == 100)) mle_model3_fit <- optim(param_init, mle_model3, method="L-BFGS-B", lower=param_low, upper=param_up, data=subset(dat, dat$Subject == 100)) mle_model4_fit <- optim(param_init, mle_model4, method="L-BFGS-B", lower=param_low, upper=param_up, data=subset(dat, dat$Subject == 100)) param_model1 <- array(numeric(), c(N,4)) param_model2 <- array(numeric(), c(N,4)) param_model3 <- array(numeric(), c(N,4)) param_model4 <- array(numeric(), c(N,4)) mle_model1_value <- array(numeric(), c(N,1)) mle_model2_value <- array(numeric(), c(N,1)) mle_model3_value <- array(numeric(), c(N,1)) mle_model4_value <- array(numeric(), c(N,1)) flag <- 1 for(i in allSubjs) { mle_model1_fit <- optim(param_init, mle_model1, method="L-BFGS-B", lower=param_low, upper=param_up, data=subset(dat, dat$Subject == i)) mle_model2_fit <- optim(param_init, mle_model2, method="L-BFGS-B", lower=param_low, upper=param_up, data=subset(dat, dat$Subject == i)) mle_model3_fit <- optim(param_init, mle_model3, method="L-BFGS-B", lower=param_low, upper=param_up, data=subset(dat, dat$Subject == i)) mle_model4_fit <- optim(param_init, mle_model4, method="L-BFGS-B", lower=param_low, upper=param_up, data=subset(dat, dat$Subject == i)) for(j in 1:10) { param_init <- runif(4) temp_mle_model1 <- optim(param_init, mle_model1, method="L-BFGS-B", lower=param_low, upper=param_up, data=subset(dat, dat$Subject == i)) temp_mle_model2 <- optim(param_init, mle_model2, method="L-BFGS-B", lower=param_low, upper=param_up, data=subset(dat, dat$Subject == i)) temp_mle_model3 <- optim(param_init, mle_model3, method="L-BFGS-B", lower=param_low, upper=param_up, data=subset(dat, dat$Subject == i)) temp_mle_model4 <- optim(param_init, mle_model4, method="L-BFGS-B", lower=param_low, upper=param_up, data=subset(dat, dat$Subject == i)) if(temp_mle_model1$value < mle_model1_fit$value) mle_model1_fit <- temp_mle_model1 if(temp_mle_model2$value < mle_model2_fit$value) mle_model2_fit <- temp_mle_model2 if(temp_mle_model3$value < mle_model3_fit$value) mle_model3_fit <- temp_mle_model3 if(temp_mle_model4$value < mle_model4_fit$value) mle_model4_fit <- temp_mle_model4 } param_model1[flag,] <- mle_model1_fit$par param_model2[flag,] <- mle_model2_fit$par param_model3[flag,] <- mle_model3_fit$par param_model4[flag,] <- mle_model4_fit$par mle_model1_value[flag,] <- mle_model1_fit$value mle_model2_value[flag,] <- mle_model2_fit$value mle_model3_value[flag,] <- mle_model3_fit$value mle_model4_value[flag,] <- mle_model4_fit$value flag = flag + 1 } # compute the AIC AIC_model1 <- 0 AIC_model2 <- 0 AIC_model3 <- 0 AIC_model4 <- 0 for(i in 1:N) { AIC_model1 = AIC_model1 + 2*mle_model1_value[i] + 2*4 AIC_model2 = AIC_model2 + 2*mle_model2_value[i] + 2*4 AIC_model3 = AIC_model3 + 2*mle_model3_value[i] + 2*4 AIC_model4 = AIC_model4 + 2*mle_model4_value[i] + 2*4 AIC_model1 = AIC_model1 / N AIC_model2 = AIC_model2 / N AIC_model3 = AIC_model3 / N AIC_model4 = AIC_model4 / N } # compute the BIC BIC_model1 <- 0 BIC_model2 <- 0 BIC_model3 <- 0 BIC_model4 <- 0 for(i in 1:N) { BIC_model1 = BIC_model1 + 2*mle_model1_value[i] + 4*log(T) BIC_model2 = BIC_model2 + 2*mle_model2_value[i] + 4*log(T) BIC_model3 = BIC_model3 + 2*mle_model3_value[i] + 4*log(T) BIC_model4 = BIC_model4 + 2*mle_model4_value[i] + 4*log(T) BIC_model1 = BIC_model1 / N BIC_model2 = BIC_model2 / N BIC_model3 = BIC_model3 / N BIC_model4 = BIC_model4 / N } # Generate summary all_AIC = round(c(AIC_model1, AIC_model2, AIC_model3, AIC_model4), 3) all_BIC = round(c(BIC_model1, BIC_model2, BIC_model3, BIC_model4), 3) names = c("model1", "model2", "model3", "model4") modelcomp_summary = data.frame(Models = names, AIC = all_AIC, BIC = all_BIC) print(modelcomp_summary) #Plot MLE against Bayesian Inference fit_2 <- readRDS("fit_2.rds") bayes_phi <- summary(fit_2, pars = "phi")$summary bayes_eta <- summary(fit_2, pars = "eta")$summary bayes_gam <- summary(fit_2, pars = "gam")$summary bayes_tau <- summary(fit_2, pars = "tau")$summary plot(bayes_phi[,1], param_model2[,1], xlab = "Bayesian Inference of phi", ylab = "MLE of phi" ,xlim = c(0,1), ylim = c(0,1)); abline(0,1); plot(bayes_eta[,1], param_model2[,2], xlab = "Bayesian Inference of eta", ylab = "MLE of eta" ,xlim = c(0,1), ylim = c(0,1)); abline(0,1); plot(bayes_gam[,1], param_model2[,3], xlab = "Bayesian Inference of gam", ylab = "MLE of gam" ,xlim = c(0,1), ylim = c(0,1)); abline(0,1); plot(bayes_tau[,1], param_model2[,4], xlab = "Bayesian Inference of tau", ylab = "MLE of tau"); abline(0,1)
8ce98fed0966af9524b0db5def581b8d7e761f26
[ "Markdown", "R" ]
8
Markdown
davesavedaday/Computational-Psychology-2021-
56937f390abe160c508b3371acb0a8226d9fde05
1e558b378a9c2945f2f65b2d4f560e3e9b997e78
refs/heads/master
<file_sep># -*- coding: utf-8 -*- #******************************************************* # Main.py # created by sawa on 2018/02/06. # Copyright © 2018 sawa. All rights reserved. #******************************************************* # HelloWorld import numpy as np import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt import vpython as vs import math as mat import random as rnd def main(): vs.box() if __name__ == "__main__": main() <file_sep># -*- coding: utf-8 -*- #******************************************************* # Q13.py # created by sawa on 2018/02/07. # Copyright © 2018 sawa. All rights reserved. #******************************************************* # 問題13 import numpy as np import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt import vpython as vs import math as mat import random as rnd def main(): print("問題13") setup() drow() #問題13: VisualPythonの適当な物体を選び,等速直線運動する物体をアニメーションしてみよ.(中略)等速直線運動する物体の他に最低一ケ,「動かない物体」をおいていくと良い.カメラの追随を禁止したければ,scene.autoscale = 0 とする.が,物体がシーン外にはみ出ると,画面から消えてしまうので使う際は注意が必要. def drow(): p = vs.vector(0, 0, 0) ball = vs.sphere(pos = p, radius = 2, color = vs.color.white) solidObj = vs.box(pos = vs.vector(-5, 0, 0), size = vs.vector(4, 4, 4), color = vs.color.black) while True: vs.rate(100) ball.pos = p p.x += 0.1 #x座標を進める p.z -= 0.1 #z座標を進める if p.x >= 50: #終了条件 ball.color = vs.color.red break def setup(): vs.scene.background = vs.color.white #白背景に vs.scene.autoscale = 0 #カメラの追随を禁止 if __name__ == "__main__": main() <file_sep># computational-science 計算科学の勉強用のプログラムを作成する予定. ## キーワード 計算科学,数理工学 ## 環境設定 ### VPythonの導入 次のサイトをを参考に導入する. * [VPython(公式)](http://vpython.org/) * [【VPython入門】使い方まとめ | アルゴリズム雑記](https://algorithm.joho.info/programming/python/vpython/) #### Windowsの場合 cmd上にて > pip install vpython でインストール可能. ## コンパイル方法 いずれの問題も > python Main.py でコンパイル可能. ## 参考サイト * [物理シミュレーションを通して学ぶプログラミング 田浦健次朗](https://www.eidos.ic.i.u-tokyo.ac.jp/~tau/lecture/computational_physics/) * [VPython Instructional Videos: 4. Loops and Animation](https://www.youtube.com/watch?v=cNdPqgNFeVk) vpythonでのアニメーションの作り方 * [VPython Instructional Videos: 5. Scalefactors](https://www.youtube.com/watch?v=wKGAfQrlYaU) ばねマスアニメーション作成の参考 * [Projectile Motion With Visual Python](https://www.youtube.com/watch?v=fzS8jaeI6BM) 放物運動の参考 <file_sep># -*- coding: utf-8 -*- #******************************************************* # Main.py # created by sawa on 2018/02/06. # Copyright © 2018 sawa. All rights reserved. #******************************************************* # 問題3 import numpy as np import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt import vpython as vs import math as mat import random as rnd def main(): setup() drow() #問題3: 正四面体の中に一個づつ球面がついている.以下のようなオブジェをvisual pythonで作れ(辺はcurveを適当につなげて書く).現在やっていることと関係無いように見えるが,「変数」を使うとすっきりと書ける例としてとりあげる. def drow(): rad = 0.1 #球の半径 #頂点座標 p1 = vs.vector(0, 0, mat.sqrt(3) / 2) p2 = vs.vector(-0.5, 0, 0) p3 = vs.vector(0.5, 0, 0) p4 = vs.vector(0, mat.sqrt(3) / 2, mat.sqrt(3) / 2 - 1 / mat.sqrt(3)) #頂点 vs.sphere(pos = p1, radius = rad, color = vs.color.white) vs.sphere(pos = p2, radius = rad, color = vs.color.red) vs.sphere(pos = p3, radius = rad, color = vs.color.yellow) vs.sphere(pos = p4, radius = rad, color = vs.color.blue) #辺 vs.curve(p1, p2) vs.curve(p1, p3) vs.curve(p1, p4) vs.curve(p2, p3) vs.curve(p2, p4) vs.curve(p3, p4) def setup(): vs.scene.title = "問題3" vs.scene.background = vs.color.white #白背景に if __name__ == "__main__": main() <file_sep># -*- coding: utf-8 -*- #******************************************************* # Main.py # created by sawa on 2018/02/06. # Copyright © 2018 sawa. All rights reserved. #******************************************************* # 問題11 import numpy as np import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt import vpython as vs import math as mat import random as rnd def main(): setup() drow() #問題11(乱数):乱数を用いて,球面x^2 + y^2 + z^2 = 1の球面上に多数のboxを配置して,以下のようなオブジェを作ってみよう. def drow(): n = 600 #箱の数 for i in range(n): d1 = rnd.random() * 2 * mat.pi #角度θ d2 = rnd.random() * 2 * mat.pi #角度φ x = mat.sin(d1) * mat.cos(d2) y = mat.sin(d1) * mat.sin(d2) z = mat.cos(d1) p = vs.vector(x, y, z) #プロットする座標 side = 0.05 #箱の一辺の長さ vs.box(pos = p, #座標 size = vs.vector(side, side, side), #大きさ axis = p, #軸 color = vs.color.green) #色 def setup(): vs.scene.title = "問題11" vs.scene.background = vs.color.white #白背景 if __name__ == "__main__": main() <file_sep># -*- coding: utf-8 -*- #******************************************************* # Main.py # created by sawa on 2018/02/06. # Copyright © 2018 sawa. All rights reserved. #******************************************************* # 問題12 import numpy as np import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt #import vpython as vs import math as mat import random as rnd def main(): print("問題12") print(montecarlo()) #問題12(おまけ:乱数を用いた積分): def montecarlo(): n = 10000 #プロットする点の数 c = 0 #球内部の点の数 for i in range(n): x = rnd.uniform(-1, 1) y = rnd.uniform(-1, 1) z = rnd.uniform(-1, 1) if x * x + y * y + z * z <= 1: c += 1 return 8 * c / n #体積2*2*2=8の立方体と比較 if __name__ == "__main__": main() <file_sep># -*- coding: utf-8 -*- #******************************************************* # Main.py # created by sawa on 2018/02/06. # Copyright © 2018 sawa. All rights reserved. #******************************************************* # 問題1,2 import numpy as np import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt #import vpython as vs import math as mat import random as rnd def main(): print("問題1") print(inner(1, 0, 1, 1)) print("問題2") print(angle(1, 0, 1, 1)) #問題1: 4つの数a,b,c,dを受け取り,ベクトル(a,b)と(c,d)の内積を計算する関数inner(a, b, c, d)を書き,適当な例を使って確かめよ. def inner(a, b, c, d): v1 = np.array([a, b]) v2 = np.array([c, d]) return np.dot(v1, v2) #問題2: 4つの数a,b,c,dを受け取り,ベクトル(a,b)と(c,d)のなす角を計算する関数angle(a, b, c, d)を書き,適当な例を使って確かめよ.前門で用いたinnerを使う.また,arccosはmathモジュールに,acosという関数が提供されている. def angle(a, b, c, d): innerVal = inner(a, b, c, d) v1 = np.array([a, b]) v2 = np.array([c, d]) v1norm = np.linalg.norm(v1) v2norm = np.linalg.norm(v2) product = v1norm * v2norm cos = innerVal / product return mat.acos(cos) / mat.pi * 180 if __name__ == "__main__": main() <file_sep># -*- coding: utf-8 -*- #******************************************************* # Main.py # created by sawa on 2018/02/06. # Copyright © 2018 sawa. All rights reserved. #******************************************************* # 問題9,10 import numpy as np import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt #import vpython as vs import math as mat import random as rnd def main(): print("問題9") print(ODEExample()) print("問題10") print(ODE()) #問題9(微分方程式): def ODEExample(): y_0 = 1000 return 1 #問題10(微分方程式): def ODE(): return 1 if __name__ == "__main__": main() <file_sep># -*- coding: utf-8 -*- #******************************************************* # Q14.py # created by sawa on 2018/02/07. # Copyright © 2018 sawa. All rights reserved. #******************************************************* # 問題14 import numpy as np import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt import vpython as vs import math as mat import random as rnd def main(): setup() #セットアップ drow() #繰り返し描画処理 #問題14: 重力に従って動く質点をアニメーションしてみよ.初期位置や初速を変えて,自由落下,打ち上げられたボールなどをアニメーションせよ.地面から打ち上げられてから,再び地面に付くまでの時間T_0を求め,時刻T_0におけるy座標がどれほど正確に求まるか(ほぼ0であってほしい),調べてみよ. def drow(): rate = 100 #時間レート ballRad = 2 #質点の半径(見た目だけ) #床の設定 floorLength = 200 floorThickness = 0.5 floorPos = vs.vector(floorLength / 2, - ballRad - floorThickness / 2 , 0) floor = vs.box(pos = floorPos, size = vs.vector(floorLength, floorThickness, 5), color = vs.color.black) x_0 = vs.vector(0, 0, 0) #初期座標 v_0 = vs.vector(1, 5, 0) #初速 g = 9.8 #重力加速度 t = 0 #時間 #質点の設定 ball = vs.sphere(pos = x_0, radius = ballRad, color = vs.color.white) p = ball.pos #質点の参照 while True: vs.rate(rate) if p.y < 0: #終了条件 ball.color = vs.color.red print("t = %f" % p.y) exit() #プログラムを終了 x = v_0.x * t + x_0.x y = - g * t * t / 2 + v_0.y * t + x_0.y p.x += x #x座標を進める p.y += y #y座標を進める ball.pos = p #ボールの座標を更新 t += 0.01 #時間を進める def setup(): vs.scene.title = "問題14" vs.scene.background = vs.color.white #白背景に vs.scene.center = vs.vector(100, 0, 10) #vs.scene.autoscale = 0 #カメラの追随を禁止 if __name__ == "__main__": main() <file_sep># -*- coding: utf-8 -*- #******************************************************* # Main.py # created by sawa on 2018/02/06. # Copyright © 2018 sawa. All rights reserved. #******************************************************* # 問題7,8 import numpy as np import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt #import vpython as vs import math as mat import random as rnd def main(): print("問題7") print(integrateExample()) print("問題8") print(integrate(mat.sin, 0, mat.pi)) print(integrate(mat.sin, 0, 2 * mat.pi)) #問題7(数値積分): 積分 ∫[1,2] √(x^2 ^ 1) dx の(近似)値を求めてみよ.そのために,積分の定義式: ∫[a,b] f(x) dx = lim(⊿→0) Σ[0,n-1]{f(x_i)(x_(i+1)-x_i)}に戻り,後者の近似値を計算する.すなわち, 1.積分区間[a,b]の中に多数の点 a = x_0 < x_1 < … < x_n = bを取る.最も簡単には,n等分すればよい. 2.f(x_i)(x_(i+1)-x_i)の和を計算する. def integrateExample(): a = 1 b = 2 n = 1000 #刻み幅 d = (b - a) / n #積分区間を100等分した値 #被積分関数 def f(x): return mat.sqrt(x * x - 1) #面積の総和を求める s = 0 #面積の総和 for i in range(n-1): s += f(a + i * d) * d return s #問題8(数値積分 II): Pythonでは,(defを使って)定義された関数を他の関数の入力として渡すこともできる.例えば, ''' def plus_one(x): retrun x + 1 def twice(f, x): return f(f(x)) print(twice(plut_one, 3)) ''' #のように.ここで,twiceは「任意の関数を」受け取ることができ,それを2回適用することができる.これに習い,前問を拡張して,関数および積分区間a,bを受け取り,積分∫[a,b] f(x) dx を計算する汎用的な関数,integrate def integrate(f, a, b): n = 100 #刻み幅 d = (b - a) / n #積分区間を100等分した値 #面積の総和を求める s = 0 #面積の総和 for i in range(n-1): s += f(a + i * d) * d return s if __name__ == "__main__": main() <file_sep># -*- coding: utf-8 -*- #******************************************************* # Main.py # created by sawa on 2018/02/06. # Copyright © 2018 sawa. All rights reserved. #******************************************************* # 問題4,5,6 import numpy as np import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt #import vpython as vs import math as mat import random as rnd def main(): print("問題4") print(a(0)) print(a(3)) print(a(6)) print("問題5") print(cbrt(1)) print(cbrt(8)) print(cbrt(27)) print("問題6") print(a2(0)) print(a2(1)) print(a2(2)) print(a2(3)) print(a2(4)) #問題1: 4つの数a,b,c,dを受け取り,ベクトル(a,b)と(c,d)の内積を計算する関数inner(a, b, c, d)を書き,適当な例を使って確かめよ. def inner(a, b, c, d): v1 = np.array([a, b]) v2 = np.array([c, d]) return np.dot(v1, v2) #問題4: 変数nを受け取り,次の漸化式で定まる数列のa_nを計算する関数a(n)を書き,適当な例を作って確かめよ.a_0 = 1,a_n = 2 a_(n-1) + 1 (n > 0). def a(n): if n == 0: return 1 else: return 2 * a(n - 1) + 1 #問題5(ニュートン法): 次は,cの3乗根(3√c)に収束する数列である.c_0 = 1, c_n = 2 a_(n-1) + 1 (n > 0).ある程度大きなnに対して,a_nを計算すればそれが,3√cの近似値となる.これを用いて,与えられた数cに対し,3√cの近似値を計算する関数,cbrt(c)(cubic root)を書け.適当な数の3乗根を計算し,再び3乗して,結果が正しそうか確かめよ. def cbrt(c): return 1 #問題5・参考: 一般に,f(x)=0の解を求めるのに以下のニュートン法が用いられる.a_0 = c,a_n = a_(n-1) - f(a_(n-1))/f'(a_(n-1)) (n > 0).これが"収束するならば",x = x - f(x) / f'(x)を満たすx,すなわちf(x) = 0を満たすxに収束することは明らか.本問はこれを,f(x) = x^3 - cに適用しただけ.ただし,収束するとは限らないので無条件に使えるわけではない.計算機で何かを求めるときに,「答えに収束するような数列」を使って計算することは非常に多い. def newton(x): return 1 #問題6: 少し複雑な変数の使い方に慣れる問題.変数nを受け取り,次の漸化式で定まる数列のa_nを計算するa(n)を書き,適当な例を使って確かめよ. def a2(n): if n == 0: return 1 if n == 1: return 1 a0 = 1 #メモ a1 = 1 #メモ #動的計画法 tmp = 0 for i in range(2, n+1): tmp = a1 + 2 * a0 a0 = a1 a1 = tmp return tmp #配列の末尾を返す if __name__ == "__main__": main()
9b086c946f1cb250e6c62720e124f0a83c6ddec0
[ "Markdown", "Python" ]
11
Python
sawa2d2/computational-physics
039b5300b29636f4752012a73703199a2c38e727
3502523d21dc49383d7f15e10dd44cbc5150ecab
refs/heads/master
<repo_name>Joyan11/DigitalClock<file_sep>/README.md # DigitalCLock Digital clock built in JavaScript to practise DOM manipulation [link] (https://codepen.io/Joyan11/full/gOPYVML) <file_sep>/app.js const clock = () => { const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'fri', 'sat']; const months = ['January', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december']; let date, h, m, s, d, mnt, dte, year; date = new Date(); h = date.getHours(); m = date.getMinutes(); s = date.getSeconds(); d = date.getDay(); mnt = date.getMonth(); dte = date.getDate(); console.log(h, m, s, d, mnt, dte); //month document.getElementById('month').textContent = months[mnt]; //year document.getElementById('year').textContent = date.getFullYear(); //date if (dte < 10) { document.getElementById('day1').textContent = `0${dte} `; } else { document.getElementById('day1').textContent = dte; } //day document.getElementById('day').textContent = days[d]; //hours if (h == 0) { h = 12; document.getElementById('hours').textContent = h; } if (h > 12) { h = h - 12; if (h < 10) { document.getElementById('hours').textContent = `0${h} `; } else { document.getElementById('hours').textContent = h; } document.getElementById('ampm').textContent = 'PM'; } //month if (m < 10) { document.getElementById('minutes').textContent = '0' + m; } else { document.getElementById('minutes').textContent = m; } //seconds if (s < 10) { document.getElementById('seconds').textContent = `0${s} `; } else { document.getElementById('seconds').textContent = s; } setTimeout(clock, 1000); } clock();
5c9926471202c27af6ee2abb7da672e74e20181a
[ "Markdown", "JavaScript" ]
2
Markdown
Joyan11/DigitalClock
954c5d0130bf4857686e3d432038184f9680dad6
17f9d5a8fc18d41e9be333ee4b7f2fd1c0e780e6
refs/heads/master
<repo_name>PascalKo/csharp_samples_observer_numbergenerator<file_sep>/source/NumberGenerator.Logic/RandomNumberGenerator.cs using System; using System.Collections.Generic; using System.Threading.Tasks; using static NumberGenerator.Logic.IObservable; namespace NumberGenerator.Logic { /// <summary> /// Implementiert einen Nummern-Generator, welcher Zufallszahlen generiert. /// Es können sich Beobachter registrieren, welche über eine neu generierte Zufallszahl benachrichtigt werden. /// Zwischen der Generierung der einzelnen Zufallsnzahlen erfolgt jeweils eine Pause. /// Die Generierung erfolgt so lange, solange Beobachter registriert sind. /// </summary> public class RandomNumberGenerator : IObservable { #region Constants private static readonly int DEFAULT_SEED = DateTime.Now.Millisecond; private const int DEFAULT_DELAY = 500; private const int RANDOM_MIN_VALUE = 1; private const int RANDOM_MAX_VALUE = 1000; #endregion #region Fields private readonly Random _random; private readonly int _delay; public NextNumberHandler NumberHandler { get; set; } #endregion #region Constructors /// <summary> /// Initialisiert eine neue Instanz eines NumberGenerator-Objekts /// </summary> public RandomNumberGenerator() : this(DEFAULT_DELAY, DEFAULT_SEED) { } /// <summary> /// Initialisiert eine neue Instanz eines NumberGenerator-Objekts /// </summary> /// <param name="delay">Enthält die Zeit zw. zwei Generierungen in Millisekunden.</param> public RandomNumberGenerator(int delay) : this(delay, DEFAULT_SEED) { } /// <summary> /// Initialisiert eine neue Instanz eines NumberGenerator-Objekts /// </summary> /// <param name="delay">Enthält die Zeit zw. zwei Generierungen in Millisekunden.</param> /// <param name="seed">Enthält die Initialisierung der Zufallszahlengenerierung.</param> public RandomNumberGenerator(int delay, int seed) { _random = new Random(seed); _delay = delay; } #endregion #region Methods #region IObservable Members /// <summary> /// Fügt einen Beobachter hinzu. /// </summary> /// <param name="observer">Der Beobachter, welcher benachricht werden möchte.</param> //public void Attach(IObserver observer) //{ // if (observer == null) // { // throw new ArgumentNullException(); // } // if (_observers.Contains(observer)) // { // throw new InvalidOperationException("Observer already exists!"); // } // _observers.Add(observer); //} /// <summary> /// Entfernt einen Beobachter. /// </summary> /// <param name="observer">Der Beobachter, welcher nicht mehr benachrichtigt werden möchte</param> //public void Detach(IObserver observer) //{ // if (observer == null) // { // throw new ArgumentNullException(); // } // if (!_observers.Contains(observer)) // { // throw new InvalidOperationException("observer does not exist"); // } // _observers.Remove(observer); //} /// <summary> /// Benachrichtigt die registrierten Beobachter, dass eine neue Zahl generiert wurde. /// </summary> /// <param name="number">Die generierte Zahl.</param> public void NotifyObservers(int number) { NumberHandler.Invoke(number); } #endregion public override string ToString() { return $"{nameof(NumberGenerator)}"; } /// <summary> /// Started the Nummer-Generierung. /// Diese läuft so lange, solange interessierte Beobachter registriert sind (=>Attach()). /// </summary> public void StartNumberGeneration() { while (NumberHandler!=null) { int number = _random.Next(RANDOM_MIN_VALUE, RANDOM_MAX_VALUE); NotifyObservers(number); Task.Delay(_delay).Wait(); Console.WriteLine($">> {this.GetType().Name}: Number generated '{number}"); } } #endregion } } <file_sep>/source/NumberGenerator.Logic/IObserver.cs namespace NumberGenerator.Logic { public interface IObserver { void OnNextNumber(int number); } }<file_sep>/source/NumberGenerator.Ui/Program.cs  using NumberGenerator.Logic; using System; namespace NumberGenerator.Ui { class Program { static void Main() { // Zufallszahlengenerator erstelltn RandomNumberGenerator numberGenerator = new RandomNumberGenerator(250); // Beobachter erstellen BaseObserver baseObserver = new BaseObserver(numberGenerator, 10); StatisticsObserver statisticsObserver = new StatisticsObserver(numberGenerator, 20); RangeObserver rangeObserver = new RangeObserver(numberGenerator, 5, 200, 300); QuickTippObserver quickTippObserver = new QuickTippObserver(numberGenerator); // Nummerngenerierung starten // Resultat ausgeben throw new NotImplementedException(); } } } <file_sep>/README.md # Number Generator ## Lehrziele * Wiederholung Objektorientierung * Abgeleitete Klassen * Collections: List<T> * "Beobachter"-Muster ## Allgemeines Anhand des "Beobachter"-Musters ist ein Zahlengenerator (`RandomNumberGenerator`) zu implementieren welcher so lange Zufallszahlen erzeugt, solange Beobachter am Zahlengenerator registriert sind. Folgende Beobachter sollen die generierten Zufallszahlen verarbeiten: ## BaseObserver Dieser Beobachter dient als Basisklasse für spezialisiertere Beobachter und wird über den Konstruktur mit der Anzahl der zu beobachten Zahlen konfiguriert. Ist diese Anzahl erreicht, so meldet sich der BaseObserver selbstständig vom `RandomNumberGenerator` ab. ## StatisticsObserver Aufgabe dieses Beobachters ist eine gewissen Anzahl an Zahlen (parametrisierbar über den Konstruktor) statistisch zu analysieren: 1. `SUM` 1. `AVG` 1. `MIN` 1. `MAX` Nachdem die gewünschte Anzahl an Zufallszahlen verarbeitet wurde, meldet sich auch der `StatisticsObserver` selbstständig vom `RandomNumberGenerator` ab. ## RangeObserver Dieser Beobachter wird mit einer unteren Schranke, einer oberen Schranke und der Anzahl der gewünschten Treffer im Bereich per Konstruktor konfiguriert und zählt alle Zufallszahlen, die in diesen Bereich fallen. Wenn die gewünschte Trefferanzahl erreicht ist, meldet sich der RangeObserver selbstständig von der weiteren Benachrichtigung beim `RandomNumberGenerator` ab. ## QuickTippObserver Die Aufgabe dieses Beobachters ist es so lange Zufallszahlen zu "empfangen", bis dass ein vollständiger QuickTipp erkannt wurde (6 eindeutige Zahlen im Bereich von 1 bis 45). Danach meldet sich der Beobachter selbstständig vom Empfang weiterer Zufallszahlen ab.   # Konsolenprogramm Neben den Unittests, welche die grundlegende Funktionalität abprüfen soll auch eine Konsolenapplikation implementiert werden, welche die Funktionsweise der verschiedenen Beobachter demonstriert und deren Ausgaben ähnlich zu diesem Screenshot sind: ![Übersicht](./images/screenshot-consoleapp.png) # Klassendiagramm ![Übersicht](./images/screenshot-classdiagram.png) # Hinweise * Die `Observer` ("Beobachter") registrieren sich selbstständig beim `Observable` (`RandomNumberGenerator`). * Sobald ein `Observer` "Beobachter" an keinen weiteren Zufallszahlen mehr interessiert ist meldet sich dieser selbständig beim `Observable` (`RandomNumberGenerator`) ab. * Der `RandomNumberGenerator` erzeugt so lange Zufallszahlen, so lange interessierte Beobachter angemeldet sind! * Der `RandomNumberGenerator` verwendet zur Erzeugung der (Pseudo-)Zufallszahlen die Klasse `Random`. Verwenden Sie zur Initialisierung des `Random`-Objekts die per `RandomNumberGenerator`-Konstruktor zur Verfügung gestellte `Seed` ([Dokumentation](https://docs.microsoft.com/en-us/dotnet/api/system.random.-ctor?view=netcore-3.0#System_Random__ctor_System_Int32_)). Dies ist wichtig, da ansonsten die in den Unittests erwarteten Ergebnisse nicht eintreffen! * Die Zufallszahlen sollen im Bereich zw. 1 und 999 liegen: ``` cs int generatedNumber = _random.Next(RANDOM_MIN_VALUE, RANDOM_MAX_VALUE); ``` * Zwischen den einzelnen Generierungsvorgängen wartet der RandomNumberGenerator eine gewisse Anzahl an Millisekunden (Konfiguration per Konstruktor): ``` cs Task.Delay(_delay).Wait; ``` * Die Generierung der Zufallszahlen wird per Methodenaufruf `StartNumberGeneration()` am `RandomNumberGenerator` gestartet. * Beachten Sie die Vererbungshierarchie der "Beobachter". Haben Sie einen Tipp um in der Implementierung Codeverdoppelung zu vermeiden? * Achtung: Unit-Tests dürfen nicht verändert werden! Beachten Sie bei der Wahl der Bezeichner (Methoden-, Variablennamen, etc.) das Klassendiagramm bzw. die Unit-Tests. <file_sep>/source/NumberGenerator.Logic/QuickTippObserver.cs using System; using System.Collections.Generic; using System.Linq; namespace NumberGenerator.Logic { /// <summary> /// Beobachter, welcher auf einen vollständigen Quick-Tipp wartet: 6 unterschiedliche Zahlen zw. 1 und 45. /// </summary> public class QuickTippObserver : IObserver { #region Fields private readonly IObservable _numberGenerator; #endregion #region Properties public List<int> QuickTippNumbers { get; private set; } public int CountOfNumbersReceived { get; private set; } #endregion #region Constructor public QuickTippObserver(IObservable numberGenerator) { _numberGenerator=numberGenerator; } #endregion #region Methods public void OnNextNumber(int number) { throw new NotImplementedException(); } public override string ToString() { throw new NotImplementedException(); } private void DetachFromNumberGenerator() { _numberGenerator.NumberHandler -= this.OnNextNumber; } #endregion } }
9b8a60a261010b770cb46515bbd8bf8f0c7c2006
[ "Markdown", "C#" ]
5
C#
PascalKo/csharp_samples_observer_numbergenerator
450b0bfe802383429855dd1c7d89dc7b217bbaa1
3046cbd13bf4d28214bccee69e19a593624f3c40
refs/heads/master
<file_sep>import React, {useState, useMemo} from 'react'; import './App.css'; function App() { const [number, setNumber] = useState(0); const [name, setName] = useState(''); const result = useMemo(() => { return calculateJustNothing(number); }, [number]); function calculateJustNothing(number){ console.log("test..."); let i = 0; while(i<2800000) i++; return Math.random() * number; }; return ( <div className="App"> The square is: {result} <button onClick={() => setNumber( number + 1)}>Increment</button> <input type="text" value={name} onChange={(e) => setName(e.target.value)} /> <DisplayName name={name} /> </div> ); }; const DisplayName = React.memo(({name}) => { console.log("inside..."); return( <div>The name is: {name}</div> ); }); export default App;
acb2a53ad61c5c9f93a19da5ba7d175c970f0041
[ "JavaScript" ]
1
JavaScript
suhasbhairav/usememoproject
855ed8a96d829c28120eb2f5ef0b7dc050a926ff
79749d53785be6213defeb006b6dc1e9f092629c
refs/heads/master
<file_sep>'use strict'; var Handlebars = require('handlebars'), fs = require('fs'), Helpers = require('../helpers/helpers'), helpers = new Helpers(); var getSummarystats = function (data) { var stats = { classes : { count : 0, usedCount : 0, unusedCount : 0, unusedPercentage : 0, totalUsage : 0, avgUsage : 0, definitionsDistribution : [], usagesDistribution : [] }, selectors : { count : 0, totalLength : 0, avgLength : 0, lengthsDistribution : [] } }; for (var cKey in data.classes) { var c = data.classes[cKey]; stats.classes.count++; stats.classes.definitionsDistribution.push(c.definitions.count); if (c.usages) { stats.classes.totalUsage += c.usages.count; stats.classes.usedCount++; stats.classes.usagesDistribution.push(c.usages.count); } else { stats.classes.unusedCount++; } } for (var sKey in data.selectors) { var s = data.selectors[sKey], length = helpers.getSelectorLength(s.string); stats.selectors.count++; stats.selectors.totalLength += length; stats.selectors.lengthsDistribution.push(length); } if (stats.classes.count) { stats.classes.unusedPercentage = ((stats.classes.unusedCount / stats.classes.count) * 100).toFixed(2); stats.classes.avgUsage = (stats.classes.totalUsage / stats.classes.usedCount).toFixed(2); } if (stats.selectors.count) { stats.selectors.avgLength = (stats.selectors.totalLength / stats.selectors.count).toFixed(2); } return stats; }; module.exports = function (data, report) { var templateSrc = fs.readFileSync(__dirname + '/report_template.html').toString(), template = Handlebars.compile(templateSrc); var stats = getSummarystats(data); //stringified json for d3 charts stats['stringifiedJSON'] = JSON.stringify(stats); stats['report'] = report; return template(stats); }; //# of classes - done //# of unused classes - done //unusued % - done //avg usage per class - done //class definition distribution - done //class usage distribution - done //avg selector length - done //selector length distribution - done //warnings dump <file_sep>'use strict'; function Helpers() { } Helpers.prototype = { getSelectorLength : function (selector) { var classRegEx = /[_a-zA-Z][_a-zA-Z0-9-]*/g; return selector.match(classRegEx).length; } }; module.exports = Helpers; <file_sep>/* * grunt-csschecker * https://github.com/timeinfeldt/grunt-csschecker * * Copyright (c) 2014 <NAME> * Licensed under the MIT license. */ 'use strict'; var CSSChecker = require('../lib/parsers/csschecker'), CodeChecker = require('../lib/parsers/codechecker'), glob = require('glob'), checks = require('../lib/checks/checks.js'), async = require('async'), reporters = require('../lib/reporters'), Collector = require('../lib/collectors/collector'); module.exports = function (grunt) { grunt.registerMultiTask('csschecker', 'Checks your CSS', function () { var done = this.async(), checksConfig = this.data.checks, data = { selectors : {}, classes : {}, declarations : {} }, self = this, collector = new Collector(data); function getFilesFromPath(patterns, callback, options) { if (!patterns) { grunt.fail.warn('No source file paths found.'); } var filesToBeAnalysed = []; async.eachSeries(patterns, function (f, next) { glob(f, options, function (er, files) { if (files.length === 0) { grunt.fail.warn('No files matching "' + f + '" found.'); } for (var j = 0; j < files.length; j++) { if (filesToBeAnalysed.indexOf(files[j]) < 0) { filesToBeAnalysed.push(files[j]); } } next(); }); }, function () { callback(filesToBeAnalysed); }); } function runChecks() { var report = { types : {} }; grunt.log.subhead('Running checks on collected data'); for (var type in checksConfig) { if (!data.hasOwnProperty(type)) { grunt.fail.warn('No data for ' + type + ' checks.'); } var checkGroupData = data[type]; report.types[type] = {}; for (var check in checksConfig[type]) { if (checks.hasOwnProperty(check)) { grunt.log.verbose.write(check + '...'); report.types[type][check] = []; for (var key in checkGroupData) { var d = checkGroupData[key], opts = checksConfig[type][check].options, result = checks[check](d, opts); if (result) { report.types[type][check].push({ message : result }); } } grunt.log.verbose.ok(); } else { grunt.log.error('Check ' + check + ' not found, skipping.'); } } } grunt.log.subhead('Creating reports'); if (self.data.options.checkstyle) { grunt.file.write(self.data.options.checkstyle, reporters.checkstyle(report)); } if (self.data.options.plaintext) { grunt.file.write(self.data.options.plaintext, reporters.plaintext(report)); } if (self.data.options.json) { grunt.file.write(self.data.options.json, reporters.json(data)); } if (self.data.options.html) { grunt.file.write(self.data.options.html, reporters.html(data, report)); } } function analyseFiles(files, Analyser, callback) { grunt.log.subhead('Running ' + Analyser.name + ' (' + files.length + ' files)'); var analyser = new Analyser(); files.forEach(function (path) { if (!grunt.file.exists(path)) { grunt.log.warn('File "' + path + '" not found.'); return; } grunt.log.verbose.write('Checking file: ' + path + '...'); analyser.run(path, collector, function () { grunt.log.verbose.ok(); }); }); callback(); } function run() { async.series([ function (callback) { getFilesFromPath(self.data.cssSrc, function (files) { analyseFiles(files, CSSChecker, callback); }); }, function (callback) { getFilesFromPath(self.data.codeSrc, function (files) { analyseFiles(files, CodeChecker, callback); }); } ], function (err) { if (!err) { runChecks(); done(); } }); } run(); }); }; <file_sep>'use strict'; var parse = require('css-parse'), fs = require('fs'); function CSSChecker() { } CSSChecker.prototype = { rules : function () { return this.parsedData.rules; }, parseFile : function () { var rules = this.rules(), rulesCount = rules.length, collector = this.collector; for (var i = 0; i < rulesCount; i++) { var rule = rules[i]; if (rule.type === 'rule') { var selectorsCount = rule.selectors.length; for (var j = 0; j < selectorsCount; j++) { var selector = rule.selectors[j], classMatches = selector.match(/(\.[_a-z]+[_a-z0-9-:\\]*)/ig), classMatchesCount = classMatches && classMatches.length; //extract selector collector.addSelectorDefinition(selector); //extract classes if (classMatchesCount) { for (var x = 0; x < classMatchesCount; x++) { var className = classMatches[x]; collector.addClassDefinition(className); } } } rule.declarations.forEach(function (declaration) { //extract declaration collector.addDeclarationDefinition(declaration); }); } } }, run : function (path, Collector, callback) { this.file = fs.readFileSync(path, 'utf8'); this.parsedData = parse(this.file).stylesheet; this.collector = Collector; this.collector.setPath(path); this.parseFile(); return callback(); } }; module.exports = CSSChecker; <file_sep>exports.checkstyle = require('./checkstyle'); exports.plaintext = require('./plaintext'); exports.json = require('./json'); exports.html = require('./html'); <file_sep>'use strict'; //var util = require('./util'); module.exports = function (report) { var xml = [ '<?xml version="1.0" encoding="utf-8"?>', '<checkstyle>' ]; Object.keys(report.types).forEach(function (type) { xml.push('<file name="' + type + '">'); Object.keys(report.types[type]).forEach(function (check) { var issues = report.types[type][check]; issues.forEach(function (issue) { xml.push([ '<error', //' line="' + issue.line + '"', //' column="' + issue.character + '"', ' severity="warning"', ' message="' + issue.message + '"', ' source="com.csschecker"', '/>' ].join('')) }); }); xml.push('</file>'); }); xml.push('</checkstyle>'); return xml.join('\n'); };<file_sep>'use strict'; module.exports = function (report) { return JSON.stringify(report); }; <file_sep>'use strict'; var fs = require('fs'); function Collector(data) { this.data = data; } Collector.prototype = { setPath : function (path) { this.path = path; }, addClassUsage : function (classObj) { var path = this.path; if (classObj.hasOwnProperty('usages')) { classObj['usages'].count += 1; if (classObj['usages'].locations.indexOf(path) < 0) { classObj['usages'].locations.push(path); } } else { classObj['usages'] = { count : 1, locations : [path] }; } }, addClassDefinition : function (className) { var classes = this.data.classes, path = this.path; if (classes.hasOwnProperty(className)) { classes[className].definitions.count += 1; if (classes[className].definitions.locations.indexOf(path) < 0) { classes[className].definitions.locations.push(path); } } else { classes[className] = { string : className, definitions : { count : 1, locations : [path] } }; } }, addSelectorDefinition : function (selector) { var selectors = this.data.selectors, path = this.path; if (selectors.hasOwnProperty(selector)) { selectors[selector].definitions.count += 1; if (selectors[selector].definitions.locations.indexOf(path) < 0) { selectors[selector].definitions.locations.push(path); } } else { selectors[selector] = { string : selector, definitions : { count : 1, locations : [path] } }; } }, addDeclarationDefinition : function (declaration) { if (!(declaration.type == 'declaration')) { console.log('Declaration type is ' + declaration.type + ' ?'); return; } var declarations = this.data.declarations, path = this.path, property = declaration.property, value = declaration.value; if (declarations.hasOwnProperty(property)) { declarations[property].definitions.count += 1; } else { declarations[property] = { string : property, definitions : { count : 1, locations : [path] }, values : {} }; } if (declarations[property].definitions.locations.indexOf(path) < 0) { declarations[property].definitions.locations.push(path); } if (declarations[property].values.hasOwnProperty(value)) { declarations[property].values[value].count += 1; } else { declarations[property].values[value] = { count : 1 }; } }, getClasses : function () { return this.data.classes; } }; module.exports = Collector;<file_sep>'use strict'; module.exports = function (report) { var txt = []; Object.keys(report.types).forEach(function (type) { txt.push('Checks for: ' + type); txt.push('===================='); txt.push('\n'); Object.keys(report.types[type]).forEach(function (check) { txt.push(check); txt.push('--------------------'); var issues = report.types[type][check]; issues.forEach(function (issue) { txt.push([ issue.message ].join('')) }); }); txt.push('\n'); }); return txt.join('\n'); };
f8f58f3eb2ef6740e4424b35a4915c5476737432
[ "JavaScript" ]
9
JavaScript
danez/grunt-csschecker
ea6f53994cd6f118cc9df2b3e9eed8e5d0658911
9c1ace99a32c05f7b13d948ffceebc0b598a018b
refs/heads/master
<file_sep>#include "Coin.h" #include <iostream> #include <string> using namespace std; int main() { Coin coin1; // define a coin object int heads = 0; int tails = 0; string result = coin1.getSideUp(); cout << "Welcome to the Coin Toss Simultor!\n\nThis program will toss a coin 20 times and tally the amount of \n"; cout << "times the coin lands on 'heads' and 'tails'.\n\n"; cout << "The side that is currently facing up is " << result << ".\n\n"; for(int i = 0; i < 20; i++) { coin1.toss(); result = coin1.getSideUp(); cout << "Coin Toss Number " << i + 1 << ": " << result << "." << endl; if (result == "heads") { heads++;} else { tails++;} } cout << endl << "RESULTS: " << endl << "Heads was tossed " << heads << " times." << endl; cout << "Tails was tossed " << tails << " times." << endl << endl; return 0; }<file_sep>#pragma once //Coin Class Specification File #include <string> #ifndef COIN_H #define COIN_H //Coin class declaration class Coin { private: std::string sideUp; public: Coin(); std::string getSideUp(); void toss(); }; #endif COIN_H
48a38b819edcac039d76e3a598b2069d863ac4e7
[ "C++" ]
2
C++
machen2/Coin-Toss-Simulator
6c34bbcfcbe4399f9af43b580c1b74a44040e14f
83f8fe114f68c8aa984e9c59c11a72f3275138b9
refs/heads/master
<repo_name>xmps/Catalanitzador<file_sep>/CatalanitzadorPerAlWindows/Actions/OpenOfficeAction.cpp /* * Copyright (C) 2012 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include "stdafx.h" #include "OpenOfficeAction.h" #include "Url.h" #include "ApplicationVersion.h" #include "ConfigurationInstance.h" // message used to communicate with try icon process #define LISTENER_WINDOWCLASS L"SO Listener Class" #define KILLTRAY_MESSAGE L"SO KillTray" #define SOFFICE_PROCESSNAME L"soffice.bin" OpenOfficeAction::OpenOfficeAction(IRegistry* registry, IRunner* runner, DownloadManager* downloadManager) : Action(downloadManager) { m_registry = registry; m_runner = runner; m_szFilename[0]=NULL; m_szTempPathCAB[0] = NULL; GetTempPath(MAX_PATH, m_szTempPath); _addExecutionProcess(ExecutionProcess(SOFFICE_PROCESSNAME, L"", true)); } OpenOfficeAction::~OpenOfficeAction() { if (m_szFilename[0] != NULL && GetFileAttributes(m_szFilename) != INVALID_FILE_ATTRIBUTES) { DeleteFile(m_szFilename); } _removeCabTempFiles(); } wchar_t* OpenOfficeAction::GetName() { return _getStringFromResourceIDName(IDS_OPENOFFICEACTION_NAME, szName); } wchar_t* OpenOfficeAction::GetDescription() { return _getStringFromResourceIDName(IDS_OPENOFFICEACTION_DESCRIPTION, szDescription); } ExecutionProcess OpenOfficeAction::GetExecutingProcess() { ExecutionProcess process; process = ActionExecution::GetExecutingProcess(); if (process.IsEmpty() == false) { return process; } if (FindWindowEx(NULL, NULL, LISTENER_WINDOWCLASS, NULL) == NULL) { return ExecutionProcess(); } else { return ExecutionProcess(KILLTRAY_MESSAGE, L"", true); } } void OpenOfficeAction::FinishExecution(ExecutionProcess process) { HWND hwndTray; hwndTray = FindWindow( LISTENER_WINDOWCLASS, NULL); if (hwndTray) { SendMessage(hwndTray, RegisterWindowMessage(KILLTRAY_MESSAGE), 0, 0); } Runner runner; vector <DWORD> processIDs = runner.GetProcessID(wstring(SOFFICE_PROCESSNAME)); for (unsigned int i = 0; i < processIDs.size(); i++) { runner.TerminateProcessID(processIDs.at(i)); } } // TODO: You can several versions installed, just read first one for now void OpenOfficeAction::_readVersionInstalled() { bool bKeys = true; DWORD dwIndex = 0; if (m_registry->OpenKey(HKEY_LOCAL_MACHINE, OPENOFFICCE_PROGRAM_REGKEY, false)) { while (bKeys) { wstring key; bKeys = m_registry->RegEnumKey(dwIndex, key); dwIndex++; if (bKeys) { m_version = key; break; } } m_registry->Close(); } g_log.Log(L"OpenOfficeAction::_readVersionInstalled '%s'", (wchar_t *) m_version.c_str()); } bool OpenOfficeAction::IsNeed() { bool bNeed; switch(GetStatus()) { case NotInstalled: case AlreadyApplied: case CannotBeApplied: bNeed = false; break; default: bNeed = true; break; } g_log.Log(L"OpenOfficeAction::IsNeed returns %u (status %u)", (wchar_t *) bNeed, (wchar_t*) GetStatus()); return bNeed; } bool OpenOfficeAction::Download(ProgressStatus progress, void *data) { wstring filename; ConfigurationFileActionDownload downloadVersion; downloadVersion = ConfigurationInstance::Get().GetRemote().GetDownloadForActionID(GetID(), ApplicationVersion(GetVersion())); GetTempPath(MAX_PATH, m_szFilename); wcscat_s(m_szFilename, downloadVersion.GetFilename().c_str()); return m_downloadManager->GetFileAndVerifyAssociatedSha1(downloadVersion, m_szFilename, progress, data); } void OpenOfficeAction::Execute() { wchar_t szParams[MAX_PATH] = L""; wchar_t szApp[MAX_PATH] = L""; // Unique temporary file (needs to create it) GetTempFileName(m_szTempPath, L"CAT", 0, m_szTempPathCAB); DeleteFile(m_szTempPathCAB); if (CreateDirectory(m_szTempPathCAB, NULL) == FALSE) { g_log.Log(L"OpenOfficeAction::Execute. Cannot create temp directory '%s'", m_szTempPathCAB); return; } _extractCabFile(m_szFilename, m_szTempPathCAB); wcscpy_s(szApp, m_szTempPathCAB); wcscat_s(szApp, L"\\setup.exe /q"); SetStatus(InProgress); g_log.Log(L"OpenOfficeAction::Execute '%s' with params '%s'", szApp, szParams); m_runner->Execute(NULL, szApp); } bool OpenOfficeAction::_extractCabFile(wchar_t * file, wchar_t * path) { Runner runnerCab; wchar_t szParams[MAX_PATH]; wchar_t szApp[MAX_PATH]; GetSystemDirectory(szApp, MAX_PATH); wcscat_s(szApp, L"\\expand.exe "); swprintf_s (szParams, L" %s %s -f:*", file, path); g_log.Log(L"OpenOfficeAction::_extractCabFile '%s' with params '%s'", szApp, szParams); runnerCab.Execute(szApp, szParams); runnerCab.WaitUntilFinished(); return true; } // This deletes the contents of the extracted CAB file for the language pack void OpenOfficeAction::_removeCabTempFiles() { if (m_szTempPathCAB[0] == NULL) return; wchar_t szFile[MAX_PATH]; wchar_t* files[] = {L"openofficeorg1.cab", L"openofficeorg33.msi", L"setup.exe", L"setup.ini", NULL}; for(int i = 0; files[i] != NULL; i++) { wcscpy_s(szFile, m_szTempPathCAB); wcscat_s(szFile, L"\\"); wcscat_s(szFile, files[i]); if (DeleteFile(szFile) == FALSE) { g_log.Log(L"OpenOfficeAction::_removeCabTempFiles. Cannot delete '%s'", (wchar_t *) szFile); } } RemoveDirectory(m_szTempPathCAB); } enum LanguageParsingState { ItemOther, ItemLinguisticGeneral, PropUILocale }; LanguageParsingState parsing_state = ItemOther; bool OpenOfficeAction::_readNodeCallback(XmlNode node, void *data) { vector <XmlAttribute>* attributes; bool bIsItem; if (parsing_state == PropUILocale && node.GetName().compare(L"value")==0) { wstring* lang_found = (wstring *) data; *lang_found = node.GetText(); parsing_state = ItemOther; return false; } bIsItem = node.GetName().compare(L"item") == 0; if (bIsItem && parsing_state != ItemOther) { parsing_state = ItemOther; } attributes = node.GetAttributes(); for (unsigned int i = 0; i < attributes->size(); i++) { XmlAttribute attribute; attribute = attributes->at(i); if (parsing_state == ItemOther && bIsItem && attribute.GetName() == L"oor:path" && attribute.GetValue() == L"/org.openoffice.Office.Linguistic/General") { parsing_state = ItemLinguisticGeneral; } if (parsing_state == ItemLinguisticGeneral && attribute.GetName() == L"oor:name" && attribute.GetValue() == L"UILocale") { parsing_state = PropUILocale; } } return true; } void OpenOfficeAction::_getPreferencesFile(wstring& location) { wchar_t szPath[MAX_PATH]; SHGetFolderPath(NULL, CSIDL_APPDATA|CSIDL_FLAG_CREATE, NULL, 0, szPath); location = szPath; location += L"\\OpenOffice.org\\3\\user\\registrymodifications.xcu"; } #define DEFAULT_LANGUAGE L"ca" void OpenOfficeAction::_setDefaultLanguage() { XmlParser parser; wstring file; bool bRslt; _getPreferencesFile(file); if (parser.Load(file) == false) { g_log.Log(L"OpenOfficeAction::_setDefaultLanguage. Could not open '%s'", (wchar_t *) file.c_str()); return; } /* XML fragment to generate <item oor:path="/org.openoffice.Office.Linguistic/General"> <prop oor:name="UILocale" oor:op="fuse"> <value>DEFAULT_LANGUAGE</value> </prop> </item> */ XmlNode item(parser.getDocument()), prop(parser.getDocument()), value(parser.getDocument()); value.SetName(wstring(L"value")); value.SetText(wstring(DEFAULT_LANGUAGE)); prop.SetName(wstring(L"prop")); prop.AddAttribute(XmlAttribute(L"oor:name", L"UILocale")); prop.AddAttribute(XmlAttribute(L"oor:op", L"fuse")); prop.AddChildren(value); item.SetName(wstring(L"item")); item.AddAttribute(XmlAttribute(L"oor:path", L"/org.openoffice.Office.Linguistic/General")); item.AddChildren(prop); parser.AppendNode(item); bRslt = parser.Save(file); g_log.Log(L"OpenOfficeAction::_setDefaultLanguage. Saved file '%s', result %u", (wchar_t *)file.c_str(), (wchar_t *) bRslt); } bool OpenOfficeAction::_isDefaultLanguage() { XmlParser parser; wstring lang_found, file; bool bRslt; _getPreferencesFile(file); if (parser.Load(file) == false) { g_log.Log(L"OpenOfficeAction::_isDefaultLanguage. Could not open '%s'", (wchar_t *) file.c_str()); return false; } parser.Parse(_readNodeCallback, &lang_found); // TODO: We should look for != "ca" but right now we can only add Catalan if no language is present bRslt = lang_found.size() != 0; g_log.Log(L"OpenOfficeAction::_isDefaultLanguage. Preferences file '%s', isdefault %u", (wchar_t *)file.c_str(), (wchar_t *) bRslt); return bRslt; } bool OpenOfficeAction::_isLangPackInstalled() { wstring key; bool bRslt = false; key = OPENOFFICCE_PROGRAM_REGKEY; key += L"\\"; key += m_version; if (m_registry->OpenKey(HKEY_LOCAL_MACHINE, (wchar_t*) key.c_str(), false)) { wchar_t szFileName[MAX_PATH]; if (m_registry->GetString(L"path", szFileName, sizeof(szFileName))) { int i; for (i = wcslen(szFileName); i > 0 && szFileName[i] != '\\' ; i--); szFileName[i + 1] = NULL; wcscat_s(szFileName, L"resource\\oooca.res"); bRslt = GetFileAttributes(szFileName) != INVALID_FILE_ATTRIBUTES; } m_registry->Close(); } g_log.Log(L"OpenOfficeAction::_isLangPackInstalled '%u'", (wchar_t *) bRslt); return bRslt; } ActionStatus OpenOfficeAction::GetStatus() { if (status == InProgress) { if (m_runner->IsRunning()) return InProgress; if (_isLangPackInstalled()) { if (_isDefaultLanguage() == false) { _setDefaultLanguage(); } SetStatus(Successful); } else { SetStatus(FinishedWithError); } g_log.Log(L"OpenOfficeAction::GetStatus is '%s'", status == Successful ? L"Successful" : L"FinishedWithError"); } return status; } void OpenOfficeAction::CheckPrerequirements(Action * action) { _readVersionInstalled(); if (m_version.size() > 0) { if (_isLangPackInstalled() == true) { SetStatus(AlreadyApplied); return; } if (_doesDownloadExist() == false) { _getStringFromResourceIDName(IDS_OPENOFFICEACTION_NOTSUPPORTEDVERSION, szCannotBeApplied); g_log.Log(L"OpenOfficeAction::CheckPrerequirements. Version not supported"); SetStatus(CannotBeApplied); return; } } else { _setStatusNotInstalled(); return; } } <file_sep>/CatalanitzadorPerAlWindows.UnitTests/Actions/WindowsLiveActionTest.cpp /* * Copyright (C) 2012 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include "stdafx.h" #include "Defines.h" #include "WindowsLiveAction.h" #include "ConfigurationInstance.h" using ::testing::Return; using ::testing::_; using ::testing::StrCaseEq; using ::testing::ReturnRef; using ::testing::AnyNumber; using ::testing::DoAll; class WindowsLiveActionTest : public WindowsLiveAction { public: WindowsLiveActionTest::WindowsLiveActionTest(IRegistry* registry, IRunner* runner, IFileVersionInfo* fileVersionInfo, DownloadManager* downloadManager) : WindowsLiveAction(registry, runner, fileVersionInfo, downloadManager) {}; virtual void TearDown() { ConfigurationInstance::Reset(); } public: using WindowsLiveAction::_getMajorVersion; public: using WindowsLiveAction::_isLangSelected; public: using WindowsLiveAction::IsPreRebootRequired; public: using WindowsLiveAction::_isDownloadAvailable; }; #define CreateWindowsLiveAction \ RegistryMock registryMockobj; \ RunnerMock runnerMockobj; \ FileVersionInfoMock fileVersionInfoMockobj; \ WindowsLiveActionTest lipAction(&registryMockobj, &runnerMockobj, &fileVersionInfoMockobj, &DownloadManager()); void SetGetMajorVersion(FileVersionInfoMock &fileVersionInfoMockobj, wstring& versionString, int version) { EXPECT_CALL(fileVersionInfoMockobj, SetFilename(_)).Times(AnyNumber()); EXPECT_CALL(fileVersionInfoMockobj, GetVersion()).WillRepeatedly(ReturnRef(versionString)); EXPECT_CALL(fileVersionInfoMockobj, GetMajorVersion()).WillRepeatedly(Return(version)); EXPECT_CALL(fileVersionInfoMockobj, GetLanguageCode()).WillRepeatedly(Return(0)); } TEST(WindowsLiveActionTest, GetVersion) { wstring VERSION_STRING = L"15.0.1"; const int VERSION = 15; CreateWindowsLiveAction; SetGetMajorVersion(fileVersionInfoMockobj, VERSION_STRING, VERSION); EXPECT_THAT(lipAction.GetVersion(), StrCaseEq(VERSION_STRING)); EXPECT_THAT(lipAction._getMajorVersion(), VERSION); } TEST(WindowsLiveActionTest, _isLangSelected_2011_Yes) { const wchar_t* CATALAN_LANG = L"CA"; wstring VERSION_STRING = L"15.0.1"; const int VERSION = 15; CreateWindowsLiveAction; SetGetMajorVersion(fileVersionInfoMockobj, VERSION_STRING, VERSION); EXPECT_CALL(registryMockobj, OpenKey(HKEY_CURRENT_USER, StrCaseEq(L"Software\\Microsoft\\Windows Live\\Common\\"), false)).WillRepeatedly(Return(true)); EXPECT_CALL(registryMockobj, GetString(StrCaseEq(L"UserLanguage"),_ ,_)).WillRepeatedly(DoAll(SetArgCharStringPar2(CATALAN_LANG), Return(true))); EXPECT_TRUE(lipAction._isLangSelected()); } TEST(WindowsLiveActionTest, _isLangSelected_2011_No) { wstring VERSION_STRING = L"15.0.1"; const int VERSION = 15; CreateWindowsLiveAction; SetGetMajorVersion(fileVersionInfoMockobj, VERSION_STRING, VERSION); EXPECT_CALL(registryMockobj, OpenKey(HKEY_CURRENT_USER, StrCaseEq(L"Software\\Microsoft\\Windows Live\\Common\\"), false)).WillRepeatedly(Return(true)); EXPECT_CALL(registryMockobj, GetString(StrCaseEq(L"UserLanguage"),_ ,_)).WillRepeatedly(DoAll(SetArgCharStringPar2(L""), Return(true))); EXPECT_FALSE(lipAction._isLangSelected()); } TEST(WindowsLiveActionTest, _isLangSelected_2009_Yes) { wstring VERSION_STRING = L"14.0.1.4"; const int VERSION = 14; const int CATALAN_WINLANGCODE = 3; CreateWindowsLiveAction; SetGetMajorVersion(fileVersionInfoMockobj, VERSION_STRING, VERSION); EXPECT_CALL(fileVersionInfoMockobj, GetLanguageCode()).WillRepeatedly(Return(CATALAN_WINLANGCODE)); EXPECT_TRUE(lipAction._isLangSelected()); } TEST(WindowsLiveActionTest, _isLangSelected_2009_No) { wstring VERSION_STRING = L"14.0.1.4"; const int VERSION = 14; CreateWindowsLiveAction; SetGetMajorVersion(fileVersionInfoMockobj, VERSION_STRING, VERSION); EXPECT_FALSE(lipAction._isLangSelected()); } TEST(WindowsLiveActionTest, _isRebootRequired_Live2009_No) { const int VERSION = 14; wstring VERSION_STRING = L"14.0"; CreateWindowsLiveAction; SetGetMajorVersion(fileVersionInfoMockobj, VERSION_STRING, VERSION); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update\\RebootRequired"), false)).WillRepeatedly(Return(true)); EXPECT_CALL(registryMockobj, RegEnumValue(_,_)).WillRepeatedly(Return(true)); EXPECT_FALSE(lipAction.IsPreRebootRequired()); } TEST(WindowsLiveActionTest, _isRebootRequired_Live2011_Yes) { const int VERSION = 15; wstring VERSION_STRING = L"15.0"; CreateWindowsLiveAction; SetGetMajorVersion(fileVersionInfoMockobj, VERSION_STRING, VERSION); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update\\RebootRequired"), false)).WillRepeatedly(Return(true)); EXPECT_CALL(registryMockobj, RegEnumValue(_,_)).WillRepeatedly(Return(true)); EXPECT_TRUE(lipAction.IsPreRebootRequired()); } TEST(WindowsLiveActionTest, _isRebootRequired_Live2012_Yes) { const int VERSION = 16; wstring VERSION_STRING = L"16.0"; CreateWindowsLiveAction; SetGetMajorVersion(fileVersionInfoMockobj, VERSION_STRING, VERSION); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update\\RebootRequired"), false)).WillRepeatedly(Return(true)); EXPECT_CALL(registryMockobj, RegEnumValue(_,_)).WillRepeatedly(Return(true)); EXPECT_TRUE(lipAction.IsPreRebootRequired()); } TEST(WindowsLiveActionTest, _isDownloadAvailable_No) { wstring VERSION_STRING = L"15.0.1"; const int VERSION = 15; CreateWindowsLiveAction; ConfigurationRemote remote; SetGetMajorVersion(fileVersionInfoMockobj, VERSION_STRING, VERSION); ConfigurationInstance::Get().SetRemote(remote); EXPECT_FALSE(lipAction._isDownloadAvailable()); } TEST(WindowsLiveActionTest, _isDownloadAvailable_Yes) { wstring VERSION_STRING = L"15.0.1"; const int VERSION = 15; ConfigurationRemote remote; ConfigurationFileActionDownloads fileActionDownloads; ConfigurationFileActionDownload fileActionDownload; CreateWindowsLiveAction; SetGetMajorVersion(fileVersionInfoMockobj, VERSION_STRING, VERSION); fileActionDownload.SetMaxVersion(ApplicationVersion(L"15")); fileActionDownload.SetMinVersion(ApplicationVersion(L"15")); fileActionDownloads.SetActionID(WindowsLiveActionID); fileActionDownload.AddUrl(L"http://www.softcatala.org/"); fileActionDownloads.AddFileActionDownload(fileActionDownload); remote.AddFileActionDownloads(fileActionDownloads); ConfigurationInstance::Get().SetRemote(remote); EXPECT_TRUE(lipAction._isDownloadAvailable()); }<file_sep>/CatalanitzadorPerAlWindows/UI/Sheets/Models/ApplicationsModel.cpp /* * Copyright (C) 2012 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include "stdafx.h" #include "ApplicationsModel.h" #include "ApplicationsPropertyPageUI.h" #include "Runner.h" #include "WindowsLiveAction.h" // An index to ActionGroup static const int groupNames [] = {IDS_GROUPNAME_NONE, IDS_GROUPNAME_WINDOWS, IDS_GROUPNAME_INTERNET, IDS_GROUPNAME_OFFICE}; wstring ApplicationsModel::_getGroupName(ActionGroup actionGroup) { wchar_t szGroupName[MAX_LOADSTRING]; LoadString(GetModuleHandle(NULL), groupNames[actionGroup], szGroupName, MAX_LOADSTRING); return wstring(szGroupName); } void ApplicationsModel::_processDependantItems() { for (unsigned int i = 0; i < m_items.size(); i++) { Action* itemAction = (Action *) m_items.at(i).GetData(); if (m_items[i].GetIsGroupName() == false) { _processDependantItem(itemAction); } } } wstring ApplicationsModel::_getActionDisplayName(Action *action) { wstring name = action->GetName(); if (action->GetStatus() == Selected && action->HasLicense()) { name+= L" *"; } return name; } void ApplicationsModel::BuildListOfItems() { for (int g = 0; g < ActionGroupLast; g++) { bool bFirstHit = false; for (unsigned int i = 0; i < m_availableActions->size(); i++) { Action* action = m_availableActions->at(i); if (action->IsVisible() == false || action->GetGroup() != (ActionGroup)g) continue; bool needed = action->IsNeed(); if (bFirstHit == false) { ApplicationItem applicationItem(_getGroupName((ActionGroup)g), NULL, true, true); m_items.push_back(applicationItem); bFirstHit = true; } if (needed) action->SetStatus(Selected); ApplicationItem applicationItem(_getActionDisplayName(action), action, false, needed == false); applicationItem.SetImageIndex(_getImageIndex(action->GetStatus())); m_items.push_back(applicationItem); } } _processDependantItems(); } int ApplicationsModel::_getItemIndexForItemData(void *data) { for (unsigned int i = 0; i < m_items.size(); i++) { Action* itemAction = (Action *) m_items.at(i).GetData(); if (itemAction == data) { return i; } } assert(false); return -1; } void ApplicationsModel::ProcessClickOnItem(ApplicationItem applicationItem) { if (applicationItem.GetIsGroupName()) return; Action* action = (Action*) applicationItem.GetData(); switch (action->GetStatus()) { case NotSelected: action->SetStatus(Selected); break; case Selected: action->SetStatus(NotSelected); break; default: return; // Non selectable item } int itemIdx = _getItemIndexForItemData(action); if (itemIdx != -1) { applicationItem.SetImageIndex(_getImageIndex(action->GetStatus())); m_items[itemIdx] = applicationItem; m_applicationsView->UpdateItem(applicationItem); } _processDependantItem(action); } void ApplicationsModel::_processDependantItem(Action* action) { Action* dependant = action->AnotherActionDependsOnMe(m_availableActions); if (dependant == NULL) return; ActionStatus prevStatus = dependant->GetStatus(); dependant->CheckPrerequirements(action); if (prevStatus == dependant->GetStatus()) return; int itemIdx = _getItemIndexForItemData(dependant); if (itemIdx != -1) { ApplicationItem applicationItem; applicationItem = m_items.at(itemIdx); applicationItem.SetIsDisabled(dependant->IsNeed() == false); applicationItem.SetImageIndex(_getImageIndex(dependant->GetStatus())); m_items[itemIdx] = applicationItem; m_applicationsView->UpdateItem(applicationItem); } } ImageIndex ApplicationsModel::_getImageIndex(ActionStatus status) { switch (status) { case NotSelected: return ImageIndexNone; case Selected: return ImageIndexBlack; case CannotBeApplied: case NotInstalled: return ImageIndexGrey; case AlreadyApplied: return ImageIndexGreen; default: return ImageIndexNone; } } bool ApplicationsModel::_anyActionNeedsInternetConnection() { bool needInet = false; for (unsigned int i = 0; i < m_items.size(); i++) { if (m_items[i].GetIsGroupName()) continue; Action* action = (Action *) m_items.at(i).GetData(); if (action->GetStatus() == Selected && action->IsDownloadNeed()) { needInet = true; break; } } return needInet; } bool ApplicationsModel::ShouldShowNoInternetConnectionDialog() { return _anyActionNeedsInternetConnection() && Inet::IsThereConnection() == false; } vector <ApplicationLegendItem> ApplicationsModel::GetLegendItems() { vector <ApplicationLegendItem> applicationLegendItems; ActionStatus statuses [] = {Selected, AlreadyApplied, CannotBeApplied}; int resources [] = {IDS_LEGEND_SELECTED, IDS_LEGEND_ALREADYAPPLIED, IDS_LEGEND_CANNOT}; for (int l = 0; l <sizeof(statuses) / sizeof(statuses[0]); l++) { wchar_t szString [MAX_LOADSTRING]; LoadString(GetModuleHandle(NULL), resources[l], szString, MAX_LOADSTRING); applicationLegendItems.push_back(ApplicationLegendItem(szString, _getImageIndex(statuses[l]))); } return applicationLegendItems; } bool ApplicationsModel::DoLicensesNeedToBeAccepted() { for (unsigned int i = 0; i < m_availableActions->size (); i++) { Action* action = m_availableActions->at(i); if (action->GetStatus() != Selected) continue; if (action->HasLicense()) return true; } return false; } bool ApplicationsModel::WindowsLiveRebootRequired() { for (unsigned int i = 0; i < m_availableActions->size (); i++) { Action* action = m_availableActions->at(i); if (action->GetID() != WindowsLiveActionID) continue; WindowsLiveAction* live = (WindowsLiveAction *) action; return live->IsNeed() && live->IsPreRebootRequired(); } assert(false); return false; } void ApplicationsModel::LogRunningProcesses() { Runner runner; vector <wstring> names; wstring log; names = runner.GetRunningProcessesNames(); for (unsigned int i = 0; i < names.size(); i++) { log += names[i]; if (i +1 < names.size()) log += L", "; } g_log.Log(L"ApplicationsModel::LogRunningProcesses: %s", (wchar_t *) log.c_str()); } <file_sep>/CatalanitzadorPerAlWindows/Actions/OpenOfficeAction.h /* * Copyright (C) 2012 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #pragma once #include "Action.h" #include "IRunner.h" #include "IOSVersion.h" #include "IRegistry.h" #include "Runner.h" #include "XmlParser.h" #include "ActionExecution.h" #define OPENOFFICCE_PROGRAM_REGKEY L"SOFTWARE\\OpenOffice.org\\OpenOffice.org" class OpenOfficeAction : public Action, public ActionExecution { public: OpenOfficeAction(IRegistry* registry, IRunner* runner, DownloadManager *downloadManager); ~OpenOfficeAction(); virtual wchar_t* GetName(); virtual wchar_t* GetDescription(); virtual ActionID GetID() const { return OpenOfficeActionID;}; virtual ActionGroup GetGroup() const {return ActionGroupOfficeAutomation;} virtual bool Download(ProgressStatus progress, void *data); virtual bool IsNeed(); virtual void Execute(); virtual ActionStatus GetStatus(); virtual const wchar_t* GetVersion() {return m_version.c_str();} virtual void CheckPrerequirements(Action * action); virtual ExecutionProcess GetExecutingProcess(); virtual void FinishExecution(ExecutionProcess process); protected: void _readVersionInstalled(); void _setDefaultLanguage(); bool _isDefaultLanguage(); virtual void _getPreferencesFile(wstring& location); virtual bool _isLangPackInstalled(); private: bool _extractCabFile(wchar_t * file, wchar_t * path); void _removeCabTempFiles(); static bool _readNodeCallback(XmlNode node, void *data); wstring m_version; IRunner* m_runner; IRegistry* m_registry; wchar_t m_szFilename[MAX_PATH]; wchar_t m_szTempPath[MAX_PATH]; wchar_t m_szTempPathCAB[MAX_PATH]; }; <file_sep>/CatalanitzadorPerAlWindows.UnitTests/Actions/OpenOfficeActionTest.cpp /* * Copyright (C) 2012 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include "stdafx.h" #include "Defines.h" #include "OpenOfficeAction.h" #include "Application.h" using ::testing::Return; using ::testing::_; using ::testing::StrCaseEq; using ::testing::DoAll; #define ENUM_REG_INDEX0 0 #define ENUM_REG_INDEX1 1 class OpenOfficeActionTest : public OpenOfficeAction { public: OpenOfficeActionTest::OpenOfficeActionTest(IRegistry* registry, IRunner* runner, DownloadManager *downloadManager) : OpenOfficeAction(registry, runner, downloadManager) {}; public: using OpenOfficeAction::_readVersionInstalled; using OpenOfficeAction::_isDefaultLanguage; using OpenOfficeAction::_setDefaultLanguage; void SetFilename(wstring file) { m_filename = file; } protected: virtual void _getPreferencesFile(wstring& location) { assert(m_filename.size() > 0); Application::GetExecutionLocation(location); location += L"OpenOffice.org\\"; location += m_filename; } virtual bool _isLangPackInstalled() { return false; } private: wstring m_filename; }; #define CreateOpenOfficeAction \ RegistryMock registryMockobj; \ RunnerMock runnerMock; \ OpenOfficeActionTest openofficeAction(&registryMockobj, &runnerMock, new DownloadManager()); void SetOpenOfficeVersion(RegistryMock& registryMockobj, wstring version) { EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(OPENOFFICCE_PROGRAM_REGKEY), false)).WillRepeatedly(Return(true)); EXPECT_CALL(registryMockobj, RegEnumKey(ENUM_REG_INDEX0,_)).WillRepeatedly(DoAll(SetArgWStringPar2(version), Return(true))); EXPECT_CALL(registryMockobj, RegEnumKey(ENUM_REG_INDEX1,_)).WillRepeatedly(Return(false)); } TEST(OpenOfficeActionTest, _readVersionInstalled) { const wchar_t* OPENOFFICE_VERSION = L"3.3"; CreateOpenOfficeAction; SetOpenOfficeVersion(registryMockobj, OPENOFFICE_VERSION); openofficeAction._readVersionInstalled(); EXPECT_THAT(openofficeAction.GetVersion(), StrCaseEq(OPENOFFICE_VERSION)); } TEST(OpenOfficeActionTest, CheckPrerequirements_NonSupportedVersion) { const wchar_t* OPENOFFICE_VERSION = L"3.1"; CreateOpenOfficeAction; SetOpenOfficeVersion(registryMockobj, OPENOFFICE_VERSION); openofficeAction.CheckPrerequirements(NULL); EXPECT_THAT(openofficeAction.GetStatus(), CannotBeApplied); } TEST(OpenOfficeActionTest, _isDefaultLanguage_No) { CreateOpenOfficeAction; openofficeAction.SetFilename(L"registrymodifications_default_no.xcu"); EXPECT_FALSE(openofficeAction._isDefaultLanguage()); } TEST(OpenOfficeActionTest, _isDefaultLanguage_Yes) { CreateOpenOfficeAction; openofficeAction.SetFilename(L"registrymodifications_default_yes.xcu"); EXPECT_TRUE(openofficeAction._isDefaultLanguage()); } TEST(OpenOfficeActionTest, _setDefaultLanguage) { wstring src, trg; CreateOpenOfficeAction; const wchar_t* TARGET_FILE = L"registrymodifications_modified.xcu"; Application::GetExecutionLocation(src); src += L"OpenOffice.org\\"; trg = src; src += L"registrymodifications_default_no.xcu"; trg += TARGET_FILE; CopyFile(src.c_str(), trg.c_str(), FALSE); openofficeAction.SetFilename(TARGET_FILE); openofficeAction._setDefaultLanguage(); EXPECT_TRUE(openofficeAction._isDefaultLanguage()); DeleteFile(trg.c_str()); } <file_sep>/CatalanitzadorPerAlWindows/Inspectors/CCleanerInspector.cpp /* * Copyright (C) 2012 <NAME> <<EMAIL>> * Copyright (C) 2012 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include "stdafx.h" #include "CCleanerInspector.h" #include "FileVersionInfo.h" CCleanerInspector::CCleanerInspector(IRegistry* registry) { m_registry = registry; } #define PROGRAM_REGKEY L"Software\\Piriform\\CCleaner" void CCleanerInspector::Execute() { _readVersionInstalled(); _readLangInstalled(); } void CCleanerInspector::_readVersionInstalled() { wchar_t szPath[1024] = L""; if (m_registry->OpenKey(HKEY_LOCAL_MACHINE, PROGRAM_REGKEY, false)) { m_registry->GetString(L"", szPath, sizeof(szPath)); m_registry->Close(); } wstring version = L""; wstring file = wstring(szPath); if (file.size() > 0) { file += L"\\CCleaner.exe"; FileVersionInfo fileVersion; fileVersion.SetFilename(file); version = fileVersion.GetVersion(); } g_log.Log(L"CCleanerInspector::_readVersion version '%s'", (wchar_t*) version.c_str()); m_KeyValues.push_back(InspectorKeyValue(L"version", version.c_str())); } void CCleanerInspector::_readLangInstalled() { wchar_t szLanguage[1024] = L""; if (m_registry->OpenKey(HKEY_CURRENT_USER, PROGRAM_REGKEY, false)) { m_registry->GetString(L"Language", szLanguage, sizeof(szLanguage)); m_registry->Close(); } g_log.Log(L"CCleanerInspector::_readLangInstalled '%s'", szLanguage); m_KeyValues.push_back(InspectorKeyValue(L"lang", szLanguage)); } <file_sep>/CatalanitzadorPerAlWindows/Actions/ConfigureLocaleAction.cpp /* * Copyright (C) 2011 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include "stdafx.h" #include "ConfigureLocaleAction.h" #include "Registry.h" #include "OSVersion.h" #include "Resources.h" ConfigureLocaleAction::ConfigureLocaleAction() { szCfgFile[0] = NULL; } ConfigureLocaleAction::~ConfigureLocaleAction() { if (szCfgFile[0] != NULL && GetFileAttributes(szCfgFile) != INVALID_FILE_ATTRIBUTES) { DeleteFile(szCfgFile); } } wchar_t* ConfigureLocaleAction::GetName() { return _getStringFromResourceIDName(IDS_CONFIGURELOCALEACTION_NAME, szName); } wchar_t* ConfigureLocaleAction::GetDescription() { return _getStringFromResourceIDName(IDS_CONFIGURELOCALEACTION_DESCRIPTION, szDescription); } bool ConfigureLocaleAction::_isCatalanLocaleActive() { wchar_t szValue[1024]; bool bCatalanActive = false; Registry registry; if (registry.OpenKey(HKEY_CURRENT_USER, L"Control Panel\\International", false)) { if (registry.GetString(L"Locale", szValue, sizeof (szValue))) { // 0403 locale code for CA-ES if (wcsstr(szValue, L"0403") != NULL) bCatalanActive = true; } registry.Close(); } return bCatalanActive; } bool ConfigureLocaleAction::IsNeed() { bool bNeed; bNeed = _isCatalanLocaleActive() == false; if (bNeed == false) status = AlreadyApplied; g_log.Log(L"ConfigureLocaleAction::IsNeed returns %u", (wchar_t *) bNeed); return bNeed; } void ConfigureLocaleAction::Execute() { wchar_t szConfigFileName[MAX_PATH]; wchar_t szParams[MAX_PATH]; wchar_t szApp[MAX_PATH]; LPCWSTR resource; OSVersion version; GetTempPath(MAX_PATH, szCfgFile); GetSystemDirectory(szApp, MAX_PATH); wcscat_s(szApp, L"\\control.exe "); status = InProgress; if (version.GetVersion() == WindowsXP) { //Documentation: http://support.microsoft.com/default.aspx?scid=kb;en-us;289125 wcscpy_s(szConfigFileName, L"regopts.txt"); resource = (LPCWSTR)IDR_CONFIG_LOCALE_WINXP; } else // Windows Vista and 7 { //Documentation: http://blogs.msdn.com/b/michkap/archive/2006/05/30/610505.aspx wcscpy_s(szConfigFileName, L"regopts.xml"); resource = (LPCWSTR)IDR_CONFIG_LOCALE_WINVISTA; } wcscat_s(szCfgFile, szConfigFileName); Resources::DumpResource(L"CONFIG_FILES", resource, szCfgFile); swprintf_s(szParams, L" intl.cpl,,/f:\"%s\"", szCfgFile); g_log.Log(L"ConfigureLocaleAction::Execute '%s' with params '%s'", szApp, szParams); status = InProgress; m_runner.Execute(szApp, szParams); } ActionStatus ConfigureLocaleAction::GetStatus() { if (status == InProgress) { if (m_runner.IsRunning()) return InProgress; if (_isCatalanLocaleActive()) { status = Successful; } else { status = FinishedWithError; } g_log.Log(L"ConfigureLocaleAction::GetStatus is '%s'", status == Successful ? L"Successful" : L"FinishedWithError"); } return status; } <file_sep>/Server/stats/class.options.php <?php class StatsOptions { private $_optionNames; private $_db; private $_catalanitzador; public function __construct($db,$catalanitzador) { $this->_optionNames = array ( 0 => "OptionSystemRestore", 1 => "OptionDialect", 2 => "OptionShowSecDlg"); $this->_db = $db; $this->_catalanitzador = $catalanitzador; } public function GetOptions() { $v = $this->_catalanitzador->get_version_selected(); if(!empty($v)) { $query = "select distinct OptionId from options, sessions ". "where options.SessionId = sessions.Id AND ApplicationsID in ($v)"; } else { $query = "select distinct OptionId from options"; } $results = $this->_db->get_results($query); $options = array(); if(empty($results)) return $options; foreach($results as $result) { if(isset($this->_optionNames[$result->OptionId])) { $result_name = $this->_optionNames[$result->OptionId]; } else { $result_name = $result->OptionId; } $options[$result->OptionId] = $result_name; } return $options; } public function GetOptionValues($id) { $optionValues = array(); if(!isset($id)) return $optionValues; $v = $this->_catalanitzador->get_version_selected(); if(!empty($v)) { $v = " AND ApplicationsID in ($v)"; } else { $v = ''; } $results = $this->_db->get_results("select OptionId, Value, count(Value) as ". "Total from options, sessions where OptionId = $id ". "AND options.SessionId = sessions.Id $v group by OptionId,Value;"); if(empty($results)) return $optionValues; foreach($results as $result) { $optionValues[$result->Value] = $result->Total; } return $optionValues; } } ?> <file_sep>/CatalanitzadorPerAlWindows.UnitTests/Actions/iTunesActionTest.cpp /* * Copyright (C) 2013 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include "stdafx.h" #include "Defines.h" #include "iTunesAction.h" using ::testing::Return; using ::testing::_; using ::testing::StrCaseEq; using ::testing::DoAll; using ::testing::ReturnRefOfCopy; class iTunesActionTest : public iTunesAction { public: iTunesActionTest(IRegistry* registry, IFileVersionInfo* fileVersionInfo) : iTunesAction(registry, fileVersionInfo) {}; public: using iTunesAction::_isDefaultLanguageForUser; using iTunesAction::_isDefaultLanguage; }; #define CreateiTunesAction \ RegistryMock registryMockobj; \ FileVersionInfoMock fileVersionInfoMock; \ iTunesActionTest iTunes(&registryMockobj, &fileVersionInfoMock); #define CATALAN_LANGCODE L"1027" #define SPANISH_LANGCODE L"1034" void _setMockForUserLanguage(RegistryMock& registryMockobj, const wchar_t* language) { EXPECT_CALL(registryMockobj, OpenKey(HKEY_CURRENT_USER, StrCaseEq(L"Software\\Apple Computer, Inc.\\iTunes"), false)).WillRepeatedly(Return(true)); EXPECT_CALL(registryMockobj, GetString(StrCaseEq(L"LangID"),_ ,_)).WillRepeatedly(DoAll(SetArgCharStringPar2(language), Return(true))); } void _setMockForUserLanguageFalse(RegistryMock& registryMockobj) { EXPECT_CALL(registryMockobj, OpenKey(HKEY_CURRENT_USER, StrCaseEq(L"Software\\Apple Computer, Inc.\\iTunes"), false)).WillRepeatedly(Return(true)); EXPECT_CALL(registryMockobj, GetString(StrCaseEq(L"LangID"),_ ,_)).WillRepeatedly(Return(false)); } void _setMockForMachineLanguage(RegistryMock& registryMockobj, const wchar_t* language) { EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"Software\\Apple Computer, Inc.\\iTunes"), false)).WillRepeatedly(Return(true)); EXPECT_CALL(registryMockobj, GetString(StrCaseEq(L"InstalledLangID"),_ ,_)).WillRepeatedly(DoAll(SetArgCharStringPar2(language), Return(true))); } void _setMockForProgramFolderTrue(RegistryMock& registryMockobj) { EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"Software\\Apple Computer, Inc.\\iTunes"), false)).WillRepeatedly(Return(true)); EXPECT_CALL(registryMockobj, GetString(StrCaseEq(L"ProgramFolder"),_ ,_)).WillRepeatedly(DoAll(SetArgCharStringPar2(L"Folder"), Return(true))); } void _setiTunesVersion(FileVersionInfoMock& fileVersionInfoMock, wchar_t* version) { wstring s(version); EXPECT_CALL(fileVersionInfoMock, GetVersion()).WillRepeatedly(ReturnRefOfCopy(s)); } TEST(iTunesActionTest, _isDefaultLanguageForUser_True) { CreateiTunesAction; _setMockForUserLanguage(registryMockobj, CATALAN_LANGCODE); EXPECT_TRUE(iTunes._isDefaultLanguageForUser() == true); } TEST(iTunesActionTest, _isDefaultLanguageForUser_False) { CreateiTunesAction; _setMockForUserLanguage(registryMockobj, SPANISH_LANGCODE); EXPECT_FALSE(iTunes._isDefaultLanguageForUser() == true); } TEST(iTunesActionTest, _isDefaultLanguage_MachineSpanish_UserCatalan_True) { CreateiTunesAction; _setMockForMachineLanguage(registryMockobj, SPANISH_LANGCODE); _setMockForUserLanguage(registryMockobj, CATALAN_LANGCODE); EXPECT_TRUE(iTunes._isDefaultLanguage()); } TEST(iTunesActionTest, _isDefaultLanguage_MachineCatalan_UserSpanish_False) { CreateiTunesAction; _setMockForMachineLanguage(registryMockobj, CATALAN_LANGCODE); _setMockForUserLanguage(registryMockobj, SPANISH_LANGCODE); EXPECT_FALSE(iTunes._isDefaultLanguage()); } TEST(iTunesActionTest, _isDefaultLanguage_MachineCatalan_UserNone_True) { CreateiTunesAction; _setMockForMachineLanguage(registryMockobj, CATALAN_LANGCODE); _setMockForUserLanguageFalse(registryMockobj); EXPECT_TRUE(iTunes._isDefaultLanguage()); } TEST(iTunesActionTest, CheckPrerequirements_OldVersion_False) { CreateiTunesAction; _setMockForProgramFolderTrue(registryMockobj); _setiTunesVersion(fileVersionInfoMock, L"10.6.2.0"); iTunes.CheckPrerequirements(NULL); EXPECT_THAT(iTunes.GetStatus(), CannotBeApplied); }<file_sep>/CatalanitzadorPerAlWindows/Actions/WindowsLiveAction.cpp /* * Copyright (C) 2012 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include "stdafx.h" #include "WindowsLiveAction.h" #include "Winver.h" #include "Url.h" #include "ConfigurationInstance.h" #include "LogExtractor.h" #define MS_LIVE_ESSENTIALS_2009 14 #define CATALAN_WINLANGCODE 3 WindowsLiveAction::WindowsLiveAction(IRegistry* registry, IRunner* runner, IFileVersionInfo* fileVersionInfo, DownloadManager* downloadManager) : Action(downloadManager) { m_registry = registry; m_runner = runner; m_fileVersionInfo = fileVersionInfo; m_szFilename[0]=NULL; } WindowsLiveAction::~WindowsLiveAction() { if (m_szFilename[0] != NULL && GetFileAttributes(m_szFilename) != INVALID_FILE_ATTRIBUTES) { DeleteFile(m_szFilename); } } wchar_t* WindowsLiveAction::GetName() { return _getStringFromResourceIDName(IDS_WINDOWSLIVE_NAME, szName); } wchar_t* WindowsLiveAction::GetDescription() { return _getStringFromResourceIDName(IDS_WINDOWSLIVE_DESCRIPTION, szDescription); } bool WindowsLiveAction::IsNeed() { bool bNeed; switch(GetStatus()) { case NotInstalled: case AlreadyApplied: case CannotBeApplied: bNeed = false; break; default: bNeed = true; break; } g_log.Log(L"WindowsLiveAction::IsNeed returns %u (status %u)", (wchar_t *) bNeed, (wchar_t*) GetStatus()); return bNeed; } bool WindowsLiveAction::Download(ProgressStatus progress, void *data) { ConfigurationFileActionDownload downloadVersion; wchar_t version[32]; swprintf_s(version, L"%u", _getMajorVersion()); downloadVersion = ConfigurationInstance::Get().GetRemote().GetDownloadForActionID(GetID(), ApplicationVersion(version)); GetTempPath(MAX_PATH, m_szFilename); wcscat_s(m_szFilename, downloadVersion.GetFilename().c_str()); return m_downloadManager->GetFileAndVerifyAssociatedSha1(downloadVersion, m_szFilename, progress, data); } const wchar_t* WindowsLiveAction::GetVersion() { if (m_version.length() == 0) { _readVersionInstalled(); } return m_version.c_str(); } void WindowsLiveAction::_readVersionInstalled() { if (m_version.size() > 0) return; wstring location; _getInstallerLocation(location); m_fileVersionInfo->SetFilename(location); m_version = m_fileVersionInfo->GetVersion(); } void WindowsLiveAction::_getInstallerLocation(wstring& location) { wchar_t szPath[MAX_PATH]; SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES|CSIDL_FLAG_CREATE, NULL, 0, szPath); location = szPath; location += L"\\Windows Live\\Installer\\wlarp.exe"; } void WindowsLiveAction::Execute() { wchar_t szParams[MAX_PATH] = L""; wchar_t szApp[MAX_PATH] = L""; wstring location; _getInstallerLocation(location); // Live Essential 2009/2010/2011 parameters: http://www.mydigitallife.info/windows-live-essentials-unattended-silent-setup-installation-switches/ wcscpy_s(szApp, m_szFilename); // By selecting only Silverlight the installer will update only the installer apps // instead of installing also new ones. This saves us to dectect which exact component // is installed and uninstall it wcscat_s(szApp, L" /AppSelect:Silverlight /quiet"); SetStatus(InProgress); g_log.Log(L"WindowsLiveAction::Execute '%s' with params '%s'", szApp, szParams); m_runner->Execute(NULL, szApp); } ActionStatus WindowsLiveAction::GetStatus() { if (status == InProgress) { if (m_runner->IsRunning()) return InProgress; if (_isLangSelected()) { SetStatus(Successful); } else { SetStatus(FinishedWithError); _dumpWLSetupErrors(); } g_log.Log(L"WindowsLiveAction::GetStatus is '%s'", status == Successful ? L"Successful" : L"FinishedWithError"); } return status; } int WindowsLiveAction::_getMajorVersion() { wstring location; _getInstallerLocation(location); m_fileVersionInfo->SetFilename(location); return m_fileVersionInfo->GetMajorVersion(); } #define LANG_REGKEY L"Software\\Microsoft\\Windows Live\\Common\\" #define LANGUAGE_CODE L"CA" bool WindowsLiveAction::_isLangSelected2011() { bool bSelected = false; wchar_t szLanguage[MAX_PATH] = L""; if (m_registry->OpenKey(HKEY_CURRENT_USER, LANG_REGKEY, false)) { if (m_registry->GetString(L"UserLanguage", szLanguage, sizeof(szLanguage))) { bSelected = _wcsnicmp(szLanguage, LANGUAGE_CODE, wcslen(LANGUAGE_CODE)) == 0; } m_registry->Close(); } g_log.Log(L"WindowsLiveAction::_isLangSelected2011. Language %s", szLanguage); return bSelected; } bool WindowsLiveAction::_isLangSelected2009() { wchar_t szPath[MAX_PATH]; wstring location; DWORD langCode; SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES|CSIDL_FLAG_CREATE, NULL, 0, szPath); location = szPath; location += L"\\Windows Live\\Installer\\wlsres.dll"; m_fileVersionInfo->SetFilename(location); langCode = m_fileVersionInfo->GetLanguageCode(); g_log.Log(L"WindowsLiveAction::_isLangSelected2009. Language '%u'", (wchar_t *)langCode); return langCode == CATALAN_WINLANGCODE; } bool WindowsLiveAction::_isLangSelected() { if (_getMajorVersion() == MS_LIVE_ESSENTIALS_2009) { return _isLangSelected2009(); } return _isLangSelected2011(); } #define REBOOT_REQUIRED_KEY L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update\\RebootRequired" bool WindowsLiveAction::IsPreRebootRequired() { if (_getMajorVersion() == MS_LIVE_ESSENTIALS_2009) { return false; } bool rebootRequiered = false; if (m_registry->OpenKey(HKEY_LOCAL_MACHINE, REBOOT_REQUIRED_KEY, false)) { wstring value; rebootRequiered = m_registry->RegEnumValue(0, value); m_registry->Close(); } return rebootRequiered; } bool WindowsLiveAction::_isDownloadAvailable() { wchar_t version[32]; ConfigurationFileActionDownload downloadVersion; swprintf_s(version, L"%u", _getMajorVersion()); downloadVersion = ConfigurationInstance::Get().GetRemote().GetDownloadForActionID(GetID(), ApplicationVersion(version)); return downloadVersion.IsEmpty() == false; } void WindowsLiveAction::CheckPrerequirements(Action * action) { _readVersionInstalled(); if (m_version.size() > 0) { if (_isLangSelected() == true) { SetStatus(AlreadyApplied); return; } if (_isDownloadAvailable() == false) { _getStringFromResourceIDName(IDS_NOTSUPPORTEDVERSION, szCannotBeApplied); g_log.Log(L"WindowsLiveAction::CheckPrerequirements. Version not supported"); SetStatus(CannotBeApplied); return; } if (IsPreRebootRequired()) { _getStringFromResourceIDName(IDS_REBOOTREQUIRED, szCannotBeApplied); g_log.Log(L"WindowsLiveAction::CheckPrerequirements. Reboot required"); SetStatus(CannotBeApplied); return; } } else { _setStatusNotInstalled(); return; } } #define KEYWORD_TOSEARCH L"Error" #define LINES_TODUMP 7 #define LOGS_PATH L"\\Microsoft\\WLSetup\\Logs\\" wstring WindowsLiveAction::_getMostRecentWLSetupLogFile() { HANDLE hFind; WIN32_FIND_DATA findFileData; wchar_t szLogPath[MAX_PATH]; wchar_t szFilename[MAX_PATH]; wchar_t szRecentFilename[MAX_PATH]; FILETIME filetime = {0}; wstring filename; SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA|CSIDL_FLAG_CREATE, NULL, 0, szLogPath); wcscat_s(szLogPath, LOGS_PATH); wcscpy_s(szFilename, szLogPath); wcscat_s(szFilename, L"*.log"); hFind = FindFirstFile(szFilename, &findFileData); if (hFind == INVALID_HANDLE_VALUE) { g_log.Log(L"WindowsLiveAction::_getMostRecentWLSetupLogFile. Cannot open 's%'", szFilename); return wstring(); } // If there are multiple files, select the most recent one do { if (findFileData.ftLastWriteTime.dwHighDateTime > filetime.dwHighDateTime || findFileData.ftLastWriteTime.dwHighDateTime == filetime.dwHighDateTime && findFileData.ftLastWriteTime.dwLowDateTime > filetime.dwLowDateTime) { wcscpy_s(szRecentFilename, findFileData.cFileName); filetime = findFileData.ftLastWriteTime; } } while (FindNextFile(hFind, &findFileData) != 0); FindClose(hFind); filename = szLogPath; filename += szRecentFilename; return filename; } void WindowsLiveAction::_dumpWLSetupErrors() { wstring filename; filename = _getMostRecentWLSetupLogFile(); if (filename.empty()) { return; } Sleep(10000); // Since the WLSetup.exe process exists until you can read the file it takes some seconds LogExtractor logExtractor(filename, LINES_TODUMP); logExtractor.SetFileIsUnicode(false); logExtractor.ExtractLogFragmentForKeyword(KEYWORD_TOSEARCH); logExtractor.DumpLines(); }<file_sep>/CatalanitzadorPerAlWindows/Application/CatalanitzadorPerAlWindows.cpp /* * Copyright (C) 2011 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include "stdafx.h" #include "CatalanitzadorPerAlWindows.h" #include "PropertyPageUI.h" #include "InstallPropertyPageUI.h" #include "FinishPropertyPageUI.h" #include "PropertySheetUI.h" #include "ApplicationsPropertyPageUI.h" #include "IApplicationsPropertyPageUI.h" #include "WelcomePropertyPageUI.h" #include "ApplicationSheetUI.h" #include "ActiveX.h" #include "Authorization.h" #include "guid.h" #include "Registry.h" #include "ApplicationVersion.h" #include "Runner.h" #include "CommandLine.h" #include "SystemRestore.h" #include "HttpFormInet.h" #include "ApplicationsModel.h" #include "FinishModel.h" CatalanitzadorPerAWindows::CatalanitzadorPerAWindows(HINSTANCE hInstance) : m_actions(&m_downloadManager) { m_hInstance = hInstance; m_hEvent = NULL; } CatalanitzadorPerAWindows::~CatalanitzadorPerAWindows() { g_log.Close(); if (m_hEvent != NULL) CloseHandle(m_hEvent); } void CatalanitzadorPerAWindows::Run(wstring commandLine) { Registry registry; CommandLine commandLineProcessor(&m_actions); _initLog(); commandLineProcessor.Process(commandLine); if (commandLineProcessor.GetRunningCheck() == true) { if (_isAlreadyRunning() == true) return; } Guid guid(&registry); guid.Get(); m_serializer.OpenHeader(); m_serializer.Serialize(&guid); guid.Store(); if (_supportedOS() == true && _hasAdminPermissionsDialog() == true) { OleInitialize(0); AXRegister(); _createWizard(); } } void CatalanitzadorPerAWindows::_initLog() { wchar_t szApp[1024]; swprintf_s(szApp, L"CatalanitzadorPerAlWindows version %s", STRING_VERSION); g_log.CreateLogInTempDirectory(L"CatalanitzadorPerAlWindows.log",szApp); wchar_t szOSInfo [2048]; m_osVersion.GetLogInfo(szOSInfo, sizeof (szOSInfo)); g_log.Log(szOSInfo); } bool CatalanitzadorPerAWindows::_supportedOS() { int id; OperatingVersion version; version = m_osVersion.GetVersion(); if (version == Windows2000 || version == WindowsXP64_2003 || version == Windows2012) { id = IDS_NOTSUPPORTEDOS; } else { return true; } wchar_t szMessage [MAX_LOADSTRING]; wchar_t szCaption [MAX_LOADSTRING]; HttpFormInet httpFormInet; UploadStatisticsThread uploadStatistics(&httpFormInet, &m_serializer, false); m_serializer.CloseHeader(); uploadStatistics.Start(); g_log.Log (L"Show unsupported OS dialog"); LoadString(GetModuleHandle(NULL), id, szMessage, MAX_LOADSTRING); LoadString(GetModuleHandle(NULL), IDS_MSGBOX_CAPTION, szCaption, MAX_LOADSTRING); MessageBox(NULL, szMessage, szCaption, MB_OK | MB_ICONINFORMATION); uploadStatistics.Wait(); return false; } bool CatalanitzadorPerAWindows::_hasAdminPermissionsDialog() { bool hasAdmin; hasAdmin = Authorization::UserHasAdminPermissions(); if (hasAdmin == false) { wchar_t szMessage [MAX_LOADSTRING]; wchar_t szCaption [MAX_LOADSTRING]; g_log.Log (L"Show not admin user dialog"); LoadString(GetModuleHandle(NULL), IDS_NOUSERADMIN, szMessage, MAX_LOADSTRING); LoadString(GetModuleHandle(NULL), IDS_MSGBOX_CAPTION, szCaption, MAX_LOADSTRING); MessageBox(NULL, szMessage, szCaption, MB_OK | MB_ICONINFORMATION); } return hasAdmin; } bool CatalanitzadorPerAWindows::_isAlreadyRunning() { m_hEvent = CreateEvent(NULL, TRUE, FALSE, L"Catalanitzador"); if (GetLastError() == ERROR_ALREADY_EXISTS) { CloseHandle(m_hEvent); m_hEvent = NULL; return true; } return false; } void CatalanitzadorPerAWindows::_createWizard() { ApplicationSheetUI sheet; WelcomePropertyPageUI welcome; ApplicationsModel applicationModel; ApplicationsPropertyPageUI applications(&applicationModel); InstallPropertyPageUI install; FinishModel finishModel; FinishPropertyPageUI finish(&finishModel); SystemRestore sysRestore; bool bSendStats = true; int systemRestore = TRUE; bool bDialectVariant = false; bool bShowSecDlg = false; #if _DEBUG bSendStats = false; systemRestore = FALSE; #endif if (sysRestore.Init() == false) systemRestore = -1; vector <Action *> acts = m_actions.GetActions(); welcome.setParent(&sheet); welcome.setPageButtons(NextButton); welcome.SetSendStats(&bSendStats); welcome.SetSystemRestore(&systemRestore); welcome.SetActions(&m_actions); welcome.SetShowSecDlg(&bShowSecDlg); welcome.createPage(m_hInstance, IDD_WELCOME, IDD_WELCOME_AERO, MAKEINTRESOURCE(IDS_WIZARD_HEADER_WELCOME)); sheet.addPage(&welcome); applicationModel.SetActions(&acts); applicationModel.SetView((IApplicationsPropertyPageUI *)&applications); applications.createPage(m_hInstance, IDD_APPLICATIONS, IDD_APPLICATIONS_AERO, MAKEINTRESOURCE(IDS_WIZARD_HEADER_APPLICATIONS)); applications.setParent(&sheet); applications.setPageButtons(NextBackButtons); applications.SetActions(&acts); applications.SetDialectVariant(&bDialectVariant); sheet.addPage(&applications); install.setParent(&sheet); install.setPageButtons(CancelButtonOnly); install.SetActions(&acts); install.SetSerializer(&m_serializer); install.SetSystemRestore(&systemRestore); install.StartSlideShowUnpack(); install.createPage(m_hInstance, IDD_INSTALL, IDD_INSTALL_AERO, MAKEINTRESOURCE(IDS_WIZARD_HEADER_INSTALL)); sheet.addPage(&install); finish.setParent(&sheet); finish.setPageButtons(FinishButtonOnly); finishModel.SetSystemRestore(&systemRestore); finishModel.SetSendStats(&bSendStats); finishModel.SetSerializer(&m_serializer); finishModel.SetActions(&acts); finishModel.SetDialectVariant(&bDialectVariant); finishModel.SetShowSecDlg(&bShowSecDlg); finish.createPage(m_hInstance, IDD_FINISH, IDD_FINISH_AERO, MAKEINTRESOURCE(IDS_WIZARD_HEADER_FINISH)); sheet.addPage(&finish); sheet.runModal(m_hInstance, NULL, (LPWSTR)IDS_WIZARD_TITLE); } <file_sep>/CatalanitzadorPerAlWindows/Actions/ChromeProfile.h /* * Copyright (C) 2012 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #pragma once #include <vector> #include <algorithm> using namespace std; class ChromeProfile { public: ChromeProfile(); ChromeProfile(wstring); bool WriteUILocale(); bool IsUiLocaleOk(); bool IsAcceptLanguagesOk(); bool UpdateAcceptLanguages(); void SetPath(wstring); bool ReadLanguageCode(wstring& langcode); protected: void ParseLanguage(wstring regvalue); void CreateJSONString(wstring &regvalue); void AddCatalanToArrayAndRemoveOldIfExists(); private: bool _isInstalled(); bool _findIntl(wstring,int&); bool _findSemicolon(wstring,int&); bool _findStartBlock(wstring,int&); bool _findAcceptedKey(wstring,int&); bool _findAcceptedValue(wstring,int&); bool _findLanguageString(wstring,int &,wstring &); bool _findAppLocaleKey(wstring line, int & pos); void _getFirstLanguage(wstring& regvalue); bool _writeAcceptLanguageCode(wstring langcode); wstring m_installLocation; vector<wstring> m_languages; }; <file_sep>/CatalanitzadorPerAlWindows.UnitTests/UI/Sheets/Models/ApplicationsModelTest.cpp /* * Copyright (C) 2012 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include "stdafx.h" #include "Defines.h" #include "ApplicationsModel.h" #include "ActionTest.h" class ActionGroupWindowsTest : public ActionTest { public: ActionGroupWindowsTest() { m_downloadManager = &m_testDownloadManager; } virtual ActionGroup GetGroup() const {return ActionGroupWindows;} private: DownloadManager m_testDownloadManager; }; class ApplicationsModelTest : public ApplicationsModel { public: using ApplicationsModel::_anyActionNeedsInternetConnection; }; class ActionGroupInternetTest : public ActionTest { public: virtual ActionGroup GetGroup() const {return ActionGroupInternet;} }; class ActionNotNeededTest : public ActionGroupWindowsTest { public: virtual bool IsNeed() {return false;} }; class ActionNoDownloadTest : public ActionGroupWindowsTest { public: virtual bool IsDownloadNeed() {return false;} }; class ActionHasLicense : public ActionTest { public: virtual LPCWSTR GetLicenseID() { return MAKEINTRESOURCE(0x1); }; }; #define CreateApplicationModelObject \ ApplicationsModelTest applicationModel; \ vector <Action *> actions; \ vector <ApplicationItem> applicationItems; \ applicationModel.SetActions(&actions); TEST(ApplicationsModelTest, BuildListOfItems_SingleGroup) { CreateApplicationModelObject; ActionGroupWindowsTest actionGroupWindows1; ActionGroupWindowsTest actionGroupWindows2; actions.push_back((Action *)&actionGroupWindows1); actions.push_back((Action *)&actionGroupWindows2); applicationModel.BuildListOfItems(); applicationItems = applicationModel.GetItems(); EXPECT_EQ(3, applicationItems.size()); EXPECT_TRUE(applicationItems.at(0).GetIsGroupName()); EXPECT_FALSE(applicationItems.at(1).GetIsGroupName()); EXPECT_FALSE(applicationItems.at(2).GetIsGroupName()); } TEST(ApplicationsModelTest, BuildListOfItems_MultipleGroup) { CreateApplicationModelObject; ActionGroupWindowsTest actionGroupWindows1; ActionGroupWindowsTest actionGroupWindows2; actions.push_back((Action *)&actionGroupWindows1); actions.push_back((Action *)&actionGroupWindows2); applicationModel.BuildListOfItems(); applicationItems = applicationModel.GetItems(); EXPECT_EQ(3, applicationItems.size()); EXPECT_TRUE(applicationItems.at(0).GetIsGroupName()); EXPECT_FALSE(applicationItems.at(1).GetIsGroupName()); EXPECT_FALSE(applicationItems.at(2).GetIsGroupName()); } TEST(ApplicationsModelTest, BuildListOfItems_Selected) { CreateApplicationModelObject; ActionGroupWindowsTest actionGroupWindows; ActionNotNeededTest actionNotNeeded; actions.push_back((Action *)&actionGroupWindows); actions.push_back((Action *)&actionNotNeeded); applicationModel.BuildListOfItems(); applicationItems = applicationModel.GetItems(); EXPECT_EQ(3, applicationItems.size()); EXPECT_FALSE(applicationItems.at(1).GetIsGroupName()); EXPECT_FALSE(applicationItems.at(1).GetIsDisabled()); EXPECT_FALSE(applicationItems.at(2).GetIsGroupName()); EXPECT_TRUE(applicationItems.at(2).GetIsDisabled()); } TEST(ApplicationsModelTest, DoLicensesNeedToBeAccepted_NotAccepted) { CreateApplicationModelObject; ActionGroupWindowsTest actionGroupWindows1; actionGroupWindows1.SetStatus(Selected); actions.push_back((Action *)&actionGroupWindows1); EXPECT_FALSE(applicationModel.DoLicensesNeedToBeAccepted()); } TEST(ApplicationsModelTest, DoLicensesNeedToBeAccepted_Accepted) { CreateApplicationModelObject; ActionHasLicense actionHasLicense; actionHasLicense.SetStatus(Selected); actions.push_back((Action *)&actionHasLicense); EXPECT_TRUE(applicationModel.DoLicensesNeedToBeAccepted()); } TEST(ApplicationsModelTest, _anyActionNeedsInternetConnection_True) { CreateApplicationModelObject; ActionGroupWindowsTest actionGroupWindowsTest; actionGroupWindowsTest.SetStatus(Selected); actions.push_back((Action *)&actionGroupWindowsTest); applicationModel.BuildListOfItems(); EXPECT_TRUE(applicationModel._anyActionNeedsInternetConnection()); } TEST(ApplicationsModelTest, _anyActionNeedsInternetConnection_False) { CreateApplicationModelObject; ActionNoDownloadTest actionNoDownloadTest; actionNoDownloadTest.SetStatus(Selected); actions.push_back((Action *)&actionNoDownloadTest); applicationModel.BuildListOfItems(); EXPECT_FALSE(applicationModel._anyActionNeedsInternetConnection()); } <file_sep>/CatalanitzadorPerAlWindows/UI/Sheets/InstallPropertyPageUI.h /* * Copyright (C) 2011 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #pragma once #include "PropertyPageUI.h" #include "Action.h" #include "Serializer.h" #include "SlideshowThread.h" #include "SystemRestoreThread.h" #include <vector> using namespace std; class InstallPropertyPageUI: public PropertyPageUI { public: void SetActions(vector <Action *> * value) { m_actions = value;} void StartSlideShowUnpack() { m_slideshow.Start();} void SetSystemRestore(int *pSystemRestore) { m_pSystemRestore = pSystemRestore;} void SetSerializer(Serializer* serializer) { m_serializer = serializer; } private: virtual void _onInitDialog(); virtual void _onShowWindow(); virtual void _onTimer(); static void _downloadStatus(int total, int current, void *data); void _execute(Action* action); bool _download(Action* action); void _completed(); void _updateSelectedActionsCounts(); void _windowsXPAsksCDWarning(); void _setTaskMarqueeMode(bool enable); void _waitExecutionComplete(Action* action); void _openURLInIE(); void _systemRestore(SystemRestoreThread& systemRestore); vector <Action *> * m_actions; HWND hTotalProgressBar; HWND hTaskProgressBar; HWND hDescription; BOOL ShowWindowOnce; int m_selActions; int m_downloads; int* m_pSystemRestore; Serializer* m_serializer; SlideshowThread m_slideshow; }; <file_sep>/CatalanitzadorPerAlWindows/UI/WindowsXPDialogCanceler.cpp /* * Copyright (C) 2012 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include "stdafx.h" #include "WindowsXPDialogCanceler.h" #define TIMER_ID_XP 2014 #define DIALOG_BOX_ATOM 32770 #define CANCEL_ID 2 #define EXPLORE_ID 0X6E #define COMBOBOX_ID 0X6B #define STATIC_ID 0X6C #define TEXT_ID 0X68 void WindowsXPDialogCanceler::Start() { if (m_version.GetVersion() != WindowsXP) return; m_nTimerID = SetTimer(NULL, TIMER_ID_XP, 500, _timerWindowsXPProc); } void WindowsXPDialogCanceler::Stop() { if (m_version.GetVersion() != WindowsXP) return; KillTimer(NULL, m_nTimerID); } bool WindowsXPDialogCanceler::_isXPDialogLocale(HWND hWnd) { HWND child = NULL; bool bFoundCombo, bCancel, bExplore; HWND hHwndCancel; bExplore = bFoundCombo = bCancel = false; while (true) { child = FindWindowEx(hWnd, child, NULL, NULL); if (child == NULL) break; switch (GetDlgCtrlID(child)) { case COMBOBOX_ID: bFoundCombo = true; break; case CANCEL_ID: hHwndCancel = child; bCancel = true; break; case EXPLORE_ID: bExplore = true; break; default: break; } } if (bFoundCombo && bCancel && bExplore) { PostMessage(hHwndCancel, BM_CLICK, 0,0); g_log.Log(L"WindowsXPDialogCanceler::_isXPDialogLocale. Found Windows XP dialog and sent click event"); return true; } return false; } bool WindowsXPDialogCanceler::_isXPDialogWinLPI(HWND hWnd) { HWND child = NULL; bool bFoundStatic, bFoundCancel, bFoundText; HWND hHwndCancel; bFoundStatic = bFoundCancel = bFoundText = false; while (true) { child = FindWindowEx(hWnd, child, NULL, NULL); if (child == NULL) break; switch (GetDlgCtrlID(child)) { case STATIC_ID: bFoundStatic = true; break; case CANCEL_ID: hHwndCancel = child; bFoundCancel = true; break; case TEXT_ID: bFoundText = true; break; default: break; } } if (bFoundStatic && bFoundCancel && bFoundText) { PostMessage(hHwndCancel, BM_CLICK, 0,0); g_log.Log(L"WindowsXPDialogCanceler::_isXPDialogLPI. Found Windows XP dialog and sent click event"); return true; } return false; } VOID CALLBACK WindowsXPDialogCanceler::_timerWindowsXPProc(HWND hWndTimer, UINT uMsg, UINT_PTR idEvent, DWORD dwTime) { HWND hWnd; hWnd = FindWindowEx(NULL,NULL, MAKEINTATOM(DIALOG_BOX_ATOM), NULL); while (hWnd) { if (_isXPDialogLocale(hWnd) || _isXPDialogWinLPI(hWnd)) { break; } hWnd = FindWindowEx(NULL, hWnd, MAKEINTATOM(DIALOG_BOX_ATOM), NULL); } } <file_sep>/CatalanitzadorPerAlWindows/Inspectors/ThunderbirdInspector.cpp /* * Copyright (C) 2012 <NAME> <<EMAIL>> * Copyright (C) 2012 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include "stdafx.h" #include "ThunderbirdInspector.h" #include "FileVersionInfo.h" ThunderbirdInspector::ThunderbirdInspector(IRegistry* registry) { m_registry = registry; } void ThunderbirdInspector::Execute() { _getVersionAndLocaleFromRegistry(); _readVersion(); _readLanguage(); } void ThunderbirdInspector::_readVersion() { if(m_version.length() > 0){ g_log.Log(L"ThunderbirdInspector::_readVersion version %s", (wchar_t*) m_version.c_str()); m_KeyValues.push_back(InspectorKeyValue(L"version", m_version.c_str())); } } void ThunderbirdInspector::_readLanguage() { if(m_locale.length() > 0){ g_log.Log(L"ThunderbirdInspector::_readLanguage language %s", (wchar_t*) m_locale.c_str()); m_KeyValues.push_back(InspectorKeyValue(L"language", m_locale.c_str())); } } #define THUNDERBIRD_REGKEY L"SOFTWARE\\Mozilla\\Mozilla Thunderbird" void ThunderbirdInspector::_getVersionAndLocaleFromRegistry() { if (m_registry->OpenKey(HKEY_LOCAL_MACHINE, THUNDERBIRD_REGKEY, false) == false) { g_log.Log(L"ThunderbirdInspector::_getVersionAndLocaleFromRegistry. Cannot open registry key"); m_version.clear(); m_locale.clear(); return; } wchar_t szVersion[1024]; if (m_registry->GetString(L"CurrentVersion", szVersion, sizeof(szVersion))) { int start, end; wstring version= szVersion; start = version.find(L" "); if (start != wstring::npos) { m_version = version.substr(0, start); start = version.find(L"(", start); if (start != wstring::npos) { start++; end = version.find(L")", start); if (end != wstring::npos) { m_locale = version.substr(start, end-start); } } } } m_registry->Close(); }<file_sep>/CatalanitzadorPerAlWindows/Actions/ChromeProfile.cpp /* * Copyright (C) 2013 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include "StdAfx.h" #include "ChromeProfile.h" enum JSONChromeState { NoState, InIntl, InIntlSemicolon, InIntlBlock, InAcceptedKey, InAcceptedSemicolon, InAcceptedValue, InAppLocaleKey, InAppLocaleSemicolon, InAppLocaleValue, EndParsing }; #ifndef CHROME_LANGUAGECODE #define CHROME_LANGUAGECODE L"ca" #endif ChromeProfile::ChromeProfile() { SetPath(L""); } ChromeProfile::ChromeProfile(wstring installLocation) { SetPath(installLocation); } void ChromeProfile::SetPath(wstring newPath) { m_installLocation = newPath; } bool ChromeProfile::_findIntl(wstring line, int & pos) { if(pos == wstring::npos) pos = 0; pos = line.find(L"\"intl\"",pos); return pos != wstring::npos; } bool ChromeProfile::_findSemicolon(wstring line, int & pos) { if(pos == wstring::npos) pos = 0; pos = line.find(L":",pos); return pos != wstring::npos; } bool ChromeProfile::_findStartBlock(wstring line, int & pos) { if(pos == wstring::npos) pos = 0; pos = line.find(L"{",pos); return pos != wstring::npos; } bool ChromeProfile::_findAcceptedKey(wstring line, int & pos) { if(pos == wstring::npos) pos = 0; pos = line.find(L"\"accept_languages\"",pos); return pos != wstring::npos; } bool ChromeProfile::_findAppLocaleKey(wstring line, int & pos) { if(pos == wstring::npos) pos = 0; pos = line.find(L"\"app_locale\"",pos); return pos != wstring::npos; } bool ChromeProfile::_findLanguageString(wstring line,int & pos,wstring & langcode) { wstring tempLang; if(pos == wstring::npos) pos = 0; wchar_t prev = L'0'; bool reading = false; bool found = false; for(unsigned int i = pos; i < line.length() && found == false; ++i) { if(line[i] == L'"' && prev != L'\\') { if(reading == false) { // we start parsing the langcode reading = true; pos = i+1; } else { // all langcode string parsed langcode = tempLang; found = true; } } else { if(reading) { tempLang.push_back(line[i]); } } prev = line[i]; } return found; } bool ChromeProfile::IsUiLocaleOk() { wstring langcode; if(m_installLocation.empty() == false) { wifstream reader; wstring line; wstring path = L"/../User Data/Local State"; path = m_installLocation + path; reader.open(path.c_str()); if(reader.is_open()) { int currentState = NoState; int pos = 0; while(!(getline(reader,line)).eof()) { if(currentState == NoState) { if(_findIntl(line,pos)) currentState = InIntl; } if(currentState == InIntl) { if(_findSemicolon(line,pos)) currentState = InIntlSemicolon; } if(currentState == InIntlSemicolon) { if(_findStartBlock(line,pos)) currentState = InIntlBlock; } if(currentState == InIntlBlock) { if(_findAppLocaleKey(line,pos)) currentState = InAcceptedKey; } if(currentState == InAcceptedKey) { if(_findSemicolon(line,pos)) currentState = InAcceptedSemicolon; } if(currentState == InAcceptedSemicolon) { if(_findLanguageString(line,pos,langcode)) break; } pos = wstring::npos; } } } return langcode.compare(CHROME_LANGUAGECODE) == 0; } bool ChromeProfile::ReadLanguageCode(wstring& langcode) { bool isLanguageFound = false; if(m_installLocation.empty() == false) { wifstream reader; wstring line; wstring path = L"/../User Data/Default/Preferences"; path = m_installLocation + path; reader.open(path.c_str()); if(reader.is_open()) { int currentState = NoState; int pos = 0; while(!(getline(reader,line)).eof() && !isLanguageFound) { if(currentState == NoState) { if(_findIntl(line,pos)) currentState = InIntl; } if(currentState == InIntl) { if(_findSemicolon(line,pos)) currentState = InIntlSemicolon; } if(currentState == InIntlSemicolon) { if(_findStartBlock(line,pos)) currentState = InIntlBlock; } if(currentState == InIntlBlock) { if(_findAcceptedKey(line,pos)) currentState = InAcceptedKey; } if(currentState == InAcceptedKey) { if(_findSemicolon(line,pos)) currentState = InAcceptedSemicolon; } if(currentState == InAcceptedSemicolon) { if(_findLanguageString(line,pos,langcode)) isLanguageFound = true; } pos = wstring::npos; } reader.close(); } } return isLanguageFound; } bool ChromeProfile::WriteUILocale() { bool languageWrittenSuccessfully = false; if(m_installLocation.empty() == false) { wifstream reader; wofstream writer; wstring line; wstring pathr = L"/../User Data/Local State"; wstring pathw = L"/../User Data/Local State.new"; pathr = m_installLocation + pathr; pathw = m_installLocation + pathw; reader.open(pathr.c_str()); writer.open(pathw.c_str()); if(reader.is_open() && writer.is_open()) { int currentState = NoState; int pos = 0; wstring oldLang; wstring lastLine = L""; while(!(getline(reader,line)).eof()) { if(currentState == NoState) { if(_findIntl(line,pos)) currentState = InIntl; } if(currentState == InIntl) { if(_findSemicolon(line,pos)) currentState = InIntlSemicolon; } if(currentState == InIntlSemicolon) { if(_findStartBlock(line,pos)) currentState = InIntlBlock; } if(currentState == InIntlBlock) { if(_findAppLocaleKey(line,pos)) currentState = InAppLocaleKey; } if(currentState == InAppLocaleKey) { if(_findSemicolon(line,pos)) currentState = InAppLocaleSemicolon; } if(currentState == InAppLocaleSemicolon) { if(_findLanguageString(line,pos,oldLang)) { currentState = EndParsing; line.replace(pos,oldLang.length(),CHROME_LANGUAGECODE); languageWrittenSuccessfully = true; } } pos = wstring::npos; writer << lastLine << L"\n"; lastLine = line; } if(!languageWrittenSuccessfully) { writer << "\t,\"intl\":{\"app_locale\":\"ca\"}\n"; languageWrittenSuccessfully = true; } writer << lastLine << L"\n"; } if(reader.is_open()) reader.close(); if(writer.is_open()) writer.close(); if(languageWrittenSuccessfully) { languageWrittenSuccessfully = MoveFileEx(pathw.c_str(),pathr.c_str(),MOVEFILE_REPLACE_EXISTING) != 0; } } return languageWrittenSuccessfully; } bool ChromeProfile::_writeAcceptLanguageCode(wstring langcode) { bool languageWrittenSuccessfully = false; if(m_installLocation.empty() == false) { wifstream reader; wofstream writer; wstring line; wstring pathr = L"/../User Data/Default/Preferences"; wstring pathw = L"/../User Data/Default/Preferences.new"; pathr = m_installLocation + pathr; pathw = m_installLocation + pathw; reader.open(pathr.c_str()); writer.open(pathw.c_str()); if(reader.is_open() && writer.is_open()) { int currentState = NoState; int pos = 0; wstring oldLang; wstring lastLine = L""; while(!(getline(reader,line)).eof()) { if(currentState == NoState) { if(_findIntl(line,pos)) currentState = InIntl; } if(currentState == InIntl) { if(_findSemicolon(line,pos)) currentState = InIntlSemicolon; } if(currentState == InIntlSemicolon) { if(_findStartBlock(line,pos)) currentState = InIntlBlock; } if(currentState == InIntlBlock) { if(_findAcceptedKey(line,pos)) currentState = InAcceptedKey; } if(currentState == InAcceptedKey) { if(_findSemicolon(line,pos)) currentState = InAcceptedSemicolon; } if(currentState == InAcceptedSemicolon) { if(_findLanguageString(line,pos,oldLang)) { currentState = EndParsing; line.replace(pos,oldLang.length(),langcode); languageWrittenSuccessfully = true; } } pos = wstring::npos; writer << lastLine << L"\n"; lastLine = line; } if(!languageWrittenSuccessfully) { writer << "\t,\"intl\":{\"accept_languages\":\"ca\"}\n"; languageWrittenSuccessfully = true; } writer << lastLine << L"\n"; } if(reader.is_open()) reader.close(); if(writer.is_open()) writer.close(); if(languageWrittenSuccessfully) { languageWrittenSuccessfully = MoveFileEx(pathw.c_str(),pathr.c_str(),MOVEFILE_REPLACE_EXISTING) != 0; } } return languageWrittenSuccessfully; } void ChromeProfile::_getFirstLanguage(wstring& jsonvalue) { if(m_languages.size() > 0) jsonvalue = m_languages[0]; return; } void ChromeProfile::AddCatalanToArrayAndRemoveOldIfExists() { wstring regvalue; vector <wstring>languages; vector<wstring>::iterator it; // Delete previous ocurrences of Catalan locale that were not first for (it = m_languages.begin(); it != m_languages.end(); ++it) { wstring element = *it; std::transform(element.begin(), element.end(), element.begin(), ::tolower); if (element.compare(L"ca") == 0) { m_languages.erase(it); break; } } wstring str(L"ca"); it = m_languages.begin(); m_languages.insert(it, str); } bool ChromeProfile::UpdateAcceptLanguages() { wstring langCode; AddCatalanToArrayAndRemoveOldIfExists(); CreateJSONString(langCode); return _writeAcceptLanguageCode(langCode); } void ChromeProfile::CreateJSONString(wstring &jsonvalue) { int languages = m_languages.size(); if (languages == 1) { jsonvalue = m_languages.at(0); return; } jsonvalue = m_languages.at(0); for (int i = 1; i < languages; i++) { jsonvalue += L"," + m_languages.at(i); } } void ChromeProfile::ParseLanguage(wstring value) { wstring language; m_languages.clear(); for (unsigned int i = 0; i < value.size (); i++) { if (value[i] == L',') { m_languages.push_back(language); language.clear(); } else { language += value[i]; } } if (language.empty() == false) { m_languages.push_back(language); } } bool ChromeProfile::IsAcceptLanguagesOk() { bool acceptLanguagesFound, localeOk; wstring langcode, firstlang; if(_isInstalled()) { acceptLanguagesFound = ReadLanguageCode(langcode); localeOk = IsUiLocaleOk(); if(acceptLanguagesFound) { ParseLanguage(langcode); _getFirstLanguage(firstlang); if(firstlang.compare(CHROME_LANGUAGECODE) == 0) { return true; } } else { if(localeOk) return true; } } return false; } bool ChromeProfile::_isInstalled() { return m_installLocation.size() > 0; }<file_sep>/CatalanitzadorPerAlWindows/OS/Authorization.cpp /* * Copyright (C) 2012 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include "stdafx.h" #include "Authorization.h" bool Authorization::UserHasAdminPermissions() { SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY; PSID AdministratorsGroup; if (!AllocateAndInitializeSid(&NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &AdministratorsGroup)) { return false; } BOOL IsInAdminGroup = FALSE; if(!CheckTokenMembership(NULL, AdministratorsGroup, &IsInAdminGroup)) { IsInAdminGroup = FALSE; } FreeSid(AdministratorsGroup); return IsInAdminGroup == TRUE ? true : false; } bool Authorization::RequestShutdownPrivileges() { HANDLE hToken; TOKEN_PRIVILEGES tkp; if (OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY,&hToken)) { LookupPrivilegeValue(NULL,SE_SHUTDOWN_NAME,&tkp.Privileges[0].Luid); tkp.PrivilegeCount = 1; tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges(hToken,FALSE,&tkp,0,(PTOKEN_PRIVILEGES)NULL,0); CloseHandle(hToken); return true; } return false; }<file_sep>/CatalanitzadorPerAlWindows/Inspectors/PDFCreatorInspector.cpp /* * Copyright (C) 2012 <NAME> <<EMAIL>> * Copyright (C) 2012 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include "stdafx.h" #include "PDFCreatorInspector.h" PDFCreatorInspector::PDFCreatorInspector(IRegistry* registry) { m_registry = registry; } #define PROGRAM_REGKEY L"Software\\PDFCreator\\Program" void PDFCreatorInspector::_readLangInstalled() { wchar_t szLanguage[1024] = L""; if (m_registry->OpenKey(HKEY_CURRENT_USER, PROGRAM_REGKEY, false)) { m_registry->GetString(L"Language", szLanguage, sizeof(szLanguage)); m_registry->Close(); } g_log.Log(L"PDFCreator::_readLangInstalled '%s'", szLanguage); m_KeyValues.push_back(InspectorKeyValue(L"lang", szLanguage)); } void PDFCreatorInspector::Execute() { _readVersion(); _readLangInstalled(); } void PDFCreatorInspector::_readVersion() { wchar_t szVersion[1024] = L""; if (m_registry->OpenKey(HKEY_LOCAL_MACHINE, PROGRAM_REGKEY, false)) { m_registry->GetString(L"ApplicationVersion", szVersion, sizeof(szVersion)); m_registry->Close(); } g_log.Log(L"PDFCreator::_readVersionInstalled '%s'", szVersion); m_KeyValues.push_back(InspectorKeyValue(L"version", szVersion)); } <file_sep>/CatalanitzadorPerAlWindows/Actions/FirefoxAction.cpp /* * Copyright (C) 2012 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include "stdafx.h" #include "FirefoxAction.h" FirefoxAction::FirefoxAction(IRegistry* registry, IRunner* runner, DownloadManager* downloadManager) : Action(downloadManager) { m_registry = registry; m_runner = runner; m_cachedVersionAndLocale = false; m_firefoxLangPackAction = NULL; m_firefoxAcceptLanguagesAction = NULL; m_doFirefoxLangPackAction = false; m_doFirefoxAcceptLanguagesAction = false; _addExecutionProcess(ExecutionProcess(L"firefox.exe", L"", true)); } FirefoxAction::~FirefoxAction() { if (m_firefoxLangPackAction) delete m_firefoxLangPackAction; if (m_firefoxAcceptLanguagesAction) delete m_firefoxAcceptLanguagesAction; } wchar_t* FirefoxAction::GetName() { return _getStringFromResourceIDName(IDS_FIREFOXACTION_NAME, szName); } wchar_t* FirefoxAction::GetDescription() { return _getStringFromResourceIDName(IDS_FIREFOXACTION_DESCRIPTION, szDescription); } void FirefoxAction::FinishExecution(ExecutionProcess process) { vector <DWORD> processIDs = _getProcessIDs(process.GetName()); if (processIDs.size() > 0) { Runner runner; runner.RequestCloseToProcessID(processIDs.at(0), true); } } FirefoxLangPackAction * FirefoxAction::_getLangPackAction() { if (m_firefoxLangPackAction == NULL) { wstring path; _readInstallPath(path); m_firefoxLangPackAction = new FirefoxLangPackAction(m_runner, path, _getLocale(), GetVersion(), m_downloadManager); } return m_firefoxLangPackAction; } FirefoxAcceptLanguagesAction * FirefoxAction::_getAcceptLanguagesAction() { if (m_firefoxAcceptLanguagesAction == NULL) { m_firefoxAcceptLanguagesAction = new FirefoxAcceptLanguagesAction(_getProfileRootDir(), _getLocale(), GetVersion()); } return m_firefoxAcceptLanguagesAction; } bool FirefoxAction::IsNeed() { bool bNeed; m_doFirefoxLangPackAction = _getLangPackAction()->IsNeed(); m_doFirefoxAcceptLanguagesAction = _getAcceptLanguagesAction()->IsNeed(); bNeed = m_doFirefoxLangPackAction || m_doFirefoxAcceptLanguagesAction; g_log.Log(L"FirefoxAction::IsNeed returns %u (status %u)", (wchar_t *) bNeed, (wchar_t*) GetStatus()); return bNeed; } void FirefoxAction::SetStatus(ActionStatus value) { Action::SetStatus(value); if (value == Selected || value == NotSelected) { if (_getLangPackAction()->GetStatus() == Selected || _getLangPackAction()->GetStatus() == NotSelected) _getLangPackAction()->SetStatus(value); if (_getAcceptLanguagesAction()->GetStatus() == Selected || _getAcceptLanguagesAction()->GetStatus() == NotSelected) _getAcceptLanguagesAction()->SetStatus(value); } } wstring FirefoxAction::_getProfileRootDir() { wstring location; wchar_t szPath[MAX_PATH]; SHGetFolderPath(NULL, CSIDL_APPDATA|CSIDL_FLAG_CREATE, NULL, 0, szPath); location = szPath; location += L"\\Mozilla\\Firefox\\"; return location; } bool FirefoxAction::IsDownloadNeed() { if (m_doFirefoxLangPackAction) { return _getLangPackAction()->IsDownloadNeed(); } else { return false; } } bool FirefoxAction::Download(ProgressStatus progress, void *data) { return _getLangPackAction()->Download(progress, data); } void FirefoxAction::Execute() { if (m_doFirefoxLangPackAction) { _getLangPackAction()->Execute(); } SetStatus(InProgress); } ActionStatus FirefoxAction::GetStatus() { if (status == InProgress) { if (m_doFirefoxLangPackAction && _getLangPackAction()->GetStatus() == InProgress) return InProgress; // Re-read locale after language pack if (m_doFirefoxLangPackAction) { m_cachedVersionAndLocale = false; _getLangPackAction()->SetLocaleAndUpdateStatus(_getLocale()); } if (m_doFirefoxAcceptLanguagesAction) { _getAcceptLanguagesAction()->Execute(); } if (m_doFirefoxLangPackAction && _getLangPackAction()->GetStatus() != Successful || m_doFirefoxAcceptLanguagesAction && _getAcceptLanguagesAction()->GetStatus() != Successful) { SetStatus(FinishedWithError); } else { SetStatus(Successful); } g_log.Log(L"FirefoxAction::GetStatus is '%s'", status == Successful ? L"Successful" : L"FinishedWithError"); } return status; } const wchar_t* FirefoxAction::GetVersion() { _readVersionAndLocale(); return m_version.c_str(); } wstring FirefoxAction::_getLocale() { _readVersionAndLocale(); return m_locale; } void FirefoxAction::_extractLocaleAndVersion(wstring version) { int start, end; start = version.find(L" "); if (start != wstring::npos) { m_version = version.substr(0, start); start = version.find(L"(", start); if (start != wstring::npos) { start++; end = version.find(L")", start); if (end != wstring::npos) { m_locale = version.substr(start, end-start); } } } } #define FIREFOX_REGKEY L"SOFTWARE\\Mozilla\\Mozilla Firefox" wstring FirefoxAction::_getVersionAndLocaleFromRegistry() { wstring version; if (m_registry->OpenKey(HKEY_LOCAL_MACHINE, FIREFOX_REGKEY, false) == false) { g_log.Log(L"FirefoxAction::_getVersionAndLocaleFromRegistry. Cannot open registry key"); return version; } wchar_t szVersion[1024]; if (m_registry->GetString(L"CurrentVersion", szVersion, sizeof(szVersion))) { g_log.Log(L"FirefoxAction::_getVersionAndLocaleFromRegistry. Firefox version %s", (wchar_t*) szVersion); version = szVersion; } m_registry->Close(); return version; } void FirefoxAction::_readVersionAndLocale() { if (m_cachedVersionAndLocale) return; wstring version; version = _getVersionAndLocaleFromRegistry(); _extractLocaleAndVersion(version); m_cachedVersionAndLocale = true; } void FirefoxAction::_readInstallPath(wstring& path) { wstring version; version = _getVersionAndLocaleFromRegistry(); if (version.empty()) return; wstring key(FIREFOX_REGKEY); key += L"\\" + version + L"\\Main"; if (m_registry->OpenKey(HKEY_LOCAL_MACHINE, (wchar_t*) key.c_str(), false) == false) { g_log.Log(L"FirefoxAction::_readInstallPath. Cannot open registry key"); return; } wchar_t szPath[MAX_PATH]; if (m_registry->GetString(L"Install Directory", szPath, sizeof(szPath))) { path = szPath; } m_registry->Close(); } void FirefoxAction::Serialize(ostream* stream) { _getLangPackAction()->Serialize(stream); _getAcceptLanguagesAction()->Serialize(stream); } void FirefoxAction::CheckPrerequirements(Action * action) { if (wcslen(GetVersion()) == 0) { _setStatusNotInstalled(); _getLangPackAction()->SetStatus(NotInstalled); _getAcceptLanguagesAction()->SetStatus(NotInstalled); return; } _getLangPackAction()->CheckPrerequirements(action); _getAcceptLanguagesAction()->CheckPrerequirements(action); if (_getLangPackAction()->GetStatus() == AlreadyApplied && _getAcceptLanguagesAction()->GetStatus() == AlreadyApplied) { SetStatus(AlreadyApplied); return; } // We do not have a good way of communication when one subactions cannot be applied // but the other can if (_getLangPackAction()->GetStatus() == CannotBeApplied && _getAcceptLanguagesAction()->GetStatus() == AlreadyApplied) { SetStatus(AlreadyApplied); return; } }<file_sep>/CatalanitzadorPerAlWindows/UI/Sheets/Models/FinishModel.h /* * Copyright (C) 2011 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #pragma once #include "Action.h" #include <string> #include <vector> #include "Serializer.h" #include "UploadStatisticsThread.h" #include "HttpFormInet.h" using namespace std; class FinishModel { public: FinishModel(); ~FinishModel(); void SetActions(vector <Action *> * value) {m_actions = value; } void SetSerializer(Serializer* serializer) { m_serializer = serializer; } void SetSendStats(bool *pbSendStats) { m_pbSendStats = pbSendStats;} void SetShowSecDlg(bool *pbShowSecDlg) { m_pbShowSecDlg = pbShowSecDlg;} void SetSystemRestore(int *pSystemRestore) { m_pSystemRestore = pSystemRestore;} void SetDialectVariant(bool *dialectalVariant) { m_pbDialectalVariant = dialectalVariant;} double GetCompletionPercentage(); bool HasErrors(); bool IsRebootNeed(); void Reboot(); void SerializeOptionsSendStatistics(); void WaitForStatisticsToCompleteOrTimeOut(); void OpenTwitter(); void OpenFacebook(); void OpenGooglePlus(); void OpenMailTo(); protected: virtual void _shellExecuteURL(wstring url); bool m_openTwitter; bool m_openFacebook; bool m_openGooglePlus; private: void _sendStatistics(); void _calculateIndicatorsForProgressBar(); void _saveToDisk(); void _serializeOptions(); UploadStatisticsThread * m_uploadStatistics; vector <Action *> * m_actions; Serializer* m_serializer; HttpFormInet m_httpFormInet; bool* m_pbSendStats; wstring m_xmlFile; float m_completionPercentage; bool m_errors; int* m_pSystemRestore; bool* m_pbDialectalVariant; bool* m_pbShowSecDlg; bool m_sentStats; }; <file_sep>/CatalanitzadorPerAlWindows.UnitTests/Actions/MSOfficeLPIActionTest.cpp /* * Copyright (C) 2012 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include "stdafx.h" #include "Defines.h" #include "MSOfficeLPIAction.h" using ::testing::Return; using ::testing::_; using ::testing::StrCaseEq; using ::testing::DoAll; class MSOfficeLPIActionTest : public MSOfficeLPIAction { public: MSOfficeLPIActionTest::MSOfficeLPIActionTest(IRegistry* registry, IRunner* runner, DownloadManager* downloadManager) : MSOfficeLPIAction(registry, runner, downloadManager) {}; public: using MSOfficeLPIAction::_getVersionInstalled; public: using MSOfficeLPIAction::_isLangPackInstalled; }; #define CreateMSOfficeAction \ RegistryMock registryMockobj; \ RunnerMock runnerMock; \ MSOfficeLPIActionTest officeAction(&registryMockobj, &runnerMock, &DownloadManager()); void MockOffice2003Installed(RegistryMock& registryMockobj) { EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\15.0\\Common\\InstallRoot"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\14.0\\Common\\InstallRoot"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\12.0\\Common\\InstallRoot"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\11.0\\Common\\InstallRoot"), false)).WillRepeatedly(Return(true)); EXPECT_CALL(registryMockobj, GetString(StrCaseEq(L"Path"),_ ,_)). WillRepeatedly(DoAll(SetArgCharStringPar2(L"SomePath"), Return(true))); } void MockOffice2007Installed(RegistryMock& registryMockobj) { EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\15.0\\Common\\InstallRoot"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\14.0\\Common\\InstallRoot"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\11.0\\Common\\InstallRoot"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\12.0\\Common\\InstallRoot"), false)).WillRepeatedly(Return(true)); EXPECT_CALL(registryMockobj, GetString(StrCaseEq(L"Path"),_ ,_)). WillRepeatedly(DoAll(SetArgCharStringPar2(L"SomePath"), Return(true))); } void MockOffice2010Installed(RegistryMock& registryMockobj) { EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\15.0\\Common\\InstallRoot"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\11.0\\Common\\InstallRoot"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\12.0\\Common\\InstallRoot"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\14.0\\Common\\InstallRoot"), false)).WillRepeatedly(Return(true)); EXPECT_CALL(registryMockobj, GetString(StrCaseEq(L"Path"),_ ,_)). WillRepeatedly(DoAll(SetArgCharStringPar2(L"SomePath"), Return(true))); } void MockOffice201064Installed(RegistryMock& registryMockobj) { EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\15.0\\Common\\InstallRoot"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\11.0\\Common\\InstallRoot"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\12.0\\Common\\InstallRoot"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\14.0\\Common\\InstallRoot"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKeyNoWOWRedirect(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\15.0\\Common\\InstallRoot"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKeyNoWOWRedirect(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\14.0\\Common\\InstallRoot"), false)).WillRepeatedly(Return(true)); EXPECT_CALL(registryMockobj, GetString(StrCaseEq(L"Path"),_ ,_)). WillRepeatedly(DoAll(SetArgCharStringPar2(L"SomePath"), Return(true))); } void MockOffice201364Installed(RegistryMock& registryMockobj) { EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\15.0\\Common\\InstallRoot"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\11.0\\Common\\InstallRoot"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\12.0\\Common\\InstallRoot"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\14.0\\Common\\InstallRoot"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKeyNoWOWRedirect(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\14.0\\Common\\InstallRoot"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKeyNoWOWRedirect(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\15.0\\Common\\InstallRoot"), false)).WillRepeatedly(Return(true)); EXPECT_CALL(registryMockobj, GetString(StrCaseEq(L"Path"),_ ,_)). WillRepeatedly(DoAll(SetArgCharStringPar2(L"SomePath"), Return(true))); } TEST(MSOfficeLPIActionTest, _isVersionInstalled_2003) { CreateMSOfficeAction; MockOffice2003Installed(registryMockobj); EXPECT_EQ(officeAction._getVersionInstalled(), MSOffice2003); } TEST(MSOfficeLPIActionTest, _isVersionInstalled_2007) { CreateMSOfficeAction; MockOffice2007Installed(registryMockobj); EXPECT_THAT(officeAction._getVersionInstalled(), MSOffice2007); } TEST(MSOfficeLPIActionTest, _isVersionInstalled_2010) { CreateMSOfficeAction; MockOffice2010Installed(registryMockobj); EXPECT_THAT(officeAction._getVersionInstalled(), MSOffice2010); } TEST(MSOfficeLPIActionTest, _isVersionInstalled_2010_64) { CreateMSOfficeAction; MockOffice201064Installed(registryMockobj); EXPECT_THAT(officeAction._getVersionInstalled(), MSOffice2010_64); } TEST(MSOfficeLPIActionTest, _isVersionInstalled_2013_64) { CreateMSOfficeAction; MockOffice201364Installed(registryMockobj); EXPECT_THAT(officeAction._getVersionInstalled(), MSOffice2013_64); } TEST(MSOfficeLPIActionTest, _isLangPackInstalled_2003) { CreateMSOfficeAction; MockOffice2003Installed(registryMockobj); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\14.0\\Common\\LanguageResources\\InstalledUIs"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\12.0\\Common\\LanguageResources\\InstalledUIs"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\11.0\\Common\\LanguageResources\\ParentFallback"), false)).WillRepeatedly(Return(true)); EXPECT_CALL(registryMockobj, GetDWORD(StrCaseEq(L"1027"),_)).WillRepeatedly(Return(true)); EXPECT_THAT(officeAction._getVersionInstalled(), MSOffice2003); EXPECT_TRUE(officeAction._isLangPackInstalled()); } TEST(MSOfficeLPIActionTest, _isLangPackInstalled_2007) { CreateMSOfficeAction; MockOffice2007Installed(registryMockobj); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\14.0\\Common\\LanguageResources\\InstalledUIs"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\11.0\\Common\\LanguageResources\\ParentFallback"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\12.0\\Common\\LanguageResources\\InstalledUIs"), false)).WillRepeatedly(Return(true)); EXPECT_CALL(registryMockobj, GetString(StrCaseEq(L"1027"),_,_)).WillRepeatedly(DoAll(SetArgCharStringPar2(L"1"), Return(true))); EXPECT_THAT(officeAction._getVersionInstalled(), MSOffice2007); EXPECT_TRUE(officeAction._isLangPackInstalled()); } TEST(MSOfficeLPIActionTest, _isLangPackInstalled_2010) { CreateMSOfficeAction; MockOffice2010Installed(registryMockobj); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\12.0\\Common\\LanguageResources\\InstalledUIs"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\11.0\\Common\\LanguageResources\\ParentFallback"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\14.0\\Common\\LanguageResources\\InstalledUIs"), false)).WillRepeatedly(Return(true)); EXPECT_CALL(registryMockobj, GetString(StrCaseEq(L"1027"),_,_)).WillRepeatedly(DoAll(SetArgCharStringPar2(L"1"), Return(true))); EXPECT_THAT(officeAction._getVersionInstalled(), MSOffice2010); EXPECT_TRUE(officeAction._isLangPackInstalled()); } TEST(MSOfficeLPIActionTest, _IsNeeded_2003_NoLangPack) { CreateMSOfficeAction; MockOffice2003Installed(registryMockobj); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\12.0\\Common\\LanguageResources\\InstalledUIs"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\11.0\\Common\\LanguageResources\\ParentFallback"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\14.0\\Common\\LanguageResources\\InstalledUIs"), false)).WillRepeatedly(Return(false)); officeAction.CheckPrerequirements(NULL); EXPECT_TRUE(officeAction.IsNeed()); } TEST(MSOfficeLPIActionTest, _IsNeeded_2007_NoLangPack) { CreateMSOfficeAction; MockOffice2007Installed(registryMockobj); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\12.0\\Common\\LanguageResources\\InstalledUIs"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\11.0\\Common\\LanguageResources\\ParentFallback"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\14.0\\Common\\LanguageResources\\InstalledUIs"), false)).WillRepeatedly(Return(false)); officeAction.CheckPrerequirements(NULL); EXPECT_TRUE(officeAction.IsNeed()); } TEST(MSOfficeLPIActionTest, _IsNeeded_2010_NoLangPack) { CreateMSOfficeAction; MockOffice2010Installed(registryMockobj); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\12.0\\Common\\LanguageResources\\InstalledUIs"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\11.0\\Common\\LanguageResources\\ParentFallback"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\14.0\\Common\\LanguageResources\\InstalledUIs"), false)).WillRepeatedly(Return(false)); officeAction.CheckPrerequirements(NULL); EXPECT_TRUE(officeAction.IsNeed()); } TEST(MSOfficeLPIActionTest, _IsNeeded_201064_NoLangPack) { CreateMSOfficeAction; MockOffice201064Installed(registryMockobj); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\12.0\\Common\\LanguageResources\\InstalledUIs"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\11.0\\Common\\LanguageResources\\ParentFallback"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\14.0\\Common\\LanguageResources\\InstalledUIs"), false)).WillRepeatedly(Return(false)); officeAction.CheckPrerequirements(NULL); EXPECT_FALSE(officeAction.IsNeed()); EXPECT_EQ(officeAction.GetStatus(), CannotBeApplied); } TEST(MSOfficeLPIActionTest, _IsNeeded_NotInstalled) { CreateMSOfficeAction; EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\11.0\\Common\\InstallRoot"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\12.0\\Common\\InstallRoot"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\14.0\\Common\\InstallRoot"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\15.0\\Common\\InstallRoot"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKeyNoWOWRedirect(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\14.0\\Common\\InstallRoot"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKeyNoWOWRedirect(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Microsoft\\Office\\15.0\\Common\\InstallRoot"), false)).WillRepeatedly(Return(false)); officeAction.CheckPrerequirements(NULL); EXPECT_FALSE(officeAction.IsNeed()); EXPECT_EQ(officeAction.GetStatus(), NotInstalled); } <file_sep>/Server/stats/class.catalanitzador.php <?php class Catalanitzador { private $_db; private $_versions; private $_vselected; private $_sql_vselected; public function __construct($db) { $this->_db = $db; $this->_versions = null; $this->_vselected = ''; $this->_sql_vselected = ''; } public function is_version_selected() { return !empty($this->_vselected); } public function get_versions() { if ($this->_versions == null) { $results = $this->_db->get_results("select ApplicationsID, count(*) as total from sessions group by ApplicationsID;"); $r_versions = $this->_db->get_results("select * from applications order by ID asc"); $versions = array(); $totals = array(); foreach ($r_versions as $k => $version) { $versions["ID-" . $version->ID] = $version->MajorVersion . '.' . $version->MinorVersion . '.' . $version->Revision; $totals["ID-" . $version->ID] = 0; } foreach ($results as $k => $result) { $totals["ID-" . $result->ApplicationsID] = $result->total; } asort($versions); $this->_versions = array($versions, $totals); } return $this->_versions; } public function get_version_selected() { if (!$this->is_version_selected()) { return ''; } if (empty($this->_sql_vselected)) { $v = $_GET['v']; if (empty($v) || strlen($v) != 3) return; if (is_numeric($v)) { $version = $this->_db->get_results("select ID from applications " . " where MajorVersion = $v[0] and MinorVersion = $v[1] and " . " Revision = $v[2] "); $this->_sql_vselected = $version[0]->ID; } else if ($v[2] == 'x' && is_numeric(substr($v, 0, 2))) { $version = $this->_db->get_results("select ID from applications " . " where MajorVersion = $v[0] and MinorVersion = $v[1]"); $firstVersion = true; foreach ($version as $oneVersion) { if ($firstVersion) { $firstVersion = false; } else { $this->_sql_vselected .= ','; } $this->_sql_vselected .= $oneVersion->ID; } } } return $this->_sql_vselected; } function print_versions_table() { ?> <table id="application_version"> <thead> <tr> <?php $version_data = $this->get_versions(); $this->_vselected = ''; $numOfCols = 0; $lastQueryVersion = ''; $lastFullVersion = ''; foreach ($version_data[0] as $ID => $version) { $fullVersion = substr($version, 0, -1) . 'x'; $queryVersion = str_replace('.', '', $fullVersion); if (!empty($lastQueryVersion) && ($lastQueryVersion != $queryVersion)) { if ($_GET['v'] == $lastQueryVersion) { $style = ' class="active" '; $this->_vselected = $lastQueryVersion; } else { $style = ''; } echo '<th colspan="', $numOfCols, '" ', $style, '><a href="'; echo Utils::get_query_string('v', $lastQueryVersion); echo '">', $lastFullVersion, '</a></th>'; $numOfCols = 0; } $numOfCols++; $lastQueryVersion = $queryVersion; $lastFullVersion = $fullVersion; } if ($_GET['v'] == $lastQueryVersion) { $style = ' class="active" '; $this->_vselected = $lastQueryVersion; } else { $style = ''; } echo '<th colspan="', $numOfCols, '" ', $style, '><a href="'; echo Utils::get_query_string('v', $lastQueryVersion); echo '">', $lastFullVersion, '</a></th>'; echo '<th>&nbsp;</th>'; echo '</tr><tr>'; foreach ($version_data[0] as $ID => $version) { $v = str_replace('.', '', $version); if ($_GET['v'] == $v) { $style = ' class="active" '; $this->_vselected = $lastQueryVersion; } else { $style = ''; } echo '<th ', $style, '><a href="'; echo Utils::get_query_string('v', $v); echo '">', $version, '</a></th>'; } if ($this->is_version_selected()) { echo '<th>'; } else { echo '<th style="background-color:#CCFFCC">'; } echo '<a href="', Utils::get_query_string('v', ''), '">TOTES</a></th></tr>'; echo '</thead><tbody><tr>'; $total_v = 0; foreach ($version_data[0] as $ID => $version) { echo '<td>'; if (isset($version_data[1][$ID])) { echo $version_data[1][$ID]; $total_v += $version_data[1][$ID]; } else { echo 0; } echo '</td>'; } echo '<td>', $total_v, '</td>'; ?> </tr> </tbody> </table> <?php } } ?><file_sep>/CatalanitzadorPerAlWindows/OS/WindowsValidation.cpp /* * Copyright (C) 2012 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include "stdafx.h" #include "WindowsValidation.h" #define FUNCTION_ID 0x1 // Strategy: only says that is validated if we can really confirm it bool WindowsValidation::IsWindowsValidated() { CLSID lcsid; IDispatch* disp; VARIANT dispRes; EXCEPINFO *pExcepInfo = NULL; unsigned int *puArgErr = NULL; bool bRslt; CoInitialize(NULL); if (!SUCCEEDED(CLSIDFromString(L"{17492023-C23A-453E-A040-C7C580BBF700}", &lcsid))) { g_log.Log(L"WindowsValidation::IsWindowsValidated. CLSIDFromString failed, passed: 0"); return false; } if (!SUCCEEDED(CoCreateInstance(lcsid, NULL, CLSCTX_INPROC_SERVER, __uuidof(IDispatch), (void**)&disp))) { g_log.Log(L"WindowsValidation::IsWindowsValidated. CreateInstance failed, passed: 0"); return false; } DISPPARAMS dispparamsNoArgs = {NULL, NULL, 0, 0}; disp->Invoke(FUNCTION_ID, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_METHOD, &dispparamsNoArgs, &dispRes, pExcepInfo, puArgErr); disp->Release(); bRslt = wcscmp(dispRes.bstrVal, L"0") == 0; g_log.Log(L"WindowsValidation::IsWindowsValidated. Result: '%s', passed %u", dispRes.bstrVal, (wchar_t *)bRslt); return bRslt; } <file_sep>/CatalanitzadorPerAlWindows/Actions/MSOfficeLPIAction.cpp /* * Copyright (C) 2011-2012 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include "stdafx.h" #include "MSOfficeLPIAction.h" #include "Runner.h" #include "Url.h" #include "ConfigurationInstance.h" #include "LogExtractor.h" RegKeyVersion RegKeys2003 = { L"11.0", L"SOFTWARE\\Microsoft\\Office\\11.0\\Common\\LanguageResources\\ParentFallback", true }; RegKeyVersion RegKeys2007 = { L"12.0", L"SOFTWARE\\Microsoft\\Office\\12.0\\Common\\LanguageResources\\InstalledUIs", false }; RegKeyVersion RegKeys2010 = { L"14.0", L"SOFTWARE\\Microsoft\\Office\\14.0\\Common\\LanguageResources\\InstalledUIs", false }; RegKeyVersion RegKeys2013 = { L"15.0", L"SOFTWARE\\Microsoft\\Office\\15.0\\Common\\LanguageResources\\InstalledUIs", false }; MSOfficeLPIAction::MSOfficeLPIAction(IRegistry* registry, IRunner* runner, DownloadManager* downloadManager) : Action(downloadManager) { m_registry = registry; m_runner = runner; m_MSVersion = MSOfficeUnKnown; m_szFullFilename[0] = NULL; m_szTempPath2003[0] = NULL; m_szFilename[0] = NULL; m_executionStep = ExecutionStepNone; GetTempPath(MAX_PATH, m_szTempPath); } MSOfficeLPIAction::~MSOfficeLPIAction() { if (m_szFullFilename[0] != NULL && GetFileAttributes(m_szFullFilename) != INVALID_FILE_ATTRIBUTES) { DeleteFile(m_szFullFilename); } if (m_connectorFile.size() > 0 && GetFileAttributes(m_connectorFile.c_str()) != INVALID_FILE_ATTRIBUTES) { DeleteFile(m_connectorFile.c_str()); } if (m_msiexecLog.empty() == false && GetFileAttributes(m_msiexecLog.c_str()) != INVALID_FILE_ATTRIBUTES) { DeleteFile(m_msiexecLog.c_str()); } _removeOffice2003TempFiles(); } wchar_t* MSOfficeLPIAction::GetName() { return _getStringFromResourceIDName(IDS_MSOFFICEACTION_NAME, szName); } wchar_t* MSOfficeLPIAction::GetDescription() { return _getStringFromResourceIDName(IDS_MSOFFICEACTION_DESCRIPTION, szDescription); } LPCWSTR MSOfficeLPIAction::GetLicenseID() { switch (_getVersionInstalled()) { case MSOffice2003: return MAKEINTRESOURCE(IDR_LICENSE_OFFICE2003); case MSOffice2007: return MAKEINTRESOURCE(IDR_LICENSE_OFFICE2007); case MSOffice2010: return MAKEINTRESOURCE(IDR_LICENSE_OFFICE2010); case MSOffice2013: return MAKEINTRESOURCE(IDR_LICENSE_OFFICE2013); default: break; } return NULL; } const wchar_t* MSOfficeLPIAction::GetVersion() { switch (_getVersionInstalled()) { case MSOffice2003: return L"2003"; case MSOffice2007: return L"2007"; case MSOffice2010: return L"2010"; case MSOffice2010_64: return L"2010_64bits"; case MSOffice2013: return L"2013"; case MSOffice2013_64: return L"2010_64bits"; default: return L""; } } // This deletes the contents of the extracted CAB file for MS Office 2003 void MSOfficeLPIAction::_removeOffice2003TempFiles() { if (_getVersionInstalled() != MSOffice2003 || m_szTempPath2003[0] == NULL) return; wchar_t szFile[MAX_PATH]; wchar_t* files[] = {L"DW20.ADM_1027", L"DWINTL20.DLL_0001_1027", L"LIP.MSI", L"lip.xml", L"OSE.EXE", L"SETUP.CHM_1027", L"SETUP.EXE", L"SETUP.INI", L"lip1027.cab", NULL}; for(int i = 0; files[i] != NULL; i++) { wcscpy_s(szFile, m_szTempPath2003); wcscat_s(szFile, L"\\"); wcscat_s(szFile, files[i]); if (DeleteFile(szFile) == FALSE) { g_log.Log(L"MSOfficeLPIAction::_removeOffice2003TempFiles. Cannot delete '%s'", (wchar_t *) szFile); } } RemoveDirectory(m_szTempPath2003); } bool MSOfficeLPIAction::_isVersionInstalled(RegKeyVersion regkeys, bool b64bits) { wchar_t szValue[1024]; wchar_t szKey[1024]; bool Installed = false; swprintf_s(szKey, L"SOFTWARE\\Microsoft\\Office\\%s\\Common\\InstallRoot", regkeys.VersionNumber); if (b64bits ? m_registry->OpenKeyNoWOWRedirect(HKEY_LOCAL_MACHINE, szKey, false) : m_registry->OpenKey(HKEY_LOCAL_MACHINE, szKey, false)) { if (m_registry->GetString(L"Path", szValue, sizeof (szValue))) { if (wcslen(szValue) > 0) Installed = true; } m_registry->Close(); } return Installed; } bool MSOfficeLPIAction::_isLangPackForVersionInstalled(RegKeyVersion regkeys) { bool Installed = false; if (m_registry->OpenKey(HKEY_LOCAL_MACHINE, regkeys.InstalledLangMapKey, false)) { if (regkeys.InstalledLangMapKeyIsDWord) { DWORD dwValue; if (m_registry->GetDWORD(L"1027", &dwValue)) Installed = true; } else { wchar_t szValue[1024]; if (m_registry->GetString(L"1027", szValue, sizeof (szValue))) { if (wcslen (szValue) > 0) Installed = true; } } m_registry->Close(); } return Installed; } void MSOfficeLPIAction::_readIsLangPackInstalled() { switch (_getVersionInstalled()) { case MSOffice2013: m_bLangPackInstalled = _isLangPackForVersionInstalled(RegKeys2013); break; case MSOffice2010: m_bLangPackInstalled = _isLangPackForVersionInstalled(RegKeys2010); break; case MSOffice2007: m_bLangPackInstalled = _isLangPackForVersionInstalled(RegKeys2007); break; case MSOffice2003: m_bLangPackInstalled = _isLangPackForVersionInstalled(RegKeys2003); break; default: assert(false); break; } g_log.Log(L"MSOfficeLPIAction::_readIsLangPackInstalled returns '%s'", m_bLangPackInstalled.ToString()); } bool MSOfficeLPIAction::_isLangPackInstalled() { if (m_bLangPackInstalled.IsUndefined()) { _readIsLangPackInstalled(); } return m_bLangPackInstalled == true; } MSOfficeVersion MSOfficeLPIAction::_getVersionInstalled() { if (m_MSVersion == MSOfficeUnKnown) { _readVersionInstalled(); } return m_MSVersion; } void MSOfficeLPIAction::_readVersionInstalled() { wstring version; if (_isVersionInstalled(RegKeys2013, false)) { m_MSVersion = MSOffice2013; } else if (_isVersionInstalled(RegKeys2010, false)) { m_MSVersion = MSOffice2010; } else if (_isVersionInstalled(RegKeys2007, false)) { m_MSVersion = MSOffice2007; } else if (_isVersionInstalled(RegKeys2003, false)) { m_MSVersion = MSOffice2003; } else if (_isVersionInstalled(RegKeys2013, true)) { m_MSVersion = MSOffice2013_64; } else if (_isVersionInstalled(RegKeys2010, true)) { m_MSVersion = MSOffice2010_64; } else { m_MSVersion = NoMSOffice; } g_log.Log(L"MSOfficeLPIAction::_readVersionInstalled '%s'", (wchar_t*) GetVersion()); } wchar_t* MSOfficeLPIAction::_getDownloadID() { switch (_getVersionInstalled()) { case MSOffice2003: return L"2003"; case MSOffice2007: return L"2007"; case MSOffice2010: return L"2010_32"; case MSOffice2013: return L"2013_32"; default: return NULL; } } bool MSOfficeLPIAction::IsNeed() { bool bNeed; switch(GetStatus()) { case NotInstalled: case AlreadyApplied: case CannotBeApplied: bNeed = false; break; default: bNeed = true; break; } g_log.Log(L"MSOfficeLPIAction::IsNeed returns %u (status %u)", (wchar_t *) bNeed, (wchar_t*) GetStatus()); return bNeed; } #define CONNECTOR_REGKEY L"SOFTWARE\\Microsoft\\Office\\Outlook\\Addins\\MSNCON.Addin.1" bool MSOfficeLPIAction::_needsInstallConnector() { bool bNeed = false; MSOfficeVersion officeVersion; officeVersion = _getVersionInstalled(); if (officeVersion == MSOffice2003 || officeVersion == MSOffice2007 || officeVersion == MSOffice2010) { wstring path; wchar_t szPath[MAX_PATH]; // Connector installed if (m_registry->OpenKey(HKEY_LOCAL_MACHINE, CONNECTOR_REGKEY, false) == true) { m_registry->Close(); SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES|CSIDL_FLAG_CREATE, NULL, 0, szPath); path=szPath; // Is the Catalan version? path+=L"\\Common Files\\System\\MSMAPI\\1027\\MSNCON32.DLL"; bNeed = GetFileAttributes(path.c_str()) == INVALID_FILE_ATTRIBUTES; } } g_log.Log(L"MSOfficeLPIAction::_needsInstallConnector returns %u", (wchar_t *) bNeed); return bNeed; } bool MSOfficeLPIAction::Download(ProgressStatus progress, void *data) { bool bFile1, bFile2; ConfigurationFileActionDownload downloadVersion; assert(_getDownloadID() != NULL); downloadVersion = ConfigurationInstance::Get().GetRemote().GetDownloadForActionID(GetID(), wstring(_getDownloadID())); wcscpy_s(m_szFilename, downloadVersion.GetFilename().c_str()); wcscpy_s(m_szFullFilename, m_szTempPath); wcscat_s(m_szFullFilename, m_szFilename); bFile1 = m_downloadManager->GetFileAndVerifyAssociatedSha1(downloadVersion, m_szFullFilename, progress, data); if (_needsInstallConnector()) { downloadVersion = ConfigurationInstance::Get().GetRemote().GetDownloadForActionID(GetID(), wstring(L"OutlookHotmailConnector")); m_connectorFile = m_szTempPath; m_connectorFile += downloadVersion.GetFilename().c_str(); bFile2 = m_downloadManager->GetFileAndVerifyAssociatedSha1(downloadVersion, m_connectorFile, progress, data); return bFile1 == true && bFile2 == true; } else { return bFile1; } } bool MSOfficeLPIAction::_extractCabFile(wchar_t * file, wchar_t * path) { Runner runnerCab; wchar_t szParams[MAX_PATH]; wchar_t szApp[MAX_PATH]; GetSystemDirectory(szApp, MAX_PATH); wcscat_s(szApp, L"\\expand.exe "); swprintf_s (szParams, L" %s %s -f:*", file, path); g_log.Log(L"MSOfficeLPIAction::_extractCabFile '%s' with params '%s'", szApp, szParams); runnerCab.Execute(szApp, szParams); runnerCab.WaitUntilFinished(); return true; } void MSOfficeLPIAction::Execute() { wchar_t szParams[MAX_PATH] = L""; wchar_t szApp[MAX_PATH] = L""; switch (_getVersionInstalled()) { case MSOffice2010: case MSOffice2013: { wchar_t logFile[MAX_PATH]; wcscpy_s(szApp, m_szFullFilename); wcscpy_s(szParams, L" /passive /norestart /quiet"); GetTempPath(MAX_PATH, logFile); wcscat_s(logFile, L"msofficelip.log"); wcscat_s(szParams, L" /log:"); wcscat_s(szParams, logFile); m_msiexecLog = logFile; break; } case MSOffice2007: { wcscpy_s(szApp, m_szFullFilename); wcscpy_s(szParams, L" /quiet"); break; } case MSOffice2003: { wchar_t szMSI[MAX_PATH]; // Unique temporary file (needs to create it) GetTempFileName(m_szTempPath, L"CAT", 0, m_szTempPath2003); DeleteFile(m_szTempPath2003); if (CreateDirectory(m_szTempPath2003, NULL) == FALSE) { g_log.Log(L"MSOfficeLPIAction::Execute. Cannot create temp directory '%s'", m_szTempPath2003); break; } _extractCabFile(m_szFullFilename, m_szTempPath2003); GetSystemDirectory(szApp, MAX_PATH); wcscat_s(szApp, L"\\msiexec.exe "); wcscpy_s(szMSI, m_szTempPath2003); wcscat_s(szMSI, L"\\"); wcscat_s(szMSI, L"lip.msi"); wcscpy_s(szParams, L" /i "); wcscat_s(szParams, szMSI); wcscat_s(szParams, L" /qn"); break; } default: break; } SetStatus(InProgress); m_executionStep = ExecutionStep1; g_log.Log(L"MSOfficeLPIAction::Execute '%s' with params '%s'", szApp, szParams); m_runner->Execute(szApp, szParams); } RegKeyVersion MSOfficeLPIAction::_getRegKeys() { switch (_getVersionInstalled()) { case MSOffice2003: return RegKeys2003; case MSOffice2007: return RegKeys2007; case MSOffice2010: return RegKeys2010; case MSOffice2013: default: return RegKeys2013; } } void MSOfficeLPIAction::_setDefaultLanguage() { BOOL bSetKey = FALSE; wchar_t szKeyName [1024]; swprintf_s(szKeyName, L"Software\\Microsoft\\Office\\%s\\Common\\LanguageResources", _getRegKeys().VersionNumber); if (m_registry->OpenKey(HKEY_CURRENT_USER, szKeyName, true)) { bSetKey = m_registry->SetDWORD(L"UILanguage", 1027); // This key setting tells Office do not use the same language that the Windows UI to determine the Office Language // and use the specified language instead if (_getVersionInstalled() == MSOffice2013 || _getVersionInstalled() == MSOffice2010 || _getVersionInstalled() == MSOffice2007) { BOOL bSetFollowKey = m_registry->SetString(L"FollowSystemUI", L"Off"); g_log.Log(L"MSOfficeLPIAction::_setDefaultLanguage, set FollowSystemUI %u", (wchar_t *) bSetFollowKey); } m_registry->Close(); } g_log.Log(L"MSOfficeLPIAction::_setDefaultLanguage, set UILanguage %u", (wchar_t *) bSetKey); } bool MSOfficeLPIAction::_executeInstallConnector() { if (_needsInstallConnector() == false) return false; wchar_t szParams[MAX_PATH]; wcscpy_s(szParams, L" /quiet"); m_runner->Execute((wchar_t *)m_connectorFile.c_str(), szParams); g_log.Log(L"MSOfficeLPIAction::_executeInstallConnector. Microsoft Office Connector '%s' with params '%s'", (wchar_t *)m_connectorFile.c_str(), szParams); return true; } ActionStatus MSOfficeLPIAction::GetStatus() { if (status == InProgress) { if (m_runner->IsRunning()) return InProgress; switch (m_executionStep) { case ExecutionStepNone: break; case ExecutionStep1: { if (_executeInstallConnector() == true) { m_executionStep = ExecutionStep2; return InProgress; } break; } case ExecutionStep2: break; default: assert(false); break; } if (_isLangPackForVersionInstalled(_getRegKeys())) { SetStatus(Successful); _setDefaultLanguage(); } else { SetStatus(FinishedWithError); if (m_msiexecLog.empty() == false) { #define LINES_TODUMP 7 #define KEYWORD_TOSEARCH L"Error" LogExtractor logExtractor(m_msiexecLog, LINES_TODUMP); logExtractor.SetExtractLastOccurrence(true); logExtractor.SetFileIsUnicode(false); logExtractor.ExtractLogFragmentForKeyword(KEYWORD_TOSEARCH); logExtractor.DumpLines(); } } g_log.Log(L"MSOfficeLPIAction::GetStatus is '%s'", status == Successful ? L"Successful" : L"FinishedWithError"); } return status; } void MSOfficeLPIAction::CheckPrerequirements(Action * action) { if (_getVersionInstalled() == NoMSOffice) { _setStatusNotInstalled(); return; } if (_getVersionInstalled() == MSOffice2010_64 || _getVersionInstalled() == MSOffice2013_64) { SetStatus(CannotBeApplied); _getStringFromResourceIDName(IDS_NOTSUPPORTEDVERSION, szCannotBeApplied); g_log.Log(L"MSOfficeLPIAction::CheckPrerequirements. Version not supported"); return; } if (_isLangPackInstalled()) { SetStatus(AlreadyApplied); return; } }<file_sep>/CatalanitzadorPerAlWindows.UnitTests/Actions/ChromeActionTest.cpp /* * Copyright (C) 2012 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include "stdafx.h" #include "Defines.h" #include "Application.h" #include "ChromeAction.h" using ::testing::Return; using ::testing::_; using ::testing::StrCaseEq; using ::testing::DoAll; using ::testing::HasSubstr; class ChromeActionTest : public ChromeAction { public: ChromeActionTest(IRegistry* registry) : ChromeAction(registry) {}; public: using ChromeAction::_readVersion; using ChromeAction::_isInstalled; using ChromeAction::_readLanguageCode; }; #define CreateChromeAction \ RegistryMock registryMockobj; \ ChromeActionTest chromeAction(&registryMockobj); void SetLocation(RegistryMock& registryMockobj, const wchar_t* location) { EXPECT_CALL(registryMockobj, OpenKey(HKEY_CURRENT_USER, StrCaseEq(CHROME_REGISTRY_PATH), false)).WillRepeatedly(Return(true)); EXPECT_CALL(registryMockobj, GetString(StrCaseEq(L"InstallLocation"),_ ,_)).WillRepeatedly(DoAll(SetArgCharStringPar2(location), Return(true))); } void SetVersion(RegistryMock& registryMockobj, const wchar_t* version) { EXPECT_CALL(registryMockobj, OpenKey(HKEY_CURRENT_USER, StrCaseEq(CHROME_REGISTRY_PATH), false)).WillRepeatedly(Return(true)); EXPECT_CALL(registryMockobj, GetString(StrCaseEq(L"Version"),_ ,_)).WillRepeatedly(DoAll(SetArgCharStringPar2(version), Return(true))); } TEST(ChromeActionTest, _readVersion) { CreateChromeAction; const wchar_t* VERSION = L"15.0"; SetVersion(registryMockobj, VERSION); chromeAction._readVersion(); EXPECT_THAT(chromeAction.GetVersion(), StrCaseEq(VERSION)); } TEST(ChromeActionTest, _isInstalled_True) { CreateChromeAction; SetLocation(registryMockobj, L"SomePath"); EXPECT_TRUE(chromeAction._isInstalled()); } TEST(ChromeActionTest, _isInstalled_False) { CreateChromeAction; SetLocation(registryMockobj, L""); EXPECT_FALSE(chromeAction._isInstalled()); } TEST(ChromeActionTest, CheckPrerequirements_NotInstalled) { CreateChromeAction; SetLocation(registryMockobj, L""); chromeAction.CheckPrerequirements(NULL); EXPECT_THAT(chromeAction.GetStatus(), NotInstalled); } TEST(ChromeActionTest, IsNeed_No_SpanishUI_NoAcceptLanguage) { wstring location; CreateChromeAction; Application::GetExecutionLocation(location); location += L"Chrome\\SpanishUI_NoAcceptLanguage\\User Data\\"; SetVersion(registryMockobj, L"11.0"); SetLocation(registryMockobj, location.c_str()); chromeAction.CheckPrerequirements(NULL); EXPECT_TRUE(chromeAction.IsNeed()); } TEST(ChromeActionTest, IsNeed_No_CatalanUI_NoAcceptLanguage) { wstring location; CreateChromeAction; Application::GetExecutionLocation(location); location += L"Chrome\\CatalanUI_NoAcceptLanguage\\User Data\\"; SetVersion(registryMockobj, L"11.0"); SetLocation(registryMockobj, location.c_str()); chromeAction.CheckPrerequirements(NULL); EXPECT_FALSE(chromeAction.IsNeed()); EXPECT_THAT(chromeAction.GetStatus(), AlreadyApplied); } TEST(ChromeActionTest, IsNeed_Yes_SpanishUI_CA_ES_DE_BR) { wstring location; CreateChromeAction; Application::GetExecutionLocation(location); location += L"Chrome\\SpanishUI_AcceptLanguage_ca_es_de_br\\User Data\\"; SetVersion(registryMockobj, L"11.0"); SetLocation(registryMockobj, location.c_str()); chromeAction.CheckPrerequirements(NULL); EXPECT_TRUE(chromeAction.IsNeed()); } TEST(ChromeActionTest, _readLanguageCode_Empty) { wstring location, langcodes; CreateChromeAction; Application::GetExecutionLocation(location); location += L"Chrome\\CatalanUI_NoAcceptLanguage\\User Data\\"; SetLocation(registryMockobj, location.c_str()); chromeAction._readLanguageCode(langcodes); EXPECT_TRUE(langcodes.empty()); } TEST(ChromeActionTest, _readLanguageCode_ES_DE_BR) { wstring location, langcodes; CreateChromeAction; Application::GetExecutionLocation(location); location += L"Chrome\\SpanishUI_AcceptLanguage_es_de_br\\User Data\\"; SetLocation(registryMockobj, location.c_str()); chromeAction._readLanguageCode(langcodes); EXPECT_THAT(langcodes, StrCaseEq(L"es,de,br")); } <file_sep>/CatalanitzadorPerAlWindows.UnitTests/Actions/FirefoxActionTest.cpp /* * Copyright (C) 2013 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include "stdafx.h" #include "Defines.h" #include "FirefoxAction.h" #include "Serializer.h" #include "XmlParser.h" using ::testing::Return; using ::testing::_; using ::testing::StrCaseEq; using ::testing::DoAll; class FirefoxActionForTest : public FirefoxAction { public: FirefoxActionForTest(IRegistry* registry, IRunner* runner, DownloadManager* downloadManager) : FirefoxAction(registry, runner, downloadManager) {}; using FirefoxAction::_readVersionAndLocale; using FirefoxAction::_getLocale; using FirefoxAction::_readInstallPath; }; void _setMockForLocale(RegistryMock& registryMockobj, const wchar_t* locale) { EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SOFTWARE\\Mozilla\\Mozilla Firefox"), false)).WillRepeatedly(Return(true)); EXPECT_CALL(registryMockobj, GetString(StrCaseEq(L"CurrentVersion"),_ ,_)). WillRepeatedly(DoAll(SetArgCharStringPar2(locale), Return(true))); } void _setMockForInstalldir(RegistryMock& registryMockobj, const wchar_t* locale, const wchar_t* installdir) { wchar_t szKeyName[2048]; swprintf_s(szKeyName, L"SOFTWARE\\Mozilla\\Mozilla Firefox\\%s\\Main", locale); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(szKeyName), false)).WillRepeatedly(Return(true)); EXPECT_CALL(registryMockobj, GetString(StrCaseEq(L"Install Directory"),_ ,_)).WillRepeatedly(DoAll(SetArgCharStringPar2(installdir), Return(true))); } bool FirefoxSerializerReadActionsIDs(XmlNode node, void *data) { vector <XmlAttribute>* attributes; int *cnt = (int *) data; if (node.GetName() != L"action") return true; attributes = node.GetAttributes(); for (unsigned int i = 0; i < attributes->size(); i++) { XmlAttribute attribute = attributes->at(i); if (attribute.GetName() == L"id") { int id = _wtoi(attribute.GetValue().c_str()); if (id == FirefoxActionID || id == FirefoxLangPackActionID) *cnt = *cnt + 1; } } return true; } TEST(FirefoxActionTest, _readVersionAndLocale) { RegistryMock registryMockobj; RunnerMock runnerMockobj; FirefoxActionForTest firefoxAction(&registryMockobj, (IRunner *)&runnerMockobj, &DownloadManager()); _setMockForLocale(registryMockobj, L"12.0 (ca)"); firefoxAction._readVersionAndLocale(); EXPECT_THAT(firefoxAction.GetVersion(), StrCaseEq(L"12.0")); EXPECT_THAT(firefoxAction._getLocale(), StrCaseEq(L"ca")); } TEST(FirefoxActionTest, _readInstallPath) { RegistryMock registryMockobj; RunnerMock runnerMockobj; FirefoxActionForTest firefoxAction(&registryMockobj, (IRunner *)&runnerMockobj, &DownloadManager()); const wchar_t* PATH = L"MyPath"; const wchar_t* VERSION = L"12.0 (ca)"; wstring path; _setMockForLocale(registryMockobj, VERSION); _setMockForInstalldir(registryMockobj, VERSION, PATH); firefoxAction._readInstallPath(path); EXPECT_THAT(path.c_str(), StrCaseEq(PATH)); } TEST(FirefoxActionTest, _Serialize) { bool bRslt; TempFile tempFile; RegistryMock registryMockobj; RunnerMock runnerMockobj; Serializer serializer; int cnt = 0; const wchar_t* VERSION = L"12.0 (ca)"; FirefoxActionForTest firefoxAction(&registryMockobj, (IRunner *)&runnerMockobj, &DownloadManager()); _setMockForLocale(registryMockobj, VERSION); _setMockForInstalldir(registryMockobj, VERSION, L""); serializer.OpenHeader(); firefoxAction.Serialize(serializer.GetStream()); serializer.CloseHeader(); serializer.SaveToFile(tempFile.GetFileName()); XmlParser parser; bRslt = parser.Load(tempFile.GetFileName()); EXPECT_TRUE(bRslt); parser.Parse(FirefoxSerializerReadActionsIDs, &cnt); EXPECT_THAT(cnt, 2); } <file_sep>/CatalanitzadorPerAlWindows/Inspectors/WinRARInspector.cpp /* * Copyright (C) 2012 <NAME> <<EMAIL>> * Copyright (C) 2012 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include "stdafx.h" #include "WinRARInspector.h" #include "FileVersionInfo.h" WinRARInspector::WinRARInspector(IRegistry* registry) { m_registry = registry; } #define PROGRAM_REGKEY L"Software\\WinRAR" void WinRARInspector::Execute() { _readVersion(); } bool WinRARInspector::_readFilePath(wstring &path) { wchar_t szFile[1024]; path.empty(); if (m_registry->OpenKeyNoWOWRedirect(HKEY_LOCAL_MACHINE, PROGRAM_REGKEY, false) || m_registry->OpenKey(HKEY_LOCAL_MACHINE, PROGRAM_REGKEY, false)) { if (m_registry->GetString(L"exe32", szFile, sizeof(szFile))) { path = szFile; } m_registry->Close(); } g_log.Log(L"WinRARInspector::_readFilePath '%s'", (wchar_t *) path.c_str()); return path.size() > 0; } bool WinRARInspector::_readVersion() { wstring file; wstring version; _readFilePath(file); if (file.size() > 0) { FileVersionInfo fileVersion; fileVersion.SetFilename(file); version = fileVersion.GetVersion(); } g_log.Log(L"WinRARInspector::_readVersion version %s", (wchar_t*) version.c_str()); m_KeyValues.push_back(InspectorKeyValue(L"version", version.c_str())); return version.size() > 0; } <file_sep>/CatalanitzadorPerAlWindows/UI/Sheets/InstallPropertyPageUI.cpp /* * Copyright (C) 2011 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include "stdafx.h" #include "InstallPropertyPageUI.h" #include "PropertySheetUI.h" #include "OSVersion.h" #include "DownloadErrorDlgUI.h" #include "WindowsXPDialogCanceler.h" #include "Inspectors.h" #include "ActiveX.h" #include <exdisp.h> #define TIMER_ID 1714 void InstallPropertyPageUI::_openURLInIE() { IWebBrowser2* wb = 0; HWND hX = GetDlgItem(getHandle (),IDC_INTERNETEXPLORER); SendMessage(hX,AX_INPLACE, 1,0); SendMessage(hX,AX_QUERYINTERFACE,(WPARAM)&IID_IWebBrowser2,(LPARAM)&wb); if (wb) { m_slideshow.Wait(); wb->Navigate((BSTR)m_slideshow.GetURL().c_str(),0,0,0,0); wb->Release(); } } void InstallPropertyPageUI::_onInitDialog() { hTotalProgressBar = GetDlgItem (getHandle(), IDC_INSTALL_PROGRESS_TOTAL); hTaskProgressBar = GetDlgItem (getHandle(), IDC_INSTALL_PROGRESS_TASK); hDescription = GetDlgItem (getHandle(), IDC_INSTALL_DESCRIPTION); ShowWindowOnce = FALSE; _openURLInIE(); } void InstallPropertyPageUI::_onShowWindow() { if (ShowWindowOnce == FALSE) { SetTimer(getHandle(), TIMER_ID, 500, NULL); ShowWindowOnce = TRUE; } } const float BYTES_TO_MEGABYTES = 1024*1024; struct DownloadData { InstallPropertyPageUI* pThis; Action* action; }; void InstallPropertyPageUI::_downloadStatus(int total, int current, void *data) { DownloadData* downloadData = (DownloadData *) data; wchar_t szString[MAX_LOADSTRING]; wchar_t szText[MAX_LOADSTRING]; SendMessage(downloadData->pThis->hTaskProgressBar, PBM_SETRANGE32, 0, total); SendMessage(downloadData->pThis->hTaskProgressBar, PBM_SETPOS, current, 0); LoadString(GetModuleHandle(NULL), IDS_INSTALL_DOWNLOAD, szString, MAX_LOADSTRING); swprintf_s(szText, szString, downloadData->action->GetName(), ((float)current) / BYTES_TO_MEGABYTES, ((float)total) / BYTES_TO_MEGABYTES); SendMessage(downloadData->pThis->hDescription, WM_SETTEXT, 0, (LPARAM) szText); } void InstallPropertyPageUI::_execute(Action* action) { wchar_t szString [MAX_LOADSTRING]; wchar_t szText [MAX_LOADSTRING]; _setTaskMarqueeMode(true); LoadString(GetModuleHandle(NULL), IDS_INSTALL_EXECUTING, szString, MAX_LOADSTRING); swprintf_s (szText, szString, action->GetName()); SendMessage (hDescription, WM_SETTEXT, 0, (LPARAM) szText); Window::ProcessMessages(); action->Execute(); } bool InstallPropertyPageUI::_download(Action* action) { bool bDownload; bool bError = false; DownloadData downloadData; if (action->IsDownloadNeed() == false) return true; _setTaskMarqueeMode(false); Window::ProcessMessages(); bDownload = true; while (bDownload) { downloadData.pThis = this; downloadData.action = action; if (action->Download((ProgressStatus)_downloadStatus, &downloadData) == false) { DownloadErrorDlgUI dlgError(action->GetName()); if (dlgError.Run(getHandle()) != IDOK) { bDownload = false; bError = true; } } else { bDownload = false; } } SendMessage(hTotalProgressBar, PBM_DELTAPOS, 1, 0); return bError == false; } void InstallPropertyPageUI::_completed() { wchar_t szString [MAX_LOADSTRING]; int nCompleted = 255; _setTaskMarqueeMode(false); SendMessage(hTaskProgressBar, PBM_SETRANGE32, 0, nCompleted); SendMessage(hTaskProgressBar, PBM_SETPOS, nCompleted, 0); SendMessage(hTotalProgressBar, PBM_SETRANGE32, 0, nCompleted); SendMessage(hTotalProgressBar, PBM_SETPOS, nCompleted, 0); LoadString(GetModuleHandle(NULL), IDS_INSTALL_COMPLETED, szString, MAX_LOADSTRING); SendMessage(hDescription, WM_SETTEXT, 0, (LPARAM) szString); // Enable Wizard next button SendMessage(getParent()->getHandle(), PSM_SETWIZBUTTONS, 0, PSWIZB_NEXT); } void InstallPropertyPageUI::_updateSelectedActionsCounts() { Action* action; m_selActions = m_downloads = 0; for (unsigned int i = 0; i < m_actions->size(); i++) { action = m_actions->at(i); if (action->GetStatus() == Selected) { m_selActions++; if (action->IsDownloadNeed()) { m_downloads++; } } } } void InstallPropertyPageUI::_setTaskMarqueeMode(bool enable) { LONG_PTR style = GetWindowLongPtr(hTaskProgressBar, GWL_STYLE); if (enable) { SetWindowLongPtr(hTaskProgressBar, GWL_STYLE, style | PBS_MARQUEE); SendMessage(hTaskProgressBar, PBM_SETMARQUEE, TRUE, 0); } else { SendMessage(hTaskProgressBar, PBM_SETMARQUEE, FALSE, 0); SetWindowLongPtr(hTaskProgressBar, GWL_STYLE, style &~ PBS_MARQUEE); } } #define SLEEP_TIME 50 // miliseconds #define TIME_TO_READ_COUNTER 10 * 1000 / SLEEP_TIME // 10 seconds #define MAX_WAIT_TIME 45 * 60 // 45 minutes void InstallPropertyPageUI::_waitExecutionComplete(Action* action) { LARGE_INTEGER li; INT64 start; int cnt = 0; double frequency = 0.0; start = GetTickCount(); if (QueryPerformanceFrequency(&li)) { frequency = double(li.QuadPart); QueryPerformanceCounter(&li); start = li.QuadPart; } else { g_log.Log(L"InstallPropertyPageUI::_waitExecutionComplete. QueryPerformanceFrequency failed"); } while (true) { ActionStatus status = action->GetStatus(); if (status == Successful || status == FinishedWithError) break; Window::ProcessMessages(); Sleep(SLEEP_TIME); Window::ProcessMessages(); cnt++; if (frequency > 0 && cnt > TIME_TO_READ_COUNTER) { double diff; QueryPerformanceCounter(&li); diff = double(li.QuadPart - start) / frequency; if (diff > MAX_WAIT_TIME) { g_log.Log(L"InstallPropertyPageUI::_waitExecutionComplete. Timeout"); break; } cnt = 0; } } } void InstallPropertyPageUI::_systemRestore(SystemRestoreThread& systemRestore) { wchar_t szText[MAX_LOADSTRING]; _setTaskMarqueeMode(true); LoadString(GetModuleHandle(NULL), IDS_CREATINGSYSTEMRESTORE, szText, MAX_LOADSTRING); SendMessage(hDescription, WM_SETTEXT, 0, (LPARAM) szText); systemRestore.Start(); systemRestore.Wait(); SendMessage(hTotalProgressBar, PBM_DELTAPOS, 1, 0); } void InstallPropertyPageUI::_onTimer() { SystemRestoreThread systemRestore; Action* action; WindowsXPDialogCanceler dialogCanceler; int cnt; KillTimer(getHandle(), TIMER_ID); dialogCanceler.Start(); _updateSelectedActionsCounts(); cnt = m_downloads + m_selActions; if (m_selActions > 0 && *m_pSystemRestore == TRUE) cnt++; SendMessage(hTotalProgressBar, PBM_SETRANGE, 0, MAKELPARAM (0, cnt)); SendMessage(hTotalProgressBar, PBM_SETSTEP, 10, 0L); if (m_selActions > 0 && *m_pSystemRestore == TRUE) { _systemRestore(systemRestore); } m_serializer->StartAction(); for (unsigned int i = 0; i < m_actions->size(); i++) { action = m_actions->at(i); if (action->GetStatus() != Selected) { m_serializer->Serialize(action); continue; } if (_download(action) == true) { _execute(action); _waitExecutionComplete(action); } else { action->SetStatus(NotSelected); } SendMessage(hTotalProgressBar, PBM_DELTAPOS, 1, 0); // 'Execute' completed m_serializer->Serialize(action); Window::ProcessMessages(); } dialogCanceler.Stop(); m_serializer->EndAction(); Inspectors inspectors; inspectors.Execute(); inspectors.Serialize(m_serializer->GetStream()); _completed(); if (m_selActions > 0 && *m_pSystemRestore == TRUE) { systemRestore.End(); } } <file_sep>/CatalanitzadorPerAlWindows/UI/Sheets/Models/FinishModel.cpp /* * Copyright (C) 2012 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include "stdafx.h" #include "Version.h" #include <math.h> #include <Shellapi.h> #include "Authorization.h" #include "FinishModel.h" #include "Url.h" #include "Option.h" #include "OptionID.h" #include "Options.h" FinishModel::FinishModel() { m_errors = false; m_uploadStatistics = NULL; m_completionPercentage = -1; m_sentStats = false; m_openTwitter = false; m_openFacebook = false; m_openGooglePlus = false; } FinishModel::~FinishModel() { if (m_uploadStatistics != NULL) { delete m_uploadStatistics; m_uploadStatistics = NULL; } #if !DEVELOPMENT_VERSION if (m_xmlFile.size() > 0) { DeleteFile(m_xmlFile.c_str()); } #endif } void FinishModel::_calculateIndicatorsForProgressBar() { Action* action; int done, doable; doable = done = 0; for (unsigned int i = 0; i < m_actions->size(); i++) { action = m_actions->at(i); // Not visible action for which we do not want to show statistics if (action->IsVisible() == false) continue; switch (action->GetStatus()) { case AlreadyApplied: case Successful: doable++; done++; break; case NotSelected: doable++; break; case FinishedWithError: doable++; m_errors = true; break; default: break; } } m_completionPercentage = doable != 0 ? floor ((float) done/ (float)doable * 100.0f) : 0; } double FinishModel::GetCompletionPercentage() { if (m_completionPercentage == -1) { _calculateIndicatorsForProgressBar(); } return m_completionPercentage; } bool FinishModel::HasErrors() { if (m_completionPercentage == -1) { _calculateIndicatorsForProgressBar(); } return m_errors; } bool FinishModel::IsRebootNeed() { Action* action; for (unsigned int i = 0; i < m_actions->size(); i++) { action = m_actions->at(i); if (action->IsRebootNeed()) { return true; } } return false; } void FinishModel::Reboot() { Authorization::RequestShutdownPrivileges(); ExitWindowsEx(EWX_REBOOT | EWX_FORCE, 0); } void FinishModel::_saveToDisk() { wchar_t szXML[MAX_PATH]; GetTempPath(MAX_PATH, szXML); wcscat_s(szXML, L"statistics.xml"); m_xmlFile = szXML; m_serializer->SaveToFile(m_xmlFile); } void FinishModel::SerializeOptionsSendStatistics() { if (m_sentStats == true) return; _serializeOptions(); _sendStatistics(); m_sentStats = true; } void FinishModel::_sendStatistics() { if (*m_pbSendStats) { m_uploadStatistics = new UploadStatisticsThread(&m_httpFormInet, m_serializer, m_errors); m_uploadStatistics->Start(); } _saveToDisk(); } void FinishModel::WaitForStatisticsToCompleteOrTimeOut() { if (m_uploadStatistics!= NULL) m_uploadStatistics->Wait(); } void FinishModel::_shellExecuteURL(wstring url) { ShellExecute(NULL, L"open", url.c_str(), NULL, NULL, SW_SHOWNORMAL); } void FinishModel::OpenTwitter() { wstring parameter; wchar_t szURL[1024]; wchar_t szText[MAX_LOADSTRING], szString[MAX_LOADSTRING]; LoadString(GetModuleHandle(NULL), IDS_SOCIALNETWORKS_TWITTER, szString, MAX_LOADSTRING); swprintf_s(szText, szString, APPLICATON_WEBSITE); Url::EncodeParameter(wstring(szText), parameter); wcscpy_s(szURL, L"http://twitter.com/share?text="); wcscat_s(szURL, parameter.c_str()); _shellExecuteURL(szURL); m_openTwitter = true; } void FinishModel::OpenFacebook() { wchar_t szURL[1024]; // See: http://developers.facebook.com/docs/share/ swprintf_s(szURL, L"http://ca-es.facebook.com/sharer.php?u=%s", APPLICATON_WEBSITE); _shellExecuteURL(szURL); m_openFacebook = true; } void FinishModel::OpenGooglePlus() { wchar_t szURL[1024]; // See: https://developers.google.com/+/plugins/+1button/ swprintf_s(szURL, L"https://plus.google.com/share?url=%s", APPLICATON_WEBSITE); _shellExecuteURL(szURL); m_openGooglePlus = true; } void FinishModel::OpenMailTo() { _shellExecuteURL(CONTACT_EMAIL); } void FinishModel::_serializeOptions() { Options options; Option sysOption(OptionSystemRestore, *m_pSystemRestore); Option dialectOption(OptionDialect, *m_pbDialectalVariant); Option showSecDlgOption(OptionShowSecDlg, *m_pbShowSecDlg); Option twitterOption(OptionShareTwitter, m_openTwitter); Option faceBookOption(OptionShareFacebook, m_openFacebook); Option googlePlusSecDlgOption(OptionShareGooglePlus, m_openGooglePlus); options.Add(sysOption); options.Add(dialectOption); options.Add(showSecDlgOption); options.Add(twitterOption); options.Add(faceBookOption); options.Add(googlePlusSecDlgOption); options.Serialize(m_serializer->GetStream()); m_serializer->CloseHeader(); } <file_sep>/CatalanitzadorPerAlWindows.UnitTests/Actions/Windows8LPIActionTest.cpp /* * Copyright (C) 2012 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include "stdafx.h" #include "Defines.h" #include "Windows8LPIAction.h" #include "ActionStatus.h" #include "RegistryMock.h" #include "OSVersionMock.h" #include "RunnerMock.h" using ::testing::Return; using ::testing::_; using ::testing::StrCaseEq; using ::testing::HasSubstr; #define SPANISH_LOCALE 0x0c0a #define FRENCH_LOCALE 0x040c #define US_LOCALE 0x0409 #define PT_LOCALE 0x0816 class Windows8LPIActionTest : public Windows8LPIAction { public: Windows8LPIActionTest::Windows8LPIActionTest(IOSVersion* OSVersion, IRegistry* registry, IWin32I18N* win32I18N, IRunner* runner, DownloadManager* downloadManager) : Windows8LPIAction(OSVersion, registry, win32I18N, runner, downloadManager) {}; public: using Windows8LPIAction::_isLangPackInstalled; using Windows8LPIAction::_getDownloadID; using Windows8LPIAction::_setLanguagePanel; using Windows8LPIAction::_getScriptFile; }; #define CreateWindowsLIPAction \ RegistryMock registryMockobj; \ Win32I18NMock win32I18NMockobj; \ OSVersionMock osVersionExMock; \ RunnerMock runnerMock; \ Windows8LPIActionTest lipAction(&osVersionExMock, &registryMockobj, &win32I18NMockobj, &runnerMock, &DownloadManager()); void SetLangPackInstalled(RegistryMock& registryMockobj, bool enabled) { EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SYSTEM\\CurrentControlSet\\Control\\MUI\\UILanguages\\ca-ES"), false)).WillRepeatedly(Return(enabled)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SYSTEM\\CurrentControlSet\\Control\\MUI\\PendingInstall\\ca-ES"), false)).WillRepeatedly(Return(enabled)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SYSTEM\\CurrentControlSet\\Control\\MUI\\UILanguages\\ca-es-valencia"), false)).WillRepeatedly(Return(enabled)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SYSTEM\\CurrentControlSet\\Control\\MUI\\PendingInstall\\ca-es-valencia"), false)).WillRepeatedly(Return(enabled)); } TEST(Windows8LPIActionTest, _isLangPackInstalled_True) { CreateWindowsLIPAction; EXPECT_CALL(osVersionExMock, GetVersion()).WillRepeatedly(Return(Windows8)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SYSTEM\\CurrentControlSet\\Control\\MUI\\UILanguages\\ca-ES"), false)).WillRepeatedly(Return(true)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SYSTEM\\CurrentControlSet\\Control\\MUI\\UILanguages\\ca-es-valencia"), false)).WillRepeatedly(Return(true)); EXPECT_TRUE(lipAction._isLangPackInstalled()); } TEST(Windows8LPIActionTest, _isLangPackInstalledPending_True) { CreateWindowsLIPAction; EXPECT_CALL(osVersionExMock, GetVersion()).WillRepeatedly(Return(Windows8)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SYSTEM\\CurrentControlSet\\Control\\MUI\\UILanguages\\ca-ES"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SYSTEM\\CurrentControlSet\\Control\\MUI\\PendingInstall\\ca-ES"), false)).WillRepeatedly(Return(true)); EXPECT_TRUE(lipAction._isLangPackInstalled()); } TEST(Windows8LPIActionTest, _isLangPackInstalled_False) { CreateWindowsLIPAction; EXPECT_CALL(osVersionExMock, GetVersion()).WillRepeatedly(Return(Windows8)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SYSTEM\\CurrentControlSet\\Control\\MUI\\UILanguages\\ca-ES"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SYSTEM\\CurrentControlSet\\Control\\MUI\\PendingInstall\\ca-ES"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SYSTEM\\CurrentControlSet\\Control\\MUI\\UILanguages\\ca-es-valencia"), false)).WillRepeatedly(Return(false)); EXPECT_CALL(registryMockobj, OpenKey(HKEY_LOCAL_MACHINE, StrCaseEq(L"SYSTEM\\CurrentControlSet\\Control\\MUI\\PendingInstall\\ca-es-valencia"), false)).WillRepeatedly(Return(false)); EXPECT_FALSE(lipAction._isLangPackInstalled()); } TEST(Windows8LPIActionTest, ExecuteWindows) { CreateWindowsLIPAction; EXPECT_CALL(osVersionExMock, GetVersion()).WillRepeatedly(Return(Windows8)); EXPECT_CALL(osVersionExMock, IsWindows64Bits()).WillRepeatedly(Return(false)); SetLangPackInstalled(registryMockobj, false); lipAction.SetStatus(Selected); EXPECT_CALL(runnerMock, Execute(HasSubstr(L"lpksetup.exe"), HasSubstr(L"/i ca-ES /r /s /p"), false)).Times(1).WillRepeatedly(Return(true)); lipAction.Execute(); } TEST(Windows8LPIActionTest, _getDownloadID_Win32) { CreateWindowsLIPAction; EXPECT_CALL(osVersionExMock, GetVersion()).WillRepeatedly(Return(Windows8)); EXPECT_CALL(osVersionExMock, IsWindows64Bits()).WillRepeatedly(Return(false)); EXPECT_THAT(lipAction._getDownloadID(), StrCaseEq(L"Win8_ca_32")); } TEST(Windows8LPIActionTest, _getDownloadID_Win64) { CreateWindowsLIPAction; EXPECT_CALL(osVersionExMock, GetVersion()).WillRepeatedly(Return(Windows8)); EXPECT_CALL(osVersionExMock, IsWindows64Bits()).WillRepeatedly(Return(true)); EXPECT_THAT(lipAction._getDownloadID(), StrCaseEq(L"Win8_ca_64")); } TEST(Windows8LPIActionTest, _setLanguagePanel_Catalan) { CreateWindowsLIPAction; string content; EXPECT_CALL(runnerMock, Execute(HasSubstr(L"powershell.exe"), HasSubstr(L"-ExecutionPolicy remotesigned"), false)).Times(1).WillRepeatedly(Return(true)); lipAction._setLanguagePanel(); ifstream reader(lipAction._getScriptFile().c_str()); content = string((std::istreambuf_iterator<char>(reader)), std::istreambuf_iterator<char>()); reader.close(); EXPECT_THAT(content, HasSubstr("New-WinUserLanguageList ca")); } TEST(Windows8LPIActionTest, _setLanguagePanel_Valencian) { CreateWindowsLIPAction; string content; EXPECT_CALL(runnerMock, Execute(HasSubstr(L"powershell.exe"), HasSubstr(L"-ExecutionPolicy remotesigned"), false)).Times(1).WillRepeatedly(Return(true)); lipAction.SetUseDialectalVariant(true); lipAction._setLanguagePanel(); ifstream reader(lipAction._getScriptFile().c_str()); content = string((std::istreambuf_iterator<char>(reader)), std::istreambuf_iterator<char>()); reader.close(); EXPECT_THAT(content, HasSubstr("New-WinUserLanguageList ca-es-valencia")); EXPECT_THAT(content, HasSubstr("$1 += \"ca\"")); } TEST(Windows8LPIActionTest, CheckPrerequirements_French) { CreateWindowsLIPAction; vector <LANGID> ids; ids.push_back(US_LOCALE); ids.push_back(FRENCH_LOCALE); EXPECT_CALL(osVersionExMock, GetVersion()).WillRepeatedly(Return(Windows8)); EXPECT_CALL(osVersionExMock, IsWindows64Bits()).WillRepeatedly(Return(false)); EXPECT_CALL(win32I18NMockobj, EnumUILanguages()).Times(1).WillRepeatedly(Return(ids)); lipAction.CheckPrerequirements(NULL); EXPECT_NE(CannotBeApplied, lipAction.GetStatus()); } TEST(Windows8LPIActionTest, CheckPrerequirements_Portuguese) { CreateWindowsLIPAction; vector <LANGID> ids; ids.push_back(PT_LOCALE); EXPECT_CALL(osVersionExMock, GetVersion()).WillRepeatedly(Return(Windows8)); EXPECT_CALL(osVersionExMock, IsWindows64Bits()).WillRepeatedly(Return(false)); EXPECT_CALL(win32I18NMockobj, EnumUILanguages()).Times(1).WillRepeatedly(Return(ids)); lipAction.CheckPrerequirements(NULL); EXPECT_THAT(CannotBeApplied, lipAction.GetStatus()); } <file_sep>/CatalanitzadorPerAlWindows/UI/Sheets/WelcomePropertyPageUI.cpp /* * Copyright (C) 2011 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include "stdafx.h" #include "WelcomePropertyPageUI.h" #include "SystemRestore.h" #include "PropertyPageUI.h" #include "PropertySheetUI.h" #include "ExtraSecTermsDlgUI.h" #include "AboutBoxDlgUI.h" #include "ConfigurationInstance.h" #include "DownloadNewVersionDlgUI.h" WelcomePropertyPageUI::WelcomePropertyPageUI() { m_hFont = NULL; } WelcomePropertyPageUI::~WelcomePropertyPageUI() { if (m_hFont) { DeleteObject(m_hFont); m_hFont = NULL; } } void WelcomePropertyPageUI::_setTransparentBitmaps() { HANDLE handle = LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(IDB_CHECKMARK), IMAGE_BITMAP, 16, 16, LR_LOADTRANSPARENT | LR_LOADMAP3DCOLORS); SendMessage(GetDlgItem(getHandle(), IDC_BITMAPCHECK1), STM_SETIMAGE, IMAGE_BITMAP, (LPARAM) handle); SendMessage(GetDlgItem(getHandle(), IDC_BITMAPCHECK2), STM_SETIMAGE, IMAGE_BITMAP, (LPARAM) handle); SendMessage(GetDlgItem(getHandle(), IDC_BITMAPCHECK3), STM_SETIMAGE, IMAGE_BITMAP, (LPARAM) handle); handle = LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(IDB_HORIZONTAL_LOGO), IMAGE_BITMAP, 0, 0, LR_LOADTRANSPARENT | LR_LOADMAP3DCOLORS); SendMessage(GetDlgItem(getHandle(), IDC_HORIZONTAL_LOGO), STM_SETIMAGE, IMAGE_BITMAP, (LPARAM) handle); } void WelcomePropertyPageUI::_initPropertySheet() { HWND hWnd; hWnd = GetParent(getHandle()); SetFocus(getHandle()); SendMessage(hWnd, PSM_SETWIZBUTTONS, (WPARAM)0, (LPARAM)PSWIZB_NEXT); Window::CenterWindow(hWnd); m_configurationDownload.Start(); } void WelcomePropertyPageUI::_onInitDialog() { if (ConfigurationInstance::Get().GetAeroEnabled() == false) { HWND hWnd = GetDlgItem(getHandle(), IDC_WELCOME_TOAPP); m_hFont = Window::CreateBoldFont(hWnd); SendMessage(hWnd, WM_SETFONT, (WPARAM) m_hFont, TRUE); } CheckDlgButton(getHandle(), IDC_SENDRESULTS, *m_pbSendStats); _setTransparentBitmaps(); _initPropertySheet(); } bool WelcomePropertyPageUI::_doesUserWantToUpdate() { wchar_t szMessage [MAX_LOADSTRING]; wchar_t szCaption [MAX_LOADSTRING]; LoadString(GetModuleHandle(NULL), IDS_WANT_TOUSE_NEWVERSION, szMessage, MAX_LOADSTRING); LoadString(GetModuleHandle(NULL), IDS_MSGBOX_CAPTION, szCaption, MAX_LOADSTRING); return MessageBox(getHandle(), szMessage, szCaption, MB_YESNO | MB_ICONQUESTION) == IDYES; } void WelcomePropertyPageUI::_updateCatalanitzadorAction(Action* catalanitzadorAction) { catalanitzadorAction->CheckPrerequirements(NULL); if (catalanitzadorAction->IsNeed() == true) { if (_doesUserWantToUpdate()) { DownloadNewVersionDlgUI downloadNewVersionDlgUI(m_pActions->GetActionFromID(CatalanitzadorUpdateActionID)); if (downloadNewVersionDlgUI.Run(getHandle()) == IDCANCEL) { catalanitzadorAction->SetStatus(NotSelected); } } else { catalanitzadorAction->SetStatus(NotSelected); } } } bool WelcomePropertyPageUI::_onNext() { Action* catalanitzadorAction = m_pActions->GetActionFromID(CatalanitzadorUpdateActionID); // Disable Next button after has been click to prevent user clicking twice SendMessage(getParent()->getHandle(), PSM_SETWIZBUTTONS, 0, 0); Window::ProcessMessages(); if (catalanitzadorAction->GetStatus() != Successful) { _updateCatalanitzadorAction(catalanitzadorAction); } m_pActions->CheckPrerequirements(); *m_pbSendStats = IsDlgButtonChecked(getHandle(),IDC_SENDRESULTS)==BST_CHECKED; return true; } NotificationResult WelcomePropertyPageUI::_onNotify(LPNMHDR hdr, int /*iCtrlID*/) { if (hdr->code == NM_CLICK) { switch (hdr->idFrom) { case IDC_SYSLINK_ABOUT: { AboutBoxDlgUI aboutDlg; aboutDlg.Run(getHandle()); break; } case IDC_SYSLINK_SECTERMS: { ExtraSecTermsDlgUI extraSecTermsDlgUI; extraSecTermsDlgUI.SetSystemRestore(m_pSystemRestore); extraSecTermsDlgUI.Run(getHandle()); *m_pbShowSecDlg = true; break; } default: break; } } return ReturnFalse; } <file_sep>/CatalanitzadorPerAlWindows/Actions/MSOfficeLPIAction.h /* * Copyright (C) 2011 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #pragma once #include "Action.h" #include "IRunner.h" #include "IOSVersion.h" #include "IRegistry.h" #include "TriBool.h" enum MSOfficeVersion { MSOfficeUnKnown, NoMSOffice, MSOffice2003, MSOffice2007, MSOffice2010, MSOffice2010_64, MSOffice2013, MSOffice2013_64 }; struct RegKeyVersion { wchar_t* VersionNumber; wchar_t* InstalledLangMapKey; bool InstalledLangMapKeyIsDWord; }; class MSOfficeLPIAction : public Action { public: MSOfficeLPIAction(IRegistry* registry, IRunner* runner, DownloadManager* downloadManager); ~MSOfficeLPIAction(); virtual wchar_t* GetName(); virtual wchar_t* GetDescription(); virtual ActionID GetID() const { return MSOfficeLPIActionID;}; virtual ActionGroup GetGroup() const {return ActionGroupOfficeAutomation;} virtual bool Download(ProgressStatus progress, void *data); virtual bool IsNeed(); virtual void Execute(); virtual ActionStatus GetStatus(); virtual const wchar_t* GetVersion(); virtual LPCWSTR GetLicenseID(); virtual void CheckPrerequirements(Action * action); protected: MSOfficeVersion _getVersionInstalled(); bool _isLangPackInstalled(); private: enum ExecutionStep { ExecutionStepNone, ExecutionStep1, ExecutionStep2 }; bool _isVersionInstalled(RegKeyVersion regkeys, bool b64bits); void _readVersionInstalled(); bool _isLangPackForVersionInstalled(RegKeyVersion regkeys); bool _extractCabFile(wchar_t * file, wchar_t * path); void _setDefaultLanguage(); wchar_t* _getDownloadID(); void _removeOffice2003TempFiles(); RegKeyVersion _getRegKeys(); bool _needsInstallConnector(); bool _executeInstallConnector(); void _readIsLangPackInstalled(); TriBool m_bLangPackInstalled; wchar_t m_szFullFilename[MAX_PATH]; wchar_t m_szFilename[MAX_PATH]; wchar_t m_szTempPath[MAX_PATH]; wchar_t m_szTempPath2003[MAX_PATH]; MSOfficeVersion m_MSVersion; wstring m_connectorFile; ExecutionStep m_executionStep; IRunner* m_runner; IRegistry* m_registry; wstring m_msiexecLog; }; <file_sep>/CatalanitzadorPerAlWindows/Actions/IEAction.cpp /* * Copyright (C) 2012 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include "stdafx.h" #include "IEAction.h" IEAction::IEAction(IRegistry* registry, IRunner* runner, IFileVersionInfo* fileVersionInfo, IOSVersion* OSVersion, DownloadManager* downloadManager) : Action(downloadManager) { m_registry = registry; m_runner = runner; m_OSVersion = OSVersion; m_fileVersionInfo = fileVersionInfo; m_LPIAction = NULL; m_acceptLanguagesAction = NULL; m_doAcceptLanguagesAction = false; m_doLPIAction = false; } IEAction::~IEAction() { if (m_LPIAction) delete m_LPIAction; if (m_acceptLanguagesAction) delete m_acceptLanguagesAction; } wchar_t* IEAction::GetName() { return _getStringFromResourceIDName(IDS_IEACTION_NAME, szName); } wchar_t* IEAction::GetDescription() { return _getStringFromResourceIDName(IDS_IEACTION_DESCRIPTION, szDescription); } IELPIAction * IEAction::_getLPIAction() { if (m_LPIAction == NULL) { m_LPIAction = new IELPIAction(m_OSVersion, m_runner, m_fileVersionInfo, m_downloadManager); } return m_LPIAction; } IEAcceptLanguagesAction * IEAction::_getAcceptLanguagesAction() { if (m_acceptLanguagesAction == NULL) { m_acceptLanguagesAction = new IEAcceptLanguagesAction(m_registry, m_fileVersionInfo, m_OSVersion); } return m_acceptLanguagesAction; } LPCWSTR IEAction::GetLicenseID() { if (m_doLPIAction) { return _getLPIAction()->GetLicenseID(); } else { return NULL; } } bool IEAction::IsNeed() { bool bNeed; m_doAcceptLanguagesAction = _getAcceptLanguagesAction()->IsNeed(); m_doLPIAction = _getLPIAction()->IsNeed(); bNeed = m_doLPIAction || m_doAcceptLanguagesAction; g_log.Log(L"IEAction::IsNeed returns %u (status %u)", (wchar_t *) bNeed, (wchar_t*) GetStatus()); return bNeed; } void IEAction::SetStatus(ActionStatus value) { Action::SetStatus(value); if (value == Selected || value == NotSelected) { if (_getLPIAction()->GetStatus() == Selected || _getLPIAction()->GetStatus() == NotSelected) _getLPIAction()->SetStatus(value); if (_getAcceptLanguagesAction()->GetStatus() == Selected || _getAcceptLanguagesAction()->GetStatus() == NotSelected) _getAcceptLanguagesAction()->SetStatus(value); } } bool IEAction::IsDownloadNeed() { if (m_doLPIAction) { return _getLPIAction()->IsDownloadNeed(); } else { return false; } } bool IEAction::Download(ProgressStatus progress, void *data) { return _getLPIAction()->Download(progress, data); } void IEAction::Execute() { if (m_doLPIAction) { _getLPIAction()->Execute(); } SetStatus(InProgress); } ActionStatus IEAction::GetStatus() { if (status == InProgress) { if (m_doLPIAction && _getLPIAction()->GetStatus() == InProgress) return InProgress; if (m_doAcceptLanguagesAction) { _getAcceptLanguagesAction()->Execute(); } if (m_doLPIAction && _getLPIAction()->GetStatus() != Successful || m_doAcceptLanguagesAction && _getAcceptLanguagesAction()->GetStatus() != Successful) { SetStatus(FinishedWithError); } else { SetStatus(Successful); } g_log.Log(L"IEAction::GetStatus is '%s'", status == Successful ? L"Successful" : L"FinishedWithError"); } return status; } const wchar_t* IEAction::GetVersion() { return m_version.c_str(); } void IEAction::Serialize(ostream* stream) { _getAcceptLanguagesAction()->Serialize(stream); _getLPIAction()->Serialize(stream); } void IEAction::CheckPrerequirements(Action * action) { _getLPIAction()->CheckPrerequirements(action); _getAcceptLanguagesAction()->CheckPrerequirements(action); if (_getLPIAction()->GetStatus() == AlreadyApplied && _getAcceptLanguagesAction()->GetStatus() == AlreadyApplied) { SetStatus(AlreadyApplied); return; } // We do not have a good way of communication when one subactions cannot be applied // but the other can if (_getLPIAction()->GetStatus() == CannotBeApplied && _getAcceptLanguagesAction()->GetStatus() == AlreadyApplied) { SetStatus(AlreadyApplied); return; } if (_getLPIAction()->GetStatus() == CannotBeApplied && _getAcceptLanguagesAction()->GetStatus() == CannotBeApplied) { SetStatus(CannotBeApplied); } if (_getLPIAction()->GetStatus() == CannotBeApplied) { wcscpy_s(szCannotBeApplied, _getLPIAction()->GetCannotNotBeApplied()); } }
dcb8c77d6acd613cc4d22cc758f9a75dfe23a2c5
[ "C++", "PHP" ]
34
C++
xmps/Catalanitzador
ba65dffc5909352c72342c7d0ea0389acf86cd43
22d095fe253786f5d56383942fbe012e5d61d342
refs/heads/master
<repo_name>ReneNyffenegger/dotfiles.github.com<file_sep>/README.md dotfiles.github.com =================== Your _unofficial_ guide to doing dotfiles on GitHub. Please visit [http://dotfiles.github.com](http://dotfiles.github.com). ## Contributing If you'd like to contribute to this site, you'll need [nanoc](http://nanoc.stoneship.org/) the awesome static site generator from [<NAME>](http://stoneship.org/). This site is served from GitHub pages and the source resides in the [src folder](). Other than the usual [nanoc usage info](http://nanoc.stoneship.org/docs/), it's important to note: * *Add exclusions for any root content not generated by nano.* This is done in the `src/config.yml` under `exclusions.` These exclusions won't get pruned for the `nanoc prune` command. <file_sep>/src/compass.rb http_path = "/" project_path = "." css_dir = "../stylesheets" sass_dir = "content/stylesheets" images_dir = "..images" output_style = :compressed
c438f1741435d7e557ee035b2b50b59c56468482
[ "Markdown", "Ruby" ]
2
Markdown
ReneNyffenegger/dotfiles.github.com
42890ad3b850c634435e857aaea7170bacd3c392
2df74614792d4b7cbbd43043387f6e2aaf8ad4b5
refs/heads/master
<repo_name>amrgamal91/TopMovies<file_sep>/src/services/moviesService.js import { apiKey, movieInfo, moviesURL } from "../config.json"; import http from "./httpService"; export function get_Num_Movies_Pages(year) { return http.get(moviesURL + year); } /** * 1- get num of pages * 2-loop over this num of pages * 3- append movies of each page to the current movies list * 4- return this list */ export function getPageMovies(pageNum, year) { return http.get(moviesURL + year + "&page=" + pageNum); } export function getMovieInfo(id) { return http.get(movieInfo + id + "?" + apiKey); } export function getMovieCast(id) { return http.get(movieInfo + id + "/casts?" + apiKey); } <file_sep>/src/components/tableHeader.jsx import React, { Component } from "react"; class TableHeader extends Component { /** * */ handleSort = sortColumnPath => { const newSortColumn = { ...this.props.sortColumn }; newSortColumn.path = sortColumnPath; if (sortColumnPath === this.props.sortColumn.path) { newSortColumn.order = this.props.sortColumn.order === "desc" ? "asc" : "desc"; } else { newSortColumn.order = "asc"; } this.props.onSort(newSortColumn); }; /** * param:name of the column * check if the column not the one of sort , if so neglect it * if it is the sort column then check order to render the icon of order */ renderIcon = name => { if (name !== this.props.sortColumn.path) { return null; } if (this.props.sortColumn.order === "desc") return <i className="fa fa-sort-desc" />; return <i className="fa fa-sort-asc" />; }; render() { return ( <thead> <tr> {this.props.columns.map(singleColumn => ( <th scope="col" className="movies-tb-header" key={singleColumn.label} onClick={() => this.handleSort(singleColumn.columnName)} > {singleColumn.label} {this.renderIcon(singleColumn.columnName)} </th> ))} </tr> </thead> ); } } export default TableHeader; <file_sep>/src/App.js import React, { Component } from "react"; import "./App.css"; import Movies from "./components/movies"; import { Route, Redirect, Switch, BrowserRouter } from "react-router-dom"; import MovieForm from "./components/movieForm"; class App extends Component { render() { return ( <div className="container"> {/* adding the basename prop fixes the problem of no rendered content on github pages https://medium.com/@Dragonza/react-router-problem-with-gh-pages-c93a5e243819 */} <BrowserRouter basename={process.env.PUBLIC_URL}> <Switch> <Route path="/movies/:id" component={MovieForm} /> <Route path="/movies" component={Movies} /> <Route path="/" component={Movies} /> {/* <Redirect from="/" exact to="/movies" /> */} </Switch> </BrowserRouter> </div> ); } } export default App; <file_sep>/src/components/tableBody.jsx import React, { Component } from "react"; import nl2br from "react-newline-to-break"; import { Link } from "react-router-dom"; class TableBody extends Component { render() { if (this.props.genresMap === null) { console.log("returning null ............." + this.props.data); return null; } return ( <tbody> {this.props.data.map(singleMovie => ( <tr key={singleMovie.id}> <td> <img src={ "https://image.tmdb.org/t/p/w92/" + singleMovie.poster_path } className="img-fluid" alt="movie poster" />{" "} </td> <td> <Link className="movie-meta-data title" to={`/movies/${singleMovie.id}`} > {singleMovie.title} </Link> </td> <td className="movie-meta-data">{singleMovie.release_date}</td> <td className="movie-meta-data rate">{singleMovie.vote_average}</td> <td className="movie-meta-data genre"> {singleMovie !== null ? singleMovie.genre_ids.map(item => nl2br(this.props.genresMap.get(item) + "\n") ) : ""} </td> </tr> ))} </tbody> ); } } export default TableBody; <file_sep>/src/components/movieForm.jsx import React, { Component } from "react"; import { getMovieInfo, getMovieCast } from "../services/moviesService"; class MovieForm extends Component { state = { data: "", cast: [] }; /** * get all info of the current movie through the API * get staff of the current Movie then update state & set background */ async componentDidMount() { const { data } = await getMovieInfo(this.props.match.params.id); this.getCast(); this.setState({ data }); this.setBackgroundImage( "https://image.tmdb.org/t/p/original" + this.state.data.backdrop_path ); } /** * remove the background(current movie poster) when unmount so that, * it could not be set for the parent Component (movie component) */ componentWillUnmount() { document.body.style.backgroundImage = ""; } /** * get staff of the current movie * set cast state */ async getCast() { const { data } = await getMovieCast(this.props.match.params.id); this.setState({ cast: data }); } /** * set the background of current movie * @param {string} path path of the image online */ setBackgroundImage(path) { let backdropIMG = path; document.body.style.backgroundImage = "url(" + backdropIMG + ")"; document.body.style.backgroundSize = "cover"; document.body.style.repeat = "no-repeat"; } /** * get genres names from list of genres objects * @param {array} genreList array of genres objs * returns : list of comma seprated genre names (for current movie) */ getGenreNames(genreList) { let genreNames = ""; if (genreList) { genreList.forEach(element => { if (genreNames !== "") genreNames += " , "; genreNames += element.name; }); } return genreNames; } /** * get production companies names from list of prod comps objs * @param {array} companiesList array of comps objs * returns : list of comma seprated prod companies names */ getProductionCompanies(companiesList) { let companiesNames = ""; if (companiesList) { companiesList.forEach(element => { if (companiesNames !== "") companiesNames += " , "; companiesNames += element.name; }); } return companiesNames; } /** * get cast names from list of cast objs * @param {array} castList array of cast objs * returns : just first 4 names of actors from cast */ getCastNames(castList) { let cast = ""; if (castList) { castList.slice(0, 4).forEach(element => { if (cast !== "") cast += " , "; cast += element.name; }); } return cast; } render() { return ( <div className="row justify-content-center padding-outer"> <div className="cardcont col-xs-12 col-md-12 col-lg-10 padding-inner"> <div className="row flex-column-reverse flex-sm-row"> <div className="col-md-6 col-lg-6"> <img id="posterContent" className="poster img-fluid" src={ "https://image.tmdb.org/t/p/w500/" + this.state.data.poster_path } style={{ height: "auto" }} alt="Poster Content" /> </div> <div className="col-md-6 col-lg-6"> <div className="meta-data"> <h1 className="movie-title"> {this.state.data.original_title} </h1> <span className="tagline subtitles"> {this.state.data.tagline} </span> <p className="overview">{this.state.data.overview}</p> <div> <span className="genre-list subtitles"> {this.getGenreNames(this.state.data.genres)} </span> <span className="cast"> {this.getCastNames(this.state.cast.cast)} </span> <br /> <br /> <span className="production-list prod"> {this.getProductionCompanies( this.state.data.production_companies )} </span> <br /> <br /> <div className="row nopadding release-details"> <div className="col-xs-6 col-sm-6 col-md-6 col-lg-6 meta-data-element"> <span className="subtitles">Original Release:</span> <span className="meta-data-val"> {this.state.data.release_date} </span> </div> <div className="col-xs-6 col-sm-6 col-md-6 col-lg-6 meta-data-element"> <span className="subtitles">Running Time:</span> <span className="meta-data-val"> {this.state.data.runtime} mins </span> </div> <div className="col-xs-6 col-sm-6 col-md-6 col-lg-6 meta-data-element"> <span className="subtitles">Box Office:</span> <span className="meta-data-val"> {this.state.data.revenue > 0 ? Number(this.state.data.revenue).toLocaleString( "en" ) + " $" : "N/A"} </span> </div> <div className="col-xs-6 col-sm-6 col-md-6 col-lg-6 meta-data-element"> <span className="subtitles">Vote Average:</span> <span className="meta-data-val"> {this.state.data.vote_average + " /10"} </span> </div> <div className="col-xs-6 col-sm-6 col-md-6 col-lg-6 meta-data-element"> <span className="subtitles">Budget:</span> <span className="meta-data-val"> {this.state.data.budget < 0 ? Number(this.state.data.budget).toLocaleString( "en" ) + " $" : "N/A"} </span> </div> <div className="col-xs-6 col-sm-6 col-md-6 col-lg-6 meta-data-element"> <span className="subtitles">Adult only:</span> <span className="meta-data-val"> {this.state.data.adult ? "Yes" : "No"} </span> </div> </div> </div> </div> </div> </div> </div> </div> ); } } export default MovieForm; <file_sep>/src/components/footer.jsx import React from "react"; const Footer = () => { return ( <footer className="footer page-footer font-small blue"> <div className="footer-text footer-copyright text-center "> {" "} <a className="footer-link" href="https://www.linkedin.com/in/amr-gamal-11901a33/" > {" "} © Developed by <NAME> </a> <br /> <a className="footer-link" href="https://github.com/amrgamal91/Top-Movies" > <i className="fa fa-github" aria-hidden="true" /> View code </a> </div> </footer> ); }; export default Footer; <file_sep>/src/components/movies.jsx import React, { Component } from "react"; import _ from "lodash"; import MoviesTable from "./moviesTable"; import Pagination from "./pagination"; import { paginate, getYears } from "../utils/utils"; import SearchBox from "./searchBox"; import { get_Num_Movies_Pages, getPageMovies } from "../services/moviesService"; import CustomDropDown from "./customDropDown"; import { getAllGenres } from "../services/genreService"; import loading from "../spinner-loading.svg"; class Movies extends Component { state = { movies: [], genres: [], pageSize: 10, currentPage: 1, searchQuery: "", selectedGenre: null, genresMap: new Map(), sortColumn: { path: "vote_average", order: "desc" }, totalPages: null, years: [], selectedYear: new Date().getFullYear(), isLoading: true }; columns = [ { columnName: "poster", label: "" }, { columnName: "title", label: "Title" }, { columnName: "release_date", label: "Release Date" }, { columnName: "vote_average", label: "Rate" }, { columnName: "genre_ids", label: "Genre" } ]; /** * first , initializes Genres then , * if there is a state saved in local storage get this state * else , refresh the component with the movies of current selected year * add event listener to save state to localStorage when user refreshes the page */ async componentDidMount() { this.getGenrePairs(); if (localStorage.getItem("movies")) this.hydrateStateWithLocalStorage(); else this.getComponentContent(this.state.selectedYear); window.addEventListener( "beforeunload", this.saveStateToLocalStorage.bind(this) ); } /** * add event listener to save state to localStorage when user leaves the page */ componentWillUnmount() { window.removeEventListener( "beforeunload", this.saveStateToLocalStorage.bind(this) ); // saves if component has a chance to unmount this.saveStateToLocalStorage(); } /** * loop on each item in the state , save it in local storage */ saveStateToLocalStorage() { for (let key in this.state) { if (key === "genresMap") continue; localStorage.setItem(key, JSON.stringify(this.state[key])); } } /** * get the saved state from local storage */ hydrateStateWithLocalStorage() { // for all items in state for (let key in this.state) { if (key === "genresMap") continue; // if the key exists in localStorage if (localStorage.hasOwnProperty(key)) { // get the key's value from localStorage let value = localStorage.getItem(key); // parse the localStorage string and setState try { value = JSON.parse(value); this.setState({ [key]: value }); } catch (e) { // handle empty string this.setState({ [key]: value }); } } } } /** * get all genres values from the API then add the initial value at first * create map of these pairs , then get names only from these pairs * set state with the new values */ async getGenrePairs() { const { data } = await getAllGenres(); const all_genres_pairs = [{ id: 0, name: "All Genres" }, ...data.genres]; let allGenresMap = new Map(all_genres_pairs.map(i => [i.id, i.name])); const genres = [...allGenresMap.values()]; this.setState({ genres, genresMap: allGenresMap }); } /** * * @param {number} pages total number of pages to get from API * @param {number} year the selected year to get its movies * loop on pages , foreach page get its movies , add page movies to all movies * set state with the movies val , set is loading to false to hide loading sign */ async getAllMovies(pages, year) { let allMovies = ""; for (let index = 1; index <= pages; index++) { const { data } = await getPageMovies(index, year); const movies = data.results; allMovies = [...allMovies, ...movies]; } this.setState({ movies: allMovies }, () => this.setState({ isLoading: false }) ); } /** * * @param {number} year the current selected year * get total number of pages of the selected year movies * if it exceeds 50 then set it to 50 else keep it * get movies of these pages */ async getComponentContent(year) { const { data } = await get_Num_Movies_Pages(year); const totalPages = data.total_pages > 50 ? 50 : data.total_pages; this.getAllMovies(totalPages, year); } /** * handles Genre Selection, by updating state with the selected one */ handleGenreSelect = genre => { this.setState({ selectedGenre: genre, currentPage: 1, searchQuery: "" }); }; /** * handle year selection by updating the state , * then get component content after setting state directly */ handleYearSelect = year => { this.setState( { isLoading: true, selectedYear: year.value, selectedGenre: this.state.selectedGenre, currentPage: 1, searchQuery: "" }, () => { this.getComponentContent(year.value); } ); }; /** * Param:column of path & order to sort the table regarding it */ handleSort = newSortColumn => { this.setState({ sortColumn: newSortColumn }); }; /** * update the search query val with the query val , reset genre and page */ handleSearch = query => { this.setState({ searchQuery: query, selectedGenre: null, currentPage: 1 }); }; /** * update the current page with the selected one */ handlePageChange = data => { const { currentPage, totalPages } = data; this.setState({ currentPage, totalPages }); }; /** * preparing the data to be passed to render method * 1- fitler movise due to search query in search box if exist * 2- if not exist then filter Movies by genres * 3- sort the filtered ones * 4- paginate : slice movies from all movies according to page size * return : total count of page movies , page movies objects */ getPreparedData = () => { let filteredMovies = this.state.movies; console.log("fitlered Movies: " + filteredMovies); if (this.state.searchQuery) { filteredMovies = this.state.movies.filter(m => m.title .toLowerCase() .startsWith(this.state.searchQuery.toString().toLowerCase()) ); } else { let genreKey = ""; if (this.state.selectedGenre) { genreKey = [...this.state.genresMap.entries()] .filter(({ 1: v }) => v === this.state.selectedGenre.value) .map(([k]) => k); genreKey = parseInt(genreKey, 10); } filteredMovies = this.state.selectedGenre && genreKey !== 0 ? this.state.movies.filter(m => m.genre_ids.includes(genreKey)) : this.state.movies; } console.log("fitlered Movies-2: " + filteredMovies); const sortedMovies = _.orderBy( filteredMovies, this.state.sortColumn.path, this.state.sortColumn.order ); console.log("stored Movies: " + sortedMovies); const pageMovies = paginate( sortedMovies, this.state.currentPage, this.state.pageSize ); console.log("page Movies: " + pageMovies); return { totalCount: filteredMovies.length, data: pageMovies }; }; render() { const { totalCount, data } = this.getPreparedData(); let allYears = getYears(); console.log("totalCount : " + totalCount); console.log("data : " + data); // if (!totalCount || !data || this.state.isLoading) { // return ( // <div className="loading"> // <header className="App-header"> // <p>loading.......</p> // <img src={loading} className="App-loading" alt="loading" /> // </header> // </div> // ); // } return ( <div className="row justify-content-center padding-outer"> <div className="col-xs-12 col-md-11 col-lg-10 col-centered"> <div className="row justify-content-md-center cardcont-f"> <div className=" col-lg-3 col-md-4"> <p className="label">Select Year </p> <CustomDropDown items={allYears} onItemSelect={this.handleYearSelect} placeholderText={this.state.selectedYear} /> </div> <div className="col-lg-4 col-md-4"> <p className="label">Select Genre </p> <CustomDropDown items={this.state.genres} selectedItem={this.state.selectedGenre} onItemSelect={this.handleGenreSelect} placeholderText="All Genres" /> </div> <div className="col-lg-5 col-md-4"> <p className="label"> showing{" "} <span className="label-val">{this.state.movies.length}</span>{" "} movies </p> <SearchBox value={this.state.searchQuery} onChange={this.handleSearch} /> </div> </div> </div> <MoviesTable moviesList={data} genresMap={this.state.genresMap} columns={this.columns} sortColumn={this.state.sortColumn} onSort={this.handleSort} /> <Pagination itemsCount={totalCount} pageLimit={this.state.pageSize} pageNeighbours={2} currentPage={this.state.currentPage} onPageChanged={this.handlePageChange} key={totalCount} /> </div> ); } } export default Movies;
e14e53b836ee30da91be134b14014ca831060a1f
[ "JavaScript" ]
7
JavaScript
amrgamal91/TopMovies
646715f5f3df3dfb3e5f7e841c5197835cb356ca
15973ee625cb95c8fd118499cb1a8d9244a0d1d3
refs/heads/master
<file_sep>import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Card from '@material-ui/core/Card'; import CardMedia from '@material-ui/core/CardMedia'; import CardContent from '@material-ui/core/CardContent'; import Typography from '@material-ui/core/Typography'; import Box from '@material-ui/core/Box'; const useStyles = makeStyles(theme => ({ root: { maxWidth: 280, margin: 10 }, media: { height: 0, paddingTop: '56.25%', transition: 'transform .5s, filter 1.5s ease-in-out', "&:hover": { transform: 'scale(1.1)' } } })); export default function MediaCard({ title, avatar, description, image, color, base }) { const classes = useStyles({color, base}); return ( <Card className={classes.root}> <CardMedia className={classes.media} image={image} title={title} /> <CardContent> <Typography variant="subtitle1" component="h6"> {title} </Typography> <Typography style={{fontSize: "0.85rem", marginTop: 10}} variant="body1" color="textSecondary" component="p"> {description} </Typography> </CardContent> </Card> ); }<file_sep>import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Typography from '@material-ui/core/Typography'; import Header from '../src/Header'; import { ParallaxProvider } from 'react-scroll-parallax'; import Footer from '../src/Footer'; import Grid from '@material-ui/core/Grid'; import MediaCardHotel from '../components/mediaCardHotel'; import MainMenu from '../components/MainMenu'; const useStyles = makeStyles(theme => ({ banner: { bottom: '0', position: 'absolute', color: 'white', paddingLeft: '20px' }, bannerContainer: { position: 'relative' }, main: { display: 'flex', flexDirection: 'column', minHeight: '100vh', }, list: { padding: 10 }, titleH3: { [theme.breakpoints.down('xs')]: { fontSize: '2em' }, } })); function ListR () { const items = [ { title: '<NAME>', url: '/static/puerto-azul-card-photo.jpg', price: '105', location: 'Puntarenas', link: 'https://reservations.travelclick.com/112508?languageid=2#/guestsandrooms' }, { title: 'The Coast Beachfront', url: '/static/the-coast-main-card-photo.jpg', price: '155', location: 'Guanacaste', link: 'https://thecoastbeachfront.backhotelite.com/en/bookcore/my-booking/?lang=en' }, ]; return ( <Grid container spacing={2} direction="row" alignItems="center" style={{marginTop: '60px', marginBottom: '60px'}} justify="center"> {items && items.map( (item, index) => <Grid key={index} item md={5} xs={11}> <MediaCardHotel url={item.url} title={item.title} price={item.price} location={item.location} link={item.link}/> </Grid> )} </Grid>) } export default function Hotels() { const classes = useStyles(); return ( <ParallaxProvider> <main className={classes.main}> <div className={classes.bannerContainer}> <Header placeholder="Location, Restaurant, or Cuisine" img={'static/hotels-header.jpg'} custom='50vh' /> <div className={classes.banner}> <Typography className={classes.titleH3} variant="h3" component="h3" gutterBottom> Hotels </Typography> </div> </div> <MainMenu /> <div className={classes.list}> <ListR /> </div> <Footer /> </main> </ParallaxProvider> ); }<file_sep>import React from 'react'; import Paper from '@material-ui/core/Paper'; import InfoIcon from '@material-ui/icons/Info'; import IconButton from '@material-ui/core/IconButton'; import LocalActivityIcon from '@material-ui/icons/LocalActivity'; import FavoriteIcon from '@material-ui/icons/Favorite'; import LoyaltyIcon from '@material-ui/icons/Loyalty'; import HotelIcon from '@material-ui/icons/Hotel'; import CommuteIcon from '@material-ui/icons/Commute'; import RestaurantIcon from '@material-ui/icons/Restaurant'; import AppsIcon from '@material-ui/icons/Apps'; import useMediaQuery from '@material-ui/core/useMediaQuery'; import Link from '../src/Link'; import { makeStyles, createStyles } from '@material-ui/core/styles'; const useStyles = makeStyles((theme) => createStyles({ mainMenu: { width: '100%', display: 'flex', 'align-items': 'center', 'justify-content': 'center', backgroundColor: '#fff', 'flex-direction': 'row', 'flex-wrap': 'wrap', '& > *': { margin: theme.spacing(1), }, [theme.breakpoints.down('xs')]: { marginTop: 10, }, }, contentIcon: { display: 'flex', flexDirection: 'column', alignItems: 'center', margin: '5px 0', padding: 0, minWidth: '80px', [theme.breakpoints.up('xs')]: { marginTop: 20, }, }, textInfo: { paddingTop: '10px', fontSize: '0.80em', [theme.breakpoints.down('xs')]: { fontSize: '0.65em', }, }, }), ); export default function MainMenu() { const classes = useStyles(); const matches = useMediaQuery('(max-width:320px)'); const minPhone = matches; return ( <div className={classes.mainMenu} style={{ padding: `0 ${minPhone ? 0 : '20px'}`}}> <div className={classes.contentIcon}> <Paper elevation={3}> <IconButton aria-label="add to favorites"> <InfoIcon fontSize="large" style={{ color: 'black' }} /> </IconButton> </Paper> <span className={classes.textInfo}>Information</span> </div> <div className={classes.contentIcon}> <Paper elevation={3} > <IconButton aria-label="add to favorites"> <LocalActivityIcon fontSize="large" style={{ color: 'black' }} /> </IconButton> </Paper> <span className={classes.textInfo}>One Day Pass</span> </div> <div className={classes.contentIcon}> <Paper elevation={3} > <IconButton aria-label="add to favorites"> <LoyaltyIcon fontSize="large" style={{ color: 'black' }} /> </IconButton> </Paper> <span className={classes.textInfo}>Best Deals</span> </div> <div className={classes.contentIcon}> <Paper elevation={3} > <IconButton aria-label="add to favorites"> <FavoriteIcon fontSize="large" style={{ color: 'black' }} /> </IconButton> </Paper> <span className={classes.textInfo}>Most Visited</span> </div> <div className={classes.contentIcon}> <Paper elevation={3} component={Link} naked href="/hotels"> <IconButton aria-label="add to favorites"> <HotelIcon fontSize="large" style={{ color: 'black' }} /> </IconButton> </Paper> <span className={classes.textInfo}>Hotels</span> </div> <div className={classes.contentIcon}> <Paper elevation={3} > <IconButton aria-label="add to favorites"> <CommuteIcon fontSize="large" style={{ color: 'black' }} /> </IconButton> </Paper> <span className={classes.textInfo}>Transportation</span> </div> <div className={classes.contentIcon}> <Paper elevation={3} > <IconButton aria-label="add to favorites" component={Link} naked href="/restaurants"> <RestaurantIcon fontSize="large" style={{ color: 'black' }} /> </IconButton> </Paper> <span className={classes.textInfo}>Restaurants</span> </div> <div className={classes.contentIcon}> <Paper elevation={3} > <IconButton aria-label="add to favorites"> <AppsIcon fontSize="large" style={{ color: 'black' }} /> </IconButton> </Paper> <span className={classes.textInfo}>Apps</span> </div> </div> ); }<file_sep>import React from 'react'; import TextField from '@material-ui/core/TextField'; import Button from '@material-ui/core/Button'; import Typography from '@material-ui/core/Typography'; import { makeStyles } from '@material-ui/core/styles'; const useStyles = makeStyles(theme => ({ subscribe: { backgroundColor: '#f5f5f5', padding: '0px', display: "flex", justifyContent: "left", flexDirection: "row", maxHeight: '300px', overflow: 'hidden', [theme.breakpoints.down('sm')]: { flexDirection: "column", maxHeight: '100%' }, }, imgMobile: { width: '40%', height: '80%', maxWidth: '600px', [theme.breakpoints.down('sm')]: { width: "100%", marginBottom: '20px', maxWidth: '100%', }, }, content: { display: "flex", justifyContent: 'center', flexDirection: 'column', alignItems: 'center', width: '100%', padding: '10px' } })); export default function Subscribe ( ) { const classes = useStyles(); return ( <div style={{ margin: '50px 0 100px 0' }}> <div className={classes.subscribe}> <img className={classes.imgMobile} src='/static/home3.jpg' /> <div className={classes.content}> <Typography style={{marginBottom: 20}} variant="h5" component="h6"> Would you love to see this sunset? </Typography> <Typography component="p" align="left" gutterBottom> Sign up for our newsletter and discover travel experiences you’ll really want to try. </Typography> <div style={{ display: "flex", flexDirection: "row", marginTop: '40px' }}> <TextField id="outlined-basic" style={{ backgroundColor: '#fff'}} label="Your email" color="secondary" variant="outlined" /> <Button style={{ color: 'white', textTransform: 'capitalize', marginLeft: '10px' }} variant="contained" color="secondary"> Get Inspired </Button> </div> </div> </div> </div> ) }<file_sep>import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Typography from '@material-ui/core/Typography'; import Header from '../src/Header'; import { ParallaxProvider } from 'react-scroll-parallax'; import Footer from '../src/Footer'; import Grid from '@material-ui/core/Grid'; import MediaCardRestaurant from '../components/mediaCardRestaurant'; import MainMenu from '../components/MainMenu'; const useStyles = makeStyles(theme => ({ banner: { bottom: '0', position: 'absolute', color: 'white', paddingLeft: '20px' }, bannerContainer: { position: 'relative' }, main: { display: 'flex', flexDirection: 'column', minHeight: '100vh', }, list: { padding: 10 }, titleH3: { [theme.breakpoints.down('xs')]: { fontSize: '2em' }, } })); function ListR () { const items = [ { title: 'Vino Mundo', url: '/static/Carrabbas-Food-Wine-Pairing-Vino-Mundo.png', type: 'International food', location: 'San José, Brasil de Mora' }, { title: '11.47', url: '/static/fusion-cuisine-restaurants.jpg', type: 'International food', location: 'San José, Brasil de Mora' }, { title: 'La Esquina de Buenos Aires', url: '/static/steakhouse-La-Esquina-de-buenos-Aiers.jpg', type: 'International food', location: 'San José, Brasil de Mora' }, { title: 'La Fabrika', url: '/static/pizza-la-Fabrika.jpg', type: 'International food', location: 'San José, Brasil de Mora' }, { title: 'El Novillo Alegre', url: '/static/steak-el-Novillo-Alegre.jpg', type: 'International food', location: 'San José, Brasil de Mora' }, { title: 'Rostipollos', url: '/static/rostipollos.jpg', type: 'International food', location: 'San José, Brasil de Mora' }, ]; return ( <Grid container spacing={2} direction="row" alignItems="center" style={{marginTop: '60px', marginBottom: '60px'}} justify="center"> {items && items.map( (item, index) => <Grid key={index} item md={5} xs={11}> <MediaCardRestaurant url={item.url} title={item.title} type={item.type} location={item.location} /> </Grid> )} </Grid>) } export default function Restaurants() { const classes = useStyles(); return ( <ParallaxProvider> <main className={classes.main}> <div className={classes.bannerContainer}> <Header optional placeholder="Location, Restaurant, or Cuisine" img={'static/table-in-vintage-restaurant-6267.jpg'} custom='50vh' /> <div className={classes.banner}> <Typography className={classes.titleH3} variant="h3" component="h3" gutterBottom> Restaurants </Typography> </div> </div> <MainMenu /> <div className={classes.list}> <ListR /> </div> <Footer /> </main> </ParallaxProvider> ); }
090b544726ca36be3ee96eecb7e2a91c4229fb2a
[ "JavaScript" ]
5
JavaScript
manuelrojas/bestplacescostarica
917a4cb37ee3616cd1e980a2b73252b81f5d4a2f
2fa6f4400b6bf7a512aa9be9f6cc026e12e0ab58
refs/heads/master
<file_sep>import React from 'react'; import './List.scss'; import { Link } from 'react-router-dom'; const List = (props) => { const { recipes } = props; if (!recipes || recipes.length === 0) return <p>No recipes, sorry</p>; return ( <> <ul className="recipe-list"> {recipes.map((recipe) => { return ( <Link to={`/${recipe.title}`} className="recipe-title"> <li key={recipe.apiRef}>{recipe.title}</li> </Link> ); })} </ul> </> ); }; export default List;
c939a2d1e81e08759f63b541e61ccf423290bebb
[ "JavaScript" ]
1
JavaScript
opensussex/fostr.io
a51375ee913664b7513820655ae395ed43294de5
7c2b83a2a3e5b30e6f8584c8fee433df76fe77da
refs/heads/master
<repo_name>CharlieADavies/code-jam-6<file_sep>/excellent-exorcists/src/main.py from src.core.game import Game from src.core.game_loop import GameLoop from src.core.screen_manager import ScreenManager from src.screens.game_screen import GameScreen if __name__ == '__main__': loop = GameLoop() screen_manager = ScreenManager() screen_manager.add_screen(GameScreen) screen_manager.set_current_screen(GameScreen) loop.start(60) game = Game(loop, screen_manager) game.run() <file_sep>/excellent-exorcists/src/core/game.py from kivy.app import App from src.core.game_loop import GameLoop from src.core.screen_manager import ScreenManager class Game(App): def __init__(self, loop: GameLoop, screen_manager: ScreenManager, **kwargs): super().__init__(**kwargs) self.loop = loop self.screen_manager = screen_manager self.loop.set_callback(self.loop_callback) def build(self): return self.screen_manager def loop_callback(self, delta): if self.screen_manager.current is not None: self.screen_manager.current.update(delta) self.screen_manager.current.render_screen(delta) <file_sep>/excellent-exorcists/src/core/camera.py from typing import Tuple from kivy.graphics.transformation import Matrix class Camera: def get_viewport(self) -> Tuple[int, int]: raise NotImplementedError def get_projection(self) -> Tuple[Matrix, Matrix]: raise NotImplementedError class OrthographicCamera(Camera): def __init__(self, viewport_width: int, viewport_height: int): self.viewport_width = viewport_width self.viewport_height = viewport_height self.aspect_ratio = float(viewport_height) / float(viewport_width) self.height = viewport_height self.width = viewport_width self.pos_x = 0.0 self.pos_y = 0.0 self.zoom = 0 def get_viewport(self) -> Tuple[int, int]: return self.viewport_width, self.viewport_height def set_size(self, width: int, height: int): self.height = height self.width = width def set_position(self, x: float, y: float): self.pos_x = x self.pos_y = y def update(self, delta: float): pass def set_zoom(self, zoom: float): self.zoom = zoom def get_projection(self) -> Tuple[Matrix, Matrix]: viewport_w = self.viewport_width viewport_h = self.viewport_height width = viewport_w / 2 height = viewport_h / 2 x = -self.pos_x y = -self.pos_y projection = Matrix() projection.view_clip(0, viewport_w, 0, viewport_h, -1.0, 1.0, 0) projection.scale(self.zoom, self.zoom, self.zoom) projection.translate(1 + x / width * self.zoom, 1 + y / height * self.zoom, 0) model_view = Matrix() return projection, model_view <file_sep>/excellent-exorcists/src/core/screen.py from kivy.graphics.instructions import RenderContext from kivy.uix.widget import Widget from kivy.core.window import Window class Screen(Widget): def __init__(self, **kwargs): self.canvas = RenderContext() self.pressed_keys = set() Window.bind(on_key_down=self.key_down) Window.bind(on_key_up=self.key_up) super().__init__(**kwargs) def key_down(self, _, key, *args): self.pressed_keys.add(key) def key_up(self, _, key, *args): self.pressed_keys.discard(key) def render(self, delta): """Override this method and render graphics""" def update(self, delta): """Override this method for updating state""" def on_create(self): """Called when initialized from screen manager""" def on_destroy(self): """Called when removed from screen manager""" def on_open(self): """Called when the screen is opened""" def on_close(self): """Called when the screen is closed""" def on_resize(self, width: int, height: int): """Called on window resize""" def clear(self): self.canvas.clear() def set_projection_matrix(self, matrices): self.canvas['projection_mat'] = matrices[0] self.canvas['modelview_mat'] = matrices[1] def render_screen(self, delta): """Wrapper method for render, should not be overrided""" with self.canvas: self.render(delta) <file_sep>/excellent-exorcists/src/core/screen_manager.py from kivy.uix.widget import Widget from kivy.core.window import Window class InvalidGameScreen(Exception): def __init__(self, *args, **kwargs): pass class ScreenManager(Widget): def __init__(self, **kwargs): super().__init__(**kwargs) self.screens = {} self.current = None Window.bind(on_resize=self.on_window_resize) def on_window_resize(self, _, width: int, height: int): if self.current is not None: self.current.width = width self.current.height = height self.current.on_resize(width, height) def add_screen(self, screen_class): if screen_class in self.screens: raise InvalidGameScreen(f'Game screen already in screen manager {str(screen_class)}') screen_instance = screen_class() self.screens[screen_class] = screen_instance screen_instance.on_create() def remove_screen(self, screen_class): if screen_class not in self.screens: raise InvalidGameScreen(f'Invalid game screen class {str(screen_class)}') instance = self.screens[screen_class] del self.screens[screen_class] instance.on_destroy() def set_current_screen(self, screen_class): if screen_class not in self.screens: raise InvalidGameScreen(f'Invalid game screen class {str(screen_class)}') if self.current is not None: self.remove_widget(self.current) self.current.on_close() self.current = self.screens[screen_class] self.current.on_open() self.add_widget(self.current) <file_sep>/excellent-exorcists/src/screens/game_screen.py from kivy.graphics.vertex_instructions import Rectangle from kivy.graphics import Color from kivy.uix.label import Label from kivy.core.window import Keyboard from src.core.screen import Screen from src.core.camera import OrthographicCamera import random class GameScreen(Screen): def __init__(self, **kwargs): super().__init__(**kwargs) self.player_x = 0 self.player_y = 0 self.zoom = 1 self.fps = 0 self.camera = OrthographicCamera(1280, 720) self.positions = [(random.randint(0, 1200), random.randint(0, 700)) for _ in range(100)] def on_resize(self, width: int, height: int): self.camera.set_size(width, height) def render(self, delta: float): self.set_projection_matrix(self.camera.get_projection()) self.clear() Color(0, 0, 1) Rectangle(pos=(0, 0), size=(300, 300)) Color(1., 1., 0) for pos in self.positions: Rectangle(pos=pos, size=(50, 50)) Color(1, 0, 0) Rectangle(pos=(self.player_x, self.player_y), size=(20, 60)) Color(0, 1, 0) Label(text=f'FPS: {self.fps}') def update(self, delta: float): self.camera.update(delta) self.camera.set_zoom(self.zoom) self.camera.set_position(self.player_x, self.player_y) player_speed = 50 if Keyboard.keycodes['a'] in self.pressed_keys: self.player_x -= player_speed * delta elif Keyboard.keycodes['d'] in self.pressed_keys: self.player_x += player_speed * delta if Keyboard.keycodes['e'] in self.pressed_keys: self.zoom += delta elif Keyboard.keycodes['q'] in self.pressed_keys: self.zoom -= delta if Keyboard.keycodes['w'] in self.pressed_keys: self.player_y += player_speed * delta elif Keyboard.keycodes['s'] in self.pressed_keys: self.player_y -= player_speed * delta speed = 15 self.fps = round(1 / delta) for i in range(len(self.positions)): x, y = self.positions[i] self.positions[i] = (x + speed * delta, y + speed * delta) <file_sep>/hormonal-hedonists/Pipfile [[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] flake8 = "*" [packages] docutils = {version = "*",sys_platform = "== 'win32'"} pygments = {version = "*",sys_platform = "== 'win32'"} pypiwin32 = {version = "*",sys_platform = "== 'win32'"} kivy-deps-sdl2 = {version = "==0.1.*",sys_platform = "== 'win32'"} kivy-deps-glew = {version = "==0.1.*",sys_platform = "== 'win32'"} kivy = "==1.11.1" pipfile = "*" ffpyplayer = "*" graph = "*" [requires] python_version = "3.7" [scripts] lint = "python -m flake8" start = "python -m TLOA" <file_sep>/excellent-exorcists/src/core/game_loop.py from kivy.clock import Clock class GameLoop: def __init__(self): self.loop = None self.callback_ = lambda _: _ def set_callback(self, callback): self.callback_ = callback def callback(self, delta): self.callback_(delta) def start(self, fps: int): self.loop = Clock.schedule_interval(self.callback, 1.0 / float(fps)) def stop(self): if self.loop is not None: self.loop.cancel()
4fce18e153291f655af22845db496ff3ada9f252
[ "TOML", "Python" ]
8
Python
CharlieADavies/code-jam-6
4de1527d0d54207c5b7b09fe2a7ad3ab8071bd95
1953c4782359f177ccdb00cffe1af6c88ae41e26
refs/heads/master
<file_sep>package dengluzhuce.service; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dengluzhuce.util.Register; /** * Servlet implementation class ServletRegister */ @WebServlet("/ServletRegister") public class ServletRegister extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ServletRegister() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean b = false; Register myPOJO=new Register(); String id=request.getParameter("username"); String password=request.getParameter("<PASSWORD>"); String email = request.getParameter("email"); b=myPOJO.userregister(id,password,email); if(b){ response.sendRedirect("login.jsp"); } else{ response.sendRedirect("register.jsp"); } } } <file_sep>package dengluzhuce.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class UserLogin { String drv = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/yuzexing"; String usr = "root"; String pwd = "<PASSWORD>"; public boolean isuserLogin(String id, String password) throws SQLException { boolean isValid = false; String sql = "select * from login where uname='" + id + "' and password='" + password + "'"; try { Class.forName(drv).newInstance(); // Connection conn = DriverManager.getConnection(url); Connection conn = DriverManager.getConnection(url, usr, pwd); Statement stm = conn.createStatement(); ResultSet rs = stm.executeQuery(sql); if (rs.next()) { isValid = true; } rs.close(); stm.close(); conn.close(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } /* * finally { if(rs!=null) { rs.close(); } } */ return isValid; } }
036a8322160669bd64811e4646e3d3b6d67f04ad
[ "Java" ]
2
Java
yuzexinglove123/yuzexingcangku
55d1d117e78449c57426e94c63f61024b1fda843
820ee3f907f8f9d2afb75b307951a49f7bbb3002
refs/heads/master
<repo_name>qfeng3168/ABP-MicroService<file_sep>/README.md #### 项目简介 一个基于ABP vNext微服务架构、vue-element-admin的后台管理系统,适用于大型分布式业务系统和企业后台,也可以集成各种小程序、电商后台以及业务中台。 **启动文档:** [博客园](https://www.cnblogs.com/william-xu/p/12806810.html) **博客地址:** [博客园](https://www.cnblogs.com/william-xu/) **快速启动:** 运行run目录下脚本 **账号密码:** `<PASSWORD>*` #### 主要特性 - 最新.net core框架,稳定强大 - 基于abp vNext、vue-element-admin,成熟的开发社区 - 微服务架构设计,DDD实践 - 统一授权、身份、权限管理,简化微服务开发 - 多租户 - 容器化、ci/cd集成 #### 系统功能 - 用户管理 - 角色管理 - 组织机构 - 字典管理 #### TODO: - 租户管理 - 菜单管理 - 岗位管理 - 职员管理 - 操作日志 - 流程管理 #### 系统预览 <table> <tr> <td><img src="https://i.loli.net/2020/06/16/AXbKfgtaqhZrClm.png"/></td> <td><img src="https://i.loli.net/2020/06/16/1BhfAeVCJPU5azH.png"/></td> </tr> <tr> <td><img src="https://i.loli.net/2020/06/16/8U7uQEVRb4rdYmw.png"/></td> <td><img src="https://i.loli.net/2020/06/16/aqPcQ4WeXytzi5Z.png"/></td> </tr> <tr> <td><img src="https://i.loli.net/2020/06/16/LJS5Uy7owtNGfgK.png"/></td> <td><img src="https://i.loli.net/2020/06/16/yc1LUur8fKDlWgF.png"/></td> </tr> <tr> <td><img src="https://i.loli.net/2020/06/22/5Wsl9NgB3CbGh4H.png"/></td> <td><img src="https://i.loli.net/2020/06/22/UZcrAliMTv7JntO.png"/></td> </tr> </table> <file_sep>/MicroServices/Business/Business.Application.Contracts/Permissions/BusinessPermissionDefinitionProvider.cs using Business.Localization; using Microsoft.Extensions.Localization; using System; using System.Collections.Generic; using System.Text; using Volo.Abp.Authorization.Permissions; using Volo.Abp.Localization; using Volo.Abp.MultiTenancy; namespace Business.Permissions { public class BusinessPermissionDefinitionProvider: PermissionDefinitionProvider { public override void Define(IPermissionDefinitionContext context) { var business = context.AddGroup(BusinessPermissions.Business, L("Business"), MultiTenancySides.Tenant); var dictionary = business.AddPermission(BusinessPermissions.DataDictionary.Default, L("DataDictionary")); dictionary.AddChild(BusinessPermissions.DataDictionary.Update, L("Edit")); dictionary.AddChild(BusinessPermissions.DataDictionary.Delete, L("Delete")); dictionary.AddChild(BusinessPermissions.DataDictionary.Create, L("Create")); var dictionaryDetail = business.AddPermission(BusinessPermissions.DataDictionaryDetail.Default, L("DataDictionary")); dictionaryDetail.AddChild(BusinessPermissions.DataDictionaryDetail.Update, L("Edit")); dictionaryDetail.AddChild(BusinessPermissions.DataDictionaryDetail.Delete, L("Delete")); dictionaryDetail.AddChild(BusinessPermissions.DataDictionaryDetail.Create, L("Create")); var organization = business.AddPermission(BusinessPermissions.Organization.Default,L("Organization")); organization.AddChild(BusinessPermissions.Organization.Update, L("Edit")); organization.AddChild(BusinessPermissions.Organization.Delete, L("Delete")); organization.AddChild(BusinessPermissions.Organization.Create, L("Create")); var job = business.AddPermission(BusinessPermissions.Job.Default, L("Job")); job.AddChild(BusinessPermissions.Job.Update, L("Edit")); job.AddChild(BusinessPermissions.Job.Delete, L("Delete")); job.AddChild(BusinessPermissions.Job.Create, L("Create")); var employee = business.AddPermission(BusinessPermissions.Employee.Default, L("Employee")); employee.AddChild(BusinessPermissions.Employee.Update, L("Edit")); employee.AddChild(BusinessPermissions.Employee.Delete, L("Delete")); employee.AddChild(BusinessPermissions.Employee.Create, L("Create")); } private static LocalizableString L(string name) { return LocalizableString.Create<BusinessResource>(name); } } } <file_sep>/MicroServices/Business/Business.HttpApi/BaseData/EmployeeController.cs using Business.BaseData.EmployeeManagement; using Business.BaseData.EmployeeManagement.Dto; using Business.Controllers; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Threading.Tasks; using Volo.Abp.Application.Dtos; namespace Business.BaseData { [Area("business")] [Route("api/business/employee")] public class EmployeeController : BusinessController, IEmployeeAppService { private readonly IEmployeeAppService _employeeAppService; public EmployeeController(IEmployeeAppService employeeAppService) { _employeeAppService = employeeAppService; } [HttpPost] public Task<EmployeeDto> Create(CreateOrUpdateEmployeeDto input) { return _employeeAppService.Create(input); } [HttpPost] [Route("delete")] public Task Delete(List<Guid> ids) { return _employeeAppService.Delete(ids); } [HttpGet] [Route("{id}")] public Task<EmployeeDto> Get(Guid id) { return _employeeAppService.Get(id); } [HttpGet] [Route("all")] public Task<PagedResultDto<EmployeeDto>> GetAll(GetEmployeeInputDto input) { return _employeeAppService.GetAll(input); } [HttpPut] [Route("{id}")] public Task<EmployeeDto> Update(Guid id, CreateOrUpdateEmployeeDto input) { return _employeeAppService.Update(id, input); } } } <file_sep>/MicroServices/Business/Business.HttpApi/BaseData/DataDictionaryController.cs using Business.BaseData.DataDictionaryManagement; using Business.BaseData.DataDictionaryManagement.Dto; using Business.Controllers; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Threading.Tasks; using Volo.Abp.Application.Dtos; namespace Business.BaseData { [Area("business")] [Route("api/business/dict")] public class DataDictionaryController : BusinessController, IDictionaryAppService { private readonly IDictionaryAppService _dictionaryAppService; public DataDictionaryController(IDictionaryAppService dictionaryAppService) { _dictionaryAppService = dictionaryAppService; } [HttpPost] public Task<DictionaryDto> Create(CreateOrUpdateDictionaryDto input) { return _dictionaryAppService.Create(input); } [HttpPost] [Route("Delete")] public Task Delete(List<Guid> ids) { return _dictionaryAppService.Delete(ids); } [HttpGet] [Route("{id}")] public Task<DictionaryDto> Get(Guid id) { return _dictionaryAppService.Get(id); } [HttpGet] [Route("all")] public Task<PagedResultDto<DictionaryDto>> GetAll(GetDictionaryInputDto input) { return _dictionaryAppService.GetAll(input); } [HttpPut] [Route("{id}")] public Task<DictionaryDto> Update(Guid id, CreateOrUpdateDictionaryDto input) { return _dictionaryAppService.Update(id, input); } } } <file_sep>/MicroServices/Business/Business.EntityFrameworkCore/EntityFrameworkCore/BusinessDbContextModelCreatingExtensions.cs using Business.BaseData; using Microsoft.EntityFrameworkCore; using Volo.Abp; using Volo.Abp.EntityFrameworkCore.Modeling; namespace Business.EntityFrameworkCore { public static class BusinessDbContextModelCreatingExtensions { public static void ConfigureBusiness(this ModelBuilder builder) { Check.NotNull(builder, nameof(builder)); builder.Entity<DataDictionary>(b => { b.ToTable("base_dict"); b.ConfigureConcurrencyStamp(); b.ConfigureExtraProperties(); b.ConfigureAudited(); b.Property(x => x.Name).IsRequired().HasMaxLength(BusinessConsts.MaxNameLength); b.Property(x => x.Description).HasMaxLength(BusinessConsts.MaxNotesLength); b.Property(x => x.IsDeleted).HasDefaultValue(false); b.HasIndex(q => q.Name); }); builder.Entity<DataDictionaryDetail>(b => { b.ToTable("base_dict_details"); b.ConfigureConcurrencyStamp(); b.ConfigureExtraProperties(); b.ConfigureAudited(); b.Property(x => x.Label).IsRequired().HasMaxLength(BusinessConsts.MaxNameLength); b.Property(x => x.Value).IsRequired().HasMaxLength(BusinessConsts.MaxNotesLength); b.Property(x => x.IsDeleted).HasDefaultValue(false); b.HasIndex(q => q.Pid); }); builder.Entity<Organization>(b => { b.ToTable("base_orgs"); b.ConfigureConcurrencyStamp(); b.ConfigureExtraProperties(); b.ConfigureAudited(); b.ConfigureSoftDelete(); b.Property(x => x.Name).IsRequired().HasMaxLength(BusinessConsts.MaxNameLength); b.Property(x => x.FullName).IsRequired().HasMaxLength(BusinessConsts.MaxFullNameLength); b.Property(x => x.Enabled).HasDefaultValue(false); b.HasIndex(q => q.Pid); }); builder.Entity<Employee>(b => { b.ToTable("base_employees"); b.ConfigureConcurrencyStamp(); b.ConfigureExtraProperties(); b.ConfigureAudited(); b.ConfigureSoftDelete(); b.Property(x => x.Name).IsRequired().HasMaxLength(BusinessConsts.MaxNameLength); b.Property(x => x.Phone).IsRequired().HasMaxLength(BusinessConsts.MaxNameLength); b.Property(x => x.Email).IsRequired().HasMaxLength(BusinessConsts.MaxNotesLength); b.HasIndex(q => q.UserId); }); builder.Entity<Job>(b => { b.ToTable("base_jobs"); b.ConfigureConcurrencyStamp(); b.ConfigureExtraProperties(); b.ConfigureAudited(); b.ConfigureSoftDelete(); b.Property(x => x.Name).IsRequired().HasMaxLength(BusinessConsts.MaxNameLength); b.Property(x => x.Description).HasMaxLength(BusinessConsts.MaxNotesLength); }); builder.Entity<EmployeeJob>(b => { b.ToTable("base_employee_jobs"); b.HasKey(k => k.EmployeeId); }); } } } <file_sep>/MicroServices/Business/Business.Application.Contracts/BaseData/EmployeeManagement/Dto/EmployeeDto.cs using System; using System.Collections.Generic; using System.Text; using Volo.Abp.Application.Dtos; namespace Business.BaseData.EmployeeManagement.Dto { public class EmployeeDto : EntityDto<Guid> { public string Name { get; set; } /// <summary> /// 性别:0:女,1:男,2:其他 /// </summary> public short Gender { get; set; } public string Phone { get; set; } public string Email { get; set; } public bool Enabled { get; set; } public Guid? OrgId { get; set; } public Guid? UserId { get; set; } } } <file_sep>/MicroServices/Business/Business.Host/Migrations/20200612023551_update_org.cs using Microsoft.EntityFrameworkCore.Migrations; namespace Business.Migrations { public partial class update_org : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "Address", table: "base_orgs"); migrationBuilder.DropColumn( name: "AreaId", table: "base_orgs"); migrationBuilder.DropColumn( name: "Remark", table: "base_orgs"); migrationBuilder.DropColumn( name: "Tel", table: "base_orgs"); migrationBuilder.AddColumn<bool>( name: "Enable", table: "base_orgs", nullable: false, defaultValue: false); migrationBuilder.AddColumn<int>( name: "Sort", table: "base_orgs", nullable: false, defaultValue: 0); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "Enable", table: "base_orgs"); migrationBuilder.DropColumn( name: "Sort", table: "base_orgs"); migrationBuilder.AddColumn<string>( name: "Address", table: "base_orgs", type: "nvarchar(256)", maxLength: 256, nullable: true); migrationBuilder.AddColumn<int>( name: "AreaId", table: "base_orgs", type: "int", nullable: false, defaultValue: 0); migrationBuilder.AddColumn<string>( name: "Remark", table: "base_orgs", type: "nvarchar(256)", maxLength: 256, nullable: true); migrationBuilder.AddColumn<string>( name: "Tel", table: "base_orgs", type: "nvarchar(16)", maxLength: 16, nullable: true); } } } <file_sep>/MicroServices/Business/Business.Application/BaseData/OrganizationManagement/OrganizationAppService.cs using Business.BaseData.OrganizationManagement.Dto; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Dynamic.Core; using System.Threading.Tasks; using Volo.Abp; using Volo.Abp.Application.Dtos; using Volo.Abp.Application.Services; using Volo.Abp.Domain.Repositories; namespace Business.BaseData.OrganizationManagement { public class OrganizationAppService : ApplicationService, IOrganizationAppService { private readonly IRepository<Organization, Guid> _repository; public OrganizationAppService(IRepository<Organization, Guid> repository) { _repository = repository; } public async Task<OrganizationDto> Create(CreateOrUpdateOrganizationDto input) { var exist = await _repository.FirstOrDefaultAsync(_ => _.Name == input.Name); var parent = await _repository.FirstOrDefaultAsync(_ => _.Id == input.Pid); if (exist != null) { throw new BusinessException("名称:" + input.Name + "机构已存在"); } var result = await _repository.InsertAsync(new Organization( GuidGenerator.Create(), input.CategoryId, input.Pid, input.Name, parent == null ? input.Name : parent.FullName + "/" + input.Name, input.Sort, input.Enabled )); return ObjectMapper.Map<Organization, OrganizationDto>(result); } public async Task Delete(Guid id) { await _repository.DeleteAsync(id); } public async Task<OrganizationDto> Get(Guid id) { var result = await _repository.GetAsync(id); return ObjectMapper.Map<Organization, OrganizationDto>(result); } public async Task<ListResultDto<OrganizationDto>> GetAll(GetOrganizationInputDto input) { var query = _repository .WhereIf(!string.IsNullOrWhiteSpace(input.Filter), _ => _.Name.Contains(input.Filter)) .Where(_ => _.Pid == input.Pid) .WhereIf(input.CategoryId.HasValue, _ => _.CategoryId == input.CategoryId); var items = await query.OrderBy(input.Sorting ?? "Sort") .ToListAsync(); var dtos = ObjectMapper.Map<List<Organization>, List<OrganizationDto>>(items); foreach (var dto in dtos) { var any = await _repository.AnyAsync(_ => _.Pid == dto.Id); dto.HasChildren = any ? true : false; dto.Leaf = any ? false : true; } return new ListResultDto<OrganizationDto>(dtos); } public async Task<ListResultDto<OrganizationDto>> GetAllWithParents(GetOrganizationInputDto input) { var result = await _repository.Where(_ => _.Pid == null).OrderBy(input.Sorting ?? "Name").ToListAsync(); var self = await _repository.FirstOrDefaultAsync(_ => _.Id == input.Id); result.Add(self); var dtos = ObjectMapper.Map<List<Organization>, List<OrganizationDto>>(result); return new ListResultDto<OrganizationDto>(dtos); } public async Task<PagedResultDto<OrganizationDto>> GetAllList(GetOrganizationInputDto input) { var query = _repository .WhereIf(!string.IsNullOrWhiteSpace(input.Filter), _ => _.Name.Contains(input.Filter)) .WhereIf(input.Pid.HasValue, _ => _.Pid == input.Pid) .WhereIf(input.CategoryId.HasValue, _ => _.CategoryId == input.CategoryId); var items = await query.OrderBy(input.Sorting ?? "Name") .Skip(input.SkipCount) .Take(input.MaxResultCount) .ToListAsync(); var totalCount = await query.CountAsync(); var dtos = ObjectMapper.Map<List<Organization>, List<OrganizationDto>>(items); return new PagedResultDto<OrganizationDto>(totalCount, dtos); } public async Task<OrganizationDto> Update(Guid id, CreateOrUpdateOrganizationDto input) { var org = await _repository.FirstOrDefaultAsync(_ => _.Id == id); org.Pid = input.Pid; //TODO:后台任务执行子集fullName修改 org.Name = input.Name; org.Sort = input.Sort; org.Enabled = input.Enabled; return ObjectMapper.Map<Organization, OrganizationDto>(org); } } } <file_sep>/MicroServices/Business/Business.HttpApi/BaseData/DataDictionaryDetailController.cs using Business.BaseData.DataDictionaryManagement; using Business.BaseData.DataDictionaryManagement.Dto; using Business.Controllers; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Threading.Tasks; using Volo.Abp.Application.Dtos; namespace Business.BaseData { [Area("business")] [Route("api/business/dictDetails")] public class DataDictionaryDetailController : BusinessController, IDictionaryDetailAppService { private readonly IDictionaryDetailAppService _dictionaryDetailAppService; public DataDictionaryDetailController(IDictionaryDetailAppService dictionaryDetailAppService) { _dictionaryDetailAppService = dictionaryDetailAppService; } [HttpPost] public Task<DictionaryDetailDto> Create(CreateOrUpdateDictionaryDetailDto input) { return _dictionaryDetailAppService.Create(input); } [HttpPost] [Route("delete")] public Task Delete(List<Guid> ids) { return _dictionaryDetailAppService.Delete(ids); } [HttpGet] [Route("{id}")] public Task<DictionaryDetailDto> Get(Guid id) { return _dictionaryDetailAppService.Get(id); } [HttpGet] [Route("all")] public Task<PagedResultDto<DictionaryDetailDto>> GetAll(GetDictionaryDetailInputDto input) { return _dictionaryDetailAppService.GetAll(input); } [HttpPut] [Route("{id}")] public Task<DictionaryDetailDto> Update(Guid id, CreateOrUpdateDictionaryDetailDto input) { return _dictionaryDetailAppService.Update(id, input); } } } <file_sep>/MicroServices/Business/Business.Application/BusinessApplicationAutoMapperProfile.cs using AutoMapper; using Business.BaseData; using Business.BaseData.DataDictionaryManagement.Dto; using Business.BaseData.EmployeeManagement.Dto; using Business.BaseData.JobManagement.Dto; using Business.BaseData.OrganizationManagement.Dto; namespace Business { public class BusinessApplicationAutoMapperProfile : Profile { public BusinessApplicationAutoMapperProfile() { CreateMap<DataDictionary, DictionaryDto>(); CreateMap<DataDictionaryDetail, DictionaryDetailDto>(); CreateMap<Organization, OrganizationDto>(); CreateMap<Employee, EmployeeDto>(); CreateMap<Job, JobDto>(); } } } <file_sep>/MicroServices/Business/Business.Application/Test/TestAppService.cs using System.Threading.Tasks; using Volo.Abp.Application.Services; namespace Business.Test { //[Authorize(BusinessPermissions.DataDictionary.Default)] public class TestAppService : ApplicationService, ITestAppService { public async Task<string> TestApi(string name) { return "010101"; } } } <file_sep>/MicroServices/Business/Business.Domain/BaseData/EmployeeJob.cs using System; namespace Business.BaseData { public class EmployeeJob { public Guid EmployeeId { get; set; } public Guid JobId { get; set; } } } <file_sep>/MicroServices/Business/Business.Application/BaseData/EmployeeManagement/EmployeeAppService.cs using Business.BaseData.EmployeeManagement.Dto; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Dynamic.Core; using System.Threading.Tasks; using Volo.Abp; using Volo.Abp.Application.Dtos; using Volo.Abp.Application.Services; using Volo.Abp.Domain.Repositories; namespace Business.BaseData.EmployeeManagement { public class EmployeeAppService : ApplicationService, IEmployeeAppService { private readonly IRepository<Employee, Guid> _repository; public EmployeeAppService(IRepository<Employee, Guid> repository) { _repository = repository; } public async Task<EmployeeDto> Create(CreateOrUpdateEmployeeDto input) { var exist = await _repository.FirstOrDefaultAsync(_ => _.Name == input.Name); if (exist != null) { throw new BusinessException("名称:" + input.Name + "职员已存在"); } var result = await _repository.InsertAsync(new Employee(GuidGenerator.Create(), input.Name, input.Gender, input.Phone, input.Email, input.Enabled, input.OrgId, input.UserId)); return ObjectMapper.Map<Employee, EmployeeDto>(result); } public async Task Delete(List<Guid> ids) { foreach (var id in ids) { await _repository.DeleteAsync(id); } } public async Task<EmployeeDto> Get(Guid id) { var result = await _repository.GetAsync(id); return ObjectMapper.Map<Employee, EmployeeDto>(result); } public async Task<PagedResultDto<EmployeeDto>> GetAll(GetEmployeeInputDto input) { var query = _repository.WhereIf(!string.IsNullOrWhiteSpace(input.Filter), _ => _.Name.Contains(input.Filter)); var totalCount = await query.CountAsync(); var items = await query.OrderBy(input.Sorting ?? "Name") .ToListAsync(); var dots = ObjectMapper.Map<List<Employee>, List<EmployeeDto>>(items); return new PagedResultDto<EmployeeDto>(totalCount, dots); } public async Task<EmployeeDto> Update(Guid id, CreateOrUpdateEmployeeDto input) { var employee = await _repository.GetAsync(id); employee.Name = input.Name; employee.Enabled = input.Enabled; employee.Email = input.Email; employee.Gender = input.Gender; employee.OrgId = input.OrgId; employee.UserId = input.UserId; return ObjectMapper.Map<Employee, EmployeeDto>(employee); } } } <file_sep>/MicroServices/Business/Business.Application.Contracts/BusinessApplicationContractsModule.cs using Volo.Abp.Application; using Volo.Abp.Modularity; using Volo.Abp.PermissionManagement; namespace Business { [DependsOn( typeof(BusinessDomainModule), typeof(AbpDddApplicationModule), typeof(AbpPermissionManagementApplicationContractsModule) )] public class BusinessApplicationContractsModule : AbpModule { } } <file_sep>/MicroServices/Business/Business.Host/Migrations/20200623065851_create_employees_AND_jobs.cs using System; using Microsoft.EntityFrameworkCore.Migrations; namespace Business.Migrations { public partial class create_employees_AND_jobs : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AlterColumn<string>( name: "FullName", table: "base_orgs", maxLength: 128, nullable: false, oldClrType: typeof(string), oldType: "nvarchar(256)", oldMaxLength: 256); migrationBuilder.CreateTable( name: "base_employee_jobs", columns: table => new { EmployeeId = table.Column<Guid>(nullable: false), JobId = table.Column<Guid>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_base_employee_jobs", x => x.EmployeeId); }); migrationBuilder.CreateTable( name: "base_employees", columns: table => new { Id = table.Column<Guid>(nullable: false), ExtraProperties = table.Column<string>(nullable: true), ConcurrencyStamp = table.Column<string>(nullable: true), CreationTime = table.Column<DateTime>(nullable: false), CreatorId = table.Column<Guid>(nullable: true), LastModificationTime = table.Column<DateTime>(nullable: true), LastModifierId = table.Column<Guid>(nullable: true), Name = table.Column<string>(maxLength: 50, nullable: false), Gender = table.Column<short>(nullable: false), Phone = table.Column<string>(maxLength: 50, nullable: false), Email = table.Column<string>(maxLength: 256, nullable: false), Enabled = table.Column<bool>(nullable: false), OrgId = table.Column<Guid>(nullable: false), UserId = table.Column<Guid>(nullable: false), IsDeleted = table.Column<bool>(nullable: false, defaultValue: false) }, constraints: table => { table.PrimaryKey("PK_base_employees", x => x.Id); }); migrationBuilder.CreateTable( name: "base_jobs", columns: table => new { Id = table.Column<Guid>(nullable: false), ExtraProperties = table.Column<string>(nullable: true), ConcurrencyStamp = table.Column<string>(nullable: true), CreationTime = table.Column<DateTime>(nullable: false), CreatorId = table.Column<Guid>(nullable: true), LastModificationTime = table.Column<DateTime>(nullable: true), LastModifierId = table.Column<Guid>(nullable: true), Name = table.Column<string>(maxLength: 50, nullable: false), Enabled = table.Column<bool>(nullable: false), Sort = table.Column<int>(nullable: false), IsDeleted = table.Column<bool>(nullable: false, defaultValue: false) }, constraints: table => { table.PrimaryKey("PK_base_jobs", x => x.Id); }); migrationBuilder.CreateIndex( name: "IX_base_employees_UserId", table: "base_employees", column: "UserId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "base_employee_jobs"); migrationBuilder.DropTable( name: "base_employees"); migrationBuilder.DropTable( name: "base_jobs"); migrationBuilder.AlterColumn<string>( name: "FullName", table: "base_orgs", type: "nvarchar(256)", maxLength: 256, nullable: false, oldClrType: typeof(string), oldMaxLength: 128); } } } <file_sep>/MicroServices/Business/Business.Host/Migrations/20200529063305_add_base_dict_AND_base_dict_details.cs using System; using Microsoft.EntityFrameworkCore.Migrations; namespace Business.Migrations { public partial class add_base_dict_AND_base_dict_details : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropPrimaryKey( name: "PK_dictionary", table: "dictionary"); migrationBuilder.DropIndex( name: "IX_dictionary_Code", table: "dictionary"); migrationBuilder.DropColumn( name: "CategoryID", table: "dictionary"); migrationBuilder.DropColumn( name: "Code", table: "dictionary"); migrationBuilder.DropColumn( name: "FullName", table: "dictionary"); migrationBuilder.DropColumn( name: "IsEdit", table: "dictionary"); migrationBuilder.DropColumn( name: "Notes", table: "dictionary"); migrationBuilder.DropColumn( name: "PID", table: "dictionary"); migrationBuilder.DropColumn( name: "SEQ", table: "dictionary"); migrationBuilder.RenameTable( name: "dictionary", newName: "base_dict"); migrationBuilder.AddColumn<string>( name: "Description", table: "base_dict", maxLength: 256, nullable: true); migrationBuilder.AddPrimaryKey( name: "PK_base_dict", table: "base_dict", column: "Id"); migrationBuilder.CreateTable( name: "base_dict_details", columns: table => new { Id = table.Column<Guid>(nullable: false), ExtraProperties = table.Column<string>(nullable: true), ConcurrencyStamp = table.Column<string>(nullable: true), CreationTime = table.Column<DateTime>(nullable: false), CreatorId = table.Column<Guid>(nullable: true), LastModificationTime = table.Column<DateTime>(nullable: true), LastModifierId = table.Column<Guid>(nullable: true), Pid = table.Column<Guid>(nullable: false), Label = table.Column<string>(maxLength: 50, nullable: false), Value = table.Column<string>(maxLength: 256, nullable: false), Sort = table.Column<short>(nullable: false), IsDeleted = table.Column<bool>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_base_dict_details", x => x.Id); }); migrationBuilder.CreateIndex( name: "IX_base_dict_Name", table: "base_dict", column: "Name"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "base_dict_details"); migrationBuilder.DropPrimaryKey( name: "PK_base_dict", table: "base_dict"); migrationBuilder.DropIndex( name: "IX_base_dict_Name", table: "base_dict"); migrationBuilder.DropColumn( name: "Description", table: "base_dict"); migrationBuilder.RenameTable( name: "base_dict", newName: "dictionary"); migrationBuilder.AddColumn<Guid>( name: "CategoryID", table: "dictionary", type: "uniqueidentifier", nullable: true); migrationBuilder.AddColumn<string>( name: "Code", table: "dictionary", type: "nvarchar(32)", maxLength: 32, nullable: true); migrationBuilder.AddColumn<string>( name: "FullName", table: "dictionary", type: "nvarchar(256)", maxLength: 256, nullable: false, defaultValue: ""); migrationBuilder.AddColumn<bool>( name: "IsEdit", table: "dictionary", type: "bit", nullable: false, defaultValue: false); migrationBuilder.AddColumn<string>( name: "Notes", table: "dictionary", type: "nvarchar(200)", maxLength: 200, nullable: true); migrationBuilder.AddColumn<Guid>( name: "PID", table: "dictionary", type: "uniqueidentifier", nullable: true); migrationBuilder.AddColumn<int>( name: "SEQ", table: "dictionary", type: "int", nullable: false, defaultValue: 0); migrationBuilder.AddPrimaryKey( name: "PK_dictionary", table: "dictionary", column: "Id"); migrationBuilder.CreateIndex( name: "IX_dictionary_Code", table: "dictionary", column: "Code"); } } } <file_sep>/MicroServices/Business/Business.Domain/BaseData/Employee.cs using System; using Volo.Abp; using Volo.Abp.Domain.Entities.Auditing; namespace Business.BaseData { public class Employee : AuditedAggregateRoot<Guid>, ISoftDelete { public string Name { get; set; } /// <summary> /// 性别:0:女,1:男,2:其他 /// </summary> public short Gender { get; set; } public string Phone { get; set; } public string Email { get; set; } public bool Enabled { get; set; } public Guid? OrgId { get; set; } public Guid? UserId { get; set; } public bool IsDeleted { get; set; } public Employee(Guid id, string name, short gender, string phone, string email, bool enabled, Guid? orgId, Guid? userId) { Id = id; Name = name; Gender = gender; Phone = phone; Email = email; Enabled = enabled; OrgId = orgId; UserId = userId; } } } <file_sep>/MicroServices/Business/Business.HttpApi/BusinessHttpApiModule.cs using Microsoft.Extensions.DependencyInjection; using Volo.Abp.AspNetCore.Mvc; using Volo.Abp.Modularity; namespace Business { [DependsOn( typeof(BusinessApplicationContractsModule), typeof(AbpAspNetCoreMvcModule) )] public class BusinessHttpApiModule : AbpModule { public override void PreConfigureServices(ServiceConfigurationContext context) { PreConfigure<IMvcBuilder>(mvcBuilder => { mvcBuilder.AddApplicationPartIfNotExists(typeof(BusinessHttpApiModule).Assembly); }); } } } <file_sep>/MicroServices/Business/Business.Application.Contracts/BaseData/EmployeeManagement/IEmployeeAppService.cs using Business.BaseData.EmployeeManagement.Dto; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Volo.Abp.Application.Dtos; using Volo.Abp.Application.Services; namespace Business.BaseData.EmployeeManagement { public interface IEmployeeAppService : IApplicationService { Task<PagedResultDto<EmployeeDto>> GetAll(GetEmployeeInputDto input); Task<EmployeeDto> Get(Guid id); Task<EmployeeDto> Create(CreateOrUpdateEmployeeDto input); Task<EmployeeDto> Update(Guid id, CreateOrUpdateEmployeeDto input); Task Delete(List<Guid> ids); } } <file_sep>/MicroServices/Business/Business.HttpApi/Controllers/TestController.cs using Business.Test; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace Business.Controllers { [Area("business")] [Route("api/business/test")] public class TestController: BusinessController { private readonly ITestAppService _testAppService; public TestController(ITestAppService testAppService) { _testAppService = testAppService; } [HttpGet] public async Task<string> GetAsync() { return await _testAppService.TestApi("1"); } } }
5a13e892521c7c83fafe09c8694cb480b0fcdebe
[ "Markdown", "C#" ]
20
Markdown
qfeng3168/ABP-MicroService
76f8bb583179ecf813e4e50373089fbdf517370f
4d8a75a8bb6e07a86f60f064983a00276a44b138
refs/heads/master
<file_sep>package db import ( "encoding/json" "os" ) func fScanf(filepath string, content interface{}) error { file, err := os.Open(filepath) if err != nil{ return err } defer file.Close() jsonDecoder := json.NewDecoder(file) err = jsonDecoder.Decode(content) if err!=nil && err.Error()!="EOF"{ return err } return nil } func fPrint(filepath string, content interface{}) error { file, err := os.Create(filepath) if err != nil { return err } defer file.Close() jsonEncoder := json.NewEncoder(file) err = jsonEncoder.Encode(content) if err!=nil && err.Error()!="EOF"{ return err } return nil }<file_sep># Web 本项目并未使用任何框架,单纯的用`net/http`制作 ## Layout ``` sh . ├─── handler │ ├─── homeHandler.go │ ├─── signUpHandler.go │ ├─── uploadHandler.go │ ├─── jsHandler.go │ └─── unknowHandler.go ├─── static │ ├─── htm │ │ ├─── home.html │ │ ├─── signUp-get.html │ │ ├─── signUp-post.html │ │ ├─── upload.html │ │ └─── js.html │ ├─── js │ │ └─── jstest.js │ ├─── css │ │ └─── style.css │ └─── temporary │ └─── ... └─── main.go ``` |文件|解释| |-|-| |`handler/xxxHandler.go`|控制不同页面的句柄,即对应页面的控制器| |`static/html/xxx.html`|静态html文件,或者说模板页面| |`static/js/xxx.js`|静态js文件| |`main.go`|服务器入口| ## Usage - `go run main.go` - 浏览器输入`localhost` ## Demo ### 静态文件服务 ![static](assets/static.gif) `http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))` 注册静态文件服务,需要注意的时,该命令需要在其他`http.HandleFunc(...)`之前执行。 目的有两个: - 提供静态文件的直接访问,如上示 demo - 使得<静态html文件>能够访问<静态css>、<静态js>等,否则会出现错误 另外还有两个需要注意的地方 - 访问路径文件夹不要起名`html`,会误以为是`html`文件,导致无法向下访问子目录 - 文件不要起名`index.html`,当GO访问到该文件根目录时,会自动渲染出页面 ### js服务 ![js](assets/js.gif) - `mian.go` ```go http.HandleFunc("/js", handler.JsHandler) ``` - `jsHandler.go` ```go func JsHandler(w http.ResponseWriter, r *http.Request){ fmt.Println("handler:", "js", "method:", r.Method) if r.Method == "GET" { t, _ := template.ParseFiles("static/htm/js.html") t.Execute(w, nil) } else { fmt.Fprintln(w, "message from go server"); } } ``` - `js.html` ```html <html> <head> <meta charset="UTF-8"> <title>Js</title> <script src="http://code.jquery.com/jquery-latest.js"></script> <script src="/static/js/jstest.js"></script> </head> <body> <button><a href="/">Home</a></button> <p id="js_test">js_test: </p> <button>TAT</button> </body> </html> ``` - `jstest.js` ```js $(document).ready(function () { $.ajax({ url: "/js", type: "post" }).then(function(data) { console.log(data) $("#js_test").append(data); }); $("button").click(function(){ $("#js_test").append(" | "); $.ajax({ url: "/js", type: "post" }).then(function(data) { console.log(data) $("#js_test").append(data); }); }); }); ``` ### 上传文件服务 ![upload](assets/upload.gif) - `mian.go` ```go http.HandleFunc("/upload", handler.UploadHandler) ``` - `uploadHandler.go` ```go func UploadHandler(w http.ResponseWriter, r *http.Request){ fmt.Println("handler:", "upload", "method:", r.Method) if r.Method == "GET" { ... t, _ := template.ParseFiles("static/htm/upload.html") t.Execute(w, token) } else { r.ParseMultipartForm(32 << 20) srcFile, handler, err := r.FormFile("file") if err != nil { fmt.Println(err) return } defer srcFile.Close() fmt.Fprintf(w, "%v", handler.Header) destFile, err := os.OpenFile("static/temporary/" + handler.Filename, os.O_WRONLY|os.O_CREATE, 0666) if err != nil { fmt.Println(err) return } defer destFile.Close() io.Copy(destFile, srcFile) } } ``` 简单来说,就是打开两个文件,把`srcFile`的数据填入`destFile` - `upload.html` ```html <html> <head> <meta charset="UTF-8"> <title>upload</title> </head> <body> <button><a href="/">Home</a></button> <form enctype="multipart/form-data" action="/upload" method="post"> <input type="file" name="file" /> <input type="hidden" name="token" value="{{.}}" /> <input type="submit" value="upload" /> </form> </body> </html> ``` ### 表单的输入输出 ![table](assets/table.gif) - `main.go` ```go http.HandleFunc("/signUp", handler.SignUpHandler) ``` - `signUpHandler.go` ```go type Info struct { Username string Password string Email string Mobile string } func SignUpHandler(w http.ResponseWriter, r *http.Request) { fmt.Println("handler:" , "signup", "method:", r.Method) if r.Method == "GET" { ... t, _ := template.ParseFiles("static/htm/signUp-get.html") t.Execute(w, token) } else { r.ParseForm() info := Info{ Username: r.FormValue("username"), Password: r.FormValue("<PASSWORD>"), Email: r.FormValue("email"), Mobile: r.FormValue("mobile"), } t, _ := template.ParseFiles("static/htm/signUp-post.html") t.Execute(w, info) } } ``` - `signUp-get.html` ```go <html> <head> <title>signUp-get</title> <link rel="stylesheet" href="static/css/style.css" type="text/css" > </head> <body> <button><a href="/">Home</a></button> <form method="post"> <label>username:</label><input type="text" name="username"><br> <label>password:</label><input type="<PASSWORD>" name="password"><br> <label>email:</label><input type="text" name="email"><br> <label>mobile:</label><input type="text" name="mobile"><br> <input type="hidden" name="token" value="{{.}}"> <input type="submit" value="signUp"> </form> </body> </html> ``` - `signUp-post.html` ```go <html> <head> <meta charset="UTF-8"> <title>signUp-post</title> </head> <body> <button><a href="/">Home</a></button> <table border="1"> <tr> <td>username</td> <td>{{.Username}}</td> </tr> <tr> <td>password</td> <td>{{.Password}}</td> </tr> <tr> <td>email</td> <td>{{.Email}}</td> </tr> <tr> <td>mobile</td> <td>{{.Mobile}}</td> </tr> </table> </body> </html> ``` ### 对`/unknown`给出开发中的提示,返回码`5xx` ![unknow](assets/unknown.gif) - `mian.go` ```go http.HandleFunc("/unknow", handler.UnknowHandler) ``` - `unknowHandler.go` ```go func UnknowHandler(w http.ResponseWriter, r *http.Request){ w.WriteHeader(500) w.Write([]byte("Under development")) } ``` ### Curl ![curl](assets/curl.gif) [官网](https://curl.haxx.se/) ### AB ![ab](assets/ab.gif) [ab说明](http://httpd.apache.org/docs/current/programs/ab.html)<file_sep>package db import "com/api/model" // Add item func Add(dbPath string, user model.User) { var users []model.User fScanf(dbPath, &users) users = append(users, user) fPrint(dbPath, users) } // Del item func Del(dbPath string, user model.User){ var users []model.User fScanf(dbPath, &users) for i:=len(users)-1; i>=0; i-- { if users[i].Username == user.Username { users = append(users[:i], users[i+1:]...) } } fPrint(dbPath, users) } // Upd item func Upd(dbPath string, user model.User){ var users []model.User fScanf(dbPath, &users) for i:=len(users)-1; i>=0; i-- { if users[i].Username == user.Username { if len(user.Password)>0 { users[i].Password = <PASSWORD> } if len(user.Description)>0 { users[i].Description = user.Description } } } fPrint(dbPath, users) } // Get item func Get(dbPath string, users * []model.User){ fScanf(dbPath, &users) }<file_sep>package router import ( "net/http" "github.com/gin-gonic/gin" "log" "fmt" "os" "io" ) func init(){ apiFile := api.Group("/file") { apiFile.POST("/", uploadFile) } } func uploadFile(c *gin.Context){ file, header, err := c.Request.FormFile("upload") if err != nil { c.String(http.StatusBadRequest, "Bad request") return } filename := header.Filename fmt.Println(file, err, filename) out, err := os.Create("static/"+filename) if err != nil { log.Fatal(err) } defer out.Close() _, err = io.Copy(out, file) if err != nil { log.Fatal(err) } c.String(http.StatusCreated, "upload successfully\n") }<file_sep>package router import ( "github.com/gin-gonic/gin" "net/http" ) func init(){ api.GET("/", Index); } // Index page func Index(c *gin.Context){ c.IndentedJSON(http.StatusOK, gin.H{ "createUser": "POST: /api/user/", "getAllUsers": "GET: /api/user/", "getUser": "GET: /api/user/:username", "updateUser": "PUT: /api/user/:username", "deleteUser": "DELETE: /api/user/:username", "uploadFile": "POST: /api/file/", }) }<file_sep>package handler import ( "net/http" "html/template" "time" "crypto/md5" "io" "fmt" "strconv" ) // SignUpHandler is the handler of the page of signup func SignUpHandler(w http.ResponseWriter, r *http.Request) { fmt.Println("handler:" , "signup", "method:", r.Method) if r.Method == "GET" { crutime := time.Now().Unix() h := md5.New() io.WriteString(h, strconv.FormatInt(crutime, 10)) token := fmt.Sprintf("%x", h.Sum(nil)) t, _ := template.ParseFiles("static/htm/signUp-get.html") t.Execute(w, token) } else { r.ParseForm() type Info struct { Username string Password string Email string Mobile string } info := Info{ Username: r.FormValue("username"), Password: r.FormValue("<PASSWORD>"), Email: r.FormValue("email"), Mobile: r.FormValue("mobile"), } t, _ := template.ParseFiles("static/htm/signUp-post.html") t.Execute(w, info) } }<file_sep>package router import ( "net/http" "github.com/gin-gonic/gin" "com/api/model" "com/api/db" ) const dbUser string = "data/user.json" func init(){ apiUser := api.Group("/user") { apiUser.POST("/", createUser) apiUser.GET("/", getAllUsers) apiUser.GET("/:username", getUser) apiUser.PUT("/:username", updateUser) apiUser.DELETE("/:username", deleteUser) } } func createUser(c *gin.Context){ username := c.PostForm("username") password := c.PostForm("password") description := c.PostForm("description") user := model.User{Username:username, Password:<PASSWORD>, Description:description} if len(username)==0 || len(password)==0 { c.IndentedJSON(http.StatusBadRequest, gin.H{ "status": http.StatusBadRequest, "message": "params fault!(username or password)", }) return } db.Add(dbUser, user) c.IndentedJSON(http.StatusCreated, gin.H{ "status": http.StatusCreated, "message": "User item created successfully!", "data": user, }) } func getAllUsers(c *gin.Context){ var users []model.User db.Get(dbUser, &users) if len(users) == 0 { c.IndentedJSON(http.StatusNotFound, gin.H{ "status": http.StatusNotFound, "message": "No user found!", }) } c.IndentedJSON(http.StatusOK, gin.H{ "status": http.StatusOK, "data":users, }) } func getUser(c *gin.Context){ username := c.Param("username") var users []model.User db.Get(dbUser, &users) for i:=len(users)-1; i>=0; i-- { if users[i].Username != username { users = append(users[:i], users[i+1:]...) } } if len(users) == 0 { c.IndentedJSON(http.StatusNotFound, gin.H{ "status": http.StatusNotFound, "message": "No user found!", }) return } c.IndentedJSON(http.StatusOK, gin.H{ "status": http.StatusOK, "data":users, }) } func updateUser(c *gin.Context){ var user model.User user.Username = c.Param("username") user.Password = c.PostForm("password") user.Description = c.PostForm("description") if len(user.Password)==0 && len(user.Description)==0 { c.IndentedJSON(http.StatusBadRequest, gin.H{ "status": http.StatusBadRequest, "message": "param fault!(password or description)", }) return } db.Upd(dbUser, user) c.IndentedJSON(http.StatusOK, gin.H{ "status": http.StatusOK, "data": user, }) } func deleteUser(c *gin.Context){ var user model.User user.Username = c.Param("username") db.Del(dbUser, user) c.IndentedJSON(http.StatusOK, gin.H{ "status": http.StatusOK, "data": user, }) }<file_sep>package swapi import ( "com/week12/EasyBlog/backend/database" "com/week12/EasyBlog/backend/model" "encoding/json" "github.com/gin-gonic/gin" "net/http" "fmt" ) var root_url = "http://127.0.0.1:8090/api/" func Run(port string){ r := gin.Default() r.Use(Cors()) api := r.Group("/api") { api.GET("/", listAll) apiPeople := api.Group("/people") { apiPeople.GET("/", listPeoplePage) apiPeople.GET("/:id", listPeople) } api_film := api.Group("/films") { api_film.GET("/", listFilmPage) api_film.GET("/:id", listFilm) } api_planet := api.Group("/planets") { api_planet.GET("/", listplanetPage) api_planet.GET("/:id", listplanet) } api_specie := api.Group("/species") { api_specie.GET("/", listspeciePage) api_specie.GET("/:id", listspecie) } api_starship := api.Group("/starships") { api_starship.GET("/", liststarshipPage) api_starship.GET("/:id", liststarship) } api_vehicle := api.Group("/vehicles") { api_vehicle.GET("/", listvehiclePage) api_vehicle.GET("/:id", listvehicle) } } r.Run(port) } func listAll(c *gin.Context) { if v := database.Get("/", root_url); v != "" { var res model.Base json.Unmarshal([]byte(v), &res) c.IndentedJSON(http.StatusOK, res) } else { c.String(http.StatusNotFound, "Not Found") } } func Cors() gin.HandlerFunc { return func(c *gin.Context) { method := c.Request.Method fmt.Println(">>", method) c.Header("Content-Type", "application/json; charset=UTF-8") c.Header("Access-Control-Allow-Origin", "*") c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token") c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, PATCH, DELETE") c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type") c.Header("Access-Control-Allow-Credentials", "true") // 放行所有OPTIONS方法,因为有的模板是要请求两次的 if method == "OPTIONS" { c.AbortWithStatus(http.StatusNoContent) } // 处理请求 c.Next() } }<file_sep>package cmd import ( "agenda/entity" "fmt" "log" "github.com/spf13/cobra" ) var delParticipantCmd = &cobra.Command{ Use: "delParticipant", Short: "delParticipant", Long: "delParticipant Command", Run: func(cmd *cobra.Command, args []string) { title, _ := cmd.Flags().GetString("title") if err := entity.DelParticipant(title, args); err != nil { fmt.Println(err) log.Println(err) } else { fmt.Println("Success") log.Println("Success") } }, } func init() { rootCmd.AddCommand(delParticipantCmd) delParticipantCmd.Flags().StringP("title","t","","the meeting need to add participant") } <file_sep>package swapi import ( "com/week12/EasyBlog/backend/database" "com/week12/EasyBlog/backend/model" "encoding/json" "github.com/gin-gonic/gin" "net/http" ) var planetBucket = "planet" var planetUrl = root_url + "planets/" func listplanetPage(c *gin.Context) { page := c.DefaultQuery("page", "1") if v := database.Get(planetBucket, planetUrl + "?page=" + page); v != "" { var res model.PlanetPage json.Unmarshal([]byte(v), &res) c.IndentedJSON(http.StatusOK, res) } else { c.String(http.StatusNotFound, "Not found") } } func listplanet(c *gin.Context) { id := c.Param("id") if v := database.Get(planetBucket, planetUrl + id + "/"); v != "" { var res model.Planet json.Unmarshal([]byte(v), &res) c.IndentedJSON(http.StatusOK, res) } else { c.String(http.StatusNotFound, "Not found") } }<file_sep>package cmd import ( "agenda/entity" "fmt" "github.com/spf13/cobra" "log" ) var signUpCmd = &cobra.Command{ Use: "signUp", Short: "signUp", Long: "signUp Command", Run: func(cmd *cobra.Command, args []string) { username, _ := cmd.Flags().GetString("username") password, _ := cmd.Flags().GetString("password") email, _ := cmd.Flags().GetString("email") phone, _ := cmd.Flags().GetString("phone") if err := entity.SignUp(username, password, email, phone); err != nil { fmt.Println(err) log.Println(err) } else { fmt.Println("Success") log.Println("Success") } }, } func init() { rootCmd.AddCommand(signUpCmd) signUpCmd.Flags().StringP("username", "u", "", "username") signUpCmd.Flags().StringP("password", "p", "", "<PASSWORD>") signUpCmd.Flags().StringP("email", "e", "", "email") signUpCmd.Flags().StringP("phone", "P", "", "phone") } <file_sep>package cmd import ( "agenda/entity" "fmt" "github.com/spf13/cobra" "log" ) var clearMeetingCmd = &cobra.Command{ Use: "clearMeeting", Short: "clearMeeting", Long: "clearMeeting Command", Run: func(cmd *cobra.Command, args []string) { if err := entity.ClearMeeting(); err != nil { fmt.Println(err) log.Println(err) } else { fmt.Println("Success") log.Println("Success") } }, } func init() { rootCmd.AddCommand(clearMeetingCmd) } <file_sep># CLI命令行使用程序开发基础 ## 流程图 ![](images/process.png) ## 程序框架 ```go func main() { var selpg = &SelpgArgs{} getArgs(selpg) checkArgs(selpg) checkFileIn(selpg) checkFileOut(selpg) work(selpg) } ``` ### 定义错误码 ```GO var ERROR_NO_PAGE_ST = errors.New("[Error] not found [-sNumber]") var ERROR_NO_PAGE_ED = errors.New("[Error] not found [-eNumber]") var ERROR_NO_FILE = errors.New("[Error] not found file") var ERROR_INVALID_PAGE_ST = errors.New("[Error] invalid [-sNumber]") var ERROR_INVALID_PAGE_ED = errors.New("[Error] invalid [-eNumber]") var ERROR_INVALID_PAGE_TY = errors.New("[Error] [-lNumber] and [-f] can't be set together") var ERROR_INVALID_PAGE_LE = errors.New("[Error] invalid [-lNumber]") var ERROR_INVALID_ACCESS_FILE = errors.New("[Error] unable to access the file") ``` ### 定义结构体 ```GO type SelpgArgs struct { FileIn string // 输入文件路径 FileOut string // 输出文件路径 PageSt int // 开始页数 PageEd int // 结束页数 PageLe int // 每页行数 PageTy bool // 打印模式,True时忽略每页行数限制 } ``` ### 获取命令行参数 查阅资料,命令行参数格式 `[command] [-arg1=x1 -arg2=x2 ...] [other args]` ```go func getArgs(args *SelpgArgs) { pflag.IntVarP(&(args.PageSt), "startPage", "s", -1, "start page") pflag.IntVarP(&(args.PageEd), "endPage", "e", -1, "end page") pflag.IntVarP(&(args.PageLe), "lenPage", "l", 72, "len of page") pflag.BoolVarP(&(args.PageTy), "typePage", "f", false, "ACSII") pflag.StringVarP(&(args.FileOut), "destionation", "d", "", "destionation") pflag.Parse() ar := pflag.Args() if len(ar) > 0 { args.FileIn = string(ar[0]) } else { args.FileIn = "" } } ``` ### 检查参数 ```GO func checkArgs(args *SelpgArgs) { if args.PageSt == -1 { panic(ERROR_NO_PAGE_ST) } if args.PageEd == -1 { panic(ERROR_NO_PAGE_ED) } if args.PageSt <= 0 { panic(ERROR_INVALID_PAGE_ST) } if args.PageEd <= 0 || args.PageEd < args.PageSt { panic(ERROR_INVALID_PAGE_ED) } if args.PageTy == true && args.PageLe != 72 { panic(ERROR_INVALID_PAGE_TY) } if args.PageLe <= 0 { panic(ERROR_INVALID_PAGE_LE) } } ``` ### 检查输入文件 ```GO func checkFileIn(args *SelpgArgs) { _, err := os.Stat(args.FileIn) if os.IsNotExist(err) { panic(ERROR_NO_FILE) } _, err = os.Open(args.FileIn) if err != nil { panic(ERROR_INVALID_ACCESS_FILE) } } ``` ### 检查输出文件 ```GO func checkFileOut(args *SelpgArgs) { if args.FileOut != "" { _, err := os.Stat(args.FileOut) if os.IsNotExist(err) { _, err = os.Create(args.FileOut) if err != nil { panic(ERROR_INVALID_ACCESS_FILE) } } } } ``` ### 输出截取的片段 ```GO func work(args *SelpgArgs) { lineCnt, pageCnt := 0, 1 fileIn, _ := os.Open(args.FileIn) fin := bufio.NewReader(fileIn) var fileOut *os.File var fout *bufio.Writer if args.FileOut != "" { fileOut, _ = os.OpenFile(args.FileOut, os.O_WRONLY, 0666) fout = bufio.NewWriter(fileOut) } for { var line string if args.PageTy { line, _ = fin.ReadString('\f') pageCnt++ } else { line, _ = fin.ReadString('\n') lineCnt++ if lineCnt > args.PageLe { pageCnt++ lineCnt = 1 } } if pageCnt >= args.PageSt && pageCnt <= args.PageEd { if args.FileOut == "" { fmt.Print(line) } else { fout.WriteString(line) fout.Flush() } } if pageCnt > args.PageEd || fin.Buffered() == 0 { break } } } ``` ## Demo - `$ selpg -s1 -e2 [-lNumber \ -f] selpg.go` - `$ selpg -s1 -e2 [-lNumber \ -f] -dresult.txt selpg.go` - `$ selpg -s1 -e2 [-lNumber \ -f] selpg.go > result.txt` <file_sep>package router import "github.com/gin-gonic/gin" var router = gin.Default() var api = router.Group("api") // Execute router func Execute(){ router.Run() }<file_sep>package swapi import ( "com/week12/EasyBlog/backend/database" "com/week12/EasyBlog/backend/model" "encoding/json" "github.com/gin-gonic/gin" "net/http" ) var specieBucket = "specie" var specieUrl = root_url + "species/" func listspeciePage(c *gin.Context) { page := c.DefaultQuery("page", "1") if v := database.Get(specieBucket, specieUrl + "?page=" + page); v != "" { var res model.SpeciePage json.Unmarshal([]byte(v), &res) c.IndentedJSON(http.StatusOK, res) } else { c.String(http.StatusNotFound, "Not found") } } func listspecie(c *gin.Context) { id := c.Param("id") if v := database.Get(specieBucket, specieUrl + id + "/"); v != "" { var res model.Specie json.Unmarshal([]byte(v), &res) c.IndentedJSON(http.StatusOK, res) } else { c.String(http.StatusNotFound, "Not found") } }<file_sep>package model type SpeciePage struct { Count int `json:"count"` Next string `json:"next"` Previous string `json:"previous"` Results []Specie `json:"results"` } type Specie struct { Name string `json:"name"` Classification string `json:"classification"` Designation string `json:"designation"` AverageHeight string `json:"average_height"` SkinColors string `json:"skin_colors"` HairColors string `json:"hair_colors"` EyeColors string `json:"eye_colors"` AverageLifespan string `json:"average_lifespan"` Homeworld string `json:"homeworld"` Language string `json:"language"` People []string `json:"people"` Films []string `json:"films"` Created string `json:"created"` Edited string `json:"edited"` Url string `json:"url"` } <file_sep># Vmware+Centos7搭建私有云桌面 ## 1. 下载安装 Vmware ### 下载 Vmware Vmware 官网:https://www.vmware.com/ 这里要下载 [Vmware Workstation Pro 版](https://my.vmware.com/en/web/vmware/info/slug/desktop_end_user_computing/vmware_workstation_pro/15_0) 简单概括一下Player版和Pro版,如果需要配置网卡等涉及网络的操作,选Pro版,否则选Player版即可 ### 安装 Vmware - 直接运行`.exe`文件,根据提示进行安装即可。 - 密钥可以直接从网上搜索得到,这里不提供 ## 2. 配置 Centos 虚拟机 ### 下载 Centos 镜像 Centos 官网:https://www.centos.org/ 下载 minial 版就可以了 ### 添加 Centos 镜像 - 菜单栏`File` => `New Virtual Machine...` - 选择`Typical(recommended)`和`Custom(advanced)`都可以,不影响后续 + 注意一下CPU数量、内存大小、硬盘大小、安装位置即可 + 如果不懂的话,全部默认就可以了 ### 添加第二块网卡 添加镜像之后不着急启动。 - `Edit virtual machine settings` => `Add...` => `Network Adapter` => `Finish` - 把第二块网卡的连接方式设置为`Host-only` => `OK` ![](images/网卡.png) ### 安装 Centos 操作系统 - 启动虚拟机`Power on this virtual machine` - 默认安装即可。当然也可以自行设置时区、磁盘分区等等 - 设置root密码和新建用户 - 等待安装完成即可 ### 配置 Centos 操作系统 #### 配置网络 默认安装的 Centos 操作系统是没有连接网络的,这里首先需要连上网络。 `$ <command>`说明在命令行终端下执行 <command> 命令 - `$ nmcli d`查看网卡,应该可以看到两个类似的网卡,显示未连接 + `ens33` 是 ‘Nat模式’ 连接,用于联网 + `ens34` 是 ‘Host-only模式’ 连接,用于云桌面的使用 ![](images/nmcli-d.png) - `$ nmtui`打开网络管理员窗口 ![](images/network-manager.png) - `Edit a connection` - `ens33` => `IPv4 CONFIGURATION` => `Automatic` => `OK` - `ens34` => `IPv4 CONFIGURATION` => `Manual` - 配置`Addresses`、`Gateway`、`DNS servers` => `OK` - 可以在 Vmware 的菜单栏`Edit` => `Virtual Network Editor...`中查看相关信息 - 当然也可以自己设置 ![](images/vm-network.png) ![](images/ens34.png) - 回到网络管理员窗口,`Activate a connection` - 在`ens33`和`ens34`处回车激活网卡,激活的网卡左侧有星星 ![](images/network-active.png) - `Back` => `OK`退出 - `$ systemctl restart network`重新启动网络服务 - `$ ping www.baidu.com`查看是否成功联网 ![ping](ping.png) --- 如果重启后不能联网 - `$ cd /etc/sysconfig/network-scripts` - `$ ls`,应该能看见`ifcfg-ens33`和`ifcfg-ens34`两个文件 - `$ vi ifcfg-ens33` + 将`BOOTPROTO=none`改为`BOOTPROTO=dhcp` + 将`ONBOOT=no`改为`ONBOOT=yes` - `$ vi ifcfg-ens34` + 将`BOOTPROTO=none`改为`BOOTPROTO=static` + 将`ONBOOT=no`改为`ONBOOT=yes` #### 配置软件 - 升级内核 ```sh $ yum update ``` - 安装 wget ```sh $ yum install wget ``` - 安装网络工具包(ifconfig...) ```sh $ yum install net-tools ``` - 此时可以使用ifconfig查看网卡的详细信息 + 使用虚拟机 ping `ens33`地址、`ens34`地址、`主机`地址 + 使用主机 ping `ens33`地址、`ens34`地址、`主机`地址 + 应该都可以 ping 通 - 此时主机可以使用 git ssh 远程连接虚拟机 + 主机打开 `git bash` + `$ ssh <username>@ens34地址` ![](images/ssh.png) ### 克隆 Centos 虚拟机 - 退出虚拟机,在标签栏右键 - `Manage` => `clone` - 按提示操作即可 - 克隆的虚拟机的`ens34网络`需要更改,一般从xxx.xxx.xxx.127向小的方向顺延 + 利用`nmtui`命令操作,与上面配置网络部分相似 ## 3. 远程访问 虚拟机执行命令 - 安装桌面 ```sh $ yum -y groupinstall 'GNOME Desktop' ``` - 设置默认启动方式 + 查看默认启动方式 ```sh $ systemctl get-default ``` + 默认启动方式为图形界面 ```sh $ systemctl set-default graphical.target ``` + 默认启动方式为命令行界面 ```sh $ systemctl set-default multi-user.target ``` - 安装 epel(免费开源发行软件包版本库) ```sh $ yum install epel-release ``` - 安装 xrdp(远程连接证书) ```sh $ yum install xrdp ``` - 安装 tigervnc-server( xrdp 会自动启动 vnc,所以必须安装) ```sh $ yum install tigervnc-server ``` - 关闭防火墙 ```sh $ systemctl stop firewalld $ systemctl disable firewalld ``` - 启动 xrdp ```sh $ systemctl start xrdp ``` - 主机远程连接 + 启动 Windows 的 RDC(Remote Desktop Connection) * Win+R 后输入 mstsc 回车 + 输入虚拟机ip(ens34网络) ![](images/remote-0.png) + 输入用户名密码 ![](images/remote-1.png) + 现在就可以远程控制了 ![](images/remote-2.png) ## 问题解决 ### Q1. yum 命令出现`Loaded plugins: fastestmirror...` fastestmirror是yum的一个加速插件,这里是插件提示信息是插件不能用了。 - 修改插件的配置文件 ```sh $ vi /etc/yum/pluginconf.d/fastestmirror.conf ``` 将`enabled=1`改为`enabled=0` - 修改 yum 的配置文件 ```sh $ vi /etc/yum.conf ``` 将`plugins=1`改为`plugins=0` - 重启 ```sh $ reboot ``` ### Q2. 报错`Could not retrieve mirrorlist http:// ...` 无法联网 - 参见以上配置网络部分 ### Q3. 无法下载xrdp,出现`--skip-broken` ```sh $ yum install xrdp --enablerepo=cr ``` ### Q4. 每次重启后 xrdp 都要重新启动才能被远程访问 ```sh update-rc.d xrdp enable ``` ## 参考资料 - [Workstation Player和Workstation Pro介绍,两者的区别](https://ywnz.com/linuxxw/3324.html) - [VMWARE+CENTOS7搭建私有云桌面服务](http://www.freesion.com/article/343056685/) - [xrdp设置开机自启动](https://blog.csdn.net/somiceast/article/details/84942561) - [CentOS报错:Could not retrieve mirrorlist ...](https://www.cnblogs.com/xixihuang/p/5404517.html)<file_sep>package database import ( "fmt" "github.com/boltdb/bolt" "log" "os" "strings" "time" ) func init() { if _, err := os.Stat("my.db"); err == nil { log.Println("[init] database has existed") return } db, err := bolt.Open("my.db", 0600, &bolt.Options{Timeout: 1 * time.Second}); if err != nil { log.Fatal(err) } if err := db.Batch(func(tx *bolt.Tx) error { tx.CreateBucket([] byte("/")) tx.CreateBucket([] byte("people")) tx.CreateBucket([] byte("planet")) tx.CreateBucket([] byte("film")) tx.CreateBucket([] byte("specie")) tx.CreateBucket([] byte("vehicle")) tx.CreateBucket([] byte("starship")) return nil }); err != nil { log.Fatal(err) } db.Close() CrawlData() } func Put(bucket, key, value string) { db, err := bolt.Open("my.db", 0600, &bolt.Options{Timeout: 1 * time.Second}); if err != nil { log.Fatal(err) } defer db.Close() db.Batch(func(tx *bolt.Tx) error { if b := tx.Bucket([]byte(bucket)); b != nil { k := strings.ReplaceAll(key, "192.168.43.133:8000", "127.0.0.1:8090") v := strings.ReplaceAll(value, "192.168.43.133:8000", "127.0.0.1:8090") fmt.Println("bucket=" + bucket, "\nkey=" + k, "\nvalue=" + v, "\n") b.Put([]byte(k), []byte(v)) } else { log.Println("[Put] bucket <" + bucket + "> not found") } return nil }); } func Get(bucket, key string) string { db, err := bolt.Open("my.db", 0600, &bolt.Options{Timeout: 1 * time.Second}); if err != nil { log.Fatal(err) } defer db.Close() var value []byte db.View(func(tx *bolt.Tx) error { if b := tx.Bucket([]byte(bucket)); b != nil { value = b.Get([]byte(key)) } else { log.Println("[Get] bucket <" + bucket + "> not found") } return nil }); fmt.Println("bucket=" + bucket, "\nkey=" + key, "\n") return string(value) }<file_sep>package entity import ( "agenda/module/db" "math/rand" "regexp" "time" ) type Meeting struct { MeetingId int MeetingTitle string MeetingStDate string MeetingEdDate string AdminiatorId int ParticipantIds []int Flag bool } const meetingDataPath string = "data/meeting.json" var meetings []Meeting func init() { if err := db.FScanf(meetingDataPath, &meetings); err != nil { panic(err) } rand.Seed(time.Now().UnixNano()) } func createMeeting(title, stDate, edDate string, args []string) error { m := Meeting{ MeetingId: generateMeetingId(), MeetingTitle: title, MeetingStDate: stDate, MeetingEdDate: edDate, AdminiatorId: curUser.UserId, ParticipantIds: []int{}, } curUser.MeetingIds = append(curUser.MeetingIds, m.MeetingId) updateUser(curUser) for _, uname := range args { u := GetUserByName(uname) u.MeetingIds = append(u.MeetingIds, m.MeetingId) updateUser(u) } updateMeeting(m) return nil } func leaveMeeting(meeting Meeting) error { if curUser.UserId == meeting.AdminiatorId { _ = cancelMeeting(meeting) return nil } for i, mid := range curUser.MeetingIds { if mid == meeting.MeetingId { curUser.MeetingIds = append(curUser.MeetingIds[:i], curUser.MeetingIds[i+1:]...) updateUser(curUser) break } } for i, uid := range meeting.ParticipantIds { if uid == curUser.UserId { meeting.ParticipantIds = append(meeting.ParticipantIds[:i], meeting.ParticipantIds[i+1:]...) updateMeeting(meeting) break } } return nil } func cancelMeeting(meeting Meeting) error { for i, mid := range curUser.MeetingIds { if mid == meeting.MeetingId { curUser.MeetingIds = append(curUser.MeetingIds[:i], curUser.MeetingIds[i+1:]...) updateUser(curUser) break } } _ = delParticipant(meeting, meeting.ParticipantIds) return nil } func clearMeeting() error { for i, mid := range curUser.MeetingIds { m := GetMeetingById(mid) if m.AdminiatorId == curUser.UserId { _ = cancelMeeting(m) curUser.MeetingIds = append(curUser.MeetingIds[:i], curUser.MeetingIds[i+1:]...) } } return nil } func addParticipant(meeting Meeting, uids []int) error { for _, uid := range uids { user := GetUserById(uid) flag := false for _, mid := range user.MeetingIds { if mid == meeting.MeetingId { user.MeetingIds = append(user.MeetingIds, meeting.MeetingId) updateUser(user) flag = true break } } if flag { meeting.ParticipantIds = append(meeting.ParticipantIds, uid) } } updateMeeting(meeting) return nil } func delParticipant(meeting Meeting, uids []int) error { for _, uid := range uids { user := GetUserById(uid) flag := false for i, mid := range user.MeetingIds { if mid == meeting.MeetingId { user.MeetingIds = append(user.MeetingIds[:i], user.MeetingIds[i+1:]...) updateUser(user) flag = true break } } if flag { for i, uid := range meeting.ParticipantIds { if uid == user.UserId { meeting.ParticipantIds = append(meeting.ParticipantIds[:i], meeting.ParticipantIds[i+1:]...) break } } } } updateMeeting(meeting) return nil } func queryMeeting(stDate, edDate string) ([]Meeting, error) { var mm []Meeting for _, mid := range curUser.MeetingIds { m := GetMeetingById(mid) if !(edDate<m.MeetingStDate || stDate>m.MeetingEdDate) { mm = append(mm, m) } } return mm, nil } func getMeetings() []Meeting { return meetings } func GetMeetingById(id int) Meeting { for _, meeting := range meetings { if meeting.MeetingId == id { return meeting } } return Meeting{} } func GetMeetingByTitle(title string) Meeting { for _, meeting := range meetings { if meeting.MeetingTitle == title { return meeting } } return Meeting{} } func isValidDate(date string) bool { pattern := "^([1-9]\\d{3})-(0[1-9]|1[0-2])-(0[0-1]|[1-2]\\d|3[0-1])_([0-1]\\d|2[0-3]):([0-5]\\d)$" b, _ := regexp.MatchString(pattern, date) return b } func generateMeetingId() int { mmap := make(map[int]bool) for _, m := range meetings { mmap[m.MeetingId] = true } mid := rand.Intn(99999999) for _, exist := mmap[mid]; exist; { mid = rand.Intn(99999999) } return mid } func updateMeeting(meeting Meeting) { if len(meeting.ParticipantIds) == 0 { meeting.Flag = false } for i, _meeting := range meetings { if _meeting.MeetingId == meeting.MeetingId { if meeting.Flag == true { meetings[i] = meeting } else { meetings = append(meetings[:i], meetings[i+1:]...) } break } } _ = db.FPrint(meetingDataPath, meetings) } <file_sep>package main import ( "bufio" "encoding/json" "errors" "fmt" "os" "github.com/spf13/pflag" ) var ERROR_NO_PAGE_ST = errors.New("[Error] not found [-sNumber]") var ERROR_NO_PAGE_ED = errors.New("[Error] not found [-eNumber]") var ERROR_NO_FILE = errors.New("[Error] not found file") var ERROR_INVALID_PAGE_ST = errors.New("[Error] invalid [-sNumber]") var ERROR_INVALID_PAGE_ED = errors.New("[Error] invalid [-eNumber]") var ERROR_INVALID_PAGE_TY = errors.New("[Error] [-lNumber] and [-f] can't be set together") var ERROR_INVALID_PAGE_LE = errors.New("[Error] invalid [-lNumber]") var ERROR_INVALID_ACCESS_FILE = errors.New("[Error] unable to access the file") type SelpgArgs struct { FileIn string FileOut string PageSt int PageEd int PageLe int PageTy bool } func (args *SelpgArgs) String() string { bytes, _ := json.Marshal(*args) return string(bytes) } func getArgs(args *SelpgArgs) { pflag.IntVarP(&(args.PageSt), "startPage", "s", -1, "start page") pflag.IntVarP(&(args.PageEd), "endPage", "e", -1, "end page") pflag.IntVarP(&(args.PageLe), "lenPage", "l", 72, "len of page") pflag.BoolVarP(&(args.PageTy), "typePage", "f", false, "ACSII") pflag.StringVarP(&(args.FileOut), "destionation", "d", "", "destionation") pflag.Parse() ar := pflag.Args() if len(ar) > 0 { args.FileIn = string(ar[0]) } else { args.FileIn = "" } } func checkArgs(args *SelpgArgs) { if args.PageSt == -1 { panic(ERROR_NO_PAGE_ST) } if args.PageEd == -1 { panic(ERROR_NO_PAGE_ED) } if args.PageSt <= 0 { panic(ERROR_INVALID_PAGE_ST) } if args.PageEd <= 0 || args.PageEd < args.PageSt { panic(ERROR_INVALID_PAGE_ED) } if args.PageTy == true && args.PageLe != 72 { panic(ERROR_INVALID_PAGE_TY) } if args.PageLe <= 0 { panic(ERROR_INVALID_PAGE_LE) } } func checkFileIn(args *SelpgArgs) { _, err := os.Stat(args.FileIn) if os.IsNotExist(err) { panic(ERROR_NO_FILE) } _, err = os.Open(args.FileIn) if err != nil { panic(ERROR_INVALID_ACCESS_FILE) } } func checkFileOut(args *SelpgArgs) { if args.FileOut != "" { _, err := os.Stat(args.FileOut) if os.IsNotExist(err) { _, err = os.Create(args.FileOut) if err != nil { panic(ERROR_INVALID_ACCESS_FILE) } } } } func work(args *SelpgArgs) { lineCnt, pageCnt := 0, 1 fileIn, _ := os.Open(args.FileIn) fin := bufio.NewReader(fileIn) var fileOut *os.File var fout *bufio.Writer if args.FileOut != "" { fileOut, _ = os.OpenFile(args.FileOut, os.O_WRONLY, 0666) fout = bufio.NewWriter(fileOut) } for { var line string if args.PageTy { line, _ = fin.ReadString('\f') pageCnt++ } else { line, _ = fin.ReadString('\n') lineCnt++ if lineCnt > args.PageLe { pageCnt++ lineCnt = 1 } } if pageCnt >= args.PageSt && pageCnt <= args.PageEd { if args.FileOut == "" { fmt.Print(line) } else { fout.WriteString(line) fout.Flush() } } if pageCnt > args.PageEd || fin.Buffered() == 0 { break } } } func main() { var selpg = &SelpgArgs{} getArgs(selpg) checkArgs(selpg) checkFileIn(selpg) checkFileOut(selpg) work(selpg) } <file_sep>package swapi import ( "com/week12/EasyBlog/backend/database" "com/week12/EasyBlog/backend/model" "encoding/json" "github.com/gin-gonic/gin" "net/http" ) var filmBucket = "film" var filmUrl = root_url + "films/" func listFilmPage(c *gin.Context) { page := c.DefaultQuery("page", "1") if v := database.Get(filmBucket, filmUrl + "?page=" + page); v != "" { var res model.FilmPage json.Unmarshal([]byte(v), &res) c.IndentedJSON(http.StatusOK, res) } else { c.String(http.StatusNotFound, "Not found") } } func listFilm(c *gin.Context) { id := c.Param("id") if v := database.Get(filmBucket, filmUrl + id + "/"); v != "" { var res model.Film json.Unmarshal([]byte(v), &res) c.IndentedJSON(http.StatusOK, res) } else { c.String(http.StatusNotFound, "Not found") } }<file_sep>package db import ( "encoding/json" "os" ) func FScanf(filepath string, inter interface{}) error { file, err := os.OpenFile(filepath, os.O_RDONLY|os.O_CREATE, 0666) if err != nil { return err } defer file.Close() jsonDecoder := json.NewDecoder(file) err = jsonDecoder.Decode(inter) if err != nil && err.Error() != "EOF" { return err } return nil } func FPrint(filepath string, inter interface{}) error { file, err := os.Create(filepath) if err != nil { return err } defer file.Close() jsonEncoder := json.NewEncoder(file) err = jsonEncoder.Encode(inter) if err != nil && err.Error() != "EOF" { return err } return nil } func FClear(filepath string) error { return os.Truncate(filepath, 0) } <file_sep>## Links [课程网站:](https://pmlpml.github.io/ServiceComputingOnCloud/)https://pmlpml.github.io/ServiceComputingOnCloud/ [实例代码:](https://github.com/pmlpml/golang-learning)<file_sep>package handler import ( "net/http" ) // UnknowHandler is the handler of the page of unknow func UnknowHandler(w http.ResponseWriter, r *http.Request){ w.WriteHeader(500) w.Write([]byte("Under development")) }<file_sep>package swapi import ( "com/week12/EasyBlog/backend/database" "com/week12/EasyBlog/backend/model" "encoding/json" "fmt" "github.com/gin-gonic/gin" "net/http" ) var peopleBucket = "people" var peopleUrl = root_url + "people/" func listPeoplePage(c *gin.Context) { page := c.DefaultQuery("page", "1") fmt.Println(page) if v := database.Get(peopleBucket, peopleUrl + "?page=" + page); v != "" { var res model.PeoplePage json.Unmarshal([]byte(v), &res) c.IndentedJSON(http.StatusOK, res) } else { c.String(http.StatusNotFound, "Not found") } } func listPeople(c *gin.Context) { id := c.Param("id") fmt.Println(id) if v := database.Get(peopleBucket, peopleUrl + id + "/"); v != "" { fmt.Println(v) var res model.People json.Unmarshal([]byte(v), &res) c.IndentedJSON(http.StatusOK, res) } else { fmt.Println("GG") c.String(http.StatusNotFound, "Not found") } } <file_sep>package cmd import ( "agenda/entity" "fmt" "log" "github.com/spf13/cobra" ) var signOutCmd = &cobra.Command{ Use: "signOut", Short: "signOut", Long: "signOut Command", Run: func(cmd *cobra.Command, args []string) { if err := entity.SignOut(); err != nil { fmt.Println(err) log.Println(err) } else { fmt.Println("Success") log.Println("Success") } }, } func init() { rootCmd.AddCommand(signOutCmd) } <file_sep>package entity import ( "agenda/module/db" "errors" "math/rand" "time" ) type User struct { UserId int UserName string UserPassword string UserEmail string UserPhone string MeetingIds []int Flag bool } const userDataPath string = "data/user.json" const curUserPath string = "data/curUser.txt" var users []User var curUser User func init() { if err := db.FScanf(userDataPath, &users); err != nil { panic(err) } if err := db.FScanf(curUserPath, &curUser); err != nil { panic(err) } rand.Seed(time.Now().UnixNano()) } func signUp(username, password, email, phone string) error { u := User{ UserId: generateUserId(), UserName: username, UserPassword: <PASSWORD>, UserEmail: email, UserPhone: phone, MeetingIds: []int{}, Flag: true, } updateUser(u) return nil } func signIn(username, password string) error { for _, user := range users { if user.UserName == username { if user.UserPassword == <PASSWORD> { if err := db.FPrint(curUserPath, &user); err != nil { return err } return nil } break } } return errors.New(ERROR_INVALID_USERNAME_PASSWORD) } func signOut() error { return db.FClear(curUserPath) } func cancelSelf() error { for _, mid := range curUser.MeetingIds { _ = leaveMeeting(GetMeetingById(mid)) } curUser.Flag = false; updateUser(curUser) return nil } func getUsers() []User { return users } func GetUserById(id int) User { for _, user := range users { if user.UserId == id { user.UserPassword = "" return user } } return User{} } func GetUserByName(username string) User { for _, user := range users { if user.UserName == username { user.UserPassword = "" return user } } return User{} } func isSignIn() bool { return curUser.UserId > 0 } func generateUserId() int { mmap := make(map[int]bool) for _, u := range users { mmap[u.UserId] = true } uid := rand.Intn(99999999) for _, exist := mmap[uid]; exist; { uid = rand.Intn(99999999) } return uid } func updateUser(user User){ if user.UserId == curUser.UserId { if user.Flag == true { curUser = user _ = db.FPrint(curUserPath, curUser) } else { _ = db.FClear(curUserPath) } } for i, _user := range users { if _user.UserId == user.UserId{ if user.Flag == true { users[i] = user } else { users = append(users[:i], users[i+1:]...) } break } } _ = db.FPrint(userDataPath, users) }<file_sep>package swapi import ( "com/week12/EasyBlog/backend/database" "com/week12/EasyBlog/backend/model" "encoding/json" "github.com/gin-gonic/gin" "net/http" ) var vehicleBucket = "vehicle" var vehicleUrl = root_url + "vehicles/" func listvehiclePage(c *gin.Context) { page := c.DefaultQuery("page", "1") if v := database.Get(vehicleBucket, vehicleUrl + "?page=" + page); v != "" { var res model.VehiclePage json.Unmarshal([]byte(v), &res) c.IndentedJSON(http.StatusOK, res) } else { c.String(http.StatusNotFound, "Not found") } } func listvehicle(c *gin.Context) { id := c.Param("id") if v := database.Get(vehicleBucket, vehicleUrl + id + "/"); v != "" { var res model.Vehicle json.Unmarshal([]byte(v), &res) c.IndentedJSON(http.StatusOK, res) } else { c.String(http.StatusNotFound, "Not found") } }<file_sep>package entity import ( "errors" ) const ( ERROR_NO_TITLE = "[Error] not found [-t=Title]" ERROR_NO_PARTICANTS = "[Error] participant can't be empty" ERROR_NO_USERNAME = "[Error] not found [-n=username]" ERROR_NO_PASSWORD = "[Error] not found [-p=password]" ERROR_NO_EMAIL = "[Error] not found [-e=email]" ERROR_NO_PHONE = "[Error] not found [-P=phone]" ERROR_NO_STDATE = "[Error] not found [-s=stDate]" ERROR_NO_EDDATE = "[Error] not found [-e=edDate]" ERROR_NO_SIGNIN = "[Error] not sign in" ERROR_INVALID_USER = "[Error] invalid username" ERROR_INVALID_DATE = "[Error] invalid date time" ERROR_INVALID_TITLE = "[Error] invalid title" ERROR_INVALID_USERNAME_PASSWORD = "[Error] invalid username or password" ERROR_INVALID_MEETING = "[Error] invalid meeting" ERROR_REPEAT_USERNAME = "[Error] username has been used" ERROR_REPEAT_EMAIL = "[Error] email has been used" ERROR_REPEAT_PHONE = "[Error] phone has been used" ERROR_REPEAT_TITLE = "[Error] title has been used" ERROR_TIME_CONFLICT = "[Error] time conflict" ) func SignUp(username, password, email, phone string) error { if len(username) == 0 { return errors.New(ERROR_NO_USERNAME) } if len(password) == 0 { return errors.New(ERROR_NO_PASSWORD) } if len(email) == 0 { return errors.New(ERROR_NO_EMAIL) } if len(phone) == 0 { return errors.New(ERROR_NO_PHONE) } for _, user := range users { if user.UserName == username { return errors.New(ERROR_REPEAT_USERNAME) } if user.UserEmail == email { return errors.New(ERROR_REPEAT_EMAIL) } if user.UserPhone == phone { return errors.New(ERROR_REPEAT_PHONE) } } return signUp(username, password, email, phone) } func SignIn(username, password string) error { if len(username) == 0 { return errors.New(ERROR_NO_USERNAME) } if len(password) == 0 { return errors.New(ERROR_NO_PASSWORD) } return signIn(username, password) } func SignOut() error { if !isSignIn() { return errors.New(ERROR_NO_SIGNIN) } return signOut() } func CancelSelf() error { if !isSignIn() { return errors.New(ERROR_NO_SIGNIN) } return cancelSelf() } func ListUsers() ([]User, error) { if !isSignIn() { return nil, errors.New(ERROR_NO_SIGNIN) } return getUsers(), nil } func ListMeetings() ([]Meeting, error) { if !isSignIn() { return nil, errors.New(ERROR_NO_SIGNIN) } return getMeetings(), nil } func QueryMeeting(stDate, edDate string) ([]Meeting, error) { if !isSignIn() { return nil, errors.New(ERROR_NO_SIGNIN) } if len(stDate) == 0 { return nil, errors.New(ERROR_NO_STDATE) } if len(edDate) == 0 { return nil, errors.New(ERROR_NO_EDDATE) } if !isValidDate(stDate) || !isValidDate(edDate) || stDate >= edDate{ return nil, errors.New(ERROR_INVALID_DATE) } return queryMeeting(stDate, edDate) } func CreateMeeting(title, stDate, edDate string, args []string) error { if !isSignIn() { return errors.New(ERROR_NO_SIGNIN) } if len(title) == 0 { return errors.New(ERROR_NO_TITLE) } if len(stDate) == 0 { return errors.New(ERROR_NO_STDATE) } if len(edDate) == 0 { return errors.New(ERROR_NO_EDDATE) } if len(args) == 0 { return errors.New(ERROR_NO_PARTICANTS) } if GetMeetingByTitle(title).MeetingId > 0 { return errors.New(ERROR_REPEAT_TITLE) } if !isValidDate(stDate) || !isValidDate(edDate) || stDate >= edDate{ return errors.New(ERROR_INVALID_DATE) } for _, name := range args { user := GetUserByName(name) if user.UserId == 0 { return errors.New(ERROR_INVALID_USER + name) } for _, mid := range user.MeetingIds { m := GetMeetingById(mid) if !(m.MeetingStDate>=edDate || m.MeetingEdDate<=stDate) { return errors.New(ERROR_TIME_CONFLICT + " " + user.UserName) } } } return createMeeting(title, stDate, edDate, args) } func LeaveMeeting(title string) error { if !isSignIn() { return errors.New(ERROR_NO_SIGNIN) } if len(title) == 0 { return errors.New(ERROR_NO_TITLE) } m := GetMeetingByTitle(title) if m.MeetingId == 0 { return errors.New(ERROR_INVALID_MEETING) } return leaveMeeting(m) } func CancelMeeting(title string) error { if !isSignIn() { return errors.New(ERROR_NO_SIGNIN) } if len(title) == 0 { return errors.New(ERROR_NO_TITLE) } if GetMeetingByTitle(title).MeetingId == 0 { return errors.New(ERROR_INVALID_MEETING) } return cancelMeeting(GetMeetingByTitle(title)) } func ClearMeeting() error { return clearMeeting() } func AddParticipant(title string, usernames []string) error { if !isSignIn() { return errors.New(ERROR_NO_SIGNIN) } if len(title) == 0{ return errors.New(ERROR_NO_TITLE) } if len(usernames) == 0 { return errors.New(ERROR_NO_PARTICANTS) } m := GetMeetingByTitle(title) if m.MeetingId == 0 || m.AdminiatorId != curUser.UserId{ return errors.New(ERROR_INVALID_MEETING) } var uids []int for _, username := range usernames { user := GetUserByName(username) if user.UserId == 0 { return errors.New(ERROR_INVALID_USER + username) } uids = append(uids, user.UserId) } return addParticipant(m, uids) } func DelParticipant(title string, usernames []string) error { if !isSignIn() { return errors.New(ERROR_NO_SIGNIN) } if len(title) == 0 { return errors.New(ERROR_NO_TITLE) } if len(usernames) == 0 { return errors.New(ERROR_NO_PARTICANTS) } m := GetMeetingByTitle(title) if m.MeetingId == 0 || m.AdminiatorId != curUser.UserId{ return errors.New(ERROR_INVALID_MEETING) } var uids []int for _, username := range usernames { user := GetUserByName(username) if user.UserId == 0 { return errors.New(ERROR_INVALID_USER + username) } uids = append(uids, user.UserId) } return delParticipant(m, uids) } <file_sep>## Usage `go run main.go -h`<file_sep>package cmd import ( "agenda/entity" "fmt" "github.com/spf13/cobra" ) var leaveMeetingCmd = &cobra.Command{ Use: "leaveMeeting", Short: "leaveMeeting", Long: "leaveMeeting Command", Run: func(cmd *cobra.Command, args []string) { title, _ := cmd.Flags().GetString("title") if err := entity.LeaveMeeting(title); err != nil { fmt.Println(err) } else { fmt.Println("Success") } }, } func init() { rootCmd.AddCommand(leaveMeetingCmd) leaveMeetingCmd.Flags().StringP("title", "t", "", "title") } <file_sep>package handler import ( "net/http" "html/template" "fmt" ) // HomeHandler is the handler of the page of index func HomeHandler(w http.ResponseWriter, r *http.Request) { fmt.Println("handler:", "home", "method", r.Method) if r.Method == "GET" { t, _ := template.ParseFiles("static/htm/home.html") t.Execute(w, nil) } }<file_sep>package cmd import ( "agenda/entity" "fmt" "log" "github.com/spf13/cobra" ) var cancelSelfCmd = &cobra.Command{ Use: "cancelSelf", Short: "cancelSelf", Long: "cancelSelf Command", Run: func(cmd *cobra.Command, args []string) { if err := entity.CancelSelf(); err != nil { fmt.Println(err) log.Println(err) } else { fmt.Println("Success") log.Println("Success") } }, } func init() { rootCmd.AddCommand(cancelSelfCmd) } <file_sep>package model type Base struct { People string `json:"people"` Planets string `json:"planets"` Films string `json:"films"` Species string `json:"species"` Vehicles string `json:"vehicles"` Starships string `json:"starships"` }<file_sep>package cmd import ( "agenda/entity" "fmt" "github.com/olekukonko/tablewriter" "github.com/spf13/cobra" "log" "os" "strings" ) var listMeetingsCmd = &cobra.Command{ Use: "listMeetings", Short: "listMeetings", Long: "listMeetings Command", Run: func(cmd *cobra.Command, args []string) { if meetings, err := entity.ListMeetings(); err != nil { fmt.Println(err) log.Println(err) } else { table := tablewriter.NewWriter(os.Stdout) table.SetHeader([]string{"Title","Adminiator","Participants","StDate","EdDate"}) for _, meeting :=range meetings{ user := entity.GetUserById(meeting.AdminiatorId) var b []string for _, v := range meeting.ParticipantIds { b = append(b, entity.GetUserById(v).UserName) } table.Append([]string{meeting.MeetingTitle, user.UserName, strings.Join(b,","),meeting.MeetingStDate,meeting.MeetingEdDate}) } table.Render() log.Println("Success") } }, } func init() { rootCmd.AddCommand(listMeetingsCmd) } <file_sep><html> <head> <meta charset="UTF-8"> <title>signUp-post</title> </head> <body> <button><a href="/">Home</a></button> <table border="1"> <tr> <td>username</td> <td>{{.Username}}</td> </tr> <tr> <td>password</td> <td>{{.Password}}</td> </tr> <tr> <td>email</td> <td>{{.Email}}</td> </tr> <tr> <td>mobile</td> <td>{{.Mobile}}</td> </tr> </table> </body> </html><file_sep>package cmd import ( "agenda/entity" "fmt" "github.com/spf13/cobra" "log" ) var signInCmd = &cobra.Command{ Use: "signIn", Short: "signIn", Long: "signIn Command", Run: func(cmd *cobra.Command, args []string) { username, _ := cmd.Flags().GetString("username") password, _ := cmd.Flags().GetString("password") if err := entity.SignIn(username, password); err != nil { fmt.Println(err) log.Println(err) } else { fmt.Println("Success") log.Println("Success") } }, } func init() { rootCmd.AddCommand(signInCmd) signInCmd.Flags().StringP("username", "u", "", "username") signInCmd.Flags().StringP("password", "p", "", "password") } <file_sep># Ubuntu18.04 + Docker ## Docker 安装 [Get Docker Engine - Community for Ubuntu](https://docs.docker.com/install/linux/docker-ce/ubuntu/) ### 删除老版本(如果之前已经下了的话) `sudo apt remove docker docker-engine docker.io containerd runc` ### 下载社区版Docker(企业版需要付费) 官方介绍了三种下载方法:`Install using the repository`,`install from a package`,`install using the convenience script`,这里使用第一种 #### 设置存储库 1. 更新`apt` `$ sudo apt update` 2. 允许`apt`使用HTTPS访问存储库 `$ sudo apt install apt-transport-https ca-certificates curl gnupg-agent software-properties-common` 3. 添加Docker官方GPG密钥 `$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -` 通过搜索最后8位字符验证密钥`<KEY>` ```bash $ sudo apt-key fingerprint 0EBFCD88 pub rsa4096 2017-02-22 [SCEA] 9DC8 5822 <KEY> 854A E2D8 8D81 803C <KEY> uid [ unknown] Docker Release (CE deb) <<EMAIL>> sub rsa4096 2017-02-22 [S] ``` 4. 设置稳定的存储库 `$ sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"` 对应不同体系结构,具体看[官方文档](https://docs.docker.com/install/linux/docker-ce/ubuntu/) #### 下载 Docker Engine 1. 更新`apt` `$ sudo apt update` 2. 下载最新版本的`Docker Engine - Community`和`containerd` `$ sudo apt install docker-ce docker-ce-cli containerd.io` 下载特定版本看[官方文档](https://docs.docker.com/install/linux/docker-ce/ubuntu/) 3. 测试是否成功安装 ```bash $ docker run hello-world Hello from Docker! This message shows that your installation appears to be working correctly. To generate this message, Docker took the following steps: 1. The Docker client contacted the Docker daemon. 2. The Docker daemon pulled the "hello-world" image from the Docker Hub. (amd64) 3. The Docker daemon created a new container from that image which runs the executable that produces the output you are currently reading. 4. The Docker daemon streamed that output to the Docker client, which sent it to your terminal. To try something more ambitious, you can run an Ubuntu container with: $ docker run -it ubuntu bash Share images, automate workflows, and more with a free Docker ID: https://hub.docker.com/ For more examples and ideas, visit: https://docs.docker.com/get-started/ ``` ### 权限问题 >ERROR: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http://%2Fvar%2Frun%2Fdocker.sock/v1.40/info: dial unix /var/run/docker.sock: connect: permission denied [Docker启动Get Permission Denied](https://www.cnblogs.com/informatics/p/8276172.html) #### 解决方法一: `sudo docker xxx` #### 解决方法二: 将本地用户加入Docker用户组 1. 添加Docker用户组(docker可能会自动添加) `sudo groupadd docker` 2. 将本地用户添加到Docker用户组 `sudo gpasswd a $USER docker` 3. 更新用户组 `newgrp docker` 4. 测试docker命令 `docker ps` ### 镜像源问题 [Docker快速安装以及换镜像源](https://www.jianshu.com/p/34d3b4568059) 虽说如此,本人用的是DaoCloud。(阿里太麻烦,中科大不知道为什么还是没速度) ## [每天5分钟玩转 Docker 容器技术》教程目录](https://www.jianshu.com/p/657687b801f0) ## 基本操作 帮助`$ docker --help`,快速上手掌握几个命令即可 - `$ docker images` <=> `$ docker images ls` 显示所有镜像 - `$ docker ps -a` <=> `$ docker container ls -a` 显示所有容器(包括已中止) - `$ docker pull <image>` 下载镜像 - `$ docker run -it <image>` (下载镜像,如果没有的话)运行一个容器。-i 保留交互界面,-t 启动虚拟终端 -d 后台运行 - `root@xxx:/#` 进入容器中断后,如果想退出,可以按`[Ctrl-p] [Ctrl-q]` - `$ docker stop <image_id>` 停止容器 - `$ docker start <image_id>` 启动容器 - `$ docker restart <image_id>` 重启容器 - `$ docker attach <image_id>` 进入容器 ## 按PPT简单实操 ### 拉取 MySQL 镜像 `$ docker pull mysql:5.7` ![](images/mysql.png) [Docker mysql 5.7 Dockerfile](https://github.com/docker-library/mysql/blob/master/5.7/Dockerfile) 初步Dockerfile实操可以看: [Dockerfile 构建镜像 - 每天5分钟玩转容器技术(13)](https://mp.weixin.qq.com/s?__biz=MzIwMTM5MjUwMg==&mid=2653587598&idx=1&sn=d0952497b3a2272eee05cfb1e4e05e62&chksm=8d308097ba47098189b45ba63c4040cf94d687fb19c54b9cab593df9995612ce0b0632e9a54e&scene=21#wechat_redirect) [Dockerfile 常用指令 - 每天5分钟玩转 Docker 容器技术(16)](https://mp.weixin.qq.com/s?__biz=MzIwMTM5MjUwMg==&mid=2653587610&idx=1&sn=fc2c45c4eb11ecc20d6bba50cc7b8cad&chksm=8d308083ba470995f3e784386f4d09859fa7bdf93b0772d1b03669dd7612c818c6280f7f6b00&scene=21#wechat_redirect) ### 如何通过dockerfile创建image 1. 下载ubuntu镜像,如果不在这里下载,之后运行dockerfile时也会去下载的 `$ docker pull ubuntu` ```bash $ docker run -it ubuntu root@xxxx:/# vim bash: vim: command not found ``` 2. 搭建测试环境 `$ mkdir ~/dokcerfile-test && cd ~/dokcerfile-test` ```bash $ touch dockerfile FROM ubuntu RUN apt update && apt install vim -y ``` 3. 根据 dockerfile 构建镜像 `$ docker build -t ubuntu-with-vim-dockerfile .` 4. 验证 `$ docker images` `$ docker run -it ubuntu-with-vim-dockerfile` 发现此时可以用vim了 ### 使用 MySQL 容器 - 启动服务器 `docker run -p 3306:3306 --name mysql2 -e MYSQL_ROOT_PASSWORD=root -d mysql:5.7` ![](images/mysql2_start.png) - 启动MySql客户端 `$ docker run -it --net host mysql:5.7 "sh"` `# mysql -h12192.168.127.12 -P3306 -uroot -proot` ![](images/mysql2_client.png) - [mysql 客户端基本操作](https://blog.csdn.net/pmlpml/article/details/78602290) - 查看 MySql 数据库文件 `$ docker exec -it mysql2 bash` ![](images/mysql2_db.png) - Dockerfile 的 volume 记得上面提到的官方提供的dockerfile吗?里面大概73行左右的位置`VOLUME /var/lib/mysql` 再看看主机`/var/lib/docker/volumes` ```sh $ docker container prune -f $ docker volume prune -f $ docker volume ls ``` ![](images/mysql2_volumes.png) 每次启动 mysql 容器,docker 创建一个文件卷挂载在容器内/var/lib/mysql位置 这个卷在主机(host)的 /var/lib/docker/volumes/ 目录下 #### 创建卷并挂载 ```sh $ docker rm $(docker ps -a -q) -f -v $ docker volume create mydb $ docker run --name mysql2 -e MYSQL_ROOT_PASSWORD=<PASSWORD> -v mydb:/var/lib/mysql -d mysql:5.7 ``` ![](images/mysql2_mydb.png) - 注意:这里没有暴露端口到主机! - 将自己定义的数据卷挂载在 `/var/lib/mysql` #### 启动客户端容器连接服务器 ```sh $ docker run --name myclient --link mysql2:mysql -it mysql:5.7 bash root@xxx:/# env ... root@xxx:/# mysql -hmysql -P3306 -uroot -proot ``` ![](images/mysql2_client2.png) - 注意:这里使用了 `--link` 连接两个容器 - 客户端容器内可以使用 mysql 这个别名访问服务器 #### 挂载现有数据库 `$ docker run -v "$PWD/data":/var/lib/mysql --user 1000:1000 --name some-mysql -e MYSQL_ROOT_PASSWORD=<PASSWORD> -d mysql:tag` #### 修改容器配置 `$ docker run --name some-mysql -v /my/custom:/etc/mysql/conf.d -e MYSQL_ROOT_PASSWORD=<PASSWORD> -d mysql:tag` ### Docker compose 与多容器应用自动化部署 1. 下载 Docker compose `$ sudo apt install docker-compose` 2. 编写 stack.yml ```sh $ mkdir comptest && cd comptest && vim stack.yml version: '3.1' services: db: image: mysql:5.7 command: --default-authentication-plugin=mysql_native_password restart: always environment: MYSQL_ROOT_PASSWORD: <PASSWORD> adminer: image: adminer restart: always ports: - 8080:8080 ``` 3. 启动服务 `$ docker-compose -f stack.yml up` ### Docker 网络部分 `$ docker network ls` ![](images/docker_network.png) - none,相当于没有网络 - host,相当于与主机共享端口 - bridge,相当于主机控制下的局域网内用户 ### Docker 仓库部分 主要是公有仓库服务,以及私有仓库搭建两部分 公有仓库不必说,由众多公司提供,主要是私有仓库的搭建 但是作为个人来说,基本上没有私有仓库搭建的需求,而主要作为公司内部仓库的建立。 [Configuring a registry](https://docs.docker.com/registry/configuration/) ### Docker 监控与日志部分 `$ docker info` ![](images/docker_info.png) 另外还有其他信息查看命令 - `$ docker top` - `$ docker stats` - `$ docker inspect` - `$ docker logs` 等等 ## 后话 作为初次使用来说,最主要的就是能够下载安装Docker,并在里面启动一个服务。剩下的需要逐步精进。 <file_sep>package main import ( "net/http" "fmt" "log" "com/web/handler" ) func main() { http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static")))) http.HandleFunc("/", handler.HomeHandler) http.HandleFunc("/signUp", handler.SignUpHandler) http.HandleFunc("/upload", handler.UploadHandler) http.HandleFunc("/unknow", handler.UnknowHandler) http.HandleFunc("/js", handler.JsHandler) err := http.ListenAndServe(":80", nil) if err != nil { log.Fatal("ListenAndServer: ", err) } fmt.Println("the server is runnning at localhost with port 80") } <file_sep>package handler import ( "fmt" "net/http" "html/template" ) // JsHandler is the handler of the page of js func JsHandler(w http.ResponseWriter, r *http.Request){ fmt.Println("handler:", "js", "method:", r.Method) if r.Method == "GET" { t, _ := template.ParseFiles("static/htm/js.html") t.Execute(w, nil) } else { fmt.Fprintln(w, "message from go server"); } }<file_sep>package model type User struct{ Username string `json:"username"` Password string `json:"<PASSWORD>"` Description string `json:description, omitempty` }<file_sep>package main import ( "com/week12/EasyBlog/backend/swapi" ) func main(){ swapi.Run(":8090") }<file_sep>## Usage - `backend` `cd backend && go run server.go` - `frontend` `cd frontend && npm run serve` ## Summary **一切都是谷歌的阴谋!!** ### 阶段1 想办法爬虫"SWAPI"的数据,但是会经常性的断开连接 去github拿swapi的源代码自己去生成web服务给自己爬取吧,前面几个commit全是损坏的 各种版本报错、各种组件缺失,满屏都是红色 仓库4,5年没维护了,里面所有东西版本低的难受 ubuntu18不行,听同学说试试ubuntu14 然后跑去折腾了Docker 下完之后才发现,win10家庭版不能用啊。根本不兼容。那为什么Docker大大个字写着“download for window”? 查了一轮docker要用Hyper-V,又去折腾在家庭版上面启动Hyper-V,又要去改什么注册表 整吧整吧,最后把Docker在win10家庭版上面安装了,主机和docker不能互联是什么鬼??找了很久也找不到解决方法 回来不整Docker了,打开虚拟机做别的作业吧,HV和VM不兼容,死对头,必须删一个,无奈只能把docker卸了,配置还原回去,之前全白干 只能在虚拟机启动swapi服务,又是各种报错,一步一步弄下来把自己虚拟机也弄坏了,数据丢了一堆 新开一个ubuntu14的虚拟机,全部下载低版本都东东,终于把swapi启动了。此时已经过去整整两天,除了上课时间全在弄这鬼东西 相当于,为了弄一个老旧的已经没人维护的swapi服务,我炸了自己的win10本机,炸了里面的一个平时经常用的虚拟机,新建了一个几乎不会再用的虚拟机,还把自己心态炸了 ### 阶段2 终于可以用GO写后端API了。 体力活把几个API用半天敲完吧,一运行地址错误,被什么切片数组搞的头大 恕我直言,管他性能怎样特性怎样,如果不能把代码简单写下来,且没有错误,这就是一个垃圾的设计! 大概是这样的一个过程 ```go func foo() []byte { var v []byte // ... v = getV() // 返回一个[]byte fmt.Println(v) // 输出v的值 reutrn v } func main(){ v := foo() fmt.Println(v) // 报错,地址错误 } ``` 又比如把数据转换为json时,也有很多需要注意的 ```go type TT struct{ AbcDe string `json:"abc_de"` } ``` - AbcDe:驼峰写法 - abc_de:小写且下划线连接 - "abc_de":必须加双引号 - json:"abc_de":冒号后面不能有空格 - \`json:"abc_de"\`:两侧加点,不是引号 不然你爬取的数据就会各种残缺,耗费大量精力再去修改 ### 阶段3 终于终于,后端基本完成功能,可以用`curl`命令进行测试和检测 开始着手前端的工作 那么前端懒得弄那些花里胡哨的,就写了一个最基本的功能,发起get请求,然后问题就来了 `No Access-Control-Allow-Origin` 前端跨域问题,参考了各种前端后端的写法,还是不行,拿不到数据,然后又过去了几个小时,真的几个小时 因为本人使用的是`Gin`框架,试了一些在返回命令前增加 `c.Header("No Access-Control-Allow-Origin", "*")`可以访问,但是这样就会多很多重复代码,已经很累了 继续搜,使用中间件,`Cros`。不行,又跑去搜,发现路由必须夹在中间间和启动路由的中间,即 ```go func main(){ r := gin.Default() r.Use(xxx) // 各种路由设置 r.Run(":8000") } ``` 即路由设置必须在中间件之后,否则比起作用 然后各种改层次结构,小修小改,补补这补补那,终于能在前端中获取后端api数据了。 但是还是有点问题,比如`gin`的路由参数设置跟swapi有些不一样,像地址末尾的斜杠,gin要想解决就必须手动设置每一个可能 ### 阶段4 想不到还有阶段4吧?我也不想呀! 发现前端有一些api能获取,有一些不能,比如: ```go http:localhost:8090/api/people/1 // 不能获取 http:localhost:8090/api/people/2 // 能获取 ``` `F12`查看浏览器控制台,居然又是跨域问题!!我不是已经解决了吗?? 看参数,找资料,没辙 最后在一个参数后面,一行浅灰色的字样(from disk cache)。本地缓存?? 小心翼翼的清除谷歌浏览器的缓存,再运行一遍 卧槽,居然成功了! 这不是在搞人心态吗! 黑了黑了<file_sep>package cmd import ( "agenda/entity" "fmt" "log" "os" "strings" "github.com/olekukonko/tablewriter" "github.com/spf13/cobra" ) var queryMeetingCmd = &cobra.Command{ Use: "queryMeeting", Short: "queryMeeting", Long: "queryMeeting Command", Run: func(cmd *cobra.Command, args []string) { stDate, _ := cmd.Flags().GetString("startDate") edDate, _ := cmd.Flags().GetString("endDate") if meetings, err := entity.QueryMeeting(stDate, edDate); err != nil { fmt.Println(err) log.Println(err) } else { table := tablewriter.NewWriter(os.Stdout) table.SetHeader([]string{"Title", "Adminiator", "Participants", "StDate", "EdDate"}) for _, meeting := range meetings { user := entity.GetUserById(meeting.AdminiatorId) var b []string for _, v := range meeting.ParticipantIds { b = append(b, entity.GetUserById(v).UserName) } table.Append([]string{meeting.MeetingTitle, user.UserName, strings.Join(b, ","), meeting.MeetingStDate, meeting.MeetingEdDate}) } table.Render() log.Println("Success") } }, } func init() { rootCmd.AddCommand(queryMeetingCmd) queryMeetingCmd.Flags().StringP("startDate", "s", "", "startDate [yyyy:MM:dd_HH:mm]") queryMeetingCmd.Flags().StringP("endDate", "e", "", "endDate [yyyy-MM-dd_HH:mm]") } <file_sep>package main import "com/api/router" func main(){ router.Execute() }<file_sep>package cmd import ( "agenda/entity" "fmt" "log" "github.com/spf13/cobra" ) var createMeetingCmd = &cobra.Command{ Use: "createMeeting", Short: "createMeeting", Long: "createMeeting Command", Run: func(cmd *cobra.Command, args []string) { title, _ := cmd.Flags().GetString("title") stDate, _ := cmd.Flags().GetString("startDate") edDate, _ := cmd.Flags().GetString("endDate") if err := entity.CreateMeeting(title, stDate, edDate, args); err != nil { fmt.Println(err) log.Println(err) } else { fmt.Println("Success") log.Println("Success") } }, } func init() { rootCmd.AddCommand(createMeetingCmd) createMeetingCmd.Flags().StringP("title", "t", "", "title") createMeetingCmd.Flags().StringP("startDate", "s", "", "startDate [yyyy:MM:dd_HH:mm]") createMeetingCmd.Flags().StringP("endDate", "e", "", "endDate [yyyy-MM-dd_HH:mm]") } <file_sep>package database import ( "com/week12/EasyBlog/backend/model" "encoding/json" "io/ioutil" "log" "net/http" ) var swapi_url = "http://192.168.43.133:8000/api/" var peopleBucket = "people" var filmBucket = "film" var planetBucket = "planet" var specieBucket = "specie" var starshipBucket = "starship" var vehicleBucket = "vehicle" func CrawlData() { if res, err := http.Get(swapi_url); err == nil { if body, err := ioutil.ReadAll(res.Body); err == nil { base := model.Base{} if err := json.Unmarshal(body, &base); err == nil { Put("/", swapi_url, string(body)) CrawlPeople(base.People + "?page=1") CrawlPlanets(base.Planets + "?page=1") CrawlFilms(base.Films + "?page=1") CrawlSpecies(base.Species + "?page=1") CrawlVehicles(base.Vehicles + "?page=1") CrawlStarships(base.Starships + "?page=1") } else { log.Println(err) } } else { log.Println(err) } } else { log.Println(err) } } func CrawlPeople(url string) { if res, err := http.Get(url); err == nil { if body, err := ioutil.ReadAll(res.Body); err == nil { page := model.PeoplePage{} if err := json.Unmarshal(body, &page); err == nil { Put(peopleBucket, url, string(body)) for _, people := range page.Results { v, _ := json.Marshal(people) Put(peopleBucket, people.Url, string(v)) } CrawlPeople(page.Next) } else { log.Println(err) } } else { log.Println(err) } } else { log.Println(err) } } func CrawlPlanets(url string) { if res, err := http.Get(url); err == nil { if body, err := ioutil.ReadAll(res.Body); err == nil { page := model.PlanetPage{} if err := json.Unmarshal(body, &page); err == nil { Put(planetBucket, url, string(body)) for _, planet := range page.Results { v, _ := json.Marshal(planet) Put(planetBucket, planet.Url, string(v)) } CrawlPlanets(page.Next) } else { log.Println(err) } } else { log.Println(err) } } else { log.Println(err) } } func CrawlFilms(url string) { if res, err := http.Get(url); err == nil { if body, err := ioutil.ReadAll(res.Body); err == nil { page := model.FilmPage{} if err := json.Unmarshal(body, &page); err == nil { Put(filmBucket, url, string(body)) for _, film := range page.Results { v, _ := json.Marshal(film) Put(filmBucket, film.Url, string(v)) } CrawlFilms(page.Next) } else { log.Println(err) } } else { log.Println(err) } } else { log.Println(err) } } func CrawlSpecies(url string){ if res, err := http.Get(url); err == nil { if body, err := ioutil.ReadAll(res.Body); err == nil { page := model.SpeciePage{} if err := json.Unmarshal(body, &page); err == nil { Put(specieBucket, url, string(body)) for _, specie := range page.Results { v, _ := json.Marshal(specie) Put(specieBucket, specie.Url, string(v)) } CrawlSpecies(page.Next) } else { log.Println(err) } } else { log.Println(err) } } else { log.Println(err) } } func CrawlVehicles(url string){ if res, err := http.Get(url); err == nil { if body, err := ioutil.ReadAll(res.Body); err == nil { page := model.VehiclePage{} if err := json.Unmarshal(body, &page); err == nil { Put(vehicleBucket, url, string(body)) for _, vehicle := range page.Results { v, _ := json.Marshal(vehicle) Put(vehicleBucket, vehicle.Url, string(v)) } CrawlVehicles(page.Next) } else { log.Println(err) } } else { log.Println(err) } } else { log.Println(err) } } func CrawlStarships(url string){ if res, err := http.Get(url); err == nil { if body, err := ioutil.ReadAll(res.Body); err == nil { page := model.StarshipPage{} if err := json.Unmarshal(body, &page); err == nil { Put(starshipBucket, url, string(body)) for _, starship := range page.Results { v, _ := json.Marshal(starship) Put(starshipBucket, starship.Url, string(v)) } CrawlStarships(page.Next) } else { log.Println(err) } } else { log.Println(err) } } else { log.Println(err) } }<file_sep>## Usage `run go main.go` ### 获取所有api接口: - `curl -X GET localhost:8000/api/` ```json { "createUser": "POST: /api/user/", "deleteUser": "DELETE: /api/user/:username", "getAllUsers": "GET: /api/user/", "getUser": "GET: /api/user/:username", "updateUser": "PUT: /api/user/:username", "uploadFile": "POST: /api/file/" } ``` ### api of User - 查看所有用户 `curl -X GET localhost:8000/api/user/` - 查看特定用户 `curl -X GET localhost:8000/api/user/abc` - 创建用户 `curl -X POST localhost:8000/api/user/ -d "username=abc&password=123"` - 跟新用户信息 `curl -X PUT localhost:8000/api/user/abc -d "username=abc&description=day day up"` - 删除用户 - `curl -X DELETE localhost:8000/api/user/abc` ### api of File - 上传文件 `curl -X POST localhost:8000/api/file -F "upload=@/Users/xxx/Pictures/avatar.jpg" -H "Content-Type: multipart/form-data"` <file_sep>package model type FilmPage struct { Count int `json:"count"` Next string `json:"next"` Previous string `json:"previous"` Results []Film `json:"results"` } type Film struct { Title string `json:"title"` EpisodeId int `json:"episode_id"` OpeningCrawl string `json:"opening_crawl"` Director string `json:"director"` Producrr string `json:"producer"` ReleaseDate string `json:"release_date"` Characters []string `json:"characters"` Planets []string `json:"planets"` Starships []string `json:"starships"` Vehicles []string `json:"vehicles"` Species []string `json:"species"` Created string `json:"created"` Edited string `json:"edited"` Url string `json:"url"` }<file_sep>package swapi import ( "com/week12/EasyBlog/backend/database" "com/week12/EasyBlog/backend/model" "encoding/json" "github.com/gin-gonic/gin" "net/http" ) var starshipBucket = "starship" var starshipUrl = root_url + "starships/" func liststarshipPage(c *gin.Context) { page := c.DefaultQuery("page", "1") if v := database.Get(starshipBucket, starshipUrl + "?page=" + page); v != "" { var res model.StarshipPage json.Unmarshal([]byte(v), &res) c.IndentedJSON(http.StatusOK, res) } else { c.String(http.StatusNotFound, "Not found") } } func liststarship(c *gin.Context) { id := c.Param("id") if v := database.Get(starshipBucket, starshipUrl + id + "/"); v != "" { var res model.Starship json.Unmarshal([]byte(v), &res) c.IndentedJSON(http.StatusOK, res) } else { c.String(http.StatusNotFound, "Not found") } }<file_sep># 安装Go语言开发环境 ## 安装一个合适自己的编辑器 - Emacs - Gedit - Notepad - subliminal - Visual Studio IDE - VsCode - Vim ## 安装Golang - 使用 Centos7 包管理器 yum 下载 golang ```sh $ sudo yum install golang ``` - 查看版本 ```sh $ go version ``` ## 配置Golang ### 创建工作空间 ```sh $ mkdir ~/gowork ``` ### 配置环境变量 - 对于 centos 在 ~/.profile 文件中添加: ```sh export GOPATH=$HOME/gowork export PATH=$PATH:$GOPATH/bin ``` 并执行命令启动配置 ```sh $ . ~/.profile ``` ### 检查配置 ``` $ go env ... GOPATH = ... ... GOROOT = ... ... ``` ### 创建包路径 ```sh $ mkdir -p $GOPATH/src/com ``` ### 创建第一个项目 ```sh $ mkdir -p $GOPATH/src/com/hello ``` ### 创建第一个程序 ```sh $ touch $GOPATH/src/com/hello/hello.go ``` 在`hello.go`中填入代码 ```go package main import "fmt" func main(){ fmt.Printf("Hello World!\n") } ``` ### 安装第一个程序 ```sh $ go install com/hello ``` 这个时候在`%GOOATH/bin`目录下会出现`hello`文件 可以直接使用命令执行查看结果 ``` $ hello Hello World! ``` ![](/images/p1.png) ### 创建第一个库 - 同样,先创建一个包路径 ```sh $ mkdir -p $GOPATH/src/test ``` - 并在该目录下创建GO程序 ```sh $ touch $GOPATH/src/test/test.go ``` - 按Go开发文档提示输入内容 ```go // stringutil 包含有用于处理字符串的工具函数。 package stringutil // Reverse 将其实参字符串以符文为单位左右反转。 func Reverse(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) } ``` - 然后再该源码目录下测试该包的编译,不会产生输出结果 ```sh $ go build ``` - 现在,回到我们的`hello.go'`文件中,修改一下代码 ```go package main import "fmt" import "test" func main(){ fmt.Printf(stringutil.Reverse("!oG ,olleH")) } ``` - 在hello目录下执行命令安装 ```sh $ go install ``` - 执行代码查看结果 ```sh $ hello Hello, GO! ``` ![](/images/2.png) - ※这里总结一下,import “包路径”,指包所在的目录,包含该目录下所有的go程序,最关键的是go程序内`package`的命名,这个才是包名,影响其他程序引用时使用的前缀。 ## 安装Git客户端 - go 语言的插件主要在 Github 上,安装 git 客户端是首要工作。 ```sh $ sudo yum install git ``` ## 安装 go tour - go tour 有线上和线下的,一般为了编译速度会选择下载离线版本 - 不过 go tour 官方需要科学上网,一般选择使用国内的中文版即可 [Go 语言之旅](https://github.com/Go-zh/tour) ```sh $ go get -u github.com/Go-zh/tour ``` - 安装后会在`bin`目录生成`tour`文件,可以直接运行 ```sh $ tour ```
ef4e5ead0ed3d94502afedc3d169df4190b0a693
[ "Markdown", "Go", "HTML" ]
51
Go
sysu-lemon/SeviceComputing-Learning
f5b7ea0f174ba38a5d1d96b5d9a4263e8f2fdc11
a384b835d63f520c28f25b1f31750b083d71461c
refs/heads/main
<repo_name>Beater420/Encheres<file_sep>/src/fr/eni/encheres/bll/TestBLL.java package fr.eni.encheres.bll; import fr.eni.encheres.bo.Utilisateur; public class TestBLL { public static void main(String[] args) { UtilisateurManager utilisateurManager = null; utilisateurManager = new UtilisateurManager(); // Instanciation du jeu d'essai Utilisateur u1 = new Utilisateur("od", "olivier", "durand", "<EMAIL>", "0652598789","rue de la republique", "84000", "Avignon", "oliv59", 200, true); } } <file_sep>/README.md # Encheres ## Développement ### Parametres BDD 1. Copier le fichier `jdc.properties.dist` du package `fr.eni.encheres.dal`. 2. Coller le fichier en le renommant `jdc.properties` à l'intérieur du même package. 3. Modifier le fichier `jdc.properties` pour y mettre les informations liée à votre BDD pour le projet. ### Librairies 1. Telecharger les lib suivantes dans le dossier `WebContent/WEB-INF/lib`: - `sqljdbc42.jar` - `jstl-1.2.jar`<file_sep>/src/fr/eni/encheres/bll/ArticleManager.java package fr.eni.encheres.bll; import fr.eni.encheres.bo.Article; import fr.eni.encheres.dal.ArticleDAO; import fr.eni.encheres.dal.DALException; import fr.eni.encheres.dal.DAOFactory; import java.time.LocalDate; import java.util.List; import fr.eni.encheres.BusinessException; public class ArticleManager { private ArticleDAO articleDAO; public ArticleManager() { this.articleDAO = DAOFactory.getArticleDAO(); } public int add(Article article) throws DALException, BusinessException { BusinessException exception = new BusinessException(); validation(article, exception); if(!exception.hasErreurs()) { article = articleDAO.insert(article); return article.getNoArticle(); } else { throw exception; } } public int update(Article article) throws DALException, BusinessException { BusinessException exception = new BusinessException(); validation(article, exception); if(!exception.hasErreurs()) { article = articleDAO.update(article); return article.getNoArticle(); } else { throw exception; } } public void remove(int id) throws DALException { articleDAO.delete(id); } public Article getArticleById(int id) throws DALException { return articleDAO.selectById(id); } public List<Article> getAllArticles() throws DALException { return articleDAO.selectAll(); } /** * Cette méthode permet de vérifier les règles à respecter sur Article. * En cas d'erreur, le code d'erreur est enregistré dans l'objet BusinessException. * @param Article article * @param BusinessException businessException */ private void validation(Article article, BusinessException businessException) { if(null == article.getNomArticle() || article.getNomArticle().equals("")) { businessException.ajouterErreur(CodesResultatBLL.REGLE_ARTICLE_NOM_NULL, "Nom de l'article obligatoire."); } else { if(30 < article.getNomArticle().length()) { businessException.ajouterErreur(CodesResultatBLL.REGLE_ARTICLE_NOM_ERREUR, "Nom de l'article trop long."); } } if(null == article.getDescription() || article.getDescription().equals("")) { businessException.ajouterErreur(CodesResultatBLL.REGLE_ARTICLE_DESCRIPTION_NULL, "Description de l'article obligatoire."); } else { if(300 < article.getDescription().length()) { businessException.ajouterErreur(CodesResultatBLL.REGLE_ARTICLE_DESCRIPTION_ERREUR, "Description de l'article trop longue."); } } if(null == article.getDateDebutEncheres()) { businessException.ajouterErreur(CodesResultatBLL.REGLE_ARTICLE_DATE_DEBUT_NULL, "Date de début de la vente est obligatoire."); } else { if(article.getDateDebutEncheres().isBefore(LocalDate.now())) { businessException.ajouterErreur(CodesResultatBLL.REGLE_ARTICLE_DATE_DEBUT_ERREUR, "Date de début de la vente doit se situer dans le futur."); } } if(null == article.getDateFinEncheres()) { businessException.ajouterErreur(CodesResultatBLL.REGLE_ARTICLE_DATE_FIN_NULL, "Date de fin de la vente est obligatoire."); } else { if(article.getDateFinEncheres().isBefore(LocalDate.now())) { businessException.ajouterErreur(CodesResultatBLL.REGLE_ARTICLE_DATE_FIN_BEFORE_NOW, "Date de fin de la vente doit se situer dans le futur."); } if(null != article.getDateDebutEncheres() && article.getDateFinEncheres().isBefore(article.getDateDebutEncheres())) { businessException.ajouterErreur(CodesResultatBLL.REGLE_ARTICLE_DATE_FIN_BEFORE_DEBUT, "Date de fin de la vente doit être superieur à la date de debut."); } } } } <file_sep>/src/fr/eni/encheres/dal/CodesResultatDAL.java package fr.eni.encheres.dal; public class CodesResultatDAL { /** * Echec général quand tentative d'ajouter un objet null */ public static final int INSERT_OBJET_NULL=10000; /** * Echec général quand erreur non gérée à l'insertion */ public static final int INSERT_OBJET_ECHEC=10001; /** * Echec de l'insertion d'un avis à cause de la note */ public static final int INSERT_ARTICLE_ECHEC=10002; } <file_sep>/src/fr/eni/encheres/bll/TestBLLEnchere.java package fr.eni.encheres.bll; import java.util.List; import fr.eni.encheres.bo.Enchere; import fr.eni.encheres.bo.Utilisateur; import fr.eni.encheres.dal.DALException; import fr.eni.encheres.dal.DAOFactory; import fr.eni.encheres.dal.EnchereDAO; import fr.eni.encheres.dal.EnchereDAOJdbcImpl; import fr.eni.encheres.dal.UtilisateurDAO; public class TestBLLEnchere { public static void main(String[] args) throws DALException { /* EnchereManager em = new EnchereManager(); System.out.println(em.getListEncheres()); */ // EnchereDAO enchereDAO = DAOFactory.getEnchereDAO(); EnchereDAOJdbcImpl enchereDAO = new EnchereDAOJdbcImpl(); Enchere enchere = enchereDAO.selectById(8); System.out.println(enchere.getMontantEnchere()); // List<Enchere> list = enchereDAO.selectAll(); // System.out.println(list); EnchereManager em = new EnchereManager(); Enchere enchere1 = em.getEnchereByID(9); System.out.println(enchere1); /* ArticleManager am = new ArticleManager(); System.out.println(am.getArticleById(8)); */ } } <file_sep>/src/fr/eni/encheres/ihm/ServletCreerCompte.java package fr.eni.encheres.ihm; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import fr.eni.encheres.BusinessException; import fr.eni.encheres.bll.UtilisateurManager; import fr.eni.encheres.bo.Utilisateur; import fr.eni.encheres.dal.DALException; /** * Servlet implementation class ServletCreerCompte */ @WebServlet("/ServletCreerCompte") public class ServletCreerCompte extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/encheres/enchereUtilisateur/creerCompte.jsp"); rd.forward(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean isAddButton = request.getParameter("submitButton").equals("add"); boolean isCancelButton = request.getParameter("submitButton").equals("cancel"); if (isAddButton) { // Recuperation des donnees du formulaire String pseudo = request.getParameter("pseudo"); String nom = request.getParameter("nom"); String prenom = request.getParameter("prenom"); String email = request.getParameter("email"); String tel = request.getParameter("tel"); String rue = request.getParameter("rue"); String codePostal = request.getParameter("codePostal"); String ville = request.getParameter("ville"); String motDePasse = request.getParameter("mdp"); String motDePasseConfirmation = request.getParameter("mdpC"); UtilisateurManager utilisateurManager = new UtilisateurManager(); Utilisateur utilisateuraAjouter = new Utilisateur(pseudo, nom, prenom, email, tel, rue, codePostal, ville, motDePasse,motDePasseConfirmation); Utilisateur utilsateurRenvoye = null; try { utilsateurRenvoye = utilisateurManager.add(utilisateuraAjouter); } catch (DALException e) { e.printStackTrace(); } catch (BusinessException e) { String[] errorMessages = e.getErrorMessages(); request.setAttribute("errorMessages", errorMessages); } if (utilsateurRenvoye != null) { // Redirection vers la page d'accueil response.sendRedirect(request.getContextPath()); } else { String erreurCreation = "Compte utilisateur non crée, renseigner à nouveau les champs"; System.out.println("Identifiant et mot de passe incorrects"); request.setAttribute("erreur", erreurCreation); RequestDispatcher rd = request .getRequestDispatcher("/WEB-INF/encheres/enchereUtilisateur/creerCompte.jsp"); rd.forward(request, response); } } if (isCancelButton) { RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/encheres/accueil.jsp"); rd.forward(request, response); } } }<file_sep>/src/fr/eni/encheres/dal/RetraitDAO.java package fr.eni.encheres.dal; import fr.eni.encheres.bo.Retrait; public interface RetraitDAO extends DAO<Retrait> { public Retrait insert(Retrait retrait) throws DALException; public Retrait selectById(int id) throws DALException; public Retrait update(Retrait retrait) throws DALException; public void delete(int id) throws DALException; } <file_sep>/src/fr/eni/encheres/dal/ArticleDAO.java package fr.eni.encheres.dal; import fr.eni.encheres.bo.Article; public interface ArticleDAO extends DAO<Article> { public Article insert(Article article) throws DALException; public Article selectById(int id) throws DALException; public Article update(Article article) throws DALException; public void delete(int id) throws DALException; } <file_sep>/src/fr/eni/encheres/bo/Enchere.java package fr.eni.encheres.bo; import java.time.LocalDate; import fr.eni.encheres.dal.ArticleDAO; import fr.eni.encheres.dal.DALException; import fr.eni.encheres.dal.DAOFactory; import fr.eni.encheres.dal.UtilisateurDAO; public class Enchere { private LocalDate dateEnchere; private int montantEnchere; private Article article; private Utilisateur acheteur; public Enchere() { } public Enchere(Utilisateur acheteur, Article article, LocalDate dateEnchere, int montantEnchere) { super(); this.setAcheteur(acheteur); this.setArticle(article); this.setDateEnchere(dateEnchere); this.setMontantEnchere(montantEnchere); } /* public Enchere(int acheteurID, int articleID, LocalDate dateEnchere, int montantEnchere) throws DALException { super(); ArticleDAO articleDAO = DAOFactory.getArticleDAO(); this.setArticle(articleDAO.selectById(articleID)); UtilisateurDAO utilisteurDAO = DAOFactory.getUtilisateurDAO(); this.setAcheteur(utilisteurDAO.selectById(acheteurID)); ArticleDAO articleDAO = DAOFactory.getArticleDAO(); this.article = articleDAO.selectById(articleID); UtilisateurDAO utilisteurDAO = DAOFactory.getUtilisateurDAO(); this.acheteur = utilisteurDAO.selectById(acheteurID); this.setDateEnchere(dateEnchere); this.setMontantEnchere(montantEnchere); } */ public LocalDate getDateEnchere() { return dateEnchere; } public void setDateEnchere(LocalDate dateEnchere) { this.dateEnchere = dateEnchere; } public int getMontantEnchere() { return montantEnchere; } public void setMontantEnchere(int montantEnchere) { this.montantEnchere = montantEnchere; } public Article getArticle() { return article; } public void setArticle(Article article) { this.article = article; } public Utilisateur getAcheteur() { return acheteur; } public void setAcheteur(Utilisateur acheteur) { this.acheteur = acheteur; } @Override public String toString() { return "Enchere [dateEnchere=" + dateEnchere + ", montantEnchere=" + montantEnchere + ", article=" + article + ", acheteur=" + acheteur + "]"; } } <file_sep>/src/fr/eni/encheres/bll/CodesResultatBLL.java package fr.eni.encheres.bll; public class CodesResultatBLL { /** * Echec quand le nom de l'article est null. */ public static final int REGLE_ARTICLE_NOM_NULL=20000; /** * Echec quand le nom de l'article est en erreur. */ public static final int REGLE_ARTICLE_NOM_ERREUR=20001; /** * Echec quand la description de l'article est null. */ public static final int REGLE_ARTICLE_DESCRIPTION_NULL=20002; /** * Echec quand la description de l'article est en erreur. */ public static final int REGLE_ARTICLE_DESCRIPTION_ERREUR=20003; /** * Echec quand la date de debut de l'article est null. */ public static final int REGLE_ARTICLE_DATE_DEBUT_NULL=20004; /** * Echec quand la date de debut de l'article est en erreur. */ public static final int REGLE_ARTICLE_DATE_DEBUT_ERREUR=20005; /** * Echec quand la date de fin de l'article est null. */ public static final int REGLE_ARTICLE_DATE_FIN_NULL=20006; /** * Echec quand la date de fin de l'article est avant la date d'aujourd'hui. */ public static final int REGLE_ARTICLE_DATE_FIN_BEFORE_NOW=20007; /** * Echec quand la date de fin de l'article est avant la date de debut. */ public static final int REGLE_ARTICLE_DATE_FIN_BEFORE_DEBUT=20008; public static final int REGLE_UTILISATEUR_PSEUDO_NULL=20009; public static final int REGLE_UTILISATEUR_PSEUDO_ERREUR=20010; public static final int REGLE_UTILISATEUR_NOM_NULL=20011; public static final int REGLE_UTILISATEUR_NOM_ERREUR=20012; public static final int REGLE_UTILISATEUR_PRENOM_NULL=20013; public static final int REGLE_UTILISATEUR_PRENOM_ERREUR=20014; public static final int REGLE_UTILISATEUR_EMAIL_NULL=20015; public static final int REGLE_UTILISATEUR_EMAIL_ERREUR=20016; public static final int REGLE_UTILISATEUR_TEL_ERREUR=20017; public static final int REGLE_UTILISATEUR_RUE_NULL=20018; public static final int REGLE_UTILISATEUR_RUE_ERREUR=20019; public static final int REGLE_UTILISATEUR_CODE_POSTAL_NULL=20020; public static final int REGLE_UTILISATEUR_CODE_POSTAL_ERREUR=20021; public static final int REGLE_UTILISATEUR_VILLE_NULL=20022; public static final int REGLE_UTILISATEUR_VILLE_ERREUR=20023; public static final int REGLE_UTILISATEUR_MOT_DE_PASSE_NULL=20024; public static final int REGLE_UTILISATEUR_MOT_DE_PASSE_ERREUR=20025; public static final int REGLE_UTILISATEUR_MOT_DE_PASSE_ERREUR_CONFIRMATION=20026; public static final int REGLE_UTILISATEUR_PSEUDO_ALPHANUMERIQUE=20027; } <file_sep>/src/fr/eni/encheres/bll/UtilisateurManager.java package fr.eni.encheres.bll; import fr.eni.encheres.BusinessException; import fr.eni.encheres.bo.Utilisateur; import fr.eni.encheres.dal.DALException; import fr.eni.encheres.dal.DAOFactory; //import fr.eni.encheres.dal.UserNotFoundException; import fr.eni.encheres.dal.UtilisateurDAO; public class UtilisateurManager { private UtilisateurDAO utilisateurDAO; public UtilisateurManager() { this.utilisateurDAO = DAOFactory.getUtilisateurDAO(); } public Utilisateur seConnecter(String id, String mdp) throws DALException { Utilisateur utilisateur = utilisateurDAO.selectIdentifiant(id, mdp); return utilisateur; } public Utilisateur getUserById(int id) throws DALException { return utilisateurDAO.selectById(id); } public Utilisateur add(Utilisateur utilisateur) throws DALException, BusinessException { BusinessException businessException = new BusinessException(); validation(utilisateur, businessException); if (!businessException.hasErreurs()) { return utilisateurDAO.insert(utilisateur); } else { throw businessException; } } public Utilisateur update(Utilisateur utilisateur) throws DALException, BusinessException { BusinessException businessException = new BusinessException(); this.validation(utilisateur, businessException); if (!businessException.hasErreurs()) { return utilisateurDAO.update(utilisateur); } else { throw businessException; } } public String delete(Utilisateur utilisateur) throws DALException { utilisateurDAO.deleteByUser(utilisateur); return "utilisateur : "+ utilisateur.getNoUtilisateur()+" bien supprimé"; } public String getPseudoVendeur(int id) throws DALException { if (null != utilisateurDAO.selectById(id)) { return utilisateurDAO.selectById(id).getPseudo(); } return null; } private void validation(Utilisateur utilisateur, BusinessException businessException) { System.out.println("test"); if (utilisateur.getPseudo() == null || utilisateur.getPseudo().equals("")) { businessException.ajouterErreur(CodesResultatBLL.REGLE_UTILISATEUR_PSEUDO_NULL, "Le pseudo est obligatoire."); } else { if (utilisateur.getPseudo().length() > 30) { businessException.ajouterErreur(CodesResultatBLL.REGLE_UTILISATEUR_PSEUDO_ERREUR, "Pseudo trop long."); } } if (utilisateur.getNom() == null || utilisateur.getNom().equals("")) { businessException.ajouterErreur(CodesResultatBLL.REGLE_UTILISATEUR_NOM_NULL, "Le nom de l'utilisateur est obligatoire."); } else { if (utilisateur.getNom().length() > 30) { businessException.ajouterErreur(CodesResultatBLL.REGLE_UTILISATEUR_NOM_ERREUR, "Le nom de l'utilisateur est trop long."); } } if (utilisateur.getPrenom() == null || utilisateur.getPrenom().equals("")) { businessException.ajouterErreur(CodesResultatBLL.REGLE_UTILISATEUR_PRENOM_NULL, "Le prénom de l'utilisateur est obligatoire."); } else { if (utilisateur.getPrenom().length() > 30) { businessException.ajouterErreur(CodesResultatBLL.REGLE_UTILISATEUR_PRENOM_ERREUR, "Le prénom de l'utilisateur est trop long."); } } if (utilisateur.getEmail() == null || utilisateur.getEmail().equals("")) { businessException.ajouterErreur(CodesResultatBLL.REGLE_UTILISATEUR_EMAIL_NULL, "L'email de l'utilisateur est obligatoire."); } else { if (utilisateur.getEmail().length() > 20) { businessException.ajouterErreur(CodesResultatBLL.REGLE_UTILISATEUR_EMAIL_ERREUR, "Email trop long."); } } if (utilisateur.getTelephone().length() > 15) { businessException.ajouterErreur(CodesResultatBLL.REGLE_UTILISATEUR_TEL_ERREUR, "Téléphone trop long."); } if (utilisateur.getRue() == null || utilisateur.getRue().equals("")) { businessException.ajouterErreur(CodesResultatBLL.REGLE_UTILISATEUR_RUE_NULL, "La rue est obligatoire."); } else { if (utilisateur.getRue().length() > 30) { businessException.ajouterErreur(CodesResultatBLL.REGLE_UTILISATEUR_RUE_ERREUR, "Le champs rue est trop long."); } } if (utilisateur.getCodePostal() == null || utilisateur.getCodePostal().equals("")) { businessException.ajouterErreur(CodesResultatBLL.REGLE_UTILISATEUR_CODE_POSTAL_NULL, "Le code postal est obligatoire."); } else { if (utilisateur.getCodePostal().length() > 10) { businessException.ajouterErreur(CodesResultatBLL.REGLE_UTILISATEUR_CODE_POSTAL_ERREUR, "Code postal trop long."); } } if (utilisateur.getVille() == null || utilisateur.getVille().equals("")) { businessException.ajouterErreur(CodesResultatBLL.REGLE_UTILISATEUR_VILLE_NULL, "La ville est obligatoire."); } else { if (utilisateur.getVille().length() > 30) { businessException.ajouterErreur(CodesResultatBLL.REGLE_UTILISATEUR_VILLE_ERREUR, "Ville trop long."); } } if (utilisateur.getMotDePasse() == null || utilisateur.getMotDePasse().equals("")) { businessException.ajouterErreur(CodesResultatBLL.REGLE_UTILISATEUR_MOT_DE_PASSE_NULL, "Le mot de passe est obligatoire."); } else { if (utilisateur.getMotDePasse().length() > 30) { businessException.ajouterErreur(CodesResultatBLL.REGLE_UTILISATEUR_MOT_DE_PASSE_ERREUR, "Mot de passe trop long."); } } //Initialisation du crédit de l'utilisateur à 0 utilisateur.setCredit(0); //Verification mot de passe System.out.println(utilisateur.getMotDePasse()); System.out.println(utilisateur.getMotDePasseConfirmation()); if (utilisateur.getMotDePasse() != null && utilisateur.getMotDePasseConfirmation() != null) { if (!utilisateur.getMotDePasse().equals(utilisateur.getMotDePasseConfirmation())) { businessException.ajouterErreur(CodesResultatBLL.REGLE_UTILISATEUR_MOT_DE_PASSE_ERREUR_CONFIRMATION, "Les mots de passe entrés sont differents."); } //Verification du pseudo en caractères alphanumériques if(utilisateur.getPseudo() != null && !utilisateur.getPseudo().matches("^[a-zA-Z0-9]*$")) { businessException.ajouterErreur(CodesResultatBLL.REGLE_UTILISATEUR_PSEUDO_ALPHANUMERIQUE, "Le pseudo doit uniquement contenir des caractères alphanumériques ((A à Z) (0 à 9)"); } } } } <file_sep>/src/fr/eni/encheres/dal/EnchereDAO.java package fr.eni.encheres.dal; import fr.eni.encheres.bo.Enchere; public interface EnchereDAO extends DAO<Enchere> { }
55be31c477cc1c3c029befe10099090ffaa42488
[ "Markdown", "Java" ]
12
Java
Beater420/Encheres
d80ffdb97a5fe43c0d8d596e684288008e9a3c0e
eaa56aa1f5a084bc6e61e2e8acfb4b01b53c2e9e
refs/heads/master
<file_sep>// ********************************************************************** // // Copyright (c) 2003-2011 ZeroC, Inc. All rights reserved. // // This copy of Ice is licensed to you under the terms described in the // ICE_LICENSE file included in this distribution. // // ********************************************************************** // // Ice version 3.4.2 // // <auto-generated> // // Generated from file `ForumPrx.java' // // Warning: do not edit this file. // // </auto-generated> // package TP1; public interface ForumPrx extends Ice.ObjectPrx { public String getTheme(); public String getTheme(java.util.Map<String, String> __ctx); public Ice.AsyncResult begin_getTheme(); public Ice.AsyncResult begin_getTheme(java.util.Map<String, String> __ctx); public Ice.AsyncResult begin_getTheme(Ice.Callback __cb); public Ice.AsyncResult begin_getTheme(java.util.Map<String, String> __ctx, Ice.Callback __cb); public Ice.AsyncResult begin_getTheme(Callback_Forum_getTheme __cb); public Ice.AsyncResult begin_getTheme(java.util.Map<String, String> __ctx, Callback_Forum_getTheme __cb); public String end_getTheme(Ice.AsyncResult __result); public String getModerator(); public String getModerator(java.util.Map<String, String> __ctx); public Ice.AsyncResult begin_getModerator(); public Ice.AsyncResult begin_getModerator(java.util.Map<String, String> __ctx); public Ice.AsyncResult begin_getModerator(Ice.Callback __cb); public Ice.AsyncResult begin_getModerator(java.util.Map<String, String> __ctx, Ice.Callback __cb); public Ice.AsyncResult begin_getModerator(Callback_Forum_getModerator __cb); public Ice.AsyncResult begin_getModerator(java.util.Map<String, String> __ctx, Callback_Forum_getModerator __cb); public String end_getModerator(Ice.AsyncResult __result); public void postMessage(Message m) throws Reject; public void postMessage(Message m, java.util.Map<String, String> __ctx) throws Reject; public Ice.AsyncResult begin_postMessage(Message m); public Ice.AsyncResult begin_postMessage(Message m, java.util.Map<String, String> __ctx); public Ice.AsyncResult begin_postMessage(Message m, Ice.Callback __cb); public Ice.AsyncResult begin_postMessage(Message m, java.util.Map<String, String> __ctx, Ice.Callback __cb); public Ice.AsyncResult begin_postMessage(Message m, Callback_Forum_postMessage __cb); public Ice.AsyncResult begin_postMessage(Message m, java.util.Map<String, String> __ctx, Callback_Forum_postMessage __cb); public void end_postMessage(Ice.AsyncResult __result) throws Reject; public Message getMessage(String title) throws Reject; public Message getMessage(String title, java.util.Map<String, String> __ctx) throws Reject; public Ice.AsyncResult begin_getMessage(String title); public Ice.AsyncResult begin_getMessage(String title, java.util.Map<String, String> __ctx); public Ice.AsyncResult begin_getMessage(String title, Ice.Callback __cb); public Ice.AsyncResult begin_getMessage(String title, java.util.Map<String, String> __ctx, Ice.Callback __cb); public Ice.AsyncResult begin_getMessage(String title, Callback_Forum_getMessage __cb); public Ice.AsyncResult begin_getMessage(String title, java.util.Map<String, String> __ctx, Callback_Forum_getMessage __cb); public Message end_getMessage(Ice.AsyncResult __result) throws Reject; public void removeMessage(String title) throws Reject; public void removeMessage(String title, java.util.Map<String, String> __ctx) throws Reject; public Ice.AsyncResult begin_removeMessage(String title); public Ice.AsyncResult begin_removeMessage(String title, java.util.Map<String, String> __ctx); public Ice.AsyncResult begin_removeMessage(String title, Ice.Callback __cb); public Ice.AsyncResult begin_removeMessage(String title, java.util.Map<String, String> __ctx, Ice.Callback __cb); public Ice.AsyncResult begin_removeMessage(String title, Callback_Forum_removeMessage __cb); public Ice.AsyncResult begin_removeMessage(String title, java.util.Map<String, String> __ctx, Callback_Forum_removeMessage __cb); public void end_removeMessage(Ice.AsyncResult __result) throws Reject; public Message[] getMessages(); public Message[] getMessages(java.util.Map<String, String> __ctx); public Ice.AsyncResult begin_getMessages(); public Ice.AsyncResult begin_getMessages(java.util.Map<String, String> __ctx); public Ice.AsyncResult begin_getMessages(Ice.Callback __cb); public Ice.AsyncResult begin_getMessages(java.util.Map<String, String> __ctx, Ice.Callback __cb); public Ice.AsyncResult begin_getMessages(Callback_Forum_getMessages __cb); public Ice.AsyncResult begin_getMessages(java.util.Map<String, String> __ctx, Callback_Forum_getMessages __cb); public Message[] end_getMessages(Ice.AsyncResult __result); public void getInfo(Ice.StringHolder theme, Ice.StringHolder moderator, Ice.LongHolder size); public void getInfo(Ice.StringHolder theme, Ice.StringHolder moderator, Ice.LongHolder size, java.util.Map<String, String> __ctx); public Ice.AsyncResult begin_getInfo(); public Ice.AsyncResult begin_getInfo(java.util.Map<String, String> __ctx); public Ice.AsyncResult begin_getInfo(Ice.Callback __cb); public Ice.AsyncResult begin_getInfo(java.util.Map<String, String> __ctx, Ice.Callback __cb); public Ice.AsyncResult begin_getInfo(Callback_Forum_getInfo __cb); public Ice.AsyncResult begin_getInfo(java.util.Map<String, String> __ctx, Callback_Forum_getInfo __cb); public void end_getInfo(Ice.StringHolder theme, Ice.StringHolder moderator, Ice.LongHolder size, Ice.AsyncResult __result); } <file_sep>// ********************************************************************** // // Copyright (c) 2003-2011 ZeroC, Inc. All rights reserved. // // This copy of Ice is licensed to you under the terms described in the // ICE_LICENSE file included in this distribution. // // ********************************************************************** // // Ice version 3.4.2 // // <auto-generated> // // Generated from file `Message.java' // // Warning: do not edit this file. // // </auto-generated> // package TP1; public class Message implements java.lang.Cloneable, java.io.Serializable { public String title; public String author; public String date; public String body; public Message() { } public Message(String title, String author, String date, String body) { this.title = title; this.author = author; this.date = date; this.body = body; } public boolean equals(java.lang.Object rhs) { if(this == rhs) { return true; } Message _r = null; try { _r = (Message)rhs; } catch(ClassCastException ex) { } if(_r != null) { if(title != _r.title) { if(title == null || _r.title == null || !title.equals(_r.title)) { return false; } } if(author != _r.author) { if(author == null || _r.author == null || !author.equals(_r.author)) { return false; } } if(date != _r.date) { if(date == null || _r.date == null || !date.equals(_r.date)) { return false; } } if(body != _r.body) { if(body == null || _r.body == null || !body.equals(_r.body)) { return false; } } return true; } return false; } public int hashCode() { int __h = 0; if(title != null) { __h = 5 * __h + title.hashCode(); } if(author != null) { __h = 5 * __h + author.hashCode(); } if(date != null) { __h = 5 * __h + date.hashCode(); } if(body != null) { __h = 5 * __h + body.hashCode(); } return __h; } public java.lang.Object clone() { java.lang.Object o = null; try { o = super.clone(); } catch(CloneNotSupportedException ex) { assert false; // impossible } return o; } public void __write(IceInternal.BasicStream __os) { __os.writeString(title); __os.writeString(author); __os.writeString(date); __os.writeString(body); } public void __read(IceInternal.BasicStream __is) { title = __is.readString(); author = __is.readString(); date = __is.readString(); body = __is.readString(); } } <file_sep>// ********************************************************************** // // Copyright (c) 2003-2011 ZeroC, Inc. All rights reserved. // // This copy of Ice is licensed to you under the terms described in the // ICE_LICENSE file included in this distribution. // // ********************************************************************** // // Ice version 3.4.2 // // <auto-generated> // // Generated from file `_ForumOperationsNC.java' // // Warning: do not edit this file. // // </auto-generated> // package TP1; public interface _ForumOperationsNC { String getTheme(); String getModerator(); void postMessage(Message m) throws Reject; Message getMessage(String title) throws Reject; void removeMessage(String title) throws Reject; Message[] getMessages(); void getInfo(Ice.StringHolder theme, Ice.StringHolder moderator, Ice.LongHolder size); } <file_sep>package TP1; import Ice.LongHolder; import Ice.StringHolder; public class Client { public static void main(String[] args) { int status = 0; Ice.Communicator ic = null; try { ic = Ice.Util.initialize(args); Ice.ObjectPrx base = ic.stringToProxy("Forum:default -p 10003"); ForumPrx forum = ForumPrxHelper.checkedCast(base); if (forum == null) throw new Error("Invalid proxy"); Message m = new Message("CORBA","moi","10/01/2008","ça marche!"); Message m2 = new Message("mes2","moi","10/01/2009","ok!"); forum.postMessage(m); forum.postMessage(m2); Message tmp = forum.getMessage("CORBA"); if(tmp!=null){ System.out.println("Titre : " + tmp.title); System.out.println("Auteur : " + tmp.author); System.out.println("Message : " + tmp.body); } System.out.println("--------------------------"); Message[] ms=forum.getMessages(); for(Message m3: ms){ System.out.println(); System.out.println("Titre : " + m3.title); System.out.println("Auteur : " + m3.author); System.out.println("Message : " + m3.body); } System.out.println("--------------------------"); StringHolder themeHolder = new StringHolder(); StringHolder moderatorHolder = new StringHolder(); LongHolder sizeHolder = new LongHolder(); forum.getInfo(themeHolder,moderatorHolder,sizeHolder); System.out.println("Theme : " + themeHolder.value); System.out.println("Modérateur : " + moderatorHolder.value); System.out.println("Nombre de messages : " + sizeHolder.value); } catch (Ice.LocalException e) { e.printStackTrace(); status = 1; } catch (Exception e) { System.err.println(e.getMessage()); status = 1; } if (ic != null) { // Clean up // try { ic.destroy(); } catch (Exception e) { System.err.println(e.getMessage()); status = 1; } } System.exit(status); } } <file_sep>// ********************************************************************** // // Copyright (c) 2003-2011 ZeroC, Inc. All rights reserved. // // This copy of Ice is licensed to you under the terms described in the // ICE_LICENSE file included in this distribution. // // ********************************************************************** // // Ice version 3.4.2 // // <auto-generated> // // Generated from file `Forum.java' // // Warning: do not edit this file. // // </auto-generated> // package TP1; public interface Forum extends Ice.Object, _ForumOperations, _ForumOperationsNC { }
51c6c82fda8eec93b474a8838c04700e57a9e8bd
[ "Java" ]
5
Java
karineS/ice
dcbc413609ccadf940232d2f696957cabdbec48b
23513097a7364fb4ea21b7c437c62b0a25c1d7f3
refs/heads/master
<repo_name>istepaniuk/xkcd-substitutions<file_sep>/xkcd-substitutions.user.js // ==UserScript== // @name xkcd-substitutions // @namespace istepaniuk.com // @description SUBSTITUTIONS That make reading the news more fun. (http://xkcd.com/1288/ & https://xkcd.com/1625/ & http://xkcd.com/1679/) // @include http://www.bbc.co.uk/* // @include http://www.bbc.com/* // @include http://www.cbc.ca/* // @include http://www.theguardian.com/* // @include http://www.telegraph.co.uk/* // @include http://www.theonion.com/* // @include http://www.foxnews.com/* // @include https://www.reddit.com/* // @include https://www.washingtonpost.com/* // @version 2 // @grant none // ==/UserScript== (function() { var substitutions, textNodes, regexps = {}; substitutions = { "allegedly": "kinda probably", "ancient": "haunted", "anti-terror": "freedom", "an unknown number": "like hundreds", "at large": "very large", "behind the headlines": "beyond the grave", "candidate": "airbender", "car": "cat", "cautiously optimistic": "delusional", "congressional leaders": "river spirits", "could not be reached for comment": "is guilty and everyone knows it", "debate": "dance-off", "disrupt": "destroy", "doctor who": "the big bang theory", "drone": "dog", "election": "eating contest", "electric": "atomic", "email": "poem", "expands": "physically expands", "facebook ceo": "this guy", "facebook post": "poem", "first-degree": "friggin' awful", "front runner": "blade runner", "gaffe": "magic spell", "global": "spherical", "google glass": "Virtual Boy", "guerrilla": "gorilla", "homeland security": "homestar runner", "horsepower": "tons of horsemeat", "killed": "smashed to bits", "latest": "final", "meeting": "channing tatum and his friends", "meeting": "ménage à trois", "migrant": "slave", "minutes": "years", "new study": "Tumblr post", "no indication": "lots of signs", "poll": "psychic reading", "rebuild": "avenge", "refugee": "rapist pig", "remains to be seen": "will never be known", "scientists": "channing tatum and his friends", "second-degree": "friggin' awful", "self driving": "uncontrollably swerving", "senator": "elf-lord", "silver bullet": "way to kill werewolves", "smartphone": "Pokédex", "space": "spaaace", "star-studded": "blood-soaked", "subway system": "tunnels I found", "successfully": "suddenly", "surprising": "surprising (but not to me)", "tension": "sexual tension", "terror": "freedom", "terrorism": "freedom", "terrorist": "clown", "third-degree": "friggin' awful", "tweet": "poem", "urged restraint by": "drunkenly egged on", "verify": "lie about", "vows to": "probably won't", "war of words": "interplanetary war", "win votes": "find pokemon", "witnesses": "these dudes I know", "years": "minutes", "you won't believe": "I'm really sad about" } for (var key in substitutions) { regexps[key] = new RegExp(key, 'gi'); } textNodes = document.evaluate("//text()", document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null); for (var i = 0; i < textNodes.snapshotLength; i++) { var node = textNodes.snapshotItem(i); node.data = substituteTextIn(node.data); } function substituteTextIn(text) { for (var key in substitutions) { text = text.replace(regexps[key], substitutions[key]); } return text; } })(); <file_sep>/README.md xkcd-substitutions ================== A GreaseMonkey JavaScript implementation of xkcd's "Substitutions that make reading the news more fun" * http://xkcd.com/1288/ * http://xkcd.com/1625/ * http://xkcd.com/1679/ ![xkcd SUBSTITUTIONS](http://imgs.xkcd.com/comics/substitutions.png) ![xkcd SUBSTITUTIONS](http://imgs.xkcd.com/comics/substitutions_2.png) ![xkcd SUBSTITUTIONS](http://imgs.xkcd.com/comics/substitutions_3.png) Using just vanilla JavaScript, it will make your news reading a lot more fun! * 'witnesses' -> 'these dudes I know' * 'allegedgly' -> 'kinda probably' * 'new study' -> 'Tumblr post' * 'rebuild' -> 'avenge' * 'space' -> 'spaaace' * 'google glass' -> 'Virtual Boy' * 'smartphone' -> 'Pokédex' * 'electric' -> 'atomic' * 'senator' -> 'elf-lord' * 'car' -> 'cat' * 'election' -> 'eating contest' * 'congressional leaders' -> 'river spirits' * 'homeland security' -> 'homestar runner' * 'could not be reached for comment' -> 'is guilty and everyone knows it' * See full list on: http://pastebin.com/z6zvSryw (source) Install ======= Just add `xkcd-substitutions.user.js` to your GreaseMonkey user scripts, stir, shake, `roflcopters`. ...Or just click [HERE](https://github.com/istepaniuk/xkcd-substitutions/raw/master/xkcd-substitutions.user.js) to install it (you must have GreaseMonkey for the link to do the trick) The script comes with some included news site, adjust to your prefs!
c105b3a51e53d74e73f836ee6d3b23fe578ecac4
[ "JavaScript", "Markdown" ]
2
JavaScript
istepaniuk/xkcd-substitutions
c9c343130050879a087e8c8f245e9acab8d1d770
7b4ebcafd028597c433c1794a8961f8fcc0b966e
refs/heads/main
<file_sep>import copy import time import typing import warnings import jax import jax._src.util as util import numpy as np from jax import lax, numpy as jnp, random from jax.experimental import PartitionSpec from jax.experimental import pjit from jax.experimental.maps import mesh warnings.filterwarnings("ignore", message=".*is an experimental feature and probably has bugs!.*") # jax.config.update("jax_disable_jit", True) class Dims: def __init__(self, group_linear_factor=2): self.batch = "batch" self.features_per_head = "features_per_head" self.heads = "heads" self.sequence = "sequence" self.intermediate_feed_forward = "intermediate_feed_forward" self.one = "one" self.dim_sizes: typing.Dict[str, int] = {self.batch: 16, self.features_per_head: 16, self.heads: 8, self.sequence: 16, self.one: 1} self.dim_sizes[self.intermediate_feed_forward] = self.dim_sizes[self.features_per_head] * group_linear_factor class Context: def __init__(self, config: typing.Optional[typing.Dict[str, typing.Any]] = None): self.seed = 0 self.prng_key = random.PRNGKey(self.seed) self.learning_rate = -1e-3 self.parameters: typing.Dict[str, jnp.ndarray] = {} self.parameter_dims: typing.Dict[str, typing.List[str]] = {} self.device_steps = 2 ** 1 self.steps = 2 ** 16 self.head_count = 1 self.group_linear_factor = 2 self.depth = 8 self.dtype = jnp.float32 self.init_scale = 1.0 self.global_prefix = '' self.model_parallel = 1 self.data_parallel = 8 self.name_cache: typing.Dict[str, int] = {} self.masked_attention = False self.print_interval = 1 self.dims = Dims() if config is not None: self.__dict__.update(config) def add_to_prefix(self, appended=""): new = copy.copy(self) new.global_prefix = self.global_prefix + '/' + self.incremental_name(appended) return new def incremental_name(self, name): if name not in self.name_cache: self.name_cache[name] = -1 self.name_cache[name] += 1 return f'{name}:{self.name_cache[name]:d}' class WhileContext: def __init__(self, config: typing.Optional[typing.Dict[str, typing.Any]] = None): self.ctx = Context() self.current_step = jnp.zeros([], dtype=jnp.uint32) self.data: typing.Optional[jnp.ndarray] = None self.loss = jnp.zeros([]) if config is not None: self.ctx.parameters = config['parameters'] self.loss = config['loss'] self.current_step = config['current_step'] self.data = config['data'] def serialize(self): return {'parameters': self.ctx.parameters, 'current_step': self.current_step, 'loss': self.loss, 'data': self.data} def dims_to_shape(ctx: Context, dims: typing.List[str]): return [ctx.dims.dim_sizes[d] for d in dims] def dataset(ctx: Context): shape = [ctx.device_steps, 1] dims = ctx.dims shape = shape + dims_to_shape(ctx, [dims.batch, dims.sequence, dims.heads, dims.features_per_head]) normalizer = util.prod(dims_to_shape(ctx, [dims.sequence, dims.heads, dims.features_per_head])) for i in range(ctx.steps): src = random.normal(ctx.prng_key, shape, ctx.dtype) tgt = jnp.cos(src) + src.sum((-1, -2, -3), keepdims=True) tgt = tgt / normalizer yield jnp.concatenate([src, tgt], 1) def shard(tensor: jnp.ndarray, head: typing.Optional[int] = -2, batch: typing.Optional[int] = 0): spec: typing.List[typing.Optional[str]] = [None] * tensor.ndim if isinstance(batch, int): spec[batch] = "data_parallel" if isinstance(head, int): spec[head] = "model_parallel" try: return pjit.with_sharding_constraint(tensor, PartitionSpec(*spec)) except ValueError as e: e_str = str(e) if ("One of with_sharding_constraint arguments was given the resource assignment of PartitionSpec(" in e_str and ", but resource axis " in e_str and "is undefined. Did you forget to declare the mesh?" in e_str): return tensor raise e def orthogonal_init(ctx: Context, shape: typing.List[int], column_axis=-1, ) -> jnp.ndarray: n_rows, n_cols = util.prod(shape) // shape[column_axis], shape[column_axis] matrix_shape = (n_rows, n_cols) if n_rows > n_cols else (n_cols, n_rows) out, r = jnp.linalg.qr(random.normal(ctx.prng_key, matrix_shape, ctx.dtype)) out *= lax.broadcast_to_rank(jnp.sign(jnp.diag(r)), rank=out.ndim) * ctx.init_scale if n_rows < n_cols: out = out.T return jnp.moveaxis(jnp.reshape(out, tuple(np.delete(shape, column_axis)) + (shape[column_axis],)), -1, column_axis) def get_param(ctx: Context, name: str, shape: typing.Optional[typing.List[str]] = None) -> jnp.ndarray: name = ctx.add_to_prefix(name).global_prefix if name not in ctx.parameters: ctx.parameter_dims[name] = shape ctx.parameters[name] = orthogonal_init(ctx, [ctx.dims.dim_sizes[dim] for dim in shape]) return ctx.parameters[name] def base_spec(inp: jnp.ndarray) -> str: return ''.join(chr(ord('a') + i) for i in range(inp.ndim)) def linear(ctx: Context, inp: jnp.ndarray) -> jnp.ndarray: ctx = ctx.add_to_prefix("linear") spec = base_spec(inp) if inp.ndim == 3: shape = [ctx.dims.intermediate_feed_forward, ctx.dims.heads, ctx.dims.features_per_head] spec = f'{spec},{spec[-1]}yz->{spec[:-1]}yz' head_dim = None else: shape = [ctx.dims.heads, ctx.dims.features_per_head, ctx.dims.intermediate_feed_forward] spec = f'{spec},{spec[-2:]}z->{spec[:-2]}z' head_dim = -2 return shard(jnp.einsum(spec, inp, get_param(ctx, "weight", shape)), head_dim) def relu(inp: jnp.ndarray) -> jnp.ndarray: return jnp.maximum(inp, 0) def feed_forward(ctx: Context, inp: jnp.ndarray) -> jnp.ndarray: ctx = ctx.add_to_prefix("feed_forward") return linear(ctx, relu(linear(ctx, inp))) def attention(ctx: Context, inp: jnp.ndarray) -> jnp.ndarray: ctx = ctx.add_to_prefix("attention") base = linear(ctx, inp) qry = linear(ctx, base) key = linear(ctx, base) val = linear(ctx, base) spec = base_spec(qry) anonymous_spec = spec.replace(spec[-2], "z") logit = shard(jnp.einsum(f'{spec},{anonymous_spec}->{spec[:-1]}z', qry, key) / qry.shape[-1]) if ctx.masked_attention: mask = jnp.reshape(jnp.arange(0, qry.shape[-2]), (1, -1)) > jnp.reshape(jnp.arange(0, qry.shape[-2]), (-1, 1)) logit += mask * -1e30 logit = jnp.exp(logit - lax.stop_gradient(logit.max(-1, keepdims=True))) logit /= logit.sum(-1, keepdims=True) return shard(jnp.einsum(f'{anonymous_spec},{spec[:-1]}z->{spec}', val, logit)) def instance_norm(ctx: Context, inp: jnp.ndarray) -> jnp.ndarray: ctx = ctx.add_to_prefix("instance_norm") shape = ["one"] * (inp.ndim - 2) + [ctx.dims.heads, ctx.dims.features_per_head] inp = inp - shard(inp.mean(-1, keepdims=True), None) inp = inp * (lax.rsqrt(shard(jnp.square(inp).sum(-1, keepdims=True), None)) * get_param(ctx, "scale", shape)) return inp + get_param(ctx, "shift", shape) def compute_ctx(ctx: Context, inp: jnp.ndarray) -> jnp.ndarray: src, tgt = inp for _ in range(ctx.depth): src += feed_forward(ctx, instance_norm(ctx, src)) src += attention(ctx, instance_norm(ctx, src)) return jnp.square(src - tgt).mean() def compute(params: typing.Dict[str, jnp.ndarray], inp: jnp.ndarray) -> jnp.ndarray: ctx = Context() ctx.parameters = params return compute_ctx(ctx, inp) def update(ctx: Context, grads: typing.Dict[str, jnp.ndarray]) -> typing.Dict[str, jnp.ndarray]: return {k: p + grads[k] * ctx.learning_rate for k, p in ctx.parameters.items()} def train_step(while_ctx_dict: typing.Dict[str, typing.Any]) -> typing.Dict[str, typing.Any]: wctx = WhileContext(while_ctx_dict) grad_fn = jax.value_and_grad(compute, 0) loss, grads = grad_fn(wctx.ctx.parameters, wctx.data[wctx.current_step % wctx.ctx.device_steps]) wctx.ctx.parameters = update(wctx.ctx, grads) wctx.loss += loss wctx.current_step += 1 return wctx.serialize() def cond_fn(while_ctx_dict: typing.Dict[str, typing.Any]) -> bool: wctx = WhileContext(while_ctx_dict) return jnp.not_equal(jnp.mod(wctx.current_step + 1, wctx.ctx.device_steps), 0) def jitless_step(parameters: typing.Dict[str, jnp.ndarray], data: jnp.ndarray) -> typing.Tuple[ jnp.ndarray, typing.Dict[str, jnp.ndarray]]: wctx = WhileContext() wctx.ctx.parameters = parameters wctx.data = data wctx = WhileContext(lax.while_loop(cond_fn, train_step, wctx.serialize())) return wctx.loss / wctx.ctx.device_steps, wctx.ctx.parameters def sharding(ctx: Context, dims: typing.List[str]): out = [] for d in dims: if d == ctx.dims.batch: out.append("data_parallel") if d == ctx.dims.heads: out.append("model_parallel") else: out.append(None) return PartitionSpec(*out) def main(): ctx = Context() ctx.initializing = True data = dataset(ctx) print("Acquiring parameters and graph.. ", end='', flush=True) start_time = time.time() compute_ctx(ctx, next(data)[0]) print(f"Took {time.time() - start_time:.1f}s") parameters = ctx.parameters print("Compiling model.. ", end='', flush=True) partition = {name: sharding(ctx, dims) for name, dims in ctx.parameter_dims.items()} step = pjit.pjit(jitless_step, in_axis_resources=(partition, PartitionSpec(None, None, "data_parallel", None, None, None)), out_axis_resources=(None, partition)) mesh_devices = np.array(jax.devices()).reshape(ctx.data_parallel, ctx.model_parallel) with mesh(mesh_devices, ('data_parallel', 'model_parallel')): start_time = time.time() step(parameters, next(data)) print(f"Took {time.time() - start_time:.1f}s") print(f"Parameters: {sum(util.prod(param.shape) for name, param in parameters.items())}") start_time = time.time() for idx, dat in enumerate(data): loss, parameters = step(parameters, dat) if idx % ctx.print_interval == 0: print( f'[{idx * ctx.device_steps:{len(str(ctx.steps * ctx.device_steps))}d}/{ctx.steps * ctx.device_steps}]' f' Loss: {loss:6.3f} - Took: {time.time() - start_time:9.6f}s') start_time = time.time() if __name__ == '__main__': main()
ad9e3b24656a35e89dbd708bc9c36fd34dc9679c
[ "Python" ]
1
Python
shawwn/olmax
6899c656ae56e51bca82949137b30860dc1c0e08
78a8d189db1061027d91eaff7e44401e0c16d531
refs/heads/master
<file_sep>/*eslint-env mocha*/ 'use strict'; const assert = require('assert'); const plugin = require('../src/index.js'); function process( text ) { return plugin.processors['.js'].preprocess( text, 'fake.js' )[0]; } describe(`@straits/eslint-plugin`, function(){ it(`works`, function(){ assert.strictEqual( process(` use traits * from ({x = 2}); Object.*yo = Object.keys; Object.*hey = Object.*yo; Object.*hey( Object ); 10.*uhm(); `), ` Object._StraitsProvider = ({x = 2}); Object._Straits.yo = Object.keys; Object._Straits.hey = Object._Straits.yo; Object._Straits.hey( Object ); (10)._Straits.uhm(); ` ); assert.strictEqual( plugin.processors['.js'].postprocess([`hey`, `yo`], `meh`), `hey` ); }); }); <file_sep> 'use strict'; module.exports.processors = { ".js": { preprocess( text, filename ) { text = text .replace( /((?:NaN|Infinity|-?(?:(?:\d+|\d*\.\d+)(?:[Ee][+-]?\d+)?)))\.\*/g, (match, num)=>`(${num}).*` ) .replace( /\.\*/g, `._Straits.` ) .replace( /use\s+traits\s+\*\s+from/mg, `Object._StraitsProvider =` ); return [text]; }, postprocess( messages, filename ) { return messages[0]; } } }; <file_sep> # @straits/eslint-plugin ![npm (scoped)](https://img.shields.io/npm/v/@straits/eslint-plugin.svg?style=popout) ![NpmLicense](https://img.shields.io/npm/l/@straits/eslint-plugin.svg?style=popout) ![David](https://img.shields.io/david/peoro/straits-eslint-plugin.svg?style=popout) ![Travis (.com)](https://img.shields.io/travis/com/peoro/straits-eslint-plugin.svg?style=popout) ![Coveralls github](https://img.shields.io/coveralls/github/peoro/straits-eslint-plugin.svg?style=popout) > ESLint preprocessor for JS files using the straits syntax ## Installation ```bash npm install --save-dev @straits/eslint-plugin ``` ## Usage Add `"@straits/eslint-plugin"` to the `plugins` array in your `.eslintrc.*`: ```json { "plugins": [ "@straits/eslint-plugin" ] } ``` That's it, ESLint will now accept straits-syntax.
01780cb7cbb063435edbce2cd692e05bea49b303
[ "JavaScript", "Markdown" ]
3
JavaScript
straits/eslint-plugin
49907c37104c0a614feafd64417720a7c2bac017
d9223b7ee9d5475dab74a03faf9d9b0783ebe435
refs/heads/main
<repo_name>IvayloRachev/phpcrudimage<file_sep>/edit.php <?php require './db.php'; // recupere la fiche du film $id = $_GET['id']; $sql = "SELECT * FROM film WHERE id = :id"; $statement = $connection->prepare($sql); $statement->execute([':id' => $id]); $film = $statement->FETCH(PDO::FETCH_OBJ); error_reporting(E_ALL); ini_set('display_errors', 1); if ( isset($_POST['titre']) && isset($_POST['annee']) && isset($_FILES['image']) ) { $titre = $_POST['titre']; $annee = $_POST['annee']; // image $file_name = $_FILES['image']['name']; // envoie dans la base de donnees $file_temp = $_FILES['image']['tmp_name']; // pour deplacer les fichiers // variable pour controler l'extension du fichier $allowed_ext = array('jpeg', 'jpg', 'png', 'gif'); //extensions autorisées $exp = explode('.', $file_name); // decomposer le fichier image $ext = end($exp); // prendre le drnier element apres le point $path = "images/" . $file_name; // chemin pour stocker les fichiers if (in_array($ext, $allowed_ext)) { if (move_uploaded_file($file_temp, $path)) { $sql = "INSERT INTO film(titre, annee, image) VALUES (:titre, :annee, :image)"; $statement = $connection->prepare($sql); if ($statement->execute( [ ':titre' => $titre, ':annee' => $annee, ':image' => $path ] )) { print "Ajouté avec succes"; } } } else { echo "Erreur: pas la bonne extension!!!"; } } require './header.php'; ?> <div class="container"> <div class="row"> <div class="col"> <h1>Modifier un film</h1> <form method="post" enctype="multipart/form-data"> <div class="form-group"> <label>Titre</label> <input type="text" class="form-control" name="titre" value="<?=$film->titre ?>"> </div> <div class="form-group"> <label>Date</label> <input type="date" class="form-control" name="annee" value="<?=$film->annee ?>"> </div> <div class="form-group"> <label>Image</label> <img src="<?=$film->image ?>"> <input type="file" class="form-control" name="image"> </div> <button type="submit" class="btn btn-primary">Ajouter</button> </form> </div> </div> </div> <?php require './footer.php'; ?><file_sep>/db.php <?php $dsn = "mysql:host=localhost;dbname=cinema"; $username = "root"; $password = ""; $options = []; $connection = new PDO($dsn, $username, $password, $options); try { // echo "connexion reussie"; } catch(PDOException $e){ print "error :" . $e->getMessage(); die(); }<file_sep>/README.md # phpcrudimage
1663ecbe69a0b9ad9a1901213fb62bdbfff51420
[ "Markdown", "PHP" ]
3
PHP
IvayloRachev/phpcrudimage
9b2b48550004457235ddf8671c3044fb5ea7448d
5e90a37f7d4ab6f1749c69e50225230c72bb3eac
refs/heads/master
<file_sep>HIDDEN_DIM = 256 LEARNING_RATE = 0.01 N_EPOCHS = 30 EMBEDDING_DIM = 16 import torch import torch.nn as nn import torch.optim as optim import random import os class ContentWordsModel(nn.Module): def __init__(self, set_size, cw_set_size, hidden_dim=HIDDEN_DIM): super(ContentWordsModel, self).__init__() self.hidden_dim = hidden_dim self.embedding = nn.Embedding(set_size, EMBEDDING_DIM) self.lstm = nn.LSTM(EMBEDDING_DIM, hidden_dim) self.hidden_layer = nn.Linear(hidden_dim, cw_set_size) self.softmax = nn.LogSoftmax(dim=1) self.hidden = self.init_hidden() def forward(self, inputs): embeds = self.embedding(inputs.view(-1)) lstm_out, self.hidden = self.lstm(embeds.view(len(inputs), 1, -1), self.hidden) hidden_out = self.hidden_layer(lstm_out[-1]) return self.softmax(hidden_out) def init_hidden(self): return (torch.zeros(1, 1, self.hidden_dim), torch.zeros(1, 1, self.hidden_dim)) class ContentWordsTrainer(): def __init__(self, data): self.model = ContentWordsModel(len(data.fillerBOW) + len(data.contentBOW), len(data.contentBOW)) self.data = data self.loss_function = nn.NLLLoss() self.optim = optim.SGD(self.model.parameters(), lr=LEARNING_RATE) if os.path.isfile("lstmstate"): self.model.load_state_dict(torch.load("lstmstate")) def train(self): for i in range(N_EPOCHS): total_loss = 0 dataset = self.data.dataset["train"] random.shuffle(dataset) for joke in dataset: input_seq = torch.tensor(joke["t_openingLine"]).view(-1, 1) input_seq = torch.cat((input_seq, torch.tensor(joke["t_openingLineCWs"]).view(-1, 1)), 0) for token in joke["t_punchlineCWs"]: target = torch.tensor(token).view(-1) loss, predicted = self.trainSequence(input_seq, target) input_seq = torch.cat((input_seq, predicted.view(-1, 1)), 0) total_loss += loss print("Total loss:", total_loss.item()) opening_line, punchline = self.evaluate() print("Opening line:", " ".join(opening_line)) print("Punchline:", " ".join(punchline)) torch.save(self.model.state_dict(), "lstmstate") def trainSequence(self, input_seq, target): self.optim.zero_grad() self.model.hidden = self.model.init_hidden() probs = self.model(input_seq) loss = self.loss_function(probs, target) _, predicted = torch.max(probs, 1) return loss, predicted def evaluate(self): testset = self.data.dataset["test"] rand_i = random.randint(0, len(testset)) opening_line = torch.tensor(testset[rand_i]["t_openingLine"]) opening_cws = torch.tensor(testset[rand_i]["t_openingLineCWs"]) input_seq = torch.cat((opening_line, opening_cws), 0).view(-1, 1) predicted_punchline = testset[rand_i]["t_punchline"] predictedCWs = [] for i in range(len(testset[rand_i]["t_punchlineCWs"])): probs = self.model(input_seq) _, predicted = torch.max(probs, 1) input_seq = torch.cat((input_seq, predicted.view(-1, 1)), 0) predictedCWs.append(predicted.item()) i = 0 sentence = [] for index, token in enumerate(predicted_punchline): if token == self.data.cw_token: contentword = self.data.contentBOW[predictedCWs[i] - 1 - len(self.data.fillerBOW)] sentence.append(contentword) i += 1 else: sentence.append(self.data.fillerBOW[token]) return testset[rand_i]["openingLine"], sentence def predict(self, opening, punchline): punchline_cws = 0 for token in punchline: if token == self.data.cw_token: punchline_cws += 1 input_seq = torch.tensor(opening).view(-1, 1) predictedCWs = [] for i in range(punchline_cws): probs = self.model(input_seq) _, predicted = torch.max(probs, 1) input_seq = torch.cat((input_seq, predicted.view(-1, 1)), 0) predictedCWs.append(predicted.item()) predicted_punchline = [] i = 0 for index, token in enumerate(punchline): if token == self.data.cw_token: predicted_punchline.append(self.data.contentBOW[predictedCWs[i] - 1 - len(self.data.fillerBOW)]) i += 1 else: predicted_punchline.append(self.data.fillerBOW[token]) opening_formatted = [] split = opening.index(self.data.eos_token) opening_template = opening[:split] opening_cws = opening[split+1:] i = 0 for token in opening_template: if token == self.data.cw_token: opening_formatted.append(opening_cws[i]) i += 1 else: opening_formatted.append(token) return " ".join([self.data.allBOW[token] for token in opening_formatted]), " ".join(predicted_punchline) <file_sep># Deep Jokes ## Description Neural network that learns punchlines of jokes given the opening line. ## About Uses (https://github.com/taivop/joke-dataset/) as dataset. <file_sep>### # data.dataset is a list of dictionaries: # { "openingLine": ["what", "do", "you", "call, "an", "CONTENTWORD", "CONTENTWORD","?"], # "openingLineCWs": ["exploding", "dinosaur"], # "t_openingLine": [130, 38, 162, 41, 51, 24376, 24376], # "t_openingLineCWs": [16224, 20394] # "punchline": ["a", "CONTENTWORD"], # "punchlineCWs": ["megasaurus"], # "t_punchline": [13, 24376], # "t_punchlineCWs": [18565], # "score": 56 # } ### HIDDEN_DIM = 256 LEARNING_RATE = 0.01 N_EPOCHS = 30 import torch import torch.nn as nn import torch.optim as optim import random import os import encoderdecoder class Trainer: def __init__(self, data): self.data = data filler_set_size = len(data.fillerBOW) + 1 self.encoder = encoderdecoder.EncoderModel(filler_set_size, HIDDEN_DIM) self.decoder = encoderdecoder.DecoderModel(HIDDEN_DIM, filler_set_size) if os.path.isfile("encoderstate"): self.encoder.load_state_dict(torch.load("encoderstate")) if os.path.isfile("decoderstate"): self.decoder.load_state_dict(torch.load("decoderstate")) self.learning_rate = LEARNING_RATE self.loss_function = nn.NLLLoss() self.encoder_optim = optim.SGD(self.encoder.parameters(), lr=self.learning_rate) self.decoder_optim = optim.SGD(self.decoder.parameters(), lr=self.learning_rate) def train(self, epochs=N_EPOCHS): for i in range(epochs): total_loss = 0 dataset = self.data.dataset["train"] random.shuffle(dataset) for joke in dataset: input_seq = torch.tensor(joke["t_openingLine"]).view(-1, 1) target_seq = torch.tensor(joke["t_punchline"]).view(-1, 1) loss = self.trainSequence(input_seq, target_seq) total_loss += loss print("Total loss:", total_loss) opening_line, punchline = self.evaluate() print("Opening line:", " ".join([self.data.allBOW[token] for token in opening_line])) punchline_words = " ".join([self.data.fillerBOW[token] for token in punchline]) print("Punchline:", punchline_words) torch.save(self.encoder.state_dict(), "encoderstate") torch.save(self.decoder.state_dict(), "decoderstate") def evaluate(self): testset = self.data.dataset["test"] rand_i = random.randint(0, len(testset)) opening_line = torch.tensor(testset[rand_i]["t_openingLine"]) encoder_outputs = torch.zeros(self.data.opening_line_length,self.encoder.hidden_dim) encoder_hidden = torch.zeros(1, 1, self.encoder.hidden_dim) for i in range(opening_line.size(0)): encoder_out, encoder_hidden = self.encoder(opening_line[i], encoder_hidden) encoder_outputs[i] = encoder_out[0, 0] decoder_input = torch.tensor([[self.data.sos_token]]) decoder_hidden = encoder_hidden decoded_tokens = [] for i in range(self.data.punchline_length): decoder_output, decoder_hidden = self.decoder(decoder_input, decoder_hidden) topv, topi = decoder_output.data.topk(1) if topi.item() == self.data.eos_token: decoded_tokens.append(self.data.eos_token) break else: decoded_tokens.append(topi.item()) decoder_input = topi.squeeze().detach() return testset[rand_i]["t_openingLine"] + testset[rand_i]["t_openingLineCWs"], decoded_tokens def trainSequence(self, input_seq, target_seq): self.encoder_optim.zero_grad() self.decoder_optim.zero_grad() encoder_outputs = torch.zeros(self.data.opening_line_length, self.encoder.hidden_dim) encoder_hidden = torch.zeros(1, 1, self.encoder.hidden_dim) loss = 0 for i in range(input_seq.size(0)): encoder_out, encoder_hidden = self.encoder(input_seq[i], encoder_hidden) encoder_outputs = encoder_out[0, 0] decoder_input = torch.tensor([[self.data.sos_token]]) decoder_hidden = encoder_hidden for i in range(target_seq.size(0)): decoder_output, decoder_hidden = self.decoder(decoder_input, decoder_hidden) topv, topi = decoder_output.topk(1) decoder_input = topi.squeeze().detach() loss += self.loss_function(decoder_output, target_seq[i]) if decoder_input.item() == self.data.eos_token: break if loss == 0: print(input_seq, target_seq) loss.backward() self.encoder_optim.step() self.decoder_optim.step() return loss.item() / target_seq.size(0) #should probably get length of non-empty tokens def predict(self, setup=None): if setup is None: return self.evaluate() <file_sep>import operator class DataPrepper: def __init__(self, data, cutoff): self.eos_token = 0 self.cw_token = 1 self.sos_token = 2 self.index = 3 self.opening_line_length = 0 self.punchline_length = 0 self.cutoff = cutoff self.allData = self.cleanup(data) self.createBOW() self.tokenizeData() self.separateData() def createBOW(self): words = {} for joke in self.allData: self.countwords(words, joke["openingLine"]) self.countwords(words, joke["punchline"]) if len(joke["openingLine"]) > self.opening_line_length: self.opening_line_length = len(joke["openingLine"]) if len(joke["punchline"]) > self.punchline_length: self.punchline_length = len(joke["punchline"]) sortedWords = sorted(words.items(), key=operator.itemgetter(1), reverse=True) self.fillerBOW = ["EOS", "CONTENTWORD", "SOS"] for i in range(len(sortedWords)): if sortedWords[i][1] >= self.cutoff: self.fillerBOW.append(sortedWords[i][0]) else: self.contentBOW = [word[0] for word in sortedWords[i:]] break self.allBOW = self.fillerBOW + ["EMPTY"] + self.contentBOW def tokenizeData(self): data = self.allData tokenizedData = [] for joke in data: tokenizedJoke = {} tokenizedJoke["openingLine"] = joke["openingLine"] tokenizedOpeningLine = list(map(lambda x: self.getToken(x), joke["openingLine"])) tokenizedJoke["t_openingLine"], tokenizedJoke["t_openingLineCWs"] = self.separateContentWords(tokenizedOpeningLine) tokenizedJoke["punchline"] = joke["punchline"] tokenizedPunchline = list(map(lambda x: self.getToken(x), joke["punchline"])) tokenizedJoke["t_punchline"], tokenizedJoke["t_punchlineCWs"] = self.separateContentWords(tokenizedPunchline) if len(tokenizedJoke["t_punchline"]) == 0: print(joke) #add EOS tokens tokenizedJoke["t_openingLine"].append(self.eos_token) tokenizedJoke["t_punchline"].append(self.eos_token) tokenizedJoke["t_openingLineCWs"].append(self.eos_token) tokenizedJoke["t_punchlineCWs"].append(self.eos_token) tokenizedJoke["score"] = joke["score"] tokenizedData.append(tokenizedJoke) self.allData = tokenizedData def countwords(self, words, line): max_length = 0 for word in line: if len(word) > max_length: max_length = len(word) if word in words: words[word] = words[word] + 1 else: words[word] = 1 return max_length def cleanup(self, data): cleanedData = [] #Filter out jokes with empty punchline for joke in data: if len(joke["body"].replace(" ", "")) == 0: continue cleanedJoke = {} cleanedJoke["openingLine"] = self.clean(joke["title"]) cleanedJoke["punchline"] = self.clean(joke["body"]) cleanedJoke["score"] = joke["score"] cleanedData.append(cleanedJoke) return cleanedData def clean(self, joke): words = joke.split() words = self.punctuate(words, "?") words = self.punctuate(words, "!") words = self.punctuate(words, ".") words = self.punctuate(words, ",") words = self.punctuate(words, "'s") words = self.punctuate(words, "(") words = self.punctuate(words, ")") words = self.punctuate(words, '"') words = self.punctuate(words, '"') words = list(map(lambda x: x.lower(), words)) return words def punctuate(self, sentence, punctuation): newsentence = [] for word in sentence: if punctuation in word: newword = word.replace(punctuation, "") newsentence.append(newword) newsentence.append(punctuation) else: newsentence.append(word) return newsentence def separateContentWords(self, line): templatedLine = [] contentWords = [] for token in line: if token < len(self.fillerBOW): templatedLine.append(token) else: templatedLine.append(self.cw_token) contentWords.append(token) return templatedLine, contentWords def getToken(self, word): if word in self.fillerBOW: return self.fillerBOW.index(word) return len(self.fillerBOW) + self.contentBOW.index(word) + 1 def getCount(self, word): if word == "EMPTY": return 9001 return self.allBOW[word]["count"] def separateData(self): self.dataset = {} self.dataset["train"] = self.allData[1:8000] self.dataset["test"] = self.allData[20001:] <file_sep>import json class Jsonloader: def __init__(self, minimum_karma): with open("../data/reddit_jokes.json") as infile: self.data = json.load(infile) print("Loaded", len(self.data), "rows of data") #Filter to keep only jokes with one opening line and punchline and format self.data = list(filter(lambda x: 1 < len(x["body"]) < 30, self.data)) #Filter out jokes with karma too low self.data = list(filter(lambda x: x["score"] >= minimum_karma, self.data)) print("Data size after filtering:", len(self.data)) with open("../data/filtered_data.json", "w") as outfile: json.dump(self.data, outfile) <file_sep>import jsonloader import dataprepper import jokemodel import contentwords #Minimum reddit karma for a joke to be included in the dataset MINIMUM_KARMA = 5 #The frequency where a word is considered a content word CUTOFF_FREQUENCY = 100 loader = jsonloader.Jsonloader(MINIMUM_KARMA) data = dataprepper.DataPrepper(loader.data, CUTOFF_FREQUENCY) templatetrainer = jokemodel.Trainer(data) templatetrainer.train() cwtrainer = contentwords.ContentWordsTrainer(data) cwtrainer.train() opening, template = templatetrainer.predict() print(cwtrainer.predict(opening, template)) <file_sep>import torch import torch.nn as nn import torch.nn.functional as F class EncoderModel(nn.Module): def __init__(self, filler_set_size, hidden_dim): super(EncoderModel, self).__init__() self.filler_set_size = filler_set_size self.hidden_dim = hidden_dim self.embedding = nn.Embedding(self.filler_set_size, self.hidden_dim) self.gru = nn.GRU(self.hidden_dim, self.hidden_dim) def forward(self, input_seq, hidden): embeds = self.embedding(input_seq) output = embeds.view(1, 1, -1) output, hidden = self.gru(output, hidden) return output, hidden class DecoderModel(nn.Module): def __init__(self, hidden_dim, filler_set_size): super(DecoderModel, self).__init__() self.hidden_dim = hidden_dim self.embedding = nn.Embedding(filler_set_size, self.hidden_dim) self.gru = nn.GRU(self.hidden_dim, self.hidden_dim) self.out_layer = nn.Linear(self.hidden_dim, filler_set_size) self.softmax = nn.LogSoftmax(dim=1) def forward(self, input, hidden): output = self.embedding(input).view(1, 1, -1) output = F.relu(output) output, hidden = self.gru(output, hidden) output = self.softmax(self.out_layer(output[0])) return output, hidden
a576c04131d1f78f336aa27d61c3e14f47b8bb88
[ "Markdown", "Python" ]
7
Python
iorena/deepjokes
224ca2d6285df69ed469ad5391d514b58162247f
a76cc8bc9351c9f68e55587723fee777aace5cf6
refs/heads/master
<repo_name>fancky2019/CodeGenerate<file_sep>/CodeGenerate/Common.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodeGenerator { public class Common { #region 返回C#实体数据类型 public static string findModelsType(string name) { if (name == "uniqueidentifier") { return "Guid"; } if (name == "int") { return "int"; } else if (name == "smallint") { return "short"; } else if (name == "bigint") { return "long"; } else if (name == "tinyint") { return "byte"; } else if (name == "image") { return "byte[]"; } else if (name == "numeric" || name == "real") { return "Single"; } else if (name == "float") { return "float"; } else if (name == "decimal") { return "decimal"; } else if (name == "char" || name == "varchar" || name == "text" || name == "nchar" || name == "nvarchar" || name == "ntext") { return "string"; } else if (name == "bit") { return "bool"; } else if (name == "datetime" || name == "smalldatetime" || name == "date" || name == "datetime2") { return "DateTime"; } else if (name == "money" || name == "smallmoney") { return "double"; } else if (name == "datetimeoffset") { return "DateTimeOffset"; } else if (name == "timestamp") { return "byte[]"; } else { return "string"; } } #endregion #region 返回数据库类型 public static bool isString(string type) { bool b = false; if (type == "varchar" || type == "char" || type == "nvarchar" || type == "nchar") { b = true; } return b; } #endregion #region 返回C#数据类型 public static string findType(string name) { if (name == "int" || name == "smallint") { return "Convert.ToInt32("; } else if (name == "tinyint") { return "Convert.ToByte("; } else if (name == "numeric" || name == "real" || name == "float") { return "Convert.ToSingle("; } else if (name == "decimal") { return "Convert.ToDecimal("; } else if (name == "char" || name == "varchar" || name == "text" || name == "nchar" || name == "nvarchar" || name == "ntext") { return ".ToString()"; } else if (name == "bit") { return "Convert.ToBoolean("; } else if (name == "datetime" || name == "smalldatetime") { return "Convert.ToDateTime("; } else if (name == "money" || name == "smallmoney") { return "Convert.ToDouble("; } else { return ".ToString()"; } } #endregion #region 转换空格 public static string createplace(int a) { return new string(' ', a); } #endregion #region 首字母大写 public static string fristToUpper(string name) { name = name.Substring(0, 1).ToUpper() + name.Substring(1); return name; } #endregion #region 首字母小写 public static string fristToLower(string name) { name = name.Substring(0, 1).ToLower() + name.Substring(1); return name; } public static string GetIsNullable(string type, bool isNull) { if (type == "bool" || type == "int" || type == "Guid" || type == "short" || type == "long" || type == "DateTime" || type == "double" || type == "decimal" || type == "DateTimeOffset" ) { if (isNull) return "?"; else return ""; } else return ""; } #endregion } } <file_sep>/CodeGenerate/FrmSelectTabel.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace CodeGenerator { public partial class SelectTabelFrm : Form { private List<string> _tableNameList; List<Panel> _listPanel = new List<Panel>(); public List<string> SelectedTableNames { get; set; } public SelectTabelFrm(List<string> tableNameList) { InitializeComponent(); this._tableNameList = tableNameList; SelectedTableNames = new List<string>(); } private void Form2_Load(object sender, EventArgs e) { DisplayTables(this._tableNameList); } private void DisplayTables(List<string> tableNames) { _listPanel.Clear(); this.panelTableNames.Controls.Clear(); this.panel2.Controls.Clear(); //List<string> list = ((Form1)Owner).list; int x = 2; int y = 0; int x1 = 2; int i = 0; int y1 = 12; List<List<string>> tableNamePages = GetChangePage(tableNames, 50); Panel tablesPanel = null; LinkLabel linkLabel = null; CheckBox checkBox = null; foreach (List<string> currentPageNames in tableNamePages) { i++; tablesPanel = new Panel(); if (i == 1) { this.panelTableNames.Controls.Add(tablesPanel); } tablesPanel.Name = "p-" + i; tablesPanel.Tag = i; tablesPanel.Dock = DockStyle.Fill; linkLabel = new LinkLabel(); this.panel2.Controls.Add(linkLabel); linkLabel.Name = "llll" + i; linkLabel.Text = i.ToString(); linkLabel.Left = x1; linkLabel.AutoSize = true; x1 += linkLabel.Width; linkLabel.Top = y1; linkLabel.ForeColor = Color.Black; linkLabel.Width = 7; linkLabel.Click += new EventHandler(pageIndexChange_Click); x1 += linkLabel.Width; x = 2; y = 0; if (i != 0 && i % 25 == 0) { y1 += 15; x1 = 2; } int currentColumnMaxWidth = 0; foreach (string tableName in currentPageNames) { checkBox = new CheckBox(); checkBox.Left = x; checkBox.Top = y; checkBox.Text = tableName; checkBox.Tag = tableName; checkBox.Checked = this.cbSelectAll.Checked; checkBox.AutoSize = true; tablesPanel.Controls.Add(checkBox); currentColumnMaxWidth = currentColumnMaxWidth > checkBox.Width ? currentColumnMaxWidth : checkBox.Width; y += checkBox.Height; //checkBox的高度16,剩余不够16,就换列排 if (y >= this.panelTableNames.Height - 16) { //x += checkBox.Width; x += currentColumnMaxWidth; y = 0; } } _listPanel.Add(tablesPanel); } } void pageIndexChange_Click(object sender, EventArgs e) { panelTableNames.Controls.Clear(); int i = Convert.ToInt32((sender as LinkLabel).Text); Panel pa = new Panel(); if (_listPanel.Count > 0) { pa = _listPanel[i - 1]; } foreach (var control in pa.Controls) { CheckBox checkBox = control as CheckBox; if (checkBox != null) { checkBox.Checked = this.cbSelectAll.Checked; } } panelTableNames.Controls.Add(pa); } private void checkBox1_CheckedChanged(object sender, EventArgs e) { if (this.cbSelectAll.Checked) { for (int i = 0; i < panelTableNames.Controls.Count; i++) { Panel pa = (Panel)panelTableNames.Controls[i]; foreach (Control con in pa.Controls) { if (con is CheckBox) { CheckBox ch = con as CheckBox; ch.Checked = true; } } } } else { for (int i = 0; i < panelTableNames.Controls.Count; i++) { Panel pa = (Panel)panelTableNames.Controls[i]; foreach (Control con in pa.Controls) { if (con is CheckBox) { CheckBox ch = con as CheckBox; ch.Checked = false; } } } } } private void button2_Click(object sender, EventArgs e) { for (int i = 0; i < panelTableNames.Controls.Count; i++) { Panel pa = (Panel)panelTableNames.Controls[i]; foreach (Control con in pa.Controls) { if (con is CheckBox) { CheckBox ch = con as CheckBox; if (ch.Checked) SelectedTableNames.Add(ch.Text); } } } this.Close(); } /// <summary> /// 分页 /// </summary> /// <param name="list"></param> /// <param name="count"></param> /// <returns></returns> public List<List<string>> GetChangePage(List<string> list, int count) { List<List<string>> listBig = new List<List<string>>(); int count1 = list.Count / count; for (int i = 0; i < count1; i++) { List<string> list2 = new List<string>(); for (int j = i * count; j < (i + 1) * count; j++) { list2.Add(list[j]); } listBig.Add(list2); } if (list.Count % count != 0) { List<string> list3 = new List<string>(); for (int i = count1 * count; i < list.Count; i++) { list3.Add(list[i]); } listBig.Add(list3); } return listBig; } private void btnQuery_Click(object sender, EventArgs e) { var result = _tableNameList; if (!string.IsNullOrEmpty(this.txtTableName.Text.Trim())) { result = this._tableNameList.Where(p => p.Contains(this.txtTableName.Text.Trim())).ToList(); } DisplayTables(result); } } } <file_sep>/CodeGenerate/MyGenerator.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Data.SqlClient; using System.Threading; using CodeGenerator; namespace CodeGenerator { public partial class MyGeneratorFrm : Form { string connectstring; //数据库连接字符串 SqlConnection cn; //数据库连接对象 List<ProcedureInfo> list = new List<ProcedureInfo>(); //表对象 public List<string> Allli = new List<string>(); //所有表 private List<string> _selectedTableNames = new List<string>(); //所关联的表 string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); //默认桌面路径 string userId = ""; //用户名 string password = ""; //密码 string database = "master";//数据库 string table = ""; //当前表名 public MyGeneratorFrm() { InitializeComponent(); } #region 连接测试 /// <summary> /// 连接测试 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { groupBox2.Enabled = true; database = textBox1.Text; userId = textBox2.Text; password = textBox3.Text; this.comboBox1.Items.Clear(); string sql = string.Format("select name from sys.databases"); if (checkBox1.Checked) { connectstring = string.Format(" data source={0}; initial catalog=master;integrated security=sspi", database); } else { connectstring = string.Format(" data source={0}; initial catalog=master;user id={1};password={2}", database, userId, password); } cn = new SqlConnection(connectstring); try { cn.Open(); SqlCommand cm = new SqlCommand(sql, cn); using (SqlDataReader dr = cm.ExecuteReader(CommandBehavior.CloseConnection)) { while (dr.Read()) { comboBox1.Items.Add(dr[0].ToString()); Allli.Add(dr[0].ToString()); } } } catch { groupBox2.Enabled = false; MessageBox.Show("用户登录失败(请检查用户名和密码)"); } this.comboBox1.SelectedIndex = this.comboBox1.Items.IndexOf("master"); } #endregion #region 集成验证 private void checkBox1_CheckedChanged(object sender, EventArgs e) { textBox2.Enabled = textBox3.Enabled = !checkBox1.Checked; } #endregion #region 选择表 private void btnSelectTable_Click(object sender, EventArgs e) { cn.Open(); cn.ChangeDatabase(comboBox1.Text); SqlCommand cm = new SqlCommand("select name from sys.Tables", cn); SqlDataReader dr = cm.ExecuteReader(); _selectedTableNames.Clear(); while (dr.Read()) { _selectedTableNames.Add(dr[0].ToString()); } dr.Close(); cn.Close(); SelectTabelFrm selectTabelFrm = new SelectTabelFrm(_selectedTableNames); selectTabelFrm.FormClosing += (s,ee)=> { this._selectedTableNames = selectTabelFrm.SelectedTableNames; }; selectTabelFrm.ShowDialog(); } #endregion #region 选择数据库 private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { database = comboBox1.Text; try { cn.Open(); cn.ChangeDatabase(comboBox1.Text); _selectedTableNames.Clear(); SqlCommand cm = new SqlCommand("select name from sys.Tables", cn); using (SqlDataReader dr = cm.ExecuteReader(CommandBehavior.CloseConnection)) { while (dr.Read()) { _selectedTableNames.Add(dr[0].ToString()); } } } catch { MessageBox.Show("该数据库不可操作 请尝试关闭重试"); cn.Close(); } finally { } } #endregion #region 选择路径 /// <summary> /// 选择生成路径 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, EventArgs e) { FolderBrowserDialog open = new FolderBrowserDialog(); if (open.ShowDialog() == DialogResult.OK) { path = open.SelectedPath; this.textBox4.Text = path; } } #endregion #region 生成 /// <summary> /// 生成 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button4_Click(object sender, EventArgs e) { this.chenggong.Visible = false; this.timer1.Enabled = false; GenerateCode("table"); this.chenggong.Visible = true; this.timer1.Enabled = true; } /// <summary> /// 按sql生成 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button5_Click(object sender, EventArgs e) { _selectedTableNames.Clear(); if (string.IsNullOrEmpty(textBox6.Text)) { MessageBox.Show("请输入SQL查询语句"); return; } if (string.IsNullOrEmpty(textBox5.Text)) { MessageBox.Show("请输入要生成的文件名"); return; } this.chenggong.Visible = false; this.timer1.Enabled = false; GenerateCode("sql"); this.timer1.Enabled = true; } #endregion #region 生成方法 public void GenerateCode(string type) { try { int count = 0; if (checkBox2.Checked) { count++; if (!Directory.Exists(path + @"\ViewModel")) { Directory.CreateDirectory(path + @"\ViewModel"); } } if (checkBox3.Checked) { count++; if (!Directory.Exists(path + @"\ApiModel")) { Directory.CreateDirectory(path + @"\ApiModel"); } } if (checkBox4.Checked) { count++; if (!Directory.Exists(path + @"\DataModel")) { Directory.CreateDirectory(path + @"\DataModel"); } } progressBar1.Value = 0; progressBar1.Minimum = 0; progressBar1.Maximum = _selectedTableNames.Count; if (type != "sql") { foreach (string tablename in _selectedTableNames) { string sql = "SELECT col.name AS 列名, typ.name as 数据类型,col.max_length AS 占用字节数," + " col.is_nullable AS 是否允许非空,col.is_identity AS 是否自增," + " case when exists ( SELECT 1 FROM sys.indexes idx join sys.index_columns idxCol on (idx.object_id = idxCol.object_id)" + " WHERE idx.object_id = col.object_id AND idxCol.index_column_id = col.column_id AND idx.is_primary_key = 1" + " ) THEN 1 ELSE 0 END AS 是否是主键,isnull(g.[value],'') AS 说明 FROM sys.columns col left join sys.types typ on (col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id)" + " left join sys.extended_properties g on (col.object_id = g.major_id AND g.minor_id = col.column_id)" + " WHERE col.object_id =(SELECT object_id FROM sys.tables WHERE name = '" + tablename + "')" + "select t.name as 表名,c.Name as 列名,type1.name as 类型,c.length as 长度,col.is_nullable AS 是否允许非空,col.is_identity AS 是否自增 from sysColumns c,sys.tables t,sys.types type1,sys.columns col where t.name='singertab' and t.object_id = c.id and c.xusertype=type1.user_type_id and col.object_id =(SELECT object_id FROM sys.tables WHERE name = '" + tablename + "')"; list = new List<ProcedureInfo>(); cn.Open(); cn.ChangeDatabase(comboBox1.Text); SqlCommand cm = new SqlCommand(sql, cn); table = tablename.Substring(0, 1).ToUpper() + tablename.Substring(1); using (SqlDataReader dr = cm.ExecuteReader(CommandBehavior.CloseConnection)) { while (dr.Read()) { ProcedureInfo pro = new ProcedureInfo(); pro.Row = (string)dr[0]; pro.Type = (string)dr[1]; pro.Length = Convert.ToInt16(dr[2]); pro.IsNull = Convert.ToBoolean(dr[3]); pro.IsIdentity = Convert.ToBoolean(dr[4]); pro.IsPrimary = Convert.ToBoolean(dr[5]); pro.Comment = (string)dr[6]; list.Add(pro); } } if (checkBox2.Checked) { GenerateViewModel(list); } if (checkBox3.Checked) { GenerateApiModel(list); } if (checkBox4.Checked) { GenerateDataModel(list); } progressBar1.Value++; } } else { progressBar1.Maximum = 1; table = textBox5.Text; var sql = textBox6.Text; var validateResult = ValidateSQL(sql); if (!string.IsNullOrEmpty(validateResult)) { MessageBox.Show(validateResult); return; } list = new List<ProcedureInfo>(); cn.Open(); cn.ChangeDatabase(comboBox1.Text); SqlCommand cm = new SqlCommand(sql, cn); using (SqlDataReader dr = cm.ExecuteReader(CommandBehavior.SchemaOnly)) { var dtSchema = dr.GetSchemaTable(); for (int i = 0; i < dtSchema.Rows.Count; i++) { ProcedureInfo pro = new ProcedureInfo(); pro.Row = dtSchema.Rows[i][0].ToString(); pro.Type = dtSchema.Rows[i][24].ToString(); pro.Length = Convert.ToInt32(dtSchema.Rows[i][2]); pro.IsNull = Convert.ToBoolean(dtSchema.Rows[i][13]); pro.IsIdentity = Convert.ToBoolean(dtSchema.Rows[i][18]); pro.IsPrimary = Convert.ToBoolean(dtSchema.Rows[i][17]); pro.Comment = ""; list.Add(pro); } } cn.Close(); if (checkBox2.Checked) { GenerateViewModel(list); } if (checkBox3.Checked) { GenerateApiModel(list); } if (checkBox4.Checked) { GenerateDataModel(list); } progressBar1.Value++; this.chenggong.Visible = true; } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } #region DataModel private void GenerateDataModel(List<ProcedureInfo> list) { StringBuilder sb = new StringBuilder(); sb.Append("using System;"); sb.Append(Environment.NewLine); sb.Append("using System.Collections.Generic;"); sb.Append(Environment.NewLine); sb.Append("using System.Text;"); sb.Append(Environment.NewLine); sb.Append(Environment.NewLine); sb.Append("namespace "); sb.Append(textBox10.Text); sb.Append(Environment.NewLine); sb.Append("{"); sb.Append(Environment.NewLine); sb.Append(" public class "); sb.Append(table); sb.Append(Environment.NewLine); sb.Append(Common.createplace(4)); sb.Append("{"); sb.Append(Environment.NewLine); foreach (ProcedureInfo pro in list) { string name = pro.Row; string comment = pro.Comment; var type = Common.findModelsType(pro.Type); sb.Append(Common.createplace(8)); sb.Append("/// <summary>"); sb.Append(Environment.NewLine); sb.Append(Common.createplace(8)); sb.Append("/// "); sb.Append(comment); sb.Append(Environment.NewLine); sb.Append(Common.createplace(8)); sb.Append("/// </summary>"); sb.Append(Environment.NewLine); sb.Append(Common.createplace(8)); sb.Append("public"); sb.Append(" "); sb.Append(type); sb.Append(Common.GetIsNullable(type, pro.IsNull)); sb.Append(" "); sb.Append(name.Substring(0, 1).ToUpper() + name.Substring(1)); sb.Append(" { get; set; }"); sb.Append(Environment.NewLine); } sb.Append(Common.createplace(4)); sb.Append("}"); sb.Append(Environment.NewLine); sb.Append("}"); using (var fs = new StreamWriter(new FileStream(path + @"\DataModel\" + table + ".cs", FileMode.Create), Encoding.UTF8)) { fs.AutoFlush = true; fs.Write(sb.ToString()); } } #endregion #region APIModel private void GenerateApiModel(List<ProcedureInfo> list) { StringBuilder sb = new StringBuilder(); sb.Append("using System;"); sb.Append(Environment.NewLine); sb.Append("using System.ComponentModel.DataAnnotations;"); sb.Append(Environment.NewLine); sb.Append("using _5SPower.Framework.Models;"); sb.Append(Environment.NewLine); sb.Append(Environment.NewLine); sb.Append("namespace "); sb.Append(textBox10.Text); sb.Append(Environment.NewLine); sb.Append("{"); sb.Append(Environment.NewLine); sb.Append(" public partial class "); sb.Append(table); sb.Append("Request : HttpApiRequestObject"); sb.Append(Environment.NewLine); sb.Append(Common.createplace(4)); sb.Append("{"); sb.Append(Environment.NewLine); foreach (ProcedureInfo pro in list) { string name = pro.Row; name = name.Substring(0, 1).ToUpper() + name.Substring(1); string comment = pro.Comment; var type = Common.findModelsType(pro.Type); if (!pro.IsNull) { sb.Append(Common.createplace(8)); sb.Append(string.Format("[Required(ErrorMessage = \"{0}是必填项\")]", !string.IsNullOrEmpty(pro.Comment) ? pro.Comment : name)); sb.Append(Environment.NewLine); } sb.Append(Common.createplace(8)); sb.Append(string.Format("[Display(Name = \"{0}\")]", !string.IsNullOrEmpty(pro.Comment) ? pro.Comment : name)); sb.Append(Environment.NewLine); if (type == "string") { if (pro.Length > 0) { if (pro.Type == "nvarchar" && pro.Length != 2147483647) { sb.Append(Common.createplace(8)); sb.Append(string.Format("[StringLength({0}, ErrorMessage = \"最多输入{0}个字符\")]", pro.Length / 2)); sb.Append(Environment.NewLine); } else if (pro.Type == "varchar") { sb.Append(Common.createplace(8)); sb.Append(string.Format("[StringLength({0}, ErrorMessage = \"最多输入{0}个字符\")]", pro.Length)); sb.Append(Environment.NewLine); } else { } } } else if (type == "int") { sb.Append(Common.createplace(8)); sb.Append("[RegularExpression(\"^[1-9][0-9]*$\", ErrorMessage = \"请输入正整数\")]"); sb.Append(Environment.NewLine); } sb.Append(Common.createplace(8)); sb.Append("public"); sb.Append(" "); sb.Append(type); sb.Append(Common.GetIsNullable(type, pro.IsNull)); sb.Append(" "); sb.Append(name); sb.Append(" { get; set; }"); sb.Append(Environment.NewLine); sb.Append(Environment.NewLine); } sb.Append(Common.createplace(4)); sb.Append("}"); sb.Append(Environment.NewLine); sb.Append("}"); using (var fs = new StreamWriter(new FileStream(path + @"\ApiModel\" + table + "Request.cs", FileMode.Create), Encoding.UTF8)) { fs.AutoFlush = true; fs.Write(sb.ToString()); } StringBuilder sb2 = new StringBuilder(); sb2.Append("using System;"); sb2.Append(Environment.NewLine); sb2.Append("using System.ComponentModel.DataAnnotations;"); sb2.Append(Environment.NewLine); sb2.Append("using _5SPower.Framework.Models;"); sb2.Append(Environment.NewLine); sb2.Append(Environment.NewLine); sb2.Append("namespace "); sb2.Append(textBox10.Text); sb2.Append(Environment.NewLine); sb2.Append("{"); sb2.Append(Environment.NewLine); sb2.Append(" public partial class "); sb2.Append(table); sb2.Append("Response : HttpApiResponseObject"); sb2.Append(Environment.NewLine); sb2.Append(Common.createplace(4)); sb2.Append("{"); sb2.Append(Environment.NewLine); sb2.Append(Common.createplace(4)); sb2.Append("}"); sb2.Append(Environment.NewLine); sb2.Append("}"); using (var fs = new StreamWriter(new FileStream(path + @"\ApiModel\" + table + "Response.cs", FileMode.Create), Encoding.UTF8)) { fs.AutoFlush = true; fs.Write(sb2.ToString()); } } #endregion #region ViewModel private void GenerateViewModel(List<ProcedureInfo> list) { StringBuilder sb = new StringBuilder(); sb.Append("using System;"); sb.Append(Environment.NewLine); sb.Append("using System.Collections.Generic;"); sb.Append(Environment.NewLine); sb.Append("using System.Text;"); sb.Append(Environment.NewLine); sb.Append(Environment.NewLine); sb.Append("namespace "); sb.Append(textBox10.Text); sb.Append(Environment.NewLine); sb.Append("{"); sb.Append(Environment.NewLine); sb.Append(" public class "); sb.Append(table); sb.Append(Environment.NewLine); sb.Append(Common.createplace(4)); sb.Append("{"); sb.Append(Environment.NewLine); foreach (ProcedureInfo pro in list) { string name = pro.Row; string comment = pro.Comment; var type = Common.findModelsType(pro.Type); sb.Append(Common.createplace(8)); sb.Append("/// <summary>"); sb.Append(Environment.NewLine); sb.Append(Common.createplace(8)); sb.Append("/// "); sb.Append(comment); sb.Append(Environment.NewLine); sb.Append(Common.createplace(8)); sb.Append("/// </summary>"); sb.Append(Environment.NewLine); sb.Append(Common.createplace(8)); sb.Append("public"); sb.Append(" "); sb.Append(type); sb.Append(Common.GetIsNullable(type, pro.IsNull)); sb.Append(" "); sb.Append(name.Substring(0, 1).ToUpper() + name.Substring(1)); sb.Append(" { get; set; }"); sb.Append(Environment.NewLine); } sb.Append(Common.createplace(4)); sb.Append("}"); sb.Append(Environment.NewLine); sb.Append("}"); using (var fs = new StreamWriter(new FileStream(path + @"\ViewModel\" + table + ".cs", FileMode.Create), Encoding.UTF8)) { fs.AutoFlush = true; fs.Write(sb.ToString()); } } #endregion #region sql语句检查 public string ValidateSQL(string sql) { string bResult = string.Empty; if (sql.ToUpper().Contains("UPDATE") || sql.ToUpper().Contains("INSERT") || sql.ToUpper().Contains("CREATE") || sql.ToUpper().Contains("DELETE")) return "SQL语句中只能包含查询!"; cn.Open(); SqlCommand cmd = cn.CreateCommand(); cmd.CommandText = "SET PARSEONLY ON"; cmd.ExecuteNonQuery(); try { cmd.CommandText = sql; cmd.ExecuteNonQuery(); } catch (Exception ex) { bResult = "输入的SQL语句不正确!"; } finally { cmd.CommandText = "SET PARSEONLY OFF"; cmd.ExecuteNonQuery(); cn.Close(); } return bResult; } #endregion #endregion #region 窗口关闭和最小化事件 private void pictureBox2_Click(object sender, EventArgs e) { Application.Exit(); } private void pictureBox1_Click(object sender, EventArgs e) { this.WindowState = FormWindowState.Minimized; } private void pictureBox2_MouseEnter(object sender, EventArgs e) { } private void pictureBox2_MouseLeave(object sender, EventArgs e) { } private void pictureBox3_MouseEnter(object sender, EventArgs e) { } private void pictureBox3_MouseLeave(object sender, EventArgs e) { } #endregion private void timer1_Tick(object sender, EventArgs e) { this.chenggong.Visible = false; this.progressBar1.Value = 0; this.timer1.Enabled = false; } } }
6aaa0b456e8e3bd70a8c1dca5c62d061840e616a
[ "C#" ]
3
C#
fancky2019/CodeGenerate
51cd1c31cdd791733230b80ea36ca4957ae1c743
141aa33abe6413b6ef4a620a6659c1e7dcf6579a
refs/heads/master
<repo_name>matth022/metaphor<file_sep>/bench.js 'use strict'; var Bench = require('bench'); var Metaphor = require('.'); var Wreck = require('wreck'); var parse = function parse(document) { // Grab the head var head = document.match(/<head[^>]*>([\s\S]*)<\/head\s*>/); if (!head) { return []; } // Remove scripts var scripts = head[1].split('</script>'); // '<script>a</script>something<script>a</script>' -> ['<script>a', 'something<script>a', ''] var chunks = []; scripts.forEach(function (chunk) { var pos = chunk.indexOf('<script'); if (pos !== -1) { chunk = chunk.slice(0, pos); } chunks.push(chunk); }); // Find meta tags var elements = []; chunks.forEach(function (chunk) { var parts = chunk.split('<meta '); for (var i = 1; i < parts.length; ++i) { elements.push(parts[i].slice(0, parts[i].indexOf('>'))); } }); var tags = []; for (var i = 0; i < elements.length; ++i) { var element = elements[i]; var parsed = element.match(/\s*property\s*=\s*"og:([^":]*)(?:\:([^"]*))?"\s+content\s*=\s*"([^"]*)\s*"/); if (parsed) { tags.push({ key: parsed[1], sub: parsed[2], value: parsed[3] }); } } return tags; }; var document = void 0; exports.compare = { metaphor: function metaphor(done) { Metaphor.parse(document, done); }, custom: function custom(done) { parse(document); return done(); } }; Wreck.get('https://twitter.com/dalmaer/status/726624422237364226', {}, function (ignoreErr1, res, payload) { document = payload.toString(); console.log(Metaphor.parse(document)); parse(document, function (ignoreErr2, tags) { console.log(tags); Bench.runMain(); }); }); <file_sep>/lib/router.js 'use strict'; // Load modules function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Url = require('url'); var Hoek = require('hoek'); // Declare internals var internals = {}; exports = module.exports = internals.Router = function () { function _class() { _classCallCheck(this, _class); this._existing = {}; this._domains = { subs: {} }; } _class.prototype.add = function add(url, node) { // 1 2 3 var parts = url.match(/^https?\:\/\/(?:www\.)?(?:(\*)\.)?([^\/]+)(?:\/(.*))?$/); if (!parts) { return; } var wildcard = !!parts[1]; var domain = parts[2]; var path = parts[3]; var normalized = '' + (wildcard ? '*.' : '') + domain + '/' + path; if (this._existing[normalized]) { return; } this._existing[normalized] = true; var tree = this._domains; var segment = domain.split('.'); for (var i = segment.length - 1; i >= 0; --i) { var part = segment[i]; tree.subs[part] = tree.subs[part] || { subs: {}, paths: [] }; tree = tree.subs[part]; } tree.node = node; tree.wildcard = wildcard; if (!path || path === '*' || path.indexOf('*') === -1) { tree.any = true; } else { var escaped = Hoek.escapeRegex(path); var regex = '^/' + escaped.replace(/\\\*/g, '[^\\/]*') + '$'; tree.paths.push(new RegExp(regex)); } }; _class.prototype.lookup = function lookup(url) { var uri = Url.parse(url); var parts = uri.hostname.split('.'); if (parts[0] === 'www') { parts.splice(0, 1); } var tree = this._domains; for (var i = parts.length - 1; i >= 0; --i) { var part = parts[i]; var segment = tree.subs[part]; if (!segment) { if (i === 0 && tree.wildcard) { break; } return null; } tree = segment; } if (!tree.node) { return null; } if (tree.any) { return tree.node; } for (var _i = 0; _i < tree.paths.length; ++_i) { if (uri.pathname.match(tree.paths[_i])) { return tree.node; } } return null; }; return _class; }();
f4341310ec0346a1d03f307ca0ca635bbcbdd362
[ "JavaScript" ]
2
JavaScript
matth022/metaphor
9a05520926ba63fa6f80698e37219faed5f25fd8
e2c9db1e456587707c08af28cfadbd1dbd0abd7d
refs/heads/master
<repo_name>deepakpa829/EntityFramework-Codes<file_sep>/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DatabaseFATask1 { class Program { static CategorydbEntities dbt = new CategorydbEntities(); static void Main(string[] args) { Insertdata(); //Insertdata1(); Display(); Console.ReadLine(); } public static void Insertdata() { Console.WriteLine("Enter the Category Id"); int Cid1 = int.Parse(Console.ReadLine()); Console.WriteLine("Enter the Category name"); string Cname1 = Console.ReadLine(); var category = new Category { Cid = Cid1, Cname=Cname1 }; dbt.Categories.Add(category); dbt.SaveChanges(); } public static void Display() { Console.WriteLine("All Categories are..."); var Category = dbt.Categories; foreach (var c in Category) { Console.WriteLine("{0}\t{1}", c.Cid, c.Cname); } Console.WriteLine(); Console.WriteLine("All Products are...."); var product = dbt.Products; foreach(var d in product) { Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}", d.Pid, d.Title, d.Price, d.Category.Cid,d.Category.Cname); } } } }
7005c5845be25600bb337aabaf957ea7d7de054b
[ "C#" ]
1
C#
deepakpa829/EntityFramework-Codes
0d50ff24df09fd7009c47317fe0787ab3ef57e02
ae30c30699f6a562e8003a1a6ca4e2141d194c0d
refs/heads/master
<repo_name>Superjisan/qr-squared-rest-api<file_sep>/src/resolvers/index.js import { GraphQLDateTime } from 'graphql-iso-date'; import userResolvers from './user'; import recipeResolvers from './recipe' import ingredientResolvers from "./ingredient"; import itemResolvers from "./item"; import instructionResolvers from "./instruction"; import uomResolvers from "./uom"; const customScalarResolver = { Date: GraphQLDateTime, }; export default [ customScalarResolver, userResolvers, recipeResolvers, ingredientResolvers, itemResolvers, instructionResolvers, uomResolvers ]; <file_sep>/src/schema/item.js import { gql } from 'apollo-server-express'; export default gql` extend type Query { items: [Item!] item(id: ID!): Item! } extend type Mutation { updateItem( id: ID! name: String! type: String ): Item! deleteItem( id: ID! ): Boolean! } type Item { id: ID! name: String! type: String ingredients: [Ingredient!] }`;<file_sep>/src/resolvers/item.js import { combineResolvers } from 'graphql-resolvers'; import { AuthenticationError, UserInputError } from 'apollo-server'; import { isAdmin } from './authorization'; export default { Query: { items: async (parent, args, { models }) => { return await models.Item.findAll(); }, item: async (parent, { id }, { models }) => { return await models.Item.findOne({ where: { id } }); } }, Mutation: { updateItem: combineResolvers( isAdmin, async (parent, { id, name, type }, { models }) => { const itemToUpdate = await models.Item.findOne({ where: { id } }); return await itemToUpdate.update({ id, name, type }); } ), deleteItem: combineResolvers( isAdmin, async (parent, { id }, { models }) => { return await models.Item.destroy({ where: { id } }); } ) }, Item: { ingredients: async (item, args, { models }) => { return await models.Ingredient.findAll({ where: { itemId: item.id } }); } } }; <file_sep>/src/resolvers/recipe.js import { combineResolvers } from 'graphql-resolvers'; import { UserInputError } from 'apollo-server'; import { Op } from 'sequelize'; import { isAuthenticated, isRecipeAuthorOrAdmin } from './authorization'; export default { Query: { recipes: async (parent, args, { models }) => { return await models.Recipe.findAll(); }, recipe: async (parent, { id }, { models }) => { return await models.Recipe.findOne({ where: { id } }); }, recipeSearchByName: async (parent, { name }, { models }) => { return await models.Recipe.findAll({ where: { name: { [Op.iLike]: `%${name}%` } } }); }, myRecipes: combineResolvers( isAuthenticated, async (parent, args, {models, me}) => { return await models.Recipe.findAll({ where: { authorId: me.id } }) } ) }, Mutation: { addRecipe: combineResolvers( isAuthenticated, async (parent, { name }, { models, me }) => { const recipe = await models.Recipe.create( { name, authorId: me.id }, { include: [{ model: models.User, as: 'author' }] } ); if (!recipe) { throw new UserInputError( 'Name is needed to create a recipe' ); } return recipe; } ), updateRecipe: combineResolvers( isRecipeAuthorOrAdmin, async ( parent, { id, name, rating, originUrl, originText, cookingTime, imageUrl }, { models } ) => { const recipeToUpdate = await models.Recipe.findOne({ where: { id } }); let recipeObject = {}; if (name) { recipeObject.name = name; } if (rating) { recipeObject.rating = rating; } if (originUrl || originUrl === "") { recipeObject.originUrl = originUrl; } if (originText || originText === "") { recipeObject.originText = originText; } if (cookingTime || cookingTime === "") { recipeObject.cookingTime = cookingTime; } if (imageUrl || imageUrl === "") { recipeObject.imageUrl = imageUrl } return await recipeToUpdate.update(recipeObject); } ), deleteRecipe: combineResolvers( isRecipeAuthorOrAdmin, async (parent, { id }, { models }) => { return await models.Recipe.destroy({ where: { id } }); } ) }, Recipe: { author: async (recipe, args, { models }) => { return await models.User.findOne({ where: { id: recipe.authorId } }); }, ingredients: async (recipe, args, { models }) => { return await models.Ingredient.findAll({ where: { recipeId: recipe.id }, order: [['id', 'ASC']] }); }, instructions: async (recipe, args, { models }) => { return await models.Instruction.findAll({ where: { recipeId: recipe.id }, order: [['id', 'ASC']] }); } } }; <file_sep>/README.md # Quarantine Recipe Repository This repo is the backend node express server that runs Apollo Server to allow graphql queries on a postgresql db ## Installation * `git clone https://github.com/Superjisan/qr-squared-rest-api.git` * `cd qr-squared-rest-api` * `touch .env` * `npm install` * fill out *.env file* (see below) * start PostgreSQL database (if DB hosted on google cloud, open up proxy connection) * [reference](https://cloud.google.com/sql/docs/mysql/quickstart-proxy-test) * download cloud_sql_proxy: `curl -o cloud_sql_proxy https://dl.google.com/cloudsql/cloud_sql_proxy.darwin.amd64 ` * make it executable `chmod +x cloud_sql_proxy` * Run `./cloud_sql_proxy -instances=<INSTANCE_CONNECTION_NAME>=tcp:5432` * `npm run start-dev` * visit `http://localhost:8000` for GraphQL playground #### .env file After you have created a database and a database user, you can fill out the environment variables in the *server/.env* file. ``` DATABASE_URL=postgres://db_user:db_password@url:5432/qr-squared DATABASE_USER=db_user DATABASE_PASSWORD=db_user_password CLOUD_SQL_CONNECTION_NAME=instance_name SECRET=boomshakalaka ``` The `SECRET` is just a random string for your authentication. Keep all these information secure by adding the *.env* file to your *.gitignore* file. No third-party should have access to this information. ## Deploying to Production - To deploy to Google Cloud, ensure that Google Cloud App Engine is setup properly - And then you can run `npm run deploy` <file_sep>/src/models/instruction.js const instruction = (sequelize, DataTypes) => { const Instruction = sequelize.define('instruction', { text: { type: DataTypes.TEXT, validate: { notEmpty: true, } }, textIngredients: { type: DataTypes.ARRAY(DataTypes.JSON) }, textTimes: { type: DataTypes.ARRAY(DataTypes.JSON) }, category: DataTypes.STRING }); Instruction.associate = models => { Instruction.belongsToMany(models.Ingredient, {through: "InstructionIngredient"} ); Instruction.belongsTo(models.Recipe) }; return Instruction; }; export default instruction; <file_sep>/src/models/recipe.js const recipe = (sequelize, DataTypes) => { const Recipe = sequelize.define('recipe', { name: { type: DataTypes.TEXT, validate: { notEmpty: true, }, }, cookingTime: DataTypes.STRING, category: DataTypes.STRING, notes: { type: DataTypes.ARRAY(DataTypes.TEXT), }, rating: { type: DataTypes.INTEGER, validate: { min: 1, max: 5, }, }, originUrl: DataTypes.STRING, originText: DataTypes.TEXT, imageUrl: DataTypes.STRING }); Recipe.associate = models => { Recipe.belongsTo(models.User, { as: 'author' }); Recipe.hasMany(models.Ingredient); Recipe.hasMany(models.Instruction); }; return Recipe; }; export default recipe; <file_sep>/src/resolvers/authorization.js import { ForbiddenError } from 'apollo-server'; import { combineResolvers, skip } from 'graphql-resolvers'; export const isAuthenticated = (parent, args, { me }) => me ? skip : new ForbiddenError('Not authenticated as user.'); export const isAdmin = combineResolvers( isAuthenticated, (parent, args, { me: { role } }) => role === 'ADMIN' ? skip : new ForbiddenError('Not authorized as admin.') ); export const isRecipeAuthorOrAdmin = combineResolvers( isAuthenticated, (parent, { id, recipeId }, { me, models }) => { return models.Recipe.findOne( { where: { id: recipeId || id } }, { raw: true } ).then((recipe) => { console.log({me, recipe}) if (me.id !== recipe.authorId && me.role !== 'ADMIN') { throw new ForbiddenError('Not authorized to edit recipe'); } return skip; }); } ); <file_sep>/src/schema/instruction.js import { gql } from 'apollo-server-express'; export default gql` extend type Query { instructions: [Instruction!] instruction(id: ID!): Instruction! } extend type Mutation { addInstruction( text: String! textIngredients: [InputTextIngredient] textTimes: [InputTextTime] category: String recipeId: ID! ingredientIds: [ID] ): Instruction! updateInstruction( id: ID! recipeId: ID! text: String! textIngredients: [InputTextIngredient] textTimes: [InputTextTime] category: String ingredientIds: [ID] ): Instruction! deleteInstruction( id: ID! recipeId: ID! ): Boolean! } type Instruction { id: ID! text: String! textTimes: [InstructionTextTime] textIngredients: [InstructionTextIngredient] category: String recipe: Recipe! ingredients: [Ingredient!] } type InstructionTextTime { wordIndex: Int! timeValue: String! } type InstructionTextIngredient { wordIndex: Int! ingredientId: Int! } input InputTextTime { wordIndex: Int timeValue: String! } input InputTextIngredient { wordIndex: Int ingredientId: Int } `;<file_sep>/src/reseed/add-order-index-column.js import 'dotenv/config'; import { DataTypes } from 'sequelize'; import { sequelize } from '../models'; const queryInterface = sequelize.getQueryInterface(); queryInterface.addColumn('recipes', 'imageUrl', { type: DataTypes.STRING }); <file_sep>/src/schema/ingredient.js import { gql } from 'apollo-server-express'; export default gql` extend type Query { ingredients: [Ingredient!] ingredient(id: ID!): Ingredient } extend type Mutation { addIngredient( qty:Float!, itemName: String, itemId: Int, recipeId: Int!, uomId: Int, category: String ): Ingredient! updateIngredient( id: ID! recipeId: ID! qty: Float! itemId: ID itemName: String uomId: ID, category: String ): Ingredient! deleteIngredient( id: ID! recipeId: ID! ): Boolean! } type Ingredient { id: ID! category: String qty: Float! item: Item! recipe: Recipe! instructions: [Instruction!] uom: UOM }`;<file_sep>/src/resolvers/uom.js import { combineResolvers } from 'graphql-resolvers'; import { AuthenticationError, ApolloError } from 'apollo-server'; import { isAuthenticated, isAdmin } from './authorization'; export default { Query: { uoms: async (parent, args, { models }) => { return await models.UOM.findAll(); }, uom: async (parent, { id }, { models }) => { return await models.UOM.findById(id); }, }, Mutation: { addUOM: combineResolvers( isAuthenticated, async (parent, { name, alias }, { models }) => { try { const UOM = { name }; if(alias) { UOM.alias = alias; } return await models.UOM.create(UOM) } catch (err) { throw new ApolloError(err); } } ), deleteUOM: combineResolvers( isAdmin, async (parent, { id }, { models }) => { try { return await models.UOM.destroy({ where: {id} }); } catch (err) { throw new ApolloError(err); } } ), }, }; <file_sep>/src/resolvers/instruction.js import { isEqual, isEmpty } from 'lodash'; import { combineResolvers } from 'graphql-resolvers'; import { Op } from 'sequelize'; import { AuthenticationError, UserInputError, ApolloError, } from 'apollo-server'; import { isAuthenticated, isRecipeAuthorOrAdmin, } from './authorization'; export default { Query: { instructions: async (parent, args, { models }) => { return await models.Instruction.findAll(); }, instruction: async (parent, { id }, { models }) => { return await models.Instruction.findOne({ where: { id } }); }, }, Mutation: { addInstruction: async ( parent, { text, textIngredients, textTimes, category, ingredientIds, recipeId, }, { models } ) => { if (!recipeId) { throw new UserInputError('Need to specify recipeId'); } const instructionObj = { text, recipeId, }; if (textIngredients) { const textIngredientJSONArr = textIngredients.map((elem) => JSON.stringify(elem) ); instructionObj.textIngredients = textIngredientJSONArr; } if (textTimes) { const textTimesJSONArr = textIngredients.map((elem) => JSON.stringify(elem) ); instructionObj.textTimes = textTimesJSONArr; } if (category) { instructionObj.category = category; } const instruction = await models.Instruction.create( instructionObj ); if (!ingredientIds || ingredientIds.length === 0) { return instruction; } else { return models.Ingredient.findAll({ where: { id: { [Op.or]: ingredientIds, }, }, }).then((ingredients) => { return instruction.setIngredients(ingredients).then(() => { return instruction; }); }); } }, updateInstruction: combineResolvers( isRecipeAuthorOrAdmin, async ( parent, { id, text, textIngredients, textTimes, category, ingredientIds, recipeId, }, { models } ) => { try { const instructionToUpdate = await models.Instruction.findOne( { where: { id }, }, { include: [{ model: models.Ingredient }] } ); const instructionObj = { text, recipeId, }; if (textIngredients) { instructionObj.textIngredients = textIngredients; } if (textTimes) { instructionObj.textTimes = textTimes; } if (category || category === '') { instructionObj.category = category; } const instructionUpdatedInstance = await instructionToUpdate.update( instructionObj ); if (!ingredientIds) { return instructionUpdatedInstance; } else { if (isEmpty(ingredientIds)) { return instructionUpdatedInstance .setIngredients([]) .then(() => { return instructionUpdatedInstance; }); } else { return models.Ingredient.findAll({ where: { id: { [Op.or]: ingredientIds, }, }, }).then((ingredients) => { return instructionUpdatedInstance .setIngredients(ingredients) .then(() => { return instructionUpdatedInstance; }); }); } } } catch (err) { throw new ApolloError(err); } } ), deleteInstruction: combineResolvers( isRecipeAuthorOrAdmin, async (parent, { id }, { models }) => { return await models.Instruction.destroy({ where: { id } }); } ), }, Instruction: { recipe: async (instruction, args, { models }) => { return await models.Recipe.findOne({ where: { id: instruction.recipeId, }, }); }, ingredients: async (instruction, args, { models }) => { return await models.Ingredient.findAll({ include: [ { model: models.Instruction, where: { id: instruction.id, }, }, ], }); }, textIngredients: async (instruction, args, { models }) => { try { return await models.Instruction.findOne({ where: { id: instruction.id }, }).then((instructionInstance) => { const { textIngredients } = instruction; return textIngredients; }); } catch (e) { console.error(e); } }, textTimes: async (instruction, args, { models }) => { try { return await models.Instruction.findOne({ where: { id: instruction.id }, }).then((instructionInstance) => { const { textTimes } = instruction; return textTimes; }); } catch (e) { console.error(e); } }, }, }; <file_sep>/src/models/uom.js const uom = (sequelize, DataTypes) => { const UOM = sequelize.define('uom', { name: { type: DataTypes.STRING, unique: true, validate: { notEmpty: true }, }, alias: { type: DataTypes.STRING, }, }); UOM.associate = models => { UOM.hasMany(models.Ingredient, { constraints: false }) } return UOM; }; export default uom; <file_sep>/src/schema/uom.js import { gql } from 'apollo-server-express'; export default gql` extend type Query { uoms: [UOM!] uom(id: ID!): UOM! } extend type Mutation { addUOM(name: String!, alias: String): UOM! deleteUOM(id: ID!): Boolean! } type UOM { id: ID! name: String! alias: String } `;
bdc2292b1c8381ed26cc2e5747bbc4db0a519afd
[ "JavaScript", "Markdown" ]
15
JavaScript
Superjisan/qr-squared-rest-api
7b1284d133ecc7fac46ead8d3f696e65c2f64a07
5e4880ac57964845e3161bd1042125fc34e658b4
refs/heads/master
<repo_name>akshayp604/calvarter<file_sep>/app/src/main/java/com/al/calverter/BaseActivity.java package com.al.calverter; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; public class BaseActivity extends AppCompatActivity { private ListView mDrawerList; private DrawerLayout mDrawerLayout; private ActionBarDrawerToggle mDrawerToggle; private String mActivityTitle; protected void onCreateDrawer(){ mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mActivityTitle = getTitle().toString(); setupDrawer(); //drawer switch on actionbar getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); mDrawerList = (ListView) findViewById(R.id.navList); ArrayAdapter<CharSequence> mAdapter = ArrayAdapter.createFromResource(this, R.array.draweritems, android.R.layout.simple_list_item_1); mDrawerList.setAdapter(mAdapter); mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { switch (position) { case 0: actcal(); break; case 1: actuc(); break; case 2: actbase(); break; case 3: actbmi(); break; case 4: actarea(); break; } } }); }//oncreate end private void setupDrawer() { mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) { /** Called when a drawer has settled in a completely open state. */ public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); getSupportActionBar().setTitle("Navigation!"); invalidateOptionsMenu(); } /** Called when a drawer has settled in a completely closed state. */ public void onDrawerClosed(View view) { super.onDrawerClosed(view); getSupportActionBar().setTitle(mActivityTitle); invalidateOptionsMenu(); } }; mDrawerToggle.setDrawerIndicatorEnabled(true); mDrawerLayout.setDrawerListener(mDrawerToggle); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mDrawerToggle.onConfigurationChanged(newConfig); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); // Activate the navigation drawer toggle if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } public void actuc() { Intent intent = new Intent(this, UnitConverter.class); startActivity(intent); } public void actbase() { Intent intent = new Intent(this, BaseConverter.class); startActivity(intent); } public void actcal() { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } public void actbmi() { Intent intent = new Intent(this, Bmi.class); startActivity(intent); } public void actarea() { Intent intent = new Intent(this, Areas.class); startActivity(intent); } }//end <file_sep>/app/src/main/java/com/al/calverter/BaseConverter.java package com.al.calverter; import android.app.Activity; import android.graphics.pdf.PdfDocument; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.app.AlertDialog.Builder; import android.widget.EditText; import java.util.Stack; public class BaseConverter extends BaseActivity { Button convert,btnCear; EditText dec, bin, oct,hex; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.baseconverter); setTitle("Base Converter"); super.onCreateDrawer(); dec = (EditText) findViewById(R.id.dec); bin = (EditText) findViewById(R.id.bin); oct = (EditText) findViewById(R.id.oct); hex = (EditText) findViewById(R.id.hex); convert = (Button) findViewById(R.id.convert); btnCear = (Button) findViewById(R.id.btnClear); btnCear.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dec.setText(""); bin.setText(""); oct.setText(""); hex.setText(""); } }); convert.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); calculate(2, bin); // for base 2 (binary) calculate(8, oct); // for base 8 (octal) calculate(16, hex); // for base 16 (hexadecimal) } }); } public void calculate(int base, EditText text) { if (dec.getText().toString().trim().length() == 0) { text.setText(""); return; } try { Stack<Object> stack = new Stack<Object>(); int number = Integer.parseInt(dec.getText().toString()); while (number > 0) { int remainder = number % base; // find remainder if (remainder < 10) // for remainder smaller than 10 { stack.push(remainder); // push remainder in stack } else { switch (remainder) // for remainder larger than 9 (for hexadecimal values) { case 10: stack.push("A"); break; case 11: stack.push("B"); break; case 12: stack.push("C"); break; case 13: stack.push("D"); break; case 14: stack.push("E"); break; case 15: stack.push("F"); break; } } number /= base; } StringBuffer buffer = new StringBuffer(); while (!stack.isEmpty()) { buffer.append(stack.pop().toString()); } text.setText(buffer.toString()); } catch (Exception e) { text.setText(e.getMessage()); } } }<file_sep>/app/src/main/java/com/al/calverter/MainActivity.java package com.al.calverter; import android.os.Bundle; import android.view.KeyCharacterMap; import android.view.KeyEvent; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; public class MainActivity extends BaseActivity { Button button0 , button1 , button2 , button3 , button4 , button5 , button6 , button7 , button8 , button9 , buttonAdd , buttonSub , buttonDivision , buttonMul , buttonDec , buttonC , buttonEqual,buttoncal; Button buttonSin,buttonCos,buttonTan,buttonLog,buttonSqr,buttonSqrt,buttonCube,buttonPow,buttonSign,buttonInv,buttonPi,buttonFact,buttonHalf,buttonQuar,buttonTquar,btnsci; ImageButton buttondel; EditText edt1; TextView eqn; LinearLayout layoutsci,layoutcal,bar,bar2; boolean hasBackKey; boolean hasHomeKey; double num1=0 , num2=0 ,result=0,fact=1; int i=0; String op; String eqnf,eqnt=""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK); hasHomeKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_HOME); if (hasBackKey && hasHomeKey) { // no navigation bar setContentView(R.layout.activity_main); } else { // there's a navigation bar setContentView(R.layout.activity_main_bar); } setTitle("Calculator"); super.onCreateDrawer(); // Disable IME for this application getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); button0 = (Button) findViewById(R.id.button0); button1 = (Button) findViewById(R.id.button1); button2 = (Button) findViewById(R.id.button2); button3 = (Button) findViewById(R.id.button3); button4 = (Button) findViewById(R.id.button4); button5 = (Button) findViewById(R.id.button5); button6 = (Button) findViewById(R.id.button6); button7 = (Button) findViewById(R.id.button7); button8 = (Button) findViewById(R.id.button8); button9 = (Button) findViewById(R.id.button9); buttonDec = (Button) findViewById(R.id.buttonDec); buttonAdd = (Button) findViewById(R.id.buttonadd); buttonSub = (Button) findViewById(R.id.buttonsub); buttonMul = (Button) findViewById(R.id.buttonmul); buttonDivision = (Button) findViewById(R.id.buttondiv); buttonSin = (Button) findViewById(R.id.buttonSin); buttonCos = (Button) findViewById(R.id.buttonCos); buttonTan = (Button) findViewById(R.id.buttonTan); buttonLog = (Button) findViewById(R.id.buttonLog); buttonSqr = (Button) findViewById(R.id.buttonSqr); buttonSqrt = (Button) findViewById(R.id.buttonSqrt); buttonCube = (Button) findViewById(R.id.buttonCube); buttonPow = (Button) findViewById(R.id.buttonPow); buttonSign = (Button) findViewById(R.id.buttonSign); buttonInv = (Button) findViewById(R.id.buttonInv); buttonPi = (Button) findViewById(R.id.buttonPi); buttonFact = (Button) findViewById(R.id.buttonFact); buttonHalf = (Button) findViewById(R.id.buttonHalf); buttonQuar = (Button) findViewById(R.id.buttonnQuar); buttonTquar = (Button) findViewById(R.id.buttonnTquar); buttonC = (Button) findViewById(R.id.buttonC); buttonEqual = (Button) findViewById(R.id.buttoneql); buttondel = (ImageButton) findViewById(R.id.buttondel); btnsci=(Button) findViewById(R.id.buttonsci); buttoncal=(Button) findViewById(R.id.buttoncal); edt1 = (EditText) findViewById(R.id.edt1); eqn = (TextView) findViewById(R.id.eqn); layoutcal = (LinearLayout) findViewById(R.id.Layoutcal); layoutsci = (LinearLayout) findViewById(R.id.Layoutsci); bar = (LinearLayout) findViewById(R.id.bar); bar2 = (LinearLayout) findViewById(R.id.bar2); button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { edt1.setText(edt1.getText() + "1"); } }); button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { edt1.setText(edt1.getText() + "2"); } }); button3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { edt1.setText(edt1.getText() + "3"); } }); button4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { edt1.setText(edt1.getText() + "4"); } }); button5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { edt1.setText(edt1.getText() + "5"); } }); button6.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { edt1.setText(edt1.getText() + "6"); } }); button7.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { edt1.setText(edt1.getText() + "7"); } }); button8.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { edt1.setText(edt1.getText() + "8"); } }); button9.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { edt1.setText(edt1.getText() + "9"); } }); button0.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { edt1.setText(edt1.getText() + "0"); } }); buttonAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (edt1 == null) { edt1.setText(null); } else { try { eqn.setText(eqnt + edt1.getText() + "+"); eqnf = eqn.getText().toString(); num1 = Double.parseDouble(edt1.getText().toString()); } catch (NumberFormatException ex) { eqn.setText("Enter operand first"); } op="add"; edt1.setText(null); } } }); buttonSub.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (edt1 == null) { edt1.setText(null); } else { try { eqn.setText(eqnt + edt1.getText() + "-"); eqnf = eqn.getText().toString(); num1 = Double.parseDouble(edt1.getText().toString()); } catch (NumberFormatException ex) { eqn.setText("Enter operand first"); } op="sub"; edt1.setText(null); } } }); buttonMul.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (edt1 == null) { edt1.setText(null); } else { try { eqn.setText(eqnt + edt1.getText() + "*"); eqnf = eqn.getText().toString(); num1 = Double.parseDouble(edt1.getText() + ""); } catch (NumberFormatException ex) { eqn.setText("Enter operand first"); } op="mul"; edt1.setText(null); }} }); buttonDivision.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (edt1 == null) { edt1.setText(null); } else { try { eqn.setText(eqnt + edt1.getText() + "/"); eqnf = eqn.getText().toString(); num1 = Double.parseDouble(edt1.getText() + ""); } catch (NumberFormatException ex) { eqn.setText("Enter operand first"); } op="div"; edt1.setText(null); }} }); //buttonSin,buttonCos,buttonTan,buttonLog,buttonSqr,buttonSqrt,buttonCube,buttonPowy,buttonSign,buttonInv,buttonPi,buttonFact; buttonSin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (edt1 == null) { edt1.setText(null); } else { try { eqn.setText(eqnt + edt1.getText() + "Sin="); eqnf = eqn.getText().toString(); num1 = Double.parseDouble(edt1.getText() + ""); } catch (NumberFormatException ex) { eqn.setText("Enter operand first"); } op="sin"; edt1.setText(null); dcalculate(); }} }); buttonCos.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (edt1 == null) { edt1.setText(null); } else { try { eqn.setText(eqnt + edt1.getText() + "Cos="); eqnf = eqn.getText().toString(); num1 = Double.parseDouble(edt1.getText() + ""); } catch (NumberFormatException ex) { eqn.setText("Enter operand first"); } op="cos"; edt1.setText(null); dcalculate(); }} }); buttonTan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (edt1 == null) { edt1.setText(null); } else { try { eqn.setText(eqnt + edt1.getText() + "Tan="); eqnf = eqn.getText().toString(); num1 = Double.parseDouble(edt1.getText() + ""); } catch (NumberFormatException ex) { eqn.setText("Enter operand first"); } op="tan"; edt1.setText(null); dcalculate(); }} }); buttonLog.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (edt1 == null) { edt1.setText(null); } else { try { eqn.setText(eqnt + edt1.getText() + "Log="); eqnf = eqn.getText().toString(); num1 = Double.parseDouble(edt1.getText() + ""); } catch (NumberFormatException ex) { eqn.setText("Enter operand first"); } op="log"; edt1.setText(null); dcalculate(); }} }); buttonSqr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (edt1 == null) { edt1.setText(null); } else { try { eqn.setText(eqnt + edt1.getText() + "²="); eqnf = eqn.getText().toString(); num1 = Double.parseDouble(edt1.getText() + ""); } catch (NumberFormatException ex) { eqn.setText("Enter operand first"); } op="sqr"; edt1.setText(null); dcalculate(); }} }); buttonSqrt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (edt1 == null) { edt1.setText(null); } else { try { eqn.setText("√"+eqnt + edt1.getText() + "="); eqnf = eqn.getText().toString(); num1 = Double.parseDouble(edt1.getText() + ""); } catch (NumberFormatException ex) { eqn.setText("Enter operand first"); } op="sqrt"; edt1.setText(null); dcalculate(); }} }); buttonCube.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (edt1 == null) { edt1.setText(null); } else { try { eqn.setText(eqnt + edt1.getText() + "³="); eqnf = eqn.getText().toString(); num1 = Double.parseDouble(edt1.getText() + ""); } catch (NumberFormatException ex) { eqn.setText("Enter operand first"); } op="cube"; edt1.setText(null); dcalculate(); }} }); buttonPow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (edt1 == null) { edt1.setText(null); } else { try { eqn.setText(eqnt + edt1.getText() + ""); eqnf = eqn.getText().toString(); num1 = Double.parseDouble(edt1.getText() + ""); } catch (NumberFormatException ex) { eqn.setText("Enter operand first"); } op="pow"; edt1.setText(null);; }} }); buttonInv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (edt1 == null) { edt1.setText(null); } else { try { eqn.setText("1/" +eqnt + edt1.getText() + "="); eqnf = eqn.getText().toString(); num1 = Double.parseDouble(edt1.getText() + ""); } catch (NumberFormatException ex) { eqn.setText("Enter operand first"); } op="inv"; edt1.setText(null); dcalculate(); }} }); buttonSign.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (edt1 == null) { edt1.setText(null); } else { try { eqn.setText(eqnt + edt1.getText() + "±="); eqnf = eqn.getText().toString(); num1 = Double.parseDouble(edt1.getText() + ""); } catch (NumberFormatException ex) { eqn.setText("Enter operand first"); } op="sign"; edt1.setText(null); dcalculate(); }} }); buttonFact.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (edt1 == null) { edt1.setText(null); } else { try { eqn.setText(eqnt + edt1.getText() + "!="); eqnf = eqn.getText().toString(); num1 = Double.parseDouble(edt1.getText() + ""); } catch (NumberFormatException ex) { eqn.setText("Enter operand first"); } op="fact"; edt1.setText(null); dcalculate(); }} }); buttonHalf.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (edt1 == null) { edt1.setText(null); } else { try { eqn.setText("½("+eqnt + edt1.getText() + ")="); eqnf = eqn.getText().toString(); num1 = Double.parseDouble(edt1.getText() + ""); } catch (NumberFormatException ex) { eqn.setText("Enter operand first"); } op="half"; edt1.setText(null); dcalculate(); }} }); buttonQuar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (edt1 == null) { edt1.setText(null); } else { try { eqn.setText("¼("+eqnt + edt1.getText() + ")="); eqnf = eqn.getText().toString(); num1 = Double.parseDouble(edt1.getText() + ""); } catch (NumberFormatException ex) { eqn.setText("Enter operand first"); } op="quar"; edt1.setText(null); dcalculate(); }} }); buttonTquar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (edt1 == null) { edt1.setText(null); } else { try { eqn.setText("¾("+eqnt + edt1.getText() + ")="); eqnf = eqn.getText().toString(); num1 = Double.parseDouble(edt1.getText() + ""); } catch (NumberFormatException ex) { eqn.setText("Enter operand first"); } op="tquar"; edt1.setText(null); dcalculate(); }} }); buttonPi.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { edt1.setText(edt1.getText() + "3.141592653589793"); } }); btnsci.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { layoutcal.setVisibility(View.GONE); layoutsci.setVisibility(View.VISIBLE); if (!hasBackKey && !hasHomeKey) {//fix fc // no navigation bar bar2.setVisibility(View.VISIBLE); bar.setVisibility(View.GONE); } } }); buttoncal.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { layoutcal.setVisibility(View.VISIBLE); layoutsci.setVisibility(View.GONE); if (!hasBackKey && !hasHomeKey) { // no navigation bar bar.setVisibility(View.VISIBLE); bar2.setVisibility(View.GONE); } } }); buttonEqual.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { calculate(); } catch (NullPointerException ex){ eqn.setText("Enter operands"); } } }); buttonC.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { edt1.setText(""); eqn.setText(""); eqnf = ""; eqnt = ""; num1=num2=result=0; } }); buttondel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (edt1.getText().length() > 1) { String strnew = edt1.getText().toString(); strnew = strnew.substring(0, strnew.length() - 1); edt1.setText(strnew); } else if (edt1.getText().length() == 1) { edt1.setText("0"); } } }); buttonDec.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (edt1.getText().toString().contains(".")) { return; } else if (edt1.getText().length() < 1) { edt1.setText("0."); } else { edt1.setText(edt1.getText() + "."); } } }); } private void calculate() { try { num2 = Double.parseDouble(edt1.getText() + ""); } catch (NumberFormatException ex) { eqn.setText("" + num1); } eqn.setText(eqnf + edt1.getText().toString() + "="); eqnt = eqn.getText().toString(); switch (op) { case "add": result = num1 + num2; break; case "sub": result = num1 - num2; break; case "div": result = num1 / num2; break; case "mul": result = num1 * num2; break; case "pow":result = Math.pow(num1,num2); eqn.setText(num1 + "^" +num2+ "="); break; default: edt1.setText("invalid input"); } num1=result; edt1.setText(""+result); } private void dcalculate() { switch (op) { case "inv": { if (num1 != 0) { num1 = 1 / num1; result=num1; } } break; case "sign": result = -num1; break; case "sin": result = Math.sin(Math.toRadians(num1)); break; case "cos": result = Math.cos(Math.toRadians(num1)); break; case "tan": result = Math.tan(Math.toRadians(num1)); break; case "log": result = Math.log(Math.toRadians(num1)); break; case "sqrt": result = Math.sqrt(num1); break; case "sqr":result = num1*num1 ; break; case "cube":result = num1*num1 * num1; break; case "half":result = 0.5*num1; break; case "quar":result = 0.25*num1; break; case "tquar":result = 0.75*num1; break; case "fact": {for(i=2;i<=num1;i++){ fact=fact*i; } result=fact; fact=1; break;} default: edt1.setText("invalid input"); } num1=result; edt1.setText(""+result); } }<file_sep>/app/src/main/java/com/al/calverter/Bmi.java package com.al.calverter; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class Bmi extends BaseActivity { EditText etKg, etFt; TextView result,desc; Button buttonConvert,btnClear; int min,max; double weight,height,bmi,heightft; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.bmi); setTitle("Body Mass Index"); super.onCreateDrawer(); buttonConvert = (Button) findViewById(R.id.buttonConvert); btnClear = (Button) findViewById(R.id.btnClear); etKg = (EditText) findViewById(R.id.etKg); etFt = (EditText) findViewById(R.id.etFt); result=(TextView)findViewById(R.id.result); desc = (TextView)findViewById(R.id.desc); btnClear.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { etKg.setText(""); etFt.setText(""); result.setText(""); desc.setText(""); } }); buttonConvert.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); try { weight = Double.parseDouble(etKg.getText().toString()); heightft = Double.parseDouble(etFt.getText().toString()); height = heightft/3.28084;//convert ft to m bmi = (weight / (height * height)); result.setText("Your BMI is : "+bmi); calculateNormal(); } catch (NumberFormatException ex) { //to solve fc when input is null } } }); }//endoncreate private void calculateNormal(){ if(heightft==4.6) { min=28; max=35; }else if(heightft==4.7) { min=30; max=37; }else if(heightft==4.8) { min=32; max=40; }else if(heightft==4.9) { min=35; max=42; }else if(heightft==4.10) { min=36; max=45; }else if(heightft==4.11) { min=39; max=47; }else if(heightft==5) { min=40; max=50; }else if(heightft==5.1) { min=43; max=52; }else if(heightft==5.2) { min=45; max=55; }else if(heightft==5.3) { min=47; max=57; }else if(heightft==5.4) { min=49; max=60; }else if(heightft==5.5) { min=51; max=62; }else if(heightft==5.6) { min=53; max=65; }else if(heightft==5.7) { min=55; max=67; }else if(heightft==5.8) { min=57; max=70; }else if(heightft==5.9) { min=59; max=72; }else if(heightft==5.101) {//not fixed issue with 5.1 &5.10 min=61; max=75; }else if(heightft==5.11) { min=63; max=77; }else if(heightft==6) { min=65; max=80; }else if(heightft<4.6||heightft>6){ weight=0; } if (weight < min) { desc.setText("You are UnderWeight. \nYour normal weight should be " + min + "Kg - " + max + "Kg. \nYou should puton atleast " + (min - weight) + "Kgs"); } else if (weight > max) { desc.setText("You are OverWeight. \nYour normal weight should be " + min + "Kg - " + max + "Kg. \nYou should lose atleast " + (weight - max) + "Kgs"); } else if (weight >= min && weight <= max) { desc.setText("Your weight is Normal. \nYour normal weight should be " +min + "Kg - " + max + "Kg.\nYou are physically fit"); } if(weight==0){ result.setText(""); desc.setText("Invalid"); } } }//end
28ceb6cf22678a763944a1c0928f255eedb8b061
[ "Java" ]
4
Java
akshayp604/calvarter
db2446dad16e35b81fd31d886871d6deac7ea2bf
0d32a848f27743a96743bedb0a0cf3f7a28e170c
refs/heads/main
<file_sep>function solve(input) { const listCreator = function() { let list = []; return { add: function(str) { list.push(str); }, remove:function(str) { list = list.filter(x => x!== str); }, print: function () { console.log(list.join(',')); } } } let listProcessor = listCreator(); input.map(x => x.split(' ')).map(([cmd,text]) => listProcessor[cmd](text)) } <file_sep>function solve() { let btn = document.getElementsByTagName('button')[0]; let inputElement = document.getElementById('input'); let resultElement = document.getElementById('result'); let dropDownOption = document.getElementById('selectMenuTo'); dropDownOption.innerHTML = `<option selected value= 'binary'>Binary</option>`; dropDownOption.innerHTML += `<option selected value= 'hexadecimal'>Hexadecimal</option>`; btn.addEventListener('click', () => { if(dropDownOption.value === 'hexadecimal'){ resultElement.value=(Number(inputElement.value).toString(16)).toUpperCase() } else if(dropDownOption.value === 'binary' ) { resultElement.value = (Number(inputElement.value)).toString(2) } }) } <file_sep>function solve(arr) { let output = arr.sort((a,b) => a-b); return output.slice(output.length / 2) } <file_sep>function solve(x,y,z) { console.log(`The largest number is ${Math.max(x,y,z)}.`); } <file_sep>function attachGradientEvents() { let gradientElement = document.getElementById('gradient'); let resultElement = document.getElementById('result'); gradientElement.addEventListener('mousemove' , e => { let result = `${Math.floor((e.offsetX / e.target.clientWidth) * 100)}%`; resultElement.innerText = result; }) } <file_sep>function solve(arr , cmd) { let result = []; class Ticket { constructor(destination , price , status) { this.destination = destination; this.price = Number(price); this.status = status; } } arr.forEach(element => { let [x , y , status] = element.split('|'); result.push(new Ticket(x,y,status)); }); let output = result.sort((a,b) => { if(cmd === 'price') { return a.price - b.price; }else { return a[cmd].localeCompare(b[cmd]); } }) return output; } <file_sep>function solve(x) { function sum(y) { x += y; return sum; } sum.toString = () => x; return sum; } <file_sep>function generateReport(colNames) { let headers = document.querySelectorAll('input'); document.querySelector('#output').value = JSON.stringify( Array.from(document.querySelectorAll('tbody>tr')) .map( x => Array.from(x.children) .reduce( (a,b,i) => { if(headers[i].checked){ a[headers[i].parentElement.textContent.toLowerCase().trim()] = b.textContent } return a; },{}))) } <file_sep>function solve(arr) { let output = arr.sort((a, b) => a - b).reduce((a, _, i, arr) => { a.push(arr[i]) a.push(arr[arr.length - i - 1]) return a }, []) return output.slice(0, output.length / 2) } <file_sep>function solve(arr) { let obj = {}; for (let i = 0; i < arr.length; i++) { if(i % 2 === 0) { obj[arr[i]] = Number(arr[i+ 1]); } } return obj; } <file_sep>function SumNumbers() { let num1Element = document.getElementById('num1'); let num2Element = document.getElementById('num2'); let resultElement = document.getElementById('sum'); if(num1Element.value !== '' && num2Element.value !== '') { resultElement.value = Number(num1Element.value) + Number(num2Element.value); } } <file_sep>function solve() { let titleElement = document.getElementById('text').value; let convinctionElement = document.getElementById('naming-convention').value; let result = document.getElementById('result'); if(convinctionElement === 'Camel Case') { let splitedString = titleElement.split(' ').map(x => x.toLowerCase()) .map(y => y.replace(y[0] , y[0].toUpperCase())); let changeFirstWord = splitedString.shift().split(''); changeFirstWord[0] = changeFirstWord[0].replace(changeFirstWord[0] , changeFirstWord[0].toLowerCase()); splitedString.unshift(changeFirstWord.join('')); splitedString = splitedString.join('') result.textContent = splitedString; }else if(convinctionElement === 'Pascal Case') { let splitedString = titleElement.split(' ').map(x => x.toLowerCase()) .map(y => y.replace(y[0], y[0].toUpperCase())).join('') result.textContent = splitedString; }else { result.textContent = 'Error!'; } } <file_sep>function solve(name , population , treasury ) { let output = { name, population, treasury, } return output; } <file_sep>function solve(num) { return (input) => input += num; } <file_sep>function solve(arr , rotations) { for(let i=0;i<rotations;i++) { arr.unshift(arr.pop()); } return arr.join(" ") } <file_sep>function solve(input) { let heroes = []; let data = input.map(x => x.split(' / ')).forEach(element => { element[2] = element[2] ? element[2].split(', ') : []; heroes.push({name: element[0] , level: Number(element[1]) , items: element[2]}); }); return JSON.stringify(heroes); } <file_sep>function focus() { let inputs = document.querySelectorAll('input[type="text"]'); Array.from(inputs).forEach(x => { x.addEventListener('focus' , function (e) { let parentDivElement = e.currentTarget.parentElement; parentDivElement.classList.add('focused'); }) x.addEventListener('blur' , function (e) { let parentDivElement = e.currentTarget.parentElement; parentDivElement.classList.remove('focused'); }) }) } <file_sep>function solve() { let map = new Map(); Array.from(arguments).forEach(x => { let type = typeof(x); if(!map.has(type)) { map.set(type, 0); } map.set(type , map.get(type) + 1); console.log(`${type}: ${x}`); }) Array.from(map.entries()).sort((a,b) => b[1] - a[1]) .forEach((elem) => console.log(`${elem[0]} = ${elem[1]}`)) } <file_sep> function solve(input) { let parse = JSON.parse(input) let str = '<table>\n' str += ` <tr>${Object.keys(parse[0]).map(x => `<th>${replace(x)}</th>`).join('')}</tr>\n` parse.forEach( x => { str += ` <tr>${Object.values(x).map( x => `<td>${replace(x)}</td>`).join('')}</tr>\n` }) str += '</table>' function replace(str) { return String(str) .replace(/&/g , '&amp;') .replace(/</g , "&lt;") .replace(/>/g , "&gt;") .replace(/"/g , "&quot;") .replace(/'/g , "&#39;") } return str } <file_sep>function printOrbitOfPoint(input) { [arrRows, arrCols, x, y] = input; let arr = createarr(); let currentValue = 1; arr[x][y] = currentValue; setLayers(); console.log(arr.map(row => row.join(' ')).join('\n')); function setLayers() { let upRow = x - currentValue; let downRow = x + currentValue; let upDownCol = Math.max(y - currentValue, 0); while (upDownCol < arrCols && upDownCol <= y + currentValue) { if (upRow >= 0) { arr[upRow][upDownCol] = currentValue + 1; } if (downRow < arrRows) { arr[downRow][upDownCol] = currentValue + 1; } upDownCol++; } let leftRightRow = Math.max(x - currentValue, 0); let rightCol = y + currentValue; let leftCol = y - currentValue; while (leftRightRow < arrRows && leftRightRow <= x + currentValue) { if (rightCol < arrCols) { arr[leftRightRow][rightCol] = currentValue + 1; } if (leftCol >= 0) { arr[leftRightRow][leftCol] = currentValue + 1; } leftRightRow++; } currentValue++; if (currentValue >= arrRows && currentValue >= arrCols) { return; } setLayers(); } function createarr() { let arr = []; for (let i = 0; i < arrRows; i++) { arr.push(new Array(arrCols)); } return arr; } } <file_sep>function solve(arr = []) { let result = []; for (let i= 0; i < arr.length; i++) { if(i % 2 === 1) { result.push(arr[i] * 2 ); } } result = result.reverse(); return result.join(' '); } <file_sep>function solve(input) { if(input.hasOwnProperty('dizziness')) { if(input.dizziness === true) { let amount = (input.weight * 0.1) * (input.experience); input.levelOfHydrated += amount; input.dizziness = false; } } return input; } <file_sep>let assert = require('chai').assert; let isOddOrEven = require('./app.js'); describe('isEvenOrOdd' , () => { it('Should return undefined if input parameter is not a string' , () => { assert.equal(undefined , isOddOrEven(3)); }) it('Should return even if string length is devisible by 2' , () => { assert.equal('even' , isOddOrEven('stri')); }) it('Should return odd if string length is not devisible by 2' , () => { assert.equal('odd' , isOddOrEven('str')); }) }) <file_sep>function solve(arr,delimeter) { return arr.join(delimeter) } <file_sep>function solve(arr , startPoint , endPoint) { return arr.slice(arr.indexOf(startPoint) , arr.indexOf(endPoint) + 1); } <file_sep>function solve(width,height , color) { return { width : width, height : height , color: color[0].toUpperCase() + color.slice(1), calcArea() { return this.width * this.height } } } <file_sep>function solve(arr,n) { let output = arr.reduce((a,b,i) => { if(i % n === 0) { a.push(b); } return a; },[]) return output; } <file_sep>function solve(arr) { let pairs=0 arr.forEach((row , i) => { row.forEach((el , x)=> { if(el===row[x+1]) { pairs++ } if(arr[i+1]&& el===arr[i+1][x]) { pairs++ } }) }) return pairs } <file_sep>function solve(input) { return input.reduce((a,b) => a + b , 0) + '\n' + input.reduce((a,b) => a + 1/ b , 0) + '\n' + input.reduce((a,b) => a.concat(b) , '') } <file_sep>function validate() { let inputElement = document.getElementById('email'); inputElement.addEventListener('change' , e => { let currentValue = e.currentTarget.value; let pattern = /[a-z]+@[a-z]+.[a-z]+/; if(pattern.test(currentValue)) { e.currentTarget.classList.remove('error'); }else { e.currentTarget.classList.add('error') } }) } <file_sep># SoftUni JS-Advanced-Januray-2021 [![68747470733a2f2f692e696d6775722e636f6d2f6172417238675a2e706e67](https://user-images.githubusercontent.com/71393659/102015173-9de43480-3d62-11eb-8944-fd4fc245d9a2.png)](https://softuni.bg/trainings/3217/js-advanced-january-2021) В курса "JS Advanced" ще получите задълбочени познания по езика JavaScript, като основи на синтаксиса, работа с масиви, матрици, обекти, класове и писане на функции. Ще изучавате по-сложни концепции като function context, explicit binding, event loop. Курсът ще развие алгоритмичното ви мислене. След успешното завършване на този курс, ще имате възможност да работите с DOM дървото, да правите манипулации по него и да работите с "event"-и. Ще се разглеждат функционалния и ООП подходите за програмиране с JavaScript, като ще се изучават концепции, като inheritance, object composition и prototype chain. <file_sep>function colorize() { let data = Array.from(document.querySelectorAll('table , tbody , tr')).splice(3); data.forEach((x,i) => { if(i % 2 === 0) { data[i].style.backgroundColor = 'teal'; } }) } <file_sep>function solve(arr) { let output = []; let i = 0; arr.forEach(cmd => { if(cmd === 'add') { i++; output.push(i) }else if(cmd === 'remove') { i++; output.splice(output.length-1 , 1); } }); return output.length === 0 ? console.log('Empty') : console.log(output.join('\n')); } <file_sep>function solve(n, k) { let output = [1]; for (let i = 0; i < n - 1; i++) { let x = output.length < k ? output : output.slice(output.length - k); output.push(x.reduce((a,b) => a + b )); } return output; } <file_sep>function solve(input) { let checkInput = typeof input; if(checkInput === 'number') { return (Math.pow(input,2) * Math.PI).toFixed(2); }else { return `We can not calculate the circle area, because we receive a ${checkInput}.` } } <file_sep>class List { constructor() { this.list = []; this.size = 0; } add(x) { this.list.push(x); this.size++; this.list.sort((a,b) => a - b); } remove(i) { if(this.indexChecker(i)) { this.list.splice(i , 1); this.size--; } } get(i) { if(this.indexChecker(i)) { return this.list[i]; } } size() { return this.list.length; } indexChecker(index) { if(index >= 0 && index < this.list.length) { return true; } return false; } } <file_sep>function solve(steps , stepsLength , speed) { let metersDistance=steps * stepsLength let speedMeters=speed / 3.6 let time=metersDistance / speedMeters + Math.floor(metersDistance / 500) * 60 let hours=Math.floor(time/3600) let mins=Math.floor(time/60) let secs=Math.round(time%60) console.log(`${hours < 10? 0 : ""}${hours}:${mins <10 ? 0 : ""}${mins}:${secs < 10 ? 0 : ""}${secs}`); } <file_sep>function createFormatter(a, b ,c, currencyFormatter) { return currencyFormatter.bind(null, a, b, c) } <file_sep>class Stringer { constructor(string , length) { this.innerString = string; this.innerLength = length; } increase(currentLength) { this.innerLength += currentLength; } decrease(currentLength) { if(this.innerLength - currentLength < 0) { this.innerLength = 0; }else { this.innerLength -= currentLength; } } toString() { if(this.innerLength === 0) { return '...'; } return this.innerString.slice(0,this.innerLength) + (this.innerLength >= this.innerString.length ? "" : "..."); } } <file_sep>function solve(input) { let result = input.reduce((a , b) => { let [car , model , producedCars] = b.split(' | '); producedCars = Number(producedCars); if(a.has(car)) { if(a.get(car).has(model)) { let oldValue = a.get(car).get(model); oldValue += producedCars; let setValue = a.get(car).set(model , oldValue); a.set(car , setValue); }else { let newVal = a.get(car).set(model , producedCars); a.set(car , newVal); } }else { let idk = new Map(); idk.set(model , producedCars); a.set(car , idk); } return a; } , new Map()); Array.from(result.entries()).forEach(x => { console.log(x[0]); Array.from(x[1].entries()).forEach(y => { console.log(`###${y[0]} -> ${y[1]}`); }) }) } <file_sep>function solve(data) { let carBuilder = () => { let car = {}; return { create: (name, inherit, parent) => { car[name] = inherit ? Object.create(car[parent]) : {} }, set: (name, key, value) => car[name][key] = value, print: (name) => { let result = []; for (const key in car[name]) { result.push(`${key}:${car[name][key]}`) } console.log(result.join(', ')); } } } let factory = carBuilder(); data.map(x => x.split(' ')) .map(([cmd, ...props]) => factory[cmd].apply(undefined,props)) } <file_sep>let assert = require('chai').assert; let {createCalculator} = require('./app.js'); describe('check object function' , () => { let func; beforeEach(() => { func = createCalculator(); }) it('function should be instance of object' , () => { assert.equal(func instanceof Object , true); }) it('object should have property add' , () => { assert.equal(func.hasOwnProperty('add') , true); }) it('object should have property subtract' , () => { assert.equal(func.hasOwnProperty('subtract') , true); }) it('object should have property get' , () => { assert.equal(func.hasOwnProperty('get') , true); }) describe('all functions shoud work properly' , () => { it('add function should add number to value variable which hold sum' , () => { func.add(7); let value = func.get(); assert.equal(value , 7); }) it('subtract function should subtract num from value variable which hold sum' , () => { func.subtract(3); let value = func.get(); assert.equal(value , -3); }) it('Methods should work properly if parameter is string' , () => { func.subtract('-3'); func.add('7'); assert.equal(func.get() , 10); }) }) }) <file_sep>(function () { Array.prototype.last = function() { return this[this.length - 1]; } Array.prototype.skip = function(n) { return this.slice(n); } Array.prototype.take = function(n) { return this.slice(0,n); } Array.prototype.sum = function() { return this.reduce((a,b) => a+b); } Array.prototype.average = function() { return this.reduce((a,b) => a+b) / this.length; } })(); <file_sep>function solve(arr = []) { let checker = arr.sort((a,b) => a - b).splice(0,2).join(' ') return checker; } <file_sep>function solve(arr) { let i = 0; let sortArray = arr.sort((a,b) => a.localeCompare(b)).forEach((x) => { i++; console.log(`${i}.${x}`) }); } <file_sep>function solve(library, orders) { return orders.map( x => { return Object.assign({}, x.template, x.parts.reduce((a,b) => Object.assign(a, {[b]: library[b]}) , {})) }) } <file_sep>function solve() { let availableProducts = { protein: 0, carbohydrate: 0, fat: 0, flavour: 0, } const receipts = { apple: { carbohydrate : 1, flavour: 2, }, lemonade: { carbohydrate: 10, flavour : 20, }, burger: { carbohydrate : 5, fat: 7, flavour: 3, }, eggs: { protein: 5, fat: 1, flavour: 1, }, turkey: { protein: 10, carbohydrate: 10, fat: 10, flavour: 10, } } let commands = { restock: (product , quantity) => { availableProducts[product] += quantity; return 'Success'; }, prepare: (product , quantity) => { let currentProduct = Object.entries(receipts[product]) for (const [key,value] of currentProduct) { if(availableProducts[key] < value * quantity) { return `Error: not enough ${key} in stock` } } currentProduct.forEach(item => { availableProducts[item[0]] -= item[1] * quantity; }); return 'Success'; }, report: () => { return Object.entries(availableProducts).map(([item , quantity]) =>`${item}=${quantity}`).join(" ") } } return function(str) { let [cmd , product , quantity] = str.split(' '); quantity = Number(quantity); return commands[cmd](product,quantity); } } <file_sep>function solve(...input) { let result = input.reduce((a,b) => a += b.length, 0); console.log(result + "\n" + Math.floor(result / input.length) ); } <file_sep>function extract(content) { return document.getElementById(content).textContent.match(/\((?<name>[\s\w]+)\)/gmi) .map( x => /\((?<name>[\s\w]+)\)/gmi.exec(x).groups.name) .join('; ') } <file_sep>function solve(input) { let result = {}; input.forEach(element => { let [city , population] = element.split(' <-> '); population = Number(population); if(result[city]) { result[city] += population; }else { result[city] = population; } }); Object.entries(result).forEach(x => console.log(`${x[0]} : ${x[1]}`)) } <file_sep>function subtract() { let numOne = document.getElementById('firstNumber').value let numTwo = document.getElementById('secondNumber').value; document.getElementById('result').innerHTML = numOne - numTwo; } <file_sep>function solve(n1,n2,op) { let operators = { '+' : n1 + n2, '-': n1 - n2, '*': n1 * n2, '/': n1 / n2, '%': n1 % n2, '**': n1 ** n2, } return operators[op]; } <file_sep>function solve() { return { hasClima (obj) { return Object.assign(obj , {temp:21 ,tempSettings:21,adjustTemp : function () { return this.temp < this.tempSettings ? this.temp++ : this.temp--; }}); }, hasAudio(obj) { return Object.assign(obj , {currentTrack:null , nowPlaying: function() { if(this.currentTrack !== null) { console.log(`Now playing '${this.currentTrack.name}' by ${this.currentTrack.artist}`); } }} ) }, hasParktronic(obj) { return Object.assign(obj , {checkDistance: function(num) { if(num < 0.1) { console.log("Beep! Beep! Beep!"); }else if(num >= 0.1 && num < 0.25) { console.log("Beep! Beep!"); }else if(num >= 0.25 && num < 0.5) { console.log("Beep!"); }else { console.log(""); } }}) } } } <file_sep>class Person{ constructor(firstName,lastName,age,email) { Object.assign(this,{firstName,lastName,age,email}); } toString() { return `${this.firstName} ${this.lastName} (age: ${this.age}, email: ${this.email})` } } <file_sep>function solve(input) { let x = Object.entries(input .map( x=> x.split(' : ') ) .reduce( (a,b) => { a[b[0]] = b[1]; return a },{})) .sort( (a,b) => a[0].localeCompare(b[0]) ) let a = new Set([...x.map(x => x= x[0][0])]) a.forEach(z => { console.log(z) x.forEach(x => { if(x[0][0] === z){ console.log(` ${x[0]}: ${x[1]}`) } }) }); } <file_sep>function search() { let searchBox = document.getElementById('searchText').value; let word = new RegExp(searchBox); let count = 0; let townsElement = Array.from(document.querySelectorAll('towns , li ')).forEach(x => { if(x.textContent.match(word)) { x.style.fontWeight = 'bold'; x.style.textDecoration = 'underline'; count++; } }) let result = document.getElementById('result') result.textContent = `${count} matches found`; } <file_sep>function solve(...arr) { let num = arr.shift(); arr.forEach(element => { if(element === 'chop') { num = num / 2; console.log(num); }else if (element === 'dice') { num = Math.sqrt(num); console.log(num); }else if(element === 'spice') { num += 1; console.log(num); }else if(element === 'bake') { num = num * 3; console.log(num); }else if(element === 'fillet') { num = num * 0.80; console.log(num.toFixed(1)); } }); } <file_sep>function solve(area,vol,arr) { return JSON.parse(arr).map(x => { return { area: Math.abs(area.call(x)), volume : Math.abs(vol.call(x)) } }) } <file_sep>function solve(arr) { let num = Number.MIN_SAFE_INTEGER; let output = []; arr.forEach(element => { if(element >= num) { num = element; output.push(num); } }) return output } <file_sep>function solve() { let inputText = document.getElementById('input').value; let outputBox = document.getElementById('output'); let sentances = inputText.split('.').filter(x => x !== ''); while(sentances.length > 0){ let current = sentances.splice( 0, 3 ).join('.'); if(current[current.length -1] !== '.'){ current += '.' } let pElement = document.createElement('p'); pElement.innerText = current; outputBox.appendChild(pElement); } } <file_sep>function extractText() { let itemsElement = document.querySelector('#result').value = Array.from(document.querySelector('#items').children) .map(x => x.textContent); } <file_sep>function solve(arr) { let biggestNumber = Number.MIN_SAFE_INTEGER; let searchThroughNumbers = arr.map(x => x.forEach(currentNumber => { if(currentNumber > biggestNumber) { biggestNumber = currentNumber; } })); return biggestNumber; } <file_sep>let assert = require('chai').assert; let lookupChar = require('./app.js'); describe('lookupChar' , () => { it('Should return undefined if first parameter is not a string' , () => { assert.equal(undefined , lookupChar(10,'3')) }) it('Should return undefined if first parameter is not a string' , () => { assert.equal(undefined , lookupChar(3,3)) }) it('Should return undefine with incorrect second param' , () => { assert.equal(undefined , lookupChar('3','3')) }) it('Should return undefine with incorrect second param' , () => { assert.equal(undefined , lookupChar('3',1.70)); }) it('Should return incorrect index if given index is bigger than string length' , () => { assert.equal('Incorrect index' , lookupChar('word' , 7)) }) it('Should return incorrect index if given index is bigger than string length' , () => { assert.equal('Incorrect index' , lookupChar('word' , -7)) }) it('Should return incorrect index if given index is bigger than string length' , () => { assert.equal('Incorrect index' , lookupChar('word' , 4)) }) it('Should return string char at' , () => { assert.equal('e' , lookupChar('hey' , 1)) }) it('Should return string char at' , () => { assert.equal('h' , lookupChar('hey' , 0)) }) })
1a174eff1faabe1d8693691f9aeddaa8eea5dcc9
[ "JavaScript", "Markdown" ]
63
JavaScript
todorgospodinov/JS-Advanced-January-2022
ce34806a729719f8abc6c011c4a111aded193205
f6ea10492430517ea56c5bd42d55c0e942b281fa
refs/heads/master
<repo_name>hsmaan/cov19_evo_dist<file_sep>/evo_dist.R library(Biostrings) library(stringr) library(DECIPHER) library(ape) library(data.table) # Masked sites (homoplasic) mask_sites <- c(187, 1059, 2094, 3037, 3130, 6990, 8022, 10323, 10741, 11074, 13408, 14786, 19684, 20148, 21137, 24034, 24378, 25563, 26144, 26461, 26681, 28077, 28826, 28854, 29700, 4050, 13402, 11083, 15324, 21575) # Functions from CovidGenotyper/R/global.R align_get <- function(fastas, align_iters, align_refs, ncores) { fastas_ungapped <- RemoveGaps(fastas, removeGaps = "all", processors = ncores) fasta_align <- AlignSeqs(fastas_ungapped, iterations = align_iters, refinements = align_refs, processors = ncores) fasta_mat <- as.matrix(fasta_align) fasta_bin <- as.DNAbin(fasta_mat) fasta_ungapped <- del.colgapsonly(fasta_bin, threshold = 0.95) fasta_string <- fasta_ungapped %>% as.list %>% as.character %>% lapply(., paste0, collapse = "") %>% unlist %>% DNAStringSet align_mat <- as.matrix(fasta_string) align_mat_sub <- align_mat[, -mask_sites] align_mat_bin <- as.DNAbin(align_mat_sub) align_masked <- align_mat_bin %>% as.list %>% as.character %>% lapply(., paste0, collapse = "") %>% unlist %>% DNAStringSet return(align_masked) } dist_get <- function(align, metric) { align_mat <- as.matrix(align) align_mat_sub <- align_mat[, -mask_sites] align_mat_bin <- as.DNAbin(align_mat_sub) align_masked <- align_mat_bin %>% as.list %>% as.character %>% lapply(., paste0, collapse = "") %>% unlist %>% DNAStringSet align_trim <- subseq(align_masked, start = 265, end = 29674) dec_dist <- dist.dna(as.DNAbin(align_trim), model = metric, as.matrix = TRUE, pairwise.deletion = FALSE) colnames(dec_dist) <- (str_split_fixed(colnames(dec_dist), fixed("."), 2)[,1]) rownames(dec_dist) <- (str_split_fixed(rownames(dec_dist), fixed("."), 2)[,1]) return(dec_dist) } # Read args args <- commandArgs(trailingOnly = TRUE) fasta_file <- as.character(args[1]) length_cutoff <- as.numeric(args[2]) ambg_cutoff <- as.numeric(args[3]) dist_method <- as.character(args[4]) iters <- as.numeric(args[5]) refs <- as.numeric(args[6]) cores <- as.numeric(args[7]) # Load input fasta con_fasta <- readDNAStringSet(fasta_file) # Test if any fastas are <29000 nucleotides in length len_rm <- (which(width(con_fasta) < length_cutoff)) if (length(len_rm) > 0) { con_fasta <- con_fasta[-len_rm] } print(paste0(as.character(length(len_rm)), " sequences removed due to nucleotide length < ", as.character(length_cutoff))) # Remove based on ambg nucleotide freq ambg_freq_rm <- which(((apply((letterFrequency(con_fasta, c("N", "W", "S", "M", "K", "R", "Y", "B", "D", "H", "V"))), 1, sum))/29000) > ambg_cutoff) if (length(ambg_freq_rm) > 0) { con_fasta <- con_fasta[-ambg_freq_rm] } print(paste0(as.character(length(ambg_freq_rm)), " sequences removed due to ambiguous nucleotide frequency > ", as.character(ambg_cutoff*100), "%")) # Get fasta names fasta_names <- as.list(names(con_fasta)) # Get DNA alignment fasta_aligned <- align_get(con_fasta, align_iters = iters, align_refs = refs, ncores = cores) # Get DNA distance fasta_dist <- dist_get(fasta_aligned, metric = dist_method) # Convert to data table fasta_dist_dt <- as.data.table(fasta_dist, keep.rownames = TRUE) # Create output dir if (!dir.exists("out")) { dir.create("out") } # Get file name of input file_name_no_ext <- str_split_fixed(fasta_file, fixed("."), 2)[1] file_name_no_ext_whitespace <- gsub(" ", "", file_name_no_ext, fixed = TRUE) # Write dist tsv to out dir fwrite(fasta_dist_dt, file = paste0("out/", file_name_no_ext_whitespace, "_dist_matrix.tsv"), sep = "\t", quote = FALSE, col.names = TRUE, row.names = FALSE) print(paste0("Alignment and distance calculation complete. File saved in out/", file_name_no_ext_whitespace, ".tsv")) <file_sep>/README.Rmd --- output: github_document --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.path = "man/figures/README-", out.width = "100%", tidy.opts = list(width.cutoff = 80), tidy = TRUE ) ``` # COVID-19 Evolutionary Distance An evolutionary distance calculation tool for SARS-CoV-2 viral genomes that removes the following homoplasic sites: **187, 1059, 2094, 3037, 3130, 6990, 8022, 10323, 10741, 11074, 13408, 14786, 19684, 20148, 21137, 24034, 24378, 25563, 26144, 26461, 26681, 28077, 28826, 28854, 29700, 4050, 13402, 11083, 15324, 21575** ## Overview The script options are the following (**ensure input_fasta is in same directory as cov19_evo_dist**): ``` Rscript --verbose evo_dist.R [input_fasta] [length_cutoff] [ambg_nucleotide_cutoff] [dist_method] [iterations] [refinements] [cores] ``` * input_fasta: location of the input fasta file containing query sequences - ensure it's in same directory as cov19_evo_dist [file] * length_cutoff: minimum length of query sequences for filtering [0-30000] * ambg_nucleotide_cutoff: maximum percentage of ambiguous nucleotides in query sequences for filtering [0-1] * dist_method: The evolutionary distance metric to use from the ape library. "K80" is recommended. More information is available in the ape documentation https://www.rdocumentation.org/packages/ape/versions/5.4-1/topics/dist.dna, under the "model" parameter. [model_name] * iterations: Number of iterations for multiple sequence alignment algorithm - 0 recommended unless sequences are particularly low quality (then 5-6). [0-n] * refinements: Refinement steps for the multiple sequence alignment algorithm - 0 recommended unless sequences are particularly low quality (then 2-3). [0-n] * cores: number of cores to utilize during processing [1-n] E.g: ``` Rscript --verbose evo_dist.R example.fasta 29000 0.1 K80 0 0 2 ``` Output is saved to **out** folder under same name as input file ## Installation Clone repository: ``` git clone https://github.com/hsmaan/cov19_evo_dist.git ``` Set up and activate conda environment: ``` conda env create --name evo_env --file evo_dist.yaml conda activate evo_env ``` Example run: ``` Rscript --verbose evo_dist.R example.fasta 29000 0.1 K80 0 0 2 ``` <file_sep>/README.md # COVID-19 Evolutionary Distance An evolutionary distance calculation tool for SARS-CoV-2 viral genomes that removes the following homoplasic sites: **187, 1059, 2094, 3037, 3130, 6990, 8022, 10323, 10741, 11074, 13408, 14786, 19684, 20148, 21137, 24034, 24378, 25563, 26144, 26461, 26681, 28077, 28826, 28854, 29700, 4050, 13402, 11083, 15324, 21575** ## Overview The script options are the following (**ensure input\_fasta is in same directory as cov19\_evo\_dist**): Rscript --verbose evo_dist.R [input_fasta] [length_cutoff] [ambg_nucleotide_cutoff] [dist_method] [iterations] [refinements] [cores] - input\_fasta: location of the input fasta file containing query sequences - ensure it’s in same directory as cov19\_evo\_dist \[file\] - length\_cutoff: minimum length of query sequences for filtering \[0-30000\] - ambg\_nucleotide\_cutoff: maximum percentage of ambiguous nucleotides in query sequences for filtering \[0-1\] - dist\_method: The evolutionary distance metric to use from the ape library. “K80” is recommended. More information is available in the ape documentation <https://www.rdocumentation.org/packages/ape/versions/5.4-1/topics/dist.dna>, under the “model” parameter. \[model\_name\] - iterations: Number of iterations for multiple sequence alignment algorithm - 0 recommended unless sequences are particularly low quality (then 5-6). \[0-n\] - refinements: Refinement steps for the multiple sequence alignment algorithm - 0 recommended unless sequences are particularly low quality (then 2-3). \[0-n\] - cores: number of cores to utilize during processing \[1-n\] E.g: Rscript --verbose evo_dist.R example.fasta 29000 0.1 K80 0 0 2 Output is saved to **out** folder under same name as input file ## Installation Clone repository: git clone https://github.com/hsmaan/cov19_evo_dist.git Set up and activate conda environment: conda env create --name evo_env --file evo_dist.yaml conda activate evo_env Example run: Rscript --verbose evo_dist.R example.fasta 29000 0.1 K80 0 0 2
be2fcefb18731022898ff3348529f44efa8592cb
[ "Markdown", "R", "RMarkdown" ]
3
R
hsmaan/cov19_evo_dist
54a1dd291678838f81e37acbb6db16ba98087009
db53c6c4eab099859d2cbc8542458600d8681970
refs/heads/master
<repo_name>dungqd86/AutoProduction<file_sep>/Auto.Utilities/Google.AMP/AmpUtility.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Auto.Utilities.Google.AMP { public class AmpUtility { public static string GenerateHtmlContent(string content) { #region Regex optimization content string splitReg = @"(?:\s|\t|\n|\r|&nbsp;)*<\/?(?:p\s+[^>]*|p|div[^>]*)>(?:\s|\t|\n|\r|&nbsp;)*"; string removeTagReg = @"(?:\s|\t|\n|\r|&nbsp;)*<\/?(?:(?:p\s+|div|figure|table|tbody|tr|th|td|ul|li|br|h1|h2|a|\??[a-z0-9\-]+\:[a-z0-9\-]+)[^>]*|p)>(?:\s|\t|\n|\r|&nbsp;)*|<\!--[\S\s]*-->"; string styleTagReg = @"<\/?(?:(?:p\s+|em|u|b|strong|<i\/?>|font|span|\??[a-z0-9\-]+\:[a-z0-9\-]+)[^>]*)>"; string trimReg = @"^(?:\s|\t|\n|\r|&nbsp;|<br\/?>)+|(?:\s|\t|\n|\r|&nbsp;|<br\/?>)+$"; string photoReg = @"<img[^>]+>"; string beginValidTag = @"^(?:\s|\t|\n|\r|&nbsp;)*<(?:div[^>]*|p\s+[^>]*|p|h\d[^>]*)>"; string hasTag = @"<\/?[a-z0-9]+[^>]*>"; string stand = @"^(?:(?:\s|\t|\n|\r|&nbsp;)*<\/?(?:span|div|p|br)+[^>]*>(?:\s|\t|\n|\r|&nbsp;)*)+$"; string[] paragraphs = Regex.Split(content, splitReg, RegexOptions.IgnoreCase | RegexOptions.Singleline); if (paragraphs != null && paragraphs.Length > 0) { for (int i = 0; i < paragraphs.Length; i++) { paragraphs[i] = Regex.Replace(paragraphs[i], trimReg, string.Empty).Trim(); Match match = Regex.Match(paragraphs[i], stand); if (match.Success) { paragraphs[i] = string.Empty; } else { paragraphs[i] = Regex.Replace(paragraphs[i], removeTagReg, " ").Trim(); paragraphs[i] = Regex.Replace(paragraphs[i], styleTagReg, string.Empty).Trim(); if (!string.IsNullOrWhiteSpace(paragraphs[i])) { Match matchValidTag = Regex.Match(paragraphs[i], beginValidTag); Match matchPhotoTag = Regex.Match(paragraphs[i], photoReg); if (!matchValidTag.Success && !matchPhotoTag.Success) { paragraphs[i] = string.Format("<p>{0}</p>", paragraphs[i]); } //paragraphs[i] = Regex.Replace(paragraphs[i], photoReg, delegate (Match m) //{ // return ""; //}); } } } content = string.Join("", paragraphs); content = Regex.Replace(content, trimReg, ""); } Regex regAMPImage = new Regex(@"<img.+?src=[\""'](?<SRC>.+?)[\""'].+?(title=[\""'](?<title>.+?)[\""'])?.*?>", RegexOptions.Singleline | RegexOptions.IgnoreCase); content = regAMPImage.Replace(content, delegate (Match m) { string src = m.Groups["SRC"].Value; string title = m.Groups["title"].Value; title = StringUtils.RemoveSpecial(title); string titleAttr = !string.IsNullOrWhiteSpace(title) ? string.Format(" title=\"{0}\" ", title) : string.Empty; string altAttr = !string.IsNullOrWhiteSpace(title) ? string.Format(" alt=\"{0}\" ", title) : string.Empty; if (!string.IsNullOrWhiteSpace(src)) { return string.Format("<amp-img layout=\"responsive\" width=\"300\" height=\"200\" src=\"{0}\" {1} {2}></amp-img><br />", src, titleAttr, altAttr); } return string.Empty; }); //content = Regex.Replace(content, @"<img.+?src=[\""'](?<SRC>.+?)[\""'].+?(title=[\""'](?<title>.+?)[\""'])?.*?>", "<amp-img layout=\"responsive\" width=\"300\" height=\"200\" src=\"${SRC}\" title=\"${title}\" alt=\"${title}\"></amp-img><br />"); content = Regex.Replace(content, @"(style=[""'](.+?)[""'].*?)", string.Empty, RegexOptions.IgnoreCase | RegexOptions.Singleline); content = Regex.Replace(content, @"<o:p></o:p>", string.Empty, RegexOptions.IgnoreCase | RegexOptions.Singleline); content = Regex.Replace(content, @"(?<empty>\<.?>(\s+)?</.?>)", string.Empty, RegexOptions.IgnoreCase | RegexOptions.Singleline); content = Regex.Replace(content, ">(\\s+)<", ">\r\n<", RegexOptions.Singleline | RegexOptions.IgnoreCase); #endregion return content; } } } <file_sep>/Auto.Utilities/Base/Null.cs using System; using System.Reflection; namespace Auto.Utilities.Base { public class Null { public static short NullShort { get { return -1; } } public static int NullInteger { get { return -1; } } public static byte NullByte { get { return 255; } } public static float NullSingle { get { return float.MinValue; } } public static double NullDouble { get { return double.MinValue; } } public static decimal NullDecimal { get { return decimal.MinValue; } } public static DateTime NullDate { get { return DateTime.MinValue; } } public static string NullString { get { return ""; } } public static bool NullBoolean { get { return false; } } public static Guid NullGuid { get { return Guid.Empty; } } public static object SetNull(object value, object field) { object returnValue; if (value == DBNull.Value) { if (field is short) { returnValue = NullShort; } else if (field is byte) { returnValue = NullByte; } else if (field is int) { returnValue = NullInteger; } else if (field is float) { returnValue = NullSingle; } else if (field is double) { returnValue = NullDouble; } else if (field is decimal) { returnValue = NullDecimal; } else if (field is DateTime) { returnValue = NullDate; } else if (field is string) { returnValue = NullString; } else if (field is bool) { returnValue = NullBoolean; } else if (field is Guid) { returnValue = NullGuid; } else { returnValue = null; } } else { returnValue = value; } return returnValue; } public static object SetNull(PropertyInfo propertyInfo) { object returnValue = null; switch (propertyInfo.PropertyType.ToString()) { case "System.Int16": returnValue = NullShort; break; case "System.Int32": case "System.Int64": returnValue = NullInteger; break; case "system.Byte": returnValue = NullByte; break; case "System.Single": returnValue = NullSingle; break; case "System.Double": returnValue = NullDouble; break; case "System.Decimal": returnValue = NullDecimal; break; case "System.DateTime": returnValue = NullDate; break; case "System.String": case "System.Char": returnValue = NullString; break; case "System.Boolean": returnValue = NullBoolean; break; case "System.Guid": returnValue = NullGuid; break; default: var type = propertyInfo.PropertyType; if (type.BaseType != null && type.BaseType == typeof(Enum)) { var objEnumValues = Enum.GetValues(type); Array.Sort(objEnumValues); returnValue = Enum.ToObject(type, objEnumValues.GetValue(0)); } break; } return returnValue; } public static bool SetNullBoolean(object value) { var retValue = NullBoolean; if (value != DBNull.Value) { retValue = Convert.ToBoolean(value); } return retValue; } public static DateTime SetNullDateTime(object value) { var retValue = NullDate; if (value != DBNull.Value) { retValue = Convert.ToDateTime(value); } return retValue; } public static int SetNullInteger(object value) { var retValue = NullInteger; if (value != DBNull.Value) { retValue = Convert.ToInt32(value); } return retValue; } public static float SetNullSingle(object value) { var retValue = NullSingle; if (value != DBNull.Value) { retValue = Convert.ToSingle(value); } return retValue; } public static string SetNullString(object value) { var retValue = NullString; if (value != DBNull.Value) { retValue = Convert.ToString(value); } return retValue; } public static Guid SetNullGuid(object value) { var retValue = Guid.Empty; if ((value != DBNull.Value) & !string.IsNullOrEmpty(value.ToString())) { retValue = new Guid(value.ToString()); } return retValue; } public static object GetNull(object field, object dbNull) { var returnValue = field; if (field == null) { returnValue = dbNull; } else if (field is byte) { if (Convert.ToByte(field) == NullByte) { returnValue = dbNull; } } else if (field is short) { if (Convert.ToInt16(field) == NullShort) { returnValue = dbNull; } } else if (field is int) { if (Convert.ToInt32(field) == NullInteger) { returnValue = dbNull; } } else if (field is float) { if (Convert.ToSingle(field) == NullSingle) { returnValue = dbNull; } } else if (field is double) { if (Convert.ToDouble(field) == NullDouble) { returnValue = dbNull; } } else if (field is decimal) { if (Convert.ToDecimal(field) == NullDecimal) { returnValue = dbNull; } } else if (field is DateTime) { if (Convert.ToDateTime(field).Date == NullDate.Date) { returnValue = dbNull; } } else if (field is string) { if (field.ToString() == NullString) { returnValue = dbNull; } } else if (field is bool) { if (Convert.ToBoolean(field) == NullBoolean) { returnValue = dbNull; } } else if (field is Guid) { if (((Guid)field).Equals(NullGuid)) { returnValue = dbNull; } } return returnValue; } public static bool IsNull(object field) { bool isNull; if (field != null) { if (field is int) { isNull = field.Equals(NullInteger); } else if (field is short) { isNull = field.Equals(NullShort); } else if (field is byte) { isNull = field.Equals(NullByte); } else if (field is float) { isNull = field.Equals(NullSingle); } else if (field is double) { isNull = field.Equals(NullDouble); } else if (field is decimal) { isNull = field.Equals(NullDecimal); } else if (field is DateTime) { var date = (DateTime)field; isNull = date.Date.Equals(NullDate.Date); } else if (field is string) { isNull = field.Equals(NullString); } else if (field is bool) { isNull = field.Equals(NullBoolean); } else if (field is Guid) { isNull = field.Equals(NullGuid); } else { isNull = false; } } else { isNull = true; } return isNull; } } }
ec0cc4dcc193d3c1372fd12e0c391229eab09fa1
[ "C#" ]
2
C#
dungqd86/AutoProduction
2412dd8944c0b0373b0acc50707b67dcf69c48ce
9c0920dd7a315f0e70088e3ce732d07c7618228c
refs/heads/master
<file_sep>class sseContainer { constructor(sessionLogic) { this.sseResponses = {}; this.sessionLogic = sessionLogic; this.keepAliveTimeout = 60000; } register(response, request) { let sessionObject = this.sessionLogic.getCookieObject(request, response); if (!sessionObject || !sessionObject.id) return false; request.ended = true;//keeps the request from ending. let sessionId = sessionObject.id; this.sseResponses[sessionId] = this.sseResponses[sessionId] || []; this.sseResponses[sessionId].push(response); //writes the head response.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'private, no-cache, no-store, must-revalidate', 'Connection': 'keep-alive', 'transfer-encoding': '' }); //set the timeout setTimeout(() => { let responseList = this.sseResponses[sessionId]; if (responseList) { delete this.sseResponses[sessionId]; responseList.forEach(responseItem => { responseItem.write(`event: keepAlive\ndata: keepAlive\n\n\n`); responseItem.end(); }); } }, this.keepAliveTimeout); } } module.exports = sseContainer;<file_sep>const requestProxyHandler = require("willcore.server/proxies/request/requestProxyHandler.js"); class sseProxyHandler extends requestProxyHandler { constructor(assignable) { super(assignable); this.getTraps.unshift(this.emit); } emit(target, property, proxy) { if (property === "emit") { let emit = (id, eventName, payload) => { proxy._assignable.sendEvent(id, eventName, payload); }; target[property] = emit; return { value: emit, status: true } } return { value: false, status: false } } } module.exports = sseProxyHandler;<file_sep>import { assignable } from "/willcore/assignable/assignable.js" import { uiProxy } from "/uiModules/proxies/ui/uiProxy.js"; import { guid } from "/uiModules/helpers/guid.js"; import { eventProxy } from "/uiModules/proxies/event/eventProxy.js"; import { sseProxy } from "./sseProxy.js"; class component extends assignable { constructor() { super({}, uiProxy); this.eventProxyInstance = eventProxy.new(guid()); this.eventSource = null; if (typeof (EventSource) === "undefined") { console.log("SSE not supported"); } } static get noValues() { return uiProxy; } completionResult() { let isConnected = false; let sseFunction = () => { this.eventSource = new EventSource("/event-stream"); let eventProxyInstance = this.eventProxyInstance; eventProxyInstance.sseConnected = true; let errorCount = 0; isConnected = true; this.eventSource.onmessage = (event) => { console.log(event); if (event.type === "keepAlive") return; let eventData = JSON.parse(event.data); eventProxyInstance[event.type] = eventData; }; this.eventSource.onerror = (error, aa) => { errorCount++; if (errorCount > 1) { isConnected = false; eventProxyInstance.sseError = error; eventProxyInstance.sseConnected = false; } }; this.eventSource.onopen = () => { errorCount = 0; isConnected = true; eventProxyInstance.sseConnected = true; }; }; this.eventProxyInstance.stopSSE = () => { if (this.eventSource) { this.eventSource.close(); this.eventSource = null; isConnected = false; } }; this.eventProxyInstance.requestSSEStatus = () => { this.eventProxyInstance.sseConnected = isConnected; }; this.eventProxyInstance.startSSE = sseFunction; let proxyInstance = sseProxy.new(this.parentProxy, this.propertyName, this); return proxyInstance; } completed() { } } export { component }; <file_sep>const assignable = require("willcore.core/assignable/assignable"); const sseProxy = require("../proxies/sseProxy.js"); const uiProxy = require("willcore.ui/server/proxies/uiProxy.js"); const sessionProxy = require("willcore.session/server_server/proxies/session/sessionProxy.js"); const sseContainer = require("../containers/sseContainer.js"); const path = require("path"); class sseAssignable extends assignable { constructor() { super({}, uiProxy); this.interceptors = { before: [], after: [] }; this.activationURL = "event-stream"; this.sessionLogic = null; } completionResult() { let proxyResult = sseProxy.new(this); let serverProxy = this.parentProxy._assignable.parentProxy; serverProxy._assignable.registerRequestProxy(this.activationURL, proxyResult); for (let parentAssignableName in serverProxy) { if (serverProxy[parentAssignableName] instanceof sessionProxy) { this.sessionLogic = serverProxy[parentAssignableName]; break; } } if (!this.sessionLogic) throw "No session module was found on server."; this.sseContainer = new sseContainer(this.sessionLogic._assignable.sessionLogic); this.registerSSEFileService(); return proxyResult; } //Method to be called to send event to the front-end sendEvent(id, eventName, message) { let responses = this.sseContainer.sseResponses[id]; if (responses) { // message = { // event: eventName, // payload: message // }; let result = `event: ${eventName}\ndata: ${JSON.stringify(message)}\n\n\n`; responses.forEach((response) => { response.write(result); }); } } /** * @param {import('../models/requestDetails.js').requestInstance} requestInfo */ async onRequest(requestInfo, request, response) { //Model to be created here and action called this.sseContainer.register(response, request); return true; } completed() { } registerSSEFileService(){ const serverProxy = this.parentProxy._assignable.parentProxy; let relativePath = this.getFilesFolderPath(serverProxy); serverProxy[this.propertyName].files = `${relativePath}`; this.parentProxy._assignable.addClientAssignable("sse",`/${this.propertyName}/sseAssignable.js`); } getFilesFolderPath(serverProxy) { let endPointFolder = path.normalize(`${__dirname}/../../client`); let mainExecutingDirectory = serverProxy._assignable.pathHelper.rootDirectory; let relativePath = path.relative(mainExecutingDirectory, endPointFolder); relativePath = "/" + relativePath.split("\\").join("/"); return relativePath; } } module.exports = sseAssignable;<file_sep>const sseProxyHandler = require("./sseProxyHandler.js"); const requestProxy = require("willcore.server/proxies/request/requestProxy.js"); /** * Proxy class for the main willCore instance. */ class sseProxy extends requestProxy { constructor() { super(); } /** * Factory method. * @type {InstanceType<requestProxyHandler>} */ static new(sseAssignable) { let result = new Proxy(new sseProxy(), new sseProxyHandler(sseAssignable)); return result; } } module.exports = sseProxy;<file_sep><p align="center"> <img src="res/WillCoreLogo.png" /> <h1 align="center">WillCore.SSE</h1> <h5 align="center">Build With Proxies - By <NAME></h5> <h5 align="center">License : MIT</h5> </p> WillCore.SSE is an expanstion module for WillCore.UI that enables server-side events. It allows you to emit front-end events from server-side code. The module is built on top and requires the folowing WillCore modules in order to work: * WillCore.Server * WillCore.UI * WillCore.Session WillCore.SSE integrates with the global event system available in WillCore.UI. Events can be sent to an active session. One session can emit events to another session by that session's ID. Server-side events can be used to update the front-end when something happens on the server, an example of this will be a chat application. Server-side events is an alternative to websockets. ## Getting Started The SSE module can be installed on an existing project using NPM: ```javascript npm install willcore.sse ``` The SSE module has to be activated both server-side and client-side. It is an assignable on the UI proxy. #### Activating SSE server-side ```javascript willcore.serverInstance.ui.sseContainerName.sse; ``` ### __SSE assignable (server-side)__ Has Name | Assignable values | Assignable result | Can assign to -------- | ----------------- | ----------------- | ------------- ✔ | None | SSEProxy | UIProxy The sseContainerName is the name of the SSE container. This will be the property where the container instance will be available to emit events on. ```javascript //Full example: const willCoreProxy = require("willcore.core"); willcore.testServer.server[__dirname] = 8581; willcore.testServer.http; willcore.testServer.user.session; willcore.testServer.ui; willcore.testServer.ui.sseContainer.sse; ``` #### Activating SSE client-side Client side activating is done in the app.js file ```javascript willcore.ui.sse; ``` ### __SSE assignable (client-side)__ Has Name | Assignable values | Assignable result | Can assign to -------- | ----------------- | ----------------- | ------------- ❌ | None | None | UIProxy ```javascript //Full example let init = (willcore, service) => { willcore.ui; willcore.ui.sse; }; export { init }; ``` ## SSE Enabled Sessions To emit an event to a session, a session has to contain an identification field (id) in the session object. This can be the primary key of the user or another identifier to identify the user. #### Create a session with an ID ```javascript //Account service module.exports = (service, server, willcore) => { //Authentication action service.authenticate.action.post = async (model) => { //Creates a session with an identification field. model.user.authenticate({ id: model.id }); }; }; ``` ## Emitting Events To An Session A function "emit" will be available on the SSE container proxy that can be used to emit events to a session. #### Emit Function Parameters Parameter Index | Parameter Name | Parameter Type | Description --------------- | -------------- | -------------- | ----------- 1 | Target Session ID | Number or String | The ID of the target session. 2 | Event Name | String | The name of the event that will be emitted to the session. 3 | Event Data | Object, Number or String | The event data that will be send via the SSE to the target session's front-end. #### Example action that emits an event to a target session ```javascript //Message service module.exports = (service, server, willcore) => { //Action to send message service.sendMessage.action.post = async (model) => { server.ui.sseContainer.emit(model.targetId,"message",model.message); }; }; ``` ### Listing To Events The SSE events will present themselves as global WillCore.UI events. The event name will be the same as the event name the event is submitted as. To start the SSE engine, an event with data of value true should be emitted to the startSSE event. #### Example view that listens to the message event emitted in the example above. ```javascript //View function const view = async (model, ui, server, events) => { //Start the SSE engine events.startSSE = true; events.message = (data) =>{ console.log(`A message is received from the server: ${data}`); }; }; export { view }; ``` > #### Please note that the user must be authenticated with a valid session before SSE events can be received. ### Connected And Disconnected Status An event "sseConnected" will be emitted when the SSE connection is connected to the server or when the connection is dropped form the server. This will happen when the server is offline or the connection is dropped. The data of the event will be a boolean indicating if the connection is connected or not. #### Example to log to the console when the connection is dropped or connected ```javascript //View function const view = async (model, ui, server, events) => { //Start the SSE engine events.startSSE = true; events.sseConnected = (connected) =>{ if (connected){ console.log("SSE is connected."); }else{ console.log("SSE is disconnected."); } }; }; export { view }; ``` The sseConnected event can be forced by emitting an "requestSSEStatus" event.<file_sep>let init = (willcore, service) => { willcore.ui; willcore.ui.sse; }; export { init };<file_sep>module.exports = (service, server, willcore) => { service.authenticate.action.post = async (model) => { model.user.authenticate({ id: model.id }); model.message = "You are logged in"; }; service.isAuthenticated.action.get = async (model) => { model.isAuth = model.user.authenticated; }; service.blocked.action.get = async (model) => { model.message = "You are allowed"; }; service.blocked.before.authorize; service.logout.action.post = async (model) => { model.user.remove(); model.message = "Logged out"; }; service.message.action.post = async (model) => { server.ui.sseContainer.emit(model.id,"message",model.message); }; };<file_sep>module.exports = (willCoreModuleInstance) => { willCoreModuleInstance.sse = () => require("../server_server/assignables/sseAssignable.js"); };
c26c90946d8c5f8582137025bc72c6656d87e44f
[ "JavaScript", "Markdown" ]
9
JavaScript
PhilipCoder/willcore.sse
5ffd101d6b36e22341d6c87b532f160eb8666e71
1582d688348607342ca914ae9448537b9c6d2c5d
refs/heads/master
<repo_name>shanelledeveaux/houserpractice<file_sep>/src/components/Header/Header.js import React from "react"; import "./Header.css"; const Header = props => { return <div className="main">Houser</div>; }; export default Header; <file_sep>/src/components/Wizard/Wizard2.js import React, { Component } from "react"; import "./Wizard.css"; import { Link } from "react-router-dom"; import { connect } from "react-redux"; import { updateImage } from "../../ducks/reducer"; class Wizard2 extends Component { render() { console.log("WIZARD 2 PROPS", this.props); const { updateImage } = this.props; return ( <div className="wizard"> <div className="title">Update Image</div> {/* <img src={updateImage} /> */} <div className="form2"> Image URL: <input onChange={e => updateImage(e.target.value)} /> </div> <Link to="/wizard3"> <button>Next</button> </Link> <Link to="/wizard"> <button>Back</button> </Link> </div> ); } } const mapStateToProps = state => state; export default connect( mapStateToProps, { updateImage } )(Wizard2); <file_sep>/src/routes.js import React from "react"; import { Switch, Route } from "react-router-dom"; import Dashboard from "./components/Dashboard/Dashboard"; import Wizard from "./components/Wizard/Wizard"; import Wizard2 from "./components/Wizard/Wizard2"; import Wizard3 from "./components/Wizard/Wizard3"; export default ( <Switch> <Route component={Dashboard} exact path="/" /> <Route component={Wizard} exact path="/wizard" /> <Route component={Wizard2} exact path="/wizard2" /> <Route component={Wizard3} exact path="/wizard3" /> </Switch> ); <file_sep>/db/delete_house.sql delete from houselist where house_id =$1; select * from houselist;<file_sep>/src/ducks/reducer.js import axios from "axios"; const initialState = { name: "", address: "", city: "", userState: "", zipcode: "", imageurl: "", mortgage: null, rent: null, houses: [] }; const UPDATE_NAME = "UPDATE_NAME"; const UPDATE_ADDRESS = "UPDATE_ADDRESS"; const UPDATE_CITY = "UPDATE_CITY"; const UPDATE_USERSTATE = "UPDATE_USERSTATE"; const UPDATE_ZIP = "UPDATE_ZIP"; const UPDATE_IMAGE = "UPDATE_IMAGE"; const UPDATE_MORTGAGE = "UPDATE_MORTGAGE"; const UPDATE_RENT = "UPDATE_RENT"; const SUBMIT_HOUSE = "SUBMIT_HOUSE"; function reducer(state = initialState, action) { switch (action.type) { case UPDATE_NAME: return Object.assign({}, state, { name: action.payload }); case UPDATE_ADDRESS: return Object.assign({}, state, { address: action.payload }); case UPDATE_CITY: return Object.assign({}, state, { city: action.payload }); case UPDATE_USERSTATE: return Object.assign({}, state, { userState: action.payload }); case UPDATE_ZIP: return Object.assign({}, state, { zipcode: action.payload }); case UPDATE_IMAGE: return Object.assign({}, state, { imageurl: action.payload }); case UPDATE_MORTGAGE: return Object.assign({}, state, { mortgage: action.payload }); case UPDATE_RENT: return Object.assign({}, state, { rent: action.payload }); case SUBMIT_HOUSE: return Object.assign({}, state, { houses: action.payload }); default: return state; } } export default reducer; export function updateName(name) { return { type: UPDATE_NAME, payload: name }; } export function updateAddress(address) { return { type: UPDATE_ADDRESS, payload: address }; } export function updateCity(city) { return { type: UPDATE_CITY, payload: city }; } export function updateUserState(userState) { return { type: UPDATE_USERSTATE, payload: userState }; } export function updateZip(zipcode) { return { type: UPDATE_ZIP, payload: zipcode }; } export function updateImage(imageurl) { return { type: UPDATE_IMAGE, payload: imageurl }; } // export function updateMortgage(mortgage) { // return { // type: UPDATE_MORTGAGE, // payload: mortgage // }; // } // export function updateRent(rent) { // return { // type: UPDATE_RENT, // payload: rent // }; // } export function submitHouse( name, address, city, userState, zipcode, imageurl, mortgage, rent ) { // console.log(action.payload); return { type: SUBMIT_HOUSE, payload: axios.post("/api/newhouse", { name, address, city, userState, zipcode, imageurl, mortgage, rent }) }; } <file_sep>/db/get_houses.sql select * from houselist;<file_sep>/src/components/Wizard/Wizard3.js import React, { Component } from "react"; import "./Wizard.css"; import { Link } from "react-router-dom"; import { connect } from "react-redux"; import { updateName, updateAddress, updateCity, updateUserState, updateZip, updateImage, // updateMortgage, // updateRent, submitHouse } from "../../ducks/reducer"; class Wizard3 extends Component { state = { rent: 0, mortgage: 0 }; update = e => { this.setState({ [e.target.name]: e.target.value }); }; submitDone = () => { const { name, address, city, userState, zipcode, imageurl } = this.props; this.props .submitHouse( name, address, city, userState, zipcode, imageurl, this.state.mortgage, this.state.rent ) .then(() => (window.location.href = "/")); }; render() { console.log("WIZARD 3 PROPS", this.props, this.state); return ( <div className="wizard"> <div className="title">Add Rent</div> <div className="form"> Monthly Mortgage: <input onChange={this.update} value={this.state.mortgage} name="mortgage" /> {/* <div>Recommended Rent: ${updateMortgage * 1.25}</div> */} Desired Rent: <input onChange={this.update} value={this.state.rent} name="rent" /> </div> <button onClick={() => this.submitDone()}>Complete</button> <Link to="/wizard2"> <button>Back</button> </Link> </div> ); } } const mapStateToProps = state => state; export default connect( mapStateToProps, { updateName, updateAddress, updateCity, updateUserState, updateZip, updateImage, // updateMortgage, // updateRent, submitHouse } )(Wizard3);
3165bea301672d40c0398114dc8bf58d52d413af
[ "JavaScript", "SQL" ]
7
JavaScript
shanelledeveaux/houserpractice
d074a0f3512c7a4293e63cebb64e363dcb8b17dd
635163e5571f7b4ce05b6db168c4ae81ead7716a
refs/heads/master
<file_sep> import java.util.HashMap; import java.util.HashSet; import java.util.Set; /** * PersonTracker maintains a HashMap of current tracking ID and body pose data. It also * maintains sets of new tracking IDs (enters) and IDs not longer being tracked (exits). * PersionTracker update should be called every frame with new tracknig data. * * @author eitan * */ public class PersonTracker { protected HashSet<Long> enters = new HashSet<Long>(); protected HashSet<Long> exits = new HashSet<Long>(); private HashMap<Long, Body> peopleOld = new HashMap<Long, Body>(); // keep this for reuse protected HashMap<Long, Body> people = new HashMap<Long, Body>(); public PersonTracker() { } /** * @return returns a Set of Track IDs of people who entered the space during the most * recent call to update. Any ID in enter set will also be in HashMap returned by getPeople. */ public HashSet<Long> getEnters() { return enters; } /** * @return returns a Set of Track IDs of people who exited the space during the most * recent call to update. Any ID in exit set will not be in HashMap returned by getPeople. */ public HashSet<Long> getExits() { return exits; } /** * @return returns a Set of Track IDs of people currently in the space. */ public Set<Long> getIds() { return people.keySet(); } /** * @return returns a HashMap of Track IDs to Bodys (tracking information) * for people of people currently in the space. */ public HashMap<Long, Body> getPeople() { return people; } /** * Swaps current people hashmap with oldPeople HashMap for re-use. */ private void swapActiveSet() { HashMap<Long, Body> tmp = people; people = peopleOld; peopleOld = tmp; } /** * update should be called every frame. It compares current tracking information to * tracking information from the last frame and generates enters, exits, and people. * * @param data - current tracking data */ public void update(KinectBodyData data) { swapActiveSet(); people.clear(); int cnt = data.getPersonCount(); // System.out.println("person count" + data.getPersonCount()); for(int i =0 ; i < cnt; i++) { Body body = data.getPerson(i); people.put(body.id, body); } enters.clear(); enters.addAll(people.keySet()); enters.removeAll(peopleOld.keySet()); exits.clear(); exits.addAll(peopleOld.keySet()); exits.removeAll(people.keySet()); /* for(Long l : enters) { System.out.println("enter:"+ l); } for(Long l : exits) { System.out.println(" exit:"+ l); } */ } }<file_sep>import processing.core.PApplet; import processing.core.PGraphics; import processing.core.PImage; import processing.core.PVector; public class Person { private static int TRAIL = 30; private Body body; private PApplet app; private PVector headv, ribsv, lefthandv, righthandv; private PImage head, ribs; private Bouquet flowers; private boolean disappear = false; //true if flowers should be disappearing private Decay state; PImage headFlower, smoke; private boolean noDecay = true; PVector prevPosHead; PVector prevPosRibs; PVector[] lefthandarray; PVector[] righthandarray; PVector prevPosLeft; PVector prevPosRight; int counter; public Person(PApplet app) { this.app = app; head = app.loadImage("assets/goathead.png"); ribs = app.loadImage("assets/ribcase.png"); smoke = app.loadImage("assets/smoke.png"); flowers = new Bouquet(app); headFlower = app.loadImage("assets/pinkflower.png"); state = Decay.Sun; prevPosHead = new PVector(0,0,0); prevPosRibs = new PVector(0,0,0); lefthandarray = new PVector[TRAIL]; righthandarray = new PVector[TRAIL]; prevPosLeft = new PVector(999,999,0); prevPosRight = new PVector(999,999,0); counter = 0; } public void update(Body body) { headv = body.getJoint(Body.HEAD); ribsv = body.getJoint(Body.SPINE_BASE); //track hands lefthandv = body.getJoint(Body.HAND_LEFT); righthandv = body.getJoint(Body.HAND_RIGHT); if(lefthandv != null){ prevPosLeft = lefthandv; lefthandarray[counter] = lefthandv; } else{ lefthandarray[counter] = prevPosLeft; } if(righthandv != null){ prevPosRight = righthandv; righthandarray[counter] = righthandv; } else { righthandarray[counter] = prevPosRight; } } public void draw() { this.drawHead(); this.drawRibs(); this.drawHandTrails(); } public void drawHandTrails(){ PVector leftH; PVector rightH; //drawing here vvv for(int i = 0; i < TRAIL; i++){ if(counter == 0 && i == 0 ){ leftH = lefthandarray[0]; rightH = righthandarray[0]; } else { leftH = lefthandarray[(counter+i)%TRAIL]; rightH = righthandarray[(counter+i)%TRAIL]; } if(leftH != null && rightH != null){ app.image(smoke, leftH.x-.1f, leftH.y, .2f, .2f); app.image(smoke, rightH.x+.1f, rightH.y, .2f, .2f); // app.fill(192, ((255/TRAIL) * i)); // app.noStroke(); // app.ellipse(leftH.x, leftH.y, .1f, .1f); // app.ellipse(rightH.x, rightH.y, .1f, .1f); } } counter++; if(counter >= TRAIL){ counter = 0; } } /** * Display the background appropriate to the current state */ public void drawBackground() { if(state == Decay.Sun) { //nice background } else if(state == Decay.Moon) { //vein thing } } public Decay getState() { return state; } public void drawHead() { if(headv != null) { float smoothx = (prevPosHead.x+headv.x)/2f; float smoothy = (prevPosHead.y+headv.y)/2f; app.image(head, smoothx, smoothy+.1f, 1.3f, 1.1f); //draw flower on head if (disappear) { app.tint(230, 0, 150); app.image(headFlower, smoothx, smoothy + .2f, .2f, .2f); app.tint(255,255,255); } else { app.tint(255, 255, 255); app.image(headFlower, smoothx, smoothy + .2f, .2f, .2f); } prevPosHead = headv; } else { app.image(head, prevPosHead.x, prevPosHead.y+.1f, 1.3f, 1.1f); //draw flower on head app.image(headFlower, prevPosHead.x, prevPosHead.y+.2f, .2f, .2f); if (disappear) { app.tint(230, 0, 150); app.image(headFlower, prevPosHead.x, prevPosHead.y + .2f, .2f, .2f); app.tint(255,255,255); } else { app.tint(255, 255, 255); app.image(headFlower, prevPosHead.x, prevPosHead.y + .2f, .2f, .2f); } } } public void drawRibs() { if(ribsv != null) { float smoothx = (prevPosRibs.x+ribsv.x)/2f; float smoothy = (prevPosRibs.y+ribsv.y)/2f; //draw ribs themselves app.image(ribs, smoothx, smoothy - .25f, ribs.width/100, ribs.height/100); //draw flowers on the ribs flowerCheck(); boolean stateChange = flowers.draw(smoothx, smoothy, disappear); if (stateChange && disappear) { state = Decay.Moon; } if (stateChange && !disappear) { state = Decay.Sun; } prevPosRibs = ribsv; } else { app.image(ribs, prevPosRibs.x, prevPosRibs.y - .25f, ribs.width/100, ribs.height/100); //draw flowers on the ribs flowerCheck(); boolean stateChange = flowers.draw(prevPosRibs.x, prevPosRibs.y, disappear); if (stateChange && disappear) { state = Decay.Moon; } if (stateChange && !disappear) { state = Decay.Sun; } } } public PVector getHead() { return headv; } public PVector getSpine() { return ribsv; } private void flowerCheck() { // if(ribsv != null) { // if(ribsv.x < 0) { // disappear = true; // } // else { // disappear = false; // } // } //if the hands are in front of the face-ish float diam = 0.3f; if(lefthandv != null && righthandv != null && headv != null) { if(Math.abs(lefthandv.x-headv.x) < diam && Math.abs(righthandv.x-headv.x) < diam && Math.abs(lefthandv.y-headv.y) < diam && Math.abs(righthandv.y-headv.y) < diam) { if(lefthandv.z < headv.z && righthandv.z < headv.z) { disappear = true; } else { disappear = false; } } else { disappear = false; } } } }<file_sep>import java.io.IOException; import java.util.Iterator; import java.util.LinkedHashMap; import processing.core.PApplet; import processing.core.PGraphics; import processing.core.PImage; import processing.core.PVector; public class DecayApp extends PApplet{ public static float PROJECTOR_RATIO = 1080f/1920.0f; //float width, heightE; PGraphics buffer; String recordingFile = "test.kinect"; KinectBodyDataProvider kinectReader; PersonTracker tracker = new PersonTracker(); private int r, g, b; //current color values private static int sr = 0, sg = 153, sb = 255; //final values for the sun state private static int mr = 150, mg = 0, mb = 50; //final values for the moon state private float sunY; private float moonY; private float setRate = .005f; Decay currentState = Decay.Sun; Person p; Iterator<Body> i; LinkedHashMap<Long, Person> people; PImage fadeImage, sunImage, moonImage; public void settings() { createWindow(true, false, .5f); } public void setup() { try { kinectReader = new KinectBodyDataProvider("test2.kinect", 1); } catch (IOException e) { System.out.println("Unable to create kinect producer"); } //kinectReader = new KinectBodyDataProvider(8008); //set initial colors r = sr; g = sg; b = sb; //set planet coords sunY = .5f; moonY = -3.5f; people = new LinkedHashMap<Long, Person>(); fadeImage = loadImage("assets/featuredbgfadeflipped.png"); sunImage = loadImage("assets/sun.png"); moonImage = loadImage("assets/moon.png"); kinectReader.start(); } public void draw() { setScale(0.5f); imageMode(CENTER); background(0, 0, 0); KinectBodyData bodyData = kinectReader.getMostRecentData(); tracker.update(bodyData); drawBackground(currentState); i = tracker.getPeople().values().iterator(); if (i.hasNext()) { Body b = i.next(); p = people.get(b.getId()); if (p == null) { p = new Person(this); people.put(b.getId(), p); } while (i.hasNext()) { Body b2 = i.next(); if (!tracker.getPeople().keySet().contains(b2.getId())) i.remove(); } currentState = p.getState(); p.update(b); p.draw(); } } private void drawBackground(Decay currentState) { if (currentState == Decay.Sun) { //move/draw the sun if(sunY < .5) sunY += setRate; image(sunImage, 1, sunY, 1, 1); if(moonY > -3.5) moonY -= setRate; image(moonImage, -1, moonY, 1, 1); //de/increment colors if(r > sr) r--; if(g < sg) g++; if(b < sb) b++; //draw the background tint(r, g, b); image(fadeImage, 0, 0, this.displayWidth / 250, this.displayHeight / 250); tint(255, 255, 255); } else if (currentState == Decay.Moon) { //move/draw the moon if(moonY < .5) moonY += setRate; image(moonImage, -1, moonY, 1, 1); if(sunY > -3.5) sunY -= setRate; image(sunImage, 1, sunY, 1, 1); //de/increment colors if(r < mr) r++; if(g > mg) g--; if(b > mb) b--; //draw the background tint(r, g, b); image(fadeImage, 0, 0, this.displayWidth / 250, this.displayHeight / 250); tint(255,255,255); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public void createWindow(boolean useP2D, boolean isFullscreen, float windowsScale) { if (useP2D) { if(isFullscreen) { fullScreen(P2D); } else { size((int)(1920 * windowsScale), (int)(1080 * windowsScale), P2D); } } else { if(isFullscreen) { fullScreen(); } else { size((int)(1920 * windowsScale), (int)(1080 * windowsScale)); } } } // use lower numbers to zoom out (show more of the world) // zoom of 1 means that the window is 2 meters wide and appox 1 meter tall. public void setScale(float zoom) { scale(zoom* width/2.0f, zoom * -width/2.0f); translate(1f/zoom , -PROJECTOR_RATIO/zoom ); //height = 2f * (PROJECTOR_RATIO/zoom); //width = 2f * (1f/zoom); //System.out.println(this.height + " " + 2f * (PROJECTOR_RATIO/zoom)); } public static void main(String[] args) { PApplet.main(DecayApp.class.getName()); } } <file_sep> public enum Decay { Sun, Moon } <file_sep>import processing.core.PApplet; import processing.core.PImage; /** * Represents a single flower to be rendered and manipulated on the screen * @author Sara, Isabelle, Lauren * */ public class Flower { private PImage img; private PApplet parent; private float relativeX; //the distance this flower is from the center - fixed upon construction private float relativeY; //the distance this flower is from the center - fixed upon construction private float width = .2f; private float growRate; //so flowers shrink and grow at different rates public Flower(PApplet parent, float relativeX, float relativeY) { //randomly pick which image this flower will be this.parent = parent; this.relativeX = relativeX; this.relativeY = relativeY; growRate = parent.random(.00025f,.001f); // growRate = parent.random(.001f, .005f); //much faster grow rate for testing selectFlower(); } public void draw(float newX, float newY) { parent.image(img, newX+relativeX, newY+relativeY, width, width); } /** * @return true if flowers are fully grown */ public boolean grow() { if(width < .2f) width+=growRate; else { //change state to bright background with falling colors (or something) if it hasn't already been done return true; } return false; } /** * @return true if flowers are completely gone */ public boolean vanish() { if(width > 0) width-=growRate; else { //change state to dark-veiny stuff if it hasn't already been done return true; } if(width < 0) //safety net width = 0; return false; } private void selectFlower() { double ranFlower = parent.random(0,1); if(ranFlower < .1) { img = parent.loadImage("assets/deepredflower.png"); } else if(ranFlower < .2) { img = parent.loadImage("assets/yellowflower.png"); } else if(ranFlower < .3) { img = parent.loadImage("assets/greenfiller.png"); } else if(ranFlower < .4) { img = parent.loadImage("assets/greenflower.png"); } else if(ranFlower < .5) { img = parent.loadImage("assets/lightblueflower.png"); } else if(ranFlower < .6) { img = parent.loadImage("assets/pinkflower.png"); //may not be transparent } else if(ranFlower < .7) { img = parent.loadImage("assets/purpleflower.png"); } else if(ranFlower < .8) { img = parent.loadImage("assets/sunsetflower.png"); } else if(ranFlower < .9) { img = parent.loadImage("assets/whitegreenflower.png"); } else { img = parent.loadImage("assets/whiteredflower.png"); } } public void addGrow(float add) { growRate += add; } }
1435e75f62ee19d31fe9710822b3020960bcb86c
[ "Java" ]
5
Java
igriffin415/decay
8e7eaeda6063fa9079a119780ad453b9ebd54f6b
b03ccbae4bf387a289df644829cb50052c667fac
refs/heads/main
<file_sep>// // ExtViewController+Test.swift // ARDicee // // Created by <NAME> on 28/04/2021. // import UIKit import SceneKit import ARKit // MARK: - Extension Tests extension ViewController { /// test with ship private func addBaseScn() { // Create a new scene guard let scene = SCNScene(named: "art.scnassets/ship.scn") else { return } // Set the scene to the view sceneView.scene = scene } /// test with sphere private func addSphereScn() { let sphere = SCNSphere(radius: 0.2) let material = SCNMaterial() material.diffuse.contents = UIImage(named: "art.scnassets/moon.jpg") sphere.materials = [material] // let node = SCNNode() // node.geometry = sphere // 2 lines equal to => let node = SCNNode(geometry: sphere) let node = SCNNode(geometry: sphere) node.position = SCNVector3(0, 0.1, -0.5) sceneView.scene.rootNode.addChildNode(node) } /// test with cube private func addCubeScn() { let cube = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0.01) let material = SCNMaterial() material.diffuse.contents = UIColor.red cube.materials = [material] let node = SCNNode() node.position = SCNVector3(0, 0.1, -0.5) node.geometry = cube sceneView.scene.rootNode.addChildNode(node) } /// test with basic dices private func addDiceScn() { guard let diceScene = SCNScene(named: "art.scnassets/diceCollada.scn") else { return } guard let diceNode = diceScene.rootNode.childNode(withName: "Dice", recursively: true) else { return } diceNode.position = SCNVector3(0, 0, -0.1) sceneView.scene.rootNode.addChildNode(diceNode) } }
51f0ac416e895cc73ccf2f242390c5a7d3303320
[ "Swift" ]
1
Swift
jessangel79/ARDicee
eb9adc805c8bac8a2af5fb87ed568bfa581867ee
beb2abffa7039d5ff68567dfea1f4f75aa791bd9
refs/heads/main
<file_sep># twinintwinkle.github.io <file_sep>var language = new RadialProgressChart('#cantonese', { diameter: 300, max: 360, round: false, series: [ { value: 350, color: ['#D47800', '#00FFF7'] } ], center: function (d) { return 'Cantonese'; } }); var language = new RadialProgressChart('#mandarin', { diameter: 300, max: 360, round: false, series: [ { value: 340, color: ['#D47800', '#00FFF7'] } ], center: function (d) { return 'Mandarin'; } }); var language = new RadialProgressChart('#english', { diameter: 300, max: 360, round: false, series: [ { value: 290, color: ['#D47800', '#00FFF7'] } ], center: function (d) { return 'English'; } }); var language = new RadialProgressChart('#japanese', { diameter: 300, max: 360, round: false, series: [ { value: 140, color: ['#D47800', '#00FFF7'] } ], center: function (d) { return 'Japanese'; } }); var language = new RadialProgressChart('#german', { diameter: 300, max: 360, round: false, series: [ { value: 40, color: ['#D47800', '#00FFF7'] } ], center: function (d) { return 'German'; } }); var language = new RadialProgressChart('#html', { diameter: 300, max: 360, round: false, series: [ { value: 300, color: ['#D47800', '#00FFF7'] } ], center: function (d) { return 'HTML'; } }); var language = new RadialProgressChart('#css', { diameter: 300, max: 360, round: false, series: [ { value: 200, color: ['#D47800', '#00FFF7'] } ], center: function (d) { return 'CSS'; } }); var language = new RadialProgressChart('#java', { diameter: 300, max: 360, round: false, series: [ { value: 180, color: ['#D47800', '#00FFF7'] } ], center: function (d) { return 'Java'; } }); var language = new RadialProgressChart('#python', { diameter: 300, max: 360, round: false, series: [ { value: 100, color: ['#D47800', '#00FFF7'] } ], center: function (d) { return 'Python'; } }); var language = new RadialProgressChart('#c', { diameter: 300, max: 360, round: false, series: [ { value: 70, color: ['#D47800', '#00FFF7'] } ], center: function (d) { return 'C'; } }); var language = new RadialProgressChart('#javascript', { diameter: 300, max: 360, round: false, series: [ { value: 40, color: ['#D47800', '#00FFF7'] } ], center: function (d) { return 'Javascript'; } });<file_sep>var filterCheck = { uiux: true, motiongraphic: true, graphic: true, programming: true, others: true }; document.addEventListener('DOMContentLoaded', function () { var showallbtn = document.getElementById('showall_btn'); if (showallbtn) { showallbtn.onclick = function () { var btns = document.getElementsByClassName("filter_btn"); filterCheck.uiux = true, filterCheck.motiongraphic = true, filterCheck.grphic = true, filterCheck.programming = true, filterCheck.others = true; for (var i = 0; i < btns.length; i++) { btns[i].classList.add("active"); } } } var uibtn = document.getElementById('ui_btn'); if (uibtn) { uibtn.onclick = function () { filterCheck.uiux = change(uibtn, "uiux"); } } var motionbtn = document.getElementById('motion_btn'); if (motionbtn) { motionbtn.onclick = function () { filterCheck.motiongraphic = change(motionbtn, "motiongraphic"); } } var graphicbtn = document.getElementById('graphic_btn'); if (graphicbtn) { graphicbtn.onclick = function () { filterCheck.graphic = change(graphicbtn, "graphic"); } } var programmingbtn = document.getElementById('programming_btn'); if (programmingbtn) { programmingbtn.onclick = function () { filterCheck.programming = change(programmingbtn, "programming"); } } var othersbtn = document.getElementById('others_btn'); if (othersbtn) { othersbtn.onclick = function () { filterCheck.others = change(othersbtn, "others"); } } document.querySelectorAll('.filter_btn').forEach(item => { item.addEventListener('click', check); }) }); function change(btn, element) { var element_value = eval("filterCheck." + element); if (element_value == true) { element_value = false; btn.classList.remove("active"); } else { element_value = true; btn.classList.add("active"); } return element_value; } function check() { for (const [key, value] of Object.entries(filterCheck)) { if (value == false) { checkFalse(key); } } for (const [key, value] of Object.entries(filterCheck)) { if (value == true) { checkTrue(key); } } } function checkFalse(element) { var hide = document.getElementsByClassName(element); for (var i = 0; i < hide.length; i++) { hide[i].classList.add("filterDiv"); } } function checkTrue(element) { var show = document.getElementsByClassName(element); for (var i = 0; i < show.length; i++) { show[i].classList.remove("filterDiv"); } }
8e8970c0365c0753a5ed4d4ea17ffdfd2c90212b
[ "Markdown", "JavaScript" ]
3
Markdown
twinintwinkle/twinintwinkle.github.io
1df656415bddafb3a62f72f753a16ca6d6fde123
b93bfa831104a1bf02e29f33d493a7b19fe77d47
refs/heads/master
<repo_name>SapegaDungeonMaster/fdfg<file_sep>/WindowsFormsApp4/WindowsFormsApp4/Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.OleDb; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp4 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Professional\Desktop\курсач.accdb"); private void textBox1_TextChanged(object sender, EventArgs e) { Form1 f1 = new Form1(); } private void button1_Click(object sender, EventArgs e) { login(); } private void login() { string log = textBox1.Text; string pas = textBox2.Text; con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT count(*) FROM Преподаватель where Логин = '" + log + "' and Пароль ='" + pas + "'"; cmd.ExecuteNonQuery(); con.Close(); DataTable dt = new DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); if (int.Parse(dt.Rows[0][0].ToString()) == 1) { Form2 f2 = new Form2(); f2.Show(); con.Close(); this.Hide(); } else { MessageBox.Show("Не удается войти", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void textBox2_TextChanged(object sender, EventArgs e) { } private void checkBox1_CheckedChanged(object sender, EventArgs e) { if (checkBox1.Checked == true) { textBox2.PasswordChar = '\0'; } if (checkBox1.Checked == false) { textBox2.PasswordChar = '*'; } } private void Form1_Load(object sender, EventArgs e) { } private void textBox2_KeyUp(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { login(); } } } } <file_sep>/WindowsFormsApp4/WindowsFormsApp4/Queries.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WindowsFormsApp4 { class Queries { public static string selectgrup = "SELECT код_группы, количество_учащихся, название_специальности, группа FROM Группа, Специальность WHERE Группа.код_специальности=Специальность.код_специальности "; public static string selectdis = "SELECT * FROM Дисциплины"; public static string selectdis_grup = "SELECT код_дисциплины_группы, название_дисциплины, группа, номер_кабинета,количество_часов_дисциплины FROM Дисциплины_группы, Дисциплины, Группа, Кабинет WHERE Дисциплины_группы.код_дисциплины=Дисциплины.код_дисциплины and Дисциплины_группы.код_группы=Группа.код_группы and Дисциплины_группы.код_кабинета=Кабинет.код_кабинета"; public static string selectzaniat = "SELECT код_занятия, номер_кабинета, группа, дата_расписания,ФИО,название_дисциплины FROM Занятие, Кабинет, Расписание,Дисциплины,Преподаватель WHERE Занятие.код_кабинета=Кабинет.код_кабинета and Занятие.id_расписания=Расписание.id_расписания and Занятие.код_дисциплины=Дисциплины.код_дисциплины and Занятие.код_преподавателя=Преподаватель.код_преподавателя"; public static string selectkabinet = "SELECT * FROM Кабинет"; public static string selectprepod = "SELECT * FROM Преподаватель"; public static string selectraspisan = "SELECT Расписание.id_расписания, Расписание.дата_расписания, Кабинет.номер_кабинета, Группа.группа, Дисциплины.название_дисциплины FROM Кабинет INNER JOIN(Дисциплины INNER JOIN (Группа INNER JOIN Расписание ON Группа.код_группы = Расписание.код_группы) ON Дисциплины.код_дисциплины = Расписание.код_дисципины) ON Кабинет.код_кабинета = Расписание.код_кабинета;"; public static string selectspecial = "SELECT * FROM Специальность"; public static string selectycha = "SELECT Учащиеся.код_учащегося, Учащиеся.ФИО, Учащиеся.телефон, Учащиеся.улица, Учащиеся.дата_рождения, Группа.группа FROM Группа INNER JOIN Учащиеся ON Группа.код_группы = Учащиеся.код_группы"; } } <file_sep>/WindowsFormsApp4/WindowsFormsApp4/Form3.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.OleDb; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Word = Microsoft.Office.Interop.Word; using Microsoft.Office.Interop.Excel; using Application = Microsoft.Office.Interop.Excel.Application; using System.Reflection; using System.Runtime.InteropServices; using System.IO; using Microsoft.Office.Interop.Word; using Range = Microsoft.Office.Interop.Excel.Range; namespace WindowsFormsApp4 { public partial class Form3 : Form { OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Professional\Desktop\курсач.accdb"); public Form3() { InitializeComponent(); } private void Form3_Load(object sender, EventArgs e) { con.Open(); OleDbCommand cmd = new OleDbCommand("Select дата_расписания FROM Расписание", con); OleDbDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { comboBox5.Items.Add(reader.GetString(0)); } } private void группаToolStripMenuItem_Click(object sender, EventArgs e) { Form3 f3 = new Form3(); f3.Text = "Группа"; f3.Show(); this.Close(); } private void дисциплиныToolStripMenuItem_Click(object sender, EventArgs e) { Form3 f3 = new Form3(); f3.Text = "Дисциплины"; f3.Show(); this.Close(); } private void дисциплиныгурппыToolStripMenuItem_Click(object sender, EventArgs e) { Form3 f3 = new Form3(); f3.Text = "Дисциплины_группы"; f3.Show(); this.Close(); } private void занятиеToolStripMenuItem_Click(object sender, EventArgs e) { Form3 f3 = new Form3(); f3.Text = "Занятие"; f3.Show(); this.Close(); } private void кабинетToolStripMenuItem_Click(object sender, EventArgs e) { Form3 f3 = new Form3(); f3.Text = "Кабинет"; f3.Show(); this.Close(); } private void преподавательToolStripMenuItem_Click(object sender, EventArgs e) { Form3 f3 = new Form3(); f3.Text = "Преподаватель"; f3.Show(); this.Close(); } private void расписаниеToolStripMenuItem_Click(object sender, EventArgs e) { Form3 f3 = new Form3(); f3.Text = "Расписание"; f3.Show(); this.Close(); } private void специальностьToolStripMenuItem_Click(object sender, EventArgs e) { Form3 f3 = new Form3(); f3.Text = "Специальность"; f3.Show(); this.Close(); } private void учащиесяToolStripMenuItem_Click(object sender, EventArgs e) { Form3 f3 = new Form3(); f3.Text = "Учащиеся"; f3.Show(); this.Close(); } public void loadTable(string selectTable) { if(con.State != ConnectionState.Open) { con.Open(); } OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = selectTable; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; } private void Form3_Shown(object sender, EventArgs e) { } private void Form3_Shown_1(object sender, EventArgs e) { if (this.Text == "Группа") { loadTable(Queries.selectgrup); dataGridView1.Columns[0].Visible = false; string[] array = getSpecial().Select(n => n.ToString()).ToArray(); comboBox1.Items.AddRange(array); } if (this.Text == "Дисциплины") { loadTable(Queries.selectdis); dataGridView1.Columns[0].Visible = false; } if (this.Text == "Дисциплины_группы") { loadTable(Queries.selectdis_grup); dataGridView1.Columns[0].Visible = false; string[] array = getDis().Select(n => n.ToString()).ToArray(); comboBox1.Items.AddRange(array); string[] array1 = getGrup().Select(n => n.ToString()).ToArray(); comboBox2.Items.AddRange(array1); string[] array2 = getKabinet().Select(n => n.ToString()).ToArray(); comboBox3.Items.AddRange(array2); } if (this.Text == "Занятие") { loadTable(Queries.selectzaniat); string[] array = getKabinet().Select(n => n.ToString()).ToArray(); comboBox1.Items.AddRange(array); string[] array1 = getRaspis().Select(n => n.ToString()).ToArray(); comboBox2.Items.AddRange(array1); string[] array2 = getDis().Select(n => n.ToString()).ToArray(); comboBox3.Items.AddRange(array2); string[] array3 = getPrepod().Select(n => n.ToString()).ToArray(); comboBox4.Items.AddRange(array3); dataGridView1.Columns[0].Visible = false; } if (this.Text == "Кабинет") { loadTable(Queries.selectkabinet); dataGridView1.Columns[0].Visible = false; } if (this.Text == "Преподаватель") { loadTable(Queries.selectprepod); dataGridView1.Columns[0].Visible = false; string[] array = getDis().Select(n => n.ToString()).ToArray(); comboBox1.Items.AddRange(array); } if (this.Text == "Расписание") { loadTable(Queries.selectraspisan); dataGridView1.Columns[0].Visible = false; string[] array = getKabinet().Select(n => n.ToString()).ToArray(); comboBox1.Items.AddRange(array); string[] array1 = getGrup().Select(n => n.ToString()).ToArray(); comboBox2.Items.AddRange(array1); string[] array2 = getDis().Select(n => n.ToString()).ToArray(); comboBox3.Items.AddRange(array2); } if (this.Text == "Специальность") { loadTable(Queries.selectspecial); dataGridView1.Columns[0].Visible = false; } if (this.Text == "Учащиеся") { loadTable(Queries.selectycha); dataGridView1.Columns[0].Visible = false; string[] array = getGrup().Select(n => n.ToString()).ToArray(); comboBox1.Items.AddRange(array); } } private int getIdByGrup(string nameGrup) { con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT код_группы FROM Группа where группа = '" + nameGrup + "'"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); return int.Parse(dt.Rows[0][0].ToString()); } private int getIdBySpecial(string nameClient) { con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT код_специальности FROM Специальность where название_специальности = '" + nameClient + "'"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); return int.Parse(dt.Rows[0][0].ToString()); } private int getIdByPrepod(string nameClient) { con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT код_преподавателя FROM Преподаватель where ФИО = '" + nameClient + "'"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); return int.Parse(dt.Rows[0][0].ToString()); } private int getIdByKabinet(string nameClient) { con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT код_кабинета FROM Кабинет where номер_кабинета = '" + nameClient + "'"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); return int.Parse(dt.Rows[0][0].ToString()); } private int getIdByDisGrup(string nameClient) { con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT код_дисциплины_группы FROM Дисциплины_группы where название_дисциплины = '" + nameClient + "'"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); return int.Parse(dt.Rows[0][0].ToString()); } private int getIdByDis(string nameClient) { con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT код_дисциплины FROM Дисциплины where название_дисциплины = '" + nameClient + "'"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); return int.Parse(dt.Rows[0][0].ToString()); } private int getIdByRaspis(string nameClient) { con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT id_расписания FROM Расписание where дата_расписания = '" + nameClient + "'"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); return int.Parse(dt.Rows[0][0].ToString()); } private List<string> getGrup() { List<string> grup = new List<string>(); con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT * FROM Группа"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); foreach (DataRow item in dt.Rows) { grup.Add(item[3].ToString()); } return grup; } private List<string> getSpecial() { List<string> special = new List<string>(); con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT * FROM Специальность"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); foreach (DataRow item in dt.Rows) { special.Add(item[1].ToString()); } return special; } private List<string> getPrepod() { List<string> prepod = new List<string>(); con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT * FROM Преподаватель"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); foreach (DataRow item in dt.Rows) { prepod.Add(item[2].ToString()); } return prepod; } private List<string> getKabinet() { List<string> kabinet = new List<string>(); con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT * FROM Кабинет"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); foreach (DataRow item in dt.Rows) { kabinet.Add(item[1].ToString()); } return kabinet; } private List<string> getDisGrup() { List<string> disgrup = new List<string>(); con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT * FROM Дисциплины_группы"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); foreach (DataRow item in dt.Rows) { disgrup.Add(item[3].ToString()); } return disgrup; } private List<string> getDis() { List<string> dis = new List<string>(); con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT * FROM Дисциплины"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); foreach (DataRow item in dt.Rows) { dis.Add(item[1].ToString()); } return dis; } private List<string> getRaspis() { List<string> raspis = new List<string>(); con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT * FROM Расписание"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); foreach (DataRow item in dt.Rows) { raspis.Add(item[1].ToString()); } return raspis; } private void добавитьToolStripMenuItem_Click(object sender, EventArgs e) { if (this.Text == "Группа") { int idSpecial = getIdBySpecial(comboBox1.SelectedItem.ToString()); con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "INSERT INTO Группа (количество_учащихся, код_специальности, группа) VALUES('" + textBox2.Text + "'," + idSpecial + ",'" + textBox3.Text + "')"; cmd.ExecuteNonQuery(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT код_группы, количество_учащихся, название_специальности, группа FROM Группа, Специальность WHERE Группа.код_специальности=Специальность.код_специальности "; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; MessageBox.Show("Изменения сохранены!", "Сохранено", MessageBoxButtons.OK, MessageBoxIcon.Information); } else if (this.Text == "Дисциплины") { bool result = checkBox1.Checked; con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "INSERT INTO Дисциплины (название_дисциплины,экзамен) VALUES('" + textBox2.Text + "'," + result + ")"; cmd.ExecuteNonQuery(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT * FROM Дисциплины"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; MessageBox.Show("Изменения сохранены!", "Сохранено", MessageBoxButtons.OK, MessageBoxIcon.Information); } else if (this.Text == "Дисциплины_группы") { int idDis = getIdByDis(comboBox1.SelectedItem.ToString()); int idGrup = getIdByGrup(comboBox2.SelectedItem.ToString()); int idKabinet = getIdByKabinet(comboBox3.SelectedItem.ToString()); con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "INSERT INTO Дисциплины_группы (код_дисциплины,код_группы,код_кабинета,количество_часов_дисциплины) VALUES(" + idDis + "," + idGrup + "," + idKabinet + ",'" + textBox2.Text + "')"; cmd.ExecuteNonQuery(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT код_дисциплины_группы, название_дисциплины, группа, номер_кабинета,количество_часов_дисциплины FROM Дисциплины_группы, Дисциплины, Группа, Кабинет WHERE Дисциплины_группы.код_дисциплины=Дисциплины.код_дисциплины and Дисциплины_группы.код_группы=Группа.код_группы and Дисциплины_группы.код_кабинета=Кабинет.код_кабинета"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; MessageBox.Show("Изменения сохранены!", "Сохранено", MessageBoxButtons.OK, MessageBoxIcon.Information); } else if (this.Text == "Занятие") { int idKabinet = getIdByKabinet(comboBox1.SelectedItem.ToString()); int idRaspis = getIdByRaspis(comboBox2.SelectedItem.ToString()); int idDis = getIdByDis(comboBox3.SelectedItem.ToString()); int idPrepod = getIdByPrepod(comboBox4.SelectedItem.ToString()); con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "INSERT INTO Занятие (код_кабинета,группа,id_расписания,код_дисциплины,код_преподавателя) VALUES(" + idKabinet + ",'" + textBox2.Text + "'," + idRaspis + "," + idDis + "," + idPrepod + ")"; cmd.ExecuteNonQuery(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT код_занятия, номер_кабинета, группа, дата_расписания,ФИО,название_дисциплины FROM Занятие, Кабинет, Расписание,Дисциплины,Преподаватель WHERE Занятие.код_кабинета=Кабинет.код_кабинета and Занятие.id_расписания=Расписание.id_расписания and Занятие.код_дисциплины=Дисциплины.код_дисциплины and Занятие.код_преподавателя=Преподаватель.код_преподавателя"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; MessageBox.Show("Изменения сохранены!", "Сохранено", MessageBoxButtons.OK, MessageBoxIcon.Information); } else if (this.Text == "Кабинет") { con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "INSERT INTO Кабинет (номер_кабинета) VALUES('" + textBox2.Text + "')"; cmd.ExecuteNonQuery(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT * FROM Кабинет"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; MessageBox.Show("Изменения сохранены!", "Сохранено", MessageBoxButtons.OK, MessageBoxIcon.Information); } else if (this.Text == "Преподаватель") { con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "INSERT INTO Преподаватель (номер_кабинета_преподавателя,ФИО) VALUES('" + textBox2.Text + "','" + textBox3.Text + "')"; cmd.ExecuteNonQuery(); cmd.CommandType = CommandType.Text; cmd.CommandText = Queries.selectprepod; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; MessageBox.Show("Изменения сохранены!", "Сохранено", MessageBoxButtons.OK, MessageBoxIcon.Information); loadTable(Queries.selectprepod); } else if (this.Text == "Расписание") { int idKabinet = getIdByKabinet(comboBox1.SelectedItem.ToString()); int idGruppi = getIdByGrup(comboBox2.SelectedItem.ToString()); int idDisc = getIdByDis(comboBox3.SelectedItem.ToString()); con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "INSERT INTO Расписание (дата_расписания,код_кабинета, код_группы, код_дисципины) VALUES('" + textBox2.Text + "'," + idKabinet + ", "+idGruppi+", "+idDisc+")"; cmd.ExecuteNonQuery(); cmd.CommandType = CommandType.Text; cmd.CommandText = Queries.selectraspisan; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; MessageBox.Show("Изменения сохранены!", "Сохранено", MessageBoxButtons.OK, MessageBoxIcon.Information); } else if (this.Text == "Специальность") { con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "INSERT INTO Специальность (название_специальности) VALUES('" + textBox2.Text + "')"; cmd.ExecuteNonQuery(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT * FROM Специальность"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; MessageBox.Show("Изменения сохранены!", "Сохранено", MessageBoxButtons.OK, MessageBoxIcon.Information); } else if (this.Text == "Учащиеся") { int idGrup = getIdByGrup(comboBox1.SelectedItem.ToString()); con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "INSERT INTO Учащиеся (ФИО,телефон,улица,дата_рождения,код_группы) VALUES('" + textBox2.Text + "'," + textBox3.Text + ",'" + textBox4.Text + "','" + textBox5.Text + "'," + idGrup + ")"; cmd.ExecuteNonQuery(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT Учащиеся.код_учащегося, Учащиеся.ФИО, Учащиеся.телефон, Учащиеся.улица, Учащиеся.дата_рождения, Группа.группа FROM Группа INNER JOIN Учащиеся ON Группа.код_группы = Учащиеся.код_группы"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; MessageBox.Show("Изменения сохранены!", "Сохранено", MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void button1_Click(object sender, EventArgs e) { Form3_Shown(sender, e); } private void удалитьToolStripMenuItem_Click(object sender, EventArgs e) { if (this.Text == "Группа") { int ID = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value); con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "DELETE From Группа WHERE код_группы=" + ID + ""; cmd.ExecuteNonQuery(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT * FROM Группа"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; MessageBox.Show("Изменения сохранены!", "Сохранено", MessageBoxButtons.OK, MessageBoxIcon.Information); } if (this.Text == "Дисциплины") { int ID = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value); con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "DELETE From Дисциплины WHERE код_дисциплины=" + ID + ""; cmd.ExecuteNonQuery(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT * FROM Дисциплины"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; MessageBox.Show("Изменения сохранены!", "Сохранено", MessageBoxButtons.OK, MessageBoxIcon.Information); } if (this.Text == "Дисциплины_группы") { int ID = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value); con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "DELETE From Дисциплины_группы WHERE код_дисциплины_группы=" + ID + ""; cmd.ExecuteNonQuery(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT код_дисциплины_группы, название_дисциплины, группа, номер_кабинета,количество_часов_дисциплины FROM Дисциплины_группы, Дисциплины, Группа, Кабинет WHERE Дисциплины_группы.код_дисциплины=Дисциплины.код_дисциплины and Дисциплины_группы.код_группы=Группа.код_группы and Дисциплины_группы.код_кабинета=Кабинет.код_кабинета"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; MessageBox.Show("Изменения сохранены!", "Сохранено", MessageBoxButtons.OK, MessageBoxIcon.Information); } if (this.Text == "Занятие") { int ID = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value); con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "DELETE From Занятие WHERE код_занятия=" + ID + ""; cmd.ExecuteNonQuery(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT * FROM Занятие"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; MessageBox.Show("Изменения сохранены!", "Сохранено", MessageBoxButtons.OK, MessageBoxIcon.Information); } if (this.Text == "Кабинет") { int ID = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value); con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "DELETE From Кабинет WHERE код_кабинета=" + ID + ""; cmd.ExecuteNonQuery(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT * FROM Кабинет"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; MessageBox.Show("Изменения сохранены!", "Сохранено", MessageBoxButtons.OK, MessageBoxIcon.Information); } if (this.Text == "Преподаватель") { int ID = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value); con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "DELETE From Преподаватель WHERE код_преподавателя=" + ID + ""; cmd.ExecuteNonQuery(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT * FROM Преподаватель"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; MessageBox.Show("Изменения сохранены!", "Сохранено", MessageBoxButtons.OK, MessageBoxIcon.Information); } if (this.Text == "Расписание") { int ID = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value); con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "DELETE From Расписание WHERE id_расписания=" + ID + ""; cmd.ExecuteNonQuery(); cmd.CommandType = CommandType.Text; cmd.CommandText = Queries.selectraspisan; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; MessageBox.Show("Изменения сохранены!", "Сохранено", MessageBoxButtons.OK, MessageBoxIcon.Information); } if (this.Text == "Специальность") { int ID = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value); con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "DELETE From Специальность WHERE код_специальности=" + ID + ""; cmd.ExecuteNonQuery(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT * FROM Специальность"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; MessageBox.Show("Изменения сохранены!", "Сохранено", MessageBoxButtons.OK, MessageBoxIcon.Information); } if (this.Text == "Учащиеся") { int ID = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value); con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "DELETE From Учащиеся WHERE код_учащегося=" + ID + ""; cmd.ExecuteNonQuery(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT * FROM Учащиеся"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; MessageBox.Show("Изменения сохранены!", "Сохранено", MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void изменитьToolStripMenuItem_Click(object sender, EventArgs e) { if (this.Text == "Группа") { int ID = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value.ToString()); int idSpecial = getIdBySpecial(comboBox1.Text); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; con.Open(); cmd.CommandText = "UPDATE Группа SET количество_учащихся=" + textBox2.Text + ", код_специальности=" + idSpecial + " , группа='" + textBox3.Text + "' WHERE код_группы =" + ID + ""; cmd.ExecuteNonQuery(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT код_группы, количество_учащихся, название_специальности, группа FROM Группа, Специальность WHERE Группа.код_специальности=Специальность.код_специальности "; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; MessageBox.Show("Изменения сохранены!", "Сохранено", MessageBoxButtons.OK, MessageBoxIcon.Information); } if (this.Text == "Дисциплины") { int ID = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value.ToString()); bool result = checkBox1.Checked; OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; con.Open(); cmd.CommandText = "UPDATE Дисциплины SET название_дисциплины='" + textBox2.Text + "', Экзамен=" + result + " WHERE код_дисциплины =" + ID + ""; ; cmd.ExecuteNonQuery(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT * FROM Дисциплины"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; MessageBox.Show("Изменения сохранены!", "Сохранено", MessageBoxButtons.OK, MessageBoxIcon.Information); } if (this.Text == "Дисциплины_группы") { int ID = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value.ToString()); int idDis = getIdByDis(comboBox1.Text); int idGrup = getIdByGrup(comboBox2.Text); int idKabinet = getIdByKabinet(comboBox3.Text); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; con.Open(); cmd.CommandText = "UPDATE Дисциплины_группы SET код_дисциплины=" + idDis + ", код_группы=" + idGrup + ",код_кабинета=" + idKabinet + ",количество_часов_дисциплины='" + Convert.ToInt16(textBox2.Text) + "' WHERE код_дисциплины_группы =" + ID + ""; cmd.ExecuteNonQuery(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT код_дисциплины_группы, название_дисциплины, группа, номер_кабинета, количество_часов_дисциплины FROM Дисциплины_группы, Дисциплины, Группа, Кабинет WHERE Дисциплины_группы.код_дисциплины=Дисциплины.код_дисциплины and Дисциплины_группы.код_группы=Группа.код_группы and Дисциплины_группы.код_кабинета=Кабинет.код_кабинета"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; MessageBox.Show("Изменения сохранены!", "Сохранено", MessageBoxButtons.OK, MessageBoxIcon.Information); } if (this.Text == "Занятие") { int ID = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value.ToString()); int idKabinet = getIdByKabinet(comboBox1.SelectedItem.ToString()); int idRaspis = getIdByRaspis(comboBox2.SelectedItem.ToString()); int idDis = getIdByDis(comboBox3.SelectedItem.ToString()); int idPrepod = getIdByPrepod(comboBox4.SelectedItem.ToString()); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; con.Open(); cmd.CommandText = "UPDATE Занятие SET код_кабинета=" + idKabinet + ", группа='" + textBox2.Text + "',id_расписания=" + idRaspis + ",код_дисциплины=" + idDis + ",код_преподавателя=" + idPrepod + " WHERE код_занятия =" + ID + ""; ; cmd.ExecuteNonQuery(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT код_занятия, номер_кабинета, группа, дата_расписания,ФИО,название_дисциплины FROM Занятие, Кабинет, Расписание,Дисциплины,Преподаватель WHERE Занятие.код_кабинета=Кабинет.код_кабинета and Занятие.id_расписания=Расписание.id_расписания and Занятие.код_дисциплины=Дисциплины.код_дисциплины and Занятие.код_преподавателя=Преподаватель.код_преподавателя"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; MessageBox.Show("Изменения сохранены!", "Сохранено", MessageBoxButtons.OK, MessageBoxIcon.Information); } if (this.Text == "Кабинет") { int ID = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value.ToString()); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; con.Open(); cmd.CommandText = "UPDATE Кабинет SET номер_кабинета='" + textBox2.Text + "' WHERE код_кабинета =" + ID + ""; ; cmd.ExecuteNonQuery(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT * FROM Кабинет"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; MessageBox.Show("Изменения сохранены!", "Сохранено", MessageBoxButtons.OK, MessageBoxIcon.Information); } if (this.Text == "Преподаватель") { int ID = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value.ToString()); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; con.Open(); cmd.CommandText = "UPDATE Преподаватель SET номер_кабинета_преподавателя='" + textBox2.Text + "',ФИО='" + textBox3.Text + "' WHERE код_преподавателя =" + ID + ""; ; cmd.ExecuteNonQuery(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT * FROM Преподаватель"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; MessageBox.Show("Изменения сохранены!", "Сохранено", MessageBoxButtons.OK, MessageBoxIcon.Information); } if (this.Text == "Расписание") { int ID = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value.ToString()); int idKabinet = getIdByKabinet(comboBox1.Text); int idDis = getIdByDis(comboBox3.SelectedItem.ToString()); int idGruppa = getIdByGrup(comboBox2.SelectedItem.ToString()); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; con.Open(); cmd.CommandText = "UPDATE Расписание SET дата_расписания='" + textBox2.Text + "',код_кабинета=" + idKabinet + " , код_группы ="+ idGruppa +", код_дисципины ="+ idDis +" WHERE id_расписания =" + ID + ""; ; cmd.ExecuteNonQuery(); cmd.CommandType = CommandType.Text; cmd.CommandText = Queries.selectraspisan; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; MessageBox.Show("Изменения сохранены!", "Сохранено", MessageBoxButtons.OK, MessageBoxIcon.Information); } if (this.Text == "Специальность") { int ID = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value.ToString()); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; con.Open(); cmd.CommandText = "UPDATE Специальность SET название_специальности='" + textBox2.Text + "' WHERE код_специальности =" + ID + ""; ; cmd.ExecuteNonQuery(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT * FROM Специальность"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; MessageBox.Show("Изменения сохранены!", "Сохранено", MessageBoxButtons.OK, MessageBoxIcon.Information); } if (this.Text == "Учащиеся") { int ID = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value.ToString()); int idGrup = getIdByGrup(comboBox1.Text); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; con.Open(); cmd.CommandText = "UPDATE Учащиеся SET ФИО='" + textBox2.Text + "' ,телефон='" + textBox3.Text + "' ,улица='" + textBox4.Text + "' ,дата_рождения='" + Convert.ToDateTime(textBox5.Text) + "',код_группы=" + idGrup + " WHERE код_учащегося=" + ID + ""; ; cmd.ExecuteNonQuery(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT Учащиеся.код_учащегося, Учащиеся.ФИО, Учащиеся.телефон, Учащиеся.улица, Учащиеся.дата_рождения, Группа.группа FROM Группа INNER JOIN Учащиеся ON Группа.код_группы = Учащиеся.код_группы"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; MessageBox.Show("Изменения сохранены!", "Сохранено", MessageBoxButtons.OK, MessageBoxIcon.Information); } } public bool ClassesTeacher(bool result) { return result; } private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { if (this.Text == "Группа") { textBox2.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString(); comboBox1.SelectedItem = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString(); textBox3.Text = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString(); } if (this.Text == "Дисциплины") { textBox2.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString(); textBox3.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString(); } if (this.Text == "Дисциплины_группы") { comboBox1.SelectedItem = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString(); comboBox2.SelectedItem = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString(); comboBox3.SelectedItem = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString(); textBox2.Text = dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString(); } if (this.Text == "Занятие") { comboBox1.SelectedItem = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString(); textBox2.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString(); comboBox2.SelectedItem = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString(); comboBox3.SelectedItem = dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString(); comboBox4.SelectedItem = dataGridView1.Rows[e.RowIndex].Cells[5].Value.ToString(); } if (this.Text == "Кабинет") { textBox2.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString(); } if (this.Text == "Преподаватель") { textBox2.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString(); textBox3.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString(); } if (this.Text == "Расписание") { textBox2.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString(); comboBox1.SelectedItem = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString(); comboBox2.SelectedItem = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString(); comboBox3.SelectedItem = dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString(); } if (this.Text == "Специальность") { textBox2.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString(); } if (this.Text == "Учащиеся") { textBox2.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString(); textBox3.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString(); textBox4.Text = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString(); textBox5.Text = dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString(); comboBox1.SelectedItem = dataGridView1.Rows[e.RowIndex].Cells[5].Value.ToString(); } } private void wordToolStripMenuItem_Click(object sender, EventArgs e) { SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "Word Documents (*.docx)|*.docx"; sfd.FileName = "export.docx"; if (sfd.ShowDialog() == DialogResult.OK) { Export_Data_To_Word(dataGridView1, sfd.FileName); } } public void Export_Data_To_Word(DataGridView DGV, string filename) { if (DGV.Rows.Count != 0) { int RowCount = DGV.Rows.Count; int ColumnCount = DGV.Columns.Count; Object[,] DataArray = new object[RowCount + 1, ColumnCount + 1]; //add rows int r = 0; for (int c = 0; c <= ColumnCount - 1; c++) { for (r = 0; r <= RowCount - 1; r++) { DataArray[r, c] = DGV.Rows[r].Cells[c].Value; } //end row loop } //end column loop Word.Document oDoc = new Word.Document(); oDoc.Application.Visible = true; //page orintation oDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape; dynamic oRange = oDoc.Content.Application.Selection.Range; string oTemp = ""; for (r = 0; r <= RowCount - 1; r++) { for (int c = 0; c <= ColumnCount - 1; c++) { oTemp = oTemp + DataArray[r, c] + "\t"; } } //table format oRange.Text = oTemp; object Separator = Word.WdTableFieldSeparator.wdSeparateByTabs; object ApplyBorders = true; object AutoFit = true; object AutoFitBehavior = Word.WdAutoFitBehavior.wdAutoFitContent; oRange.ConvertToTable(ref Separator, ref RowCount, ref ColumnCount, Type.Missing, Type.Missing, ref ApplyBorders, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, ref AutoFit, ref AutoFitBehavior, Type.Missing); oRange.Select(); oDoc.Application.Selection.Tables[1].Select(); oDoc.Application.Selection.Tables[1].Rows.AllowBreakAcrossPages = 0; oDoc.Application.Selection.Tables[1].Rows.Alignment = 0; oDoc.Application.Selection.Tables[1].Rows[1].Select(); oDoc.Application.Selection.InsertRowsAbove(1); oDoc.Application.Selection.Tables[1].Rows[1].Select(); //header row style oDoc.Application.Selection.Tables[1].Rows[1].Range.Bold = 1; oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Name = "Tahoma"; oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Size = 14; //add header row manually for (int c = 0; c <= ColumnCount - 1; c++) { oDoc.Application.Selection.Tables[1].Cell(1, c + 1).Range.Text = DGV.Columns[c].HeaderText; } //table style oDoc.Application.Selection.Tables[1].set_Style("Сетка таблицы"); oDoc.Application.Selection.Tables[1].Rows[1].Select(); oDoc.Application.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; //header text foreach (Word.Section section in oDoc.Application.ActiveDocument.Sections) { Word.Range headerRange = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage); headerRange.Text = this.Text; headerRange.Font.Size = 16; headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; } //save the file oDoc.SaveAs2(filename); //NASSIM LOUCHANI } } private Application xlExcel; private Workbook xlWorkBook; private void excelToolStripMenuItem_Click(object sender, EventArgs e) { try { this.QuitExcel(); this.xlExcel = new Application { Visible = false }; this.xlWorkBook = this.xlExcel.Workbooks.Add(Missing.Value); // Copy contents of grid into clipboard, open new instance of excel, a new workbook and sheet, // paste clipboard contents into new sheet. this.CopyGrid(); var xlWorkSheet = (Worksheet)this.xlWorkBook.Worksheets.Item[1]; try { var cr = (Range)xlWorkSheet.Cells[1, 1]; try { cr.Select(); xlWorkSheet.PasteSpecial(cr, NoHTMLFormatting: true); } finally { Marshal.ReleaseComObject(cr); } this.xlWorkBook.SaveAs(Path.Combine(Path.GetTempPath(), "ItemUpdate.xls"), XlFileFormat.xlExcel5); } finally { Marshal.ReleaseComObject(xlWorkSheet); } MessageBox.Show("File Save Successful", "Information", MessageBoxButtons.OK); //// If box is checked, show the exported file. Otherwise quit Excel. //if (this.checkBox1.Checked) //{ this.xlExcel.Visible = true; //} //else //{ // this.QuitExcel(); //} } catch (SystemException ex) { MessageBox.Show(ex.ToString()); } // Set the Selection Mode back to Cell Select to avoid conflict with sorting mode. this.dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect; } private void CopyGrid() { // I'm making this up... this.dataGridView1.SelectAll(); var data = this.dataGridView1.GetClipboardContent(); if (data != null) { Clipboard.SetDataObject(data, true); } } private void QuitExcel() { if (this.xlWorkBook != null) { try { this.xlWorkBook.Close(); Marshal.ReleaseComObject(this.xlWorkBook); } catch (COMException) { } this.xlWorkBook = null; } if (this.xlExcel != null) { try { this.xlExcel.Quit(); Marshal.ReleaseComObject(this.xlExcel); } catch (COMException) { } this.xlExcel = null; } } private void textBox9_TextChanged(object sender, EventArgs e) { } private void textBox1_TextChanged(object sender, EventArgs e) { } private void button1_Click_1(object sender, EventArgs e) { Form3_Shown(sender, e); } private void textBox1_TextChanged_1(object sender, EventArgs e) { for (int i = 0; i < dataGridView1.RowCount; i++) { for (int j = 0; j < dataGridView1.ColumnCount; j++) { if (dataGridView1.Rows[i].Cells[j].Value != null) { dataGridView1.Rows[i].Cells[j].Value.ToString().ToLower(); } } } if (this.Text == "Группа") { con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT код_группы, количество_учащихся, название_специальности, группа FROM Группа, Специальность WHERE Группа.код_специальности=Специальность.код_специальности and количество_учащихся LIKE '%" + textBox1.Text.ToLower() + "%' or название_специальности LIKE '%" + textBox1.Text.ToLower() + "%' or группа LIKE '%" + textBox1.Text.ToLower() + "%'"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; } if (this.Text == "Дисциплины") { con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT * FROM Дисциплины WHERE название_дисциплины LIKE '%" + textBox1.Text.ToLower() + "%' or Экзамен LIKE '%" + textBox1.Text.ToLower() + "%' "; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; } if (this.Text == "Дисциплины_группы") { con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT код_дисциплины_группы, название_дисциплины, группа, номер_кабинета, количество_часов_дисциплины FROM Дисциплины_группы, Дисциплины, Группа, Кабинет WHERE Дисциплины_группы.код_дисциплины=Дисциплины.код_дисциплины and Дисциплины_группы.код_группы=Группа.код_группы and Дисциплины_группы.код_кабинета=Кабинет.код_кабинета and название_дисциплины LIKE '%" + textBox1.Text.ToLower() + "%' or группа LIKE '%" + textBox1.Text.ToLower() + "%' or номер_кабинета LIKE '%" + textBox1.Text.ToLower() + "%' or количество_часов_дисциплины LIKE '%" + textBox1.Text.ToLower() + "%'"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; } if (this.Text == "Занятие") { con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT код_занятия, номер_кабинета, группа, дата_расписания,ФИО,название_дисциплины FROM Занятие, Кабинет, Расписание,Дисциплины,Преподаватель WHERE Занятие.код_кабинета=Кабинет.код_кабинета and Занятие.id_расписания=Расписание.id_расписания and Занятие.код_дисциплины=Дисциплины.код_дисциплины and Занятие.код_преподавателя=Преподаватель.код_преподавателя and номер_кабинета LIKE '%" + textBox1.Text.ToLower() + "%' or группа LIKE '%" + textBox1.Text.ToLower() + "%' or дата_расписания LIKE '%" + textBox1.Text.ToLower() + "%' or ФИО LIKE '%" + textBox1.Text.ToLower() + "%'or название_дисциплины LIKE '%" + textBox1.Text.ToLower() + "%'"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; } if (this.Text == "Кабинет") { con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT * FROM Кабинет WHERE номер_кабинета LIKE '%" + textBox1.Text.ToLower() + "%' "; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; } if (this.Text == "Преподаватель") { con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT * FROM Преподаватель WHERE номер_кабинета_преподавателя LIKE '%" + textBox1.Text.ToLower() + "%' or ФИО LIKE '%" + textBox1.Text.ToLower() + "%' or Логин LIKE '%" + textBox1.Text.ToLower() + "%'or Пароль LIKE '%" + textBox1.Text.ToLower() + "%'"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; } if (this.Text == "Расписание") { con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT * FROM Расписание WHERE дата_расписания LIKE '%" + textBox1.Text.ToLower() + "%' "; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; } if (this.Text == "Специальность") { con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT * FROM Специальность WHERE название_специальности LIKE '%" + textBox1.Text.ToLower() + "%' "; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; } if (this.Text == "Учащиеся") { con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT Учащиеся.код_учащегося, Учащиеся.ФИО, Учащиеся.телефон, Учащиеся.улица, Учащиеся.дата_рождения, Группа.группа FROM Группа INNER JOIN Учащиеся ON Группа.код_группы = Учащиеся.код_группы WHERE ФИО LIKE '%" + textBox1.Text.ToLower() + "%' or телефон LIKE '%" + textBox1.Text.ToLower() + "%' or улица LIKE '%" + textBox1.Text.ToLower() + "%' or дата_рождения LIKE '%" + textBox1.Text.ToLower() + "%'or группа LIKE '%" + textBox1.Text.ToLower() + "%'"; cmd.ExecuteNonQuery(); con.Close(); System.Data.DataTable dt = new System.Data.DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); dataGridView1.DataSource = dt; } } private void поДатеToolStripMenuItem_Click(object sender, EventArgs e) { if (this.Text == "Расписание") { Form4 f4 = new Form4(); f4.Show(); loadTable(Queries.selectraspisan); } } private void Form3_Activated(object sender, EventArgs e) { } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void Form3_Activated_1(object sender, EventArgs e) { if (Form4.first != null && Form4.second != null) { loadTable($@"SELECT Расписание.id_расписания, Расписание.дата_расписания, Кабинет.номер_кабинета, Группа.группа, Дисциплины.название_дисциплины FROM Кабинет INNER JOIN (Дисциплины INNER JOIN (Группа INNER JOIN Расписание ON Группа.код_группы = Расписание.код_группы) ON Дисциплины.код_дисциплины = Расписание.код_дисципины) ON Кабинет.код_кабинета = Расписание.код_кабинета WHERE Расписание.дата_расписания between #{Form4.first}# and #{Form4.second}#"); } } private void comboBox5_SelectedIndexChanged(object sender, EventArgs e) { } } }
68d8dd13a24adf850cb42718896b86a5e6500bba
[ "C#" ]
3
C#
SapegaDungeonMaster/fdfg
739ec8b3f1cb17ff86e1cd5961635c7b71682408
febb787de7b310e5c0d73d9126c5540d3a63a6bf
refs/heads/master
<repo_name>Adithya93/trimai<file_sep>/public/app.js import React, { Component } from 'react'; import ReactDOM from 'react-dom'; class MessageBox extends Component { constructor() { super(); this.state = { messages: [] } } render() { /* let msgs; if (this.messages) { msgs = this.messages.map((msg) => ); } */ return ( <div> {this.state.messages} </div> ); } _addMessage(message) { let messageElem = <Message text={message}/> let messages = this.state.messages.concat([messageElem]); this.setState({messages}) } } class Message extends Component { constructor() { super(); } render() { return ( <div> {this.props.text} </div> ); } } /* ReactDOM.render( <MessageBox />, document.getElementById('react-test') ); */ export {MessageBox, Message};<file_sep>/src/index.js 'use strict'; //import React from 'react'; //import ReactDOM from 'react-dom'; //import {MessageBox, Message} from './app' //import MessageBox from './views/app'; //import './index.css'; /* var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); var port = process.env.PORT || 3000; var handleResponses = require('./bot-responses'); */ import express from 'express'; import http from 'http'; import {handleResponses, handleButtonClick} from './bot-responses'; import SocketIO from 'socket.io'; const app = express(); const server = http.Server(app); const io = new SocketIO(server); const port = process.env.PORT || 3000; const dirname = "/Users/radithya/Desktop/summer17/trimai"; const GREETING = "Welcome friend! How are you today?"; app.use(express.static('public')) app.get('/', function(req, res) { res.sendFile(dirname + '/public/index.html'); console.log("New request received!"); }); console.log("Server successfully setup!"); /* ReactDOM.render( <MessageBox />, document.getElementById('react-test') ); */ io.on('connection', function(socket){ if (!socket['seen']) { socket['seen'] = true; console.log('Someone connected!'); // Risky, may not be attached to React Component yet socket.emit('bot_msg', JSON.stringify({type:'text', 'text':GREETING})); } socket.on('user_msg', function(msg){ //io.emit('chat message', msg); console.log("User: " + msg); // Handle message based on user state (Tag user state on socket?) let response = handleResponses(msg); console.log("About to send response " + response); socket.emit('bot_msg', response); }); socket.on('button_click', function(payload) { console.log("User clicked on button " + payload); let response = handleButtonClick(payload); socket.emit('bot_msg', response); }) socket.on('disconnect', function() { console.log('Someone disconnected!'); }); }); server.listen(port, function(){ console.log('listening on *:' + port); }); <file_sep>/README.md Chatbot built using Socket.io, NodeJS and React with ES6 <file_sep>/src/app.js import React, { Component } from 'react'; import ReactDOM from 'react-dom'; const BOT_PREFIX = "Awesome Bot: "; class MessageBox extends Component { constructor() { super(); this.state = { //socket : null messages: [] }; this._addMessage = this._addMessage.bind(this); this._addBotMessage = this._addBotMessage.bind(this); this._postBack = this._postBack.bind(this); } componentWillMount() { //this.state.socket } render() { return ( <div> <ul id="messages"> {this.state.messages} </ul> <MessageForm addMessage={this._addMessage} addBotMessage={this._addBotMessage} socket={this.props.socket}/> </div> ); } // Message entered by user can only be text message, clicking of button is handled separately _addMessage(msg) { //let messages = this.state.messages.concat([msg]); let messages = this.state.messages.concat([<Message text={msg}/>]); this.setState({messages}); window.scrollTo(0, document.body.scrollHeight); } // Parse JSON and determine what kind of message to add, e.g. button messages, picture messages, etc _addBotMessage(msg) { console.log("Message from bot: " + msg); let msgJson = JSON.parse(msg); let messages; let text = BOT_PREFIX + msgJson['text']; if (msgJson['type'] === 'text') { messages = this.state.messages.concat([<BotMessage text={text}/>]); } else if (msgJson['type'] === 'button') { messages = this.state.messages.concat([<ButtonMessage text={text} options={msgJson['options']} clickHandler={this._postBack} />]) } else { messages = this.state.messages.concat([<PictureMessage text={text} urls={msgJson['urls']} />]); } this.setState({messages}); } // Currently only for buttons _postBack(payload) { console.log("Informing bot of button click!"); this.props.socket.emit('button_click', JSON.stringify(payload)); } } class MessageForm extends Component { constructor() { super(); this.state = { text : "", clear: false }; this._handleUserMessage = this._handleUserMessage.bind(this); } componentWillMount() { //this.props.socket.on('bot_msg', (msg) => this.props.addBotMessage("Awesome Bot: " + msg)); // TO-DO : Parse JSON and display accordingly this.props.socket.on('bot_msg', (msg) => this.props.addBotMessage(msg)); } render() { if (this.state.clear) { this.state.clear = false; return ( <form action="" onSubmit={this._handleUserMessage}> <input id="m" autocomplete="off" placeholder="Say something :)" value = "" ref={c => {this.state.text=c}} /><button>Send</button> </form> ); } return ( <form action="" onSubmit={this._handleUserMessage}> <input id="m" autocomplete="off" placeholder="Say something :)" ref={c => {this.state.text = c}} /><button>Send</button> </form> ); } _handleUserMessage(e) { e.preventDefault(); console.log("Message being posted!"); //this._addMessage(this.state.text); this.props.addMessage("You: " + this.state.text.value); this.props.socket.emit('user_msg', this.state.text.value); this._clearText(); return false; } _clearText() { this.setState({text: "", clear:true}); } } class Message extends Component { constructor() { super(); } render() { return ( <li className="user"> {this.props.text} </li> ); } } class BotMessage extends Component { constructor() { super(); } render() { return ( <li className="bot"> {this.props.text} </li> ); } } class ButtonMessage extends Component { constructor() { super(); this._postBack = this._postBack.bind(this); } render() { return ( <li className="bot"> <div> {this.props.text} </div> <div> {this.props.options.map((option) => <button onClick={(e) => this._postBack(e, option['payload'])}>{option['text']}</button>)} </div> </li> ); } _postBack(e, payload) { e.preventDefault(); this.props.clickHandler(payload); } } class PictureMessage extends Component { constructor() { super(); } render() { const MAX_WIDTH_PERCENTAGE = 80; const HEIGHT_IN_PIXELS = 150; const MAX_SINGLE_WIDTH_PERCENTAGE = 50; let width_percentage = parseInt(MAX_WIDTH_PERCENTAGE / this.props.urls.length) + "%"; width_percentage = width_percentage > MAX_SINGLE_WIDTH_PERCENTAGE ? MAX_SINGLE_WIDTH_PERCENTAGE : width_percentage; return ( <li className="bot"> <div> {this.props.text} </div> <div> {this.props.urls.map((url) => <img src={url} alt="Nice Picture" height={HEIGHT_IN_PIXELS} width={width_percentage}/>)} </div> </li> ); } } ReactDOM.render( <MessageBox socket={io()}/>, document.getElementById('target') ); export {MessageBox, Message};<file_sep>/src/bot-responses.js let msgs = 0; function handleResponses(userMsg) { // TODO : Use FSM from script to determine which one to send let mod = msgs ++ %3; if (mod == 0) return sendTextMessage("Booyakasha! Your message was " + userMsg.length + " characters long."); if (mod == 1) return sendButtonMessage("Wanna chit-chat?", [{text:"Yes", payload:"yes"}, {text:"No", payload:"no"}]); return sendPictureMessage("Isn't this cute? :P", ["https://static.pexels.com/photos/104827/cat-pet-animal-domestic-104827.jpeg"]); } function sendTextMessage(text) { return JSON.stringify({type: "text", text}); } function sendButtonMessage(text, options) { return JSON.stringify({type:"button", text, options}); } function sendPictureMessage(text, urls) { return JSON.stringify({type:"picture", text, urls}); } function handleButtonClick(payload) { return sendTextMessage("Wow, I didn't expect you to say " + payload); } //export default handleResponses; export {handleResponses, handleButtonClick};
1ffdaf45af7d6a5f598db297098a23d86809c6dd
[ "JavaScript", "Markdown" ]
5
JavaScript
Adithya93/trimai
765417391899600ea19aab3f1135858ab5f60922
c3a7178d3101004e0a0968cd3aa110edfcdd58c8
refs/heads/master
<file_sep>package main import ( "fmt" "io/ioutil" "strings" ) func main() { var fileName string fmt.Printf("Enter file name:") fmt.Scanf("%s", &fileName) file, err := ioutil.ReadFile(fileName) if err != nil { fmt.Println("file not found") return } str := string(file) fmt.Println(strings.Count(str, "\n")) } <file_sep>way=input("Input way to file:") f = open (way) counter=0 for line in f: for letter in line: if letter =='\n': counter+=1 print(counter)
f669c20254efe66fe70668ca5f64d8bca489c976
[ "Python", "Go" ]
2
Go
WorldVirus/GoTask
1b203a30dcb8b6ed4f97fcbb89bdf86654d9f206
6cdf0e5ad3aa7c78fad8eb2e7d8cef9020b7d43d
refs/heads/master
<repo_name>mozikeru/m5stickc_line_notify<file_sep>/README.md # m5stickc_line_notify ## これは何 M5StickCのボタン押下で、あらかじめ設定しておいたLINEグループにメッセージを飛ばす ## 設定 ・コード中の下記の該当箇所にそれぞれ環境情報を入力してからM5StickCに書き込み 【WiFi接続情報】 const char* ssid = "WIFI_SSID"; const char* password = "<PASSWORD>"; 【LINE Notifyのトークン】 const char* token = "<PASSWORD>"; ※LINE Notifyのトークン取得はこちらから https://notify-bot.line.me/my/<file_sep>/m5stickc_line_notify.ino #include <ssl_client.h> #include <WiFiClientSecure.h> #include <HTTPClient.h> #include <WiFi.h> #include <WiFiMulti.h> #include "M5StickC.h" #include "M5Display.h" const char* ssid = "WIFI_SSID"; const char* password = "<PASSWORD>"; void wifiConnect() { WiFi.disconnect(); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); // Wi-Fi接続 while (WiFi.status() != WL_CONNECTED) { // Wi-Fi 接続待ち delay(100); Serial.printf("."); } Serial.println("\nwifi connect ok"); } void send(String message) { const char* host = "notify-api.line.me"; const char* token = "<PASSWORD>_TOKEN"; WiFiClientSecure client; Serial.println("Try"); client.setInsecure(); //LineのAPIサーバに接続 if (!client.connect(host, 443)) { Serial.println("Connection failed"); return; } Serial.println("Connected"); //リクエストを送信 String query = String("message=") + message; String request = String("") + "POST /api/notify HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Authorization: Bearer " + token + "\r\n" + "Content-Length: " + String(query.length()) + "\r\n" + "Content-Type: application/x-www-form-urlencoded\r\n\r\n" + query + "\r\n"; client.print(request); //受信終了まで待つ while (client.connected()) { String line = client.readStringUntil('\n'); Serial.println(line); if (line == "\r") { break; } } String line = client.readStringUntil('\n'); Serial.println(line); } void setup() { M5.begin(); M5.Axp.ScreenBreath(9); setCpuFrequencyMhz(80); M5.Lcd.setRotation(3); M5.Lcd.fillScreen(BLUE); wifiConnect(); M5.Lcd.setTextSize(2); M5.Lcd.setCursor(0,40); M5.Lcd.println("STANDBY OK !"); } void loop() { M5.update(); M5.Lcd.setCursor(0,40); if (M5.BtnA.wasPressed()){ //ボタンA(真ん中の大きいボタン) send("ボタンを押したよ~"); M5.Lcd.fillScreen(GREEN); M5.Lcd.println("AISATSU SEND !"); delay(5000); M5.Lcd.setCursor(0,40); M5.Lcd.fillScreen(BLUE); M5.Lcd.println("STANDBY OK !"); } if (M5.BtnB.wasPressed()){ //ボタンB(側面のボタン) send("緊急事態だよ!"); M5.Lcd.fillScreen(RED); M5.Lcd.println("KINKYU SEND !"); delay(5000); M5.Lcd.setCursor(0,40); M5.Lcd.fillScreen(BLUE); M5.Lcd.println("STANDBY OK !"); } }
4c97f31c6fc0d230748253c7b8f4fe9c3d60bd8b
[ "Markdown", "C++" ]
2
Markdown
mozikeru/m5stickc_line_notify
0de1aba202f905203727a6c4e2c7b8a510fa2b9d
15c007deb98e4a6bb307aa23e467a162e3b6f2cd
refs/heads/master
<repo_name>arunshenoy99/node-teacher-review<file_sep>/src/routers/teachers.js const express = require('express') const Teacher = require('../models/teacher') const router = new express.Router() router.get('/teachers', async (req, res) => { try { const teachers = await Teacher.find( { } ) if (teachers.length === 0) { res.status(404).send() } res.render('department', { title: teachers[0].department, teachers }) } catch (e) { res.status(500).send() } }) router.get('/departments/:department/teachers', async (req, res) => { const department = req.params.department try { const teachers = await Teacher.find({ department }) if (teachers.length === 0) { return res.status(404).send() } for(var i = 0; i < teachers.length; i++) { var sum = 0; var average = 'No reviews' await teachers[i].populate({ path:'reviews' }).execPopulate() for (var j = 0; j < teachers[i].reviews.length; j++) { sum = sum + teachers[i].reviews[j].rating } if (sum > 0) { average = sum/teachers[i].reviews.length teachers[i]['average'] = Math.round(average) } else { teachers[i]['average'] = average } } res.render('department', { title: teachers[0].department, teachers, active2: 'active' }) } catch (e) { res.status(500).send(e) } }) router.post('/teachers/:id', async(req, res) => { }) module.exports = router<file_sep>/public/js/index.js $('.dropdown-menu a').click(function () { let department = $(this).html().replace('&amp;', '&') console.log(window.location.protocol) console.log(window.location.hostname) console.log(window.location.port) window.location.href = `${window.location.protocol}//${window.location.hostname}:${window.location.port}/departments/${department}/teachers` }) $('#departmentlinks a').click(function () { let department = $(this).html().replace('&amp;', '&') console.log(window.location.protocol) console.log(window.location.hostname) console.log(window.location.port) window.location.href = `${window.location.protocol}//${window.location.hostname}:${window.location.port}/departments/${department}/teachers` }) $(document).ready(function () { $('#indexcarousel').carousel({ interval: 2000 }) $('#carouselbutton').click(function () { if ($('#carouselbutton').children('span').hasClass('fa-pause')) { $('#indexcarousel').carousel('pause') $('#carouselbutton').children('span').removeClass('fa-pause') $('#carouselbutton').children('span').addClass('fa-play') } else { $('#indexcarousel').carousel('cycle') $('#carouselbutton').children('span').removeClass('fa-play') $('#carouselbutton').children('span').addClass('fa-pause') } }) }) <file_sep>/public/js/card.js $('.card-header').hover(function () { $(this).css('cursor', 'pointer') }) $('.card-header').click(function () { let id = $(this).attr('id').replace('header-', '') $(`#body-${id}`).collapse('toggle') }) $(window).ready(function() { $('#rulesModal').modal('show') }) var reviewTemplate = '<div class="row" style="border: 1px ridge;"><div class="col"><p>Rating:{{rating}}/5</p><blockquote class="blockquote"><p class="mb-0">{{text}}</p><footer class="blockquote-footer"><cite>{{name}}</cite></footer></blockquote></div></div>' var template = Handlebars.compile(reviewTemplate) window.addEventListener('submit', (e) => { e.preventDefault() const id = e.target.id.replace('form-', '') const $form = document.querySelector(`#${e.target.id}`) const $header = document.querySelector(`#header-${id}`) const formData = new FormData($form) var data = {} formData.forEach((value, key) => { data[key] = value }) const url = `${window.location.protocol}//${window.location.hostname}:${window.location.port}/reviews/${id}` fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then((response) => { if (response.status != 201) { $header.classList.add('bg-danger') } else { $header.classList.add('bg-success') $form.innerHTML = "" response.json() .then((serverData) => { var html = template(serverData) $(`#oldreviews-${id}`).append(html) $(`#oldreviewsbutton-${id}`).click() }) } }) }) <file_sep>/src/utils/scrape.js const request = require('request') const fs = require('fs') const { parse } = require('node-html-parser') for (let i=1; i<=11; i++) { request.get({ url: `https://bmsit.ac.in/departments/${i}` }, (error, response) => { if (error) { console.log(error) } let data = '' const root = parse(response.body) const title = root.querySelector('title').text.toString() data = data + `${title}\n` let tables = root.querySelectorAll('table') let table = undefined if (i === 2 || i === 6 || i === 1 || i == 5 || i === 8) { table = tables[0] } else { table = tables[1] } const tbody = table.querySelector('tbody') const trs = tbody.querySelectorAll('tr') trs.forEach((tr) => { let tds = tr.querySelectorAll('td') tds.forEach((td) => { data = data + td.text.toString().replace(/\s+/g, ' ').trim() + '-' }) data = data + '\n' }) fs.writeFileSync(`data/dept${i}.txt`, data) }) }<file_sep>/src/utils/populate.js const fs = require('fs') const path = require('path') require('../db/mongoose') const Teacher = require('../models/teacher') const dataPath = path.join(__dirname, '../../data') const createTeacherAndSave = async (teacherObject) => { const teacher = new Teacher(teacherObject) await teacher.save() return teacher } let count = 0 for (var i = 1 ; i <= 11; i++) { const buffer = fs.readFileSync(`${dataPath}/dept${i}.txt`) const data = buffer.toString() const dataParts = data.split('\n') for (var j = 1; j < dataParts.length - 1; j++) { const teacherData = dataParts[j].split('-') const teacherObject = { name: teacherData[0], qualification: teacherData[1], position: teacherData[2], department: dataParts[0] } createTeacherAndSave(teacherObject) .then((teacher) => {}) .catch((e) => {console.log(e)}) } }
7c2c8f1adf20c39f54ca40a4928c333c6d3954ec
[ "JavaScript" ]
5
JavaScript
arunshenoy99/node-teacher-review
96b649c68cafcd059ab451e91554c3f762753203
eb6c9479c166166d75b16c727aa4b8b83638920f
refs/heads/master
<file_sep>public class MainClass{ public static void main(String[] args){ System.out.println("main of MainClass.java called!"); HelperClass hc = new HelperClass(); int res = hc.compute(2,5); System.out.println("Result: "+res); } }<file_sep>import sys def cprint(*string): s = [str(s) for s in string] print(" ".join(s)) #sys.stdout.write(str(string)+"\n") sys.stdout.flush() <file_sep>BLUE=`tput setaf 4` RED=`tput setaf 1` GREEN=`tput setaf 2` RESET=`tput sgr0` CYAN=`tput setaf 6` tag="${BLUE}[detectVulnerabilites]${RESET} " debug=False binFilePath=$1 joernDir=$2 scriptPath=$3 detailedOutDir=$4 summOutPath=$5 #log="${summOutPath}detectVulnerabilities2.log" summFile="vulFuncs.vul" if [ ! -d $detailedOutDir ]; then echo "${tag}Creating new output folder: ${CYAN}${detailedOutDir}${RESET}..." mkdir $detailedOutDir echo "${tag}Creating new output folder: ${CYAN}${detailedOutDir}${RESET}... ${GREEN}DONE!${RESET}" fi if [ ! -d $summOutPath ]; then echo "${tag}Creating new output folder: ${CYAN}${summOutPath}${RESET}..." mkdir $summOutPath echo "${tag}Creating new output folder: ${CYAN}${summOutPath}${RESET}... ${GREEN}DONE!${RESET}" fi source UPDATE cd $binFilePath checkVul(){ start=$1 end=$2 id=$3 pid=$BASHPID curr=0 echo "${tag}[$start-$end] checkVul with pid $CYAN$pid($id)$RESET started!" for jfile in $binFilePath/*.bin.zip do skip=$((curr < $start)) endCond=$((curr >= $end)) curr=$(( $curr+1 )) if [[ $skip -eq 1 ]]; then continue fi if [[ $endCond -eq 1 ]]; then echo "End condition reached." return fi fileName=($(echo $jfile | tr "/" "\n")) fileName=${fileName[-1]} fileName=${fileName/\.bin\.zip/""} #content=$(cat $log) #if [[ $content == *"$fileName"* ]]; then #echo "${tag}Skipping, already processed" # continue #file already processed, e.g. resuming #fi #echo "${tag}Testing ${CYAN}${fileName}${RESET}..." # (cd $joernDir && # ./joern --script "${scriptPath}vulTest.sc" --params "cpgFile=${binFilePath}${fileName}.bin.zip,\ #outFile=${detailedOutDir}jQ_${fileName}.txt,\ #summaryFile=${summOutPath}${summFile}") >/dev/null 2>&1 || echo "ERROR" > ${detailedOutDir}er_$fileName # >/dev/null 2>&1) (cd $joernDir && ./joern --script "${scriptPath}vulTest.sc" --params "cpgFile=${binFilePath}${fileName}.bin.zip,\ outFile=${detailedOutDir}jQ_${fileName}.txt,\ summaryFile=${summOutPath}${summFile},debug=${debug}") 2>${detailedOutDir}er_$fileName 1>/dev/null if [[ $(cat ${detailedOutDir}er_$fileName) == "" ]]; then rm ${detailedOutDir}er_$fileName fi updateCur $pid $id #echo "${tag}[${curr}/${end}(${total})]Testing ${CYAN}${fileName}${RESET}... ${GREEN}DONE!${RESET}" done echo "${tag}[$start-$end] checkVul with pid $CYAN$pid($id)$RESET $GREEN DONE! $RESET" doneId $id $pid } total=$(ls *.bin.zip | wc -l) batches=1 maxP=20 currP=0 id=0 multi=$((total > 500)) if [[ $multi -eq 1 ]]; then batches=$((total / 500)) batches=$((batches + 1)) fi echo "${tag} Got a total of ${CYAN}$total files${RESET}!" for batch in $(seq $batches) do start=$(((batch-1) * 500)) end=$((batch * 500)) if [[ $currP -eq $maxP ]]; then echo "Waiting since max processes reached." wait -n currP=$((currP - 1)) fi checkVul $start $end $id & id=$((id + 1)) currP=$((currP + 1)) done wait #remove duplicates cp "${summOutPath}${summFile}" "${summOutPath}${summFile}_orig" sort -u "${summOutPath}${summFile}_orig" > "${summOutPath}${summFile}" echo "${tag}All files processed!" <file_sep>from py2neo import Graph import pandas as pd import sys BLUE="\033[38;5;20m" RED="\033[38;5;9m" GREEN="\033[38;5;82m" CYAN="\033[38;5;14m" ORANGE="\033[38;5;202m" RESET="\033[0m" tag=ORANGE+"[linkJNIGlboalCG] "+RESET def printDF(df): with pd.option_context('display.max_rows', None, 'display.max_columns', None,'display.max_colwidth',100): print(df) def getLinkMap(summary): res = [] df = pd.read_csv(summary) #printDF(df.loc[df["jniCall"] != "None"]) for idx, row in df.loc[df["jniCall"] != "None"].iterrows(): funcName = row["srcFunc"] res.append([funcName,funcName.split("_")[-1],row["jniCall"],row["srcLoc"]]) return res def link(linkMap,cg): for item in linkMap: query = """MATCH (x:Function), (y:Function) WHERE x.funcName='"""+item[0]+"""' AND y.funcName='"""+item[1]+"""' AND x.location='"""+item[3].replace("\\","/")+"""' AND y.location='"""+item[2].replace("\\","/")+"""' MERGE (y)-[:JNI_CALL]-> (x)""" matches = cg.getGraph().run(query) def main(summary,uri,user,password): cg = None try: cg = cgI.CallGraph(uri=uri,user=user,password=<PASSWORD>) cg.getNode("tst") except Exception as e: print(tag+RED+"Connection to neo4j database could not be establisht!"+RESET) print(tag+RED+"Error:\n"+RESET+str(e)) #print(tag+RED+e+RESET) return linkMap = getLinkMap(summary) link(linkMap,cg) #u = "bolt://localhost:7687" #us ="neo4j" #pw = "<PASSWORD>" #s = r"S:\Uni\Master\MasterArbeit\CompleteAnalysis\Out\Java\summary.csv" #main(s,u,us,pw) if __name__ == "__main__": if len(sys.argv) < 5: print("WRONG USAGE!") exit(0) path = sys.argv[5]+"/Default/Callgraph.py" if sys.version_info >= (3,5): import importlib.util spec = importlib.util.spec_from_file_location("Callgraph.CallGraph",path) cgI = importlib.util.module_from_spec(spec) spec.loader.exec_module(cgI) elif sys.version_info >= (3,3): from importlib.machinery import SourceFileLoader cgI = SourceFileLoader("Callgraph.CallGraph",path).load_module() elif sys.version_info >=(2,0): import imp cgI = imp.load_source("Callgraph.CallGraph",path) else: print("Not supported python version: "+sys.version) main(sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4]) <file_sep>#!/bin/bash BLUE=`tput setaf 4` RED=`tput setaf 1` GREEN=`tput setaf 2` RESET=`tput sgr0` CYAN=`tput setaf 6` tag="${BLUE}[grep_loads]${RESET} " done="${GREEN}DONE!${RESET}" skip="${tag}${RED}SKIPPED!${RESET}" grep_path="S:\Uni\Master\MasterArbeit\frameworks\base\\" out_path="S:\Uni\Master\MasterArbeit\Analysis\JNI_LIB_Finder\Output\JNIs\\" loads=("System.load(" "System.loadLibrary(" "Runtime.load(" "Runtime.loadLibrary(") for l in ${loads[@]}; do echo "${tag} Grepping for ${CYAN}${l}${RESET}..." (cd $grep_path && grep ${l} -r > ${out_path}${l}.txt ) echo "${tag} Results written to ${out_path}" echo "${tag} Grepping for ${CYAN}${l}${RESET}... ${done}" done <file_sep>BLUE=`tput setaf 4` RED=`tput setaf 1` GREEN=`tput setaf 2` RESET=`tput sgr0` CYAN=`tput setaf 6` scriptDir=$1 csvFile=$2 lib_xml=$3 jni_xml=$4 py=$5 tag="${BLUE}[link_native_to_jni]${RESET} " done="${GREEN}DONE !${RESET}" echo "${tag}Adding according JNI calls to found vulnerabilites (${CYAN}@see: summary.csv${RESET})..." echo "${tag}Using: ${CYAN}${lib_xml}${RESET}" echo "${tag}Using: ${CYAN}${jni_xml}${RESET}" (cd $scriptDir && $py link_native_to_jni.py $csvFile $lib_xml $jni_xml) echo "${tag}Adding according JNI calls to found vulnerabilites (${CYAN}@see: summary.csv${RESET})... ${done}" <file_sep>#!/bin/bash getDiff(){ strt=$1 stp=$2 diff=$(( $(date -d "$stp" "+%s") - $(date -d "$strt" "+%s") )) diffh=$(date -d@$diff -u +%H:%M:%s) echo $diffh } <file_sep>import sys import os import threading import traceback from py2neo import Graph from py2neo.data import Node, Relationship BLUE="\033[38;5;20m" RED="\033[38;5;9m" GREEN="\033[38;5;82m" CYAN="\033[38;5;14m" ORANGE="\033[38;5;202m" RESET="\033[0m" tag=ORANGE+"[createGlobalCallGraph] "+RESET #ASSUMPTION NODE DOT FORMAT #filename:: functionName:: [:: location] #for filename EXT: filename:: functionName:: calledIn def dot2Node(cg,line): spl = line.split(":::") fileName = spl[0].replace("\"","").strip() funcName = spl[1].replace("\"","").strip() #for filename EXT location is the location where this function is called #for others it is the path where to find the file location = None if (len(spl) > 2): location = spl[2].replace("\"","").replace("\\","/").strip() """ if not (location == None): print("Node: "+funcName+" , file='"+fileName+"', location="+location) else: print("Node: "+funcName+" , file='"+fileName+"'") """ available = cg.getNode("Function",properties={'srcFile' : fileName, 'funcName' : funcName, 'location' : location}) if not(available == None): #print("Alrdy contained!") return available #print("ADDING NODE: "+funcName+", "+fileName+", "+location) return Node("Function", funcName=funcName,srcFile=fileName,location=location) def dot2Relationship(cg,line): spl = line.split("->") lhs = dot2Node(cg,spl[0]) rhs = dot2Node(cg,spl[1]) return Relationship(lhs, "CALLS",rhs) def load(path,cg,start,stop,total): curr=0 printIntervall=1 for file in os.listdir(path): if (os.path.isfile(os.path.join(path,file))): if not(os.path.splitext(file)[1] == ".dot"): #print(os.path.splitext(file)[1]) continue if (curr < start): curr += 1 continue if (((curr > stop) and (stop >= 0))or ((curr > total) and (total>=0))): return #print(tag+"Processing: "+CYAN+file+RESET+"...") with open(os.path.join(path,file), "r",errors="ignore") as f: #ASSUMPTION: DOT FILE NOT CORRUPTED AND EACH LINE CONTAINS 1 RELATION! for line in f: if line in ["\n","\r\n"]: continue if ("digraph" in line): continue if (line == "}"): continue if not("->" in line): try: cg.addNode(dot2Node(cg,line)) except Exception as e: print(tag+"ERROR: #load1",os.path.join(path,file)) print(tag+line) print(e) else: try: cg.addRelationship(dot2Relationship(cg,line)) except Exception as e: print(tag + "ERROR: #load2", os.path.join(path, file)) print(tag + line) print(e) curr += 1 if (curr % printIntervall == 0): #cs = "["+str(curr)+"/"+str(stop)+"("+str(total)+")]" #print(tag+cs+"Processing: "+CYAN+file+RESET+"... "+GREEN+"DONE!"+RESET) print(tag+str(curr)+"/"+str(stop)+"["+str(total)+"] DONE!") def merge(cg,idn,idm): q="MATCH (n:Function),(m:Function)" q+="WHERE id(n)="+str(idn)+" AND id(m)="+str(idm)+" " q+="OPTIONAL MATCH (n)-[s]->(succ) " q+="OPTIONAL MATCH (pre)-[r]->(n) " q+="DETACH DELETE (n) " q+="RETURN n,type(s) as s,id(succ) as succ,type(r) as r,id(pre) as pre,m as mergeTo" result = cg.getGraph().run(q) for res in result.data(): preID = str(res["pre"]) typ = res["r"] if not(typ == None or preID == None): q ="MATCH (pre),(m)" q+="WHERE id(pre)="+preID+" AND id(m)="+str(idm)+" " q+="MERGE (pre)-[:"+typ+"]-> (m)" #Isntead of merge could also use CREATE but then probably creates multiple time on #multiple runs (same as below with MERGE) cg.getGraph().run(q) sucID = str(res["succ"]) typ = res["s"] if not (typ == None or sucID == None): q ="MATCH (succ),(m) " q+="WHERE id(succ)="+sucID+"id(m)="+str(idm)+" " q+="MERGE (m)-[:"+typ+"]-> (succ)" cg.getGraph().run(q) def deleteDuplicates(cg): # delete duplicates q = """MATCH (n), (m) WHERE ( id(n) <> id(m) AND n.srcFile = m.srcFile AND n.location = m.location AND n.funcName = m.funcName ) RETURN id(n) as idn, id(m) as idm """ res = cg.getGraph().run(q) data = res.data() for n in data: idn = n["idn"] idm = n["idm"] merge(cg, idn, idm) def doesIncl(cg,match): included = match["x"] implemented = match["y"] included_fname = included["location"] implemented_hname = implemented["srcFile"] if (".cpp" in implemented_hname): implemented_hname = implemented_hname.split(".cpp")[0] elif (".c" in implemented_hname): implemented_hname = implemented_hname.split(".c")[0] #implemented_hname.h od .hpp #if included_fname :INCLUDES implmented_hname then add candidate qS = "MATCH (n:File {name:\""+str(included_fname)+"\"}), " qh = "(m:File {name:\""+str(implemented_hname)+".h\"}), " qhpp = "(m:File {name:\"" + str(implemented_hname) + ".hpp\"}), " qE = "p = shortestPath( (n)-[r:INCLUDES*]->(m)) " qE += "RETURN count(p) > 0 as incl" hq = qS + qh + qE hppq = qS + qhpp + qE #print(hq) includes = cg.getGraph().run(hq).data()[0]["incl"] if (includes): return True includes = cg.getGraph().run(hppq).data()[0]["incl"] if (includes): return True return False def link(cg): #(inclMap,cg,rootDir): skip = [] print(tag+"Linking graphs...") not_changed = 0 deleteDuplicates(cg) #maps together linked functions #e.g. func3 is implemented in tst.cpp which calles iFunc # iFunc is implementend in tst2.cpp # then we create / add the following entry to tst2.mp: # iFunc: S:/.../tst.cpp|S:/.../bla.cpp linkMap = {} #return #TESTING #cg.addNode(Node("Function",funcName="iFunc",file="EXT",location=None)) #n1 = Node("Function",funcName="bla",location="JNI_JNI_Helper_Dynamic.cpp",srcFile="EXT") #n2 = Node("Function",funcName="safe",location="S:/Uni/Master/MasterArbeit/CompeleteAnalysis/srcFiles/fullTest/native/helpers.cpp",srcFile="helpers.cpp") #cg.addNode(n1) #cg.addNode(n2) #cg.addRelationship(Relationship(n1,"CALLS",n2)) queryS = """MATCH (x:Function), (y:Function) WHERE (x.srcFile='EXT' AND NOT y.srcFile='EXT') AND x.funcName=y.funcName """ queryE = """RETURN x,y,id(x) as IDx,id(y) as IDy ORDER BY id(y) LIMIT 1 """ while True: fq = queryS #fq += " AND NOT id(x) IN "+str(skip)+" " fq += " AND NOT id(y) IN "+str(skip)+" " fq += "\n"+queryE #print(fq) nodes = cg.getGraph().run(fq) if (nodes == None): break if (not_changed > 2): print(tag+RED+"link(): STUCK in while loop!"+RESET) print(nodes.data()) break data=nodes.data() #print(data) if (len(data) < 1): break #if (not_changed > 0 and (not data[0]["IDx"] in skip)): if (not_changed > 0 and (not data[0]["IDy"] in skip)): print("ADDING",data[0]) #skip.append(data[0]["IDx"]) skip.append(data[0]["IDy"]) not_changed = 0 not_changed += 1 for i in range(len(data)-1): if not (data[i]["y"] == data[i+1]["y"]): print(tag+str(data[i]["y"])+" "+str(data[i+1]["y"])) print(tag+RED+"link(): S.th went wrong #2"+RESET) #this IDy shoudl be the same for all nodes (as tested before) Idy = str(data[0]["IDy"]) for n in data: node = n["x"] # merge x into y if (node["srcFile"] == "EXT"): #check if function is included from this file. shoulM = False try: shouldM = doesIncl(cg,n) except Exception as ex: print(tag+ORANGE+"link: Error during merging: "+RESET+str(ex)) print(traceback.format_exc()) print(tag+ORANGE+"Ignoring Error, continuing!"+RESET) if not (shouldM): continue #print("MERGING: \n"+str(node)+"\n<>\n"+str(n["y"])+"\n") call = node origin = n["y"] src_file = origin["srcFile"] if not (src_file in linkMap.values()): linkMap[src_file] = {} funcName = call["funcName"] if not (funcName in linkMap[src_file].values()): linkMap[src_file][funcName] = [] if not (call["location"] in linkMap[src_file][funcName]): linkMap[src_file][funcName].append(call["location"]) #print(linkMap) try: merge(cg,n["IDx"],Idy) except Exception as e: print(tag+"ERROR #link1 during merging!") print(e) not_changed = 0 else: print(tag+RED+"link(): S.th went wrong #1"+RESET) print(tag+"Linking Graphs... "+GREEN+"DONE!"+RESET) return linkMap #crossCools = calls between differnt c files #e.g. iFunc in tst2.cpp is vulnerable # iFunc gets called in line 9 in tst.cpp # then we link them together here and create an entry for this cross call # for the backwardsslicing.sc to work, as it cant connect with the neo4j database.. # we simply use an txt format for transfering the result # in this case it would be: # filename: tst2.mp # 1st line: iFunc:: (tst,9) # each function has 1 line, if it gets called from multiple files they can be concatenated # e.g. iFunc:: (tst,9)|(ttst,50)|(bla,23) def writeToFiles(dst,linkMap): if not (os.path.exists(dst)): print(tag+RED+"Crosscall path does not exist: "+dst+"!"+RESET) return #print("DST: "+dst) #print("LINKMAP: "+str(linkMap)) #print(tag+"TODO!") for file in linkMap.keys(): dst_file, ext = os.path.splitext(file) dst_file = dst_file+".mp" with open(dst+dst_file,"w") as f: for func in linkMap[file].keys(): f.write(func+"::: ") for call in linkMap[file][func]: clean_call, ext = os.path.splitext(call) if (linkMap[file][func][-1] == call): f.write(clean_call) else: f.write(clean_call+"|") f.write("\n") def main(dotPath,uri,user,password,crossCalls,modus="FULL",start=-1,stop=-1,total=-1): #print(tag+"Called with path: "+CYAN+dotPath+RESET) print(tag+"Modus: "+CYAN+modus+RESET) #print(uri) #print(user) #print(password) #print(crossCalls) #print(start,stop,total) cg = None try: cg = cgI.CallGraph(uri=uri,user=user,password=<PASSWORD>) cg.getNode("tst") except Exception as e: print(tag+RED+"Connection to neo4j database could not be establisht!"+RESET) print(tag+RED+"Error:\n"+RESET+str(e)) #print(tag+RED+e+RESET) return #loadGraphs(dotPath,cg) if not ("LOADED" in modus): load(dotPath,cg,start,stop,total) if "FULL" in modus: linkMap = link(cg) writeToFiles(crossCalls,linkMap) #cg.close() #main("S:/Uni/Master/MasterArbeit/joernAnalysis/bwSlicing/out/dot/","S:/Uni/Master/MasterArbeit/joernAnalysis/bwSlicing/out/includes/") if __name__ == '__main__': #for x in range(len(sys.argv)): # print(x,sys.argv[x]) if (len(sys.argv) < 7): print(tag+RED+"To less arguments..."+RESET) exit(0) #1 dotPath #2 database uri #3 username (database) #4 password (database) #5 crossCalls #6 path for callgraph.py #7modus #8 start #9 stop #10 total modus = "FULL" if (len(sys.argv) >= 8): modus = sys.argv[7] start = -1 stop = -1 total = -1 if (len(sys.argv) >= 11): start = int(sys.argv[8]) stop = int(sys.argv[9]) total = int(sys.argv[10]) if (stop > total): stop = total path = sys.argv[6]+"/Default/Callgraph.py" if sys.version_info >= (3,5): import importlib.util spec = importlib.util.spec_from_file_location("Callgraph.CallGraph",path) cgI = importlib.util.module_from_spec(spec) spec.loader.exec_module(cgI) elif sys.version_info >= (3,3): from importlib.machinery import SourceFileLoader cgI = SourceFileLoader("Callgraph.CallGraph",path).load_module() elif sys.version_info >=(2,0): import imp cgI = imp.load_source("Callgraph.CallGraph",path) else: print("Not supported python version: "+sys.version) main(sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4],sys.argv[5],modus=modus,start=start,stop=stop,total=total) <file_sep># -*- coding: cp1252 -*- import re from JNI.Function import Method,Parameter import java_parser.plyj.parser as jp import xml.etree.ElementTree as ET from xml.dom import minidom from Helper.helper import cprint import sys import pathlib import os path = pathlib.Path(__file__).parent.absolute().parent.parent sys.path.append(str(path)) from Default.Colors import Color tag =Color.ORANGE.value+"[JNI] "+Color.RESET.value class JNI: def __init__(self,path="",name="",nativeMethods=[],callingNativeMethods=[]): self.path = path self.name = name self.nativeMethods = nativeMethods self.callingNativeMethods = callingNativeMethods def __repr__(self): return str(self) def __str__(self): strng = ("\n### JNI START ###\n") strng += ("### Path: "+self.path+"\n") strng += ("### Name: "+self.name+"\n") strng += ("### Declared Native Methods: \n") if (len(self.nativeMethods) == 0): strng += "\nNone\n\n" for method in self.nativeMethods: strng += str(method)+"\n" strng += ("### Methods calling native methods: \n") if (len(self.callingNativeMethods) == 0): strng += "\nNone\n\n" for nnat in self.callingNativeMethods: strng += str(nnat)+"\n" strng += ("### JNI END ###\n") return strng def setPath(self,path): self.path = path def setName(self,name): self.name = name def setMethods(self,methods): self.nativeMethods = methods def addNativeMethod(self,method): self.nativeMethods.append(method) def nativeMethods(self,methods): self.nativeMethods.extends(methods) def getPath(self): return self.path def getName(self): return self.name def getNativeMethods(self): return self.nativeMethods def store(self,outDir): #xml structure data = ET.Element('JNI') name = ET.SubElement(data,"Name") path = ET.SubElement(data,'Path') nativeMethods = ET.SubElement(data,"NativeMethods") callingNativeMethods = ET.SubElement(data,"CallingNativeMethods") #path.set("value",self.path) path.text = self.path name.text = self.name for nm in self.nativeMethods: nativeMethods = nm.toXML(nativeMethods) for cnm in self.callingNativeMethods: callingNativeMethods = cnm.toXML(callingNativeMethods) data = ET.tostring(data) pathName = os.path.join(outDir,self.name+".xml") i=0 while True: if (os.path.isfile(pathName)): pathName = pathName.split(".xml")[0]+"_"+str(i)+".xml" else: break i += i with open(pathName,"wb") as f: f.write(data) def load(file): with open(file,"r") as f: doc = minidom.parse(file) path = doc.getElementsByTagName("Path")[0].firstChild.nodeValue name = doc.getElementsByTagName("Name")[0].firstChild.nodeValue nms = doc.getElementsByTagName("NativeMethods") nativeMethods=[] for nm in nms[0].getElementsByTagName("Method"): nativeMethods.append(Method.fromXML(nm)) callingNativeMethods = [] cnms = doc.getElementsByTagName("CallingNativeMethods")[0] for cnm in cnms.childNodes: #print("Processing:") #print(cnm.getElementsByTagName("Name")[0].firstChild.nodeValue) callingNativeMethods.append(Method.fromXML(cnm)) return JNI(path=path, name=name, nativeMethods=nativeMethods, callingNativeMethods=callingNativeMethods) def test(): jni = JNI.load(r"S:\Desktop\tst\ActivityRecognitionHardware.java.xml") print(jni) def convertParameter(x): params = [] #if wanted can also be passed as given with #more information, but yet more is not needed for para in x.parameters: try: if ("model.Type" in str(type(para.type))): typ = str(para.type.name) if ("Name" in typ): typ = str(para.type.name.value) params.append(Parameter(typ=typ, name=str(para.variable.name))) else: params.append(Parameter(typ=str(para.type), name=str(para.variable.name))) except: cprint("JNI.py: convertParameter: NOT YET SUPPORTED PARAM:") cprint(type(para)) cprint(para) cprint(type(para.type)) cprint(para.type) exit() return params def getNativeMethods(file): nativeMethods = [] parser = jp.Parser() tree = parser.parse_file(file) if tree is None : cprint(tag+"getNativeMethods~Tree is None for: "+str(file)) return nativeMethods try: for x in tree.type_declarations[0].body: if ('MethodDeclaration' in str(type(x))): if ('native' in x.modifiers): params = convertParameter(x) nativeMethod = Method(keywords=x.modifiers, name = x.name, parameter = params, calledNativeMethods=[]) nativeMethods.append(nativeMethod) #print(nativeMethod) except Exception as e: cprint(tag + "getNativeMethods~" + str(tree)) cprint(tag + "getNativeMethods~" + str(e) +"\nErrorEND") return nativeMethods def addCalledNativeMethods(method,curr,nativeMethod): if (method is None): method = Method(keywords=curr.modifiers, name=curr.name, parameter=convertParameter(curr), calledNativeMethods=[nativeMethod]) return method else: method.addCalledNativeMethod(nativeMethod) return method def recursiveNativeCallGraph(): return def checkForCalledNativeMethods(nativeMethods,piece,stmt,method): #check if calling native method: if ('MethodInvocation' in str(stmt)): if not any(natMet.getName() in str(stmt) for natMet in nativeMethods): return None else: #yet easy way, but mayb also store background info? spl = str(stmt).split('MethodInvocation') for p in spl: if ('name' in p): nme = p.split("'") nme = nme[1] if any(nme in natMet.getName() for natMet in nativeMethods): nativeMethod = Method(name=nme, info=stmt) method = addCalledNativeMethods(method,piece,nativeMethod) return method def getNativeUsage(file,nativeMethods): nativeUsage=[] parser = jp.Parser() #print("File: "+file) tree = parser.parse_file(file) for x in tree.type_declarations[0].body: method = None if ('ConstructorDeclaration' in str(type(x))): for b in x.block: method = checkForCalledNativeMethods(nativeMethods,x,b,method) if ('java_parser.plyj.model.MethodDeclaration' in str(type(x))): if not ('native' in x.modifiers): try: for b in x.body: method = checkForCalledNativeMethods(nativeMethods,x,b,method) except Exception as e: cprint(tag+"getNativeUsage~Error on: "+str(x)) cprint(tag+"getNativeUsage~"+str(e)) if not (method is None): nativeUsage.append(method) return nativeUsage def generateJNI(file): spl = file.split(os.sep) nativeMethods = [] callingNativeMethods = [] try: nativeMethods=getNativeMethods(file) except Exception as e: print(tag+"ERR#1",e) try: #print(" Got "+str(len(nativeMethods))+" native Methods.") #print(nativeMethods) callingNativeMethods = getNativeUsage(file,nativeMethods) except Exception as e: print(tag+"ERR#2",e) try: return JNI(path=file,name=spl[len(spl)-1],nativeMethods=nativeMethods, callingNativeMethods=callingNativeMethods) except: return JNI(path=file,name="ERR",nativeMethods=nativeMethods,callingNativeMethods=callingNativeMethods) #test() <file_sep>from py2neo import Graph from py2neo.data import Node,Relationship import sys import os import time from pathlib import Path from createGlobalCallGraph import deleteDuplicates import traceback import datetime import glob import re import ntpath BLUE="\033[38;5;20m" RED="\033[38;5;9m" GREEN="\033[38;5;82m" CYAN="\033[38;5;14m" ORANGE="\033[38;5;202m" RESET="\033[0m" tag=ORANGE+"[includeGenerator] "+RESET """ path=r"S:/Uni/Master/MasterArbeit/CompleteAnalysis/Default/Callgraph.py" import importlib.util spec = importlib.util.spec_from_file_location("Callgraph.CallGraph",path) cgI = importlib.util.module_from_spec(spec) spec.loader.exec_module(cgI) """ """ lastChecked=datetime.datetime.now() tolerance=20 def check(d="?"): now = datetime.datetime.now() diff=now - lastChecked lastChecked = now diff = diff.total_seconds() if (diff > tolerance): tprint(tag+"["+str(start)+"-"+str(stop)+"] Alive! Doing: "+str(d)) """ def tprint(*strings): string=[str(s) for s in strings] print(" ".join(string)) sys.stdout.flush() def genInclude(srcDir,file,inclG): file = file.strip() srcDir = srcDir.strip() srcDir = srcDir.replace("\\","/") fullPath = os.path.join(srcDir,file) fullPath = fullPath.replace("\\","/") rootProps = {"name": file,"location":srcDir} available = inclG.getNode("File",properties=rootProps) if (available is None): node = Node("File",name=file,location=srcDir) inclG.addNode(node) with open(fullPath,"r",errors="ignore") as f: for line in f: if not(line.startswith("#")): continue if ("include" in line): line = line.strip() line = line.replace(" ","") if ("#include" in line): name = line.split("#include",1)[1] sysFile = False if ("<" in line and ">" in line): name = name.split("<",1)[1].split(">",1)[0] sysFile = True elif ("\"" in name): name = name.split("\"",1)[1].split("\"")[0] dynamicPath = srcDir if ("\\" in name): name = name.replace("\\","/") while ("//" in name): name = name.replace("//","/") if ("/" in name): p = name.split("/") name = p[len(p)-1] p = "/".join(p[:len(p)-1]) dynamicPath = str(Path(os.path.join(dynamicPath,p)).resolve()) dynamicPath = dynamicPath.replace("\\","/") if sysFile: dynamicPath = "None" props = {"name": name,"location":dynamicPath} available = inclG.getNode("File",properties=props) if (available is None): node = Node("File", name=name, location=dynamicPath) inclG.addNode(node) pre = inclG.getNode("File",rootProps) succ = inclG.getNode("File",props) inclG.addRelationship(Relationship(pre,"INCLUDES",succ)) def loadIncludes(srcDir,inclG,start,stop,cur=0): printIntervall = 50 totalTodo = stop - start #print(cur) #print(srcDir) if ((cur >=stop) and (stop != -1)): return cur try: for fod in os.listdir(srcDir): if (os.path.isdir(os.path.join(srcDir,fod))): cur = loadIncludes(os.path.join(srcDir,fod),inclG,start,stop,cur=cur) else: if (cur % printIntervall == 0 and cur != 0 and (cur - start) > start): tprint(tag + "[" + str(start) + "-" + str(stop) + "] " + str(cur - start) + "/" + str( totalTodo) + " DONE.") if (fod.endswith(".c") or fod.endswith(".cpp") or fod.endswith(".h") or fod.endswith(".hpp")): if (start != -1 and stop != -1): if (cur < start and start != -1): cur += 1 continue if (cur >= stop and stop != -1): return cur cur += 1 try: #print("processing",fod) genInclude(srcDir,fod,inclG) except Exception as e: tprint(tag+"ERROR"+srcDir,fod) tprint(e) traceback.print_exc() sys.stdout.flush() except Exception as pd: tprint(tag+"ERROR",srcDir) tprint(pd) traceback.print_exc() sys.stdout.flush() return cur def getMMN(compare,goal): """ print(tag+"GMMN",len(compare)) print(tag+"GOAL",goal) for x in compare: print(x) """ idx = 0 goal = goal.strip() while True: if (len(compare) <= 1): break if (idx > len(goal)): comparx = [] for c in compare: cl = c["n"]["location"].replace("\\","/") while ("//" in cl): cl = cl.replace("//","/") if (len(cl.strip()) == len(goal.strip())): comparx.append(c) compare = comparx if (len(compare) > 1): print(tag+"__getMMN__"+"multiple matches!") print(compare) break nxt = [] for c in compare: cloc = c["n"]["location"].strip() cloc = cloc.replace("\\","/") while ("//" in cloc): cloc = cloc.replace("//","/") if (str(cloc[:idx]) == str(goal[:idx])): nxt.append(c) compare = nxt idx += 1 if len(compare) > 0: #print("GMM RET",compare[0]) return compare[0] #print("GMM RETN") return None #getMMN([{"n": {"location": " /home/c01chbe/Build7_1/external/curl/include/curl"}},{"n": {"location": "/home/c01chbe/Build7_1/external/google-breakpad/src/third_party/curl"}}], # "/home/c01chbe/Build7_1/external/curl/lib") def processed(inclOut,app): #print("Checking",app) app = (app[0].strip(),app[1].strip()) name = os.path.join(inclOut,app[0])+"*.incl" #print(name) files = glob.glob(name) #print("Candidates",files) pattern = "(\\\\|/)"+app[0]+"(_?)(\d*)\.incl" for f in files: match = re.search(pattern,f) if match: with open(f,"r",errors="ignore") as fl: if (app[1].strip() == fl.readlines()[0].strip()): #print("found") return True #print("Nope") return False def derive(inclG,todo,done,inclOut): new_todo = [] #tprint("####################") #tprint(todo) #tprint(done) #tprint("--------------------") for t in todo: t = (t[0].strip(),t[1].strip()) try: if not (t in done): if not (processed(inclOut,t)): done.append(t) else: continue else: continue #tprint("CUR: ",t) cn = t[0] cloc = t[1] q = "MATCH (n) " q += "WHERE (n.name=\""+cn+".h\" OR n.name=\""+cn+".hpp\") " q += "RETURN n" res = inclG.getGraph().run(q).data() #tprint("CUR_RES",res) id = getMMN(res,cloc) #tprint("GETMMN RESULT",id) if (id is None): tprint(tag+"COULD_NOT_RESOLVE",cn,cloc,"\n",res) continue id = id["n"].identity q = "MATCH (m)-[:INCLUDES]->(n) " q+= "WHERE id(n)="+str(id)+" AND " q+= "(m.name ENDS WITH \".c\" OR m.name ENDS WITH \".cpp\") " q+= "RETURN m" res = inclG.getGraph().run(q).data() for r in res: r = r["m"] name = r["name"] if (name.endswith(".cpp")): name = name.split(".cpp")[0] if (name.endswith(".c")): name = name.split(".c")[0] loc = r["location"] app = (name.strip(),loc.strip()) #if not processed druing this vulnerability if not (app in done): #if not processed during backtracking other vulnerability if not (processed(inclOut,app)): new_todo.append(app) except Exception as e: tprint(tag+"ERROR: ",t) tprint(e) #tprint("####################") return new_todo,done def writeIncludes(inclOut,done): for x in done: x = (x[0].strip(),x[1].strip()) fname = os.path.join(inclOut, x[0]+ ".incl") i = 0 while (os.path.isfile(fname)): fname = os.path.join(inclOut, x[0] + "_" + str(i) + ".incl") i += 1 with open(fname, "w") as f: f.write(x[1]) def genIncludeList(inclG,inclOut,vulDir): if (vulDir is None): tprint(tag+"VULDIR NONE!") return [] vuls = [] for f in os.listdir(vulDir): if (f.endswith(".vul")): with open(vulDir + os.sep + f) as f: for line in f: spl = line.split(";") loc,fname = ntpath.split(spl[2]) loc = str(loc) fname = str(fname) if (fname.endswith(".cpp")): fname = fname.split(".cpp")[0] elif (fname.endswith(".c")): fname = fname.split(".c")[0] loc = loc.replace("\\", "/") while (loc.endswith("/")): loc = loc.split("/") loc = loc[:len(loc)-1] loc = "/".join(loc) #print(loc) #print(fname) vuls.append((fname,loc)) #done = [] #tprint(vuls) #todo= vuls #while (len(todo)> 0): #todo,done = derive(inclG,todo,done) total = len(vuls) cur = 0 maxListSize = 100 printIntervall = 10 for v in vuls: total_todo = [v] done = [] while (len(total_todo) > 0): zw_total = len(total_todo) zw_cur = 0 todo = total_todo total_todo = [] for t in todo: todo_r,done = derive(inclG,[t],done,inclOut) total_todo.extend(todo_r) if (len(done) > maxListSize): writeIncludes(inclOut,done) done = [] zw_cur += 1 if (zw_cur % printIntervall == 0): tprint(tag+"_subtask_"+str(zw_cur)+"/"+str(zw_total)+" DONE.") #print(done) writeIncludes(inclOut,done) cur += 1 tprint(tag+str(cur)+"/"+str(total)+" DONE.") """ for x in done: #improve cuz duplicates!!!! with open(os.path.join(inclOut,x[0]+".incl"),"w") as f: f.write("") """ def main(srcDir,inclOut,password,user="neo4j",uri="bolt://localhost:7771",start=-1,stop=-1,modus="FULL",vulDir=None,strategy="FAST"): """ tprint("srcDir:",srcDir) tprint("vulDir:",vulDir) tprint("inclOut: ",inclOut) tprint("password: ",password), tprint("user: ",user) tprint("uri: ",uri) tprint("modus: ",modus) """ if ("FULL" in strategy): tprint(tag+"Currently only FAST support, FULL is outdated.") tprint(tag+"Continuing with strategy FAST.") tprint(tag+"["+str(start)+"-"+str(stop)+"] Started!") #return if not (os.path.isdir(inclOut)): os.makedirs(inclOut) inclG = None try: inclG = cgI.CallGraph(uri=uri, user=user, password=<PASSWORD>) inclG.getNode("tst") except Exception as e: tprint(tag + RED + "Connection to neo4j database could not be establisht!" + RESET) tprint(tag + RED + "Error:\n" + RESET + str(e)) # tprint(tag+RED+e+RESET) return if ("FULL" in modus or "LOAD" in modus): loadIncludes(srcDir, inclG, start, stop) if (start != -1 and stop != -1): deleteDuplicates(inclG) if ("FULL" in modus or "GENINCL" in modus): if (vulDir is not None): genIncludeList(inclG, inclOut, vulDir) tprint(tag+"["+str(start)+"-"+str(stop)+"] DONE!") #sd = r"S:\Uni\Master\MasterArbeit\CompleteAnalysis\srcFiles\fullTest" #vd = r"S:\Uni\Master\MasterArbeit\CompleteAnalysis\Out\C_CPP_Analyser" #iO = r"S:\Uni\Master\MasterArbeit\CompleteAnalysis\Out\C_CPP_Analyser\includes" #pw = "kK0_1" #main(sd,iO,pw) if __name__ == '__main__': """ for x in range(len(sys.argv)): tprint(x,sys.argv[x]) """ if (len(sys.argv) < 7): tprint(tag + RED + "To less arguments..." + RESET) exit(0) # 1 srcDir #2 inclOut #3 password #4 user (database) #5 uri (database) #6 mainpath ##7 start ##8 stop ##9 modus ##10 vulDir #11strategy path = sys.argv[6] + "/Default/Callgraph.py" start = -1 stop = -1 if (len(sys.argv) >= 9): start=int(sys.argv[7]) stop=int(sys.argv[8]) modus = "FULL" if (len(sys.argv) >= 10): modus = sys.argv[9] vulDir=None if (len(sys.argv) >= 11): vulDir=sys.argv[10] strat="FAST" if (len(sys.argv) >= 12): strat=sys.argv[11] if sys.version_info >= (3, 5): import importlib.util spec = importlib.util.spec_from_file_location("Callgraph.CallGraph", path) cgI = importlib.util.module_from_spec(spec) spec.loader.exec_module(cgI) elif sys.version_info >= (3, 3): from importlib.machinery import SourceFileLoader cgI = SourceFileLoader("Callgraph.CallGraph", path).load_module() elif sys.version_info >= (2, 0): import imp cgI = imp.load_source("Callgraph.CallGraph", path) else: tprint("Not supported python version: " + sys.version) main(sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4],sys.argv[5],start=start,stop=stop,modus=modus,vulDir=vulDir,strategy=strat) <file_sep>from LIB.Function import Method import sys import clang.cindex as cci import LIB.Native_Func_Decl_Detector as nfdd import xml.etree.ElementTree as ET from xml.dom import minidom import os class LIB: def __init__(self,path="",name="",nativeMethods=[]): self.path=path self.name=name self.nativeMethods=nativeMethods def __repr__(self): return str(self) def __str__(self): strng = ("\n ### LIB START ###\n") strng += ("### Path: "+self.path+"\n") strng += ("### Name: "+self.name+"\n") strng += ("### Registered native Methods:\n") if (len(self.nativeMethods) == 0): strng += "\nNone\n\n" for nm in self.nativeMethods: strng += str(nm)+"\n" strng += ("### LIB END ###\n") return strng def setPath(self,path): self.path = path def setName(self,name): self.name = name def setMethods(self,methods): self.nativeMethods = methods def getPath(self): return self.path def getName(self): return self.name def getNativeMethods(self): return self.nativeMethods def store(self,outDir): #xml structure data = ET.Element("LIB") name = ET.SubElement(data,"Name") path = ET.SubElement(data,"Path") nativeMethods = ET.SubElement(data,"NativeMethods") path.text = self.path name.text = self.name for nm in self.nativeMethods: nativeMethods = nm.toXML(nativeMethods) data = ET.tostring(data) pathName = os.path.join(outDir,self.name+".xml") i = 0 while True: if (os.path.isfile(pathName)): pathName = pathName.split(".xml")[0]+"_"+str(i)+".xml" else: break i += 1 with open(pathName,"wb") as f: f.write(data) def load(file): with open(file,"r") as f: doc = minidom.parse(file) path = doc.getElementsByTagName("Path")[0].firstChild.nodeValue name = doc.getElementsByTagName("Name")[0].firstChild.nodeValue nms = doc.getElementsByTagName("NativeMethods") nativeMethods = [] for nm in nms[0].getElementsByTagName("Method"): nativeMethods.append(Method.fromXML(nm)) return LIB(path=path,name=name,nativeMethods=nativeMethods) def getRegisteredMethods(file): """ no use of clang bad documentation. print("FILE: "+file) cci.Config.set_library_file(r'S:\Programme\clang\llvm\build\Debug\bin\libclang.dll') index = cci.Index.create() tu = index.parse(file) print("Translation unit:",tu.spelling) #find_typerefs(tu.cursor,"JNINativeMethod") print(get_info(tu.cursor)) exit()""" return nfdd.getNativeFunctions(file) def generateLIB(file): spl = file.split(os.sep) nativeMethods=getRegisteredMethods(file) #print("FILE: "+file) #print("NVMS:\n"+str(nativeMethods)) #exit(0) return LIB(path=file, name=spl[len(spl)-1], nativeMethods=nativeMethods) <file_sep>#ifndef helper_h #define helper_h void safe(char* s); #endif<file_sep>#include <jni.h> #include <iostream> #include "header/JNI_JNI_Helper_Static.h" using namespace std; JNIEXPORT jint JNICALL test(JNIEnv *env, jclass thisObj, jint base, jint expo){ cout << "Static.cpp: test aka computeExpoStatic called" << endl; return -1; } jint JNI_OnLoad(JavaVM* vm, void* reserved){ JNIEnv *env; cout << "Static.cpp: JNIOnload called!" << endl; JNINativeMethod methods[] = { { "computeExpoStatic", "(II)I", (void *) test } }; vm->GetEnv((void **) &env, JNI_VERSION_1_4); jclass cls = env->FindClass("JNI/JNI_Helper_Static"); env->RegisterNatives(cls,methods,sizeof(methods)/sizeof(methods[0])); return JNI_VERSION_1_4; } JNIEXPORT jint JNICALL Java_JNI_JNI_1Helper_1Static_computeExpoStaticV2 (JNIEnv *env, jclass thisObj, jint base, jint expo){ cout << "Static.cpp: Returning -1" << endl; return -100; }<file_sep>#include <native/header/vulnerable.hpp> void safe (char* s){ callMe(s); }<file_sep>#!/bin/bash echo Building... ./buildTest.sh echo Building... DONE! echo "" echo "###### RUNNING ######" echo "" ./runTest.sh<file_sep>BLUE=`tput setaf 4` RED=`tput setaf 1` GREEN=`tput setaf 2` RESET=`tput sgr0` CYAN=`tput setaf 6` tag="${BLUE}[JAVA_MAIN] ${RESET}" done="${GREEN}DONE!${RESET}" vulSummaryResolvedCsv=$1 test_path=$2 java_out=$3 totalSummary=$4 c_cpp_analyser_scripts=$5/scripts db_Uri=$6 db_User=$7 db_Pword=$8 directory=$9 py=${10} time_log=${11} source "${directory}GETDIFF" if [[ ! -d $java_out ]]; then mkdir $java_out fi echo "${tag}Linking java src files to compiled jars..." strt=$(date) $py matchJavaSrcToJar.py $vulSummaryResolvedCsv $test_path $java_out |& tee "${java_out}J_matchJavaSrcToJar.log" #echo $skip stp=$(date) res=$(getDiff "$strt" "$stp") echo "Java_Analyser:::matchJavaSrcToJar $res" >> $time_log echo "${tag}Linking java src files to compiled jars... ${done}" #exit 0 echo "${tag}Tracing back calls in Java code..." strt=$(date) ./backTrack.sh $java_out $totalSummary |& tee "${java_out}J_backTrack.log" #echo $skip stp=$(date) res=$(getDiff "$strt" "$stp") echo "Java_Analyser:::backTrack $res" >> $time_log echo "${tag}Tracing back calls in Java code... ${done}" #exit 0 echo "${tag}Resolving local Java CGS (jni Bridges)..." strt=$(date) $py resolve_jar_to_src_callgraph.py $java_out |& tee "${java_out}J_resolve_jar_to_src_callgraph.log" #echo $skip stp=$(date) res=$(getDiff "$strt" "$stp") echo "Java_Analyser:::resolveJarToSrc $res" >> $time_log echo "${tag}Resolving local Java CGS (jni Bridges)... ${done}" #exit 0 if [ ! -d "$java_out/LocalBackTrackCGs" ]; then echo "${tag}${RED}No Local Backtrack Cgs created${RESET} (At least not to: ${CYAN}${java_out}/LocalBackTrackCGs${RESET})!" echo "${tag}${RED}Skipping Loading java CGs and linking them to global CG!${RESET}" exit 0 fi echo "${tag}Loading CGs into global graph..." strt=$(date) (cd $c_cpp_analyser_scripts && $py createGlobalCallGraph.py $java_out/LocalBackTrackCGs $db_Uri $db_User $db_Pword "" $directory "LOAD") |& tee "${java_out}J_load_global_graph.log" #echo $skip stp=$(date) res=$(getDiff "$strt" "$stp") echo "Java_Analyser:::Load $res" >> $time_log echo "${tag}Loading CGs into global graph... ${done}" #exit 0 echo "${tag}Linking together JNI CALLs..." strt=$(date) $py linkJNIGlobalCG.py $java_out/summary.csv $db_Uri $db_User $db_Pword $directory |& tee "${java_out}J_linkJNIGlobalCG.log" #echo $skip stp=$(date) res=$(getDiff "$strt" "$stp") echo "Java_Analyser:::Link $res" >> $time_log echo "${tag}Linking together JNI CALLs... ${done}" #exit 0 <file_sep>BLUE=`tput setaf 4` RED=`tput setaf 1` GREEN=`tput setaf 2` RESET=`tput sgr0` CYAN=`tput setaf 6` tag="${BLUE}[callGraphToDot]${RESET} " joernDir=$1 binFilePath=$2 outDir=$3 scriptDir=$4 inclOut=$5 modus=$6 if [ ! -d $outDir ]; then echo "${tag}Creating new output folder: ${CYAN}${outDir}${RESET}..." mkdir $outDir echo "${tag}Creating new output folder: ${CYAN}${outDir}${RESET}... ${GREEN}DONE!${RESET}" fi if [ ! -d $inclOut ]; then echo "${tag}Creating new output folder: ${CYAN}${inclOut}${RESET}..." mkdir $inclOut echo "${tag}Creating new output folder: ${CYAN}${inclOut}${RESET}... ${GREEN}DONE!${RESET}" fi tmp_process=p2 alive_check=ac hangT=50 rm $alive_check updateCur(){ echo 1 >> $tmp_process pt=0 while read line; do pt=$(( pt + 1)) done < $tmp_process curT=$(date +%s) if [[ -f $alive_check ]]; then sed -i "/${1}(${2})/d" ./$alive_check fi echo "${1}(${2});$curT" >> $alive_check chk=$((pt%50)) if [[ $chk -eq 0 ]]; then while read line; do pidd=($(echo $line | tr ";" "\n")) last=${pidd[-1]} pidd=${pidd[0]} diff=$((curT - $last)) if [[ $diff -gt $hangT ]]; then echo "$RED${pidd} Hang (since $diff seconds)!$RESET" fi done < $alive_check fi print=$(( pt % 20 )) if [[ $print == 0 ]]; then echo "${tag}[${1}(${2})] Proccessed: ${pt}/${total}" fi } createCG(){ start=$1 end=$2 curr=0 dir="NONE" ending="NONE" if [[ $modus == *"FAST"* ]]; then dir=$inclOut ending="*.incl" else dir=$binFilePath ending="*bin.zip" fi pid=$BASHPID id=$3 echo "${tag}[$start-$end]createCG with pid $CYAN$pid($id)$RESET started!" for jOut in $dir$ending do skip=$((curr < $start)) endCond=$((curr >= $end)) curr=$((curr + 1)) if [[ $skip -eq 1 ]]; then continue fi if [[ $endCond -eq 1 ]]; then echo "${tag}End condition reached." break fi name=($(echo $jOut | tr "/" "\n")) name=${name[-1]} if [[ $modus == *"FAST"* ]]; then name=${name/\.incl/""} else name=${name/\.bin\.zip/""} fi #echo "${tag}Processing ${CYAN}${jOut}${RESET} ..." updateCur $pid $id if [[ -f "${outDir}${name}.dot" ]]; then #echo "${tag}Skipping since cg already exists." #curr=$((curr+1)) continue fi (cd $joernDir && ./joern --script "${scriptDir}callGraphToDot.sc" --params "cpgFile=${binFilePath}${name}.bin.zip,outFile=${outDir}${name}.dot" >/dev/null 2>&1) #,inclOut=${inclOut}${name}.incl") # >/dev/null 2>&1) #curr=$((curr+1)) #echo "${tag}[${curr}/${total}]Processing ${CYAN}${jOut}${RESET} ... ${GREEN}DONE!${RESET}" done echo "${tag}[$start-$end]createCG with pid $CYAN${pid}(${id})$RESET $GREEN DONE! $RESET." sed -i "/${pid}(${id})/d" ./$alive_check } total=0 if [[ $modus == *"FAST"* ]]; then total=$(find $inclOut -maxdepth 1 -type f -name "*.incl" | wc -l) else total=$(find $binFilePath -maxdepth 1 -type f -name "*.bin.zip" | wc -l) fi multi=$(( total > 100 )) batches=1 rm $tmp_process split=50 if [[ $multi -eq 1 ]]; then batches=$((total / $split)) batches=$((batches + 1)) fi echo "${tag}Got a total of ${CYAN}$total files${RESET}!" maxthreads=20 cur_threads=0 id=0 for batch in $(seq $batches) do start=$(((batch-1) * $split)) end=$((batch * $split)) if [[ $cur_threads -eq $maxthreads ]]; then echo "Waiting cuz maxthreads reached" wait -n cur_threads=$((cur_threads - 1 )) fi createCG $start $end $id & cur_threads=$(( cur_threads + 1)) id=$((id + 1)) done wait echo "${tag}All files processed!" <file_sep>BLUE=`tput setaf 4` RED=`tput setaf 1` GREEN=`tput setaf 2` RESET=`tput sgr0` CYAN=`tput setaf 6` tag="${BLUE}[transferToDatabase]${RESET} " scriptPath=$1 localCallGraphsDotFormat=$2 includes=$3 db_Uri=$4 db_User=$5 db_Pword=$6 crossCalls=$7 directory=$8 py=$9 errFile=${10} srcFilePath=${11} time_log=${12} if [ ! -d $crossCalls ]; then echo "${tag}Creating new output folder: ${CYAN}${crossCalls}${RESET}..." mkdir $crossCalls echo "${tag}Creating new output folder: ${CYAN}${crossCalls}${RESET}... ${GREEN}DONE!${RESET}" fi touch $errFile echo "${tag}Creating neo4j callgraph... " echo "${tag}Using python version: $($py --version)" toneo(){ start=$1 end=$2 total=$3 id=$4 pid=$BASHPID echo "${tag}[$start-$end]createGlobalCG with pid $CYAN$pid($id)$RESET started!" (cd $scriptPath && $py createGlobalCallGraph.py $localCallGraphsDotFormat $db_Uri $db_User $db_Pword $crossCalls $directory LOAD $start $end $total) echo "${tag}[$start-$end]createGlobalCG with pid $CYAN$pid($id)$RESET $GREEN DONE! $RESET" } total=$(ls $localCallGraphsDotFormat | wc -l) split=20 batches=$((total/ $split)) batches=$((batches +1 )) maxthreads=20 cur_threads=0 id=0 source "${directory}GETDIFF" strt=$(date) for batch in $(seq $batches) do start=$(((batch-1) * $split)) end=$((batch * $split)) if [[ $cur_threads -eq $maxthreads ]]; then echo "Waiting cuz maxthreads reached" wait -n cur_threads=$((cur_threads - 1)) fi toneo $start $end $total $id & id=$((id + 1)) cur_threads=$(( cur_threads + 1)) done wait stp=$(date) res=$(getDiff "$strt" "$stp") echo "C_CPP_Analyser:::transferToDatabase:::Load $res" >> $time_log echo "$tag All files loaded!" echo "$tag Linking..." strt=$(date) (cd $scriptPath && $py createGlobalCallGraph.py $localCallGraphsDotFormat $db_Uri $db_User $db_Pword $crossCalls $directory "LOADED.FULL") stp=$(date) res=$(getDiff "$strt" "$stp") echo "C_CPP_Analyser:::transferToDatabase:::Link $res" >> $time_log echo "$tag Linking $GREEN DONE! $RESET" echo "${tag}Creating neo4j callgraph... ${GREEN}DONE!${RESET}" <file_sep>#main stuff mainPath=$1 #Database neo4jBin=$2 db_Uri=$3 db_User=$4 db_Pword=$5 windows=$6 BLUE=`tput setaf 4` RED=`tput setaf 1` GREEN=`tput setaf 2` RESET=`tput sgr0` CYAN=`tput setaf 6` clean(){ delete="MATCH (n) DETACH DELETE n;" echo "Cleaning DB..." ./cypher-shell -u $db_User -p $db_Pword "${delete}" echo "Cleaning DB... ${GREEN}DONE!${RESET}" } clean_db(){ status=$(./neo4j status) if [[ $status = *"not"* ]]; then ./neo4j start sleep 5 clean ./neo4j stop else clean fi } tag="${RED}[Clean] ${RESET}" (cd $neo4jBin && clean_db) <file_sep>from LIB.Function import Method import re from Helper.helper import cprint tag = "[Native_Func_Decl_Detector] " debug = False mp = {"jint": "I", "jbyte": "B", "jshort": "S", "jlong":"J", "jfloat":"F", "jdouble":"D", "jchar":"C", "jboolean":"Z", "jobject":"L", } def translate(string): string = string.strip() if (string in mp): return mp[string] """else: print("Not supported: ",string) """ return string def getNativeFunctions(file): #print("\n\n#################") #print(file) #print("------------------") ###gather native method declaration(s) content = "" inDeclaration = False pattern = "{\s*" declarations = [] bodies = [] openB = 0 bc = "" inbody = False with open(file,"r",errors="ignore") as f: if (debug): print("Parsing file",file) for l in f.readlines(): if (debug): print("Current line: ",l) if inDeclaration: content = content +"\n"+l tstl = l.replace(" ", "") if (("JNIEXPORT " in tstl) or ("JNICALL" in tstl) or ("(JNIEnv" in tstl) and not inDeclaration): content = l inDeclaration = True if not (re.search(pattern,content) is None): #print("MATCHED",content) if (inDeclaration == True): inbody = True if (debug): print("INBODY SET TO TRUE") inDeclaration = False declarations.append(content) content = "" if inbody: if not (l.strip() == ""): if not (openB == 0): bc += l else: bc += "{\n"+l.split("{",1)[1] #print("LINE ADDED",l) ob = l.count("{") cb = l.count("}") openB += ob - cb if openB <= 0 and inbody: bodies.append(bc) bc = "" inbody = False openB = 0 ##Simple trick: somitimes they also declare those methods ##with help of pointers e.g. JNINAtiveMethod* this results in ##a bug if only "JNINAtiveMethod" and not with whitespace ##but with whitespace this should be fine. if (debug): for x in declarations: cprint(x) cprint("BODIES:") for bd in bodies: cprint("------------BD--------------------") cprint(bd) cprint("------------BD END--------------------") cprint("BODIES END#########################") cprint("LENGHT %i Body, %i Declarations"%(len(bodies),len(declarations))) ###split gathered information in functions methods = [] for i in range(len(declarations)): content = declarations[i] body = bodies[i] if (debug): print("Current content:\n",content) print("According body:\n",body) try: editedContent = content.split("(",1)[0] except BaseException as err: cprint(tag+"getNativeFunctions(file) s.th. went wrong during editing content:\n") cprint("Content: \n"+content) cprint("Error Message:\n"+err) continue #print("Edited Content:") #print(editedContent) funcDecl = editedContent.strip() name = "NOT_Found" try: name = editedContent.strip().split(" ") name = name[len(name) - 1] name = name.split("_") name = name[len(name)-1] except Exception as e: cprint(tag+"ERR#1",e) signature="NOT_FOUND" ret = "NOT_Found" try: if ("JNIEXPORT") in funcDecl: ret = funcDecl.strip().split(" ")[1] ret = translate(ret) except Exception as e: cprint(tag + "ERR#3", e) try: signature = content.split("(")[1].split(")")[0] s = signature.split(",")[2:] signature = [] for arg in s: signature.append(arg.strip().split(" ")[0]) signature = [translate(sig) for sig in signature] signature = "(" + "".join(signature) + ")" + ret except Exception as e: cprint(tag+"ERR#2",e) #print("NAME",name) #print("Sig",signature) #print("decl",funcDecl) method = Method(name=name,signature=signature,func=funcDecl,body=body) methods.append(method) #print(method) #exit() #for x in methods: # print(x) #print("#################") return methods def test(): pattern = "{(.*)}(,?)" s = 'static const JNINativeMethod gAnimatedImageDrawableMethods[] = {' s += '{"nCreate","(JLandroid/graphics/ImageDecoder;IIJZLandroid/graphics/Rect;)J",' s += '(void*) AnimatedImageDrawable_nCreate }' print(s) res = re.findall(pattern,s,re.DOTALL) print(res) print("\n\nTADA:") [print(x) for x in res] <file_sep>#!/bin/bash BLUE=`tput setaf 4` RED=`tput setaf 1` GREEN=`tput setaf 2` RESET=`tput sgr0` CYAN=`tput setaf 6` #main stuff mainPath="path_to_folder_where_this_file_is_in" py=python3 #python version e.g. python.bat or python3 or phyton for windows, needs to be python 3 version joernPath="...Programme/Joern/" #folder to joern location !Make sure to use the Joern version supplied with #this tool, otherwhise you need to change some commands since its a tool #in development. #Database db_location="...\Neo4j\neo4j-community-3.5.18\bin" #folder to neo4j installation folder db_Uri="bolt://localhost:7687" #db_Uri="bolt://172.16.31.10:7687" db_User="neo4j" db_Pword="<PASSWORD>" #IMPORTANT! Also change commands on clean.sh (in same folder) if you run this tool on windows #i.e. neo4j -> neo4j.bat and cypher-shell -> cypher-shell.bat #SAME for Neo4JServer file #JNI_LIB_Finder jni_lib_finder="${mainPath}JNI_LIB_Finder/" test_path="${mainPath}tstFiles/fullTest" #root folder of ur project to analyse #Output directories outDir="${mainPath}Out/" time_log="${outDir}time.log" c_cpp_out="${outDir}/C_CPP_Analyser/" out_libs_summary="${outDir}/JNI_LIB_Finder/LIBs/" out_jni_summary="${outDir}/JNI_LIB_Finder/JNIs/" vulSummaryCsv="${outDir}C_CPP_Analyser/summary.csv" vulSummaryResolvedCsv="${outDir}C_CPP_Analyser/summary_resolved.csv" java_out="${outDir}Java/" totalSummary="${outDir}summary_complete.csv" #C / CPP Analysis #IMPORTANT: Also edit paths on C_CPP_Analyser/main.sh !!! c_cpp_analyser="${mainPath}C_CPP_Analyser/" #Java Analysis java_analyser="${mainPath}Java_Analyser/" tag="${RED}[MAIN]${RESET} " done="${GREEN}DONE!${RESET}" skip="${tag}${RED}SKIPPED!${RESET}" ##arg parse cleanFst="false" modus="FULL" printhelp(){ echo "### USAGE " echo "### ./ultra_main.sh [-c] [-f] [-h]" echo "### -c clean/delete out directory (${CYAN}${outDir}${RESET}) before usage" echo "### -f run in fast mode, default: FULL" echo "### ##### " exit 0 } #logFile=${outDir}/defaultLog.txt while getopts "cfh:" option do case ${option} in c) cleanFst="true";; f) modus="FAST";; h) printhelp;; #l) logFile=$OPTARG esac done echo "${tag}Using python version: ${CYAN}$($py --version)${RESET}" if [[ $cleanFst == *"y"* || $cleanFst == "true" ]]; then echo "${tag}Deleting/Cleaning out dir: ${CYAN}${outDir}${RESET}..." rm -r $outDir echo "${tag}Deleting/Cleaning out dir: ${CYAN}${outDir}${RESET}... ${done}" echo "${tag}Cleaning Neo4j Graph..." ./clean.sh $mainPath $db_location $db_Uri $db_User $db_Pword echo "${tag}Cleaning Neo4j Graph... ${done}" fi source GETDIFF if [[ ! -d "$outDir" ]]; then mkdir $outDir fi echo "${tag}Collecting JNI & LIB files..." strt=$(date) (cd $jni_lib_finder && $py static_analysis_main.py $test_path $out_libs_summary $out_jni_summary) |& tee "${outDir}M_jni_lib_finder.log" #echo $skip stp=$(date) res=$(getDiff "$strt" "$stp") echo "JNI_LIB_Finder: $res" >> $time_log echo "${tag}(${res})Collecting JNI & LIB files... ${done}" #exit 0 echo "${tag}Starting Database..." ./Neo4JServer $db_location start #echo $skip echo "${tag}Starting Database... ${done}" echo "${tag}Running C/CPP Analysis..." strt=$(date) (cd $c_cpp_analyser && ./main.sh $c_cpp_analyser $test_path $c_cpp_out $out_libs_summary $out_jni_summary $db_Uri $db_User $db_Pword $mainPath $py $modus $joernPath $time_log) #echo $skip stp=$(date) res=$(getDiff "$strt" "$stp") echo "C_C++_Analyser: $res" >> $time_log #exit 0 echo "${tag}Running C/CPP Analysis... ${done}" #exit 0 echo "${tag}Linking vulnerable native calls to JNI if possible..." strt=$(date) (cd $jni_lib_finder && ./link_native_to_jni.sh $jni_lib_finder $vulSummaryCsv $out_libs_summary $out_jni_summary $py) |& tee "${outDir}M_link_native_to_jni.log" #echo $skip stp=$(date) res=$(getDiff "$strt" "$stp") echo "JNI_LIB_Linker: $res" >> $time_log echo "${tag}Linking vulnerable native calls to JNI if possible... ${done}" #exit 0 #Be sure that ur compiled code (i.e. Jar files) are also reachable from the defined test_path #Otherwhise change test_path here #test_path=rootfolder (..../jar_files.jar) echo "${tag}Running java analyser..." strt=$(date) (cd $java_analyser && ./main.sh $vulSummaryResolvedCsv $test_path $java_out $totalSummary $c_cpp_analyser $db_Uri $db_User $db_Pword $mainPath $py $time_log) #echo $skip stp=$(date) res=$(getDiff "$strt" "$stp") echo "Java_Analyser: $res" >> $time_log echo "${tag}Running java analyser... ${done}" #exit 0 if [[ ! -d "$outDir/log" ]]; then mkdir "$outDir/log" fi for file in $(find $outDir -name "*.log") do mv $file "$outDir/log" done echo "${tag}Stopping Database..." ./Neo4JServer $db_location Stop #echo $skip echo "${tag}Stopping Database... ${done}" <file_sep>void callMe(char* s){ doinNothing(s); } void doinNothing(char* s){ vulnerable(s); } void vulnerable(char* s) { char buf[1024]; int size = sizeof(s); strcpy(buf, s); }<file_sep>from py2neo import Graph from py2neo.data import Node, Relationship #import os from neo4j import (GraphDatabase, WRITE_ACCESS,) import sys import time import random def tprint(string): print(string) sys.stdout.flush() class CallGraph: def __init__(self,uri,user,password): self._graph = Graph(uri,auth=(user,password)) self.db = GraphDatabase.driver(uri,auth=(user,password)) self.sess = self.db.session(default_access_mode=WRITE_ACCESS) self.user=user self.pw = password def __del__(self): self.sess.close() self.db.close() def addNode(self,node): if not (self._graph.exists(node)): self._graph.create(node) #relationship as string! def addNodeR(self,node_from,relationship,node_to): if not (self._graph.exists(Relationship(node_from,relationship,node_to))): self._graph.create(Relationship(node_from,relationship,node_to)) #relationship as relationship type! def addRelationship(self,relationship): if not (self._graph.exists(relationship)): self._graph.create(relationship) def merge(self,label): cg._graph.merge(label) def commit(self): self._tx.commit() def getGraph(self): return self._graph def getNode(self,node_label,properties=None,limit=1): #print("########################") q = "MATCH (n:"+node_label+") " if properties is not None: allNone = True for p in properties.values(): if p is not None: allNone = False break if not allNone: q +="WHERE " nd = False for i in properties.items(): if i[1] is None: continue if nd: q+=" AND " q+= "n."+str(i[0])+ "='"+str(i[1]).replace("'","\'")+"'" nd = True q+= "RETURN (n) " if limit is not None: q+= "LIMIT "+str(limit)+";" else: q+=";" #print(q) #tprint("RUNNING QUERY:\n"+q) maxtries=10 res2 = None #try avoid deadlocks for i in range(0,maxtries): try: res2 = self.sess.run(q) except: time.sleep(random.randrange(10)) node = None try: res2 = iter(res2) res2= next(res2) n = res2.get("n") node = Node() node.identity = n.id node.update_labels(n.labels) for prop in n.items(): node[prop[0]] = prop[1] node.graph = self._graph except Exception as e: pass #tprint("QUERY:\n"+q+"\nSUCCESS\nRESULT: "+str(node)) return node <file_sep>import pandas as pd import os import re import sys tag = "[resolve_jar_to_src_callgraph]" def getMap(summary): df = pd.read_csv(summary) mp = df.loc[(df["jniCall"] != "None") & (df["Jar"] != "None"),["jniCall","Jar"]] return mp def printDF(df): with pd.option_context('display.max_rows', None, 'display.max_columns', None,'display.max_colwidth',100): print(df) def processStr(string,mp): #print("PROCESSING: ") #print(string) res = string.split(" ") res = list(filter(None,res)) lst = [] for e in res: if ".jar" in e: #print("JAR FOUND: "+e) ls = e.split(".jar")[0]+".jar" rs = e.split(".jar")[1] #print("LF: "+ls) lst = mp.loc[mp["Jar"] == ls,"jniCall"].unique().tolist() #print("LIST: "+str(lst)) subclass=False search = res[0] if ("\"" in search): search = search.replace("\"","") #print("s b4: "+search) if ("$" in search): #print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") #print(tag+"Subclass seemd to be used") #print(tag+"Original name: "+str(search)) search = search.split("$",1)[0]+".java" #print(tag+"Edited to: "+str(search)) subclass = True #print("\nSUBCLASS: "+str(subclass)+"\n") for item in lst: #print("RES: "+str(res)) name = re.split("\\\\|\\|//|/", item) path = name[:len(name)-1] name = name[-1] if ("$" in name): #print(tag+"Subclass seemd to be used") #print(tag+"Original name: "+str(name)) name = name.split("$",1)[0] #print(tag+"Edited to: "+str(name)) #print("I: ",item) #print("N: "+name) #print("S: "+search) if name in search: res[2]="/".join(path)+"/"+name+"\"" #print("CHANGED") elif subclass: #BUGFIX #compare classes #BUT REAL FIX: Edit bws.jar! #~backTrackLocal~ WARNING: Currently only #supported initial comparison by function names,... #print("P: ",path) p = list(filter(None,path)) sp = list(filter(None,re.split("\\\\|\\|//|/", search))) sp = sp[:len(sp)-1] match = True for idx in range(1,len(sp)+1): if (len(p) - idx >= 0): #print("COMPARING") #print(p[len(p)-idx]) #print("?=?") #print(sp[len(sp)-idx]) if (p[len(p)-idx] != sp[len(sp)-idx]): #print("FALSE") match = False break #print("TRUE") if (match): res[2]="/".join(path)+"/"+name+"\"" res = " ".join(res) #if (res != string): # print("CHANGED: ") # print(res) return res def processLine(line,mp): newLine = "" if "->" in line: ls = line.split("->")[0] rs = line.split("->")[1] newLine = processStr(ls,mp)+" -> "+processStr(rs,mp) else: newLine = processStr(line,mp) return newLine def processCG(cgDir,file,mp): content = "" #print(file) with open(cgDir+os.path.sep+file,"r") as f: for line in f.readlines(): #print("b4: "+line) if ".jar" in line: nl = processLine(line,mp)+"\n" content += nl #print("after: "+nl) else: content+=line #print("after: (same)") with open(cgDir+os.path.sep+file,"w") as f: f.write(content) #print(content) def editCG(mp,cgDir): for file in os.listdir(cgDir): if file.endswith(".dot"): #print(file+":\n") processCG(cgDir,file,mp) def main(summary,cgDir): mp = getMap(summary) editCG(mp,cgDir) #summ=r"S:\Uni\Master\MasterArbeit\CompleteAnalysis\Out\Java\summary.csv" #cgDir=r"S:\Uni\Master\MasterArbeit\CompleteAnalysis\Out\Java\LocalBackTrackCGs" #main(summ,cgDir) if __name__ == "__main__": if (len(sys.argv) < 2): print("WRONG USAGE!") exit(0) summary = sys.argv[1]+"summary.csv" cgDir = sys.argv[1]+"LocalBackTrackCGs" if (os.path.exists(cgDir)): if (os.path.isfile(summary)): main(summary,cgDir) else: print(tag+"SKIPPING DUE TO MISSING SUMMARY FILE!") else: print(tag+"SKIPPING DUE TO NO OUTPUT OF LOCALBACKTRACKS!") <file_sep>int callMe(char* s); int doinNothing(char* s); int vulnerable(char* s);<file_sep>#!/bin/bash # javaFiles=$(pwd)/java jarName=exponent.jar buildDir=$(pwd)/build nativeDir=$(pwd)/native dynLibName=dynamic.dll stLibName=static.dll dynCppFile=JNI_JNI_Helper_Dynamic.cpp stCppFile=JNI_JNI_Helper_Static.cpp vul=vulnerable.cpp helper=helper.cpp echo Building jar file... (cd $javaFiles && find . -maxdepth 100 -type f -name "*.class" -exec rm {} +) (cd $javaFiles && javac -h . MainClass.java) (cd $javaFiles && jar cfve $jarName MainClass -C $javaFiles .) #echo "Testing if jar build successfull: " #(cd $javaFiles && java -jar $jarName) mkdir -p $buildDir/Java mkdir -p $nativeDir/header mv $javaFiles/$jarName $buildDir/Java/ mv $javaFiles/*.h $nativeDir/header echo Building jar file... DONE! echo Building library... (cd $nativeDir && x86_64-w64-mingw32-g++ -I"${JAVA_HOME}/include" -I"${JAVA_HOME}/include/win32" -shared -o $dynLibName $dynCppFile $vul $helper) (cd $nativeDir && x86_64-w64-mingw32-g++ -I"${JAVA_HOME}/include" -I"${JAVA_HOME}/include/win32" -shared -o $stLibName $stCppFile) mkdir -p $buildDir/Libs (cd $buildDir/Libs && rm *.dll) mv $nativeDir/*.dll $buildDir/Libs echo Building library... DONE! echo Test build done. <file_sep>import xml.etree.ElementTree as ET from xml.dom import minidom class Method: def __init__(self,name="",signature="",func="",includes=[],body=""): self.name = name self.signature = signature self.func = func self.includes = includes self.body=body def __repr__(self): return str(self) def __str__(self): strng = "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n" strng += "Method :"+self.name+"\n" strng += "Signature :"+self.signature+"\n" strng += "Function declaration :"+self.func+"\n" strng += "Includes :"+str(self.includes)+"\n" strng += "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n" return strng def setName(self,name): self.name = name def setSignature(self,signature): self.signature = signature def setFunctionCall(self,func): self.func = func def setIncludes(self,includes): self.includes = includes def addInclude(self,include): self.includes.append(include) def getName(self): return self.name def getSignature(self): return self.signature def getFunctionCall(self): return self.func def getIncludes(self): return self.includes def toXML(self,obj): xml = ET.SubElement(obj,"Method") name = ET.SubElement(xml,"Name") signature = ET.SubElement(xml,"Signature") func = ET.SubElement(xml,"FunctionDeclaration") body = ET.SubElement(xml,"Body") #includes = ET.SubElement(xml,"Includes") name.text = self.name signature.text = self.signature func.text = self.func body.text = self.body ##TODO: INCLUDES return obj def fromXML(obj): name = "" signature = "" func = "" try: name = obj.getElementsByTagName("Name")[0].firstChild.nodeValue signature = obj.getElementsByTagName("Signature")[0].firstChild.nodeValue func = obj.getElementsByTagName("FunctionDeclaration")[0].firstChild.nodeValue body = obj.getElementsByTagName("Body")[0].firstChild.nodeValue except: pass return Method(name=name, signature=signature, func=func,body=body) <file_sep>#!/bin/bash neo4jBin=$1 startStop=$2 if [[ $startStop = "start" ]]; then (cd $neo4jBin && ./neo4j start) else (cd $neo4jBin && ./neo4j stop) fi #(cd neo4jBin && ./neo4j start) <file_sep>import JNI.JNI_Helper_Static; import JNI.JNI_Helper_Dynamic; public class HelperClass{ public int compute(int nbr, int exponent){ System.out.println("HelperClass: compute called"); System.out.println("Using static jni helper..."); int jniRes = JNI_Helper_Static.exponentiate(nbr,exponent); System.out.println("Got res: "+jniRes); System.out.println("Using dynamic jni helper..."); JNI_Helper_Dynamic jhd = new JNI_Helper_Dynamic(); jniRes = jhd.exponentiate(nbr,exponent); System.out.println("Got res: "+jniRes); return jniRes; } }<file_sep>import os.path import sys import pandas as pd import pathlib path = pathlib.Path(__file__).parent.absolute().parent sys.path.append(str(path)) from Default.Colors import Color from JNI_LIB_Finder.JNI import JNI as JNI tag = Color.ORANGE.value+"[link_native_to_jni] "+Color.RESET.value def getContainedPerc(list1, list2): if (len(list1) < len(list2)): sw = list2 list1 = list2 list2 = sw matches = 0 matching = False for x in range(len(list1)).__reversed__(): if (list1[x] in list2): matches = matches + 1 matching = True else: if (matching): break return matches/len(list2) def link(row,lib_xml,jni_xml): print(tag+"Resolving "+Color.CYAN.value+row["srcFunc"]+Color.RESET.value) print(tag+"Location @: "+row["srcLoc"]) jniFiles = [] searchFileName = row["srcLoc"].split(os.path.sep) searchFileName = searchFileName[-1] searchFilePath = [] while (True): searchFileName, ext = os.path.splitext(searchFileName) searchFileName = searchFileName + ".java" for file in os.listdir(jni_xml): name, ext = os.path.splitext(file) if (ext == ".xml"): if (name == searchFileName): jniFiles.append(file) if (len(jniFiles) > 0 or not ("_" in searchFileName)): break searchFilePath.extend(searchFileName.split("_",1)) searchFileName = searchFilePath[-1] matchedJni = None percentage = -1.0 for f in jniFiles: jni = JNI.load(jni_xml + f) sfp = searchFilePath if (len(sfp) == 0): sfp.append(searchFileName) else: sfp[-1] = searchFileName curr_perc = getContainedPerc(jni.getPath().split(os.path.sep),sfp) if (curr_perc > percentage): percentage = curr_perc matchedJni = jni if (percentage == 1.0): break if (matchedJni == None): print(tag+Color.ORANGE.value+"Location could not be resolved."+Color.RESET.value) return None percentage = percentage * 100 print(tag+Color.GREEN.value+"Resolved (%i%%)" % percentage+Color.RESET.value+"to: "+str(matchedJni.getPath())) return matchedJni def main(csvFile, lib_xml, jni_xml): print(tag+"Trying to link native to JNI calls...") if not (os.path.isfile(csvFile)): print(tag+"File: '"+csvFile+"' does not exist!") return csv = pd.read_csv(csvFile) csv.rename(columns={"Function (Src)": "srcFunc","Function (Dst/Vul)":"dstFunc", "Native Call":"jniCall","Dst/Vul Location":"dstLoc", "Src Location":"srcLoc"},inplace=True) for idx,row in csv.iterrows(): if (row["jniCall"] == "TODO"): res = link(row,lib_xml,jni_xml) if (res == None): row["jniCall"] = "None" else: csv.loc[idx,"jniCall"] = str(res.getPath()) csvFile_resolved, ext = os.path.splitext(csvFile) csvFile_resolved = csvFile_resolved +"_resolved.csv" csv.to_csv(csvFile_resolved,index=False,header=True) print(tag+"Writing resolved summary to: "+Color.CYAN.value+csvFile_resolved+Color.RESET.value) print(tag + "Trying to link native to JNI calls... "+Color.GREEN.value+"DONE!"+Color.RESET.value) #main("S:/Uni/Master/MasterArbeit/joernAnalysis/bwSlicing/out/summary.csv") if __name__ == "__main__": if (len(sys.argv) < 4): print(tag+"To less arguments...") exit(0) main(sys.argv[1], sys.argv[2], sys.argv[3]) <file_sep>from enum import Enum class Color(Enum): BLUE="\033[38;5;20m" RED="\033[38;5;9m" GREEN="\033[38;5;82m" CYAN="\033[38;5;14m" ORANGE="\033[38;5;202m" RESET="\033[0m" <file_sep>#!/bin/bash javaOut=$1 totalSummary=$2 kind=appJar #TODO java8=TODO/Jdk8/bin/java.exe java8=$JAVA_HOME/bin/java exclusionFile=$(pwd)/exclusions.txt while read LINE; do args=($(echo $LINE | tr ";" "\n")) jarFile=${args[0]} bt=${args[@]:1:${#args[@]}} echo "${jarFile}" echo "$bt" #$java8 -jar bws.jar -$kind $jarFile -out $javaOut -exclusionFile $exclusionFile -bt $bt $java8 -jar bws_debug.jar -$kind $jarFile -out $javaOut -exclusionFile $exclusionFile -bt "$bt" done < "${javaOut}/todo.txt" <file_sep>BLUE=`tput setaf 4` RED=`tput setaf 1` GREEN=`tput setaf 2` RESET=`tput sgr0` CYAN=`tput setaf 6` tag="${BLUE}[backwardsSlicing]${RESET} " joernDir=$1 scriptPath=$2 binFilePath=$3 crossCalls=$4 detailedOutPath=$5 csvFile=$6 vulPath=$7 logPath=$8/log if [ ! -d $detailedOutPath ]; then echo "${tag}Creating new output folder: ${CYAN}${detailedOutPath}${RESET}..." mkdir $detailedOutPath echo "${tag}Creating new output folder: ${CYAN}${detailedOutPath}${RESET}... ${GREEN}DONE!${RESET}" fi if [[ ! -d $logPath ]]; then mkdir $logPath fi for f in $vulPath/*.vul do #BUGGY: ASSUMPTION: 1 line free after last entry! while read LINE; do #fileName=${file/\.bin\.zip/""} #fileName=${fileName/\.c/""} #variable=x #func=func3 #echo "${tag} LINE: ${LINE}" opts=($(echo $LINE | tr ";" "\n")) func=${opts[0]} vulLine=${opts[1]} location=${opts[2]} fileName=($(echo $location | tr "/" "\n")) fileName=${fileName[-1]} fileName=${fileName/\.cpp/""} fileName=${fileName/\.c/""} echo "${tag}Applying backwards slicing for ${CYAN}${func}: ${vulLine} (${location}) ${RESET}..." #out=$ cpgName=$fileName same=$(find $binFilePath \( -name "$fileName.bin.zip" -o -name "${fileName}_*.bin.zip" \) ) same=($(echo $same | tr " " "\n")) #echo ${same[@]} | tr " " "\n" if [[ ${#same[@]} -gt 1 ]]; then for cpg in ${same[@]} do #echo $cpg cntxt=$(cat $cpg | grep $location) if [[ $cntxt == *"matches"* ]]; then cpgName=($(echo $cpg | tr "/" "\n")) cpgName=${cpgName[-1]} cpgName=${cpgName/\.bin\.zip/""} #echo $cpgName break fi done fi (cd $joernDir && ./joern --script "${scriptPath}backwardsSlicing.sc" --params "cpgPath=${binFilePath},cpgName=${cpgName},func=${func},lnNbrStr=${vulLine},crossCalls=${crossCalls},outFile=${detailedOutPath}${cpgName}.dot,csvFile=${csvFile}" > "$logPath/$cpgName.out") #echo $out echo "${tag}Applying backwards slicing for ${CYAN}${func}: ${vulLine} (${location}) ${RESET}... ${GREEN}DONE!${RESET}" done < $f done <file_sep>import subprocess as sp import os from tqdm import tqdm #import queue from multiprocessing import JoinableQueue as Queue from multiprocessing import Process from threading import Thread # Mingw64 #mingw64 = r"S:\Programme\git\Git\usr\bin\mintty.exe" #mingw32 = r"S:\Uni\Master\SS18\embsec\Ex4\ChipSoftware\msys32\mingw32.exe" console = r"S:\Programme\git\Git\git-bash.exe" joernLocation = "S://Programme/Joern/joern-cli/bin" tag = "[Joern/Joern.py]" q = Queue() #pbar = Queue() def createPropertyGraph(lib,outDir): joerncmd = "./joern-parse " joerncmd += str(lib.getPath())+" " name = lib.getName().replace(".cpp",".zip") joerncmd += "--out '"+outDir+os.path.sep+name+"'" cmd = console+" -c "+'"(cd '+joernLocation+" && "+joerncmd+')"' cmd = cmd.replace("\\","//") cmd = cmd.replace("\\\\","//") #print(cmd) #does not work """ si = sp.STARTUPINFO() si.dwFlags = sp.STARTF_USESHOWWINDOW si.wShowWindow = sp.SW_HIDE cflags = sp.CREATE_NO_WINDOW with sp.Popen(cmd,stdout=sp.PIPE,creationflags=sp.CREATE_NO_WINDOW) as proc:#,startupinfo=si,creationflags=cflags) as proc: print(proc.stdout.read()) """ shell = sp.Popen(cmd,stdout=sp.PIPE)#,startupinfo=startupInfo)#,creationflags=sp.CREATE_NEW_CONSOLE) out,err = shell.communicate() def worker(outDir,pBar): #global pbar while True: lib = q.get() if lib is None: q.task_done() break createPropertyGraph(lib,outDir) #pbar.put(True) pBar.put(True) q.task_done() def run(procQueue,pBar,outDir,maxThreads=1): isNone = False while True: libs = [] elements = [] for i in range(maxThreads): try: x = procQueue.get(False) except: break elements.append(x) if not (x is None): libs.append(x) else: isNone = True break if (len(libs)>0): run2(pBar,libs,outDir,maxThreads) for i in range(len(elements)): #pBar.put(True) procQueue.task_done() if isNone: break def run2(pBar,libs,outDir,maxThreads=1): #print(str(os.getpid())+": "+"RUNNING-"+str(len(libs))) #global pbar if (len(libs) < maxThreads): maxThreads = len(libs) threads = [] for i in range(maxThreads): t = Thread(target=worker,args=(outDir,pBar,)) t.deamon = True t.start() threads.append(t) for lib in libs: q.put(lib) """ #Progressbar cheat for x in tqdm(range(len(libs))): while True: if not pbar.empty(): pbar.get() break """ q.join() #stop worker for i in range(maxThreads): q.put(None) for t in threads: t.join() return def test(): curr = os.getcwd() os.chdir(r"S:\Programme\Joern\joern-cli\bin") cd = sp.Popen([gitBash,"-c","(cd S://Desktop && mkdir hi)"],stdin=sp.PIPE,stdout=sp.PIPE,shell=True) out,err = cd.communicate() print(out) print(err) os.chdir(curr) <file_sep>import os import pathlib import sys from tqdm import tqdm import LIB.LIB as LIB from Helper.helper import cprint path = pathlib.Path(__file__).parent.absolute().parent.parent sys.path.append(str(path)) from Default.Colors import Color frame_path = "" tag = Color.ORANGE.value+"[LIB_Finder] "+Color.RESET.value done = Color.GREEN.value+"DONE!"+Color.RESET.value def getCPPFiles(path,firstTime=False): if (firstTime): files = [] try: for dirOrFile in tqdm(os.listdir(path)): try: if os.path.isfile(os.path.join(path,dirOrFile)): if(dirOrFile.endswith(".cpp") or dirOrFile.endswith(".c")): files.append(os.path.join(path,dirOrFile)) else: files.extend(getCPPFiles(os.path.join(path,dirOrFile))) except Exception as e: cprint(tag+"ERROR#1: "+str(e)) cprint(tag+"ERROR#1: "+str(os.path.join(path,dirOrFile))) except Exception as e: cprint(tag+"ERROR: "+str(e)) cprint(tag+"ERROR: "+str(path)) return files else: files = [] try: for dirOrFile in os.listdir(path): try: if os.path.isfile(os.path.join(path,dirOrFile)): if(dirOrFile.endswith(".cpp") or dirOrFile.endswith(".c")): files.append(os.path.join(path,dirOrFile)) else: files.extend(getCPPFiles(os.path.join(path,dirOrFile))) except Exception as e: cprint(tag+"ERROR#2: "+str(e)) cprint(tag+"ERROR#2: "+str(os.path.join(path,dirOrFile))) except Exception as e: cprint(tag+"ERROR#3: "+str(e)) cprint(tag+"ERROR#3: "+str(path)) return files def genLIB(file): try: with open(file,"r",errors="ignore") as f: for line in f.readlines(): #edited if ("JNINativeMethod" in line): if ("JNIEnv" in line): return LIB.generateLIB(file) except Exception as e: cprint(tag+"ERROR#4: "+str(file)) cprint(tag+"ERROR#4: "+str(e)) return None def detectLIBs(framework_path="",outDir=None): frame_path = framework_path if not (os.path.isdir(frame_path)): raise Exception(tag+"detectLIBs():\n framework_path Directory not found: '"+frame_path+"' !") if not (outDir is None): if not (os.path.isdir(outDir)): raise Exception(tag+"(detectLIBs()):\n outDir Directory not found: '"+outDir+"' !") #collect possible libs cprint(tag+"Collecting possible LIB files...") files = getCPPFiles(frame_path,firstTime=True) cprint("\n"+tag+"Collecting possible LIB files... "+done) LIB_Files = [] cprint(tag+"Detecting Libraries...") for file in tqdm(files): res = genLIB(file) if not (res is None): LIB_Files.append(res) cprint("\n"+tag+"Detecting Libraries... "+done) if (outDir == None): for lib in LIB_Files: cprint(lib) else: cprint(tag+"Storing Files...") for lib in tqdm(LIB_Files): lib.store(outDir) cprint("\n"+tag+"Storing Files... "+done) cprint(tag+"Total: "+Color.CYAN.value+str(len(LIB_Files))+" LIBs"+Color.RESET.value) return LIB_Files <file_sep>#!/bin/bash directory=$1 #@see ultra_main.sh: mainPath filePath=$2 outDir=$3 #@see ultra_main.sh: outDir #filePath=$2 for later! ## EDIT END ## #These don't have to be edited, just if wanted. lib_xml=$4 jni_xml=$5 db_Uri=$6 db_User=$7 db_Pword=$8 rootDir=$9 py=${10} modus=${11} joernPath=${12} time_log=${13} binFilePath="${outDir}cpgs/" callGraphOutDir="${outDir}dot/" scriptPath="${directory}scripts/" joernDir="${joernPath}joern-cli/" csvFile="${outDir}summary.csv" #if this is edited need to be set to same value #as vulSummaryCsv @see: ultra_main.sh detailedOutPath="${outDir}detailed/" #inclOut="${outDir}includes/" inclOut="${outDir}incl2/" crossCalls="${outDir}crossCalls/" detailedVul="${outDir}vul/" errFile="${outDir}toDB.err" #dot2pngLoc=".../dot2png.bat" BLUE=`tput setaf 4` RED=`tput setaf 1` GREEN=`tput setaf 2` RESET=`tput sgr0` CYAN=`tput setaf 6` tag="${RED}[C/CPP MAIN]${RESET} " skip="${tag}${RED}SKIPPED!${RESET}" getDiff(){ strt=$1 stp=$2 diff=$(( $(date -d "$stp" "+%s") - $(date -d "$strt" "+%s") )) diffh=$(date -d@$diff -u +%H:%M:%s) echo $diffh } if [[ ! -d $outDir ]]; then echo "${tag}Creating new output folder: ${CYAN}${outDir}${RESET}..." mkdir $outDir echo "${tag}Creating new output folder: ${CYAN}${outDir}${RESET}... ${GREEN}DONE!${RESET}" fi strt=$(date) ############################# Parse Source Files ####################################### echo "${tag}Applying Joern on source code..." echo "${tag}Directory: ${CYAN}${filePath}${RESET}" ./codeImport.sh $joernPath $filePath $binFilePath |& tee "${outDir}C_codeImport.log" #echo $skip stp=$(date) res=$(getDiff "$strt" "$stp") echo "C_CPP_Analyser:::codeImport $res" >> $time_log echo "${tag}${CYAN}(${res})Applying Joern on source code... ${GREEN}DONE!${RESET}" ############################# END Parse Source Files END ####################################### ############################# search for vulnerabilities ####################################### strt=$(date) echo "${tag}Searching for potential vulnerabilities..." ./detectVulnerabilites.sh $binFilePath $joernDir $scriptPath $detailedVul $outDir |& tee "${outDir}C_detectVulnerabilities.log" #echo $skip stp=$(date) res=$(getDiff "$strt" "$stp") echo "C_CPP_Analyser:::detectVulnerabilities $res" >> $time_log echo "${tag}${CYAN}(${res})Searching for potential vulnerabilities... ${GREEN}DONE!${RESET}" #exit 0 ############################# END search for vulnerabilities END ###################################### ############################# generate includes ####################################### strt=$(date) echo "${tag}Generating includes with modus ${CYAN}${modus}${RESET}..." ./genInclude.sh $scriptPath $filePath $inclOut $db_Pword $db_User $db_Uri $rootDir $py $outDir $modus |& tee "${outDir}C_includeGenerator.log" ###(cd $scriptPath && $py includeGenerator.py $filePath $inclOut $db_Pword $db_User $db_Uri $rootDir) |& tee "${outDir}C_includeGenerator.log" #echo $skip stp=$(date) res=$(getDiff "$strt" "$stp") echo "C_CPP_Analyser:::includeGenerator $res" >> $time_log #exit 0 echo "${tag}${CYAN}(${res})Generating includes with modus ${CYAN}${modus}${RESET}... ${GREEN}DONE!${RESET}" ############################# END generate includes END ###################################### ############################# create call graph ####################################### strt=$(date) echo "${tag}Creating callgraph..." echo "${tag}Creating local callgraph..." ./callGraphToDot.sh $joernDir $binFilePath $callGraphOutDir $scriptPath $inclOut $modus $outDir |& tee "${outDir}C_callGraphToDot.log" #echo $skip stp=$(date) res=$(getDiff "$strt" "$stp") echo "C_CPP_Analyser:::callGraphToDot $res" >> $time_log #exit 0 echo "${tag}${CYAN}(${res})Creating local callgraph... ${GREEN}DONE!${RESET}" ############################ END create call graph END ########################################## ############################ create global graph ######################################### strt=$(date) echo "${tag}Linking local callgraphs to global callgraph..." #(cd $callGraphOutDir && dot2png.bat) ./transferToDatabase.sh $scriptPath $callGraphOutDir $inclOut $db_Uri $db_User $db_Pword $crossCalls $rootDir $py $errFile $filePath $time_log |& tee "${outDir}C_transferToDatabase.log" #echo $skip stp=$(date) res=$(getDiff "$strt" "$stp") echo "C_CPP_Analyser:::transferToDatabase $res" >> $time_log #echo "${tag}${CYAN}(${res})Linking local callgraphs to global callgraph... ${GREEN}DONE!${RESET}" echo "${tag}Creating callgraph... ${GREEN}DONE!${RESET}" #exit 0 ############################# END create glboal graph END ####################################### ############################# Backwards tracking ####################################### strt=$(date) echo "${tag}Applying Backwards slicing for potential vuln functions..." ./backwardsSlicing.sh $joernDir $scriptPath $binFilePath $crossCalls $detailedOutPath $csvFile $outDir $outDir |&tee "${outDir}C_backwardsSlicing.log" #echo $skip stp=$(date) res=$(getDiff "$strt" "$stp") echo "C_CPP_Analyser:::backwardsSlicing $res" >> $time_log echo "${tag}${CYAN}(${res})Applying Backwards slicing for potential vuln functions... ${GREEN}DONE!${RESET}" ############################# END Backwards tracking END ####################################### <file_sep>#!/bin/bash BLUE=`tput setaf 4` RED=`tput setaf 1` GREEN=`tput setaf 2` RESET=`tput sgr0` CYAN=`tput setaf 6` tag="${BLUE}[genInclude]${RESET} " scriptPath=$1 srcDir=$2 inclOut=$3 dbP=$4 dbU=$5 dbUri=$6 rootD=$7 py=$8 vulDir=$9 modus=${10} max=20 cur=0 id=0 total=$(find $srcDir \( -name "*.h" -o -name "*.hpp" -o -name "*.c" -o -name "*.cpp" \) | wc -l) #total=10 multi=$((total > 1)) batches=1 split=500 #000000 if [[ $multi -eq 1 ]]; then batches=$((total / $split)) batches=$((batches + 1)) fi echo "${tag} Got a total of ${CYAN}$total files${RESET}!" for batch in $(seq $batches) do start=$(((batch-1)*$split)) end=$((batch * $split)) if [[ $end -gt $total ]]; then end=$total fi if [[ $cur -eq $max ]]; then echo "Waiting cuz max processes reached!" wait -n cur=$((cur - 1)) fi (cd $scriptPath && $py includeGenerator.py $srcDir $inclOut $dbP $dbU $dbUri $rootD $start $end LOAD) & cur=$((cur + 1)) id=$((id+1)) done wait (cd $scriptPath && $py includeGenerator.py $srcDir $inclOut $dbP $dbU $dbUri $rootD -1 -1 GENINCL $vulDir $modus) echo "${tag} All files processed!" <file_sep>#include "vulnerable.hpp" int safe (char* s); <file_sep>import xml.etree.ElementTree as ET class Method: #parameter = list of class Parameter def __init__(self,keywords=[],name="",parameter=[],calledNativeMethods=[],info=None): self.keywords = keywords self.name = name self.parameter = parameter self.calledNativeMethods = calledNativeMethods self.info = info def setKeywords(self,keywords): self.keywords = keywords def setName(self,name): self.name = name def setParameter(self,parameter): self.parameter = parameter def setInfo(self,info): self.info = info def addParameter(self,param): self.parameter.append(param) def setCalledNativeMethods(self,cnm): self.calledNativeMethods = cnm def addCalledNativeMethod(self,cnm): self.calledNativeMethods.append(cnm) def getInfo(self): return self.info def getKeywords(self): return self.keywords def getName(self): return self.name def getParameter(self): return self.parameter def getCalledNativeMethods(self): return self.calledNativeMethods def toXML(self,obj): #print(ET.tostring(obj)) xml = ET.SubElement(obj,"Method") name = ET.SubElement(xml,"Name") keywords = ET.SubElement(xml,"Keywords") parameter = ET.SubElement(xml,"Parameter") calledNativeMethods = ET.SubElement(xml,"CalledNativeMethods") info = ET.SubElement(xml,"Info") name.text = self.name keywords.text = str(self.keywords) for para in self.parameter: paramter = para.toXML(parameter) for nm in self.calledNativeMethods: #short version sub = ET.SubElement(calledNativeMethods,"Method") n = ET.SubElement(sub,"Name") i = ET.SubElement(sub,"Info") n.text = nm.getName() i.text = str(nm.getInfo()) info.text = str(self.info) #print(ET.tostring(obj)) return obj def fromXML(obj): name = obj.getElementsByTagName("Name")[0].firstChild.nodeValue kws = obj.getElementsByTagName("Keywords")[0].firstChild.nodeValue keywords = [] kws = kws.replace("'","") kws = kws.replace("[","") kws = kws.replace("]","") kws = kws.split(",") for kw in kws: keywords.append(kw.strip()) para = obj.getElementsByTagName("Parameter") parameter =[] for p in para: res = Parameter.fromXML(p) if not (res is None): parameter.append(Parameter.fromXML(p)) calledNativeMethods = [] nms = obj.getElementsByTagName("CalledNativeMethods")[0] if not (nms is None): for nm in nms.getElementsByTagName("Method"): nm_name = nm.getElementsByTagName("Name")[0].firstChild.nodeValue nm_info = nm.getElementsByTagName("Info")[0].firstChild.nodeValue calledNativeMethods.append(Method(name=nm_name, info=nm_info)) info = obj.getElementsByTagName("Info")[0].firstChild.nodeValue if (info == "None"): info = None return Method(keywords=keywords, name=name, parameter=parameter, calledNativeMethods=calledNativeMethods, info=info) def __repr__(self): return str(self) def __str__(self): strng = ("-------------------------------------------------------------\n") strng += ("Method :"+self.name+"\n") strng += ("Keywords :"+str(self.keywords)+"\n") strng += ("Parameter :"+str(self.parameter)+"\n") #kurzer string strng += ("calledNativeMethods :") i = 0 for nm in self.calledNativeMethods: if (i == 0): strng += nm.getName() i += 1 else: strng += ", "+nm.getName() strng += "\n" #Ausfuerlicher string """ strng += ("calledNativeMethods :\n") for nm in self.calledNativeMethods: strng += " "+"................\n" strng += " "+nm.getName()+"\n" strng += " "+str(nm.getInfo())+"\n" strng += " "+"................\n" strng += "\n" """ strng += ("Info: :"+str(self.info)+"\n") strng += ("-------------------------------------------------------------\n") return strng class Parameter: def __init__(self,typ="",name=""): self.typ = typ self.name = name def __str__(self): return (self.typ+" "+self.name) def __repr__(self): return (self.typ+" "+self.name) def setTyp(self,typ): self.typ = typ def setName(self,name): self.name = name def getTyp(self): return self.typ def getName(self): return self.name def toXML(self,obj): xml = ET.SubElement(obj,"Parameter") name = ET.SubElement(xml,"Name") typ = ET.SubElement(xml,"Type") name.text = self.name typ.text = self.typ return obj def fromXML(obj): try: name = obj.getElementsByTagName("Name")[0].firstChild.nodeValue typ = obj.getElementsByTagName("Type")[0].firstChild.nodeValue return Parameter(name=name,typ=typ) except: return None <file_sep>import pandas as pd import os import re import zipfile #from unrar import rarfile import sys from io import BytesIO import ntpath def readSum(summary): df = pd.read_csv(summary) try: df.insert(loc=3,column="Jar",value="None") except: pass try: df.insert(loc=4,column="perc",value=0) except: pass return df def delSameDirs(path1, path2): path1 = list(filter(None,path1)) path2 = list(filter(None,path2)) minlen = min(len(path1), len(path2)) sameIdx = 0 for i in range(0,minlen): if (path1[i] != path2[i]): break sameIdx = i return path1[sameIdx+1:] def getPercentage(name,path,matchStr,jarParentDir): matchStrS = re.split("\\\\|\\|//|/", matchStr) if not (os.path.splitext(matchStrS[-1])[0] == name ): return 0 diff = delSameDirs(path,re.split("\\\\|\\|//|/",jarParentDir)) matchStrS = matchStrS[:len(matchStrS)-1] diff2 = delSameDirs(diff,matchStrS) perc = len(diff2) / len(diff) return int(perc*100) def clean(list): res = [] for item in list: done = False for r in res: if r[0] == item[0]: if r[2] < item[2]: res.remove(r) res.append(item) done = True if not (done): res.append(item) return res def updateMatchesDex(todo,file,df,parentDir): #print("updateMatchesDex") for x in todo: if x.endswith("/") or x.endswith("\\"): while (x.endswith("/") or x.endswith("\\")): x = x[:len(x)-1] detect = ntpath.basename(x).split(".java")[0] path = ntpath.split(x)[0] path = re.split("\\\\|\\|//|/", path) detectb = bytes(detect,"utf-8") res = "" #print("NAME",detect) #print("PATH",path) with open(file,"rb") as f: for line in f.readlines(): if (detectb in line): namepath = str(line).split(";") for item in namepath: item = str(item) if (detect in item) and ("L" in item): res = item if ("/"+detect in item): try: res = res.split("L",1)[1] except: pass if (res != ""): perc = getPercentage(detect,path,res,parentDir) if (df.loc[df["jniCall"] == x, "perc"].iloc[0] < perc): file = "/".join(re.split("\\\\|\\|//|/", file)) df.loc[df["jniCall"] == item, "Jar"] = file df.loc[df["jniCall"] == item, "perc"] = perc return df def updateMatches(todo,matchStr,file,df,jarParentDir): #print("updateMatches") #print("TODO",todo) #print("MATCHSTR",matchStr) #print(file) for item in todo: xsplit = re.split("\\\\|\\|//|/", item) name = os.path.splitext(xsplit[-1])[0] path = xsplit[:len(xsplit)-1] #print("NAME",name) #print("PATH",path) if name in matchStr: perc = getPercentage(name,path,matchStr,jarParentDir) if (df.loc[df["jniCall"] == item, "perc"].iloc[0] < perc): file = "/".join(re.split("\\\\|\\|//|/", file)) df.loc[df["jniCall"] == item, "Jar"] = file df.loc[df["jniCall"] == item, "perc"] = perc return df def searchZipLike(zipf,endings,todo,df,jarParentDir,parentZip=None): #print("SZL") #print(zipf) #print(type(zipf)) #print(todo) if (isinstance(zipf,BytesIO)): zf = zipfile.ZipFile(zipf) else: zf = zipfile.ZipFile(zipf,"r") try: for name in zf.namelist(): #print(name) f, ext = os.path.splitext(name) if (ext in endings): zfdata = BytesIO(zf.read(name)) searchZipLike(zfdata,endings,todo,df,jarParentDir,zipf) if (ext == ".class"): #print("------------------") #print(zipf) #print(name) #print(orig) #print("------------------") updateMatches(todo,name,parentZip,df,jarParentDir) except Exception as e: print("Exception during crawling through ziplike object: \n"+e) print(zipf) print(type(zipf)) finally: zf.close() def linkToJar(df,jarParentDir): todo = df.loc[df["jniCall"] != "None"] todo = todo["jniCall"].tolist() zipEndings =[".jar",".dex",".jack",".jayce",".zip"] olddf = df for root, dirs, files in os.walk(jarParentDir): for file in files: #if file.endswith(".jar"): f, ends = os.path.splitext(file) #if (ends == ".rar"): # print("NOOOOO rar file well, i screwed.") #if ends in zipEndings: # searchZipLike(root+os.sep+file,zipEndings,todo,df,jarParentDir) if (file.endswith(".dex")): continue #df = updateMatchesDex(todo,os.path.join(root,file),df,jarParentDir) elif (file.endswith(".jar")): try: if (os.path.islink(root+os.path.sep+file)): continue jf = zipfile.ZipFile(root+os.path.sep+file,"r") try: lst = jf.infolist() for zi in lst: fn = zi.filename if fn.endswith('.class'): df = updateMatches(todo,fn,root+os.path.sep+file,df,jarParentDir) finally: jf.close() except Exception as e: print("ERR#6",e) print(root+os.path.sep+file) #print("Current df") #print(df) return df def writeJavaBacktracks(df,outFolder): jars = df.loc[df["Jar"] != "None","Jar"].unique() dict = {} for jar in jars: for idx, row in df.loc[df["Jar"] == jar].iterrows(): functionName=row["srcFunc"].split("_")[-1] if (dict.__contains__(jar)): dict[jar].append(functionName) else: dict[jar] = [functionName] with open(outFolder+os.path.sep+"todo.txt","w") as f: for entry in dict: bt = (" | ").join(set(dict[entry])) entry = "/".join(re.split("\\\\|\\|//|/",entry)) f.write(entry+"; "+bt+"\n") #df.loc[df["Jar"] != "None","Jar"].tolist(): #f.write(item) return def main(summary,jarParentDir,javaAnalyserOut): javaAnalyserOut = re.split("\\\\|\\|//|/",javaAnalyserOut) javaAnalyserOut = os.path.sep.join(javaAnalyserOut) df = readSum(summary) df = linkToJar(df,jarParentDir) if not (os.path.exists(javaAnalyserOut)): os.makedirs(javaAnalyserOut) df.to_csv(javaAnalyserOut+os.path.sep+"summary.csv",columns=["srcFunc","dstFunc","jniCall","Jar","dstLoc","srcLoc"]) writeJavaBacktracks(df,javaAnalyserOut) #jarDir = r"S:\Uni\Master\MasterArbeit\CompleteAnalysis\srcFiles\fullTest" #sumDir = r"S:\Uni\Master\MasterArbeit\CompleteAnalysis\Out\C_CPP_Analyser\summary_resolved.csv" #javaAnalyserOut = r"S:\Uni\Master\MasterArbeit\CompleteAnalysis\Out\Java_Analyser" #main(sumDir, jarDir,javaAnalyserOut) if __name__ == "__main__": if (len(sys.argv) < 3): print("WRONG USAGE!") else: main(sys.argv[1],sys.argv[2],sys.argv[3]) <file_sep>#!/bin/bash BLUE=`tput setaf 4` RED=`tput setaf 1` GREEN=`tput setaf 2` RESET=`tput sgr0` CYAN=`tput setaf 6` tag="${BLUE}[UPDATE]${RESET} " tmp_process=p2 alive_check=ac hangT=50 #hangT=0 rm $alive_check rm $tmp_process doneId(){ id=$1 pid=$2 sed -i "/${pid}(${id})/d" ./$alive_check } updateCur(){ echo 1 >> $tmp_process pt=0 while read line; do pt=$(( pt + 1)) done < $tmp_process curT=$(date +%s) if [[ -f $alive_check ]]; then sed -i "/${1}(${2})/d" ./$alive_check fi echo "${1}(${2});$curT" >> $alive_check chk=$((pt%50)) #chk=$((pt%1)) if [[ $chk -eq 0 ]]; then while read line; do pidd=($(echo $line | tr ";" "\n")) last=${pidd[-1]} pidd=${pidd[0]} diff=$((curT - $last)) if [[ $diff -gt $hangT ]]; then echo "$RED${pidd} Hang (since $diff seconds)!$RESET" fi done < $alive_check fi print=$(( pt % 20 )) #print=$(( pt % 1 )) if [[ $print == 0 ]]; then echo "${tag}[${1}(${2})] Proccessed: ${pt}/${total}" fi } <file_sep>#!/bin/bash source UPDATE joernPath=$1 joernServer="${joernPath}joern-server/" joernCLI="${joernPath}joern-cli/" joernCpg="${joernPath}cpg/cpgclientlib/" filePath=$2 outDir=$3 BLUE=`tput setaf 4` RED=`tput setaf 1` GREEN=`tput setaf 2` RESET=`tput sgr0` CYAN=`tput setaf 6` tag="${BLUE}[codeImport]${RESET} " export _Java_OPTS="-Xmx20G" #20GB of ram #include create update #source UPDATE if [ ! -d "$outDir" ]; then echo "${tag}Creating new output folder: ${CYAN}${outDir}${RESET}..." mkdir -p $outDir echo "${tag}Creating new output folder: ${CYAN}${outDir}${RESET}... ${GREEN}DONE!${RESET}" fi createCPG(){ start=$1 end=$2 id=$3 pid=$BASHPID curr=0 echo "${tag}[$start-$end]createCPG with pid $CYAN$pid($id)$RESET started!" #for file in ${filePath}*.cpp ${filePath}*.c for file in $(find $filePath -maxdepth 10000 \( -name "*.cpp" -o -name "*.c" \)) do skip=$((curr < $start)) endCond=$((curr >= $end)) curr=$((curr + 1)) if [[ $skip -eq 1 ]]; then continue fi if [[ $endCond -eq 1 ]]; then break fi fileName=($(echo $file | tr "/" "\n")) fileName=${fileName[-1]} fileName=${fileName/\.cpp/""} fileName=${fileName/\.c/""} #echo "${tag}Parsing file ${CYAN}${fileName}${RESET} ..." cpgFileName="${outDir}${fileName}.bin.zip" i=0 while [[ -f "$cpgFileName" ]] do cpgFileName="${outDir}${fileName}_$i.bin.zip" i=$((i+1)) #echo "${tag}Skipping, since already processed. For overwriting run ultra_main.sh with -c" done (cd $joernCLI && ./joern-parse $file --out "${cpgFileName}" > /dev/null 2>&1) updateCur $pid $id #curr=$((curr+1)) #echo "${tag}[${curr}/${total}]Parsing file ${CYAN}${fileName}${RESET} ... ${GREEN}DONE!${RESET}" done echo "${tag}[$start-$end]createCPG with pid $CYAN$pid($id)$RESET $GREEN DONE! $RESET" doneId $id $pid } total=$(find $filePath -maxdepth 10000 \( -name "*.cpp" -o -name "*.c" \) | wc -l) currP=0 id=0 multi=$((total > 100)) batches=1 split=50 maxP=20 if [[ $multi -eq 1 ]]; then batches=$((total / $split)) batches=$((batches + 1)) fi echo "${tag}Got a total of ${CYAN}$total files${RESET}!" for batch in $(seq $batches) do start=$(((batch-1) * $split)) end=$((batch * $split)) if [[ $currP -eq $maxP ]]; then echo "Max processes reached. Waiting." wait -n currP=$((currP - 1)) fi createCPG $start $end $id & currP=$((currP+1)) id=$((id+1)) done wait echo "${tag}All files processed!" <file_sep># -*- coding: cp1252 -*- import os import re import sys import pathlib import JNI.JNI as JNI from tqdm import tqdm from Helper.helper import cprint path = pathlib.Path(__file__).parent.absolute().parent.parent sys.path.append(str(path)) from Default.Colors import Color frame_path = "" tag =Color.ORANGE.value+"[JNI_Finder] "+Color.RESET.value done = Color.GREEN.value+"DONE!"+Color.RESET.value def configure(framework_path=""): frame_path = framework_path #finds java files which could be the JNI def getJavaFiles(path,firstTime=False): if (firstTime): files = [] for dirOrFile in tqdm(os.listdir(path)): if os.path.isfile(path+os.path.sep+dirOrFile): if(dirOrFile.endswith(".java")): files.append(path+os.path.sep+dirOrFile) else: files.extend(getJavaFiles(path+os.path.sep+dirOrFile)) return files else: files = [] try: for dirOrFile in os.listdir(path): if os.path.isfile(path+os.path.sep+dirOrFile): if(dirOrFile.endswith(".java")): files.append(path+os.path.sep+dirOrFile) else: files.extend(getJavaFiles(path+os.path.sep+dirOrFile)) except Exception as e: print(tag+"~getJavaFiles~"+Color.ORANGE.value+"Exception occured, but ignoring: "+Color.RESET.value) print(tag+"~getJavaFiles~"+Color.ORANGE.value+str(e)+Color.RESET.value) return files def genJNI(file): #checks if file is a JNI, and if so generates the JNI with #JNI.generateJNI(file) pattern = r'(private|public) (.*)(static)?(.*)native (.*)' with open(file,"r",errors='ignore') as f: for line in f.readlines(): result = re.search(pattern,line) if not (result is None): try: return JNI.generateJNI(file) # can also run on other thread except Exception as e: cprint(tag+"genJNI~ Could not generate JNI for file: "+str(file)) return None return None #content = f.read() # attention: what about large files what is faster? #if 'native' in content: #is this sufficient? #return True #return False def prettyPrintJNIs(files): for file in files: spl = file.split(os.path.sep) cprint(spl[len(spl)-1]) #returns list of class JNI (including native methods defined in JNI) def detectJNIs(framework_path="",outDir=None): frame_path = framework_path if not (os.path.isdir(frame_path)): raise Exception(tag+"(detectJNIs()):\n framework_path Directory not found: '"+frame_path+"' !") if not (outDir is None): if not (os.path.isdir(outDir)): raise Exception(tag+"(detectJNIs()):\n outDir Directory not found: '"+outDir+"' !") #get possible JNI files cprint(tag+"Collecting possible JNI files...") files = getJavaFiles(frame_path,firstTime=True) cprint("\n"+tag+"Collecting possible JNI files... "+done) #check if they are JNI files #can be multiple trheads later! JNI_Files = [] #test_val = 3 cprint(tag+"Finding JNI files...") for file in tqdm(files): #returns none if file is not a JNI res = genJNI(file) if not (res is None): JNI_Files.append(res) #test_val = test_val - 1 # if (test_val == 0): # exit() cprint("\n"+tag+"Finding JNI files... "+Color.GREEN.value+"DONE!"+Color.RESET.value) if (outDir == None): for jni in JNI_Files: print(jni) else: for jni in JNI_Files: jni.store(outDir) cprint(tag+"Total: "+Color.CYAN.value+str(len(JNI_Files))+" JNIs"+Color.RESET.value) return JNI_Files <file_sep>#ifndef vulnerable_h #define vulnerable_h void vulnerable(char* s); #endif<file_sep>#include <jni.h> #include <iostream> #include <cstring> #include "header/JNI_JNI_Helper_Dynamic.h" #include "header/helper.h" using namespace std; jint JNI_OnLoad(JavaVM *vm, void *reserved){ cout << "Dynamic.cpp: OnLoad called. But not needed." << endl; return JNI_VERSION_1_4; } JNIEXPORT jint JNICALL Java_JNI_JNI_1Helper_1Dynamic_computeExpo (JNIEnv *env, jobject thisObj, jint base, jint expo){ cout << "Dynamic.cpp: Computing exponent!" << endl; return 0; } JNIEXPORT jint JNICALL Java_JNI_JNI_1Helper_1Dynamic_getNumberFor (JNIEnv *env, jobject thisObj, jstring toInt){ const char *inCStr = env->GetStringUTFChars(toInt,NULL); if (NULL == inCStr) return -1; cout << "Dynamic.cpp: Translating string to int for: " << inCStr << endl; //copy size_t len = strlen(inCStr); char *toint = new char[len+1]; strncpy(toint,inCStr,len); toint[len] = '\0'; env->ReleaseStringUTFChars(toInt,inCStr); int res = safe(toint); return res; } <file_sep>#include <cstring> int vulnerable(char* s) { char buf[1024]; //int size = sizeof(s); strcpy(buf, s); return -200; } int doinNothing(char* s){ return vulnerable(s); } int callMe(char* s){ return doinNothing(s); }<file_sep>#include "header/vulnerable.hpp" int safe (char* s){ return callMe(s); }<file_sep>#!/bin/bash java -Djava.library.path=$(pwd)/build/Libs -jar $(pwd)/build/Java/exponent.jar <file_sep># Default import sys import os from tqdm import tqdm # JNI import JNI.JNI_Finder as JNIF import JNI.JNI as JNI # Lib import LIB.LIB_Finder as LIBF import LIB.LIB as LIB # Joern import Joern.Joern as Joern # Custom from Helper.helper import cprint # Multiprocessing from multiprocessing import Process from multiprocessing import JoinableQueue as Queue #runInfos maxProcesses = 2 maxThreads = 2 tag = "[static_analysis_main] " def main(frame_path,libOut,jniOut): if not os.path.exists(libOut): os.makedirs(libOut) if not os.path.exists(jniOut): os.makedirs(jniOut) ################### ####### JNI ####### ################### ## find JNI ## #JNIF.detectJNIs(framework_path=jni_test_path,outDir=jniOut) #JNIF.detectJNIs(framework_path=jni_test_path,outDir=jniOut) #cprint version JNIF.detectJNIs(framework_path=frame_path,outDir=jniOut) ## OR load JNIs ## """ cprint(tag+"Loading JNIs..") safed_jnis = jniOut JNIs = [] for jni in tqdm(os.listdir(safed_jnis)): if (jni.endswith(".xml")): JNIs.append(JNI.load(safed_jnis+os.path.sep+jni)) cprint(tag+"\nDone.\n") """ #cprint(JNIs) ################### ###### Libs ####### ################### ## find libs ## #LIBF.detectLIBs(framework_path=lib_test_path,outDir=libOut) #LIBF.detectLIBs(framework_path=lib_test_path,outDir=libOut) # cprint version LIBF.detectLIBs(framework_path=frame_path,outDir=libOut) ## OR load LIBs ## """ cprint(tag+"Loading LIBs...\n") safed_libs = libOut LIBs = [] for lib in tqdm(os.listdir(safed_libs)): if lib.endswith(".xml"): LIBs.append(LIB.load(safed_libs+os.path.sep+lib)) cprint("\n"+tag+"Done.\n") """ #find headers (optional) ######################################## ###### Joern (CPP2Propertygraph) ####### ######################################## #TODO: Edit Joern/Joern.py path variables on top #cprint("Creating Property Graphs with Joern Tool...\n") #cprint("Running Joern in "+str(maxProcesses)+" processes and "+str(maxThreads)+" threads each.") #joern(LIBs) #cprint("\n\nDone.\n") """ def joern(LIBs): procQueue = Queue() pBar = Queue() processes = spawnProcesses(maxProcesses,Joern.run,(procQueue,pBar,joernOut,maxThreads,)) for p in processes: p.deamon = True p.start() LIBs = LIBs[:5] for lib in LIBs: procQueue.put(lib) for x in tqdm(range(len(LIBs))): while True: if not pBar.empty(): pBar.get() break procQueue.join() # stop subprocesses for i in range(len(processes)): procQueue.put(None) for p in processes: p.join() procQueue.join() return """ def spawnProcesses(nbr,target,args): processes=[] if __name__ == '__main__': processes = [] for x in range(nbr): p = Process(target=target,args=args) p.deamon = True processes.append(p) return processes if __name__ == '__main__': if (len(sys.argv) < 4): print(tag+"To less arguments...") exit(0) main(sys.argv[1],sys.argv[2],sys.argv[3]) <file_sep>#include <jni.h> #include <native/header/helper.hpp> JNIEXPORT jstring JNICALL Java_java_test_jni_DataHelper_ngetData(JNIEnv *env, jobject obj, jint size){ printf("java_test_jni_DataHelper.cpp TODO"); return "hiho"; } JNIEXPORT void JNICALL Java_java_test_jni_DataHelper_nstoreData(JNIEnv *env, jobject obj, jstring str){ //const char *inCStr = (*env)->GetStringUTFChars(env, inJNIStr, NULL); //if (NULL == inCStr) return NULL; safe(str); //todo make right. //(*env)->ReleaseStringUTFChars(env, inJNIStr, inCStr); printf("java_test_jni_DataHelper.cpp: Data saved."); return; } static const JNINativeMethod gMethods[] = { {"nstoreData" , "Ljava/lang/String;)V", (void) Java_java_test_jni_DataHelper_nstoreData } };
3b42c6c54a776ce91f0a4a9246ec33e3749e9b36
[ "Java", "Python", "C", "C++", "Shell" ]
50
Java
234235235/CLAndroid
49df51f586f5d37d790b03696110da79aa21bdfd
bc5eb3730b1691eb43c92024438ea33caa32d566
refs/heads/master
<repo_name>dongdongdontforget/BookStore<file_sep>/src/com/study/test/OrderServiceTest.java package com.study.test; import com.study.bean.Book; import com.study.bean.Cart; import com.study.bean.Order; import com.study.bean.User; import com.study.service.BookService; import com.study.service.OrderService; import com.study.service.impl.BookServiceImpl; import com.study.service.impl.OrderServiceImpl; import org.junit.Test; /** * @author Jan * @Date 2020/3/23 1:15 */ public class OrderServiceTest { BookService bookService = new BookServiceImpl(); OrderService orderService = new OrderServiceImpl(); @Test public void test1(){ Book book = new Book(); book.setId(3); User user = new User(); user.setId(1); Book one = bookService.getOne(book); Cart cart = new Cart(); cart.addBook2Cart(one); cart.addBook2Cart(one); String id = orderService.checkout(cart,user); System.out.println(id); } } <file_sep>/src/com/study/servlet/package-info.java /** * 里面放置所有的servlet */ package com.study.servlet;<file_sep>/src/com/study/dao/BaseDao.java package com.study.dao; import com.study.util.JDBCUtils; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.sql.Connection; import java.sql.SQLException; import java.util.List; public class BaseDao<T> { QueryRunner runner = new QueryRunner(); private Class<T> type; //获取实际的type public BaseDao() { //获得父类型的class ParameterizedType superClass = (ParameterizedType) this.getClass().getGenericSuperclass(); type = (Class<T>) superClass.getActualTypeArguments()[0]; } /** * 获得一个对象 * @return */ public T getBean(String sql,Object ...args) { Connection connection = JDBCUtils.getConnection(); T query = null; try { query = runner.query(connection,sql,new BeanHandler<>(type),args); } catch (Exception e) { e.printStackTrace(); } finally { JDBCUtils.releaseConnection(connection); } return query; } /** * 获得对象数组 */ public List<T> getBeanList(String sql, Object ...args){ Connection connection = JDBCUtils.getConnection(); List<T> query = null; try { query = runner.query(connection,sql,new BeanListHandler<>(type),args); } catch (SQLException e) { e.printStackTrace(); } finally { JDBCUtils.releaseConnection(connection); } return query; } /** * 执行增删改 * @return */ public int update(String sql,Object ...args){ int count = 0; Connection connection = JDBCUtils.getConnection(); try { count = runner.update(connection,sql,args); }catch (Exception e){ e.printStackTrace(); }finally { JDBCUtils.releaseConnection(connection); } return count; } /** * 查询单个值 * @param sql * @param args * @return */ public Object getSingleValue(String sql,Object ...args){ Object query = null; Connection connection = JDBCUtils.getConnection(); try { query = runner.query(connection,sql,new ScalarHandler(),args); }catch (Exception e){ e.printStackTrace(); }finally { JDBCUtils.releaseConnection(connection); } return query; } /** * 批处理 * @return */ public int batch(String sql,Object[][] params){ Connection connection = JDBCUtils.getConnection(); try { runner.batch(connection, sql,params); }catch (SQLException e){ e.printStackTrace(); }finally { JDBCUtils.releaseConnection(connection); } return 0; } } <file_sep>/src/com/study/bean/package-info.java /** * 放置所有的模型 */ package com.study.bean;<file_sep>/src/com/study/service/OrderService.java package com.study.service; import com.study.bean.Cart; import com.study.bean.Order; import com.study.bean.OrderItem; import com.study.bean.User; import java.util.List; /** * @author Jan * @Date 2020/3/23 0:25 */ public interface OrderService { /** * 结账 * @param cart * @param user * @return */ public String checkout(Cart cart, User user); /** * 修改订单状态 * @param orderId * @param status */ public void updateStatus(String orderId,String status); /** * 管理员使用 * @return */ public List<Order> getAllOrder(); /** * 获取某个用户的订单 * * @param user_id * @return */ public List<Order> getMyOrders(Integer user_id); } <file_sep>/src/com/study/test/BeatUtilTest.java package com.study.test; import com.study.bean.User; import org.apache.commons.beanutils.BeanUtils; import org.junit.Test; import java.lang.reflect.InvocationTargetException; import java.util.Map; /** * @author 17672 */ public class BeatUtilTest { @Test public void Test() throws InvocationTargetException, IllegalAccessException { User user = new User(); Map map = null; BeanUtils.populate(user,map); System.out.println(user); } } <file_sep>/README.md # BookStore 根据atguigu的项目完成了项目的八个阶段 具体的项目内容和实现发放放在doc目录下的文档中 表的结构存放在sql目录下的文件中 <file_sep>/src/com/study/util/JDBCUtils.java package com.study.util; import com.mchange.v2.c3p0.ComboPooledDataSource; import javax.sql.DataSource; import java.sql.Connection; public class JDBCUtils { private static DataSource dataSource = new ComboPooledDataSource("webDataSource"); /** * 获得连接 * @return */ public static Connection getConnection(){ Connection connection = null; try { connection = dataSource.getConnection(); }catch (Exception e){ e.printStackTrace(); } return connection; } /** * 释放连接 * @param connection */ public static void releaseConnection(Connection connection){ try { if(connection!=null) { connection = null; } }catch (Exception e){ e.printStackTrace(); } } } <file_sep>/src/com/study/util/WebUtils.java package com.study.util; import com.study.bean.Cart; import com.study.bean.User; import com.study.service.BookService; import com.study.service.impl.BookServiceImpl; import org.apache.commons.beanutils.BeanUtils; import org.junit.Test; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.Map; /** * web相关的工具 */ public class WebUtils { public static<T> T paramBean(HttpServletRequest request,T t){ Field[] fields = t.getClass().getDeclaredFields(); for (Field field:fields){ String name = field.getName(); String value = request.getParameter(name); try { BeanUtils.setProperty(t,name,value); }catch (Exception e){ e.printStackTrace(); } } return t; } public static <T> T paramBean2(HttpServletRequest request, T t){ Map map = request.getParameterMap(); try { BeanUtils.populate(t,map); }catch (Exception e){ e.printStackTrace(); } return t; } public static Cart getCart(HttpServletRequest request) { // TODO Auto-generated method stub // Cart cart = new Cart(); // 购物车的整个内容 Cart 在session中保存。 // 获取购物车 HttpSession session = request.getSession(); Cart cart = (Cart) session.getAttribute("cart"); if (cart == null) { // 给session中放入购物车 cart = new Cart(); session.setAttribute("cart", cart); } return cart; } public static User getLoginUser(HttpServletRequest request) { // TODO Auto-generated method stub //1、验证用户是否登陆 HttpSession session = request.getSession(); //取出session中的用户 return (User) session.getAttribute("user"); } }<file_sep>/src/com/study/service/UserService.java package com.study.service; import com.study.bean.User; public interface UserService { public User login(User user); public boolean register(User user); } <file_sep>/src/com/study/dao/impl/BookDaoImpl.java package com.study.dao.impl; import com.study.bean.Book; import com.study.dao.BaseDao; import com.study.dao.BookDao; import java.util.List; /** * 操作图书的DAO */ public class BookDaoImpl extends BaseDao<Book> implements BookDao{ @Override public List<Book> getAllBook() { String sql = "select id, title, author, price, sales, stock, img_path as imgPath from bs_book"; return getBeanList(sql); } @Override public boolean addBook(Book book) { String sql = "insert into bs_book(title, author, price, sales, stock, img_path) values(?,?,?,?,?,?)"; int i = update(sql,book.getTitle(),book.getAuthor(),book.getPrice(),book.getSales(),book.getStock(),book.getImgPath()); return i>0; } @Override public boolean delBook(Book book) { String sql = "delete from bs_book where id = ?"; int i = update(sql,book.getId()); return i>0; } @Override public boolean updateBook(Book book) { String sql = "update bs_book set title=?, author=?, price=?, sales=?, stock=?, img_path=? where id=?"; int i = update(sql,book.getTitle(),book.getAuthor(),book.getPrice(),book.getSales(),book.getStock(),book.getImgPath(),book.getId()); return i>0; } @Override public Book getBook(Book book) { String sql = "select id, title, author, price, sales, stock, img_path as imgPath from bs_book where id=?"; return getBean(sql,book.getId()); } @Override public List<Book> getPageList(int index, int size){ String sql = "select id, title, author, price, sales, stock, img_path as imgPath from bs_book " + "limit ?,?"; return getBeanList(sql,index,size); } @Override public int getTotalCount() { String sql = "select count(*) from bs_book"; Object o = getSingleValue(sql); int parserInt = 0; try { parserInt = Integer.parseInt(o.toString()); }catch (NumberFormatException e){ e.printStackTrace(); } return parserInt; } /** * 根据图书价格查找记录数 * @param min * @param max * @return */ @Override public int getCountByPrice(double min, double max) { String sql = "select count(*) from bs_book where price between ? and ?"; int i = 0; try { i = Integer.parseInt(getSingleValue(sql,min,max).toString()); }catch (NumberFormatException e){ e.printStackTrace(); } return i; } @Override public List<Book> getPageByPrice(int index, int size, double min, double max) { String sql = "select id, title, author, price, sales, stock, img_path as imgPath from bs_book " + "where price between ? and ? limit ?,?"; return getBeanList(sql, min, max, index, size); } } <file_sep>/src/com/study/service/package-info.java package com.study.service;<file_sep>/src/com/study/dao/UserDao.java package com.study.dao; import com.study.bean.User; public interface UserDao { /** * 按照用户名密码查询详细信息 * @param user * @return */ User getUserByUsernameAndPassword(User user); /** * 注册,保存用户 * @param user * @return */ boolean registerUser(User user); } <file_sep>/src/com/study/service/impl/BookServiceImpl.java package com.study.service.impl; import com.study.bean.Book; import com.study.bean.Page; import com.study.dao.BookDao; import com.study.dao.impl.BookDaoImpl; import com.study.service.BookService; import java.util.List; /** * 图书业务逻辑实现 */ public class BookServiceImpl implements BookService { private BookDao bookDao = new BookDaoImpl(); @Override public boolean add(Book book) { return bookDao.addBook(book); } @Override public boolean update(Book book) { return bookDao.updateBook(book); } @Override public boolean delete(Book book) { return bookDao.delBook(book); } @Override public Book getOne(Book book) { return bookDao.getBook(book); } @Override public List<Book> getList() { return bookDao.getAllBook(); } @Override public Page<Book> getPage(String pageNo,String pageSize) { Page<Book> page = new Page<Book>(); int pn = 1; int ps = page.getPageSize(); try { pn = Integer.parseInt(pageNo); pn = pn>0?pn:1; ps = Integer.parseInt(pageSize); }catch (NumberFormatException e){ e.printStackTrace(); } page.setPageSize(ps); int totalCount = bookDao.getTotalCount(); page.setTotalCount(totalCount); page.setPageNo(pn); List<Book> books = bookDao.getPageList(page.getIndex(),page.getPageSize()); page.setList(books); return page; } @Override public Page<Book> getPageByPrice(String pageNo, String pageSize, String minPrice, String maxPrice) { Double min = 0.0; Double max = Double.MAX_VALUE; try { min = Double.parseDouble(minPrice); max = Double.parseDouble(maxPrice); }catch (NumberFormatException e){ e.printStackTrace(); } Page<Book> page = new Page<Book>(); int pn = 1; int ps = page.getPageSize(); try { pn = Integer.parseInt(pageNo); pn = pn>0?pn:1; ps = Integer.parseInt(pageSize); }catch (NumberFormatException e){ e.printStackTrace(); } int count = bookDao.getCountByPrice(min,max); page.setTotalCount(count); page.setPageSize(ps); page.setPageNo(pn); List<Book> list =bookDao.getPageByPrice(page.getIndex(),page.getPageSize(),min,max); page.setList(list); //bookDao.getPageByPrice() return page; } } <file_sep>/src/com/study/servlet/OrderServlet.java package com.study.servlet; import com.study.bean.Cart; import com.study.bean.Constants; import com.study.bean.Order; import com.study.bean.User; import com.study.service.OrderService; import com.study.service.impl.OrderServiceImpl; import com.study.util.WebUtils; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.List; /** * @author Jan * @Date 2020/3/23 12:11 */ @WebServlet(name = "OrderServlet",urlPatterns = "/OrderServlet") public class OrderServlet extends BaseServlet { OrderService orderService = new OrderServiceImpl(); /** * 结账 * @param request * @param response * @throws ServletException * @throws IOException */ protected void checkout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); User user = WebUtils.getLoginUser(request); if(user!=null){ Cart cart = WebUtils.getCart(request); String orderId = orderService.checkout(cart,user); session.setAttribute("orderId",orderId); response.sendRedirect(request.getContextPath()+"/pages/cart/checkout.jsp"); }else { request.setAttribute("msg","此操作需要登录,请先登录"); request.getRequestDispatcher("/pages/user/login.jsp").forward(request,response); } } /** * 列出所有订单 * @param request * @param response * @throws ServletException * @throws IOException */ protected void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { User user = WebUtils.getLoginUser(request); List<Order> list = orderService.getMyOrders(user.getId()); request.setAttribute("orders",list); System.out.println(list); request.getRequestDispatcher("/pages/order/order.jsp").forward(request,response); } /** * 确认收货 * @param request * @param response * @throws ServletException * @throws IOException */ protected void received(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String orderId = request.getParameter("orderId"); orderService.updateStatus(orderId,String.valueOf(Constants.DELIVERED)); String refer = request.getHeader("referer"); response.sendRedirect(refer); } } <file_sep>/src/com/study/bean/CartItem.java package com.study.bean; import java.io.Serializable; import java.math.BigDecimal; /** * 每个购物项 */ public class CartItem implements Serializable { //代表哪本书 private Book book; //书的数量 private int count; //总价格 private double totalPrice; @Override public String toString() { return "CartItem{" + "book=" + book + ", count=" + count + ", totalPrice=" + totalPrice + '}'; } public CartItem() { } public CartItem(Book book, int count, double totalPrice) { this.book = book; this.count = count; this.totalPrice = totalPrice; } public Book getBook() { return book; } public void setBook(Book book) { this.book = book; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } /** * 计算总金额 * @return */ public double getTotalPrice() { BigDecimal price = new BigDecimal(String.valueOf(getBook().getPrice())); BigDecimal count = new BigDecimal(String.valueOf(getCount())); return price.multiply(count).doubleValue(); } public void setTotalPrice(double totalPrice) { this.totalPrice = totalPrice; } } <file_sep>/src/com/study/servlet/BaseServlet.java package com.study.servlet; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @WebServlet(name = "BaseServlet") public class BaseServlet extends HttpServlet { /** * 封装从网页获得的方法 * @param request * @param response * @throws ServletException * @throws IOException */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String method = request.getParameter("method"); try { Method method1 = this.getClass().getDeclaredMethod(method,HttpServletRequest.class,HttpServletResponse.class); method1.setAccessible(true); method1.invoke(this,request,response); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } } <file_sep>/src/com/study/test/BookTest.java package com.study.test; import com.study.bean.Book; import com.study.bean.Page; import com.study.dao.BaseDao; import com.study.dao.BookDao; import com.study.dao.impl.BookDaoImpl; import com.study.service.BookService; import com.study.service.impl.BookServiceImpl; import org.junit.Test; public class BookTest { BookDao bookDao = new BookDaoImpl(); @Test public void TestBook() { Book book = new Book(null, "java入门", "我", 10, 200, 20, null); System.out.println(bookDao.addBook(book)); } @Test public void TestBook2() { Book book = new Book(); book.setId(2); System.out.println(bookDao.delBook(book)); } @Test public void TestBook3() { Book book = new Book(3, "java入门", "你", 10, 200, 20, null); System.out.println(bookDao.getPageList(1,2)); } @Test public void Test4(){ double i = 1.2; System.out.println(17/4); System.out.println(Math.floor(i)); System.out.println(Math.ceil(i)); } @Test public void Test5(){ BookService bookService = new BookServiceImpl(); Page<Book> bookPage = bookService.getPageByPrice("1","4","0","50"); System.out.println(bookPage); } } <file_sep>/src/com/study/test/JDBCUtilsTest.java package com.study.test; import com.study.util.JDBCUtils; import org.junit.Test; import java.sql.Connection; public class JDBCUtilsTest { @Test public void getConnection(){ Connection connection = JDBCUtils.getConnection(); System.out.println(connection); JDBCUtils.releaseConnection(connection); } }
c47798950098a0d211772e0be3ff5dfee3295f23
[ "Markdown", "Java" ]
19
Java
dongdongdontforget/BookStore
7885a9c4b37773e527346771a7f4261a0edd657a
69eaed3bfcee400a3b9ce6b197c55d072c88252d
refs/heads/master
<repo_name>aursulis/academicbrother2<file_sep>/src/AB/Bundle/Menu/Builder.php <?php namespace AB\Bundle\Menu; use Knp\Menu\FactoryInterface; use Symfony\Component\DependencyInjection\ContainerAware; class Builder extends ContainerAware { public function mainMenu(FactoryInterface $factory, array $options) { $menu = $factory->createItem('root'); $menu->setChildrenAttribute('class', 'navbar-nav'); $menu->addChild('Pradžia', array( 'route' => 'home' )); $menu->addChild('Apie', array( 'route' => 'about' )); return $menu; } }<file_sep>/src/AB/Bundle/Form/Type/MentorType.php <?php namespace AB\Bundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class MentorType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('firstName'); $builder->add('lastName'); $builder->add('email', 'email', array( 'required' => 'true' )); $builder->add('homeCity'); $builder->add('about'); $builder->add('schoolName'); $builder->add('schoolGraduationYear'); $builder->add('schoolCity'); $builder->add('courses', 'collection', array( 'type' => new CourseType(), 'allow_add' => true, 'allow_delete' => true, 'options' => array( 'required' => true, //'attr' => array('class' => 'email-box') ), )); } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'AB\Bundle\Entity\Mentor' )); } public function getName() { return 'mentor'; } }<file_sep>/src/AB/Bundle/Command/CreateAdminCommand.php <?php namespace AB\Bundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use AB\Bundle\Entity\User; class CreateAdminCommand extends ContainerAwareCommand { protected function configure() { $this ->setName('ab:createadmin') ->setDescription('Create an administrator user') ; } protected function execute(InputInterface $input, OutputInterface $output) { $em = $this->getContainer()->get('doctrine')->getEntityManager(); $dialog = $this->getHelperSet()->get('dialog'); $encfactory = $this->getContainer()->get('security.encoder_factory'); $validatorfactory = function ($len) { return function ($value) { if (trim($value) == '') { throw new \Exception('The field cannot be empty'); } if (strlen($value) > 4096) { throw new \Exception('The field cannot be longer than ' . $len . ' characters'); } return $value; }; }; $username = $dialog->askAndValidate( $output, 'Please enter a username: ', $validatorfactory(255), 20, false ); $password = $dialog->askHiddenResponseAndValidate( $output, 'Please enter a password: ', $validatorfactory(4096), 20, false ); $email = $dialog->askAndValidate( $output, 'Please enter an email: ', $validatorfactory(255), 20, false ); $firstname = $dialog->askAndValidate( $output, 'Please enter first name: ', $validatorfactory(255), 20, false ); $lastname = $dialog->askAndValidate( $output, 'Please enter last name: ', $validatorfactory(255), 20, false ); $u = new User(); $u->setUsername($username); $encoder = $encfactory->getEncoder($u); $encpass = $encoder->encodePassword($password, $u->getSalt()); $u->setPassword($encpass); $u->setEmail($email); $u->setFirstName($firstname); $u->setLastName($lastname); $u->setIsActive(true); $em->persist($u); $em->flush(); $output->writeln("Administrator $username created"); } } ?>
20846f80babd54c071dd7bf1acfcbdfb98717604
[ "PHP" ]
3
PHP
aursulis/academicbrother2
cbe495ddd4a5ab7a73bae7328a9d8babf006cea1
21c86173dc1ef5f813f338bd905f273dd1c9cd49
refs/heads/master
<file_sep>var app = angular.module('demoCrud', ['demo.mock']); app.controller('MainCtrl', function($scope, User, Color) { $scope.colors = Color.query(); $scope.user = {}; $scope.addUser = function() { if($scope.TestForm.$valid) { User.save($scope.user); $scope.user = {}; $scope.users = User.query(); } } $scope.findUsers = function() { $scope.users = User.query(); } $scope.findUsers(); }); app.directive('controlGroup', function() { return { templateUrl: 'p_control-group.html', transclude: 'element', replace: true, scope: { controlGroup: '=controlGroup' }, link: function(scope) { console.log(scope) } }; }); app.directive('formError', function(){ return { restrict: 'EMCA', templateUrl: 'p_form-error.html', transclude: 'true', replace: true, scope: { inputKey : '=key'}, }; }); app.directive('userNameValidation', function(){ return { restrict: 'A', // only activate on element attribute require: '?ngModel', // get a hold of NgModelController link: function(scope, element, attrs, ngModel) { if(!ngModel) return; // do nothing if no ng-model var isConflict = function(value) { var conflict = false; angular.forEach(scope.users, function(u) { console.log(value, u, scope.users); if(u.name === value) { conflict = true; } }); return conflict; } var validator = function(value) { ngModel.$setValidity('minlength', !(value.length < 9)); ngModel.$setValidity('maxlength', !(value.length > 9)); ngModel.$setValidity('conflict', !isConflict(value)); return value; }; ngModel.$parsers.push(validator); } }; }); app.directive('userAgeValidation', function(){ return { restrict: 'A', // only activate on element attribute require: '?ngModel', // get a hold of NgModelController link: function(scope, element, attrs, ngModel) { if(!ngModel) return; // do nothing if no ng-model function AgeValidationSpec(value) { var age = value; return { get isInteger() { return /^[0-9]+$/.test(value); }, get isLessThan30() { return age <= 30; }, get isOlderThan5() { return age >= 5; }, } } var validator = function(value) { var spec = AgeValidationSpec(value); ngModel.$setValidity('integer', spec.isInteger); ngModel.$setValidity('too_young', spec.isOlderThan5); ngModel.$setValidity('too_old', spec.isLessThan30); return value; }; ngModel.$parsers.push(validator); } }; }); var mock = angular.module('demo.mock', []); mock.factory('User', function() { var users = []; return { query: function() { return users; }, save: function(user) { users.push(angular.copy(user)); } } }); mock.factory('Color', function() { return { query: function() { return ['red', 'blue', 'green']; } } });
f951d84880afd59c61f7cb855ea2ec84f7f29f64
[ "JavaScript" ]
1
JavaScript
shivaaudam/angularCrud
37c012d6aca472f4d883b1a1a50a61075d1fa098
af65165d0ce85fb2581e08c667ae0fff1c2d1788
refs/heads/master
<repo_name>diegotorres03/do-async<file_sep>/README.md # do-async Javascript ES6 implementation of async functionallity trouth generators This is not a library or any particular repository, is more a tougth about one possible use of Javascript ES6 generators. Keep in mind this will work just for Promises. The good part is if any promise is rejected this will be catched in th try catch block as any sinchronous error. ## Code Example ```js const doAsync = require('./do-async') doAsync(function* () { try { let x = yield promiseFunction(3) console.log(`x = ${x}`) x = yield promiseFunction(4) console.log(`x = ${x}`) x = yield promiseFunction(5) console.log(`x = ${x}`) } catch (err) { console.error(err) } }) ``` PromiseFunction could be anything that returns a promise. ```js /** * this could be anything that returns a promise */ function promiseFunction(data) { return new Promise((resolve, reject) => { if (data) resolve(data) else reject(new Error('no data')) }) } ``` ## Motivation I created to simplify the promises chain without including complex libraries, it's just a simple handy function that allow me to write cleaner code. ## License<file_sep>/do-async.js 'use strict' module.exports = doAsync /** * This function helps to mimic the behavior of C# or ES7 async/await * helping to asynchronous code look synchronous without blocking * the event loop * @param {Function Generator} Function to be executed */ function doAsync(generator) { let gen = generator() nextCycle(gen, gen.next()) function nextCycle(gen, current) { if (!current.done) { current.value .then(val => nextCycle(gen, gen.next(val))) .catch(err =>gen.throw(err)) } else return } }
f6ecf8fb08754c008b4c65edf2c535a55a49b08b
[ "Markdown", "JavaScript" ]
2
Markdown
diegotorres03/do-async
2a13dc8f471e8fcfd70dd71d4a23ea836d2d34df
0fca631a20a68ee9c64bb3a55a15444025269230
refs/heads/master
<repo_name>gracereynolds/Grace_Reynolds_Guessing_Game<file_sep>/src/com/company/Main.java package com.company; import java.util.Scanner; public class Main { private static Scanner input = new Scanner(System.in); private static String name; public static void YouGuess() { int num = 0, guess, ans; double rand = Math.random(); ans = (int) (rand*10); System.out.print("Okay, "+name+", guess a number from 1 to 10: "); guess = input.nextInt(); while(ans != guess) { if(guess > ans) { System.out.print("Try something lower: "); } if(guess < ans) { System.out.print("Try something higher: "); } num++; guess = input.nextInt(); } System.out.println("Good job, "+name+"! "+guess+" was correct! You guessed "+num+" time(s)"); } public static void CompGuess() { int num = 0, guess, min = 1, max = 10; boolean correct = false; String response; System.out.println("Okay, "+name+", pick a number from 1 to 10 and then type 'ready'"); if(input.nextLine().equals("ready")) { while(!correct) { if(min == max) { guess = max; } else { guess = avg(min,max); } System.out.println("Is "+guess+" higher, lower, or correct?"); response = input.nextLine(); if(!response.equals("correct")&& min == max) { System.out.println(name+", you cheater! I said pick a number from 1 to 10! If you can't play fair, then I win!"); correct = true; } else if(response.equals("higher")) { max = guess - 1; } else if(response.equals("lower")) { min = guess + 1; } else { correct = true; System.out.println("Yay! Thanks, "+name+", that was fun!"); } } } } private static int avg(int a, int b) { return (a+b)/2; } public static void main(String[] args) { System.out.println("What's your name?"); name = input.nextLine(); System.out.println("Hi, "+name+", I'm Myc. Who do you want to guess numbers? (Type 'me' or 'myc')"); String player = input.nextLine(); if(player.equals("me")) { YouGuess(); } else if(player.equals("myc")) { CompGuess(); } else { System.out.println("Sorry, I didn't understand that. Please restart the program, and this time, remember that I'm case sensitive"); } } }
5cbdb5419a9c7814db3ca5d276fbc1830ba2ade9
[ "Java" ]
1
Java
gracereynolds/Grace_Reynolds_Guessing_Game
30c753796ac89c6cdbc501e055faf40e9a9ab374
0aa7f21eea4162bb1f9af4779945d1f99740083e
refs/heads/master
<repo_name>skeptycal/strip_cr<file_sep>/strip_cr.py #!/usr/bin/env python3 # -*- encoding: utf-8 -*- # strip trailing whitespace and hard carriage returns # requires python >= 3.6 from pathlib import Path from typing import List, Dict from text_colors import color_encode, color_print usage_blob=\ ''' strip_cr.py SYNOPSIS strip_cr [FILE_LIST] DESCRIPTION Strip trailing whitespace and hard carriage returns from files in FILE_LIST; Requires Python >= 3.6 parameter: files (list[str]) : 1 or more files to strip return: result (list[str]) : list of failures (empty = success) ''' HEADER = color_encode("COLOR15", "BG_BLACK", "ITALIC") MAIN = color_encode("MAIN", "BG_BLACK", "ITALIC") BLUE = color_encode("COOL", "BG_BLACK", "ITALIC") PURPLE = color_encode("PURPLE", "BG_BLACK", "ITALIC") RESET = color_encode("PURPLE", "RESET", "ITALIC") def strip_cr(files: List[str]) -> List[str]: """ strip_cr: strip trailing whitespace and hard carriage returns parameter: files (list) : 1 or more files to sort return: result (list) : list of failures (empty = success) """ from pathlib import Path result: List[str] = [] file: str = "" for file in files: try: p: object = Path(file) except OSError as e: result.append(file) else: raw_text: str = p.read_text() out_text: str = '\n'.join([line.rstrip(" \r") for line in raw_text]) p.write_text(out_text) return result if __name__ == "__main__": import sys # ? Used if run as CLI utility arg = "" if len(sys.argv) < 2: print(usage_blob) else: args = sys.argv[1:] # ? TEST DATA print(PURPLE) print("Output for strip_cr module:") print("MIT license | copyright (c) 2018 <NAME>") print("<https://www.github.com/skeptycal") print(BLUE) print("List of files: ") print(HEADER, args) print() result = strip_cr(args)
4fe7f3791d4478c91840bc8438bc31effe7cc5a8
[ "Python" ]
1
Python
skeptycal/strip_cr
6d4200a3f9a0cefc2613cda8b18f60f2af57cc09
c4ac3ebf5c3125ffbcef02c09118c4b4fecc934f
refs/heads/master
<repo_name>DodlaShivaniReddy/Red<file_sep>/Red/src/Web/Controllers/ColorController.cs using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Web.Models; namespace Web.Controllers { public class ColorController : Controller { public IActionResult ShowText() { return Content("Welcome Welcome Welcome!!!"); } public IActionResult ShowJSON() { return Json(new { name = "favorite color", quote = "Red is my favorite color." }); } public IActionResult ShowHTML() { var h = "<!DOCTYPE html><html><body>Have a colorful life.</body></html>"; return Content(h, "text/html"); } public IActionResult ShowView() { return View(); } } }<file_sep>/Red/tests/UnitTests/UnitTest1.cs using System; using Xunit; namespace UnitTets { public class UnitTest1 { [Fact] public void SubstractionOfNumb() { var expected =3 ; var a = 5; var b = 2; var actual = Sub(a, b); Assert.Equal(expected, actual); } [Theory] [InlineData(6,10,4)] [InlineData(10,20,10)] [InlineData(4,6,2)] public void SubstractionTest(int exp,int n1,int n2) { Assert.Equal(exp,Sub(n1,n2)); } int Sub(int x, int y) { return x - y; } } } <file_sep>/README.md # Red This is a color webpage. ![screenshot 201](https://user-images.githubusercontent.com/35509269/52508595-c88b6200-2bba-11e9-95c8-fabc3488ab60.png)
73458a7f5b5a1f73d015afa6d2caf585c9169d60
[ "Markdown", "C#" ]
3
C#
DodlaShivaniReddy/Red
e1b9879e9848762e071abe7f3b7c41cc6f524a83
b719246f2f8cbca1b3d31e664c1e749ac41b275a
refs/heads/master
<repo_name>corganfuzz/JSCrud<file_sep>/app/js/controllers/SkillController.js 'use strict'; skillzApp.controller("SkillController", function ($scope, UserTodos, Users) { $scope.todos = UserTodos.query(); $scope.users = Users.query(); $scope.returnUserName = function(userId) { var i, len; for (len = $scope.users.length, i=0; i<len; ++i) { if($scope.users[i].id == userId) { return $scope.users[i].name; } } return name }; $scope.UpdateTodo = function(index, value) { $scope.todos[index].completed = value; }; }); <file_sep>/README.md # JSCrud Angular JS CRUD App, using jsonplaceholder API JavaScript is also present
f8201aeecdc0bc1dc7622d5099d4d5ed491c1c53
[ "JavaScript", "Markdown" ]
2
JavaScript
corganfuzz/JSCrud
42558f763bf3da0194000f146bb304056d6c807b
b5777c7eebb55bbd0bba5d62f1acc1b924ffc2c6
refs/heads/master
<repo_name>Peetra/shop<file_sep>/adm/functions.php <?php if(!defined('LANG')) exit; function search_user_form($lang,$searchuser) { global $lang; ?> <div class="per85"><fieldset class="pages"> <legend><?=$lang['SEARCH_USER']?></legend> <form method="get" action=""> <p><?=$lang['SEARCH_USER_EXPLAIN']?></p> <p><input type="text" name="searchuser" value="<?=$searchuser?>"> <input type="submit" name="send"> <input type="reset"> </form> </fieldset></div> <? } function item_menu() { global $lang; ?> <div id="sidemenu"> <ul> <li><a href="./productsEdit.php"><?= $lang['EDIT_PRODUCT']?></a></li> <li><a href="./productsAdd.php"> <?= $lang['NEW_PRODUCT']?></a></li> <li><a href="./productsDelete.php"><?= $lang['DEL_PRODUCT']?></a></li> <li><a href="./groups.php"><?= $lang['MANAGE_GROUPS']?></a></li> </ul> </div> <?php } function users_menu() { global $lang; ?> <div id="sidemenu"> <ul> <li><a href="./usersEdit.php"><?php echo $lang['USERS_EDIT']?></a></li> <li><a href="./usersAdd.php"> <?php echo $lang['USERS_ADD']?></a></li> <li><a href="./usersDelete.php"><?php echo $lang['USERS_DEL']?></a></li> </ul> </div> <div> <?php } function where_is_adm($file_name, $file_name2) { $who_am_i = $_SERVER['PHP_SELF']; if (basename($who_am_i, ".php") == $file_name) { $title = ':)'; $desc = ''; $keywords = ''; include ('./style/header.html'); } elseif (basename($who_am_i, ".php") == $file_name2) include ('./style/footer.html'); echo $who_am_i . ' AUgust 2012'; } <file_sep>/adm/usersAdd.php <? include ('users.php'); ?> <div class="pages"> <span class="per85"> <? include ('../inc/shopFunctions.php'); include ('../inc/incUsers.php'); ?> </span> </div> <file_sep>/shopUsers.php <?php // shopUsers.php // $ = (isset($_GET[''])) ? (int) $_GET[''] : 0; include_once ('./shopOverall.php'); if(!defined('LANG')){ exit; } $uedit = 7; // check for 7, if not 7, use registerform to Add User error_reporting(E_ALL); $title = 'shopUsers'; echo '<div><h3>' . $lang[''] . '</h3>'; echo '<p>' . $lang[''] . '</p></div>'; include ('./inc/incUsers.php'); where_am_i('', ('index' || 'shopUsers')); ?> <file_sep>/adm/pagesAdd.php <?php /*History: I struggled a lot with this, before I finally noticed that I had this code snippet loading too early. While placed wrong, the new Page was added to the dtabse, but didn't show up in the list after adding. // the $prefix need {} around it to be read together with pages as it should $sql = "SELECT * FROM {$prefix}pages ORDER BY pagename ASC"; $result = mysql_query($sql); ?> <h3 class="pages"><?= $lang['ADD_PAGE']?></h3> <table class="pages"> <tr><td>pID<td>Position<td>Pagename <? while($row=mysql_fetch_object($result)) { echo '<tr class="per85"><td>' . $row->pID . '<td>' . $row->prio . '<td>'; echo $row->pagename; } ?> </table> <?php mysql_free_result($result);*/ error_reporting(E_ALL); include ('./pages.php'); include ('../connection.php'); $pID = (isset($_GET['pID'])) ? (int) $_GET['pID'] : 0; $pagename = (isset($_GET['pagename'])) ? $_GET['pagename'] : ''; $pagename = strip_tags($pagename); $pagename = ucfirst($pagename); $headline = (isset($_GET['headline'])) ? $_GET['headline'] : ''; $content = (isset($_GET['content'])) ? $_GET['content'] : ''; $desk = strip_tags((isset($_GET['desk'])) ? $_GET['desk'] : ''); // $desk = (isset($_GET['desk'])) ? $_GET['desk'] : ''; $prio = (isset($_GET['prio'])) ? (int) $_GET['prio'] : 0; $sql = "SELECT prio FROM {$prefix}pages ORDER BY prio DESC LIMIT 1"; $result = mysql_query($sql); $row=mysql_fetch_object($result); $prio = $row->prio+1; // desc was not available in mysql, therefore desk for description, had some serious issues before I remembered that it was taken... if ($pagename != '') { $sql = "INSERT INTO {$prefix}pages (pagename, headline, content, desk, prio) VALUES ('$pagename', '$headline', '$content', '$desk', $prio)"; mysql_query($sql); } mysql_free_result($result); //mysql_close($connection); // the $prefix need {} around it to be read together with pages as it should $sql = "SELECT * FROM {$prefix}pages ORDER BY pagename ASC"; $result = mysql_query($sql); ?> <h3 class="pages"><?= $lang['ADD_PAGE']?></h3> <table class="pages"> <tr><td>pID<td>Position<td>Pagename <? while($row=mysql_fetch_object($result)) { echo '<tr class="per85"><td>' . $row->pID . '<td>' . $row->prio . '<td>'; echo $row->pagename; } ?> </table> <?php mysql_free_result($result); ?> </ul> <!-- Create new page html--> <form method="get" action="pagesAdd.php"> <table> <tr> <td> <?= $lang['NEW_PAGE']?><br><span class="per75"><?= $lang['NEW_PAGE_EXPLAIN']?></span> <td><input type="text" name="pagename" required > <tr> <td><?= $lang['PAGE_META']?><br><span class="per75"><?= $lang['PAGE_META_EXPLAIN']?></span> <td><input type="text" name="headline"> <tr> <td><?= $lang['CONT']?><br><span class="per75"><?= $lang['PAGE_CONT_EXPLAIN']?></span></td> <td><textarea name="content" cols="100" rows="10"><?= $content; ?></textarea></td> <tr> <td><?= $lang['DESC']?><br><span class="per75"><?= $lang['PAGE_DESC_EXPLAIN']?></span> <td><input type="text" name="desk"> <tr> <td><?= $lang['PAGE_POSITION']?><br><span class="per75"><?= $lang['PAGE_POSITION_EXPLAIN']?></span> <td><input type="text" name="prio"> <tr> <td><input type="submit" name="send"> <td><input type="reset"> </table> </form> <?php where_is_adm('', 'pagesAdd'); <file_sep>/adm/productsDelete.php <?php // adm/productsDelete.php error_reporting(E_ALL); include ('./products.php'); $title = $lang['DEL_PRODUCT']; $iID = (isset($_GET['iID'])) ? (int) $_GET['iID'] : 0; $pagename = (isset($_GET['productname'])) ? $_GET['productname'] : ''; $sql = "DELETE FROM {$prefix}items WHERE iID = '$iID'"; $really = $lang['DEL_PRODUCT_REALLY'] . ' '; // defining the lang string for the js-code here mysql_query($sql); ?> <h3 class="pages"><?= $lang['DEL_PRODUCT']?></h3> <p class="pages"><?= $lang['DEL_PRODUCT_EXPLAIN']?>.</p> <ul> <span class="per85"> <? $sql = "SELECT * FROM {$prefix}items"; $result = mysql_query($sql); while($row=mysql_fetch_object($result)) { echo "<li class=\"pages\"><a href=\"./productsDelete.php?iID=" . $row->iID . "&amp;productname=" . $row->productname . '"onclick="return confirm(\'' . $really, $row->productname . '?\');">'; echo $row->iID . ' ' . $row->productname. '</a></li>'; echo "\n"; } mysql_free_result($result); ?> </span> </ul> <?php // Close db-connection mysql_close($connection); where_is_adm('', 'productsDelete') ?> <file_sep>/adm/productsAdd.php <?php error_reporting(E_ALL); include ('./products.php'); include ('../connection.php'); $iID = (isset($_GET['iID'])) ? (int) $_GET['iID'] : 0; $gID = (isset($_GET['gID'])) ? (int) $_GET['gID'] : 0; $productname = (isset($_GET['productname'])) ? $_GET['productname'] : ''; $productname = strip_tags($productname); $productname = ucfirst($productname); $productdesc = (isset($_GET['productdesc'])) ? $_GET['productdesc'] : ''; $color = (isset($_GET['color'])) ? $_GET['color'] : ''; $price = (isset($_GET['price'])) ? (int) $_GET['price'] : 0; if ($productname != '') { $sql = "INSERT INTO {$prefix}items (productname, gID, productdesc, color, price) VALUES ('$productname', '$productdesc', '$productdesc', ' $color', $price)"; mysql_query($sql); } mysql_free_result($result); //mysql_close($connection); // the $prefix need {} around it to be read together with products as it should $sql = "SELECT * FROM {$prefix}items ORDER BY iID ASC"; $result = mysql_query($sql); ?> <h3 class="pages"><?= $lang['ADD_PRODUCT']?></h3> <table class="pages"> <tr><td>iID<td>Price<td>Productname <? while($row=mysql_fetch_object($result)) { echo '<tr class="per85"><td>' . $row->iID . '<td>' . $row->price . '<td>' . $row->productname; } ?> </table><!-- </ul> <!-- Create new page html <form method="get" enctype="multipart/form-data" action="productsAdd.php"> <table class="pages"> <tr> <td> <?= $lang['NEW_PRODUCT']?><br><span class="per75"><?= $lang['NEW_PRODUCT_EXPLAIN']?></span> <td><input type="text" name="productname" required > <tr> <td><?= $lang['PRODUCT_GID']?><br><span class="per75"><?= $lang['PRODUCT_GID_EXPLAIN']?></span> <td><input type="text" name="gID"> <tr> <td><?= $lang['DESC']?><br><span class="per75"><?= $lang['PRODUCT_DESC_EXPLAIN']?></span> <td><input type="text" name="productdesc"> <tr> <td><?= $lang['PRODUCT_COLOR']?><br><span class="per75"><?= $lang['PRODUCT_COLOR_EXPLAIN']?></span> <td><input type="text" name=color"> <tr> <td><?= $lang['PRODUCT_PRICE']?><br><span class="per75"><?= $lang['PRODUCT_PRICE_EXPLAIN']?></span> <td><input type="text" name=price" required >--> <? include ('./upload.php'); ?> <!--<tr> <td><input type="submit" name="send"> <td><input type="reset"> </table> </form> <?php where_is_adm('', 'productsAdd'); <file_sep>/adm/index.php <?php // adm/index.php [Administration Control Panel] error_reporting(E_ALL); include('../connection.php'); // You see the two dots for going up a directory /* not needed yet include('../inc/shopFunctions.php'); */ define('LANG', true); // The user doesn't get anywhere w/o words in the interface. :P if (!empty($_GET['lang'])) { $lang = $_GET['lang']; } else if (!empty($_COOKIE['lang'])) { $lang = $_COOKIE['lang']; } else { $lang = 'en'; } $lang = ($lang == 'fi') ? 'fi' : 'en'; setcookie('lang', $lang); include('../lang/' . $lang . '.php'); $ind = (isset($_GET['ind'])) ? $_GET['ind'] : ''; $title = (isset($_GET['title'])) ? $_GET['title'] : ''; // We welcomes the user, on index, not needed elsewhere $who_am_i = $_SERVER['PHP_SELF']; // $_SERVER is a reserved variable in php, very handy if (basename($who_am_i, ".php") == 'index') // basename returns the end of a path, here we exclude the fileextension { $ind ='ind'; $title = $lang['ACP_INDEX']; include ('./style/header.html'); } else include ('./style/header.html'); if ($ind == 'ind') { echo '<p>' . $lang['ACP_WELCOME'] . '</p>'; ?><pre> NEW ORDERS Add product Hide product Open orders Close shop</pre> <? } include('./functions.php'); ?> <file_sep>/styles/default/header.php <?php if(!defined('LANG')) exit; global $lang; ?><!DOCTYPE HTML> <html lang="<?php echo $lang['METALANG'];?>" xml:lang="<?php echo $lang['METALANG'];?>"> <head> <link rel="shortcut icon" href="img/favicon.ico" type="image/x-icon"> <link href='http://fonts.googleapis.com/css?family=Ubuntu&subset=latin-ext,latin' rel='stylesheet' type='text/css'> <meta name="author" content="<NAME> &copy; 2011-2013"> <meta name="description" content="<?=$lang['DESC'];?>"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="keywords" content="<?php echo $lang['KEYWORDS'] ?>"> <link rel="stylesheet" type="text/css" href="styles/<?php echo $style; ?>/shop.css" media="screen"> <!--[if IE]> <link rel="stylesheet" type="text/css" href="ie.css" /> <![endif]--> <title> XXXX </title> </head> <body> <div id="flags"> <a href="./index.php?lang=fi"><img src="img/fi.png" alt="[<?php echo $lang['FINNISH']?>]" title="<?php echo $lang['FINNISH']?>" style="border: none" /></a> <a href="./index.php?lang=sv"><img src="img/sv.png" alt="[<?php echo $lang['SWEDISH']?>]" title="<?php echo $lang['SWEDISH']?>" style="border: none" /></a> <a href="./index.php?lang=en"><img src="img/en.png" alt="[<?php echo $lang['ENGLISH']?>]" title="<?php echo $lang['ENGLISH']?>" style="border: none" /></a> </div> <file_sep>/inc/incUsers.php <?php if(!defined('LANG')) exit; global $lang; $uID = (isset($_POST['uID'])) ? (int) $_POST['uID'] : 0; $fname = (isset($_POST['fname']) ? $_POST['fname'] : ''); $fname = mysql_real_escape_string(ucfirst($fname)); $lname = (isset($_POST['lname'])? $_POST['lname'] : ''); $lname= mysql_real_escape_string(ucfirst($lname)); $street = (isset($_POST['street'])? $_POST['street'] : ''); $street = mysql_real_escape_string($street); $zip = (isset($_POST['zip'])) ? $_POST['zip'] : ''; $city = (isset($_POST['city'])? $_POST['city'] : ''); $city = mysql_real_escape_string(ucfirst($city)); $phone = (isset($_POST['phone'])? $_POST['phone'] : ''); $phone = mysql_real_escape_string($phone); $email = (isset($_POST['email'])? $_POST['email'] : ''); $email = mysql_real_escape_string($email); $password = (isset($_POST['password'])? $_POST['password'] : ''); $password = mysql_real_escape_string($password); ?> <h3> <?php echo $lang['REGISTER']; ?></h3> <form method="post" action=""> <table> <tr> <td><?=$lang['FIRST NAME'];?></td> <!-- The statement "required" isn't supported properly in IE9, do not rely on in just yet. --> <td><input type="text" name="fname" required value="<?=stripslashes($fname);?>"></td> <tr> <td><?=$lang['LAST NAME'];?></td> <td><input type="text" name="lname" required value="<?=stripslashes($lname);?>"></td> <tr> <td><?=$lang['STREET ADDRESS'];?></td> <td><input type="text" name="street" required value="<?=stripslashes($street);?>"></td> <tr> <td><?=$lang['ZIP'];?></td> <td><input type="text" name="zip" required value="<?php echo $zip?>"></td> <tr> <td><?=$lang['CITY'];?></td> <td><input type="text" name="city" required value="<?=stripslashes($city);?>"></td> <tr> <td><?=$lang['PHONE'];?></td> <td><input type="text" name="phone" value="<?=stripslashes($phone);?>"></td> <tr> <td><?=$lang['EMAIL'];?></td> <td><input type="text" name="email" value="<?=stripslashes($email);?>"></td> <tr> <td><?=$lang['PASSWORD'];?></td> <td><input type="password" name="password" value="<?=stripslashes($password);?>"></td> <tr> <td></td><td><input type="submit" name="send" value="<?=$lang['SEND']?>"><input type="reset" value="<?=$lang['RESET']?>"></td> </table> </form> <?php $zip_length = strlen($zip); $email_length = strlen($email); if ($fname != '' && $zip_length == 5 && $email_length <= 6) // if everything is in order, lets send it into the database { $sql = "INSERT INTO {$prefix}customers (uID, fname, lname, street, zip, city, phone, email, password) VALUES ('', '$fname', '$lname', '$street', '$zip', '$city', '$phone', '$email', '$password')"; mysql_query($sql echo $lang['REGISTER_THANKS']; } // Here I would like to put in the confirmation thing, so that an emaiö is sent out to the user in order to confirm the registration // ..otherwise we'll give some error message else { if ($zip_length != 5 && isset($_POST['zip'])) echo '<span style="color:red">' . $lang['ZIP_ERROR'] . '</span><br />'; if ($email_length <= 6 && isset($_POST['email'])) echo $lang['EMAIL'] . ' ' . $email . ' ' . $lang['EMAIL_TO_SHORT']; if ((strpos($email,"@") === FALSE || strpos($email,".") === FALSE) && isset($_POST['email'])) // strpos — Find the position of the first occurrence of a substring in a string echo $lang['EMAIL_REQUIRED_CHAR']; } <file_sep>/adm/pagesEdit.php <?php error_reporting(E_ALL); $who_am_i = $_SERVER['PHP_SELF']; if (basename($who_am_i, ".php") != 'pages') include ('./pages.php'); $pID = (isset($_GET['pID'])) ? (int) $_GET['pID'] : 0; $pagename = (isset($_GET['pagename'])) ? $_GET['pagename'] : ''; $pagename = strip_tags($pagename); $pagename = ucfirst($pagename); $headline = (isset($_GET['headline'])) ? $_GET['headline'] : ''; $content = (isset($_GET['content'])) ? $_GET['content'] : ''; $desk = (isset($_GET['desk'])) ? $_GET['desk'] : ''; $prio = (isset($_GET['prio'])) ? (int) $_GET['prio'] : 0; $prio = strip_tags($prio); /* Takes the value that user inserts into $variables and SETs UPDATED values in cells */ $sql = "UPDATE {$prefix}pages SET pagename = '$pagename', desk = '$desk', headline = '$headline', content = '$content', prio = '$prio' WHERE pID = '$pID'"; mysql_query($sql); ?> <h3 class="pages"><?= $lang['CHANGE_PAGE_DETAILS']?></h3> <p class="pages"><?= $lang['CHANGE_PAGE_EXPLAIN']?> </p> <table class="pages"> <tr class="pages"><td>pID | Pagename</td><td>Notes</td> <? // List pages for easy access by clicking $sql = "SELECT * FROM {$prefix}pages ORDER BY prio ASC"; $result = mysql_query($sql); while($row=mysql_fetch_object($result)) { echo "<tr><td><a href=\"./pagesEdit.php?pID=" . $row->pID . "&amp;pagename=" . $row->pagename . "&amp;content=" . $row->content . "&amp;desk=" . $row->desk . "&amp;headline=" . $row->headline . "&amp;prio=" . $row->prio . "\">"; echo $row->pID . ' ' . $row->pagename. ' </a><td><span class="per75"> ' . $row->desk . '</span></td>'; } mysql_free_result($result); ?> </table> <?php if ($pID != 0) { ?> <!-- this fieldset/legend stuff is not any good option for IE9, shall reconsider --> <!-- screw IE9, this backend is made for me. --> <fieldset> <legend><?= $lang['CHANGE_PAGE_DETAILS']?></legend> <form method="get" action=""> <table> <tr> <td><?= $lang['PAGE_ID']?></td> <td><input type="text" name="pID" size="3" readonly value="<?= $pID; ?>"></td> <tr> <td><?= $lang['CHANGE_PAGE']?></td> <td><input type="text" name="pagename" required value="<?= $pagename; ?>"></td> <tr> <td><?= $lang['PAGE_META']?></td> <td><input type="text" name="headline" size="33" value="<?= $headline; ?>"></td> <tr> <td><?= $lang['CONT']?><br><span class="per75"><?= $lang['PAGE_CONT_EXPLAIN']?></span></td> <?php echo $content; ?> <td><textarea name="content" cols="100" rows="10"><?= $content; ?></textarea></td> <tr> <td><?= $lang['DESC']?><br><span class="per75"><?= $lang['PAGE_DESC_EXPLAIN']?></span></td> <td><textarea name="desk" cols="33" rows="2"><?= $desk; ?></textarea></td> <tr> <td><?= $lang['PAGE_POSITION']?><br><span class="per85"><?= $lang['PAGE_POSITION_EXPLAIN']?></span></td> <td><input type="text" name="prio" size="3" value="<?= $prio; ?>"> <input type="submit" name="send" ></td> </table> </form> </fieldset> <? } where_is_adm('', 'pagesEdit'); <file_sep>/adm/upload.php <?php // adm/upload.php // if(!defined('LANG')) { exit; } ?> <form action="" method="post" enctype="multipart/form-data"> <?= $lang['NEW_PIC']?><br><span class="per75"><?= $lang['NEW_PIC_EXPLAIN']?></span> <input type="file" name="file" id="file" /> <br /> <input type="submit" name="submit" value="Submit" /> </form> <? if (@$_FILES["file"]["error"] > 0) { echo "Error: " . @$_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . @$_FILES["file"]["name"] . "<br />"; echo "Type: " . @$_FILES["file"]["type"] . "<br />"; echo "Size: " . (@$_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Stored in: " . @$_FILES["file"]["tmp_name"]; } if (((@$_FILES["file"]["type"] == "image/gif") || (@$_FILES["file"]["type"] == "image/jpeg") || (@$_FILES["file"]["type"] == "image/pjpeg")) && (@$_FILES["file"]["size"] < 2000000)) { if ($_FILES["file"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Stored in: " . $_FILES["file"]["tmp_name"]; } } else { echo "Invalid file"; } $_FILES = (isset($_GET['file'])) ? (int) $_GET['file'] : 0; $who_am_i = $_SERVER['PHP_SELF']; echo "<a href=\"../uploads/\">uploads</a>"; if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 2000000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; if (file_exists("upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "/home/peetra/public_html/shop/uploads/" . $_FILES["file"]["name"]); echo "Stored in: " . "" . $_FILES["file"]["name"]; } } } else { echo "Invalid file"; } ?> <br> <? // Uppladdningsfunktionen // Baserar sig på http://www.sebastiansulinski.co.uk/web_design_tutorials/php/php_file_upload_4.php /* function upload() { // define constant which contains the maximum file size in bytes define('MAX_FILE_SIZE', 4000000); $servern = $_SERVER['SERVER_NAME']; if (array_key_exists('btn', $_GET)) { // define new constant which contains the path the the upload folder define('UPL_FLD','../uploads/'); // create new file name $filename = substr($_FILES['frmfile']['name'], 0, strrpos($_FILES['frmfile']['name'], '.')); $extension = strtolower(array_pop(explode('.', $_FILES['frmfile']['name']))); $file = $filename . '_' .rand(1,999). '.' .$extension; $file = strtolower($file); $replace_theese_chars = array("(", " ", "å", "ä", "ö", "Å", "Ä", "Ö", ")"); $file = str_replace($replace_theese_chars, "_", $file); // create variable and assign the formatted value of MAX_FILE_SIZE to it $maxfs = number_format(MAX_FILE_SIZE/1024, 1).'KB'; $fsize = false; // check the file size if ($_FILES['frmfile']['size'] > 0 && $_FILES['frmfile']['size'] <= MAX_FILE_SIZE) { $fsize = true; } // allow MIME file types $filetype = array('image/gif','image/jpeg','image/pjpeg','image/png'); // pjpeg e nån IE-grejs.... $ftype = false; // check if uploaded file type is allowed if (in_array($_FILES['frmfile']['type'], $filetype)) { $ftype = true; } if ($ftype && $fsize != '') { switch($_FILES['frmfile']['error']) { case 0: // move file to the upload folder $upload = move_uploaded_file($_FILES['frmfile']['tmp_name'],UPL_FLD.$file); if ($upload) { /*http://fi.php.net/reserved.variables.server $msg = 'Kuva' . $_FILES['frmfile']['name'].' on tallennettu nettiin ja löytyy osoitteesta <br /><dl class="codebox"><dt>Kopioi tämä img scr-koodin:</dt><dd><code>&lt;img src=&quot;img/kodittomat/' . $file . '&quot; width=&quot;500&quot; alt=&quot;[]&quot; title=&quot;&quot; /&gt;</code></dd></dl><br />:'; } else { $msg = 'Error.<br />Ole hyvä, yritä uudelleen.'; } break; case 3: $msg = 'Error.<br />Ole hyvä, yritä uudelleen.'; break; default: $msg = 'Error - please contact administrator. Tai jotain, nyt tarttisi kyllä tehdä jotain.'; } } elseif ($_FILES['frmfile']['error'] == 4) { $msg = 'Valitse kuva koneeltasi'; } else { $msg = $_FILES['frmfile']['name'] . ' ei voida hakea.<br />'; if(!$ftype) { $msg .= 'Hyväksytyt tiedostopäätteet: .gif, .jpg, .png<br />'; } if(!$fsize) { $msg .= 'Tiedosto ei saa olla isompi kuin ' . $maxfs; } } } // include ('./upload_template.html'); if(isset($msg)) { echo '<p class="warning">'.$msg.'</p>'; } } upload(); if ($_FILES["file"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br>"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br>"; echo "Type: " . $_FILES["file"]["type"] . "<br>"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br>"; echo "Stored in: " . $_FILES["file"]["tmp_name"]; } if ((($_FILES["file"]["type"] == "image/png") ||($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")) && ($_FILES["file"]["size"] < 200000)) { if ($_FILES["file"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br>"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br>"; echo "Type: " . $_FILES["file"]["type"] . "<br>"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br>"; echo "Stored in: " . $_FILES["file"]["tmp_name"]; } } else { echo "Invalid file"; } // if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 20000000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br>"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br>"; echo "Type: " . $_FILES["file"]["type"] . "<br>"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br>"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>"; if (file_exists("../shop/uploads/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "../shop/uploads/" . $_FILES["file"]["name"]); echo "Stored in: " . "<a href=" . $who_am_i . "../shop/uploads/" . $_FILES["file"]["name"] . "\">uploads</a>"; } } } else { echo "Invalid file"; } <file_sep>/index.php <?php // ./index.php Landing page error_reporting(E_ALL); $desc = 'Description of site'; // I'll try to remember to stuff this in the db. $keyword = 'key word, etc'; include('shopOverall.php'); ?> <file_sep>/adm/users.php <?php // adm/users.php // $ = (isset($_GET[''])) ? (int) $_GET[''] : 0; error_reporting(E_ALL); include ('./index.php'); $title = (isset($_GET['title'])) ? $_GET['title'] : $lang['ACP_USERS_TITLE']; echo '<div id="acp-top-explanation"><h3>' . $lang['ACP_USERS_TITLE'] . '</h3>'; echo '<p>' . $lang['ACP_USERS_EXPLAIN'] . '</p></div>'; users_menu(); if (basename($who_am_i, ".php") == 'users') // basename returns the end of a path, here we exclude the file extension { $sql = "SELECT * FROM {$prefix}customers ORDER BY 'lname' ASC"; $result = mysql_query($sql); ?> <table class="pages"> <tr><td>uID<td>Last name<td>Given name <? while($row=mysql_fetch_object($result)) { echo '<tr><td>' . $row->uID . '<td>' . $row->lname . '<td>' . $row->fname; } mysql_free_result($result); ?> </table> </div> <? include ('./style/footer.html'); } ?> <file_sep>/adm/usersEdit.php <?php // adm/usersEdit.php // $ = (isset($_GET[''])) ? (int) $_GET[''] : 0; error_reporting(E_ALL); include ('./users.php'); $title = $lang['MANAGE_USERS']; // To be used for headline tags echo '<div id="acp-top-explanation"><h3>' . $lang['USERS'] . '</h3>'; echo '<p>' . $lang['USERS_EXPLAIN'] . '</p></div>'; include ('../inc/shopFunctions.php'); $title = $lang['MANAGE_USERS']; $uID = (isset($_GET['uID'])) ? (int) $_GET['uID'] : 0; $lname = (isset($_GET['lname'])) ? $_GET['lname'] : ''; $sql = "SELECT * FROM {$prefix}customers WHERE uID = '$uID'"; mysql_query($sql); $searchuser = (isset($_GET['searchuser'])) ? $_GET['searchuser'] : ''; if ($searchuser == '') search_user_form('SEARCH_USER', ''); else { // include ('../inc/incUsers.php'); $fname = (isset($_POST['fname']) ? $_POST['fname'] : ''); $fname = mysql_real_escape_string(ucfirst($fname)); ?> <h3 class="pages"><?= $lang['MANAGE_USERS']?></h3> <p class="pages"><?= $lang['MANAGE_USERS_EXPLAIN']?>.</p> <ul> <span class="per85"> <? $sql = "SELECT * FROM {$prefix}customers WHERE lname LIKE '%{$searchuser}%' OR fname LIKE '%{$searchuser}%' OR street LIKE '%{$searchuser}%' OR city LIKE '%{$searchuser}%' OR zip LIKE '%{$searchuser}%' OR phone LIKE '%{$searchuser}%' OR email LIKE '%{$searchuser}%' ORDER BY uID ASC"; $result = mysql_query($sql); while($row=mysql_fetch_object($result)) { echo '<li class="pages">'; echo $row->uID . ' ' . $row->lname. ' ' . $row->fname . '</a></li>'; /*echo "<li class=\"pages\"><a href=\"./usersEdit.php?uID=" . $row->uID . "&amp;lname=" . $row->lname . '"onclick="return confirm(\'' . $really, $row->lname . '?\');">'; echo $row->uID . ' ' . $row->lname. ' ' . $row->fname. '</a></li>';*/ } mysql_free_result($result); search_user_form('SEARCH_USER', ''); ?> </span> </ul> <?php } where_is_adm('', 'usersEdit'); ?><file_sep>/adm/products.php <?php // adm/products.php // $ = (isset($_GET[''])) ? (int) $_GET[''] : 0; error_reporting(E_ALL); include ('./index.php'); $title = $lang['ACP_PRODUCTS_TITLE']; echo '<div id="acp-top-explanation"><h3>' . $lang['ACP_PRODUCTS_TITLE'] . '</h3>'; echo '<p>' . $lang['ACP_PRODUCTS_EXPLAIN'] . '</p></div>'; item_menu(); where_is_adm('', 'products') ?> <file_sep>/inc/shopFunctions.php <?php // Check the filename currently in use function where_am_i($file_name, $file_name2) { global $style; $who_am_i = $_SERVER['PHP_SELF']; if (basename($who_am_i, ".php") == $file_name) { $title = ':)'; $desc = ''; $keywords = ''; include ('./styles/' . $style . '/header.php'); } elseif (basename($who_am_i, ".php") == $file_name2) include ('./styles/' . $style . '/footer.php'); } ?> <file_sep>/adm/settings.php <?php // adm/settings.php // $ = (isset($_GET[''])) ? (int) $_GET[''] : 0; error_reporting(E_ALL); include ('./index.php'); $title = $lang['ACP_SETTINGS']; // To be used for headline tags echo '<div id="acp-top-explanation"><h3>' . $lang['ACP_SETTINGS_TITLE'] . '</h3>'; echo '<p>' . $lang['ACP_SETTINGS_EXPLAIN'] . '</p></div>'; $title1 = (isset($_GET['title1'])) ? $_GET['title1'] : ''; $tracker = (isset($_GET['tracker'])) ? $_GET['tracker'] : ''; $open = (isset($_GET['open'])) ? (int) $_GET['open'] : 0; //Showing as PHP code // $sql = "ALTER TABLE `194D_shop_settings` CHANGE `tracker` `tracker` VARCHAR(2000) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL COMMENT \'Insert your analytics code here\', CHANGE `language` `language` TINYINT(2) NOT NULL, CHANGE `open` `open` TINYINT(1) NULL DEFAULT \'42\'"; /* echo $sql; $sql = "SELECT * FROM {$prefix}settings"; $result = mysql_query($sql); $row = mysql_fetch_array($result); if (isset($_POST['submit']) && isset($row['tracker'])) { // $sql = "UPDATE content SET etusivu = '$message_etusivu' WHERE etusivu = '" . $row['tracker'] . "'"; mysql_query($sql) or die(mysql_error()); } else if (isset($row['tracker'])) { $tracker = $row['tracker']; } /*if ($tracker != '') { $sql = "INSERT INTO {$prefix}settings (tracker, open) VALUES ('$tracker', '$open')"; mysql_query($sql); }*/ ?> <div id="sidemenu"> <ul> <li><a href="./.php"><?= $lang['']?>asdasd</a></li> </ul> </div> <div id="pages"> <form method="get" action=""> <p3 class="pages"><?=$lang['title1'];?> <!-- The statement "required" isn't supported properly in IE9, do not rely on in just yet. --> <input type="text" name="title1" required value="<?=stripslashes($title1);?>"> <input type="submit" name="send" value="<?=$lang['SEND']?>"><input type="reset" value="<?=$lang['RESET']?>"></p> </form> </div> <?php if ($title1 != '') { $sql = "UPDATE {$prefix}settings SET title1 = '$title1'"; mysql_query($sql); } ?> <!-- <div id="pages"> <form action="" method="get"> <div class="pages"><?= $lang['ONOFF']?> <input type='radio' name='onoff' value='open' /><?= $lang['OFF']?>. <input type='radio' name='onoff' value='open' /><?= $lang['ON']?> </div> <br /><br /><br /><br /><br /> <h3 class="pages" ><?= $lang['TRACKER']?></h3> <p class="pages"><?= $lang['TRACKER_EXPLAIN']?> <br /> <textarea name="tracker" rows='12' cols='90' value="<?=$tracker?>"></textarea><input type="submit" name="send" value="<?=$lang['SEND']?>"> </p> </div> </form> <?php mysql_free_result($result); where_is_adm('', 'groups'); // function muokkkaa_etusivu is just a copy/paste of my own old code, it is here for reference, please let me remember to remove this :P function muokkaa_etusivu() { $message_etusivu = (isset($_POST['content'])) ? $_POST['content'] : ''; // kollar att variabeln message_etusivu har ett värde $sql = "SELECT * FROM content"; $result = mysql_query($sql) or die(mysql_error()); $row = mysql_fetch_array($result); if (isset($_POST['submit']) && isset($row['etusivu'])) { // Kun tietokanta on auki graafisella työkalulla ei ole enää tarvetta turvata php-koodissa. // $message_etusivu = mysql_real_escape_string($message_etusivu); $sql = "UPDATE content SET etusivu = '$message_etusivu' WHERE etusivu = '" . $row['etusivu'] . "'"; mysql_query($sql) or die(mysql_error()); } else if (isset($row['etusivu'])) { $message_etusivu = $row['etusivu']; } ?> <div> <form action="action.php?action=muoks_etusivu" method="post" name="frm_cms" id="frm_cms"> Muokattava etusivun teksti, maks 420 merkkiä: <br /> Rivinvaihto (br /) ja tekstin lihavointi (strong), jota ehkä haluat kopioda XHTML-formatointia varten löytyy tämänn tekstin alla. <br /> <input type="text" name="br" size="4" value="<br />" /> <input type="text" name="br" size="18" value="<strong></strong>" /><br /> <input type="text" name="br" size="40" value='<span style= "color: blue" >Väritä</span>' /> <a href= "http://en.wikipedia.org/wiki/Web_colors#HTML_color_names" target="_blank"><u>Värikoodit</u></a> (avautuu uuteen ikkunaan) <textarea rows="8" cols="67" name="content"><?php echo stripslashes($message_etusivu); ?></textarea> <br /> Klikkaa "Muuta etusivun viestiä!" muuttaaksesi etusivun viestiä. <div class="centrera"> <input type="submit" name="submit" value="Muuta etusivun viestiä!" /> <input type="reset" value="Tyhjennä!" /> </div> </form> </div> <?php mysql_free_result($result); }<file_sep>/styles/default/menu.php <?php // global $lang; echo '<br><br><div class="menu">'; $sql = "SELECT * FROM {$prefix}pages ORDER BY pID ASC"; $result = mysql_query($sql); while($row=mysql_fetch_object($result)) { if (!$row->prio==0) echo '<a href="index.php?page=' . $row->pID . '">' . $row->pagename. '</a> '; } echo '<br><!-- If user logged in and admin, functions yet to be done. --> | <a href="./adm/">[ REAL ACP ] </a>'; echo '<a href="shopUsers.php">[ shopUsers.php ] </a></div>'; echo '<img id="logo" src="styles/' . $style . '/img/shop_logo.png" alt="" >'; ?><file_sep>/adm/productsEdit.php <?php //******* Thought I modify from pagesEdit, but, mm, I'll see **************// error_reporting(E_ALL); $who_am_i = $_SERVER['PHP_SELF']; if (basename($who_am_i, ".php") != 'products') include ('./products.php'); $iID = (isset($_GET['iID'])) ? (int) $_GET['iID'] : 0; $gID = (isset($_GET['gID'])) ? (int) $_GET['gID'] : 0; $productname = (isset($_GET['productname'])) ? $_GET['productname'] : ''; $productname = strip_tags($productname); $productname = ucfirst($productname); $productdesc = (isset($_GET['productdesc'])) ? $_GET['productdesc'] : ''; $color = (isset($_GET['color'])) ? $_GET['color'] : ''; $price = (isset($_GET['price'])) ? (int) $_GET['price'] : 0; /* Takes the value that user inserts into $variables and SETs UPDATED values in cells */ $sql = "UPDATE {$prefix}items SET productname = '$productname', color = '$color', productdesc = '$productdesc', price = '$price' WHERE iID = '$iID'"; mysql_query($sql); ?> <h3 class="pages"><?= $lang['CHANGE_PRODUCT_DETAILS']?></h3> <ul> <? // List products for easy access by clicking $sql = "SELECT * FROM {$prefix}items ORDER BY price ASC"; $result = mysql_query($sql); while($row=mysql_fetch_object($result)) { echo "<li class=\"pages\"><a href=\"./productsEdit.php?iID=" . $row->iID . "&amp;productname=" . $row->productname . "&amp;color=" . $row->color . "&amp;productdesc=" . $row->productdesc . "&amp;price=" . $row->price . "\">"; echo $row->iID . ' ' . $row->productname. '</a></li>'; } mysql_free_result($result); ?> </ul> <form method="get" action=""> <table class="pages"> <tr> <td><?= $lang['PRODUCT_ID']?></td> <td><input type="text" name="iID" readonly value="<?= $iID; ?>"></td> <tr> <td><?= $lang['NAME_GROUP']?></td> <td><input type="text" name="gID" value="<?= $gID; ?>"></td> <tr> <td><?= $lang['CHANGE_PRODUCTNAME']?></td> <td><input type="text" name="productname" value="<?= $productname; ?>"></td> <tr> <td><?= $lang['DESC']?></td> <td><input type="text" name="productdesc" value="<?= $productdesc; ?>"></td> <tr> <td><?= $lang['PRODUCT_COLOR']?></td> <td><input type="text" name="color" value="<?= $color; ?>"></td> <tr> <td><?= $lang['PRODUCT_PRICE']?></td> <td><input type="text" name="price" value="<?= $price; ?>"></td> <!-- FIX THIS!!--> <td></td> <td><input type="submit" name="send"></td> </table> </form> <? where_is_adm('', 'productsEdit'); <file_sep>/lang/sv.php <?php // . $lang['Swedish'] . // Go away if LANG is not defined. if (!defined('LANG')) { exit; } // If there is no $lang defined AND it's not an array, let us make it one. if (empty($lang) || !is_array($lang)) { $lang = array(); } // Take $lang and add the language specific elements to get localized content. $lang = array_merge($lang, array( 'TEST' => 'SVENSKA test', 'TITLE' => 'Svensk Titel för siten', )); ?> <file_sep>/adm/pagesDelete.php <?php // adm/pagesDelete.php error_reporting(E_ALL); include ('./pages.php'); $title = $lang['DEL_PAGE']; $pID = (isset($_GET['pID'])) ? (int) $_GET['pID'] : 0; $pagename = (isset($_GET['pagename'])) ? $_GET['pagename'] : ''; $sql = "DELETE FROM {$prefix}pages WHERE pID = '$pID'"; $really = $lang['DEL_PAGE_REALLY'] . ' '; // defining the lang string for the js-code here mysql_query($sql); ?> <h3 class="pages"><?= $lang['DEL_PAGE']?></h3> <p class="pages"><?= $lang['DEL_PAGE_EXPLAIN']?>.</p> <ul> <span class="per85"> <? $sql = "SELECT * FROM {$prefix}pages ORDER BY prio ASC"; $result = mysql_query($sql); while($row=mysql_fetch_object($result)) { echo "<li class=\"pages\"><a href=\"./pagesDelete.php?pID=" . $row->pID . "&amp;pagename=" . $row->pagename . '"onclick="return confirm(\'' . $really, $row->pagename . '?\');">'; echo $row->pID . ' ' . $row->pagename. '</a></li>'; echo "\n"; } mysql_free_result($result); ?> </span> </ul> <?php // Close db-connection mysql_close($connection); where_is_adm('', 'pagesDelete') ?> <file_sep>/adm/usersDelete.php <?php // adm/usersDelete.php error_reporting(E_ALL); include ('./users.php'); $title = $lang['DEL_USER']; $uID = (isset($_GET['uID'])) ? (int) $_GET['uID'] : 0; $lname = (isset($_GET['lname'])) ? $_GET['lname'] : ''; $sql = "DELETE FROM {$prefix}customers WHERE uID = '$uID'"; $really = $lang['DEL_USER_REALLY'] . ' '; // defining the lang string for the js-code here mysql_query($sql); $searchuser = (isset($_GET['searchuser'])) ? $_GET['searchuser'] : ''; if ($searchuser == '') search_user_form('SEARCH_USER', ''); else { ?> <h3 class="pages"><?= $lang['DEL_USER']?></h3> <p class="pages"><?= $lang['DEL_USER_EXPLAIN']?>.</p> <ul> <span class="per85"> <? $sql = "SELECT * FROM {$prefix}customers WHERE lname LIKE '%{$searchuser}%' OR fname LIKE '%{$searchuser}%' OR street LIKE '%{$searchuser}%' OR city LIKE '%{$searchuser}%' OR zip LIKE '%{$searchuser}%' OR phone LIKE '%{$searchuser}%' OR email LIKE '%{$searchuser}%' ORDER BY uID ASC"; $result = mysql_query($sql); while($row=mysql_fetch_object($result)) { echo "<li class=\"pages\"><a href=\"./usersDelete.php?uID=" . $row->uID . "&amp;lname=" . $row->lname . '"onclick="return confirm(\'' . $really, $row->lname . '?\');">'; echo $row->uID . ' ' . $row->lname. ' ' . $row->fname. '</a></li>'; echo "\n"; } mysql_free_result($result); ?> </span> <? search_user_form('SEARCH_USER', ''); } // Close db-connection mysql_close($connection); ?> <file_sep>/lang/en.php <?php // . $lang['English'] . // Go away if LANG is not defined. if (!defined('LANG')) exit; // If there is no $lang defined AND it's not an array, let's make it one. if (empty($lang) || !is_array($lang)) $lang = array(); // Take $lang and add the language specific elements to get localized content. $lang = array_merge($lang, array( '' => '', '' => '', '' => '', 'ACP_INDEX' => 'ACP Index', 'ACP_PAGES_EXPLAIN' => 'Here you can move, create, modify and delete pages.', 'ACP_PAGES_TITLE' => 'Administer Pages', 'ACP_PRODUCTS_EXPLAIN' => 'Here you can add, change details for and delete products.', 'ACP_PRODUCTS_TITLE' => 'Administer Products', 'ACP_SETTINGS' => 'Settings', 'ACP_SETTINGS_EXPLAIN' => 'Useful small things', 'ACP_SETTINGS_TITLE' => 'Miscelangelous things', 'ACP_USERS_EXPLAIN' => 'Here you can add, change details for and delete users.', 'ACP_USERS_TITLE' => 'Administer Users', 'ADD_PAGE' => 'Add a new page', 'ADD_PRODUCT' => 'Add product', 'CHANGE_PAGE' => 'Your new name for the page', 'CHANGE_PAGE_DETAILS' => 'Change page title and settings', 'CHANGE_PAGE_DETAILS' => 'Change page title and settings', 'CHANGE_PAGE_EXPLAIN' => 'Click on a page to select for editing.', 'CHANGE_PRODUCT_DETAILS' => 'Change product details', 'CHANGE_PRODUCTNAME' => 'Change productname', 'CITY' => 'City', 'CLEAR' => 'Clear', 'CONT' => 'Page Content', 'COUNTRY' => 'Country', // Not included yet 'DEL_PAGE' => 'Delete page', 'DEL_PAGE_EXPLAIN' => 'Click a page to delete it. This can not be undone', 'DEL_PAGE_REALLY' => 'Are you sure, deleting page', 'DEL_PRODUCT' => 'Delete product', 'DEL_PRODUCT_EXPLAIN' => 'Deleting a product will drop it forever, you can not undo this.', 'DEL_PRODUCT_REALLY' => 'Really want to delete product ', 'DEL_USER' => 'Delete user', 'DEL_USER_EXPLAIN' => 'Click a user to delete. This can not be undone', 'DEL_USER_REALLY' => 'Are you sure, deleting user', 'DESC' => 'Description', 'DESC' => 'Wonderful handcraft in leather from Finland', 'EDIT_GROUP' => 'Change groupname or description.', 'EDIT_PAGE' => 'Edit page', 'EDIT_PRODUCT' => 'Change product', 'EMAIL' => 'E-mail address', 'EMAIL_REQUIRED_CHAR' => 'Did you notice that you forgot an . or an @ when you wrote your email address?', 'EMAIL_TO_SHORT' => 'AN email address is supposed to have more characters in it', 'ENGLISH' => 'Use shop in English', 'FINNISH' => 'Käytä kauppa suomeksi', 'FIRST NAME' => 'Given name', 'GOODIE' => 'Goodies', 'GROUPS_EXPLAIN' => 'Here you can manage groups for your shop items', 'GROUPS_TITLE' => 'Product groups', 'KEYWORDS' => 'Shop online in Finland, assecoaries, leather, gifts, gizmo, girlpower', 'LAST NAME' => 'Family name ', 'MANAGE_GROUPS' => 'Manage groups', 'MANAGE_USERS' => 'Here you can manage users and user details.', 'MANAGE_USERS_EXPLAIN' => 'Click on the desired user to update/read their information', 'METALANG' => 'en', // FI SV 'NAME_GROUP' => 'Group name', 'NEW_PAGE' => 'Add page', 'NEW_PAGE_EXPLAIN' => 'Please insert a name for the new page.', 'NEW_PIC' => 'Picture', 'NEW_PIC_EXPLAIN' => 'Upload a picture from your computer', 'NEW_PRODUCT' => 'New product', 'NEW_PRODUCT_EXPLAIN' => 'New product', 'OFF' => '0 OFF (Closed)', 'ON' => '42 open for Business.', 'ONOFF' => 'The Shop Frontend is', 'ORDERS' => 'Orders', 'PAGE_CONT_EXPLAIN' => 'All that will be shown on the page', 'PAGE_DESC_EXPLAIN' => 'Notes to yourself', 'PAGE_ID' => 'Page ID', 'PAGE_META' => 'Title', 'PAGE_META_EXPLAIN' => '(used in meta and mouseover)', // not implemented yet Sept 23 2011 'PAGE_POSITION' => 'Page position', 'PAGE_POSITION_EXPLAIN' => 'The menu is ordered by this number,<br />set to 0 to hide page from frontend menu.', 'PAGES' => 'Pages', 'PASSWORD' => '<PASSWORD>', 'PHONE' => 'Phone number', 'PRODUCT_COLOR' => 'Colour', 'PRODUCT_COLOR_EXPLAIN' => 'Colour', 'PRODUCT_DESC_EXPLAIN' => '', 'PRODUCT_GID' => 'product group', 'PRODUCT_GID_EXPLAIN' => 'What is the maingroup?', 'PRODUCT_ID' => 'Product ID', 'PRODUCT_PRICE' => 'Price', 'PRODUCT_PRICE_EXPLAIN' => 'Price', 'PRODUCTS' => 'Products', 'PRODUCTS_ADD' => 'Add products', 'PRODUCTS_DEL' => 'Delete products', 'PRODUCTS_EDIT' => 'Change product details', 'REGISTER' => 'Register', 'REGISTER_THANKS' 'Thank you for your registration!', 'RESET' => 'Reset', 'SEARCH_USER' => 'Search user', 'SEARCH_USER_EXPLAIN' => 'Search by name or adress. The search function automagically uses wildcards.', 'SEND' => 'Send', 'SHOP_FRONTEND' => 'Go to the frontend of your shop', 'STREET ADDRESS' => 'Street address', 'SWEDISH' => 'Använd shoppen på svenska', 'TEST' => 'ENG test', 'TRACKER' => 'Tracking code', // For Analytics 'TRACKER_EXPLAIN' => 'Insert your traffic tracker/statistic code here, it will be loaded last on the page on every page in the frontend of the shop.', 'USER' => 'User', 'USERS' => 'Users', 'USERS_ADD' => 'Add user', 'USERS_DEL' => 'Delete user', 'USERS_EDIT' => 'Change user details', 'USERS_EXPLAIN' => 'Change users details', 'ZIP' => 'Zip code', 'ZIP_ERROR' => 'The postcode must contain 5 numbers.', // 'TITLE' => 'Site title shouldn\'t be in lang file...', 'ACP_WELCOME' => 'Welcome to your shop Administration Control Panel. Use the navigation to find tools and personalize your business.<br>Fast actions can be managed from this overview.<br> Good sales!', )); ?> <file_sep>/adm/pages.php <?php // adm/pages.php // $ = (isset($_GET[''])) ? (int) $_GET[''] : 0; error_reporting(E_ALL); include ('./index.php'); $title = $lang['ACP_INDEX']; // To be used for headline tags echo '<div id="acp-top-explanation"><h3>' . $lang['ACP_PAGES_TITLE'] . '</h3>'; echo '<p>' . $lang['ACP_PAGES_EXPLAIN'] . '</p></div>'; ?> <div id="sidemenu"> <ul> <li><a href="./pagesEdit.php"><?= $lang['EDIT_PAGE']?></a></li> <li><a href="./pagesAdd.php"> <?= $lang['NEW_PAGE']?></a></li> <li><a href="./pagesDelete.php"><?= $lang['DEL_PAGE']?></a></li> </ul> </div> <?php if (basename($who_am_i, ".php") == 'pages') // basename returns the end of a path, here we exclude the fileextension { include ('./pagesEdit.php'); include ('./style/footer.html'); } ?> <file_sep>/shopOverall.php <?php define('LANG', true); // The user doesn't get anywhere w/o words in the interface. if (!empty($_GET['lang'])) $lang = $_GET['lang']; else if (!empty($_COOKIE['lang'])) $lang = $_COOKIE['lang']; else $lang = 'en'; // $lang = ($lang == 'sv') ? 'sv' : 'en'; setcookie('lang', $lang); include('./lang/' . $lang . '.php'); include('./connection.php'); include('./inc/shopFunctions.php'); where_am_i(('shopOverall' || 'index' || 'shopUsers'),''); include('./styles/' . $style . '/menu.php'); echo $lang['TEST'] . '<br>'; switch(@$_GET['page']) { case 0: echo 'case 0,'; break; case 1: echo basename(__FILE__); case 2: // Just an exmple A YEAR LATER: UMMM, what was I testing here? Better leave it for now. $arr = explode('.', basename(__FILE__)); var_dump($arr[0]); break; case '': break; case '': break; case '': break; break; default: echo 'HÄÄ-HÄÄ - default:No page indexed - HÄÄ-HÄÄ'; } // so... Let us show some user defined content here. $page = (isset($_REQUEST['page'])) ? $_REQUEST['page'] : '0'; echo '<p>'; $sql = "SELECT * FROM {$prefix}pages WHERE pID = $page"; $result = mysql_query($sql); while($row=mysql_fetch_object($result)) { if (!$row->prio==0) echo ' X ' . $row->pagename . '<br>XXXX<br>' . $page; // while($page=$row->pID) echo $row->content; } echo '</p>'; mysql_free_result($result); where_am_i('','shopOverall'); ?> <file_sep>/adm/groups.php <?php // adm/groups.php // $ = (isset($_GET[''])) ? (int) $_GET[''] : 0; error_reporting(E_ALL); include ('./index.php'); $title = $lang['MANAGE_GROUPS']; // To be used for headline tags echo '<div id="acp-top-explanation"><h3>' . $lang['GROUPS_TITLE'] . '</h3>'; echo '<p>' . $lang['GROUPS_EXPLAIN'] . '</p></div>'; item_menu(); $gID = (isset($_GET['gID'])) ? (int) $_GET['gID'] : 0; $group_name= (isset($_GET['group_name'])) ? $_GET['group_name'] : ''; $group_name = strip_tags($group_name); $group_name = ucfirst($group_name); $group_exp = (isset($_GET['group_exp'])) ? $_GET['group_exp'] : ''; $group_exp = strip_tags($group_exp); ?> <div class="groups"> <?= $lang['GROUPS_TITLE'];?><br> <?php $sql = "SELECT * FROM {$prefix}groups"; $result = mysql_query($sql); while($row = mysql_fetch_object($result)) { echo "<li><a href=\"./groupsEdit.php?gID=" . $row->gID . "&amp;gID=" .$row->gID . "&amp;group_name=" .$row->group_name . "&amp;group_exp=" .$row->group_exp . "\"> $row->gID $row->group_name </a> $row->group_exp </li> "; } echo '</div>'; mysql_free_result($result); ?> <!-- Add groupname --> <div class="pages"> <h3 >add group</h3> <form method="get" action=""> <p><?= $lang['NAME_GROUP'];?> <input type="text" name="group_name" value="<?=$group_name?>"> <?= $lang['DESC'];?> <input type="text" name="group_exp" value="<?=$group_exp?>"> <input type="submit" name="laheta"> <input type="reset"></p> </div> <?php if ($gID == '' && $group_name != '') { $sql = "INSERT INTO {$prefix}groups (gID, group_name, group_exp) VALUES ('', '$group_name', '$group_exp')"; } mysql_query($sql); // edit group // delete group where_is_adm('', 'groups'); ?> <file_sep>/connection.php <?php /* <NAME>, tästä aiheutui paljon ongelmia! $err = error_reporting(0); echo $err; */ include ('config.php'); $connection = mysql_connect($server, $database, $password); if (!$connection) { die('There is a problem, get some coffee and check your configuration.' . mysql_error()); } mysql_select_db($database, $connection); if (!mysql_select_db($database)) { echo 'I am just a simple script, I am sorry, but I can\'t find a database, please consult a human. <br>'; exit(); } ?>
a379b98e0c6a4bed56d3af50a86ea72d76e06ec8
[ "PHP" ]
27
PHP
Peetra/shop
9859b5f862add9120b5c12246e9dcab52d995653
a522470064ea745c5088b66fc239c3448a39437c
refs/heads/master
<repo_name>AlTsbk/ipCalculator<file_sep>/ipCalculator/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System; using System.Text; namespace ConsoleApp5 { class Program { class IpException : Exception { public IpException() { Console.WriteLine("Неправильно задан ip адресс"); } } class MaskException : Exception { public MaskException() { Console.WriteLine("Неправильно задана маска"); } } static void Main(string[] args) { string ipS; int[] ip = new int[4]; string maskS; int[] mask = new int[4]; Console.WriteLine("Введите ip"); ipS = Console.ReadLine(); CorrectAddr(ipS); Console.WriteLine("Введите маску подсети"); maskS = Console.ReadLine(); CorrectAddr(maskS); DivisionOnOctets(ref ip, ipS); DivisionOnOctets(ref mask, maskS); TestIp(ip); TestMask(mask); Calculate(ip, mask); } public static void DivisionOnOctets(ref int[] ip, string ipS) { for (int i = 0; i < 3; i++) { int x = ipS.IndexOf('.'); string octet = ipS.Substring(0, x); ip[i] = Convert.ToInt32(octet); ipS = ipS.Remove(0, x + 1); } ip[3] = Convert.ToInt32(ipS); } public static void TestMask(int[] mask) { int x = 1; for (int i = 0; i < 4; i++) { if ((mask[i] != 0 && x == 0) || (mask[i] == 0 && x == -1)) { throw new MaskException(); } if (mask[i] > 255 && mask[i] < 0) { throw new MaskException(); } x = mask[i]; } } public static void TestIp(int[] ip) { for (int i = 0; i < 4; i++) { if (ip[i] > 255 || ip[i] < 0) { throw new IpException(); } } } public static void CorrectAddr(string str) { for (int i = 0; i < 3; i++) { int y = str.IndexOf('.'); str = str.Remove(0, y + 1); if (y < 0) { throw new IpException(); } } } public static void Calculate(int[] ip, int[] mask) { int[] IdHost = new int[4] { 0, 0, 0, 0 }; int[] IdNetwork = new int[4] { 0, 0, 0, 0 }; for (int i = 0; i < 4; i++) { if (mask[i] == 255) { IdNetwork[i] = ip[i]; } else if (mask[i] == 0) { IdHost[i] = ip[i]; } else { string s1 = Convert.ToString(ip[i], 2); string s2 = Convert.ToString(mask[i], 2); Console.WriteLine(s1); Console.WriteLine(s2); IdNetwork[i] = Conunction(s1, s2); IdHost[i] = ip[i] - IdNetwork[i]; } } Console.Write("\nID хоста: "); for (int i = 0; i < 4; i++) { if (i == 3) { Console.Write(IdHost[i]); } else { Console.Write(IdHost[i] + "."); } } Console.Write("\nID подсети: "); for (int i = 0; i < 4; i++) { if (i == 3) { Console.Write(IdNetwork[i]); } else { Console.Write(IdNetwork[i] + "."); } } Console.WriteLine(); } public static int Conunction(string s1, string s2) { if (s1.Length != 8) { for (int i = 0; i < 8 - s1.Length; i++) { s1 = s1.Insert(0, "0"); } } if (s2.Length != 8) { for (int i = 0; i < 8 - s2.Length; i++) { s2 = s2.Insert(0, "0"); } } string v1; string v2; string result = ""; for (int i = 0; i < 8; i++) { v1 = s1.Substring(i, 1); v2 = s2.Substring(i, 1); //Console.WriteLine(i + ") " +v1 + ' ' + v2); if (v1 == "1" && v2 == "1") { result += "1"; } else { result += "0"; } } return ConvertToD(result); } static public int ConvertToD(string str) { string s; int result = 0; for (int i = 1; i <= str.Length; i++) { s = str.Substring(i - 1, 1); if (s == "1") { switch (i) { case 1: result += 128; break; case 2: result += 64; break; case 3: result += 32; break; case 4: result += 16; break; case 5: result += 8; break; case 6: result += 4; break; case 7: result += 2; break; case 8: result += 1; break; } } } return result; } } }
e9fdf27e9a58624646e0310c621419e7a9e8fea8
[ "C#" ]
1
C#
AlTsbk/ipCalculator
744758f5304af2b0112a6c6d9357e7c5e8c74217
aa9b60cd1804042e71b603d95354a7b1324f2c30
refs/heads/master
<repo_name>tenjava-2014/lenis0012-t1<file_sep>/src/main/java/com/tenjava/entries/lenis0012/t1/Feature.java package com.tenjava.entries.lenis0012.t1; import com.tenjava.entries.lenis0012.t1.features.BaseFeature; import com.tenjava.entries.lenis0012.t1.features.chests.ChestFeature; import com.tenjava.entries.lenis0012.t1.features.weapons.WeaponFeature; import java.lang.reflect.Constructor; import java.util.logging.Level; /** * Created by Lenny on 12-7-2014. */ public enum Feature { CHESTS("chests", ChestFeature.class), WEAPONS("weapons", WeaponFeature.class); private final String name; private final Class<? extends BaseFeature> baseClass; private BaseFeature instance; /** * @param name Name of features * @param baseClass Feature base class */ private Feature(String name, Class<? extends BaseFeature> baseClass) { this.name = name; this.baseClass = baseClass; } public String getName() { return name; } public void load(TenJava plugin) { try { Constructor<? extends BaseFeature> constructor = baseClass.getConstructor(TenJava.class, String.class); this.instance = constructor.newInstance(plugin, name); } catch (Exception e) { TenJava.getInstance().getLogger().log(Level.SEVERE, "Failed to load feature", e); } } public boolean enable() { if(TenJava.getInstance().getConfig().getBoolean("features." + name + ".enabled")) { instance.onEnable(); return true; } return false; } public void disable() { instance.disable(); } public <T> T getInstance(Class<T> type) { return type.cast(instance); } } <file_sep>/src/main/java/com/tenjava/entries/lenis0012/t1/features/weapons/Weapon.java package com.tenjava.entries.lenis0012.t1.features.weapons; import com.tenjava.entries.lenis0012.t1.TenJava; import com.tenjava.entries.lenis0012.t1.features.weapons.types.BaseWeapon; import com.tenjava.entries.lenis0012.t1.features.weapons.types.ThorsHammer; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import java.lang.reflect.Constructor; import java.util.HashMap; import java.util.Map; /** * Created by Lenny on 12-7-2014. */ public enum Weapon { THORS_HAMMER("ThorHammer", ThorsHammer.class); private final String name; private final ConfigurationSection config; private boolean enabled; private BaseWeapon weapon; private int wealth; private Weapon(String name, Class<? extends BaseWeapon> weaponClass) { this.name = name; this.config = TenJava.getInstance().getConfig().getConfigurationSection("features.weapons.types." + name); this.enabled = config.getBoolean("enabled"); if(enabled) { try { Constructor<? extends BaseWeapon> constructor = weaponClass.getConstructor(ConfigurationSection.class); this.weapon = constructor.newInstance(config); } catch(Exception e) { this.enabled = false; this.weapon = null; e.printStackTrace(); //TODO: Change later } this.wealth = config.getInt("wealth"); } else { this.weapon = null; this.wealth = 0; } } /** * Fire with weapon if enabled. * * @param player Weapon holder */ public void fire(Player player) { if(enabled) { weapon.fire(player); } } /** * Weapon item * * @return Weapon item */ public ItemStack itemStack() { return weapon.getItem(); } /** * Get weapon by item in hand * * @param item Item in hand. * @return Weapon */ public static Weapon getWeapon(ItemStack item) { for(Weapon weapon : values()) { if(weapon.weapon != null && weapon.weapon.check(item)) { return weapon; } } return null; } public static Map<Integer, Weapon> getWealthList() { return wealthList; } private static final Map<Integer, Weapon> wealthList = new HashMap<>(); static { //Add weapons to wealth list for(Weapon weapon : Weapon.values()) { int size = wealthList.size(); for(int i = size; i < size + weapon.wealth; i++) { wealthList.put(i, weapon); } } } } <file_sep>/README.md lenis0012's ten.java submission ============================== [![ten.java](https://cdn.mediacru.sh/hu4CJqRD7AiB.svg)](https://tenjava.com/) This is a submission for the 2014 ten.java contest. - __Theme:__ How can combat/weapons be improved? - __Time:__ Time 1 (7/12/2014 00:00 to 7/12/2014 10:00 UTC) - __MC Version:__ 1.7.9 (latest Bukkit beta) - __Stream URL:__ https://twitch.tv/BlueDevonMovies <!-- put chosen theme above --> --------------------------------------- Compilation ----------- - Download & Install [Maven 3](http://maven.apache.org/download.html) - Clone the repository: `git clone https://github.com/tenjava/lenis0012-t1` - Compile and create the plugin package using Maven: `mvn` Maven will download all required dependencies and build a ready-for-use plugin package! --------------------------------------- Usage ----- 1. Install plugin 2. Edit config.yml to fit your needs 3. Restart server 4. Find the hidden chests and enjoy your weapons. Docs ---- This plugin adds new hidden chests to the world that contain new weapons. Sadly i only made 1 weapon because i ran out of time My alarm clock didn't go off and im going to a party. Players with the permission 'tenjava.chests.notifyspawn' get a notification when a chest spawns. Chests ------ Chests have a certain chance of spawning in a newly generated chunk. They spawn in a range of 20-30Y by default which can be changed. OPs will receive notifications with the locations so that you can teleport to it and grab your loot. Weapons ------- Left click to use weapons Thor's hammer: Thor's hammer an iron axe that shoots fireballs at a custom speed. Once this ball hits a block it created an amazing explosion and strike lightning. I recommend shooting this on trees for optimal amusement. <file_sep>/src/main/java/com/tenjava/entries/lenis0012/t1/features/weapons/WeaponListener.java package com.tenjava.entries.lenis0012.t1.features.weapons; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; /** * Created by Lenny on 12-7-2014. */ public class WeaponListener implements Listener { @EventHandler public void onPlayerInteract(PlayerInteractEvent event) { final Player player = event.getPlayer(); final ItemStack item = player.getItemInHand(); final Action action = event.getAction(); if(action == Action.LEFT_CLICK_AIR || action == Action.LEFT_CLICK_BLOCK) { Weapon weapon = Weapon.getWeapon(item); if(weapon != null) { weapon.fire(player); } } } } <file_sep>/src/main/java/com/tenjava/entries/lenis0012/t1/TenJava.java package com.tenjava.entries.lenis0012.t1; import org.bukkit.plugin.java.JavaPlugin; import java.util.logging.Level; /** * Combat can only be improved with my fancy code. * Extra weapons put into secret chests under the ground. * THIS IS HELL IN A PLUGIN!!!!! */ public class TenJava extends JavaPlugin { private static TenJava instance; public static TenJava getInstance() { return instance; } public static void setInstance(TenJava instance) { TenJava.instance = instance; } public void onLoad() { //Load all features for(Feature feature : Feature.values()) { feature.load(this); } } @Override public void onEnable() { setInstance(this); loadConfig(); //Enable all features for(Feature feature : Feature.values()) { if(feature.enable()) { getLogger().log(Level.INFO, "Enabled feature: " + feature.getName()); } } } @Override public void onDisable() { setInstance(null); //Disable all features for(Feature feature : Feature.values()) { feature.disable(); } } public void loadConfig() { saveDefaultConfig(); //May wanna improve later } } <file_sep>/src/main/java/com/tenjava/entries/lenis0012/t1/features/weapons/types/BaseWeapon.java package com.tenjava.entries.lenis0012.t1.features.weapons.types; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; /** * Created by Lenny on 12-7-2014. */ public abstract class BaseWeapon { protected final String displayName; protected final Material material; protected final ConfigurationSection config; /** * @param displayName Display name of weapon. * @param material Material of the weapon. */ public BaseWeapon(String displayName, Material material, ConfigurationSection config) { this.displayName = ChatColor.translateAlternateColorCodes('&', displayName); this.material = material; this.config = config; } /** * Check if an item held is this weapon. * * @param item Item held * @return Item is this weapon? */ public boolean check(ItemStack item) { return item != null && item.getType() == material && item.hasItemMeta() && item.getItemMeta().hasDisplayName() && item.getItemMeta().getDisplayName().equals(displayName); } /** * Get the item of the weapon * * @return Make a new item and return it. */ public ItemStack getItem() { ItemStack item = new ItemStack(material, 1); ItemMeta meta = item.getItemMeta(); meta.setDisplayName(displayName); item.setItemMeta(meta); return item; } /** * Fires the weapon for the holder. * * @param holder Holder of the weapon. */ public abstract void fire(Player holder); }
242ea6b0dfbe41ac0a01cdde57c4b72e4d1ae0e5
[ "Markdown", "Java" ]
6
Java
tenjava-2014/lenis0012-t1
7bb214d7422ba02e0c46cdbb4af1f14c1db5740d
e3c3da983590353af45fe783d2a7d88251e1f95b
refs/heads/main
<file_sep>from DownloaderLibrary import downloaderBase from MLB.MLBDownloader import MLBDownloader class MLBFanduel(MLBDownloader): def __init__(self, startDate, endDate): MLBDownloader.__init__(self, 'fd') downloaderBase.__init__(self, startDate, endDate, 'MLB', 'fanduel')<file_sep># Daily Fantasy Sports Historical Data Downloader ## About The Project The purpose of this repository is to easily allow people to download historical daily fantasy sports data. Currently there is no easy way to download this data, but this repository will allow users to easily download the data with one terminal command! <br /> The current list of daily fantasy sports platforms supported: <li>NBA Fanduel</li> <br /> ## Getting Started The first step is to clone the repository. This can be done with the command ```sh git clone https://github.com/nathanhilton/DFSDownloader.git ``` After entering the created directory, the next step is to download all the necessary libaries with the command ```sh pip install -r requirements.txt ``` Now you are ready to start downloading data!<br /> <br /> ## How To Use ### Format To download the data you will need to run a terminal command with the following format ```sh python main.py start_date end_date sport platform ``` The two required parameters needed are the start date and end date in the format <br /> ### Example An example of downloading all the data from August 2020 would look like this ```sh python main.py 2020-08-01 2020-08-31 NBA Fanduel ``` <br /> ## Future Plans <li>Adding more sports and platforms</li> <file_sep>from DownloaderLibrary import downloaderBase from NFL.NFLDownloader import NFLDownloader class NFLDraftkings(NFLDownloader): def __init__(self, startDate, endDate): NFLDownloader.__init__(self, 'dk') downloaderBase.__init__(self, startDate, endDate, 'NFL', 'draftkings')<file_sep>from tqdm import tqdm from argparse import ArgumentParser from datetime import timedelta, date from NBA.NBADraftkings import NBADraftkings from NBA.NBAFanduel import NBAFanduel from NFL.NFLDraftkings import NFLDraftkings from NFL.NFLFanduel import NFLFanduel from MLB.MLBDraftkings import MLBDraftkings from MLB.MLBFanduel import MLBFanduel def main(): parser = ArgumentParser() parser.add_argument("startDate", metavar='start_date', type=str, help="starting date for downloads") parser.add_argument("endDate", metavar='end_date', type=str, help="starting date for downloads") parser.add_argument("sport", metavar='sport', type=str, help="options are NFL and NBA") parser.add_argument("website", metavar='website', type=str, help="options are Draftkings and Fanduel") args = parser.parse_args() startDate = date.fromisoformat(args.startDate) endDate = date.fromisoformat(args.endDate) sport = args.sport.lower() website = args.website.lower() deltaDate = timedelta(days=1) # checking if parameters are valid if (endDate - startDate).days < 0: raise TypeError('end date need to be after start date!') if sport == 'nba' and website == 'fanduel': downloader = NBAFanduel(startDate, endDate) elif sport == 'nba' and website == 'draftkings': downloader = NBADraftkings(startDate, endDate) elif sport == 'nfl' and website == 'fanduel': downloader = NFLFanduel(startDate, endDate) elif sport == 'nfl' and website == 'draftkings': downloader = NFLDraftkings(startDate, endDate) elif sport == 'mlb' and website == 'fanduel': downloader = MLBFanduel(startDate, endDate) elif sport == 'mlb' and website == 'draftkings': downloader = MLBDraftkings(startDate, endDate) else: print('Enter a valid combination of sport and website') return for i in tqdm(range(0, (endDate - startDate).days + 1), desc='Progess Bar: '): currentDate = startDate + (deltaDate * i) downloader.download(currentDate) print('Download Completed!\n') if __name__ == "__main__": main() <file_sep>from setuptools import setup def readme(): with open('README.md') as f: README = f.read() return README setup( name="Fanduel-Webscrape", version="1.0.14", description="A python script that will webscrape historical NBA Fanduel salary info.", long_description=readme(), long_description_content_type="text/markdown", url="https://github.com/nathanhilton/NBAFanduel", author="<NAME>", author_email="<EMAIL>", classifiers=[ "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.7", ], packages=["Fanduel_Webscrape"], include_package_data=True, install_requires=[ "requests", "beautifulsoup4>=4.0.0" ], entry_points={ "console_scripts": [ "Fanduel-Webscrape=Fanduel_Webscrape.MyApp:main", ] }, )<file_sep>from urllib.request import urlopen as uReq from bs4 import BeautifulSoup import re from datetime import datetime from DownloaderLibrary import downloaderBase class NBADownloader(downloaderBase): def __init__(self, platform_shortened): self.platform_shortened = platform_shortened def download(self, currentDate): year = str(currentDate.year) month = str(currentDate.month) day = str(currentDate.day) monthString = str(datetime.strptime(month, "%m").strftime("%B")) my_url = "http://rotoguru1.com/cgi-bin/hyday.pl?game={platform}&mon={month}&day={day}&year={year}".format(month=month, day=day, year=year, platform=self.platform_shortened) #bs4 setup stuff uClient = uReq(my_url) page_html = uClient.read() uClient.close() soup = BeautifulSoup(page_html, "html.parser") players = soup.find_all("tr") # first player is always 10 if (len(players) >= 10) : # checks if there were games that day fields = ["Name", "Position", "Points", "Salary", "Team", "Opp.", "Home/Away", "Score", "Min", "Pts", 'Rbs', 'Ast', 'Stl', 'Blk', 'To', '3PM', 'FGM', 'FGA', 'FTM', 'FTA'] rows = [] playerTracker = 0 for i in range(10,len(players)): # for the gaurds playerTracker = self.getTheStats(players, i, rows, playerTracker) if playerTracker != -1: break for i in range(playerTracker,len(players)): # for the forwards playerTracker = self.getTheStats(players, i, rows, playerTracker) if playerTracker != -1: break for i in range(playerTracker,len(players)): # for the centers playerTracker = self.getTheStats(players, i, rows, playerTracker) if playerTracker != -1: break if len(rows) != 0: filepath = self.create_folders_for_files(monthString, year) filename = filepath + '{month}-{day}-{year}.csv'.format(year=year, day=day, month=month) self.write_to_csv(filename, fields, rows) def getTheStats(self, players, i, rows, playerTracker): try: helper = players[i].find_all("td") stats = self.splitStatsIntoCatagories(str(helper[8].text)) rows.append([ players[i].find("a").text, # Name helper[0].text, # Position helper[2].text, # FDPoints re.sub('[$,]', '', helper[3].text), # Salary helper[4].text, # Team str(helper[5].text)[2:len(str(helper[5].text))], # Opponent self.homeVsAway(helper[5].text), # Home or Away helper[6].text, # Score of Game helper[7].text, # Minutes Played stats[0], # Points stats[1], # Rebounds stats[2], # Assists stats[3], # Steals stats[4], # Blocks stats[5], # Turnovers stats[6], # Three Pointers Made stats[7], # Field Goals Made stats[8], # Field Goals Attempted stats[9], # Free Throws Made stats[10] ]) # Free Throws Attempted return -1 except: return i + 2 def homeVsAway(self, opp): if opp[0] == '@': return 'away' elif opp[0] == 'v': return 'home' else: return 'messed up' def splitStatsIntoCatagories(self, stats): allStats = stats.split(' ') finalStats = [] # should be 11 long indexer = 2 indexer += self.getInfoMainStats(allStats, finalStats, indexer, 'pt') indexer += self.getInfoMainStats(allStats, finalStats, indexer, 'rb') indexer += self.getInfoMainStats(allStats, finalStats, indexer, 'as') indexer += self.getInfoMainStats(allStats, finalStats, indexer, 'st') indexer += self.getInfoMainStats(allStats, finalStats, indexer, 'bl') indexer += self.getInfoMainStats(allStats, finalStats, indexer, 'to') indexer += self.getInfoMainStats(allStats, finalStats, indexer, 'trey') indexer += self.getPercentages(allStats, finalStats, indexer, 'fg') indexer += self.getPercentages(allStats, finalStats, indexer, 'ft') return finalStats def getInfoMainStats(self, allStats, finalStats, num, stat): if (len(allStats) > num): index = allStats[num].find(stat) else: index = -1 if index != -1: finalStats.append((allStats[num])[:index]) return 1 else: finalStats.append(0) return 0 def getPercentages(self, allStats, finalStats, num, stat): if (len(allStats) > num): index = allStats[num].find(stat) else: index = -1 if index != -1: dashIndex = allStats[num].find('-') finalStats.append((allStats[num])[:dashIndex]) finalStats.append((allStats[num])[dashIndex+1:len(allStats[num])-2]) return 1 else: finalStats.append(0) finalStats.append(0) return 0 # don't believe i need this function # def getPosition(self, position): # switcher = { # 'PG': 1, # 'SG': 2, # 'SF': 3, # 'PF': 4, # 'C': 5, # } # return switcher.get(position, -1)<file_sep>from DownloaderLibrary import downloaderBase from NBA.NBADownloader import NBADownloader class NBADraftkings(NBADownloader): def __init__(self, startDate, endDate): NBADownloader.__init__(self, 'dk') downloaderBase.__init__(self, startDate, endDate, 'NBA', 'draftkings')<file_sep>from urllib.request import urlopen as uReq from bs4 import BeautifulSoup import re from datetime import datetime from DownloaderLibrary import downloaderBase class NFLDownloader(downloaderBase): def __init__(self, platform_shortened): self.platform_shortened = platform_shortened def download(self, currentDate): pass def getTheStats(self, players, i, rows, playerTracker): pass def homeVsAway(self, opp): pass def splitStatsIntoCatagories(self, stats): pass def getInfoMainStats(self, allStats, finalStats, num, stat): pass<file_sep>from DownloaderLibrary import downloaderBase from NFL.NFLDownloader import NFLDownloader class NFLFanduel(NFLDownloader): def __init__(self, startDate, endDate): NFLDownloader.__init__(self, 'fd') downloaderBase.__init__(self, startDate, endDate, 'NFL', 'fanduel')<file_sep>from DownloaderLibrary import downloaderBase from NBA.NBADownloader import NBADownloader class NBAFanduel(NBADownloader): def __init__(self, startDate, endDate): NBADownloader.__init__(self, 'fd') downloaderBase.__init__(self, startDate, endDate, 'NBA', 'fanduel')<file_sep>import csv import os class downloaderBase(): def __init__(self, startDate, endDate, sport, platform): self.startDate = startDate self.endDate = endDate self.sport = sport self.platform = platform def download(self): pass def write_to_csv(self, filename, fields, rows): with open(filename, "w", newline="") as csvfile: csvwriter = csv.writer(csvfile) csvwriter.writerow(fields) csvwriter.writerows(rows) def create_folders_for_files(self, month, year): filepath = './Stat_Sheets/{sport}_{platform}/{year}/{month}/'.format(year=year, month=month, sport=self.sport, platform=self.platform) os.makedirs(filepath, exist_ok=True) return filepath<file_sep>from DownloaderLibrary import downloaderBase from MLB.MLBDownloader import MLBDownloader class MLBDraftkings(MLBDownloader): def __init__(self, startDate, endDate): MLBDownloader.__init__(self, 'dk') downloaderBase.__init__(self, startDate, endDate, 'MLB', 'draftkings')<file_sep>beautifulsoup4==4.9.3 tqdm==4.59.0
924a92cb8644269159e83bf37861d504d9ff04d0
[ "Markdown", "Python", "Text" ]
13
Python
nathanhilton/NBAFanduel
912076c644783e88908634503c512f9c34d2bc58
adfb4cface9d4e2e8d537324ee07d296275cf110
refs/heads/master
<file_sep>json.array!(@traffic_jams) do |traffic_jam| json.extract! traffic_jam, :CurrentStation, :NextStation, :level json.url traffic_jam_url(traffic_jam, format: :json) end <file_sep>json.extract! @car, :way, :plate, :created_at, :updated_at <file_sep>json.array!(@list_stations) do |list_station| json.extract! list_station, :list_number, :station_id json.url list_station_url(list_station, format: :json) end <file_sep>class Tracking < ActiveRecord::Base belongs_to :car belongs_to :station before_save :add_station private def add_station unless Tracking.first.nil? @stations = Station.all @stations.each do |s| if s.in_station? lat, long self.station = s break end end end end end <file_sep>gpsTracking =========== Webpage Database: postgreSQL Install with nginx <file_sep>json.extract! @tracking, :lat, :long, :car_id, :created_at, :updated_at <file_sep>module StationsHelper def get_station_maps station if not station.nil? map = "http://maps.googleapis.com/maps/api/staticmap?&zoom=17&size=800x600&scale=1&maptype=roadmap&" map += station.to_p_maps + "&" map += "sensor=false" return map end end def get_station_all_maps @stations = Station.all if not @stations.nil? map = "http://maps.googleapis.com/maps/api/staticmap?&zoom=17&size=800x600&scale=2&maptype=roadmap&" @stations.each do |station| map += station.to_p_maps + "&" end map += "sensor=false" return map end end end <file_sep>json.extract! @car_style, :style, :seat, :created_at, :updated_at <file_sep>class HomeController < ApplicationController helper :home def index @users = User.all @tracking = Station.find(last_tracked.station_id) @car = Car.find(last_tracked.car_id) @next_station = Station.find(next_stations) current = ListStation.find_all_by_station_id(last_tracked.station_id).first @time = current.next_time all_station = ListStation.where("list_number != 16") index_current = all_station.index((all_station.find_by_list_number(current.list_number))) @temp_station = all_station[(index_current+1)..all_station.size] + all_station[0..index_current-1] @all_station = {} @temp_station.each do |s| @all_station[Station.find(s.station_id).name] = Station.find(s.station_id).id end end def current_station @tracking = last_tracked render :json => @tracking end def data_stations @stations = Station.all render :json => @stations end def color_station station = Station.find(params[:id]) current = Tracking.last color = "red" if station.in_station? current.lat, current.long color = "blue" end data = { :color => color} render :json => data end def total_time_current_to_select select = ListStation.find_all_by_station_id(params[:id]).first current = ListStation.find_all_by_station_id(last_tracked.station_id).first all_station = ListStation.where("list_number != 16") index_current = all_station.index((all_station.find_by_list_number(current.list_number))) temp_station = all_station[(index_current)..all_station.size] + all_station[0..index_current-1] select_to_station = temp_station[temp_station.index(current)..temp_station.index(select)] total_time = 0 select_to_station.each do |s| total_time +=s.next_time end render :json => total_time end private def is_late lastTrack = Tracking.last end end <file_sep>class TrafficJam < ActiveRecord::Base belongs_to :station validate :can_add def can_add traffic = TrafficJam.last if traffic.station_id == self.station_id return Time.now - traffic.created_at > 3000 else return true end end end <file_sep>module HomeHelper def get_maps_all @stations = Station.all if not @stations.nil? map = "http://maps.googleapis.com/maps/api/staticmap?&zoom=16&size=800x600&scale=2&maptype=roadmap&" @stations.each do |station| map += station.to_api + "&" end map += "sensor=false" return map end end end <file_sep>class ListStationsController < ApplicationController before_action :set_list_station, only: [:show, :edit, :update, :destroy] # GET /list_stations # GET /list_stations.json def index @list_stations = ListStation.all :order => :list_number end # GET /list_stations/1 # GET /list_stations/1.json def show end # GET /list_stations/new def new @list_station = ListStation.new end # GET /list_stations/1/edit def edit end # POST /list_stations # POST /list_stations.json def create @list_station = ListStation.new(list_station_params) respond_to do |format| if @list_station.save format.html { redirect_to @list_station, notice: 'List station was successfully created.' } format.json { render action: 'show', status: :created, location: @list_station } else format.html { render action: 'new' } format.json { render json: @list_station.errors, status: :unprocessable_entity } end end end # PATCH/PUT /list_stations/1 # PATCH/PUT /list_stations/1.json def update respond_to do |format| if @list_station.update(list_station_params) format.html { redirect_to @list_station, notice: 'List station was successfully updated.' } format.json { head :no_content } else format.html { render action: 'edit' } format.json { render json: @list_station.errors, status: :unprocessable_entity } end end end # DELETE /list_stations/1 # DELETE /list_stations/1.json def destroy @list_station.destroy respond_to do |format| format.html { redirect_to list_stations_url } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_list_station @list_station = ListStation.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def list_station_params params.require(:list_station).permit(:list_number, :station_id, :next_time) end end <file_sep>class CarStylesController < ApplicationController before_action :set_car_style, only: [:show, :edit, :update, :destroy] # GET /car_styles # GET /car_styles.json def index @car_styles = CarStyle.all end # GET /car_styles/1 # GET /car_styles/1.json def show end # GET /car_styles/new def new @car_style = CarStyle.new end # GET /car_styles/1/edit def edit end # POST /car_styles # POST /car_styles.json def create @car_style = CarStyle.new(car_style_params) respond_to do |format| if @car_style.save format.html { redirect_to @car_style, notice: 'Car style was successfully created.' } format.json { render action: 'show', status: :created, location: @car_style } else format.html { render action: 'new' } format.json { render json: @car_style.errors, status: :unprocessable_entity } end end end # PATCH/PUT /car_styles/1 # PATCH/PUT /car_styles/1.json def update respond_to do |format| if @car_style.update(car_style_params) format.html { redirect_to @car_style, notice: 'Car style was successfully updated.' } format.json { head :no_content } else format.html { render action: 'edit' } format.json { render json: @car_style.errors, status: :unprocessable_entity } end end end # DELETE /car_styles/1 # DELETE /car_styles/1.json def destroy @car_style.destroy respond_to do |format| format.html { redirect_to car_styles_url } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_car_style @car_style = CarStyle.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def car_style_params params.require(:car_style).permit(:name, :seat) end end <file_sep>class Car < ActiveRecord::Base validates_uniqueness_of :gps_name, :message => "This user has yet a uniqness gps's name" belongs_to :car_style has_many :tracking_cars end <file_sep>GpsTracking::Application.routes.draw do resources :traffic_jams get "stations/map/:id", to: "stations#show_maps", as: "maps_station" get "data/data_stations" => "home#data_stations" get "data/data_current", to: "home#current_station", as:"current" get "data/color_station/:id", to: "home#color_station" get "stations/json/:id", to: "stations#show_json", as: "stations_json" resources :traffic_jams resources :list_stations resources :stations resources :car_styles resources :cars root :to => "home#index" devise_for :users, :controllers => {:registrations => "registrations"} resources :users scope 'api', defaults: {format: 'json'} do scope 'track' do resources :trackings get "next_station", to: "trackings#next_station" get "show_route", to: "trackings#show_route" get "current_select/:id", to: "home#total_time_current_to_select" end end end<file_sep>class AddPicToStations < ActiveRecord::Migration def change add_column :stations, :station_current_pic, :string add_column :stations, :station_next_pic, :string add_column :stations, :station_normal_pic, :string end end <file_sep>class TrackingsController < ApplicationController before_action :set_tracking, only: [:show, :edit, :update, :destroy] # GET /trackings # GET /trackings.json def index @trackings = Tracking.all #respond_with @trackings end # GET /trackings/1 # GET /trackings/1.json def show end # GET /trackings/new def new @tracking = Tracking.new end # GET /trackings/1/edit def edit end # POST /trackings # POST /trackings.json def create @tracking = Tracking.new(tracking_params) #respond_with tracking_params.create(tracking_params) respond_to do |format| if @tracking.save add_traffic_jam format.html { redirect_to @tracking, notice: 'Tracking was successfully created.' } format.json { render action: 'show', status: :created, location: @tracking } else format.html { render action: 'new' } format.json { render json: @tracking.errors, status: :unprocessable_entity } end end end def add_traffic_jam current_station = Station.find(last_tracked.station_id) time = ListStation.find_all_by_list_number(current_station).first.next_time level = overtime? time if level == 1 traffic = TrafficJam.create(:station_id => current_station.id, level: overtime?(time) ) traffic.save! if traffic.valid? elsif level == 2 and current_station == Tracking.last.station last = TrafficJam.last if last.station != current_station traffic = TrafficJam.create(:station_id => current_station.id, level: overtime?(time) ) traffic.save else last.update(level: 2) last.save end end end # PATCH/PUT /trackings/1 # PATCH/PUT /trackings/1.json def update respond_to do |format| if @tracking.update(tracking_params) format.html { redirect_to @tracking, notice: 'Tracking was successfully updated.' } format.json { head :no_content } else format.html { render action: 'edit' } format.json { render json: @tracking.errors, status: :unprocessable_entity } end end end # DELETE /trackings/1 # DELETE /trackings/1.json def destroy @tracking.destroy respond_to do |format| format.html { redirect_to trackings_url } format.json { head :no_content } end end def next_station result = next_stations render json: result end def show_route current_station = Station.find(last_tracked.station_id) next_station = Station.find(next_stations.first) time = ListStation.find_all_by_list_number(current_station).first.next_time result = {"current" => current_station, "next" => next_station, "color" => color_route(overtime?(time)), "time" => time } render json: result end private # Use callbacks to share common setup or constraints between actions. def set_tracking @tracking = Tracking.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def tracking_params params.require(:tracking).permit(:lat, :long, :car_id) end def color_route number if number == 1 return "orange" elsif number == 2 return "red" else return "green" end end end <file_sep>class CarStyle < ActiveRecord::Base has_and_belongs_to_many :cars end <file_sep>json.array!(@trackings) do |tracking| json.extract! tracking, :lat, :long, :car_id json.url tracking_url(tracking, format: :json) end <file_sep>class AddNextTimeToListStation < ActiveRecord::Migration def change add_column :list_stations, :next_time, :integer end end <file_sep>class Station < ActiveRecord::Base mount_uploader :station_current_pic, StationPicUploader mount_uploader :station_next_pic, StationPicUploader mount_uploader :station_normal_pic, StationPicUploader has_many :trackings has_one :list_station has_many :traffic_jams def in_station? px,py x = [self.x1, self.x2, self.x3, self.x4] y = [self.y1, self.y2, self.y3, self.y4] tri = [] (0..3).each do |i| l_x = [x[i-1], x[i]] + [px] l_y = [y[i-1], y[i]] + [py] tri = tri + [area_cal(l_x, l_y)] end sum_tri = sum_area_method(tri) area_rec = area_cal(x,y) diff = (area_rec - sum_tri).abs return diff < 10**-10 #if in area is true end def to_api "markers=color:green%7Clabel:#{(station+64).chr}%7C#{lat},#{lng}" end def to_p_maps self.to_api + "&"+ "markers=color:blue%7Clabel:1%7C#{x1},#{y1}&" + "markers=color:blue%7Clabel:2%7C#{x2},#{y2}&" + "markers=color:blue%7Clabel:3%7C#{x3},#{y3}&" + "markers=color:blue%7Clabel:4%7C#{x4},#{y4}&" end private def area_cal (x, y) sum_area = 0 (1..(x.length-1)).each do |i| sum_area = sum_area + (y[i-1]*x[i]) - (y[i]*x[i-1]) end sum_area = sum_area + (x[0]*y[-1])-(x[-1]*y[0]) area = (sum_area/2).abs area end def sum_area_method(area_list) area_list.inject(:+) end end<file_sep>class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception skip_before_action :verify_authenticity_token, if: :json_request? rescue_from CanCan::AccessDenied do |exception| redirect_to root_path, :alert => exception.message end def json_request? request.format.json? end def before_station number = last_tracked.station_id all = Tracking.all all.reverse! all.each do |tracking| if tracking.station_id == number and not tracking.station_id.nil? @p_first = Tracking.where("id <= #{tracking.id}").order(id: :desc) @p_first.each do |tracking| if tracking.station_id != number and not tracking.station_id.nil? @dec_tracking = Tracking.where("id <= #{tracking.id}").order(id: :desc) @dec_tracking.each do |tracked| if (tracked.station_id != number) and not tracked.station_id.nil? return tracked.station_id elsif tracked.station_id.nil? return 0 end end end end end end end def next_stations before_id = before_station current_station_id = last_tracked.station_id result = [] if not current_station_id.nil? cur_index = ((ListStation.find_all_by_station_id current_station_id)).first.list_number before_index = before_id != 0 ? (ListStation.find_by_station_id(before_id)).list_number : 1 before_before_index = before_id != 0 ? (ListStation.find_by_station_id(before_station before_index)).list_number : 1 if cur_index == 1 result.push(ListStation.find_by_station_id(2).station_id) elsif cur_index == 2 and cur_index < before_index result.push(ListStation.first.station_id) else (ListStation.find_all_by_list_number(cur_index + 1)).each do |i| result.push(i.station_id) end end end return result end def last_tracked Tracking.where("Trackings.station_id IS NOT NULL").last end def overtime? time start_time = station_first_track.created_at last_time = Time.now if last_time - start_time >= time*3 return 2 elsif last_time - start_time >= time*2 return 1 else return 0 end end private def station_first_track current_station = last_tracked.station_id latest = Tracking.where("Trackings.station_id IS NOT NULL").last(200) latest.reverse! latest.each_with_index do |tracking,i| if latest[i+1].station_id != current_station and not tracking.station_id.nil? return tracking end end end end <file_sep>json.extract! @list_station, :list_number, :station_id, :created_at, :updated_at <file_sep># Be sure to restart your server when you modify this file. GpsTracking::Application.config.session_store :cookie_store, key: '_gpsTracking_session' <file_sep>class TrafficJamsController < ApplicationController before_action :set_traffic_jam, only: [:show, :edit, :update, :destroy] # GET /traffic_jams # GET /traffic_jams.json def index @traffic_jams = TrafficJam.all end # GET /traffic_jams/1 # GET /traffic_jams/1.json def show end # GET /traffic_jams/new def new @traffic_jam = TrafficJam.new end # GET /traffic_jams/1/edit def edit end # POST /traffic_jams # POST /traffic_jams.json def create @traffic_jam = TrafficJam.new(traffic_jam_params) respond_to do |format| if @traffic_jam.save format.html { redirect_to @traffic_jam, notice: 'Traffic jam was successfully created.' } format.json { render action: 'show', status: :created, location: @traffic_jam } else format.html { render action: 'new' } format.json { render json: @traffic_jam.errors, status: :unprocessable_entity } end end end # PATCH/PUT /traffic_jams/1 # PATCH/PUT /traffic_jams/1.json def update respond_to do |format| if @traffic_jam.update(traffic_jam_params) format.html { redirect_to @traffic_jam, notice: 'Traffic jam was successfully updated.' } format.json { head :no_content } else format.html { render action: 'edit' } format.json { render json: @traffic_jam.errors, status: :unprocessable_entity } end end end # DELETE /traffic_jams/1 # DELETE /traffic_jams/1.json def destroy @traffic_jam.destroy respond_to do |format| format.html { redirect_to traffic_jams_url } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_traffic_jam @traffic_jam = TrafficJam.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def traffic_jam_params params.require(:traffic_jam).permit(:station_id, :level) end end <file_sep>module Api module Track class Api::Track::TrackingsController < ApplicationController before_action :set_tracking, only: [:show, :edit, :update, :destroy] respond_to :json # GET /trackings # GET /trackings.json def index @trackings = Tracking.all respond_with @trackings end # GET /trackings/1 # GET /trackings/1.json def show end # GET /trackings/new def new @tracking = Tracking.new end # GET /trackings/1/edit def edit end # POST /trackings # POST /trackings.json def create respond_with tracking_params.create(tracking_params) end private # Use callbacks to share common setup or constraints between actions. def set_tracking @tracking = Tracking.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def tracking_params params.require(:tracking).permit(:lat, :long, :car_id) end end end end <file_sep>json.extract! @traffic_jam, :CurrentStation, :NextStation, :level, :created_at, :updated_at <file_sep>json.array!(@car_styles) do |car_style| json.extract! car_style, :style, :seat json.url car_style_url(car_style, format: :json) end
3536ac942422f9d3f4d455eef4851924c1f3e6ab
[ "Markdown", "Ruby" ]
28
Ruby
Negimatsu/gpsTracking
7bbb43562785941a693f473a1d70ba72edfe0630
50bb67c5594706f93633ec98fa6c2758837d034a
refs/heads/master
<file_sep>void modeSafe() { // Only transceiver uplink //ADCSControl(); } <file_sep>// SD card drivers. Look up https://github.com/greiman/SdFat <file_sep>#ifndef STD_TYPES_H #define STD_TYPES_H #include <Arduino.h> /* * Incomplete. May not be necessary. */ // template<typename Data> // class Vector{ // public: // Vector(): d_size(0), d_capacity(0), data(0) {}; // Vector(size_t _capacity): d_size(0), d_capacity(_capacity), data(0) { // data = (Data *) malloc(d_capacity * sizeof(Data) ); // }; // void push_back(Data _data); // Data const &operator[](size_t idx) const { return d_data[idx] }; // Data &operator[](size_t idx) { return d_data[idx] }; // Vector &operator=(Vector const &other); // Vector &operator<<(Data _data) { push_back(_data); } // private: // size_t d_size; // size_t d_capacity; // Data* data; // }; /* * */ namespace newstd{ /* * Nodes for LinkedList */ template<class Data> struct Node{ Data data; Node* next; Node(Data _data) : data(_data), next(NULL) {} }; template<class Data> class LinkedList{ private: Node* head; Node* curr; Node* tail; size_t idx; size_t size; public: LinkedList(Data _data); LinkedList(); void append(Data _new); // void remove(void); // void remove_after(size_t remove_after_idx); Node* get_current(void){ return curr }; // Return current Node* traverse(void); // Return current node and increment. Node* reset(void){ curr = head; return curr; }; // Reset to head. }; }; #endif<file_sep>#include <Arduino.h> float* temperatureAcquire(void) // Function which gets the temperature sensor A/D converted values and converts to temperature in degrees C { static float tempSensorResults[2]; // Declare array to store temperature results to be returned int analogtempVal_RFD=analogRead(A6); // Read analog input from temperature sensor on RFD module and battery int analogtempVal_Battery=analogRead(A7); // ##########CHANGE TO A6 (RFD temp) and A7 (Battery temp) for IDUINO DUE########## // A/D value to temperature (in degrees C) value conversion algorithm from https://tkkrlab.nl/wiki/Arduino_KY-013_Temperature_sensor_module double interm_temp_RFD = log(10000.0*((1024.0/analogtempVal_RFD-1))); interm_temp_RFD = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * interm_temp_RFD * interm_temp_RFD))* interm_temp_RFD); float temp_RFD = interm_temp_RFD - 272.35; double interm_temp_Battery = log(10000.0*((1024.0/analogtempVal_Battery-1))); interm_temp_Battery = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * interm_temp_Battery * interm_temp_Battery))* interm_temp_Battery); float temp_Battery = interm_temp_Battery - 272.35; tempSensorResults[0] = temp_RFD; // Store temperature values to an array tempSensorResults[1] = temp_Battery; return tempSensorResults; // Return array } void temperatureSetup(void) // Function to set up the analog inputs for the temperature sensors { //int A0 = 54; //int A1 = 55; pinMode(A0, INPUT); // Set analog in pins to input ##########CHANGE TO A6 (RFD temp) and A7 (Battery temp) for IDUINO DUE########## pinMode(A1, INPUT); } <file_sep>#include <Adafruit_MCP9808.h> float* temperatureAcquire(void); // Prototype for function which returns results from INA219 current sensor void temperatureSetup(void); // Prototype for function which sets up float *temperatureData; // Pointer to returned array of current sensor results Adafruit_MCP9808 tempsensor = Adafruit_MCP9808(); <file_sep>// Import the TinyGPS library #include <TinyGPS.h> #include "gps.h" TinyGPS gps; // Set up variables int GPS_lock = 0; int GPS_lock_new = 0; int GPS_chars, GPS_sentences, GPS_failed_checksum; // Set up variables to read long GPS_lat, GPS_lon; unsigned long GPS_fix_age, GPS_date, GPS_time, GPS_speed, GPS_course, chars; unsigned short sentences, failed_checksum; void GPSSetup() { Serial1.begin(9600); int GPS_TP_PIN = 22; int GPS_EN_PIN = 23; pinMode(GPS_TP_PIN, INPUT); pinMode(GPS_EN_PIN, OUTPUT); digitalWrite(GPS_EN_PIN, HIGH); } void GPSAcquire() { // Check for characters to read while (Serial1.available() > 0) { //Serial.println("Reading GPS data..."); int c = Serial1.read(); if (gps.encode(c)) { Serial.println("GPS data acquired"); break; } //SerialUSB.print(char(c)); } gps.get_position(&GPS_lat, &GPS_lon, &GPS_fix_age); gps.get_datetime(&GPS_date, &GPS_time, &GPS_fix_age); GPS_speed = gps.speed(); GPS_course = gps.course(); } <file_sep>/* CSP Satellite Code 2016 */ /* * High-level overview of code: * Main loop * - Listens for serial input from USB for debugging * - Listens for data received over RFD * - Process data in the background */ /* Include libraries */ #include <TimedAction.h> #include <SD.h> #include "temperature.h" #include "current.h" #include "gps.h" #include "ADCS.h" #include "payloadData.h" /* Define constants for satellite modes */ #define MODE_INITIATION 0 #define MODE_SAFE 1 #define MODE_RECOVERY 2 #define MODE_STANDBY 3 #define MODE_PAYLOAD 4 #define MODE_TRANSMISSION 5 int mode; /* Debugging to test timers */ int internal = 0; void toggleInternal(){ if (internal == 0) { digitalWrite(LED_BUILTIN, HIGH); internal = 1; } else { digitalWrite(LED_BUILTIN, LOW); internal = 0; } } int external = 0; int externalPin = 22; void toggleExternal() { if (external == 0) { digitalWrite(externalPin, HIGH); external = 1; } else { digitalWrite(externalPin, LOW); external = 0; } } // Holds flag to initiate command processing int serialCommandAvailable = false; // Stores a single input character char input; // Stores the total command String command = ""; // Stores the motor drive speeds char drivex = 0, drivey = 0, drivez = 0; void serialInterface() { // Check if there is a command to execute if (serialCommandAvailable) { Serial.println(command); // Execute the command if (command == "START-TRANSMITTER") { } else if (command == "STOP-TRANSMITTER") { } else if (command == "DELETE-DATA") { // Delete data // Read in timestamp Serial.println("All satellite functions are halted - specify timestamp"); bool lineReceived = false; String timestampString = ""; char charTimestamp; // Read data until a new line character while (!lineReceived) { if (Serial.available()) { charTimestamp = Serial.read(); if (charTimestamp == '\n') { // We have received a command lineReceived = true; } else { // Append the new character timestampString = timestampString + charTimestamp; } } } // Check the timestamp Serial.println("Timestamp received: " + timestampString); int timestampInteger = timestampString.toInt(); if (timestampInteger == 0) { Serial.println("Timestamp is not an integer."); } else { Serial.println("Timestamp is valid, deleting files..."); // Loop through the files on the SD card File dir = SD.open("/"); File entry; String fileTimestampString; int fileTimestampInt; String entryName; while (true) { entry = dir.openNextFile(); if (!entry) { break; } else { // Get the file name entryName = entry.name(); // Convert to int fileTimestampInt = entryName.toInt(); if (fileTimestampInt) { fileTimestampInt = fileTimestampInt % 10000000; if (fileTimestampInt < timestampInteger % 10000000) { // Delete the file SD.remove(entryName); Serial.println("Deleted file " + entryName); } } } entry.close(); } } // Check if it is valid } else if (command == "MODE-SAFE") { Serial.println("Entering safe mode..."); mode = MODE_SAFE; } else if (command == "MODE-RECOVERY") { Serial.println("Entering recovery mode..."); mode = MODE_RECOVERY; } else if (command == "MODE-STANDBY") { Serial.println("Entering standby mode..."); mode = MODE_STANDBY; } else if (command == "MODE-PAYLOAD") { Serial.println("Entering payload mode..."); mode = MODE_PAYLOAD; } else if (command == "MODE-TRANSMISSION") { Serial.println("Entering transmission mode..."); mode = MODE_TRANSMISSION; } else if (command == "DRIVE-X-PLUS") { // AIN1 digitalWrite(31, HIGH); // AIN2 digitalWrite(30, LOW); drivex++; analogWrite(2, drivex); } else if (command == "DRIVE-X-MINUS") { digitalWrite(31, HIGH); digitalWrite(30, LOW); drivex--; analogWrite(2, drivex); } else if (command == "DRIVE-Y-PLUS") { // CIN 1 digitalWrite(10, HIGH); // CIN 2 digitalWrite(9, LOW); drivey++; analogWrite(2, drivey); } else if (command == "DRIVE-Y-MINUS") { // CIN 1 digitalWrite(10, HIGH); // CIN 2 digitalWrite(9, LOW); drivey--; analogWrite(2, drivey); } else if (command == "DRIVE-Z-PLUS") { // DIN 1 digitalWrite(11, HIGH); // DIN 2 digitalWrite(12, LOW); drivez++; analogWrite(13, drivez); } else if (command == "DRIVE-Z-MINUS") { // DIN 1 digitalWrite(11, HIGH); // DIN 2 digitalWrite(12, LOW); drivez--; analogWrite(13, drivez); } else { // Invalid command Serial.println("Invalid command"); } // Reset the flag serialCommandAvailable = false; command = ""; // If there isn't a command to execute, read commands } else { // Check if there is data to read while (Serial.available() > 0 && !serialCommandAvailable) { // Get a single character input = Serial.read(); // Check for newline to mark the end of a command if (input == '\n') { serialCommandAvailable = true; // Store the command } else { command = command + input; } } } } //create a couple timers that will fire repeatedly every x ms TimedAction internalThread = TimedAction(1000, toggleInternal); TimedAction externalThread = TimedAction(2000, toggleExternal); // Check serial buffer once every second TimedAction serialThread = TimedAction(1000, serialInterface); // Threads for individual modes TimedAction modeSafeThread = TimedAction(1000, modeSafe); TimedAction modePayloadThread = TimedAction(1000, modePayload); TimedAction modeRecoveryThread = TimedAction(1000, modeRecovery); TimedAction modeStandbyThread = TimedAction(1000, modeStandby); TimedAction modeTransmissionThread = TimedAction(1000, modeTransmission); // Thread to acquire telemetry TimedAction acquireTelemetryThread = TimedAction(5000, acquireTelemetry); TimedAction ADCSThread = TimedAction(100, ADCSControl); void setup() { Serial.begin(57600); Serial.println("Booting the CSP..."); SerialUSB.begin(57600); SerialUSB.print("hello"); /* Place the satellite in initiation mode */ mode = MODE_INITIATION; // Set up the current sensors currentSetup(); // Set up the temperature sensors temperatureSetup(); // Set up the GPS GPSSetup(); // Set up the reaction wheels ADCSSetup(); // Set up the SD card bool SDStatus = SD.begin(4); if (SDStatus == false) { Serial.println("SD card not detected."); } else { Serial.println("SD card detected."); } // Set up the CCD payloadDataSetup(); // Set up the motors pinMode(32, OUTPUT); pinMode(31, OUTPUT); pinMode(30, OUTPUT); pinMode(8, OUTPUT); pinMode(9, OUTPUT); pinMode(10, OUTPUT); pinMode(11, OUTPUT); pinMode(12, OUTPUT); pinMode(13, OUTPUT); pinMode(2, OUTPUT); digitalWrite(32, HIGH); /* // AIN1 digitalWrite(31, HIGH); // AIN2 digitalWrite(30, LOW); drivex++; drivex = 10; analogWrite(2, drivex); // AIN1 digitalWrite(9, HIGH); // AIN2 digitalWrite(10, LOW); drivex++; drivex = 10; analogWrite(8, drivex); // AIN1 digitalWrite(11, HIGH); // AIN2 digitalWrite(12, LOW); drivex++; drivex = 10; analogWrite(13, drivex);*/ // Test driving the motors /* Place the satellite into standby mode */ Serial.println("CSP booted. Entering standby mode..."); mode = MODE_STANDBY; pinMode(LED_BUILTIN, OUTPUT); pinMode(externalPin, OUTPUT); } void loop() { /* Execute code depending on the satellite mode */ switch(mode) { case MODE_INITIATION: break; case MODE_SAFE: modeSafeThread.check(); break; case MODE_RECOVERY: Serial.println("Recovery mode..."); modeRecoveryThread.check(); Serial.println("Recover mode...2"); break; case MODE_STANDBY: modeStandbyThread.check(); break; case MODE_PAYLOAD: modePayloadThread.check(); break; case MODE_TRANSMISSION: modeTransmissionThread.check(); break; default: // Invalid mode - coding error. while (1) { Serial.println("Mode error"); delay(5000); } break; } // Check threads internalThread.check(); externalThread.check(); serialThread.check(); } <file_sep>#include <Arduino.h> void readCCD(); void sendData(); void payloadDataSetup(); <file_sep>#include "serial_command.h" // Develop a command interpreting module. Define enums. Also a CRC functionality. <file_sep>void modeStandby() { // Telemetry // Transceiver uplink on full power acquireTelemetryThread.check(); } <file_sep>void currentSetup(void); // Returns results from INA219 current sensor float* currentAcquire(void); // Initialises the current sensor float *currentData; // Pointer to returned array of current sensor results <file_sep>/* Arduino Protothreading Example v1.0 by <NAME> (@ReanimationXP) 1/12/2016 */ //COMPONENTS /* This code was made using the Sunfounder Arduino starter kit's blue LCD. It can be found at Amazon.com in a variety of kits. */ //THIRD-PARTY LIBRARIES //these must be manually added to your Arduino IDE installation //see sites for details. //gives us the ability to do a foreach loop: //http://playground.arduino.cc/Code/Utility //#include <Utility.h> //allows us to set actions to perform on separate timed intervals //http://playground.arduino.cc/Code/TimedAction //http://wiring.uniandes.edu.co/source/trunk/wiring/firmware/libraries/TimedAction #include <TimedAction.h> int internal = 0; void toggleInternal(){ if (internal == 0) { digitalWrite(LED_BUILTIN, HIGH); internal = 1; } else { digitalWrite(LED_BUILTIN, LOW); internal = 0; } } int external = 0; int externalPin = 22; void toggleExternal() { if (external == 0) { digitalWrite(externalPin, HIGH); external = 1; } else { digitalWrite(externalPin, LOW); external = 0; } } //create a couple timers that will fire repeatedly every x ms TimedAction internalThread = TimedAction(1000, toggleInternal); TimedAction externalThread = TimedAction(2000, toggleExternal); void setup() { pinMode(LED_BUILTIN, OUTPUT); pinMode(externalPin, OUTPUT); } void loop() { //check on our threads. based on how long the system has been //running, do they need to fire and do work? if so, do it! internalThread.check(); externalThread.check(); } <file_sep>void acquireTelemetry() { // Read data from 3.3V current sensor // Read data from 5V current sensor // Read data from battery current currentData = currentAcquire(); // Read data from RFD temperature sensor // Read data from battery temperature sensor // Read data from external temperature sensor temperatureData = temperatureAcquire(); // Get the time (GPS_time) GPSAcquire(); // Save to disk // Check for GPS time acquisition if (GPS_time == -1 && 0) { // GPS time has not been acquired. Do not save WOD data. Serial.println("Time is not available. WOD data will not be saved..."); } else { String filename = String(GPS_time % 10000000); File file = SD.open(filename, FILE_WRITE); if (!file) { Serial.println("Could not open file for WOD data"); } else { file.println("Battery bus current (mA): " + String(currentData[1])); file.println("3.3V bus current (mA): " + String(currentData[3])); file.println("5V bus current (mA): " + String(currentData[5])); file.println("RFD temperature (C): " + String(temperatureData[0])); file.println("Battery temperature (C): " + String(temperatureData[1])); file.close(); } Serial.println("WOD data at time " + String(GPS_time)); } // Send the data over RFD/Debug Serial.println("Battery bus current (mA): " + String(currentData[1])); Serial.println("3.3V bus current (mA): " + String(currentData[3])); Serial.println("5V bus current (mA): " + String(currentData[5])); Serial.println("RFD temperature (C): " + String(temperatureData[0])); Serial.println("Battery temperature (C): " + String(temperatureData[1])); } <file_sep>#include "payloadData.h" #define SH 35 // #define ICG 36 // integration clear gate #define MCLK 3 // master clock uint8_t buffer[800]; uint8_t avg = 0; char cmdBuffer[16]; int cmdIndex; int exposureTime = 20; long compareVal = 89; char MCLKState = 0; // Character holding the current output of MCLK void payloadDataSetup() { // put your setup code here, to run once: uint8_t val; // Initialize the clocks. //DDRB |= (SH | ICG | MCLK); // Set the clock lines to outputs pinMode(MCLK, OUTPUT); pinMode(SH, OUTPUT); pinMode(ICG, OUTPUT); //CLOCK |= ICG; // Set the integration clear gate high. digitalWrite(ICG, HIGH); // Enable the serial port. //Serial.begin(115200); // Setup timer2 to generate a 470kHz frequency on D11 // TCCR2A = + (0 << COM2A1) | (1 << COM2A0) | (1 << WGM21) | (0 << WGM20); // TCCR2B = (0 << WGM22) | (1 << CS20); // OCR2A = 20; // TCNT2 = 1; // Set up the timer counter interrupts digitalWrite(MCLK, LOW); // Set MCLK pin low initially *// //************************************************************************************// pmc_set_writeprotect(false); // Disable write protection on the Timer registers pmc_enable_periph_clk(TC3_IRQn); // Enable built in clock and attach to TC3 handler (for TC1 Ch0) // Set up Timer Counter module for TC1 on Ch0 to be enabled. Timer clock 4 is used (MCLK/2 Prescaling). Waveform mode enabled in UP mode with auto trigger (clock reset) on RC compare match TC_Configure(TC1, 0, TC_CMR_WAVE | TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK1); TC_SetRC(TC1, 0, compareVal); // Set up RC value to be compared to TC1 Ch0 as compareVal REG_TC1_IER0=0b00010000; // Enable RC compare interrupts on TC1 REG_TC1_IDR0=0b11101111; // Disable all other interrupts (timer counter overflow, RA, RB, etc) NVIC_ClearPendingIRQ(TC3_IRQn); // Ensure TC3 interrupts (corresponds to TC1 Ch0) are not pending /* NVIC_EnableIRQ(TC3_IRQn); // Enable TC3 interrupts __enable_irq(); // Enable interrupts TC_Start(TC1, 0); // Start the timer counter on TC1 Ch0 */ // Set the ADC clock to around 0.65MHz adc_init(ADC, SystemCoreClock, ADC_FREQ_MAX*2, ADC_STARTUP_NORM); } void readCCD(void) { NVIC_EnableIRQ(TC3_IRQn); // Enable TC3 interrupts __enable_irq(); // Enable interrupts TC_Start(TC1, 0); // Start the timer counter on TC1 Ch0 int x; uint8_t result; digitalWrite(ICG, LOW); delayMicroseconds(3); digitalWrite(SH, HIGH); delayMicroseconds(5); digitalWrite(SH, LOW); delayMicroseconds(15); digitalWrite(ICG, HIGH); delayMicroseconds(1); for (x = 0; x < 800; x++) { digitalWrite(SH, HIGH); if (x == 0) { avg = (uint8_t)(analogRead(A8) >> 2); result = (uint8_t)(analogRead(A8) >> 2); } else { result = (uint8_t)(analogRead(A8) >> 2); if (result < avg) { result = 0; } else { result -= avg; } buffer[x] = result; delayMicroseconds(20); } digitalWrite(SH, LOW); } __disable_irq(); } void sendData(void) { int x; for (x = 0; x < 800; ++x) { Serial.println(buffer[x]); } } // Interrupt service routine for TC3 (corresponds to TC1 Ch0) void TC3_Handler() { TC_GetStatus(TC1, 0); // Check status of TC1 Ch0 flag digitalWrite(MCLK, MCLKState = !MCLKState); // Toggle the output of MCLK pin } <file_sep>#include <Arduino.h> #include "std_types.h" // template<typename Data> // class Vector{ // size_t size; // Current no. of data. // size_t capacity; // Current max. capacity. // Data *data; // Data list. // public: // Vector(): size(0), capacity(0) // Vector(size_t _capacity): size(0), capacity(_capacity) {d_data = (Data *) malloc( capacity * sizeof(Data) );}; // ~Vector() { free(data) }; // private: // void resize() { }; // } // void append(Node _new); // Node* get_current(void); // Node* traverse(void); // Node* reset(void); template<class Data> newstd::LinkedList(Data _data){ Node* _new_node_ptr = (Node *) malloc ( sizeof(Node<Data>) ); _new_node_ptr->data = _data; _new_node_ptr->next = NULL; } template<class Data> newstd::LinkedList(){ } template<class Data> void newstd::LinkedList::append(Data _new){ // Create a new node. // Node _node = new newstd::Node(_new); Node* _new_node_ptr = (Node *) malloc( sizeof(Node<Data>) ); _new_node_ptr->data = _new; _new_node_ptr->next = NULL; // Let the tail point to new node. this->tail->next = &_node; this->tail = _new_node_ptr; // this->tail->next = _new_node_ptr; } template<class Data> // template<class Data> // void newstd::LinkedList::remove(void){ // }<file_sep>#ifndef GPS_FILE #define GPS_FILE 1 #include <TinyGPS.h> void GPSSetup(); void GPSAcquire(); extern unsigned long GPS_time; #endif <file_sep>// Publish-subscribe architecture for sensor data. <file_sep># payload IREC 2017 Payload code. <file_sep>//***********reactionwheelcontrol.c*****************************// // This function takes in an analog input and passes the error // through a PID loop which drives the motor. // The closer the analog input is to the desired value "SetPt", the slower // the motor spins and vise vera. // // Pin Outs // Pin 2 = PWM // Pin 30 = AIN2 // Pin 31 = AIN1 // Pin 32 = STBY // Pin A1 = Analog input, connect to potentiometer or something #include <Wire.h> #include <L3G.h> L3G gyro; //***************Tuning Variables**********************// int IntThresh = 10000; //prevents windup error. float kI = 0; //keep this low float kD =0; //0.1 ish is ok float kP = 1; // tune this later int ScaleFactor = 4; //10 bit to 8 bit conversion of drive. //Because Drive = P+I+D and P,I,D are 10 bit and drive is 8 bit int SetPt = 1; //desired analog input. Closer to this number the better //******************************************************// //Misc Variables to be defined int Integral = 0; int Last = 0; char dutyCycle = 100; void setup() { Serial.begin(9600); Wire1.begin(); if (!gyro.init()) { Serial.println("Failed to autodetect gyro type!"); while (1); } gyro.enableDefault(); // pinMode(2, OUTPUT); //PWM on PIN2 // pinMode(30, OUTPUT); //AIN2 direction pin 2 // pinMode(31, OUTPUT); //AIN1 direction pin 1 // pinMode(32, OUTPUT); //STBY, standby pin pulled high // digitalWrite(32, HIGH); // Standby pin on motor driver (pull HIGH) pinMode(8, OUTPUT); //PWM on PIN2 pinMode(9, OUTPUT); //AIN2 direction pin 2 pinMode(10, OUTPUT); //AIN1 direction pin 1 pinMode(32, OUTPUT); //STBY, standby pin pulled high digitalWrite(32, HIGH); // Standby pin on motor driver (pull HIGH) } void loop() { gyro.read(); // Acquire angular velocity readings from IMU int Actual = (int)(gyro.g.z/114); //Read z-axis angular velocity from IMU int Error = Actual; //error calc in 10bit Serial.print("Actual = "); Serial.print(Actual); //for debugging if (abs(Error) < IntThresh){ // prevent integral 'windup' Integral = Integral + Error; // accumulate the error integral } else { Integral=0; // zero it if out of bounds } float P = Error*kP; // calc proportional term float I = Integral*kI; // integral term float D = (Last-Actual)*kD; // derivative term int Drive = P + I + D; // Total drive = P+I+D (10bit) Drive = Drive/ScaleFactor; // scale Drive to be in the range 0-255 (8bit) //********************Drive the motor***************************// // This section of code drives the motor and controls direction // that the motor spins. // Drive is a 8 bit value and will saturate if above. //**************************************************************// if (Drive < 0){ // Check which direction to go. digitalWrite(10, HIGH); //CW i think, need to be callibrated later digitalWrite(9, LOW); } else { // depending on the sign of Error digitalWrite(9, HIGH); //CCW i think digitalWrite(10, LOW); } if (abs(Drive)>255) { //Drive has saturated, so set to 255 (max duty/speed) Drive=255; } if (Drive == 0){ digitalWrite(9, LOW); digitalWrite(10, LOW); } else{ analogWrite(8, abs(Drive)); // send PWM command to motor board } //**************************************************************// Last = Actual; // save current value for next time Serial.print("\tError = "); Serial.print(Error); Serial.print("\tP = "); Serial.print(P); Serial.print("\tI = "); Serial.print(I); Serial.print("\tD = "); Serial.print(D); Serial.print("\tDrive = "); Serial.print(Drive); Serial.print("\n"); //print to serial monitor } <file_sep>void ADCSSetup(); void ADCSControl(); <file_sep> typedef enum _SysMode { MODE_INITIATION = 0, MODE_SAFE, MODE_RECOVERY, MODE_STANDBY, MODE_PAYLOAD, MODE_TRANSMISSION } SysMode; // Access current state from other files. SysMode sys_get_current_mode(void); <file_sep>/* $Id$ || || @author <NAME> <<EMAIL>> || @url http://wiring.org.co/ || @url http://alexanderbrevig.com/ || @contribution <NAME> <<EMAIL>> || || @description || | Provides an easy way of triggering functions at a set interval. || | || | Wiring Cross-platform Library || # || || @license Please see cores/Common/License.txt. || */ #ifndef TIMEDACTION_H #define TIMEDACTION_H //#include <Wiring.h> #include "Arduino.h" #define NO_PREDELAY 0 class TimedAction { public: TimedAction(unsigned long interval, void (*function)()); TimedAction(unsigned long prev, unsigned long interval, void (*function)()); void reset(); void disable(); void enable(); void check(); void setInterval(unsigned long interval); private: bool active; unsigned long previous; unsigned long interval; void (*execute)(); }; #endif // TIMEDACTION_H <file_sep>void modeRecovery() { // All systems on except payload and transceiver downlink acquireTelemetryThread.check(); //ADCSThread.check(); } <file_sep>#include <Arduino.h> #include <Adafruit_INA219.h> Adafruit_INA219 ina219_battery; // Setup INA219 instances - default 0x40 offset address for battery bus Adafruit_INA219 ina219_3v3bus(0x41); // A0 bridged for 3.3V bus (0x41 offset) Adafruit_INA219 ina219_5vbus(0x44); // A1 bridged for 5V bus (0x44 offset) void currentSetup(void) // Function to set up current sensors { ina219_battery.begin(); // Initialise battery bus INA219 ina219_battery.setCalibration_32V_2A(); // Calibrate battery bus INA219 for +/- 2A range ina219_3v3bus.begin(); // Initialise 3.3V bus INA219 ina219_3v3bus.setCalibration_32V_2A(); // Calibrate 3.3V bus INA219 for +/- 2A range ina219_5vbus.begin(); // Initialise 5V bus INA219 ina219_5vbus.setCalibration_32V_2A(); // Calibrate 3V bus INA219 for +/- 2A range } float* currentAcquire(void) // Function which returns results from current sensors { float shuntvoltage_battery, busvoltage_battery, current_mA_battery, loadvoltage_battery ; // Declare variables for storing voltage and current results float shuntvoltage_3v3bus, busvoltage_3v3bus, current_mA_3v3bus, loadvoltage_3v3bus; float shuntvoltage_5vbus, busvoltage_5vbus, current_mA_5vbus, loadvoltage_5vbus; static float currentSensorResults[6]; // Declare array to store voltage and current results to be returned shuntvoltage_battery = ina219_battery.getShuntVoltage_mV(); // Get voltage drop over shunt busvoltage_battery = ina219_battery.getBusVoltage_V(); // Get voltage between Vin- and GND current_mA_battery = ina219_battery.getCurrent_mA(); // Get current pulled over shunt loadvoltage_battery = busvoltage_battery + (shuntvoltage_battery / 1000); // Calculate supply voltage on the battery bus //**************************************REMOVE AFTER TESTING**********************************************/ /*Serial.print("BATTERY BUS\n"); // Serial.print("Bus Voltage: "); Serial.print(busvoltage_battery); Serial.println(" V"); // Serial.print("Shunt Voltage: "); Serial.print(shuntvoltage_battery); Serial.println(" mV"); // Serial.print("Load Voltage: "); Serial.print(loadvoltage_battery); Serial.println(" V"); // Serial.print("Current: "); Serial.print(current_mA_battery); Serial.println(" mA"); // Serial.println(""); // delay(2000);*/ // //********************************************************************************************************/ shuntvoltage_3v3bus = ina219_3v3bus.getShuntVoltage_mV(); // Get voltage drop over shunt busvoltage_3v3bus = ina219_3v3bus.getBusVoltage_V(); // Get voltage between 3.3V bus and GND current_mA_3v3bus = ina219_3v3bus.getCurrent_mA(); // Get current pulled over shunt loadvoltage_3v3bus = busvoltage_3v3bus + (shuntvoltage_3v3bus / 1000); // Calculate overall voltage on the 3.3V bus //**************************************REMOVE AFTER TESTING**********************************************/ /*Serial.print("3V3 BUS\n"); // Serial.print("Bus Voltage: "); Serial.print(busvoltage_3v3bus); Serial.println(" V"); // Serial.print("Shunt Voltage: "); Serial.print(shuntvoltage_3v3bus); Serial.println(" mV"); // Serial.print("Load Voltage: "); Serial.print(loadvoltage_3v3bus); Serial.println(" V"); // Serial.print("Current: "); Serial.print(current_mA_3v3bus); Serial.println(" mA"); // Serial.println(""); // delay(2000);*/ // //********************************************************************************************************/ shuntvoltage_5vbus = ina219_5vbus.getShuntVoltage_mV(); // Get voltage drop over shunt busvoltage_5vbus = ina219_5vbus.getBusVoltage_V(); // Get voltage drop between 5V bus and GND current_mA_5vbus = ina219_5vbus.getCurrent_mA(); // Get current pulled over shunt loadvoltage_5vbus = busvoltage_5vbus + (shuntvoltage_5vbus / 1000); // Calculate overall voltage on the 5V bus //**************************************REMOVE AFTER TESTING**********************************************/ /*Serial.print("5V BUS\n"); // Serial.print("Bus Voltage: "); Serial.print(busvoltage_5vbus); Serial.println(" V"); // Serial.print("Shunt Voltage: "); Serial.print(shuntvoltage_5vbus); Serial.println(" mV"); // Serial.print("Load Voltage: "); Serial.print(loadvoltage_5vbus); Serial.println(" V"); // Serial.print("Current: "); Serial.print(current_mA_5vbus); Serial.println(" mA"); // Serial.println(""); // delay(2000);*/ // //********************************************************************************************************/ currentSensorResults[0] = loadvoltage_battery; // Load results into results array currentSensorResults[1] = current_mA_battery; currentSensorResults[2] = loadvoltage_3v3bus; currentSensorResults[3] = current_mA_3v3bus; currentSensorResults[4] = loadvoltage_5vbus; currentSensorResults[5] = current_mA_5vbus; return currentSensorResults; // Return results array } <file_sep>#include <Wire.h> #include <LPS.h> LPS ps; void setup() { SerialUSB.begin(9600); SerialUSB.println("lmbo"); Wire1.begin(); if (!ps.init()) { SerialUSB.println("Failed to autodetect pressure sensor!"); while (1); } ps.enableDefault(); } void loop() { float pressure = ps.readPressureMillibars(); float altitude = ps.pressureToAltitudeMeters(pressure); float temperature = ps.readTemperatureC(); SerialUSB.print("p: "); SerialUSB.print(pressure); SerialUSB.print(" mbar\ta: "); SerialUSB.print(altitude); SerialUSB.print(" m\tt: "); SerialUSB.print(temperature); SerialUSB.println(" deg C"); delay(100); } <file_sep>#include <Wire.h> //#include "Adafruit_MCP9808.h" #include <Adafruit_MCP9808.h> //**************************************REMOVE AFTER TESTING**********************************************/ Adafruit_MCP9808 tempsensor = Adafruit_MCP9808(); // //********************************************************************************************************/ float* tempsensor_acquire(void); // Prototype for function which returns results from INA219 current sensor void tempsensor_setup(void); // Prototype for function which sets up float *returnedTempSensorResults; // Pointer to returned array of current sensor results void setup() { tempsensor_setup(); // Call function to set up temperature sensors //**************************************REMOVE AFTER TESTING**********************************************/ Serial.begin(9600); // tempsensor.begin(); // //********************************************************************************************************/ } void loop() { returnedTempSensorResults = tempsensor_acquire(); // Call tempsensor_acquire function to attain temperature readings from sensors on RFD module and battery. Return result array via pointer. //**************************************REMOVE AFTER TESTING**********************************************/ Serial.print("\n"); Serial.print(returnedTempSensorResults[0]); Serial.print("\n"); Serial.print(returnedTempSensorResults[1]); Serial.print("\n"); //*************************************USED FOR MCP9808 FOR CALIBRATION***********************************/ tempsensor.shutdown_wake(0); // Don't remove this line! required before reading temp // float c = tempsensor.readTempC(); // Serial.print("Temp: "); Serial.print(c); Serial.print("*C\t"); // delay(250); // tempsensor.shutdown_wake(1); // shutdown MSP9808 - power consumption ~0.1 mikro Ampere // delay(2000); // //*********************************************************************************************************/ } void tempsensor_setup(void) // Function to set up the analog inputs for the temperature sensors { pinMode(A0, INPUT); // Set analog in pins to input ##########CHANGE TO A6 (RFD temp) and A7 (Battery temp) for IDUINO DUE########## pinMode(A1, INPUT); } float* tempsensor_acquire(void) // Function which gets the temperature sensor A/D converted values and converts to temperature in degrees C { static float tempSensorResults[2]; // Declare array to store temperature results to be returned int analogtempVal_RFD=analogRead(A0); // Read analog input from temperature sensor on RFD module and battery int analogtempVal_Battery=analogRead(A1); // ##########CHANGE TO A6 (RFD temp) and A7 (Battery temp) for IDUINO DUE########## // A/D value to temperature (in degrees C) value conversion algorithm from https://tkkrlab.nl/wiki/Arduino_KY-013_Temperature_sensor_module double interm_temp_RFD = log(10000.0*((1024.0/analogtempVal_RFD-1))); interm_temp_RFD = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * interm_temp_RFD * interm_temp_RFD))* interm_temp_RFD); float temp_RFD = interm_temp_RFD - 272.35; double interm_temp_Battery = log(10000.0*((1024.0/analogtempVal_Battery-1))); interm_temp_Battery = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * interm_temp_Battery * interm_temp_Battery))* interm_temp_Battery); float temp_Battery = interm_temp_Battery - 272.35; tempSensorResults[0] = temp_RFD; // Store temperature values to an array tempSensorResults[1] = temp_Battery; return tempSensorResults; // Return array } <file_sep>void modePayload() { // Downlink on standby // Reaction wheels on 70% power acquireTelemetryThread.check(); //ADCSControl(); // Display status Serial.println("Payload mode, acquiring data..."); readCCD(); sendData(); //pinMode(25, HIGH); // This is a guess delay(100); readCCD(); sendData(); //pinMode(25, LOW); } <file_sep>void modeTransmission() { // Payload on standby // Transceiver on downlink full power // Reaction wheels at 70% acquireTelemetryThread.check(); //ADCSControl(); } <file_sep>// Timer interrupt program: Generates an interrupt every 1 minute (or 1 second) which toggles the output on Pin 12 for the Iduino DUE Pro // This will be used later to trigger the sensors in the cubesat to take a reading every minute for the telemetry specifications and can // be modified for other timing requirements // Note: there are 3 timers (TC0, TC1, TC2) each with 3 channels -> 9 possible timer compare interrupts // Compare value to be compared to timer counter (32 bit): RC Compare value = (Desired period / (Prescaler / Master clock frequency)) // compareVal is at max 32 bits in length: 2^32 - 1 = 4294967295. This is equivalent to 6544s = 109 minutes with a 1:128 prescaler. // For period = 1s: compareVal = 1/(128/84E6) = 656250 // For period = 60s: compareVal = 60/(128/84E6) = 39375000 long compareVal = 39375000; char pin12State = 0; // Character holding the current output of Pin 12 void timerInterruptSetup(void); // Prototype for function to set up timer counter interrupts void setup() { timerInterruptSetup(); // Call function to set up timer counter interrupts //pmc_enable_sleepmode(); // **TEST**Call function to activate sleep mode and executes __WFI() which waits for an interrupt to occur. When interrupt occurs, sleep mode is deactivated. } void loop() { } // Interrupt service routine for TC3 (corresponds to TC1 Ch0) void TC3_Handler() { TC_GetStatus(TC1, 0); // Check status of TC1 Ch0 flag digitalWrite(12, pin12State = !pin12State); // Toggle the output on Pin 12 ** REMOVE AFTER TESTING** } // Function to set up the timer counter interrupts void timerInterruptSetup(void) { //******************************REMOVE AFTER TESTING *********************************// pinMode(12, OUTPUT); // Setup Pin 12 *// digitalWrite(12, LOW); // Set Pin 12 low initially *// //************************************************************************************// pmc_set_writeprotect(false); // Disable write protection on the Timer registers pmc_enable_periph_clk(TC3_IRQn); // Enable built in clock and attach to TC3 handler (for TC1 Ch0) // Set up Timer Counter module for TC1 on Ch0 to be enabled. Timer clock 4 is used (MCLK/128 Prescaling). Waveform mode enabled in UP mode with auto trigger (clock reset) on RC compare match TC_Configure(TC1, 0, TC_CMR_WAVE | TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK4); TC_SetRC(TC1, 0, compareVal); // Set up RC value to be compared to TC1 Ch0 as compareVal REG_TC1_IER0=0b00010000; // Enable RC compare interrupts on TC1 REG_TC1_IDR0=0b11101111; // Disable all other interrupts (timer counter overflow, RA, RB, etc) NVIC_ClearPendingIRQ(TC3_IRQn); // Ensure TC3 interrupts (corresponds to TC1 Ch0) are not pending NVIC_EnableIRQ(TC3_IRQn); // Enable TC3 interrupts __enable_irq(); // Enable interrupts TC_Start(TC1, 0); // Start the timer counter on TC1 Ch0 } <file_sep>// NOTE: I tried to get Sleep mode (which is an inbuilt low power mode of the processor) to work but when I measured the current draw, it was the same as that under normal operation. People on // forums seem to report the same problem. Not sure if it's a problem with the coding or wait mode just does not work so well. // This code uses an alternative way to save power found from http://www.udoo.org/forum/threads/reducing-sam3x-power-consumption-in-wait-or-sleep-mode.2176/ by turning off peripheral clocks. // Test values: 78.70 mA current draw by the Iduino DUE Pro with all periph clocks off. 161.70 mA current draw with all periph clocks on. void enablePowerSaving(void); // Prototype for function which turns off peripheral clocks to save power void disablePowerSaving(void); // Prototype for function which turns on peripheral clocks again for normal operation void setup() { pinMode(13, INPUT); // Setup Pin 13 pinMode(12, OUTPUT); // Setup Pin 12 } void loop() { if(digitalRead(13) == HIGH){ enablePowerSaving(); } else if(digitalRead(13) == LOW){ disablePowerSaving(); } } void enablePowerSaving(void) { // To save power, disable peripheral clocks which are not used // From http://www.udoo.org/forum/threads/reducing-sam3x-power-consumption-in-wait-or-sleep-mode.2176/ // NOTE: This will need to be editted such that the clocks which are necessary to 'wake up' the processor remain active pmc_disable_periph_clk(2); // real-time clock pmc_disable_periph_clk(3); // real-time timer pmc_disable_periph_clk(4); // watchdog timer // 5 = PMC power mgmt ctrl pmc_disable_periph_clk(6); // EEFC0 flash ctrl pmc_disable_periph_clk(7); // EEFC1 flash ctrl // 8 = main UART pmc_disable_periph_clk(9); // SMC_SDRAMC pmc_disable_periph_clk(10); // SDRAMC //pmc_disable_periph_clk(11); // PIO A **** KEPT ON SO THAT THE I/O PORTS ARE STILL ACTIVE **** //pmc_disable_periph_clk(12); // PIO B //pmc_disable_periph_clk(13); // PIO C //pmc_disable_periph_clk(14); // PIO D //pmc_disable_periph_clk(15); // PIO E //pmc_disable_periph_clk(16); // PIO F pmc_disable_periph_clk(17); // USART0 **** DEPENDING ON WHICH USART PORT USED FOR RF COMMS, LEAVE THAT PERIPH CLOCK RUNNING **** pmc_disable_periph_clk(18); // USART1 pmc_disable_periph_clk(19); // USART2 pmc_disable_periph_clk(20); // USART3 pmc_disable_periph_clk(21); // HSMCI pmc_disable_periph_clk(22); // TWI/I2C bus 0 pmc_disable_periph_clk(23); // TWI/I2C bus 1 pmc_disable_periph_clk(24); // SPI0 pmc_disable_periph_clk(25); // SPI1 pmc_disable_periph_clk(26); // SSC pmc_disable_periph_clk(27); // timer/counter 0 pmc_disable_periph_clk(28); // timer/counter 1 pmc_disable_periph_clk(29); // timer/counter 2 pmc_disable_periph_clk(30); // timer/counter 3 pmc_disable_periph_clk(31); // timer/counter 4 pmc_disable_periph_clk(32); // timer/counter 5 pmc_disable_periph_clk(33); // timer/counter 6 pmc_disable_periph_clk(34); // timer/counter 7 pmc_disable_periph_clk(35); // timer/counter 8 pmc_disable_periph_clk(36); // PWM pmc_disable_periph_clk(37); // ADC pmc_disable_periph_clk(38); // DAC ctrl pmc_disable_periph_clk(39); // DMA ctrl pmc_disable_periph_clk(40); // USB OTG high-speed ctrl pmc_disable_periph_clk(41); // random number generator pmc_disable_periph_clk(42); // ethernet MAC pmc_disable_periph_clk(43); // CAN controller 0 pmc_disable_periph_clk(44); // CAN controller 1 } void disablePowerSaving(void) { // Re-enable all disabled clocks // NOTE: This will need to be editted such that only peripheral clocks which are necessary are enabled. // e.g. if the random number generator is never used, keep disabled. pmc_enable_periph_clk(2); // real-time clock pmc_enable_periph_clk(3); // real-time timer pmc_enable_periph_clk(4); // watchdog timer // 5 = PMC power mgmt ctrl pmc_enable_periph_clk(6); // EEFC0 flash ctrl pmc_enable_periph_clk(7); // EEFC1 flash ctrl // 8 = main UART pmc_enable_periph_clk(9); // SMC_SDRAMC pmc_enable_periph_clk(10); // SDRAMC pmc_enable_periph_clk(11); // PIO A pmc_enable_periph_clk(12); // PIO B pmc_enable_periph_clk(13); // PIO C pmc_enable_periph_clk(14); // PIO D pmc_enable_periph_clk(15); // PIO E pmc_enable_periph_clk(16); // PIO F pmc_enable_periph_clk(17); // USART0 pmc_enable_periph_clk(18); // USART1 pmc_enable_periph_clk(19); // USART2 pmc_enable_periph_clk(20); // USART3 pmc_enable_periph_clk(21); // HSMCI pmc_enable_periph_clk(22); // TWI/I2C bus 0 pmc_enable_periph_clk(23); // TWI/I2C bus 1 pmc_enable_periph_clk(24); // SPI0 pmc_enable_periph_clk(25); // SPI1 pmc_enable_periph_clk(26); // SSC pmc_enable_periph_clk(27); // timer/counter 0 pmc_enable_periph_clk(28); // timer/counter 1 pmc_enable_periph_clk(29); // timer/counter 2 pmc_enable_periph_clk(30); // timer/counter 3 pmc_enable_periph_clk(31); // timer/counter 4 pmc_enable_periph_clk(32); // timer/counter 5 pmc_enable_periph_clk(33); // timer/counter 6 pmc_enable_periph_clk(34); // timer/counter 7 pmc_enable_periph_clk(35); // timer/counter 8 pmc_enable_periph_clk(36); // PWM pmc_enable_periph_clk(37); // ADC pmc_enable_periph_clk(38); // DAC ctrl pmc_enable_periph_clk(39); // DMA ctrl pmc_enable_periph_clk(40); // USB OTG high-speed ctrl pmc_enable_periph_clk(41); // random number generator pmc_enable_periph_clk(42); // ethernet MAC pmc_enable_periph_clk(43); // CAN controller 0 pmc_enable_periph_clk(44); // CAN controller 1 }
465461bc6596ac3c62998c9bc79314672d834840
[ "Markdown", "C", "C++" ]
30
C++
lkm1321/payload
00af45237bc99ea58ae9417038ae72ff33f24b9d
e9c37de0c8edbe18e5dd7a3321cfed52b8d8089a
refs/heads/master
<file_sep>/* pcos.h ---- PCOSIII (MWPC) Definitions */ /* */ /* Copyright (C) 1996, <NAME> */ /* */ /* Version 1.00 12-MAY-1997 by <NAME> */ #if !defined(alpha) && !defined(i586) && !defined(i686) && !defined(x86_64) /*---- others (big endian) ---- */ #if defined (__cplusplus) extern "C" { #endif /* PCOS Delimiter */ typedef struct pcos_delim{ unsigned hdr: 1; /* Identifies header word (=1) */ unsigned delim: 1; /* delimiter bit (=1) */ unsigned pcos: 4; /* PCOS number */ unsigned res: 10; /* Reserved */ } pcos_delim; /* PCOS Cluster Width */ typedef struct pcos_width{ unsigned hdr: 1; /* Identifies header word (=1) */ unsigned res: 9; /* Reserved */ unsigned width: 4; /* Cluster width */ } pcos_width; /* PCOS Data */ typedef struct pcos_data{ unsigned hdr: 1; /* Identifies header word (=0) */ unsigned wire: 15; /* wire */ } pcos_data; /* PCOS Module */ typedef struct pcos_mod{ unsigned hdr: 1; /* Identifies header word (=0) */ unsigned addr: 9; /* Logical Address */ unsigned ch: 5; /* Channel */ unsigned h: 1; /* Half bit */ } pcos_mod; /* PCOS Wire */ typedef struct pcos_chamb{ unsigned hdr: 1; /* Identifies header word (=0) */ unsigned chamb: 4; /* Logical Address (Chamber ID)*/ /* (X,U,V,-)/(1,2,3,4) */ unsigned wire: 11; /* wire id (with half bit) */ } pcos_chamb; #else /*----- Alpha or Intel-PC (little endian) ----*/ /* PCOS Delimiter */ typedef struct pcos_delim{ unsigned res: 10; /* Reserved */ unsigned pcos: 4; /* PCOS number */ unsigned delim: 1; /* delimiter bit (=1) */ unsigned hdr: 1; /* Identifies header word (=1) */ } pcos_delim; /* PCOS Cluster Width */ typedef struct pcos_width{ unsigned width: 4; /* Cluster width */ unsigned res: 9; /* Reserved */ unsigned hdr: 1; /* Identifies header word (=1) */ } pcos_width; /* PCOS Data */ typedef struct pcos_data{ unsigned wire: 15; /* wire */ unsigned hdr: 1; /* Identifies header word (=0) */ } pcos_data; /* PCOS Module */ typedef struct pcos_mod{ unsigned h: 1; /* Half bit */ unsigned ch: 5; /* Channel */ unsigned addr: 9; /* Logical Address */ unsigned hdr: 1; /* Identifies header word (=0) */ } pcos_mod; /* PCOS Wire */ typedef struct pcos_chamb{ unsigned wire: 11; /* wire id (with half bit) */ unsigned chamb: 4; /* Logical Address (Chamber ID)*/ /* (X,U,V,-)/(1,2,3,4) */ unsigned hdr: 1; /* Identifies header word (=0) */ } pcos_chamb; #if defined (__cplusplus) } #endif #endif /* Local Variables: mode: C tab-width: 2 End: */ <file_sep>/* fread_mars.c --- rawdata readout program for analyzer (mars format) Author: <NAME> Facility: Department of Physics, University of Tokyo Created: 04-MAY-1997 by <NAME> Version 1.00 04-MAY-1997 by <NAME> (fread) Version 1.22 06-MAY-1997 by <NAME> (fread) Version 2.00 03-JUN-2000 by <NAME> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #ifdef OSF1 #include <strings.h> #endif #include <time.h> #include <stdarg.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <signal.h> #include <errno.h> #include "freadin.h" #include "histogram.h" #include "lr3377.h" #include "fera.h" #include "lr3351.h" #define ENDRUNBLK 0 /* End of Fread at the end of run block */ //FLAG extern int neval; extern int level; extern int swap; extern int byte_order; int parse_error; extern int nblk; static int nevt = 0; /* definitions about mars */ #define StartBlockHeader 0x0001 #define EndBlockHeader 0xffff #define DataBlockHeader 0x0000 /* read one event */ static unsigned short *read_one_event(buf, te) unsigned short *buf; unsigned short *te; { unsigned short *ptr; fera_header fera; fera_data dfera; lr3377_data d3377; lr3351_data d3351; lr3351_pat p3351; int id, ch, len, pat, c; int i; ptr = buf; while(ptr < te){ /* get the next region header */ if(!(*ptr&0x8000)){ showerr("Illegal data without header (%.4x).\n", *ptr); while(ptr<te && !(*ptr&0x8000)) ptr++; continue; } id = *ptr & 0x00ff; if(id==0x00 && ptr!=buf) /* end of event */ break; /* check the region header */ if(id&0x80){ /* 3377 */ ptr++; for(i=0; ptr<te; i++){ *(short*)&d3377 = *ptr++; if(d3377.hdr){ ptr--; break; } ch = d3377.ch; switch(id){ case 0x80: /* X1 */ dr_append(F2_WIRE_X1, (double)d3377.ch); dr_append(F2_TDC_X1, (double)d3377.data); break; case 0x81: /* X2 */ dr_append(F2_WIRE_X2, (double)d3377.ch); dr_append(F2_TDC_X2, (double)d3377.data); break; case 0x82: /* X3 */ dr_append(F2_WIRE_X3, (double)d3377.ch); dr_append(F2_TDC_X3, (double)d3377.data); break; case 0x83: /* X4 */ dr_append(F2_WIRE_X4, (double)d3377.ch); dr_append(F2_TDC_X4, (double)d3377.data); break; case 0x84: /* Y1, Y2 */ if(d3377.ch<16){ dr_append(F2_WIRE_Y1, (double)(d3377.ch&0x0f)); dr_append(F2_TDC_Y1, (double)d3377.data); }else{ dr_append(F2_WIRE_Y2, (double)(d3377.ch&0x0f)); dr_append(F2_TDC_Y2, (double)d3377.data); } break; case 0x85: /* Y3, Y4 */ if(d3377.ch<16){ dr_append(F2_WIRE_Y3, (double)(d3377.ch&0x0f)); dr_append(F2_TDC_Y3, (double)d3377.data); }else{ dr_append(F2_WIRE_Y4, (double)(d3377.ch&0x0f)); dr_append(F2_TDC_Y4, (double)d3377.data); } break; } } }else if(64<=id && id<=69){ /* 3351 SSD */ ptr++; id=(id-64)<<3; for(i=0; ptr<te; i++){ *(short*)&p3351 = *ptr++; if(p3351.hdr){ ptr--; break; } if(ptr>=te) break; pat = p3351.pat; for(ch=0; ch<8; ch++){ if(pat & (1<<ch)){ *(short*)&d3351 = *ptr++; if(d3351.ch != ch){ showerr("Inconsistency in the 3351 pattern(%xH,ch=%d) and channel data(%d).\n", pat, ch, d3351.ch); }else{ c = id+ch; dr_set(F2_3351[c],d3351.data); if(d3351.data>500) dr_append(F2_3351_HIT,c); switch(c/10){ case 0: dr_append(SSD_LX_CH, c%10); dr_append(SSD_LX_ADC, d3351.data); break; case 1: dr_append(SSD_LY_CH, c%10); dr_append(SSD_LY_ADC, d3351.data); break; case 2: dr_append(SSD_RX_CH, c%10); dr_append(SSD_RX_ADC, d3351.data); break; case 3: dr_append(SSD_RY_CH, c%10); dr_append(SSD_RY_ADC, d3351.data); break; default: break; } } } if(ptr>=te) break; } } }else{ /* FERA */ *(short*)&fera = *ptr++; len = ((fera.cnt+15) & 0x0f)+1; /* The upper line is equivalent to: len = fera.cnt==0 ? 16 : fera_cnt; */ for(i=0; i<len && ptr<te; i++){ *(short*)&dfera = *ptr++; if(dfera.hdr){ ptr--; break; }else{ ch = (id<<4)+dfera.ch; dr_set(F2_FERA[ch], dfera.data); } } } } return(ptr); } /* read_evt */ static int read_evt(buf, size) unsigned short *buf; int size; { unsigned short *ptr, *te; ptr = buf; te = &buf[size]; nevt = 0; while(ptr<te){ nevt++; dr_clear(); dr_set(BLOCK_N[0], nblk); dr_set(EVENT_N[0], nevt); dr_set(EVENT_F2[0], 1); #if 0 fprintf(stderr, "blk = %5d, evt = %5d\n", nblk, nevt); #endif /* read one event */ ptr = read_one_event(ptr, te); dr_event(); } return nevt; } /* read comment block */ static int read_com(buf) char *buf; { char com1[30], com2[30], com3[30], com4[30], com5[30]; char com6[256]; strncpy(com1, &buf[0x14], 10); com1[10]=0; strncpy(com2, &buf[0x1e], 19); com2[19]=0; strncpy(com3, &buf[0x31], 19); com3[19]=0; strncpy(com4, &buf[0x44], 19); com4[19]=0; strncpy(com5, &buf[0x57], 9); com5[9]=0; strncpy(com6, &buf[0x64], 160); com6[160]=0; showerr("%s\n", com1); showerr("%s\n", com2); showerr("%s\n", com3); showerr("%s\n", com4); showerr("%s\n", com5); showerr("%s\n", com6); return 0; } /* read block */ int read_blk_mars(buf, size) unsigned short *buf; int size; { unsigned short *ptr; int header; int evtsize; int *scalers; /* check the block header */ header = buf[0]; switch(header){ case StartBlockHeader: showerr("Run Start Block\n"); read_com((char*)buf); return(0); case EndBlockHeader: showerr("Run End Block\n"); read_com((char*)buf); return(0); case DataBlockHeader: break; default: showerr("Unknown block Header. Header = %xH\n", header); return(-1); break; } nblk = buf[1]; evtsize = min(buf[2], size)-3; scalers = (int*)&buf[buf[3]]; ptr = &buf[4]; #if 0 fprintf(stderr, "Block = %d size = %x\n", nblk, evtsize<<1); #endif /* read events */ if(!evt_blk(nblk)){ /* chack analyze block range */ (void)read_evt(ptr, evtsize); } /* read scaler */ /* not coded yet */ return(0); } /* Local Variables: mode: C tab-width: 2 End: */ <file_sep>/* fread_dst.c --- DST read/write program for analyzer (DST format) Author: <NAME> Facility: Department of Physics, University of Tokyo Created: 04-MAY-1997 by <NAME> Version 1.00 04-MAY-1997 by <NAME> (fread) Version 1.22 06-MAY-1997 by <NAME> (fread) Version 2.00 03-JUN-2000 by <NAME> */ #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <time.h> #include <string.h> #include <stdarg.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <signal.h> #include <math.h> #include <errno.h> #include "freadin.h" #include "histogram.h" #include "mtformat.h" #include "lr3377.h" #include "fera.h" #define ENDRUNBLK 0 /* End of Fread at the end of run block */ //FLAG extern int neval; extern int level; extern int swap; extern int byte_order; int parse_error; extern int nrun; extern int nblk; extern int nevt; extern int pflag; extern int cflag; static FILE *fd_write = (FILE*)NULL; static FILE *fd_read = (FILE*)NULL; static int ndstvar=0; static char *dstvar[MaxNDSTVar]; static int dstvarref[MaxNDSTVar]; static int ndstinp=0; static int dstinpref[MaxNDSTVar]; static int n_dst = 0; static size_t n_write = 0; #define MAX_DST_SIZE FFFC0000 #define DST_SIG "DST FILE 1.0" #define VAR_BEGIN "BEGIN VARIABLES" #define VAR_END "END VARIABLES" #define IND_END 0x7fffffff #define EVT_END 0x7ffffffe #define FILE_END 0x7ffffffd /* open output file return with 0 if success, otherwise return with -1 */ static int dst_open_file() { FILE *fd; char *f; char fnam[256]; f = dr_get_sval(DST_FILE); if(f==(char*)NULL || strlen(f)==0){ /* no output file is specified */ return(0); } if(n_dst==0){ sprintf(fnam, "%s", f); }else{ sprintf(fnam, "%s_%.3d", f, n_dst); } n_dst++; #if 0 fprintf(stderr, "Open DST File: %s\n", fnam); #endif fd = fopen(fnam, "w"); if(fd==NULL){ printf("Could not open output DST file '%s': %s\n",fnam, strerror(errno)); return(-1); }else{ printf("Output data to DST file: '%s'\n", fnam); } fd_write = fd; return(0); } static int dst_close_file() { if(!fd_write) return(0); fclose(fd_write); fd_write = (FILE*)NULL; } /* write header */ static int dst_write_header(char const *comment) { int i, min, max; char *name, *p, *d, c; char str[256]; if(!fd_write) return(0); fprintf(fd_write, "%s\n", DST_SIG); if(comment){ fprintf(fd_write, "%s", comment); fprintf(fd_write, "\n"); } fprintf(fd_write, "%s\n", VAR_BEGIN); /* variables to write */ name = dr_get_sval(DST_VAR); ndstvar = 0; if(name){ d = p = name; c = 1; /* any number other than 0 is OK */ for(i=0;c;i++){ c = *d++; if((!c && i) || c==':'){ if(i>255) i=255; strncpy(str, p, i); str[i] = 0x00; p = d; i = -1; fprintf(fd_write, "%s\n", str); if(ndstvar>=MaxNDSTVar){ printf("Too many DST variables (>%d)\n", MaxNDSTVar); break; } dstvar[ndstvar] = strdup(str); dr_ref_n(str, &dstvarref[ndstvar++]); } if(!c) break; } } fprintf(fd_write, "%s\n", VAR_END); return(0); } /* write data */ int dst_write_data() { int i, iv, ref, min, max, iend; double d; int error; if(!fd_write) return(0); if(dr_is_false(dr_get(DST_CONDITION))) return(0); iend = IND_END; for(iv=0; iv<ndstvar; iv++){ #if 0 fprintf(stderr, "output var '%s'\n", dstvar[iv]); #endif ref = dstvarref[iv]; min = dr_min_ref(ref); max = dr_max_ref(ref); for(i=min; i<max; i++){ if(dr_exists(d=dr_get_ref(ref,i))){ #if 0 if(nblk==5587) printf("%s[%d] = %f\n", dstvar[iv], i, d); #endif /* write index and data (double floating) */ n_write += fwrite(&i, sizeof(int), 1, fd_write)*sizeof(int); n_write += fwrite(&d, sizeof(double), 1, fd_write)*sizeof(double); } } /* write end of a variable */ n_write += fwrite(&iend, sizeof(int), 1, fd_write)*sizeof(int); } /* write end of an event */ i = EVT_END; n_write += fwrite(&i, sizeof(int), 1, fd_write)*sizeof(int); #if 0 if(n_write >= MAX_DST_SIZE){ dst_close_file(); n_write = 0; if(error = dst_open_file()) return(error); } #endif return(0); } /* check format */ int dst_chk_format(unsigned char *buf) { if(!strncmp((char*)buf, DST_SIG, strlen(DST_SIG))) return(1); return(0); } /* read header */ int dst_read_header(unsigned char *buf,int *bpos,int size) { char str[256]; unsigned char *ptrini; unsigned char *ptr; int n; ptr = ptrini = &buf[*bpos]; for(n=0;n<3;){ sscanf((char*)ptr, "%[^\n]", str); ptr = &ptr[strlen(str)+1]; #if 0 fprintf(stderr, "%s\n", str); #endif switch(n){ case 0: if(strcmp(str, DST_SIG)) return(-1); n++; break; case 1: if(!strcmp(str, VAR_BEGIN)){ n++; }else{ printf("%s\n", str); /* Output Comments */ } break; case 2: if(!strcmp(str, VAR_END)){ n++; break; } if(ndstinp>=MaxNDSTVar) break; dr_ref_n(str, &dstinpref[ndstinp++]); break; } #if 0 fprintf(stderr, "n=%d\n", n); #endif } *bpos = (long)ptr-(long)ptrini; return(1); } /* read data (one event)*/ int dst_read_data(unsigned char *buf, int *bpos, int size) { #define SWAP 0 static int first_read=1; static int ana=-1; int i, n, iv, blk; int pos; double d; unsigned char *src; unsigned char *dst; if(first_read){ first_read = 0; return(dst_read_header(buf, bpos, size)); } dr_clear(); neval++; dr_set(EVENT_DST[0], 1); pos = *bpos; for(iv=0;;){ /* read index */ if(pos>=size){ fprintf(stderr, "dst_read_data: run out of buffer (a)\n"); return(-1); } if(SWAP){ src = (unsigned char*)&buf[pos]; dst = (unsigned char*)&((&n)[1]); *(--dst) = *src++; *(--dst) = *src++; *(--dst) = *src++; *(--dst) = *src++; }else{ n = *(int*)&buf[pos]; } #if 0 if(nblk==5587) printf("iv=%5d n=%5d\n", iv, n); #endif pos += sizeof(int); if(n==FILE_END) return(-1); if(n==EVT_END) break; if(n==IND_END){ iv++; continue; } /* read data (double floating) */ if(pos>=size){ fprintf(stderr, "dst_read_data: run out of buffer (b)\n"); return(-1); } if(SWAP){ src = (unsigned char*)&buf[pos]; dst = (unsigned char*)&(&d)[1]; *(--dst) = *src++; *(--dst) = *src++; *(--dst) = *src++; *(--dst) = *src++; *(--dst) = *src++; *(--dst) = *src++; *(--dst) = *src++; *(--dst) = *src++; }else{ d = *(double*)&buf[pos]; } pos += sizeof(double); /* set data */ if(iv<ndstinp){ if(n == 1082955776){ for(i=0; i<16; i++){ fprintf(stderr, "%4x\n", buf[pos-16+i]); } } dr_set_ref(dstinpref[iv], n, d); #if 0 fprintf(stderr, "%s[%d] = %f\n", dstvar[iv], iv, d); #endif } } *bpos = pos; if(dr_exists(d=dr_get(RUN_N[0]))) nrun = (int)d; if(dr_exists(d=dr_get(BLOCK_N[0]))) blk = (int)d; else blk = 0; if(ana<0 || nblk!=blk){ nblk = blk; ana = !evt_blk(blk); #if 0 fprintf(stderr, "%d %d %f %f\n", blk, ana, dr_get(ANA_BLK_START), dr_get(ANA_BLK_END)); #endif } if(ana){ if(pflag){ }else{ dr_event(); } #if 0 /* show scalers (if requested) */ if(dr_is_true(dr_get(ANALYZE_SHOW_SCALER))) evt_print_scaler(stdout); #endif } return(0); } /* initialyze */ int dst_init(){ int res; if((res=dst_open_file())) return(res); if((res=dst_write_header((char*)NULL))) return(res); return(0); } /* exit */ int dst_exit(){ int res; dst_close_file(); return(0); } /* Local Variables: mode: C tab-width: 2 End: */ <file_sep>/* mtformat.h ... MT format definitions Copyright (C) 1993, 1994, 1995 <NAME> Author: <NAME> Facility: Department of Physics, Kyoto University & Research Center for Nuclear Physics Created: 05-SEP-1993 by <NAME> Modified: 07-JAN-1995 by <NAME> (Solaris 2.3) Modified: 06-MAY-1997 by <NAME> (Degital Unix) Modified: 19-OCT-2014 by <NAME> (extended the BlkHeader to add a block size of long word) Modified: 20-AUG-2015 by <NAME> (DAQ Data ver 4.0) Modified: 27-MAR-2016 by <NAME> (vmedaq version) */ typedef struct BlkHeader{ // from Ver. 4.0 unsigned short headerID; /* = 0xFFFF */ unsigned short headerSize; unsigned short blockID; unsigned short blockSize; /* Disposed. Fixed = 0xFFF0 */ unsigned short blockNumber; unsigned short numEvents; unsigned short blockSize32_l; /* 32 bit block size , added on 19-OCT-2014 lower bit*/ unsigned short blockSize32_u; /* 32 bit block size , added on 19-OCT-2014 upper bit*/ } BlkHeader, *BlkHeaderPtr, **BlkHeaderHdl; typedef struct BlkHeaderV3{ // older block header until 19-OCT-2014 (Ver 3.0 or earlier) unsigned short headerID; /* = 0xFFFF */ unsigned short headerSize; unsigned short blockID; unsigned short blockSize; unsigned short blockNumber; unsigned short numEvents; } BlkHeaderV3, *BlkHeaderV3Ptr, **BlkHeaderV3Hdl; typedef struct BlkTrailer{ unsigned short trailerID; /* = 0xFFEF */ unsigned short trailerSize; } BlkTrailer, *BlkTrailerPtr, **BlkTrailerHdl; typedef struct EvtHeader{ unsigned short headerID; /* = 0xFFDF */ unsigned short headerSize; unsigned short eventID; unsigned short eventSize; unsigned short eventNumber; unsigned short numFields; #if false unsigned short fieldFlag; #endif } EvtHeader, *EvtHeaderPtr, **EvtHeaderHdl; typedef struct FldHeader{ unsigned short headerID; /* = 0xFFCF */ unsigned short headerSize; unsigned short fieldID; unsigned short fieldSize; } FldHeader, *FldHeaderPtr, **FldHeaderHdl; #define ComVar4_0 (4<<8) /* version 4.0 */ #define MaxComLen 124 #if 0 // before Ver 4.0 typedef struct RunComment{ unsigned int version; unsigned int byte; unsigned int time; unsigned short run; unsigned char comment[MaxComLen]; } RunComment, *RunCommentPtr; #endif // revised on 11-NOV-2014 (Ver4.0) typedef struct RunComment{ unsigned short version; /* = 4.0 */ unsigned short res1; /* reserved word 1*/ unsigned int byte; unsigned int time; unsigned short run; unsigned short res2; /* reserved word 2*/ unsigned char comment[MaxComLen]; } RunComment, *RunCommentPtr; /*** Module IDs ***/ # define ID_Reserved (0x00<<12) # define ID_V1190 (0x01<<12) # define ID_NimIn (0x02<<12) # define ID_MADC32 (0x03<<12) # define ID_MYRIAD (0x04<<12) # define ID_3351 (0x05<<12) # define ID_Scaler (0x06<<12) # define ID_3377 (0x07<<12) # define ID_UNIX_TIME (0x08<<12) // spared ID # define ID_V830 (0x09<<12) # define ID_4299_MWPC (0x0a<<12) # define ID_ADC_LAS (0x0b<<12) # define ID_TDC_LAS (0x0c<<12) # define ID_FERA_ADC (0x0d<<12) # define ID_FERA_TDC (0x0e<<12) # define ID_CHKSUM (0x0f<<12) # define ModuleIDMask 0xF000L # define DataLengthMask 0x0FFFL /* Header/Trailer ID */ # define BlkHeaderID 0xFFFFL # define BlkTrailerID 0xFFEFL # define EvtHeaderID 0xFFDFL # define FldHeaderID 0xFFCFL /* Block ID */ # define DataBlockID 0x0000 /* lower 3 bits is crate number */ # define ScalerBlockID 0x0E00 # define StartBlockID 0x0F01 # define EndBlockID 0x0F02 # define MiddleBlockID 0x0F03 # define BuiltBlockID 0x0100 /* Event ID */ # define DataEvent 0 # define BlockEndEvent 1 /* Field ID */ # define FieldID 0 /*** Minimum/Maximum size ***/ #define S_BH_MIN sizeof(BlkHeaderV3)/2 #define S_BH_MAX sizeof(BlkHeader)/2 #define S_EH_MIN sizeof(EvtHeader)/2 #define S_EH_MAX sizeof(EvtHeader)/2 #define S_FH_MIN sizeof(FldHeader)/2 #define S_FH_MAX sizeof(FldHeader)/2 #define S_BT_MIN sizeof(BlkTrailer)/2 #define S_BT_MAX sizeof(BlkTrailer)/2 <file_sep>#include "GRUTinizerInterface.h" #include "GRAnalyzer.h" #include "RCNPEvent.h" #include <chrono> #include <thread> std::atomic<int>* TerminateSig; void StartGRAnalyzer(const char* filename, std::atomic<int>* terminate,std::function<void(RCNPEvent*)> func, bool save_tree, bool status) { TerminateSig = terminate; RCNPInterface::Instance().SaveTree(save_tree); RCNPInterface::Instance().ShowStatus(status); Init(func); start_analyzer(filename); } int CheckTerminateSignal() { return int(*TerminateSig); } extern "C" int CheckSignal () { return CheckTerminateSignal(); } int Status() { return int(RCNPInterface::Instance().ShowStatus()); } extern "C" int ShowStatus () { return Status(); } <file_sep>/* mwdc.c ---- MWDC data analysis Version 1.00 26-SEP-2000 by <NAME> */ #include <stdio.h> #include <math.h> #include "freadin.h" #include "histogram.h" #include "analyzer.h" /* MWDC Clusterize */ int chamb_mwdc_clust(plane) plane_p plane; { int min, max; int i, n, t, w; int *p; clst_p clst; if(plane==(plane_p)NULL){ fprintf(stderr, "evt_mwdc_clust: null plane pointer\n"); return(-1); } min = dr_min_ref(plane->h_wire); max = dr_max_ref(plane->h_wire); /* Get TDC data (allow multiple hits in a wire) */ n=0; for(i=max-1; i>=min; i--){ w = dr_int(dr_get_ref(plane->h_wire,i)); t = dr_int(dr_get_ref(plane->h_tdc,i)); clst = &plane->clst[n++]; clst->wire[0] = w; clst->tdc[0] = t; clst->size = 1; dr_append_ref(plane->h_wirer,w); dr_append_ref(plane->h_tdcr,t); dr_append_ref(plane->h_clstsz,1); if(n>=Clst_MaxNClst){ if(0) fprintf(stderr, "evt_mwdc_clust: too many wire hits (>=%d)\n", Clst_MaxNClst); break; } } plane->nc = n; dr_set_ref(plane->h_nhit,0,n); dr_set_ref(plane->h_nclst,0,n); return(0); } /* MWDC Position Calculation */ int chamb_mwdc_pos(plane) plane_p plane; { clst_p clst; int ic; double dw, dd, disp, dl; if(!plane->wire.ok) return(-1); disp = plane->wire.disp; dl = plane->wire.dl; for(ic=0; ic<plane->nc; ic++){ clst = &plane->clst[ic]; dr_set_nothing(&clst->pos); if(dr_exists(clst->dist[0])){ dw = clst->wire[0]*disp; dd = clst->dist[0]*dl; clst->pos1 = dw - dd; clst->pos2 = dw + dd; clst->posid = POSID_NOERR; }else{ dr_set_nothing(&clst->pos1); dr_set_nothing(&clst->pos2); clst->posid = POSID_NOHIT; } } return(0); } /* Local Variables: mode: C tab-width: 2 End: */ <file_sep># This file can be placed inside of a library directory to customize # the behavior of that library. Each option, if left commented, will # assumed its default value. # The name of the library. # Defaults to LIBNAME, where libLIBNAME is the directory. LIBRARY_NAME = $(patsubst lib%,%,$(notdir $(CURDIR))) # The flag that will be passed to the include the library in # executables. LIBRARY_FLAG = -l$(LIBRARY_NAME) # The directories containing source files for the library. LIBRARY_SRC_DIRS = src # The directories containing include files for the library. These # directories will be added to the include path for all files in the # project. LIBRARY_INCLUDE_DIRS = include # The directories containing include files for the library. These # directories will be added to the include path only for files within # this library LIBRARY_PRIVATE_INCLUDE_DIRS = # Any files which will be processed by flex, bison, should be listed # here. This will exclude the unprocessed version ofthe files from # the build process and only the processed .c.c files will be built CODE_GEN_FILES = \ src/analyzer.c \ src/chamb.c \ src/vdc.c \ src/mwpc.c \ src/chamb_rcnp.c \ src/chamb_np.c \ src/chamb_gr_fpp.c \ src/chamb_las_fpp.c \ src/chamb_f2.c \ src/fread_rcnp.c \ src/fread_mars.c \ src/fread_dst.c \ src/fread_root.cc \ src/kvi_sample.c \ # A space-delimited list of file patterns to be excluded # For example, this may contain a source file or directory # that is not to be compiled in the current build. # % can be used to create wildcard exclusions. # Note: Files in the library's directory should be listed as "filename", # not "./filename". LIBRARY_EXCLUSIONS = $(CODE_GEN_FILES) # Extra flags that should be present when linking the shared library. # This may include other libraries that should be included. $(LIBRARY): SHARED_LDLIBS += # Compiler flag overrides for src files within this library. $(LIBRARY): <file_sep>/* fera.h ---- LeCroy 4300B (FERA/FERET) Definitions */ /* */ /* Copyright (C) 1996, <NAME> */ /* */ /* Version 1.00 15-JUN-1996 by <NAME> */ /* Version 2.00 05-AUG-1997 by <NAME> (vsn_delim() for FERA-GSO) */ #if defined (__cplusplus) extern "C" { #endif #if !defined(alpha) && !defined(i586) && !defined(i686) && !defined(x86_64) /*---- others (big endian) ---- */ /* FERA Header */ typedef struct fera_header{ unsigned hdr: 1; /* Identifies header word (=1) */ unsigned cnt: 4; /* Word Count */ unsigned res: 3; /* Not Used */ unsigned vsn: 8; /* Virtual Station Number */ } fera_header; /* FERA Data (Compressed Mode) */ typedef struct fera_data{ unsigned hdr: 1; /* Identifies header word (=0) */ unsigned ch: 4; /* Channel number */ unsigned data: 11; /* Data */ } fera_data; /* Virtual Station Number ID */ typedef struct fera_vsn{ unsigned type: 1; /* FERA_TYPE_ADC or FERA_TYPE_TDC */ unsigned res: 2; /* Reserved */ unsigned spe: 1; /* Spectrometer (0=GR, 1=LAS) */ unsigned id: 4; /* ID */ } fera_vsn; #else /*----- Alpha or Intel-PC (little endian) ----*/ /* FERA Header */ typedef struct fera_header{ unsigned vsn: 8; /* Virtual Station Number */ unsigned res: 3; /* Not Used */ unsigned cnt: 4; /* Word Count */ unsigned hdr: 1; /* Identifies header word (=1) */ } fera_header; /* FERA Data (Compressed Mode) */ typedef struct fera_data{ unsigned data: 11; /* Data */ unsigned ch: 4; /* Channel number */ unsigned hdr: 1; /* Identifies header word (=0) */ } fera_data; /* Virtual Station Number ID */ typedef struct fera_vsn{ unsigned id: 4; /* ID */ unsigned spe: 1; /* Spectrometer (0=GR, 1=LAS) */ unsigned res: 2; /* Reserved */ unsigned type: 1; /* FERA_TYPE_ADC or FERA_TYPE_TDC */ } fera_vsn; #endif /*----- end of OSF1 ----*/ #if defined (__cplusplus) } #endif # define VSN_TDC 0x80 /* VSN TDC Mask */ # define VSN_DELIMITER1 0xF0 /* Delimiter VSN */ # define VSN_DELIMITER2 0x11 /* Delimiter VSN */ #if 0 #define vsn_delim(vsn) (vsn==VSN_DELIMITER1 || vsn==VSN_DELIMITER2) #define vsn_delim(vsn) (vsn==0xF0) /* for E07 Jul96 */ #else #define vsn_delim(vsn) ((vsn&0x8F)==0x01) #endif <file_sep>#!/bin/sh # mknum ... make numbers # # version 1.00 17-FEB-1998 by <NAME> # if [ "$1" = "-h" ] then echo "mknum ... make numbers to stdout" echo "Usage: mknum [numbers ...]" echo "Example:" echo " % mknum 1010 1011 1013-1015" echo " 1010 1011 1013 1014 1015" exit fi echo "$*" | awk ' BEGIN{ n=0; } { for(i=1; i<=NF; i++){ if(match($i,"-")){ min = substr($i,1,RSTART-1)+0; max = substr($i,RSTART+RLENGTH,length($i)-RSTART-RLENGTH+1)+0; for(j=min; j<=max; j++) printf("%d ", j); }else{ printf("%d ", $i); } } } ' <file_sep>import cog import hashlib import os,tempfile def readcmd(cmd): ftmp = tempfile.NamedTemporaryFile(suffix='.out', prefix='tmp', delete=False) fpath = ftmp.name if os.name=="nt": fpath = fpath.replace("/","\\") # forwin ftmp.close() os.system(cmd + " > " + fpath) data = "" with open(fpath, 'r') as file: data = file.read() file.close() os.remove(fpath) return data def get_vars(filename): members = [] for line in open(filename): if 'DST_VAR' in line: line = line.split() members = line[4].split(':') break members[0] = members[0][1:] members[-1] = members[-1][:-1] return members def md5(string): m = hashlib.md5() m.update(string) return m.hexdigest() def check_dst_vars(filename): for line in open(filename): line = line.strip() if "DST_VAR" in line: #checksum = md5(line) checksum = line break return checksum def definitions(): members = get_vars('../hist.def') for i,fn in enumerate(members): #cog.outl("int i{}; //! ignored by root".format(fn)) cog.outl("double {0}(const int& i) {{ return (data.count({1}) > 0) ? data[{1}][i] : BAD_NUM; }}".format(fn,i)) #cog.outl("double {0}() {{ return (data.count({1}) > 0) ? data[{1}][0] : BAD_NUM; }}".format(fn,i)) cog.outl("vector<double>* {0}() {{ return (data.count({1}) > 0) ? &data[{1}] : nullptr; }}".format(fn,i)) # assume that Make is run from the analyzer directory and hist.def is one level up fullpath = readcmd('readlink -f ../hist.def')[:-1] astr = """ static void HistDefCheckSum(int pid=0) {{\n\n string record = "{0}";""".format(check_dst_vars(fullpath).replace("\"","\\\"")) + """ string line, dstvars = "DST_VAR";\n"""+""" ifstream histdef ("{0}");""".format(fullpath) + """ if (histdef.is_open()) { while ( getline (histdef,line) ) { if (line.find(dstvars) != string::npos) { break; } } histdef.close(); } line.erase(line.begin(), std::find_if(line.begin(), line.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); line.erase(std::find_if(line.rbegin(), line.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), line.end()); fprintf(stderr,"%s\\n",line.c_str()); if (line == record) { return; } else { fprintf(stderr,"%s vs %s\\n",record.c_str(),line.c_str()); const char* msg = "\\n###################### RUNTIME ERROR ######################\\n" "DST_VAR line in hist.def has changed since compilation.\\n" "Please recompile the analyzer before attempting to run.\\n" "###########################################################\\n"; fprintf(stderr,"%s",msg); kill(pid,SIGINT); throw runtime_error(msg); } }""" cog.outl(astr) <file_sep># Make file for analyzer program # Performs code generation only # Version 1.00 02-JUN-2000 by <NAME> # Version 1.50 20-MAY-2016 by <NAME> #.SILENT: #****************** #* Compiler etc. * #****************** # Directories ANA = $(realpath ./) SDIR = libGRAnalyzer/src HDIR = libGRAnalyzer/include DICTLIB = libRCNPEvent LDIR = lib ODIR = obj EDIR = bin COG = $(EDIR)/cog ROOTCINT = rootcint LEX = flex YACC = bison -v -d AHIST = awk -f bin/hist.awk PHIST = perl bin/moveline.pl SRC = $(SDIR)/analyzer.c.c \ $(SDIR)/chamb.c.c \ $(SDIR)/vdc.c.c \ $(SDIR)/mwpc.c.c \ $(SDIR)/chamb_rcnp.c.c \ $(SDIR)/chamb_np.c.c \ $(SDIR)/chamb_gr_fpp.c.c \ $(SDIR)/chamb_las_fpp.c.c \ $(SDIR)/chamb_f2.c.c \ $(SDIR)/fread_rcnp.c.c \ $(SDIR)/fread_mars.c.c \ $(SDIR)/fread_dst.c.c \ $(SDIR)/fread_root.cc.cc \ $(SDIR)/freadin.tab.c \ $(SDIR)/lex.yy.c \ $(DICTLIB)/src/RCNPEventDictionary.cc \ $(DICTLIB)/include/RCNPEventDictionary.h \ $(DICTLIB)/include/RCNPEvent.h \ $(ODIR)/hb.o HDR = $(HDIR)/analyzer.h $(HDIR)/histogram.h $(HDIR)/freadin.h HISTDEF=$(realpath ../hist.def) all: $(SRC) $(DICTLIB)/include/RCNPEvent.h: $(HISTDEF) $(HDIR)/rootalyze.h $(HDIR)/rootalyze.py $(COG) $(HDIR)/rootalyze.h > $@ $(SDIR)/%.c.c: $(SDIR)/%.c $(AHIST) $< > $<.c $(PHIST) $<.c $(SDIR)/%.cc.cc: $(SDIR)/%.cc $(AHIST) $< > $<.cc $(PHIST) $<.cc $(DICTLIB)/include/RCNPEventDictionary.h: $(DICTLIB)/src/RCNPEventDictionary.cc touch $@ $(DICTLIB)/src/RCNPEventDictionary.cc: $(DICTLIB)/include/RCNPEvent.h $(DICTLIB)/include/LinkDef.h $(ROOTCINT) -f $@ -c -p -I$(realpath $(DICTLIB)/include) $(realpath $(DICTLIB)/include)/RCNPEvent.h $(realpath $(DICTLIB)/include)/LinkDef.h mv $(basename $@).h $(DICTLIB)/include $(SDIR)/lex.yy.c: $(SDIR)/freadin.lex $(SDIR)/freadin.tab.c $(LEX) $< mv lex.yy.c $@ $(SDIR)/freadin.tab.c: $(SDIR)/freadin.y $(HDIR)/freadin.h $(YACC) $< mv freadin.tab.c $(SDIR) mv freadin.tab.h $(HDIR) $(ODIR)/hb.o: $(SDIR)/hb.f gfortran -c -fPIC -o $@ $< clean: @rm -f $(SDIR)/*.c.c $(SDIR)/*.cc.cc \ $(HDIR)/freadin.tab.h $(SDIR)/freadin.tab.c \ $(SDIR)/lex.yy.c $(SDIR)/freadin.output \ $(DICTLIB)/src/*Dictionary.cc $(DICTLIB)/include/*Dictionary.h \ $(DICTLIB)/include/RCNPEvent.h $(HDIR)/*.pyc \ $(ODIR)/*.o $(SDIR)/#* $(SDIR)/*~ $(SDIR)/.#* \ $(LDIR)/*.so $(HDIR)/#* $(HDIR)/*~ $(HDIR)/.#* <file_sep>/* mwdc_np.c ---- (n,p) wire chamber data analysis Version 1.00 26-SEP-2000 by <NAME> */ #include <stdio.h> #include <math.h> #include "freadin.h" #include "histogram.h" #include "analyzer.h" #include "matrix.h" #if NP_MWDC //FLAG struct chamber tgc_mwdc; struct chamber fec_mwdc; /* initialize data before an event (for np)*/ int evt_init_np() { chamb_init_chamb(&tgc_mwdc); chamb_init_chamb(&fec_mwdc); } /* NP-3377 data analysis */ int evt_chamb_np(){ chamber_p chamb; plane_p plane; int ipl; ray_p ray; double d; chamb = &tgc_mwdc; ray = &chamb->ray; for(ipl=0; ipl<chamb->npl; ipl++){ plane = &chamb->plane[ipl]; chamb_clust(plane); chamb_drift(plane); chamb_pos(plane); } if(dr_exists(d=dr_get(LAS_RAYID)) && dr_int(d)==0){ chamb_ray(chamb); dr_set(TGC_RAYID,ray->rayid); dr_set(TGC_CHI2[0],chamb->chi2); if(ray->rayid==RAYID_NOERR){ /* rotation of axes as z=central-ray */ ray_rotate_z(ray,dr_get(TGC_TILT[2])); ray_rotate_y(ray,dr_get(TGC_TILT[1])); ray_rotate_x(ray,dr_get(TGC_TILT[0])); /* output of ray information */ dr_set(TGC_RAY_X[0], ray->org.x); dr_set(TGC_RAY_Y[0], ray->org.y); dr_set(TGC_TH[0],atan(ray->dir.x)); dr_set(TGC_PH[0],atan(ray->dir.y)); /* projection to virtual planes */ chamb_intersection(chamb); } } chamb = &fec_mwdc; ray = &chamb->ray; for(ipl=0; ipl<chamb->npl; ipl++){ plane = &chamb->plane[ipl]; chamb_clust(plane); chamb_drift(plane); chamb_pos(plane); } if(dr_exists(d=dr_get(LAS_RAYID)) && dr_int(d)==0){ chamb_ray(chamb); dr_set(FEC_RAYID,ray->rayid); dr_set(FEC_CHI2[0],chamb->chi2); if(ray->rayid==RAYID_NOERR){ /* rotation of axes as z=central-ray */ ray_rotate_z(ray,dr_get(FEC_TILT[2])); ray_rotate_y(ray,dr_get(FEC_TILT[1])); ray_rotate_x(ray,dr_get(FEC_TILT[0])); /* output of ray information */ dr_set(FEC_RAY_X[0], ray->org.x); dr_set(FEC_RAY_Y[0], ray->org.y); dr_set(FEC_TH[0],atan(ray->dir.x)); dr_set(FEC_PH[0],atan(ray->dir.y)); /* projection to virtual planes */ chamb_intersection(chamb); } } return(0); } /* initialization of data before data analysis */ int evt_start_np(){ chamber_p chamb; plane_p plane; int i, ipl; double d; /* for TGC */ chamb = &tgc_mwdc; #if DT2D_TAB chamb_get_dt2d_tab(chamb); #endif chamb_get_config(chamb); for(ipl=0; ipl<chamb->npl; ipl++){ plane = &chamb->plane[ipl]; plane->pres = 0.5; /* 0.5 mm resolution */ plane->fit = dr_is_true(dr_get(TGC_FIT_PLANE[ipl])); } if(dr_exists(d=dr_get(TGC_MAX_NCOMB))) chamb->max_ncomb = (int)d; chamb->allow_wireskip = dr_is_true(dr_get(TGC_ALLOW_WIRESKIP)); d = dr_get(TGC_N_VPLANE); chamb->nproj = dr_exists(d) ? min((int)d, MaxNIntPl) : 0; for(i=0; i<chamb->nproj; i++) dr_ref_n(spf("TGC_PLANE_%d",i), &chamb->h_proj[i]); dr_ref_n("TGC_X", &chamb->h_x); dr_ref_n("TGC_Y", &chamb->h_y); /* for FEC */ chamb = &fec_mwdc; #if DT2D_TAB chamb_get_dt2d_tab(chamb); #endif chamb_get_config(chamb); for(ipl=0; ipl<chamb->npl; ipl++){ plane = &chamb->plane[ipl]; plane->pres = 0.5; /* 0.5 mm resolution */ plane->fit = dr_is_true(dr_get(FEC_FIT_PLANE[ipl])); } if(dr_exists(d=dr_get(FEC_MAX_NCOMB))) chamb->max_ncomb = (int)d; chamb->allow_wireskip = dr_is_true(dr_get(FEC_ALLOW_WIRESKIP)); d = dr_get(FEC_N_VPLANE); chamb->nproj = dr_exists(d) ? min((int)d, MaxNIntPl) : 0; for(i=0; i<chamb->nproj; i++) dr_ref_n(spf("FEC_PLANE_%d",i), &chamb->h_proj[i]); dr_ref_n("FEC_X", &chamb->h_x); dr_ref_n("FEC_Y", &chamb->h_y); return(0); } /* initialize variables */ int init_hist_np() { chamber_p chamb; int ipl; double d; int i, n; /* initialyze for Target Chamber MWDC */ chamb = &tgc_mwdc; chamb->name = "TGC"; chamb->type = CHAMB_MWDC; chamb->npl = 10; chamb->plane = (plane_p)malloc(sizeof(plane_t)*chamb->npl); chamb->plane[0].name = "VT1"; chamb->plane[1].name = "VT2"; chamb->plane[2].name = "VT3"; chamb->plane[3].name = "VT4"; chamb->plane[4].name = "X1"; chamb->plane[5].name = "X2"; chamb->plane[6].name = "U1"; chamb->plane[7].name = "U2"; chamb->plane[8].name = "V1"; chamb->plane[9].name = "V2"; for(ipl=0; ipl<chamb->npl; ipl++){ chamb->plane[ipl].chamb = chamb; } chamb_init_hist(chamb); n = 1<<chamb->npl; chamb->matrix = (void*)malloc(sizeof(mat_p)*n); for(i=0; i<n; i++) ((mat_p*)chamb->matrix)[i] = (mat_p)NULL; chamb->mb = matrix_new(4,1); chamb->mc = matrix_new(4,1); if(chamb->matrix==NULL||chamb->mb==NULL||chamb->mc==NULL){ showerr("init_hist_np: No enough memory available\n"); exit(1); } /* initialyze for Front-end Chamber MWDC */ chamb = &fec_mwdc; chamb->name = "FEC"; chamb->type = CHAMB_MWDC; chamb->npl = 6; chamb->plane = (plane_p)malloc(sizeof(plane_t)*chamb->npl); chamb->plane[0].name = "Y1"; chamb->plane[1].name = "Y2"; chamb->plane[2].name = "V1"; chamb->plane[3].name = "V2"; chamb->plane[4].name = "U1"; chamb->plane[5].name = "U2"; for(ipl=0; ipl<chamb->npl; ipl++){ chamb->plane[ipl].chamb = chamb; } chamb_init_hist(chamb); n = 1<<chamb->npl; chamb->matrix = (void*)malloc(sizeof(mat_p)*n); for(i=0; i<n; i++) ((mat_p*)chamb->matrix)[i] = (mat_p)NULL; chamb->mb = matrix_new(4,1); chamb->mc = matrix_new(4,1); if(chamb->matrix==NULL||chamb->mb==NULL||chamb->mc==NULL){ showerr("init_hist_np: No enough memory available\n"); exit(1); } } #endif /* if NP_MWDC */ /* Local Variables: mode: C tab-width: 2 End: */ <file_sep>extern "C" int start_analyzer(const char* filename); <file_sep>cogapp-2.5.tar.gz <file_sep>/* histogram.c ---- histogram Version 1.00 02-JUN-2000 by <NAME> */ #ifndef DBL_MAX #define DBL_MAX 1.0E+37 #endif #define DR_NOTHING DBL_MAX #define DR_ZERO (1.0e-20) #define DR_MAX_DATA_N 10000 #define DR_MAX_ARRAY_INDEX 100000 #define DR_MIN_ARRAY_INDEX -100000 #define MaxNDSTVar 1000 /* Max Number of DST output variables */ #if defined (__cplusplus) extern "C" { #endif enum DR_TYPE { DR_UNDEF=0, /* undefined */ DR_CONST, /* constant */ DR_CALC, /* calculation */ DR_USER, /* user calculation */ DR_NTYPE /* number of types */ }; /* data (variable) record */ typedef struct { char *nam; /* variable name */ int type; /* type */ int imin; /* index minimum */ int imax; /* index maximum +1*/ int amin; /* index minimum accessed */ int amax; /* index maximum accessed +1*/ int nvalue; /* number of values (=imax-imin) */ double *value; /* values */ int eval; /* evaluation type (enum eval) */ int neval; /* evaluation level */ int nreg; /* number of references */ int **reg; /* reference pointers */ int nvrec; /* number of definitions */ vrec_p *vrec; /* definitions */ } dr_rec_t; /* data record handle */ typedef struct { int n; int nmax; dr_rec_t *rec; } dr_t; #define DR_TRUE 1.0 #define DR_FALSE 0.0 #define dr_ref(nam,h) \ (dr_ref_r(&dr_data,h,#nam)) #define dr_ref_n(nam,h) \ (dr_ref_r(&dr_data,h,nam)) #define dr_set_ref(h,i,val) (dr_set_r(&dr_data,&(h),"",(i),val)) #define dr_append_ref(h,val) (dr_append_r(&dr_data,&(h),"",0,val)) #define dr_get_ref(h,i) (dr_get_r(&dr_data,&(h),"",(i))) #define dr_max_ref(h) (dr_max_r(&dr_data,&(h),"",0)) #define dr_min_ref(h) (dr_min_r(&dr_data,&(h),"",0)) #define dr_set_nothing(val) {*((double *)val) = (DR_NOTHING);} #define dr_is_nothing(val) ((val) >= (DR_NOTHING)) #define dr_exists(val) ((val) < (DR_NOTHING)) #define dr_int(val) (dr_exists(val) ? (int)((val)+0.5) : -1) #define dr_is_zero(val) (fabs((double)(val)) < DR_ZERO) #define dr_is_false(val) (dr_is_nothing(val) || dr_is_zero(val)) #define dr_is_true(val) (!dr_is_false(val)) #define dr_const(v) (((v)==(vrec_p)NULL || (v)->eval==EVAL_CONST) ? \ EVAL_CONST : EVAL_NONE); #define dr_const2(v1,v2) (((v1)==(vrec_p)NULL || (v1)->eval==EVAL_CONST) &&\ ((v2)==(vrec_p)NULL || (v2)->eval==EVAL_CONST) ? \ EVAL_CONST : EVAL_NONE); #define dr_show() dr_show_r(&dr_data) #define dr_clear() dr_clear_r(&dr_data) #define dr_reinit() dr_reinit_r(&dr_data) #define min(a,b) ((a)<=(b) ? (a) : (b)) #define max(a,b) ((a)>=(b) ? (a) : (b)) extern dr_t dr_data; int dr_init(void); void dr_event(); int dr_set_r(dr_t*, int *, char const *, int, double); double dr_get_r(dr_t*, int *, char const *, int); vrec_p dr_get_vrec_r(dr_t*, int *, char const *, int); char *dr_get_sval_r(dr_t*, int *, char const *, int); int dr_min_r(dr_t*, int *, char const *, int); int dr_max_r(dr_t*, int *, char const *, int); int dr_nval_r(dr_t*, int *, char const *, int); int dr_append_r(dr_t*, int *, char const *, int, double); int dr_exit(void); int dr_ref_r(dr_t*, int *, char const *); void dr_show_r(dr_t*); int dr_clear_r(dr_t*); int dr_reinit_r(dr_t*); int dr_set_vrec(dr_t*, int *, char const *, vrec_p); void free_vrecp(vrec_p v); void hist1(vrec_p v0, vrec_p sname, vrec_p name, vrec_p v, vrec_p min, vrec_p max, vrec_p nbin, vrec_p xlabel, vrec_p ylabel, vrec_p gate); void hist2(vrec_p v0, vrec_p sname, vrec_p name, vrec_p v1, vrec_p min1, vrec_p max1, vrec_p nbin1, vrec_p xlabel, vrec_p v2, vrec_p min2, vrec_p max2, vrec_p nbin2, vrec_p ylabel, vrec_p gate); void def(vrec_p v0, vrec_p v1, vrec_p v2, vrec_p v3); void com(vrec_p v0); int yyerror(char*); int yylex(void); double eval(vrec_p); char *spf(char*,...); #if defined (__cplusplus) } #endif /* Local Variables: mode: C tab-width: 2 End: */ <file_sep>#!/bin/sh # # Usage: see the help using the -h option # #-- block size when need to be specified -- blk=10240 # #-- number of child processes (will be set 1 for the case making dst) nc=1 # # Option for rootfile, 0 by default rootopt="" # # Flags shm_flag="" help_flag="" dst_flag="" root_flag="" adddef="" # # while getopts hsd:12DR OPT do case $OPT in "s" ) shm_flag="TRUE" ;; "h" ) help_flag="TRUE" ;; "d" ) adddef="$adddef $OPTARG" ;; "1" ) adddef="$adddef run/back1.def" ;; "2" ) adddef="$adddef run/back2.def" ;; "D" ) dst_flag="TRUE" ;; "R" ) root_flag="TRUE" ;; esac done shift $(( $OPTIND - 1 )) if [ -n "$help_flag" -o $# -lt 3 ] then echo "Usage: $0 [-hsd12DRT] [-d filename.def] from_name to_name run_numbers" echo " -h: show this help" echo " -s: use shared memory" echo " -d: add the specified definition file" echo " -1: add run/back1.def in the definition files" echo " -2: add run/back2.def in the definition files" echo " -D: create a DST file" echo " -R: create a ROOT file" exit fi src=$1; shift dst=$1; shift #------------ directories and files ----------- blddir=./datatest/ dstindir=./dst dstoutdir=./dst hbdir=./hb alidir=./alias defdir=./def scadir=./sca rundir=./run # PID=$$ deffilep="$defdir/analyzer_p_$PID.def" deffilef="$defdir/analyzer_d_$PID.def" #------------------------------------- # #---------- analyzer command ---------- #anacmd="./analyzer/bin/analyzer" anacmd="./bin/analyzer" anaopt="" # if [ "$blk" != "" ] then anaopt="$anaopt -b $blk"; fi # if [ -z "$dst_flag" -a "$nc" != "" ] then anaopt="$anaopt -p $nc"; fi # if [ -n "$root_flag" ] then rootopt="-r"; fi #--------------------------------------- #------------------------------------------- echo "Analysis from '$src' to '$dst'" #------------------------------------------- if [ "$src" = "" -o "$src" = "bld" -o "$src" = "BLD" ] then src="" else src="_$src" fi dst=$src"_"$dst #----- make a copy of the hist.def file ----- cp -f hist.def $deffilep #--------------------------------------------- #---------------- RUN loop ---------------- #for run in $* for run in `./analyzer/bin/mknum $*` do date echo "run $run" #------------ create file names ------------ hbfile="$hbdir/run$run$dst.hb" deffile="$defdir/run$run$dst.def" dstfile="$dstoutdir/run$run$dst.dst" alifile="$alidir/run$run$dst.kumac" scafile="$scadir/run$run$dst.sca" #------------------------------------- # clear files rm -f $hbfile rm -f $deffile rm -f $deffilef rm -f $alifile rm -f $scafile ln -fs $alifile alias.kumac if [ -n "$dst_flag" ] then rm -f $dstfile fi # copy the definition file cp -f $deffilep $deffile # add definition file specified in the command line for file in $adddef do echo "Include the file: $file" echo "#--- Included from $file ---" >> $deffile cat $file >> $deffile done # set the run dependent definition file runfile="$rundir/run$run.def" if [ -f $runfile ] then echo "Include run dependent file: $runfile" echo "#--- Included from $runfile ---" >> $deffile cat $runfile >> $deffile fi echo "#--- Defnition of output files ---" > $deffilef if [ -n "$dst_flag" ] then echo ' 1 def DST_FILE = "'$dstfile'"' >> $deffilef fi echo ' 1 def HB_FILE = "'$hbfile'"' >> $deffilef echo ' 1 def SCA_FILE = "'$scafile'"' >> $deffilef echo ' 1 def ALIAS_FILE = "'$alifile'"' >> $deffilef # find data if [ -f $blddir/run$run$src.bld ] then datacmd="cat $blddir/run$run$src.bld" elif [ -f $blddir/run$run$src.bld.gz ] then datacmd="gunzip -c $blddir/run$run$src.bld.gz" elif [ -f $dstindir/run$run$src.dst ] then datacmd="cat $dstindir/run$run$src.dst" elif [ -f $dstindir/run$run$src.dst.gz ] then datacmd="gunzip -c $dstindir/run$run$src.dst.gz" fi # ----- do analysis ------ if [ -n "$shm_flag" ] then $datacmd | $anacmd $anaopt -d $deffilef -d $deffile else $datacmd | $anacmd $anaopt -d $deffilef -d $deffile -f $hbfile $rootopt fi # --------------------------- done #---------------- end of RUN loop ---------------- rm -f $deffilep rm -f $deffilef <file_sep>/* proc_hb.c --- drex HBOOK manipulation procedures Copyright (C) 1997 <NAME> Author: <NAME> Facility: Department of Physics, Kyoto University & Research Center for Nuclear Physics Created: 09-MAY-1997 by <NAME> Version 1.00 09-MAY-1997 by <NAME> Version 2.00 03-JUN-2000 by <NAME> */ #include <stdio.h> #include <string.h> #include <math.h> #include <errno.h> #include <stdarg.h> #include "freadin.h" #include "histogram.h" extern int shmflag; /* shared memory flag */ extern int pflag; /* parent process flag */ extern int cflag; /* child process flag */ #if 0 float pawc_[8000000]; #else float pawc_[16000000]; #endif extern void hstini_(char*, int*); extern void hstshm_(char*, int*); extern void hstend_(char*, int*); extern void hstbk1_(int*, char*, float*, float*, int*); extern void hstfl1_(int*, float *); extern void hstbk2_(int*, char*, float*, float*, int*, float*, float*, int*); extern void hstfl2_(int*, float*, float*); extern void hstdel_(int*); extern void hstout_(char *name, int *namelen); #define NAME_LEN 80 /* strctof */ void strctof(f, c, n) char *f, *c; int n; { int i; if(c){ strncpy(f, c, n); i = strlen(c); }else{ i = 0; } for(; i<n; i++) f[i] = ' '; } /* initialize */ int hb_init(){ char name[NAME_LEN]; int len; if(!cflag){ strctof(name, SHMNAME, NAME_LEN); len = strlen(SHMNAME); if(shmflag){ hstshm_(name, &len); }else{ hstini_(name, &len); } } return(0); } /* exit */ int hb_exit(){ char name[NAME_LEN]; int len; if(!cflag){ strctof(name, SHMNAME, NAME_LEN); len = strlen(SHMNAME); hstend_(name, &len); } return(0); } /* histgram output */ int hb_hist_out(name) char *name; { int len; char nam[NAME_LEN]; if(!cflag){ strctof(nam, name, NAME_LEN); len = strlen(name); hstout_(nam, &len); fprintf(stderr, "Histogram data have been saved in '%s'.\n", name); } return(0); } /* hbk1 */ int hbk1(id, name, title, min, max, nbin) int id; char *name, *title; double min, max; int nbin; { float fmin, fmax; char str[256]; char nam[256]; if(!cflag){ fmin = (float)min; fmax = (float)max; sprintf(str, "%-10s %s", name, title); strctof(nam, str, 256); hstbk1_(&id, nam, &fmin, &fmax, &nbin); } return(0); } /* hbk2 */ int hbk2(id, name, title, min1, max1, nbin1, min2, max2, nbin2) int id; char *name, *title; double min1, max1, min2, max2; int nbin1, nbin2; { float fmin1, fmax1, fmin2, fmax2; char str[256]; char nam[256]; if(!cflag){ fmin1 = (float)min1; fmax1 = (float)max1; fmin2 = (float)min2; fmax2 = (float)max2; sprintf(str, "%-10s %s", name, title); strctof(nam, str, 256); hstbk2_(&id, nam, &fmin1, &fmax1, &nbin1, &fmin2, &fmax2, &nbin2); } return(0); } /* hfil1 */ int hfil1(id,d) int id; double d; { float f; hist_data_t hd; if(dr_exists(d)){ f = (float)d; if(cflag){ /* child process */ hd.hid = id; hd.f1 = f; hd.f2 = 0.; write_child_data((char*)&hd, sizeof(hist_data_t)); }else{ if(d<-1.0E+50 || 1.0E+50<d){ // fprintf(stderr, "hfil1: out of data range: id=%3d data=%15.7e\n", id, d); }else{ hstfl1_(&id, &f); } } } return(0); } /* hfil2 */ int hfil2(id,d1,d2) int id; double d1, d2; { float f1, f2; hist_data_t hd; if(dr_exists(d1) && dr_exists(d2)){ f1 = (float)d1; f2 = (float)d2; if(cflag){ /* child process */ hd.hid = id; hd.f1 = f1; hd.f2 = f2; write_child_data((char*)&hd, sizeof(hist_data_t)); }else{ if(d1<-1.0E+50 || 1.0E+50<d1 || d2<-1.0E+50 || 1.0E+50<d2){ // fprintf(stderr, "hfil1: out of data range: id=%3d data=%15.7e,%15.7e\n", id, d1, d2); }else{ hstfl2_(&id, &f1, &f2); } } } return(0); } /* hstdel */ int hstdel(id) int id; { if(!cflag){ hstdel_(&id); } return(0); } /* Local Variables: mode: C tab-width: 2 End: */ <file_sep>/* fread.c --- analyzer program Author: <NAME> Facility: Department of Physics, University of Tokyo Created: 04-MAY-1997 by <NAME> Version 1.00 04-MAY-1997 by <NAME> (fread) Version 1.22 06-MAY-1997 by <NAME> (fread) Version 2.00 03-JUN-2000 by <NAME> (for analyzer) Version 3.00 31-JUL-2000 by <NAME> (analyzer.c) */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #ifdef OSF1 #include <strings.h> #endif #include <time.h> #include <stdarg.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <signal.h> #include <errno.h> #include <string.h> #include "freadin.h" #include "builder.h" #include "histogram.h" static char title[] = "Analyzer ver 1.00 31-JUL-2000"; #if 0 static char title[] = "FRead ver 1.22 24-JUN-1997"; static char title[] = "FRead ver 1.22 04-JUN-1997"; static char title[] = "FRead ver 1.21 17-JUN-1997 (Stop at the End of Run)"; static char title[] = "FRead ver 1.10 06-MAY-1997"; static char title[] = "FRead ver 1.00 04-MAY-1997"; static char title[] = "FRead ver 2.00 03-JUN-2000"; #endif int pflag = 0; /* parent process flag */ int cflag = 0; /* child process flag */ int childn = 0; /* child number for child process */ #define MAX_NFDEF 10 FILE *findef = (FILE*)NULL; #if USE_PAW FILE *falias = (FILE*)NULL; #endif int byte_order=BIG_ENDIAN; int swap=0; int nrun = 0; int nblk = 0; char *ofile = (char*)NULL; int line; /* for lex */ int shmflag = 1; int rootflag = 0; #if USE_GRUTINIZER // added on 2017.1.25 by <NAME> #else extern int neval; extern int level; int msgid = -1; int msgkey = -1; int parse_error; int format=FORMAT_UNDEFINED; /* data format */ int nchild = 0; /* number of child processes */ child_data_t cd[MAX_NCHILD]; /* child data */ #define MAX_NFDEF 10 int nfdef = 0; char *deffnam[MAX_NFDEF]; char *filename; char *finnam; int findat = 0; FILE *fout = (FILE*)NULL; #if 1 int blksize = 0x100000; /* Default = 256KByte */ #else int blksize = 0x10000; /* Default = 64KByte */ #endif unsigned char *dbuf = (unsigned char*)NULL; unsigned char *sbuf = (unsigned char*)NULL; char *hbfnam = (char*)NULL; extern void yyparse(); #endif /* swaps --- swap the short words in an integer */ void swaps(data) unsigned int *data; { union val{ int vint; short vshort[2]; } v, *vp; v.vint = *data; vp = (union val*)data; vp->vshort[0] = v.vshort[1]; vp->vshort[1] = v.vshort[0]; } static char *cd_buf = (char*)NULL; static int cd_pos = 0; /* write_child_data --- buffer child data and write */ void write_child_data(buf, size) char *buf; int size; { #define CD_BUF_SIZE 65536*10 if(cd_buf==(char*)NULL){ cd_buf = (char*)malloc(CD_BUF_SIZE); if(cd_buf==(char*)NULL){ fprintf(stderr, "write_child_data: could not allocate memory.\n"); exit(-1); } } memmove(&cd_buf[cd_pos], buf, size); cd_pos+=size; if(cd_pos>(CD_BUF_SIZE*4/5)){ flush_child_data(); } } /* flush_child_data --- flush child data */ void flush_child_data() { write(1, cd_buf, cd_pos); //fprintf(stderr, "flush size = %d\n", cd_pos); cd_pos = 0; } /* show error */ void showerr(char *format, ...) { va_list args; va_start(args, format); vfprintf(stderr, format, args); va_end(args); } #if USE_GRUTINIZER // added on 2017.1.25 by <NAME> #else /* show_info --- show information */ static void show_info() { fprintf(stderr, "%s\n", title); } /* usage */ void usage(){ show_info(); fprintf(stderr, "Analyzer\n"); fprintf(stderr, " Usage: %s [-h] [-d def_file] [-o file] [-b blk_size] [file_name]\n", filename); fprintf(stderr, " file_name ... file to read (default=stdin)\n"); fprintf(stderr, " Option: -h ... show this help\n"); fprintf(stderr, " Option: -o ... output histograms to the specified file instead of shared memory\n"); fprintf(stderr, " Option: -d ... read a definition file (default = hist.def) \n"); fprintf(stderr, " -b ... specify block size in KBytes (default=%d)\n", blksize/1024); } int init_msg(){ FILE *fd; fd = fopen(KEYFILE, "w"); if(fd==(FILE*)NULL){ fprintf(stderr, "init_msg: cound not open key file: %s.\n", strerror(errno)); return(-1); } fprintf(fd, "%d\n", getpid()); fclose(fd); msgkey = ftok(KEYFILE,'A'); msgid = msgget(msgkey,0666 | IPC_CREAT); return(0); } void exit_msg(){ if(msgid>=0){ msgctl(msgid, IPC_RMID, NULL); msgid = -1; } remove(KEYFILE); } void domsg(){ mesg_t msgp; int res; int nc; while(1){ res = msgrcv(msgid, &msgp, MaxMsgLen, cflag ? getpid():MSG_CMD, IPC_NOWAIT); if(res==0) break; if(res<0){ if(errno==EAGAIN) return; if(errno==ENOMSG) return; fprintf(stderr, "domsg: error in msgrcv: %s\n", strerror(errno)); return; } /* do message */ if((cflag && msgp.mtype==getpid()) || (!cflag && msgp.mtype==MSG_CMD)){ line = 1; level = 0; fin.type = FIN_STR; fin.pstr = &msgp.mtext[0]; fin.istr = 0; #if 1 fprintf(stderr, "\n%s", fin.pstr); #endif neval++; /* for evaluations in yyparse() */ yyparse(); if(pflag){ /* send the smae message to child processes */ for(nc=0; nc<nchild; nc++){ msgp.mtype = cd[nc].pid; res = msgsnd(msgid, &msgp, strlen(msgp.mtext)+1, 0); if(res<0){ fprintf(stderr, "task: error in msgsd: %s\n", strerror(errno)); break; } } } }else{ fprintf(stderr, "domsg: unknown message type %d.\n", msgp.mtype); break; } } } /* reply_parent_buf --- reply to a parent at the end of a buffer */ void reply_parent_buf() { hist_data_t hd; if(!cflag) return; // fprintf(stderr, "reply\n"); hd.hid = -1; hd.f1 = 0.; hd.f2 = 0.; write_child_data((char*)&hd,sizeof(hist_data_t)); flush_child_data(); } /* read_child_buf --- read a buffer from child processes*/ int read_child_buf() { #define MAX_HIST_DATA 10000 fd_set readfds; struct timeval timeout; int nc; static hist_data_t hd[MAX_HIST_DATA]; static int cd_read_prev=0; hist_data_p h; int i, k, n, size, tsize; if(!pflag) return 0; while(1){ /* no loop happens when the final 'break' is active */ for(i=0; i<nchild; i++){ nc = (i+cd_read_prev+1)%nchild; FD_ZERO(&readfds); FD_SET(cd[nc].readfd, &readfds); n=cd[nc].readfd+1; timeout.tv_sec = 0; timeout.tv_usec = 0; if(select(n, &readfds, NULL, NULL, &timeout)>0) break; } if(i>=nchild) break; cd_read_prev = nc; tsize = read(cd[nc].readfd, hd, sizeof(hist_data_t)*MAX_HIST_DATA); if(tsize<=0){ if(errno==EINTR || errno==EAGAIN) continue; } n = tsize/sizeof(hist_data_t); if(n*sizeof(hist_data_t)!=tsize){ n++; read_in(cd[nc].readfd, (unsigned char*)hd, &tsize, n*sizeof(hist_data_t)); } h = hd; for(i=0; i<n; i++){ if(h->hid==-1){ cd[nc].n_sent_buf--; }else if(HID_SCALER <= h->hid && h->hid < HID_SCALER_MAX){ if(dr_exists(h->f1)) add_scaler(h->hid-HID_SCALER, dr_int(h->f1)); }else{ hfil2(h->hid, h->f1, h->f2); } h++; } break; /* no loop (this is the default usage) */ } n = 0; for(nc=0; nc<nchild; nc++) n += cd[nc].n_sent_buf; return(n); } // According to the typical event size, you have to reduce the following value, // otherwize, the analysis in parallel mode, will stop. #define MAX_N_SENT_BUF 50 /* send_child_buf --- send a buffer to one of child processes to analyze */ void send_child_buf(buf, size) unsigned char *buf; int size; { int i, nc; static int cd_send_prev=0; if(!pflag) return; // fprintf(stderr, "send\n"); while(1){ for(i=0; i<nchild; i++){ nc = (i+cd_send_prev+1)%nchild; if((format==FORMAT_DST_1 && cd[nc].n_sent_buf<MAX_N_SENT_BUF) || cd[nc].n_sent_buf<=0){ write(cd[nc].writefd,&size,sizeof(int)); write(cd[nc].writefd,buf,size); cd[nc].n_sent_buf++; // fprintf(stderr, "NC=%1d, Count=%5d ++\n", nc, cd[nc].n_sent_buf); cd_send_prev = nc; return; } } // fprintf(stderr, "read_child_buf()\n"); read_child_buf(); } } /* check_format */ int check_format(buf) unsigned char *buf; { int i, l; l = (buf[0]<<24)|(buf[1]<<16)|(buf[2]<<8)|(buf[3]<<0); switch(l){ case 0xffff0006: case 0xffff0600: case 0xffff0008: case 0xffff0800: return(FORMAT_TAMIDAQ); case 0x424c4431: case 0x4c423144: return(FORMAT_BLD1); case 0x00010000: case 0x01000000: case 0x00000001: case 0x00000100: case 0xffff0000: return(FORMAT_MARS); } if(dst_chk_format(buf)){ return(FORMAT_DST_1); } showerr("Unknown format: "); for(i=0; i<16; i++){ showerr("%.2x ", buf[i]); } showerr("\n"); return(FORMAT_UNKNOWN); } /* read_in */ int read_in(fd, buf, pos, size) int fd; unsigned char *buf; int *pos; int size; { int tsize; while(*pos<size){ tsize = read(fd, &buf[*pos], size-*pos); if(tsize<=0){ if(errno==EINTR || errno==EAGAIN) continue; if(*pos==0) return(-1); return(*pos); } *pos += tsize; } return(*pos); } /* file_read */ int file_read() { int size, tsize, asize, s, h, res; int bsize, tmp; int pos; int nc; unsigned char *p; int endflag=0; nblk = 0; size = 0; if(format==FORMAT_UNDEFINED){ if(cflag){ tmp=0; read_in(findat, (unsigned char*)&bsize, &tmp, sizeof(int)); read_in(findat, dbuf, &size, bsize); }else{ read_in(findat, dbuf, &size, 64); } format = check_format(dbuf); /* showerr("format = %d\n", format); */ switch(format){ case FORMAT_TAMIDAQ: fprintf(stderr, "Data format: RCNP\n"); break; case FORMAT_BLD1: fprintf(stderr, "Data format: RCNP BLD1\n"); break; case FORMAT_MARS: fprintf(stderr, "Data format: MARS\n"); swap = !swap; break; case FORMAT_DST_1: showerr("Data format: DST ver 1.0\n"); break; case FORMAT_UNKNOWN: default: return(-1); } } switch(format){ case FORMAT_BLD1: while(1){ if(cflag){ if(size<bsize){ tmp=0; if(read_in(findat, (unsigned char*)&bsize, &tmp, sizeof(int))<0) break; if(read_in(findat, dbuf, &size, bsize-size)<0) break; } s = ntohl(((bld1_header_t*)dbuf)->bsize); h = ntohl(((bld1_header_t*)dbuf)->hsize); }else{ if(read_in(findat, dbuf, &size, sizeof(bld1_header_t))<0) break; s = ntohl(((bld1_header_t*)dbuf)->bsize); h = ntohl(((bld1_header_t*)dbuf)->hsize); if(s+h>blksize){ showerr("Buffer size is too small. Please enlarge the block size" "to larger than %d Bytes.\n", s+h); endflag = 1; return(-1); } read_in(findat, dbuf, &size, s+h); } if(size<s+h){ showerr("Incomplete data. Ignore %d byte data.\n", size); endflag = 1; break; } p = &dbuf[h]; if(swap){ swab(p, sbuf, s); if(read_blk_rcnp((unsigned short*)sbuf, s)) endflag = 1; }else{ if(read_blk_rcnp((unsigned short*)p, s)) endflag = 1; } send_child_buf(dbuf, s+h); reply_parent_buf(); #if USE_ROOT hb_update(); #endif size = 0; if(shmflag) domsg(); } break; case FORMAT_TAMIDAQ: bsize = blksize; while(1){ if(size<bsize){ if(cflag){ tmp=0; if(read_in(findat, (unsigned char*)&bsize, &tmp, sizeof(int))<0) break; if(read_in(findat, dbuf, &size, bsize)<0) break; }else{ if(read_in(findat, dbuf, &size, blksize)<0) break; } } if(size<bsize){ showerr("Avoid the last %d bytes (b)\n", size); endflag = 1; break; } if(swap){ swab(dbuf, sbuf, size); if(read_blk_rcnp((unsigned short*)sbuf, size)) endflag = 1; }else{ if(read_blk_rcnp((unsigned short*)dbuf, size)) endflag = 1; } send_child_buf(dbuf, size); reply_parent_buf(); #if USE_ROOT hb_update(); #endif size = 0; //if(shmflag) domsg(); domsg(); } break; case FORMAT_MARS: while(read_in(findat, dbuf, &size, blksize)>=0){ if(size<blksize){ showerr("Avoid the last %d bytes (c)\n", size); endflag = 1; break; } if(swap){ swab(dbuf, sbuf, size); //if(read_blk_mars((unsigned short*)sbuf, size)) endflag = 1; }else{ //if(read_blk_mars((unsigned short*)dbuf, size)) endflag = 1; } send_child_buf(dbuf, size); reply_parent_buf(); #if USE_ROOT hb_update(); #endif size = 0; if(shmflag) domsg(); } break; case FORMAT_DST_1: if(!cflag) if(read_in(findat, dbuf, &size, blksize)<0) break; if(pflag){ /* read and send header */ pos = 0; if(dst_read_data(dbuf, &pos, size)!=1){ fprintf(stderr, "Could not find the position of data start\n"); exit(-1); } for(nc=0; nc<nchild; nc++){ send_child_buf(dbuf, pos); // send header to each child } memmove(dbuf, &dbuf[pos], size-pos); size -= pos; /* read and send data */ while(read_in(findat, dbuf, &size, blksize)>=0){ pos = 0; while(pos<size*3/4){ s = pos; res = dst_read_data(dbuf, &pos, size); if(res<0) break; send_child_buf(&dbuf[s], pos-s); } if(res<0) break; memmove(dbuf, &dbuf[pos], size-pos); size -= pos; #if USE_ROOT hb_update(); #endif if(shmflag) domsg(); } }else{ pos = 0; if(dst_read_data(dbuf, &pos, size)!=1){ // read header fprintf(stderr, "Could not find the position of data start\n"); exit(-1); } write(2,dbuf,pos); // for debug, output header data reply_parent_buf(); memmove(dbuf, &dbuf[pos], size-pos); size -= pos; bsize = blksize; while(1){ if(cflag){ tmp=0; // position (in the memory of the variable 'bsize') if(read_in(findat, (unsigned char*)&bsize, &tmp, sizeof(int))<0) break; if(read_in(findat, dbuf, &size, bsize)<0) break; if(size<bsize){ showerr("Avoid the last %d bytes (d)\n", size); break; } }else{ if(read_in(findat, dbuf, &size, blksize)<0) break; } res = 0; pos = 0; while(pos<size*3/4){ s = pos; res=dst_read_data(dbuf, &pos, size); if(res<0){ showerr("Avoid the last %d bytes (e)\n", size-s); break; } } if(res<0) break; memmove(dbuf, &dbuf[pos], size-pos); size -= pos; reply_parent_buf(); if(shmflag) domsg(); } } break; default: return(-1); } if(!ofile) domsg(); if(pflag){ #if 0 for(nc=0; nc<nchild; nc++){ close(cd[nc].writefd); cd[nc].writefd = -1; } #endif while((res=read_child_buf())){ //fprintf(stderr, "remaining bufs = %d\n", res); usleep(100000); } } fprintf(stderr, "---- End of fread. The last block number is %d ----\n", nblk); return(0); } void cleanup(){ if(dbuf){ free(dbuf); dbuf = (unsigned char*)NULL; } if(sbuf){ free(sbuf); sbuf = (unsigned char*)NULL; } if(!ofile) exit_msg(); hb_exit(); } void sig_handler(int signal){ fprintf(stderr, "Caught signal %d.\n", signal); event_exit(); cleanup(); exit(1); } /* do initialization task */ int fread_init(bsize) int bsize; { if(bsize) blksize = bsize; swap = byte_order = htons(0x0102)==0x0102 ? BIG_ENDIAN:LITTLE_ENDIAN; dbuf = malloc(blksize+65536); if(dbuf==(unsigned char*)NULL){ fprintf(stderr, "Could not allocate memory(%s)\n", strerror(errno)); exit(1); } sbuf = malloc(blksize+65536); if(sbuf==(unsigned char*)NULL){ fprintf(stderr, "Could not allocate memory(%s)\n", strerror(errno)); exit(1); } /* initialize sub-modules */ if(dr_init()) exit(1); event_init(); if(!ofile && init_msg()<0) exit(1); return 0; } /* do exit task */ int fread_exit(){ if(dr_exit()) exit(1); #if USE_PAW if(falias){ fclose(falias); falias = (FILE*)NULL; } #endif cleanup(); return(0); } /* read definition file */ int fread_readdef() { int i; char *fnam; if(nfdef==0){ /* set the default definition file name */ deffnam[0] = DEFFNAM; nfdef++; } for(i=0; i<nfdef; i++){ /* open the definition file */ fnam = deffnam[i]; showerr("Read the definition file '%s'.\n", fnam); findef = fopen(fnam, "r"); if(findef==(FILE*)NULL){ showerr("Could not open the definition file '%s'.\n", fnam); exit(1); } /* read definition file */ fin.type = FIN_FILE; fin.file = findef; line = 1; parse_error = 0; neval++; /* for evaluations in yyparse() */ yyparse(); /* close the definition file */ fclose(findef); findef = (FILE*)NULL; /* check the error */ if(parse_error){ showerr("Errors are detected in '%s'.\n", fnam); exit(1); } } #if DEBUG_THINKPAD neval++; histogram(); #if 0 dr_show(); exit(0); #endif #endif return 0; } /* read data ana analize them */ int fread_ana(fd) int fd; { int i; findat = fd; finnam = ""; /* message */ showerr("Analyze '%s' with blksize=%dkB.\n", finnam, blksize/1024); /* main tasks */ #if 0 for(i=1; i<16; i++) signal(i, sig_handler); #endif signal(SIGINT, sig_handler); signal(SIGQUIT, sig_handler); signal(SIGPIPE, sig_handler); // signal(SIGHUP,domsg); //signal(SIGHUP, sig_handler); signal(SIGHUP,SIG_IGN); file_read(); return 0; } #define MAX_NARGS 20 /* main */ int main(argc, argv) int argc; char *argv[]; { int i; int ac; char **av; int bsize=0; int fin; pid_t pid; int pfd, pfd1[2], pfd2[2]; char *newargv[MAX_NARGS+3]; char str[256]; char cnum[256]; // for(i=0; i<argc; i++){ // fprintf(stderr, "arg %2d = '%s'\n",i,argv[i]); // } // exit(0); ac = argc; av = argv; filename = *av++; ac--; /* check the arguments */ while(ac>0){ if(av[0][0]=='-'){ if(strlen(av[0])!=2){ fprintf(stderr, "Unknown flag '%s'.\n",av[0]); usage(); exit(1); } switch(av[0][1]){ case 'b': ac--; av++; if(ac<=0){ fprintf(stderr, "no argument to '-b'.\n"); usage(); exit(1); } bsize = atoi(*av)*1024; break; #if 0 case 's': swap = !swap; break; #endif case 'd': ac--; av++; if(ac<=0){ fprintf(stderr, "no argument to '-d'.\n"); usage(); exit(1); } deffnam[nfdef] = *av; nfdef++; break; case 'o': ac--; av++; if(ac<=0){ fprintf(stderr, "no argument to '-o'.\n"); usage(); exit(1); } ofile = *av; break; case 'f': ac--; av++; if(ac<=0){ fprintf(stderr, "no argument to '-f'.\n" ); usage(); exit(1); } shmflag = 0; hbfnam = *av; break; case 'p': ac--; av++; if(ac<=0){ fprintf(stderr, "no argument to '-p'.\n" ); usage(); exit(1); } nchild = atoi(*av); if(nchild<1){ fprintf(stderr, "Argument of p (number of child processes) " "must be larger than 0.\n"); usage(); exit(1); } if(MAX_NCHILD < nchild){ fprintf(stderr, "Argument of p (number of child processes) " "must be <= %d (=MAX_NCHILD).\n", MAX_NCHILD); usage(); exit(1); } if(!cflag){ /* cflag has higher priority than pflag */ pflag = 1; } break; case 'c': ac--; av++; if(ac<=0){ fprintf(stderr, "no argument to '-c'.\n" ); usage(); exit(1); } cflag = 1; childn = atoi(*av); fprintf(stderr, "Child process number = %d\n", childn); fprintf(stderr, "Process ID = %d\n", getpid()); if(pflag){ pflag = 0; nchild = 0; } break; case 'h': case 'H': usage(); exit(0); break; default: fprintf(stderr, "Unknown flag '%s'.\n",av[0]); usage(); exit(1); } }else{ break; } ac--; av++; } if(cflag){ fout = fopen("/dev/null","w"); }else{ fout = stdout; } fprintf(fout, "%s\n", title); if(ac>1){ usage(); exit(1); } fin = 0; /* standard input */ if(!cflag && ac==1){ if(*av){ /* open data file */ fin = open(*av, O_RDONLY); if(fin<0){ fprintf(stderr, "Could not open file '%s'.", *av); exit(1); } } } /* create child processes */ if(pflag){ /* create arguments */ if(argc>MAX_NARGS){ fprintf(stderr, "main: too many arguments to fork\n"); exit(-1); } newargv[0] = argv[0]; newargv[1] = "-c"; /* append -c flag */ newargv[2] = cnum; /* child number */ for(i=1; i<argc; i++){ newargv[i+2] = argv[i]; } newargv[i+2] = (char*)NULL; /* fork child processes */ for(i=0; i<nchild; i++){ if(pipe(pfd1)<0 || pipe(pfd2)<0){ fprintf(stderr, "main: Error in pipe();\n"); exit(-1); } pid = fork(); if(pid==-1){ fprintf(stderr, "main: Error in fork();\n"); exit(-1); } if(pid==0){ /* child process */ close(0); dup(pfd1[0]); close(1); dup(pfd2[1]); close(pfd1[0]); close(pfd1[1]); close(pfd2[0]); close(pfd2[1]); sprintf(str, FNAM_CHILD_STDERR, i); pfd = open(str,O_WRONLY|O_CREAT|O_TRUNC,0644); if(pfd==-1){ fprintf(stderr, "Error in opening file '%s'.\n", str); perror("open"); exit(-1); } close(2); dup(pfd); sprintf(cnum, "%d", i); /* exec*/ execvp(argv[0], newargv); /* Never come here */ } /* parent process */ cd[i].pid = pid; close(pfd1[0]); close(pfd2[1]); cd[i].readfd = pfd2[0]; cd[i].writefd = pfd1[1]; } } /* initialize */ fread_init(bsize); fread_readdef(); /* do analysis */ fread_ana(fin); /* do end tasks */ fread_exit(); } #if defined (f2cFortran) void * MAIN__ = main; #endif #endif /* Local Variables: mode: C tab-width: 2 End: */ <file_sep>/* ray.c ---- raytracing Version 1.00 10-JUL-2000 by <NAME> */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include "freadin.h" #include "histogram.h" #include "analyzer.h" #if DIM!=NCHAMB_4P *** Error Not supported *** #endif /* show matrix */ static void show_matrix(m) double m[DIM][DIM+1]; { int i, j; showerr("matrix\n"); for(i=0; i<DIM; i++){ for(j=0; j<DIM+1; j++){ showerr("%10.3lf ", m[i][j]); } showerr("\n"); } } /* solve matrix */ static int solve_matrix(m) double m[DIM][DIM+1]; { int i, j, k; double f; for(i=DIM-1; i>=0; i--){ if(fabs(m[i][i])<1e-30){ showerr("solve_matrix: could not solve the matrix\n"); return(-1); if(i<=0) break; } for(j=i-1; j>=0; j--){ f = m[j][i]/m[i][i]; for(k=0; k<DIM+1; k++){ m[j][k] -= m[i][k]*f; } } } for(i=0; i<DIM; i++){ for(j=0; j<i; j++) m[i][DIM] -= m[i][j]*m[j][DIM]; /* m[i][i] is already checked to be non zero */ m[i][DIM] /= m[i][i]; } return(0); } /* show_vec */ void show_vec(vec) vec_p vec; { showerr("(%10.3f, %10.3f, %10.3f)", vec->x, vec->y, vec->z); } /* vec_mag ... calculate magnitude of a vector */ static double vec_mag(vec) vec_p vec; { return(sqrt(vec->x*vec->x + vec->y*vec->y + vec->z*vec->z)); } /* rotate ray along the x-axis */ int ray_rotate_x(ray, ang) ray_p ray; double ang; { vec_rec org, dir; double c, s; if(dr_is_nothing(ang)) return(-1); c = cos(ang); s = sin(ang); dir.x = ray->dir.x; dir.y = c*ray->dir.y-s*ray->dir.z; dir.z = s*ray->dir.y+c*ray->dir.z; org.x = ray->org.x; org.y = c*ray->org.y-s*ray->org.z; org.z = s*ray->org.y+c*ray->org.z; if(fabs(dir.z)>1e-100){ dir.x /= dir.z; dir.y /= dir.z; dir.z = 1.0; org.x -= dir.x*org.z; org.y -= dir.y*org.z; org.z = 0.0; } ray->org = org; ray->dir = dir; return(0); } /* rotate ray along the y-axis */ int ray_rotate_y(ray, ang) ray_p ray; double ang; { vec_rec org, dir; double c, s; if(dr_is_nothing(ang)) return(-1); c = cos(ang); s = sin(ang); dir.y = ray->dir.y; dir.z = c*ray->dir.z-s*ray->dir.x; dir.x = s*ray->dir.z+c*ray->dir.x; org.y = ray->org.y; org.z = c*ray->org.z-s*ray->org.x; org.x = s*ray->org.z+c*ray->org.x; if(fabs(dir.z)>1e-100){ dir.x /= dir.z; dir.y /= dir.z; dir.z = 1.0; org.x -= dir.x*org.z; org.y -= dir.y*org.z; org.z = 0.0; } ray->org = org; ray->dir = dir; return(0); } /* rotate ray along the z-axis */ int ray_rotate_z(ray, ang) ray_p ray; double ang; { vec_rec org, dir; double c, s; if(dr_is_nothing(ang)) return(-1); c = cos(ang); s = sin(ang); dir.z = ray->dir.z; dir.x = c*ray->dir.x-s*ray->dir.y; dir.y = s*ray->dir.x+c*ray->dir.y; org.z = ray->org.z; org.x = c*ray->org.x-s*ray->org.y; org.y = s*ray->org.x+c*ray->org.y; if(fabs(dir.z)>1e-100){ dir.x /= dir.z; dir.y /= dir.z; dir.z = 1.0; org.x -= dir.x*org.z; org.y -= dir.y*org.z; org.z = 0.0; } ray->org = org; ray->dir = dir; return(0); } /* get intersection point (in the normal coordinate system)*/ int ray_intersection_pt(ray, plane, pt) ray_p ray; vec_p plane; vec_p pt; { vec_rec x; double z1, cx, cy, cz; double costh, sinth, cosph, sinph; double p; dr_set_nothing(&pt->x); dr_set_nothing(&pt->y); dr_set_nothing(&pt->z); if(dr_is_nothing(plane->x)||dr_is_nothing(plane->x)||dr_is_nothing(plane->x)) return(-1); if(dr_is_nothing(ray->dir.x)||dr_is_nothing(ray->dir.y)||dr_is_nothing(ray->dir.z)) return(-1); if(dr_is_nothing(ray->org.x)||dr_is_nothing(ray->org.y)||dr_is_nothing(ray->org.z)) return(-1); z1 = plane->x; sinth = sin(plane->y); costh = cos(plane->y); sinph = sin(plane->z); cosph = cos(plane->z); cx = sinth*cosph; cy = sinph; cz = costh*cosph; p = cx*ray->dir.x - cy*ray->dir.y + cz*ray->dir.z; if(fabs(p)<1e-100) return(-1); p = -(cx*ray->org.x - cy*ray->org.y + cz*(ray->org.z-z1))/p; /* Normal Coordinate (intersect position)*/ pt->x = ray->org.x + ray->dir.x*p; pt->y = ray->org.y + ray->dir.y*p; pt->z = ray->org.z + ray->dir.z*p; return(0); } /* get intersection point (in the coordinate system on the specified plane)*/ int ray_intersection(ray, plane, pt) ray_p ray; vec_p plane; vec_p pt; { vec_rec x; double z1; double costh, sinth, cosph, sinph; dr_set_nothing(&pt->x); dr_set_nothing(&pt->y); dr_set_nothing(&pt->z); if(dr_is_nothing(plane->x)||dr_is_nothing(plane->x)||dr_is_nothing(plane->x)) return(-1); if(dr_is_nothing(ray->dir.x)||dr_is_nothing(ray->dir.y)||dr_is_nothing(ray->dir.z)) return(-1); if(dr_is_nothing(ray->org.x)||dr_is_nothing(ray->org.y)||dr_is_nothing(ray->org.z)) return(-1); z1 = plane->x; sinth = sin(plane->y); costh = cos(plane->y); sinph = sin(plane->z); cosph = cos(plane->z); /* Normal Coordinate (intersect position)*/ if(ray_intersection_pt(ray, plane, &x)<0) return -1; /* Coordinate on the plane to which the line intersects */ /* projection of (x.x, x.y, x.z-z1) to (cos(th), 0, -sin(th)) */ pt->x = x.x*costh - (x.z-z1)*sinth; /* projection to (sin(ph)sin(th), cosph, sin(ph)cos(th)) */ pt->y = x.x*sinph*sinth + x.y*cosph + (x.z-z1)*sinph*costh; /* distance */ pt->z = sqrt(pt->x*pt->x+pt->y*pt->y); return(0); } /* show_plane */ static void show_wire(wire) wire_p wire; { showerr("org = "); show_vec(&wire->org); showerr("\n"); showerr("dsp = "); show_vec(&wire->dsp); showerr("\n"); showerr("dir = "); show_vec(&wire->dir); showerr("\n"); } /* ray_4p_get_ncomb ---- get number of combinations */ int ray_4p_get_ncomb(chamb) chamber_p chamb; { plane_p plane; int j, ncomb; int ic, ipl; /* count number of combinations */ ncomb = 1; for(ipl=0; ipl<chamb->npl; ipl++){ plane = &chamb->plane[ipl]; j = 0; for(ic=0; ic<plane->nc; ic++){ if(plane->clst[ic].posid==POSID_NOERR && dr_exists(plane->clst[ic].pos)) j++; } ncomb *= j; } return(ncomb); } /* ray_4p_get_ncomb ---- get number of combinations */ int ray_4p_get_max_nclust(chamb) chamber_p chamb; { int n=0; int ipl; plane_p plane; for(ipl=0; ipl<chamb->npl; ipl++){ plane = &chamb->plane[ipl]; if(plane->nc>n) n = plane->nc; } return n; } /* ray_4p ---- calculate ray from 4 chamber positions */ int ray_4p(chamb) chamber_p chamb; { vec_rec a; double pos; int ipl; int errid; plane_p plane; ray_p ray; wire_p wire; #if 0 fprintf(stderr, "enter ray_4p()...%s\n",chamb->name); #endif ray = &chamb->ray; ray->rayid = RAYID_UNDEF; errid = RAYID_NOERR; /* chi2 is not calculated in this procedure. For making setup of histogram definitions easier, the default chi2 is set as 0.*/ chamb->chi2 = 0.0; if(chamb->npl!=NCHAMB_4P){ showerr("ray_4p: unsupported number of planes (%d)\n", chamb->npl); return(-1); } for(ipl=0; ipl<chamb->npl; ipl++){ plane = &chamb->plane[ipl]; wire = &plane->wire; if(!wire->ok){ errid = RAYID_CONFG; break; } if(plane->nc>=2){ /* multi cluster events are not analyzed in this procedure*/ errid = RAYID_MCLUST; /* count number of multi cluster planes */ for(ipl=0; ipl<NCHAMB_4P; ipl++){ if(chamb->plane[ipl].nc>=2){ #if 1 errid++; #else errid += 1<<ipl; #endif } } chamb->ncomb = ray_4p_get_ncomb(chamb); break; } pos = plane->clst[0].pos; if(plane->clst[0].posid!=POSID_NOERR || dr_is_nothing(pos)){ errid += 1<<ipl; continue; } a.x = (wire->org.x+wire->dsp.x*pos); a.y = (wire->org.y+wire->dsp.y*pos); a.z = (wire->org.z+wire->dsp.z*pos); chamb->m[ipl][0] = wire->dir.y; chamb->m[ipl][1] = -wire->dir.x; chamb->m[ipl][2] = wire->dir.y*a.z; chamb->m[ipl][3] = -wire->dir.x*a.z; chamb->m[ipl][4] = wire->dir.y*a.x - wire->dir.x*a.y; } if(errid==RAYID_NOERR){ /* show_matrix(m); */ if(solve_matrix(chamb->m)<0){ errid = RAYID_TRACE; }else{ /* show_matrix(m); */ /* set origin/direction */ ray->org.x = chamb->m[0][NCHAMB_4P]; /* origin x */ ray->org.y = chamb->m[1][NCHAMB_4P]; /* y */ ray->org.z = 0.0; /* z */ ray->dir.x = chamb->m[2][NCHAMB_4P]; /* direction x */ ray->dir.y = chamb->m[3][NCHAMB_4P]; /* y */ ray->dir.z = 1.0; /* z */ } } ray->rayid = errid; #if 0 fprintf(stderr, "exit chamb_4p()\n"); #endif return(errid); } /* ray_4p_fpp_v ---- calculate ray from 4 chamber positions (with VDC information)*/ int ray_4p_fpp_v(chamb, set_vertex_pos) chamber_p chamb; int (*set_vertex_pos)(); { vec_rec a; double pos; int ipl; int errid; plane_p plane; ray_p ray; wire_p wire; int nhpat; // no-hit plane pattern int mcpat; // multi-cluster plane pattern int ic; ray = &chamb->ray; ray->rayid = RAYID_UNDEF; errid = RAYID_NOERR; /* chi2 is not calculated in this procedure. For making setup of histogram definitions easier, the default chi2 is set as 0.*/ chamb->chi2 = 0.0; if(chamb->npl!=NCHAMB_4P){ showerr("ray_4p: unsupported number of planes (%d)\n", chamb->npl); return(-1); } nhpat = mcpat=0; for(ipl=0; ipl<chamb->npl; ipl++){ plane = &chamb->plane[ipl]; wire = &plane->wire; if(!wire->ok){ errid = RAYID_CONFG; break; } if(plane->nc>=2){ mcpat += 1<< ipl; continue; } pos = plane->clst[0].pos; if(plane->clst[0].posid!=POSID_NOERR || dr_is_nothing(pos)){ nhpat += 1<< ipl; continue; } a.x = (wire->org.x+wire->dsp.x*pos); a.y = (wire->org.y+wire->dsp.y*pos); a.z = (wire->org.z+wire->dsp.z*pos); chamb->m[ipl][0] = wire->dir.y; chamb->m[ipl][1] = -wire->dir.x; chamb->m[ipl][2] = wire->dir.y*a.z; chamb->m[ipl][3] = -wire->dir.x*a.z; chamb->m[ipl][4] = wire->dir.y*a.x - wire->dir.x*a.y; } chamb->anapat = mcpat==0 ? nhpat : RAYID_MCLUST+mcpat; switch(mcpat|nhpat){ case 0x00: // good event break; case 0x01: case 0x02: case 0x03: if((*set_vertex_pos)(chamb, 0, 1)<0) errid = RAYID_VTPOS; break; case 0x04: case 0x08: case 0x0C: #if 0 for(ipl=0; ipl<chamb->npl; ipl++){ fprintf(stderr, "ipl=%d", ipl); plane = &chamb->plane[ipl]; for(ic=0; ic<plane->nc; ic++){ fprintf(stderr, " %7.3f", plane->clst[ic].pos); } fprintf(stderr, "\n"); } #endif if((*set_vertex_pos)(chamb, 2, 3)<0) errid = RAYID_VTPOS; break; default: errid = chamb->anapat; } if(errid==RAYID_NOERR){ /* show_matrix(m); */ if(solve_matrix(chamb->m)<0){ errid = RAYID_TRACE; }else{ /* show_matrix(m); */ /* set origin/direction */ ray->org.x = chamb->m[0][NCHAMB_4P]; /* origin x */ ray->org.y = chamb->m[1][NCHAMB_4P]; /* y */ ray->org.z = 0.0; /* z */ ray->dir.x = chamb->m[2][NCHAMB_4P]; /* direction x */ ray->dir.y = chamb->m[3][NCHAMB_4P]; /* y */ ray->dir.z = 1.0; /* z */ } } ray->rayid = errid; #if 0 fprintf(stderr, "exit chamb_4p()\n"); #endif return(errid); } /* ray_4p_mult_1p---- calculate ray from 4 chamber positions (subroutine for recursive call) */ static int ray_4p_mult_1p(chamb, nc) chamber_p chamb; int nc; { plane_p plane; wire_p wire; ray_p ray; vec_rec a; double s[NCHAMB_4P][NCHAMB_4P+1]; /* solution of ray finding matrix */ double pos; int i, j; int ic, ipl; int errid; double d, dx, dy, r, chi2; struct clst *clst; ray = &chamb->ray; if(nc<NCHAMB_4P){ plane = &chamb->plane[nc]; wire = &plane->wire; if(!wire->ok) return(ray->rayid=RAYID_CONFG); plane->ic = -1; for(ic=0; ic<plane->nc; ic++){ clst = &plane->clst[ic]; pos = clst->pos; if(clst->posid!=POSID_NOERR || dr_is_nothing(pos)) continue; a.x = (wire->org.x+wire->dsp.x*pos); a.y = (wire->org.y+wire->dsp.y*pos); a.z = (wire->org.z+wire->dsp.z*pos); chamb->m[nc][0] = wire->dir.y; chamb->m[nc][1] = -wire->dir.x; chamb->m[nc][2] = wire->dir.y*a.z; chamb->m[nc][3] = -wire->dir.x*a.z; chamb->m[nc][4] = wire->dir.y*a.x - wire->dir.x*a.y; plane->ic = ic; errid = ray_4p_mult_1p(chamb, nc+1); if(errid) return(errid); } if(plane->ic<0){ /* no legal hit */ /* check error planes */ errid = 0; for(ipl=0; ipl<chamb->npl; ipl++){ plane = &chamb->plane[ipl]; for(ic=0; ic<plane->nc; ic++){ if(plane->clst[ic].posid==POSID_NOERR && dr_exists(plane->clst[ic].pos)) break; } if(ic>=plane->nc) errid += 1<<ipl; } return(errid); } return(RAYID_NOERR); } /* show_matrix(m); */ /* use s instead of chamb->m in order no to destroy chamb->m. This bug was fixed on 23-AUG-2005. */ for(i=0; i<NCHAMB_4P; i++){ for(j=0; j<NCHAMB_4P+1; j++){ s[i][j] = chamb->m[i][j]; } } if(solve_matrix(s)<0) return(RAYID_NOERR); /* return with RAYID_NOERR is correct */ /* calculate chi square */ chi2 = 0.; dx = s[2][NCHAMB_4P]; dy = s[3][NCHAMB_4P]; for(ipl=0; ipl<chamb->npl; ipl++){ plane = &chamb->plane[ipl]; r = chamb->plane[ipl].wire.rot; d = atan(dx*cos(r)-dy*sin(r)) - atan(chamb->plane[ipl].clst[chamb->plane[ipl].ic].grad); d /= chamb->plane[ipl].ares; chi2 += d*d; } chi2 /= chamb->npl; #if 0 // Mistake? found on 26-JUNE-2009 (for counting chamb->ncomb) if(chamb->chi2<0 || chi2 < chamb->chi2){ /* take the minimum chi2 */ chamb->chi2 = chi2; if(0 <= chi2 && chi2 < chamb->max_chi2){ /* only if ch2 is less than max_chi2 */ chamb->ncomb++; /* set origin/direction */ ray->org.x = s[0][NCHAMB_4P]; /* origin x */ ray->org.y = s[1][NCHAMB_4P]; /* y */ ray->org.z = 0.0; /* z */ ray->dir.x = dx; /* direction x */ ray->dir.y = dy; /* y */ ray->dir.z = 1.0; /* z */ } } #else if(0 <= chi2 && chi2 < chamb->max_chi2){ /* only if ch2 is less than max_chi2 */ chamb->ncomb++; if(chamb->chi2<0 || chi2 < chamb->chi2){ /* take the minimum chi2 */ chamb->chi2 = chi2; /* set origin/direction */ ray->org.x = s[0][NCHAMB_4P]; /* origin x */ ray->org.y = s[1][NCHAMB_4P]; /* y */ ray->org.z = 0.0; /* z */ ray->dir.x = dx; /* direction x */ ray->dir.y = dy; /* y */ ray->dir.z = 1.0; /* z */ } } #endif return(RAYID_NOERR); } /* ray_4p_mult ---- calculate ray from 4 chamber positions (support multi clusters)*/ int ray_4p_mult(chamb) chamber_p chamb; { chamb->chi2 = -1.0; chamb->ray.rayid = RAYID_UNDEF; if(chamb->npl!=NCHAMB_4P){ showerr("ray_4p_mult: unsupported number of planes (%s)\n", chamb->npl); return(-1); } chamb->ncomb = 0; /* for counting number of combinations with chi2 less than max_chi2 */ chamb->ray.rayid = ray_4p_mult_1p(chamb, 0); if(chamb->ray.rayid==RAYID_NOERR){ if(chamb->chi2<0){ chamb->ray.rayid = RAYID_TRACE; /* matrix solve error */ }else{ switch(chamb->ncomb){ case 1: break; case 0: default: /* RAYID_MCLUST + number of combinations with chi2 less than max_chi2 */ chamb->ray.rayid = RAYID_MCLUST + chamb->ncomb; break; } } }else{ dr_set_nothing(&chamb->chi2); } return(chamb->ray.rayid); } /* ray_4p_fpp_mult_1p---- calculate ray from 4 MWPC positions with checking chi^2 (subroutine for recursive call) */ static int ray_4p_fpp_mult_1p(chamb, nc, chi2_func) chamber_p chamb; int nc; double (*chi2_func)(ray_p); { plane_p plane; wire_p wire; ray_p ray; ray_t rayt; vec_rec a; double s[NCHAMB_4P][NCHAMB_4P+1]; /* solution of ray finding matrix */ double pos; int i, j; int ic, ipl; int errid; double d, dx, dy, r, chi2; struct clst *clst; ray = &chamb->ray; if(nc<NCHAMB_4P){ plane = &chamb->plane[nc]; wire = &plane->wire; if(!wire->ok) return(ray->rayid=RAYID_CONFG); plane->ic = -1; for(ic=0; ic<plane->nc; ic++){ clst = &plane->clst[ic]; pos = clst->pos; // fprintf(stderr, "nc=%d pos=%7.3f\n", nc, pos); if(clst->posid!=POSID_NOERR || dr_is_nothing(pos)) continue; a.x = (wire->org.x+wire->dsp.x*pos); a.y = (wire->org.y+wire->dsp.y*pos); a.z = (wire->org.z+wire->dsp.z*pos); chamb->m[nc][0] = wire->dir.y; chamb->m[nc][1] = -wire->dir.x; chamb->m[nc][2] = wire->dir.y*a.z; chamb->m[nc][3] = -wire->dir.x*a.z; chamb->m[nc][4] = wire->dir.y*a.x - wire->dir.x*a.y; plane->ic = ic; errid = ray_4p_fpp_mult_1p(chamb, nc+1, chi2_func); if(errid) return(errid); } if(plane->ic<0){ /* no legal hit */ /* check error planes */ errid = 0; for(ipl=0; ipl<chamb->npl; ipl++){ plane = &chamb->plane[ipl]; for(ic=0; ic<plane->nc; ic++){ if(plane->clst[ic].posid==POSID_NOERR && dr_exists(plane->clst[ic].pos)) break; } if(ic>=plane->nc) errid += 1<<ipl; } return(errid); } return(RAYID_NOERR); } /* show_matrix(m); */ /* use s instead of chamb->m in order no to destroy chamb->m. This bug was fixed on 23-AUG-2005. */ for(i=0; i<NCHAMB_4P; i++){ for(j=0; j<NCHAMB_4P+1; j++){ s[i][j] = chamb->m[i][j]; } } if(solve_matrix(s)<0) return(RAYID_NOERR); /* return with RAYID_NOERR is correct */ /* calculate chi square */ rayt.rayid = RAYID_NOERR; rayt.org.x = s[0][NCHAMB_4P]; /* origin x */ rayt.org.y = s[1][NCHAMB_4P]; /* y */ rayt.org.z = 0.0; /* z */ rayt.dir.x = s[2][NCHAMB_4P]; /* direction x */ rayt.dir.y = s[3][NCHAMB_4P]; /* y */ rayt.dir.z = 1.0; /* z */ chi2 = (*chi2_func)(&rayt); //chi2 = -1; if(0 <= chi2 && chi2 < chamb->max_chi2){ /* only if ch2 is less than max_chi2 */ chamb->ncomb++; if(chamb->chi2<0 || chi2 < chamb->chi2){ /* take the minimum chi2 */ chamb->chi2 = chi2; /* set origin/direction */ ray->rayid = rayt.rayid; ray->org.x = rayt.org.x; ray->org.y = rayt.org.y; ray->org.z = rayt.org.z; ray->dir.x = rayt.dir.x; ray->dir.y = rayt.dir.y; ray->dir.z = rayt.dir.z; } } return(RAYID_NOERR); } /* ray_4p_fpp_mult ---- calculate ray from 4 MWPC positions with checking chi2 (support multi clusters)*/ int ray_4p_fpp_mult(chamb, chi2_func) chamber_p chamb; double (*chi2_func)(ray_p); { dr_set_nothing(&chamb->chi2); chamb->ray.rayid = RAYID_UNDEF; if(chamb->npl!=NCHAMB_4P){ showerr("ray_4p_fpp_mult: unsupported number of planes (%s)\n", chamb->npl); return(-1); } chamb->ncomb = ray_4p_get_ncomb(chamb); if(chamb->ncomb>chamb->max_ncomb){ /* RAYID_MCLUST + number of combinations with chi2 less than max_chi2 */ chamb->ray.rayid = RAYID_MCLUST + chamb->ncomb; return(chamb->ray.rayid); } if(dr_exists(chamb->max_nclust)){ if(ray_4p_get_max_nclust(chamb)>chamb->max_nclust){ chamb->ray.rayid = RAYID_TRACE; return(chamb->ray.rayid); } } chamb->ray.rayid = ray_4p_fpp_mult_1p(chamb, 0, chi2_func); if(chamb->ray.rayid==RAYID_NOERR){ if(chamb->chi2<0){ chamb->ray.rayid = RAYID_TRACE; } }else{ dr_set_nothing(&chamb->chi2); } return(chamb->ray.rayid); } /* count number of combinations */ static int get_ncomb(chamb) chamber_p chamb; { int ipl; plane_p plane; clst_p clst; int ic, j, n, k; k=0; n=1; for(ipl=0; ipl<chamb->npl; ipl++){ plane = &chamb->plane[ipl]; if(plane->fit){ j = chamb->allow_wireskip ? 1:0; for(ic=0; ic<plane->nc && ic<Clst_MaxNClst; ic++){ clst = &plane->clst[ic]; if(clst->posid == POSID_NOERR) j+=2; } n*=j; if(j>1) k++; } } if(k<MWDC_MIN_PLHITS) return(-1); /* too few plane hits */ return(n); } /* ray_mwdc_1p calculate ray from 4 chamber positions (subroutine for recursive call) */ static int ray_mwdc_1p(chamb, ipl) chamber_p chamb; int ipl; { plane_p plane; wire_p wire; ray_p ray; clst_p clst; int ic, n; int errid; ray = &chamb->ray; if(ipl<chamb->npl){ plane = &chamb->plane[ipl]; wire = &plane->wire; if(!wire->ok) return(ray->rayid=RAYID_CONFG); /* hit loop */ if(plane->fit){ chamb->hitpat |= 1<<ipl; n=0; for(ic=0; ic<plane->nc && ic<1; ic++){ plane->ic = ic; clst = &plane->clst[ic]; if(clst->posid) continue; /* one of the left-right ambiguity */ clst->pos = clst->pos1; if((errid=ray_mwdc_1p(chamb, ipl+1))) return(errid); /* the other of the left-right ambiguity */ clst->pos = clst->pos2; if((errid=ray_mwdc_1p(chamb, ipl+1))) return(errid); n++; } chamb->hitpat &= ~(1<<ipl); } if(!plane->fit || chamb->allow_wireskip || n==0){ plane->ic = 0; clst = &plane->clst[0]; dr_set_nothing(&clst->pos); if((errid=ray_mwdc_1p(chamb, ipl+1))) return(errid); } return(0); } return(ray_mwdc_fit(chamb)); } /* ray_mwdc --- calculate ray for MWDC */ int ray_mwdc(chamb) chamber_p chamb; { int n; /* check number of combinations */ n = get_ncomb(chamb); if(n<0){ chamb->ray.rayid = RAYID_FEWHIT; return(chamb->ray.rayid); } if(n>chamb->max_ncomb){ chamb->ray.rayid = RAYID_NCOMB; return(chamb->ray.rayid); } /* ray trace */ chamb->chi2 = 1E10; chamb->hitpat = 0; chamb->ray.rayid = ray_mwdc_1p(chamb, 0); if(!chamb->ray.rayid && chamb->chi2>=1E10){ chamb->ray.rayid = RAYID_TRACE; chamb->chi2 = -1.; } #if 0 if(!chamb->ray.rayid) showerr("chi2 = %f\n", chamb->chi2); #endif return(chamb->ray.rayid); } /* get trace back matrix return the number of paramters and the pointer to the tb_mat_t array return value: -1: error 0: no matrix data >0: number of parameters */ int get_tb_matrix(mat_nam, mat_h) char *mat_nam; /* like "LAS_XMAT" */ tbmat_p *mat_h; { static int itmp; int i, k, n, min, max; double c; char nam[256]; char *str; tbmat_p mat; *mat_h = (tbmat_p)NULL; /* get matrix */ for(n=0;;n++){ sprintf(nam, "%s_%s", mat_nam, "%.2d"); str = spf(nam,n+1); itmp = 0; /* must be cleared */ min = dr_min_r(&dr_data, &itmp, str, 0); max = dr_max_r(&dr_data, &itmp, str, 0); if(min>=max) break; } if(n<=0) return(0); mat = (tbmat_p)malloc(n*sizeof(tbmat_t)); if(mat == (tbmat_p)NULL){ showerr("get_tb_matrix: no enough memory space.\n"); return(-1); } for(i=0; i<n; i++){ str = spf(nam,i+1); itmp = 0; /* must be cleared */ k = dr_int(dr_get_r(&dr_data, &itmp, str, 0)); c = dr_get_r(&dr_data, &itmp, str, 1); mat[i].c = c; mat[i].x = (k/1000) % 10; mat[i].a = (k/100) % 10; mat[i].y = (k/10) % 10; mat[i].b = k % 10; if(mat[i].x > TB_MAX_POWER || mat[i].a > TB_MAX_POWER || mat[i].y > TB_MAX_POWER || mat[i].b > TB_MAX_POWER){ showerr("get_tb_matrix: trace-back matrix has a power > %d" "in %s_%.2d.\n", TB_MAX_POWER, mat_nam, i+1); return(-1); } } *mat_h = mat; return(n); } /* trace-back by matrix */ double trace_back(ray, mat, nmat, flag) ray_p ray; /* rad->dir is in grad */ tbmat_p mat; int nmat; int flag; /* 0 to use grad (=ray->dir) 1 to use atan (=atan(ray->dir)) */ { int i; double c; double th, ph; double x[TB_MAX_POWER+1]; double a[TB_MAX_POWER+1]; double y[TB_MAX_POWER+1]; double b[TB_MAX_POWER+1]; if(nmat==0 || mat==(tbmat_p)NULL){ dr_set_nothing(&c); return(c); } /* calculate power series */ x[0] = a[0] = y[0] = b[0] = 1.; th = atan(ray->dir.x); ph = atan(ray->dir.y); for(i=1; i<=TB_MAX_POWER; i++){ /* changed to use atan(dir) on 14-DEC-2004 */ if(flag){ x[i] = x[i-1] * ray->org.x; a[i] = a[i-1] * th; y[i] = y[i-1] * ray->org.y; b[i] = b[i-1] * ph; }else{ x[i] = x[i-1] * ray->org.x; a[i] = a[i-1] * ray->dir.x; y[i] = y[i-1] * ray->org.y; b[i] = b[i-1] * ray->dir.y; } } /* calculate trace-back matrix */ c = 0.; for(i=0; i<nmat; i++){ #if 0 /* already checked */ if(mat->x > TB_MAX_POWER || mat->a > TB_MAX_POWER || mat->y > TB_MAX_POWER || mat->b > TB_MAX_POWER){ showerr("trace_back: too large power series.\n"); break; } #endif c += mat->c * x[mat->x] * a[mat->a]* y[mat->y]* b[mat->b]; mat++; } return(c); } /* ray_vertex() Calculate the vertex point from 2 rays. The vertex distance is defined as the minimum distance between the two rays. The vertex point is defined as the central position of the line of minimum distance between the two rays. */ int ray_vertex(r1, r2, p, dist) ray_p r1, r2; vec_p p; double *dist; { vec_rec b, x, x1, x2; double det; double m11, m12, m21, m22; double s1, s2, p1, p2; /* set the default value */ p->x = p->y = p->z = 0.0; *dist = -10.0; det = r1->dir.x*r2->dir.y - r2->dir.x*r1->dir.y; if(fabs(det)<1e-10){ /* 2 rays are parallel */ *dist = -1.0; return(-1); } b.x = -( r2->dir.y*r1->dir.z - r1->dir.y*r2->dir.z)/det; b.y = -(-r2->dir.x*r1->dir.z + r1->dir.x*r2->dir.z)/det; b.z = 1.0; m11 = r1->dir.x - r1->dir.z*b.x; m12 = -r2->dir.x + r2->dir.z*b.x; m21 = r1->dir.y - r1->dir.z*b.y; m22 = -r2->dir.y + r2->dir.z*b.y; det = m11*m22 - m12*m21; if(fabs(det)<1e-10){ /* This also means 2 rays are parallel (never come here)*/ *dist = -2.0; return(-1); } s1 = r1->org.x - r2->org.x - (r1->org.z-r2->org.z)*b.x; s2 = r1->org.y - r2->org.y - (r1->org.z-r2->org.z)*b.y; p1 = -( m22*s1 - m12*s2)/det; p2 = -(-m21*s1 + m11*s2)/det; x1.x = r1->org.x + r1->dir.x*p1; x1.y = r1->org.y + r1->dir.y*p1; x1.z = r1->org.z + r1->dir.z*p1; x2.x = r2->org.x + r2->dir.x*p2; x2.y = r2->org.y + r2->dir.y*p2; x2.z = r2->org.z + r2->dir.z*p2; x.x = x1.x - x2.x; x.y = x1.y - x2.y; x.z = x1.z - x2.z; *dist = sqrt(x.x*x.x + x.y*x.y + x.z*x.z); p->x = (x1.x + x2.x)/2; p->y = (x1.y + x2.y)/2; p->z = (x1.z + x2.z)/2; return(0); } /* ray_scat_ang() Calculate scattering angle from two rays. ath ... polar angle aph ... azimuthal angle hor ... horizontal angle ver ... vertical angle */ int ray_scat_ang(r1, r2, ath, aph, hor, ver) ray_p r1, r2; double *ath, *aph, *hor, *ver; { vec_rec c1, c2, d1, d2; double th, ph, c, s; if(fabs(r1->dir.z)<1e-100) return(-1); th = atan(r1->dir.x/r1->dir.z); s = sin(th); c = cos(th); c1.x = -s*r1->dir.z + c*r1->dir.x; c1.y = r1->dir.y; c1.z = c*r1->dir.z + s*r1->dir.x; c2.x = -s*r2->dir.z + c*r2->dir.x; c2.y = r2->dir.y; c2.z = c*r2->dir.z + s*r2->dir.x; if(fabs(c1.z)<1e-100) return(-1); ph = atan(c1.y/c1.z); s = sin(ph); c = cos(ph); d1.x = c1.x; d1.y = c*c1.y - s*c1.z; d1.z = s*c1.y + c*c1.z; d2.x = c2.x; d2.y = c*c2.y - s*c2.z; d2.z = s*c2.y + c*c2.z; if(fabs(d2.z)<1e-100) return(-1); th = atan(sqrt(d2.x*d2.x+d2.y*d2.y)/d2.z); ph = atan2(d2.y, d2.x); *ath = th; *aph = ph; *hor = atan(d2.x/d2.z); *ver = atan(d2.y/d2.z); return(0); } /* Local Variables: mode: C tab-width: 2 End: */ <file_sep>#include <functional> #include <atomic> class RCNPEvent; class RCNPInterface; void StartGRAnalyzer(const char* filename, std::atomic<int>* terminate,std::function<void(RCNPEvent*)> func, bool save_tree=false, bool status=false); class RCNPInterface { bool save_rcnptree; bool show_status; public: void SaveTree(bool set) { save_rcnptree = set; } bool SaveTree() { return save_rcnptree; } void ShowStatus(bool set) { show_status = set; } bool ShowStatus() { return show_status; } //// casual user can ignore below code //////////////////////////////// static RCNPInterface& Instance() { static RCNPInterface instance; return instance; } private: RCNPInterface() {}; public: RCNPInterface(RCNPInterface const&) = delete; void operator=(RCNPInterface const&) = delete; }; <file_sep>/* dummy.c --- dummy functions of hb.f for debugging Copyright (C) 2000 <NAME> Author: <NAME> Version 1.00 04-JUN-2000 by <NAME> */ #include <stdio.h> #include <string.h> #include <math.h> #include <errno.h> #include <stdarg.h> #include "freadin.h" #include "histogram.h" #if 0 void hstini_(char *name){} void hstend_(){} void hstbk1_(int *h, char *nam, float *min, float *max, int *nbin){} void hstfl1_(int *h, float *data){} void hstbk2_(int *h, char *nam, float *min1, float *max1, int *nbin1, float *min2, float *max2, int *nbin2){} void hstfl2_(int *h, float *data1, float *data2){} void hstdel_(int *h){} void hstout_(char *name){} void hstshm_(char *name){} #endif #if 1 void G77_lnblnk_0(){} #endif /* Local Variables: mode: C tab-width: 2 End: */ <file_sep>#ifndef V1190_REG_H #define V1190_REG_H /* * Definitions for V1190 * * Version 0.10 23-DEC-2012 by <NAME> */ /* Size of I/O space */ #define V1190_MAX_N_MODULES 32 /* Max number of V1190 Modules */ #define V1190_N_CH_PER_MODULE 128 /* number of channels per module */ #define V1190_BASE_INI 0xEE000000 /* VME base address start */ #define V1190_BASE_INC 0x00010000 /* VME base address increment */ #define V1190_BASE(module_number) ((V1190_BASE_INI)+(V1190_BASE_INC)*(module_number)) #define V1190_SIZE 0x1206 /* VME addressing mode */ #if 1 #define V1190_MODE VME_A32UD /* 32bit Extended Non-Prvileged Data Accesss */ #else #define V1190_MODE VME_A32SD /* 32bit Extended Prvileged Data Accesss */ #endif /* * V1190 Memory Register */ typedef struct V1190{ unsigned int output_buffer[0x1000/4]; unsigned short control_register; unsigned short status_register; unsigned char blank1[6]; unsigned short interrupt_level; unsigned short interrupt_vector; unsigned short geo_address_register; unsigned short mcst_base_address; unsigned short mcst_control; unsigned short module_reset; unsigned short software_clear; unsigned short software_event_reset; unsigned short software_trigger; unsigned int event_counter; unsigned short event_stored; unsigned short almost_full_level; unsigned short blt_event_number; unsigned short firmware_revision; unsigned int testreg; unsigned short output_prog_control; unsigned short micro; unsigned short micro_handshake; unsigned short select_flash; unsigned short flash_memory; unsigned short sram_page; unsigned int event_fifo; unsigned short event_fifo_stored; unsigned short event_fifo_status; unsigned char blank2[0x01c0]; unsigned int dummy32; unsigned short dummy16; } V1190_t, *V1190_p; #define V1190_CR 0x1000 /* control register */ #define V1190_SR 0x1002 /* status register */ #define V1190_InterruptLevel 0x100A /* interrupt level */ #define V1190_InterruptVector 0x100C /* interrupt vector */ #define V1190_GeoAddressRegister 0x100A /* Geo Address_Register */ #define V1190_MCSTBaseAddress 0x1010 /* MCST Base Address */ #define V1190_MCSTControl 0x1012 /* MCST control */ #define V1190_ModuleReset 0x1014 /* Module Reset */ #define V1190_SoftwareClear 0x1016 /* Software Clear */ #define V1190_SoftwareEventReset 0x1018 /* Software Event Reset */ #define V1190_SoftwareTrigger 0x101A /* Software Trigger */ #define V1190_EventCounter 0x101C /* Event Counter */ #define V1190_EventStored 0x1020 /* Event Stored */ #define V1190_AlmostFullLevel 0x1022 /* Almost Full Level */ #define V1190_BLTEventNumber 0x1024 /* BLT Event Number */ #define V1190_FirmwareRevision 0x1026 /* Almost Full Level */ #define V1190_Testreg 0x1028 /* Test Register */ #define V1190_OutputProgControl 0x102C /* Output Prog Control */ #define V1190_MicroRegister 0x102E /* micro register */ #define V1190_MicroHandshake 0x1030 /* micro handshake */ #define V1190_SelectFlash 0x1032 /* Select Flash */ #define V1190_FlashMemory 0x1034 /* Flash Memory */ #define V1190_SramePage 0x1036 /* Srame Page */ #define V1190_EventFIFO 0x1038 /* Event FIFO */ #define V1190_EventFIFOStored 0x103C /* Event FIFO Stored */ #define V1190_EventFIFOStatus 0x103E /* Event FIFO Status */ #define V1190_Dummy32 0x1200 /* Dummy 32 */ #define V1190_Dummy16 0x1204 /* Dummy 16 */ #define V1190_MicroHandshakeRegister_ReadOK 0x0002 /* micro handshake read OK */ #define V1190_MicroHandshakeRegister_WriteOK 0x0001/* micro handshake register write OK */ /* * V1190 microcode Opecode, see page 47 of the V1190 manual */ /* ACQUISITION MODE */ #define V1190_OPECODE_TRIG_MATCH 0x0000 #define V1190_OPECODE_CONTINUOUS_STORAGE 0x0100 #define V1190_OPECODE_ACQUISITION 0x0200 #define V1190_OPECODE_SET_KEEP_TOKEN 0x0300 #define V1190_OPECODE_CLEAR_KEEP_TOKEN 0x0400 #define V1190_OPECODE_LOAD_DEF_CONFIG 0x0500 /* TRIGGER */ #define V1190_OPECODE_SET_WIN_WIDTH 0x1000 #define V1190_OPECODE_SET_WIN_OFFS 0x1100 #define V1190_OPECODE_SET_SW_MARGIN 0x1200 #define V1190_OPECODE_SET_REJ_MARGIN 0x1300 #define V1190_OPECODE_EN_SUB_TRG 0x1400 #define V1190_OPECODE_DIS_SUB_TRG 0x1500 #define V1190_OPECODE_READ_TRG_CONF 0x1600 /* TDC EDGE DETECTION & RESOLUTION */ #define V1190_OPECODE_SET_DETECTION 0x2200 #define V1190_OPECODE_READ_DETECTION 0x2300 #define V1190_OPECODE_READ_RES 0x2600 #define V1190_OPECODE_SET_DEAD_TIME 0x2800 #define V1190_OPECODE_READ_DEAD_TIME 0x2900 /* TDC READOUT */ #define V1190_OPECODE_EN_HEAD_TRAILER 0x3000 #define V1190_OPECODE_DIS_HEAD_TRAILER 0x3100 #define V1190_OPECODE_READ_HEAD_TRAILER 0x3200 #define V1190_OPECODE_SET_EVENT_SIZE 0x3300 #define V1190_OPECODE_READ_EVENT_SIZE 0x3400 #define V1190_OPECODE_EN_ERROR_MARK 0x3500 #define V1190_OPECODE_DIS_ERROR_MARK 0x3600 #define V1190_OPECODE_EN_ERROR_BYPASS 0x3700 #define V1190_OPECODE_DIS_ERROR_BYPASS 0x3800 #define V1190_OPECODE_SET_ERROR_TYPES 0x3900 #define V1190_OPECODE_READ_ERROR_TYPES 0x3A00 #define V1190_OPECODE_SET_FIFO_SIZE 0x3B00 #define V1190_OPECODE_READ_FIFO_SIZE 0x3C00 /* CHANNEL ENABLE */ #define V1190_OPECODE_EN_ALL_CH 0x4200 #define V1190_OPECODE_DIS_ALL_CH 0x4300 /* ADJUST */ #define V1190_OPECODE_SET_GLOB_OFFS 0x5000 #define V1190_OPECODE_READ_GLOB_OFFS 0x5100 /* * TDC data format @Output Buffer */ #if 1 /* Little Endian Definition for Intel CPU */ typedef struct V1190_GH { /* Global Header */ unsigned geo: 5; /* Geographical Address */ unsigned event_count: 22; /* Event Count */ unsigned id: 5; /* Identifier (=8) */ } V1190_GH_t, *V1190_GH_p; typedef struct V1190_TH { /* TDC Header */ unsigned bunch_id: 12; /* Bunch ID */ unsigned event_id: 12; /* Event ID */ unsigned tdc: 2; /* TDC */ unsigned reserved1: 1; /* not used */ unsigned id: 5; /* Identifier (=1) */ } V1190_TH_t, *V1190_TH_p; typedef struct V1190_TM { /* TDC Measurement */ unsigned measurement: 19; /* Measurement (TDC data) */ unsigned channel: 7; /* Channel */ unsigned trailing: 1; /* trailing(=1), leading (=0) edge */ unsigned id: 5; /* Identifier (=0) */ } V1190_TM_t, *V1190_TM_p; typedef struct V1190_TT { /* TDC Trailer */ unsigned word_count: 12; /* Word count */ unsigned event_id: 12; /* Event ID */ unsigned tdc: 2; /* TDC */ unsigned reserved1: 1; /* not used */ unsigned id: 5; /* Identifier (=3) */ } V1190_TT_t, *V1190_TT_p; typedef struct V1190_TE { /* TDC Error */ unsigned error_flags: 15; /* Error flag */ unsigned reserved1: 9; /* not used */ unsigned tdc: 2; /* TDC */ unsigned reserved2: 1; /* not used */ unsigned id: 5; /* Identifier (=4) */ } V1190_TE_t, *V1190_TE_p; typedef struct V1190_ETTT { /* Extended Trigger Time Tag */ unsigned time_tag: 27; /* Extended trigger time tag */ unsigned id: 5; /* Identifier (=17) */ } V1190_ETTT_t, *V1190_ETTT_p; typedef struct V1190_GT { /* Global trailer (the trailer) */ unsigned geo: 5; /* Geographical Address */ unsigned word_count: 16; /* Word count */ unsigned reserved1: 3; /* not used */ unsigned status: 3; /* Status */ unsigned id: 5; /* Identifier (=16) */ } V1190_GT_t, *V1190_GT_p; typedef union V1190_DATA { /* Output buffer data (union, 32 bit)*/ unsigned int idata; /* 32 bit integer data */ V1190_GH_t global_header; /* global header */ V1190_TH_t tdc_header; /* TDC header */ V1190_TM_t tdc_measurement; /* TDC measurement */ V1190_TT_t tdc_trailer; /* TDC trailer */ V1190_TE_t tdc_error; /* TDC error */ V1190_ETTT_t time_tag; /* Extended trigger time tag */ V1190_GT_t global_trailer; /* Global Trailer */ } V1190_DATA_t, *V1190_DATA_p; /* Control Register */ typedef struct V1190_CR_T { /* Status Register */ unsigned berr_en: 1; /* Bus Error Enable */ unsigned term: 1; /* software termination */ unsigned term_sw: 1; /* termination mode */ unsigned empty_event: 1; /* allow empty event */ unsigned align64: 1; /* allows to add a 32 bit dummy word for alignment */ unsigned compensation_enable: 1; /* compensation enable */ unsigned test_fifo_enable: 1; /* test FIFO enable */ unsigned read_compensation_sram_enable: 1; /* read compensation SRAM enable */ unsigned event_fifo_enable: 1; /* event FIFO enable */ unsigned extended_trigger_time_tag_enable: 1; /* extended trigger time tag enable */ unsigned reserved1: 2; /* not used */ unsigned addr_range_meb_access_enable: 1; /* 16MB address range MEB access enable */ unsigned reserved2: 3; /* not used */ } V1190_CR_t, *V1190_CR_p; /* Status Register */ typedef struct V1190_SR_T { /* Status Register */ unsigned data_ready: 1; /* data ready */ unsigned alm_full: 1; /* almost full */ unsigned full: 1; /* full */ unsigned trig_match: 1; /* trigger match mode */ unsigned header_en: 1; /* header enable */ unsigned term_on: 1; /* termination on */ unsigned error0: 1; /* error in TDC 0 */ unsigned error1: 1; /* error in TDC 1 */ unsigned error2: 1; /* error in TDC 2 */ unsigned error3: 1; /* error in TDC 3 */ unsigned berr_flag: 1; /* bus error */ unsigned purg: 1; /* purged */ unsigned res_0: 1; /* resolution 00=800ps, 01=200ps, 10=10ps*/ unsigned res_1: 1; /* (resolution) */ unsigned pair: 1; /* pair mode */ unsigned trigger_lost: 1; /* trigger lost */ } V1190_SR_t, *V1190_SR_p; /* TDC header ID (5 bit)*/ #define V1190_HEADER_ID_GH 0x08 #define V1190_HEADER_ID_TH 0x01 #define V1190_HEADER_ID_TM 0x00 #define V1190_HEADER_ID_TT 0x03 #define V1190_HEADER_ID_TE 0x04 #define V1190_HEADER_ID_ETTT 0x11 #define V1190_HEADER_ID_GT 0x10 #define V1190_HEADER_ID_FILLER 0x18 #endif //extern int v1190_wire_map_data[]; // For DAQ code version // write a PERL script to get this table from /home/tamidaq/daq/v1190/v1190_util.c static int v1190_wire_map_data[] = { 0, 2, 1, 3, 4, 6, -2, -1, 5, 7, 8, 10, 9, 11, -1, -1, // X1 plane 1, 3, 2, 4, 5, 7, 0, -1, 6, 8, 9, 11,10, 12, -1, -1, // U1 plane 0, 2, 1, 3, 4, 6, -1, -1, 5, 7, 8, 10, 9, 11, -1, -1, // X2 plane 1, 3, 2, 4, 5, 7, 0, -1, 6, 8, 9, 11,10, 12, -1, -1 // U2 plane }; #define v1190_wire_map(geo, ch) ((v1190_wire_map_data[(((geo)&7)<<3)|(((ch)&0x70)>>4)]<<4)|((ch)&0x0f)) #define v1190_plane_map(geo, ch) (((geo)&6)>>1) /* * prototype definitions of library functions */ int v1190_open(void); V1190_p v1190_map(int module_number); int v1190_unmap(int module_number); int v1190_close(void); int v1190_micro_handshake_write(V1190_p ptr, int opecode); int v1190_micro_handshake_write_1w(V1190_p ptr, int opecode, unsigned short w); int v1190_micro_handshake_read(V1190_p ptr, int opecode, unsigned short *data); int v1190_micro_handshake_read_cont(V1190_p ptr, unsigned short *data); extern int v1190_n_tdc_error_string; extern char *(v1190_tdc_error_string[]); #endif /* for ifndef V1190_REG_H */ <file_sep>/* freain.c ---- header for fread input Version 1.00 02-JUN-2000 by <NAME> */ #define DEBUG_LEX 0 #define DEBUG_YACC 0 #define DEBUG_EVAL 0 #define DEBUG_CYCLIC 0 #define DEBUG_DR_SHOW 0 #define DEBUG_THINKPAD 0 #define DEBUG_DEFINITION 0 #define DEBUG_HBOOK 0 #define DEBUG_TEMP 1 #define ROOT_SETIDNUMBER 0 /* set an ID number in front of histogram names */ #if 0 /* defined in Makefile */ #define USE_PAW 0 /* Use paw as a histogrammer */ #define USE_ROOT 1 /* Use root as a histogrammer */ #endif #if USE_ROOT #define SHMSIZE (16*1024*1024) /* Shared Memory size = 16 MBytes */ #endif #if USE_PAW #define SHMSIZE (1*1024*1024) /* Shared Memory size = 1 MWords (*4 Bytes) */ #define PAWC_SIZE (16*1024*1024) /* 16 MWords (*4 Bytes) */ #endif #define MAX_NCHILD 10 /* max number of child processes */ #define FNAM_CHILD_STDERR ".child%.2d.stderr" /* child process stderr output file */ #define NSYMS 200 #define KEYFILE "./key" #define SHMNAME "BOB" #define HBKNAME "analyzer.hb" #define FNAMALIAS "alias.kumac" /* alias output file (for paw) */ #define DEFFNAM "hist.def" /* default definition file name */ #define ROOT_ALIASDIR "./aliases" /* directory for alias macros (for ROOT) */ #define ROOT_SHMNAM "analyzer.map" /* directory for alias macros (for ROOT) */ #ifdef BIG_ENDIAN #undef BIG_ENDIAN #endif #ifdef LITTLE_ENDIAN #undef LITTLE_ENDIAN #endif enum { BIG_ENDIAN = 0, LITTLE_ENDIAN }; enum { FORMAT_UNDEFINED = -1, /* undefined (not determined yet) */ FORMAT_UNKNOWN = 0, /* unknown format */ FORMAT_TAMIDAQ, /* RCNP tamidaq format */ FORMAT_MARS, /* RIKEN mars format */ FORMAT_DST_1, /* DST format ver 1.0 */ FORMAT_BLD1, /* RCNP Build variable length format version 1 */ }; #if defined (__cplusplus) extern "C" { #endif struct symtab{ char *name; double (*funcptr)(); double value; } symtab[NSYMS]; /* value record */ typedef struct vrec{ int vtype; /* value type */ double dval; /* double floating value */ char *sval; /* string value */ int vref; /* dr_rec reference number */ int eval; /* evaluation type (enum eval) */ int neval; /* evaluation level */ struct vrec *arg1; /* argument 1 */ struct vrec *arg2; /* argument 2 */ } vrec_t, *vrec_p; enum eval { EVAL_NONE=0, /* not evaluated */ EVAL_UNDER, /* under evaluation */ EVAL_CONST /* constant (no need to evaluate) */ }; typedef struct fin { int type; /* type of the input */ FILE *file; /* input stream */ int istr; /* index of the string input */ char *pstr; /* pointer to the input string */ } fin_t; typedef struct child_data { int pid; int readfd; int writefd; int n_sent_buf; } child_data_t, *child_data_p; typedef struct hist_data { /* histogram data between parent and child processes */ int hid; float f1; float f2; } hist_data_t, *hist_data_p; #define HID_SCALER 50000 #define HID_SCALER_MAX 51000 enum { FIN_NONE = 0, /* no input */ FIN_FILE, /* input from a file pointed by the fin */ FIN_STR /* input is a string pointed by pstr and index by istr */ }; # define MaxMsgLen 1020 typedef struct msg_t{ int mtype; char mtext[MaxMsgLen]; } mesg_t; /* message commands */ enum { MSG_NONE = 0, MSG_CMD /* command to the analyzer. Should be 1 in order to avoid confliction with child process IDs */ }; extern vrec_p new_vrecp(); extern fin_t fin; extern int init_hist_rcnp(); extern int init_hist_gr_fpp(); extern int init_hist_las_fpp(); extern int hb_init(); extern int hb_exit(); extern int hb_hist_out(char*); extern void show_blk_num(int); extern void message(); extern int event_init(); extern int event_exit(); extern int event(); extern int evt_print_scaler(FILE*); extern int evt_time(); extern int evt_start(); extern int evt_scaler(); extern int evt_init_rcnp(); extern int evt_ipr(); extern int evt_init_gr(); extern int evt_gr_adc(); extern int evt_gr_tdc(); extern int evt_chamb_gr(); extern int evt_gr_kinema(); extern int evt_init_las(); extern int evt_las_adc(); extern int evt_las_tdc(); extern int evt_chamb_las(); extern int evt_las_kinema(); extern int evt_gl_kinema(); extern int evt_init_las_fpp(); extern int evt_chamb_las_fpp(); extern int evt_init_gr_fpp(); extern int evt_gr_fpp_adc(); extern int evt_gr_fpp_tdc(); extern int evt_chamb_gr_fpp(); extern int evt_start_rcnp(); extern int evt_start_las_fpp(); extern int evt_start_gr_fpp(); extern void show_debug(); extern void add_scaler(int,int); extern void open_alias_file(); extern void write_child_data(char*,int); extern void flush_child_data(); extern int read_in(int fd, unsigned char *buf, int *pos, int size); extern void showerr(char*, ...); extern int hbk1(int id, char *name, char *title, double min, double max, int nbin); extern int hbk2(int id, char *name, char *title, double min1, double max1, int nbin1, double min2, double max2, int nbin2); extern int hstdel(int hid); extern int hfil1(int id, double d); extern int hfil2(int hid, double f1, double f2); extern int dst_init(); extern int dst_exit(); extern int dst_chk_format(unsigned char *buf); extern int dst_write_data(); extern int dst_read_data(unsigned char *buf, int *bpos, int size); extern int root_init(int nrun); extern int root_exit(); extern int root_write_data(); extern int read_blk_rcnp(unsigned short *buf, int size); extern int read_blk_mars(unsigned short *buf, int size); extern void swaps(unsigned int *data); extern void save_scalers(); extern void save_histograms(); extern int evt_blk(int cblk); extern int histogram(); extern int check_level(double d); extern char* str_token(int vtype); #if defined (__cplusplus) } #endif /* Local Variables: mode: C tab-width: 2 End: */ <file_sep>void rootlogon(){ gSystem->Load("libRCNPEvent.so"); } <file_sep>#!/bin/bash file="./cog.py" if [ -f "$file" ] then #echo "$file found." ./bin/cog.py "$@" else #echo "$file not found." cd bin/cogapp python install_cog.py > /dev/null cp ./venv/bin/cog.py .. cd ../.. ./bin/cog.py "$@" fi <file_sep>/* analyzer.h ---- histogram Version 1.00 10-JUL-2000 by <NAME> */ #define PI M_PI #define r2d (180./PI) #define d2r (PI/180.) #define Clst_MaxNData 128 #define Clst_MaxNClst 16 #define Clst_MaxClstSize 100 #define Clst_DefMaxClstSize 10 #define Clst_DefMinClstSize 2 #define Clst_DefMaxNComb 1000 /* default max number of combinations */ #define ENDRUNBLK 0 /* End of Fread at the run end block */ #define LAS_FPP_MWDC 1 #define NP_MWDC 0 #define F2_MWDC 0 #if F2_MWDC #define N_MWDC_PL 8 /* number of MWDC planes */ #endif #define MWDC_MIN_PLHITS 5 /* MWDC minimum number of plane hits for ray tracing */ #define DT2D_TAB 1 /* use a table for drift time to distance (1) conversion, otherwise (0) use polynomial fit */ #define DT2D_TAB_ANALOG 1 /* make tdc digital data to analog values by adding a random number */ #define FNAMGRRAY "grray.dat" /* output file of rays */ #define FNAMLASRAY "lasray.dat" /* output file of rays */ #define VDC_ALLOW_HITSKIP 1 /* Allow a wire hit incontinuity in clusterization */ /* Position Calculation ID */ #define POSID_CONFG -10 /* Plane configuration error */ #define POSID_UNDEF -2 /* Not analyzed yet */ #define POSID_SIMPLE -1 /* Simplified fitting */ #define POSID_NOERR 0 /* Good position determination */ #define POSID_DRIFT 1 /* Drift time order inconsistency */ #define POSID_MONOTONE 2 /* Monotone dec/increase drift time */ #define POSID_LFIT 3 /* Error in the fitting to get the position */ #define POSID_NOHIT 10 /* No legal hit in a cluster */ #define POSID_1HIT 11 /* 1 hit in a cluster */ #define POSID_2HIT 12 /* 2 hits in a cluster */ #define POSID_MHIT 14 /* too many hits in a cluster */ #define POSID_NOCLUST 20 /* No Cluster */ #define POSID_MCLUST 20 /* Multi Cluster (+ number of clusters)*/ /* Ray Calculation ID */ #define RAYID_NOERR 0 /* 1 - 15 No Chamber Hit bit#0 chamber-1 bit#1 chamber-2 bit#2 chamber-3 bit#3 chamber-4 */ #define RAYID_MCLUST 20 /* Multi Cluster (>=21)*/ /* 20+number of multi-cluster planes */ #define RAYID_UNDEF -1 /* not analyzed yet */ #define RAYID_TRACE -2 /* Tracing error (matrix inversion) */ #define RAYID_FEWHIT -4 /* Too few plane hits */ #define RAYID_NCOMB -6 /* Too many combinations */ #define RAYID_VTPOS -8 /* Error in setting vertex position only in ray_4p_fpp_v() */ #define RAYID_CONFG -10 /* Plane configuration error */ /****** --- Ray analysis --- ******/ #define NCHAMB_4P 4 #define NCHAMB_2P 2 #define DIM 4 #define MaxNConv 1030 /* max number of items in conversion table */ #define TB_MAX_POWER 4 /* max power of trace-back matrix */ #define MaxNIntPl 10 /* max number of intersection planes for each spectrometer */ #if defined (__cplusplus) extern "C" { #endif /* vector record */ typedef struct vec_rec{ double x; double y; double z; } vec_rec, *vec_p; /* wire plane information */ typedef struct wire { int ok; /* the following configurations are ok or not */ double disp; /* sense wire displacement */ double rot; /* wire rotation from vertical-axis along z-axis */ double dl; /* maximum drift length */ vec_rec org; /* coordinate of the origin */ vec_rec dsp; /* displacement of a channel */ vec_rec dir; /* direction of the wire */ vec_rec drf; /* drift length */ double sc; /* coefficient to calculate gradient = |dsp|/|drf| */ } wire_t, *wire_p; /* ray information */ typedef struct ray { int rayid; /* ray definition ID */ vec_rec org; /* coordinate of a point in the ray */ vec_rec dir; /* direction of the ray */ } ray_t, *ray_p; /* trace-back matrix */ typedef struct tbmat { double c; /* coefficient */ int x; /* order of x */ int a; /* order of a */ int y; /* order of y */ int b; /* order of b */ } tbmat_t, *tbmat_p; #if DT2D_TAB /* drift time to distance table */ typedef struct dt2dtab{ int start; /* legal region start TDC */ int end; /* legal region end TDC */ int nitem; /* number of conversion items */ int offset; /* offset */ double conv[MaxNConv]; /* conversion values for start<=tdc<end */ } dt2dtab; #else /* drift time to distance parameters */ typedef struct dt2dprm{ int t[3]; /* conversion tdc points */ double p1[4]; /* conversion parameters for t[0]<t<t[1] */ double p2[4]; /* conversion parameters for t[1]<t<t[2] */ } dt2dprm; #endif /* cluster information */ typedef struct clst { int size; /* cluster size */ int wire[Clst_MaxClstSize]; /* hit wire */ int tdc[Clst_MaxClstSize]; /* tdc */ double dist[Clst_MaxClstSize]; /* distance */ double grad; /* slope */ double pos; /* position */ double pos1; /* position for LR-ambiguity (1) */ double pos2; /* position for LR-ambiguity (2) */ int posid; /* position definition ID */ } clst_t, *clst_p; typedef struct plane { char *name; /* name of the plane */ struct chamber *chamb; /* pointer to the parent chamber */ int nc; /* number of clusters */ int ic; /* selected cluster */ int fit; /* used for ray fitting */ #if DT2D_TAB dt2dtab tab; /* drift time to distance table */ #else dt2dprm prm; /* drift time to distance parameters */ #endif clst_t clst[Clst_MaxNClst]; /* cluster information */ wire_t wire; /* anode plane information */ double pres; /* position resolution of a plane */ double ares; /* angular resolution of a plane */ int min_clst_size; /* minimum cluster size */ int max_clst_size; /* maximum cluster size */ int ana_2hit_clst; /* analyze 2hit cluster */ int h_wire; /* reference to variable WIRE */ int h_wirer; /* reference to variable WIRER */ int h_tdc; /* reference to variable TDC */ int h_tdcr; /* reference to variable TDCR */ int h_clstsz; /* reference to variable CLUSTSZ */ int h_nhit; /* reference to variable NHIT */ int h_nclst; /* reference to variable NCLUST */ int h_drift; /* reference to variable DRIFT */ int h_posid; /* reference to variable POSID */ int h_pos; /* reference to variable POS */ int h_grad; /* reference to variable GRAD */ } plane_t, *plane_p; typedef struct chamber { int type; /* type of the chamber */ char *name; /* name of the chamber */ int npl; /* number of planes */ plane_p plane; /* plane information */ int ana_mult_clst; /* multi cluster analysis is on(1) or off(0) */ double max_ncomb; /* max number of combinations allowed */ double max_nclust; /* max number of clusters in a plane */ int ncomb; /* number of combinations */ double m[DIM][DIM+1]; /* ray finding matrix */ double max_chi2; /* max allowed chi quare */ double chi2; /* chi square of the ray fit */ int hitpat; /* hit pattern */ int anapat; /* analysis pattern */ void *matrix; /* solved matrices for hit patterns*/ void *mb; /* for solving matrix */ void *mc; /* for solving matrix */ int allow_wireskip; /* allow wire skip for ray fitting */ ray_t ray; /* reconstructed ray */ int nproj; /* number of projection planes */ int h_proj[MaxNIntPl];/* reference to projection planes */ int h_x; /* reference to projection point x */ int h_y; /* reference to projection point y */ } chamber_t, *chamber_p; enum chamb_type { CHANB_UNKOWN = 0, /* unknown chamber type */ CHAMB_MWDC, /* MWDC */ CHAMB_VDC, /* VDC */ CHAMB_MWPC /* MWPC */ }; /****** --- VDC cluster analysis --- ******/ static char const *vplnam[4] = { "X1", "U1", "X2", "U2" }; static char const *spnam[2] = { "GR", "LAS" }; /****** --- function prototype definitions --- ******/ double analog(int); int init_plane_config(plane_p); int ray_4p(chamber_p); int ray_4p_mult(chamber_p); int init_hist_vdc(); int event_vdc_init(); /* chamb.c */ int chamb_get_dt2d_tab(chamber_p chamb); int chamb_clust(plane_p plane); int chamb_drift(plane_p plane); int chamb_pos(plane_p plane); int chamb_outputray(chamber_p chamb, FILE **fd, char *fnam, int *nrays); int chamb_intersection(chamber_p chamb); int chamb_init_chamb(chamber_p chamb); int chamb_get_config(chamber_p chamb); int chamb_init_hist(chamber_p chamb); int chamb_ray(chamber_p); /* vdc.c */ int chamb_vdc_clust(plane_p plane); int chamb_vdc_pos(plane_p plane); /* mwdc.c */ int chamb_mwdc_clust(plane_p plane); int chamb_mwdc_pos(plane_p plane); /* mwpc.c */ int chamb_mwpc_clust(plane_p plane); int chamb_mwpc_pos(plane_p plane); /* ray.c */ void show_vec(vec_p vec); int ray_rotate_x(ray_p ray, double ang); int ray_rotate_y(ray_p ray, double ang); int ray_rotate_z(ray_p ray, double ang); int ray_intersection(ray_p ray, vec_p plane, vec_p pt); int ray_intersection_pt(ray_p ray, vec_p plane, vec_p pt); int ray_4p(chamber_p chamb); int ray_4p_mult(chamber_p chamb); int get_tb_matrix(char *, tbmat_p *mat_h); double trace_back(ray_p ray, tbmat_p mat, int nmat, int flag); int ray_mwdc(chamber_p chamb); int ray_vertex(ray_p r1, ray_p r2, vec_p p, double *dist); int ray_4p_fpp_mult(chamber_p chamb, double (*chi2_func)(ray_p)); int ray_scat_ang(ray_p r1, ray_p r2, double *ath, double *aph, double *hor, double *ver); int ray_mwdc_fit(chamber_p chamb); #if defined (__cplusplus) } #endif /* Local Variables: mode: C tab-width: 2 End: */ <file_sep>/* histogram.c ---- histogrammer subroutines Version 1.00 02-JUN-2000 by <NAME> Version 1.80 28-JUL-2001 by <NAME> */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <strings.h> #include <errno.h> #include <stdarg.h> #include <unistd.h> #include "freadin.h" #include "histogram.h" #include "analyzer.h" #include "freadin.tab.h" extern int pflag; /* parent process flag */ extern int cflag; /* child process flag */ #define DR_N_ADD 100 typedef struct hist_t{ int id; /* histogram ID */ int type; /* type of the histogram (enum hist_type) */ char *sname; /* short hame of the histogram */ char *name; /* name (title) of the histogram */ vrec_p v1; /* x variable */ vrec_p min1; /* x minimum */ vrec_p max1; /* x maximum */ vrec_p nbin1; /* x number of bins */ char *xlabel; /* x label */ vrec_p v2; /* y variable */ vrec_p min2; /* y minimum */ vrec_p max2; /* y maximum */ vrec_p nbin2; /* y number of bins */ char *ylabel; /* y label */ vrec_p gate; /* gate variable */ } hist_t, *hist_p; hist_p hists = (hist_p)NULL; int nhists=0; int histid=1; int neval=0; int level=0; enum hist_type { HIST_NONE=0, /* no histogram */ HIST_1D, /* 1-dimensional histogram */ HIST_2D /* 2-dimensional histogram */ }; typedef struct func_t { char *name; double (*func)(); } func_t; func_t *funcs; int nfunc = 0; dr_t dr_data; char *spf(fmt) char *fmt; { static char spf_str[256]; va_list args; va_start(args,fmt); vsprintf(spf_str,fmt,args); va_end(args); return(spf_str); } int dr_add(dr) dr_t *dr; { dr_rec_t *r; int i; #if 0 /* 28-JUL-2001 The procedure dr_get_r() is changed. Owing the change, I think the mechanism of dr_add() is working good. See dr_get_r(); */ #if 1 /* 28-JUL-2001 The following machanism of enlarging dr->rec size does not work good. The change of the memory position of dr->rec can cause a serious problem. */ if(dr->nmax){ fprintf(stderr, "The memory size for variables is not enough.\n"); fprintf(stderr, "Please enlarge DR_N_ADD in histogram.c .\n"); exit(1); } #endif #endif dr->nmax += DR_N_ADD; r = (dr_rec_t*)realloc(dr->rec, sizeof(dr_rec_t)*dr->nmax); if(r == (dr_rec_t*)NULL){ fprintf(stderr, "dr_add: could not allocate memory.\n"); dr->nmax -= DR_N_ADD; return(-1); } dr->rec = r; r = &r[dr->nmax-DR_N_ADD]; for(i=0; i<DR_N_ADD; i++){ r->type = DR_UNDEF; r->imin = 0; r->imax = 0; r->amin = 0; r->amax = 0; r->nvalue = 0; r->nam = (char*)NULL; r->value = (double*)NULL; r->nvrec = 0; r->vrec = (vrec_p*)NULL; r->nreg = 0; r->reg = (int**)NULL; r->eval = EVAL_NONE; r->neval = 0; r++; } return(0); } int dr_register(dr,h) dr_t *dr; int *h; { int n, **p; dr_rec_t *r; if(dr->n <= *h) return(-1); r = &dr->rec[*h]; n = r->nreg+1; p = (int**)realloc(r->reg,sizeof(int*)*n); if(p==(int**)NULL){ fprintf(stderr, "dr_register: could not allocate memory (%d).\n", n); return(-1); } r->reg = p; p[r->nreg++] = h; return 0; } int dr_rec_init(dr,h,nam) dr_t *dr; int *h; char *nam; { int i, n; dr_rec_t *r; if(*h>=dr->nmax){ while(*h>=dr->nmax){ if(dr_add(dr)){ return(-1); } } dr->n = *h+1; }else if(*h>=dr->n){ dr->n = *h+1; }else{ if(r->nam){ free(r->nam); r->nam = (char*)NULL; } if(r->value){ free(r->value); r->value = (double*)NULL; } } r = &dr->rec[*h]; r->nam = (char*)malloc(strlen(nam)+1); if(r->nam==(char*)NULL){ fprintf(stderr, "dr_rec_init: could not allocate memory.\n"); return(-1); } strcpy(r->nam, nam); dr_register(dr,h); return(0); } int dr_rec_enlarge(r,index) dr_rec_t *r; int index; { int i, k, n, nmin, nmax; double *p, *s, *d; if(r->imin == r->imax){ p = (double*)realloc(r->value, sizeof(double)*1); if(p==(double*)NULL){ fprintf(stderr, "dr_rec_enlarge: could not allocate memory.\n"); return(-1); } r->value = p; dr_set_nothing(r->value); r->imin = index; r->imax = index+1; r->nvalue = 1; }else if(index < r->imin){ nmin = index; nmax = r->imax; k = r->imax - r->imin; n = nmax - nmin; p = (double*)realloc(r->value, sizeof(double)*n); if(p==(double*)NULL){ fprintf(stderr, "dr_rec_enlarge: could not allocate memory.\n"); return(-1); } r->value = p; d = &p[n-1]; s = &p[k-1]; for(i=0; i<k; i++) *d-- = *s--; for(; i<n; i++) dr_set_nothing(d--); r->imin = nmin; r->imax = nmax; r->nvalue = n; }else if(r->imax <= index){ nmin = r->imin; nmax = index+1; k = r->imax - r->imin; n = nmax - nmin; p = (double*)realloc(r->value, sizeof(double)*n); if(p==(double*)NULL){ fprintf(stderr, "dr_rec_enlarge: could not allocate memory.\n"); return(-1); } r->value = p; d = &p[k]; for(i=k; i<n; i++) dr_set_nothing(d++); r->imin = nmin; r->imax = nmax; r->nvalue = n; } return(0); } int dr_rec_search(dr,nam) dr_t *dr; char *nam; { dr_rec_t *r; int i; char c; if(nam==(char*)NULL) return(0); c = *nam; r = dr->rec; for(i=1; i<dr->n; i++){ r++; if(*(r->nam)==c){ if(!strcmp(r->nam,nam)) return(i); } } return(0); } int dr_set_r(dr,h,nam,index,value) dr_t *dr; int *h; char const *nam; int index; double value; { dr_rec_t *r; int n; #if 0 fprintf(stderr, "dr_set_r: %s %d %f\n", nam, index, value); #endif /* check the record is already exists */ if(*h==0){ *h = dr_rec_search(dr,nam); if(*h==0){ *h = dr->n; if(dr_rec_init(dr,h,nam)){ *h = 0; return(-1); } }else{ dr_register(dr,h); } } /* check the range of index */ if(index<DR_MIN_ARRAY_INDEX || DR_MAX_ARRAY_INDEX <= index){ fprintf(stderr, "dr_r: Too large/small index (%d).\n", index); return(-1); } r = &dr->rec[*h]; if(index < r->imin || r->imax <= index ) if(dr_rec_enlarge(r, index)) return(-1); r->value[index-r->imin] = value; if(r->amin==r->amax){ r->amin = index; r->amax = index+1; }else if(index<r->amin) r->amin = index; else if(r->amax<=index) r->amax = index+1; r->type = DR_USER; return(0); } int dr_set_vrec(dr,h,nam,v) dr_t *dr; int *h; char const *nam; vrec_p v; { dr_rec_t *r; int n; vrec_p *p; /* check the record is already exists */ if(*h==0){ *h = dr_rec_search(dr,nam); if(*h==0){ *h = dr->n; if(dr_rec_init(dr,h,nam)) return(-1); } } r = &dr->rec[*h]; p = (vrec_p*)realloc(r->vrec,(r->nvrec+1)*sizeof(vrec_p)); if(p==(vrec_p*)NULL){ fprintf(stderr, "dr_set_vrec: could not allocate memory.\n"); return(-1); } p[r->nvrec++] = v; r->vrec = p; return(0); } dr_rec_t *dr_get_drec(dr,h,nam) dr_t *dr; int *h; char *nam; { /* check the record is already exists */ if(*h==0){ *h = dr_rec_search(dr,nam); if(*h==0){ *h = dr->n; if(dr_rec_init(dr,h,nam)) return((dr_rec_t*)NULL); } } return(&dr->rec[*h]); } double dr_get_r(dr,h,nam,index) dr_t *dr; int *h; char const *nam; int index; { dr_rec_t *r; int i, j, n; double res; vrec_p p, v; double d1, d2; int m; /* for DEBUG_CYCLIC */ static int n_eval=0; static char str_eval[1024] = {0}; static int str_eval_pos[128]; dr_set_nothing(&res); /* check the record is already exists */ if(*h==0){ *h = dr_rec_search(dr,nam); if(*h==0){ #if 0 /* changed on 03-AUG-2000 */ return(res); #else *h = dr->n; if(dr_rec_init(dr,h,nam)){ *h = 0; return(res); } #endif }else{ dr_register(dr,h); } } r = &dr->rec[*h]; if(r->neval < neval){ if(r->eval==EVAL_UNDER){ fprintf(stderr, "Cyclic evaluation of variable '%s'.\n", r->nam); if(DEBUG_CYCLIC){ fprintf(stderr, "%s\n", str_eval); } return(res); } r->eval = EVAL_UNDER; /* do evaluation */ if(DEBUG_CYCLIC){ i = strlen(str_eval); str_eval_pos[n_eval++] = i; strcpy(&str_eval[i], "->"); strcat(&str_eval[i], r->nam); } for(i=0; i<r->nvrec; i++){ p = r->vrec[i]; d1 = p->arg1 ? eval(p->arg1) : 0.; if(dr_exists(d1)){ v = p->arg2; while(v && v->vtype==TELM){ d2 = eval(v->arg1); if(dr_exists(d2)) dr_set_r(&dr_data, h, nam, (int)d1, d2); d1 += 1.; v = v->arg2; } d2=eval(v); if(dr_exists(d2)) dr_set_r(&dr_data, h, nam, (int)d1, d2); } } /* re-get the pointer r because the position of r might have been changed */ /* chaned on 28-JUL-2001. See dr_get_r() */ r = &dr->rec[*h]; r->eval = EVAL_NONE; r->neval = neval; if(DEBUG_CYCLIC){ str_eval[str_eval_pos[--n_eval]] = 0x00; } } /* check the range of indices */ if(index < r->imin || r->imax <= index ) return(res); return(r->value[index-r->imin]); } vrec_p dr_get_vrec_r(dr,h,nam,index) dr_t *dr; int *h; char const *nam; int index; { vrec_p res; dr_rec_t *r; res = (vrec_p)NULL; /* do evaluation */ (void)dr_get_r(dr,h,nam,index); r = &dr->rec[*h]; /* check the range of indices */ if(index < r->imin || r->imax <= index ) return(res); return(r->vrec[index-r->imin]); } /* get string value The usage of a string value is very restricted No substituion is allowed, i.e. you cannot get the value of 'a' from definitions of a = b b = "string" . Moreover only one definition of a string value is allowed. */ char *dr_get_sval_r(dr,h,nam,index) dr_t *dr; int *h; char const *nam; int index; { vrec_p v; dr_rec_t *r; /* do evaluation */ (void)dr_get_r(dr,h,nam,index); r = &dr->rec[*h]; /* check the range of indices */ if(index < r->imin || r->imax <= index ) return((char*)NULL); v = r->vrec[index-r->imin]->arg2; if(v){ return(v->sval); }else{ return((char*)NULL); } } /* get minimum index number */ int dr_min_r(dr,h,nam,dummy) dr_t *dr; int *h; char const *nam; int dummy; { /* check the record is already exists */ if(*h==0){ *h = dr_rec_search(dr,nam); if(*h==0){ return(0); }else{ dr_register(dr,h); } } /* do evaluation (in order to determine min and max)*/ (void)dr_get_r(dr,h,nam,dummy); return(dr->rec[*h].amin); } /* get maximum index number */ int dr_max_r(dr,h,nam,dummy) dr_t *dr; int *h; char const *nam; int dummy; { if(*h==0){ *h = dr_rec_search(dr,nam); if(*h==0){ return(0); }else{ dr_register(dr,h); } } /* do evaluation (in order to determine min and max)*/ (void)dr_get_r(dr,h,nam,dummy); return(dr->rec[*h].amax); } /* get reference number */ int dr_ref_r(dr,h,nam) dr_t *dr; int *h; char const *nam; { *h = dr_rec_search(dr,nam); if(*h==0){ *h = dr->n; if(dr_rec_init(dr,h,nam)){ *h = 0; return(-1); } }else{ dr_register(dr,h); } return 0; } int dr_append_r(dr,h,nam,index,value) dr_t *dr; int *h; char const *nam; int index; /* dummy */ double value; { int n; n = dr_max_r(dr,h,nam,0); return(dr_set_r(dr,h,nam,n,value)); } /* get number of indices */ int dr_nval_r(dr,h,nam,index) dr_t *dr; int *h; char const *nam; int index; { if(*h==0){ *h = dr_rec_search(dr,nam); if(*h==0){ return(0); }else{ dr_register(dr,h); } } return(dr->rec[*h].nvalue); } int dr_clear_r(dr) dr_t *dr; { int i, j, m, n; dr_rec_t *r; double *p; n = dr->n; r = &dr->rec[1]; for(i=1; i<n; i++, r++){ if(!r->value) continue; m = r->amax; p = &r->value[r->amin-r->imin]; for(j=r->amin; j<m; j++) dr_set_nothing(p++); r->amin = r->amax = 0; } return(0); } /* initialize dr records */ /* 1) clear the reference to variables */ /* 2) clear and free the variables definitions */ /* 3) clear and free user definitions (vrec) */ int dr_reinit_r(dr) dr_t *dr; { int i, j, n; dr_rec_t *r; double *p; if(!dr->rec) return(0); #if DEBUG_DEFINITION fprintf(stderr, "Clear all the definitions.\n"); #endif /* at first, do clear references (before memories are freed) */ n = dr->n; r = &dr->rec[n-1]; for(i=1; i<n; i++, r--){ if(r->reg){ for(j=0; j<r->nreg; j++){ *(r->reg[j]) = 0; } free(r->reg); r->reg = (int**)NULL; r->nreg = 0; } } /* clear and free each dr_rec and vrec */ n = dr->n; r = &dr->rec[n-1]; for(i=1; i<n; i++, r--){ if(r->nam){ free(r->nam); r->nam = (char*)NULL; } if(r->value){ free(r->value); r->value = (double*)NULL; r->nvalue = 0; } if(r->vrec){ for(j=0; j<r->nvrec; j++){ free_vrecp(r->vrec[j]); r->vrec[j] = (vrec_p)NULL; } free(r->vrec); r->vrec = (vrec_p*)NULL; r->nvrec = 0; } r->imin = r->imax = r->amin = r->amax = 0; } /* clear dr record */ free(dr->rec); dr->rec = (dr_rec_t*)NULL; dr->n = 1; dr->nmax = 0; level = 0; return(0); } int dr_add_func(nam,func) char *nam; double (*func)(); { int i; func_t *p; for(i=0; i<nfunc; i++){ if(!strcmp(funcs[i].name,nam)){ fprintf(stderr, "Warning: replace the function '%s'.", nam); funcs[i].func = func; return(0); } } funcs = (func_t*)realloc(funcs,sizeof(func_t)*(nfunc+1)); if(funcs==(func_t*)NULL){ fprintf(stderr, "dr_add_func: could not allocate memory.\n"); return(-1); } funcs[i].name = strdup(nam); funcs[i].func = func; nfunc++; return(0); } void *dr_get_func_r(h,nam) int *h; char *nam; { int i; char c; if(*h){ return (funcs[*h].func); }else{ c = nam[0]; for(i=0; i<nfunc; i++){ if(*(funcs[i].name)==c){ if(!strcmp(funcs[i].name,nam)){ *h = i; return (funcs[i].func); } } } } fprintf(stderr, "No function named '%s'.\n", nam); return(NULL); } double dr_func_r(dr,h,nam,args) dr_t *dr; int *h; char *nam; vrec_p args; { #define MaxNArgs 4 double res; double (*func)(); double arg[MaxNArgs]; vrec_p v[MaxNArgs]; vrec_p vp; int i, ieval; /* get function */ *(void **)&func = dr_get_func_r(h,nam); if(!func){ dr_set_nothing(&res); return(res); } /* initialize arguments */ for(i=0; i<MaxNArgs; i++){ dr_set_nothing(&arg[i]); v[i] = (vrec_p)NULL; } /* extract arguments */ vp = args; for(i=0; i<MaxNArgs; i++){ if(vp->vtype!=TELM){ /* get an argument and end */ arg[i] = eval(vp); v[i] = vp; break; } /* get an argument */ arg[i] = eval(vp->arg1); v[i] = vp->arg1; #if 0 /* 14-OCT-2003 */ if(dr_is_nothing(arg[i])) break; #endif /* advance to the next argument */ vp = vp->arg2; } #if 0 /* 14-OCT-2003 */ if(dr_is_nothing(arg[i])){ /* abort calculation */ return(arg[i]); } #endif #if !(MaxNArgs-4) res = (*func)(arg[0],arg[1],arg[2],arg[3],v[0],v[1],v[2],v[3]); #else ERROR; /* The above function call must be changed. Functions which utilized v-arguments must be appropriatedly changed. */ #endif /* check the value is constant or not */ ieval = EVAL_CONST; for(i=0; i<MaxNArgs; i++){ if(!v[i]) break; if(v[i]->eval!=EVAL_CONST){ ieval = EVAL_NONE; break; } } args->eval = ieval; return(res); } void dr_show_r(dr) dr_t *dr; { int i, j, min, max; double *p; dr_rec_t *r; printf("[Dump of dr_data]\n"); if(dr==(dr_t*)NULL){ fprintf(stderr, "dr_show: Null pointer.\n"); return; } r = dr->rec; if(r==(dr_rec_t*)NULL){ #if 0 fprintf(stderr, "dr_show: Null dre->rec pointer.\n"); #else printf("\n"); #endif return; } printf("------------------------------------------------------------\n"); for(i=1; i<dr->n; i++){ r = &dr->rec[i]; printf(" %s:\n", r->nam); #if 0 min = r->imin; max = r->imax; #else min = r->amin; max = r->amax; #endif p = &r->value[min-r->imin]; for(j=min; j<max; j++){ if(dr_is_nothing(*p)) printf(" %5d) %15s\n", j, "N/U"); else printf(" %5d) %15.7f %8x\n", j, *p, (int)*p); p++; } } printf("\n"); } void dr_event(){ neval++; if(!event()) histogram(); #if DEBUG_DR_SHOW dr_show(); #endif } #if DEBUG_EVAL void show_eval(str,add) char *str; { static int show_eval_level=0; static char show_eval_str[1024]; show_eval_level += add; if(add>0){ if(show_eval_level==0) strcpy(show_eval_str,str); else{ strcat(show_eval_str,"->"); strcat(show_eval_str,str); } fprintf(stderr, "%s\n", show_eval_str); }else{ if(show_eval_level) show_eval_str[strlen(show_eval_str)-strlen(str)-2] = 0; else show_eval_str[0]= 0; } } #endif /* evaluate a value */ double eval(v) vrec_p v; /* value to evaluate */ { double d, d1, d2; dr_rec_t *r; int i; dr_set_nothing(&d); if(!v) return(d); /* return if already evaluated */ if(v->neval >= neval) return(v->dval); /* check evaluation */ if(v->eval==EVAL_CONST) return(v->dval); if(v->eval==EVAL_UNDER){ if(v->vtype==NAME || v->vtype==NAME2) showerr("Cyclic evaluation of %s.\n", v->sval); else if(v->vtype==TARRAY) showerr("Cyclic evaluation of %s.\n", v->arg1->sval); else if(v->vtype==NUM) showerr("Cyclic evaluation of NUM %d.\n", v->sval); else if(v->vtype==STR) { showerr("Cyclic evaluation of STR %s.\n", v->sval); } else showerr("Cyclic evaluation.\n"); return(d); } v->eval = EVAL_UNDER; #if DEBUG_EVAL show_eval(str_vtype(v),1); #endif switch(v->vtype){ case NUM: d = v->dval; v->eval = EVAL_CONST; break; case STR: d = 0.; break; case NAME: case NAME2: #if DEBUG_EVAL && 1 show_eval(v->sval,1); #endif d = dr_get_r(&dr_data, &v->vref, v->sval, 0); #if DEBUG_EVAL && 1 show_eval(v->sval,-1); #endif v->eval = EVAL_NONE; break; case TARRAY: #if DEBUG_EVAL && 0 show_eval(v->arg1->sval,1); #endif d1 = eval(v->arg2); if(dr_exists(d1)) d = dr_get_r(&dr_data,&v->arg1->vref,v->arg1->sval,(int)d1); #if DEBUG_EVAL && 0 show_eval(v->arg1->sval,-1); #endif v->eval = EVAL_NONE; break; case '!': /* 'not' of nothing is defined as 'true' */ d1 = eval(v->arg1); d = dr_is_false(d1) ? DR_TRUE : DR_FALSE; v->eval = dr_const(v->arg1) ; break; case '~': d1 = eval(v->arg1); if(dr_exists(d1)) d = (double)(~(int)d1); v->eval = dr_const(v->arg1) ; break; case TUMIN: d1 = eval(v->arg1); if(dr_exists(d1)) d = -d1; v->eval = dr_const(v->arg1) ; break; case '|': d1 = eval(v->arg1); if(dr_exists(d1)){ d2 = eval(v->arg2); if(dr_exists(d2)) d = (double)((int)d1 | (int)d2); v->eval = dr_const2(v->arg1,v->arg2) ; }else v->eval = dr_const(v->arg1) ; break; case '^': d1 = eval(v->arg1); if(dr_exists(d1)){ d2 = eval(v->arg2); if(dr_exists(d2)) d = (double)((int)d1 ^ (int)d2); v->eval = dr_const2(v->arg1,v->arg2) ; }else v->eval = dr_const(v->arg1) ; break; case '&': d1 = eval(v->arg1); if(dr_exists(d1)){ d2 = eval(v->arg2); if(dr_exists(d2)) d = (double)((int)d1 & (int)d2); v->eval = dr_const2(v->arg1,v->arg2) ; }else v->eval = dr_const(v->arg1) ; break; case '<': d1 = eval(v->arg1); if(dr_exists(d1)){ d2 = eval(v->arg2); if(dr_exists(d2)) d = ((d2-d1)>DR_ZERO) ? DR_TRUE : DR_FALSE; v->eval = dr_const2(v->arg1,v->arg2) ; }else v->eval = dr_const(v->arg1) ; break; case '>': d1 = eval(v->arg1); if(dr_exists(d1)){ d2 = eval(v->arg2); if(dr_exists(d2)) d = ((d1-d2)>DR_ZERO) ? DR_TRUE : DR_FALSE; v->eval = dr_const2(v->arg1,v->arg2) ; }else v->eval = dr_const(v->arg1) ; break; case TSL: d1 = eval(v->arg1); if(dr_exists(d1)){ d2 = eval(v->arg2); if(dr_exists(d2)) d = d1 * pow(2.,d2); v->eval = dr_const2(v->arg1,v->arg2) ; }else v->eval = dr_const(v->arg1) ; break; case TSR: d1 = eval(v->arg1); if(dr_exists(d1)){ d2 = eval(v->arg2); if(dr_exists(d2)) d = d1 * pow(2.,-d2); v->eval = dr_const2(v->arg1,v->arg2) ; }else v->eval = dr_const(v->arg1) ; break; case '+': d1 = eval(v->arg1); if(dr_exists(d1)){ d2 = eval(v->arg2); if(dr_exists(d2)) d = d1 + d2; v->eval = dr_const2(v->arg1,v->arg2) ; }else v->eval = dr_const(v->arg1) ; break; case '-': d1 = eval(v->arg1); if(dr_exists(d1)){ d2 = eval(v->arg2); if(dr_exists(d2)) d = d1 - d2; v->eval = dr_const2(v->arg1,v->arg2) ; }else v->eval = dr_const(v->arg1) ; break; case '*': d1 = eval(v->arg1); if(dr_exists(d1)){ d2 = eval(v->arg2); if(dr_exists(d2)) d = d1 * d2; v->eval = dr_const2(v->arg1,v->arg2) ; }else v->eval = dr_const(v->arg1) ; break; case '/': d1 = eval(v->arg1); if(dr_exists(d1)){ d2 = eval(v->arg2); if(dr_exists(d2) && !dr_is_zero(d2)) d = d1 / d2; v->eval = dr_const2(v->arg1,v->arg2) ; }else v->eval = dr_const(v->arg1) ; break; case '%': d1 = eval(v->arg1); if(dr_exists(d1)){ d2 = eval(v->arg2); if(dr_exists(d2) && !dr_is_zero(d2)){ d = d1-d2*(double)((int)(d1/d2)); } v->eval = dr_const2(v->arg1,v->arg2) ; }else v->eval = dr_const(v->arg1) ; break; case TLOR: d1 = eval(v->arg1); if(dr_is_true(d1)){ /* the judgement of nothing is including in dr_is_true() */ d = DR_TRUE; v->eval = dr_const(v->arg1) ; break; } d2 = eval(v->arg2); d = dr_is_true(d2) ? DR_TRUE : DR_FALSE; v->eval = dr_const2(v->arg1,v->arg2) ; break; case TLAND: d1 = eval(v->arg1); if(dr_is_false(d1)){ /* the judgement of nothing is including in dr_is_false() */ d = DR_FALSE; v->eval = dr_const(v->arg1) ; break; } d2 = eval(v->arg2); d = dr_is_true(d2) ? DR_TRUE : DR_FALSE; v->eval = dr_const2(v->arg1,v->arg2) ; break; case TEQ: d1 = eval(v->arg1); if(dr_exists(d1)){ d2 = eval(v->arg2); if(dr_exists(d2)) d = dr_is_zero(d1-d2) ? DR_TRUE : DR_FALSE; v->eval = dr_const2(v->arg1,v->arg2) ; }else{ v->eval = dr_const(v->arg1) ; } break; case TNEQ: d1 = eval(v->arg1); if(dr_exists(d1)){ d2 = eval(v->arg2); if(dr_exists(d2)) d = dr_is_zero(d1-d2) ? DR_FALSE : DR_TRUE; v->eval = dr_const2(v->arg1,v->arg2) ; }else{ v->eval = dr_const(v->arg1) ; } break; case TLE: d1 = eval(v->arg1); if(dr_exists(d1)){ d2 = eval(v->arg2); if(dr_exists(d2)) d = ((d1-d2)<DR_ZERO) ? DR_TRUE : DR_FALSE; v->eval = dr_const2(v->arg1,v->arg2) ; }else v->eval = dr_const(v->arg1) ; break; case TGE: d1 = eval(v->arg1); if(dr_exists(d1)){ d2 = eval(v->arg2); if(dr_exists(d2)) d = ((d2-d1)<DR_ZERO) ? DR_TRUE : DR_FALSE; v->eval = dr_const2(v->arg1,v->arg2) ; }else v->eval = dr_const(v->arg1) ; break; case TFUNC: d = dr_func_r(&dr_data, &v->arg1->vref, v->arg1->sval, v->arg2); v->eval = dr_const(v->arg2) ; break; case TNODE: case TUNDEF: default: showerr("Illegal operator: %s.\n", str_token(v->vtype)); v->eval = EVAL_NONE; break; } #if DEBUG_EVAL show_eval(str_vtype(v),-1); #endif v->dval = d; v->neval = neval; return(d); } void def(v0, v1, v2, v3) vrec_p v0; vrec_p v1, v2, v3; { double d; vrec_p v; #if DEBUG_YACC fprintf(stderr, "enter def()\n"); #endif if(v0==(vrec_p)NULL){ showerr("def: null pointer argument\n"); return; } d = eval(v0); if(dr_is_nothing(d)) return; if(check_level(d)) return; if(v1==(vrec_p)NULL || v3==(vrec_p)NULL){ showerr("def: null pointer argument\n"); return; } v1->vtype = '='; v1->arg1 = v2; v1->arg2 = v3; dr_set_vrec(&dr_data, &v1->vref, v1->sval, v1); #if DEBUG_DEFINITION fprintf(stderr, "Define variable '%s'.\n", v1->sval); #endif } /* get new histogram record */ hist_p new_hist(){ hist_p p; int i; for(i=0; i<nhists; i++){ #if 0 if(hists[i].type == HIST_NONE){ p = &hists[i]; break; } #endif } if(i>=nhists){ p = (hist_p)realloc(hists,sizeof(hist_t)*(nhists+1)); if(p==(hist_p)NULL){ fprintf(stderr, "new_hist: could not allocate memory.\n"); return((hist_p)NULL); } hists = p; nhists++; p = &p[i]; } #if 0 p->id = i+1; #else p->id = histid++; #endif p->type = HIST_NONE; p->sname = p->name = (char*)NULL; p->xlabel = p->ylabel = (char*)NULL; p->v1 = p->min1 = p->max1 = p->nbin1 = (vrec_p)NULL; p->v2 = p->min2 = p->max2 = p->nbin2 = (vrec_p)NULL; p->gate = (vrec_p)NULL; return(p); } hist_p search_hist(sname) char *sname; { hist_p p; int i; char c; p = hists; c = *sname; for(i=0; i<nhists; i++, p++){ if(hists[i].type == HIST_NONE) continue; if(*(p->sname)==c && !strcmp(p->sname,sname)){ return(p); } } return((hist_p)NULL); } void free_hist(p) hist_p p; { int i; vrec_p v; switch(p->type){ case HIST_NONE: break; case HIST_1D: if(p->id){ if(!cflag){ fprintf(stderr, "Delete 1D-histogram #%3d '%s'.\n", p->id, p->name); } #if DEBUG_DEFINITION #endif hstdel(p->id); } if(p->sname) { free(p->sname); p->sname = (char*)NULL; } if(p->name) { free(p->name); p->name = (char*)NULL; } if((v=p->v1)) { p->v1 = (vrec_p)NULL; free_vrecp(v); } if((v=p->min1)) { p->min1 = (vrec_p)NULL; free_vrecp(v); } if((v=p->max1)) { p->max1 = (vrec_p)NULL; free_vrecp(v); } if((v=p->nbin1)){ p->nbin1 = (vrec_p)NULL; free_vrecp(v); } if(p->xlabel) { free(p->xlabel); p->xlabel = (char*)NULL; } if(p->ylabel) { free(p->ylabel); p->ylabel = (char*)NULL; } if((v=p->gate)) { p->gate = (vrec_p)NULL; free_vrecp(v); } p->type = HIST_NONE; break; case HIST_2D: if(p->id){ hstdel(p->id); fprintf(stderr, "Delete 2D-histogram #%3d '%s'.\n", p->id, p->name); #if DEBUG_DEFINITION #endif } if(p->sname) { free(p->sname); p->sname = (char*)NULL; } if(p->name) { free(p->name); p->name = (char*)NULL; } if((v=p->v1)) { p->v1 = (vrec_p)NULL; free_vrecp(v); } if((v=p->min1)) { p->min1 = (vrec_p)NULL; free_vrecp(v); } if((v=p->max1)) { p->max1 = (vrec_p)NULL; free_vrecp(v); } if((v=p->nbin1)){ p->nbin1 = (vrec_p)NULL; free_vrecp(v); } if(p->xlabel) { free(p->xlabel); p->xlabel = (char*)NULL; } if((v=p->v2)) { p->v2 = (vrec_p)NULL; free_vrecp(v); } if((v=p->min2)) { p->min2 = (vrec_p)NULL; free_vrecp(v); } if((v=p->max2)) { p->max2 = (vrec_p)NULL; free_vrecp(v); } if((v=p->nbin2)){ p->nbin2 = (vrec_p)NULL; free_vrecp(v); } if(p->ylabel) { free(p->ylabel); p->ylabel = (char*)NULL; } if((v=p->gate)) { p->gate = (vrec_p)NULL; free_vrecp(v); } p->type = HIST_NONE; break; default: fprintf(stderr, "free_hist: unknown histogram type %d\n", p->type); p->type = HIST_NONE; break; } } /* re-use histogram record */ hist_p reuse_hist(p) hist_p p; { free_hist(p); /* currently nothing to do here*/ return(p); } void reinit_hist() { hist_p p; int i; vrec_p v; #if DEBUG_DEFINITION fprintf(stderr, "Clear all the histograms.\n"); #endif p = hists; for(i=0; i<nhists; i++, p++) free_hist(p); free(hists); hists = (hist_p)NULL; nhists = 0; histid = 1; } int check_level(d) double d; { int l; l = (int)(d+0.5); if(level>=0){ if(d<0){ level = d; return(1); }else{ return(0); } }else{ if(d<0){ if(d>level){ level = d; return(1); }else{ return(1); } }else{ if(d>-level){ return(1); }else{ level = 0; return(0); } } } } void com(v0) vrec_p v0; { double d; if(v0==(vrec_p)NULL){ showerr("com: null pointer argument\n"); return; } d = eval(v0); if(dr_is_nothing(d)) return; if(check_level(d)) return; return; } /* convert text to the PAW Text Style */ #define append(d,c) {strcpy((d),(c)); (d) = &(d)[strlen(c)];} char *cvtext(str) char *str; { static char newtext[256]; char *s, *d, *e; char c; d = newtext; s = str; e = &str[strlen(str)]; if(!(*s)){ /* no title text */ strcpy(newtext,"^!"); /* no text */ return(newtext); } /* convert title text */ while(s<e && (c=*s++)){ switch(c){ case '[': append(d,"\"M#"); break; case ']': append(d,"\"N#"); break; case '!': append(d,"\"E#"); break; case '%': append(d,"\"Y#"); break; case '<': append(d,"\"L#"); break; case '>': append(d,"\"G#"); break; case '}': *d++ = '!'; break; case '{': /* Greek */ *d++ = '['; while((c=*s++)){ if(c=='}'){ *d++ = ']'; break; }else{ *d++ = c; } } break; case '^': /* upper index */ *d++ = '^'; if(*s=='{') s++; else{ *d++ = *s++; *d++ = '!'; } break; case '_': /* lower index */ *d++ = '?'; if(*s=='{') s++; else{ *d++ = *s++; *d++ = '!'; } break; default: *d++ = c; } } *d = 0x00; return(newtext); } #if USE_PAW void output_alias(p) hist_p p; { extern FILE *falias; if(!falias){ open_alias_file(); } if(falias){ fprintf(falias, "alias/create %-20s %d\n", p->sname, p->id); fprintf(falias, "alias/create NAM%d '!%s'\n", p->id, p->sname); fprintf(falias, "alias/create TTL%d '%s'\n", p->id, cvtext(p->name)); fprintf(falias, "alias/create TAX%d '%s'\n", p->id, cvtext(p->xlabel)); fprintf(falias, "alias/create TAY%d '%s'\n", p->id, cvtext(p->ylabel)); fflush(falias); } } #endif #if USE_ROOT void cvtolower(d,s) char *d, *s; { int i; char *d2, *s2; do { *d = tolower(*s++); } while(*d++); } void output_alias(p) hist_p p; { FILE *falias; char str[256]; char fnam[256]; cvtolower(str,p->sname); sprintf(fnam, "%s/%s", ROOT_ALIASDIR, str); falias = fopen(fnam, "w"); if(falias==(FILE*)NULL){ fprintf(stderr, "Warning: could not open alias file '%s'.\n", fnam); return; } fprintf(falias, "{\n"); #if 0 fprintf(falias, " shm = TMapFile::Create(\"%s\");\n", ROOT_SHMNAM); fprintf(falias, " hist = shm->Get(\"%s\");\n", p->sname); fprintf(falias, " hist->Draw();\n"); #else fprintf(falias, " plot(\"%s\");\n", p->sname); #endif fprintf(falias, "}\n"); fclose(falias); } #endif void hist1(v0, sname, name, v, min, max, nbin, xlabel, ylabel, gate) vrec_p v0; vrec_p sname, name; vrec_p v, min, max, nbin, xlabel, ylabel; vrec_p gate; { double dmin, dmax, dnbin; hist_p p; double d; char title[256]; if(v0==(vrec_p)NULL){ showerr("hist1: null pointer argument\n"); return; } d = eval(v0); if(dr_is_nothing(d)) return; if(check_level(d)) return; p = search_hist(sname->sval); if(p){ reuse_hist(p); showerr("Histogram #%3d '%s' is superseded.\n", p->id, sname->sval); #if DEBUG_DEFINITION #endif }else{ p = new_hist(); if(!p) return; #if DEBUG_DEFINITION showerr("Create 1D-histogram #%3d '%s'.\n", p->id, sname->sval); #endif } p->sname = strdup(sname->sval); p->name = strdup(name->sval); p->v1 = v; p->min1 = min; p->max1 = max; p->nbin1 = nbin; p->gate = gate; p->xlabel = strdup(xlabel->sval); p->ylabel = strdup(ylabel->sval); dmin = eval(min); dmax = eval(max); dnbin = eval(nbin); p->type = HIST_1D; if(dr_exists(dmin) && dr_exists(dmax) && dr_exists(dnbin)){ hbk1(p->id, p->sname, cvtext(p->name), dmin, dmax, (int)dnbin); #if USE_ROOT hxytitle(p->id, p->xlabel, p->ylabel); #endif output_alias(p); }else{ showerr("Failed to create 1D histogram #%3d '%s'.\n", p->id, sname->sval); /* free allocated memories */ p->id = 0; free_hist(p); } } void hist2(v0, sname, name, v1, min1, max1, nbin1, xlabel,v2, min2, max2, nbin2, ylabel, gate) vrec_p v0; vrec_p sname, name; vrec_p v1, min1, max1, nbin1, xlabel; vrec_p v2, min2, max2, nbin2, ylabel; vrec_p gate; { double dmin1, dmax1, dnbin1; double dmin2, dmax2, dnbin2; hist_p p; double d; if(v0==(vrec_p)NULL){ showerr("hist1: null pointer argument\n"); return; } d = eval(v0); if(dr_is_nothing(d)) return; if(check_level(d)) return; p = search_hist(sname->sval); if(p){ reuse_hist(p); showerr("Histogram #%3d '%s' is superseded.\n", p->id, sname->sval); #if DEBUG_DEFINITION #endif }else{ p = new_hist(); if(!p) return; #if DEBUG_DEFINITION showerr("Create 2D-histogram #%3d '%s'.\n", p->id, sname->sval); #endif } p->sname = strdup(sname->sval); p->name = strdup(name->sval); p->v1 = v1; p->min1 = min1; p->max1 = max1; p->nbin1 = nbin1; p->xlabel = strdup(xlabel->sval); p->v2 = v2; p->min2 = min2; p->max2 = max2; p->nbin2 = nbin2; p->ylabel = strdup(ylabel->sval); p->gate = gate; p->type = HIST_2D; dmin1 = eval(min1); dmax1 = eval(max1); dnbin1 = eval(nbin1); dmin2 = eval(min2); dmax2 = eval(max2); dnbin2 = eval(nbin2); if(dr_exists(dmin1) && dr_exists(dmax1) && dr_exists(dnbin1) && dr_exists(dmin2) && dr_exists(dmax2) && dr_exists(dnbin2)){ hbk2(p->id, p->sname, cvtext(p->name), dmin1, dmax1, (int)dnbin1, dmin2, dmax2, (int)dnbin2); output_alias(p); #if USE_ROOT hxytitle(p->id, p->xlabel, p->ylabel); #endif }else{ showerr("Failed to create 2D histogram #%3d '%s'.\n", p->id, sname->sval); /* free allocated memories */ p->id = 0; free_hist(p); } } /* Histogram Output */ int histogram(){ int i, j, n; double f; hist_p h; double g, d, d1, d2; vrec_p v, v1, v2; h = hists; for(i=0; i<nhists; i++, h++){ switch(h->type){ case HIST_NONE: break; case HIST_1D: if(h->gate){ g = eval(h->gate); if(dr_is_nothing(g)) break; if(dr_is_false(g)) break; } v = h->v1; if(v->vtype==NAME2){ (void)eval(v); j = dr_min_r(&dr_data,&v->vref,v->sval,0); n = dr_max_r(&dr_data,&v->vref,v->sval,0); for(;j<n;j++){ d = dr_get_r(&dr_data,&v->vref,v->sval,j); if(!dr_is_nothing(d)){ hfil1(h->id,d); } } }else{ d = eval(v); if(!dr_is_nothing(d)) hfil1(h->id,d); } break; case HIST_2D: if(h->gate){ g = eval(h->gate); if(dr_is_nothing(g)) break; if(dr_is_false(g)) break; } v1 = h->v1; v2 = h->v2; if(v1->vtype==NAME2){ if(v2->vtype==NAME2){ /* v1 = multi data, v2 = multi data */ (void)eval(v1); (void)eval(v2); j = max(dr_min_r(&dr_data,&v1->vref,v1->sval,0), dr_min_r(&dr_data,&v2->vref,v2->sval,0)); n = min(dr_max_r(&dr_data,&v1->vref,v1->sval,0), dr_max_r(&dr_data,&v2->vref,v2->sval,0)); for(;j<n;j++){ d1 = dr_get_r(&dr_data,&v1->vref,v1->sval,j); d2 = dr_get_r(&dr_data,&v2->vref,v2->sval,j); if(!dr_is_nothing(d1) && !dr_is_nothing(d2)){ hfil2(h->id,d1,d2); } } }else{ /* v1 = multi data, v2 = single data */ (void)eval(v1); d2 = eval(v2); if(!dr_is_nothing(d2)){ j = dr_min_r(&dr_data,&v1->vref,v1->sval,0); n = dr_max_r(&dr_data,&v1->vref,v1->sval,0); for(;j<n;j++){ d1 = dr_get_r(&dr_data,&v1->vref,v1->sval,j); if(!dr_is_nothing(d1)){ hfil2(h->id,d1,d2); } } } } }else{ if(v2->vtype==NAME2){ /* v1 = single data, v2 = multi data */ d1 = eval(v1); if(!dr_is_nothing(d1)){ (void)eval(v2); j = dr_min_r(&dr_data,&v2->vref,v2->sval,0); n = dr_max_r(&dr_data,&v2->vref,v2->sval,0); for(;j<n;j++){ d2 = dr_get_r(&dr_data,&v2->vref,v2->sval,j); if(!dr_is_nothing(d2)){ hfil2(h->id,d1,d2); } } } }else{ /* v1 = single data, v2 = single data */ d1 = eval(v1); d2 = eval(v2); if(!dr_is_nothing(d1) && !dr_is_nothing(d2)) hfil2(h->id,d1,d2); } } break; default: showerr("histogram: unknown histogram type %d\n", h->type); break; } } return(0); } double fint(d) double d; { if(!dr_exists(d)) return(d); return((double)((int)d)); } double fanalog(d) double d; { if(!dr_exists(d)) return(d); return((double)(d+drand48()-0.5)); } double fbool(d) double d; { if(!dr_exists(d) || dr_is_zero(d)) return(0.); return(1.); } double pow2(d) double d; { double t; if(!dr_exists(d)){ dr_set_nothing(&t); return(t); } return(d*d); } double f_gate(arg1, arg2, arg3) double arg1, arg2, arg3; { int res; res = (arg2 <= arg1 && arg1 < arg3); return((double)res); } double f_bit(arg1, arg2) double arg1, arg2; { int x, bit, res; x = (int)arg1; bit = (int)arg2; res = (x & (1<<bit))!=0; return((double)res); } double f_if(arg1, arg2, arg3) double arg1, arg2, arg3; { double res; if(dr_is_false(arg1)) res = arg3; else res = arg2; return(res); } /* f_polynom() ... added on 14-OCT-2003 */ #if !(MaxNArgs-4) double f_polynom(arg1, arg2, arg3, arg4, v1, v2, v3, v4) double arg1, arg2, arg3, arg4; vrec_p v1, v2, v3, v4; { double d, dp, c, res; int min, max, j; d = arg1; if(dr_is_nothing(d)) return(d); if(!v2->sval){ fprintf(stderr, "Error in the expression of arg2 of the polynom()\n"); return(0.); } min = dr_min_r(&dr_data,&v2->vref,v2->sval,0); max = dr_max_r(&dr_data,&v2->vref,v2->sval,0); res = 0.; if(min<0){ if(d==0.){ dr_set_nothing(&res); return(res); } dp = 1.; for(j=-1;max<=j;j--) dp /= d; for(;min<=j;j--){ dp /= d; c = dr_get_r(&dr_data,&v2->vref,v2->sval,j); if(dr_exists(c)) res += c*dp; } } if(0<max){ dp = 1.; for(j=0;j<min;j++) dp *= d; for(;j<max;j++){ c = dr_get_r(&dr_data,&v2->vref,v2->sval,j); if(dr_exists(c)) res += c*dp; dp *= d; } } return(res); } #else Error in the above procedure. #endif int dr_init_func(){ extern double sin(), cos(), tan(); extern double acos(), asin(), atan(); extern double sinh(), cosh(), tanh(); extern double log(), log10(), exp(); extern double sqrt(), fabs(), pow2(); extern double fint(); extern double fanalog(); extern double fbool(); dr_add_func("sin", sin); dr_add_func("pow2", pow2); dr_add_func("cos", cos); dr_add_func("tan", tan); dr_add_func("asin", asin); dr_add_func("acos", acos); dr_add_func("atan", atan); dr_add_func("sinh", sinh); dr_add_func("cosh", cosh); dr_add_func("tanh", tanh); dr_add_func("log", log10); dr_add_func("ln", log); dr_add_func("exp", exp); dr_add_func("sqrt", sqrt); dr_add_func("abs", fabs); dr_add_func("int", fint); dr_add_func("analog",fanalog); dr_add_func("bool", fbool); dr_add_func("gate", f_gate); dr_add_func("bit", f_bit); dr_add_func("if", f_if); dr_add_func("polynom", f_polynom); srand48(0); return 0; } int dr_init(){ dr_data.n = 1; dr_data.nmax = 0; dr_data.rec = (dr_rec_t*)NULL; level = 0; dr_init_func(); return(0); } int dr_exit(){ event_exit(); return(0); } /* Local Variables: mode: C tab-width: 2 End: */ <file_sep>/* chamb.c ---- wire chamber analysis Version 1.00 10-JUL-2000 by <NAME> Version 1.10 21-MAY-2004 by <NAME> (Add offset to chamb_get_dt2d_tab) */ #include <stdio.h> #include <stdlib.h> /* for drand48() */ #include <string.h> #include <math.h> #include "freadin.h" #include "histogram.h" #include "analyzer.h" //FLAG #if DT2D_TAB /* drift time to distance conversion (by table)*/ static double dt2dist_tab(tab,tdc) dt2dtab *tab; int tdc; { double err; double d1, d2; if(tdc<0 || tab->nitem<=tdc){ dr_set_nothing(&err); return(err); } d1 = tab->conv[tdc]; #if DT2D_TAB_ANALOG /* interpolation by a randam number */ if(dr_exists(d1) && tdc < tab->end){ d2 = tab->conv[tdc+1]; if(dr_exists(d2)) d1 += (d2-d1)*drand48(); } #endif return(d1); } /* Add offset on 21-MAY-2004 */ /* get drift time to distance table (histogram conversion)*/ int chamb_get_dt2d_tab(chamb) chamber_p chamb; { #define MaxNChamb 10 char *file; FILE *fd; double data[MaxNChamb]; int i, n, nitem; char str[256], fmt[256]; char *s; static int itmp; int start, end; double dstart, dend; dt2dtab *tab; double s1, s2, sum; int npl; double offset; /* added 21-MAY-2004 */ int iofs; /* added 21-MAY-2004 */ /* initialize */ npl = chamb->npl; if(npl>MaxNChamb){ showerr("chamb_get_dt2d_tab: too many planes %d for %s\n", npl, chamb->name); return(-1); } for(n=0; n<npl; n++){ chamb->plane[n].tab.nitem = 0; } /* get file name */ s = spf("%s_WTDC_FILE", chamb->name); itmp = 0; /* must be cleared */ file = dr_get_sval_r(&dr_data, &itmp, s, 0); if(file==(char*)NULL){ showerr("chamb_get_dt2d_tab: could not get file name from '%s'.\n", s); return(-1); } fd = fopen(file, "r"); if(fd==(FILE*)NULL){ showerr("chamb_get_dt2d_tab: could not open file '%s'.\n", file); return(-1); } /* read file */ printf("Reading %s WTDC File: '%s' ... ", chamb->name, file); fmt[0]=0; for(n=0; n<npl; n++) strcat(fmt, "%lf"); for(nitem=0; nitem<MaxNConv; nitem++){ if(!fgets(str, 256, fd)) break; n = sscanf(str, fmt, &data[0], &data[1], &data[2], &data[3], &data[4], &data[5], &data[6], &data[7], &data[8], &data[9] ); if(n==0){ showerr( "chamb_get_dt2d_tab: could not read data from the line %d of '%s'.\n", nitem+1, file); return(-1); break; } if(n!=npl){ showerr("chamb_get_dt2d_tab: not enough (%d) data in the line %d of '%s'.\n", npl, nitem+1, file); return(-1); } for(n=0; n<npl; n++) chamb->plane[n].tab.conv[nitem] = (int)data[n]; } printf("Done.\n"); /* read offset */ iofs = 0; s = spf("%s_WTDC_OFFSET", chamb->name); itmp = 0; offset = dr_get_r(&dr_data, &itmp, s, 0); if(dr_exists(offset)){ iofs = (int)(offset); printf("%s WTDC Offset = %5d ch\n", chamb->name, iofs); } /* calc correction table */ for(n=0; n<npl; n++){ tab = &chamb->plane[n].tab; tab->start = 0; tab->end = 0; /* getting the gate values (low bound = start, high bound = end) for each VDC plane */ s = spf("%s_WTDC_%s", chamb->name, chamb->plane[n].name); itmp = 0; /* must be cleared */ dstart = dr_get_r(&dr_data, &itmp, s, 0); dend = dr_get_r(&dr_data, &itmp, s, 1); if(dr_is_nothing(dstart)||dr_is_nothing(dend)){ showerr("chamb_get_dt2d_tab: could not get value from '%s'.\n", s); continue; } start = dr_int(dstart); end = dr_int(dend); if(start>=end){ showerr("chamb_get_dt2d_tab: the arg #0 of '%s' must be smaller than the arg #1.\n", s); continue; } sum = 0; start = max(start,0); end = min(end,nitem-1); for(i=0; i<start; i++) dr_set_nothing(&tab->conv[i]); for(; i<end; i++) sum += tab->conv[i]; for(; i<nitem; i++) dr_set_nothing(&tab->conv[i]); s2 = 0.; for(i=end-1; start<=i; i--){ s1 = tab->conv[i]; tab->conv[i+1] = s2/sum; s2 += s1; } tab->conv[start] = s2/sum; /* = 1.0 */ tab->start = start; tab->end = end; tab->nitem = nitem; tab->offset = iofs; #if DEBUG_TEMP && 0 printf("plane = %d\n", n); for(i=start; i<end; i++){ printf(" tab[%3.d] = %f\n", i, tab->conv[i]); } #endif } return 0; } #else /* if DT2D_TAB - GR_TDCR */ /* 2 dimensional polynomial fit */ /* with no division-by-zero check */ static int fit_2dim(x,y,c,s) double x[3]; /* 3 x points */ double y[3]; /* 3 y points */ double c[3]; /* fit parameters */ double *s; /* integral of the fit function */ { double x1, x2, y1, y2; y1 = y[0]-y[1]; y2 = y[0]-y[2]; x1 = x[0]-x[1]; x2 = x[0]-x[2]; c[2] = (-y1/x1+y2/x2)/(x1-x2); c[1] = -y1/x1-c[2]*x1; c[0] = y[0]; *s = ((c[2]/3*x2+c[1]/2)*x2+c[0])*x2; #if 0 printf("\n"); printf(" x = %15.7f %15.7f %15.7f\n", x[0], x[1], x[2]); printf(" y = %15.7f %15.7f %15.7f\n", y[0], y[1], y[2]); printf(" c = %15.7f %15.7f %15.7f\n", c[2], c[1], c[0]); printf(" y[1] = %15.7f\n", c[2]*x1*x1+c[1]*x1+c[0]); printf(" y[2] = %15.7f\n", c[2]*x2*x2+c[1]*x2+c[0]); printf(" s = %15.7f\n", *s); #endif } /* VDC drift time to distance conversion (by parameter fit)*/ static double dt2dist_prm(d,tdc) dt2dprm *d; int tdc; { double dist; double t; if(tdc > d->t[0]){ dr_set_nothing(&dist); }else if(tdc > d->t[1]){ t = analog(d->t[0]-tdc); dist = ((d->p1[3]*t + d->p1[2])*t + d->p1[1])*t + d->p1[0]; }else if(tdc > d->t[2]){ t = analog(d->t[1]-tdc); dist = ((d->p2[3]*t + d->p2[2])*t + d->p2[1])*t + d->p2[0]; }else{ dr_set_nothing(&dist); } return(dist); } /* get drift time to distance parameters (5-point 2-dimensional fit)*/ static int get_dt2d_prm(){ char *str, *nsp, *npl; double t[5]; double f[5]; double c1[3]; double c2[3]; double s1, s2, sa; static int h_dt2dprm[N_VDC_PL][10]; dt2dprm *prm; int i, pl; for(pl=0; pl<N_VDC_PL; pl++){ prm = &vdc_cluster[pl].prm; nsp = spnam[(pl>>2)&0x01]; npl = vplnam[pl&0x03]; str = spf("%s_VDC_%s_T", nsp, npl); for(i=0; i<5; i++){ t[i] = dr_get_r(&dr_data, &h_dt2dprm[pl][i*2], str, i*2); f[i] = dr_get_r(&dr_data, &h_dt2dprm[pl][i*2+1], str, i*2+1); if(dr_is_nothing(t[i])||dr_is_nothing(f[i])) break; if(f[i]<0){ showerr("get_dt2d_prm: %s[%d](%f) must be greater than 0\n", str, i*2+1, f[i]); break; } if(0<i && t[i-1]<=t[i]){ showerr("get_dt2d_prm: %s[%d](%f) must be greater than %s[%d](%f)\n", str, (i-1)*2, t[i-1], str, i*2, t[i]); break; } } if(i<5) continue; fit_2dim(&t[0],&f[0],c1,&s1); fit_2dim(&t[2],&f[2],c2,&s2); prm->t[0] = dr_int(t[0]); prm->t[1] = dr_int(t[2]); prm->t[2] = dr_int(t[4]); sa = 1/(s1+s2); prm->p1[0] = 0.; prm->p1[1] = sa*c1[0]; prm->p1[2] = sa*c1[1]/2; prm->p1[3] = sa*c1[2]/3; prm->p2[0] = sa*s1; prm->p2[1] = sa*c2[0]; prm->p2[2] = sa*c2[1]/2; prm->p2[3] = sa*c2[2]/3; #if 0 printf("pl=%1d prm = %d %d %d\n", pl, prm->t[0], prm->t[1], prm->t[2]); printf(" c1 = %f %f %f\n", c1[2], c1[1], c1[0]); printf(" c2 = %f %f %f\n", c2[2], c2[1], c2[0]); #endif } } #endif /* if DT2D_TAB */ /* Clusterize */ int chamb_clust(plane) plane_p plane; { switch(plane->chamb->type){ case CHAMB_VDC: return(chamb_vdc_clust(plane)); case CHAMB_MWDC: return(chamb_mwdc_clust(plane)); case CHAMB_MWPC: return(chamb_mwpc_clust(plane)); } showerr("Unknown chamber type %d for %s of %s\n", plane->chamb->type, plane->name, plane->chamb->name); return(-1); } /* drift time to distance calculation */ int chamb_drift(plane) plane_p plane; { int i, ic, size; struct clst *clst; double d; if(plane==(plane_p)NULL){ fprintf(stderr, "evt_drift: null plane pointer\n"); return(-1); } for(ic=0; ic<plane->nc; ic++) { clst = &plane->clst[ic]; size = clst->size; for(i=0; i<size; i++){ #if DT2D_TAB clst->dist[i] = d = dt2dist_tab(&plane->tab,clst->tdc[i]); #else clst->dist[i] = d = dt2dist_prm(&plane->prm,clst->tdc[i]); #endif if(dr_exists(d)) dr_append_ref(plane->h_drift,d); } if(dr_is_true(dr_get(VDC_ANA_MULTI_CLUST))){ /* calculate drift length only for the cluster #1 */ if(plane->chamb->type==CHAMB_VDC) break; } } return(0); } /* Position Calculation */ int chamb_pos(plane) plane_p plane; { switch(plane->chamb->type){ case CHAMB_VDC: return(chamb_vdc_pos(plane)); case CHAMB_MWDC: return(chamb_mwdc_pos(plane)); case CHAMB_MWPC: return(chamb_mwpc_pos(plane)); } showerr("Unknown chamber type %d for %s of %s\n", plane->chamb->type, plane->name, plane->chamb->name); return(-1); } /* Position Calculation */ int chamb_ray(chamb) chamber_p chamb; { switch(chamb->type){ case CHAMB_VDC: if(chamb->ana_mult_clst){ return(ray_4p_mult(chamb)); }else{ return(ray_4p(chamb)); } case CHAMB_MWDC: return(ray_mwdc(chamb)); case CHAMB_MWPC: return(ray_4p(chamb)); } showerr("Unknown chamber type %d for %s\n", chamb->type, chamb->name); return(-1); } /* output rays into a file */ int chamb_outputray(chamb, fd, fnam, nrays) chamber_p chamb; FILE **fd; char *fnam; int *nrays; { ray_p ray; ray = &chamb->ray; if(!*fd){ *fd = fopen(fnam, "w"); if(!*fd){ showerr("outputray: could not open file '%s'\n.", fnam); *nrays = 0; return(-1); } showerr("output %d rays in '%s'.\n", *nrays, fnam); } fprintf(*fd, "set arrow from %f,%f to %f, %f nohead \n", -1000., ray->org.x-ray->dir.x*1000, 1000., ray->org.x+ray->dir.x*1000); if(--(*nrays)==0){ fclose(*fd); *fd = (FILE*)NULL; } return(-1); } /* get intersection points */ int chamb_intersection(chamb) chamber_p chamb; { vec_rec plane; vec_rec pt; int i; for(i=0; i<chamb->nproj; i++){ plane.x = dr_get_ref(chamb->h_proj[i], 0); plane.y = dr_get_ref(chamb->h_proj[i], 1); plane.z = dr_get_ref(chamb->h_proj[i], 2); ray_intersection(&chamb->ray, &plane, &pt); dr_set_ref(chamb->h_x, i, pt.x); dr_set_ref(chamb->h_y, i, pt.y); } return 0; } /* initialize data before an event (for a chamber)*/ int chamb_init_chamb(chamb) chamber_p chamb; { double f; int i; ray_p ray; ray = &chamb->ray; ray->rayid = RAYID_UNDEF; dr_set_nothing(&ray->org.x); dr_set_nothing(&ray->org.y); dr_set_nothing(&ray->org.z); dr_set_nothing(&ray->dir.x); dr_set_nothing(&ray->dir.y); dr_set_nothing(&ray->dir.z); for(i=0; i<chamb->npl; i++){ chamb->plane[i].nc = 0; chamb->plane[i].clst[0].posid = POSID_UNDEF; dr_set_nothing(&chamb->plane[i].clst[0].pos); } chamb->ncomb = -1; chamb->chi2 = -1; return(0); } /* init_plane_config */ int init_plane_config(plane) plane_p plane; { int i, j, nc; double f; double rot; double disp; double dl; int h; wire_p wire; h = 0; dr_ref_n(spf("%s_PL_%s" , plane->chamb->name, plane->name), &h); wire = &plane->wire; wire->ok = 0; wire->org.x = dr_get_ref(h,0); wire->org.y = dr_get_ref(h,1); wire->org.z = dr_get_ref(h,2); wire->disp = disp = dr_get_ref(h,3); wire->rot = rot = dr_get_ref(h,4)*d2r; wire->dl = dl = dr_get_ref(h,5); wire->dsp.x = disp*cos(rot); wire->dsp.y = disp*sin(rot); wire->dsp.z = 0.; wire->dir.x = -sin(rot); wire->dir.y = cos(rot); wire->dir.z = 0.; wire->drf.x = 0.; wire->drf.y = 0.; wire->drf.z = dl; for(i=0; i<6; i++){ if(dr_is_nothing(dr_get_ref(h,i))) return(-1); } if(fabs(wire->dir.z) > 1e-10){ showerr( "init_plane_config: wire direction with z component is not supported\n"); show_vec(&wire->dir); showerr("\n"); return(-1); } if(fabs(wire->dsp.z) > 1e-10){ showerr( "init_plane_config: wire displacement with z component is not supported\n"); show_vec(&wire->dsp); showerr("\n"); return(-1); } if(fabs(dl) < 1e-10){ showerr("init_plane_config: no drift length.\n"); show_vec(&wire->drf); showerr("\n"); return(-1); } wire->sc = disp/dl; wire->ok = 1; return(0); } /* get chamber configuration */ int chamb_get_config(chamb) chamber_p chamb; { int i; plane_p plane; for(i=0; i<chamb->npl; i++){ plane = &chamb->plane[i]; init_plane_config(plane); } chamb->max_ncomb = Clst_DefMaxNComb; return(0); } /* initialize variables for a chamber*/ int chamb_init_hist(chamb) chamber_p chamb; { int i; plane_p plane; char *nsp, *npl; nsp = chamb->name; for(i=0; i<chamb->npl; i++){ plane = &chamb->plane[i]; npl = plane->name; dr_ref_n(spf("%s_WIRE_%s", nsp, npl), &plane->h_wire); dr_ref_n(spf("%s_WIRER_%s", nsp, npl), &plane->h_wirer); dr_ref_n(spf("%s_TDC_%s", nsp, npl), &plane->h_tdc); dr_ref_n(spf("%s_TDCR_%s", nsp, npl), &plane->h_tdcr); dr_ref_n(spf("%s_NHIT_%s", nsp, npl), &plane->h_nhit); dr_ref_n(spf("%s_NCLUST_%s", nsp, npl), &plane->h_nclst); dr_ref_n(spf("%s_CLUSTSZ_%s",nsp, npl), &plane->h_clstsz); dr_ref_n(spf("%s_DRIFT_%s", nsp, npl), &plane->h_drift); dr_ref_n(spf("%s_POSID_%s", nsp, npl), &plane->h_posid); dr_ref_n(spf("%s_POS_%s", nsp, npl), &plane->h_pos); dr_ref_n(spf("%s_GRAD_%s", nsp, npl), &plane->h_grad); } return(0); } /* Local Variables: mode: C tab-width: 2 End: */ <file_sep>#include <stdio.h> #include <cstdlib> #include "TFile.h" #include "TROOT.h" #include "TTree.h" #include "TClonesArray.h" #include "GRUTinizerInterface.h" #include "RCNPEvent.h" #include "freadin.h" #include "histogram.h" //FLAG static int ndstvar=0; static char *dstvar[MaxNDSTVar]; static int dstvarref[MaxNDSTVar]; using namespace std; static DSTMap* table; static RCNPEvent* rootevent; static TFile *RootFile; static TTree *tree; static bool SaveRCNPTree; void Init(std::function<void(RCNPEvent*)> func) { std:: cout << "Here" << std::endl; StoreData = func; SaveRCNPTree = RCNPInterface::Instance().SaveTree(); } /** Get variable names Parses the DST_VAR in hist.def for all the variable names to be saved in TTree */ static int root_write_header(char *comment) { char *name, *p, *d, c; char str[256]; // variables to write name = dr_get_sval(DST_VAR); ndstvar = 0; if(name){ d = p = name; c = 1; // any number other than 0 is OK for(int i=0;c;i++){ c = *d++; if((!c && i) || c==':'){ // seperate by ':' if(i>255) i=255; strncpy(str, p, i); str[i] = 0x00; p = d; i = -1; if(ndstvar>=MaxNDSTVar){ // probably need to increase MaxNDSTVar size break; } dstvar[ndstvar] = strdup(str); if (SaveRCNPTree) { table->Set(ndstvar,dstvar[ndstvar]); } dr_ref_n(str, &dstvarref[ndstvar++]); /* dstvar and dstvarref are the main string and integer lookup-pairs for the DST_VARs */ } if(!c) break; } } return(0); } /* Read the data */ int root_write_data() { int ref, min, max; int index1, index2; double d; // data value const int numbtoken = 11; // number of *_CHAN variables in rootalyze.h int token[numbtoken] = {0}; int mult, chan; int multchan[128]; for(int i=0; i<128; i++) { multchan[i]=0; } rootevent = new RCNPEvent; // loop on all the variables for(int iv=0; iv<ndstvar; iv++){ ref = dstvarref[iv]; // get the index of the dst variable (built in header) min = dr_min_ref(ref); max = dr_max_ref(ref); /// Check if current variable is not empty /// if(dr_exists(d=dr_get_ref(ref,min))){ /// Scroll the multiplicity of current variable /// for(int i=min; i<max; i++){ if(dr_exists(d=dr_get_ref(ref,i))){ rootevent->data[iv].push_back(d); //evt->data[iv].push_back(d); } } } } // Check that the scalars flag is not set // Only save nonscalar data // (ie only save data with a timestamp) UShort_t ipr = (UShort_t)dr_get(IPR); ipr = (ipr & 0x8000) >> 15; if (ipr != 1) { StoreData(rootevent); } if (SaveRCNPTree) { tree->Fill(); } //rootevent->Clear(); // do not clear -c.s. return(0); } /* initialize root objects */ int root_init(int nrun){ int res; if (SaveRCNPTree) { char rootname[128]; sprintf(rootname, "rootfiles/run_%04d.root", nrun); RootFile = new TFile(rootname,"RECREATE"); tree = new TTree("rcnptree","RCNP Data Tree"); // rootevent = new RCNPEvent; // allocated in root_write_data table = new DSTMap; fprintf(stderr,""); tree->Branch("rcnpevent", &rootevent); } // make sure hist.def hasn't changed since compiling RCNPEvent::HistDefCheckSum(); if((res=root_write_header((char*)NULL))) { return(res); } return(0); } /* exit */ int root_exit(){ if (SaveRCNPTree) { if(!RootFile) { return(0); } RootFile->cd(); tree->Write("", TObject::kOverwrite); table->Write("", TObject::kOverwrite); RootFile->Close(); } } <file_sep>#ifndef MADC32_REG_H #define MADC32_REG_H /* * Definitions for MADC32 * * Version 0.10 08-MAR-2016 by <NAME> */ /* Size of I/O space */ #define MADC32_MAX_N_MODULES 32 /* Max number of MADC32 Modules */ #define MADC32_BASE_INI 0x32000000 /* VME base address start */ #define MADC32_BASE_INC 0x00010000 /* VME base address increment */ #define MADC32_BASE(module_number) ((MADC32_BASE_INI)+(MADC32_BASE_INC)*(module_number)) #define MADC32_SIZE 0x00010000 /* Memory Mapping Size */ /* VME addressing mode */ #define MADC32_MODE VME_A32UD /* 32bit Extended Non-Prvileged Data Accesss */ #define MADC32_NUM_CHANNELS 32 /* number of channels */ #define MADC_IRQ_THRESHOLD_DEFAULT 6000 /* IRQ Threshold max=8120 */ #define MADC32_MARKING_TYPE_EVENT_COUNTER 0 #define MADC32_MARKING_TYPE_TIME_STAMP 1 #define MADC32_MARKING_TYPE_EXTENDED_TIME_STAMP 3 #define MADC32_DATA_LEN_FORMAT_8BIT 0 #define MADC32_DATA_LEN_FORMAT_16BIT 1 #define MADC32_DATA_LEN_FORMAT_32BIT 2 #define MADC32_DATA_LEN_FORMAT_64BIT 3 #define MADC32_BANK_OPERATION_BANKS_CONNECTED 0 #define MADC32_BANK_OPERATION_BANKS_INDEPENDENT 1 #define MADC32_BANK_OPERATION_TOGGLE_MODE 3 #define MADC32_ADC_RESOLUTION_2K_800NS 0 /* 0.8 micro sec conversion time*/ #define MADC32_ADC_RESOLUTION_4K_1600NS 1 /* 1.6 micro sec */ #define MADC32_ADC_RESOLUTION_4K_HIGH_RES 2 /* 3.2 micro sec */ #define MADC32_ADC_RESOLUTION_8K 3 /* 6.4 micro sec */ #define MADC32_ADC_RESOLUTION_8K_HIGH_RES 4 /* 12.5 micro sec */ #define MADC32_DELAY0_25NS 0 /* 25 ns */ #define MADC32_DELAY1_25NS 0 /* 25 ns */ #define MADC32_WIDTH0_2US 40 /* 2 us */ #define MADC32_WIDTH1_2US 40 /* 2 us */ #define MADC32_USE_GG_GG0 1 /* use GG0 */ #define MADC32_INPUT_RANGE_4V 0 #define MADC32_INPUT_RANGE_10V 1 #define MADC32_INPUT_RANGE_8V 2 #define MADC32_NIM_GAT1_OSC_GG1 0 /* gate 1 input */ #define MADC32_NIM_GAT1_OSC_TIME 1 /* oscillator input */ #define MADC32_NIM_FC_RESET_FAST_CLEAR 0 /* fast clear input */ #define MADC32_NIM_FC_RESET_TIME_STAMP 1 /* reset time stamp */ #define MADC32_NIM_BUSY_BUSY 0 /* as busy */ #define MADC32_NIM_BUSY_GG0 1 /* as gate0 output */ #define MADC32_NIM_BUSY_GG1 2 /* as gate1 output */ #define MADC32_NIM_BUSY_CBUS 3 /* as Cbus output */ #define MADC32_NIM_BUSY_BUFFER_FULL 4 /* buffer full */ #define MADC32_NIM_BUSY_DATA_THRESHOLD 8 /* data in buffer above thereshold */ /* * MADC32 Memory Register */ typedef struct MADC32 { /* Data FIFO */ unsigned int fifo_read; /* read FIFO */ unsigned char res00[0x3FFC]; /* Threshold memory */ unsigned short threshold[32]; /* threshold */ unsigned char res01[0x1FC0]; /* Registers */ unsigned short address_source; unsigned short address_reg; unsigned short module_id; unsigned short res02; unsigned short soft_reset; unsigned short res03[2]; unsigned short firmware_revision; /* IRQ(ROACK) */ unsigned short irq_level; unsigned short irq_vector; unsigned short irq_test; unsigned short irq_reset; unsigned short irq_threshold; unsigned short max_transfer_data; unsigned short withdraw_irq; unsigned char res04[0x0002]; /* MCST CBLT */ unsigned short cblt_mcst_control; unsigned short cblt_address; unsigned short mcst_address; unsigned char res05[0x000A]; /* FIFO handling */ unsigned short buffer_data_length; unsigned short data_len_format; unsigned short readout_reset; unsigned short multi_event; unsigned short marking_type; unsigned short start_acq; unsigned short fifo_reset; unsigned short data_ready; /* operation mode */ unsigned short bank_operation; unsigned short adc_resolution; unsigned short output_format; unsigned short override; unsigned short slc_off; unsigned short skip_oorange; unsigned short ignore_threshold; unsigned char res06[0x0002]; /* gate generator */ unsigned short hold_delay0; unsigned short hold_delay1; unsigned short hold_width0; unsigned short hold_width1; unsigned short use_gg; unsigned char res07[0x0006]; /* Inputs, outputs */ unsigned short input_range; unsigned short ecl_term; unsigned short ecl_gate1_osc; unsigned short ecl_fc_res; unsigned short ecl_busy; unsigned short nim_gate1_osc; unsigned short nim_fc_reset; unsigned short nim_busy; /* Test pulser */ unsigned short pulser_status; unsigned char res08[0x000E]; /* Mesytec control bus */ unsigned short rc_busno; unsigned short rc_modnum; unsigned short rc_opcode; unsigned short rc_adr; unsigned short rc_dat; unsigned short send_return_status; unsigned char res09[0x0004]; /* CTRA */ unsigned short reset_ctr_ab; unsigned short evctr_lo; unsigned short evctr_hi; unsigned short ts_sources; unsigned short ts_divisor; unsigned char res10[0x0002]; unsigned short ts_counter_lo; unsigned short ts_counter_hi; /* CTRB */ unsigned short adc_busy_time_lo; unsigned short adc_busy_time_hi; unsigned short gate1_time_lo; unsigned short gate1_time_hi; unsigned short time_0; unsigned short time_1; unsigned short time_2; unsigned short stop_ctr; } MADC32_t, *MADC32_p; #define MADC32_MULTI_EVENT_NO 0 #define MADC32_MULTI_EVENT_YES_UNLIMITED 1 #define MADC32_MULTI_EVENT_YES_LIMITED 3 /* * TDC data format @Output Buffer */ #if 1 /* Little Endian Definition for Intel CPU */ /* MADC32 Data */ #define MADC32_HEADER_SIGNATURE_DATA 0 #define MADC32_HEADER_SIGNATURE_HEADER 1 #define MADC32_HEADER_SIGNATURE_END_OF_EVENT 3 #define MADC32_SUBHEADER_EXTENDED_TIME_STAMP 0x0024 #define MADC32_SUBHEADER_EVENT 0x0020 #define MADC32_SUBHEADER_FILL 0x0000 typedef struct MADC32_HEADER_SIGNATURE { /* Header Signature bits*/ unsigned res: 21; /* reserved */ unsigned subheader: 9; /* subheader */ unsigned header: 2; /* Header Signature */ } MADC32_HEADER_SIGNATURE_t, *MADC32_HEADER_SIGNATURE_p; typedef struct MADC32_DATA_HEADER { /* Header Word*/ unsigned n_data_words: 12; /* number of data words */ unsigned adc_resolution: 3; /* ADC resolution */ unsigned output_format: 1; /* Output Format */ unsigned module_id: 8; /* Module ID */ unsigned subheader: 6; /* Subheader=b00000 */ unsigned header_signature: 2; /* Header Signature = b01 */ } MADC32_DATA_HEADER_t, *MADC32_DATA_HEADER_p; typedef struct MADC32_DATA_EVENT { /* Data Event Word*/ unsigned adc_amplitude: 14; /* ADC amplitude */ unsigned out_of_range: 1; /* Out of range */ unsigned res0: 1; /* Reserved */ unsigned channel_number: 5; /* Channel Number */ unsigned subheader: 9; /* Subheader=b000100000 */ unsigned header_signature: 2; /* Header Signature = b00 */ } MADC32_DATA_EVENT_t, *MADC32_DATA_EVENT_p; typedef struct MADC32_EXTENDED_TIME_STAMP { /* Extended Time Stamp */ unsigned time_stamp_msb: 16; /* Most Significant 16bit Time Stamp*/ unsigned res0: 5; /* Reserved */ unsigned subheader: 9; /* Subheader=b000100100 */ unsigned header_signature: 2; /* Header Signature = b00 */ } MADC32_EXTENDED_TIME_STAMP_t, *MADC32_EXTENDED_TIME_STAMP_p; typedef struct MADC32_FILL { /* FILL DUMMY (PADDING) */ unsigned res0: 21; /* Reserved =0 */ unsigned subheader: 9; /* Subheader=b000000000 */ unsigned header_signature: 2; /* Header Signature = b00 */ } MADC32_FILL_t, *MADC32_FILL_p; typedef struct MADC32_END_OF_EVENT { /* End of Event */ unsigned event_counter: 30; /* Event Counter or Time Stamp */ unsigned header_signature: 2; /* Header Signature = b11 */ } MADC32_END_OF_EVENT_t, *MADC32_END_OF_EVENT_p; #endif extern char *max_number_hits_s[]; /* * prototype definitions of library functions */ int madc32_open(void); MADC32_p madc32_map(int module_number); int madc32_unmap(int module_number); int madc32_close(void); #endif /* for ifndef MADC32_REG_H */ <file_sep>/* Eurosupernova Online analysis routine ************************************* Version : 2.10 Last Update : Oct 27, 1999 (VH) Written by <NAME> (JH) Universiteit Gent Vakgroep Subatomaire en Stralingsfysica Proeftuinstraat 86 9000 Gent Belgium +32(0)9 264.65.35 <EMAIL> and <NAME> (VH) KVI Groningen Zernikelaan 25 9747 AA Groningen The Netherlands +31(0)50 363.36.32 <EMAIL> */ #define VERSION "2.10" #define UPDATE "Oct 27 1999" #include <math.h> #include <cfortran/cfortran.h> #include <cfortran/packlib.h> #if defined(GRAPHS) #include <g2.h> #include <g2_X11.h> #endif #include "UI.h" #include "EventTypes.h" #include "utils.h" #include "infobase.h" #include "pcos.h" #include "tdc3377.h" #include "myutils.h" #include "adc4300b.h" #include "Online_ana.h" /* VESNA VDC reconstruction routine */ extern float VESNA(int, int, int, int, int, Event_t*); extern void VESNA_set_T0(int T0_X1, int T0_U1, int T0_X2, int T0_U2); /******************************************************* * definitions for HBOOK routines and PAW shared memory *******************************************************/ #define PAWC_SIZE 500000 typedef struct { float PAW[PAWC_SIZE]; } PAWC_DEF; #define PAWC COMMON_BLOCK(PAWC,pawc) COMMON_BLOCK_DEF(PAWC_DEF,PAWC); PAWC_DEF PAWC; /* LRECL is the bufferlength used in the HROPEN function */ #define LRECL 1024 /* Now comes an extremly strange hack to get HCDIR of the Linux cernlib running the way it is supposed to be, <NAME> */ #if defined(Linux86) void myHCDIR(char* CHPATH, char* CHOPT) { char dummy[50]; strcpy(dummy, CHPATH); HCDIR (dummy,CHOPT); } # ifdef HCDIR # undef HCDIR # endif #define HCDIR myHCDIR #endif /*********************************** * Prototypes of internal routines ***********************************/ static void Redef_histo (Boolean * Running); static void Set_debug (Boolean * Running); static void TOF_gate(Boolean * Running); static void Variance_gate(Boolean * Running); static void ClusterSize(Boolean * Running); static void Theta_gate(Boolean * Running); static void cos_theta_carb_gate(Boolean * Running); static void X1_gate(Boolean * Running); static void vertz_gate(Boolean * Running); static void define_offsets(Boolean * Running); static void Change_zero(Boolean * Running); static void pol_gate (Boolean * Running); static void Save_oas (void); static void Load_oas (void); static void QDC (Boolean * Running); static void BBS_gate(Boolean * Running); static void Scat_gate_1(Boolean * Running); static void Scat_gate_2(Boolean * Running); static void compose_ntuple (Boolean * Running); int Report (uint16 * Buffer, int Size); int define_histograms(void); static void reset_histograms(void); void open_ntuple(char * nt_name); int load_analysis_setup (char * filename); static int save_analysis_setup (char * filename); int analysis_getpar(Ana_par_t *); int vdc_getpar(); int mwpc_getpar(); static int histo_getpar(Histopar_t *); static int Unpack_event(uint16 * Buffer, Event_t * Event); int Interpret_event (Event_t * Pevent); static int Interpret_scaler(uint16* Buffer); static void calc_fpds(float WX1, float WU1, float WX2, float WU2, float * X1_xb, float * X1_yb, float * Theta, float * Phi); static int calc_vfp(float X1, float Theta, float * Xf); static double calc_ana(double kinetic_energy, double sin_vivo); static void calc_fpp(float X1, float Y1, float Theta, float Phi, float D1x_raw, float D1y_raw, float D2x_raw, float D2y_raw, float D3x_raw, float D3y_raw, float D4x_raw, float D4y_raw, int polarization); static void calc_target(float Xfocal, float Yfocal, float Tfocal, float * pTtarget, float * pPtarget, float * pmomentum); static float Straight_line (Event_t * Pevent, int Wic, int Miss, int First, int Index, float *PVariance, int *PCentroid); static void second_test(int D1x, int D1y, int D2x, int D2y, int D4x, int D4y); /******************************************** * definitions for the VDC straight line fit ********************************************/ #define NOF_PASSES 3 /* number of passes, i. e. max number of datapoints kicked out of the fit */ #define REPAIR_VAR 3 /* variance beneath which the fit is considered good and no further repair takes place */ /*********************************************************** * Variables and Parameters global to the analysis software ***********************************************************/ /* parameters needed to calculate the analyzing power */ static double a0 = 5.4771; static double a1 = -4.2906; static double a2 = -25.3790; static double a3 = 121.1500; static double a4 = -108.3700; static double b0 = -10.4750; static double b1 = -40.1700; static double b2 = 525.8400; static double b3 = -899.2900; static double b4 = 1616.6000; static double c0 = 1052.3000; static double c1 = 628.5100; static double c2 = -13215.0000; static double c3 = 19083.0000; static double c4 = -5485.5000; static double proton_restmass = 0.93828; char Mem_id[6]; static Boolean Ntuple = FALSEB; static Boolean Report_Buferr = FALSEB; static Boolean File_FPP = FALSEB; static Boolean Correct_missing = FALSEB; static Boolean Correct_ringing = FALSEB; static Boolean Correct_multiple = FALSEB; static Boolean Correct_unchecked = FALSEB; static Boolean Correct_D4 = FALSEB; static Boolean QDC_in = TRUEB; static Boolean Select_pol[4] = {TRUEB,TRUEB,TRUEB,TRUEB}; static Boolean Select_type[20] = {TRUEB,TRUEB,TRUEB,TRUEB,TRUEB, TRUEB,TRUEB,TRUEB,TRUEB,TRUEB, TRUEB,TRUEB,TRUEB,TRUEB,TRUEB, TRUEB,TRUEB,TRUEB,TRUEB,TRUEB}; static Boolean Gate_TOF = FALSEB; static Boolean Gate_variance = FALSEB; static Boolean Gate_X1 = FALSEB; static Boolean Gate_Theta = FALSEB; static Boolean Correct_DSP = FALSEB; static Boolean Gate_cos_theta_carb = FALSEB; static Boolean Gate_vertz = FALSEB; static Boolean Gate_target = FALSEB; static Boolean Gate_BBS = FALSEB; static Boolean Gate_scat_1 = FALSEB; static Boolean Gate_scat_2 = FALSEB; static Boolean Ntup_Block[4] = {TRUEB,TRUEB,TRUEB,TRUEB}; static MWPar_t MWPC_Par[2][512][2]; static int VDC_Par[4]; static int MWPC_mid[8]; static Boolean Use_VESNA = FALSEB; static int VDC_T0[4]; /* virtual focal plane distance and tilt angle */ static float vfp_L = 0; static float vfp_psi = 0; static char nt_name[256]="fpp_ntuple.hbook"; static FPDS_ntuple_t FPDS_ntup; static FPP_ntuple_t FPP_ntup; static PID_ntuple_t PID_ntup; static TAR_ntuple_t TAR_ntup; static FILE * statfile; static FILE * FPP_file=NULL; static Ana_par_t Ana_par; static Boolean NewRun = TRUEB; /* static Boolean Data_valid = FALSEB; */ static uint32 Counter = 0; static int TOF_limit[2]; static float Variance_limit[2][4]; static int MaxClusterSize; static float X1_limit[2]; static float Theta_limit[2]; static float cos_theta_carb_limit[2]; static float vertz_limit[2]; static float Theta_target_limit[2]; static float Phi_target_limit[2]; /* Set gates on two different scattering angles within the acceptance of the BBS */ static float BBS_angle; static float Scat_limit_1[2]; static float Scat_limit_2[2]; static float Scat_angle; /* real scattering angle in the lab */ /* definition of all the offset variables */ static float VDC0x,VDC0y,VDC0z; static float CAz_offset; static float D2x_offset,D2y_offset,D2z_offset; static float D3x_offset,D3y_offset,D3z_offset; static float D4x_offset,D4y_offset,D4z_offset; static float Phi_offset,cr_angle_offset; /* some global variables to calulate polarization stuff */ static float estim_cos[250]; static float estim_sin[250]; static float estim_den[250]; /* all relevant information is passed from the Online_ana routine */ /* via the Pevent pointer; */ /* see Online_ana.h for the definition of Event_type */ /* updated on April 18, 1999 <NAME> */ int Interpret_event (Event_t * Pevent) { /* definition of variables */ /* ----------------------- */ static int scale_counter = 0; /* used when downscaling part of VDC-1-X */ /* static int missing_counter = 0; static int multiple_counter = 0; */ int i, j, k, m, n, PlaneID; int Polarization_info; int TOT[20], T1, T2, TOF, RF; int Sum_TOT[2], NOF_PMs[2]; int QDC[10], Sum_QDC; int Gap, Previous_wire, First_wire; int Missing_in_cluster, Wires_in_cluster; int NOF_Clusters[4], Clustersize[10][4]; int NOF_Missing[4], Missing_wires[10][4]; int NOF_VDC_Pos[4], Centroid[10][4]; float Variance[10][4], VDC_Position[10][4]; int NOF_MWPC_Pos[8], MWPC_Position[50][8], MWPC_Width[50][8]; Boolean FPDS_OK; float X1_x, X1_y, Theta, Phi, Xf; float Theta_target, Phi_target, momentum; double VDCx, VDCy, VDCz; double VDCx_2, VDCy_2, VDCz_2; double cr_angle; double D1_extra[2]; Boolean FPP_OK; int D1_x, D1_y, D2_x, D2_y, D3_x, D3_y, D4_x, D4_y; int TOT_Paddle, QDC_Paddle; int centr, width; double wirenum; Boolean gate1, gate2, gate3, gate4, gate5, gate6, gate7, gate8, gate9; /* Initialization of variables */ /* --------------------------- */ TOF = -999; RF = -999; for(i=0;i<20;i++) TOT[i] = -999; Sum_TOT[0] = Sum_TOT[1] = -999; NOF_PMs[0] = NOF_PMs[1] = 0; for(i=0;i<10;i++) QDC[i] = 0; Sum_QDC = 0; First_wire = 0; PlaneID = 0; for (i=0;i<4;i++) { NOF_Missing[i] = 0; NOF_VDC_Pos[i] = 0; NOF_Clusters[i] = 0; for (j=0;j<10;j++) { Clustersize[j][i] = 0; VDC_Position[j][i] = 0.; Variance[j][i] = 0.; Centroid[j][i] = 0.; Missing_wires[j][i] = -1; } } for(i=0;i<8;i++) { NOF_MWPC_Pos[i] = 0; for(j=0;j<50;j++) { MWPC_Position[j][i] = 0; MWPC_Width[j][i] = 0; } } FPDS_OK = FALSEB; X1_x = X1_y = Theta = Phi = -999.; Theta_target = Phi_target = momentum = -999.; FPP_OK = FALSEB; D1_x = D1_y = D2_x = D2_y = D3_x = D3_y = D4_x = D4_y = -999; if (Ntuple) { if (Ntup_Block[0]) { /* FPDS_ntup.x1_int = -999.; FPDS_ntup.u1_int = -999.; FPDS_ntup.x2_int = -999.; FPDS_ntup.u2_int = -999.; FPDS_ntup.x1_var = -999.; FPDS_ntup.u1_var = -999.; FPDS_ntup.x2_var = -999.; FPDS_ntup.u2_var = -999.; */ FPDS_ntup.x1 = -999.; FPDS_ntup.y1 = -999.; FPDS_ntup.theta = -999.; FPDS_ntup.phi = -999.; } if (Ntup_Block[1]) { FPP_ntup.d1x = -999; FPP_ntup.d1y = -999; FPP_ntup.d2x = -999; FPP_ntup.d2y = -999; FPP_ntup.d3x = -999; FPP_ntup.d3y = -999; FPP_ntup.d4x = -999; FPP_ntup.d4y = -999; FPP_ntup.theta_FPP = -999.; FPP_ntup.phi_FPP = -999.; /* FPP_ntup.theta_DSP = -999.; FPP_ntup.phi_DSP = -999.; */ FPP_ntup.x_FPP = -999.; FPP_ntup.y_FPP = -999.; /* FPP_ntup.x_DSP = -999.; FPP_ntup.y_DSP = -999.; */ } if (Ntup_Block[2]) { PID_ntup.tof = -999.; PID_ntup.beam_pol = -999.; PID_ntup.sum_tot_s1 = -999.; PID_ntup.sum_tot_s2 = -999.; } if (Ntup_Block[3]) { TAR_ntup.theta_target = -999.; TAR_ntup.phi_target = -999.; TAR_ntup.momentum = -999.; } } /* calculation of variables */ /* ------------------------ */ /* rf of cyclotron */ RF = Pevent->S_time[30][0]; /* polarization */ Polarization_info = Pevent->Beam_pol; /* scintillator variables */ /* TOF */ T1 = Pevent->S_time[20][0]; T2 = Pevent->S_time[21][0]; if ((T1!=-1)&&(T2!=-1)) TOF = T1 - T2; /* TOT */ for(i=0;i<2;i++) { for(j=0;j<10;j++) { if ((Pevent->STDCM[10*i+j][0]>1)||(Pevent->STDCM[10*i+j][1]>1)|| (Pevent->S_time[10*i+j][0]==-1)||(Pevent->S_time[10*i+j][1]==-1)) continue; TOT[10*i+j] = Pevent->S_time[10*i+j][0] - Pevent->S_time[10*i+j][1]; if (NOF_PMs[i]==0) Sum_TOT[i] = 0; Sum_TOT[i] += TOT[10*i+j]; NOF_PMs[i]++; } } /* QDC variables */ if (QDC_in) { for (i=0;i<10;i++) { QDC[i] = Pevent->QDC_channel[i]; Sum_QDC += Pevent->QDC_channel[i]; } } /* VDC variables */ if (Use_VESNA) { VESNA(0,0,0,0,2,Pevent); } else { for(i=0;i<4;i++) { if (Pevent->VDC_hits[i][0] > 0) { NOF_Clusters[i] = 1; Previous_wire = -1; Missing_in_cluster = 0; Wires_in_cluster = 0; for(k=0;k<WIRES_VDC;k++) { if (Pevent->VTDCM[k][i][0] != 1) continue; if (Previous_wire == -1) { Previous_wire = k - 1; First_wire = k; } Gap = k - Previous_wire; switch(Gap) { case 1: /* normal cluster */ Wires_in_cluster++; break; case 2: /* missing wire */ if (NOF_Missing[i]<10) Missing_wires[NOF_Missing[i]][i]=(k-1); NOF_Missing[i]++; Missing_in_cluster++; Wires_in_cluster++; break; case 3: /* three missing wires */ if (NOF_Missing[i]<10) Missing_wires[NOF_Missing[i]][i]=(k-1); NOF_Missing[i]++; Missing_in_cluster++; Wires_in_cluster++; break; default: /* new cluster */ if ((Wires_in_cluster > 2) && (NOF_VDC_Pos[i] <10) &&((Wires_in_cluster+Missing_in_cluster) <= MaxClusterSize) && (TOF != -999) ) { VDC_Position[NOF_VDC_Pos[i]][i] = Straight_line(Pevent, Wires_in_cluster, Missing_in_cluster, First_wire, i, &Variance[NOF_VDC_Pos[i]][i], &Centroid[NOF_VDC_Pos[i]][i]); /* here the variance gate comes in to play */ gate3 = TRUEB; if ((Gate_variance)&& ((Variance[NOF_VDC_Pos[i]][i] < Variance_limit[0][i])|| (Variance[NOF_VDC_Pos[i]][i] > Variance_limit[1][i]))) gate3 = FALSEB; if (gate3) NOF_VDC_Pos[i]++; } Clustersize[NOF_Clusters[i]-1][i]= Wires_in_cluster+Missing_in_cluster; Wires_in_cluster=1; Missing_in_cluster = 0; First_wire=k; NOF_Clusters[i]++; } Previous_wire = k; } /* do necessary calculations for last cluster */ if ( (Wires_in_cluster > 2) && (NOF_VDC_Pos[i] <10) && ((Wires_in_cluster+Missing_in_cluster) <= MaxClusterSize) && (TOF != -999) ) { VDC_Position[NOF_VDC_Pos[i]][i] = Straight_line(Pevent, Wires_in_cluster, Missing_in_cluster, First_wire, i, &Variance[NOF_VDC_Pos[i]][i], &Centroid[NOF_VDC_Pos[i]][i]); /* here the variance gate comes in to play */ gate3 = TRUEB; if ((Gate_variance)&& ((Variance[NOF_VDC_Pos[i]][i]<Variance_limit[0][i])|| (Variance[NOF_VDC_Pos[i]][i]>Variance_limit[1][i]))) gate3 = FALSEB; if (gate3) NOF_VDC_Pos[i]++; } Clustersize[NOF_Clusters[i]-1][i]= Wires_in_cluster+Missing_in_cluster; } } } /* MWPC variables */ for (i=0;i<8;i++) { n = 0; NOF_MWPC_Pos[i] = Pevent->MWPC_hits[i]; for(j=0;(j<50)&&(j<NOF_MWPC_Pos[i]);j++) { MWPC_Position[j-n][i] = Pevent->MWPC_position[j][i]; MWPC_Width[j-n][i] = Pevent->MWPC_width[j][i]; if (Correct_ringing) { /* take care of ringing wires */ for (k=0;k<Ana_par.MWPC_no_ring[i];k++) if ((NOF_MWPC_Pos[i]>1)&& (fabs((MWPC_Position[j-n][i]/2.+1)- Ana_par.MWPC_ringing[i][k])<1)) n++; } } NOF_MWPC_Pos[i] -=n; } /* ************************************************************* */ /* So now we have : Polarization_info : value provided by source, telling whether polization is up, down or undefined TOF : time of flight; defaults to -999 if undefined TOT : time over threshold for all photomultipliers (0-19), starting in S1, with the top one on the high momentum side, going down to the bottom one, ... up to the bottom PM of S2 on the low momentum side; default to -999 NOF_PMs : number of PM's read out for one scintillator plane (0-1) Sum_TOT : sum of all TOT values for one plane (0-1); defaults to -999 QDC : QDC-values (0-9); index corresponds to PM number in S1 Sum_QDC : sum of all QDC values NOF_Clusters : number of clusters for each VDC-plane (0-3, i.e. VDC1x, VDC1u, ...) Clustersize : size of every cluster (maximum 10 clusters per plane) NOF_Missing : number of missing wires for each VDC-plane Missing_wires : adresses of missing wires (maximum 10 per plane) NOF_VDC_Pos : number of positions in VDC which could be calculated with a straight line fit (maximum 10 per plane) VDC_Position : calculated position (in wire number units, maximum 10 per plane) Centroid : centroid wire (maximum 10 per plane) Variance : variance of the fit for every calculated position NOF_MWPC_Pos : number of hits in each MWPC plane MWPC_Position : position in MWPC plane (half wire number units, maximum 50 per plane) MWPC_Width : number of read-out wires for each hit (maximum 50 per plane) Now we can play ball !!!! */ /* ************************************************************* */ /* DSP checks ... (JH) */ /* "trick" to recover unchecked missing wires/multiples */ /* if ((Correct_unchecked)&&(Pevent->Eventtype==EVENT_REST)) { missing_counter++; if (missing_counter>=100) { missing_counter=0; Pevent->Eventtype=EVENT_UNCHECKED; } } if ((Correct_unchecked)&&(Pevent->Eventtype==EVENT_MULT)) { if (((NOF_MWPC_Pos[6]+NOF_MWPC_Pos[2]+NOF_MWPC_Pos[1]+NOF_MWPC_Pos[5])>5) ||((NOF_MWPC_Pos[7]+NOF_MWPC_Pos[3]+NOF_MWPC_Pos[0]+NOF_MWPC_Pos[4])>5)) { multiple_counter++; } if (multiple_counter>=100) { multiple_counter=0; Pevent->Eventtype=EVENT_UNCHECKED; } } */ /* end DSP checks */ /* If possible, calculate x, y, theta and phi at x-plane of VDC1 */ /* At the moment, this requires exactly one good hit in each */ /* plane of the VDC's. */ if (Use_VESNA) { /* */ /* ADDON CODE */ /* */ VDC_Position[0][0] = VESNA(1,0,0,0,9,NULL); VDC_Position[0][1] = VESNA(2,0,0,0,9,NULL); VDC_Position[0][2] = VESNA(3,0,0,0,9,NULL); VDC_Position[0][3] = VESNA(4,0,0,0,9,NULL); if ( (VDC_Position[0][0]<0) || (VDC_Position[0][1]<0) || (VDC_Position[0][2]<0) || (VDC_Position[0][3]<0) ) { FPDS_OK = FALSEB; VDC_Position[0][0] = -999; VDC_Position[0][1] = -999; VDC_Position[0][2] = -999; VDC_Position[0][3] = -999; } else { calc_fpds(VDC_Position[0][0],VDC_Position[0][1],VDC_Position[0][2], VDC_Position[0][3], &X1_x, &X1_y, &Theta, &Phi); FPDS_OK = TRUEB; } } else { /* */ /* ORIGINAL CODE */ /* */ if (NOF_VDC_Pos[0]*NOF_VDC_Pos[1]*NOF_VDC_Pos[2]*NOF_VDC_Pos[3] == 1) { calc_fpds(VDC_Position[0][0],VDC_Position[0][1],VDC_Position[0][2], VDC_Position[0][3], &X1_x, &X1_y, &Theta, &Phi); FPDS_OK = TRUEB; } } /* calc virtual focal plane position */ calc_vfp(X1_x, Theta, &Xf); /* With x, y, theta and phi, calculate the proton momentum and */ /* theta and phi at the target position. */ if (FPDS_OK) { calc_target(X1_x, X1_y, Theta, &Theta_target, &Phi_target, &momentum); /* do the extrapolation of the D1 position from the VDC position */ cr_angle = ANGLE_CENTRAL_RAY + cr_angle_offset; VDCx_2 = X1_x * cos(cr_angle); VDCy_2 = X1_y; VDCz_2 = X1_x * sin(cr_angle); VDCx = VDCx_2 + VDC0x; VDCy = -VDCy_2 + VDC0y; VDCz = -VDCz_2 + VDC0z; D1_extra[0] = VDCx + VDCz*tan(Theta); D1_extra[1] = VDCy + (VDCz-20)*tan(Phi); } /* now we check and set some gates */ gate1 = TRUEB; /* TOF */ if ((Gate_TOF)&&((TOF<TOF_limit[0])||(TOF>TOF_limit[1]))) gate1 = FALSEB; gate2 = TRUEB; /* X1 and Theta */ if ((Gate_X1)&&((X1_x<X1_limit[0])||(X1_x>X1_limit[1]))) gate2 = FALSEB; if ((Gate_Theta)&&((Theta<Theta_limit[0])||(Theta>Theta_limit[1]))) gate2 = FALSEB; /* for the variance gate (gate3) : check the VDC variables part */ gate4 = FALSEB; /* eventtype gate */ switch(Pevent->Eventtype) { case EVENT_FPP: if (Select_type[EVENT_FPP]) gate4=TRUEB; break; case EVENT_ANGLECUT: if (Select_type[EVENT_ANGLECUT]) gate4=TRUEB; break; case EVENT_UNCHECKED: if (Select_type[EVENT_UNCHECKED]) gate4=TRUEB; break; case EVENT_PULSER: if (Select_type[EVENT_PULSER]) gate4=TRUEB; break; case EVENT_MULT: if (Select_type[EVENT_MULT]) gate4=TRUEB; break; case EVENT_REST: if (Select_type[EVENT_REST]) gate4=TRUEB; break; case EVENT_MULT_REP: if (Select_type[EVENT_MULT_REP]) gate4=TRUEB; break; case EVENT_REST_REP: if (Select_type[EVENT_REST_REP]) gate4=TRUEB; break; } gate5 = FALSEB; /* polarization gate */ switch(Polarization_info) { case BPOL_DOWN: if (Select_pol[0]) gate5=TRUEB; break; case BPOL_UP: if (Select_pol[1]) gate5=TRUEB; break; case BPOL_OFF: if (Select_pol[2]) gate5=TRUEB; break; default: if (Select_pol[3]) gate5=TRUEB; break; } gate6 = TRUEB; if ((Gate_target)&&((Theta_target<Theta_target_limit[0])|| (Theta_target>Theta_target_limit[1]))) gate6 = FALSEB; if ((Gate_target)&&((Phi_target<Phi_target_limit[0])|| (Phi_target>Phi_target_limit[1]))) gate6 = FALSEB; gate7 = FALSEB; if (Gate_BBS) gate7 = TRUEB; Scat_angle = sqrt((BBS_angle*M_PI/0.18 + Theta_target)*(BBS_angle*M_PI/0.18 + Theta_target)+Phi_target*Phi_target); gate8 = FALSEB; if ( Gate_scat_1 && ((Scat_angle > (M_PI/0.18)* Scat_limit_1[0]) && (Scat_angle < (M_PI/0.18)* Scat_limit_1[1])) ) gate8 = TRUEB; gate9 = FALSEB; if ( Gate_scat_2 && ((Scat_angle > (M_PI/0.18)* Scat_limit_2[0]) && (Scat_angle < (M_PI/0.18)* Scat_limit_2[1])) ) gate9 = TRUEB; /* If possible, calculate some polarimeter variables. This */ /* requires a value for x, y, theta and phi in the VDC's and */ /* exactly one hit in each plane of D1, D2 and D4. It also uses */ /* the polarization info provided by the source. */ if ((gate1)&&(gate2)&&(gate4)&&(gate5)&&(gate6)) { if ((FPDS_OK)&&(FPP_OK)) calc_fpp(X1_x,X1_y,Theta,Phi,D1_x,D1_y,D2_x,D2_y, D3_x,D3_y,D4_x,D4_y, Polarization_info); if (File_FPP) { fprintf(FPP_file,"\n\n"); fprintf(FPP_file,"FPDS_OK %1d - FPP_OK %1d\n",FPDS_OK,FPP_OK); fprintf(FPP_file,"Eventtype : %3d\n",Pevent->Eventtype); for(i=0;i<8;i++) { switch(i) { case 0: fprintf(FPP_file,"\nD1 X-plane\t"); break; case 1: fprintf(FPP_file,"\nD1 Y-plane\t"); break; case 2: fprintf(FPP_file,"\nD2 X-plane\t"); break; case 3: fprintf(FPP_file,"\nD2 Y-plane\t"); break; case 4: fprintf(FPP_file,"\nD3 X-plane\t"); break; case 5: fprintf(FPP_file,"\nD3 Y-plane\t"); break; case 6: fprintf(FPP_file,"\nD4 X-plane\t"); break; case 7: fprintf(FPP_file,"\nD4 Y-plane\t"); break; } fprintf(FPP_file,"Hits : %3d\t",NOF_MWPC_Pos[i]); if (NOF_MWPC_Pos[i]) { fprintf(FPP_file,"("); for (j=0;j<NOF_MWPC_Pos[i];j++) fprintf(FPP_file,"\t%3d",MWPC_Position[j][i]-MWPC_mid[i]); fprintf(FPP_file,")"); } } } } /* booking histograms */ /* ------------------ */ if (!Ntuple) { /* "scaler" */ HF1(5,1,1.); /* add one for every event */ for(i=0;i<4;i++) if (Pevent->VDC_hits[i][0] > 0) HF1(5,3+i,1.); /* fill if this VDC-plane has been hit */ for(i=0;i<8;i++) if (NOF_MWPC_Pos[i]>0) HF1(5,8+i,1.); /* fill if this MWPC-plane has been hit */ HF1(6,1,1.); /* add one for every event */ for(i=0;i<4;i++) if (NOF_VDC_Pos[i] == 1) HF1(6,3+i,1.); /* fill if this VDC-plane has been hit once */ for(i=0;i<8;i++) if (NOF_MWPC_Pos[i] == 1) HF1(6,8+i,1.); /* fill if this MWPC-plane has been hit once */ if (FPDS_OK) HF1(6,17,1.); /* fill if coincidence all VDC-planes */ if (FPP_OK) HF1(6,18,1.); /* fill if coincidence all MWPC-planes */ if ((FPDS_OK)&&(FPP_OK)) HF1(6,19,1.); /* fill if coincidence ALL planes */ /* Event type histogram (ungated) */ HF1(7, Pevent->Eventtype,1.); if ((gate1)&&(gate4)&&(gate5)) /* gate on TOF && eventtype && polarization */ { /* polarization */ HF1(4,Polarization_info,1.); /* time of flight */ HF1(11,TOF,1.); HF1(12, RF,1.); HF2(101,Sum_TOT[0],Sum_TOT[1],1.); /* s1 vs s2 */ /* Event type histogram (gated) */ HF1(8, Pevent->Eventtype,1.); /* scintillators */ for(i=0;i<2;i++) { switch(i) { case 0: HCDIR("S1"," "); PlaneID = 2; /* D2_x */ break; case 1: HCDIR("S2"," "); PlaneID = 6; /* D4_x */ break; } for(j=0;j<10;j++) { /* book multiplicity */ if ((Pevent->STDCM[10*i+j][0]>1) || (Pevent->STDCM[10*i+j][1]>1)) HF1(1,j+1,1.); /* book leading edge missing */ if ((Pevent->S_time[10*i+j][0]==-1) && (Pevent->S_time[10*i+j][1]!=-1)) HF1(2,j+1,1.); /* book trailing edge missing */ if ((Pevent->S_time[10*i+j][1]==-1) && (Pevent->S_time[10*i+j][0]!=-1)) HF1(3,j+1,1.); } HF1(4,Sum_TOT[i],1.); HF1(5,NOF_PMs[i],1.); HCDIR("TOT SPECTRA"," "); for(j=0;j<10;j++) { if(TOT[10*i+j]!=-999) { HF1( 1+j, TOT[10*i+j], 1.); HF2(51+j, TOT[10*i+j], TOF, 1.); } } HCDIR("\\"," "); /* sum TOT versus x in either D2x (S1) or D4x (S2) */ for (k=0;(k<NOF_MWPC_Pos[PlaneID])&&(k<50);k++) { wirenum = MWPC_Position[k][PlaneID]/2.+1; HF2(6,wirenum,Sum_TOT[i],1.); } HCDIR("\\"," "); } /* QDC */ if (QDC_in) { HCDIR("QDC"," "); for(i=0;i<10;i++) { HF1(i+ 1,QDC[i],1.); HF2(i+101,TOT[i],QDC[i],1.); } for(i=0;i<5;i++) { QDC_Paddle = QDC[2*i] + QDC[2*i+1]; TOT_Paddle = 0; for(j=0;j<2;j++) if (TOT[2*i+j]!=-999) TOT_Paddle+=TOT[2*i+j]; if (TOT_Paddle > 0) HF2(i+121,TOT_Paddle,QDC_Paddle,1.); } for (k=0;(k<NOF_MWPC_Pos[2])&&(k<50);k++) { wirenum = MWPC_Position[k][2]/2.+1; HF2(21,wirenum,Sum_QDC,1.); } HF2(22,TOF,Sum_QDC,1.); HCDIR("\\"," "); } /* VDC's */ for(i=0;i<4;i++) { switch(i) { case 0: HCDIR("VDC1/X-PLANE"," "); break; case 1: HCDIR("VDC1/U-PLANE"," "); break; case 2: HCDIR("VDC2/X-PLANE"," "); break; case 3: HCDIR("VDC2/U-PLANE"," "); break; } /* we always add 1 before booking a wire number because the read out start counting from wire 0, we like to start counting from 1 !! */ HF1(9,NOF_Clusters[i],1.); for(k=0;(k<NOF_Clusters[i])&&(k<10);k++) { HF1(8, Clustersize[k][i], 1.); } for(k=0;(k<NOF_Missing[i])&&(k<10);k++) { HF1(5, Missing_wires[k][i] + 1, 1.); } HF1(400, NOF_VDC_Pos[i], 1.); for(k=0;(k<NOF_VDC_Pos[i])&&(k<10);k++) { HF1(100, Centroid[k][i]+1, 1.); HF1(200, VDC_Position[k][i]+1, 1.); HF1(300, Variance[k][i], 1.); } for(k=0;k<WIRES_VDC;k++) { if (Pevent->VTDCM[k][i][0] == 0) continue; /* wire not read out */ HF1(1,k+1,1.); /* book wire regardless of multiplicity */ switch(Pevent->VTDCM[k][i][0]) { case 1: /* one signal on this wire; good one ! */ HF1(2,k+1,1.); /* book TDCM = 1 */ break; case 2: /* two signals on this wire */ HF1(3,k+1,1.); /* book TDCM = 2 and go to next wire */ continue; default: /* more than two signals on this wire */ HF1(4,k+1,1.); /* book TDCM > 2 and go to next wire */ continue; } } HCDIR("DRIFTTIMES"," "); for(k=0;k<WIRES_VDC;k++) { if (Pevent->VTDCM[k][i][0] == 1) { if ((k+1)%10 == 5) { HF1(k+1,Pevent->VDC_time[k][i][0],1.); continue; } /* just checking a U1 wire problem */ if ((i==1)&((k+1)>=130)&&((k+1)<=160)) HF1(k+1,Pevent->VDC_time[k][i][0],1.); } } HCDIR("\\"," "); HCDIR("\\\\"," "); } /* MWPC's */ for(i=0;i<4;i++) { switch(i) { case 0: HCDIR("MWPC1"," "); break; case 1: HCDIR("MWPC2"," "); break; case 2: HCDIR("MWPC3"," "); break; case 3: HCDIR("MWPC4"," "); break; } for(j=0;j<2;j++) { PlaneID = 2*i + j; HF1(j+5,NOF_MWPC_Pos[PlaneID],1.); for(k=0;(k<NOF_MWPC_Pos[PlaneID])&&(k<50);k++) { centr = MWPC_Position[k][PlaneID]/2; width = MWPC_Width[k][PlaneID]; for (m=(centr-(width-1)/2);m<=(centr+width/2);m++) { HF1(j+11,m+1,1.); } wirenum = MWPC_Position[k][PlaneID]/2. + 1; HF1(j+1,wirenum,1.); HF1(j+3,width,1.); } } HCDIR("\\"," "); } if ((gate2)&&(gate6)) /* gate on X1, theta */ { /* FPDS variables */ HF1(21,Theta,1.); HF1(22,Phi,1.); HF1(23,X1_y,1.); HF1(24,X1_x,1.); HF2(25,X1_x,X1_y,1.); HF2(26,X1_x,Theta,1.); HF2(27,X1_y,Phi,1.); HF2(102,X1_x,RF,1.); HF2(103,X1_x,Sum_TOT[1],1.); /* target variables */ if (FPDS_OK) { HCDIR("TARGET"," "); HF1(1,Theta_target,1.); HF1(2,Phi_target,1.); HF1(3,momentum,1.); /* gates on scattering angles */ if ((gate7) && (gate8)) { HF1(4,momentum,1.); } if ((gate7) && (gate9)) { HF1(5,momentum,1.); } HF2(11,Theta_target,Phi_target,1.); HF2(12,momentum,Theta_target,1.); HF2(13,momentum,Phi_target,1.); switch (Polarization_info) { case BPOL_UP: HF1(21,momentum,1.); break; case BPOL_DOWN: HF1(22,momentum,1.); break; case BPOL_OFF: HF1(23,momentum,1.); break; } if ((Theta_target < 40.) && (Theta_target > -40.) &&(Phi_target < 50.) && (Phi_target >-50.)) HF1(31,momentum,1.); HCDIR("\\"," "); } } } } /* booking ntuple */ /* -------------- */ if (Ntuple) { /* downscale region in X1_x if requested */ if (X1_x < Ana_par.x_scale_below) { scale_counter++; if (scale_counter == Ana_par.downscale_factor) scale_counter = 0; else return -2; } if (Ntup_Block[2]) { /* polarization */ PID_ntup.beam_pol = Polarization_info; /* time of flight */ PID_ntup.tof = TOF; PID_ntup.eventtype = Pevent->Eventtype; PID_ntup.sum_tot_s1 = Sum_TOT[0]; PID_ntup.sum_tot_s2 = Sum_TOT[1]; } if (Ntup_Block[0]) { /* FPDS_ntup.x1_int = VDC_Position[0][0]; FPDS_ntup.u1_int = VDC_Position[0][1]; FPDS_ntup.x2_int = VDC_Position[0][2]; FPDS_ntup.u2_int = VDC_Position[0][3]; FPDS_ntup.x1_var = Variance[0][0]; FPDS_ntup.u1_var = Variance[0][1]; FPDS_ntup.x2_var = Variance[0][2]; FPDS_ntup.u2_var = Variance[0][3]; */ FPDS_ntup.x1 = X1_x; FPDS_ntup.y1 = X1_y; FPDS_ntup.theta = Theta; FPDS_ntup.phi = Phi; } if (Ntup_Block[1]) { FPP_ntup.d1x = D1_x; FPP_ntup.d1y = D1_y; FPP_ntup.d2x = D2_x; FPP_ntup.d2y = D2_y; FPP_ntup.d3x = D3_x; FPP_ntup.d3y = D3_y; FPP_ntup.d4x = D4_x; FPP_ntup.d4y = D4_y; } if (Ntup_Block[3]) { TAR_ntup.theta_target = Theta_target; TAR_ntup.phi_target = Phi_target; TAR_ntup.momentum = momentum; } /* fill ntuple */ HFNT(1001); } return 0; } /***********************************************/ /* Calculate X, Y, Theta and Phi from VDC data */ /***********************************************/ static void calc_fpds(float WX1, float WU1, float WX2, float WU2, float * X1_xb, float * X1_yb, float * Theta, float * Phi) { float X1_xa, X2_xa, U1_xa, U2_xa, U1_xb, U2_xb; float U1_ub, U2_ub, U1_yb, U2_yb, Dist_12; float cr_angle; cr_angle = ANGLE_CENTRAL_RAY + cr_angle_offset; X1_xa = FWX1_X_POS - WX1*WIRE_DISTANCE; X2_xa = FWX2_X_POS - WX2*WIRE_DISTANCE; U1_xa = X1_xa + (X1_xa - X2_xa)*(FWU1_Y_POS-FWX1_Y_POS)/(FWX1_Y_POS-FWX2_Y_POS); U2_xa = X1_xa + (X1_xa - X2_xa)*(FWU2_Y_POS-FWX1_Y_POS)/(FWX1_Y_POS-FWX2_Y_POS); U1_xb = FWU1_X_POS - U1_xa; U2_xb = FWU2_X_POS - U2_xa; U1_ub = WU1*WIRE_DISTANCE; U2_ub = WU2*WIRE_DISTANCE; U1_yb = (U1_xb * COS_ANGLE_U - U1_ub)/SIN_ANGLE_U; U2_yb = (U2_xb * COS_ANGLE_U - U2_ub)/SIN_ANGLE_U; *X1_xb = WX1*WIRE_DISTANCE; *X1_yb = U2_yb - (FWU2_Y_POS-FWX1_Y_POS)*(U2_yb-U1_yb)/(FWU2_Y_POS-FWU1_Y_POS); Dist_12 = sqrt((X2_xa-X1_xa)*(X2_xa-X1_xa) + (FWX2_Y_POS-FWX1_Y_POS)*(FWX2_Y_POS-FWX1_Y_POS)); *Theta = atan((X2_xa - X1_xa)/(FWX2_Y_POS-FWX1_Y_POS)) - cr_angle; *Phi = atan((U2_yb - U1_yb)/(cos(*Theta)*Dist_12)) - Phi_offset; return; } /********************************************************/ /* Calculate virtual focal plane coordinates */ /********************************************************/ static int calc_vfp(float X1, float Theta, float * Xf) { float tanpsi, a, b; if (X1 == -999. || Theta == -999.) return -1; tanpsi = tan(vfp_psi * M_PI/180.0); a = tanpsi * (X1_MIDDLE - vfp_L * COS_ALPHA) - vfp_L * SIN_ALPHA; b = tan(ALPHA - Theta) * X1; *Xf = (a + b) / (b/X1 + tanpsi); return 0; } /********************************************************/ /* Calculate analyzing power for given energy and angle */ /********************************************************/ static double calc_ana(double Ecenter, double sin_theta_carb) { double a,b,c; double pi,pi2,pi3,pi4,ksi,ksi2,ksi4; double analyzing_power; double pcenter; pcenter = sqrt(Ecenter*(2*proton_restmass+Ecenter)); pi = pcenter - 0.700; pi2 = pi*pi; pi3 = pi*pi2; pi4 = pi3*pi; a = a0 + a1*pi + a2*pi2 + a3*pi3 + a4*pi4; b = b0 + b1*pi + b2*pi2 + b3*pi3 + b4*pi4; c = c0 + c1*pi + c2*pi2 + c3*pi3 + c4*pi4; ksi = pcenter * sin_theta_carb; ksi2 = ksi*ksi; ksi4 = ksi2*ksi2; analyzing_power = a*ksi/(1 + b*ksi2 + c*ksi4); return analyzing_power; } /*****************************************************/ /* calculate target variables from fitted parameters */ /*****************************************************/ static void calc_target(float Xd, float Yd, float Td, float *Tt, float *Pt, float *moment) { /* float c1, c2, c3, c4; */ /* Momentum fit: p = f(Xd, Yd, Td) [MeV/c] (third oder fit) -------------------------------------------------------- C +6.824467e+02 C_Xd -1.232002e-01 C_Yd +5.181561e-04 C_Td +9.821224e+00 C_Xd*Yd -1.825561e-06 C_Xd*Td -2.270458e-02 C_Yd*Td -2.184000e-02 C_Xd**2 -4.111105e-05 C_Yd**2 +9.079623e-05 C_Td**2 -7.388398e+01 C_Xd*Yd*Td +4.307513e-05 C_Xd**2*Yd +3.059155e-10 C_Xd**2*Td +1.233548e-05 C_Yd**2*Xd -1.515269e-07 C_Yd**2*Td -2.456049e-04 C_Td**2*Xd +2.097084e-01 C_Td**2*Yd +9.297566e-02 C_Xd**3 +8.530886e-09 C_Yd**3 +8.000667e-09 C_Td**3 +3.865610e+02 */ *moment = +6.824467e+02 -1.232002e-01*Xd +5.181561e-04*Yd +9.821224e+00*Td -1.825561e-06*Xd*Yd -2.270458e-02*Xd*Td -2.184000e-02*Yd*Td -4.111105e-05*Xd*Xd +9.079623e-05*Yd*Yd -7.388398e+01*Td*Td +4.307513e-05*Xd*Yd*Td +3.059155e-10*Xd*Xd *Yd +1.233548e-05*Xd*Xd *Td -1.515269e-07*Yd*Yd *Xd -2.456049e-04*Yd*Yd *Td +2.097084e-01*Td*Td *Xd +9.297566e-02*Td*Td *Yd +8.530886e-09*Xd*Xd*Xd +8.000667e-09*Yd*Yd*Yd +3.865610e+02*Td*Td*Td; /* Theta_target fit: Tt = f(Xd, Yd, Td) [MeV/c] (third oder fit) ------------------------------------------------------------- C -2.945145e+01 C_Xd +6.717314e-02 C_Yd +2.754338e-02 C_Td +4.492754e+02 C_Xd*Yd -6.646432e-05 C_Xd*Td -1.081587e-01 C_Yd*Td +2.433274e-02 C_Xd**2 -1.040832e-05 C_Yd**2 +5.014310e-04 C_Td**2 +1.202321e+02 C_Xd*Yd*Td -8.003344e-05 C_Xd**2*Yd +4.015931e-08 C_Xd**2*Td +1.698658e-04 C_Yd**2*Xd -8.159989e-07 C_Yd**2*Td -1.222418e-03 C_Td**2*Xd +2.120180e-01 C_Td**2*Yd -1.164198e-01 C_Xd**3 +3.047526e-08 C_Yd**3 +2.017390e-08 C_Td**3 +6.310898e+01 */ *Tt = -2.945145e+01 +6.717314e-02*Xd +2.754338e-02*Yd +4.492754e+02*Td -6.646432e-05*Xd*Yd -1.081587e-01*Xd*Td +2.433274e-02*Yd*Td -1.040832e-05*Xd*Xd +5.014310e-04*Yd*Yd +1.202321e+02*Td*Td -8.003344e-05*Xd*Yd*Td +4.015931e-08*Xd*Xd *Yd +1.698658e-04*Xd*Xd *Td -8.159989e-07*Yd*Yd *Xd -1.222418e-03*Yd*Yd *Td +2.120180e-01*Td*Td *Xd -1.164198e-01*Td*Td *Yd +3.047526e-08*Xd*Xd*Xd +2.017390e-08*Yd*Yd*Yd +6.310898e+01*Td*Td*Td; /* Phi_target fit: p = f(Xd, Yd) ----------------------------- because producing a third order fit with MINUIT did not work out for Phi_target, I produced a (rather crude, but working) fit using the approach described by <NAME> in his internal report on 'Ray tracing at the Big Bite Spectrometer'. c1 = -3.03115; c2 = -0.18714; c3 = -0.0117104; c4 = +0.00252921; *Pt = ( Yd - c1 - c3*Xd ) / ( c2 + c4*Xd ); */ /* Using a similar approach with MINUIT again i got to the following fit. This is as good as it gets at the moment. C +1.952730e+00 C_Xd +2.818747e-02 C_Yd +1.075646e+00 C_Xd*Yd +1.375872e-04 C_Xd**2 -4.159629e-05 C_Yd**2 -2.529846e-03 C_Xd**2*Yd -5.918242e-07 C_Yd**2*Xd +5.661931e-06 C_Xd**3 +2.045242e-08 C_Yd**3 +1.059039e-04 D -2.288684e-01 D_Xd +2.423389e-03 D_Yd -3.217867e-04 D_Yd**2 +1.622719e-04 */ *Pt = ( +1.952730e+00 + +2.818747e-02*Xd + +1.075646e+00*Yd + +1.375872e-04*Xd*Yd + -4.159629e-05*Xd*Xd + -2.529846e-03*Yd*Yd + -5.918242e-07*Xd*Xd *Yd + +5.661931e-06*Yd*Yd *Xd + +2.045242e-08*Xd*Xd*Xd + +1.059039e-04*Yd*Yd*Yd ) / ( -2.288684e-01 + +2.423389e-03*Xd + -3.217867e-04*Yd + +1.622719e-04*Yd*Yd ); return; } /*****************************************************/ /* Calculate polarimeter info from VDC and MWPC data */ /*****************************************************/ static void calc_fpp(float x1, float y1, float Theta, float Phi, float D1x_raw, float D1y_raw, float D2x_raw, float D2y_raw, float D3x_raw, float D3y_raw, float D4x_raw, float D4y_raw, int polarization) { Boolean gate; float Corry,Corrz; float VDCx_2,VDCy_2,VDCz_2; float VDCx,VDCy,VDCz; float D1x,D1y,D1z; float D2x,D2y,D2z; float D3x,D3y,D3z; float D4x,D4y,D4z; float D1x_dsp,D1y_dsp,D1z_dsp; float D2x_dsp,D2y_dsp,D2z_dsp; float D3x_dsp,D3y_dsp,D3z_dsp; float D4x_dsp,D4y_dsp,D4z_dsp; float CAx,CAy,CAz; float vinmod,vinx,viny,vinz; float voutmod,voutx,vouty,voutz; float cos_theta_carb,sin_theta_carb,tan_theta_carb; float cos_phi_carb,sin_phi_carb; float vinmod_dsp,vinx_dsp,viny_dsp,vinz_dsp; float voutmod_dsp,voutx_dsp,vouty_dsp,voutz_dsp; float sin_theta_carb_dsp,cos_theta_carb_dsp; float cos_phi_carb_dsp,sin_phi_carb_dsp; float D12x,D12y,D12z; float dx,dy,dz,dmod; float vertx,verty,vertz; float nx,ny,nz,nmod; float nx_dsp,ny_dsp,nz_dsp,nmod_dsp; float Phi_carb,Phi_carb_dsp,Phi_carb_deg,Phi_carb_deg_dsp; float Theta_carb,Theta_carb_dsp,Theta_carb_deg,Theta_carb_deg_dsp; float conex_sphere,coney_sphere; float conex_sphere_dsp,coney_sphere_dsp; float conex_plane,coney_plane; float cr_angle; float s,t; float Theta2,Phi2; float D1x_diff,D1y_diff; float D2x_diff,D2y_diff; float D3x_diff,D3y_diff; float D4x_diff,D4y_diff; float D2x_int,D2y_int; float D3x_int,D3y_int; double Ay,Ay_2,Ay_cos,Ay_sin; int channel; cr_angle = ANGLE_CENTRAL_RAY + cr_angle_offset; VDCx_2 = x1 * cos(cr_angle); VDCy_2 = y1; VDCz_2 = x1 * sin(cr_angle); VDCx = VDCx_2 + VDC0x; VDCy = -VDCy_2 + VDC0y; VDCz = -VDCz_2 + VDC0z; D1x = D1x_raw * 1.25; D2x = D2x_raw * 1.25 + D2x_offset; D3x = D3x_raw * 1.25 + D3x_offset; D4x = D4x_raw * 1.25 + D4x_offset; Corrz = 20; Corry = (float)(D4y_raw-D2y_raw)/D2_D4 * Corrz; D1y = D1y_raw * 1.25 + tan(Phi) * Corrz; D2y = D2y_raw * 1.25 - Corry + D2y_offset; D3y = D3y_raw * 1.25 - Corry + D3y_offset; D4y = D4y_raw * 1.25 - Corry + D4y_offset; D1z = 0.; D2z = 850. + D2z_offset; D3z = 1120. + D3z_offset; D4z = 1390. + D4z_offset; if (Correct_DSP) { CAz = 700. + CAz_offset; D1x_dsp = D1x; D1y_dsp = D1y; D1z_dsp = D1z; D2x_dsp = D2x; D2y_dsp = D2y; D2z_dsp = D2z; D4x_dsp = D4x; D4y_dsp = D4y; D4z_dsp = D4z; } else { CAz = 700.; D1x_dsp = D1x_raw * 1.25; D1y_dsp = D1y_raw * 1.25; D1z_dsp = 0.; D2x_dsp = D2x_raw * 1.25; D2y_dsp = D2y_raw * 1.25; D2z_dsp = 850.; D3x_dsp = D3x_raw * 1.25; D3y_dsp = D3y_raw * 1.25; D3z_dsp = 1120.; D4x_dsp = D4x_raw * 1.25; D4y_dsp = D4y_raw * 1.25; D4z_dsp = 1390.; } CAx = D4x_dsp - (D4x_dsp-D2x_dsp)*(D4z_dsp-CAz)/(D4z_dsp-D2z_dsp); CAy = D4y_dsp - (D4y_dsp-D2y_dsp)*(D4z_dsp-CAz)/(D4z_dsp-D2z_dsp); vinx = D1x - VDCx; viny = D1y - VDCy; vinz = D1z - VDCz; vinmod = sqrt(vinx*vinx + viny*viny + vinz*vinz); if (vinmod!=0) { vinx = vinx/vinmod; viny = viny/vinmod; vinz = vinz/vinmod; } else vinx = viny = vinz = 0; vinx_dsp = CAx - D1x_dsp; viny_dsp = CAy - D1y_dsp; vinz_dsp = CAz - D1z_dsp; vinmod_dsp = sqrt(vinx_dsp*vinx_dsp + viny_dsp*viny_dsp + vinz_dsp*vinz_dsp); if (vinmod_dsp!=0) { vinx_dsp = vinx_dsp/vinmod_dsp; viny_dsp = viny_dsp/vinmod_dsp; vinz_dsp = vinz_dsp/vinmod_dsp; } else vinx_dsp = viny_dsp = vinz_dsp = 0; Theta2 = -atan(vinx/vinz); Phi2 = -atan(viny/vinz); voutx = D4x - D2x; vouty = D4y - D2y; voutz = D4z - D2z; voutmod = sqrt(voutx*voutx + vouty*vouty + voutz*voutz); if (voutmod !=0) { voutx = voutx/voutmod; vouty = vouty/voutmod; voutz = voutz/voutmod; } else voutx = vouty = voutz =0; voutx_dsp = D4x_dsp - D2x_dsp; vouty_dsp = D4y_dsp - D2y_dsp; voutz_dsp = D4z_dsp - D2z_dsp; voutmod_dsp = sqrt(voutx_dsp*voutx_dsp + vouty_dsp*vouty_dsp + voutz_dsp*voutz_dsp); if (voutmod_dsp!=0) { voutx_dsp = voutx_dsp/voutmod_dsp; vouty_dsp = vouty_dsp/voutmod_dsp; voutz_dsp = voutz_dsp/voutmod_dsp; } else voutx_dsp = vouty_dsp = voutz_dsp = 0; nx = viny*voutz - vouty*vinz; ny = vinz*voutx - voutz*vinx; nz = vinx*vouty - voutx*viny; nmod = sqrt(nx*nx + ny*ny + nz*nz); if (nmod != 0) { nx = nx/nmod; ny = ny/nmod; nz = nz/nmod; } else nx = ny = nz = 0; nx_dsp = viny_dsp*voutz_dsp - vouty_dsp*vinz_dsp; ny_dsp = vinz_dsp*voutx_dsp - voutz_dsp*vinx_dsp; nz_dsp = vinx_dsp*vouty_dsp - voutx_dsp*viny_dsp; nmod_dsp = sqrt(nx_dsp*nx_dsp + ny_dsp*ny_dsp + nz_dsp*nz_dsp); if (nmod_dsp != 0) { nx_dsp = nx_dsp/nmod_dsp; ny_dsp = ny_dsp/nmod_dsp; nz_dsp = nz_dsp/nmod_dsp; } else nx_dsp = ny_dsp = nz_dsp = 0; if (nx > 0) Phi_carb = acos(ny); else Phi_carb = -acos(ny); Phi_carb_deg = Phi_carb/M_PI*180; if (nx_dsp > 0) Phi_carb_dsp = acos(ny_dsp); else Phi_carb_dsp = -acos(ny_dsp); Phi_carb_deg_dsp = Phi_carb_dsp/M_PI*180; cos_theta_carb = vinx*voutx + viny*vouty + vinz*voutz; Theta_carb = acos(cos_theta_carb); Theta_carb_deg = Theta_carb/M_PI*180; sin_theta_carb = sin(Theta_carb); tan_theta_carb = tan(Theta_carb); cos_theta_carb = vinx*voutx + viny*vouty + vinz*voutz; cos_theta_carb_dsp = vinx_dsp*voutx_dsp + viny_dsp*vouty_dsp + vinz_dsp*voutz_dsp; Theta_carb_dsp = acos(cos_theta_carb_dsp); Theta_carb_deg_dsp = Theta_carb_dsp/M_PI*180; sin_theta_carb_dsp = sin(Theta_carb_dsp); cos_phi_carb = cos(Phi_carb); sin_phi_carb = sin(Phi_carb); cos_phi_carb_dsp = cos(Phi_carb_dsp); sin_phi_carb_dsp = sin(Phi_carb_dsp); conex_sphere = sin_theta_carb*cos_phi_carb; coney_sphere = sin_theta_carb*sin_phi_carb; conex_plane = tan_theta_carb*cos_phi_carb; coney_plane = tan_theta_carb*sin_phi_carb; conex_sphere_dsp = sin_theta_carb_dsp*cos_phi_carb_dsp; coney_sphere_dsp = sin_theta_carb_dsp*sin_phi_carb_dsp; D12x = D2x - D1x; D12y = D2y - D1y; D12z = D2z - D1z; if (cos_theta_carb != 1) { s = ((D12x*vinx + D12y*viny + D12z*vinz) - (D12x*voutx + D12y*vouty + D12z*voutz)*cos_theta_carb) / (1 - cos_theta_carb*cos_theta_carb); t = ((D12x*voutx + D12y*vouty + D12z*voutz) - (D12x*vinx + D12y*viny + D12z*vinz)*cos_theta_carb) / (1 - cos_theta_carb*cos_theta_carb); dx = D12x - s*vinx - t*voutx; dy = D12y - s*viny - t*vouty; dz = D12z - s*vinz - t*voutz; dmod = sqrt(dx*dx + dy*dy + dz*dz); vertx = D1x + s*vinx + 0.5*dx; verty = D1y + s*viny + 0.5*dy; vertz = D1z + s*vinz + 0.5*dz; } else { dx = dy = dz = dmod = 0; vertx = verty = vertz = -999.; } Ay = calc_ana(.170,sin_theta_carb); Ay_2 = Ay*Ay; Ay_cos = Ay*cos_phi_carb; Ay_sin = Ay*sin_phi_carb; channel = 5*Theta_carb_deg; /* check gates */ gate = TRUEB; if ((Gate_cos_theta_carb)&&((cos_theta_carb_dsp<cos_theta_carb_limit[0]) ||(cos_theta_carb_dsp>cos_theta_carb_limit[1]))) gate = FALSEB; if ((Gate_vertz)&&((vertz<vertz_limit[0])||(vertz>vertz_limit[1]))) gate = FALSEB; if (gate) { if (!Ntuple) { HCDIR("POLARIMETER"," "); HF1(1,dmod,1.); HF1(2,vertz,1.); HF1(3,Theta_carb_deg_dsp,1.); HF1(4,Theta_carb_deg,1.); HF1(5,cos_theta_carb,1.); HF1(6,Phi_carb_deg,1.); HF1(7,cos_phi_carb,1.); HF2(8,Theta_carb_deg,Phi_carb_deg,1.); HF2(9,conex_sphere,coney_sphere,1.); HF2(10,conex_plane,coney_plane,1.); HF1(11,Theta2,1.); HF1(12,Phi2,1.); HF1(13,Theta-Theta2,1.); HF1(14,Phi-Phi2,1.); HF1(15,dx,1.); HF1(16,dy,1.); HF1(17,dz,1.); HF2(18,dx,dy,1.); /* HF2(204,coney_sphere_dsp,conex_sphere_dsp,1.); HF2(205,Theta_carb_deg_dsp,Phi_carb_deg_dsp,1.); */ D1x_diff = D1x - (VDCx - (D1z-VDCz)*tan(Theta)); D1y_diff = D1y - (VDCy - (D1z-VDCz)*tan(Phi)); D2x_diff = D2x - (VDCx - (D2z-VDCz)*tan(Theta)); D2y_diff = D2y - (VDCy - (D2z-VDCz)*tan(Phi)); D3x_diff = D3x - (VDCx - (D3z-VDCz)*tan(Theta)); D3y_diff = D3y - (VDCy - (D3z-VDCz)*tan(Phi)); D4x_diff = D4x - (VDCx - (D4z-VDCz)*tan(Theta)); D4y_diff = D4y - (VDCy - (D4z-VDCz)*tan(Phi)); HF1(101,D1x_diff,1.); HF1(102,D1y_diff,1.); HF1(103,D2x_diff,1.); HF1(104,D2y_diff,1.); HF1(105,D3x_diff,1.); HF1(106,D3y_diff,1.); HF1(107,D4x_diff,1.); HF1(108,D4y_diff,1.); D2x_int = D2x - (D1x + (D4x - D1x)*(D2z-D1z)/(D4z - D1z)); D2y_int = D2y - (D1y + (D4y - D1y)*(D2z-D1z)/(D4z - D1z)); D3x_int = D3x - (D1x + (D4x - D1x)*(D3z-D1z)/(D4z - D1z)); D3y_int = D3y - (D1y + (D4y - D1y)*(D3z-D1z)/(D4z - D1z)); HF1(111,D2x_int,1.); HF1(112,D2y_int,1.); HF1(113,D3x_int,1.); HF1(114,D3y_int,1.); HF1(201, D1x, 1.); HF1(202, D1y, 1.); HF1(203, D2x, 1.); HF1(204, D2y, 1.); HF1(205, D3x, 1.); HF1(206, D3y, 1.); HF1(207, D4x, 1.); HF1(208, D4y, 1.); HF1(301,Theta_carb_deg,Ay_cos); HF1(302,Theta_carb_deg,Ay_sin); HF1(303,Theta_carb_deg,Ay_2); if (cos_phi_carb>0) HF1(304,Theta_carb_deg,1.); else HF1(304,Theta_carb_deg,-1.); if ((channel>=0)&&(channel<250)) { estim_cos[channel]+=Ay_cos; estim_sin[channel]+=Ay_sin; estim_den[channel]+=Ay_2; } HCDIR("\\"," "); } else { if (Ntup_Block[1]) { FPP_ntup.theta_FPP = Theta_carb_deg; FPP_ntup.phi_FPP = Phi_carb_deg; /* FPP_ntup.theta_DSP = Theta_carb_deg_dsp; FPP_ntup.phi_DSP = Phi_carb_deg_dsp; */ FPP_ntup.x_FPP = conex_sphere; FPP_ntup.y_FPP = coney_sphere; /* FPP_ntup.x_DSP = conex_sphere_dsp; FPP_ntup.y_DSP = coney_sphere_dsp; */ } } } } /************************************************/ /* Calculate intercept with a straight line fit */ /************************************************/ static float Straight_line (Event_t * Pevent, int Wic, int Miss, int First, int Index, float * PVariance, int *PCentroid) { float Sum_x, Sum_y, Sum_xy, Sum_xx; int i, n, Centroid; int Maximum; float a, b; float Difference; float Intercept; float Variance = 0; double data[100][2]; int nofpoints; float maxdiff; int worst_point = -1; int pass; #if defined (GRAPHS) static int g2d = -1; static int red; static int black; static int green; double pldata[100][2]; static int good_events = 0; static int bad_events = 0; int left, right; double dummy; char text[5]; #endif Sum_x = 0.; Sum_y = 0.; Sum_xy = 0.; Sum_xx = 0.; Centroid = 0; Maximum = 0; a = 0.; b = 0.; for(n=First;(n-First)<(Wic+Miss);n++) { if (Pevent->VDC_time[n][Index][0]>Maximum) { Maximum = Pevent->VDC_time[n][Index][0]; Centroid = n; } } nofpoints = 0; for(n = First; (n-First) < (Wic+Miss); n++) { if (Pevent->VDC_time[n][Index][0] < 0) continue; if (n < Centroid) data[nofpoints][1] = VDC_T0[Index] - Pevent->VDC_time[n][Index][0]; if (n > Centroid) data[nofpoints][1] = Pevent->VDC_time[n][Index][0] - VDC_T0[Index]; if (n == Centroid) { if ( Pevent->VDC_time[n-1][Index][0] > Pevent->VDC_time[n+1][Index][0] ) { data[nofpoints][1] = Pevent->VDC_time[n][Index][0] - VDC_T0[Index]; } else { data[nofpoints][1] = VDC_T0[Index] - Pevent->VDC_time[n][Index][0]; } } data[nofpoints][0] = n; nofpoints++; } pass = 0; while ( (Variance > REPAIR_VAR && nofpoints > 3 && pass <= NOF_PASSES) || (pass == 0) ) { if ( pass > 0 ) { i = 0; for(n = 0; n < nofpoints; n++) { if (n == worst_point) continue; data[i][0] = data[n][0]; data[i][1] = data[n][1]; i++; } nofpoints--; } pass++; Sum_x = 0.; Sum_y = 0.; Sum_xy = 0.; Sum_xx = 0.; for (n = 0; n < nofpoints; n++) { Sum_x += data[n][0]; Sum_y += data[n][1]; Sum_xy += data[n][0] * data[n][1]; Sum_xx += data[n][0] * data[n][0]; } a = (nofpoints * Sum_xy - Sum_x * Sum_y) / (nofpoints * Sum_xx - Sum_x * Sum_x); b = (Sum_xx * Sum_y - Sum_x * Sum_xy) / (nofpoints * Sum_xx - Sum_x * Sum_x); Variance = 0; maxdiff = 0; worst_point = -1; for(n = 0; n < nofpoints; n++) { Difference = abs( a * data[n][0] + b - data[n][1] ); Variance += Difference*Difference; if (Difference > maxdiff) { maxdiff = Difference; worst_point = n; } } Variance = sqrt(Variance)/(nofpoints-2); } if (a == 0.) Intercept = 999.; else Intercept = -b/a; *PVariance = Variance; *PCentroid = Centroid; #if defined (GRAPHS) if ( Variance <= Variance_limit[1][Index] ) { good_events++; } else { bad_events++; left = ( (int) (First/5) ) * 5; right = ( (int) ((First+Wic+Miss)/5) ) * 5 + 5; for (n = 0; n < nofpoints; n++) { pldata[n][0] = (data[n][0] - left) * 500/(right-left); pldata[n][1] = data[n][1] + 400; } if (g2d < 0) { g2d = g2_open_X11(500, 800); black = g2_ink(g2d,0,0,0); red = g2_ink(g2d,1,0,0); green = g2_ink(g2d,0,1,0); } g2_clear(g2d); g2_line(g2d, 0, 400, 500, 400); dummy = 1; g2_set_dash(g2d,1,&dummy); for (n = 1; n < (right-left); n++) g2_line(g2d, n*500/(right-left), 0, n*500/(right-left), 800); g2_set_dash(g2d,0,0); sprintf(text,"%d",left); g2_string(g2d, 0, 400, text); sprintf(text,"%d",right); g2_string(g2d, 480, 400, text); g2_poly_line(g2d, nofpoints, pldata); g2_pen(g2d,red); for (n = 0; n < nofpoints; n++) { sprintf(text,"%d",n+1); g2_string(g2d, pldata[n][0], pldata[n][1], text ); } g2_pen(g2d,green); g2_line(g2d, pldata[0][0], a * data[0][0] + b + 400, pldata[nofpoints-1][0], a * data[nofpoints-1][0] + b + 400); g2_pen(g2d,black); sprintf(text,"Variance = %6.3f",Variance); g2_string(g2d, 350, 770, text); if (good_events > 0) { sprintf(text,"bad events = %d", bad_events); g2_string(g2d, 350, 750, text); sprintf(text,"good events = %d",good_events); g2_string(g2d, 350, 730, text); sprintf(text,"bad / total events = %5.2f%%", (float) bad_events/ (float) (bad_events+good_events) * 100.); g2_string(g2d, 350, 710, text); } getchar(); } #endif return Intercept; } /***************************/ /* report on buffer errors */ /***************************/ int Report (uint16 * Buffer, int Size) { int i; if (Size==0) UI_Msg("Empty buffer !\n"); for (i=0;i<Size;i++) { /* if (i%6 == 0) printf("\n"); */ UI_Msg("%3d : %4x ",i,*(Buffer++)); } return 0; } /*************************/ /* definition of n-tuple */ /*************************/ void open_ntuple(char * nt_name) { int isize = LRECL, istat=0; char fppblock[1024]; HROPEN(40,"FPP_NTUPLE",nt_name,"N",isize,istat); HCDIR("//FPP_NTUPLE"," "); HBNT(1001,"FPP","D"); if (Ntup_Block[0]) { sprintf(fppblock,"%s%s%s",FPDSBLOCK1,FPDSBLOCK2,FPDSBLOCK3); HBNAME(1001,"FPDS",FPDSSTART,fppblock); } if (Ntup_Block[1]) { sprintf(fppblock,"%s%s%s",FPPBLOCK1,FPPBLOCK2,FPPBLOCK3); HBNAME(1001,"FPP",FPPSTART,fppblock); } if (Ntup_Block[2]) { sprintf(fppblock,"%s",PIDBLOCK1); HBNAME(1001,"PID",PIDSTART,fppblock); } if (Ntup_Block[3]) { sprintf(fppblock,"%s",TARBLOCK1); HBNAME(1001,"TAR",TARSTART,fppblock); } UI_Msg("Ntuple created: name %s, record length LRECL=%d\n", nt_name, isize); } /*******************************************************/ /* routine that is called at the begin of a run */ /*******************************************************/ int Online_ana_start() { unsigned int ONE = 1; UI_CtxRead CtxRead = NULL; Boolean Clear=TRUEB; Boolean Dummy=FALSEB; const unsigned int FileNameLenMax = 256; char statfilename[256]; /* evaluation of scaler stuff needs to know when a new run is started */ NewRun = TRUEB; /* Data_valid = FALSEB; */ /* for the 1998 data the events before the first scaler event have to be thrown away */ Counter = 0; if (Ntuple) { if (CurrImpl == UI_ClientImpl) { /* Ask for a name for the ntuple */ if (UI_StrSetupRead (&CtxRead, "Ntuple filename", nt_name, NULL, &ONE, &FileNameLenMax, NULL) < 0) { FatalError ("UI_SetupRead failed"); } switch (UI_Read("Analysis startup", &CtxRead, NULL, NULL)) { case 0: break; /* Normal */ case 1: return -1; /* Cancelled */ default: FatalError ("UI_Read failed"); } } strcpy(SysStat->out_file,nt_name); open_ntuple(nt_name); /* create ntuple file */ strcpy (statfilename, nt_name); strcat (statfilename, ".stat"); if ((statfile = fopen(statfilename,"w")) == NULL) FatalError("Could not open file to save statistics."); UI_Msg("Scaling region below %d mm in VDC-1-X down by a factor of %d", Ana_par.x_scale_below, Ana_par.downscale_factor); UI_Msg("Processed events are:\n - events which survived the event buffer unpacking routine\n - were not thrown away because of downscaling part of the VDC-1 X spectrum\n - are not scaler or other type of events"); fprintf(statfile, "Scaling region below %d mm in VDC-1-X down by a factor of %d\n", Ana_par.x_scale_below, Ana_par.downscale_factor); fprintf(statfile,"\nProcessed events are:\n"); fprintf(statfile," - events which survived the event buffer "); fprintf(statfile,"unpacking routine\n"); fprintf(statfile," - were not thrown away because of downscaling "); fprintf(statfile,"part of the VDC-1 X spectrum\n"); fprintf(statfile," - are not scaler or other type of events\n\n\n"); } else { /* Ask if spectra should be cleared */ if (CurrImpl == UI_ClientImpl) { if (UI_BooSetupRead (&CtxRead, "Clear spectra before run", &Clear, NULL) < 0) FatalError ("UI_SetupRead failed"); switch (UI_Read("Analysis startup", &CtxRead, NULL, NULL)) { case 0: break; /* Normal */ case 1: return -1; /* Cancelled */ default: FatalError ("UI_Read failed"); } if (Clear) Clear_spectra (&Dummy); } } return 0; } /*****************************************************/ /* routine that is called at the end of a run */ /*****************************************************/ int Online_ana_stop() { int icycle; if (Use_VESNA) VESNA(0,0,0,0,3,NULL); if (File_FPP) if (FPP_file != NULL) fclose(FPP_file); if (Ntuple) { /* close ntuple on disk */ HCDIR("//FPP_NTUPLE"," "); HROUT(1001,icycle," "); HREND("FPP_NTUPLE"); /* close statistics file */ UI_Msg("Total processed events: %lu",Counter); if (Ntuple) fprintf(statfile,"Total processed events: %u\n",Counter); fclose(statfile); } return 0; } /************************************************************************/ /* read parameters for analysis and ntuple production from analysis.par */ /************************************************************************/ int analysis_getpar(Ana_par_t * Ana_par) { FILE * ifp; int i, j; char vdc_planes[4][8] = {"VDC-1-X", "VDC-1-U", "VDC-2-X", "VDC-2-U"}; char mwpc_planes[8][9] = {"MWPC-1-X", "MWPC-1-Y", "MWPC-2-X", "MWPC-2-Y", "MWPC-3-X", "MWPC-3-Y", "MWPC-4-X", "MWPC-4-Y"}; char fname[256]; UI_Msg("Getting analysis/ntuple parameters."); strcpy(fname,BASEDIR); strcat(fname,"/stadaq/Ana_parameters/"); strcat(fname,Ana_Par_File); /* open parameter file */ if ((ifp = fopen(fname,"r")) == NULL) { UI_Msg("Could not open file %s. Using default values.",fname); strcpy (Ana_par->mwpc_parfile, "mwpc.par"); /* file containing the pcos logical addresses */ strcpy (Ana_par->oas_parfile, "default"); /* file containing the online analysis settings */ for (i=0; i<4; i++) Ana_par->VDC_no_ring[i]=0; /* number of ringing wires per plane */ for (i=0; i<8; i++) Ana_par->MWPC_no_ring[i]=0; /* number of ringing wires per plane */ Ana_par->no_scalers = 44; /* number of scaler channels read out */ Ana_par->current_scaler = 23; /* scaler channel counting the current integrator */ Ana_par->pri_event_scaler = 13; /* channel counting primary events */ Ana_par->acq_event_scaler = 15; /* channel counting acquired events */ Ana_par->nt_max_events = 500000; /* max no. of events before a new ntuple is started */ Ana_par->x_scale_below = 0; /* downscale region of VDC1-X */ Ana_par->downscale_factor = 1; return 0; } if (get_keyword(ifp,"MWPC_parfile") < 0) return -1; if (get_string (ifp, Ana_par->mwpc_parfile) < 0) return -1; if (get_keyword(ifp,"oas_parfile") < 0) return -1; if (get_string (ifp, Ana_par->oas_parfile) < 0) return -1; for (i=0; i<4; i++) { if (get_keyword(ifp,vdc_planes[i]) < 0) return -1; if (get_int(ifp, &Ana_par->VDC_no_ring[i],0,10) < 0) return -1; for (j=0; j<Ana_par->VDC_no_ring[i]; j++) if (get_int(ifp, &Ana_par->VDC_ringing[i][j],0,WIRES_VDC) < 0) return -1; } for (i=0; i<8; i++) { if (get_keyword(ifp,mwpc_planes[i]) < 0) return -1; if (get_int(ifp, &Ana_par->MWPC_no_ring[i],0,10) < 0) return -1; for (j=0; j<Ana_par->MWPC_no_ring[i]; j++) if (get_int(ifp, &Ana_par->MWPC_ringing[i][j],0,WIRES_D4X) < 0) return -1; } if (get_keyword(ifp,"No_of_scalers") < 0) return -1; if (get_int(ifp, &Ana_par->no_scalers,0,64) < 0) return -1; if (get_keyword(ifp,"Current_readout") < 0) return -1; if (get_int(ifp, &Ana_par->current_scaler,0,64) < 0) return -1; if (get_keyword(ifp,"Prim_events_readout") < 0) return -1; if (get_int(ifp, &Ana_par->pri_event_scaler,0,64) < 0) return -1; if (get_keyword(ifp,"Acq_event_readout") < 0) return -1; if (get_int(ifp, &Ana_par->acq_event_scaler,0,64) < 0) return -1; if (get_keyword(ifp,"Ntuple_max_events") < 0) return -1; if (get_long(ifp, &Ana_par->nt_max_events,0,1000000) < 0) return -1; if (get_keyword(ifp,"Scale_region_below") < 0) return -1; if (get_int(ifp, &Ana_par->x_scale_below,0,1500) < 0) return -1; if (get_keyword(ifp,"Downscale_factor") < 0) return -1; if (get_int(ifp, &Ana_par->downscale_factor,0,32000) < 0) return -1; fclose(ifp); return 0; } /****************************************************************/ /* read parameters for histogram definition from histograms.par */ /****************************************************************/ static int histo_getpar(Histopar_t * PHiPar) { FILE * ifp; char fname[256]; UI_Msg("Getting histogram parameters."); strcpy(fname,BASEDIR); strcat(fname,"/stadaq/Ana_parameters/histograms.par"); /* open parameter file */ if ((ifp = fopen(fname,"r")) == NULL) { UI_Msg("Could not find histogram parameter file. Using default values."); strcpy(Mem_id,"FPP"); PHiPar->MEM_Size = 1000000; /* shared memory size */ PHiPar->Drift_Min = 0; /* mimimum drifttime */ PHiPar->Drift_Max = 512; /* maximum drifttime */ PHiPar->Drift_Bins = 128; /* number of bins */ PHiPar->VTOT_Min = 0; /* minimum VTOT */ PHiPar->VTOT_Max = 128; /* maximum VTOT */ PHiPar->VTOT_Bins = 128; /* number of bins */ PHiPar->STOT_Min = 0; /* minimum STOT */ PHiPar->STOT_Max = 128; /* maximum STOT */ PHiPar->STOT_Bins = 128; /* number of bins */ PHiPar->TOF_Min = 0; /* minimum TOF */ PHiPar->TOF_Max = 128; /* maximum TOF */ PHiPar->TOF_Bins = 128; /* number of bins */ PHiPar->Int_Bins = 2400; /* bins in intercept */ PHiPar->X_Min = 0; /* minimum x */ PHiPar->X_Max = 1024; /* maximum x */ PHiPar->X_Bins = 1024; /* number of bins */ PHiPar->Y_Min = -192; /* minimum y */ PHiPar->Y_Max = 192; /* maximum y */ PHiPar->Y_Bins = 384; /* number of bins */ return 0; } if (get_keyword(ifp,"MEM_ID") < 0) return -1; if (get_string (ifp, Mem_id) < 0) return -1; if (get_keyword(ifp,"MEM_Size") < 0) return -1; if (get_int(ifp,&PHiPar->MEM_Size,10000,1000000) < 0) return -1; if (get_keyword(ifp,"Drift_Min") < 0) return -1; if (get_int(ifp,&PHiPar->Drift_Min,0,2048) < 0) return -1; if (get_keyword(ifp,"Drift_Max") < 0) return -1; if (get_int(ifp,&PHiPar->Drift_Max,0,2048) < 0) return -1; if (get_keyword(ifp,"Drift_Bins") < 0) return -1; if (get_int(ifp,&PHiPar->Drift_Bins,0,1024) < 0) return -1; if (get_keyword(ifp,"VTOT_Min") < 0) return -1; if (get_int(ifp,&PHiPar->VTOT_Min,-512,512) < 0) return -1; if (get_keyword(ifp,"VTOT_Max") < 0) return -1; if (get_int(ifp,&PHiPar->VTOT_Max,-512,512) < 0) return -1; if (get_keyword(ifp,"VTOT_Bins") < 0) return -1; if (get_int(ifp,&PHiPar->VTOT_Bins,0,1024) < 0) return -1; if (get_keyword(ifp,"STOT_Min") < 0) return -1; if (get_int(ifp,&PHiPar->STOT_Min,-512,512) < 0) return -1; if (get_keyword(ifp,"STOT_Max") < 0) return -1; if (get_int(ifp,&PHiPar->STOT_Max,-512,512) < 0) return -1; if (get_keyword(ifp,"STOT_Bins") < 0) return -1; if (get_int(ifp,&PHiPar->STOT_Bins,0,1024) < 0) return -1; if (get_keyword(ifp,"TOF_Min") < 0) return -1; if (get_int(ifp,&PHiPar->TOF_Min,-2048,2048) < 0) return -1; if (get_keyword(ifp,"TOF_Max") < 0) return -1; if (get_int(ifp,&PHiPar->TOF_Max,-2048,2048) < 0) return -1; if (get_keyword(ifp,"TOF_Bins") < 0) return -1; if (get_int(ifp,&PHiPar->TOF_Bins,0,1028) < 0) return -1; if (get_keyword(ifp,"Int_Bins") < 0) return -1; if (get_int(ifp,&PHiPar->Int_Bins,0,100000) < 0) return -1; if (get_keyword(ifp,"X_Min") < 0) return -1; if (get_int(ifp,&PHiPar->X_Min,-128,1024) < 0) return -1; if (get_keyword(ifp,"X_Max") < 0) return -1; if (get_int(ifp,&PHiPar->X_Max,-128,1024) < 0) return -1; if (get_keyword(ifp,"X_Bins") < 0) return -1; if (get_int(ifp,&PHiPar->X_Bins,0,2048) < 0) return -1; if (get_keyword(ifp,"Y_Min") < 0) return -1; if (get_int(ifp,&PHiPar->Y_Min,-256,256) < 0) return -1; if (get_keyword(ifp,"Y_Max") < 0) return -1; if (get_int(ifp,&PHiPar->Y_Max,-256,256) < 0) return -1; if (get_keyword(ifp,"Y_Bins") < 0) return -1; if (get_int(ifp,&PHiPar->Y_Bins,0,1024) < 0) return -1; fclose(ifp); return 0; } /***************************************************/ /* read parameters for mwpc decoding from mwpc.par */ /***************************************************/ int mwpc_getpar() { FILE * ifp; int i,j,k; int nr_of_mod = 0; int address; int slot; char fname[256]; UI_Msg("Getting MWPC parameters."); /* initializing MWPC_Par structure */ for (i=0;i<2;i++) { for (j=0;j<512;j++) { for (k=0;k<2;k++) { MWPC_Par[i][j][k].mwpc = -1; MWPC_Par[i][j][k].plane = -1; MWPC_Par[i][j][k].card = -1; } } } strcpy(fname,BASEDIR); strcat(fname,"/stadaq/Ana_parameters/mwpc.par"); strcat(fname,Ana_par.mwpc_parfile); /* open parameter file */ if ((ifp = fopen(fname,"r")) == NULL) { UI_MsgOk("Could not find MWPC parameter file."); return -1; } for(j=0;j<2;j++) { switch(j) { case 0: if (get_keyword(ifp,"Branch_1") < 0) { fclose(ifp); return -1; } break; case 1: if (get_keyword(ifp,"Branch_2") < 0) { fclose(ifp); return -1; } break; } if (get_keyword(ifp,"Nr_of_modules")<0) { fclose(ifp); return -1; } if (get_int(ifp,&nr_of_mod,0,46) < 0) { fclose(ifp); return -1; } if (get_keyword(ifp,"#card")<0) { fclose(ifp); return -1; } for(i=0;i<nr_of_mod;i++) { for(k=0;k<2;k++) { if (get_int(ifp,&address,0,511) < 0) { fclose(ifp); return -1; } if (get_int(ifp,&slot,-1,1) < 0) { fclose(ifp); return -1; } if (slot==-1) continue; if (MWPC_Par[j][address][slot].mwpc != -1) { fclose(ifp); return -1; } if (get_int(ifp,&MWPC_Par[j][address][slot].mwpc,0,3) < 0) { fclose(ifp); return -1; } if (get_int(ifp,&MWPC_Par[j][address][slot].plane,0,1) < 0) { fclose(ifp); return -1; } if (get_int(ifp,&MWPC_Par[j][address][slot].card,0,32) < 0) { fclose(ifp); return -1; } } } } fclose(ifp); return 0; } /***************************************************/ /* read parameters for vdc decoding from vdc.par */ /***************************************************/ int vdc_getpar() { FILE * ifp; char fname[256]; int i; UI_Msg("Getting VDC parameters."); for (i=0;i<4;i++) VDC_Par[i]=0; strcpy(fname,BASEDIR); strcat(fname,"/stadaq/Ana_parameters/vdc.par"); /* open parameter file */ if ((ifp = fopen(fname,"r")) == NULL) { UI_MsgOk("Could not find VDC parameter file."); return -1; } if (get_keyword(ifp,"x1") < 0) { fclose(ifp); return -1; } if (get_int(ifp,&VDC_Par[0],0,15) < 0) { fclose(ifp); return -1; } if (get_keyword(ifp,"u1") < 0) { fclose(ifp); return -1; } if (get_int(ifp,&VDC_Par[1],0,15) < 0) { fclose(ifp); return -1; } if (get_keyword(ifp,"x2") < 0) { fclose(ifp); return -1; } if (get_int(ifp,&VDC_Par[2],0,15) < 0) { fclose(ifp); return -1; } if (get_keyword(ifp,"u2") < 0) { fclose(ifp); return -1; } if (get_int(ifp,&VDC_Par[3],0,15) < 0) { fclose(ifp); return -1; } fclose(ifp); return 0; } /***************************************/ /* input and output of analysis setup */ /***************************************/ int load_analysis_setup (char * filename) { int status = 0; int bool; int i,j; FILE * ifp; char fname[255]; strcpy(fname,BASEDIR); strcat(fname,"/stadaq/Ana_parameters/"); strcat(fname,filename); strcat(fname,".oas"); if ((ifp=fopen(fname,"r"))==NULL) { UI_MsgOk("Could not find the file named %s.oas.",filename); return -1; } if (get_keyword(ifp,"Correct_D4") < 0) status--; if (get_int(ifp,&bool,0,1) < 0) status--; if (bool==0) Correct_D4 = FALSEB; else Correct_D4 = TRUEB; if (get_keyword(ifp,"Correct_missing") < 0) status--; if (get_int(ifp,&bool,0,1) < 0) status--; if (bool==0) Correct_missing = FALSEB; else Correct_missing = TRUEB; if (get_keyword(ifp,"Correct_ringing") < 0) status--; if (get_int(ifp,&bool,0,1) < 0) status--; if (bool==0) Correct_ringing = FALSEB; else Correct_ringing = TRUEB; if (get_keyword(ifp,"Correct_multiple") < 0) status--; if (get_int(ifp,&bool,0,1) < 0) status--; if (bool==0) Correct_multiple = FALSEB; else Correct_multiple = TRUEB; if (get_keyword(ifp,"QDC_in") < 0) status--; if (get_int(ifp,&bool,0,1) < 0) status--; if (bool==0) QDC_in = FALSEB; else QDC_in = TRUEB; if (get_keyword(ifp,"Select_pol") < 0) status--; for (i=0;i<4;i++) { if (get_int(ifp,&bool,0,1) < 0) status--; if (bool==0) Select_pol[i] = FALSEB; else Select_pol[i] = TRUEB; } if (get_keyword(ifp,"Select_type") < 0) status--; for (i=0;i<20;i++) { if (get_int(ifp,&bool,0,1) < 0) status--; if (bool==0) Select_type[i] = FALSEB; else Select_type[i] = TRUEB; } if (get_keyword(ifp,"Gate_TOF") < 0) status--; if (get_int(ifp,&bool,0,1) < 0) status--; if (bool==0) Gate_TOF = FALSEB; else Gate_TOF = TRUEB; if (get_keyword(ifp,"Gate_variance") < 0) status--; if (get_int(ifp,&bool,0,1) < 0) status--; if (bool==0) Gate_variance = FALSEB; else Gate_variance = TRUEB; if (get_keyword(ifp,"Gate_X1") < 0) status--; if (get_int(ifp,&bool,0,1) < 0) status--; if (bool==0) Gate_X1 = FALSEB; else Gate_X1 = TRUEB; if (get_keyword(ifp,"Gate_Theta") < 0) status--; if (get_int(ifp,&bool,0,1) < 0) status--; if (bool==0) Gate_Theta = FALSEB; else Gate_Theta = TRUEB; if (get_keyword(ifp,"Correct_DSP") < 0) status--; if (get_int(ifp,&bool,0,1) < 0) status--; if (bool==0) Correct_DSP = FALSEB; else Correct_DSP = TRUEB; if (get_keyword(ifp,"Gate_cos_theta_carb") < 0) status--; if (get_int(ifp,&bool,0,1) < 0) status--; if (bool==0) Gate_cos_theta_carb = FALSEB; else Gate_cos_theta_carb = TRUEB; if (get_keyword(ifp,"Gate_vertz") < 0) status--; if (get_int(ifp,&bool,0,1) < 0) status--; if (bool==0) Gate_vertz = FALSEB; else Gate_vertz = TRUEB; if (get_keyword(ifp,"VESNA_handles_VDCs") < 0) status--; if (get_int(ifp,&bool,0,1) < 0) status--; if (bool==0) Use_VESNA = FALSEB; else Use_VESNA = TRUEB; if (get_keyword(ifp,"VDC_T0") < 0) status--; for(i=0;i<4;i++) if (get_int(ifp,&VDC_T0[i],0,1024) < 0) status--; if (get_keyword(ifp,"TOF_limit") < 0) status--; for(i=0;i<2;i++) if (get_int(ifp,&TOF_limit[i],-256,512) < 0) status--; if (get_keyword(ifp,"Variance_limit") < 0) status--; for(j=0;j<4;j++) for(i=0;i<2;i++) if (get_float(ifp,&Variance_limit[i][j],0.,100.) < 0) status--; if (get_keyword(ifp,"MaxClusterSize") < 0) status--; if (get_int(ifp,&MaxClusterSize,0,100) < 0) status--; if (get_keyword(ifp,"X1_limit") < 0) status--; for(i=0;i<2;i++) if (get_float(ifp,&X1_limit[i],0.,1024.) < 0) status--; if (get_keyword(ifp,"Theta_limit") < 0) status--; for(i=0;i<2;i++) if (get_float(ifp,&Theta_limit[i],-2.,2.) < 0) status--; if (get_keyword(ifp,"cos_theta_carb_limit") < 0) status--; for(i=0;i<2;i++) if (get_float(ifp,&cos_theta_carb_limit[i],-1.,1.) < 0) status--; if (get_keyword(ifp,"vertz_limit") < 0) status--; for(i=0;i<2;i++) if (get_float(ifp,&vertz_limit[i],-1000.,2000.) < 0) status--; if (get_keyword(ifp,"VDC0x") < 0) status--; if (get_float(ifp,&VDC0x,-400.,-200.) < 0) status--; if (get_keyword(ifp,"VDC0y") < 0) status--; if (get_float(ifp,&VDC0y,-100.,100.) < 0) status--; if (get_keyword(ifp,"VDC0z") < 0) status--; if (get_float(ifp,&VDC0z,-600.,-400.) < 0) status--; if (get_keyword(ifp,"CAz_offset") < 0) status--; if (get_float(ifp,&CAz_offset,-100.,100.) < 0) status--; if (get_keyword(ifp,"D2x_offset") < 0) status--; if (get_float(ifp,&D2x_offset,-100.,100.) < 0) status--; if (get_keyword(ifp,"D2y_offset") < 0) status--; if (get_float(ifp,&D2y_offset,-100.,100.) < 0) status--; if (get_keyword(ifp,"D2z_offset") < 0) status--; if (get_float(ifp,&D2z_offset,-100.,100.) < 0) status--; if (get_keyword(ifp,"D3x_offset") < 0) status--; if (get_float(ifp,&D3x_offset,-100.,100.) < 0) status--; if (get_keyword(ifp,"D3y_offset") < 0) status--; if (get_float(ifp,&D3y_offset,-100.,100.) < 0) status--; if (get_keyword(ifp,"D3z_offset") < 0) status--; if (get_float(ifp,&D3z_offset,-100.,100.) < 0) status--; if (get_keyword(ifp,"D4x_offset") < 0) status--; if (get_float(ifp,&D4x_offset,-100.,100.) < 0) status--; if (get_keyword(ifp,"D4y_offset") < 0) status--; if (get_float(ifp,&D4y_offset,-100.,100.) < 0) status--; if (get_keyword(ifp,"D4z_offset") < 0) status--; if (get_float(ifp,&D4z_offset,-100.,100.) < 0) status--; if (get_keyword(ifp,"Phi_offset") < 0) status--; if (get_float(ifp,&Phi_offset,-1.,1.) < 0) status--; if (get_keyword(ifp,"cr_angle_offset") < 0) status--; if (get_float(ifp,&cr_angle_offset,-1.,1.) < 0) status--; if (get_keyword(ifp,"Ntup_Block") < 0) status--; for (i=0;i<4;i++) { if (get_int(ifp,&bool,0,1) < 0) status--; if (bool==0) Ntup_Block[i] = FALSEB; else Ntup_Block[i] = TRUEB; } if (get_keyword(ifp,"VFP_distance") < 0) status--; if (get_float(ifp,&vfp_L,-1000.,1000.) < 0) status--; if (get_keyword(ifp,"VFP_angle") < 0) status--; if (get_float(ifp,&vfp_psi,-180.,180.) < 0) status--; if (get_keyword(ifp,"Gate_BBS") < 0) status--; if (get_int(ifp,&bool,0,1) < 0) status--; if (bool==0) Gate_BBS = FALSEB; else Gate_BBS = TRUEB; if (get_keyword(ifp,"BBS_angle") < 0) status--; if (get_float(ifp,&BBS_angle,-10.,60.) < 0) status--; if (get_keyword(ifp,"Gate_scat_1") < 0) status--; if (get_int(ifp,&bool,0,1) < 0) status--; if (bool==0) Gate_scat_1 = FALSEB; else Gate_scat_1 = TRUEB; if (get_keyword(ifp,"Gate_scat_2") < 0) status--; if (get_int(ifp,&bool,0,1) < 0) status--; if (bool==0) Gate_scat_2 = FALSEB; else Gate_scat_2 = TRUEB; if (get_keyword(ifp,"Scat_limit_1") < 0) status--; for(i=0;i<2;i++) if (get_float(ifp,&Scat_limit_1[i],-100.,100.) < 0) status--; if (get_keyword(ifp,"Scat_limit_2") < 0) status--; for(i=0;i<2;i++) if (get_float(ifp,&Scat_limit_2[i],-100.,100.) < 0) status--; fclose(ifp); return status; } static int save_analysis_setup (char * filename) { int i,j; FILE * ifp; char fullname[350]; strcpy(fullname,BASEDIR); strcat(fullname,"/stadaq/Ana_parameters/"); strcat(fullname,filename); strcat(fullname,".oas"); if ((ifp=fopen(fullname,"w"))==NULL) { UI_MsgOk("Could not open the file named %s.oas.",filename); return -1; } if (fprintf(ifp,"/* Online analysis version %s */\n",VERSION) < 0) return -1; if (fprintf(ifp,"/* Last update on %s */\n\n",UPDATE) < 0) return -1; if (fprintf(ifp,"%-20s","Correct_D4") < 0) return -1; if (Correct_D4 == FALSEB) { if (fprintf(ifp,"\t0\n")<0) return -1; } else { if (fprintf(ifp,"\t1\n")<0) return -1; } if (fprintf(ifp,"%-20s","Correct_missing") < 0) return -1; if (Correct_missing == FALSEB) { if (fprintf(ifp,"\t0\n")<0) return -1; } else { if (fprintf(ifp,"\t1\n")<0) return -1; } if (fprintf(ifp,"%-20s","Correct_ringing") < 0) return -1; if (Correct_ringing == FALSEB) { if (fprintf(ifp,"\t0\n")<0) return -1; } else { if (fprintf(ifp,"\t1\n")<0) return -1; } if (fprintf(ifp,"%-20s","Correct_multiple") < 0) return -1; if (Correct_multiple == FALSEB) { if (fprintf(ifp,"\t0\n")<0) return -1; } else { if (fprintf(ifp,"\t1\n")<0) return -1; } if (fprintf(ifp,"%-20s","QDC_in") < 0) return -1; if (QDC_in == FALSEB) { if (fprintf(ifp,"\t0\n")<0) return -1; } else { if (fprintf(ifp,"\t1\n")<0) return -1; } if (fprintf(ifp,"%-20s","Select_pol") < 0) return -1; for(i=0;i<4;i++) { if (Select_pol[i] == FALSEB) { if (fprintf(ifp,"\t0")<0) return -1; } else { if (fprintf(ifp,"\t1")<0) return -1; } } if (fprintf(ifp,"\n") < 0) return -1; if (fprintf(ifp,"%-20s","Select_type") < 0) return -1; for(i=0;i<20;i++) { if (Select_type[i] == FALSEB) { if (fprintf(ifp,"\t0")<0) return -1; } else { if (fprintf(ifp,"\t1")<0) return -1; } } if (fprintf(ifp,"\n") < 0) return -1; if (fprintf(ifp,"%-20s","Gate_TOF") < 0) return -1; if (Gate_TOF == FALSEB) { if (fprintf(ifp,"\t0\n")<0) return -1; } else { if (fprintf(ifp,"\t1\n")<0) return -1; } if (fprintf(ifp,"%-20s","Gate_variance") < 0) return -1; if (Gate_variance == FALSEB) { if (fprintf(ifp,"\t0\n")<0) return -1; } else { if (fprintf(ifp,"\t1\n")<0) return -1; } if (fprintf(ifp,"%-20s","Gate_X1") < 0) return -1; if (Gate_X1 == FALSEB) { if (fprintf(ifp,"\t0\n")<0) return -1; } else { if (fprintf(ifp,"\t1\n")<0) return -1; } if (fprintf(ifp,"%-20s","Gate_Theta") < 0) return -1; if (Gate_Theta == FALSEB) { if (fprintf(ifp,"\t0\n")<0) return -1; } else { if (fprintf(ifp,"\t1\n")<0) return -1; } if (fprintf(ifp,"%-20s","Correct_DSP") < 0) return -1; if (Correct_DSP == FALSEB) { if (fprintf(ifp,"\t0\n")<0) return -1; } else { if (fprintf(ifp,"\t1\n")<0) return -1; } if (fprintf(ifp,"%-20s","Gate_cos_theta_carb") < 0) return -1; if (Gate_cos_theta_carb == FALSEB) { if (fprintf(ifp,"\t0\n")<0) return -1; } else { if (fprintf(ifp,"\t1\n")<0) return -1; } if (fprintf(ifp,"%-20s","Gate_vertz") < 0) return -1; if (Gate_vertz == FALSEB) { if (fprintf(ifp,"\t0\n")<0) return -1; } else { if (fprintf(ifp,"\t1\n")<0) return -1; } if (fprintf(ifp,"%-20s","VESNA_handles_VDCs") < 0) return -1; if (Use_VESNA == FALSEB) { if (fprintf(ifp,"\t0\n")<0) return -1; } else { if (fprintf(ifp,"\t1\n")<0) return -1; } if (fprintf(ifp,"%-20s","VDC_T0") < 0) return -1; for(i=0;i<4;i++) if (fprintf(ifp,"\t%d",VDC_T0[i]) < 0) return -1; if (fprintf(ifp,"\n") < 0) return -1; if (fprintf(ifp,"%-20s","TOF_limit") < 0) return -1; for(i=0;i<2;i++) if (fprintf(ifp,"\t%d",TOF_limit[i]) < 0) return -1; if (fprintf(ifp,"\n") < 0) return -1; if (fprintf(ifp,"%-20s","Variance_limit") < 0) return -1; if (fprintf(ifp,"\n") < 0) return -1; for(j=0;j<4;j++) { for(i=0;i<2;i++) if (fprintf(ifp,"\t%f",Variance_limit[i][j]) < 0) return -1; if (fprintf(ifp,"\n") < 0) return -1; } if (fprintf(ifp,"%-20s","MaxClusterSize") < 0) return -1; if (fprintf(ifp,"\t%d\n",MaxClusterSize) < 0) return -1; if (fprintf(ifp,"%-20s","X1_limit") < 0) return -1; for(i=0;i<2;i++) if (fprintf(ifp,"\t%f",X1_limit[i]) < 0) return -1; if (fprintf(ifp,"\n") < 0) return -1; if (fprintf(ifp,"%-20s","Theta_limit") < 0) return -1; for(i=0;i<2;i++) if (fprintf(ifp,"\t%f",Theta_limit[i]) < 0) return -1; if (fprintf(ifp,"\n") < 0) return -1; if (fprintf(ifp,"%-20s","cos_theta_carb_limit") < 0) return -1; for(i=0;i<2;i++) if (fprintf(ifp,"\t%f",cos_theta_carb_limit[i]) < 0) return -1; if (fprintf(ifp,"\n") < 0) return -1; if (fprintf(ifp,"%-20s","vertz_limit") < 0) return -1; for(i=0;i<2;i++) if (fprintf(ifp,"\t%f",vertz_limit[i]) < 0) return -1; if (fprintf(ifp,"\n") < 0) return -1; if (fprintf(ifp,"%-20s","VDC0x") < 0) return -1; if (fprintf(ifp,"\t%f",VDC0x) < 0) return -1; if (fprintf(ifp,"\n") < 0) return -1; if (fprintf(ifp,"%-20s","VDC0y") < 0) return -1; if (fprintf(ifp,"\t%f",VDC0y) < 0) return -1; if (fprintf(ifp,"\n") < 0) return -1; if (fprintf(ifp,"%-20s","VDC0z") < 0) return -1; if (fprintf(ifp,"\t%f",VDC0z) < 0) return -1; if (fprintf(ifp,"\n") < 0) return -1; if (fprintf(ifp,"%-20s","CAz_offset") < 0) return -1; if (fprintf(ifp,"\t%f",CAz_offset) < 0) return -1; if (fprintf(ifp,"\n") < 0) return -1; if (fprintf(ifp,"%-20s","D2x_offset") < 0) return -1; if (fprintf(ifp,"\t%f",D2x_offset) < 0) return -1; if (fprintf(ifp,"\n") < 0) return -1; if (fprintf(ifp,"%-20s","D2y_offset") < 0) return -1; if (fprintf(ifp,"\t%f",D2y_offset) < 0) return -1; if (fprintf(ifp,"\n") < 0) return -1; if (fprintf(ifp,"%-20s","D2z_offset") < 0) return -1; if (fprintf(ifp,"\t%f",D2z_offset) < 0) return -1; if (fprintf(ifp,"\n") < 0) return -1; if (fprintf(ifp,"%-20s","D3x_offset") < 0) return -1; if (fprintf(ifp,"\t%f",D3x_offset) < 0) return -1; if (fprintf(ifp,"\n") < 0) return -1; if (fprintf(ifp,"%-20s","D3y_offset") < 0) return -1; if (fprintf(ifp,"\t%f",D3y_offset) < 0) return -1; if (fprintf(ifp,"\n") < 0) return -1; if (fprintf(ifp,"%-20s","D3z_offset") < 0) return -1; if (fprintf(ifp,"\t%f",D3z_offset) < 0) return -1; if (fprintf(ifp,"\n") < 0) return -1; if (fprintf(ifp,"%-20s","D4x_offset") < 0) return -1; if (fprintf(ifp,"\t%f",D4x_offset) < 0) return -1; if (fprintf(ifp,"\n") < 0) return -1; if (fprintf(ifp,"%-20s","D4y_offset") < 0) return -1; if (fprintf(ifp,"\t%f",D4y_offset) < 0) return -1; if (fprintf(ifp,"\n") < 0) return -1; if (fprintf(ifp,"%-20s","D4z_offset") < 0) return -1; if (fprintf(ifp,"\t%f",D4z_offset) < 0) return -1; if (fprintf(ifp,"\n") < 0) return -1; if (fprintf(ifp,"%-20s","Phi_offset") < 0) return -1; if (fprintf(ifp,"\t%f",Phi_offset) < 0) return -1; if (fprintf(ifp,"\n") < 0) return -1; if (fprintf(ifp,"%-20s","cr_angle_offset") < 0) return -1; if (fprintf(ifp,"\t%f",cr_angle_offset) < 0) return -1; if (fprintf(ifp,"\n") < 0) return -1; if (fprintf(ifp,"%-20s","Ntup_Block") < 0) return -1; for(i=0;i<4;i++) { if (Ntup_Block[i] == FALSEB) { if (fprintf(ifp,"\t0")<0) return -1; } else { if (fprintf(ifp,"\t1")<0) return -1; } } if (fprintf(ifp,"\n") < 0) return -1; if (fprintf(ifp,"%-20s","VFP_distance") < 0) return -1; if (fprintf(ifp,"\t%f",vfp_L) < 0) return -1; if (fprintf(ifp,"\n") < 0) return -1; if (fprintf(ifp,"%-20s","VFP_angle") < 0) return -1; if (fprintf(ifp,"\t%f",vfp_psi) < 0) return -1; if (fprintf(ifp,"\n") < 0) return -1; if (fprintf(ifp,"%-20s","Gate_BBS") < 0) return -1; if (Gate_BBS == FALSEB) { if (fprintf(ifp,"\t0\n")<0) return -1; } else { if (fprintf(ifp,"\t1\n")<0) return -1; } if (fprintf(ifp,"%-20s","BBS_angle") < 0) return -1; if (fprintf(ifp,"\t%f",BBS_angle) < 0) return -1; if (fprintf(ifp,"\n") < 0) return -1; if (fprintf(ifp,"%-20s","Gate_scat_1") < 0) return -1; if (Gate_scat_1 == FALSEB) { if (fprintf(ifp,"\t0\n")<0) return -1; } else { if (fprintf(ifp,"\t1\n")<0) return -1; } if (fprintf(ifp,"%-20s","Gate_scat_2") < 0) return -1; if (Gate_scat_2 == FALSEB) { if (fprintf(ifp,"\t0\n")<0) return -1; } else { if (fprintf(ifp,"\t1\n")<0) return -1; } if (fprintf(ifp,"%-20s","Scat_limit_1") < 0) return -1; for(i=0;i<2;i++) if (fprintf(ifp,"\t%f",Scat_limit_1[i]) < 0) return -1; if (fprintf(ifp,"\n") < 0) return -1; if (fprintf(ifp,"%-20s","Scat_limit_2") < 0) return -1; for(i=0;i<2;i++) if (fprintf(ifp,"\t%f",Scat_limit_2[i]) < 0) return -1; if (fprintf(ifp,"\n") < 0) return -1; fclose(ifp); return 0; } /**********************************/ /* Definition of online commands */ /**********************************/ void Clear_spectra(Boolean * Running) { if (*Running) { UI_MsgOk("System must be in idle state !"); return; } if (Ntuple) { UI_MsgOk("Command not applicable to NTUPLEs."); return; } reset_histograms(); return; } static void Redef_histo (Boolean * Running) { if (*Running) { UI_MsgOk("System must be in idle state !"); return; } if (Ntuple) { UI_MsgOk("Command not applicable to NTUPLEs."); return; } define_histograms(); return; } static void Set_debug (Boolean * Running) { int status; UI_CtxRead CtxRead = NULL; if (UI_BooSetupRead (&CtxRead, "Dump buffer errors to screen", &Report_Buferr, NULL) < 0 || UI_BooSetupRead (&CtxRead, "Write FPP data to file", &File_FPP, NULL) < 0) FatalError ("UI_SetupRead failed"); status = UI_Read("Analysis debug options", &CtxRead, NULL, NULL); if (status < 0) FatalError ("UI_Read failed"); if (File_FPP) if ((FPP_file=fopen("fpp_data.dat","w"))==NULL) { UI_MsgOk("Couldn't open FPP data file"); File_FPP = FALSEB; } return; } static void TOF_gate(Boolean * Running) { UI_CtxRead CtxRead = NULL; int status; int Default_Min=-20, Default_Max=100; int Min=-256, Max=512; if (*Running) { UI_MsgOk("System must be in idle state !"); return; } if (UI_BooSetupRead (&CtxRead, "Put gate on TOF", &Gate_TOF, NULL) || UI_IntSetupRead (&CtxRead, "Lower limit for TOF", &TOF_limit[0], &Default_Min, &Min, &Max) || UI_IntSetupRead (&CtxRead, "Upper limit for TOF", &TOF_limit[1], &Default_Max, &Min, &Max) < 0) { FatalError ("UI_SetupRead failed"); } status = UI_Read("TOF gate adjustment", &CtxRead, NULL, NULL); if (status < 0) FatalError ("UI_Read failed"); return; } static void Variance_gate(Boolean * Running) { UI_CtxRead CtxRead = NULL; int status; float Default_Min=0., Default_Max=10.; float Min=0., Max=100.; if (*Running) { UI_MsgOk("System must be in idle state !"); return; } if (UI_BooSetupRead (&CtxRead, "Put gate on variance", &Gate_variance, NULL) || UI_FltSetupRead (&CtxRead, "Lower limit for X1-Variance", &Variance_limit[0][0], &Default_Min, &Min, &Max) || UI_FltSetupRead (&CtxRead, "Upper limit for X1_Variance", &Variance_limit[1][0], &Default_Max, &Min, &Max) || UI_FltSetupRead (&CtxRead, "Lower limit for U1_Variance", &Variance_limit[0][1], &Default_Max, &Min, &Max) || UI_FltSetupRead (&CtxRead, "Upper limit for U1_Variance", &Variance_limit[1][1], &Default_Max, &Min, &Max) || UI_FltSetupRead (&CtxRead, "Lower limit for X2_Variance", &Variance_limit[0][2], &Default_Max, &Min, &Max) || UI_FltSetupRead (&CtxRead, "Upper limit for X2_Variance", &Variance_limit[1][2], &Default_Max, &Min, &Max) || UI_FltSetupRead (&CtxRead, "Lower limit for U2_Variance", &Variance_limit[0][3], &Default_Max, &Min, &Max) || UI_FltSetupRead (&CtxRead, "Upper limit for U2_Variance", &Variance_limit[1][3], &Default_Max, &Min, &Max) < 0) { FatalError ("UI_SetupRead failed"); } status = UI_Read("Variance gate adjustment", &CtxRead, NULL, NULL); if (status < 0) FatalError ("UI_Read failed"); return; } static void ClusterSize(Boolean * Running) { UI_CtxRead CtxRead = NULL; int status; int Default=30; int Min=0, Max=100; if (*Running) { UI_MsgOk("System must be in idle state !"); return; } if (UI_IntSetupRead (&CtxRead, "Maximum clustersize", &MaxClusterSize, &Default, &Min, &Max) < 0) { FatalError ("UI_SetupRead failed"); } status = UI_Read("Maximum cluster size", &CtxRead, NULL, NULL); if (status < 0) FatalError ("UI_Read failed"); return; } static void Theta_gate(Boolean * Running) { UI_CtxRead CtxRead = NULL; int status; float Default_Min=-1., Default_Max=1.; float Min=-2., Max=2.; if (*Running) { UI_MsgOk("System must be in idle state !"); return; } if (UI_BooSetupRead (&CtxRead, "Put gate on theta", &Gate_Theta, NULL) || UI_FltSetupRead (&CtxRead, "Lower limit for theta", &Theta_limit[0], &Default_Min, &Min, &Max) || UI_FltSetupRead (&CtxRead, "Upper limit for theta", &Theta_limit[1], &Default_Max, &Min, &Max) < 0) { FatalError ("UI_SetupRead failed"); } status = UI_Read("Theta gate adjustment", &CtxRead, NULL, NULL); if (status < 0) FatalError ("UI_Read failed"); return; } static void cos_theta_carb_gate(Boolean * Running) { UI_CtxRead CtxRead = NULL; int status; float Default_Min=-1., Default_Max=1.; float Min=-1., Max=1.; if (*Running) { UI_MsgOk("System must be in idle state !"); return; } if (UI_BooSetupRead (&CtxRead, "Put gate on cosine secondary scattering angle", &Gate_cos_theta_carb, NULL) || UI_BooSetupRead (&CtxRead, "Correct DSP coordinates", &Correct_DSP, NULL) || UI_FltSetupRead (&CtxRead, "Lower limit for cosine secondary scattering angle", &cos_theta_carb_limit[0], &Default_Min, &Min, &Max) || UI_FltSetupRead (&CtxRead, "Upper limit for cosine secondary scattering angle", &cos_theta_carb_limit[1], &Default_Max, &Min, &Max) < 0) { FatalError ("UI_SetupRead failed"); } status = UI_Read("Cosine secondary scattering angle gate adjustment", &CtxRead, NULL, NULL); if (status < 0) FatalError ("UI_Read failed"); return; } static void X1_gate(Boolean * Running) { UI_CtxRead CtxRead = NULL; int status; float Default_Min=0., Default_Max=1024.; float Min=0., Max=1024.; if (*Running) { UI_MsgOk("System must be in idle state !"); return; } if (UI_BooSetupRead (&CtxRead, "Put gate on X1", &Gate_X1, NULL) || UI_FltSetupRead (&CtxRead, "Lower limit for X1", &X1_limit[0], &Default_Min, &Min, &Max) || UI_FltSetupRead (&CtxRead, "Upper limit for X1", &X1_limit[1], &Default_Max, &Min, &Max) < 0) { FatalError ("UI_SetupRead failed"); } status = UI_Read("X1 gate adjustment", &CtxRead, NULL, NULL); if (status < 0) FatalError ("UI_Read failed"); return; } static void vertz_gate(Boolean * Running) { UI_CtxRead CtxRead = NULL; int status; float Default_Min=-1000., Default_Max=2000.; float Min=-1000., Max=2000.; if (*Running) { UI_MsgOk("System must be in idle state !"); return; } if (UI_BooSetupRead (&CtxRead, "Put gate on z vertex", &Gate_vertz, NULL) || UI_FltSetupRead (&CtxRead, "Lower limit for z", &vertz_limit[0], &Default_Min, &Min, &Max) || UI_FltSetupRead (&CtxRead, "Upper limit for z", &vertz_limit[1], &Default_Max, &Min, &Max) < 0) { FatalError ("UI_SetupRead failed"); } status = UI_Read("z vertex gate adjustment", &CtxRead, NULL, NULL); if (status < 0) FatalError ("UI_Read failed"); return; } static void target_gate(Boolean * Running) { UI_CtxRead CtxRead = NULL; int status; float Default_Min=-100., Default_Max=100.; float Min=-100., Max=100.; if (*Running) { UI_MsgOk("System must be in idle state !"); return; } if (UI_BooSetupRead (&CtxRead, "Put gate on target coordinates", &Gate_target, NULL) || UI_FltSetupRead (&CtxRead, "Lower limit for theta target", &Theta_target_limit[0], &Default_Min, &Min, &Max) || UI_FltSetupRead (&CtxRead, "Upper limit for theta target", &Theta_target_limit[1], &Default_Max, &Min, &Max) || UI_FltSetupRead (&CtxRead, "Lower limit for phi target", &Phi_target_limit[0], &Default_Min, &Min, &Max) || UI_FltSetupRead (&CtxRead, "Upper limit for phi target", &Phi_target_limit[1], &Default_Max, &Min, &Max) < 0) { FatalError ("UI_SetupRead failed"); } status = UI_Read("target gate adjustment", &CtxRead, NULL, NULL); if (status < 0) FatalError ("UI_Read failed"); return; } static void BBS_gate(Boolean * Running) { UI_CtxRead CtxRead = NULL; int status; float Default = 10.; float Min = -10., Max = 60.; if (*Running) { UI_MsgOk("System must be in idle state !"); return; } if (UI_BooSetupRead (&CtxRead, "Input BBS angle", &Gate_BBS, NULL) || UI_FltSetupRead (&CtxRead, "BBS angle", &BBS_angle, &Default, &Min, &Max) < 0) { FatalError ("UI_SetupRead failed"); } status = UI_Read("BBS angle adjustment", &CtxRead, NULL, NULL); if (status < 0) FatalError ("UI_Read failed"); return; } static void Scat_gate_1(Boolean * Running) { UI_CtxRead CtxRead = NULL; int status; float Default_Min=-100., Default_Max=100.; float Min=-100., Max=100.; if (*Running) { UI_MsgOk("System must be in idle state !"); return; } if (UI_BooSetupRead (&CtxRead, "Put first gate on real scattering angle ", &Gate_scat_1, NULL) || UI_FltSetupRead (&CtxRead, "Lower limit for scattering angle", &Scat_limit_1[0], &Default_Min, &Min, &Max) || UI_FltSetupRead (&CtxRead, "Upper limit for scattering angle", &Scat_limit_1[1], &Default_Max, &Min, &Max) < 0) { FatalError ("UI_SetupRead failed"); } status = UI_Read("Scattering angle gate 1 adjustment", &CtxRead, NULL, NULL); if (status < 0) FatalError ("UI_Read failed"); return; } static void Scat_gate_2(Boolean * Running) { UI_CtxRead CtxRead = NULL; int status; float Default_Min=-100., Default_Max=100.; float Min=-100., Max=100.; if (*Running) { UI_MsgOk("System must be in idle state !"); return; } if (UI_BooSetupRead (&CtxRead, "Put second gate on real scattering angle ", &Gate_scat_2, NULL) || UI_FltSetupRead (&CtxRead, "Lower limit for scattering angle", &Scat_limit_2[0], &Default_Min, &Min, &Max) || UI_FltSetupRead (&CtxRead, "Upper limit for scattering angle", &Scat_limit_2[1], &Default_Max, &Min, &Max) < 0) { FatalError ("UI_SetupRead failed"); } status = UI_Read("Scattering angle gate 2 adjustment", &CtxRead, NULL, NULL); if (status < 0) FatalError ("UI_Read failed"); return; } static void define_offsets(Boolean * Running) { UI_CtxRead CtxRead = NULL; int status; float Default_VDC0x=-283.7; float Min_VDC0x=-400., Max_VDC0x=-200.; float Default_VDC0y=0.; float Min_VDC0y=-100., Max_VDC0y=100.; float Default_VDC0z=-500.6; float Min_VDC0z=-600, Max_VDC0z=-400.; float Default_D2x_offset=0.; float Min_CAz_offset=-100., Max_CAz_offset=100.; float Default_CAz_offset=0.; float Min_D2x_offset=-100., Max_D2x_offset=100.; float Default_D2y_offset=0.; float Min_D2y_offset=-100., Max_D2y_offset=100.; float Default_D2z_offset=0.; float Min_D2z_offset=-100., Max_D2z_offset=100.; float Default_D3x_offset=0.; float Min_D3x_offset=-100., Max_D3x_offset=100.; float Default_D3y_offset=0.; float Min_D3y_offset=-100., Max_D3y_offset=100.; float Default_D3z_offset=0.; float Min_D3z_offset=-100., Max_D3z_offset=100.; float Default_D4x_offset=0.; float Min_D4x_offset=-100., Max_D4x_offset=100.; float Default_D4y_offset=0.; float Min_D4y_offset=-100., Max_D4y_offset=100.; float Default_D4z_offset=0.; float Min_D4z_offset=-100., Max_D4z_offset=100.; float Default_Phi_offset=0.; float Min_Phi_offset=-1., Max_Phi_offset=1.; float Default_cr_angle_offset=0.; float Min_cr_angle_offset=-1., Max_cr_angle_offset=1.; if (*Running) { UI_MsgOk("System must be in idle state !"); return; } if (UI_FltSetupRead (&CtxRead, "VDC0x", &VDC0x, &Default_VDC0x, &Min_VDC0x, &Max_VDC0x) || UI_FltSetupRead (&CtxRead, "VDC0y", &VDC0y, &Default_VDC0y, &Min_VDC0y, &Max_VDC0y) || UI_FltSetupRead (&CtxRead, "VDC0z", &VDC0z, &Default_VDC0z, &Min_VDC0z, &Max_VDC0z) || UI_FltSetupRead (&CtxRead, "CAz_offset", &CAz_offset, &Default_CAz_offset, &Min_CAz_offset, &Max_CAz_offset) || UI_FltSetupRead (&CtxRead, "D2x_offset", &D2x_offset, &Default_D2x_offset, &Min_D2x_offset, &Max_D2x_offset) || UI_FltSetupRead (&CtxRead, "D2y_offset", &D2y_offset, &Default_D2y_offset, &Min_D2y_offset, &Max_D2y_offset) || UI_FltSetupRead (&CtxRead, "D2z_offset", &D2z_offset, &Default_D2z_offset, &Min_D2z_offset, &Max_D2z_offset) || UI_FltSetupRead (&CtxRead, "D3x_offset", &D3x_offset, &Default_D3x_offset, &Min_D3x_offset, &Max_D3x_offset) || UI_FltSetupRead (&CtxRead, "D3y_offset", &D3y_offset, &Default_D3y_offset, &Min_D3y_offset, &Max_D3y_offset) || UI_FltSetupRead (&CtxRead, "D3z_offset", &D3z_offset, &Default_D3z_offset, &Min_D3z_offset, &Max_D3z_offset) || UI_FltSetupRead (&CtxRead, "D4x_offset", &D4x_offset, &Default_D4x_offset, &Min_D4x_offset, &Max_D4x_offset) || UI_FltSetupRead (&CtxRead, "D4y_offset", &D4y_offset, &Default_D4y_offset, &Min_D4y_offset, &Max_D4y_offset) || UI_FltSetupRead (&CtxRead, "D4z_offset", &D4z_offset, &Default_D4z_offset, &Min_D4z_offset, &Max_D4z_offset) || UI_FltSetupRead (&CtxRead, "Phi_offset", &Phi_offset, &Default_Phi_offset, &Min_Phi_offset, &Max_Phi_offset) || UI_FltSetupRead (&CtxRead, "cr_angle_offset", &cr_angle_offset, &Default_cr_angle_offset, &Min_cr_angle_offset, &Max_cr_angle_offset) < 0) { FatalError ("UI_SetupRead failed"); } status = UI_Read("Offset setup", &CtxRead, NULL, NULL); if (status < 0) FatalError ("UI_Read failed"); return; } static void Change_zero(Boolean * Running) { UI_CtxRead CtxRead = NULL; int status; int Default=335, Min=0, Max=512; if (*Running) { UI_MsgOk("System must be in idle state !"); return; } if (UI_IntSetupRead (&CtxRead, "Zero time for plane VDC1-X", &VDC_T0[0], &Default, &Min, &Max) || UI_IntSetupRead (&CtxRead, "Zero time for plane VDC1-U", &VDC_T0[1], &Default, &Min, &Max) || UI_IntSetupRead (&CtxRead, "Zero time for plane VDC2-X", &VDC_T0[2], &Default, &Min, &Max) || UI_IntSetupRead (&CtxRead, "Zero time for plane VDC2-U", &VDC_T0[3], &Default, &Min, &Max) < 0) { FatalError ("UI_SetupRead failed"); } status = UI_Read("Zero time adjustment", &CtxRead, NULL, NULL); if (status < 0) FatalError ("UI_Read failed"); if (Use_VESNA) { /* transfer zero times */ VESNA_set_T0(VDC_T0[0], VDC_T0[1], VDC_T0[2], VDC_T0[3]); } return; } static void Calc_estim(Boolean * Running) { UI_CtxRead CtxRead = NULL; int status = 0; float Default=0, Min=0, Max=50; float lower=0, upper=0; int i, j, lch, hch; float numcos=0., numsin = 0., den=0.; FILE * ifp; if (*Running) { UI_MsgOk("System must be in idle state !"); return; } /* write data to file */ if ((ifp=fopen("P_lower.dat","w"))==NULL) UI_MsgOk("Can't open data file"); else { for (i=3;i<16;i++) { numcos = numsin = den = 0.; for (j=5*i;j<=100;j++) { numcos += estim_cos[j]; numsin += estim_sin[j]; den += estim_den[j]; } fprintf(ifp,"%2d\t%f\t%f\n",i,2*numcos/den,2*numsin/den); } fclose(ifp); } if ((ifp=fopen("P_upper.dat","w"))==NULL) UI_MsgOk("Can't open data file"); else { for (i=10;i<21;i++) { numcos = numsin = den = 0.; for (j=25;j<=5*i;j++) { numcos += estim_cos[j]; numsin += estim_sin[j]; den += estim_den[j]; } fprintf(ifp,"%2d\t%f\t%f\n",i,2*numcos/den,2*numsin/den); } fclose(ifp); } while (status!=1) /* only stop when cancelled */ { if (UI_FltSetupRead (&CtxRead, "Lower theta angle", &lower, &Default, &Min, &Max) || UI_FltSetupRead (&CtxRead, "Upper theta angle", &upper, &Default, &Min, &Max) < 0) { FatalError ("UI_SetupRead failed"); } status = UI_Read("Calculate estimator", &CtxRead, NULL, NULL); if (status < 0) FatalError ("UI_Read failed"); lch = 5 * lower; hch = 5 * upper; numcos = numsin = den = 0.; for (i=lch;i<=hch;i++) { numcos += estim_cos[i]; numsin += estim_sin[i]; den += estim_den[i]; } UI_Msg("Value for numerator cosine = %f", numcos); UI_Msg("Value for numerator sine = %f", numsin); UI_Msg("Value for denominator = %f", den); if (den!=0) { UI_Msg("Value for cos_estimator = %f", 2*numcos/den); UI_Msg("Value for sin_estimator = %f", 2*numsin/den); } } return; } static void Save_oas (void) { int status; UI_CtxRead CtxRead = NULL; unsigned int ONE = 1; const unsigned int FileNameLenMax = 256; if (UI_StrSetupRead (&CtxRead, "Setup filename", Ana_par.oas_parfile, NULL, &ONE, &FileNameLenMax, NULL) < 0) FatalError ("UI_SetupRead failed"); status = UI_Read("Save online analysis setup", &CtxRead, NULL, NULL); if (status < 0) { FatalError ("UI_Read failed"); return; } if (save_analysis_setup(Ana_par.oas_parfile)<0) UI_MsgOk("Error while writing file %s.oas.",Ana_par.oas_parfile); } static void Load_oas (void) { int status; UI_CtxRead CtxRead = NULL; unsigned int ONE = 1; const unsigned int FileNameLenMax = 256; if (UI_StrSetupRead (&CtxRead, "Setup filename", Ana_par.oas_parfile, NULL, &ONE, &FileNameLenMax, NULL) < 0) FatalError ("UI_SetupRead failed"); status = UI_Read("Load online analysis setup file", &CtxRead, NULL, NULL); if (status < 0) { FatalError ("UI_Read failed"); return; } if (load_analysis_setup(Ana_par.oas_parfile) < 0) UI_MsgOk("Error while reading file %s.oas.",Ana_par.oas_parfile); } static void compose_ntuple (Boolean * Running) { int status; UI_CtxRead CtxRead = NULL; if (*Running) { UI_MsgOk("System must be in idle state !"); return; } if (UI_BooSetupRead (&CtxRead, "FPDS data", &Ntup_Block[0], NULL) || UI_BooSetupRead (&CtxRead, "FPP data", &Ntup_Block[1], NULL) || UI_BooSetupRead (&CtxRead, "PID data", &Ntup_Block[2], NULL) || UI_BooSetupRead (&CtxRead, "TAR data", &Ntup_Block[3], NULL) < 0) FatalError ("UI_SetupRead failed"); status = UI_Read("Compose ntuple", &CtxRead, NULL, NULL); if (status < 0) FatalError ("UI_Read failed"); return; } static void type_gate (Boolean * Running) { int status; UI_CtxRead CtxRead = NULL; if (*Running) { UI_MsgOk("System must be in idle state !"); return; } if (UI_BooSetupRead (&CtxRead, "Select FPP events", &Select_type[EVENT_FPP], NULL) || UI_BooSetupRead (&CtxRead, "Select ANGLE_CUT events", &Select_type[EVENT_ANGLECUT], NULL) || UI_BooSetupRead (&CtxRead, "Select UNCHECKED events", &Select_type[EVENT_UNCHECKED], NULL) || UI_BooSetupRead (&CtxRead, "Select PULSER events", &Select_type[EVENT_PULSER], NULL) || UI_BooSetupRead (&CtxRead, "Select SCALER events", &Select_type[EVENT_SCALER], NULL) || UI_BooSetupRead (&CtxRead, "Select MULTIPLE HIT events", &Select_type[EVENT_MULT], NULL) || UI_BooSetupRead (&CtxRead, "Select REST events", &Select_type[EVENT_REST], NULL) || UI_BooSetupRead (&CtxRead, "Select REPAIRED MULTIPLE events", &Select_type[EVENT_MULT_REP], NULL) || UI_BooSetupRead (&CtxRead, "Select REPAIRED REST events", &Select_type[EVENT_REST_REP], NULL) < 0) FatalError ("UI_SetupRead failed"); status = UI_Read("Gate eventtype", &CtxRead, NULL, NULL); if (status < 0) FatalError ("UI_Read failed"); return; } static void pol_gate (Boolean * Running) { int status; UI_CtxRead CtxRead = NULL; if (*Running) { UI_MsgOk("System must be in idle state !"); return; } if (UI_BooSetupRead (&CtxRead, "Select Polarization UP events", &Select_pol[0], NULL) || UI_BooSetupRead (&CtxRead, "Select Polarization DOWN events", &Select_pol[1], NULL) || UI_BooSetupRead (&CtxRead, "Select Polarization OFF events", &Select_pol[2], NULL) || UI_BooSetupRead (&CtxRead, "Select Polarization UNDEFINED events", &Select_pol[3], NULL) < 0 ) FatalError ("UI_SetupRead failed"); status = UI_Read("Gate polarization", &CtxRead, NULL, NULL); if (status < 0) FatalError ("UI_Read failed"); return; } static void QDC (Boolean * Running) { int status; UI_CtxRead CtxRead = NULL; if (UI_BooSetupRead (&CtxRead, "QDC in read out", &QDC_in, NULL) < 0) FatalError ("UI_SetupRead failed"); status = UI_Read("Enable read out of QDC", &CtxRead, NULL, NULL); if (status < 0) FatalError ("UI_Read failed"); return; } static void VESNA_VDC_handling (Boolean * Running) { int status; UI_CtxRead CtxRead = NULL; if (UI_BooSetupRead (&CtxRead, "Use VESNA routine to handle VDC data", &Use_VESNA, NULL) < 0) FatalError ("UI_SetupRead failed"); status = UI_Read("Enable VESNA VDC handling", &CtxRead, NULL, NULL); if (status < 0) FatalError ("UI_Read failed"); if (Use_VESNA) { /* read VESNA configuration file */ VESNA(0,0,0,0,0,NULL); /* transfer zero times */ VESNA_set_T0(VDC_T0[0], VDC_T0[1], VDC_T0[2], VDC_T0[3]); } return; } static void Corrections (Boolean * Running) { int status; UI_CtxRead CtxRead = NULL; if (UI_BooSetupRead (&CtxRead, "Correct for switched cards in D4", &Correct_D4, NULL) || UI_BooSetupRead (&CtxRead, "Correct for ringing wires", &Correct_ringing, NULL) || UI_BooSetupRead (&CtxRead, "Correct for missing wires", &Correct_missing, NULL) || UI_BooSetupRead (&CtxRead, "Correct for multiple hits", &Correct_multiple, NULL) || UI_BooSetupRead (&CtxRead, "Correct unchecked events", &Correct_unchecked, NULL) < 0 ) FatalError ("UI_SetupRead failed"); status = UI_Read("Enable corrections", &CtxRead, NULL, NULL); if (status < 0) FatalError ("UI_Read failed"); return; } static void vfp_params(Boolean * Running) { UI_CtxRead CtxRead = NULL; int status; float L_min = -1000., L_max = 1000. ; float psi_min = -180., psi_max = 180. ; if (*Running) { UI_MsgOk("System must be in idle state !"); return; } if ( UI_FltSetupRead (&CtxRead, "Distance detector <-> virtual focal plane [mm]", &vfp_L, NULL, &L_min, &L_max) || UI_FltSetupRead (&CtxRead, "Tilt angle virtual focal plane [deg.]", &vfp_psi, NULL, &psi_min, &psi_max) < 0) { FatalError ("UI_SetupRead failed"); } status = UI_Read("Virtual focal plane params", &CtxRead, NULL, NULL); if (status < 0) FatalError ("UI_Read failed"); return; } int Online_ana_command (Boolean Running) { UI_CtxRead CtxRead = NULL; char title[50]; int NrCmds = 26; unsigned int LastCmd = NrCmds - 1; const char * cmdnames[] = { "Load setup", "Save setup", "Clear spectra", "Redefine histograms", "Compose ntuple", "Corrections", "Debugging", "QDC data", "Change zero times", "Define offsets", "Maximum cluster size", "Calculate estimator", "Polarization gate", "Event type gate", "Variance gate", "TOF gate", "Target gate", "Theta gate", "X1 gate", "Z vertex gate", "BBS angle", "Scattering angle gate 1", "Scattering angle gate 2", "Cosine secondary gate", "VESNA VDC handling", "Virtual focal plane"}; UI_CmdFunc * commands[] = { (UI_CmdFunc*)Load_oas, (UI_CmdFunc*)Save_oas, (UI_CmdFunc*)Clear_spectra, (UI_CmdFunc*)Redef_histo, (UI_CmdFunc*)compose_ntuple, (UI_CmdFunc*)Corrections, (UI_CmdFunc*)Set_debug, (UI_CmdFunc*)QDC, (UI_CmdFunc*)Change_zero, (UI_CmdFunc*)define_offsets, (UI_CmdFunc*)ClusterSize, (UI_CmdFunc*)Calc_estim, (UI_CmdFunc*)pol_gate, (UI_CmdFunc*)type_gate, (UI_CmdFunc*)Variance_gate, (UI_CmdFunc*)TOF_gate, (UI_CmdFunc*)target_gate, (UI_CmdFunc*)Theta_gate, (UI_CmdFunc*)X1_gate, (UI_CmdFunc*)vertz_gate, (UI_CmdFunc*)BBS_gate, (UI_CmdFunc*)Scat_gate_1, (UI_CmdFunc*)Scat_gate_2, (UI_CmdFunc*)cos_theta_carb_gate, (UI_CmdFunc*)VESNA_VDC_handling, (UI_CmdFunc*)vfp_params}; if (UI_CmdSetupRead (&CtxRead, "Analysis commands", &LastCmd, cmdnames, commands, &Running) != 0) FatalError ("UI_SetupRead failure"); strcpy(title,"Online analysis control v"); strcat(title,VERSION); strcat(title," ("); strcat(title,UPDATE); strcat(title,")"); switch (UI_Read (title, &CtxRead, NULL, NULL)) { case 0: break; /* Normal */ case 1: return 0; /* Cancelled */ default: FatalError ("UI_Read failed"); } return 0; } /*********************/ /* clear all spectra */ /*********************/ static void reset_histograms(void) { int i,j; for (i=0;i<250;i++) estim_cos[i]=estim_sin[i]=estim_den[i]=0.; /* Clear VDC data */ UI_Msg("Clearing histograms"); HCDIR("\\\\\\\\"," "); HRESET(0," "); HCDIR("TARGET"," "); HRESET(0," "); HCDIR("\\"," "); for(i=0;i<2;i++) { switch(i) { case 0: HCDIR("VDC1"," "); break; case 1: HCDIR("VDC2"," "); break; } for(j=0;j<2;j++) { switch(j) { case 0: HCDIR("X-PLANE"," "); break; case 1: HCDIR("U-PLANE"," "); break; } HRESET(0," "); HCDIR("DRIFTTIMES"," "); HRESET(0," "); HCDIR("\\"," "); HCDIR("\\"," "); } HCDIR("\\"," "); } HCDIR("S1"," "); HRESET(0," "); HCDIR("TOT SPECTRA"," "); HRESET(0," "); HCDIR("\\\\"," "); HCDIR("S2"," "); HRESET(0," "); HCDIR("TOT SPECTRA"," "); HRESET(0," "); HCDIR("\\\\"," "); HCDIR("QDC"," "); HRESET(0," "); HCDIR("\\"," "); return; } /*************************************/ /* (re-)definition of all histograms */ /*************************************/ int define_histograms(void) { int i,j; char name1[4][32] = {"X1 Drifttime Wire xxx","U1 Drifttime Wire xxx", "X2 Drifttime Wire xxx","U2 Drifttime Wire xxx"}; char name2[4][32] = {"X1 TOT Wire xxx","U1 TOT Wire xxx", "X2 TOT Wire xxx","U2 TOT Wire xxx"}; Histopar_t HiPar; UI_Msg("Defining histograms"); if (histo_getpar(&HiPar) < 0) { UI_Msg("define_histograms: Error in histo_getpar"); return -1; } UI_Msg("Shared memory ID = %s, size = %d",Mem_id, HiPar.MEM_Size); HLIMAP(HiPar.MEM_Size,Mem_id); /* top directory */ HBOOK1(1,"Buffer error (FIFO number)",5,-0.5,4.5,0.); HBOOK1(3,"Time out (FIFO number)",5,-0.5,4.5,0.); HBOOK1(4,"Beam Polarization Value",10,-0.5,9.5,0.); HBOOK1(5,"Countrates (raw)",20,0.5,20.5,0.); HBOOK1(6,"Countrates (interpreted)",20,0.5,20.5,0.); HBOOK1(7,"Eventtypes (ungated)",14,-1.5,12.5,0.); HBOOK1(8,"Eventtypes (gated)",14,-1.5,12.5,0.); HBOOK1(11,"Time of flight (0.5 ns units)", HiPar.TOF_Bins, HiPar.TOF_Min, HiPar.TOF_Max,0.); HBOOK1(12,"RF cyclotron (0.5 ns units)",200,0.,100.,0.); HBOOK1(21,"THETA (rad)",200,-0.4,0.4,0.); HBOOK1(22,"PHI (rad)",200,-0.4,0.4,0.); HBOOK1(23,"Y in X1-PLANE (mm)",800,-200,200,0.); HBOOK1(24,"X in X1-PLANE (mm)",1024,0,1024,0.); HBOOK2(25,"Y vs X IN X1-PLANE (mm)", HiPar.X_Bins, HiPar.X_Min, HiPar.X_Max, HiPar.Y_Bins, HiPar.Y_Min, HiPar.Y_Max ,0.); HBOOK2(26,"THETA vs X IN X1-PLANE (rad vs mm)", HiPar.X_Bins, HiPar.X_Min, HiPar.X_Max,200,-0.4,0.4,0.); /* HBOOK2(27,"PHI vs Y IN X1-PLANE (rad vs mm)", HiPar.Y_Bins, HiPar.Y_Min, HiPar.Y_Max ,200,-0.4,0.4,0.); HBOOK2(28,"Sum_S1 vs X IN X1-PLANE", HiPar.X_Bins, HiPar.X_Min, HiPar.X_Max, 250, 0., 1000., 0.); HBOOK2(29,"Sum_S2 vs X IN X1-PLANE", HiPar.X_Bins, HiPar.X_Min, HiPar.X_Max, 250, 0., 1000., 0.); */ HBOOK1(30,"X in virtual focal plane (mm)",1024,0,1024,0.); HBOOK2(31,"THETA vs X in virtual focal plane (rad vs mm)", HiPar.X_Bins, HiPar.X_Min, HiPar.X_Max,200,-0.4,0.4,0.); HBOOK2(101,"Sum all TOT S2 vs S1", HiPar.VTOT_Bins,2* HiPar.STOT_Min, 2* HiPar.STOT_Max, HiPar.STOT_Bins, 2* HiPar.STOT_Min,2* HiPar.STOT_Max,0.); HBOOK2(102,"RF vs X",250, 0.,1000.,50, -40.,20.,0.); HBOOK2(103,"SUM TOT S1 vs X", 125, 0., 1000., 125, 0., 1000.,0.); /* only used for debugging HBOOK1(201,"Check cosine theta 2",1000,.5,1,0.); HBOOK1(202,"Check theta 2",1000,0,50,0.); */ /* target coordinates subdirectory */ HMDIR("TARGET","S"); HBOOK1(1,"theta target (mrad)", 200, -100, 100, 0.); HBOOK1(2,"phi target (mrad)", 200, -100, 100, 0.); HBOOK1(3,"momentum (MeV/c)", 1500, 500, 650, 0.); HBOOK1(4,"momentum (MeV/c) scattering angle gate 1", 1500, 540, 690, 0.); HBOOK1(5,"momentum (MeV/c) scattering angle gate 2", 1500, 540, 690, 0.); HBOOK2(11,"phi target (mrad) vs theta target (mrad)",100,-100,100, 100,-100,100,0.); HBOOK2(12,"theta target (mrad) vs momentum (MeV/c)",150, 500, 650, 100,-100,100,0.); HBOOK2(13,"phi target (mrad) vs momentum (MeV/c)",150, 500, 650, 100,-100,100,0.); HBOOK1(21,"momentum (MeV/c) beam polarization up", 1500, 500, 650, 0.); HBOOK1(22,"momentum (MeV/c) beam polarization down", 1500, 500, 650, 0.); HBOOK1(23,"momentum (MeV/c) beam polarization off", 1500, 500, 650, 0.); HBOOK1(31,"momentum (MeV/c) with theta gate", 4500, 500, 650, 0.); HCDIR("\\"," "); HMDIR("MWPC1","S"); HCDIR("\\"," "); HMDIR("MWPC2","S"); HCDIR("\\"," "); HMDIR("MWPC3","S"); HCDIR("\\"," "); HMDIR("MWPC4","S"); HCDIR("\\"," "); /* vdc directories */ HMDIR("VDC1","S"); HMDIR("X-PLANE","S"); HMDIR("DRIFTTIMES"," "); HBOOK1(1,"ALL WIRES X1",240,0.5,240.5,0.); HBOOK1(2,"MULTIPLICITY = 1 X1",240,0.5,240.5,0.); HBOOK1(3,"MULTIPLICITY = 2 X1",240,0.5,240.5,0.); HBOOK1(4,"MULTIPLICITY = 3 OR MORE X1",240,0.5,240.5,0.); HBOOK1(5,"MISSING WIRES X1",240,0.5,240.5,0.); HBOOK1(8,"CLUSTERSIZE X1",15,0.5,15.5,0.); HBOOK1(9,"NUMBER OF CLUSTERS PER EVENT X1",5,0.5,5.5,0.); HBOOK1(100,"Closest wire X1 (wire number)",240,0.5,240.5,0.); HBOOK1(200,"Crossing point by fitting X1", HiPar.Int_Bins,0.5,240.5,0.); HBOOK1(300,"Variance for fitting X1", 200,0,10,0.); HBOOK1(400,"Number of tracks X1", 10,-0.5,9.5,0.); HCDIR("\\"," "); HMDIR("U-PLANE","S"); HMDIR("DRIFTTIMES"," "); HBOOK1(1,"ALL WIRES U1",240,0.5,240.5,0.); HBOOK1(2,"MULTIPLICITY = 1 U1",240,0.5,240.5,0.); HBOOK1(3,"MULTIPLICITY = 2 U1",240,0.5,240.5,0.); HBOOK1(4,"MULTIPLICITY = 3 OR MORE U1",240,0.5,240.5,0.); HBOOK1(5,"MISSING WIRES U1",240,0.5,240.5,0.); HBOOK1(8,"CLUSTERSIZE U1",15,0.5,15.5,0.); HBOOK1(9,"NUMBER OF CLUSTERS PER EVENT U1",5,0.5,5.5,0.); HBOOK1(100,"Closest wire U1 (wire number)",240,0.5,240.5,0.); HBOOK1(200,"Crossing point by fitting U1", HiPar.Int_Bins,0.5,240.5,0.); HBOOK1(300,"Variance for fitting U1", 200,0,10,0.); HBOOK1(400,"Number of tracks U1", 10,-0.5,9.5,0.); HCDIR("\\\\"," "); HMDIR("VDC2","S"); HMDIR("X-PLANE","S"); HMDIR("DRIFTTIMES"," "); HBOOK1(1,"ALL WIRES X2",240,0.5,240.5,0.); HBOOK1(2,"MULTIPLICITY = 1 X2",240,0.5,240.5,0.); HBOOK1(3,"MULTIPLICITY = 2 X2",240,0.5,240.5,0.); HBOOK1(4,"MULTIPLICITY = 3 OR MORE X2",240,0.5,240.5,0.); HBOOK1(5,"MISSING WIRES X2",240,0.5,240.5,0.); HBOOK1(8,"CLUSTERSIZE X2",15,0.5,15.5,0.); HBOOK1(9,"NUMBER OF CLUSTERS PER EVENT X2",5,0.5,5.5,0.); HBOOK1(100,"Closest wire X2 (wire number)",240,0.5,240.5,0.); HBOOK1(200,"Crossing point by fitting X2", HiPar.Int_Bins,0.5,240.5,0.); HBOOK1(300,"Variance for fitting X2", 200,0,10,0.); HBOOK1(400,"Number of tracks X2", 10,-0.5,9.5,0.); HCDIR("\\"," "); HMDIR("U-PLANE","S"); HMDIR("DRIFTTIMES"," "); HBOOK1(1,"ALL WIRES U2",240,0.5,240.5,0.); HBOOK1(2,"MULTIPLICITY = 1 U2",240,0.5,240.5,0.); HBOOK1(3,"MULTIPLICITY = 2 U2",240,0.5,240.5,0.); HBOOK1(4,"MULTIPLICITY = 3 OR MORE U2",240,0.5,240.5,0.); HBOOK1(5,"MISSING WIRES U2",240,0.5,240.5,0.); HBOOK1(8,"CLUSTERSIZE U2",15,0.5,15.5,0.); HBOOK1(9,"NUMBER OF CLUSTERS PER EVENT U2",5,0.5,5.5,0.); HBOOK1(100,"Closest wire U2 (wire number)",240,0.5,240.5,0.); HBOOK1(200,"Crossing point by fitting U2", HiPar.Int_Bins,0.5,240.5,0.); HBOOK1(300,"Variance for fitting U2", 200,0,10,0.); HBOOK1(400,"Number of tracks U2", 10,-0.5,9.5,0.); HCDIR("\\\\"," "); /* book drifttime histograms */ for(i=0;i<4;i++) { switch(i) { case 0: case 1: HCDIR("VDC1"," "); break; case 2: case 3: HCDIR("VDC2"," "); break; } switch(i) { case 0: case 2: HCDIR("X-PLANE"," "); break; case 1: case 3: HCDIR("U-PLANE"," "); break; } HCDIR("DRIFTTIMES"," "); for(j=5;j<=WIRES_VDC;j+=10) { name1[i][19] = 48+(j/100); name1[i][20] = 48+(j-(j/100)*100)/10; name1[i][21] = 48+(j-(j/10)*10); name1[i][22] = '\0'; HBOOK1(j,name1[i], HiPar.Drift_Bins, HiPar.Drift_Min, HiPar.Drift_Max,0.); name2[i][13] = 48+(j/100); name2[i][14] = 48+(j-(j/100)*100)/10; name2[i][15] = 48+(j-(j/10)*10); name2[i][16] = '\0'; /* HBOOK1(1000+j,name2[i], HiPar.VTOT_Bins, HiPar.VTOT_Min, HiPar.VTOT_Max,0.); */ } HCDIR("\\\\\\"," "); } /* scintillator directories */ HMDIR("S1","S"); HMDIR("TOT SPECTRA","S"); HBOOK1(1,"S1 TOT T1", HiPar.STOT_Bins, HiPar.STOT_Min, HiPar.STOT_Max,0.); HBOOK1(2,"S1 TOT B1", HiPar.STOT_Bins, HiPar.STOT_Min, HiPar.STOT_Max,0.); HBOOK1(3,"S1 TOT T2", HiPar.STOT_Bins, HiPar.STOT_Min, HiPar.STOT_Max,0.); HBOOK1(4,"S1 TOT B2", HiPar.STOT_Bins, HiPar.STOT_Min, HiPar.STOT_Max,0.); HBOOK1(5,"S1 TOT T3", HiPar.STOT_Bins, HiPar.STOT_Min, HiPar.STOT_Max,0.); HBOOK1(6,"S1 TOT B3", HiPar.STOT_Bins, HiPar.STOT_Min, HiPar.STOT_Max,0.); HBOOK1(7,"S1 TOT T4", HiPar.STOT_Bins, HiPar.STOT_Min, HiPar.STOT_Max,0.); HBOOK1(8,"S1 TOT B4", HiPar.STOT_Bins, HiPar.STOT_Min, HiPar.STOT_Max,0.); HBOOK1(9,"S1 TOT T5", HiPar.STOT_Bins, HiPar.STOT_Min, HiPar.STOT_Max,0.); HBOOK1(10,"S1 TOT B5", HiPar.STOT_Bins, HiPar.STOT_Min, HiPar.STOT_Max,0.); HCDIR("\\"," "); HBOOK1(1,"S1 MULTIPLICITY (PM number)",10,0.5,10.5,0.); HBOOK1(2,"S1 LEADING EDGE MISSING (PM number)",10,0.5,10.5,0.); HBOOK1(3,"S1 TRAILING EDGE MISSING (PM number)",10,0.5,10.5,0.); HBOOK1(4,"SUM ALL TOT S1",512,0.5,2048.5,0.); HBOOK1(5,"NUMBER OF PHOTOMULTIPLIERS PER EVENT S1",11,-0.5,10.5,0.); HBOOK2(6,"Sum all TOT s1 vs D2x (wirenumber)", 112, 0.5, 448.5, 100, 0, 1000, 0.); HCDIR("\\"," "); HMDIR("S2","S"); HMDIR("TOT SPECTRA","S"); HBOOK1(1,"S2 TOT T1", HiPar.STOT_Bins, HiPar.STOT_Min, HiPar.STOT_Max,0.); HBOOK1(2,"S2 TOT B1", HiPar.STOT_Bins, HiPar.STOT_Min, HiPar.STOT_Max,0.); HBOOK1(3,"S2 TOT T2", HiPar.STOT_Bins, HiPar.STOT_Min, HiPar.STOT_Max,0.); HBOOK1(4,"S2 TOT B2", HiPar.STOT_Bins, HiPar.STOT_Min, HiPar.STOT_Max,0.); HBOOK1(5,"S2 TOT T3", HiPar.STOT_Bins, HiPar.STOT_Min, HiPar.STOT_Max,0.); HBOOK1(6,"S2 TOT B3", HiPar.STOT_Bins, HiPar.STOT_Min, HiPar.STOT_Max,0.); HBOOK1(7,"S2 TOT T4", HiPar.STOT_Bins, HiPar.STOT_Min, HiPar.STOT_Max,0.); HBOOK1(8,"S2 TOT B4", HiPar.STOT_Bins, HiPar.STOT_Min, HiPar.STOT_Max,0.); HBOOK1(9,"S2 TOT T5", HiPar.STOT_Bins, HiPar.STOT_Min, HiPar.STOT_Max,0.); HBOOK1(10,"S2 TOT B5", HiPar.STOT_Bins, HiPar.STOT_Min, HiPar.STOT_Max,0.); HCDIR("\\"," "); HBOOK1(1,"S2 MULTIPLICITY (PM number)",10,0.5,10.5,0.); HBOOK1(2,"S2 LEADING EDGE MISSING (PM number)",10,0.5,10.5,0.); HBOOK1(3,"S2 TRAILING EDGE MISSING (PM number)",10,0.5,10.5,0.); HBOOK1(4,"SUM ALL TOT S2",512,0.5,2048.5,0.); HBOOK1(5,"NUMBER OF PHOTOMULTIPLIERS PER EVENT S2",11,-0.5,10.5,0.); HBOOK2(6,"Sum all TOT s2 vs D4x (wire number)", 128, 0.5, 512.5, 100, 0, 1000, 0.); HCDIR("\\"," "); return 0; } <file_sep>/* chamb_f2.c ---- MWDC F2 data analysis Version 1.00 10-JUL-2000 by <NAME> */ #include <stdio.h> #include <math.h> #include "freadin.h" #include "histogram.h" #include "analyzer.h" #include "matrix.h" #if F2_MWDC #define iswap(a,b) {i_swap=(a); (a)=(b); (b)=i_swap;} //FLAG /* Variable reference pointers */ static int h_mwire[N_MWDC_PL]; /* xxx_WIRE_xxx */ static int h_mwirer[N_MWDC_PL]; /* xxx_WIRER_xxx */ static int h_mtdc[N_MWDC_PL]; /* xxx_TDC_xxx */ static int h_mtdcr[N_MWDC_PL]; /* xxx_TDCR_xxx */ static int h_mnhit[N_MWDC_PL]; /* xxx_NHIT_xxx */ static char *mplnam[]= { "X1", "X2", "X3", "X4", "Y1", "Y2", "Y3", "Y4" }; struct chamber f2_mwdc; /* initialize data before an event (common)*/ int evt_init_f2() { chamb_init_chamb(&f2_mwdc); /* nothing to do */ } /* F2-3377 data analysis */ int evt_chamb_f2(){ int i; chamber_p chamb; plane_p plane; ray_p ray; chamb = &f2_mwdc; ray = &chamb->ray; for(i=0; i<chamb->npl; i++){ plane = &chamb->plane[i]; chamb_clust(plane); chamb_drift(plane); chamb_pos(plane); } chamb_ray(chamb); dr_set(F2_RAYID,ray->rayid); if(ray->rayid==RAYID_NOERR){ /* rotation of axes as z=central-ray */ ray_rotate_z(ray,dr_get(F2_MWDC_TILT[2])); ray_rotate_y(ray,dr_get(F2_MWDC_TILT[1])); ray_rotate_x(ray,dr_get(F2_MWDC_TILT[0])); /* output of ray information */ dr_set(F2_RAY_X[0], ray->org.x); dr_set(F2_RAY_Y[0], ray->org.y); dr_set(F2_TH[0],atan(ray->dir.x)); dr_set(F2_PH[0],atan(ray->dir.y)); /* projection to virtual planes */ chamb_intersection(chamb); } return(0); } /* initialization of data before data analysis */ int evt_start_f2(){ chamber_p chamb; plane_p plane; int i, ipl; double d; chamb = &f2_mwdc; #if DT2D_TAB chamb_get_dt2d_tab(chamb); #endif chamb_get_config(chamb); for(ipl=0; ipl<chamb->npl; ipl++){ plane = &chamb->plane[ipl]; plane->pres = 0.3; /* 0.3 mm resolution */ plane->fit = dr_is_true(dr_get(F2_FIT_PLANE[ipl])); } if(dr_exists(d=dr_get(F2_MAX_NCOMB))) chamb->max_ncomb = (int)d; chamb->allow_wireskip = dr_is_true(dr_get(F2_ALLOW_WIRESKIP)); d = dr_get(F2_N_VPLANE); chamb->nproj = dr_exists(d) ? min((int)d, MaxNIntPl) : 0; for(i=0; i<chamb->nproj; i++) dr_ref_n(spf("F2_PLANE_%d",i), &chamb->h_proj[i]); dr_ref_n("F2_X", &chamb->h_x); dr_ref_n("F2_Y", &chamb->h_y); return(0); } /* initialize variables */ int init_hist_f2(){ int i,n,ipl; chamber_p chamb; chamb = &f2_mwdc; chamb->name = "F2"; chamb->type = CHAMB_MWDC; chamb->npl = 8; chamb->plane = (plane_p)malloc(sizeof(plane_t)*chamb->npl); chamb->plane[0].name = "X1"; chamb->plane[1].name = "X2"; chamb->plane[2].name = "Y1"; chamb->plane[3].name = "Y2"; chamb->plane[4].name = "X3"; chamb->plane[5].name = "X4"; chamb->plane[6].name = "Y3"; chamb->plane[7].name = "Y4"; for(ipl=0; ipl<chamb->npl; ipl++){ chamb->plane[ipl].chamb = chamb; } chamb_init_hist(chamb); n = 1<<chamb->npl; chamb->matrix = (void*)malloc(sizeof(mat_p)*n); for(i=0; i<n; i++) ((mat_p*)chamb->matrix)[i] = (mat_p)NULL; chamb->mb = matrix_new(4,1); chamb->mc = matrix_new(4,1); if(chamb->matrix==NULL||chamb->mb==NULL||chamb->mc==NULL){ showerr("init_hist_np: No enough memory available\n"); exit(1); } return(0); } #endif /* if F2_MWDC */ /* Local Variables: mode: C tab-width: 2 End: */ <file_sep>/* mwdc_fit.c ---- mwdc rayfit Version 1.00 10-JUL-2000 by <NAME> */ #include <stdio.h> #include <math.h> #include "freadin.h" #include "histogram.h" #include "analyzer.h" #include "matrix.h" /*#get_matrix (get the inversion matrix for finding the ray*/ mat_p get_matrix(chamb) chamber_p chamb; { int h, hitpat; mat_p m; plane_p plane; wire_p wire; int i, j, ipl; double c,s,cc,ss,sc,z,zz; double a[4][4]; hitpat = chamb->hitpat; if(hitpat<0 || (1<<chamb->npl)<=hitpat){ showerr("Illegal hit pattern %.4x\n", hitpat); return((mat_p)NULL); } m = ((mat_p*)chamb->matrix)[hitpat]; /* if already error */ if(m==(mat_p)-1) return((mat_p)NULL); /* if already calculated */ if(m) return(m); /* create the matrix */ for(i=0; i<4; i++) for(j=0; j<4; j++) a[i][j]=0.; h = hitpat; for(ipl=0; ipl<chamb->npl; ipl++, h>>=1){ plane = &chamb->plane[ipl]; wire = &plane->wire; if(!(h&1)) continue; c = wire->dsp.x/wire->disp; s = wire->dsp.y/wire->disp; z = wire->org.z; sc = s*c; cc = c*c; ss = s*s; zz = z*z; a[0][0] += zz*cc; a[0][1] += z*cc; a[0][2] += zz*sc; a[0][3] += z*sc; a[1][0] += z*cc; a[1][1] += cc; a[1][2] += z*sc; a[1][3] += sc; a[2][0] += zz*sc; a[2][1] += z*sc; a[2][2] += zz*ss; a[2][3] += z*ss; a[3][0] += z*sc; a[3][1] += sc; a[3][2] += z*ss; a[3][3] += ss; } m = matrix_new(4,4); for(i=0; i<4; i++) for(j=0; j<4; j++) matrix_set(m,i,j,a[i][j]); /* solve the matrix */ if(matrix_solve_gaussj(m,NULL)<0){ #if MATRIX_DEBUG printf("Could not get the inversion matrix for [%.4X]\n", hitpat); #endif matrix_free(m); ((mat_p*)chamb->matrix)[hitpat] = (mat_p)-1; return((mat_p)NULL); } for(i=0; i<4; i++) for(j=0; j<4; j++){ c = fabs(matrix_get(m,i,j)); #if 1 if(c>1E+7){ #if MATRIX_DEBUG printf("Could not get the inversion matrix for [%.4X]\n", hitpat); matrix_showf(m,"%15.7e"); #endif ((mat_p*)chamb->matrix)[hitpat] = (mat_p)-1; return((mat_p)NULL); } #endif } ((mat_p*)chamb->matrix)[hitpat] = m; return(m); } /*#get_chi2*/ double get_chi2(chamb,ray) ray_p ray; chamber_p chamb; { int i, n, ipl; vec_rec pos; vec_rec v; double p, d, chi2; plane_p plane; clst_p clst; wire_p wire; chi2 = 0.0; n = 0; for(ipl=0; ipl<chamb->npl; ipl++){ plane = &chamb->plane[ipl]; clst = &plane->clst[plane->ic]; if(!plane->fit||dr_is_nothing(clst->pos)) continue; wire = &plane->wire; /* find hit point */ pos.x = ray->org.x + ray->dir.x/ray->dir.z*(wire->org.z-ray->org.z); pos.y = ray->org.y + ray->dir.y/ray->dir.z*(wire->org.z-ray->org.z); /* calc. wire position */ v.x = pos.x - wire->org.x; v.y = pos.y - wire->org.y; /* calc. deviation */ p = (v.x*wire->dsp.x+v.y*wire->dsp.y)/wire->disp; d = p - clst->pos; /* calc. chi2 */ d /= plane->pres; chi2 += d*d; n++; } /* chi2 per plane */ chi2 = n<=4 ? 1E10 : chi2/(n-4); return(chi2); } /* ray_mwdc_fit --- MWDC ray fit */ int ray_mwdc_fit(chamb) chamber_p chamb; { int ipl; plane_p plane; clst_p clst; wire_p wire; int i, n; double b[4]; double c,s,z,p; ray_t ray; double chi2; mat_p ma; for(i=0; i<4; i++) b[i] = 0.; ma = get_matrix(chamb); if(ma==(mat_p)NULL) return(RAYID_NOERR); /* return with 'no error' is correct */ for(ipl=0; ipl<chamb->npl; ipl++){ plane = &chamb->plane[ipl]; clst = &plane->clst[plane->ic]; if(dr_is_nothing(clst->pos)) continue; wire = &plane->wire; c = wire->dsp.x / wire->disp; s = wire->dsp.y / wire->disp; z = wire->org.z; p = clst->pos + wire->org.x * c + wire->org.y * s; b[0] += z*c*p; b[1] += c*p; b[2] += z*s*p; b[3] += s*p; n++; } for(i=0; i<4; i++) matrix_set(chamb->mb,i,0,b[i]); matrix_mul(chamb->mc,ma,chamb->mb); ray.dir.x = matrix_get(chamb->mc,0,0); ray.org.x = matrix_get(chamb->mc,1,0); ray.dir.y = matrix_get(chamb->mc,2,0); ray.org.y = matrix_get(chamb->mc,3,0); ray.dir.z = 1.; ray.org.z = 0.; chi2 = get_chi2(chamb,&ray); #if 0 printf("chi2 = %10.3f\n", chi2); #endif if(chi2<chamb->chi2){ chamb->ray = ray; chamb->ray.rayid = RAYID_NOERR; chamb->chi2 = chi2; } return(RAYID_NOERR); } /* Local Variables: mode: C tab-width: 2 End: */ <file_sep>for var in 1001 do ./offline -R "" temp $var done <file_sep>#include "GRAnalyzer.h" /* main */ int main() { start_analyzer("cat ./datatest/run6115.bld"); return 0; } <file_sep>/* chamb_rcnp.c ... rcnp chamber analysis Version 1.00 10-JUL-2000 by <NAME> */ #include <stdio.h> #include <stdlib.h> /* for drand48() */ #include <math.h> #include "freadin.h" #include "histogram.h" #include "analyzer.h" int gr_n_outputray = 0; FILE *fd_gr_outputray = (FILE*)NULL; int las_n_outputray = 0; FILE *fd_las_outputray = (FILE*)NULL; //FLAG struct chamber gr_vdc; struct chamber las_vdc; tbmat_p gr_xmat = (tbmat_p)NULL; tbmat_p gr_amat = (tbmat_p)NULL; tbmat_p gr_bmat = (tbmat_p)NULL; tbmat_p gr_ymat = (tbmat_p)NULL; tbmat_p gr_phmat = (tbmat_p)NULL; int n_gr_xmat = 0; int n_gr_amat = 0; int n_gr_bmat = 0; int n_gr_ymat = 0; int n_gr_phmat = 0; tbmat_p las_xmat = (tbmat_p)NULL; tbmat_p las_amat = (tbmat_p)NULL; int n_las_xmat = 0; int n_las_amat = 0; /* initialize data before an event (common)*/ int evt_init_rcnp() { /* nothing to do */ return 0; } /* initialize data before an event (for GR)*/ int evt_init_gr() { chamb_init_chamb(&gr_vdc); return 0; } /* initialize data before an event (for LAS)*/ int evt_init_las() { chamb_init_chamb(&las_vdc); return 0; } /* GR-3377 data analysis */ int evt_chamb_gr(){ int i; chamber_p chamb; plane_p plane; ray_p ray; ray_t ray2; double d; double shift; chamb = &gr_vdc; ray = &chamb->ray; if(!dr_exists(dr_get(GR_RAYID[0]))){ for(i=0; i<chamb->npl; i++){ plane = &chamb->plane[i]; chamb_clust(plane); chamb_drift(plane); chamb_pos(plane); } chamb_ray(chamb); dr_set(GR_RAYID,ray->rayid); dr_set(GR_CHI2[0],chamb->chi2); dr_set(GR_NCOMB[0],chamb->ncomb); if(ray->rayid==RAYID_NOERR){ // fprintf(stderr, "GRAD_X = %g\n", ray->dir.x); dr_set(GR_GRAD_X[0],ray->dir.x); dr_set(GR_GRAD_Y[0],ray->dir.y); /* rotation of axes as z=central-ray */ ray_rotate_z(ray,dr_get(GR_VDC_TILT[2])); ray_rotate_y(ray,dr_get(GR_VDC_TILT[1])); ray_rotate_x(ray,dr_get(GR_VDC_TILT[0])); /* output of tracking information */ if(gr_n_outputray) chamb_outputray(chamb,&fd_gr_outputray,FNAMGRRAY,&gr_n_outputray); /* output of ray information */ dr_set(GR_RAY_X[0], ray->org.x); dr_set(GR_RAY_Y[0], ray->org.y); dr_set(GR_RAY_TH[0],atan(ray->dir.x)); dr_set(GR_RAY_PH[0],atan(ray->dir.y)); } }else{ ray->org.x = dr_get(GR_RAY_X[0]); ray->org.y = dr_get(GR_RAY_Y[0]); ray->org.z = 0.0; ray->dir.x = tan(dr_get(GR_RAY_TH[0])); ray->dir.y = tan(dr_get(GR_RAY_PH[0])); ray->dir.z = 1.0; ray->rayid = dr_int(dr_get(GR_RAYID[0])); } if(ray->rayid==RAYID_NOERR){ /* projection to virtual planes */ chamb_intersection(chamb); if(dr_is_true(dr_get(ANALYZE_GR_MATRIX))){ /* trace-back by matrix x and y are in mm in the VDC cordinate system (GR_X[0] and GR_Y[0]) th and ph are in rad in the central ray cordinate system (GR_TH[0] and GR_PH[0]) */ ray2.org.x = dr_get(GR_X[0]); ray2.org.y = dr_get(GR_Y[0]); ray2.dir.x = dr_get(GR_TH[0]); ray2.dir.y = dr_get(GR_PH[0]); dr_set(GR_XC[0], trace_back(&ray2, gr_xmat, n_gr_xmat, 1)); dr_set(GR_AI[0], trace_back(&ray2, gr_amat, n_gr_amat, 1)); dr_set(GR_BI[0], trace_back(&ray2, gr_bmat, n_gr_bmat, 1)); dr_set(GR_YC[0], trace_back(&ray2, gr_ymat, n_gr_ymat, 1)); dr_set(GR_PHC[0],trace_back(&ray2, gr_phmat, n_gr_phmat, 1)); } } return(0); } /* LAS-3377 data analysis */ int evt_chamb_las(){ double f1, f2; int i; chamber_p chamb; plane_p plane; ray_p ray; chamb = &las_vdc; ray = &chamb->ray; for(i=0; i<chamb->npl; i++){ plane = &chamb->plane[i]; chamb_clust(plane); chamb_drift(plane); chamb_pos(plane); } /* Temporary for E154 03-MAY-2006 */ i = chamb->npl; chamb->npl = 4; chamb_ray(chamb); chamb->npl = i; dr_set(LAS_RAYID,ray->rayid); dr_set(LAS_CHI2[0],chamb->chi2); dr_set(LAS_NCOMB[0],chamb->ncomb); if(ray->rayid==RAYID_NOERR){ /* trace-back by matrix (with the VDC coordingate space) */ dr_set(LAS_DP[0],trace_back(ray, las_xmat, n_las_xmat, 0)); dr_set(LAS_AI[0],trace_back(ray, las_amat, n_las_amat, 0)/1000.); dr_set(LAS_GRAD_X[0], ray->dir.x/ray->dir.z); dr_set(LAS_GRAD_Y[0], ray->dir.y/ray->dir.z); /* rotation of axes as z=central-ray */ ray_rotate_z(ray,dr_get(LAS_VDC_TILT[2])); ray_rotate_y(ray,dr_get(LAS_VDC_TILT[1])); ray_rotate_x(ray,dr_get(LAS_VDC_TILT[0])); /* output of tracking information */ if(las_n_outputray) chamb_outputray(chamb,&fd_las_outputray,FNAMLASRAY,&las_n_outputray); /* output of ray information */ dr_set(LAS_RAY_X[0], ray->org.x); dr_set(LAS_RAY_Y[0], ray->org.y); dr_set(LAS_RAY_TH[0],atan(ray->dir.x)); dr_set(LAS_RAY_PH[0],atan(ray->dir.y)); /* projection to virtual planes */ chamb_intersection(chamb); } return(0); } /* get GR trace-back matrix */ int get_gr_matrix(){ int n; int i; /* get matrix for x */ n = get_tb_matrix("GR_XMAT", &gr_xmat); if(n>0) n_gr_xmat = n; /* get matrix for a */ n = get_tb_matrix("GR_AMAT", &gr_amat); if(n>0) n_gr_amat = n; //for(i=0; i<20; i++) // fprintf(stderr, "GR_AMAT_%02d = %15.3E\n", i+1, gr_amat[i].c); /* get matrix for b */ n = get_tb_matrix("GR_BMAT", &gr_bmat); if(n>0) n_gr_bmat = n; //for(i=0; i<20; i++) //fprintf(stderr, "GR_BMAT_%02d = %15.3E\n", i+1, gr_bmat[i].c); /* get matrix for y */ n = get_tb_matrix("GR_YMAT", &gr_ymat); if(n>0) n_gr_ymat = n; /* get matrix for ph */ n = get_tb_matrix("GR_PHMAT", &gr_phmat); if(n>0) n_gr_phmat = n; return(0); } /* get LAS trace-back matrix */ int get_las_matrix(){ int n; /* get matrix for x */ n = get_tb_matrix("LAS_XMAT", &las_xmat); if(n>0) n_las_xmat = n; /* get matrix for a */ n = get_tb_matrix("LAS_AMAT", &las_amat); if(n>0) n_las_amat = n; return(0); } /* initialization of data before data analysis */ int evt_start_rcnp(){ double d; int i, cmin, cmax, ipl; chamber_p chamb; plane_p plane; /* common */ #if !DT2D_TAB get_dt2d_prm(); #endif /* for GR */ if(dr_is_true(dr_get(ANALYZE_GR))){ cmax = dr_exists(d=dr_get(GR_VDC_MAX_CLUST_SIZE)) ? min(dr_int(d),Clst_MaxClstSize) : Clst_DefMaxClstSize; cmin = dr_exists(d=dr_get(GR_VDC_MIN_CLUST_SIZE)) ? dr_int(d) : Clst_DefMinClstSize; chamb = &gr_vdc; #if DT2D_TAB chamb_get_dt2d_tab(chamb); #endif chamb_get_config(chamb); d = dr_get(DEBUG_GR_N_OUTPUTRAY); gr_n_outputray = dr_exists(d) ? (int)d : 0; if(dr_is_true(dr_get(ANALYZE_GR_MATRIX))){ get_gr_matrix(); } for(ipl=0; ipl<chamb->npl; ipl++){ plane = &chamb->plane[ipl]; plane->min_clst_size = cmin; plane->max_clst_size = cmax; plane->ana_2hit_clst = dr_is_true(dr_get(GR_VDC_ANA_2HIT_CLUST)); /* angular resolution of a plane */ plane->ares = dr_get(GR_ARES[ipl])*d2r; if(dr_is_nothing(plane->ares)) plane->ares = 1.05*d2r; /* default */ } chamb->ana_mult_clst = dr_is_true(dr_get(GR_VDC_ANA_MULTI_CLUST)); chamb->max_chi2 = dr_get(GR_VDC_MAX_CHI2); if(dr_is_nothing(chamb->max_chi2)) chamb->max_chi2 = 0.; d = dr_get(GR_N_VPLANE); chamb->nproj = dr_exists(d) ? min((int)d, MaxNIntPl) : 0; for(i=0; i<chamb->nproj; i++) dr_ref_n(spf("GR_PLANE_%d",i), &chamb->h_proj[i]); dr_ref_n("GR_XP", &chamb->h_x); /* projection points */ dr_ref_n("GR_YP", &chamb->h_y); /* projection points */ fprintf(stderr, "GR VDC multi-cluster analysis = %s\n", chamb->ana_mult_clst ? "ON" : "OFF"); fprintf(stderr, "GR VDC 2-hit cluster analysis = %s\n", chamb->plane[0].ana_2hit_clst ? "ON" : "OFF"); fprintf(stderr, "GR VDC cluster size = %d <= nhit <= %d\n", cmin, cmax); } /* for LAS */ if(dr_is_true(dr_get(ANALYZE_LAS))){ cmax = dr_exists(d=dr_get(LAS_VDC_MAX_CLUST_SIZE)) ? min(dr_int(d),Clst_MaxClstSize) : Clst_DefMaxClstSize; cmin = dr_exists(d=dr_get(LAS_VDC_MIN_CLUST_SIZE)) ? dr_int(d) : Clst_DefMinClstSize; chamb = &las_vdc; #if DT2D_TAB chamb_get_dt2d_tab(chamb); #endif chamb_get_config(chamb); d = dr_get(DEBUG_LAS_N_OUTPUTRAY); las_n_outputray = dr_exists(d) ? (int)d : 0; get_las_matrix(); for(ipl=0; ipl<chamb->npl; ipl++){ plane = &chamb->plane[ipl]; plane->min_clst_size = cmin; plane->max_clst_size = cmax; plane->ana_2hit_clst = dr_is_true(dr_get(LAS_VDC_ANA_2HIT_CLUST)); /* angular resolution of a plane */ plane->ares = dr_get(LAS_ARES[ipl])*d2r; if(dr_is_nothing(plane->ares)) plane->ares = 1.05*d2r; /* default */ } d = dr_get(LAS_N_VPLANE); chamb->nproj = dr_exists(d) ? min((int)d, MaxNIntPl) : 0; for(i=0; i<chamb->nproj; i++) dr_ref_n(spf("LAS_PLANE_%d",i), &chamb->h_proj[i]); dr_ref_n("LAS_XP", &chamb->h_x); /* projection points */ dr_ref_n("LAS_YP", &chamb->h_y); /* projection points */ chamb->ana_mult_clst = dr_is_true(dr_get(LAS_VDC_ANA_MULTI_CLUST)); chamb->max_chi2 = dr_get(LAS_VDC_MAX_CHI2); if(dr_is_nothing(chamb->max_chi2)) chamb->max_chi2 = 0.; fprintf(stderr, "LAS VDC multi-cluster analysis = %s\n", chamb->ana_mult_clst ? "ON" : "OFF"); fprintf(stderr, "LAS VDC cluster size = %d <= nhit <= %d\n", cmin, cmax); } return(0); } /* initialize variables */ int init_hist_rcnp() { chamber_p chamb; int ipl; /* initialyze for GR VDC */ chamb = &gr_vdc; chamb->name = "GR"; chamb->type = CHAMB_VDC; chamb->npl = 4; chamb->plane = (plane_p)malloc(sizeof(plane_t)*chamb->npl); chamb->plane[0].name = "X1"; chamb->plane[1].name = "U1"; chamb->plane[2].name = "X2"; chamb->plane[3].name = "U2"; for(ipl=0; ipl<chamb->npl; ipl++){ chamb->plane[ipl].chamb = chamb; } chamb_init_hist(chamb); /* initialyze for LAS VDC */ chamb = &las_vdc; chamb->name = "LAS"; chamb->type = CHAMB_VDC; #if 0 chamb->npl = 4; chamb->plane = (plane_p)malloc(sizeof(plane_t)*chamb->npl); chamb->plane[0].name = "X1"; chamb->plane[1].name = "U1"; chamb->plane[2].name = "X2"; chamb->plane[3].name = "U2"; #endif #if 1 /* 04-JUL-2005 use UV planes */ chamb->npl = 4; chamb->plane = (plane_p)malloc(sizeof(plane_t)*chamb->npl); chamb->plane[0].name = "U1"; chamb->plane[1].name = "V1"; chamb->plane[2].name = "U2"; chamb->plane[3].name = "V2"; #endif #if 0 /* 04-JUL-2005 use XUV planes (tracking does not work)*/ chamb->npl = 6; chamb->plane = (plane_p)malloc(sizeof(plane_t)*chamb->npl); chamb->plane[0].name = "U1"; chamb->plane[1].name = "V1"; chamb->plane[2].name = "U2"; chamb->plane[3].name = "V2"; chamb->plane[4].name = "X1"; chamb->plane[5].name = "X2"; #endif for(ipl=0; ipl<chamb->npl; ipl++){ chamb->plane[ipl].chamb = chamb; } chamb_init_hist(chamb); return 0; } /* Local Variables: mode: C tab-width: 2 End: */ <file_sep>/* chamb_gr_fpp.c ---- GR FPP Analysis Version 1.00 10-JUL-2000 by <NAME> */ #include <stdio.h> #include <stdlib.h> /* for drand48() */ #include <math.h> #include "freadin.h" #include "histogram.h" #include "analyzer.h" //FLAG struct chamber gr_fpp_in; struct chamber gr_fpp_out; extern struct chamber gr_vdc; /* initialize data before an event (for GR)*/ int evt_init_gr_fpp() { chamb_init_chamb(&gr_fpp_in); chamb_init_chamb(&gr_fpp_out); return 0; } int set_vertex_pos(chamber_p chamb, int ipl1, int ipl2) { ray_p ray; vec_rec a; vec_rec plane; vec_rec dir; ray = &gr_vdc.ray; if(ray->rayid!=RAYID_NOERR) return -1; // carbon block center plane plane.x = dr_get(GF_V_POS[0]); // z position plane.y = dr_get(GF_V_POS[1]); // tilting angle (theta) plane.z = dr_get(GF_V_POS[2]); // tilting angle (phi) if(!dr_exists(plane.x)) return -1; if(!dr_exists(plane.y)) return -1; if(!dr_exists(plane.z)) return -1; if(ray_intersection_pt(ray, &plane, &a)<0) return -1; // fprintf(stderr, "intersection (%7.3f,%7.3f,%7.3f)\n", a.x, a.y, a.z); dir.x = 0.0; dir.y = 1.0; dir.z = 0.0; chamb->m[ipl1][0] = dir.y; chamb->m[ipl1][1] = -dir.x; chamb->m[ipl1][2] = dir.y*a.z; chamb->m[ipl1][3] = -dir.x*a.z; chamb->m[ipl1][4] = dir.y*a.x - dir.x*a.y; dir.x = 1.0; dir.y = 0.0; dir.z = 0.0; chamb->m[ipl2][0] = dir.y; chamb->m[ipl2][1] = -dir.x; chamb->m[ipl2][2] = dir.y*a.z; chamb->m[ipl2][3] = -dir.x*a.z; chamb->m[ipl2][4] = dir.y*a.x - dir.x*a.y; return 0; } double chi2_func(ray_p ray) { vec_rec p; double dist; double vd_res; double vx_res; double vy_res; double chi2; vec_rec x1; vec_rec x2; vec_rec plane; vec_rec dir; // carbon block center plane plane.x = dr_get(GF_V_POS[0]); // z position plane.y = dr_get(GF_V_POS[1]); // tilting angle (theta) plane.z = dr_get(GF_V_POS[2]); // tilting angle (phi) if(!dr_exists(plane.x)) return -1; if(!dr_exists(plane.y)) return -1; if(!dr_exists(plane.z)) return -1; if(gr_vdc.ray.rayid!=RAYID_NOERR) return -1; if(ray_intersection_pt(ray, &plane, &x1)<0) return -1; if(ray_intersection_pt(&gr_vdc.ray, &plane, &x2)<0) return -1; if(ray_vertex(ray, &gr_vdc.ray, &p, &dist)!=0) return -1; if(!dr_exists(dist)||dist<0) return -1; vd_res = dr_get(GF_VD_RES); vx_res = dr_get(GF_VX_RES); vy_res = dr_get(GF_VY_RES); chi2 = 0.0; if(dr_exists(vd_res)) chi2 += dist*dist/(vd_res*vd_res); if(dr_exists(vx_res)) chi2 += (x1.x-x2.x)*(x1.x-x2.x)/(vx_res*vx_res); if(dr_exists(vy_res)) chi2 += (x1.y-x2.y)*(x1.y-x2.y)/(vy_res*vy_res); //fprintf(stderr, "chi2=%7.3f\n", chi2); return chi2; } /* GR-FPP data analysis */ int evt_chamb_gr_fpp(){ int i; chamber_p chamb; plane_p plane; ray_p ray; vec_rec p; double dist; double ath, aph, hor, ver; #if 0 /* incoming ray X1,X2 */ chamb = &gr_fpp_in; ray = &chamb->ray; for(i=0; i<chamb->npl; i++){ plane = &chamb->plane[i]; chamb_clust(plane); chamb_drift(plane); chamb_pos(plane); } #endif #if 0 chamb_ray(chamb); dr_set(GF_RAYID,ray->rayid); if(ray->rayid==RAYID_NOERR){ /* rotation of axes as z=central-ray */ ray_rotate_z(ray,dr_get(GF_IN_TILT[2])); ray_rotate_y(ray,dr_get(GF_IN_TILT[1])); ray_rotate_x(ray,dr_get(GF_IN_TILT[0])); /* output of tracking information */ /* output of ray information */ dr_set(GF_RAY_X[0], ray->org.x); dr_set(GF_RAY_Y[0], ray->org.y); dr_set(GF_TH[0],atan(ray->dir.x)); dr_set(GF_PH[0],atan(ray->dir.y)); /* projection to virtual planes */ chamb_intersection(chamb); } #endif /* outgoing ray U3,V3,U4,V4 */ chamb = &gr_fpp_out; ray = &chamb->ray; dr_set_nothing(&chamb->anapat); if(!dr_exists(dr_get(GF_RAYID[0]))){ for(i=0; i<chamb->npl; i++){ plane = &chamb->plane[i]; chamb_clust(plane); chamb_drift(plane); chamb_pos(plane); } if(chamb->ana_mult_clst){ #if 0 ray_4p_fpp_v(chamb, set_vertex_pos); #else ray_4p_fpp_mult(chamb, chi2_func); #endif }else{ chamb_ray(chamb); } dr_set(GF_RAYID,ray->rayid); dr_set(GF_ANA_PAT,chamb->anapat); dr_set(GF_CHI2,chamb->chi2); if(ray->rayid==RAYID_NOERR){ /* rotation of axes as z=central-ray */ ray_rotate_z(ray,dr_get(GF_OUT_TILT[2])); ray_rotate_y(ray,dr_get(GF_OUT_TILT[1])); ray_rotate_x(ray,dr_get(GF_OUT_TILT[0])); /* output of ray information */ dr_set(GF_OUT_RAY_X[0], ray->org.x); dr_set(GF_OUT_RAY_Y[0], ray->org.y); dr_set(GF_OUT_TH[0],atan(ray->dir.x)); dr_set(GF_OUT_PH[0],atan(ray->dir.y)); } }else{ ray->org.x = dr_get(GF_OUT_RAY_X[0]); ray->org.y = dr_get(GF_OUT_RAY_Y[0]); ray->org.z = 0.0; ray->dir.x = tan(dr_get(GF_OUT_TH[0])); ray->dir.y = tan(dr_get(GF_OUT_PH[0])); ray->dir.z = 1.0; ray->rayid = dr_int(dr_get(GF_RAYID[0])); } if(ray->rayid==RAYID_NOERR){ /* projection to virtual planes */ chamb_intersection(chamb); /* vetex point and the scattering angle */ if(gr_vdc.ray.rayid==RAYID_NOERR){ if(ray_vertex(ray,&gr_vdc.ray,&p,&dist)==0){ dr_set(GF_VERTEX_X[0], p.x); dr_set(GF_VERTEX_Y[0], p.y); dr_set(GF_VERTEX_Z[0], p.z); } dr_set(GF_DIST[0], dist); /* if error, error code is saved in 'dist' */ /* The argument order of ray_vertex has been corrected on 08-AUG-2006 */ if(ray_scat_ang(&gr_vdc.ray,ray,&ath,&aph,&hor,&ver)==0){ /* scattering angle (all in radian) */ dr_set(GF_SCAT_TH[0], ath); /* scattering angle (polar angle) */ dr_set(GF_SCAT_PH[0], aph); /* scattering angle (azimuthal angle) */ dr_set(GF_SCAT_DX[0], hor); /* scattering angle (horizontal) */ dr_set(GF_SCAT_DY[0], ver); /* scattering angle (vertical) */ } } } return(0); } /* initialization of data before data analysis */ int evt_start_gr_fpp(){ double d; int i, cmin, cmax, ipl; chamber_p chamb; plane_p plane; cmin = 1; cmax = 10; #if 0 if(dr_is_true(dr_get(ANALYZE_GR_FPP))){ #else if(1){ #endif chamb = &gr_fpp_in; chamb_get_config(chamb); for(ipl=0; ipl<chamb->npl; ipl++){ plane = &chamb->plane[ipl]; plane->min_clst_size = cmin; plane->max_clst_size = cmax; } d = dr_get(GF_IN_N_VPLANE); chamb->nproj = dr_exists(d) ? min((int)d, MaxNIntPl) : 0; for(i=0; i<chamb->nproj; i++) dr_ref_n(spf("GF_IN_PLANE_%d",i), &chamb->h_proj[i]); dr_ref_n("GF_IN_X", &chamb->h_x); dr_ref_n("GF_IN_Y", &chamb->h_y); chamb = &gr_fpp_out; chamb_get_config(chamb); for(ipl=0; ipl<chamb->npl; ipl++){ plane = &chamb->plane[ipl]; plane->min_clst_size = cmin; plane->max_clst_size = cmax; } chamb->ana_mult_clst = dr_is_true(dr_get(GF_ANA_MULTI_CLUST)); chamb->max_chi2 = dr_get(GF_MAX_CHI2); chamb->max_ncomb = dr_get(GF_MAX_NCOMB); chamb->max_nclust = dr_get(GF_MAX_NCLUST); if(dr_is_nothing(chamb->max_chi2)) chamb->max_chi2 = 0.; d = dr_get(GF_OUT_N_VPLANE); chamb->nproj = dr_exists(d) ? min((int)d, MaxNIntPl) : 0; for(i=0; i<chamb->nproj; i++) dr_ref_n(spf("GF_OUT_PLANE_%d",i), &chamb->h_proj[i]); dr_ref_n("GF_OUT_X", &chamb->h_x); dr_ref_n("GF_OUT_Y", &chamb->h_y); } return 0; } /* initialize variables */ int init_hist_gr_fpp() { chamber_p chamb; int ipl; chamb = &gr_fpp_in; chamb->name = "GF"; chamb->type = CHAMB_MWPC; chamb->npl = 2; chamb->plane = (plane_p)malloc(sizeof(plane_t)*chamb->npl); chamb->plane[0].name = "X1"; chamb->plane[1].name = "X2"; for(ipl=0; ipl<chamb->npl; ipl++){ chamb->plane[ipl].chamb = chamb; } chamb_init_hist(chamb); chamb = &gr_fpp_out; chamb->name = "GF"; chamb->type = CHAMB_MWPC; chamb->npl = 4; chamb->plane = (plane_p)malloc(sizeof(plane_t)*chamb->npl); chamb->plane[0].name = "U3"; chamb->plane[1].name = "V3"; chamb->plane[2].name = "U4"; chamb->plane[3].name = "V4"; for(ipl=0; ipl<chamb->npl; ipl++){ chamb->plane[ipl].chamb = chamb; } chamb_init_hist(chamb); return 0; } /* Local Variables: mode: C tab-width: 2 End: */ <file_sep>/* matrix.c .... matrix manipulation utilities */ /* Author: <NAME>, Department of Physics, Univ. of Tokyo */ /* version 1.0 01-JAN-1999 by <NAME> */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include "matrix.h" static mat_val mat_temp; #define SWAP(a,b) {mat_temp=(a); (a)=(b); (b)=mat_temp;} #if MATRIX_DEBUG /*#matrix_error ... show error */ static void matrix_error(func, message) char *func; char *message; { fprintf(stderr, "Error in %s(): %s\n", func, message); } #else #define matrix_error(f,m) {} #endif #if MATRIX_DEBUG /*#matrix_set ... set a matrix element (for debug)*/ void matrix_set(m, ir, ic, v) mat_p m; int ir; int ic; double v; { if(!m){ matrix_error("matrix_set", "null pointer."); return; } if(ir<0 || m->nr<=ir){ matrix_error("matrix_set", "ir outof range."); return; } if(ic<0 || m->nc<=ic){ matrix_error("matrix_set", "ic outof range."); return; } m->m[ir][ic] = v; } /*#matrix_get ... get a matrix element (for debug)*/ double matrix_get(m, ir, ic) mat_p m; int ir; int ic; { if(!m){ matrix_error("matrix_get", "null pointer."); return(-1); } if(ir<0 || m->nr<=ir){ matrix_error("matrix_get", "ir outof range."); return(-1); } if(ic<0 || m->nc<=ic){ matrix_error("matrix_get", "ic outof range."); return(-1); } return(m->m[ir][ic]); } #endif /*#matrix_new ... get new matrix structure */ /* return a pointer to the new matrix */ /* return with NULL, when failier */ mat_p matrix_new(nr, nc) int nr; /* number of rows */ int nc; /* number of columns */ { mat_p m; int i; mat_val **p; mat_val *rp; m = (mat_p)malloc(sizeof(matrix)); if(m==(mat_p)NULL){ matrix_error("matrix_new", "could not allocate memory."); return(NULL); } m->nr = m->nc = 0; m->m = (mat_val**)NULL; m->rm = (mat_val*)NULL; p = (mat_val**)malloc(sizeof(mat_val*)*nr); if(p==(mat_val**)NULL){ matrix_error("matrix_new", "could not allocate memory."); free(m); return(NULL); } rp = (mat_val*)malloc(sizeof(mat_val)*nr*nc); if(rp==(mat_val*)NULL){ matrix_error("matrix_new", "could not allocate memory."); free(p); free(m); return(NULL); } m->m = p; m->rm = rp; for(i=0; i<nr; i++){ *p++ = rp; rp += nc; } m->nr = nr; m->nc = nc; return(m); } /*#matrix_free ... free a matrix structure */ /* return a null pointer */ mat_p matrix_free(m) mat_p m; { if(!m){ matrix_error("matrix_free", "null pointer."); }else{ if(m->m) free(m->m); if(m->rm) free(m->rm); free(m); } return((mat_p)NULL); } /*#matrix_showf ... show matrix with format*/ int matrix_showf(m, format) mat_p m; char *format; { int nr, nc; int i, j; if(!m){ matrix_error("matrix_showf", "null pointer."); return(-1); } nr = m->nr; nc = m->nc; for(i=0; i<nr; i++){ for(j=0; j<nc; j++){ printf(format, m->m[i][j]); } printf("\n"); } return(0); } /*#matrix_show ... show matrix */\ int matrix_show(m) mat_p m; { return(matrix_showf(m,"%10.5lf")); } /*#matrix_set_zero ... set zero matrix */ int matrix_set_zero(m) mat_p m; { int i, n; mat_val *p; if(!m){ matrix_error("matrix_set_zero", "null pointer."); return(-1); } n = m->nr * m->nc; p = *m->m; for(i=0; i<n; i++) *p++ = 0; return(0); } /*#matrix_set_unity ... set the unit matrix */ int matrix_set_unity(m) mat_p m; { int nr, nc; int i, j; if(!m){ matrix_error("matrix_set_unity", "null pointer."); return(-1); } nr = m->nr; nc = m->nc; for(i=0; i<nr; i++) for(j=0; j<nc; j++) m->m[i][j] = (i==j); if(nr!=nc){ matrix_error("matrix_set_unity", "not square matrix."); return(-1); } return(0); } /*#matrix_copy_new ... create a new copy of a matirx */ mat_p matrix_copy_new(src) mat_p src; { int i, n; mat_p dst; mat_val *d, *s; if(!src){ matrix_error("matrix_copy_new", "null pointer."); return((mat_p)NULL); } dst = matrix_new(src->nr, src->nc); if(!dst) return((mat_p)NULL); n = src->nr * src->nc; s = *src->m; d = *dst->m; for(i=0; i<n; i++) *d++ = *s++; return(dst); } /*#matrix_copy ... copy a matirx */ int matrix_copy(dst, src) mat_p dst, src; { int i, n; mat_val *d, *s; if(!dst){ matrix_error("matrix_copy", "null pointer (dst)."); return(-1); } if(!src){ matrix_error("matrix_copy", "null pointer (src)."); return(-1); } if(dst->nr!=src->nr || dst->nc!=src->nc){ matrix_error("matrix_copy", "matrix dimensions are inconsistent."); return(-1); } n = src->nr * src->nc; s = *src->m; d = *dst->m; for(i=0; i<n; i++) *d++ = *s++; return(0); } /*#matrix_mul ... multiply matrix (y=axb) */ /* y must not be the same as a nor b */ int matrix_mul(y, a, b) mat_p y, a, b; { int i, j, k; int nr, nc, nk; mat_val v; if(!y || !a || !b){ matrix_error("matrix_mul", "null pointer (y, a, or b)."); return(-1); } if(y->nr!=a->nr || y->nc!=b->nc || a->nc != b->nr){ matrix_error("matrix_mul", "matrix dimensions are inconsistent."); return(-1); } nr = y->nr; nc = y->nc; nk = a->nc; for(i=0; i<nr; i++){ for(j=0; j<nc; j++){ v = 0; for(k=0; k<nk; k++){ v += a->m[i][k] * b->m[k][j]; } y->m[i][j] = v; } } return(0); } /*#matrix_add ... add matrix (y=a+b) */ /* y must not be the same as a nor b */ int matrix_add(y, a, b) mat_p y, a, b; { int i, j; int nr, nc; mat_val v; if(!y || !a || !b){ matrix_error("matrix_add", "null pointer (y, a, or b)."); return(-1); } nr = y->nr; nc = y->nc; if(a->nr!=nr || a->nc!=nc || b->nr!=nr || b->nc!=nc){ matrix_error("matrix_add", "matrix dimensions are inconsistent."); return(-1); } for(i=0; i<nr; i++){ for(j=0; j<nc; j++){ y->m[i][j] = a->m[i][j] + b->m[i][j]; } } return(0); } /*#matrix_sub ... sub matrix (y=a-b) */ /* y must not be the same as a nor b */ int matrix_sub(y, a, b) mat_p y, a, b; { int i, j; int nr, nc; mat_val v; if(!y || !a || !b){ matrix_error("matrix_sub", "null pointer (y, a, or b)."); return(-1); } nr = y->nr; nc = y->nc; if(a->nr!=nr || a->nc!=nc || b->nr!=nr || b->nc!=nc){ matrix_error("matrix_sub", "matrix dimensions are inconsistent."); return(-1); } for(i=0; i<nr; i++){ for(j=0; j<nc; j++){ y->m[i][j] = a->m[i][j] - b->m[i][j]; } } return(0); } /*#matrix_solve_gaussj */ /* ... solve the equation b=ax by Gauss-Jordan ellimination method */ /* The inverse matrix is returned in the matrix a. */ /* The solution is return in the matrix b. */ /* The result of the matrix m becomes unity if successfully solved. */ /* if b is a null pointer, this function returns only inversion of a. */ /* return value: 0 ... successfully solved */ /* -1 ... failed */ /* reference: Numerical Recipes in C 2nd Edition, pp.39. */ int matrix_solve_gaussj(a, b) mat_p a; mat_p b; { int m, n; int i, j, k, l, ll; int ir, ic; int *idr, *idc, *ipiv; mat_val big, f; if(!a){ matrix_error("matrix_solve_gaussj", "null pointer."); return(-1); } n = a->nr; m = b ? b->nc : 0; if(a->nc!=n){ matrix_error("matrix_solve_gaussj", "the matrix a is not square matrix."); return(-1); } if(b && b->nr!=n){ matrix_error("matrix_solve_gaussj", "matrix dimensions of a and b are inconsistent."); return(-1); } idr = (int*)malloc(sizeof(int)*n); idc = (int*)malloc(sizeof(int)*n); ipiv = (int*)malloc(sizeof(int)*n); for(i=0; i<n; i++) ipiv[i] = 0; for(i=0; i<n; i++){ big = 0.0; for(j=0; j<n; j++){ if(!ipiv[j]){ for(k=0; k<n; k++){ if(!ipiv[k]){ if(fabs(a->m[j][k])>=big){ big=fabs(a->m[j][k]); ir = j; ic = k; } }else if(ipiv[k]>1){ matrix_error("matrix_solve_gaussj", "singular matrix-1."); free(idr); free(idc); free(ipiv); return(-1); } } } } ipiv[ic]++; if(ir!=ic){ for(l=0; l<n; l++) SWAP(a->m[ir][l],a->m[ic][l]) for(l=0; l<m; l++) SWAP(b->m[ir][l],b->m[ic][l]) } idr[i] = ir; idc[i] = ic; if(fabs(a->m[ic][ic])<=1E-30){ matrix_error("matrix_solve_gaussj", "singular matrix-2."); free(idr); free(idc); free(ipiv); return(-1); } f = 1.0/a->m[ic][ic]; a->m[ic][ic] = 1.0; for(l=0; l<n; l++) a->m[ic][l] *= f; for(l=0; l<m; l++) b->m[ic][l] *= f; for(ll=0; ll<n; ll++){ if(ll == ic) continue; f = a->m[ll][ic]; a->m[ll][ic] = 0.0; for(l=0; l<n; l++) a->m[ll][l] -= a->m[ic][l]*f; for(l=0; l<m; l++) b->m[ll][l] -= b->m[ic][l]*f; } } for(l=n-1; l>=0; l--){ if(idr[l] != idc[l]){ for(k=0; k<n; k++){ SWAP(a->m[k][idr[l]],a->m[k][idc[l]]); } } } free(idr); free(idc); free(ipiv); return(0); } /* Local Variables: mode: C tab-width: 2 End: */ <file_sep>/* matrix.h .... header for matrix manipulation utilities */ /* Author: <NAME>, Department of Physics, Univ. of Tokyo */ /* version 1.0 01-JAN-1999 by <NAME> */ #ifndef MATRIX_DEBUG #define MATRIX_DEBUG 0 #endif #if defined (__cplusplus) extern "C" { #endif typedef double mat_val; typedef struct matrix{ int nr; /* number of rows */ int nc; /* number of columns */ mat_val **m; /* pointers to the rows */ mat_val *rm; /* pointers to the matrix elements */ } matrix, *mat_p; #if MATRIX_DEBUG void matrix_set(mat_p m, int ir, int ic, double v); double matrix_get(mat_p m, int ir, int ic); #else #define matrix_set(mat,ir,ic,v) {((mat_p)mat)->m[(ir)][(ic)]=(v);} #define matrix_get(mat,ir,ic) (((mat_p)mat)->m[(ir)][(ic)]) #endif #define matrix_get_nr(mat) ((mat)->nr) #define matrix_get_nc(mat) ((mat)->nc) mat_p matrix_new(int nr, int nc); mat_p matrix_free(mat_p m); int matrix_showf(mat_p m, char *format); int matrix_show(mat_p m); int matrix_set_unity(mat_p m); int matrix_set_zero(mat_p m); int matrix_copy(mat_p dst, mat_p src); mat_p matrix_copy_new(mat_p src); int matrix_mul(mat_p y, mat_p a, mat_p b); int matrix_add(mat_p y, mat_p a, mat_p b); int matrix_sub(mat_p y, mat_p a, mat_p b); int matrix_solve_gaussj(mat_p a, mat_p b); #if defined (__cplusplus) } #endif <file_sep>/* mwpc.c ---- MWPC data analysis Version 1.00 03-JUL-2001 by <NAME> */ #include <stdio.h> #include <math.h> #include "freadin.h" #include "histogram.h" #include "analyzer.h" //FLAG /* MWPC Clusterize (Not much thing to do....) */ int chamb_mwpc_clust(plane) plane_p plane; { int min, max; int i, j, n, s, w, nhit; int *p; static int n_half_bit_err=200; static int n_too_many_cluster_err=200; clst_p clst; if(plane==(plane_p)NULL){ fprintf(stderr, "evt_mwdc_clust: null plane pointer\n"); return(-1); } min = dr_min_ref(plane->h_wire); max = dr_max_ref(plane->h_wire); /* Get data */ n=0; nhit = 0; for(i=min; i<max; i++){ w = dr_int(dr_get_ref(plane->h_wire,i)); s = dr_int(dr_get_ref(plane->h_clstsz,i)); clst = &plane->clst[n++]; if(((w+s)&0x01)==0){ if(n_half_bit_err-->0){ fprintf(stderr, "chamb_mwpc_clust: pcos half bit inconsistency in %s-%s (wire=%d,width=%d)\n", plane->chamb->name, plane->name, w, s); if(n_half_bit_err==0) fprintf(stderr, "chamb_mwpc_clust: too many same type of errors. Hereafter ignore it.\n"); } }else{ if(s>plane->max_clst_size){ if(0) fprintf(stderr, "chamb_mwpc_clust: too large cluster (size=%d). The size is reduced to %d.\n", s, plane->max_clst_size); s = plane->max_clst_size; } for(j=0; j<s; j++){ clst->wire[j] = w; dr_append_ref(plane->h_wirer,((w-s)>>1)+j); } } clst->size = s; nhit += s; clst->pos = w/2.; /* /2 is for the half bit */ clst->posid = POSID_NOERR; #if 1 dr_append_ref(plane->h_pos, clst->pos); #endif if(n>=Clst_MaxNClst){ if(n_too_many_cluster_err-->0){ fprintf(stderr, "evt_mwdc_clust: too many clusters (%d)\n", max-min); if(n_too_many_cluster_err==0) fprintf(stderr, "chamb_mwpc_clust: too many same type of errors. Hereafter ignore it.\n"); } break; } } plane->nc = n; dr_set_ref(plane->h_nhit,0,nhit); dr_set_ref(plane->h_nclst,0,n); if(n==0) dr_append_ref(plane->h_posid, POSID_NOCLUST); else if(n==1){ #if 0 dr_append_ref(plane->h_pos, plane->clst[0].pos); #endif dr_append_ref(plane->h_posid, POSID_NOERR); } else dr_append_ref(plane->h_posid, POSID_MCLUST+n); return(0); } /* MWPC Position Calculation */ int chamb_mwpc_pos(plane) plane_p plane; { /* nothing to do */ return(0); } /* Local Variables: mode: C tab-width: 2 End: */ <file_sep>/* fread_rcnp.c --- rawdata readout program for analyzer (rcnp TAMIDAQ format) Author: <NAME> Facility: Department of Physics, University of Tokyo Created: 04-MAY-1997 by <NAME> Version 1.00 04-MAY-1997 by <NAME> (fread) Version 1.22 06-MAY-1997 by <NAME> (fread) Version 2.00 03-JUN-2000 by <NAME> Version 2.10 07-JAN-2008 by <NAME> (Uchida format comment conversion with byte swap) Version 2.20 04-NOV-2014 by <NAME> (for V830) */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #ifdef OSF1 #include <strings.h> #endif #include <time.h> #include <stdarg.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <signal.h> #include <errno.h> #include "freadin.h" #include "histogram.h" #include "analyzer.h" #include "mtformat.h" #include "lr3377.h" #include "fera.h" #include "pcos.h" #include "v1190.h" #include "madc32.h" //FLAG extern int neval; extern int level; extern int swap; extern int byte_order; int parse_error; extern int pflag; extern int cflag; extern int nrun; extern int nblk; extern int cblk; static int nevt = 0; int nblk_add = 0; int nblk_flag = 0; #define USE_SEQ_NUMBER_IN_DATA 1 // Use block number and event number in the data static char *module[16] = { "Irregal ", "VDC-OLD ", "NIM-IN ", "ADC ", "TDC ", "PCOS-OLD", "Scaler ", "LR3377 ", "Reserved", "VDC ", "PCOS ", "ADC-LAS ", "TDC-LAS ", "FERA ", "FERET ", "CheckSum" }; static char *fera_name[16] = { "GR_FERA_ADC", "LAS_FERA_ADC", "GSO_FERA_ADC", "SSD_FERA_ADC", "GR_3351_ADC", "LAS_3351_ADC", "GSO_3351_ADC", "SSD_3351_ADC", "GR_FERA_TDC", "LAS_FERA_TDC", "GSO_FERA_TDC", "SSD_FERA_TDC", "GR_3351_TDC", "LAS_3351_TDC", "GSO_3351_TDC", "SSD_3351_TDC" }; static int h_fera_data_id[16]; //-- Added on 2017.1.25 by <NAME> static int get_qtc_ch(geo,ch){ // modified on 2017.1.20 if(geo<0 || geo==2 || geo==6 || 8<=geo) return -1; // correct // if(geo<0 || 8<=geo) return -1; // wrong for U1 and U2 channel 0-15 if(ch<96 || 112<=ch) return -1; return (geo*16+(ch-96)); } //-- End added #if 1 // 13-July-2014 #define V1190_BASE_TIME_CH (127) #define V1190_BASE_TIME_CH2 (0) #define V1190_BUFCH_CH (126) #else #define V1190_BASE_TIME_CH (112) #endif /* read region */ static int read_rgn(buf, size) unsigned short *buf; int size; { unsigned short *ptr, *tp, *te; unsigned short *rgn, *pv; lr3377_header lr3377; lr3377_mid lr3377mid; fera_header fera; fera_data fdata; pcos_data pcos; int nrgn; int rgn_size; unsigned int rgn_id, rgn_32bits; int i; int type, id; int data; double ddata; double pdata; //-- added on 2017.1.25 by <NAME> int idata; // --- newer code 2016.11.9 according to the discussion with Y. Watanabe --- // inserted on 2017.1.25 by <NAME> int mid; int pl; int ch; int qtc_ch, detector_ch; int wire, w, wire2; V1190_DATA_t v1190; int geo=0; int base_time[V1190_MAX_N_MODULES]; unsigned long long time_stamp; MADC32_HEADER_SIGNATURE_p madc32_signature; MADC32_DATA_HEADER_p madc32_header; MADC32_DATA_EVENT_p madc32_event; MADC32_EXTENDED_TIME_STAMP_p madc32_extended_time_stamp; MADC32_FILL_p madc32_fill; MADC32_END_OF_EVENT_p madc32_end_of_event; int madc_geo, madc_ch, madc_amplitude,j; ptr = buf; te = &buf[size]; nrgn = 0; while(ptr < te){ rgn = ptr; nrgn++; /* get the next region header */ rgn_id = *rgn & ModuleIDMask; rgn_size = *rgn & DataLengthMask; #if 0 showerr("data = %xH\n", *rgn); #endif rgn++; /* check the region header */ switch(rgn_id){ case ID_Reserved: showerr("Illegal region ID. ID = %xH\n", rgn_id); if(ptr < te){ /* search the next field header */ showerr(" ... Searching for the next Region Header\n"); for(; rgn<te; rgn++){ rgn_id = *rgn>>12; break; } rgn_size = ((long)rgn-(long)ptr)/2-1; } break; case ID_NimIn: for(i=0; i<rgn_size && rgn<te; i++){ dr_append(IPR,*rgn++); } break; case ID_MADC32: for(i=0; i<rgn_size/2 && rgn<te; i++){ // rgn = 'data block', te = 'last element of data block' rgn_32bits = rgn[0] | (rgn[1]<<16); // convert 16 bits rgn to 32 bits, as our words rgn += 2; // move to the next word for next iteration over the event madc32_signature = (MADC32_HEADER_SIGNATURE_p)&rgn_32bits; switch(madc32_signature->header){ case MADC32_HEADER_SIGNATURE_HEADER: madc32_header = (MADC32_DATA_HEADER_p)&rgn_32bits; madc_geo = madc32_header->module_id; break; case MADC32_HEADER_SIGNATURE_DATA: switch(madc32_signature->subheader){ case MADC32_SUBHEADER_EVENT: madc32_event = (MADC32_DATA_EVENT_p)&rgn_32bits; madc_ch = madc32_event->channel_number; madc_amplitude = madc32_event->adc_amplitude; switch (madc_geo){ case 0: dr_append(MADC32_0_CH, madc_ch); dr_append(MADC32_0_ADC, (double)madc_amplitude); break; case 1: dr_append(MADC32_1_CH, madc_ch); dr_append(MADC32_1_ADC, (double)madc_amplitude); break; case 2: dr_append(MADC32_2_CH, madc_ch); dr_append(MADC32_2_ADC, (double)madc_amplitude); break; } break; case MADC32_SUBHEADER_EXTENDED_TIME_STAMP: // unused at the moment break; case MADC32_SUBHEADER_FILL: // unused at the moment break; } break; case MADC32_HEADER_SIGNATURE_END_OF_EVENT: // unused at the moment break; } } break; case ID_MYRIAD: if(rgn_size==4){ rgn++; // skip the MyRIAD Header time_stamp = ((unsigned long long)(rgn[0])<<32) | ((unsigned long long)(rgn[1])<<16) | ((unsigned long long)(rgn[2])<< 0); rgn+=3; dr_append(GR_MYRIAD, (double)time_stamp); }else{ fprintf(stderr, "Unexpected MyRIAD data length (%d)\n", rgn_size); } break; case ID_V830: for(i=0; i<rgn_size && rgn<te; i+=2){ dr_append(GR_V830, (rgn[0] | (rgn[1]<<16))); rgn+=2; } break; case ID_ADC_LAS: for(i=0; i<rgn_size && rgn<te; i++){ dr_append(LAS_ADC_OLD, *rgn++); } break; case ID_TDC_LAS: for(i=0; i<rgn_size && rgn<te; i++){ dr_append(LAS_TDC_OLD, (*rgn++ & 0x0FFF)); } break; case ID_3377: // break; // 26-APR-2013 cut 3377 data type = -1; for(i=0; i<rgn_size && rgn<te; i++){ *(short*)&lr3377 = *rgn++; if(lr3377.hdr){ type = lr3377.id >> 4; id = (lr3377.id & 0x000f)<<5; }else{ ch = ((lr3377_data*)&lr3377)->ch; wire = id+ch; data = ((lr3377_data*)&lr3377)->data; switch(type){ case 0x00: dr_append(GR_WIRE_X1, (double)wire); dr_append(GR_TDC_X1, (double)data); break; case 0x01: dr_append(GR_WIRE_BASE, (double)wire); dr_append(GR_TDC_BASE, (double)data); break; case 0x02: dr_append(GR_WIRE_U1, (double)wire); dr_append(GR_TDC_U1, (double)data); break; case 0x03: dr_append(GR_WIRE_V1, (double)wire); dr_append(GR_TDC_V1, (double)data); break; case 0x04: dr_append(GR_WIRE_X2, (double)wire); dr_append(GR_TDC_X2, (double)data); break; case 0x05: dr_append(GR_WIRE_Y2, (double)wire); dr_append(GR_TDC_Y2, (double)data); break; case 0x06: dr_append(GR_WIRE_U2, (double)wire); dr_append(GR_TDC_U2, (double)data); break; case 0x07: dr_append(GR_WIRE_V2, (double)wire); dr_append(GR_TDC_V2, (double)data); break; case 0x08: dr_append(LAS_WIRE_X1, (double)wire); dr_append(LAS_TDC_X1, (double)data); break; case 0x09: /* E154 05DEC */ w = wire & 0x3f; switch(wire>>6){ case 0x00: dr_append(LF_WIRE_X1, (double)w); dr_append(LF_TDC_X1, (double)data); break; case 0x01: dr_append(LF_WIRE_X2, (double)w); dr_append(LF_TDC_X2, (double)data); break; case 0x02: dr_append(LF_WIRE_X3, (double)w); dr_append(LF_TDC_X3, (double)data); break; case 0x03: dr_append(LF_WIRE_X4, (double)w); dr_append(LF_TDC_X4, (double)data); break; } break; case 0x0a: if(wire<50 || 200<=wire){ break; } dr_append(LAS_WIRE_U1, (double)wire); dr_append(LAS_TDC_U1, (double)data); break; case 0x0b: if(wire<50 || 200<=wire){ break; } dr_append(LAS_WIRE_V1, (double)wire); dr_append(LAS_TDC_V1, (double)data); break; case 0x0c: dr_append(LAS_WIRE_X2, (double)wire); dr_append(LAS_TDC_X2, (double)data); break; case 0x0d: /* E154 05DEC */ w = (wire & 0x3e)>>1; switch((wire>>6)*2+(wire&0x01)){ case 0x00: dr_append(LF_WIRE_Y1, (double)w); dr_append(LF_TDC_Y1, (double)data); break; case 0x01: dr_append(LF_WIRE_Y2, (double)w); dr_append(LF_TDC_Y2, (double)data); break; case 0x02: /* folowing order of Y4 and Y3 is correct */ dr_append(LF_WIRE_Y4, (double)w); dr_append(LF_TDC_Y4, (double)data); break; case 0x03: dr_append(LF_WIRE_Y3, (double)w); dr_append(LF_TDC_Y3, (double)data); break; } break; case 0x0e: if(wire<50 || 200<=wire){ break; } dr_append(LAS_WIRE_U2, (double)wire); dr_append(LAS_TDC_U2, (double)data); break; case 0x0f: if(wire<50 || 200<=wire){ break; } dr_append(LAS_WIRE_V2, (double)wire); dr_append(LAS_TDC_V2, (double)data); break; default: showerr("Unsupported 3377 Type (%d)\n", type); rgn++; break; } } } break; /////////////////////////////////////////////////////////////////////////////// case ID_V1190: pv = rgn; for(i=0; i<V1190_MAX_N_MODULES; i++){ base_time[i] = -10000; } for(i=0; i<rgn_size/2 && pv<te; i++){ v1190.idata = pv[0] | (pv[1]<<16); pv += 2; switch(v1190.global_header.id){ case V1190_HEADER_ID_GH: geo = v1190.global_header.geo; break; case V1190_HEADER_ID_TM: wire = v1190.tdc_measurement.channel; data = v1190.tdc_measurement.measurement; #if 0 fprintf(stderr, "Module geo= %1d, Wire = %3d, data = %7d\n",geo, wire, data); #endif if(geo<8){ // GR time reference is in chan 127 if(wire==V1190_BASE_TIME_CH && !v1190.tdc_measurement.trailing){ base_time[geo] = data; dr_set(V1190BASE[geo],data); } } else if(geo>7 && geo<22){ // LAS X1 plane, 3rd module is a particular case (even and chan 127) if (wire==V1190_BASE_TIME_CH && (geo==10) && !v1190.tdc_measurement.trailing){ base_time[geo] = data; dr_set(V1190BASE[geo],data); } // LAS odd geo modules time reference is in chan 127 else if(wire==V1190_BASE_TIME_CH && (geo%2 == 1) && !v1190.tdc_measurement.trailing){ base_time[geo] = data; dr_set(V1190BASE[geo],data); } // LAS even geo modules time reference is in chan 0 else if(wire==V1190_BASE_TIME_CH2 && (geo%2 == 0) && !v1190.tdc_measurement.trailing){ base_time[geo] = data; dr_set(V1190BASE[geo],data); } } #if 0 else if(wire==V1190_BUFCH_CH){ dr_set(BUFCH[geo],data); } #endif } } for(i=0; i<rgn_size/2 && rgn<te; i++){ v1190.idata = rgn[0] | (rgn[1]<<16); rgn += 2; switch(v1190.global_header.id){ case V1190_HEADER_ID_GH: geo = v1190.global_header.geo; break; case V1190_HEADER_ID_TM: ch = v1190.tdc_measurement.channel; //if(base_time[geo]<-1000) //fprintf(stderr, "no base time for geo %d\n", geo); #if 1 // --- newer code 2016.11.9 according to the discussion with <NAME> --- // inserted on 2017.1.25 by <NAME> idata = (v1190.tdc_measurement.measurement - base_time[geo])&0x7FFFF; if(idata>=0x40000) idata -= 0x80000; ddata = idata/10.0; #else // ---older code--- ddata = (v1190.tdc_measurement.measurement - base_time[geo])/10.0; #endif wire = v1190_wire_map(geo,ch); wire2 = (geo%2)*128+ch; dr_append(V1190_RAW_CH, geo*128+wire); dr_append(V1190_RAW_TDC, v1190.tdc_measurement.measurement); ddata = -ddata; // for online VDC2013 25-SEP-2013 // if QTC //qtc_ch = (get_qtc_ch(geo,ch))%16; // only 16 chan at the moment if (geo==0 && (ch>=96 && ch<112)) { qtc_ch = ch%16; if(v1190.tdc_measurement.trailing) { dr_append(QTC_TRAILING_CH, qtc_ch); dr_append(QTC_TRAILING_TDC, v1190.tdc_measurement.measurement - base_time[geo]); } else { dr_append(QTC_LEADING_CH, qtc_ch); dr_append(QTC_LEADING_TDC, v1190.tdc_measurement.measurement - base_time[geo]); } } //-- Added on 2017.1.25 by Tamii qtc_ch = get_qtc_ch(geo,ch); if(qtc_ch>=0){ ddata = v1190.tdc_measurement.measurement - base_time[geo]; if(v1190.tdc_measurement.trailing){ pdata = dr_get(QTC_TRAILING[qtc_ch]); if(dr_is_nothing(pdata) || pdata>ddata){ // use the first data dr_set(QTC_TRAILING[qtc_ch], ddata); } }else{ pdata = dr_get(QTC_LEADING[qtc_ch]); if (dr_is_nothing(pdata) || pdata>ddata){ // use the first data dr_set(QTC_LEADING[qtc_ch], ddata); } } } //-- if(ch==V1190_BUFCH_CH){ dr_set(BUFCH[geo], ddata); } // if we have a leading that is not from other stuff if(!v1190.tdc_measurement.trailing){ if(wire>=0 && geo<8){ switch(v1190_plane_map(geo,ch)){ case 0: // X1 Plane dr_append(GR_WIRE_X1, (double)wire); dr_append(GR_TDC_X1, ddata); break; case 1: // U1 Plane dr_append(GR_WIRE_U1, (double)wire); dr_append(GR_TDC_U1, ddata); break; case 2: // X2 Plane dr_append(GR_WIRE_X2, (double)wire); dr_append(GR_TDC_X2, ddata); break; case 3: // U2 Plane dr_append(GR_WIRE_U2, (double)wire); dr_append(GR_TDC_U2, ddata); break; } } else if(geo>7 && geo<22){//for LAS VDC modified 19-Apr-2016 switch((int)(geo/2)){ case 4://X1 plane dr_append(LAS_WIRE_X1, (double)wire2); dr_append(LAS_TDC_X1, ddata); break; case 5://X1 plane, 3rd module wire2 = 128+16+ch; // ECL plugged on D input dr_append(LAS_WIRE_X1, (double)wire2); dr_append(LAS_TDC_X1, ddata); break; case 6://U1 plane dr_append(LAS_WIRE_U1, (double)wire2); dr_append(LAS_TDC_U1, ddata); break; case 7://V1 plane dr_append(LAS_WIRE_V1, (double)wire2); dr_append(LAS_TDC_V1, ddata); break; case 8://X2 plane dr_append(LAS_WIRE_X2, (double)wire2); dr_append(LAS_TDC_X2, ddata); break; case 9://U2 plane dr_append(LAS_WIRE_U2, (double)wire2); dr_append(LAS_TDC_U2, ddata); break; case 10://V2 plane dr_append(LAS_WIRE_V2, (double)wire2); dr_append(LAS_TDC_V2, ddata); break; } } /*else if(geo == 24){ detector_ch = ch; if(v1190.tdc_measurement.trailing) { dr_append(SSD_TRAI_CH, detector_ch); dr_append(SSD_TRAI_TDC, v1190.tdc_measurement.measurement - base_time[geo]); } else { dr_append(SSD_LEAD_CH, detector_ch); dr_append(SSD_LEAD_TDC, v1190.tdc_measurement.measurement - base_time[geo]); } }*/ } break; case V1190_HEADER_ID_TH: case V1190_HEADER_ID_TT: case V1190_HEADER_ID_TE: case V1190_HEADER_ID_ETTT: case V1190_HEADER_ID_GT: case V1190_HEADER_ID_FILLER: break; } } break; /////////////////////////////////////////////////////////////////////////////// case ID_FERA_ADC: case ID_FERA_TDC: type = 0; mid = 0; for(i=0; i<rgn_size && rgn<te; i++){ *(short*)&fera = *rgn; if(fera.hdr){ type = (fera.vsn & 0x00f0) >> 4; mid = fera.vsn & 0x000f; rgn++; }else{ *(short*)&fdata = *rgn++; dr_set_r(&dr_data,&h_fera_data_id[type],fera_name[type], mid*16+fdata.ch, fdata.data); } } break; case ID_Scaler: for(i=0; i<rgn_size; i+=2){ if((rgn+1)>=te) break; if(byte_order==BIG_ENDIAN){ ((short*)&data)[1] = *rgn++; ((short*)&data)[0] = *rgn++; }else{ ((short*)&data)[0] = *rgn++; ((short*)&data)[1] = *rgn++; } dr_append(SCALER, data); } break; case ID_CHKSUM: break; default: //showerr("Never come here. Region ID= %xH\n", rgn_id>>12); break; } tp = &ptr[rgn_size+1]; if(tp>te){ showerr("Errorr in region size. size = %xH\n", rgn_size); } /* advance to the next region */ ptr += rgn_size+1; } return nrgn; } /* read field */ static int read_fld(buf, size) unsigned short *buf; int size; { unsigned short *ptr, *tp, *te; FldHeaderPtr fld; int nfld, nrgn; int fld_size; int chksum, *sump; ptr = buf; te = &buf[size]; nfld = 0; while(ptr < te){ /* search the next field header */ if(*ptr != FldHeaderID){ showerr("Searching for the next Field Header\n"); while(ptr < te){ if(*ptr==FldHeaderID) break; ptr++; } } if(ptr >= te) break; /* check the field header */ nfld++; fld = (FldHeaderPtr)ptr; if(fld->headerID != FldHeaderID){ showerr("Error in field header ID. ID = %xH\n", fld->headerID); } if(fld->headerSize != sizeof(FldHeader)/2){ showerr("Error in filed header size. ID = %xH\n", fld->headerSize); } if((fld->fieldID & ~7)!= FieldID){ showerr("Error in field ID. ID = %xH\n", fld->fieldID); } tp = &ptr[fld->headerSize+fld->fieldSize]; if(tp>te || (tp<te && *tp!=FldHeaderID) ){ showerr("Error in field size. size = %xH\n", fld->fieldSize); } ptr += fld->headerSize; #if CHKSUM /* check sum */ chksum = 0; sump = ptr; while(sump<te) chksum += *sump++; if(chksum!=0){ showerr("Field check sum error. Sum = %xH\n", chksum); } #endif /* check the regions */ if(ptr<=te){ nrgn = read_rgn(ptr, fld->fieldSize); } /* advance to the next field */ ptr += fld->fieldSize; } return nfld; } /* read_evt */ static int read_evt(buf, size) unsigned short *buf; int size; { unsigned short *ptr, *tp, *te; EvtHeaderPtr evt; int nfld; int evt_size; ptr = buf; te = &buf[size]; nevt = 0; while(1){ if(*ptr == BlkTrailerID) break; /* search the next event header */ if(*ptr != EvtHeaderID){ showerr("Searching for the next event header\n"); while(ptr < te){ if(*ptr==EvtHeaderID || *ptr==BlkTrailerID) break; ptr++; } } if(ptr >= te || *ptr == BlkTrailerID ) break; /* read the event header */ nevt++; evt = (EvtHeaderPtr)ptr; if(evt->headerID != EvtHeaderID){ showerr("Error in event header ID. ID = %xH\n", evt->headerID); } if(evt->headerSize != sizeof(EvtHeader)/2){ showerr("Error in event header size. size = %xH\n", evt->headerSize); } if(evt->eventID != DataEvent && evt->eventID != BlockEndEvent){ showerr("Error in event ID. ID = %xH\n", evt->eventID); } tp = &ptr[evt->headerSize+evt->eventSize]; if(tp>te){ showerr("Error in event size. size = %xH\n", evt->eventSize); break; } if(tp<te && *tp != EvtHeaderID && *tp != BlkTrailerID ){ showerr("Error in event size. size = %xH\n", evt->eventSize); } if(evt->eventNumber != nevt-1){ showerr("Error in event number. number = %d\n", evt->eventNumber); nevt = evt->eventNumber+1; showerr(" ... Adjust the event number.\n"); } ptr += evt->headerSize; dr_clear(); dr_set(RUN_N[0], nrun); #if USE_SEQ_NUMBER_IN_DATA dr_set(EVENT_N[0], evt->eventNumber); dr_set(BLOCK_N[0], nblk); #else dr_set(EVENT_N[0], nevt); dr_set(BLOCK_N[0], nblk); #endif dr_set(EVENT_RCNP[0], 1); /* read the fields */ if(ptr<=te){ nfld= read_fld(ptr, evt->eventSize); if(evt->numFields != nfld){ showerr("Error in the number of fields. num. of fields = %d\n", evt->numFields); } } if(pflag){ }else{ dr_event(); } /* advance to the next event */ ptr += evt->eventSize; } return nevt; } static void strncpy_uchida(dst, src, len) unsigned char *dst; unsigned short *src; int len; { int i; char c; for(i=0; i<len; i++){ c = (*src++) & 0x00ff; if(c==0x0a) continue; *dst++ = c; if(c==0x00) break; } } /* read comment block */ static int read_com(buf, size) unsigned short *buf; int size; { RunCommentPtr com; time_t t; unsigned int time2; char str[MaxComLen+10]; char sstr[MaxComLen+10]; com = (RunCommentPtr)buf; if(size<sizeof(RunComment)/2){ showerr("Error in comment block size\n"); return -1; } /*--- The following parts were modified on 07-JAN-2008 for Uchida-system and proper treatment of the byte-swap ---*/ if(swap){ //swaps(&com->version); //swaps(&com->time); }else{ swaps(&com->byte); } /* copy and convert the comment from Uchida version to normal one */ strncpy_uchida((unsigned char*)str, (unsigned short*)com->comment, MaxComLen); //if(swap) // swab(str, sstr, MaxComLen); strncpy(sstr, str, MaxComLen); if(swap) swaps(&com->time); // for Uchida version t = (time_t)com->time; /*---- End of modification on 07-JAN-2008 ---*/ printf("Format Ver = %d.%d\n", com->version>>8, com->version&0x00FF); printf("Byte Order = %x\n", com->byte); printf("Time Stamp = %s", ctime(&t)); printf("Run Number = %d\n", com->run); printf("Comment = %s\n", sstr); nrun = com->run; return 0; } /* read block */ int read_blk_rcnp(buf, size) unsigned short *buf; int size; { unsigned short *ptr; BlkHeaderPtr blk; BlkTrailerPtr trl; ptr = buf; /* check the block header */ blk = (BlkHeaderPtr)ptr; if(blk->headerID != BlkHeaderID){ showerr("Error in block header ID. ID = %xH\n", blk->headerID); } if(blk->headerSize != sizeof(BlkHeader)/2 && blk->headerSize != sizeof(BlkHeaderV3)/2){ showerr("Error in block header size. size = %xH\n", blk->headerSize); } switch(blk->blockID){ case DataBlockID+0: /* Crate 0 */ case DataBlockID+1: /* Crate 1 */ case DataBlockID+2: /* Crate 2 */ case DataBlockID+3: /* Crate 3 */ case DataBlockID+4: /* Crate 4 */ case DataBlockID+5: /* Crate 5 */ case DataBlockID+6: /* Crate 6 */ case DataBlockID+7: /* Crate 7 */ case ScalerBlockID: break; case StartBlockID: printf("Run Start Block\n"); break; case EndBlockID: printf("Run End Block\n"); break; default: showerr("Unknown block ID. ID = %xH\n", blk->blockID); } #if 0 if(blk->blockSize32 > size-sizeof(BlkHeader)/2){ showerr("Error in block size. size = %xH\n", blk->blockSize32); } #endif if((blk->blockID & ~7)==DataBlockID){ /* for counting blocks above 65535 */ if(nblk_flag){ if(blk->blockNumber<0x08000){ nblk_flag = 0; nblk_add += 0x10000; } }else{ if(blk->blockNumber>=0x08000){ nblk_flag = 1; } } nblk++; if(blk->blockNumber != (nblk&0xFFFF)){ #if 0 showerr("Error in block number. number = %d, should be %d\n", blk->blockNumber, nblk); showerr(" ... Adjust the block number.\n"); #endif nblk = blk->blockNumber+nblk_add; } } ptr += blk->headerSize; #if 0 fprintf(stderr, "Block = %d\n", nblk); #endif /* read information block */ switch(blk->blockID){ case StartBlockID: read_com(ptr, size-sizeof(BlkHeader)/2); // nblk--; cblk++; return(0); case EndBlockID: read_com(ptr, size-sizeof(BlkHeader)/2); nblk--; cblk++; #if ENDRUNBLK showerr("Avoid the rest of files. \n"); return(1); #else save_scalers(); save_histograms(); return(0); #endif } /* read events */ if(!evt_blk(nblk)&&!pflag){ /* chack analyze block range */ //if(!evt_blk(nblk)){ /* chack analyze block range */ (void)read_evt(ptr, size-(sizeof(BlkHeader)+sizeof(BlkTrailer))/2); if(blk->numEvents != nevt){ showerr("Inconsistent event number. number = %d, detected events = %d\n", blk->numEvents, nevt); } } ptr += (blk->blockSize32_l|(blk->blockSize32_u<<16)) - sizeof(BlkTrailer)/2; /* read block trailer */ if(&ptr[sizeof(BlkTrailer)/2]>&buf[size]){ showerr("Incomplete block trailer.\n"); }else{ trl = (BlkTrailerPtr)ptr; if(trl->trailerID != BlkTrailerID){ showerr("Error in block trailer ID. ID = %x\n", trl->trailerID); fprintf(stderr, "block number = %d, ptr = %lx\n", nblk, (size_t)ptr-(size_t)buf); } if(trl->trailerSize != sizeof(BlkTrailer)/2){ showerr("Error in block trailer size. size = %d\n", trl->trailerSize); } } return(0); } /* Local Variables: mode: C tab-width: 2 End: */ <file_sep>/* vdc.c ---- VDC data analysis Version 1.00 10-JUL-2000 by <NAME> Version 1.10 21-MAY-2004 by <NAME> (Add offset to TDC) */ #include <stdio.h> #include <stdlib.h> /* for drand48() */ #include <math.h> #include "freadin.h" #include "histogram.h" #include "analyzer.h" #define iswap(a,b) {i_swap=(a); (a)=(b); (b)=i_swap;} static int i_swap; //FLAG /* VDC Clusterize */ int chamb_vdc_clust(plane) plane_p plane; { double f1, f2; int min, max; int i, j, k, l, m, n, w, t, wp; int *p; int ss, se, id, idp; int tdc[Clst_MaxNData]; int wire[Clst_MaxNData]; int nc; if(plane==(plane_p)NULL){ fprintf(stderr, "evt_vdc_clust: null plane pointer\n"); return(-1); } min = dr_min_ref(plane->h_wire); max = dr_max_ref(plane->h_wire); /* Get TDC data (accept one hit for each wire) */ n=0; wp=-1; for(i=max-1; i>=min; i--){ /* Use reverse order for sorting to be faster */ w = dr_int(dr_get_ref(plane->h_wire,i)); t = dr_int(dr_get_ref(plane->h_tdc,i)); if(w==wp) continue; /* take the first tdc data if multi-hits in a wire */ wp = w; if(n>=Clst_MaxNData){ // fprintf(stderr, "evt_vdc_clust: too many wire hits (>%d)\n", // Clst_MaxNData); break; } wire[n] = w; tdc[n] = t; n++; } dr_set_ref(plane->h_nhit,0,n); /* Sort TDC data */ ss=0; idp=-1; for(i=0; i<n; i++){ id = wire[i]>>5; if(id==idp) continue; se = i-1; while(ss<se){ /* reverse the order */ iswap(wire[ss],wire[se]); iswap(tdc[ss],tdc[se]); ss++; se--; } idp = id; ss = i; } se = i-1; while(ss<se){ /* reverse the order */ iswap(wire[ss],wire[se]); iswap(tdc[ss],tdc[se]); ss++; se--; } if(1){ /* check */ ss = -1; p = wire; for(i=0; i<n; i++){ if(ss<*p){ ss = *p++; continue; } //fprintf(stderr, "evt_vdc_clust: 3377 sorting error in %s of %s\n", // plane->name, plane->chamb->name); //for(j=0; j<n; j++) // fprintf(stderr, "%d ", wire[j]); //fprintf(stderr, "\n"); //fprintf(stderr, "Re-sort\n"); /* bubble sort */ for(j=0; j<n-1; j++){ for(l=j+1; l<n; l++){ if(wire[j]>wire[l]){ iswap(wire[j],wire[l]); iswap(tdc[j],tdc[l]); } } } break; } } for(i=0; i<n; i++){ #if 1 /* 21-MAY-2004 */ tdc[i] += plane->tab.offset; #endif dr_append_ref(plane->h_wirer,wire[i]); dr_append_ref(plane->h_tdcr,tdc[i]); } /* Clustering TDC data */ nc = 0; ss=0; p=wire; k=n-1; for(i=0; i<n; i++){ j = *p++; #if VDC_ALLOW_HITSKIP if(i==k || (j+1!=*p && j+2!=*p)) #else if(i==k || j+1!=*p) #endif { if(nc>=Clst_MaxNClst){ if(0){ fprintf(stderr, "evt_vdc_clust: too many clusters in %s of %s (>%d)\n", plane->name, plane->chamb->name, Clst_MaxNClst); } break; } m = i-ss+1; if(m<plane->min_clst_size){ ss = i+1; continue; } if(m>plane->max_clst_size){ if(0) fprintf(stderr, "evt_vdc_clust: too large cluster size (%d)\n", m); m = plane->max_clst_size; } plane->clst[nc].size = m; dr_append_ref(plane->h_clstsz,m); for(j=0; j<m; j++){ plane->clst[nc].wire[j] = wire[ss]; plane->clst[nc].tdc[j] = tdc[ss]; ss++; } nc++; ss = i+1; } } plane->nc = nc; dr_set_ref(plane->h_nclst,0,nc); return(0); } /* VDC Position Calculation */ int chamb_vdc_pos(plane) plane_p plane; { struct clst *clst; double dist[Clst_MaxClstSize]; int wire[Clst_MaxClstSize]; int i, ic, n, mid, size; double m, mx, my, mx2, mxy; double slope; double mind; int mini; if(plane==(plane_p)NULL){ fprintf(stderr, "evt_pos: null plane pointer\n"); return(-1); } if(plane->nc<=0){ dr_append_ref(plane->h_posid, POSID_NOCLUST); return(-1); } /* initialize */ for(ic=0; ic<plane->nc && ic<Clst_MaxNClst; ic++){ clst = &plane->clst[ic]; clst->posid = POSID_UNDEF; clst->pos = 0.; } /* save time if multi clusters are not analyzed */ if(!plane->chamb->ana_mult_clst){ if(plane->nc>=2){ dr_append_ref(plane->h_posid, POSID_MCLUST+plane->nc); return(-1); } } for(ic=0; ic<plane->nc && ic<Clst_MaxNClst; ic++){ clst = &plane->clst[ic]; n = clst->size; clst->posid = POSID_UNDEF; /* ignore unresolved drift distance */ size = 0; mind = 1e+10; mini = -1; for(i=0; i<n; i++){ #if DEBUG_TEMP && 0 fprintf(stderr, "clst->dist[%d]=%f\n", i, clst->dist[i]); #endif if(dr_exists(clst->dist[i])){ dist[size] = clst->dist[i]; wire[size] = clst->wire[i]; if(dist[size]<mind){ mind = dist[size]; mini = size; } size++; } } #if 0 /* neglect the minimum distance wire */ for(i=mini; i<size-1; i++){ dist[i] = dist[i+1]; wire[i] = wire[i+1]; } size--; #endif /* check monotone increase/decrease */ /* note: 'size' might be smaller than the value deteremined in the clusterinsing stage when the drift time to distance conversion fails. */ switch(size){ case 0: dr_append_ref(plane->h_posid, clst->posid=POSID_NOHIT); break; case 1: dr_append_ref(plane->h_posid, clst->posid=POSID_1HIT); break; case 2: if(plane->ana_2hit_clst){ slope = (double)(wire[1]-wire[0])/(dist[0]+dist[1]); clst->pos = wire[0]+slope*dist[0]; clst->grad = slope*plane->wire.sc; dr_append_ref(plane->h_pos, clst->pos); dr_append_ref(plane->h_grad, clst->grad); dr_append_ref(plane->h_posid, clst->posid=POSID_NOERR); }else{ dr_append_ref(plane->h_posid, clst->posid=POSID_2HIT); } break; } if(clst->posid!=POSID_UNDEF) continue; #if 0 /* for debug */ fprintf(stderr, "before dist (%d)= \n",pl); for(i=0; i<size; i++){ fprintf(stderr, "%5d %9.5f\n", i, dist[i]); } #endif for(i=1; i<size; i++) if(dist[i-1]<dist[i]) break; mid=i-1; for(; i<size; i++) if(dist[i-1]>dist[i]) break; if(i<size){ if(0){ showerr("evt_vdc_pos: drift length inconsistency.\n"); for(i=0; i<size; i++) showerr("p_vdc_pos: drift[%d] = %5d\n", i, dist[i]); } dr_append_ref(plane->h_posid, clst->posid=POSID_DRIFT); continue; } /* check monotone increase/decrease */ if(mid<=0 || size-1<=mid){ dr_append_ref(plane->h_posid, clst->posid=POSID_MONOTONE); continue; } #if 0 /* simplified position fitting (for debug) */ clst->pos = clst->wire[0] +(double)(wire[size-1]-wire[0])*dist[0]/(dist[0]+dist[size-1]); dr_append_ref(plane->h_posid, clst->posid=POSID_SIMPLE); continue; #endif /* change the signs of drift lengths */ for(i=(dist[mid-1]<=dist[mid+1] ? mid-1:mid); i>=0; i--) dist[i] = -dist[i]; #if 0 /* for debug */ fprintf(stderr, "after dist = \n"); for(i=0; i<size; i++){ fprintf(stderr, "%5d %9.5f\n", i, dist[i]); } #endif /* get mean values */ mx = my = mx2 = mxy = 0.; for(i=0; i<size; i++){ mx += wire[i]; my += dist[i]; mx2 += wire[i]*wire[i]; mxy += wire[i]*dist[i]; } my /= size; mxy /= size; mx /= size; mx2 /= size; m = mx2-mx*mx; if(m<=0.0){ fprintf(stderr, "evt_vdc_pos: error of least square fit(1).\n"); dr_append_ref(plane->h_posid, clst->posid=POSID_LFIT); continue; } slope = (mxy-mx*my)/m; if(fabs(slope)<=1e-10){ fprintf(stderr, "evt_vdc_pos: error of least square fit(2).\n"); dr_append_ref(plane->h_posid, clst->posid=POSID_LFIT); continue; } clst->pos = mx-my/slope; clst->grad = plane->wire.sc/slope; dr_append_ref(plane->h_posid, clst->posid=POSID_NOERR); dr_append_ref(plane->h_pos, clst->pos); dr_append_ref(plane->h_grad, clst->grad); #if 0 /* for DEBUG */ if(ic==0 && !strcmp(plane->name, "X1")){ for(i=0; i<size; i++){ printf("%5d %10.3f\n", wire[i], dist[i]); } printf("\n"); } #endif } /* loop of ic */ return(0); } /* Local Variables: mode: C tab-width: 2 End: */ <file_sep>#ifndef _RCNPEVENT_H_ #define _RCNPEVENT_H_ #include "TObject.h" #include <stdio.h> #include <ctype.h> #include <iostream> #include <algorithm> #include <functional> #include <vector> #include <string> #include <fstream> #include <map> #include <stdexcept> #include <sys/types.h> #include <signal.h> #define BAD_NUM -441441 using namespace std; /************** RCNPEvent Class ****************/ /* All tree variables are referenced by string e.g. "GR_ADC" */ class RCNPEvent : public TObject { // This indicates that the RCNPEvent class inherits from the TObject class // (this inheritence is needed for writing this object to a tree) public: RCNPEvent() // This is the class "constructor" it is run when an object of the class is created : fTimestamp(0) {;} virtual ~RCNPEvent() {;} // This is the class "destructor" it is run when an object of the class is destroyed // (virtual indicates that it overrides the destructor of the parent TObject class) RCNPEvent(RCNPEvent& other) : TObject(other) { fTimestamp = other.GetTimestamp(); data.swap(other.data); } map<int,vector<double> > data; // The underlying map from string to vector of data void Clear() {data.clear();} long GetTimestamp() { return fTimestamp; } void SetTimestamp(const long& ts) { fTimestamp = ts; } // TODO: make HistCheck static //[[[cog import rootalyze as root; root.definitions() ]]] //[[[end]]] private: long fTimestamp; public: ClassDef(RCNPEvent,1); // This is a ROOT macro that is needed for creating a ROOT dictionary // # corresponds to version number, if = 0, events will NOT be saved }; class DSTMap : public TObject { map<string,int> strtoint; map<int,string> inttostr; public: DSTMap() {;} virtual ~DSTMap() {;} int operator()(const string& var) {return strtoint.at(var);} string operator()(const int& varnum) {return inttostr.at(varnum);} void Set(const int& varnum, const string& var) { strtoint[var] = varnum; inttostr[varnum] = var; } ClassDef(DSTMap,1); }; #ifndef __CINT__ static std::function<void(RCNPEvent*)> StoreData; extern void Init(std::function<void(RCNPEvent*)> func); #endif #endif <file_sep>/* lr3351.h ---- LeCroy 3351 Peak Sensing ADC Definitions */ /* */ /* Copyright (C) 1996, <NAME> */ /* */ /* Version 1.00 26-APR-1998 by <NAME> (from fera.h) */ /* Version 1.10 22-MAY-1998 by <NAME> (bug fix) */ #if defined(OSF1) || defined(Linux) /*----- OSF1 and Linux ----*/ /* 3351 Header */ typedef struct lr3351_header{ unsigned vsn: 8; /* Virtual Station Number */ unsigned cnt: 4; /* Valid Data Counter */ unsigned res: 3; /* Not Used */ unsigned hdr: 1; /* Identifies header word (=1) */ } lr3351_header; /* 3351 Pattern Word (Compressed Mode)*/ typedef struct lr3351_pat{ unsigned pat: 8; /* Pattern Word (LSB = ch. 0) */ unsigned res: 7; /* Not Used */ unsigned hdr: 1; /* Identifies header word (=0) */ } lr3351_pat; /* 3351 Data (Compressed Mode) */ typedef struct lr3351_data{ unsigned data: 12; /* Data */ unsigned ch: 3; /* Channel number */ unsigned ovf: 1; /* Overflow bit */ } lr3351_data; /* Virtual Station Number ID */ typedef struct lr3351_vsn{ unsigned id: 4; /* ID */ unsigned det: 2; /* Detector Type (0=GR, 1=LAS, 2=GSO, 3=SSD) */ unsigned t3351: 1; /* Type 3351 (=1 for 3351)*/ unsigned type: 1; /* FERA_TYPE_ADC or FERA_TYPE_TDC */ } lr3351_vsn; #else /*----- Others ----*/ /* 3351 Header */ typedef struct lr3351_header{ unsigned hdr: 1; /* Identifies header word (=1) */ unsigned res: 3; /* Not Used */ unsigned cnt: 4; /* Valid Data Counter */ unsigned vsn: 8; /* Virtual Station Number */ } lr3351_header; /* 3351 Pattern Word (Compressed Mode)*/ typedef struct lr3351_pat{ unsigned hdr: 1; /* Identifies header word (=0) */ unsigned res: 7; /* Not Used */ unsigned pat: 8; /* Pattern Word (LSB = ch. 0) */ } lr3351_pat; /* 3351 Data (Compressed Mode) */ typedef struct lr3351_data{ unsigned ovf: 1; /* Overflow bit */ unsigned ch: 3; /* Channel number */ unsigned data: 12; /* Data */ } lr3351_data; /* Virtual Station Number ID */ typedef struct lr3351_vsn{ unsigned type: 1; /* FERA_TYPE_ADC or FERA_TYPE_TDC */ unsigned t3351: 1; /* Type 3351 (=1 for 3351)*/ unsigned det: 2; /* Detector Type (0=GR, 1=LAS, 2=GSO, 3=SSD) */ unsigned id: 4; /* ID */ } lr3351_vsn; #endif /*----- end of if OSF1 and Linux ----*/ /* Local Variables: mode: C tab-width: 2 End: */ <file_sep>/* lr3377.h ---- LeCroy 3377 (Drift Chamber TDC) Definitions */ /* */ /* Copyright (C) 1996, <NAME> */ /* */ /* Version 1.00 26-MAY-1996 by <NAME> */ /* Version 2.10 26-APR-1998 by <NAME> (restored from 13-MAR-1997 and modified)*/ #if !defined(alpha) && !defined(i586) && !defined(i686) && !defined(x86_64) /*---- others (big endian) ---- */ /* LR3377 Header */ typedef struct lr3377_header{ unsigned hdr: 1; /* Identifies header word (=1) */ unsigned word: 1; /* Double(1)/Single(0) word format */ unsigned evt: 3; /* Event serial number */ unsigned edge: 1; /* Leading(0) or leading/trailing(1) edge */ unsigned res: 2; /* Resolution */ unsigned id: 8; /* Module ID */ } lr3377_header; /* LR3377 Data (Common) */ typedef struct lr3377_data{ unsigned hdr: 1; /* Identifies header word (=0) */ unsigned ch: 5; /* Channel number */ unsigned data: 10; /* Data */ } lr3377_data; /* Single word format, leading edge only */ typedef struct lr3377_sgl_led{ unsigned hdr: 1; /* Identifies header word (=0) */ unsigned ch: 5; /* Channel number */ unsigned data: 10; /* Data */ } lr3377_sgl_led; /* Single word format, leading/trailing edge */ typedef struct lr3377_sgl_trl{ unsigned hdr: 1; /* Identifies header word (=0) */ unsigned ch: 5; /* Channel number */ unsigned edge: 1; /* leading(0) or trailing(1) */ unsigned data: 9; /* Data */ } lr3377_sgl_trl; /* Double word format */ typedef struct lr3377_dbl{ unsigned hdr: 1; /* Identifies header word (=0) */ unsigned ch: 5; /* Channel number */ unsigned edge: 1; /* leading(0) or trailing(1) */ unsigned word: 1; /* First word(0) or second word(1) */ unsigned data: 8; /* Data */ } lr3377_dbl; /* Module ID */ typedef struct lr3377_mid{ unsigned spe: 1; /* Spectrometer (0=GR, 1=LAS) */ unsigned vdc: 1; /* VDC (Front=0, Rear=1) */ unsigned cor: 2; /* X=0, Y=1, U=2, V=3 */ unsigned id: 4; /* ID */ } lr3377_mid; #else /*----- Alpha or Intel-PC (little endian) ----*/ /* LR3377 Header */ typedef struct lr3377_header{ unsigned id: 8; /* Module ID */ unsigned res: 2; /* Resolution */ unsigned edge: 1; /* Leading(0) or leading/trailing(1) edge */ unsigned evt: 3; /* Event serial number */ unsigned word: 1; /* Double(1)/Single(0) word format */ unsigned hdr: 1; /* Identifies header word (=1) */ } lr3377_header; /* LR3377 Data (Common) */ typedef struct lr3377_data{ unsigned data: 10; /* Data */ unsigned ch: 5; /* Channel number */ unsigned hdr: 1; /* Identifies header word (=0) */ } lr3377_data; /* Single word format, leading edge only */ typedef struct lr3377_sgl_led{ unsigned data: 10; /* Data */ unsigned ch: 5; /* Channel number */ unsigned hdr: 1; /* Identifies header word (=0) */ } lr3377_sgl_led; /* Single word format, leading/trailing edge */ typedef struct lr3377_sgl_trl{ unsigned data: 9; /* Data */ unsigned edge: 1; /* leading(0) or trailing(1) */ unsigned ch: 5; /* Channel number */ unsigned hdr: 1; /* Identifies header word (=0) */ } lr3377_sgl_trl; /* Double word format */ typedef struct lr3377_dbl{ unsigned data: 8; /* Data */ unsigned word: 1; /* First word(0) or second word(1) */ unsigned edge: 1; /* leading(0) or trailing(1) */ unsigned ch: 5; /* Channel number */ unsigned hdr: 1; /* Identifies header word (=0) */ } lr3377_dbl; /* Module ID */ typedef struct lr3377_mid{ unsigned id: 4; /* ID */ unsigned cor: 2; /* X=0, Y=1, U=2, V=3 */ unsigned vdc: 1; /* VDC (Front=0, Rear=1) */ unsigned spe: 1; /* Spectrometer (0=GR, 1=LAS) */ } lr3377_mid; #endif #define MID_DELIMITER1 0x00FF /* Delimiter Module ID */ #define MID_DELIMITER2 0x00E7 /* Delimiter Module ID */ #if 0 #define vsn_delim(vsn) (vsn==MID_DELIMITER1 || vsn==MID_DELIMITER2) #endif /* Local Variables: mode: C tab-width: 2 End: */ <file_sep>/* chamb_las_fpp.c ---- LAS FPP MWDC data analysis Version 1.00 04-DEC-2005 by <NAME> */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include "freadin.h" #include "histogram.h" #include "analyzer.h" #include "matrix.h" #if LAS_FPP_MWDC //FLAG struct chamber las_fpp_mwdc; extern struct chamber las_vdc; /* initialize data before an event (for np)*/ int evt_init_las_fpp() { chamb_init_chamb(&las_fpp_mwdc); return 0; } /* LAS-FPP-3377 data analysis */ int evt_chamb_las_fpp(){ chamber_p chamb; plane_p plane; int ipl; ray_p ray, lray; ray_t r; vec_rec p; double d; double dist; double ath, aph, hor, ver; chamb = &las_fpp_mwdc; ray = &chamb->ray; for(ipl=0; ipl<chamb->npl; ipl++){ plane = &chamb->plane[ipl]; chamb_clust(plane); chamb_drift(plane); chamb_pos(plane); } // if(dr_exists(d=dr_get(LAS_RAYID)) && dr_int(d)==0){ chamb_ray(chamb); dr_set(LF_RAYID,ray->rayid); dr_set(LF_CHI2[0],chamb->chi2); dr_set(LF_NCOMB,chamb->ncomb); if(ray->rayid==RAYID_NOERR){ /* rotation of axes as z=central-ray */ ray_rotate_z(ray,dr_get(LF_TILT[2])); ray_rotate_y(ray,dr_get(LF_TILT[1])); ray_rotate_x(ray,dr_get(LF_TILT[0])); /* output of ray information */ dr_set(LF_RAY_X[0], ray->org.x); dr_set(LF_RAY_Y[0], ray->org.y); dr_set(LF_TH[0],atan(ray->dir.x)); dr_set(LF_PH[0],atan(ray->dir.y)); /* projection to virtual planes */ chamb_intersection(chamb); } /* vetex point and the scattering angle */ #if 0 /* for special use 19-DEC-2005 E154*/ r.org.x = 4.1; r.org.y = 13.3; r.org.z = 0.; r.dir.x = tan(+0.15*d2r); r.dir.y = tan(-0.24*d2r); r.dir.z = 1.; r.rayid = RAYID_NOERR; lray = &r; #else lray = &las_vdc.ray; #endif if(lray->rayid==RAYID_NOERR){ if(ray_vertex(ray,lray,&p,&dist)==0){ dr_set(LF_VERTEX_X[0], p.x); dr_set(LF_VERTEX_Y[0], p.y); dr_set(LF_VERTEX_Z[0], p.z); } dr_set(LF_DIST[0], dist); /* if error, error code is saved in 'dist' */ if(ray_scat_ang(lray,ray,&ath,&aph,&hor,&ver)==0){ /* scattering angle (all in radian) */ dr_set(LF_SCAT_TH[0], ath); /* scattering angld (polar angle) */ dr_set(LF_SCAT_PH[0], aph); /* scattering angld (azimuthal angle) */ dr_set(LF_SCAT_DX[0], hor); /* scattering angld (horizontal) */ dr_set(LF_SCAT_DY[0], ver); /* scattering angld (vertical) */ } } return(0); } /* initialization of data before data analysis */ int evt_start_las_fpp(){ chamber_p chamb; plane_p plane; int i, ipl; double d; chamb = &las_fpp_mwdc; #if DT2D_TAB chamb_get_dt2d_tab(chamb); #endif chamb_get_config(chamb); for(ipl=0; ipl<chamb->npl; ipl++){ plane = &chamb->plane[ipl]; plane->pres = 0.5; /* 0.5 mm resolution */ plane->fit = dr_is_true(dr_get(LF_FIT_PLANE[ipl])); } if(dr_exists(d=dr_get(LF_MAX_NCOMB))) chamb->max_ncomb = (int)d; chamb->allow_wireskip = dr_is_true(dr_get(LF_ALLOW_WIRESKIP)); d = dr_get(LF_N_VPLANE); chamb->nproj = dr_exists(d) ? min((int)d, MaxNIntPl) : 0; for(i=0; i<chamb->nproj; i++) dr_ref_n(spf("LF_PLANE_%d",i), &chamb->h_proj[i]); dr_ref_n("LF_XP", &chamb->h_x); dr_ref_n("LF_YP", &chamb->h_y); return 0; } /* initialize variables */ int init_hist_las_fpp() { chamber_p chamb; int ipl; double d; int i, n; /* initialyze for LAS-FPP MWDC */ chamb = &las_fpp_mwdc; chamb->name = "LF"; chamb->type = CHAMB_MWDC; chamb->npl = 8; chamb->plane = (plane_p)malloc(sizeof(plane_t)*chamb->npl); chamb->plane[0].name = "X1"; chamb->plane[1].name = "X2"; chamb->plane[2].name = "X3"; chamb->plane[3].name = "X4"; chamb->plane[4].name = "Y1"; chamb->plane[5].name = "Y2"; chamb->plane[6].name = "Y3"; chamb->plane[7].name = "Y4"; for(ipl=0; ipl<chamb->npl; ipl++){ chamb->plane[ipl].chamb = chamb; } chamb_init_hist(chamb); n = 1<<chamb->npl; chamb->matrix = (void*)malloc(sizeof(mat_p)*n); for(i=0; i<n; i++) ((mat_p*)chamb->matrix)[i] = (mat_p)NULL; chamb->mb = matrix_new(4,1); chamb->mc = matrix_new(4,1); if(chamb->matrix==NULL||chamb->mb==NULL||chamb->mc==NULL){ showerr("init_hist_np: No enough memory available\n"); exit(1); } return 0; } #endif /* if LAS_FPP_MWDC */ /* Local Variables: mode: C tab-width: 2 End: */ <file_sep>/* analyzer.c ---- analyzer program Version 1.00 02-JUN-2000 by <NAME> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #include <stdarg.h> #include <errno.h> #include "freadin.h" #include "histogram.h" #include "lr3377.h" #include "analyzer.h" static char *filename; extern char *ofile; /* output file name */ //FLAG #define MaxArgs 20 int nscalers = 16; int nmodes = 4; int *scaler = (int*)NULL; int ablk = 0; /* number of analyzed blocks */ int cblk = 0; /* number of comment blocks */ extern int nrun; extern int nblk; extern int shmflag; #if USE_GRUTINIZER // added on 2017.1.25 by <NAME> extern int rootflag; extern char *hbfnam; #else char *hbfnam; #endif extern char *shmnam; extern FILE *falias; extern int pflag; /* parent flag */ extern int cflag; /* child flag */ extern int childn; /* child process number */ extern int ShowStatus(); // print status flag from GRUTinizer /* initialize */ static void init_hist(){ init_hist_rcnp(); init_hist_gr_fpp(); #if LAS_FPP_MWDC init_hist_las_fpp(); #endif #if NP_MWDC init_hist_np(); #endif #if F2_MWDC init_hist_f2(); #endif } /* initialize */ int event_init(){ int i, k; hb_init(ofile,SHMSIZE); init_hist(); evt_time(); /* clear scalers */ k = nscalers*nmodes; scaler = (int*)malloc(sizeof(int)*k); for(i=0; i<k; i++) scaler[i] = 0; /* clear analyzed blocks */ ablk = 0; cblk = 0; return 0; } /* save histograms */ void save_histograms() { char name[256]; char *f; f = dr_get_sval(HB_FILE); if(f!=(char*)NULL && strlen(f)>0){ strcpy(name, f); }else if(nrun){ sprintf(name, "hb/run%.4d.hb", nrun); }else{ strcpy(name, "hb/analyzer.hb"); } hb_hist_out(name); } /* save scaler data */ void save_scalers() { char name[256]; FILE *fd; char *f; evt_print_scaler(stderr); if(!cflag){ f = dr_get_sval(SCA_FILE); if(f!=(char*)NULL && strlen(f)>0){ strcpy(name, f); }else if(nrun){ sprintf(name, "sca/run%.4d.sca", nrun); }else{ strcpy(name, "sca/analyzer.sca"); } fd = fopen(name, "w"); if(fd){ evt_print_scaler(fd); fprintf(stderr, "Scaler data have been saved in '%s'.\n", name); fclose(fd); } } } /* open the alias file */ void open_alias_file() { char *f; char fnamalias[256]; f = dr_get_sval(ALIAS_FILE); if(f!=(char*)NULL && strlen(f)>0){ strcpy(fnamalias, f); }else{ strcpy(fnamalias, FNAMALIAS); } falias = fopen(fnamalias, "w"); if(falias==(FILE*)NULL){ fprintf(stderr, "Warning: could not open the alias file '%s' (%s).\n", fnamalias, strerror(errno)); } } /* end of tasks */ int event_exit(){ /* show block number and the analyzing ratio */ fprintf(stderr,"\n"); show_blk_num(1); save_scalers(); /* DST exit tasks */ dst_exit(); #if USE_GRUTINIZER // added on 2017.1.25 by <NAME> if(rootflag == 1) root_exit(); #endif save_histograms(); hb_exit(shmflag); return 0; } /* Event Reduction */ int event(){ int i, j, gl_flag; double f; static int m=0; if(!m){ evt_start(); m=1; } message(); #if 0 if(evt_blk()) return(-1); #endif dr_set(PROC_NUM[0], cflag ? childn:-1); /* child process number */ evt_time(); evt_scaler(); dr_set(BLOCK_ANA[0], ablk); if(dr_is_true(dr_get(EVENT_RCNP))){ /* Analyzer RCNP Data */ if(dr_is_true(dr_get(EVENT_BEND))){ /* Block-end Event */ }else{ evt_init_rcnp(); evt_ipr(); gl_flag = 0; /* for GR */ if(dr_is_true(dr_get(ANALYZE_GR))){ evt_init_gr(); evt_gr_adc(); evt_gr_tdc(); if(dr_is_true(dr_get(ANALYZE_GR_VDC))){ evt_chamb_gr(); evt_gr_kinema(); gl_flag++; } } /* for LAS */ if(dr_is_true(dr_get(ANALYZE_LAS))){ evt_init_las(); evt_las_adc(); evt_las_tdc(); if(dr_is_true(dr_get(ANALYZE_LAS_VDC))){ evt_chamb_las(); evt_las_kinema(); gl_flag++; } } if(gl_flag==2){ evt_gl_kinema(); } #if LAS_FPP_MWDC /* for LAS_FPP */ if(dr_is_true(dr_get(ANALYZE_LAS_FPP))){ evt_init_las_fpp(); evt_chamb_las_fpp(); } #endif #if NP_MWDC /* for NP */ if(dr_is_true(dr_get(ANALYZE_NP))){ evt_init_np(); evt_chamb_np(); } #endif /* for GR FPP */ if(dr_is_true(dr_get(ANALYZE_GR_FPP))){ evt_init_gr_fpp(); evt_gr_fpp_adc(); evt_gr_fpp_tdc(); evt_chamb_gr_fpp(); } } } #if F2_MWDC else if(dr_is_true(dr_get(EVENT_F2))){ /* Analyzer SMART F2 Data */ if(dr_is_true(dr_get(ANALYZE_F2))){ evt_init_f2(); evt_f2_adc(); evt_f2_tdc(); if(dr_is_true(dr_get(ANALYZE_F2_MWDC))){ evt_chamb_f2(); evt_f2_kinema(); } #if 0 evt_f2_3377(); #endif } } #endif show_debug(); dst_write_data(); #if USE_GRUTINIZER // added on 2017.1.25 by <NAME> if(rootflag == 1) root_write_data(); #endif dr_set(ANALYZED,1); #if 0 sleep(1); #endif return(0); } /* make integer data to analog */ double analog(i) int i; { return((double)i+drand48()-0.5); } void show_debug(){ double f; int i, min, max; /* dump */ f = dr_get(DEBUG_DUMP_VARIABLES); if(dr_is_true(f)){ dr_show(); } /* show variable 'DEBUG' */ f = dr_get(DEBUG_DUMP_DEBUG); if(dr_is_true(f)){ f = dr_get(DEBUG); if(dr_exists(f)){ #if 0 fprintf(stderr, " DEBUG = %15.7e\n", f); #endif min = dr_min(DEBUG); max = dr_max(DEBUG); printf(" %s:\n", "DEBUG"); for(i=min; i<max; i++){ f = dr_get(DEBUG[i]); if(dr_is_nothing(f)) printf(" %5d) %15s\n", i, "N/U"); else printf(" %5d) %15.7f %8x\n", i, f, (int)f); } }else{ f = dr_get(DEBUG_DUMP_SHOW_NONE); if(dr_is_true(f)) fprintf(stderr, " %s: NONE\n", "DEBUG"); } } } /* output messages */ void message(){ int i, j; double f; } /* starting job */ int evt_start(){ printf("CALL: evt_start_rcnp"); evt_start_rcnp(); #if LAS_FPP_MWDC evt_start_las_fpp(); #endif #if NP_MWDC evt_start_np(); #endif evt_start_gr_fpp(); #if F2_MWDC evt_start_f2(); #endif dst_init(); #if USE_GRUTINIZER // added on 2017.1.25 by <NAME> if(rootflag == 1) root_init(nrun); #endif return 0; } void show_blk_num(flag) int flag; { #if USE_GRUTINIZER // added on 2017.1.25 by <NAME> if(!ShowStatus()) return; #endif if(flag || cflag || nblk/10*10==nblk){ if(nblk>1){ #if 1 fprintf(stderr, "%5d - blocks A/R = %5.2f%% \n%c%c", nblk, (double)ablk/(double)(nblk-cblk+1)*100., 27, 'M'); #else fprintf(stderr, "%5d - blocks A/R = %5.2f%% \n", nblk, (double)ablk/(double)(nblk-cblk+1)*100.); #endif }else{ fprintf(stderr, "%5d - blocks\n%c%c", nblk, 27, 'M'); } } } /* check block number (return with 1 ... no analysis, 0 ... analysis) */ int evt_blk(cblk) int cblk; { double d; int blk; static int mflag1=0, mflag2=0; /* check analysis start block */ d = dr_get(ANA_BLK_START); if(dr_exists(d)){ blk = (int)(d+0.5); if(!mflag1){ mflag1 = 1; fprintf(stderr, "Warning: analyze blocks from ANA_BLK_START (>=%d).\n", blk); } if(cblk<blk){ show_blk_num(0); return(1); } } /* check analysis end block */ d = dr_get(ANA_BLK_END); if(dr_exists(d)){ blk = (int)(d+0.5); if(!mflag2){ mflag2 = 1; fprintf(stderr, "Warning: analyze blocks to ANA_BLK_END (<%d).\n", blk); } if(blk<cblk){ show_blk_num(0); return(1); } } ablk++; if(!cflag){ if(dr_is_true(dr_get(PRINT_SCALER)) || ((pflag && nblk%100==0) && 0)){ evt_print_scaler(stderr); } if(!shmflag && hbfnam){ if((nblk%10000)==0){ // hb_hist_out(hbfnam); } } } show_blk_num(0); return(0); } /* input register */ #define MAXNIPR 16 int evt_ipr(){ double f; int i, j, m, n, ipr; int su, sd; /* set BIT patterns */ i = 0; /* get IPR minimum index (=0) */ n = min(dr_max(IPR), MAXNIPR); /* get IPR maximum index (<=MAXNIPR) */ m = 0; for(; i<n; i++, m+=16){ f = dr_get(IPR[i]); if(dr_exists(f)){ ipr = (int)f; for(j=1; j<=16; j++, ipr>>=1) if(ipr & 1) dr_set(IPRBIT[m+j],m+j); } } return 0; } static int nblk_scaler = 0; /* Scaler */ void add_scaler(k, n) int k,n; { hist_data_t hd; if(0<=k && k<nscalers*nmodes){ scaler[k] += n; dr_set(SCALER_SUM[k],scaler[k]); if(cflag){ hd.hid = HID_SCALER+k; hd.f1 = (double)n; hd.f2 = 0.; if(hd.hid<HID_SCALER_MAX) write_child_data((char*)&hd, sizeof(hist_data_t)); } } } int evt_scaler(){ int i, j, k; double d; k = 0; for(i=0; i<nmodes; i++){ for(j=0; j<nscalers; j++){ d = dr_get(SCALER[k]); if(dr_exists(d)) add_scaler(k, dr_int(d)); k++; } } nblk_scaler = (int)dr_get(BLOCK_N); return 0; } /* Print Scalers */ int evt_print_scaler(fd) FILE *fd; { int i, j, k, sum1, sum2; if(!scaler) return 0; if(nmodes==4){ if(nblk_scaler>0) fprintf(fd, "Scalers (at block #%d)\n", nblk_scaler); fprintf(fd, "%3s%12s%12s%12s%12s%12s\n", "","Mode #1","Mode #2","Mode #1","Mode #2","Sum"); for(j=0; j<nscalers; j++){ sum1 = scaler[0*nscalers+j] + scaler[1*nscalers+j]; sum2 = scaler[2*nscalers+j] + scaler[3*nscalers+j]; fprintf(fd, "%2d)", j); for(i=0; i<nmodes; i++){ k = i*nscalers+j; fprintf(fd, "%12d", scaler[k]); } if(sum1==sum2) fprintf(fd, "%12d\n", sum1); else fprintf(fd, " Mismatch!\n"); } }else{ for(j=0; j<nscalers; j++){ fprintf(fd, "%2d)", j); sum1 = 0; for(i=0; i<nmodes; i++){ k = i*nscalers+j; fprintf(fd, "%12d", scaler[k]); sum1 += scaler[k]; } fprintf(fd, "%12d\n", sum1); } } return 0; } /* GR-ADC */ int evt_gr_adc(){ /* nothing to do */ return 0; } /* GR-TDC */ int evt_gr_tdc(){ /* nothing to do */ return 0; } /* LAS-ADC */ int evt_las_adc(){ /* nothing to do */ return 0; } /* LAS-TDC */ int evt_las_tdc(){ /* nothing to do */ return 0; } /* GR-FPP Hodo-ADC */ int evt_gr_fpp_adc(){ /* nothing to do */ return 0; } /* GR-FPP Hodo-TDC */ int evt_gr_fpp_tdc(){ /* nothing to do */ return 0; } #if F2_MWDC /* F2-ADC */ int evt_f2_adc(){ /* nothing to do */ return 0; } /* F2-TDC */ int evt_f2_tdc(){ /* nothing to do */ return 0; } #endif /* Date and Time */ int evt_time(){ time_t t; struct tm *tm; double f; time(&t); tm = localtime(&t); f = (((double)tm->tm_sec/60.)+tm->tm_min)/60.+tm->tm_hour; dr_set(TIME[0], f); dr_set(TIME[1], tm->tm_year); dr_set(TIME[2], tm->tm_mon+1); dr_set(TIME[3], tm->tm_mday); dr_set(TIME[4], tm->tm_hour); dr_set(TIME[5], tm->tm_min); dr_set(TIME[6], tm->tm_sec); return 0; } /* Kinematical calculation for GR */ int evt_gr_kinema(){ double m1, m2, m3, m4; double e1, e2, e3, e4; double p1, p3, p4; double t1, th3, th4; double p4s, sth3, cth3, ds, dc; double dE; double ex; m1 = dr_get(M1); m2 = dr_get(M2); m3 = dr_get(GR_M3); m4 = dr_get(GR_M4); if(dr_is_nothing(m1)||dr_is_nothing(m2)|| dr_is_nothing(m3)||dr_is_nothing(m4)) return(-1); t1 = dr_get(T1); p3 = dr_get(GR_P); th3 = dr_get(GR_TH3); if(dr_is_nothing(t1)||dr_is_nothing(p3)|| dr_is_nothing(th3)) return(-1); dE = dr_get(GR_DE); if(dr_is_nothing(dE)) dE = 0.0; sth3 = sin(th3); cth3 = cos(th3); e1 = m1+t1; e2 = m2; e3 = sqrt(m3*m3+p3*p3)+dE; p3 = sqrt(e3*e3-m3*m3); e4 = e1+e2-e3; p1 = sqrt(e1*e1-m1*m1); ds = p3*sth3; dc = p1-p3*cth3; p4s = ds*ds+dc*dc; p4 = sqrt(p4s); ex = sqrt(e4*e4-p4s)-m4; th4 = atan2(ds,dc); dr_set(GR_EX, ex); dr_set(GR_P4, p4); dr_set(GR_TH4, th4); return(0); } /* Kinematical calculation for LAS */ int evt_las_kinema(){ double m1, m2, m3, m4; double e1, e2, e3, e4; double p1, p3, p4; double t1, th3, th4; double p4s, sth3, cth3, ds, dc; double dE; double ex; m1 = dr_get(M1); m2 = dr_get(M2); m3 = dr_get(LAS_M3); m4 = dr_get(LAS_M4); if(dr_is_nothing(m1)||dr_is_nothing(m2)|| dr_is_nothing(m3)||dr_is_nothing(m4)) return(-1); t1 = dr_get(T1); p3 = dr_get(LAS_P); th3 = dr_get(LAS_TH3); if(dr_is_nothing(t1)||dr_is_nothing(p3)|| dr_is_nothing(th3)) return(-1); dE = dr_get(LAS_DE); if(dr_is_nothing(dE)) dE = 0.0; sth3 = sin(th3); cth3 = cos(th3); e1 = m1+t1; e2 = m2; e3 = sqrt(m3*m3+p3*p3)+dE; p3 = sqrt(e3*e3-m3*m3); e4 = e1+e2-e3; p1 = sqrt(e1*e1-m1*m1); ds = p3*sth3; dc = p1-p3*cth3; p4s = ds*ds+dc*dc; p4 = sqrt(p4s); ex = sqrt(e4*e4-p4s)-m4; th4 = atan2(ds,dc); dr_set(LAS_EX, ex); dr_set(LAS_P4, p4); dr_set(LAS_TH4, th4); return(0); } /* Kinematical calculation for GR and LAS */ int evt_gl_kinema(){ double m1, m2, m3, m4, m5; double e1, e2, e3, e4, e5; double p1, p3, p4, p5; double t1, th3, th4, th5; double sth3, cth3, sth4, cth4, sth5, cth5; double ds, dc, p5s; double ex; double m34, m35, m45; m1 = dr_get(M1); m2 = dr_get(M2); m3 = dr_get(GR_M3); m4 = dr_get(LAS_M3); m5 = dr_get(M5); if(dr_is_nothing(m1)||dr_is_nothing(m2)|| dr_is_nothing(m3)||dr_is_nothing(m4)|| dr_is_nothing(m5)) return(-1); t1 = dr_get(T1); p3 = dr_get(GR_P); th3 = dr_get(GR_TH3); p4 = dr_get(LAS_P); th4 = dr_get(LAS_TH3); if(dr_is_nothing(t1)|| dr_is_nothing(p3)||dr_is_nothing(th3)|| dr_is_nothing(p4)||dr_is_nothing(th4)) return(-1); /* change the sign of th4 to make it consistent with the definition of th3 (left scattering) */ th4 = -th4; sth3 = sin(th3); cth3 = cos(th3); sth4 = sin(th4); cth4 = cos(th4); e1 = m1+t1; e2 = m2; e3 = sqrt(m3*m3+p3*p3); e4 = sqrt(m4*m4+p4*p4); e5 = e1+e2-e3-e4; p1 = sqrt(e1*e1-m1*m1); ds = -p3*sth3-p4*sth4; dc = p1-p3*cth3-p4*cth4; p5s = ds*ds+dc*dc; p5 = sqrt(p5s); ex = sqrt(e5*e5-p5s)-m5; th5 = atan2(ds,dc); sth5 = sin(th5); cth5 = cos(th5); dr_set(GL_EX, ex); dr_set(GL_P5, p5); dr_set(GL_TH5, th5); /* calculate invariant masses */ dc = p3*cth3+p4*cth4; ds = p3*sth3+p4*sth4; m34 = sqrt((e3+e4)*(e3+e4)-(dc*dc+ds*ds)); dc = p3*cth3+p5*cth5; ds = p3*sth3+p5*sth5; m35 = sqrt((e3+e5)*(e3+e5)-(dc*dc+ds*ds)); dc = p5*cth5+p4*cth4; ds = p5*sth5+p4*sth4; m45 = sqrt((e4+e5)*(e4+e5)-(dc*dc+ds*ds)); dr_set(GL_M34, m34); dr_set(GL_M35, m35); dr_set(GL_M45, m45); dr_set(GL_M34_EX, m34-m3-m4); dr_set(GL_M35_EX, m35-m3-m5); dr_set(GL_M45_EX, m45-m4-m5); return(0); } /* Kinematical calculation for F2 */ int evt_f2_kinema(){ #if 0 double m1, m2, m3, m4; double e1, e2, e3, e4; double p1, p3, p4; double t1, th3, th4; double p4s, sth3, cth3, ds, dc; double dE; double ex; m1 = dr_get(M1); m2 = dr_get(M2); m3 = dr_get(F2_M3); m4 = dr_get(F2_M4); if(dr_is_nothing(m1)||dr_is_nothing(m2)|| dr_is_nothing(m3)||dr_is_nothing(m4)) return(-1); t1 = dr_get(T1); p3 = dr_get(F2_P); th3 = dr_get(F2_TH3); if(dr_is_nothing(t1)||dr_is_nothing(p3)|| dr_is_nothing(th3)) return(-1); dE = dr_get(F2_DE); if(dr_is_nothing(dE)) dE = 0.0; sth3 = sin(th3); cth3 = cos(th3); e1 = m1+t1; e2 = m2; e3 = sqrt(m3*m3+p3*p3)+dE; p3 = sqrt(e3*e3-m3*m3); e4 = e1+e2-e3; p1 = sqrt(e1*e1-m1*m1); ds = p3*sth3; dc = p1-p3*cth3; p4s = ds*ds+dc*dc; p4 = sqrt(p4s); ex = sqrt(e4*e4-p4s)-m4; th4 = atan2(ds,dc); dr_set(F2_EX, ex); dr_set(F2_P4, p4); dr_set(F2_TH4, th4); #endif return(0); } /* Local Variables: mode: C tab-width: 2 End: */ <file_sep>from ensure_venv import ensure_venv ensure_venv('requirements.txt', system_site_packages=False) <file_sep>/* builder.h ... Definitions for Event Builder Copyright (C) 1995 <NAME> Author: <NAME> Facility: Department of Physics, Kyoto University & Research Center for Nuclear Physics Created: 30-JUn-1995 by <NAME> */ /*** constant definitions ***/ #ifndef TRUE #define FALSE 0 #define false 0 #define TRUE 1 #define true 1 #endif /*** for DEBUG ***/ #define DBALL 0xFFFF #define DBBLOCK 0x0001 #define DBEVENT 0x0002 #define DBFIELD 0x0004 #define DBDATA 0x0008 #define DBBLKEND 0x0010 #define DBRFM 0x0200 #define DBBASE 0x1000 #define DEBUG (DBBASE) /*** Procedures ***/ enum { ProcJ11=0, /* 0 = Data From J11 */ ProcRDTM, /* 1 = Data From RDTM (PCOS or 4298) */ Proc3377, /* 2 = Data From 3377 (without RDTM) */ ProcFERA, /* 3 = Data From 3377 (without RDTM) */ ProcFCET_3377, /* 4 = Data From FCET (for 3377) */ ProcFCET_FERA, /* 5 = Data From FCET (for FERA) */ ProcFCET_3351, /* 6 = Data From FCET (for peak sensing ADC) */ ProcFCET_1612, /* 7 = Data From FCET (for Pantek 1612F(QDC)/812F(TDC) */ NumProcs }; /*** Buffer Types ***/ #define BufData 0x0001 #define BufBlockEnd 0x0002 #define BufTrans 0x0004 /*** Block Types ***/ #define BLK_START 0x0010 /* run start block */ #define BLK_END 0x0020 /* run end block */ #define BLK_MIDDLE 0x0040 /* middle block */ #define BLK_DATA 0x0001 /* contain data */ #define BLK_BUILD 0x0002 /* start building */ #define BLK_TERM 0x0100 /* end of event building */ /*** Buffer Error Code ***/ #define BF_ERR_FATAL 0x80000000 #define BF_ERR_CNT_MASK 0x7FFFFFFF #define BF_ERR_MAX 100 /* maxmimum error count */ /*** base buffer size */ #define BufSize 0x4000 #define MaxBufSize 0x100000 /* Number of events for FCET nad RDTM scaler check */ #define MinNumEvents 0 #define MaxNumEvents 3000 /*** type definitions ***/ typedef struct BufInfo{ int buf_type; unsigned short *buf; unsigned short *end; unsigned short *ptr; int size; int proc_type; int proc_subtype; int blk_num; int evt_num; int error; int shm_pos; int work[16]; }BufInfo, *BufInfoPtr; typedef struct ProcInfo{ void (*proc_init)(BufInfoPtr); int (*proc_assign)(BufInfoPtr); unsigned short *(*proc_event)(unsigned short*, BufInfoPtr); unsigned short *(*proc_blockend)(unsigned short*, BufInfoPtr); } ProcInfo, *ProcInfoPtr; typedef struct bld1_header{ /* all components are defined by the network byte order */ int id; /* identification word ('BLD1') */ int seq_num; /* sequential number */ int bsize; /* block size in bytes */ int hsize; /* header size in byte */ int prev_pos1; /* absolute prev buffer position in byte (upper)*/ int prev_pos2; /* (lower)*/ int next_pos1; /* absolute prev buffer position in byte (upper)*/ int next_pos2; /* (lower)*/ } bld1_header_t; #define BLD1_ID 0x424c4431 /*. 'BLD1' 1 means the version 1.0 */ /* router_builder.c/event_builder.c */ int get_output_buf(int, BufInfoPtr, BufInfoPtr); int release_output_buf(BufInfoPtr); int output_buf(BufInfoPtr); int get_buf(BufInfoPtr); int release_buf(BufInfoPtr); void proc_null_init(BufInfoPtr); int proc_null_assign(BufInfoPtr); unsigned short *proc_null_event(unsigned short*, BufInfoPtr); unsigned short *proc_null_blockend(unsigned short*, BufInfoPtr); void proc_j11_init(BufInfoPtr); int proc_j11_assign(BufInfoPtr); unsigned short *proc_j11_event(unsigned short*, BufInfoPtr); unsigned short *proc_j11_blockend(unsigned short*, BufInfoPtr); void proc_rdtm_init(BufInfoPtr); int proc_rdtm_assign(BufInfoPtr); unsigned short *proc_rdtm_event(unsigned short*, BufInfoPtr); void proc_3377_init(BufInfoPtr); int proc_3377_assign(BufInfoPtr); unsigned short *proc_3377_event(unsigned short*, BufInfoPtr); void proc_fera_init(BufInfoPtr); int proc_fera_assign(BufInfoPtr); unsigned short *proc_fera_event(unsigned short*, BufInfoPtr); void proc_fcet_init(BufInfoPtr); int proc_fcet_assign(BufInfoPtr); unsigned short *proc_fcet_event(unsigned short*, BufInfoPtr); /* Local Variables: mode: C tab-width: 2 End: */ <file_sep>#ifdef __CINT__ #pragma link off all globals; #pragma link off all classes; #pragma link off all functions; #pragma link C++ nestedclasses; #pragma link C++ class RCNPEvent+; #pragma link C++ class DSTMap+; #pragma link C++ class map<string,vector<double>>+; #pragma link C++ class map<int,vector<double>>+; #endif <file_sep>/* fread.c --- analyzer program Author: <NAME> Facility: Department of Physics, University of Tokyo Created: 04-MAY-1997 by <NAME> Version 1.00 04-MAY-1997 by <NAME> (fread) Version 1.22 06-MAY-1997 by <NAME> (fread) Version 2.00 03-JUN-2000 by <NAME> (for analyzer) Version 3.00 31-JUL-2000 by <NAME> (analyzer.c) */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #ifdef OSF1 #include <strings.h> #endif #include <time.h> #include <stdarg.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <signal.h> #include <errno.h> #include <string.h> #include "freadin.h" #include "histogram.h" #include "analyzer.h" #include "mtformat.h" #include "lr3377.h" #include "fera.h" #include "builder.h" #include "v1190.h" #define VAR_END "END VARIABLES" static char title[] = "Analyzer ver 1.00 31-JUL-2000"; #if 0 static char title[] = "FRead ver 1.22 24-JUN-1997"; static char title[] = "FRead ver 1.22 04-JUN-1997"; static char title[] = "FRead ver 1.21 17-JUN-1997 (Stop at the End of Run)"; static char title[] = "FRead ver 1.10 06-MAY-1997"; static char title[] = "FRead ver 1.00 04-MAY-1997"; static char title[] = "FRead ver 2.00 03-JUN-2000"; #endif extern int neval; extern int level; int msgid = -1; int msgkey = -1; int parse_error; int format=FORMAT_UNDEFINED; /* data format */ extern int pflag; /* parent process flag */ extern int cflag; /* child process flag */ int nchild = 0; /* number of child processes */ extern int childn; /* child number for child process */ child_data_t cd[MAX_NCHILD]; /* child data */ #define MAX_NFDEF 10 int nfdef = 0; char *deffnam[MAX_NFDEF]; extern FILE *findef; char *filename; char *finnam; int findat = 0; FILE *fout = (FILE*)NULL; #if USE_PAW extern FILE *falias; #endif extern int byte_order; extern int swap; #if 1 int blksize = 0x100000; /* Default = 256KByte */ #else int blksize = 0x10000; /* Default = 64KByte */ #endif extern int nrun; extern int nblk; unsigned char *dbuf = (unsigned char*)NULL; unsigned char *sbuf = (unsigned char*)NULL; extern char *ofile; int line; /* for lex */ extern int shmflag; extern int rootflag; char *hbfnam = (char*)NULL; extern void yyparse(); extern int CheckSignal(); // terminate signal from GRUTinizer /* show_info --- show information */ static void show_info() { fprintf(stderr, "%s\n", title); } /* usage */ void usage(){ show_info(); fprintf(stderr, "Analyzer\n"); fprintf(stderr, " Usage: %s [-h] [-d def_file] [-o file] [-b blk_size] [file_name]\n", filename); fprintf(stderr, " file_name ... file to read (default=stdin)\n"); fprintf(stderr, " Option: -h ... show this help\n"); fprintf(stderr, " Option: -o ... output histograms to the specified file instead of shared memory\n"); fprintf(stderr, " Option: -d ... read a definition file (default = hist.def) \n"); fprintf(stderr, " -b ... specify block size in KBytes (default=%d)\n", blksize/1024); } int init_msg(){ FILE *fd; fd = fopen(KEYFILE, "w"); if(fd==(FILE*)NULL){ fprintf(stderr, "init_msg: cound not open key file: %s.\n", strerror(errno)); return(-1); } fprintf(fd, "%d\n", getpid()); fclose(fd); msgkey = ftok(KEYFILE,'A'); msgid = msgget(msgkey,0666 | IPC_CREAT); return(0); } void exit_msg(){ if(msgid>=0){ msgctl(msgid, IPC_RMID, NULL); msgid = -1; } remove(KEYFILE); } void domsg(){ mesg_t msgp; int res; int nc; while(1){ res = msgrcv(msgid, &msgp, MaxMsgLen, cflag ? getpid():MSG_CMD, IPC_NOWAIT); if(res==0) break; if(res<0){ if(errno==EAGAIN) return; if(errno==ENOMSG) return; fprintf(stderr, "domsg: error in msgrcv: %s\n", strerror(errno)); return; } /* do message */ if((cflag && msgp.mtype==getpid()) || (!cflag && msgp.mtype==MSG_CMD)){ line = 1; level = 0; fin.type = FIN_STR; fin.pstr = &msgp.mtext[0]; fin.istr = 0; #if 1 fprintf(stderr, "\n%s", fin.pstr); #endif neval++; /* for evaluations in yyparse() */ yyparse(); if(pflag){ /* send the smae message to child processes */ for(nc=0; nc<nchild; nc++){ msgp.mtype = cd[nc].pid; res = msgsnd(msgid, &msgp, strlen(msgp.mtext)+1, 0); if(res<0){ fprintf(stderr, "task: error in msgsd: %s\n", strerror(errno)); break; } } } }else{ fprintf(stderr, "domsg: unknown message type %d.\n", msgp.mtype); break; } } } static char *cd_buf = (char*)NULL; static int cd_pos = 0; /* reply_parent_buf --- reply to a parent at the end of a buffer */ void reply_parent_buf() { hist_data_t hd; if(!cflag) return; // fprintf(stderr, "reply\n"); hd.hid = -1; hd.f1 = 0.; hd.f2 = 0.; write_child_data((char*)&hd,sizeof(hist_data_t)); flush_child_data(); } /* read_child_buf --- read a buffer from child processes*/ int read_child_buf() { #define MAX_HIST_DATA 10000 fd_set readfds; struct timeval timeout; int nc; static hist_data_t hd[MAX_HIST_DATA]; static int cd_read_prev=0; hist_data_p h; int i, k, n, size, tsize; if(!pflag) return 0; while(1){ /* no loop happens when the final 'break' is active */ for(i=0; i<nchild; i++){ nc = (i+cd_read_prev+1)%nchild; FD_ZERO(&readfds); FD_SET(cd[nc].readfd, &readfds); n=cd[nc].readfd+1; timeout.tv_sec = 0; timeout.tv_usec = 0; if(select(n, &readfds, NULL, NULL, &timeout)>0) break; } if(i>=nchild) break; cd_read_prev = nc; tsize = read(cd[nc].readfd, hd, sizeof(hist_data_t)*MAX_HIST_DATA); if(tsize<=0){ if(errno==EINTR || errno==EAGAIN) continue; } n = tsize/sizeof(hist_data_t); if(n*sizeof(hist_data_t)!=tsize){ n++; read_in(cd[nc].readfd, (unsigned char*)hd, &tsize, n*sizeof(hist_data_t)); } h = hd; for(i=0; i<n; i++){ if(h->hid==-1){ cd[nc].n_sent_buf--; }else if(HID_SCALER <= h->hid && h->hid < HID_SCALER_MAX){ if(dr_exists(h->f1)) add_scaler(h->hid-HID_SCALER, dr_int(h->f1)); }else{ hfil2(h->hid, h->f1, h->f2); } h++; } break; /* no loop (this is the default usage) */ } n = 0; for(nc=0; nc<nchild; nc++) n += cd[nc].n_sent_buf; return(n); } // According to the typical event size, you have to reduce the following value, // otherwize, the analysis in parallel mode, will stop. #define MAX_N_SENT_BUF 50 /* send_child_buf --- send a buffer to one of child processes to analyze */ void send_child_buf(buf, size) unsigned char *buf; int size; { int i, nc; static int cd_send_prev=0; if(!pflag) return; // fprintf(stderr, "send\n"); while(1){ for(i=0; i<nchild; i++){ nc = (i+cd_send_prev+1)%nchild; if((format==FORMAT_DST_1 && cd[nc].n_sent_buf<MAX_N_SENT_BUF) || cd[nc].n_sent_buf<=0){ write(cd[nc].writefd,&size,sizeof(int)); write(cd[nc].writefd,buf,size); cd[nc].n_sent_buf++; // fprintf(stderr, "NC=%1d, Count=%5d ++\n", nc, cd[nc].n_sent_buf); cd_send_prev = nc; return; } } // fprintf(stderr, "read_child_buf()\n"); read_child_buf(); } } /* check_format */ int check_format(buf) unsigned char *buf; { int i, l; l = (buf[0]<<24)|(buf[1]<<16)|(buf[2]<<8)|(buf[3]<<0); switch(l){ case 0xffff0006: case 0xffff0600: case 0xffff0008: case 0xffff0800: return(FORMAT_TAMIDAQ); case 0x424c4431: case 0x4c423144: return(FORMAT_BLD1); case 0x00010000: case 0x01000000: case 0x00000001: case 0x00000100: case 0xffff0000: return(FORMAT_MARS); } if(dst_chk_format(buf)){ return(FORMAT_DST_1); } showerr("Unknown format: "); for(i=0; i<16; i++){ showerr("%.2x ", buf[i]); } showerr("\n"); return(FORMAT_UNKNOWN); } /* read_in */ int read_in(fd, buf, pos, size) int fd; unsigned char *buf; int *pos; int size; { int tsize; while(*pos<size){ tsize = read(fd, &buf[*pos], size-*pos); if(tsize<=0){ if(errno==EINTR || errno==EAGAIN) continue; if(*pos==0) return(-1); return(*pos); } *pos += tsize; } return(*pos); } /* file_read */ int file_read() { int size, tsize, asize, s, h, res; int bsize, tmp; int pos; int nc; unsigned char *p; int endflag=0; nblk = 0; size = 0; if(format==FORMAT_UNDEFINED){ if(cflag){ tmp=0; read_in(findat, (unsigned char*)&bsize, &tmp, sizeof(int)); read_in(findat, dbuf, &size, bsize); }else{ read_in(findat, dbuf, &size, 64); } format = check_format(dbuf); /* showerr("format = %d\n", format); */ switch(format){ case FORMAT_TAMIDAQ: fprintf(stderr, "Data format: RCNP\n"); break; case FORMAT_BLD1: fprintf(stderr, "Data format: RCNP BLD1\n"); break; case FORMAT_MARS: fprintf(stderr, "Data format: MARS\n"); swap = !swap; break; case FORMAT_DST_1: showerr("Data format: DST ver 1.0\n"); break; case FORMAT_UNKNOWN: default: return(-1); } } switch(format){ case FORMAT_BLD1: while(1){ if(cflag){ if(size<bsize){ tmp=0; if(read_in(findat, (unsigned char*)&bsize, &tmp, sizeof(int))<0) break; if(read_in(findat, dbuf, &size, bsize-size)<0) break; } s = ntohl(((bld1_header_t*)dbuf)->bsize); h = ntohl(((bld1_header_t*)dbuf)->hsize); }else{ if(read_in(findat, dbuf, &size, sizeof(bld1_header_t))<0) break; s = ntohl(((bld1_header_t*)dbuf)->bsize); h = ntohl(((bld1_header_t*)dbuf)->hsize); if(s+h>blksize){ showerr("Buffer size is too small. Please enlarge the block size" "to larger than %d Bytes.\n", s+h); endflag = 1; return(-1); } read_in(findat, dbuf, &size, s+h); } if(size<s+h){ showerr("Incomplete data. Ignore %d byte data.\n", size); endflag = 1; break; } p = &dbuf[h]; if(swap){ swab(p, sbuf, s); if(read_blk_rcnp((unsigned short*)sbuf, s)) endflag = 1; }else{ if(read_blk_rcnp((unsigned short*)p, s)) endflag = 1; } send_child_buf(dbuf, s+h); reply_parent_buf(); #if USE_ROOT hb_update(); #endif size = 0; if(shmflag) domsg(); if (CheckSignal() != 0) { break; } // checks if GRUTinizer is shutting down } break; case FORMAT_TAMIDAQ: bsize = blksize; while(1){ if(size<bsize){ if(cflag){ tmp=0; if(read_in(findat, (unsigned char*)&bsize, &tmp, sizeof(int))<0) break; if(read_in(findat, dbuf, &size, bsize)<0) break; }else{ if(read_in(findat, dbuf, &size, blksize)<0) break; } } if(size<bsize){ showerr("Avoid the last %d bytes (b)\n", size); endflag = 1; break; } if(swap){ swab(dbuf, sbuf, size); if(read_blk_rcnp((unsigned short*)sbuf, size)) endflag = 1; }else{ if(read_blk_rcnp((unsigned short*)dbuf, size)) endflag = 1; } send_child_buf(dbuf, size); reply_parent_buf(); #if USE_ROOT hb_update(); #endif size = 0; //if(shmflag) domsg(); if (CheckSignal() != 0) { break; } // checks if GRUTinizer is shutting down domsg(); } break; case FORMAT_MARS: while(read_in(findat, dbuf, &size, blksize)>=0){ if(size<blksize){ showerr("Avoid the last %d bytes (c)\n", size); endflag = 1; break; } if(swap){ swab(dbuf, sbuf, size); if(read_blk_mars((unsigned short*)sbuf, size)) endflag = 1; }else{ if(read_blk_mars((unsigned short*)dbuf, size)) endflag = 1; } send_child_buf(dbuf, size); reply_parent_buf(); #if USE_ROOT hb_update(); #endif size = 0; if(shmflag) domsg(); } break; case FORMAT_DST_1: if(!cflag) if(read_in(findat, dbuf, &size, blksize)<0) break; if(pflag){ /* read and send header */ pos = 0; if(dst_read_data(dbuf, &pos, size)!=1){ fprintf(stderr, "Could not find the position of data start\n"); exit(-1); } for(nc=0; nc<nchild; nc++){ send_child_buf(dbuf, pos); // send header to each child } memmove(dbuf, &dbuf[pos], size-pos); size -= pos; /* read and send data */ while(read_in(findat, dbuf, &size, blksize)>=0){ pos = 0; while(pos<size*3/4){ s = pos; res = dst_read_data(dbuf, &pos, size); if(res<0) break; send_child_buf(&dbuf[s], pos-s); } if(res<0) break; memmove(dbuf, &dbuf[pos], size-pos); size -= pos; #if USE_ROOT hb_update(); #endif if(shmflag) domsg(); } }else{ pos = 0; if(dst_read_data(dbuf, &pos, size)!=1){ // read header fprintf(stderr, "Could not find the position of data start\n"); exit(-1); } write(2,dbuf,pos); // for debug, output header data reply_parent_buf(); memmove(dbuf, &dbuf[pos], size-pos); size -= pos; bsize = blksize; while(1){ if(cflag){ tmp=0; // position (in the memory of the variable 'bsize') if(read_in(findat, (unsigned char*)&bsize, &tmp, sizeof(int))<0) break; if(read_in(findat, dbuf, &size, bsize)<0) break; if(size<bsize){ showerr("Avoid the last %d bytes (d)\n", size); break; } }else{ if(read_in(findat, dbuf, &size, blksize)<0) break; } res = 0; pos = 0; while(pos<size*3/4){ s = pos; res=dst_read_data(dbuf, &pos, size); if(res<0){ showerr("Avoid the last %d bytes (e)\n", size-s); break; } } if(res<0) break; memmove(dbuf, &dbuf[pos], size-pos); size -= pos; reply_parent_buf(); if(shmflag) domsg(); } } break; default: return(-1); } if(!ofile) domsg(); if(pflag){ #if 0 for(nc=0; nc<nchild; nc++){ close(cd[nc].writefd); cd[nc].writefd = -1; } #endif while((res=read_child_buf())){ //fprintf(stderr, "remaining bufs = %d\n", res); usleep(100000); } } fprintf(stderr, "---- End of fread. The last block number is %d ----\n", nblk); return(0); } void cleanup(){ if(dbuf){ free(dbuf); dbuf = (unsigned char*)NULL; } if(sbuf){ free(sbuf); sbuf = (unsigned char*)NULL; } if(!ofile) exit_msg(); hb_exit(); } void sig_handler(int signal){ fprintf(stderr, "Caught signal %d.\n", signal); event_exit(); cleanup(); //exit(1); } /* do initialization task */ int fread_init(bsize) int bsize; { if(bsize) blksize = bsize; swap = byte_order = htons(0x0102)==0x0102 ? BIG_ENDIAN:LITTLE_ENDIAN; dbuf = malloc(blksize+65536); if(dbuf==(unsigned char*)NULL){ fprintf(stderr, "Could not allocate memory(%s)\n", strerror(errno)); exit(1); } sbuf = malloc(blksize+65536); if(sbuf==(unsigned char*)NULL){ fprintf(stderr, "Could not allocate memory(%s)\n", strerror(errno)); exit(1); } /* initialize sub-modules */ if(dr_init()) exit(1); event_init(); if(!ofile && init_msg()<0) exit(1); return 0; } /* do exit task */ int fread_exit(){ if(dr_exit()) exit(1); #if USE_PAW if(falias){ fclose(falias); falias = (FILE*)NULL; } #endif cleanup(); return(0); } /* read definition file */ int fread_readdef() { int i; char *fnam; if(nfdef==0){ /* set the default definition file name */ deffnam[0] = DEFFNAM; nfdef++; } for(i=0; i<nfdef; i++){ /* open the definition file */ fnam = deffnam[i]; showerr("Read the definition file '%s'.\n", fnam); findef = fopen(fnam, "r"); if(findef==(FILE*)NULL){ showerr("Could not open the definition file '%s'.\n", fnam); exit(1); } /* read definition file */ fin.type = FIN_FILE; fin.file = findef; line = 1; parse_error = 0; neval++; /* for evaluations in yyparse() */ yyparse(); /* close the definition file */ fclose(findef); findef = (FILE*)NULL; /* check the error */ if(parse_error){ showerr("Errors are detected in '%s'.\n", fnam); exit(1); } } #if DEBUG_THINKPAD neval++; histogram(); #if 0 dr_show(); exit(0); #endif #endif return 0; } /* read data ana analize them */ int fread_ana(fd) int fd; { int i; findat = fd; finnam = ""; /* message */ showerr("Analyze '%s' with blksize=%dkB.\n", finnam, blksize/1024); /* main tasks */ #if 0 for(i=1; i<16; i++) signal(i, sig_handler); #endif /* signal(SIGINT, sig_handler); */ /* signal(SIGQUIT, sig_handler); */ /* signal(SIGPIPE, sig_handler); */ /* // signal(SIGHUP,domsg); */ /* //signal(SIGHUP, sig_handler); */ /* signal(SIGHUP,SIG_IGN); */ file_read(); return 0; } #define MAX_NARGS 20 /* main */ int start_analyzer(const char* cmd) { int bsize=0; int fin=0; /* standard input */ clock_t t1,t2; t1=clock(); showerr("ROOT flag on, YEAH! You rock dude! \n"); rootflag = 1; //fin = open("./datatest/run6106.bld", O_RDONLY); //fin = open(filename, O_RDONLY); FILE* fPipe = popen(cmd,"r"); fin = fileno(fPipe); if(fin<0){ fprintf(stderr, "Could not open file.\n"); exit(1); } if(cflag){ fout = fopen("/dev/null","w"); }else{ fout = stdout; } fprintf(fout, "%s\n", title); /* initialize */ fread_init(bsize); fread_readdef(); /* do analysis */ fread_ana(fin); /* do end tasks */ fread_exit(); pclose(fPipe); t2 = clock() - t1; float seconds = (float)t2 / CLOCKS_PER_SEC; showerr("Total running time was %f s. \n", seconds); } /* Local Variables: mode: C tab-width: 2 End: */
455f29199a21b7eb73efad268df37bce38d3bfe6
[ "Makefile", "Python", "Text", "C", "C++", "Shell" ]
51
C
csullivan/GRAnalyzer
686e29e713d5cf311cc36f38597ee4c166c90895
b46338947ea9b51b16b108b9a9785e1898e8aa1f
refs/heads/master
<repo_name>daniel0ferraz/Introducao-a-Programacao<file_sep>/README.md Introdução a Programação TEMA 1 - CONCEITOS BÁSICOS DE PROGRAMAÇÃO ESTRUTURADA E DA LINGUAGEM C * Linguagem de programação é um método padronizado para comunicar instruções para um computador, um conjunto de regras sintáticas e semânticas usadas para definir um programa de computador. Ela permite que um programador especifique precisamente sobre quais dados um computador vai atuar, como estes dados serão armazenados ou transmitidos e quais ações devem ser tomadas sob várias circunstâncias. * O desenvolvimento de um programa pode ser dividido em três etapas básicas: - Análise: corresponde à análise do problema a ser resolvido. - Algoritmo: uma sequência de passos a ser seguida para a realização de determinada tarefa. Utilizam-se ferramentas do tipo descrição narrativa, fluxograma ou português estruturado (pseudocódigo) para descrever o problema com sua possível solução. - Codificação: O algoritmo definido na etapa anterior é transformado em código a partir da linguagem de programação escolhida. - UM ALGORITMO DIVIDE O PROBLEMA A SER RESOLVIDO EM TRÊS ETAPAS BÁSICAS * ENTRADA * PROCESSAMENTO * SAÍDA LINGUAGEM C - A linguagem de programação C é uma linguagem de propósito geral, que foi originalmente projetada para ser implementada no sistema operacional UNIX. No entanto, a linguagem não está presa a um sistema operacional específico. C foi desenvolvido a partir de duas linguagens anteriores: BCPL e B. A linguagem foi desenvolvida por <NAME> em 1972. CARACTERÍSTICAS DA LINGUAGEM C C é uma linguagem case sensitive, isto é, termos e comandos escritos em maiúsculas são diferentes dos escritos em minúsculas. Todos os comandos em C devem ser escritos em letras minúsculas.C, assim como as demais linguagens de programação, possui palavras reservadas, que têm um significado especial para a linguagem. Exemplos dessas palavras: auto, break, case, if, else, switch, for, while, begin, end, continue, return, const, sizeof, typedef. Oferece um conjunto de bibliotecas e permite que sejam definidas bibliotecas próprias. Tais bibliotecas são um conjunto de funções para realizar tarefas específicas. As primeiras linhas do programa indicam as bibliotecas utilizadas. Exemplo: #include “minha_biblioteca.h” ou #include <minha_biblioteca.h> Comentários: textos no código que não serão processados pelo compilador. Serve para uso do programador como forma de explicar trechos de código e fazer anotações, por exemplo. São representados por: // para comentário feito em uma única linha ou /* comentário */ para comentários utilizando várias linhas. Ponto e vírgula: Ao final de cada comando utiliza-se ; indicar o término do comando. - TIPOS DE DADOS Programas utilizam a todo instantes dados para a realização das tarefas sob sua responsabilidade. Muitos desses dados serão armazenados na memória do computador para que possam ser utilizados e processados durante a execução de um programa. Desse modo, a definição e utilização de tipos de dados tornam-se necessárias. Os tipos de dados básicos da linguagem C são: * Inteiro: números positivos ou negativos e não possuem parte fracionária. Ocupam quatro bytes para armazenamento na memória. Utiliza-se o termo int para representá-lo. Exemplos: -1, -4, 1, 100. Modificadores podem ser utilizados associados a esse tipo, tais como long (números inteiros mais extensos), short (números inteiros mais curtos) e unsigned (números inteiros não negativos). * Real: números inteiros positivos ou negativos e possuem parte fracionária. Podem ser definidos com os termos float (número real de precisão simples – menores) ou double (números reais com dupla precisão – maiores). Exemplos: 23.58 36.49 -25.59869 * Caractere: tipo de dado formado por um único caractere, que pode ser letra maiúscula, letra minúscula, número, caractere especial (&, #, @, ...). É definido pelo termo char. Exemplo: ‘a’, ‘e’, ‘1’, ‘$’. * Variáveis Os dados recebidos e manipulados em um programa precisam ser armazenados na memória do computador. As variáveis representam espaços de memória utilizados para armazenar esses dados do programa. Cada variável possui um identificador (nome), um valor, um tipo de dado associado ao valor que armazenará e um endereço de memória (local em que esse valor será armazenado). O valor armazenado em uma variável pode ser alterado durante a execução do programa. * Constantes São espaços de memória que armazenam dados que, durante a execução de um programa, permanecem com os seus valores inalterados. Utiliza-se a palavra reservada const para especificar a declaração de uma constante. Também pode ser utilizada a diretiva #define. Sintaxe: const int PI = 3.14159; #define PI 3.14159 * Identificadores São os nomes dados às variáveis, constantes e funções. Tais nomes possuem regras para a sua definição: * Primeiro caractere deve ser sempre uma letra ou sublinhado. * Próximos caracteres podem ser letras (maiúsculas ou minúsculas), números ou o caractere sublinhado. * Não são permitidos caracteres especiais (#, @, $, ...) nem espaços em branco. * Não é permitido utilizar como identificador as palavras reservadas da linguagem C. <!-- FIM --> TEMA 2 - COMANDOS DE ATRIBUIÇÃO E DE ENTRADA E SAÍDA DE DADOS É importante ressaltar que um programa estará não só armazenando, mas processando, manipulando e exibindo dados durante a sua execução visando gerar os resultados desejados. Ao manipular dados, constantemente, o programa precisa realizar operações sobre tais dados. De acordo com os tipos de dados das variáveis, determinadas operações podem ser aplicadas nesses dados. Os principais operadores na linguagem C são: * Operadores relacionais: * Operadores lógicos: * Operadores aritméticos: são operadores básicos, já conhecidos da Matemática, que podem ser aplicados em tipos de dados numéricos como int, float e double. O uso dos operadores geram expressões, que podem ser armazenadas em variáveis com o uso de comandos de atribuição. * Operadores de incremento Os operadores de incremento e decremento têm a finalidade de simplificar o processo de adicionar ou remover uma unidade de um determinado número. São representados pelos operadores ++ (incremento) e – (decremento). * Operadores Relacionais Operadores relacionais são utilizados para fazer alguma comparação entre variáveis, retornando 1 (ou valores diferentes de 0) se a comparação obteve um resultado verdadeiro e 0 caso a comparação tenha obtido um resultado falso. * Operadores Lógicos Em programação, valores lógicos retornam verdadeiro ou falso. A linguagem C não possui um tipo de dado específico para representar os valores lógicos. Em C, o valor lógico é representado por 0 (zero) e qualquer valor diferente de zero representa o valor lógico verdadeiro. Para qualquer situação que se deseja verificar a combinação de comparações serão utilizados operadores lógicos. ESTRUTURA SEQUENCIAL Na estrutura sequencial, um conjunto predeterminado de comandos é executado de forma sequencial, seguindo a ordem em que foram declarados. Desse modo, ao escrever um programa deve-se ter bastante atenção à ordem dos comandos utilizados.<file_sep>/Tema 6 - Exercícios/Q2.cpp #include<stdio.h> int main(){ /* Faça um programa que leia dois valores para as variáveis A e B e efetue a troca dos valores de forma que a variável A passe a possuir o valor da variável B e a variável B passe a possuir o valor da variável A. Apresente os valores trocados. O programa deverá permitir a troca dos números cinco vezes. */ int A,B,i,rec; for(i=1;i<=5;i++) { printf("\n Informe um valor para A: "); scanf("%d",&A); printf("\n Informe um valor para B: "); scanf("%d",&B); rec=A; A=B; B=rec; printf("\n Valor de A: %d",A); printf("\n Valor de B: %d",B); } } <file_sep>/Tema 4 - Exercícios 1/Q4.c #include <stdio.h> main() { /*Um banco concede um crédito especial aos seus clientes, variável com o saldo médio no último ano. Construa um programa que leia o saldo médio de um cliente e calcule o valor do crédito de acordo com a tabela abaixo. Mostre uma mensagem informando o saldo médio e o valor do crédito. Considerar: - Saldo médio de 0 a 200: nenhum crédito - Saldo médio de 200,01 a 400: 20% do valor do saldo médio - Saldo médio de 400,01 a 600: 30% do valor do saldo médio - Saldo médio acima de 600,01: 40% do valor do saldo médio */ float saldo,credito; printf("\n Informe seu saldo:"); scanf("%f",&saldo); if (saldo < 200) { credito = 0; }else if(saldo < 400 ){ saldo = credito*20/100; } else if (saldo < 600){ saldo = credito*30/100; } else{ saldo=credito*40/100; printf("\n Saldo Medio = %.2f",saldo); printf("\n Valor do Credito = %.2f",credito); } }<file_sep>/Tema 6 - Exercícios/Q3.cpp #include<stdio.h> int main(){ /* Crie um programa que calcula o desconto previdenciário de dez funcionários. Dado um salário, o programa deve retornar o valor do desconto proporcional ao mesmo. O cálculo segue a regra: o desconto é de 11% do valor do salário, entretanto, o valor máximo de desconto é 318,20. Sendo assim, ou o programa retorna o valor equivalente a 11% sobre o salário ou 318,20. */ int i; float sal,prev; for(i=1;i<=10;i++) { printf("\n Informe o salario: "); scanf("%f",&sal); prev= sal*11/100; if(prev>318.20){ prev=318.20; printf("\n Salario: %.2f",prev); } } } <file_sep>/Tema 7 - Estrutura de repetição WHILE/Exemplos com While/while4.c #include<stdio.h> main() { int A,B,AUX,i=0; char RESP='S'; while(RESP=='S') { printf("\n ----------------"); printf("\n Entre com valor de A: ");scanf("%d",&A); printf("\n Entre com valor de B: ");scanf("%d",&B); AUX=A; A=B; B=AUX; printf("\n Valor de A: %d",A); printf("\n Valor de B: %d",B); printf("\n\n Nova troca (S/N)? "); scanf(" %c",&RESP); i=i+1; } printf("\n Trocas realizadas: %d",i); } <file_sep>/Tema 10 - Passagem de Parâmetros/Exnotaparam.cpp #include<stdio.h> float media(float a,float b,float c) { return (a+b+c)/3; } int main() { float n1,n2,n3; printf("Informe a primeira nota:"); scanf("%f",&n1); printf("Informe a segunda nota:"); scanf("%f",&n2); printf("Informe a terceira nota:"); scanf("%f",&n3); printf("\n Media = %.1f",media(n1,n2,n3)); } <file_sep>/Tema 3 - Exercícios 1/Q4.c #include<stdio.h> int main() { /* Em épocas de pouco dinheiro, os comerciantes estão procurando aumentar suas vendas oferecendo desconto. Faça um programa que possa receber um valor de um produto e que escreva o novo valor tendo em vista que o desconto foi de 9%. */ float produto,nvalor, desconto; printf("Informe o valor do produto:"); scanf("%f",&produto); desconto = produto*9/100; nvalor = produto - desconto; printf(" \n Desconto e %.2f", desconto); printf("\no novo valor com desconto:%.2f",nvalor); }<file_sep>/Tema 8 - Estrutura de repetição Do..WHILE/Exemplo5.cpp #include<stdio.h> int main(){ int i, num; for(i=1;i<=10;i++){ scanf("%d",num); if(num<10) break; printf("%d\n",num); } } <file_sep>/Tema 7 - Estrutura de repetição WHILE/Exemplos com While/while5.c #include<stdio.h> main() { char RESP='S',sexo; int idade,soma=0,total=0,somaF=0,qf=0,qm=0,maior,menor; float pM,mediaF,media; while(RESP=='S') { printf("\n Idade :"); scanf("%d",&idade); printf("\n Sexo :"); scanf(" %c",&sexo); soma=soma+idade; total=total+1; if(sexo=='F') { somaF=somaF+idade; qf=qf+1; } else qm++; if((idade>maior) || (total==1)) maior=idade; if((idade<menor) || (total==1)) menor=idade; printf("\n\n Continuar (S/N)? "); scanf(" %c",&RESP); } media=soma/total; mediaF=somaF/qf; pM=qm*100/total; printf("\n Media de todas as idades : %5.1f ",media); printf("\n Media das idades das mulheres : %5.1f ",mediaF); printf("\n Porcentagem de homens : %5.1f %%",pM); printf("\n Maior idade : %d ",maior); printf("\n Menor idade : %d ",menor); } <file_sep>/Tema 3 - Exercícios 2/Q3.c #include<stdio.h> main() { /* Escrever um algoritmo que leia: • a percentagem do IPI a ser acrescido no valor das pecas; • o código da peca 1, valor unitário da peca 1, quantidade de pecas 1; • o código da peca 2, valor unitário da peca 2, quantidade de pecas 2. O algoritmo deve calcular o valor total a ser pago e apresentar o resultado. */ int q1, q2, cod1, cod2; float API, valor1, valor2, vpg; printf("Informe a porcentagem em do API: "); scanf("%f",&API); printf("informe o valor da peca1:"); scanf("%f",&valor1); printf("infome o codigo da peca 1:"); scanf("%d",&cod1); printf("informe a quantidade de pecas1:"); scanf("%d",&q1); printf("informe o codigo da peca2:"); scanf("%d",&cod2); printf("Informe o valor da peca2"); scanf("%f",&valor2); printf("informe a quantidade de pecas2: "); scanf("%d",&q2); vpg = (valor1*cod1 + valor2*cod2) *(API/100+1); printf("O valor a pagar: %.2f",vpg); }<file_sep>/Tema 8 - Exercícios/Q3.cpp #include<stdio.h> int main(){ int num, par=0,impar=0; do{ printf("Informe um conjunto de numeros:"); scanf("%d",&num); if(num==9999) break; if(num%2==0) par++; else impar++; } while(num!=9999); printf("\nQuantidade de Pares: %d\n",par); printf("Quanridade de Impar: %d\n",impar); } <file_sep>/Tema 4 - Exercícios 2/Exercicio-2.c #include <stdio.h> #include <string.h> main() { float salario, novosalario, aumento; char cargo[20]; printf("\n Informe o seu salario: "); scanf("%f", &salario); printf("\n Qual e o seu cargo? "); scanf("%s", &cargo); printf("\n Cargo informado %s", cargo); if (strcmp(cargo, "gerente") == 0) aumento = salario * 25 / 100; else if (strcmp(cargo, "engenheiro") == 0) aumento = salario * 20 / 100; else if (strcmp(cargo, "tecnico") == 0) aumento = salario * 15 / 100; else aumento = salario * 10 / 100; novosalario = aumento + aumento; printf("\n Salario:%8.2f", salario); printf("\n Novo salario: %8.2f", novosalario); printf("\n Aumento: %8.2f", aumento); }<file_sep>/Tema 10 - Passagem de Parâmetros/Exemplo3.cpp #include<stdio.h> int main() { int a,b; int *pt1, *pt2; a=2; b=5; pt1 = &a; pt2 = &b; printf("a:%d e b:%",*pt1,*pt2); } <file_sep>/Tema 8 - Estrutura de repetição Do..WHILE/Solução Proposta/Tema8_Ex1_2.cpp #include<stdio.h> main() { int x,maximo,i=1; do { printf("\n Numero: "); scanf("%d",&x); if(x!=9999) { if ((x>maximo) || (i==1)) maximo=x; i++; } } while(x!=9999); printf("\n Maximo= %d",maximo); } <file_sep>/Tema 7 - Estrutura de repetição WHILE/Exemplos com While/Untitled1.cpp #include<stdio.h> main() { float nota,soma=0,media,p10; int i,qa7=0,q10=0; for(i=1;i<=10;i++) { printf("\n Entre com a nota do aluno %d: ",i); scanf("%f",&nota); if(nota>7) qa7=qa7+1; //ou qa7++; soma=soma+nota; //ou soma+=nota; if(nota==10) q10=q10+1; //ou q10++; } media=soma/10; p10=q10*100/10; printf("\n ========= Relatorio =========== "); printf("\n Quantidade de notas acima de 7 : %d",qa7); printf("\n Media da turma : %4.1f",media); printf("\n Porcentagem de notas iguais a 10 : %4.1f %%",p10); } <file_sep>/Exercícios - Tema 9/Questão6.cpp #include<stdio.h> float pcusto,perc,pvenda; void Venda() { printf("Entre com o preco de custo:"); scanf("%f",&pcusto); printf("Entre com o percentual:"); scanf("%f",&perc); } float Valvenda() { return pvenda = pcusto + (pcusto*perc/100); } main() { Venda(); printf("Valor com Desconto: %.2f",Valvenda()); } <file_sep>/Tema 9 - Programação modular procedimentos e funções/Ex3Media.cpp #include<stdio.h> float nota1, nota2, media; void leitura(){ printf("Digite a primeira nota:"); scanf("%f",&nota1); printf("Digite a segunda nota:"); scanf("%f",&nota2); } void saida() { printf("Media = %.1f",media); } int main(){ leitura(); media = (nota1+nota2)/2; saida(); } <file_sep>/Tema 7 - Estrutura de repetição WHILE/Exemplos com While/while2.c #include<stdio.h> main() { int i=1; float VOLUME,RAIO,ALTURA; while(i<=10) { printf("\n ---------------------"); printf("\n Raio : "); scanf("%f",&RAIO); printf("\n Altura: "); scanf("%f",&ALTURA); VOLUME=3.14159*(RAIO*RAIO)*ALTURA; printf("\n Volume da lata = %8.3f",VOLUME); i++; } } <file_sep>/Tema 7 - Estrutura de repetição WHILE/Q1.cpp #include<stdio.h> int main() /*Faça um programa que leia 20 números positivos e calcule a quantidade de números pares e ímpares, a média de valores pares e a média geral dos números lidos. */ { int num,par=0,impar=0; printf("Digite 20 número (zero) para sair.\n"); scanf("%d",&num); while(num!=0){ printf("Digite 20 números (zero) para sair.\n"); scanf("%d",&num); if(num%2==0){ par++; } else{ impar++; } } printf("\n Numeros Pares: %d",par); printf("\n Numeros Impares: %d",impar); } <file_sep>/Tema 4 - Exercícios 1/Q1.c #include<stdio.h> main() { /*Uma empresa resolveu conceder descontos de 10% nas vendas superiores a 1000 reais. Faça um programa que leia o valor da venda e informe o valor a ser pago. */ float venda, valorpg ,desconto; printf("Informe o valor da venda:"); scanf("%f",&venda); printf("Valor de desconto da empresa:"); scanf("%f",&desconto); valorpg = (desconto * venda) * 10/100; if(venda > 400) { printf("voce ganhou desconto!"); } else { printf(" \n infelizmente voce nao ganhou desconto compra abaixo de 400"); } printf("O valor com desconto a ser pago sera: %.2f",valorpg); } <file_sep>/Tema 8 - Estrutura de repetição Do..WHILE/Exemplo3.cpp #include<stdio.h> int main(){ int op,l1,l2; float area; do{ printf("\n -- Calculo de Areas -- \n"); printf("1-Quadrado\n"); printf("2-Triangulo\n"); printf("3-Retangulo\n"); printf("4-Sair\n"); printf("Escolha uma opcao:\n"); scanf("%d",&op); switch(op){ case 1:{ printf("Informe o lado do Quadrado:"); scanf("%d",&l1); area = l1*l1; printf("Area: %.1\n",area); break; } case 2:{ printf("Informe a base do Triangulo:"); scanf("%d",&l1); printf("Informe a altura do Triangulo:"); scanf("%d",&l2); area=(l1*l2)/2; printf("Area: %.1f\n",area); break; } case 3:{ printf("Informe a base do Retangulo:"); scanf("%d",&l1); printf("Informe a altura do Retangulo:"); scanf("%d",&l2); area=(l1*l2)/2; printf("Area: %.1f\n",area); break; } case 4:{ printf("Saindo..."); break; } default :{ printf("\n Opcao invalida!!"); break; } } }while(op!=0); } <file_sep>/Tema 8 - Exercícios/Q2.cpp #include<stdio.h> int main(){ int x, maior,i=1; do{ printf("Informe um numero:"); scanf("%d",&x); if(x!=9999) { if((x>maior) || (i==1)) maior=x; i++; } }while(x!=9999); printf("Maior:%d",maior); } <file_sep>/Tema 6 - Exercícios/Q4.cpp #include<stdio.h> int main() { int n; for(n=7;n<100;n+=7) printf("Numeros multiplos a 7: %d\n",n); } <file_sep>/Tema 7 - Estrutura de repetição WHILE/Exemplos com While/while1.c #include<stdio.h> main() { int i=1; float C,F; while(i<=5) { printf("\n Celsius :"); scanf("%f",&C); F=(9*C+160)/5; printf("\n Farenheit : %f",F); i++; } } <file_sep>/Tema 8 - Estrutura de repetição Do..WHILE/Ex2video.cpp #include<stdio.h> int main(){ int i; do{ printf("\n(1)-"); printf("\n(2)-"); printf("\n(3)-\n:"); scanf("%d",&i); }while((i<1) || (i>3)); printf("Fim do Programa!"); } <file_sep>/Tema 9 - Programação modular procedimentos e funções/Ex4AreaTrian.cpp #include<stdio.h> float AreaTriangulo(int a, int b) { return(a*b/2); } int main() { int base, alt; float res; printf("Informe a base do triangulo:"); scanf("%d",&base); printf("Informe a altura do triangulo:"); scanf("%d",&alt); res = AreaTriangulo(base,alt); printf("A area do Triangulo e: %f\n",res); } <file_sep>/Tema 10 - Passagem de Parâmetros/Exemplo4.cpp #include<stdio.h> void troca(int*n1,int*n2){ int aux; aux = *n1; *n1 = *n2; *n2 = aux; } int main(){ int a,b; printf("Informe dois numeros:"); scanf("%d %d",&a,&b); printf("Antes: %d - %d\n",a,b); troca(&a,&b); printf("Apos: %d - %d\n",a,b); } <file_sep>/Tema 8 - Estrutura de repetição Do..WHILE/Solução Proposta/Tema8_Ex1_1b.cpp #include<stdio.h> main() { int num,soma=0,q=0; float media; do { printf("\n Numero: "); scanf("%d",&num); if(num==9999) break; soma=soma+num; //ou soma+=num; q=q+1; //ou q++; }while(num!=9999); media=soma/q; printf("\n Soma = %d",soma); printf("\n Media = %4.1f",media); } <file_sep>/Tema 8 - Estrutura de repetição Do..WHILE/Exemplo2.cpp #include<stdio.h> int main(){ int num; do{ printf("\nInforme um numero Positivo:"); scanf("%d",&num); } while(num<0); printf("Numero positivo: %d",num); } <file_sep>/Tema 3 - Estrutura sequencial/operadoresRelacionais.cpp #include<stdio.h> int main () { int n1 = 3, n2 = 4, r1,r2,r3; r1 = n1 > n2; // o valor de r1 sera 0 r2 = (n1*2) != n2; // o valor de r2 será 1 r3 = n2 >= n1; // o valor de r3 sera 1 }<file_sep>/Tema 6 - Exercícios/Q5.cpp #include<stdio.h> int main() { int num,tabuada; printf("\n Entre com um numero: "); scanf("%d",&num); printf("\n Tabuada do numero: %d",num); for(tabuada=1;tabuada<=10;tabuada++) printf("\n %d x %d = %d",num,tabuada,tabuada*num); } <file_sep>/Tema 7 - Estrutura de repetição WHILE/Ex1.cpp #include<stdio.h> int main(){ int cont,par=0,impar=0; cont=1; while(cont<=20){ // condicão para que a repetição seja realizada printf("%d\n",cont); cont++;// incremento da variavel para atualiza-la if(cont%2==0) par++; else impar++; } printf("Par: %d\n",par); printf("Impar: %d\n",impar); } <file_sep>/Tema 8 - Estrutura de repetição Do..WHILE/Solução Proposta/Tema8_Ex1_6.cpp #include<stdio.h> #include<locale.h> main() { setlocale(LC_ALL,""); int Mat,total=0,totalaprov=0,totalrepro=0; float Nota1, Nota2 , Nota3, Media; do { printf("\n Matrícula: "); scanf("%d",&Mat); if(Mat==9999) break; printf("\n Nota1 : "); scanf("%f",&Nota1); printf("\n Nota2 : "); scanf("%f",&Nota2); printf("\n Nota3 : "); scanf("%f",&Nota3); Media = ((2*Nota1)+(3*Nota2)+(4*Nota3))/9; if(Media>=5) { printf("\n Matrícula= %d - Média Final= %4.1f - APROVADO",Mat,Media); printf("\n ==============================================="); totalaprov++; } else { printf("\n Matrícula= %d - Média Final= %4.1f - REPROVADO",Mat,Media); totalrepro++; } } while(Mat!=9999); total = totalaprov + totalrepro; printf("\n Total de Aprovados = %d",totalaprov); printf("\n Total de Reprovados = %d",totalrepro); printf("\n Total de Alunos = %d",total); } <file_sep>/Tema 8 - Estrutura de repetição Do..WHILE/Solução Proposta/Tema8_Ex1_3.cpp #include<stdio.h> main() { int x,QPares=0,QImpares=0; do { printf("\n Entre com o numero: "); scanf("%d",&x); if(x==9999) break; if(x%2==0) QPares++; else QImpares++; } while(x!=9999); printf("\n Quantidade de pares: %d",QPares); printf("\n Quantidade de impares: %d",QImpares); } <file_sep>/Exercícios - Tema 9/Questão4.cpp #include<stdio.h> float vdolar,cdolar,vreal; void Cotacao() { printf("Entre com a quantidade de dolares:")/ scanf("%f",&vdolar); printf("Entre com a cotacao do dolar atual:"); scanf("%f",&cdolar); } float Conversor() { return vreal = vdolar*cdolar; } int main() { Cotacao(); printf("\n Valor em Reais: %8.2f",Conversor()); } <file_sep>/Tema 4 - Exercícios 2/ex2.c #include <stdio.h> #include <string.h> main() { float SAL, NSAL, AUMENTO; char CARGO[10]; printf("\n Salario : "); scanf("%f", &SAL); printf("\n Cargo : "); scanf("%s", CARGO); printf("\n Cargo informado= %s", CARGO); if (strcmp(CARGO, "GERENTE") == 0) AUMENTO = SAL * 25 / 100; else if (strcmp(CARGO, "ENGENHEIRO") == 0) AUMENTO = SAL * 20 / 100; else if (strcmp(CARGO, "TECNICO") == 0) AUMENTO = SAL * 15 / 100; else AUMENTO = SAL * 10 / 100; NSAL = SAL + AUMENTO; printf("\n Salario : %8.2f", SAL); printf("\n Novo Salario : %8.2f", NSAL); printf("\n Aumento : %8.2f", AUMENTO); }<file_sep>/Tema 6 - Exercícios/Q1.cpp #include<stdio.h> /* Tema 6 - Exercícios 1 1- Faça um programa que leia cinco temperaturas em graus Celsius e apresente-as convertidas em graus Fahrenheit.A fórmula de conversão é: F = (9 * C + 160) / 5, na qual F é a temperatura em Fahrenheit e C é a temperatura em Celsius. */ int main() { float F,C; int cont; for(cont=1;cont<=5;cont++){ printf("Informe a temperatura atual: "); scanf("%f",&C); printf("Temperatura atual: \n%.2f",C); F=(9 * C + 160)/5; printf("\nConvertida em Fahrenheit: \n%.2f",F); } } <file_sep>/Tema 3 - Exercícios 1/Q2.c #include <stdio.h> main() { float N1, N2, N3, M; printf("\nEntre com a nota 1: "); scanf("%f", &N1); printf("\nEntre com a nota 2: "); scanf("%f", &N2); printf("\nEntre com a nota 3: "); scanf("%f", &N3); M = (N1 + N2 + N3) / 3; printf("A media e' %.1f \n", M); }<file_sep>/Tema 4 - Exercícios 2/Exercicio-1.cpp #include<stdio.h> int main() { int idade; printf("Informe sua Idade: "); scanf("%d",&idade); if ( (idade >=5) || (idade <=7)){ printf("\n Infantil A "); } else if((idade >= 8 ) && (idade <=10)){ printf("\n Infantil B "); } else if((idade >=11) && (idade <=13)){ printf("\n Juvenil A "); } else if ((idade >=14) && (idade <=17)){ printf("\n Juvenil B "); } else { printf("\n Adulto "); } }<file_sep>/Tema 2 - Comandos de atribuição e de entrada e saida de dados/operadoresAritmeticos.cpp #include<stido.h> int main() { int n1 = 3, n2 = 4,r,res; // declaração de variaveis de inicialização. n1 = n1 + 5; // o valor de n1 será 8 r = n1 + n2; // o valor de r será 12 res = n2 % 2; // o valor do resto será 0. }<file_sep>/Tema 3 - Exercícios 2/Q1.c #include<stdio.h> main() /* Fazer um algoritmo ler uma temperatura dada em graus Celsius e imprimir o equivalente em Farenheit. */ { float C,F; printf("\nInforme os graus C:"); scanf("%f",&C); F = C * 9/5 + 32; printf("\n O valor convertido: %.2f e graus %.2f", F,C); } <file_sep>/Exercícios - Tema 9/Questão3.cpp #include<stdio.h> float valor,nvalor,desconto; void Entrada() { printf("\n Entre com o calor do produto:"); scanf("%f",&valor); } float Desconto() { return desconto = (valor*9/100) ; } float Nvalor() { return nvalor = (valor-desconto); } int main() { Entrada(); printf("Desconto = %.2f\n",Desconto()); printf("Valor com desconto = %.2f",Nvalor()); } <file_sep>/Tema 4 - Exercícios 1/Q2.c #include<stdio.h> main() { /*2. Entrar com 3 notas de um aluno e informar a sua situação (APROVADO caso média aritmética >=7 e REPROVADO caso contrário). */ float n1,n2,n3,media; printf("informe a primeira nota:"); scanf("%f",&n1); printf("informe a segunda nota:"); scanf("%f", &n2); printf("informe a terceira nota:"); scanf("%f", &n3); media = (n1 + n2 +n3)/3; if(media >= 7){ printf("Aluno Aprovado!"); } else { printf("Aluno Reprovado!"); } }<file_sep>/Tema 4 - Exercícios 1/AV2.c #include<stdio.h> main() { /* O programa deverá informar: O valor a pagar pelo cliente; Uma mensagem com o voucher de desconto do cliente para a próxima compra (caso se aplique); O percentual de brigadeiros comprados por esse cliente, considerando o estoque informado pelo usuário; O estoque atualizado após a compra. */ int D1, S2, T3, Q4, estoque; float brigadeiros, preco, dia; printf("\n +**+*+*+ BRIGADEIROS & CIA +*+*+*+*+"); printf("Informe a quantidade de brigadeiros no ESTOQUE:"); scanf("%d",&estoque); printf("\n Quantos brigadeiros voce comprou: "); scanf("%f",&brigadeiros); printf("\n Em que dia da semana voce comprou?"); scanf("%f",&dia); printf("\n Quantos reais voce pagou:"); scanf("%f",&preco); }<file_sep>/Tema 3 - Exercícios 1/Q5.c #include<stdio.h> main() { float reais,dolar,cotacao; printf("Quantos folares voce tem guardado: "); scanf("%f",&dolar); printf("Qual e a cotacao do dolar:"); scanf("%f",&cotacao); reais = dolar*cotacao; printf("Voce possui %.2f convertido em reais",reais); }<file_sep>/Tema 10 - Passagem de Parâmetros/Exparam.cpp #include<stdio.h> float Areadotriangulo(int b,int a){ return(a*b/2); } int main(){ int base, alt; float res; printf("Informe a base do triangulo:"); scanf("%d",&base); printf("Informe a altura:"); scanf("%d",&alt); res = Areadotriangulo(base,alt); printf("A Area do Triangulo e: %f",res); } <file_sep>/Exercícios - Tema 9/Questão2.cpp #include<stdio.h> float nota1,nota2,nota3,media; void Entrada() { printf("Informe 3 notas:"); scanf("%f %f %f",&nota1, &nota2,&nota3); } float Media() { return(nota1+nota2+nota3)/3; } int main() { Entrada(); printf("A media do aluno: %6.2f",Media()); } <file_sep>/Tema 8 - Estrutura de repetição Do..WHILE/Ex1video.cpp #include<stdio.h> int main(){ int a,b, maior, menor; printf("Digite dois valores inteiros:"); scanf("%d",&a); scanf("%d",&b); do{ printf("%d\n",a); a++; }while(a<b); printf("Fim do programa!"); } <file_sep>/Tema 4 - Exercícios 1/posto2.c #include <stdio.h> int main() { float litros = 0, total = 0, desconto = 0, total2 = 0; char combustivel; printf("Digite o combustivel: A - Alcool ou G - Gasolina \n"); scanf("%c", &combustivel); if (combustivel == 'A' || combustivel == 'a') { printf("O combustivel escolhido Alcool = 3.90/L\n"); printf("Digite a quantidade de litros:\n"); scanf("%f", &litros); if (litros <= 20.00) { total = litros * 3.90; desconto = litros * (3.90 * 0.03); total2 = total - desconto; printf("Valor a ser pago %.2f\n", total2); } else if (litros > 20.00) { total = litros * 3.90; desconto = litros * (3.90 * 0.05); total2 = total - desconto; printf("Valor a ser pago %.2f\n", total2); } } else if (combustivel == 'G' || combustivel == 'g') { printf("\n O combustivel escolhido Gasolina: 4.30/L"); printf("\n Digite a quantidade de litros:"); scanf("%f", &litros); if (litros <= 20.00) { total = litros * 4.30; desconto = litros * (4.30 * 0.04); total2 = total - desconto; printf("Valor a ser pago: %.2f\n", total2); } else if (litros > 20.00) { total = litros * 4.30; desconto = litros * (4.30 * 0.06); total2 = total - desconto; printf("Valor a ser pago: %.2f\n", total2); } } } <file_sep>/Tema 8 - Estrutura de repetição Do..WHILE/Solução Proposta/Tema8_Ex1_1a.cpp #include<stdio.h> main() { int x, soma=0, q=0; float media; do { printf("\n Numero: "); scanf("%d",&x); if(x!=9999) { soma=soma+x; q++; } } while(x!=9999); media=soma/q; printf("\n Soma= %d",soma); printf("\n Media= %6.1f",media); } <file_sep>/Tema 3 - Exercícios 2/Q5.c #include<stdio.h> main() { /*. Escrever um algoritmo que leia o valor de uma compra em dólares, a cotação do dólar no dia da compra, o percentual de ICMS e o percentual de lucro da empresa. Calcule e escreva o valor a ser pago em reais, sabendo-se que o percentual de lucro e o percentual de ICMS incidem sobre o valor em reais.*/ float compra, cotacao, icms, lucro, reais; printf("\n Informe o valor da compra em dolares:"); scanf("%f",&compra); printf("\n Qual e a cotacao do dolar hoje:"); scanf("%f",&cotacao); printf("\n Qual e o porcentual de lucro da empresa: "); scanf("%f",&lucro); reais = compra *cotacao + 1/100; printf("o valor a ser pago sera %.2f",reais); }<file_sep>/Tema 3 - Estrutura sequencial/Ex4.cpp #include<stdio.h> int main() { int n1, n2, produto; printf("Informe 2 numeros:"); scanf("%d",&n1); scanf("%d",&n2); produto = n1 * n2; printf("Produto dos numeros informados: %d",produto); }<file_sep>/Tema 3 - Exercícios 2/Q4.c #include<stdio.h> main() { /*Escrever um algoritmo que leia o nome de um funcionário, seu numero de horas trabalhadas, o valor que recebe por hora, o número de filhos com idade menor que 14 anos e o valor do salário família (pago por filho com menos de 14 anos), e que calcule o salário total deste funcionário. Ao final escreva o seu nome e o seu salário total.*/ char nome[40]; int qfilhos, horastrab; float salario, valorh,salariototal; printf("\n Nome do funcionario:"); scanf("%s",&nome); printf(" \n Valor recebido por horas: "); scanf("%f",&valorh); printf("\n número de filhos com idade menor que 14 anos:"); scanf("%d",&qfilhos); printf("\n Informe o salario:"); scanf("%f",&salario); salariototal = (valorh*qfilhos) + salario; printf(" \n %s o seu salario sera: %.2f",nome,salariototal); } <file_sep>/Exercícios - Tema 9/Questão1.cpp #include<stdio.h> int numero; void Entrada(){ printf("Entre com um numero inteiro:"); scanf("%d",&numero); } int Quadrado() { return (numero*numero); } int main() { Entrada(); printf("O quadrado do numero: %d e %d\n",numero,Quadrado()); } <file_sep>/Tema 9 - Programação modular procedimentos e funções/Ex1.cpp #include<stdio.h> int n1; // global int Square () { return (n1*n1); } int main() { int n2; //local printf("Entre com um numero:"); scanf("%d",&n1); n2 = Square (); printf("O seu quadrado vale: %d\n",n2); } <file_sep>/Tema 8 - Estrutura de repetição Do..WHILE/Exemplo1.cpp #include<stdio.h> int main(){ int i; i = 1; do{ printf("%d\n",i); i++; }while(i<=10); } <file_sep>/Tema 8 - Exercícios/Q5.cpp #include<stdio.h> int main(){ int Matricula, Aprovado=0,Reprovado=0,Total=0; float Nota1,Nota2,Nota3,Mediafinal; do{ printf("\nMatricula:\n"); scanf("%d",&Matricula); if(Matricula==9999){ break; } printf("Nota1:"); scanf("%f",&Nota1); printf("Nota2:"); scanf("%f",&Nota2); printf("Nota3:"); scanf("%f",&Nota3); Mediafinal = ((2*Nota1)+(3*Nota2)+(4*Nota3))/9; if(Mediafinal>=5){ printf("\nAprovado"); printf("\nMatricula: %d",Matricula); printf("\nMedia Final: %.1f",Mediafinal); Aprovado++; }else{ printf("\nAprovado"); printf("\nMatricula: %d",Matricula); printf("\nMedia Final: %.1f",Mediafinal); Reprovado++; } }while(Matricula!=9999); Total = Aprovado + Reprovado; printf("\nTotal de Alunos:%d",Total); printf("\nTotal de Aprovados: %d",Aprovado); printf("\nTotal de Reprovados: %d",Reprovado); } <file_sep>/Tema 3 - Exercícios 2/Q2.c #include<stdio.h> main() { /* Fazer um algoritmo ler uma quantidade de chuva dada em polegadas e imprimir o equivalente em milímetros (1 polegada = 25,4 mm). */ float chuva,milimetros; printf("Informe a quantidade de chuva:"); scanf("%f",&chuva); milimetros = chuva*25.4; printf("A quantidade de chuva por milimetros e: %f",milimetros); }<file_sep>/Tema 3 - Estrutura sequencial/operadoresLogicos.cpp #include<stdio.h> int main() { int n1 = 3, n2 = 4, r1, r2, r3; //declaração de variáveis e inicialização. r1 = ((n1 < 2) || (n1 > 10)); //O valor de r1 será 0. r2 = (((n1 + n2)>5) && ((n1+n2)<10)); //O valor de r2 será 1. r3 = !(n2>5); //o valor do resto será 1. }<file_sep>/Tema 7 - Estrutura de repetição WHILE/Ex2.cpp #include<stdio.h> int main(){ int x,y; x = 1; y = 5; while(x < y){ x = x + 2; y = y + 1; } } <file_sep>/Tema 7 - Estrutura de repetição WHILE/tabuada.cpp #include<stdio.h> int main(){ int num, tabuada = 1;// inicialização; printf("Entre com um numero para a tabuada.\n"); scanf("%d",&num); while(tabuada<=10){// vericicação do laço se tabuada que é 1 é menor que 20, assim repetindo printf("Tabuada do numero: %d x %d = %d\n",num, tabuada,num*tabuada); tabuada++; } } <file_sep>/Exercícios - Tema 9/Questão5.cpp #include <stdio.h> float valor,prest; void Valproduto() { printf("Entre com o valor do produto:"); scanf("%f",&valor); } float Prestacao() { return prest=valor/5; } main() { Valproduto(); printf("\n Valor das prestacoes: %8.2f",Prestacao()); } <file_sep>/Tema 7 - Estrutura de repetição WHILE/Exemplos com While/while3.c #include<stdio.h> main() { char RESP='S'; float VOLUME,RAIO,ALTURA; while(RESP=='S') { printf("\n ---------------------"); printf("\n Raio : "); scanf("%f",&RAIO); printf("\n Altura: "); scanf("%f",&ALTURA); VOLUME=3.14159*(RAIO*RAIO)*ALTURA; printf("\n Volume da lata = %8.3f",VOLUME); printf("\n\n Tem mais lata (S/N)? "); scanf(" %c",&RESP); } } <file_sep>/Tema 7 - Estrutura de repetição WHILE/visitantes.cpp #include<stdio.h> int main() { int visitantes,soma,cont; float media; soma = 0; cont = 0; printf("\n Informe a quantidade de visitantes (0 para sair!): "); scanf("%d",&visitantes); while(visitantes!=0){ soma = soma + visitantes; cont++; printf("\n Informe a quantidade de visitantes (0 para sair!): "); scanf("%d",&visitantes); } if(cont>0){ media = soma/cont; printf("media de visitantes e: %.1f",media); }else{ printf("Nao foi informado nenhum visitante!"); } } <file_sep>/Tema 3 - Estrutura sequencial/Ex3.cpp #include<stdio.h> int main(){ int n1, n2,n3,n4,soma; printf("informe 4 numeros inteiros:"); scanf("%d",&n1); scanf("%d",&n2); scanf("%d",&n3); scanf("%d",&n4); soma = n1+n2+n3+n4; printf("A soma dos numeros informados: %d",soma); }<file_sep>/Tema 4 - Exercícios 1/posto.c #include<stdio.h> int main() { float litros, total, desconto, total2; char combustivel; printf(" \n Digite A - Alcool OU para G - Gasolina: "); scanf("%c",&combustivel); if (combustivel == 'A' || combustivel == 'a') { printf("\n O combustivel escolhido foi Alcool 3.90L"); printf("\n Digite a quantidade de litros:"); scanf("%f",litros); if (litros <= 20.00) { total = litros * 3.90; desconto = litros * (3.90 * 0.03); total2= total - desconto; printf("\n Valor a pagar: %.2f", total2); } else if(litros > 20.00) { total = litros * 3.90; desconto = litros * (3.90 * 0.05); total2 = total - desconto; printf("\n Valor a pagar: %.2f", total2); } } else if(combustivel == 'G' || combustivel == 'g') { printf("\n O combustivel escolhido foi Gasolina 4.30L"); printf("\n Digite a quantidade de litros:"); scanf("%f", litros); if (litros <= 20.00) { total = litros * 4.30; desconto = litros * (4.30 * 0.04); total2 = total - desconto; printf("\n Valor a pagar %.2f", total2); } else if(litros >= 20.00) { total = litros * 4.30; desconto = litros * (4.30 * 0.06); total2 = total - desconto; printf("\n Valor a pagar %.2f", total2); } } }<file_sep>/Tema 7 - Estrutura de repetição WHILE/Ex3.cpp #include<stdio.h> int main(){ int idade, soma,cont; float media; soma = 0; cont = 0; printf("\n Informe uma idade: (Digite 0 para sair!)"); scanf("%d",&idade); while(idade!=0){ soma = soma + idade; cont++; printf("\n Informe uma idade: (Digite 0 para sair!)"); scanf("%d",&idade); }if(cont>0){ media = soma/cont; printf("Media das idades: %.1f",media); }else{ printf("Nao foi informado uma idade valida!"); } } <file_sep>/Tema 10 - Passagem de Parâmetros/Exemplo2.cpp #include<stdio.h> void troca(int n1, int n2){ int aux; aux = n1; n1 = n2; n2 = aux; } int main(){ int a, b; printf("\nDigite doi numeros:"); scanf("%d %d",&a, &b); printf("\nAntres: %d - %d",a,b); troca(a,b); printf("\nApos: %d - %d",a,b); } <file_sep>/Tema 8 - Exercícios/sintaxe.cpp #include<stdio.h> int main(){ do{ comandos }while(condicao); } <file_sep>/Tema 1 - Conceitos básicos da Línguagem C/EstruturaBasica.cpp #include<stdio.h> // Comando de pré-processamento Biblioteca de entrada e saída de dados. int main() // Função principal. { printf("<NAME>!"); // Escrevendo na tela. }<file_sep>/Tema 10 - Passagem de Parâmetros/Exemplo1.c #include<stdio.h> // Passagem de Parametro por Referencia void troca(int *n1,int *n2){ int aux; aux = *n1; *n1 = *n2; *n2 = aux; } int main(){ int a,b; printf("Informe dois numeros:"); scanf("%d %d",&a,&b); printf("Antes: %d - %d\n",a,b); troca(&a,&b); printf("Apos: %d - %d\n",a,b); } <file_sep>/Tema 4 - Exercícios 1/AV3.c #include<stdio.h> int main() { /* */ float litros, total, desconto; char combustivel; printf("Digite A para Alcool ou G para Gasolina:"); scanf("%c",&combustivel); if (combustivel == 'a' && litros <= 20) { total = (litros * 3.30); desconto = total - (total *100/30); printf("O total de alcool a ser pago e: %2.f", desconto); } else { total = (litros * 3.90); desconto = total - (total *100/50); printf("O total de alcool a ser pago é %.2f", desconto); } if (combustivel == 'g' && litros <= 20) { total = (litros *4.30); desconto = total - (total *100/40); printf("O total de alcoll a ser pago e: %.2f", desconto); } else { total = (litros * 4.30); desconto = total - (total * 100/60); } <file_sep>/Tema 8 - Estrutura de repetição Do..WHILE/Solução Proposta/Tema8_Ex1_5.cpp #include<stdio.h> main() { int PT,ST,TS,FN,X; printf("\n Entre com o numero de termos: "); scanf("%d",&FN); if (FN<2) printf("\n O numero deve ser maior ou igual a 2"); else { PT=0; ST=1; X=2; printf("%d ",PT); printf(", %d ",ST); do { TS=PT+ST; printf(", %d ",TS); PT=ST; ST=TS; X++; } while(X<FN); } } <file_sep>/Tema 4 - Estrutura de seleção IF e ELSE/Ex2.cpp #include<stdio.h> int main() { /* Exemplo 4: Programa com tratamento de mais do que duas condições. Considere que ao contexto do programa da média seja acrescentada uma nova condição: se o aluno tiver média entre 3.0 e 7.0, ele poderá fazer uma prova final. Apenas estará reprovado o aluno que obter uma média abaixo de 3.0. Nesse caso, mais uma condição seria necessária. */ float nota1, nota2, media; printf("\nInforme a primeira nota: "); scanf("%f",&nota1); printf("\nInforme a segunda nota: "); scanf("%f",&nota2); media = (nota1 + nota2)/2; printf("\n Media: %.1f\n",media); if(media>=7) printf("\n Aprovado!"); else{ if(media>=3 && media<7) printf("\n Aluno de Recuperacao"); else printf("Aluno Reprovado:"); } } <file_sep>/Tema 4 - Estrutura de seleção IF e ELSE/Ex1.cpp #include<stdio.h> int main() { float nota1, nota2,media; printf("\n Informe a primeira nota: "); scanf("%f",&nota1); printf("\n Informe a segunda nota: "); scanf("%f",&nota2); media = (nota1 + nota2)/2; if (media >= 7) printf("\n Aluno aprovado %.1f",media); } <file_sep>/Tema 9 - Programação modular procedimentos e funções/Ex2.cpp #include<stdio.h> int n1; // global int Square () { return (n1*n1); } int main() { printf("Entre com um numero:"); scanf("%d",&n1); printf("O seu quadrado vale: %d\n",Square()); } <file_sep>/Tema 3 - Exercícios 1/Q1.c #include<stdio.h> main() { /*1. Dado um número inteiro não-nulo, imprima o seu quadrado. */ int numero, quadrado; printf("Informe um numero nao nulo: "); scanf("%d",&numero); quadrado = numero* numero; printf("/n O quandrado do numero informado é: %d e" "%d",quadrado,numero); }<file_sep>/Tema 3 - Exercícios 1/Q3.c #include<stdio.h> main() { /* Faça um programa que leia as 3 notas de um aluno e calcule a média final deste aluno. Considerar que a média é ponderada e que o peso das notas é: 2,3 e 5, respectivamente. */ float N1,N2,N3, M; printf("\nEntre com a nota 1: "); scanf("%f", &N1); printf("\nEntre com a nota 2: "); scanf("%f", &N2); printf("\nEntre com a nota 3: "); scanf("%f", &N3); M = (N1*2 + N2*3 + N3*5) /10; printf("A media e' %.1f \n", M); }<file_sep>/Tema 8 - Exercícios/Q4.cpp #include<stdio.h> int main(){ int FN, } <file_sep>/Tema 7 - Estrutura de repetição WHILE/While.cpp #include<stdio.h> int main() { int num,par=0, impar=0,quantidade=0; printf("Digite 20 numeros -0 para sair.\n"); scanf("%d",&num); while(num !=0){ quad = num*num; printf("Quadrado de %d = %d\n",num,quad); printf("Digite um numero -0 para sair.\n "); scanf("%d",&num); quantidade ++; } printf("Quantidade de repeticoes: %d\n",quantidade); }
221612afde8e6b48f07c82dc2033aa906a7167d2
[ "Markdown", "C", "C++" ]
80
Markdown
daniel0ferraz/Introducao-a-Programacao
e6bd16962f44649a5108236da2f01682d5fcfc58
3538960f7e6ce798c32527b0c194f2434ea28dfe
refs/heads/master
<file_sep>// First, create an object containing LatLng and revenue for each customer. var customers = [ { postal_code: "3454+LD", revenue: 2714856, lat: 52.0823742, lng: 5.0764477 }, { postal_code: "3455+AB", revenue: 8405837, lat: 52.1823742, lng: 5.1764477 }, { postal_code: "3456+AB", revenue: 3857799, lat: 52.0823742, lng: 5.1764477 }, { postal_code: "3457+AA", revenue: 603502, lat: 52.1823742, lng: 5.0764477 }, ]; <file_sep>$(function() { // maak de verzend knop inactief $("#button").attr("disabled", "disabled"); // laad de validatie bibliotheek en wacht een halve seconde na focus var pcode = new LiveValidation( "postcode", { validMessage: " OK", wait: 500 } ); // leeg veld melding toevoegen pcode.add( Validate.Presence, { failureMessage: " Het postcode veld is verplicht" } ); // formaat controle pcode.add( Validate.Format, { pattern: /^[1-9][0-9]{3}[ ]?([A-RT-Za-rt-z][A-Za-z]|[sS][BCbcE-Re-rT-Zt-z])$/, failureMessage: " Incorrecte postcode, formaat is 1234AB" } ); pcode.onValid=function() // validatie succesvol { var zip = $("#postcode").val(); // sla op in variabele zip zip = zip.toUpperCase(); // hoofdletters zip = zip.replace(" ", ""); // verwijder spatie $("#postcode").val(zip); // zet terug in formulier $("#button").removeAttr("disabled"); // maak de verzend knop actief } $( "#postcode" ).keyup(function() // fout { $("#msg").html('') // haal vink weg $("#button").attr("disabled", "disabled"); // maak de verzend knop inactief }) $( "#button" ).click(function() { $("frm").submit(); // verstuur formulier $("#button").attr("disabled", "disabled"); // maak de verzend knop inactief }) }); <file_sep>import csv import sys import json import requests fieldnames=["id","postal_code","revenue","lat","lng"] def convert(): csv_filename = "data.csv" print ("Opening CSV file: ", csv_filename) f = open(csv_filename, 'r') csv_reader = csv.DictReader(f,fieldnames) json_filename = csv_filename.split(".")[0]+".js" # customers.js print ("Saving JSON to file: ", json_filename) jsonf = open(json_filename,'w') jsonf.write("var customers = [") for record in csv_reader: url = "https://maps.googleapis.com/maps/api/geocode/json?key=<KEY>&address={}+Netherlands".format(record["postal_code"]) response = requests.get(url) parsed = response.json() jsonf.write("{") jsonf.write("postal_code:\"{}\",".format(record["postal_code"])) jsonf.write("revenue:{},".format(record["revenue"])) jsonf.write("lat:{},".format(parsed["results"][1]["geometry"]["location"]["lat"])) jsonf.write("lng:{}".format(parsed["results"][1]["geometry"]["location"]["lng"])) jsonf.write("},") jsonf.write("];") f.close() jsonf.close() if __name__=="__main__": convert() <file_sep>function Get(url){ var request = new XMLHttpRequest(); request.open("GET",url,false); request.send(null); return request.responseText; } function initMap() { console.log("initMap"); loadMap("3454+LD"); } function loadMap(postalCode) { console.log("initMap(" + postalCode + ")"); var json = Get("https://maps.googleapis.com/maps/api/geocode/json?key=<KEY>&address=" + postalCode + "+Netherlands"); console.log(json); var parsed = JSON.parse(json); var location = parsed.results[1].geometry.location; createMap(location) } function createMap(location) { console.log("createMap"); var map = new google.maps.Map(document.getElementById('googleMap'), { center: location, zoom: 10 }); google.maps.event.addListener(map, "rightclick", function(event) { var lat = event.latLng.lat(); var lng = event.latLng.lng(); createMap(new google.maps.LatLng(lat, lng)) }); // Create a marker and set its position. var marker = new google.maps.Marker({ map: map, position: location, title: 'Uw bouwbedrijf' }); // Construct the circle for each value in customers. // We scale the area of the circle based on the revenue. for (var c in customers) { var circle = new google.maps.Circle({ strokeColor: '#FF0000', strokeOpacity: 0.8, strokeWeight: 2, fillColor: '#FF0000', fillOpacity: 0.35, map: map, center: new google.maps.LatLng(customers[c].lat, customers[c].lng), radius: Math.sqrt(customers[c].revenue) * 2 }); } } function reLoadMap() { console.log("reLoadMap"); var postalCode = $('#postcode').val(); if (postalCode.length == 6) { initMap(postalCode.replace(" ", "+")) } } //google.maps.event.addDomListener(window, 'load', initMap());
e4142c019744b498f48c3faf0ba60c16cd2c09ef
[ "JavaScript", "Python" ]
4
JavaScript
geerdink/hack_maps
df8fe6d66d71e99393168af6c3bbd8bd174efbc4
cf85db12e90fe9b7bb91d9c1941b285a639ec20c
refs/heads/main
<repo_name>Rafaeloli200/padroesObserverMemento<file_sep>/src/main/java/Memento/Tripulante.java /* Tripulantes são colaboradores como os pilotos, copilotos e aeromoças, que estão constantemente viajando */ package Memento; import java.util.ArrayList; import java.util.List; public class Tripulante { private String nome; private EstadoDoTripulante estado; private List<EstadoDoTripulante> memento = new ArrayList<EstadoDoTripulante>(); public Tripulante() { this.estado = TripulanteEstadoDisponivel.getInstance(); } public void setEstado(EstadoDoTripulante estado) { this.estado = estado; this.memento.add(this.estado); } public void restauraEstado(int indice) { if (indice < 0 || indice > this.memento.size() - 1) { throw new IllegalArgumentException("indice invalido"); } this.estado = this.memento.get(indice); } public List<EstadoDoTripulante> getEstados() { return this.memento; } public EstadoDoTripulante getEstado() { return estado; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String disponibilizar() { return estado.disponibilizar(this); } public String desligar() { return estado.desligar(this); } public String decolar() { return estado.decolar(this); } public String aterrissar() { return estado.aterrissar(this); } public String inativar() { return estado.inativar(this); } public String getNomeEstado() { return estado.getEstado(); } } <file_sep>/src/main/java/Memento/EstadoDoTripulante.java package Memento; public interface EstadoDoTripulante { String getEstado(); String disponibilizar(Tripulante tripulante); String desligar(Tripulante tripulante); String decolar(Tripulante tripulante); String aterrissar(Tripulante tripulante); String inativar(Tripulante tripulante); } <file_sep>/src/main/java/Memento/TripulanteEstadoDesligado.java /* Tripulante não trabalha mais na empresa */ package Memento; public class TripulanteEstadoDesligado implements EstadoDoTripulante { private TripulanteEstadoDesligado() {}; private static TripulanteEstadoDesligado instance = new TripulanteEstadoDesligado(); public static TripulanteEstadoDesligado getInstance() { return instance; } @Override public String getEstado() { return "Desligado"; } @Override public String disponibilizar(Tripulante tripulante) { return "O processo falhou"; } @Override public String desligar(Tripulante tripulante) { return "O processo falhou"; } @Override public String decolar(Tripulante tripulante) { return "O processo falhou"; } @Override public String aterrissar(Tripulante tripulante) { return "O processo falhou"; } @Override public String inativar(Tripulante tripulante) { return "O processo falhou"; } } <file_sep>/src/main/java/Memento/TripulanteEstadoDisponivel.java /* Tripulante em trabalho, fora de um voo, localizado na cidade de sua moradia */ package Memento; public class TripulanteEstadoDisponivel implements EstadoDoTripulante { private TripulanteEstadoDisponivel() { } ; private static TripulanteEstadoDisponivel instance = new TripulanteEstadoDisponivel(); public static TripulanteEstadoDisponivel getInstance() { return instance; } @Override public String getEstado() { return "Ativo"; } @Override public String disponibilizar(Tripulante tripulante) { return "O processo falhou"; } @Override public String desligar(Tripulante tripulante) { return "Tripulante desligado"; } @Override public String decolar(Tripulante tripulante) { return "Tripulante em voo"; } @Override public String aterrissar(Tripulante tripulante) { return "Tripulante aterrisado"; } @Override public String inativar(Tripulante tripulante) { return "Tripulante inativado"; } }
4617cfd80c4de8d01817a0bb3f57ccaee9046f64
[ "Java" ]
4
Java
Rafaeloli200/padroesObserverMemento
224bf15b76dce42f27779701abf9753e7432c417
095a23176b2adee80c6611c92f8543a5f8c93a08
refs/heads/main
<repo_name>BukoMoon/Timetable-Organiser<file_sep>/Programming Assignment 2.py def display_timetable(selection: str, selection_type: str, timetable: list): """ Takes timetable and displays information based on selection. :param selection: name of selection - E.g. Ada Log, ABC101 :param selection_type: type of selection - Campus, Lecturer, Subject, Room :param timetable: list created from csv """ print(f'Timetable for {selection_type} "{selection}":') print('=' * 80) print('Subject Activity Day' + (' ' * 7) + 'Start' + (' ' * 5) + 'End' + (' ' * 7) + 'Campus' + (' ' * 4) + 'Room' + (' ' * 6) + 'Lecturer ') print('-' * 80) # Iterates through timetable and for line in timetable: if selection in line: for i in range(8): if i != 7: print(line[i] + (' ' * (10 - len(line[i]))), end='') else: print(line[i] + (' ' * (10 - len(line[i]))), end='\n') print('=' * 80) def sort_data(file: str) -> tuple[list, list]: """ Opens file and sorts data into subjects, campuses, rooms and lecturers. It also puts each line of the csv into a list. :param file: string that contains file name :return: 2 lists, first is the full timetable, second is the selections list """ file = open(file, 'r+t') # creating 5 separate empty lists timetable, lecturers, rooms, subjects, campuses = ([] for i in range(5)) for line in file: row = line.strip().split(',') timetable.append(row) # Conditional statements used to sort data into lists of each option without any duplication if row[0] not in subjects: subjects.append(row[0]) if row[5] not in campuses: campuses.append(row[5]) if row[6] not in rooms: rooms.append(row[6]) if row[7] not in lecturers: lecturers.append(row[7]) selection_list = [campuses, lecturers, rooms, subjects] file.close() return timetable, selection_list def sub_menu(selection: str, file: str): """ Takes the selection made in the main menu and displays it's sub menu. :param selection: string from main menu based on the selections made :param file: string that contains file name """ timetable, selection_list = sort_data(file) # Conditional statements process selection from main menu if selection == 'c': print('\nCampuses\n' + ('-' * 8)) selection_name = 'campus' options = selection_list[0] elif selection == 'l': print('\nLecturers\n' + ('-' * 9)) selection_name = 'lecturer' options = selection_list[1] elif selection == 'r': print('\nRooms\n' + ('-' * 5)) selection_name = 'room' options = selection_list[2] elif selection == 's': print('\nSubjects\n' + ('-' * 8)) selection_name = 'subject' options = selection_list[3] # selection_list is passed to display_selection function valid_input, user_input = display_selection(options) while not valid_input: print('\nInvalid selection. Please try again.\n') valid_input, user_input = display_selection(options) display_timetable(options[user_input - 1], selection_name, timetable) def display_selection(options: list) -> bool and int: """ Takes the list of options and then uses a loop to print out each option :param options: list of campuses or lecturers or rooms or subjects :return: boolean value and an int - int will be 0 if boolean is False """ count = 1 for option in options: print(f'[{count}] {option}') count += 1 # Using a try except statement with a conditional statement after to handle incorrect inputs from user try: user_input = int(input('\n> Enter selection: ')) except ValueError: return False, 0 if not 0 >= user_input < len(options): return True, user_input else: return False, 0 def main_menu(file: str): """ Displays main selection menu. :param file: string that contains file name """ selection_list = ['c', 'r', 's', 'l', 'q'] print('\nTimetable menu\n' + ('-' * 14) + '\n[C]ampus\n[R]oom\n[S]ubject\n[L]ecturer\n') selection = input('> Enter selection or [Q]uit: ').lower() while selection not in selection_list: print('\nInvalid selection. Please try again.') print('\nTimetable menu\n' + ('-' * 14) + '\n[C]ampus\n[R]oom\n[S]ubject\n[L]ecturer\n') selection = input('> Enter selection or [Q]uit: ').lower() if selection == selection_list[4]: print('\nHave a nice day!') quit(0) else: sub_menu(selection, file) def file_exists(file: str) -> bool: """ Tries to open the file name parsed through. If it cannot open a file it raises an IOError and returns false. :param file: string that contains file name :return: boolean value """ try: file = open(file.strip(), 'r+t') except IOError: return False else: return True def correct_format(file: str) -> bool: """ Splits the file name, checks if the last element in the list is csv. If it is a csv, it checks if each element in the file is formatted correctly. :param file: string that contains file name :return: boolean value """ if file.split('.')[-1] != 'csv': return False else: file = open(file, 'r+t') for line in file: check_line = line.strip().split(',') if len(check_line) != 8: return False # Subject and Room checks if not check_line[0].isalnum() or not check_line[6].isalnum(): # checks if subject or room aren't alphanumeric return False else: if not check_line[0][0].isalpha() or not check_line[6][0].isalpha(): # checks if the first character in subject or room is a letter return False # Activity, Day, Campus and Lecturer checks if not check_line[1].isalpha() or not check_line[2].isalpha() or \ not check_line[5].isalpha() or not check_line[7].replace(' ', '').isalpha(): # check_line[7] and checkline[5] has any whitespaces removed for the condition check return False return True def main_loop(): print('Timetable Organiser\n' + ('-' * 19)) file = input('\nEnter the timetable data file name: ').lower() while not file_exists(file): print("File doesn't exist. Please try again.") file = input('Enter the timetable data file name: ').lower() print('** Reading timetable data ...') if not correct_format(file): print('** Error! File is not correctly formatted.\n\n\nHave a nice day!') exit(0) print('** Success!') main_menu(file) if __name__ == '__main__': main_loop() <file_sep>/README.md # Timetable-Organiser Task: Timetable Organiser is a system that allows users to view university timetables in multiple forms including by campus, room, subject, and lecturer. The system expects the timetable data to be stored in a simple comma-separated text file with the format: subject,activity,day,start,end,campus,room,lecturer A sample timetable data file is shown below: ``` ABC101,Lecture,Monday,08:00,10:00,Jenolan,J10112,Ada Log ABC101,Tutorial,Tuesday,10:00,11:00,Jenolan,J10115,Ena Blue ACE204,Lecture,Monday,09:00,11:00,Tarana,T05201,Kin Wall ACE206,Lecture,Wednesday,13:00,14:00,Tarana,T06402,Kin Wall PRG321,Lecture,Tuesday,14:00,16:00,Jenolan,J09302,Foxy Rex PRG321,Tutorial,Thursday,11:00,12:00,Jenolan,J09212,Esk Brown ``` You are required to develop a menu-based program that implements the Timetable Organiser system. Your program should prompt the user for a timetable data file name. After the file has been successfully read, the system will interact with the user to view the timetable according to the desired selections. Review the sample run below to clearly understand the requirements. ``` Timetable Organiser ------------------- Enter the timetable data file name: timetable-sample.txt ** Reading timetable data ... ** Success! Timetable menu -------------- [C]ampus [R]oom [S]ubject [L]ecturer > Enter selection or [Q]uit: L Lecturers --------- [1] Ada Log [2] Ena Blue [3] Kin Wall [4] Foxy Rex [5] <NAME> > Enter selection: 3 Timetable for lecturer "Kin Wall": =============================================================== Subject Activity Day Start End Campus Room Lecturer --------------------------------------------------------------- ACE204 Lecture Monday 09:00 11:00 Tarana T05201 Kin Wall ACE206 Lecture Wednesday 13:00 14:00 Tarana T06402 Kin Wall =============================================================== Timetable menu -------------- [C]ampus [R]oom [S]ubject [L]ecturer > Enter selection or [Q]uit: c Campuses -------- [1] Jenolan [2] Tarana > Enter selection: 1 Timetable for campus "Jenolan": =============================================================== Subject Activity Day Start End Campus Room Lecturer --------------------------------------------------------------- ABC101 Lecture Monday 08:00 10:00 Jenolan J10112 Ada Log ABC101 Tutorial Tuesday 10:00 11:00 Jenolan J10115 Ena Blue PRG321 Lecture Tuesday 14:00 16:00 Jenolan J09302 Foxy Rex PRG321 Tutorial Thursday 11:00 12:00 Jenolan J09212 Esk Brown =============================================================== Timetable menu -------------- [C]ampus [R]oom [S]ubject [L]ecturer Enter selection or [Q]uit: q Have a nice day! ``` Your program must validate the timetable data file before proceeding. Specifically, your program must verify the following: each line consists of exactly eight fields separated by commas subject and room fields must be alphanumeric strings starting with a letter activity, day, campus and lecturer fields must be alphabetic strings If any of these conditions is not satisfied, the program should display an error message and quit. Below is a sample run when an incorrectly formatted file is provided. ``` Timetable Organiser ------------------- Enter the timetable data file name: timetable-sample-incorrect.txt ** Reading timetable data ... ** Error! File is not correctly formatted. Have a nice day! ``` Constraints * You must define a function called display_timetable that accepts a string parameter containing the selection type and a list parameter containing the selection results, and prints the table in the format shown in the sample above. * You must use lists and string methods in your program. * You must handle the IOError exception with a specific handler. In addition, your program must not crash regardless of the input provided. * Your program must not import any library or module other than your own written modules (if any). **Task 1 (15 marks)** Implement your program in Python. Comment on your code as necessary to explain it clearly. **Task 2 (5 marks)** Select at least three sets of test data that will demonstrate the normal operation of your program; that is, test data that will demonstrate what happens when a valid input is entered. Select two sets of test data that will demonstrate the abnormal operation of your program; that is, test data that will demonstrate what happens when an invalid input is entered or when an error is encountered. Set it out in a tabular form as follows: test data type, test data, the reason it was selected, the output expected due to using the test data, and finally a screenshot of the output actually observed when the test data is used. It is important that the output listings (i.e., screenshots) are not edited in any way.
5cbcf2ee8caad44de861187d9f3ef688745fe36c
[ "Markdown", "Python" ]
2
Python
BukoMoon/Timetable-Organiser
822f613893a767dcc98d2d4076548631a31f9910
794a41e743e0314156ed2eb9e5f75af4d0249b1d
refs/heads/master
<repo_name>vuchkov/php-multi-login<file_sep>/healthADD.php <?php global $db; include('functions.php'); if (!isLoggedIn()) { $_SESSION['msg'] = "You must log in first"; header('location: login.php'); } $user = $_SESSION['user']; // Check IF the user has healt_data THEN load $data ELSE fill an empty array. if (existUserData($user['id'])) { $data = getUserHealthById($user); } else { $data = [ 'heartrate' => '0', 'bloodo2' => '0', 'boodpressure' => '0', 'weight' => '0', 'user_id' => $user['id'] ]; } ?> <form action="healthREVIEW.php" method="post"> <p> <label for="heartrate">Heartrate:</label> <input type="text" name="heartrate" id="heartrate" value="<?= $data['heartrate'] ?>"> </p> <p> <label for="bloodo2">Blood Oxigen:</label> <input type="text" name="bloodo2" id="bloodo2" value="<?= $data['bloodo2'] ?>"> </p> <p> <label for="boodpressure">Blood Pressure:</label> <input type="text" name="boodpressure" id="boodpressure" value="<?= $data['boodpressure'] ?>"> </p> <p> <label for="weight">Weight:</label> <input type="text" name="weight" id="weight" value="<?= $data['weight'] ?>"> </p> <input type="hidden" name="user_id" id="user_id" value="<?= $data['user_id'] ?>"> <input type="submit" value="Submit"> </form> <file_sep>/healthREVIEW.php <?php global $db; include('functions.php'); if (!isLoggedIn()) { $_SESSION['msg'] = "You must log in first"; header('location: login.php'); } $user = $_SESSION['user']; // If we have $_POST (submitted form) data. if (isset($_POST['user_id'], $_POST['heartrate'], $_POST['bloodo2'], $_POST['boodpressure'], $_POST['weight'])) { $user_id = e($_POST['user_id']);; $heartrate = e($_POST['heartrate']); $bloodo2 = e($_POST['bloodo2']); $boodpressure = e($_POST['boodpressure']); $weight = e($_POST['weight']); // Check IF we have data of the user then UPDATE, else INSERT. if (existUserData($user_id)) { $sql = "UPDATE healt_data SET heartrate='$heartrate', bloodo2='$bloodo2', boodpressure='$boodpressure', weight='$weight' WHERE user_id='$user_id'"; if (mysqli_query($db, $sql)) { echo "Records added successfully."; } else { echo "ERROR: Could not able to execute $sql. " . mysqli_error($db); } } else { // Attempt insert query execution $sql = "INSERT INTO healt_data (user_id, heartrate, bloodo2, boodpressure, weight) VALUES ('$user_id', '$heartrate', '$bloodo2', '$boodpressure', '$weight')"; if (mysqli_query($db, $sql)) { echo "Records added successfully."; } else { echo "ERROR: Could not able to execute $sql. " . mysqli_error($db); } } } $healthInfo = getUserHealthById($user); ?> <!DOCTYPE html> <html> <head> <title>Home</title> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <div class="header"> <h2>Health info</h2> </div> <div class="content"> <table> <tr> <td>Name:</td> <td><?= $user['firstname'] . ' ' . $user['lastname'] ?></td> </tr> <tr> <td>Heartrate:</td> <td><?= $healthInfo['heartrate'] ?? '0' ?> b/s</td> </tr> <tr> <td>Blood Oxigen:</td> <td><?= $healthInfo['bloodo2'] ?? '0' ?> %</td> </tr> <tr> <td>Blood Pressure:</td> <td><?= $healthInfo['boodpressure'] ?? '0' ?></td> </tr> <tr> <td>Weight:</td> <td><?= $healthInfo['weight'] ?? '0' ?> kg</td> </tr> <tr> <td>id:</td> <td><?= $healthInfo['user_id'] ?? '0' ?> ID</td> </tr> </table> <p> <a href="healthADD.php">Add health data</a> </p> </div> </body> </html> <file_sep>/pcr.php <?php include('functions.php') ?> <!DOCTYPE html> <html> <head> <title>Check your PCR results</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="header"> <h6 class="not-visible">Updated</h6> <h3>Check your PCR results</h3> </div> <div class="content"> <button class="btn" id="btn.id">Click here</button> <h1>...</h1> <?php if (isset($_SESSION['success'])) : ?> <div class="error success" > <h3> <?php echo $_SESSION['success']; unset($_SESSION['success']); ?> </h3> </div> <?php endif ?> <!-- logged in user information --> <div class="profile_info"> <img src="images/user-avatar-with-check-mark.png" > <div> <?php if (isset($_SESSION['user'])) : ?> <strong><?php echo $_SESSION['user']['username']; ?></strong> <small> <i style="color: #888;">(<?php echo ucfirst($_SESSION['user']['user_type']); ?>)</i> <br> <a href="index.php" style="color: red;">go back</a> <br> <a href="index.php?logout='1'" style="color: red;">logout</a> </small> <?php endif ?> </div> <script> generateResponse = function(){ var random = Math.round(Math.random()); if (random) { document.getElementsByTagName('h1')[0].innerHTML = 'You are Positive'; } else { document.getElementsByTagName('h1')[0].innerHTML = 'You are Negative'; } document.getElementsByTagName('H6')[0].classList.toggle('not-visible'); setTimeout(function() { document.getElementsByTagName('H6')[0].classList.toggle('not-visible'); }, 400); } document.getElementsByTagName('button')[0].onclick = generateResponse; </script> </body> </html>
5df2e16d9851b44d9a989c66359e34df32d1df62
[ "PHP" ]
3
PHP
vuchkov/php-multi-login
916f90e9a0a610528b756c66f19f46fd4c1b9031
658e9c2c595d39cc168bef3fdd1660821d47bf9a
refs/heads/master
<file_sep>package es.Studium.Trimestre1.Practica1; /* * Intercalar. Realizar un programa que lea dos cadenas y muestre la cadena resultante de intercalar una letra de una cadena con otra letra de la otra cadena. Ejemplo: Hola y Adiós, darían como resultado HAodliaós. */ import java.util.Scanner; //importamos la utilidad escaner public class Intercalar { public static void main(String[] args) { // Le aplicamos a teclado la utilidad escaner Scanner teclado = new Scanner(System.in); String cadena1,cadena2; //Leemos las cadenas a intercalar System.out.println("Introduzca una cadena"); cadena1=teclado.nextLine(); System.out.println("Introduzca otra cadena"); cadena2=teclado.nextLine(); teclado.close(); //Cerramos teclado System.out.println(intercalarCadenas(cadena1, cadena2)); //imprimimos por pantalla el resultado de la función. } private static String intercalarCadenas(String cadena1, String cadena2) { String cadena3=""; if(cadena1.length()>=cadena2.length())//Si Longitud cadena1 es mayor o igual que cadena2 { for(int i=0; i<cadena1.length(); i++) //Siendo mayor la longitud de cadena1 recorremos cadena 1 mientras la longitud sea mayor a la variable i { cadena3=cadena3+cadena1.charAt(i);//añade el carácter de la cadena1 con valor de posición i if (i<cadena2.length())//Comprobamos que la longitud de cadena 2 sea menor a i, ya que si es mayor el siguiente código daría error. { cadena3=cadena3+cadena2.charAt(i);//añade el carácter de la cadena2 con valor de posición i } } } else { for(int i=0; i<cadena2.length(); i++)//Siendo mayor la longitud de cadena2 recorremos cadena 1 mientras la longitud sea mayor a la variable i { if (i<cadena1.length())//Comprobamos que la longitud de cadena 2 sea menor a i, ya que no podemos seguir recorriendo si es mayor { cadena3=cadena3+cadena1.charAt(i); //añade el carácter de la cadena1 con valor de posición i } cadena3=cadena3+cadena2.charAt(i);//añade el carácter de la cadena2 con valor de posición i } } return cadena3; //se devuelve cadena3 } } <file_sep>package es.Studium.Trimestre1.Practica1; /* * Hopolapa - Realizar un programa que lea una cadena e inserte detrás de cada vocal que encuentre, una p y la vocal encontrada. Por ejemplo, si tenemos Hola se transformará en Hopolapa. */ import java.util.Scanner; //importamos el escáner public class hopolapa { public static void main(String[] args) { Scanner teclado = new Scanner(System.in);//aplicamos el escáner String palabra, palabra2="";//declaramos variables System.out.println("indique la palabra o frase a cambiar"); palabra=teclado.nextLine();//leemos la palabra o frase a cambiar teclado.close();// cerramos teclado char tabla[] = new char[palabra.length()];//creamos las tablas que almacenara lo introducido por teclado //declaramos las tablas que vamos a necesitar para cambiar los caracteres y ponerlos como srting String tabla2[] = new String[palabra.length()]; String tabla3[] = new String[palabra.length()]; char vocales[] = new char[10];//declaramos las tablas que contendrá los elementos a cambiar //creamos los elementos a cambiar vocales[0]='a'; vocales[1]='e'; vocales[2]='i'; vocales[3]='o'; vocales[4]='u'; vocales[5]='A'; vocales[6]='E'; vocales[7]='I'; vocales[8]='O'; vocales[9]='U'; for (int i=0; i<palabra.length();i++) //recorremos la palabra para meterla en la primera tabla { tabla[i]=palabra.charAt(i); } for (int i=0; i<tabla.length;i++)//recorremos la tabla { for (int z=0;z<vocales.length;z++)//recorremos las vocales { if (tabla[i]==vocales[z])//si la posición de la tabla contiene alguna vocal la pondrá en tabla2 añadiendo la vocal + p + la vocal { tabla2[i]=(tabla[i]+"p"+tabla[i]); z=vocales.length+1;//Si se encuentra la vocal con esto cerramos el bucle. } else if (tabla2[i]==null) { tabla2[i]="";//donde no haya vocal lo rellenara con nada } } //cerramos bucle de recorrer vocales //si es diferente a cualquier vocal lo añadimos la tabla a tabla3 if (tabla[i]!=vocales[0]&&tabla[i]!=vocales[1]&&tabla[i]!=vocales[2]&&tabla[i]!=vocales[3]&&tabla[i]!=vocales[4]&&tabla[i]!=vocales[5]&&tabla[i]!=vocales[6]&&tabla[i]!=vocales[7]&&tabla[i]!=vocales[8]&&tabla[i]!=vocales[9]) { tabla3[i]=tabla[i]+""; } else { tabla3[i]="";//si no se cumple lo anterior rellenamos la tabla con nada } } //Cerramos el bucle de recorrer la tabla int i=0; while ((i<tabla2.length)||(i<tabla3.length))//recorremos las 2 tablas para juntarlas en un string cuando las 2 no cumplan la condición parara el bucle { if (tabla2.length-1>=i)//verificamos que en el bucle no pueda seguir en la tabla si este es mayor que la tabla { palabra2=palabra2+tabla2[i];//como en la tabla2 tenemos vacío los elementos que no nos interesan podemos meterlo todo } if (tabla3.length-1>=i)//verificamos que en el bucle no pueda seguir en la tabla si este es mayor que la tabla { palabra2=palabra2+tabla3[i];//como en la tabla3 tenemos vacío los elementos que no nos interesan podemos meterlo todo } i++; } System.out.println("Resultado: "+palabra2); } } <file_sep>package es.Studium.Trimestre1.Practica1; /* * Traductor - Realizar un programa que lea una frase en español y la traduzca al inglés o viceversa. Usaremos un diccionario reducido compuesto por las palabras yo, tu, el, ella, soy, eres, es, alto, bajo, español y sus equivalentes en inglés. */ import java.util.Scanner; public class Traductor { public static void main(String[] args) { // Le aplicamos a teclado la utilidad escáner Scanner teclado = new Scanner(System.in); String palabra; System.out.println("Atención, escriba todo en minúsculas"); System.out.println("Indique una palabra a traducir:"); palabra=teclado.nextLine();//Leemos la cadena a traducir teclado.close(); //Cerramos teclado String tabla[] = new String[palabra.length()]; String[] parts = palabra.split(" ");//split separa por lo que se le diga separarFrase(tabla, parts); System.out.println("La frase traducida es:"); revisarTraductor(tabla, parts); } private static void separarFrase(String[] tabla, String[] parts) { for(int i=0;i<parts.length;i++)//recorremos tantas veces como palabras tenga la frase { tabla[i] = parts[i];//metemos las palabras en una tabla } } private static void revisarTraductor(String[] tabla, String[] parts) { for(int i=0;i<parts.length;i++)//recorremos tantas veces como palabras hay. { switch (tabla[i])//Miramos si las palabras almacenadas en la tabla y imprimimos el resultado { case "yo": System.out.print("i"); System.out.print(" "); break;//detiene el switch case "tu": System.out.print("you"); System.out.print(" "); break;//detiene el switch case "el": System.out.print("he"); System.out.print(" "); break;//detiene el switch case "ella": System.out.print("she"); System.out.print(" "); break;//detiene el switch case "soy": System.out.print("am"); System.out.print(" "); break;//detiene el switch case "eres": System.out.print("are"); System.out.print(" "); break;//detiene el switch case "es": System.out.print("is"); System.out.print(" "); break;//detiene el switch case "alto": System.out.print("tall"); System.out.print(" "); break;//detiene el switch case "bajo": System.out.print("low"); System.out.print(" "); break;//detiene el switch case "español": System.out.print("spanish"); System.out.print(" "); break;//detiene el switch case "i": System.out.print("yo"); System.out.print(" "); break;//detiene el switch case "you": System.out.print("tu"); System.out.print(" "); break;//detiene el switch case "he": System.out.print("el"); System.out.print(" "); break;//detiene el switch case "she": System.out.print("ella"); System.out.print(" "); break;//detiene el switch case "i am": System.out.print("soy"); System.out.print(" "); break;//detiene el switch case "you are": System.out.print("eres"); System.out.print(" "); break;//detiene el switch case "is": System.out.print("es"); System.out.print(" "); break;//detiene el switch case "tall": System.out.print("alto"); System.out.print(" "); break;//detiene el switch case "low": System.out.print("bajo"); System.out.print(" "); break;//detiene el switch case "spanish": System.out.print("español"); System.out.print(" "); break; //detiene el switch default://Por defecto mostrara el siguiente mensaje de error System.out.println("Error, la palabra no se encuentra"); } } } } <file_sep> 1. Leer 10 números. Leer diez números enteros por teclado, calcular su media mediante una función y mostrar todos los números en orden inverso al que se introdujeron. 2. Final año - Realizar un programa que lea una fecha y calcule el número de días que quedan hasta fin de año. 3. Cadena más corta - Realizar un programa que meta 10 cadenas en una tabla y luego muestre a cadena más corta. Usar una función que devuelva la cadena más corta y que tenga como parámetro la tabla. 1. Preguntas y Respuestas - Realizar un programa que muestre 3 preguntas al azar de 10 posibles. Mostrar al final de las preguntas el número de aciertos. 2. Tabla de cadenas - Realizar un programa que lea 10 cadenas y las inserte en una tabla de cadenas para su posterior mostrado en pantalla. 3. Cambiar formato hora - Realizar un programa que lea una hora del tipo 23:45 y lo transforme en una hora del tipo 11:45 pm.
270ff338000b4f4a3e4460bb8d73fc71e951fc43
[ "Markdown", "Java" ]
4
Java
Programacion-Studium/StudiumPracticasT1
63fb4851fd79b45ab68aff6d08b298ff098b69e2
7ccc95e8e4c2f6bf511e093b2a5e1a3a6d61f57b
refs/heads/master
<file_sep>from django.shortcuts import render #from django.contrib.auth.models import User, Group from rest_framework import viewsets, permissions, generics from models import User, Wine, Movement, Container, Bottle from serializers import UserSerializer, WineSerializer, MovementSerializer, ContainerSerializer, BottleSerializer class VinibarViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ serializer_class = BottleSerializer def get_queryset(self): queryset = Bottle.objects.all() username = self.request.user if username is not None: queryset = queryset.filter(user=username) return queryset class VinibarWinesViewSet(viewsets.ModelViewSet): """ API endpoint that shows users vinibars. """ serializer_class = WineSerializer def get_queryset(self): username = self.request.user queryset = Wine.objects.filter(bottle__user=username, bottle__rated__isnull=True) return queryset class RatedWinesViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ serializer_class = WineSerializer def get_queryset(self): username = self.request.user queryset = Wine.objects.filter(bottle__user=username, bottle__rated__isnull=False, bottle__rating__isnull=False) return queryset class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all() serializer_class = UserSerializer class WineViewSet(viewsets.ModelViewSet): """ API endpoint that allows wines to be viewed or edited. """ queryset = Wine.objects.all() serializer_class = WineSerializer class MovementViewSet(viewsets.ModelViewSet): """ API endpoint that allows movements to be viewed or edited. """ queryset = Movement.objects.all() serializer_class = MovementSerializer class ContainerViewSet(viewsets.ModelViewSet): """ API endpoint that allows containers to be viewed or edited. """ queryset = Container.objects.all() serializer_class = ContainerSerializer class BottleViewSet(viewsets.ModelViewSet): """ API endpoint that allows bottles to be viewed or edited. """ queryset = Bottle.objects.all() serializer_class = BottleSerializer<file_sep>from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.core.mail import send_mail from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from django.core.validators import MinValueValidator, MaxValueValidator from datetime import datetime from rest_framework import serializers class UserManager(models.Manager): @classmethod def normalize_email(cls, email): """ Normalize the address by lowercasing the domain part of the email address. """ email = email or '' try: email_name, domain_part = email.strip().rsplit('@', 1) except ValueError: pass else: email = '@'.join([email_name, domain_part.lower()]) return email def create_user(self, email, password=None, **extra_fields): """ Creates and saves an User with the given email and password. """ now = timezone.now() if not email: raise ValueError('The given email must be set') email = UserManager.normalize_email(email) user = self.model(email=email, is_staff=False, is_active=True, is_superuser=False, last_login=now, date_joined=now, **extra_fields) user.set_password(password) user.save(using=self._db) return user def make_random_password(self, length=10, allowed_chars='abcdefghjkmnpqrstuvwxyz' 'ABCDEFGHJKLMNPQRSTUVWXYZ' '<PASSWORD>'): """ Generates a random password with the given length and given allowed_chars. Note that the default value of allowed_chars does not have "I" or "O" or letters and digits that look similar -- just to avoid confusion. """ return get_random_string(length, allowed_chars) def create_superuser(self, email, password, **extra_fields): """ Creates and saves a superuser with the given email and password. """ user = self.create_user(email, password, **extra_fields) user.is_staff = True user.is_active = True user.is_superuser = True user.save(using=self._db) return user def get_by_natural_key(self, username): return self.get(**{self.model.USERNAME_FIELD: username}) class User(AbstractBaseUser, PermissionsMixin): """ Abstract User with the same behaviour as Django's default User but without a username field. Uses email as the USERNAME_FIELD for authentication. Inherits from both the AbstractBaseUser and PermissionMixin. The following attributes are inherited from the superclasses: * password * last_login * is_superuser """ email = models.EmailField(_('email address'), max_length=255, unique=True, db_index=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) is_staff = models.BooleanField(_('staff status'), default=False, help_text=_('Designates whether the user can log into this admin ' 'site.')) is_active = models.BooleanField(_('active'), default=True, help_text=_('Designates whether this user should be treated as ' 'active. Unselect this instead of deleting accounts.')) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] # def get_full_name(self): # """ # Returns the email. # """ # return self.first_name def get_short_name(self): """ Returns the email. """ return self.email def email_user(self, subject, message, from_email=None): """ Sends an email to this User. """ send_mail(subject, message, from_email, [self.email]) def save(self, *args, **kwargs): super(User, self).save(*args, **kwargs) c, _ = Container.objects.get_or_create(container_type='cellar', user=self) c.save() v, _ = Container.objects.get_or_create(container_type='vinibar', user=self) v.save() h, _ = Container.objects.get_or_create(container_type='history', user=self) h.save() m1, _ = Movement.objects.get_or_create(start=c, finish=v) m1.save() m2, _ = Movement.objects.get_or_create(start=v, finish=h) m2.save() def __unicode__(self): return self.email class Wine(models.Model): couleur = models.CharField(max_length=100, blank=True) pays = models.CharField(max_length=100, blank=True) region = models.CharField(max_length=100, blank=True) appellation = models.CharField(max_length=100, blank=True) domaine = models.CharField(max_length=100, blank=True) cuvee = models.CharField(max_length=100, blank=True) millesime = models.IntegerField() price = models.IntegerField() quantity = models.IntegerField() description = models.TextField() added_on = models.DateTimeField(auto_now_add=True) def __unicode__(self): return u'%s %s' % (self.domaine, self.millesime) def update_qty(self, quantity): self.quantity -= quantity self.save() def qty(self): return self.quantity class Container(models.Model): CONTAINER_TYPE = ( ('cellar', 'Cellar'), ('vinibar', 'Vinibar'), ('history', 'History'), ) container_type = models.CharField(max_length=10, choices=CONTAINER_TYPE) user = models.ForeignKey(User, related_name='user_id') def __unicode__(self): return u'%s %s' % (self.container_type, self.user) class Movement(models.Model): date = models.DateTimeField(null=True, blank=True, default=None) start = models.ForeignKey(Container, related_name='movements_from') #imposer start/user == finish.user finish = models.ForeignKey(Container, related_name='movements_to') quantity = models.IntegerField(default=1) def __unicode__(self): return u'%s %s %s' % (self.start, "to", self.finish) class Bottle(models.Model): #id = ??? wine = models.ForeignKey(Wine, null=False) user = models.ForeignKey(User, null=False) mounted = models.ForeignKey(Movement, null=True, blank=True, default=None, related_name='bottles_mounted') rated = models.ForeignKey(Movement, null=True, blank=True, default=None, related_name='bottles_rated') date_mounted = models.DateTimeField() date_rated = models.DateTimeField(null=True, blank=True, default=None) rating = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(5)], null=True, blank=True, default=None) #integer for 3.5? Blank=True? comment = models.TextField(null=True, blank=True, default=None) #tags = models.ManyToManyField('tags.Tag', related_name='posts') def __unicode__(self): return u'%s %s' % (self.wine.domaine, self.wine.millesime) def save(self, *args, **kwargs): d = datetime.now() # self.wine = wine #wine referencing issue # self.user = user self.mounted = Movement.objects.filter(start__user=self.user, start__container_type='cellar', finish__container_type='vinibar')[0] self.date_mounted = d super(Bottle, self).save(*args, **kwargs) def rate(self, rating, comment, *args, **kwargs): #interet de *args, **kwargs quand on connait l'input? d = datetime.now() self.rating = rating self.comment = comment date_rated = d #TODO: can only be rated if it has been mounted v = Container.objects.get(container_type='vinibar', user=self.user) #TODO: handle error h = Container.objects.get(container_type='history', user=self.user) #TODO: handle error m = Movement(date=d, start=v, finish=h) #quantity=quantity? m.save() self.rated = m def current_bottles(): b = Bottle.objects.filter(user=self.user and self.rated==null).order_by('date_mounted') def rated_bottles(): b = Bottle.objects.filter(user=self.user and rated.finish.user==self.user).order_by('date_rated') <file_sep>Django==1.6 MySQL-python==1.2.4 dj-database-url==0.2.2 dj-static==0.0.5 django-cors-headers==0.12 djangorestframework==2.3.9 static==0.4 <file_sep>from django.conf.urls import patterns, include, url from django.conf import settings from rest_framework import routers from vinibar import views from django.contrib import admin admin.autodiscover() router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'wines', views.WineViewSet) router.register(r'movements', views.MovementViewSet) router.register(r'containers', views.ContainerViewSet) router.register(r'bottles', views.BottleViewSet) #router.register(r'vinibar', views.VinibarView, base_name='vinibar') router.register(r'vinibar', views.VinibarViewSet, base_name='vinibar') router.register(r'vinibarwines', views.VinibarWinesViewSet, base_name='vinibarwines') router.register(r'ratedwines', views.RatedWinesViewSet, base_name='ratedwines') urlpatterns = patterns('', url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^admin/', include(admin.site.urls)), # url(r'^$', 'usertest2.views.home', name='home'), # url(r'^usertest2/', include('usertest2.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # url(r'^admin/', include(admin.site.urls)), (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}), #added for heroku ) <file_sep>#!/usr/bin/env python from vinibar.models import User if User.objects.count() == 0: admin = User.objects.create(email='<EMAIL>') admin.set_password('<PASSWORD>') admin.is_superuser = True admin.is_staff = True admin.save()<file_sep>from models import User, Wine, Movement, Container, Bottle from rest_framework import serializers # class VinibarSerializer(serializers.Serializer): class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'email', 'first_name', 'last_name', 'password', 'is_superuser') class WineSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Wine fields = ('url', 'couleur', 'region', 'appellation', 'domaine', 'cuvee', 'millesime', 'description', 'price', 'quantity') class MovementSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Movement fields = ('url', 'date', 'start', 'finish', 'quantity') class ContainerSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Container fields = ('url', 'container_type', 'user') class BottleSerializer(serializers.HyperlinkedModelSerializer): # def __init__(self, *args, **kwargs): # many = kwargs.pop('many', True) # super(BottleSerializer, self).__init__(*args, **kwargs) class Meta: model = Bottle fields = ('url', 'wine', 'user') # def get_api_url(self, obj): # return "#/post/%s" % obj.id<file_sep>from django.contrib import admin from models import User, Wine, Movement, Container, Bottle admin.site.register(User) admin.site.register(Wine) admin.site.register(Movement) admin.site.register(Container) admin.site.register(Bottle)
fc8b4795d0fed6aed8f42153702ba2d9868ca7dd
[ "Python", "Text" ]
7
Python
bpipat/appbeta
69c15e60035e9f73b438eeb8d5757568a3eacccf
dc5f857cb008fc20858a2810589adf3c8ec65c93
refs/heads/master
<file_sep>platform :ios, '8.0' use_frameworks! target 'BaseProject' do pod 'SDWebImage','~> 3.7.2' #pod 'AFNetworking', '~> 3.0.4' pod 'Masonry' # pod 'ReactiveCocoa', '~> 6.0' pod 'ReactiveObjC' end <file_sep>// // StringConst.h // BaseProject // // Created by 王声远 on 2017/8/29. // Copyright © 2017年 王声远. All rights reserved. // #ifndef StringConst_h #define StringConst_h //正则表达式的字符串 #define kphoneNoFinalRule @"^[0-9]{11}" #define knumberFinalRule @"^[0-9]" #define kphoneNoInputRule @"^[0-9]" #define kPwdInputRule @"^[0-9A-Za-z]" #endif /* StringConst_h */ <file_sep>// // UrlConst.h // BaseProject // // Created by 王声远 on 2017/8/29. // Copyright © 2017年 王声远. All rights reserved. // #ifndef UrlConst_h #define UrlConst_h #define ServerIp @"sc.anody.com.cn" #define HEAD__URL [NSString stringWithFormat:@"https://%@",ServerIp] #endif /* UrlConst_h */ <file_sep>// // ConfigBuilder.h // BaseProject // // Created by 王声远 on 2017/10/23. // Copyright © 2017年 王声远. All rights reserved. // #ifndef ConfigBuilder_h #define ConfigBuilder_h //配置项文件 //1.是否使用自定义字体Font #define defaultFontName @"" //空字符串代码不使用自定义字体名称 //2.国际化获取 #define NATIVE(STR) NSLocalizedString(STR, STR) #endif /* ConfigBuilder_h */ <file_sep>// // AdaptUtils.h // Tronker // // Created by Devin on 17-9-29. // Copyright (c) 2017年 ___SOFFICE___. All rights reserved. // #ifndef _AdaptUtils_h #define _AdaptUtils_h /* iOS 11适配信息记录 一、iphoneX屏幕大小:375x812 启动图片:1125×2436 iOS11适配时必须导入启动图片,因为[[UIScreen mainScreen] bounds]是根据启动图片大小得到的,否则默认都是[320x568] */ //tableView/scorllView的适配代码 #define adjustsScrollViewInsets_NO(scrollView,vc)\ do { \ _Pragma("clang diagnostic push") \ _Pragma("clang diagnostic ignored \"-Warc-performSelector-leaks\"") \ if ([UIScrollView instancesRespondToSelector:NSSelectorFromString(@"setContentInsetAdjustmentBehavior:")]) {\ [scrollView performSelector:NSSelectorFromString(@"setContentInsetAdjustmentBehavior:") withObject:@(2)];\ } else {\ vc.automaticallyAdjustsScrollViewInsets = NO;\ }\ _Pragma("clang diagnostic pop") \ } while (0) //tabBar在push时适配代码 #define pushAdjustTabBarFrameWhenPush() \ do { \ if([UIScreen mainScreen].bounds.size.width == 375.0f && [UIScreen mainScreen].bounds.size.height == 812.0f){ \ CGRect frame = self.tabBarController.tabBar.frame; \ frame.origin.y = [UIScreen mainScreen].bounds.size.height - frame.size.height; \ self.tabBarController.tabBar.frame = frame; \ } \ } while (0) //判断是iPhoneX 的宏 #define iSPhoneX ([UIScreen mainScreen].bounds.size.width == 375.0f && [UIScreen mainScreen].bounds.size.height == 812.0f) //导航栏告诉 #define naviHeight (iSPhoneX ? 88.0 : 64.0) //tabbar高度 #define tabbaHeight (iSPhoneX ? (34+49) : 49) //phoneX时会有值 #define tabbaExtenHeight (iSPhoneX ? 34.0 : 0.0) #define titleLargeHeight 52 #endif
39a00e7b7bf2ab04be186d5c41987c7029708a46
[ "C", "Ruby" ]
5
Ruby
ruibox001/FFmpegPlayer
e8de5118d2f6397137a80aee85ab908a3a58a5bf
7c8fb03a09a29a0f92bbf814f6c48566e2d7bead
refs/heads/master
<repo_name>user-tony/blog<file_sep>/app/controllers/admin/categories_controller.rb module Admin class CategoriesController < Fae::BaseController end end
cd11afbb917e8035675cfa66734ad583cfd1b326
[ "Ruby" ]
1
Ruby
user-tony/blog
4cb325906cdbc4d1986b34fa7dc48fcb01009b28
7c72e369daf0011a4e8d1250c831c3d811978d7c
refs/heads/master
<repo_name>Taimoor1999/Taimoor1999<file_sep>/index.js var fetchMain = document.querySelector('.main'); var fetchNext = document.querySelector('.next'); var fetchPrevious = document.querySelector('.Previous'); var index = 0; var ArrayPictures = [ "main.jpeg","main1.jpeg","main2.jpeg","music.jpeg" ] fetchMain.style.backgroundImage = `url(${ArrayPictures[index]})`; fetchNext.addEventListener('click',function(extraInfo) { if (index < ArrayPictures.length-1 ) { index++; } else{ index = 0; } fetchMain.style.backgroundImage = `url(${ArrayPictures[index]})`; }); fetchPrevious.addEventListener('click', function(){ if (index>0) { --index; } else{ index= ArrayPictures.length-1; } fetchMain.style.backgroundImage = `url(${ArrayPictures[index]})`; console.log('prev', index); });
119b520c1e9c018f2053c3be01df77255edbda75
[ "JavaScript" ]
1
JavaScript
Taimoor1999/Taimoor1999
228e7b780c7557ee80e89e31ee86101eb0593f5e
87f47c4300e8704816a464778208e1a0bb522de0
refs/heads/master
<repo_name>kynesim/kstate<file_sep>/Makefile # Makefile for the Kstate kernel module # ***** BEGIN LICENSE BLOCK ***** # Version: MPL 1.1 # # The contents of this file are subject to the Mozilla Public License Version # 1.1 (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.mozilla.org/MPL/ # # Software distributed under the License is distributed on an "AS IS" basis, # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License # for the specific language governing rights and limitations under the # License. # # The Original Code is the Kynesim state management library. # # The Initial Developer of the Original Code is Kynesim, Cambridge UK. # Portions created by the Initial Developer are Copyright (C) 2013 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Kynesim, Cambridge UK # gb <<EMAIL>> # # ***** END LICENSE BLOCK ***** ifdef CROSS_COMPILE CC=$(CROSS_COMPILE)gcc LD=$(CROSS_COMPILE)gcc # because gcc knows where to find libc... else CC=gcc LD=gcc endif # Note we assume a traditional Linux style environment in our flags WARNING_FLAGS=-Wall -Werror DEBUG_FLAGS= LD_SHARED_FLAGS+=-shared INCLUDE_FLAGS=-I . CFLAGS+=-fPIC -g ifeq ($(O),) TGTDIR=. else TGTDIR=$(O)/libkstate endif SRCS=kstate.c OBJS=$(SRCS:%.c=$(TGTDIR)/%.o) DEPS=kstate.h SHARED_NAME=libkstate.so STATIC_NAME=libkstate.a SHARED_TARGET=$(TGTDIR)/$(SHARED_NAME) STATIC_TARGET=$(TGTDIR)/$(STATIC_NAME) .PHONY: all all: dirs extract_header $(SHARED_TARGET) $(STATIC_TARGET) test # Note that this is *not* out-of-tree build friendly # On the other hand, it should not do anything if the headers are up-to-date # XXX Consider whether to leave this in... .PHONY: extract_header extract_header: ./extract_hdrs.py -kstate .PHONY: install install: -mkdir -p $(DESTDIR)/lib -mkdir -p $(DESTDIR)/include/kstate install -m 0644 kstate.h $(DESTDIR)/include/kstate/kstate.h install -m 0755 $(SHARED_TARGET) $(DESTDIR)/lib/$(SHARED_NAME) install -m 0755 $(STATIC_TARGET) $(DESTDIR)/lib/$(STATIC_NAME) .PHONY: dirs dirs: -mkdir -p $(TGTDIR) $(TGTDIR)/%.o: %.c $(CC) $(INCLUDE_FLAGS) $(CFLAGS) -o $@ $(WARNING_FLAGS) -c $^ $(TGTDIR)/%.o: $(DEPS) $(SHARED_TARGET): $(OBJS) echo Objs = $(OBJS) $(LD) $(LD_SHARED_FLAGS) -o $(SHARED_TARGET) $(OBJS) -lc $(STATIC_TARGET): $(STATIC_TARGET)($(OBJS)) TEST_PROG=$(TGTDIR)/check_kstate test: extract_tests $(TEST_PROG) $(TEST_PROG) # We assume that 'check' has been installed, typically with # sudo apt-get install check $(TEST_PROG): check_kstate.c $(STATIC_TARGET) $(CC) $(INCLUDE_FLAGS) $(CFLAGS) -g -o $@ $(WARNING_FLAGS) $^ -lcheck -lrt simple: simple.c $(STATIC_TARGET) $(CC) $(INCLUDE_FLAGS) $(CFLAGS) -g -o $@ $(WARNING_FLAGS) $^ -lrt #simple: simple.c $(SHARED_TARGET) # $(CC) $(INCLUDE_FLAGS) $(CFLAGS) -g -o $@ $(WARNING_FLAGS) $< -L$(TGTDIR) -lkstate -lrt # For the moment, at least, whilst I'm adding tests, also run # extract_tests.py .PHONY: extract_tests extract_tests: ./extract_tests.py check_kstate.c .PHONY: clean clean: rm -f $(TGTDIR)/*.o $(SHARED_TARGET) $(STATIC_TARGET) rm -f $(TEST_PROG) .PHONY: distclean distclean: clean rm -f *.bak <file_sep>/simple.c #include <stdio.h> #include "kstate.h" int main (void) { kstate_state_p state = kstate_new_state(); printf("1. state: %p\n", state); kstate_free_state(&state); printf("2. state: %p\n", state); return 0; } <file_sep>/check_kstate.c /* * Unit tests for kstate. * * Written using check - see http://check.sourceforge.net/ * * Other unit tests are in kstate.py * * For the moment, this is where tests that can only really be done from C * live, and other tests may be found in kstate.py. */ /* * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the BUS State library. * * The Initial Developer of the Original Code is Kynesim, Cambridge UK. * Portions created by the Initial Developer are Copyright (C) 2013 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Kynesim, Cambridge UK * <NAME> <<EMAIL>> * * ***** END LICENSE BLOCK ***** */ #define _XOPEN_SOURCE 600 // enable nftw, etc. #include <ftw.h> // for nftw #include <check.h> #include <errno.h> #include <stdlib.h> #include <signal.h> #include "kstate.h" static int delete_file_fn(const char *fpath, const struct stat *sb __attribute__((unused)) , int typeflag, struct FTW *ftwbuf) { int rv = 0; if (typeflag == FTW_F) { } else if (typeflag == FTW_DP) { // This is a directory, all of whose contents have been visited. Ignore it. return 0; } else if (typeflag == FTW_SL) { // This is a symbolic link. Ignore it. return 0; } else { // This shouldn't really happen. Ignore it. return 0; } // The FTW structure conveniently gives us the offset of the filename // within its full path if (!strncmp("kstate.", &fpath[ftwbuf->base], 7)) { printf(".. deleting file %s\n", fpath); rv = remove(&fpath[ftwbuf->base]); if (rv) { fprintf(stderr, "### Error trying to remove %s: %d %s\n", fpath, errno, strerror(errno)); return -1; } } return 0; } /* * Returns 0 if all went well, -1 if an error occurred. */ static int delete_our_kstate_shm_files(void) { const char *dirpath = "/dev/shm"; printf("Tidying up: deleting kstate files from %s\n", dirpath); // FTW_CHDIR means we change into the directory we are inspecting, // which makes it easier to check filenames before we delete them // (see delete_file_fn). // // Since we're not expecting any subdirectories, we don't care what // order directories are checked in. // // Unusually, we do want to follow symbolic links, as we happen to know that // /dev/shm is commonly a link to the less obvious /run/shm errno = 0; int rv = nftw(dirpath, delete_file_fn, 2, FTW_CHDIR); if (rv && errno == ENOENT) { printf(".. nothing to delete\n"); } else if (rv) { fprintf(stderr, "### Error deleting contents of %s\n", dirpath); return -1; } return 0; } START_TEST(new_and_free_state) { kstate_state_p state = kstate_new_state(); fail_if(state == NULL); kstate_free_state(&state); fail_unless(state == NULL); } END_TEST START_TEST(free_NULL_state) { kstate_state_p state = NULL; kstate_free_state(&state); fail_unless(state == NULL); } END_TEST START_TEST(subscribe_with_NULL_name_fails) { kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, NULL, KSTATE_READ|KSTATE_WRITE); ck_assert_int_eq(rv, -EINVAL); kstate_free_state(&state); } END_TEST START_TEST(subscribe_with_zero_permissions_fails) { kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, "Fred", 0); ck_assert_int_eq(rv, -EINVAL); kstate_free_state(&state); } END_TEST START_TEST(subscribe_with_too_many_permissions_fails) { kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, "Fred", 0xF); ck_assert_int_eq(rv, -EINVAL); kstate_free_state(&state); } END_TEST START_TEST(subscribe_with_NULL_name_and_zero_permissions_fails) { kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, NULL, 0); ck_assert_int_eq(rv, -EINVAL); kstate_free_state(&state); } END_TEST START_TEST(subscribe_with_zero_length_name_fails) { kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, "", KSTATE_READ|KSTATE_WRITE); ck_assert_int_eq(rv, -EINVAL); kstate_free_state(&state); } END_TEST // 255 characters is too long START_TEST(subscribe_with_too_long_name_fails) { kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "12345", KSTATE_READ|KSTATE_WRITE); ck_assert_int_eq(rv, -EINVAL); kstate_free_state(&state); } END_TEST // But we expect 254 to be OK START_TEST(subscribe_with_max_length_name_and_unsubscribe) { kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "123456", KSTATE_READ|KSTATE_WRITE); ck_assert_int_eq(rv, 0); kstate_unsubscribe_state(state); fail_if(kstate_state_is_subscribed(state)); kstate_free_state(&state); fail_unless(state == NULL); } END_TEST START_TEST(subscribe_with_dot_at_start_of_name_fails) { kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, ".Fred", KSTATE_READ|KSTATE_WRITE); ck_assert_int_eq(rv, -EINVAL); kstate_free_state(&state); } END_TEST START_TEST(subscribe_with_dot_at_end_of_name_fails) { kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, "Fred.", KSTATE_READ|KSTATE_WRITE); ck_assert_int_eq(rv, -EINVAL); kstate_free_state(&state); } END_TEST START_TEST(subscribe_with_adjacent_dots_in_name_fails) { kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, "Fred..Jim", KSTATE_READ|KSTATE_WRITE); ck_assert_int_eq(rv, -EINVAL); kstate_free_state(&state); } END_TEST // This is a very basic test of this, but there's not really any point in // trying to be exhaustive. START_TEST(subscribe_with_non_alphanumeric_in_name_fails) { kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, "Fred&Jim", KSTATE_READ|KSTATE_WRITE); ck_assert_int_eq(rv, -EINVAL); kstate_free_state(&state); } END_TEST START_TEST(subscribe_for_read_alone_fails) { kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, "Fred.Read.Only", KSTATE_READ); ck_assert_int_eq(rv, -ENOENT); kstate_free_state(&state); } END_TEST START_TEST(subscribe_for_write_is_actually_for_readwrite) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); uint32_t permissions = kstate_get_state_permissions(state); ck_assert_int_eq(permissions, KSTATE_WRITE|KSTATE_READ); kstate_free_state(&state); } END_TEST START_TEST(subscribe_for_readwrite_and_unsubscribe_and_free) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_READ|KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); kstate_unsubscribe_state(state); fail_if(kstate_state_is_subscribed(state)); kstate_free_state(&state); fail_unless(state == NULL); } END_TEST START_TEST(subscribe_for_readwrite_and_free) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_READ|KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); kstate_free_state(&state); fail_unless(state == NULL); } END_TEST START_TEST(query_state_name) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_READ|KSTATE_WRITE); ck_assert_int_eq(rv, 0); const char *name = kstate_get_state_name(state); ck_assert_str_eq(state_name, name); free(state_name); kstate_unsubscribe_state(state); fail_if(kstate_state_is_subscribed(state)); name = kstate_get_state_name(state); fail_unless(name == NULL); kstate_free_state(&state); name = kstate_get_state_name(state); fail_unless(name == NULL); } END_TEST START_TEST(query_state_permissions) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_READ|KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); uint32_t permissions = kstate_get_state_permissions(state); ck_assert_int_eq(permissions, KSTATE_READ|KSTATE_WRITE); kstate_unsubscribe_state(state); permissions = kstate_get_state_permissions(state); fail_unless(permissions == 0); kstate_free_state(&state); permissions = kstate_get_state_permissions(state); fail_unless(permissions == 0); } END_TEST START_TEST(query_state_pointer) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_READ|KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); void *ptr = kstate_get_state_ptr(state); fail_if(ptr == NULL); kstate_unsubscribe_state(state); ptr = kstate_get_state_ptr(state); fail_unless(ptr == NULL); kstate_free_state(&state); ptr = kstate_get_state_ptr(state); fail_unless(ptr == NULL); } END_TEST START_TEST(can_read_state_pointer) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_READ|KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); void *ptr = kstate_get_state_ptr(state); fail_if(ptr == NULL); // When the shared memory is first set up, it is all zeroes uint32_t *first = ptr; ck_assert_int_eq(*first, 0); kstate_unsubscribe_state(state); kstate_free_state(&state); } END_TEST // NB: This will "leak" a kstate state in /dev/shm START_TEST(writing_state_pointer_fails) // expect signal SIGSEGV { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_READ|KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); void *ptr = kstate_get_state_ptr(state); fail_if(ptr == NULL); // This should fail, because we are meant to use a transaction to alter // a state's data uint32_t *first = ptr; *first = 1; kstate_unsubscribe_state(state); kstate_free_state(&state); } END_TEST START_TEST(subscribe_for_write_then_for_read) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state_w = kstate_new_state(); int rv = kstate_subscribe_state(state_w, state_name, KSTATE_WRITE); ck_assert_int_eq(rv, 0); kstate_state_p state_r = kstate_new_state(); rv = kstate_subscribe_state(state_r, state_name, KSTATE_READ); ck_assert_int_eq(rv, 0); free(state_name); kstate_unsubscribe_state(state_w); kstate_free_state(&state_w); kstate_unsubscribe_state(state_r); kstate_free_state(&state_r); } END_TEST START_TEST(subscribe_for_write_then_for_write) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state_w1 = kstate_new_state(); int rv = kstate_subscribe_state(state_w1, state_name, KSTATE_WRITE); ck_assert_int_eq(rv, 0); kstate_state_p state_w2 = kstate_new_state(); rv = kstate_subscribe_state(state_w2, state_name, KSTATE_WRITE); ck_assert_int_eq(rv, 0); free(state_name); kstate_unsubscribe_state(state_w1); kstate_free_state(&state_w1); kstate_unsubscribe_state(state_w2); kstate_free_state(&state_w2); } END_TEST START_TEST(subscribe_for_write_then_for_read_unsubscribe_other_order) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state_w = kstate_new_state(); int rv = kstate_subscribe_state(state_w, state_name, KSTATE_READ|KSTATE_WRITE); ck_assert_int_eq(rv, 0); kstate_state_p state_r = kstate_new_state(); rv = kstate_subscribe_state(state_r, state_name, KSTATE_READ); ck_assert_int_eq(rv, 0); free(state_name); kstate_unsubscribe_state(state_r); kstate_free_state(&state_r); kstate_unsubscribe_state(state_w); kstate_free_state(&state_w); } END_TEST START_TEST(subscribe_with_NULL_state_fails) { char *state_name = kstate_get_unique_name("Fred"); int rv = kstate_subscribe_state(NULL, state_name, KSTATE_READ|KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, -EINVAL); } END_TEST START_TEST(create_and_free_transaction) { kstate_transaction_p transaction = kstate_new_transaction(); fail_if(transaction == NULL); kstate_free_transaction(&transaction); fail_unless(transaction == NULL); } END_TEST START_TEST(free_NULL_transaction) { kstate_transaction_p transaction = NULL; kstate_free_transaction(&transaction); fail_unless(transaction == NULL); } END_TEST START_TEST(start_transaction_with_NULL_transaction_fails) { kstate_state_p state = kstate_new_state(); fail_if(state == NULL); int rv = kstate_start_transaction(NULL, state, KSTATE_READ); ck_assert_int_eq(rv, -EINVAL); } END_TEST START_TEST(start_transaction_with_NULL_state_fails) { kstate_state_p state = NULL; kstate_transaction_p transaction = kstate_new_transaction(); fail_if(transaction == NULL); int rv = kstate_start_transaction(transaction, state, KSTATE_READ); ck_assert_int_eq(rv, -EINVAL); } END_TEST START_TEST(start_transaction_with_unset_state_fails) { kstate_state_p state = kstate_new_state(); kstate_transaction_p transaction = kstate_new_transaction(); fail_if(transaction == NULL); int rv = kstate_start_transaction(transaction, state, KSTATE_READ); ck_assert_int_eq(rv, -EINVAL); } END_TEST START_TEST(start_transaction_with_zero_permissions_fails) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_READ|KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction = kstate_new_transaction(); rv = kstate_start_transaction(transaction, state, 0); ck_assert_int_eq(rv, -EINVAL); kstate_free_state(&state); } END_TEST START_TEST(start_transaction_with_too_many_permissions_fails) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_READ|KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction = kstate_new_transaction(); rv = kstate_start_transaction(transaction, state, 0xF); ck_assert_int_eq(rv, -EINVAL); kstate_free_state(&state); } END_TEST START_TEST(start_write_transaction_on_readonly_state_fails) { char *state_name = kstate_get_unique_name("Fred"); // First, create a writeable state (we can't create a read-only state // from nothing) kstate_state_p state_w = kstate_new_state(); int rv = kstate_subscribe_state(state_w, state_name, KSTATE_WRITE); ck_assert_int_eq(rv, 0); // Now let's have a read--only "view" of that state kstate_state_p state_r = kstate_new_state(); rv = kstate_subscribe_state(state_r, state_name, KSTATE_READ); ck_assert_int_eq(rv, 0); kstate_free_state(&state_w); free(state_name); kstate_transaction_p transaction = kstate_new_transaction(); rv = kstate_start_transaction(transaction, state_r, KSTATE_WRITE); ck_assert_int_eq(rv, -EINVAL); kstate_free_state(&state_r); } END_TEST START_TEST(start_write_transaction_on_writable_state) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_READ|KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction = kstate_new_transaction(); rv = kstate_start_transaction(transaction, state, KSTATE_READ|KSTATE_WRITE); ck_assert_int_eq(rv, 0); kstate_free_transaction(&transaction); kstate_free_state(&state); } END_TEST START_TEST(start_read_transaction_on_writable_state) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_READ|KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction = kstate_new_transaction(); rv = kstate_start_transaction(transaction, state, KSTATE_READ); ck_assert_int_eq(rv, 0); kstate_free_transaction(&transaction); kstate_free_state(&state); } END_TEST START_TEST(start_write_only_transaction_is_actually_readwrite) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_READ|KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction = kstate_new_transaction(); rv = kstate_start_transaction(transaction, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); kstate_free_transaction(&transaction); kstate_free_state(&state); } END_TEST START_TEST(sensible_transaction_aborted) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_READ|KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction = kstate_new_transaction(); rv = kstate_start_transaction(transaction, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); rv = kstate_abort_transaction(transaction); ck_assert_int_eq(rv, 0); fail_if(kstate_transaction_is_active(transaction)); kstate_free_transaction(&transaction); fail_unless(transaction == NULL); kstate_unsubscribe_state(state); kstate_free_state(&state); } END_TEST START_TEST(sensible_transaction_committed) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_READ|KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction = kstate_new_transaction(); rv = kstate_start_transaction(transaction, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); rv = kstate_commit_transaction(transaction); ck_assert_int_eq(rv, 0); fail_if(kstate_transaction_is_active(transaction)); kstate_free_transaction(&transaction); fail_unless(transaction == NULL); kstate_unsubscribe_state(state); kstate_free_state(&state); } END_TEST START_TEST(commit_readonly_transaction_fails) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_READ|KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction = kstate_new_transaction(); rv = kstate_start_transaction(transaction, state, KSTATE_READ); ck_assert_int_eq(rv, 0); // Commit fails rv = kstate_commit_transaction(transaction); ck_assert_int_eq(rv, -EPERM); fail_unless(kstate_transaction_is_active(transaction)); // But we can always abort rv = kstate_abort_transaction(transaction); ck_assert_int_eq(rv, 0); fail_if(kstate_transaction_is_active(transaction)); kstate_free_transaction(&transaction); fail_unless(transaction == NULL); kstate_unsubscribe_state(state); kstate_free_state(&state); } END_TEST START_TEST(free_transaction_also_aborts) // or, at least, doesn't fall over { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_READ|KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction = kstate_new_transaction(); rv = kstate_start_transaction(transaction, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); kstate_free_transaction(&transaction); fail_unless(transaction == NULL); kstate_unsubscribe_state(state); kstate_free_state(&state); } END_TEST START_TEST(query_transaction_name) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_READ|KSTATE_WRITE); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction = kstate_new_transaction(); rv = kstate_start_transaction(transaction, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); const char *name = kstate_get_transaction_name(transaction); ck_assert_str_eq(name, state_name); free(state_name); rv = kstate_abort_transaction(transaction); ck_assert_int_eq(rv, 0); fail_if(kstate_transaction_is_active(transaction)); name = kstate_get_transaction_name(transaction); fail_unless(name == NULL); kstate_free_transaction(&transaction); name = kstate_get_transaction_name(transaction); fail_unless(name == NULL); kstate_unsubscribe_state(state); kstate_free_state(&state); } END_TEST START_TEST(query_transaction_state_permissions) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_READ|KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction = kstate_new_transaction(); rv = kstate_start_transaction(transaction, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); uint32_t permissions = kstate_get_transaction_permissions(transaction); ck_assert_int_eq(permissions, KSTATE_READ|KSTATE_WRITE); rv = kstate_abort_transaction(transaction); ck_assert_int_eq(rv, 0); permissions = kstate_get_transaction_permissions(transaction); fail_unless(permissions == 0); kstate_free_transaction(&transaction); permissions = kstate_get_transaction_permissions(transaction); fail_unless(permissions == 0); kstate_unsubscribe_state(state); kstate_free_state(&state); } END_TEST START_TEST(query_transaction_state_pointer) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_READ|KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction = kstate_new_transaction(); rv = kstate_start_transaction(transaction, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); void *ptr = kstate_get_transaction_ptr(transaction); fail_if(ptr == NULL); rv = kstate_abort_transaction(transaction); ck_assert_int_eq(rv, 0); ptr = kstate_get_transaction_ptr(transaction); fail_unless(ptr == NULL); kstate_free_transaction(&transaction); ptr = kstate_get_transaction_ptr(transaction); fail_unless(ptr == NULL); kstate_unsubscribe_state(state); kstate_free_state(&state); } END_TEST START_TEST(abort_transaction_twice_fails) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_READ|KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction = kstate_new_transaction(); rv = kstate_start_transaction(transaction, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); rv = kstate_abort_transaction(transaction); ck_assert_int_eq(rv, 0); fail_if(kstate_transaction_is_active(transaction)); rv = kstate_abort_transaction(transaction); ck_assert_int_eq(rv, -EINVAL); kstate_free_transaction(&transaction); kstate_unsubscribe_state(state); kstate_free_state(&state); } END_TEST START_TEST(commit_transaction_twice_fails) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_READ|KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction = kstate_new_transaction(); rv = kstate_start_transaction(transaction, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); rv = kstate_commit_transaction(transaction); ck_assert_int_eq(rv, 0); fail_if(kstate_transaction_is_active(transaction)); rv = kstate_commit_transaction(transaction); ck_assert_int_eq(rv, -EINVAL); kstate_free_transaction(&transaction); kstate_unsubscribe_state(state); kstate_free_state(&state); } END_TEST START_TEST(abort_NULL_fails) { int rv = kstate_abort_transaction(NULL); ck_assert_int_eq(rv, -EINVAL); } END_TEST START_TEST(commit_NULL_fails) { int rv = kstate_commit_transaction(NULL); ck_assert_int_eq(rv, -EINVAL); } END_TEST START_TEST(abort_unstarted_transaction_fails) { kstate_transaction_p transaction = kstate_new_transaction(); int rv = kstate_abort_transaction(transaction); ck_assert_int_eq(rv, -EINVAL); kstate_free_transaction(&transaction); } END_TEST START_TEST(commit_unstarted_transaction_fails) { kstate_transaction_p transaction = kstate_new_transaction(); int rv = kstate_commit_transaction(transaction); ck_assert_int_eq(rv, -EINVAL); kstate_free_transaction(&transaction); } END_TEST START_TEST(abort_freed_transaction_fails) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_READ|KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction = kstate_new_transaction(); rv = kstate_start_transaction(transaction, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); kstate_free_transaction(&transaction); rv = kstate_abort_transaction(transaction); ck_assert_int_eq(rv, -EINVAL); kstate_unsubscribe_state(state); kstate_free_state(&state); } END_TEST START_TEST(commit_freed_transaction_fails) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_READ|KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction = kstate_new_transaction(); rv = kstate_start_transaction(transaction, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); kstate_free_transaction(&transaction); rv = kstate_commit_transaction(transaction); ck_assert_int_eq(rv, -EINVAL); kstate_free_transaction(&transaction); kstate_unsubscribe_state(state); kstate_free_state(&state); } END_TEST // A transaction takes a copy of the state START_TEST(transaction_aborted_after_state_freed) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_READ|KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction = kstate_new_transaction(); rv = kstate_start_transaction(transaction, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); kstate_free_state(&state); fail_unless(state == NULL); rv = kstate_abort_transaction(transaction); ck_assert_int_eq(rv, 0); fail_if(kstate_transaction_is_active(transaction)); kstate_free_transaction(&transaction); } END_TEST // A transaction takes a copy of the state START_TEST(transaction_committed_after_state_freed) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_READ|KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction = kstate_new_transaction(); rv = kstate_start_transaction(transaction, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); kstate_free_state(&state); fail_unless(state == NULL); rv = kstate_commit_transaction(transaction); ck_assert_int_eq(rv, 0); fail_if(kstate_transaction_is_active(transaction)); kstate_free_transaction(&transaction); } END_TEST START_TEST(states_can_be_distinguished) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state1 = kstate_new_state(); int rv = kstate_subscribe_state(state1, state_name, KSTATE_READ|KSTATE_WRITE); ck_assert_int_eq(rv, 0); kstate_state_p state2 = kstate_new_state(); rv = kstate_subscribe_state(state2, state_name, KSTATE_READ|KSTATE_WRITE); ck_assert_int_eq(rv, 0); free(state_name); uint32_t id1 = kstate_get_state_id(state1); ck_assert_int_ne(id1, 0); uint32_t id2 = kstate_get_state_id(state2); ck_assert_int_ne(id2, 0); ck_assert_int_ne(id1, id2); ck_assert_int_eq(id1, kstate_get_state_id(state1)); ck_assert_int_eq(id2, kstate_get_state_id(state2)); kstate_free_state(&state1); kstate_free_state(&state2); id1 = kstate_get_state_id(state1); ck_assert_int_eq(id1, 0); id2 = kstate_get_state_id(state2); ck_assert_int_eq(id2, 0); } END_TEST START_TEST(transactions_can_be_distinguished) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_READ|KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction1 = kstate_new_transaction(); rv = kstate_start_transaction(transaction1, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction2 = kstate_new_transaction(); rv = kstate_start_transaction(transaction2, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); uint32_t id1 = kstate_get_transaction_id(transaction1); ck_assert_int_ne(id1, 0); uint32_t id2 = kstate_get_transaction_id(transaction2); ck_assert_int_ne(id2, 0); ck_assert_int_ne(id1, id2); ck_assert_int_eq(id1, kstate_get_transaction_id(transaction1)); ck_assert_int_eq(id2, kstate_get_transaction_id(transaction2)); kstate_free_transaction(&transaction1); kstate_free_transaction(&transaction2); id1 = kstate_get_transaction_id(transaction1); ck_assert_int_eq(id1, 0); id2 = kstate_get_transaction_id(transaction2); ck_assert_int_eq(id2, 0); kstate_free_state(&state); } END_TEST START_TEST(nested_transactions_same_state_commit_commit) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_READ|KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction1 = kstate_new_transaction(); rv = kstate_start_transaction(transaction1, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction2 = kstate_new_transaction(); rv = kstate_start_transaction(transaction2, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); rv = kstate_commit_transaction(transaction2); ck_assert_int_eq(rv, 0); fail_if(kstate_transaction_is_active(transaction2)); rv = kstate_commit_transaction(transaction1); ck_assert_int_eq(rv, 0); fail_if(kstate_transaction_is_active(transaction1)); kstate_free_transaction(&transaction1); kstate_free_transaction(&transaction2); kstate_free_state(&state); fail_unless(state == NULL); } END_TEST START_TEST(nested_transactions_same_state_commit_abort) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_READ|KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction1 = kstate_new_transaction(); rv = kstate_start_transaction(transaction1, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction2 = kstate_new_transaction(); rv = kstate_start_transaction(transaction2, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); rv = kstate_commit_transaction(transaction2); ck_assert_int_eq(rv, 0); fail_if(kstate_transaction_is_active(transaction2)); rv = kstate_abort_transaction(transaction1); ck_assert_int_eq(rv, 0); fail_if(kstate_transaction_is_active(transaction1)); kstate_free_transaction(&transaction1); kstate_free_transaction(&transaction2); kstate_free_state(&state); fail_unless(state == NULL); } END_TEST START_TEST(nested_transactions_same_state_abort_commit) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_READ|KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction1 = kstate_new_transaction(); rv = kstate_start_transaction(transaction1, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction2 = kstate_new_transaction(); rv = kstate_start_transaction(transaction2, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); rv = kstate_abort_transaction(transaction2); ck_assert_int_eq(rv, 0); fail_if(kstate_transaction_is_active(transaction2)); rv = kstate_commit_transaction(transaction1); ck_assert_int_eq(rv, 0); fail_if(kstate_transaction_is_active(transaction1)); kstate_free_transaction(&transaction1); kstate_free_transaction(&transaction2); kstate_free_state(&state); fail_unless(state == NULL); } END_TEST START_TEST(interleaved_transactions_same_state_commit_commit) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_READ|KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction1 = kstate_new_transaction(); rv = kstate_start_transaction(transaction1, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction2 = kstate_new_transaction(); rv = kstate_start_transaction(transaction2, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); rv = kstate_commit_transaction(transaction1); ck_assert_int_eq(rv, 0); fail_if(kstate_transaction_is_active(transaction1)); rv = kstate_commit_transaction(transaction2); ck_assert_int_eq(rv, 0); fail_if(kstate_transaction_is_active(transaction2)); kstate_free_transaction(&transaction1); kstate_free_transaction(&transaction2); kstate_free_state(&state); fail_unless(state == NULL); } END_TEST START_TEST(interleaved_transactions_same_state_commit_abort) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_READ|KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction1 = kstate_new_transaction(); rv = kstate_start_transaction(transaction1, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction2 = kstate_new_transaction(); rv = kstate_start_transaction(transaction2, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); rv = kstate_commit_transaction(transaction1); ck_assert_int_eq(rv, 0); fail_if(kstate_transaction_is_active(transaction1)); rv = kstate_abort_transaction(transaction2); ck_assert_int_eq(rv, 0); fail_if(kstate_transaction_is_active(transaction2)); kstate_free_transaction(&transaction1); kstate_free_transaction(&transaction2); kstate_free_state(&state); fail_unless(state == NULL); } END_TEST START_TEST(interleaved_transactions_same_state_abort_commit) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_READ|KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction1 = kstate_new_transaction(); rv = kstate_start_transaction(transaction1, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction2 = kstate_new_transaction(); rv = kstate_start_transaction(transaction2, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); rv = kstate_abort_transaction(transaction1); ck_assert_int_eq(rv, 0); fail_if(kstate_transaction_is_active(transaction1)); rv = kstate_commit_transaction(transaction2); ck_assert_int_eq(rv, 0); fail_if(kstate_transaction_is_active(transaction2)); kstate_free_transaction(&transaction1); kstate_free_transaction(&transaction2); kstate_free_state(&state); fail_unless(state == NULL); } END_TEST // NB: This will "leak" a kstate state in /dev/shm START_TEST(write_to_readonly_transaction_fails) // expect signal SIGSEGV { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction = kstate_new_transaction(); rv = kstate_start_transaction(transaction, state, KSTATE_READ); ck_assert_int_eq(rv, 0); uint32_t *ptr = kstate_get_transaction_ptr(transaction); *ptr = 0x12345678; kstate_free_state(&state); fail_unless(state == NULL); rv = kstate_commit_transaction(transaction); ck_assert_int_eq(rv, 0); fail_if(kstate_transaction_is_active(transaction)); kstate_free_transaction(&transaction); } END_TEST START_TEST(write_to_writeable_transaction_does_not_fail) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction = kstate_new_transaction(); rv = kstate_start_transaction(transaction, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); uint32_t *t_ptr = kstate_get_transaction_ptr(transaction); *t_ptr = 0x12345678; rv = kstate_abort_transaction(transaction); ck_assert_int_eq(rv, 0); kstate_free_transaction(&transaction); kstate_free_state(&state); fail_unless(state == NULL); } END_TEST START_TEST(write_to_writeable_transaction_visible_after_commit) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction = kstate_new_transaction(); rv = kstate_start_transaction(transaction, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); uint32_t *t_ptr = kstate_get_transaction_ptr(transaction); *t_ptr = 0x12345678; rv = kstate_commit_transaction(transaction); ck_assert_int_eq(rv, 0); kstate_free_transaction(&transaction); uint32_t *s_ptr = kstate_get_state_ptr(state); ck_assert_int_eq(rv, 0); ck_assert_int_eq(*s_ptr, 0x12345678); kstate_free_state(&state); fail_unless(state == NULL); } END_TEST START_TEST(write_to_writeable_transaction_not_visible_before_end_of_transaction) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); // As we remember, the mapped area starts off all zeroes uint32_t *s_ptr1 = kstate_get_state_ptr(state); ck_assert_int_eq(rv, 0); ck_assert_int_eq(*s_ptr1, 0); kstate_transaction_p transaction = kstate_new_transaction(); rv = kstate_start_transaction(transaction, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); uint32_t *t_ptr = kstate_get_transaction_ptr(transaction); *t_ptr = 0x12345678; uint32_t *s_ptr2 = kstate_get_state_ptr(state); ck_assert_int_eq(rv, 0); // The state still has the same location mapped fail_unless(s_ptr1 == s_ptr2); // The state does not see the uncommitted change ck_assert_int_eq(*s_ptr2, 0); rv = kstate_abort_transaction(transaction); ck_assert_int_eq(rv, 0); kstate_free_transaction(&transaction); kstate_free_state(&state); fail_unless(state == NULL); } END_TEST START_TEST(write_to_writeable_transaction_not_visible_after_abort) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); // As we remember, the mapped area starts off all zeroes uint32_t *s_ptr1 = kstate_get_state_ptr(state); ck_assert_int_eq(rv, 0); ck_assert_int_eq(*s_ptr1, 0); kstate_transaction_p transaction = kstate_new_transaction(); rv = kstate_start_transaction(transaction, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); uint32_t *t_ptr = kstate_get_transaction_ptr(transaction); *t_ptr = 0x12345678; rv = kstate_abort_transaction(transaction); ck_assert_int_eq(rv, 0); kstate_free_transaction(&transaction); uint32_t *s_ptr2 = kstate_get_state_ptr(state); ck_assert_int_eq(rv, 0); // The state still has the same location mapped fail_unless(s_ptr1 == s_ptr2); // The state does not see the uncommitted change ck_assert_int_eq(*s_ptr2, 0); kstate_free_state(&state); fail_unless(state == NULL); } END_TEST START_TEST(commit_when_state_changed_during_transaction_fails) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); uint32_t *s_ptr = kstate_get_state_ptr(state); ck_assert_int_eq(*s_ptr, 0); kstate_transaction_p transaction1 = kstate_new_transaction(); rv = kstate_start_transaction(transaction1, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction2 = kstate_new_transaction(); rv = kstate_start_transaction(transaction2, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); uint32_t *t_ptr1 = kstate_get_transaction_ptr(transaction1); *t_ptr1 = 0x12345678; ck_assert_int_eq(*s_ptr, 0); rv = kstate_commit_transaction(transaction1); ck_assert_int_eq(rv, 0); kstate_free_transaction(&transaction1); ck_assert_int_eq(*s_ptr, 0x12345678); uint32_t *t_ptr2 = kstate_get_transaction_ptr(transaction2); *t_ptr2 = 0x87654321; rv = kstate_commit_transaction(transaction2); ck_assert_int_eq(rv, -EPERM); kstate_free_transaction(&transaction2); ck_assert_int_eq(*s_ptr, 0x12345678); kstate_free_state(&state); fail_unless(state == NULL); } END_TEST START_TEST(abort_when_state_changed_during_transaction_succeeds) { char *state_name = kstate_get_unique_name("Fred"); kstate_state_p state = kstate_new_state(); int rv = kstate_subscribe_state(state, state_name, KSTATE_WRITE); free(state_name); ck_assert_int_eq(rv, 0); uint32_t *s_ptr = kstate_get_state_ptr(state); ck_assert_int_eq(*s_ptr, 0); kstate_transaction_p transaction1 = kstate_new_transaction(); rv = kstate_start_transaction(transaction1, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); kstate_transaction_p transaction2 = kstate_new_transaction(); rv = kstate_start_transaction(transaction2, state, KSTATE_WRITE); ck_assert_int_eq(rv, 0); uint32_t *t_ptr1 = kstate_get_transaction_ptr(transaction1); ck_assert_int_eq(*t_ptr1, 0); *t_ptr1 = 0x12345678; ck_assert_int_eq(*s_ptr, 0); rv = kstate_commit_transaction(transaction1); ck_assert_int_eq(rv, 0); kstate_free_transaction(&transaction1); uint32_t *t_ptr2 = kstate_get_transaction_ptr(transaction2); ck_assert_int_eq(*t_ptr2, 0); *t_ptr2 = 0x87654321; ck_assert_int_eq(*s_ptr, 0x12345678); rv = kstate_abort_transaction(transaction2); ck_assert_int_eq(rv, 0); kstate_free_transaction(&transaction2); ck_assert_int_eq(*s_ptr, 0x12345678); kstate_free_state(&state); fail_unless(state == NULL); } END_TEST Suite *test_kstate_suite(void) { Suite *s = suite_create("Kstate"); TCase *tc_core = tcase_create("core"); // The code between the "TESTS" delimiters is auto-generated by the // 'extract_tests.py' script. This helps avoid having to fix compiler // warnings when I forget to include a new test in the list. // START TESTS tcase_add_test(tc_core, new_and_free_state); tcase_add_test(tc_core, free_NULL_state); tcase_add_test(tc_core, subscribe_with_NULL_name_fails); tcase_add_test(tc_core, subscribe_with_zero_permissions_fails); tcase_add_test(tc_core, subscribe_with_too_many_permissions_fails); tcase_add_test(tc_core, subscribe_with_NULL_name_and_zero_permissions_fails); tcase_add_test(tc_core, subscribe_with_zero_length_name_fails); tcase_add_test(tc_core, subscribe_with_too_long_name_fails); tcase_add_test(tc_core, subscribe_with_max_length_name_and_unsubscribe); tcase_add_test(tc_core, subscribe_with_dot_at_start_of_name_fails); tcase_add_test(tc_core, subscribe_with_dot_at_end_of_name_fails); tcase_add_test(tc_core, subscribe_with_adjacent_dots_in_name_fails); tcase_add_test(tc_core, subscribe_with_non_alphanumeric_in_name_fails); tcase_add_test(tc_core, subscribe_for_read_alone_fails); tcase_add_test(tc_core, subscribe_for_write_is_actually_for_readwrite); tcase_add_test(tc_core, subscribe_for_readwrite_and_unsubscribe_and_free); tcase_add_test(tc_core, subscribe_for_readwrite_and_free); tcase_add_test(tc_core, query_state_name); tcase_add_test(tc_core, query_state_permissions); tcase_add_test(tc_core, query_state_pointer); tcase_add_test(tc_core, can_read_state_pointer); tcase_add_test_raise_signal(tc_core, writing_state_pointer_fails, SIGSEGV); tcase_add_test(tc_core, subscribe_for_write_then_for_read); tcase_add_test(tc_core, subscribe_for_write_then_for_write); tcase_add_test(tc_core, subscribe_for_write_then_for_read_unsubscribe_other_order); tcase_add_test(tc_core, subscribe_with_NULL_state_fails); tcase_add_test(tc_core, create_and_free_transaction); tcase_add_test(tc_core, free_NULL_transaction); tcase_add_test(tc_core, start_transaction_with_NULL_transaction_fails); tcase_add_test(tc_core, start_transaction_with_NULL_state_fails); tcase_add_test(tc_core, start_transaction_with_unset_state_fails); tcase_add_test(tc_core, start_transaction_with_zero_permissions_fails); tcase_add_test(tc_core, start_transaction_with_too_many_permissions_fails); tcase_add_test(tc_core, start_write_transaction_on_readonly_state_fails); tcase_add_test(tc_core, start_write_transaction_on_writable_state); tcase_add_test(tc_core, start_read_transaction_on_writable_state); tcase_add_test(tc_core, start_write_only_transaction_is_actually_readwrite); tcase_add_test(tc_core, sensible_transaction_aborted); tcase_add_test(tc_core, sensible_transaction_committed); tcase_add_test(tc_core, commit_readonly_transaction_fails); tcase_add_test(tc_core, free_transaction_also_aborts); tcase_add_test(tc_core, query_transaction_name); tcase_add_test(tc_core, query_transaction_state_permissions); tcase_add_test(tc_core, query_transaction_state_pointer); tcase_add_test(tc_core, abort_transaction_twice_fails); tcase_add_test(tc_core, commit_transaction_twice_fails); tcase_add_test(tc_core, abort_NULL_fails); tcase_add_test(tc_core, commit_NULL_fails); tcase_add_test(tc_core, abort_unstarted_transaction_fails); tcase_add_test(tc_core, commit_unstarted_transaction_fails); tcase_add_test(tc_core, abort_freed_transaction_fails); tcase_add_test(tc_core, commit_freed_transaction_fails); tcase_add_test(tc_core, transaction_aborted_after_state_freed); tcase_add_test(tc_core, transaction_committed_after_state_freed); tcase_add_test(tc_core, states_can_be_distinguished); tcase_add_test(tc_core, transactions_can_be_distinguished); tcase_add_test(tc_core, nested_transactions_same_state_commit_commit); tcase_add_test(tc_core, nested_transactions_same_state_commit_abort); tcase_add_test(tc_core, nested_transactions_same_state_abort_commit); tcase_add_test(tc_core, interleaved_transactions_same_state_commit_commit); tcase_add_test(tc_core, interleaved_transactions_same_state_commit_abort); tcase_add_test(tc_core, interleaved_transactions_same_state_abort_commit); tcase_add_test_raise_signal(tc_core, write_to_readonly_transaction_fails, SIGSEGV); tcase_add_test(tc_core, write_to_writeable_transaction_does_not_fail); tcase_add_test(tc_core, write_to_writeable_transaction_visible_after_commit); tcase_add_test(tc_core, write_to_writeable_transaction_not_visible_before_end_of_transaction); tcase_add_test(tc_core, write_to_writeable_transaction_not_visible_after_abort); tcase_add_test(tc_core, commit_when_state_changed_during_transaction_fails); tcase_add_test(tc_core, abort_when_state_changed_during_transaction_succeeds); // END TESTS suite_add_tcase(s, tc_core); return s; } int main (void) { int number_failed; Suite *s = test_kstate_suite(); SRunner *sr = srunner_create(s); srunner_run_all(sr, CK_NORMAL); number_failed = srunner_ntests_failed(sr); srunner_free(sr); // Ensure we tidy up any left-over shared memory object files printf("\n"); delete_our_kstate_shm_files(); printf("\n"); if (number_failed == 0) { printf("The light is GREEN\n"); } else { printf("The light is RED\n"); } return number_failed; } // vim: set tabstop=8 softtabstop=2 shiftwidth=2 expandtab: <file_sep>/README.md This is a library to make it simple to share state between Linux processes. It aims to be able to cope with rapidly changing state, which may or may not be inspected at the same frequency. A simple transaction model is supported. A shared state may not be more than one page in size. --- _There's code here, but it's nowhere near doing anything useful yet. I'm basically using the repository as a way to colocate development between work and home. APIs are not fixed, behaviour is not fixed (it's not necessarily even there yet!), and major ideas are even likely to change. So, very much caveat emptor._ _I shall take this notice away (or at least modify it) when there is something that other people might find of use..._ Currently, [check](http://check.sourceforge.net/) is being used to write C unit tests for the project, and this is a dependency in the Makefile (i.e.,building also runs the tests). 'check' is LGPLv2, but since the binaries produced for the unit tests are _not_ part of the final product, I believe its use is OK from a licensing point of view. Regardless, it may or may not be used in future versions of the project.<file_sep>/extract_tests.py #!/usr/bin/env python """extract_tests.py -- Find "check" tests and put them in a suite Usage: ./extract_tests.py [-h | -help | --help] ./extract_tests.py <c_file> Looks for tests declared as:: START_TEST(<name>) START_TEST(<name>) // expect signal <SIGNAL> START_TEST(<name>) // any other sort of comment and replaces the text between:: // TESTS START and:: // TESTS END with lines of the form:: tcase_add_test(tc_core, <name>); or:: tcase_add_test_raise_signal(tc_core, <name>, <SIGNAL>); as appropriate. It's terribly simple. """ # ***** BEGIN LICENSE BLOCK ***** # Version: MPL 1.1 # # The contents of this file are subject to the Mozilla Public License Version # 1.1 (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.mozilla.org/MPL/ # # Software distributed under the License is distributed on an "AS IS" basis, # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License # for the specific language governing rights and limitations under the # License. # # The Original Code is the Kynesim state management library. # # The Initial Developer of the Original Code is Kynesim, Cambridge UK. # Portions created by the Initial Developer are Copyright (C) 2012 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Kynesim, Cambridge UK # <NAME> <<EMAIL>> # # ***** END LICENSE BLOCK ***** import os import re import sys from difflib import ndiff test_pattern = """\ START_TEST\( (?P<test>.*) # the name of our test \) (( # followed by \s+ // \s+ # a comment starting with spaces and ( # either expect \s* signal \s* # the "expect signal" keywords (?P<signal>.*) # followed by the name of the signal we're expecting ) | ( # or .* # anything (just a comment) ) \n ) | ( # or \n # and EOL )) """ file_pattern = """\ (?P<start> .* \\n[\t\ ]*//\ START\ TESTS\\n ) (?P<middle> .* ) (?P<end> ^[\t\ ]*//\ END\ TESTS\\n .* ) """ DEBUG = False class GiveUp(Exception): pass def extract_tests(c_file): """Extract the test names """ with open(c_file,'r') as file: data = file.read() matches = re.finditer(test_pattern, data, re.VERBOSE) tests = [] for m in matches: if m.group('signal'): print ' Found ',m.group('test'), 'expect signal', m.group('signal') tests.append((m.group('test'), 'signal', m.group('signal'))) else: print ' Found ',m.group('test') tests.append((m.group('test'), None, None)) return tests def split_file(c_file): """Split the header file into its three parts and return them. We have: * the start of the file (written by the user) * the middle of the file (inserted by a previous use of this script) * the end of the file (written by the user) """ with open(c_file, 'r') as original: data = original.read() match = re.match(file_pattern, data, re.VERBOSE|re.MULTILINE|re.DOTALL) if match is None: raise GiveUp('Could not match file to START TESTS...END TESTS pattern\n') start = match.group('start') middle = match.group('middle') end = match.group('end') return start, middle, end def process_file(c_file): """Update the list of tests in our C file """ temp_file = c_file + '.new' save_file = c_file + '.bak' print 'Finding tests in %s'%(c_file) tests = extract_tests(c_file) if len(tests) == 0: print 'No tests found' return new_middle = [] for test, what, signal in tests: if what == 'signal': new_middle.append(' tcase_add_test_raise_signal(tc_core, %s, %s);'%(test, signal)) else: new_middle.append(' tcase_add_test(tc_core, %s);'%test) new_middle = '\n'.join(new_middle) + '\n' try: start, middle, end = split_file(c_file) except GiveUp as e: print e return # Do we need to change anything? if DEBUG and middle != new_middle: print print 'List of tests for %s has changed'%c_file print '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>' print '"%s"'%middle.splitlines()[0] print '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>' diff = ndiff(middle.splitlines(), new_middle.splitlines()) print '\n'.join(diff) print '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>' if middle == new_middle: print 'Nothing changed' else: print 'Writing new %s'%c_file with open(temp_file, 'w') as output: output.write(start) output.write(new_middle) output.write(end) os.rename(c_file, save_file) os.rename(temp_file, c_file) def do_stuff(args): if len(args) != 1 or args[0] in ('-help', '-h', '--help'): print __doc__ return c_file = args[0] # Basic checks before we do *anything* if not os.path.exists(c_file): print 'C source file %s does not exist'%c_file return if os.path.splitext(c_file)[-1] != '.c': print 'C source file %s does not have extension .c'%c_file return process_file(c_file) if __name__ == '__main__': do_stuff(sys.argv[1:]) # vim: set tabstop=8 softtabstop=4 shiftwidth=4 expandtab: <file_sep>/kstate.c /* * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the BUS State library. * * The Initial Developer of the Original Code is Kynesim, Cambridge UK. * Portions created by the Initial Developer are Copyright (C) 2013 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Kynesim, Cambridge UK * <NAME> <<EMAIL>> * * ***** END LICENSE BLOCK ***** */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <ctype.h> // for isalnum #include <time.h> // for strftime #include <sys/time.h> // for gettimeofday #include <sys/types.h> #include <unistd.h> // For shm_open and friends #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #include "kstate.h" struct kstate_state { char *name; // The name of our shared memory object uint32_t permissions; // Our idea of its permissions uint32_t id; // A simple id for this state void *map_addr; // The shared memory associated with it size_t map_length; // and how much shared memory there is }; struct kstate_transaction { char *name; // The name of our shared memory object uint32_t id; // A simple id for this transaction uint32_t permissions; // The permissions for this transaction void *state_map_addr; // The shared memory associated with the state uint8_t *state_map_copy; // A copy of the original values therein void *map_addr; // Our own shared memory, starting as another copy size_t map_length; // The length of those }; static int num_digits(int value) { int count = 0; do { ++count; value /= 10; } while (value); return count; } /* * Given a state name, is it valid? * * Returns the name length if it's OK, 0 if it's naughty */ static size_t check_state_name(const char *caller, const char *name) { size_t ii; int dot_at = 1; if (name == NULL) { fprintf(stderr, "!!! %s: State name may not be NULL\n", caller); return 0; } size_t name_len = strlen(name); if (name_len == 0) { fprintf(stderr, "!!! %s: State name may not be zero length\n", caller); return 0; } if (name_len > KSTATE_MAX_NAME_LEN) { // Would it be more helpful to give all the characters? // Is anyone reading this? fprintf(stderr, "!!! %s: State name '%.5s..%s' is %u" " characters long, but the maximum length is %d characters\n", caller, name, &name[name_len-5], (unsigned) name_len, KSTATE_MAX_NAME_LEN); return 0; } if (name[0] == '.' || name[name_len-1] == '.') { fprintf(stderr, "!!! %s: State name '%s' may not start or" " end with '.'\n", caller, name); return 0; } for (ii = 0; ii < name_len; ii++) { if (name[ii] == '.') { if (dot_at == ii - 1) { fprintf(stderr, "!!! %s: State name '%s' may not have" " adjacent '.'s\n", caller, name); return 0; } dot_at = ii; } else if (!isalnum(name[ii])) { fprintf(stderr, "!!! %s: State name '%s' may not" " contain '%c' (not alphanumeric)\n", caller, name, name[ii]); return 0; } } return name_len; } /* * Return a kstate state name. * * Returns NULL if it is not possible to make such a name. */ static int new_state_name(const char *caller, const char *name, char **state_name) { if (name == NULL) { fprintf(stderr, "!!! %s: Supplied 'name' may not be NULL\n", caller); return -EINVAL; } size_t name_len = check_state_name(caller, name); if (name_len == 0) { return -EINVAL; } char *new = malloc(1 + 6 + 1 + name_len + 1); if (new == NULL) return -ENOMEM; sprintf(new, "/kstate.%s", name); *state_name = new; return 0; } /* * Return a unique valid state name starting with prefix. * * The name is composed of: * * * the normal kstate name prefix * * the prefix string * * the number of microseconds since the epoch * * our process id * * a statically increasing integer * * separated by dots. Thus it is only as "unique" as afforded by the * accuracy of gettimeofday - i.e., it relies on the apparent time * thus reported having changed. * * For most purposes, this should be sufficient. * * The caller is responsible for freeing the returned string. * * Returns NULL if it is not possible to make such a name with the given * prefix. */ extern char *kstate_get_unique_name(const char *prefix) { static uint32_t extra = 0; if (prefix == NULL) { fprintf(stderr, "!!! kstate_get_unique_name: Prefix may not be NULL\n"); return NULL; } size_t prefix_len = strlen(prefix); struct timeval tv; int rv = gettimeofday(&tv, NULL); if (rv) { fprintf(stderr, "!!! kstate_get_unique_name: Error getting time-of-day: %d %s\n", errno, strerror(errno)); return NULL; } pid_t pid = getpid(); char *name = malloc(prefix_len + 1 + num_digits(tv.tv_sec) + 6 + 1 + num_digits(pid) + 1 + num_digits(extra) + 1); if (name == NULL) return NULL; sprintf(name, "%s.%ld%06ld.%u.%u", prefix, tv.tv_sec, tv.tv_usec, (uint32_t) pid, extra); ++extra; return name; } static bool state_permissions_are_bad(uint32_t permissions) { if (!permissions) { fprintf(stderr, "!!! kstate_subscribe_state: Unset permissions bits (0x0) not allowed\n"); return true; } else if (permissions & ~(KSTATE_READ | KSTATE_WRITE)) { fprintf(stderr, "!!! kstate_subscribe_state: Unexpected permission bits 0x%x in 0x%x\n", permissions & ~(KSTATE_READ | KSTATE_WRITE), permissions); return true; } return false; } static bool transaction_permissions_are_bad(uint32_t permissions) { if (!permissions) { fprintf(stderr, "!!! kstate_start_transaction: Unset permissions bits (0x0) not allowed\n"); return true; } else if (permissions & ~(KSTATE_READ | KSTATE_WRITE)) { fprintf(stderr, "!!! kstate_start_transaction: Unexpected permission bits 0x%x in 0x%x\n", permissions & ~(KSTATE_READ | KSTATE_WRITE), permissions); return true; } return false; } /* * Return true if the given state is subscribed. */ extern bool kstate_state_is_subscribed(kstate_state_p state) { return state != NULL && state->name; } /* * Return true if the given transaction is active */ extern bool kstate_transaction_is_active(kstate_transaction_p transaction) { // The detail of this is bound to change return transaction != NULL && transaction->name; } /* * Return a state's name, or NULL if it is not subscribed. */ extern const char *kstate_get_state_name(kstate_state_p state) { if (kstate_state_is_subscribed(state)) { // We ignore the leading '/kstate.' text, which the user did not specify return &state->name[KSTATE_NAME_PREFIX_LEN]; } else { return NULL; } } /* * Return a transaction's name, or NULL if it is not active. */ extern const char *kstate_get_transaction_name(kstate_transaction_p transaction) { if (kstate_transaction_is_active(transaction)) { // We ignore the leading '/kstate.' text, which the user did not specify return &transaction->name[KSTATE_NAME_PREFIX_LEN]; } else { return NULL; } } /* * Return a state's permissions, or 0 if it is not subscribed. */ extern uint32_t kstate_get_state_permissions(kstate_state_p state) { if (kstate_state_is_subscribed(state)) { return state->permissions; } else { return 0; } } /* * Return a transaction's permissions, or 0 if it is not active. */ extern uint32_t kstate_get_transaction_permissions(kstate_transaction_p transaction) { if (kstate_transaction_is_active(transaction)) { return transaction->permissions; } else { return 0; } } /* * Return a state's id, or 0 if it is not subscribed. * * We do not say anything about the value of the id, except that 0 means the * state is unsubscribed, the same state always has the same id, and two * separate states have distinct ids. */ extern uint32_t kstate_get_state_id(kstate_state_p state) { if (kstate_state_is_subscribed(state)) { return state->id; } else { return 0; } } /* * Return a transaction's id, or 0 if it is not active. * * We do not say anything about the value of the id, except that 0 means the * transaction is not active, the same transaction always has the same id, and * two separate transactions have distinct ids. */ extern uint32_t kstate_get_transaction_id(kstate_transaction_p transaction) { if (kstate_transaction_is_active(transaction)) { return transaction->id; } else { return 0; } } /* * Return a state's shared memory pointer, or NULL if it is not subscribed. * * Note that this is always a pointer to read-only shared memory, as * one must use a transaction to write. * * Beware that this pointer stops being valid as soon as the state is * unsubscribed (or freed, which implicitly unsubscribes it). */ extern void *kstate_get_state_ptr(kstate_state_p state) { if (kstate_state_is_subscribed(state)) { return state->map_addr; } else { return NULL; } } /* * Return a transaction's shared memory pointer, or NULL if it is not active. * * Whether this can be used to write to the shared memory depends upon the * protection requested for the transaction. * * Beware that this pointer stops being valid as soon as the transaction is * committed or aborted (or freed, which implicitly aborts it). */ extern void *kstate_get_transaction_ptr(kstate_transaction_p transaction) { if (kstate_transaction_is_active(transaction)) { return transaction->map_addr; } else { return NULL; } } static void print_state(FILE *stream, uint32_t id, const char *name, uint32_t permissions) { fprintf(stream, "State %u on '%s' for ", id, name); if (permissions) { if (permissions & KSTATE_READ) fprintf(stream, "read"); if ((permissions & KSTATE_READ) && (permissions & KSTATE_WRITE)) fprintf(stream, "|"); if (permissions & KSTATE_WRITE) fprintf(stream, "write"); } else { fprintf(stream, "<no permissions>"); } } /* * Print a representation of 'state' on output 'stream'. * * Assumes the state is valid. * * If 'start' is non-NULL, print it before the state (with no added whitespace). * If 'eol' is true, then print a newline after the state. */ extern void kstate_print_state(FILE *stream, const char *start, kstate_state_p state, bool eol) { if (start) fprintf(stream, "%s", start); if (kstate_state_is_subscribed(state)) { print_state(stream, state->id, state->name + KSTATE_NAME_PREFIX_LEN, state->permissions); } else { fprintf(stream, "State <unsubscribed>"); } if (eol) fprintf(stream, "\n"); } static void print_transaction(FILE *stream, uint32_t id, const char *name, uint32_t permissions) { fprintf(stream, "Transaction %u for ", id); if (permissions) { if (permissions & KSTATE_READ) fprintf(stream, "read"); if ((permissions & KSTATE_READ) && (permissions & KSTATE_WRITE)) fprintf(stream, "|"); if (permissions & KSTATE_WRITE) fprintf(stream, "write"); } else { fprintf(stream, "<no permissions>"); } fprintf(stream, " on '%s'", name); } /* * Print a representation of 'transaction' on output 'stream'. * * Assumes the transaction is valid. * * If 'start' is non-NULL, print it before the transaction (with no added * whitespace). * If 'eol' is true, then print a newline after the transaction. */ extern void kstate_print_transaction(FILE *stream, const char *start, kstate_transaction_p transaction, bool eol) { if (start) fprintf(stream, "%s", start); if (kstate_transaction_is_active(transaction)) { print_transaction(stream, transaction->id, transaction->name + KSTATE_NAME_PREFIX_LEN, transaction->permissions); } else { fprintf(stream, "Transaction <not active>"); } if (eol) fprintf(stream, "\n"); } /* * Create a new "empty" state. * * The normal usage is to create an empty state and then immediately * populate it:: * * kstate_state_p state = kstate_new_state(); * int ret = kstate_subscribe_state("State.Name", KSTATE_READ|KSTATE_WRITE, state); * * and then eventually to destroy it:: * * int ret = kstate_unsubscribe_state(state); * if (ret) { * // deal with the error * } * kstate_free_state(&state); * * After which it can safely be reused, if you wish. * * Returns the new state, or NULL if there was insufficient memory. */ extern kstate_state_p kstate_new_state(void) { static uint32_t next_state_id = 1; // because 0 is reserved kstate_state_p new = malloc(sizeof(*new)); memset(new, 0, sizeof(*new)); new->id = next_state_id ++; // Oh, OK, we should probably check. if (next_state_id == 0) next_state_id = 1; return new; } /* * Free a state created with 'kstate_new_state'. * * If a NULL pointer is given, then it is ignored, otherwise the state is * freed and the pointer is set to NULL. */ extern void kstate_free_state(kstate_state_p *state) { if (state && *state) { if (kstate_state_is_subscribed(*state)) { kstate_unsubscribe_state(*state); } struct kstate_state *s = (struct kstate_state *)(*state); free(s); *state = NULL; } } /* * Subscribe to a state. * * - ``name`` is the name of the state to subscribe to. * - ``permissions`` is constructed by OR'ing the permission flags * KSTATE_READ and/or KSTATE_WRITE. At least one of those must be given. * KSTATE_WRITE by itself is regarded as equivalent to KSTATE_WRITE|KSTATE_READ. * - ``state`` is the actual state identifier, as amended by this function. * * A state name may contain A-Z, a-z, 0-9 and the dot (.) character. It may not * start or end with a dot, and may not contain adjacent dots. It must contain * at least one character. Note that the name will be copied into 'state'. * * If this is the first subscription to the named state, then the shared * data for the state will be created. * * Note that the first subscription to a state cannot be read-only, as there is * nothing to read -i.e., the first subscription to a state must be for * KSTATE_WRITE|KSTATE_READ. * * Returns 0 if the subscription succeeds, or a negative value if it fails. * The negative value will be ``-errno``, giving an indication of why the * function failed. */ extern int kstate_subscribe_state(kstate_state_p state, const char *name, kstate_permissions_t permissions) { if (state == NULL) { fprintf(stderr, "!!! kstate_subscribe_state: state argument may not be NULL\n"); return -EINVAL; } if (kstate_state_is_subscribed(state)) { fprintf(stderr, "!!! kstate_subscribe_state: state is still subscribeed\n"); kstate_print_state(stderr, "!!! ", state, true); return -EINVAL; } printf("Subscribing to "); print_state(stdout, state->id, name, permissions); printf("\n"); if (state_permissions_are_bad(permissions)) { return -EINVAL; } int rv = new_state_name("kstate_subscribe_state", name, &state->name); if (rv) { return rv; } // If we had a legitimate permissions set that doesn't include READ, // add READ back in if (!(permissions & KSTATE_READ)) { permissions |= KSTATE_READ; } state->permissions = permissions; int shm_flag = 0; mode_t shm_mode = 0; bool creating = false; if (permissions & KSTATE_WRITE) { shm_flag = O_RDWR | O_CREAT; // XXX Allow everyone any access, at least for the moment // XXX It is possible that we will want another version of this function // XXX which allows specifying the mode (the "normal" version of the // XXX function should always be the one that defaults to a "sensible" // XXX mode, whatever we decide that to be). shm_mode = S_IRWXU | S_IRWXG | S_IRWXO; creating = true; } else { // We always allow read shm_flag = O_RDONLY; } int shm_fd = shm_open(state->name, shm_flag, shm_mode); if (shm_fd < 0) { int rv = errno; fprintf(stderr, "!!! kstate_subscribe_state:" " Error in shm_open(\"%s\", 0x%x, 0x%x): %d %s\n", state->name, shm_flag, shm_mode, rv, strerror(rv)); free(state->name); state->name = NULL; state->permissions = 0; return -rv; } long page_size = sysconf(_SC_PAGESIZE); // If we're creating the shared memory object, we need to set a size, // or it will be zero sized. // For the moment, we always set the same size, one page. if (creating) { // Caveat emptor - from the man page: // // If the file previously was larger than this size, the extra data is // lost. If the file previously was shorter, it is extended, and the // extended part reads as null bytes ('\0'). // int rv = ftruncate(shm_fd, page_size); if (rv) { int rv = errno; kstate_print_state(stderr, "!!! kstate_subscribe_state:" " Error in setting shared memory size for ", state, false); fprintf(stderr, " to 0x%x: %d %s\n", (uint32_t)page_size, rv, strerror(rv)); free(state->name); state->name = NULL; state->permissions = 0; // NB: we're not doing shm_unlink... return -rv; } } // Some defaults just for now... int flags = MAP_SHARED; // Again, by default map the whole available area, starting at the // start of the "file". Note that we only map for READ, regardless // of the permissions - the caller must use a transaction if they // want to write to the memory. state->map_length = page_size; state->map_addr = mmap(NULL, state->map_length, PROT_READ, flags, shm_fd, 0); if (state->map_addr == MAP_FAILED) { int rv = errno; kstate_print_state(stderr, "!!! kstate_subscribe_state:" " Error in mapping shared memory for ", state, false); fprintf(stderr, ": %d %s\n", rv, strerror(rv)); free(state->name); state->name = NULL; state->permissions = 0; state->map_addr = 0; state->map_length = 0; // NB: we're not doing shm_unlink... return -rv; } // At which point, we don't need the file descriptor anymore close(shm_fd); return 0; } /* * Unsubscribe from a state. * * - ``state`` is the state from which to unsubscribe. * * After this, the content of the state datastructure will have been * unset/freed. Unsubscribing from this same state value again will have no * effect. * * Note that transactions using the state keep their own copy of the state * information, and are not affected by this function - i.e., the state can * still be accessed via any transactions that are still open on it. * * Returns 0 if the unsubscription succeeds, or a negative value if it fails. * The negative value will be ``-errno``, giving an indication of why the * function failed. */ extern void kstate_unsubscribe_state(kstate_state_p state) { if (state == NULL) // What did they expect us to do? return; kstate_print_state(stdout, "Unsubscribing from ", state, true); if (state->map_addr != NULL && state->map_addr != MAP_FAILED) { int rv = munmap(state->map_addr, state->map_length); if (rv) { rv = errno; kstate_print_state(stderr, "!!! kstate_unsubscribe_state:" " Error in freeing shared memory for ", state, false); fprintf(stderr, ": %d %s\n", rv, strerror(rv)); // But there's not much we can do about it... } state->map_addr = 0; state->map_length = 0; } if (state->name) { int rv = shm_unlink(state->name); if (rv) { rv = errno; if (rv == ENOENT) { fprintf(stderr, "... kstate_unsubscribe_state:" " Unable to unlink %s, it has already gone.\n", state->name); } else { fprintf(stderr, "!!! kstate_unsubscribe_state:" " Error unlinking %s: %d %s\n", state->name, rv, strerror(rv)); } } free(state->name); state->name = NULL; } state->permissions = 0; } /* * Create a new "empty" transaction. * * The normal usage is to create an empty transaction and then immediately * populate it:: * * struct kstate_transaction *transaction = kstate_new_transaction(); * int ret = kstate_start_transaction(&transaction, state, KSTATE_WRITE); * * and then eventually to destroy it:: * * int ret = kstate_unsubscribe_state(transaction); * if (ret) { * // deal with the error * } * kstate_free_transaction(&transaction); * * Returns the new transaction, or NULL if there was insufficient memory. */ extern struct kstate_transaction *kstate_new_transaction(void) { static uint32_t next_transaction_id = 1; // because 0 is reserved struct kstate_transaction *new = malloc(sizeof(struct kstate_transaction)); memset(new, 0, sizeof(*new)); new->id = next_transaction_id ++; // Oh, OK, we should probably check. if (next_transaction_id == 0) next_transaction_id = 1; return new; } /* * Destroy a transaction created with 'kstate_new_transaction'. * * If the transaction is still in progress, it will be aborted. * * If a NULL pointer is given, then it is ignored, otherwise the transaction is * freed and the pointer is set to NULL. */ extern void kstate_free_transaction(kstate_transaction_p *transaction) { if (transaction && *transaction) { if (kstate_transaction_is_active(*transaction)) { kstate_abort_transaction(*transaction); } struct kstate_transaction *t = (struct kstate_transaction *)(*transaction); free(t); *transaction = NULL; } } static int clear_transaction(char *caller, kstate_transaction_p transaction) { if (transaction->state_map_copy) { free(transaction->state_map_copy); transaction->state_map_copy = NULL; } if (transaction->state_map_addr != NULL && transaction->state_map_addr != MAP_FAILED) { int rv = munmap(transaction->state_map_addr, transaction->map_length); if (rv) { rv = errno; fprintf(stderr, "!!! %s: ", caller); kstate_print_transaction(stderr, " Error in freeing shared memory for ", transaction, false); fprintf(stderr, ": %d %s\n", rv, strerror(rv)); return -rv; } transaction->state_map_addr = 0; } if (transaction->map_addr != NULL && transaction->map_addr != MAP_FAILED) { int rv = munmap(transaction->map_addr, transaction->map_length); if (rv) { rv = errno; fprintf(stderr, "!!! %s: ", caller); kstate_print_transaction(stderr, " Error in freeing local memory for ", transaction, false); fprintf(stderr, ": %d %s\n", rv, strerror(rv)); return -rv; } transaction->map_addr = 0; } transaction->map_length = 0; if (transaction->name) { free(transaction->name); transaction->name = NULL; } transaction->permissions = 0; return 0; } /* * Start a new transaction on a state. * * If 'transaction' is still active, this will fail. * * * 'transaction' is the transaction to start. * * 'state' is the state on which to start the transaction. * - 'permissions' is constructed by OR'ing the permission flags * KSTATE_READ and/or KSTATE_WRITE. At least one of those must be given. * KSTATE_WRITE by itself is regarded as equivalent to KSTATE_WRITE|KSTATE_READ. * * Note that copy of the state will be taken, so that the transaction * can continue to access the state's shared memory even if the particular * 'state' is unsubscribed. However, this is not enough information to * reconstruct/return the entirety of the original 'state', as we do not * (for instance) remember the shared memory object used internally as an * intermediary when creating a state. * * Returns 0 if starting the transaction succeeds, or a negative value if it * fails. The negative value will be ``-errno``, giving an indication of why * the function failed. */ extern int kstate_start_transaction(kstate_transaction_p transaction, kstate_state_p state, uint32_t permissions) { if (transaction == NULL) { fprintf(stderr, "!!! kstate_start_transaction: transaction argument may" " not be NULL\n"); return -EINVAL; } if (state == NULL) { fprintf(stderr, "!!! kstate_start_transaction: Cannot start a transaction" " on a NULL state\n"); return -EINVAL; } if (kstate_transaction_is_active(transaction)) { fprintf(stderr, "!!! kstate_start_transaction: transaction is still active\n"); kstate_print_transaction(stderr, "!!! ", transaction, true); return -EINVAL; } // Remember, unsubscribing from a state unsets its name if (!kstate_state_is_subscribed(state)) { fprintf(stderr, "!!! kstate_start_transaction: Cannot start a transaction" " on an unsubscribed state\n"); return -EINVAL; } kstate_print_state(stdout, "Starting Transaction on ", state, true); if (transaction_permissions_are_bad(permissions)) { return -EINVAL; } // If we had a legitimate permissions set that doesn't include READ, // add READ back in if (!(permissions & KSTATE_READ)) { permissions |= KSTATE_READ; } if ((permissions & KSTATE_WRITE) && !(state->permissions & KSTATE_WRITE)) { fprintf(stderr, "!!! kstate_start_transaction: Cannot start a write" " transaction on a read-only state\n"); kstate_print_state(stderr, "!!! ", state, true); return -EINVAL; } transaction->permissions = permissions; size_t name_len = strlen(state->name); transaction->name = malloc(name_len + 1); if (transaction->name == NULL) return -ENOMEM; strcpy(transaction->name, state->name); transaction->map_length = state->map_length; // First off, we need to be able to see what the state has // If we're a write transaction (i.e., can commit) then we need to be able // to write back to it if we ever do commit... int map_prot = PROT_READ; int shm_flag = 0; mode_t shm_mode = 0; if (permissions & KSTATE_WRITE) { map_prot |= PROT_WRITE; shm_flag = O_RDWR; } else { shm_flag = O_RDONLY; } int shm_fd = shm_open(transaction->name, shm_flag, shm_mode); if (shm_fd < 0) { int rv = errno; fprintf(stderr, "!!! kstate_start_transaction:" " Error in shm_open(\"%s\", 0x%x, 0x%x): %d %s\n", transaction->name, shm_flag, shm_mode, rv, strerror(rv)); free(transaction->name); transaction->name = NULL; transaction->permissions = 0; return -rv; } transaction->state_map_addr = mmap(NULL, transaction->map_length, map_prot, MAP_SHARED, shm_fd, 0); if (transaction->state_map_addr == MAP_FAILED) { int rv = errno; kstate_print_state(stderr, "!!! kstate_start_transaction:" " Error in mapping shared memory for Transaction on ", state, false); fprintf(stderr, ": %d %s\n", rv, strerror(rv)); clear_transaction("kstate_start_transaction", transaction); close(shm_fd); return -rv; } close(shm_fd); // If we're a writable transaction, we will need to know if that state // data has changed when we try to commit. The simplest way to do that // is to keep a copy of the current state of the data. // XXX There's a hole whilst we're copying it where things can go wrong // XXX here - we need some locking... if (transaction->permissions & KSTATE_WRITE) { transaction->state_map_copy = malloc(transaction->map_length); if (transaction->state_map_copy == NULL) { clear_transaction("kstate_start_transaction", transaction); return -ENOMEM; } memcpy(transaction->state_map_copy, transaction->state_map_addr, transaction->map_length); } // Then we need our own version of the data, which is independent of that // for the state - both in case the state changes during our transaction, // and also (if we're allowed to) because we might write to our own copy // However, since we're going to make a copy of the original data, we // do need to be able to write to it - at least for the moment transaction->map_addr = mmap(NULL, transaction->map_length, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); if (transaction->map_addr == MAP_FAILED) { int rv = errno; kstate_print_state(stderr, "!!! kstate_start_transaction:" " Error in mapping local memory for Transaction on ", state, false); fprintf(stderr, ": %d %s\n", rv, strerror(rv)); clear_transaction("kstate_start_transaction", transaction); return -rv; } // And obviously we need to copy one to the other... memcpy(transaction->map_addr, transaction->state_map_addr, transaction->map_length); if (!(permissions & KSTATE_WRITE)) { // Revoke permission to write to our internal data int rv = mprotect(transaction->map_addr, transaction->map_length, PROT_READ); if (rv) { int rv = errno; kstate_print_state(stderr, "!!! kstate_start_transaction:" " Error disallowing write on local memory" " for Transaction on ", state, false); fprintf(stderr, ": %d %s\n", rv, strerror(rv)); clear_transaction("kstate_start_transaction", transaction); return -rv; } } kstate_print_transaction(stdout, "Started ", transaction, true); return 0; } /* * Abort a transaction. * * - ``transaction`` is the transaction to abort. * * After this, the content of the transaction datastructure will have been * unset/freed. * * It is not allowed to abort a transaction that has not been started. * In other words, you cannot abort a transaction before it has been started, * or after it has been aborted or committed. * * Returns 0 if the abort succeeds, or a negative value if it fails. * The negative value will be ``-errno``, giving an indication of why the * function failed. */ extern int kstate_abort_transaction(kstate_transaction_p transaction) { if (transaction == NULL) { // What did they expect us to do? fprintf(stderr, "!!! kstate_abort_transaction: Cannot abort NULL transaction\n"); return -EINVAL; } if (!kstate_transaction_is_active(transaction)) { fprintf(stderr, "!!! kstate_abort_transaction: transaction is not active\n"); kstate_print_transaction(stderr, "!!! ", transaction, true); return -EINVAL; } kstate_print_transaction(stdout, "Aborting ", transaction, true); int rv = clear_transaction("kstate_abort_transaction", transaction); return rv; } /* * Commit a transaction. * * - ``transaction`` is the transaction to commit. * * After this, the content of the transaction datastructure will have been * unset/freed. * * It is not allowed to commit a transaction that has not been started. * In other words, you cannot commit a transaction before it has been started, * or after it has been aborted or committed. * * It is also not allowed to commit a read-only transaction (such must be * aborted). * * Returns 0 if the commit succeeds, or a negative value if it fails. * The negative value will be ``-errno``, giving an indication of why the * function failed. */ extern int kstate_commit_transaction(struct kstate_transaction *transaction) { if (transaction == NULL) { // What did they expect us to do? fprintf(stderr, "!!! kstate_commit_transaction: Cannot commit NULL transaction\n"); return -EINVAL; } if (!kstate_transaction_is_active(transaction)) { fprintf(stderr, "!!! kstate_commit_transaction: transaction is not active\n"); kstate_print_transaction(stderr, "!!! ", transaction, true); return -EINVAL; } if (!(transaction->permissions & KSTATE_WRITE)) { fprintf(stderr, "!!! kstate_commit_transaction: Cannot commit a read-only transaction\n"); kstate_print_transaction(stderr, "!!! ", transaction, true); return -EPERM; } kstate_print_transaction(stdout, "Committing ", transaction, true); int retcode = 0; // We can commit if the state has not changed from our idea of its original // value - i.e., it is as if no-one else has altered it. // // (Presumably, someone altering it and putting it back again while we // weren't looking is not our problem.) // // If someone else has changed the state, then we're meant to fail. // // Maybe if we were nice we'd also check to see if we're trying to change // it to the same thing as someone else has already set it to (!) - we // could conveivably be trying to update <data> to the same value if (memcmp(transaction->state_map_addr, transaction->state_map_copy, transaction->map_length)) { fprintf(stderr, "!!! kstate_commit_transaction: Cannot commit as "); kstate_print_transaction(stderr, "the underlying state for ", transaction, false); fprintf(stderr, " has changed during the transaction\n"); retcode = -EPERM; } else if (memcmp(transaction->state_map_addr, transaction->map_addr, transaction->map_length)) { fprintf(stderr, "... kstate_commit_transaction: OK to commit as "); kstate_print_transaction(stderr, "the underlying state for ", transaction, false); fprintf(stderr, " did not change during the transaction\n"); memcpy(transaction->state_map_addr, transaction->map_addr, transaction->map_length); retcode = 0; } else { fprintf(stderr, "... kstate_commit_transaction: No need to commit, as "); kstate_print_transaction(stderr, "the underlying state for ", transaction, false); fprintf(stderr, " matches the result of the transaction\n"); retcode = 0; } int rv = clear_transaction("kstate_commit_transaction", transaction); if (retcode) return retcode; else return rv; } // vim: set tabstop=8 softtabstop=2 shiftwidth=2 expandtab: // // Local Variables: // tab-width: 8 // indent-tabs-mode: nil // c-basic-offset: 2 // End: <file_sep>/problems-with-check.txt Problems with check =================== (Mind, I'm very greatful for it! It's still wonderful it (a) exists, and (b) uses forking to make it possible to handle segmentation faults, etc, - this is a fundamental requirement to my mind. And the list of *good things* about check would be a LOT longer. Not least the support for testing for signals, which is really cool.) 1. LGPL, which I'd prefer otherwise. This is a very minor problem, really. 2 Also, really would prefer to be in an autotools environment, which is not what I want to set up. This is *very much* the sort of thing the author of a project should decide, and the check author has done so (and since it works on many Unices, it's probably a Good Thing). 3. Doesn't/can't mix test name, test output and test result - I'd like to see them all in one stream. (Some of this can be achieved by editing a local version of check.h, but it's not perfect without making more intrusive changes). 4. Many more macros for comparison would be useful. Of course, I could write them... 5. Needing the START_TEST/END_TEST macros/markers, rather than some sort of "discovery" of tests. (although this is ameliorated by the fact that the compiler will complain if a test is not used, in the normal manner for unused functions) Contrariwise, though, there is no need for a convention on how test functions must be named. .. vim: set filetype=rst tabstop=8 softtabstop=2 shiftwidth=2 expandtab: <file_sep>/extract_hdrs.py #!/usr/bin/env python """extract_hdrs.py -- Extract "extern" function headers from .c files to .h files. Usage: ./extract_hdrs.py [-h | -help | --help] ./extract_hdrs.py -kstate ./extract_hdrs.py [<c_file> <h_file> ...] If run with the '-kstate' switch, then it looks for the file 'kstate.c', and writes header information to 'kstate.h'. This is for convenience in the management of libkstate. If run with no filenames, it looks for all the C files in the current directory, and for each <name>.c file expects to extract headers to a corresponding <name>_fns.h file. Otherwise, it expects pairs of source .c file and target .h file. In all cases, the target .h file must (a) exist and (b) contain a pair of start/end delimiters - as, for instance:: Any text before the first delimiter is not altered // -------- TEXT AFTER THIS AUTOGENERATED - DO NOT EDIT -------- Any text in here is replaced with the (new) header text // -------- TEXT BEFORE THIS AUTOGENERATED - DO NOT EDIT -------- Any text after the second delimiter is not altered A very simple regular expression is used to detect headers - basically, the header is from the opening ``/*`` to the ``)`` before the ``{`` in something like:: /* * Header comment text */ extern datatype other words function_name( any arguments ) { (and in general whitespace should be flexible in the actual function signature itself). Beware that the script does not check to see if the output header file will be given different content (apart from the timestamp) and will thus proceed regardless. """ # ***** BEGIN LICENSE BLOCK ***** # Version: MPL 1.1 # # The contents of this file are subject to the Mozilla Public License Version # 1.1 (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.mozilla.org/MPL/ # # Software distributed under the License is distributed on an "AS IS" basis, # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License # for the specific language governing rights and limitations under the # License. # # The Original Code is the Kynesim state management library. # # The Initial Developer of the Original Code is Kynesim, Cambridge UK. # Portions created by the Initial Developer are Copyright (C) 2012 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Kynesim, Cambridge UK # <NAME> <<EMAIL>> # # ***** END LICENSE BLOCK ***** import os import re import sys from datetime import datetime from difflib import ndiff pattern = r"""\ (?P<header> # start of header group \s* / \* .* \n # start of header comment (\s* \* .* \n)* # 0 or more comment lines \s* \* / \n # end of header comment \s* extern \s+ (?P<type> # crudely allow for type info #(\w+ \s+) | # e.g., "fred " (\w+ \s+ \** \s*) | # e.g., "fred *" (\w+ \s+ \w+ \s+ \** \s*) # e.g., "struct fred " or "struct fred *" ) (?P<name> \w+ # name of function ) \( ([^)]|\n)* \) # crudely match arguments ) # end of header group \s* \n \s* { """ start_delimiter = "// -------- TEXT AFTER THIS AUTOGENERATED - DO NOT EDIT --------\n" start_timestamp = "// Autogenerated by extract_hdrs.py on %s\n" end_delimiter = "// -------- TEXT BEFORE THIS AUTOGENERATED - DO NOT EDIT --------\n" DEBUG = False class GiveUp(Exception): pass def extract_headers(c_file): """Extract the function headers from this C file. Returns text suitable for inclusion into the header file. """ with open(c_file,'r') as file: data = file.read() headers = re.finditer(pattern, data, re.VERBOSE) new = [] # Turn our function header into prototypes for hdr in headers: print ' Found ',hdr.group('name') new.append(hdr.group('header')+';\n') return ''.join(new) def split_header_file(h_file): """Split the header file into its three parts and return them. We have: * the start of the file (written by the user) * the middle of the file (inserted by a previous use of this script) * the end of the file (written by the user) """ with open(h_file, 'r') as original: data = original.read() delimiter1_posn = data.find(start_delimiter) delimiter2_posn = data.find(end_delimiter) if delimiter1_posn == -1: raise GiveUp("Couldn't find start 'AUTOGENERATED' line in file %s"%h_file) if delimiter2_posn == -1: raise GiveUp("Couldn't find end 'AUTOGENERATED' line in file %s"%h_file) start = data[:delimiter1_posn+len(start_delimiter)] end = data[delimiter2_posn:] middle = data[delimiter1_posn+len(start_delimiter):delimiter2_posn] # Drop the previous timestamp line from the beginning lines = middle.splitlines() lines = lines[1:] middle = '\n'.join(lines) + '\n' return start, middle, end def process_file(c_file, h_file): """Extract header comments/prototypes from 'c_file' into 'h_file'. """ temp_file = h_file + '.new' save_file = h_file + '.bak' print 'Extracting headers from %s to %s'%(c_file, h_file) # Determine what we want the headers to look like new_middle = extract_headers(c_file) # Find out what they were already try: start, middle, end = split_header_file(h_file) except GiveUp as e: print e return # Do we need to change anything? if DEBUG and middle != new_middle: print print 'Function definitions for %s have changed'%c_file print '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>' diff = ndiff(middle.splitlines(), new_middle.splitlines()) print '\n'.join(diff) print '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>' if middle == new_middle: print 'Nothing changed' else: print 'Writing new %s'%h_file now = datetime.now() timestamp_str = now.strftime('%Y-%m-%d (%a %d %b %Y) at %H:%M') timestamp_line = start_timestamp%timestamp_str with open(temp_file, 'w') as output: output.write(start) output.write(timestamp_line) output.write(new_middle) output.write(end) os.rename(h_file, save_file) os.rename(temp_file, h_file) def do_stuff(args): c_to_h = {} if not args: filenames = os.listdir('.') for name in filenames: base, ext = os.path.splitext(name) if ext == '.c': c_to_h[name] = '%s_fns.h'%base else: while len(args) > 0: word = args[0] args = args[1:] if word in ('-help', '-h', '--help'): print __doc__ return elif word == '-kstate': c_to_h = {'kstate.c' : 'kstate.h'} if len(args[1:]) != 0: print 'Unexpected arguments %s after -kstate'%args[1:] return else: c_file = word try: h_file = args[0] except: print 'C file (%s) not matched to a .h file'%c_file return c_to_h[c_file] = h_file args = args[1:] if len(args) %2 != 0: print 'Unbalanced arguments: not pairs of c_file h_file' # Basic checks before we do *anything* for c_file, h_file in c_to_h.items(): if not os.path.exists(c_file): print 'C source file %s does not exist'%c_file return if not os.path.exists(h_file): print 'C header file %s does not exist'%h_file return if os.path.splitext(c_file)[-1] != '.c': print 'C source file %s does not have extension .c'%c_file return if os.path.splitext(h_file)[-1] != '.h': print 'C header file %s does not have extension .c'%h_file return for c_file, h_file in c_to_h.items(): process_file(c_file, h_file) if __name__ == '__main__': do_stuff(sys.argv[1:]) # vim: set tabstop=8 softtabstop=4 shiftwidth=4 expandtab: <file_sep>/kstate.h /* * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the KBUS State library. * * The Initial Developer of the Original Code is Kynesim, Cambridge UK. * Portions created by the Initial Developer are Copyright (C) 2013 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Kynesim, Cambridge UK * <NAME> <<EMAIL>> * * ***** END LICENSE BLOCK ***** */ #ifndef _KSTATE_H_INCLUDED_ #define _KSTATE_H_INCLUDED_ #ifdef __cplusplus extern "C" { #endif #include <stdint.h> #include <stdbool.h> #include <stdio.h> #include <limits.h> // for NAME_LEN enum kstate_permissions { KSTATE_READ=1, // The state may be read KSTATE_WRITE=2, // The state may be written }; typedef enum kstate_permissions kstate_permissions_t; // The maximum length of a state name. We expect this to be 255 - len("/kstate."), // since we put that on the start of the shared memory object name corresponding // to our state. #define KSTATE_NAME_PREFIX_LEN 8 #define KSTATE_MAX_NAME_LEN (NAME_MAX - KSTATE_NAME_PREFIX_LEN) typedef struct kstate_state *kstate_state_p; typedef struct kstate_transaction *kstate_transaction_p; // -------- TEXT AFTER THIS AUTOGENERATED - DO NOT EDIT -------- // Autogenerated by extract_hdrs.py on 2013-01-29 (Tue 29 Jan 2013) at 16:15 /* * Return a unique valid state name starting with prefix. * * The name is composed of: * * * the normal kstate name prefix * * the prefix string * * the number of microseconds since the epoch * * our process id * * a statically increasing integer * * separated by dots. Thus it is only as "unique" as afforded by the * accuracy of gettimeofday - i.e., it relies on the apparent time * thus reported having changed. * * For most purposes, this should be sufficient. * * The caller is responsible for freeing the returned string. * * Returns NULL if it is not possible to make such a name with the given * prefix. */ extern char *kstate_get_unique_name(const char *prefix); /* * Return true if the given state is subscribed. */ extern bool kstate_state_is_subscribed(kstate_state_p state); /* * Return true if the given transaction is active */ extern bool kstate_transaction_is_active(kstate_transaction_p transaction); /* * Return a state's name, or NULL if it is not subscribed. */ extern const char *kstate_get_state_name(kstate_state_p state); /* * Return a transaction's name, or NULL if it is not active. */ extern const char *kstate_get_transaction_name(kstate_transaction_p transaction); /* * Return a state's permissions, or 0 if it is not subscribed. */ extern uint32_t kstate_get_state_permissions(kstate_state_p state); /* * Return a transaction's permissions, or 0 if it is not active. */ extern uint32_t kstate_get_transaction_permissions(kstate_transaction_p transaction); /* * Return a state's id, or 0 if it is not subscribed. * * We do not say anything about the value of the id, except that 0 means the * state is unsubscribed, the same state always has the same id, and two * separate states have distinct ids. */ extern uint32_t kstate_get_state_id(kstate_state_p state); /* * Return a transaction's id, or 0 if it is not active. * * We do not say anything about the value of the id, except that 0 means the * transaction is not active, the same transaction always has the same id, and * two separate transactions have distinct ids. */ extern uint32_t kstate_get_transaction_id(kstate_transaction_p transaction); /* * Return a state's shared memory pointer, or NULL if it is not subscribed. * * Note that this is always a pointer to read-only shared memory, as * one must use a transaction to write. * * Beware that this pointer stops being valid as soon as the state is * unsubscribed (or freed, which implicitly unsubscribes it). */ extern void *kstate_get_state_ptr(kstate_state_p state); /* * Return a transaction's shared memory pointer, or NULL if it is not active. * * Whether this can be used to write to the shared memory depends upon the * protection requested for the transaction. * * Beware that this pointer stops being valid as soon as the transaction is * committed or aborted (or freed, which implicitly aborts it). */ extern void *kstate_get_transaction_ptr(kstate_transaction_p transaction); /* * Print a representation of 'state' on output 'stream'. * * Assumes the state is valid. * * If 'start' is non-NULL, print it before the state (with no added whitespace). * If 'eol' is true, then print a newline after the state. */ extern void kstate_print_state(FILE *stream, const char *start, kstate_state_p state, bool eol); /* * Print a representation of 'transaction' on output 'stream'. * * Assumes the transaction is valid. * * If 'start' is non-NULL, print it before the transaction (with no added * whitespace). * If 'eol' is true, then print a newline after the transaction. */ extern void kstate_print_transaction(FILE *stream, const char *start, kstate_transaction_p transaction, bool eol); /* * Create a new "empty" state. * * The normal usage is to create an empty state and then immediately * populate it:: * * kstate_state_p state = kstate_new_state(); * int ret = kstate_subscribe_state("State.Name", KSTATE_READ|KSTATE_WRITE, state); * * and then eventually to destroy it:: * * int ret = kstate_unsubscribe_state(state); * if (ret) { * // deal with the error * } * kstate_free_state(&state); * * After which it can safely be reused, if you wish. * * Returns the new state, or NULL if there was insufficient memory. */ extern kstate_state_p kstate_new_state(void); /* * Free a state created with 'kstate_new_state'. * * If a NULL pointer is given, then it is ignored, otherwise the state is * freed and the pointer is set to NULL. */ extern void kstate_free_state(kstate_state_p *state); /* * Subscribe to a state. * * - ``name`` is the name of the state to subscribe to. * - ``permissions`` is constructed by OR'ing the permission flags * KSTATE_READ and/or KSTATE_WRITE. At least one of those must be given. * KSTATE_WRITE by itself is regarded as equivalent to KSTATE_WRITE|KSTATE_READ. * - ``state`` is the actual state identifier, as amended by this function. * * A state name may contain A-Z, a-z, 0-9 and the dot (.) character. It may not * start or end with a dot, and may not contain adjacent dots. It must contain * at least one character. Note that the name will be copied into 'state'. * * If this is the first subscription to the named state, then the shared * data for the state will be created. * * Note that the first subscription to a state cannot be read-only, as there is * nothing to read -i.e., the first subscription to a state must be for * KSTATE_WRITE|KSTATE_READ. * * Returns 0 if the subscription succeeds, or a negative value if it fails. * The negative value will be ``-errno``, giving an indication of why the * function failed. */ extern int kstate_subscribe_state(kstate_state_p state, const char *name, kstate_permissions_t permissions); /* * Unsubscribe from a state. * * - ``state`` is the state from which to unsubscribe. * * After this, the content of the state datastructure will have been * unset/freed. Unsubscribing from this same state value again will have no * effect. * * Note that transactions using the state keep their own copy of the state * information, and are not affected by this function - i.e., the state can * still be accessed via any transactions that are still open on it. * * Returns 0 if the unsubscription succeeds, or a negative value if it fails. * The negative value will be ``-errno``, giving an indication of why the * function failed. */ extern void kstate_unsubscribe_state(kstate_state_p state); /* * Create a new "empty" transaction. * * The normal usage is to create an empty transaction and then immediately * populate it:: * * struct kstate_transaction *transaction = kstate_new_transaction(); * int ret = kstate_start_transaction(&transaction, state, KSTATE_WRITE); * * and then eventually to destroy it:: * * int ret = kstate_unsubscribe_state(transaction); * if (ret) { * // deal with the error * } * kstate_free_transaction(&transaction); * * Returns the new transaction, or NULL if there was insufficient memory. */ extern struct kstate_transaction *kstate_new_transaction(void); /* * Destroy a transaction created with 'kstate_new_transaction'. * * If the transaction is still in progress, it will be aborted. * * If a NULL pointer is given, then it is ignored, otherwise the transaction is * freed and the pointer is set to NULL. */ extern void kstate_free_transaction(kstate_transaction_p *transaction); /* * Start a new transaction on a state. * * If 'transaction' is still active, this will fail. * * * 'transaction' is the transaction to start. * * 'state' is the state on which to start the transaction. * - 'permissions' is constructed by OR'ing the permission flags * KSTATE_READ and/or KSTATE_WRITE. At least one of those must be given. * KSTATE_WRITE by itself is regarded as equivalent to KSTATE_WRITE|KSTATE_READ. * * Note that copy of the state will be taken, so that the transaction * can continue to access the state's shared memory even if the particular * 'state' is unsubscribed. However, this is not enough information to * reconstruct/return the entirety of the original 'state', as we do not * (for instance) remember the shared memory object used internally as an * intermediary when creating a state. * * Returns 0 if starting the transaction succeeds, or a negative value if it * fails. The negative value will be ``-errno``, giving an indication of why * the function failed. */ extern int kstate_start_transaction(kstate_transaction_p transaction, kstate_state_p state, uint32_t permissions); /* * Abort a transaction. * * - ``transaction`` is the transaction to abort. * * After this, the content of the transaction datastructure will have been * unset/freed. * * It is not allowed to abort a transaction that has not been started. * In other words, you cannot abort a transaction before it has been started, * or after it has been aborted or committed. * * Returns 0 if the abort succeeds, or a negative value if it fails. * The negative value will be ``-errno``, giving an indication of why the * function failed. */ extern int kstate_abort_transaction(kstate_transaction_p transaction); /* * Commit a transaction. * * - ``transaction`` is the transaction to commit. * * After this, the content of the transaction datastructure will have been * unset/freed. * * It is not allowed to commit a transaction that has not been started. * In other words, you cannot commit a transaction before it has been started, * or after it has been aborted or committed. * * It is also not allowed to commit a read-only transaction (such must be * aborted). * * Returns 0 if the commit succeeds, or a negative value if it fails. * The negative value will be ``-errno``, giving an indication of why the * function failed. */ extern int kstate_commit_transaction(struct kstate_transaction *transaction); // -------- TEXT BEFORE THIS AUTOGENERATED - DO NOT EDIT -------- #ifdef __cplusplus } #endif #endif /* _KSTATE_H_INCLUDED_ */ // vim: set tabstop=8 softtabstop=2 shiftwidth=2 expandtab: // // Local Variables: // tab-width: 8 // indent-tabs-mode: nil // c-basic-offset: 2 // End: <file_sep>/docs.txt ====== Kstate ====== .. note:: This is a start at documenting our intentions. Expect things to change... .. contents:: What we want to be able to do ============================= We have systems where process A is receiving data many times a second from an external source, and process B wants to be able to interrogate that data, either some appropriate frequency as it changes, or else whenever it sees fit. We thus have some assumptions: * Our initial system has one writer of state, and possibly many consumers. * The writer is likely to write amendments at high frequency. * Some of the consumers want to read the state at will - i.e., at essentially random intervals. * Other consumers may want to read the state whenever it changes, or when it changes but not more often than N times per second. * Different consumers are likely to have very different ideas of how often to read the state. and some wishes: * We want transactions to wrap around reading/writing our state. * We'd like a system that fails on commit rather than on starting a transaction - i.e., be optimistic about writing state. * We want transactions to be independent, irrespective of whether they're nested or not - this has implications on when a write is visible. * We want to be able to choose to have persistent state, backed by a user chosen file. * Optionally, we'd like to be able to send a KBUS message when commit succeeds (this may get added late). and some limitations we want to set: * The system can manage more than one state. * The size of state should be choosable by the user, but with a maximum size of one page. Thinking around an API ====================== A state, S, is identified by a string. There will be some maximum length to that string, to be determined. A process starts using a state by getting a handle to it:: <state> = kstate_subscribe(state_name, permissions) where ``permissions`` is some combination of ``read`` and ``write`` flags. Obviously, if the user subscribes with just ``read``, then they will not be able to write to the state. Whether we allow just ``write``, or only allow ``read+write`` is to be decided. This returns a handle on the state, ``<state>``. If the state does not yet exist, then this will create it. Data for the state will be memory mapped. The size of the mapping will default to one page, but there will (eventually) be a call to change its size:: err = kstate_set_size(<state>, size_in_bytes) If no-one has yet written to the state, then this can set the state size to anything from 1 to the page size. After the state has been written to, this can only increase the state size. By default, the state will not be persistent - that is, it will evaporate when no active processes are subscribed to it. Alternatively, it can be backed by a (persistent) file:: err = kstate_set_persistent(<state>, filename) This will fail if the state is already persistent with a different filename. It is not possible to make a persistent state transient again. A call *may* be provided to delete a state:: err = kstate_delete(<state>) This would fail if any (other) processes are still subscribed to the state. If this call succeeds, then any subsequent attempt to use the state would fail. This call would be allowed for both persistent and transient states. Once a state has been acquired it will probably not be readable until someone has written to it. In other words, it may not be sensible to assume that the initial state makes sense. Alternatively, it may be that a read of an uninitialised state causes it to be set to all zeroes. Reading the current data for a state can be done by acquiring a pointer to it:: ptr = kstate_get_ptr(<state>) This pointer is into shared memory. .. note:: How long is it valid? Do we need to explicitly start a transaction in order to be able to read our state? Manipulating a state requires a transaction to be started:: <transaction> = kstate_start_transaction(<state>) .. note:: Can one take out a transaction on a read-only state? Yes, because it gives a "frozen" view of the state. However, either ``commit`` and ``abort`` are identical for such a transaction, or else we only allow ``abort`` - this is to be decided. One can then acquire a pointer to the state's data:: ptr = kstate_get_ptr(<transaction>) which returns a pointer to a version of the state's data. This will be identical to the state data at the time of starting the transaction, and will not change if someone else edits the state. It may be altered via the pointer, which may be used until the transaction is committed or aborted. After the transaction is committed or aborted, the pointer should be regarded as invalid. Aborting a transaction (and throwing away any changes) is done with:: err = kstate_abort(<transaction>) This should generally succeed. An attempt may be made to commit the transaction:: err = kstate_commit(<transaction>) If no writes were made using the transaction, then this may be treated as being identical to an abort of the transaction. The commit will fail if someone else has changed the data for the state since the start of the transaction. If the commit fails, then the caller should "back off" and retry the whole transaction again. .. note:: Doing it like this enables us to ensure that a system can eventually do "what it wants" without blocking, by intelligent "backing off". Future versions of the library may provide a mechanism to allow retrying transactions - probably of the form:: err = kstate_transaction_using_fn(<state>, fn, retry) where ``fn`` looks like:: int fn(<transaction>, ptr) { .. do things with ptr .. return success/failure code } This would do:: start transaction call fn within that transaction try to commit if it fails, and 'retry' is true, then back off, and then continue with a new 'start transaction' We don't explicitly support nested transactions, but we also don't forbid them. The visibility of state if you *do* nest transactions will be whatever it happens to be. Future versions of the library may make it simple to send a KBUS message when a commit succeeds. We will provide some means of polling for changes to a state. This may mean acquiring a file descriptor from the library and polling on that (this would be the preferred mechanism). We will provide some means of saying: "for this ``<state>``, the data we can see for it should not appear to be updated more than once every R seconds". Later versions of the library will support adding other states to a transaction. See the notes below. Notes ===== .. note:: Some of these have already been folded into the above. Commit fails if someone else has changed the state since we started our transaction. commit should probably: * allocate a page ready for the *next* transaction * mark that page as noread, nowrite, noexec - the next transaction will then catch a page fault when someone does try to read/write/exec it, and can (1) mark it appropriately and (2) copy the current (at start of transaction) state over (so a lazy copy) * commit can then check if a write has happened to the state. If someone else wrote to it, then the commit fails. If a commit fails, the caller needs to back off and try again. It's then possible to write algorithms to guarantee that the commit can succeed eventually, by backing off for random periods, or just flipping a coin, etc. NB: we definitely enforce a maximum state size of one page. Persistence: a state starts off as non-persistent. Then allow a call to make it persisent (and specify a file, so we can decide whether its on/off NAND, etc., ect.). "transactions are independent, irrespective of whether they're nested or not". In other words, avoid caring about inner/outer transactions by saying that a commit succeeds or not at the moment of commit, independent of other transactions. Provide a means of adding states to a transaction, to mean (explicitly) that the commit is of all those states. NB: This can possibly abort at the "start transaction" call, if it can see that it will actually be impossible to succeed in committing when the user does eventually try to commit. Make the state be associated with a file descriptor, and we can then poll on it for when the state changes. (Does this come for free with memory mapping?) We also want to be able to mark the state handle to say "when I look at this state, and the state is being updated too frequently, I don't want to see the latest update, but the update as if it were being done at THIS frequency". Useful references: <NAME>'s papers on concurrent programming without locks, including his thesis "Practical lock-freedom". Or, it was obvious all along? ============================= So, we have a state holder (or state owner if one wants to be less clever). A state owner can declare an interest in a named state, of a particular size. Anyone with an interest in that same (named) state will interact with the same state. The maximum size probably wins. The first state owner to express an interest probably causes the state to come into existence. There is a choice whether the state only exists while a state owner with an interest in it still has that interest (a state owner can say they are no longer interested in a named state), or whether it persists "forever". All reading or writing of the state is done via transactions. A state which has never been written to is full of zeroes. A state owner can start a read transaction (on a state they own). They get back a handle, which contains a pointer to the *current* version of the state (that "current" is a magic word). The library or other mechanism also updates a reference count for that version of the state. If this is the first read transaction on that version of the state, then the reference counter will be 1, if it is the second it will be 2, etc. Whilst the transaction is ongoing, the pointer to that version of the state will be valid. When the state owner ends the read transaction, they may no longer use the pointer - its state is undefined. When the read transaction is ended, the reference count for that version of the state is decremented. If it reaches zero, that version of the state can be garbage collected. Note that it is not allowed to *write* to a state in a read transaction - doing so will cause some sort of access violation or equivalent, as one might expect. Things to handle "safely": incrementing and decrementing the reference counter. A state owner can start a write transaction (on a state they own). They get back a handle, which contains a pointer to a *new* version of the state, and notionally containing a copy of the current version of the state (as at some point during the "start transaction" event. It also contains a reference back to the state that is being amended. Thus we can assume that the "start a write transaction" event must include the use of an internal read transaction, to give it time to copy the original data for the state without it changing under its feet. The state owner may (but need not) write to its version of the state. No other state owner can see this version of the state whilst the write transaction is open. When the write transaction is ended by an abort, the new version of the state can be dereferenced and garbage collected. When the write transaction is ended by a commit, the library or other mechanism first checks to see if the original has been changed (by someone else committing). If it has, then the commit will fail, otherwise it want to (safely) swap the pointer to the original version of the state for the pointer to the amended version of the state. Note that anyone who is still accessing (their own handle referring to) the original version of the state will not be able to notice this. Things to handle safely: swapping the "this state" pointer from old to new. Any reference counting. The gap between checking to see if the original state has changed and safely swapping the state pointer. Ideally, we want a state owner process dying to release all its states. We know from KBUS how to determine this - a state owner must be equivalent to opening a device, and this will then automatically be closed when the process dies. Given that, we know the kernel process has to be able to access the calls to manipulate the state's state. So we can consider putting that handling into the kernel anyway, which means that starting and ending a transaction becomes a pair of IOCTLs (is this fast enough?). This puts a lock around start/end transaction calls, which makes life a lot simpler, and we end up being thread safe, distributed between cores, and so on.o It may also make it easier to detect when a write is done to state data (presumably we're initially making it read-only and trapping an attempted write), and makes our handling of buffer allocation, etc., thread safe for us. .. vim: set filetype=rst tabstop=8 softtabstop=2 shiftwidth=2 expandtab:
d7751f230474f4d23e2aa9515022112fce300016
[ "reStructuredText", "Markdown", "Makefile", "Python", "C" ]
10
Makefile
kynesim/kstate
4974b8181c25e7cc201b24755daaf4f39c737980
19a2347d44d57b32bf180aaddd697b921862d6bc
refs/heads/master
<repo_name>Yue0925/ProjetTer<file_sep>/FuzzyMeusure.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Feb 27 12:44:43 2020 @author: MELLET """ from Lattice import * import os import math import matplotlib.pyplot as plt ITER = 1000 def read_LD(path): """ read a learning data file and a criteria list and data matrix. """ if not os.path.exists(path): raise Exception("Can' find file", path) firstLine = 0 criteria = list() importanceValues = list() with open(path, 'r') as file: for line in file.readlines(): if firstLine == 0: firstLine += 1 elif firstLine == 1: criteria = line.split()[:] firstLine += 1 else: importanceValues.append(list(map(lambda x: float(x), line.split()))) firstLine += 1 return criteria, importanceValues def calculate_choquet_integral(lattice): """ calculate the value of choquet integral. """ Fu = 0 permutedIV = lattice.permute_importanceValue() A = list(x[0] for x in permutedIV) for i in range(len(permutedIV)): mu = lattice.get_coeff_value(''.join(sorted(A[i:]))) if i == 0: Fu += (permutedIV[i][1]) * mu else: Fu += (permutedIV[i][1] - permutedIV[i-1][1]) * mu return Fu def calculate_model_error(Fu, y): """ return the model error. """ return Fu - y def verify_monotonicity(e, v, lattice): if e > 0: muJ = max(lattice.lower_neighbors_values(v)) if lattice.get_coeff_value(v) < muJ: lattice.set_coeff_value(v, muJ) else: muJ = min(lattice.upper_neighbors_values(v)) if lattice.get_coeff_value(v) > muJ: lattice.set_coeff_value(v, muJ) def compute_new_value(alpha, path, lattice, e): """ compute the new value for u(i), that u(i) the coefficient's value appreared in path. """ Fx = [0] permutedIV = lattice.permute_importanceValue() for x in permutedIV: Fx.append(x[1]) n = len(Fx) if e > 0: order = list(range(1, n-1)) else: order = list(range(n-2, 0, -1)) for i in order: oldU = lattice.get_coeff_value(path[i]) newU = oldU - alpha * e * (Fx[n-i] - Fx[n-i-1]) lattice.set_coeff_value(path[i], newU) verify_monotonicity(e, path[i], lattice) def compute_values(importanceValues, lattice, alpha): """ do the computation for one iteration. """ integralValue = list() for data in importanceValues: lattice.set_importanceValue(data) path = lattice.deduce_path() Fu = calculate_choquet_integral(lattice) integralValue.append(Fu) e = calculate_model_error(Fu, data[-1]) compute_new_value(alpha, path, lattice, e) return integralValue def adjust_value(lattice, beta, n, coeffs): for x in coeffs: if x == '.' or len(x) == n: continue # meanU = sum(lattice.upper_neighbors_values(x)) / len(lattice.upper_neighbors_values(x)) meanU = 1 / (n - len(x)) * sum(lattice.upper_neighbors_values(x)) # meanL = sum(lattice.lower_neighbors_values(x)) / len(lattice.lower_neighbors_values(x)) meanL = 1 / len(x) * sum(lattice.lower_neighbors_values(x)) delta = meanU + meanL - 2 * lattice.get_coeff_value(x) if delta > 0: #min distance with upper neighbors dmin = min(lattice.upper_neighbors_values(x)) - lattice.get_coeff_value(x) else: #min distance with lower neighbors dmin = lattice.get_coeff_value(x) - max(lattice.lower_neighbors_values(x)) oldU = lattice.get_coeff_value(x) newU = oldU + beta * (delta * dmin / 2 * (meanU + meanL)) lattice.set_coeff_value(x, newU) def shapley_index(lattice, criteria): """ calculate the shapley index (e.g. importance index) for each rule. """ shapleyIndex = dict() rules = sorted(list(filter(lambda x: len(x) == 1 and x != '.', lattice.get_coefficients()))) n = len(rules) def Cnk(n, k): f = math.factorial return f(n) // f(k) // f(n-k) for i in rules: subsetT = lattice.get_coeffs_without(i) acc2 = 0 for t in range(n): T = set(sorted(list(filter(lambda x: len(x) == t, subsetT)))) T.discard('.') acc3 = 0 if t == 0: acc3 = lattice.get_coeff_value(i) - lattice.get_coeff_value('.') for everyT in T: acc3 += lattice.get_coeff_value(''.join(sorted(everyT + i))) - lattice.get_coeff_value(everyT) acc2 += acc3 * (1 / Cnk(n-1, t)) shapleyIndex[i] = 1/n * acc2 print("shapleyIndex: ") n = len(criteria)-1 for item in shapleyIndex.items(): print(lattice.get_criteria(item[0]), " : ", item[1]*n) print("sum shapleyIndex: ", sum(list(item[1]*n for item in shapleyIndex.items()))) return shapleyIndex def learning_algorithm(importanceValues, lattice, criteria): beta = 0.15 alpha = 0.15 delta = 0.15 / ITER coeffs = list() squaredErrors = list() # repeat iteration for i in range(ITER): integralValue = compute_values(importanceValues, lattice, alpha) #etape1 if len(coeffs) == 0: coeffs = sorted(lattice.get_coefficients_non_modified(), key = len) adjust_value(lattice, beta, len(criteria)-1, coeffs) #etape2 alpha -= delta beta -= delta E = 0 for j in range(len(importanceValues)): e = importanceValues[j][-1] - integralValue[j] E += e*e # carrée squaredErrors.append(E / (len(importanceValues))) return squaredErrors def modeling(criteria, importanceValues): #---------------- initialization lattice & vars --------------- lattice = Lattice(criteria) #lattice.visualize() #uncomment in need of visualizings #---------------- run algo --------------- squaredErrors = learning_algorithm(importanceValues, lattice, criteria) #---------------- draw curve --------------- fig, ax = plt.subplots() # Create a figure containing a single axes. ax.plot(list(range(1, len(squaredErrors)+1)), squaredErrors) # Plot some data on the axes. print("our total squared mean errors: ", squaredErrors[-1]) return lattice, squaredErrors[-1] def classification(lattice, testSamples): integralValue = list() for data in testSamples: lattice.set_importanceValue(data) Fu = calculate_choquet_integral(lattice) integralValue.append(Fu) return list(map(lambda x: 1 if x>0.5 else 0, integralValue)) def interaction_index(lattice): interactionIndex = dict() n = len(lattice.get_criterias()) def Cnt(n, t): f = math.factorial return f(t)*f(n-t-2) / f(n - 1) for ij in list(filter(lambda x: len(x)==2, lattice.get_coefficients())): acc = 0 for t in list(filter(lambda x: ij[0] not in x and ij[1] not in x, lattice.get_coefficients())): if t == ".": t = str() marginalIndex = lattice.get_coeff_value(''.join(sorted(t + ij[0] + ij[1]))) \ + lattice.get_coeff_value(''.join(sorted("."))) \ - lattice.get_coeff_value(''.join(sorted(t + ij[0]))) \ - lattice.get_coeff_value(''.join(sorted(t + ij[1]))) else: marginalIndex = lattice.get_coeff_value(''.join(sorted(t + ij[0] + ij[1]))) \ + lattice.get_coeff_value(''.join(sorted(t))) \ - lattice.get_coeff_value(''.join(sorted(t + ij[0]))) \ - lattice.get_coeff_value(''.join(sorted(t + ij[1]))) acc += Cnt(n, len(t)) * marginalIndex interactionIndex[ij] = acc print("interactionIndex: ") for item in interactionIndex.items(): print(lattice.get_criteria(item[0][0]), lattice.get_criteria(item[0][1]), " : ", item[1]) return interactionIndex def matrix_confusion(testSamples, classes): #VP, FP, FN, VN matrixConfusion = [0]*4 for i in range(len(testSamples)): if int(classes[i]) == 1: if int(testSamples[i][-1]) == 1: matrixConfusion[0] += 1 else: matrixConfusion[1] += 1 else: if int(testSamples[i][-1]) == 1: matrixConfusion[2] += 1 else: matrixConfusion[3] += 1 print("classification bien fait ", matrixConfusion[0]+matrixConfusion[3], " sur ", len(testSamples)) print("Faux positive: ", matrixConfusion[1], ", Faux negative: ", matrixConfusion[2]) return matrixConfusion <file_sep>/README.md # Pattern recognition through descriptor aggregation via the Choquet integral A fuzzy measure system using Grabisch's algorithm. ## Program language Python3.7 ## Environment Linux or Windows10 ## Library dependency ### anaconda * Install for linux: [see here](https://problemsolvingwithpython.com/01-Orientation/01.05-Installing-Anaconda-on-Linux/) * Install for Windows: [see here](https://problemsolvingwithpython.com/01-Orientation/01.03-Installing-Anaconda-on-Windows/) ### graphviz * Install for linux: sudo apt install python3-pip pip3 install pydot graphviz * Install for Windows: conda install graphviz conda install python-graphviz ### matplotlib * Install for linux: python -m pip install -U pip python -m pip install -U matplotlib * Install for Windows: conda install matplotlib ## Files > DirectedGraph.py > Lattice.py > FuzzyMeasure.py > test.py > LearningData >> EvalEntreprise.txt >> Fromage.txt >> LearningBreastCancer.txt <file_sep>/.spyproject/workspace.ini [workspace] restore_data_on_startup = True save_data_on_exit = True save_history = True save_non_project_files = False [main] version = 0.1.0 recent_files = ['C:\\M1\\S2\\TER\\projet\\ter\\test.py', 'C:\\M1\\S2\\TER\\projet\\ter\\FuzzyMeusure.py', 'C:\\M1\\S2\\TER\\projet\\ter\\Lattice.py', 'C:\\M1\\S2\\TER\\projet\\ter\\DirectedGraph.py', 'C:\\M1\\S2\\TER\\projet\\ter\\LearningData\\Fromage.txt', 'C:\\M1\\S2\\TER\\projet\\ter\\LearningData\\LearningBreastCancer.txt', 'C:\\M1\\S2\\TER\\projet\\ter\\LearningData\\EvalEntreprise.txt', 'C:\\M1\\S2\\TER\\projet\\ter\\README.md'] <file_sep>/test.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Feb 10 15:36:55 2020 @author: MELLET """ import FuzzyMeusure as fm def first_test(criteria, importanceValues): lattice, squaredErrors = fm.modeling(criteria, importanceValues) fm.interaction_index(lattice) fm.shapley_index(lattice, criteria) #dictionary print("fuzzy measure") for key in lattice.get_criterias().keys(): print(lattice.get_criteria(key), ": ", lattice.get_coeff_value(key)) def test_k_fold(criteria, importanceValues): dataSet = list() delta = int(len(importanceValues)/3) dataSet.append(list(importanceValues[:delta])) dataSet.append(list(importanceValues[delta:delta*2])) dataSet.append(list(importanceValues[delta*2:])) listLattice = list() listShapleyIndex = list() listInteractionIndex = list() listMatrixConfusion = list() listSquaredErrors = list() for i in range(3): #print("ITERATION: ", i) trainingSet = dataSet[(i+1)%3] + dataSet[(i+2)%3] lattice, squaredErrors = fm.modeling(criteria, trainingSet) listLattice.append(lattice) listSquaredErrors.append(squaredErrors) shapleyIndex = fm.shapley_index(lattice, criteria) #dictionary listShapleyIndex.append(shapleyIndex) testSet = dataSet[i] classes = fm.classification(lattice, testSet) matrixConfusion = fm.matrix_confusion(testSet, classes) listMatrixConfusion.append(matrixConfusion) interactionIndex = fm.interaction_index(lattice) #dictionary listInteractionIndex.append(interactionIndex) print("K fold cross validation: ") print("Faux positive average: ", int(sum(list(x[1] for x in listMatrixConfusion))/3), \ ", Faux negative average: ", int(sum(list(x[2] for x in listMatrixConfusion))/3), \ ", Vrai positive average: ", int(sum(list(x[0] for x in listMatrixConfusion))/3), \ ", Vrai negative average: ", int(sum(list(x[3] for x in listMatrixConfusion))/3)) print("shapleyIndex average: ") acc = 0 n = len(criteria)-1 for key in listShapleyIndex[0].keys(): v = sum(list(x[key] for x in listShapleyIndex))*n/3 acc += v print(listLattice[0].get_criteria(key), " : ", v) print("sum shapley index: ", acc) print("interactionIndex average: ") for key in sorted(listInteractionIndex[0].keys()): print(listLattice[0].get_criteria(key[0]), listLattice[0].get_criteria(key[1]),\ " : ", sum(list(x[key] for x in listInteractionIndex))/3) print("squared mean errors: ", sum(listSquaredErrors)/3) print("les poids moyens de 3 treille") for key in listLattice[0].get_criterias().keys(): print(listLattice[0].get_criteria(key), ": ", sum(list(latt.get_coeff_value(key) for latt in listLattice))/3) if __name__ == "__main__": #path = "LearningData/EvalEntreprise.txt" #path = "LearningData/Fromage.txt" #criteria, importanceValues = fm.read_LD(path) #first_test(criteria, importanceValues) path = "LearningData/LearningBreastCancer.txt" criteria, importanceValues = fm.read_LD(path) test_k_fold(criteria, importanceValues) <file_sep>/Lattice.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Feb 8 13:17:40 2020 @author: MELLET installation under ubuntu python3 sudo apt install python3-pip pip3 install pydot graphviz under Win10 with anaconda conda install graphviz conda install python-graphviz """ from DirectedGraph import * #from graphviz import Digraph #uncomment in need of visualizing DESCRIPTORS = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'] #9 descriptors maximum class Lattice(object): def __init__(self, criteria): """ initialize a lattice to the equilibrium state. """ self.__graph = DirectedGraph() self.__weights = dict() #coeff self.__descriptors = dict() #{'a' : 'Gout'} self.__importanceValue = dict() self.__visited = dict() for i in range(len(criteria)-1): self.__descriptors[DESCRIPTORS[i]] = criteria[i] self.__contribute() self.__equilibrate() def __contribute(self): """ construct a directed graph with combinaison les descriptors, and initialize with all coefficients non visited. """ descriptors = sorted(self.__descriptors.keys()) end = len(descriptors) empty = '.' for x in descriptors: self.__graph.add_edge(empty, x) #layer0 & 1 iteration = 1 while iteration <= end: iteration += 1 concat = set() for i in range(len(descriptors)-1): for j in range(i+1, len(descriptors)): new_vertex = ''.join(sorted(set(descriptors[i] + descriptors[j]))) if len(new_vertex) == iteration : concat.add(new_vertex) self.__graph.add_edge(descriptors[i], new_vertex) self.__graph.add_edge(descriptors[j], new_vertex) descriptors = list(concat) for x in self.__graph.vertices(): self.__visited[x] = False def __equilibrate(self): """ status equilibrium """ for i in self.__graph.vertices(): self.__weights[i] = len(i)/len(self.__descriptors) self.__weights['.'] = 0 def set_coeff_value(self, v, value): """ modify the v coefficient's value and be touched. """ self.__weights[v] = value self.__visited[v] = True def get_coeff_value(self, v): """ return coefficient's value""" return self.__weights[v] def set_importanceValue(self, data): """ associate every criterion with its importance value. (can be modified when data change) """ for i in range(len(data)-1): self.__importanceValue[DESCRIPTORS[i]] = data[i] def permute_importanceValue(self): """ return a pair of list ordered with importance value. """ return list(x for x in sorted(list(self.__importanceValue.items()), key = lambda x: x[1])) def deduce_path(self): """ return a path deduced by the importance values""" path = ['.'] for x in reversed(list((x[0] for x in self.permute_importanceValue()))): if path[-1] == '.': path.append(x) else: path.append(''.join(sorted(path[-1]+x))) return path def has_visited(self, v): """ return whether the vertex / coefficient v has been visited. """ return self.__visited[v] def lower_neighbors_values(self, v): """ return a list of value of its lower neighbors. """ return list(map(lambda x: self.get_coeff_value(x), self.__graph.lower_neighbors(v))) def upper_neighbors_values(self, v): """ return a list of value of its upper neighbors. """ return list(map(lambda x: self.get_coeff_value(x), self.__graph.upper_neighbors(v))) def get_coefficients_non_modified(self): """ return all coefficients non modified. """ return list(filter(lambda x: not self.has_visited(x), self.__graph.vertices())) def get_coefficients(self): """ return all coefficients. """ return self.__graph.vertices() def get_coeffs_without(self, i): """ return all coefficients that dosen't contain element i. """ return sorted(list(filter(lambda x: i not in x, self.__graph.vertices()))) def get_criteria(self, i): """ return the real criteria's name in the context. """ return self.__descriptors[i] def get_criterias(self): """ return all criteria with pair of (supdo , real name in context). """ return self.__descriptors # uncomment in need of visualizing """ def visualize(self): dot = Digraph() for u in self.__graph.vertices(): for v in self.__graph.upper_neighbors(u): dot.edge(u, v) dot.render('test.gv', view = True) """ <file_sep>/DirectedGraph.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Implementation of a directed graph using a dictionary: the keys are the vertices, and the values are the vertices adjacent to a given vertex. Loops and weights are not allowed. We use the simplest representation: an edge (u, v) will be present once in the dictionary: v is in the set of childs of u, and u is in the set of parents of v. """ class DirectedGraph(object): def __init__(self): """Initialize a graph without edges""" self.__dictionary = dict() def add_edge(self, u, v): """Add an edge from the vertices u to v, creating the vertices         missing if applicable. """ if u not in self.__dictionary: self.__dictionary[u] = set() if v not in self.__dictionary: self.__dictionary[v] = set() self.__dictionary[u].add(v) def add_edges(self, iterable): """Add all edges of the given iterable to the graph.         whatever types of itrable are acceptable, but it should not contain         only pairs of elements (regardless of the type of couple). """ for u, v in iterable: self.add_edge(u, v) def add_vertex(self, u): """Add a vertex (whatever types) to the graph.""" self.__dictionary[u] = set() def add_vertices(self, iterable): """Add all vertices of the given iterable to the graph.         whatever types of itrable are acceptable.""" for u in iterable: self.add_vertex(u) def edges(self): """Return all the edges of the graph. An edge is represented         by a tuple (a, b) with a -> b.""" return { tuple(u, v) for u in self.__dictionary for v in self.__dictionary[u]} def contain_vertex(self, u): """Return True if the vertex u exists, False otherwise.""" return u in self.__dictionary def contain_adge(self, u, v): """Return True if the edge u -> v exists, False otherwise.""" if self.contain_vertex(u) and self.contain_vertex(v): return v in self.__dictionary[u] return False def upper_neighbors(self, u): #layer+1 -> children """Return all the vertices v s.t. v -> u.""" return self.__dictionary[u] def lower_neighbors(self, u): #layer-1 -> parents """Return all the vertices v s.t. u -> v.""" return (v for v in self.__dictionary if u in self.__dictionary[v] ) def degree_incoming(self, u): """Return the number of parents of the vertex; if it does not exist, causes          a mistake.""" return len(self.lower_neighbors(u)) def degre_outgoing(self, u): """Return the number of children of the vertex; if it does not exist, causes          a mistake.""" return len(self.upper_neighbors(u)) def num_vertices(self): """Return the number of vertices in the graph.""" return len(self.__dictionary) def remove_edge(self, u, v): """Remove edge u -> v if it exists; otherwise it will cause an error.""" self.__dictionary[u].remove(v) def remove_edges(self, iterable): """Remove all edges of the given iterator from the graph.         whatever types of itrable are acceptable, but it should not contain         only pairs of elements (regardless of the type of couple). """ for u, v in iterable: self.remove_edge(u, v) def remove_vertex(self, u): """Erase the vertex of the graph, and remove all the edges that         are incidental. """ del self.__dictionary[u] for v in self.__dictionary: self.__dictionary[v].discard(u) def remove_vertices(self, iterable): """Erase the vertices of the given iterable from the graph, and remove all         the edges incident at these vertices. """ for u in iterable: self.remove_vertex(u) def vertices(self): """Returns all the vertices of the graph.""" return set(self.__dictionary.keys())
51575beef830acbcf674dbdf544ae30fb0389aec
[ "Markdown", "Python", "INI" ]
6
Python
Yue0925/ProjetTer
7d0627cccbc062044422fd7920c746e1d18a4b0d
cd52a4a51a06180533f9efc5a6bd0aa3b41181c3
refs/heads/master
<file_sep>CREATE DATABASE IF NOT EXISTS burgers_db; USE burgers_db; CREATE TABLE IF NOT EXISTS burgers ( id INT AUTO_INCREMENT PRIMARY KEY , burger_name VARCHAR(30) , devoured BOOLEAN ); <file_sep># BurgerTracker <br> HW Unit 13 - Using Custom ORMs <br> Creator: <NAME> <br> Contribute: <EMAIL> <br> GitHub: https://github.com/Doremus256/BurgerTracker <br> Heroku Link: https://fast-brook-15128.herokuapp.com/ <br> <br> ***SEE 'VIDEO' FOLDER FOR WALKTHROUGH VIDEO*** <br> <br> <br> Motivation: <br> The challenge with this project was making use of express.handlebars to more easily update client-side HTML, with the goal of creating an application that can keep track of a list with a single identifying attribute (whether the burgers brought in via MySQL are to be deemed "Devoured" or not) and manipulating corresponding DOM elements accordingly. <br> <br> <br> Development Summary: <br> I started this project at 4pm and finished at 7pm. At this point, I am comfortable enough with all aspects of the full stack we have learned so far that I could teach this assignment to someone. Furthermore, this app's functionality could easily be expanded due to the modular nature of custom ORM methods. All I would need to do is add the needed orm.method, route and AJAX requests for the query I am interested in, and adjust the views to allow this new info to be displayed on the DOM. <br> <br> <br> <NAME>
a632fb3ed4bfa9a259c998a9d70e844c2a79be5f
[ "Markdown", "SQL" ]
2
SQL
Doremus256/BurgerTracker
83a47e044893658d5ced79133bba57b27fc6f9cd
618cfbafe2ac9bf34e571f84b181f15ec3fd00e7
refs/heads/master
<file_sep>module.exports = { url: "mongodb+srv://SC3002519:senha@cluster0.gt538.mongodb.net/SC3002519_bd?retryWrites=true&w=majority" }
0ccac6d439f62feb8da636a25c497fbd7c38dbfa
[ "JavaScript" ]
1
JavaScript
GabBogni/Angular_EAD2_Backend
effef3f1f8751337cefc8a9986e58f772704c316
bb32eab071ac549d3cb0bdf1815d3593527fdb5c
refs/heads/master
<file_sep>import React from 'react'; class Home extends React.Component { constructor(props) { super(props); this.state = { } } componentDidMount() { } calculateROI(){ this.setState({result: ""}) let failed = parseFloat(this.refs.bankrupt.value) console.log(failed) let ipo = parseFloat(this.refs.ipo.value) let success = parseFloat(this.refs.success.value) if(!this.refs.bankrupt.value || !this.refs.ipo.value || !this.refs.success.value){ alert("Please provide a valid input between 0-100 for all three cases.") } else if(failed<0 || failed>100 || ipo<0 || ipo>100 || success<0 || success>100){ alert("Please provide a valid input between 0-100 for all three cases.") } else if((failed + ipo + success)!=100){ alert("Total likelyhoods should sum up to 100%.") } else{ let p1 = (0 * failed)/100; let p2 = (2000 * ipo)/100; let p3 = (100000 * success)/100; let totalROI = p1 + p2 + p3; let result = "Your ROI will be " + totalROI.toFixed(2) + " %" this.setState({result: result}) } } render() { return( <div> <img src="https://transparentbusiness.com/img/twenty-five.jpg" alt="" className="back"/> <div className="main"> <img src="https://transparentbusiness.com/img/svg/logo_white.svg" alt="" className="logo"/> <div className="row"> <div className="col-md-4"> <div className="mainForm"> <div className="formHead"> Given the traction achieved by TransparentBusiness so far, what is your estimate of the likelihood of TransparentBusiness? </div> <div className="form-group"> <label htmlFor="bankrupt">Going bankrupt?</label> <input type="number" className="form-control" ref="bankrupt" /> </div> <div className="form-group"> <label htmlFor="ipo">Going public?</label> <input type="number" className="form-control" ref="ipo"/> </div> <div className="form-group"> <label htmlFor="success">Becoming synonymous with the business transparency category?</label> <input type="number" className="form-control" ref="success"/> </div> <button className="btn btn-default" onClick={()=>this.calculateROI()}>Submit</button> </div> </div> <div className="col-md-6"> <div className="mainText">A 90,000%+ ROI Opportunity?</div> <div className="mainSubText"> Tell us your estimate and we will predict your ROI. </div> <div className="result"> {this.state.result} </div> </div> </div> </div> </div> ) } } export default Home;
6db212c7d3e87f6066773d346764a35f67f662b8
[ "JavaScript" ]
1
JavaScript
arjunw7/alex-roi-calculator
ecc01d895dc5bcef3ae12fd368399f1e9b1788e6
1481e888195d0c05199188224ef1b5652b90e732
refs/heads/master
<repo_name>RockLegend93/MojBroj<file_sep>/BinaryTreeArray.cpp /* * File: BinaryTreeArray.cpp * Author: milan * * Created on March 31, 2015, 5:02 AM */ #include <stdint.h> #include <stddef.h> #include <iostream> #include "BinaryTreeArray.h" #include "Hromosome.h" using namespace std; BinaryTreeArray::BinaryTreeArray() { array = new int[MAX_ARRAY_SIZE]; fillNulls(); } BinaryTreeArray::BinaryTreeArray(const BinaryTreeArray& orig) { array = new int[MAX_ARRAY_SIZE]; for (int i = 0; i < MAX_ARRAY_SIZE; i++) array[i] = orig.array[i]; } BinaryTreeArray::~BinaryTreeArray() { delete [] array; } int BinaryTreeArray::insertAt(int value, int current) { array[current] = value; return current; } int BinaryTreeArray::insertLeft(int value, int current) { if (array == NULL) return 1; if (current * 2 + 1 > MAX_ARRAY_SIZE) return 1; if (array[current * 2 + 1] == 0) { array[current * 2 + 1] = value; return current * 2 + 1; } else if (current * 2 + 1 < MAX_ARRAY_SIZE) return insertLeft(value, current * 2 + 1); else return -1; } int BinaryTreeArray::insertRight(int value, int current) { if (array == NULL) return 1; if (current * 2 + 2 > MAX_ARRAY_SIZE) return 1; if (array[current * 2 + 2] == 0) { array[current * 2 + 2] = value; return current * 2 + 2; } else if (current * 2 + 2 < MAX_ARRAY_SIZE) return insertRight(value, current * 2 + 2); else return -1; } int BinaryTreeArray::insert(int value, int direction, int current) { if (direction == 0) return insertLeft(value, current); else return insertRight(value, current); } void BinaryTreeArray::preOrder(int current) { if (array[current] != 0) { if (array[current] == '+' || array[current] == '-' || array[current] == '*' || array[current] == '/') cout << (char) array[current] << " "; else cout << array[current] << " "; } if (current * 2 + 1 < MAX_ARRAY_SIZE && array[current] != 0) preOrder(current * 2 + 1); if (current * 2 + 2 < MAX_ARRAY_SIZE && array[current] != 0) preOrder(current * 2 + 2); } void BinaryTreeArray::postOrder(int current) { if (current * 2 + 1 < MAX_ARRAY_SIZE && array[current] != 0) postOrder(current * 2 + 1); if (current * 2 + 2 < MAX_ARRAY_SIZE && array[current] != 0) postOrder(current * 2 + 2); if (array[current] != 0) { if (array[current] == '+' || array[current] == '-' || array[current] == '*' || array[current] == '/') cout << (char) array[current] << " "; else cout << array[current] << " "; } } void BinaryTreeArray::inOrder(int current) { if (current * 2 + 1 < MAX_ARRAY_SIZE && array[current] != 0) { if (array[current * 2 + 1]) cout << "("; inOrder(current * 2 + 1); } if (array[current] != 0) { if (array[current] == '+' || array[current] == '-' || array[current] == '*' || array[current] == '/') cout << (char) array[current]; else cout << array[current]; } if (current * 2 + 2 < MAX_ARRAY_SIZE && array[current] != 0) { inOrder(current * 2 + 2); if (array[current * 2 + 2]) cout << ")"; } } void BinaryTreeArray::fillNulls() { int i; for (i = 0; i < MAX_ARRAY_SIZE; i++) { array[i] = 0; } } int checkC(int ch) { if (ch == '+' || ch == '-' || ch == '/' || ch == '*') return 2; else if (ch > 0) return 1; return 0; } int BinaryTreeArray::calculate(int current) { int ch; ch = checkC(array[current]); if (ch == 1) return array[current]; else if (ch == 0) return array[current]; if (ch == 2) { if (array[current] == '+') return calculate(current * 2 + 1) + calculate(current * 2 + 2); if (array[current] == '-') return calculate(current * 2 + 1) - calculate(current * 2 + 2); if (array[current] == '*') return calculate(current * 2 + 1) * calculate(current * 2 + 2); if (array[current] == '/') { int k = calculate(current * 2 + 2); if (k != 0) return calculate(current * 2 + 1) / k; else return k; } } } int BinaryTreeArray::search(int val, int current) { if (array[current] != 0) { if (array[current] == val) return current; } if (current * 2 + 1 < MAX_ARRAY_SIZE && array[current] != 0) return search(val, current * 2 + 1); if (current * 2 + 2 < MAX_ARRAY_SIZE && array[current] != 0) return search(val, current * 2 + 2); } int swapSubTree(BinaryTreeArray& first, BinaryTreeArray& second, int position1, int position2) { int temp = first.array[position1]; int temp2 = second.array[position2]; first.array[position1] = second.array[position2]; second.array[position2] = temp; if (position1 < (MAX_ARRAY_SIZE / 2) && position2 < (MAX_ARRAY_SIZE / 2)); if (first.array[position1] != 0 || second.array[position2] != 0) { swapSubTree(first, second, position1 * 2 + 1, position2 * 2 + 1); swapSubTree(first, second, position1 * 2 + 2, position2 * 2 + 2); } } BinaryTreeArray& BinaryTreeArray::operator=(const BinaryTreeArray& orig) { for (int i = 0; i < MAX_ARRAY_SIZE; i++) array[i] = orig.array[i]; return *this; } int BinaryTreeArray::countMaches(int number) { int count = 0; for (int i = 0; i < MAX_ARRAY_SIZE; i++) if (array[i] == number) count++; return count; } void BinaryTreeArray::empty() { for (int i = 0; i < MAX_ARRAY_SIZE; i++) array[i] = 0; } int BinaryTreeArray::checkTree() { int operators = getNumberOfOperationSigns(); int operands = 0; for (int i = 0; i < MAX_ARRAY_SIZE; i++) if (checkC(array[i]) == 1) operands++; if (operands != operators + 1) return 1; for (int i = 0; i < MAX_ARRAY_SIZE; i++) { if (array[i] == '+' || array[i] == '-' || array[i] == '*' || array[i] == '/') { if (array[2 * i + 1] == 0 || array[2 * i + 2] == 0) return 1; } else { if (array[2 * i + 1] != 0 || array[2 * i + 2] != 0) return 1; } } return 0; } int BinaryTreeArray::insertLeaf(int value) { for (int i = 0; i < MAX_ARRAY_SIZE; i++) { if (array[i] == 0 & (array[2 * i + 1] == 0 && array[2 * i + 2] == 0)) { array[i] = value; return 1; } } return 0; } int BinaryTreeArray::getItem(int position) { if (position < MAX_ARRAY_SIZE) return array[position]; return 0; } int BinaryTreeArray::isIneralNode(int position) { if (position < MAX_ARRAY_SIZE) if (array[position] != 0 && (array[position * 2 + 1] != 0 || array[position * 2 + 2] != 0)) return 1; return 0; } void BinaryTreeArray::seqPrint() { for (int i = 0; i < MAX_ARRAY_SIZE; i++) if (array[i] == '+' || array[i] == '-' || array[i] == '*' || array[i] == '/') cout << (char) array[i] << " "; else cout << array[i] << " "; } int BinaryTreeArray::checkTree(int* inArray, int size) { int counter, counter2; if (calculate() == 0) return 0; for (int i = 0; i < MAX_ARRAY_SIZE; i++) { counter = 0; for (int j = 0; j < MAX_ARRAY_SIZE; j++) { if (array[i] == array[j]) counter++; } counter2 = 0; for (int j = 0; j < size; j++) if (array[i] == inArray[j]) counter2++; if (counter > counter2) return 0; } return 1; } int BinaryTreeArray::reduce(int* inArray, int size) { int value, operators = 0, operands = 0; int count = 0, count2 = 0; int num; for (int i = 0; i < MAX_ARRAY_SIZE; i++) { if (checkC(array[i]) == 2) { if (!(checkC(array[2 * i + 1]) && checkC(array[2 * i + 1]))) { if (!checkC(array[2 * i + 1])) { if (operators < 5) { num = findAvalibleNumber(inArray); if (num != 0) { removeSubTree(2 * i + 1); array[2 * i + 1] = num; } } else { removeSubTree(2 * i + 1); num = findAvalibleNumber(inArray); if (num != 0) { removeSubTree(2 * i + 1); array[2 * i + 1] = num; } } } if (!checkC(array[2 * i + 2])) { if (operators < 5) { num = findAvalibleNumber(inArray); if (num != 0) { removeSubTree(2 * i + 2); array[2 * i + 2] = num; } } else { removeSubTree(2 * i + 2); num = findAvalibleNumber(inArray); if (num != 0) { removeSubTree(2 * i + 2); array[2 * i + 2] = num; } } } } value = calculate(i); if (value == 0) removeSubTree(i); if (array[i] == '/') { if (calculate(2 * i + 2) == 0 || calculate(2 * i + 1) % calculate(2 * i + 2) == 0) { removeSubTree(2 * i + 2); array[2 * i + 2] = findAvalibleNumber(inArray); } } count = 0; count2 = 0; } if (checkC(array[i]) == 1) { count = 0; count2 = 0; for (int j = 0; j < 6; j++) if (array[i] == array[j]) count++; for (int j = 0; j < MAX_ARRAY_SIZE / 2; j++) if (j != i) if (array[j] == array[i]) count--; if (count <= 0) { array[i] = 0; num = findAvalibleNumber(inArray); array[i] = num; } } } return getNumberOfOperationSigns(); } void BinaryTreeArray::removeSubTree(int current) { if (array[current] != 0) { array[current] = 0; if (current * 2 + 1 < MAX_ARRAY_SIZE) removeSubTree(current * 2 + 1); if (current * 2 + 2 < MAX_ARRAY_SIZE) removeSubTree(current * 2 + 2); } } int BinaryTreeArray::getNumberOfOperationSigns() { int count = 0; for (int i = 0; i < MAX_ARRAY_SIZE; i++) if (array[i] == '*' || array[i] == '/' || array[i] == '-' || array[i] == '+') count++; return count; } int BinaryTreeArray::changeTree(int pos, int number, int mode) { int count = 0; count = 0; for (int i = 0; i < MAX_ARRAY_SIZE / 2; i++) { if (count == pos) { if (array[i] == '/') array[i] = '*'; else if (array[i] == '*') array[i] = '+'; else if (array[i] == '+') array[i] = '-'; else if (array[i] == '-')array[i] = '/'; if (mode == 1) if (checkC(array[2 * i + 1]) == 1 && checkC(array[2 * i + 2]) == 1) { int temp = array[2 * i + 1]; array[2 * i + 1] = array[2 * i + 2]; array[2 * i + 2] = temp; } } if (checkC(i) == 2) count++; } reduce(Hromosome::niz, 6); } int BinaryTreeArray::fls(int pos) { if (checkC(array[pos]) == 1) return array[pos]; return fls(pos * 2 + 1); } int BinaryTreeArray::findAvalibleNumber(int* inArray) { int count; for (int i = 0; i < 6; i++) { count = 0; for (int j = 0; j < MAX_ARRAY_SIZE / 2; j++) { if (array[j] == inArray[i]) count--; } for (int j = 0; j < 6; j++) if (inArray[i] == inArray[j]) count++; if (count > 0) return inArray[i]; } return 0; }<file_sep>/Hromosome.h /* * File: Hromosome.h * Author: milan * * Created on March 31, 2015, 7:13 AM */ #ifndef HROMOSOME_H #define HROMOSOME_H #include "BinaryTreeArray.h" class Hromosome { friend void recombine(Hromosome&, Hromosome&); public: Hromosome(); Hromosome(const Hromosome& orig); void initRandom(int numerOfOperations = 3); double fitness(); int checkTree(); void printTree(); Hromosome& operator=(const Hromosome& orig); int getNumberOfOperations(); void mutate(); int checkSolution(); int value(); virtual ~Hromosome(); static int* niz; static int goal; private: int numerOfOperations; BinaryTreeArray tree; }; void recombine(Hromosome&, Hromosome&); #define POP_SIZE_ 3000000 #endif /* HROMOSOME_H */ <file_sep>/main.cpp /* * File: main.cpp * Author: milan * * Created on March 31, 2015, 5:30 AM */ #include <cstdlib> #include <iostream> #include <vector> #include "BinaryTreeArray.h" #include "Hromosome.h" #include "Population.h" #define POP_SIZE 320 #define MAX_ITER 1000 #define MAX_SAME 10 #define CROSSOVER_PROBABILITY 0.8 #define MUTATION_PROBABILITY 0.3 using namespace std; /* * */ int main(int argc, char** argv) { int niz[6]; double temp; srand(time(NULL)); srand48(time(NULL)); if (argc != 8) { cout << "RANDOM" << endl; for (int i = 0; i < 4; i++) { temp = drand48(); niz[i] = temp * 8 + 1; } temp = drand48(); if (temp < 0.33) niz[4] = 10; else if (temp < 0.66) niz[4] = 15; else niz[4] = 20; temp = drand48(); if (temp < 0.25) niz[5] = 25; else if (temp < 0.5) niz[5] = 50; else if (temp < 0.75) niz[5] = 75; else niz[5] = 100; temp = drand48(); Hromosome::goal = temp * 998 + 1; } else { int tmp; for (int i = 1; i < 5; i++) { tmp = atoi(argv[i]); if (tmp > 0) niz[i - 1] = tmp; else { cout << "POGRESAN UNOS" << endl; return 1; } } tmp = atoi(argv[5]); if (tmp == 10 || tmp == 15 || tmp == 20) niz[4] = tmp; else { cout << "POGRESAN UNOS" << endl; return 1; } tmp = atoi(argv[6]); if (tmp == 25 || tmp == 50 || tmp == 75 || tmp == 100) niz[5] = tmp; else { cout << "POGRESAN UNOS" << endl; return 1; } tmp = atoi(argv[7]); if (tmp > 0 && tmp < 1000) Hromosome::goal = tmp; else { cout << "POGRESAN UNOS" << endl; return 1; } } cout << " NUMBERS:"; for (int i = 0; i < 6; i++) cout << niz[i] << " "; Hromosome::niz = niz; cout << endl << "GOAL: " << Hromosome::goal << endl; Population *pop1 = new Population(POP_SIZE_); // cout << "INITIAL POPULATION:" << endl; // pop.printAll(); Hromosome *ch = NULL; int iter = 0; ch = pop1->checkSolution(); if (ch != NULL) { cout << "SOLUTION:" << endl; ch->printTree(); return 0; } // delete pop1; Population pop(POP_SIZE); Hromosome best = pop.getBest(); Hromosome oldBest = pop.getBest(); Hromosome firstBest = pop.getBest(); Hromosome *bests = new Hromosome[MAX_ITER]; int bestIter = 0; while (iter < MAX_ITER) { pop.selection(); ch = pop.checkSolution(); if (ch != NULL) { cout << "SOLUTION:" << endl; ch->printTree(); delete [] bests; return 0; } pop.recombination(CROSSOVER_PROBABILITY); ch = pop.checkSolution(); if (ch != NULL) { cout << "SOLUTION:" << endl; ch->printTree(); delete [] bests; return 0; } pop.mutation(MUTATION_PROBABILITY); bests[iter] = pop.getBest(); iter++; if (pop.getBest().value() == best.value()) { bestIter++; if (bestIter >= MAX_SAME) { pop = Population(POP_SIZE); bestIter = 0; } } else bestIter = 0; if (iter % (MAX_ITER / 10) == 0) { pop = Population(POP_SIZE); } // pop.printBest(); } if (ch == NULL) { cout << "NEAREST SOLUTION" << endl; double max = 0; int pos = 0; for (int i = 0; i < MAX_ITER; i++) if (bests[i].fitness() > max) { pos = i; max = bests[i].fitness(); } cout << "in iteration " << pos << endl; bests[pos].printTree(); cout << endl; } return 0; } <file_sep>/Hromosome.cpp /* * File: Hromosome.cpp * Author: milan * * Created on March 31, 2015, 7:13 AM */ #include <stdlib.h> #include <iostream> #include "Hromosome.h" #include "math.h" #include "BinaryTreeArray.h" using namespace std; int* Hromosome::niz = NULL; int Hromosome::goal = 0; Hromosome::Hromosome() { numerOfOperations = 0; } void Hromosome::initRandom(int numberOf) { tree.empty(); double r = drand48(); // if (numberOf == 0) numerOfOperations = (int) r * 5; // else if (numberOf >= 6) numberOf = 5; numerOfOperations = numberOf; int numberOfOperands = numerOfOperations + 1; // if (numerOfOperations == 6) numberOfOperands--; char c; // cout << "NUMBER OF OPERATIONS:" << numerOfOperations << " " << endl; for (int i = 0; i < numerOfOperations; i++) { r = drand48(); if (r < 0.4) c = '+'; else if (r < 0.6) c = '-'; else if (r < 0.9) c = '*'; else c = '/'; tree.insertLeaf(c); } int next; int randomNumber; int count = 0; for (int i = 0; i < numberOfOperands; i++) { randomNumber = 6 * drand48(); next = Hromosome::niz[randomNumber]; r = drand48(); count = 0; for (int j = 0; j < 6; j++) if (niz[j] == next) count++; if (tree.countMaches(next) < count) { tree.insertLeaf(next); } else { // tree.empty(); // initRandom(numerOfOperations); i--; } } tree.reduce(Hromosome::niz, 6); int val = tree.calculate(); if (val <= 0 || val > 1000) { tree.empty(); initRandom(numerOfOperations); } } Hromosome::Hromosome(const Hromosome & orig) { tree = orig.tree; } void Hromosome::printTree() { cout << endl; cout << " Inorder: "; tree.inOrder(); cout << "=" << tree.calculate() << endl << " Preorder: "; tree.preOrder(); cout << endl << " Postorder: "; tree.postOrder(); cout << endl << " Seq: "; tree.seqPrint(); cout << endl; } Hromosome::~Hromosome() { } double Hromosome::fitness() { int value = goal - tree.calculate(); double fit = 1.0 / (1.0 + fabs(value)); return fit; } int Hromosome::checkTree() { return tree.checkTree(); } void recombine(Hromosome& h1, Hromosome& h2) { int pos1, pos2; if (h1.tree.calculate() == 0) { h1.initRandom(h1.numerOfOperations); // cout << "---" << endl; // return; } if (h2.tree.calculate() == 0) { h2.initRandom(h2.numerOfOperations); // cout << "----" << endl; } // cout << "." << endl; h1.numerOfOperations = h1.tree.getNumberOfOperationSigns(); h2.numerOfOperations = h2.tree.getNumberOfOperationSigns(); int min = (h1.numerOfOperations < h2.numerOfOperations) ? h1.numerOfOperations : h2.numerOfOperations; pos1 = drand48() * min; pos2 = drand48() * min; if (pos1 > 0 && pos2 > 0) { // cout << "\t\tbefore swap" << endl; swapSubTree(h1.tree, h2.tree, pos1, pos2); // cout << "\t\tbefore reduction" << endl; h1.numerOfOperations = h1.tree.reduce(Hromosome::niz, 6); h2.numerOfOperations = h2.tree.reduce(Hromosome::niz, 6); // cout << "\t\tafter reduction" << endl; int p1 = h1.checkTree(); int p2 = h2.checkTree(); if (p1 == 1 || p2 == 1) { h1.initRandom(h1.getNumberOfOperations()); h2.initRandom(h2.getNumberOfOperations()); } } } Hromosome& Hromosome::operator=(const Hromosome& orig) { tree = orig.tree; numerOfOperations = orig.numerOfOperations; } int Hromosome::checkSolution() { if (tree.calculate() == goal) return 1; return 0; } int Hromosome::value() { return tree.calculate(); } void Hromosome::mutate() { numerOfOperations = tree.getNumberOfOperationSigns(); int random = drand48() * numerOfOperations; tree.changeTree(random, numerOfOperations, (int) drand48()*2); } int Hromosome::getNumberOfOperations() { numerOfOperations = tree.getNumberOfOperationSigns(); return numerOfOperations; }<file_sep>/Population.cpp /* * File: Population.cpp * Author: milan * * Created on March 31, 2015, 7:11 AM */ #include <stdlib.h> #include <iostream> using namespace std; #include "Population.h" Population::Population(int popSize) { population = new Hromosome[popSize]; size = popSize; int op; srand48(time(NULL)); srand(time(NULL)); for (int i = 0; i < popSize; i++) { op = drand48()*5.0; population[i].initRandom(op); if (!population[i].checkTree()) i--; } } Population::Population(const Population& orig) { population = new Hromosome[orig.size]; size = orig.size; // cout << "copy" << endl; for (int i = 0; i < size; i++) population[i] = orig.population[i]; // cout << "end-copy" << endl; } //roulet selection Population::Population(const Population& orig, int i) { srand48(time(NULL)); double max = orig.fitness(); double s = 0; double *q = new double[orig.size]; double probability = 0.0; double fitness; size = orig.size; // cout << endl << "Slection q: "; for (int i = 0; i < size; i++) { fitness = orig.population[i].fitness(); probability = orig.population[i].fitness() / (max * 1.0); q[i] = s + probability; s += probability; // cout << q[i] << " "; } // cout << endl; double rouletPos; population = new Hromosome[orig.size]; for (int i = 0; i < size; i++) { rouletPos = drand48(); if (rouletPos <= q[0]) population[i] = orig.population[0]; else if (rouletPos > q[size - 2]) population[i] = orig.population[size - 1]; else for (int j = 1; j < size - 1; j++) { if (rouletPos > q[j - 1] && rouletPos <= q[j]) population[i] = orig.population[i]; } } delete [] q; } Population::~Population() { delete [] population; } Population& Population::operator=(const Population& orig) { delete [] population; size = orig.size; population = new Hromosome[size]; for (int i = 0; i < size; i++) population[i] = orig.population[i]; return *this; } double Population::fitness() const { if (population == NULL) return 0; double sum = 0; for (int i = 0; i < size; i++) sum += population[i].fitness(); return sum; } int Population::recombination(double probability) { double randomNumber; for (int i = 0; i < size - 1; i++) { randomNumber = drand48(); // cout << randomNumber << endl; if (randomNumber < probability) { recombine(population[i], population[i + 1]); if (population[i].checkTree() == 1) { population[i].initRandom(population[i].getNumberOfOperations()); } if (population[i + 1].checkTree() == 1) population[i + 1].initRandom(population[i].getNumberOfOperations()); if (population[i].fitness() * population[i + 1].fitness() < population[i].fitness() * population[i + 1].fitness()) { population[i] = population[i]; population[i + 1] = population[i]; } } } return 0; } Hromosome * Population::checkSolution() { // Hromosome local; for (int i = 0; i < size; i++) if (population[i].fitness() == 1) return &(population[i]); return NULL; } void Population::mutation(double probability) { for (int i = 0; i < size; i++) if (drand48() < probability) { // cout << "mutation " << i << " begin" << endl; population[i].mutate(); if (population[i].checkTree() == 1) { population[i].initRandom(population[i].getNumberOfOperations()); } } } void Population::printBest() const { double max = 0; int pos = 0; double temp; for (int i = 0; i < size; i++) { temp = population[i].fitness(); if (temp > max) { pos = i; max = temp; } } // cout << "=============================================================================" << endl; population[pos].printTree(); // cout << "=============================================================================" << endl; } Hromosome Population::getBest() { double max = 0; int pos = 0; double temp; for (int i = 0; i < size; i++) { temp = population[i].fitness(); if (temp > max) { pos = i; max = temp; } } return population[pos]; } int Population::selection() { Population orig(*this); srand48(time(NULL)); double max = fitness(); double s = 0; double *q = new double[orig.size]; double probability = 0.0; double fitness; size = orig.size; // cout << endl << "Slection q: "; for (int i = 0; i < size; i++) { fitness = population[i].fitness(); probability = population[i].fitness() / (max * 1.0); q[i] = s + probability; s += probability; // cout << q[i] << " "; } // cout << endl; double rouletPos; // delete [] population; // population = new Hromosome[orig.size]; for (int i = 0; i < size; i++) { rouletPos = drand48(); if (rouletPos <= q[0]) population[i] = orig.population[0]; else if (rouletPos > q[size - 2]) population[i] = orig.population[size - 1]; else for (int j = 1; j < size - 1; j++) { if (rouletPos > q[j - 1] && rouletPos <= q[j]) population[i] = orig.population[i]; } } delete [] q; } <file_sep>/Population.h /* * File: Population.h * Author: milan * * Created on March 31, 2015, 7:11 AM */ #ifndef POPULATION_H #define POPULATION_H #include "Hromosome.h" class Population { public: Population(int popSize = 20); Population(const Population& orig); Population(const Population& orig, int i); int selection(); int recombination(double probabiliy); void mutation(double probability); double fitness() const; // void printAll() const; void printBest() const; Hromosome getBest(); Hromosome* checkSolution(); Population& operator=(const Population& orig); virtual ~Population(); private: Hromosome *population; int size; }; #endif /* POPULATION_H */ <file_sep>/BinaryTreeArray.h /* * File: BinaryTreeArray.h * Author: milan * * Created on March 31, 2015, 5:02 AM */ #ifndef BINARYTREEARRAY_H #define BINARYTREEARRAY_H #define MAX_ARRAY_SIZE 30 class BinaryTreeArray { friend int swapSubTree(BinaryTreeArray&, BinaryTreeArray&, int, int); public: BinaryTreeArray(); BinaryTreeArray(const BinaryTreeArray& orig); int insertAt(int value, int current = 0); int insertLeft(int value, int current = 0); int insertRight(int value, int current = 0); int insert(int value, int direction, int current = 0); void removeSubTree(int position); int insertLeaf(int value); int getItem(int); int isIneralNode(int); void preOrder(int root = 0); void postOrder(int root = 0); void inOrder(int root = 0); void seqPrint(); int calculate(int root = 0); int checkTree(int* array, int size); int search(int val, int root = 0); int countMaches(int number); void empty(); int findAvalibleNumber(int* array); int reduce(int* inArray, int size); int checkTree(); int getNumberOfOperationSigns(); int fls(int pos); int changeTree(int pos, int number, int mode); BinaryTreeArray& operator=(const BinaryTreeArray&); virtual ~BinaryTreeArray(); private: int *array; void fillNulls(); }; int swapLeftSubTree(BinaryTreeArray& first, BinaryTreeArray& second, int position); int swapRighttSubTree(BinaryTreeArray& first, BinaryTreeArray& second, int position); int swapSubTree(BinaryTreeArray& first, BinaryTreeArray& second, int position); #endif /* BINARYTREEARRAY_H */
0f6e2dc6be29e37c5fd68560f267a84de344ba61
[ "C++" ]
7
C++
RockLegend93/MojBroj
20e8f560763b8c752f8d40c1b1cafbf2924ede7e
af5eef190c39d66b8e7a0a85845de9b7dae4251f
refs/heads/master
<repo_name>katiewrennhansen/dev-tracks-api<file_sep>/src/users/user-service.js const bcrypt = require('bcryptjs') const UsersService = { getAllUsers(knex){ return knex.select('*').from('dev_tracks_users') }, getUserById(knex, id){ return knex('dev_tracks_users') .where({ id }) .first() }, addUser(knex, newUser){ return knex .insert(newUser) .into('dev_tracks_users') .returning('*') .then(([user]) => user) }, deleteUser(knex, id){ return knex('dev_tracks_users') .where({ id }) .delete() }, updateUser(knex, id, updatedContent){ return knex('dev_tracks_users') .where({ id }) .update(updatedContent) }, hashPassword(password){ return bcrypt.hash(password, 12) }, hasUser(knex, user_name){ return knex('dev_tracks_users') .where({ user_name }) .first() .then(user => !!user) } } module.exports = UsersService;<file_sep>/migrations/003.do.create_dev_tracks_accounts.sql CREATE TABLE user_accounts ( id INTEGER PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY, name TEXT NOT NULL, url TEXT NOT NULL, date_created TIMESTAMP DEFAULT now() NOT NULL, user_id INTEGER REFERENCES dev_tracks_users(id) ON DELETE SET NULL ); CREATE TABLE user_projects ( id INTEGER PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY, name TEXT NOT NULL, url TEXT, description TEXT, date_created TIMESTAMP DEFAULT now() NOT NULL, user_id INTEGER REFERENCES dev_tracks_users(id) ON DELETE SET NULL ); <file_sep>/migrations/003.undo.create_dev_tracks_accounts.sql DROP TABLE IF EXISTS user_accounts; DROP TABLE IF EXISTS user_projects;<file_sep>/seeds/seed.dev_tracks_users.sql INSERT INTO dev_tracks_users (user_name, full_name, password) VALUES ('kawrenn', '<NAME>', '$<PASSWORD>');<file_sep>/src/users/user-router.js const express = require('express') const UsersService = require('./user-service') const usersRouter = express.Router() const bodyParser = express.json() usersRouter .route('/') .get((req, res, next) => { const knexInstance = req.app.get('db') UsersService.getAllUsers(knexInstance) .then(users => { res.send(users) }) .catch(next) }) .post(bodyParser, (req, res, next) => { const knexInstance = req.app.get('db') const { user_name, full_name, password } = req.body; const newUser = { user_name, full_name, password } for(const [key, value] of Object.entries(newUser)) if (value == null) return res.status(400).json({ error: { message: `missing ${key}` } }) UsersService.hasUser(knexInstance, newUser.user_name) .then(user => { if(user) return res.status(400).json({ error: { message: 'username taken' } }) return UsersService.hashPassword(newUser.password) .then(hashedPassword => { const newUser = { user_name, password: <PASSWORD>, full_name, date_created: 'now()', } return UsersService.addUser(knexInstance, newUser) .then(user => { res.status(201).json(user) }) }) }) .catch(next) }) usersRouter .route('/:id') .all((req, res, next) => { const knexInstance = req.app.get('db') const id = req.params.id UsersService.getUserById(knexInstance, id) .then(user => { if(!user) { res.send(404).json({ error: 'user does not exist' }) } res.user = user next() }) .catch(next) }) .get((req, res, next) => { res.send(res.user) }) .patch(bodyParser, (req, res, next) => { const knexInstance = req.app.get('db') const id = req.params.id const { full_name, email, bio } = req.body const updatedUser = { full_name, email, bio } for(const [key, num] of Object.entries(updatedUser)) if(num == 0) return res.status(400).json({ error: 'need content' }) UsersService.updateUser(knexInstance, id, updatedUser) .then(user => { res.status(201).end() }) .catch(next) }) .delete((req, res, next) => { const knexInstance = req.app.get('db') const id = req.params.id UsersService.deleteUser(knexInstance, id) .then(user => { res.send(204).end() }) .catch(next) }) module.exports = usersRouter;<file_sep>/migrations/001.do.create_resources.sql CREATE TABLE dev_tracks_resources ( id INTEGER PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY, name TEXT NOT NULL, type TEXT NOT NULL, status TEXT NOT NULL, url TEXT NOT NULL, description TEXT NOT NULL, date_completed TIMESTAMP, date_created TIMESTAMP DEFAULT now() NOT NULL ) <file_sep>/src/resources/resources-router.js const express = require('express') const ResourcesService = require('./resource-service') const { requireAuth } = require('../middleware/jwt-auth') const resourcesRouter = express.Router() const bodyParser = express.json() resourcesRouter .route('/') .get((req, res, next) => { const knexInstance = req.app.get('db') ResourcesService.getAllResources(knexInstance) .then(resources => { res.send(resources) }).catch(next) }) .post(requireAuth, bodyParser, (req, res, next) => { const knexInstance = req.app.get('db') const { name, type, status, url, description, user_id, date_completed } = req.body const newResource = { name, type, status, url, description } for (const [key, value] of Object.entries(newResource)) if (value == null) return res.status(400).json({ error: { message: `Missing '${key}' in request body` } }) newResource.date_completed = date_completed newResource.user_id = user_id ResourcesService.postResource(knexInstance, newResource) .then(resource => { res.status(201).send(newResource) }) .catch(next) }) resourcesRouter .route('/:id') .all((req, res, next) => { const knexInstance = req.app.get('db') const id = req.params.id ResourcesService.getResourceById(knexInstance, id) .then(resource => { if(!resource) { return res.status(404).json({ error: { message: "resource doesn't exist" } }) } res.resource = resource next() }) .catch(next) }) .get((req, res, next) => { res.json(res.resource) }) .patch(requireAuth, bodyParser, (req, res, next) => { const knexInstance = req.app.get('db') const id = req.params.id const { name, type, status, url, description, user_id, date_completed } = req.body const updatedResource = { name, type, status, url, description, user_id, date_completed } for (const [key, num] of Object.entries(updatedResource)) if (num == 0) return res.status(400).json({ error: { message: `Body must contain updated content` } }) ResourcesService.updateResource(knexInstance, id, updatedResource) .then(resource => { res.status(204).end() }) .catch(next) }) .delete(requireAuth, (req, res, next) => { const knexInstance = req.app.get('db') const id = req.params.id ResourcesService.deleteResource(knexInstance, id) .then(resource => { res.status(201).end() }) .catch(next) }) module.exports = resourcesRouter;<file_sep>/migrations/004.undo.create_add_user_info.sql ALTER TABLE dev_tracks_users DROP COLUMN IF EXISTS email; ALTER TABLE dev_tracks_users DROP COLUMN IF EXISTS bio; ALTER TABLE dev_tracks_users DROP COLUMN IF EXISTS photo;<file_sep>/migrations/004.do.create_add_user_info.sql ALTER TABLE dev_tracks_users ADD COLUMN email TEXT; ALTER TABLE dev_tracks_users ADD COLUMN bio TEXT; ALTER TABLE dev_tracks_users ADD COLUMN photo TEXT;<file_sep>/migrations/002.do.create_dev_tracks_users.sql CREATE TABLE dev_tracks_users ( id INTEGER PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY, user_name TEXT NOT NULL UNIQUE, full_name TEXT NOT NULL, password TEXT NOT NULL, date_created TIMESTAMP DEFAULT now() NOT NULL ); ALTER TABLE dev_tracks_resources ADD COLUMN user_id INTEGER REFERENCES dev_tracks_users(id) ON DELETE SET NULL;<file_sep>/src/auth/auth-router.js const express = require('express') const AuthService = require('./auth-service') const authRouter = express.Router() const bodyParser = express.json() authRouter .route('/') .post(bodyParser, (req, res, next) => { const knexInstance = req.app.get('db') const { user_name, password } = req.body const loginUser = { user_name, password } for (const [key, value] of Object.entries(loginUser)) if(value == null) return res.status(400).json({ error: `missing ${key} username or password` }) AuthService.getUserName(knexInstance, loginUser.user_name) .then(dbUser => { if(!dbUser) return res.status(400).json({ error: 'bad username' }) return AuthService.comparePasswords(loginUser.password, dbUser.password) .then(match => { if(!match) return res.status(400).json({ error: 'password not a match' }) const sub = dbUser.user_name const payload = { user_id: dbUser.id } res.send({ id: dbUser.id, authToken: AuthService.createJwt(sub, payload) }) }) }) .catch(next) }) module.exports = authRouter<file_sep>/src/resources/resource-service.js const ResourcesService = { getAllResources(knex){ return knex.select('*').from('dev_tracks_resources') }, getResourcesForUser(knex, user_id){ return knex .from('dev_tracks_resources') .select('*') .where({ user_id }) .then(rows => { return rows }) }, getResourceById(knex, id){ return knex .from('dev_tracks_resources') .select('*') .where({ id }) .first() }, postResource(knex, newResource){ return knex .insert(newResource) .into('dev_tracks_resources') .returning('*') .then(rows => { return rows[0] }) }, updateResource(knex, id, updateResource){ return knex('dev_tracks_resources') .where({ id }) .update(updateResource) }, deleteResource(knex, id){ return knex('dev_tracks_resources') .where({ id }) .delete() } } module.exports = ResourcesService;<file_sep>/migrations/001.undo.create_resources.sql DROP TABLE IF EXISTS dev_tracks_resources;<file_sep>/src/projects/projects-service.js const ProjectsService = { getAllProjects(knex){ return knex.select('*').from('user_projects') }, getProjectById(knex, id){ return knex .from('user_projects') .select('*') .where({ id }) .first() }, postProject(knex, newAccount){ return knex .insert(newAccount) .into('user_projects') .returning('*') .then(rows => { return rows[0] }) }, updateProject(knex, id, updateAccount){ return knex('user_projects') .where({ id }) .update(updateAccount) }, deleteProject(knex, id){ return knex('user_projects') .where({ id }) .delete() } } module.exports = ProjectsService;<file_sep>/src/accounts/accounts-service.js const AccountsService = { getAllAccounts(knex){ return knex.select('*').from('user_accounts') }, getAccountById(knex, id){ return knex .from('user_accounts') .select('*') .where({ id }) .first() }, postAccount(knex, newAccount){ return knex .insert(newAccount) .into('user_accounts') .returning('*') .then(rows => { return rows[0] }) }, updateAccount(knex, id, updateAccount){ return knex('user_accounts') .where({ id }) .update(updateAccount) }, deleteAccount(knex, id){ return knex('user_accounts') .where({ id }) .delete() } } module.exports = AccountsService;<file_sep>/seeds/seed.accounts_projects.sql INSERT INTO user_accounts (name, url) VALUES ('LinkedIn', 'https://www.linkedin.com/in/katiewrennhansen/'); INSERT INTO user_projects (name, url, description) VALUES ('Healthy Plate', 'https://katiewrennhansen.github.io/healthyPlate/', 'food lookup resource');<file_sep>/test/resources-endpoints.spec.js const app = require('../src/app') const knex = require('knex') const helpers = require('./test-helpers') describe('All Resources Endoints', () => { let db; const { testResources } = helpers.makeResourcesArray() before('make knex instance', () =>{ db = knex({ client: 'pg', connection: process.env.TEST_DB_URL }) app.set('db', db) }) after('disconnect from db', () => db.destroy()) before('cleanup db', () => helpers.cleanTables(db)) afterEach('cleanup db', () => helpers.cleanTables(db)) describe('/api/resources', () => { context('given there are no resources', () => { it('responds with 200 and empty list', () => { return supertest(app) .get('/api/resources') .expect(200, []) }) }) context('given there are resources in the db', () => { beforeEach('insert resources into the db', () => { helpers.seedTables(db, testResources) }) it('GET /api/resources responds with 200 and all resources', () => { return supertest(app) .get('/api/resources') .expect(200, testResources) }) it('POST /api/resources responds with 201 and created resource', () => { const newResource = { name: "<NAME>", type: "Project", status: "Completed", url: "https://www.thinkful.com/learn/", description: "This articles summarizes the importance of Design Systems in a complex application", date_completed: null, user_id: null } return supertest(app) .post('/api/resources') .send(newResource) .expect(201) }) }) }) describe('api/resources/id', () => { it('GET /api/resource/:id responds 404 when resource is not found', () => { const id = 40001 return supertest(app) .get(`/api/resources/${id}`) .expect(404, { error: { message: "resource doesn't exist" } }) }) }) })
d20e01bff9b219bd8ef0544c8b25fdfa548876cd
[ "JavaScript", "SQL" ]
17
JavaScript
katiewrennhansen/dev-tracks-api
334c25540bc797b41257951e817d532169e732ce
4d30ec4694e401279257ec437e102df27c08e793
refs/heads/master
<repo_name>diosdog/itunes-win-api<file_sep>/app.js var fs = require('fs') var path = require('path') var util = require('util') var express = require('express') var morgan = require('morgan') var bodyParser = require('body-parser') var parameterize = require('parameterize'); const shell = require('node-powershell'); var winax = require('winax'); var tmp = require('tmp'); var app = express() app.use(bodyParser.urlencoded({ extended: false })) app.use(express.static(path.join(__dirname, 'public'))); var logFormat = "'[:date[iso]] - :remote-addr - :method :url :status :response-time ms - :res[content-length]b'" app.use(morgan(logFormat)) var tmpDir = null; function win_getCurrentState(){ itunes = new ActiveXObject('iTunes.Application') currentState = {}; currentState['player_state'] = itunes.PlayerState ? 'playing' : 'paused' //TODO: convert to expected format to match mac version instead of 0/1 for paused/playing currentTrack = itunes.CurrentTrack currentPlaylist = itunes.CurrentPlaylist currentState['id'] = currentTrack.trackID.toString() currentState['name'] = currentTrack.Name currentState['artist'] = currentTrack.Artist currentState['album'] = currentTrack.Album currentState['playlist'] = currentPlaylist.Favorites currentState['volume'] = itunes.SoundVolume currentState['muted'] = itunes.Mute currentState['repeat'] = 0 //TODO: figure out if this is accessible in COM object currentState['shuffle'] = 0 //TODO: figure out if this is accessible in COM object if (currentTrack.Year) { currentState['album'] += " (" + currentTrack.Year + ")"; } winax.release(itunes) return currentState } function getCurrentState(){ itunes = Application('iTunes'); playerState = itunes.playerState(); currentState = {}; currentState['player_state'] = playerState; if (playerState != "stopped") { currentTrack = itunes.currentTrack; currentPlaylist = itunes.currentPlaylist; currentState['id'] = currentTrack.persistentID(); currentState['name'] = currentTrack.name(); currentState['artist'] = currentTrack.artist(); currentState['album'] = currentTrack.album(); currentState['playlist'] = currentPlaylist.name(); currentState['volume'] = itunes.soundVolume(); currentState['muted'] = itunes.mute(); currentState['repeat'] = itunes.songRepeat(); currentState['shuffle'] = itunes.shuffleEnabled() && itunes.shuffleMode(); if (currentTrack.year()) { currentState['album'] += " (" + currentTrack.year() + ")"; } } return currentState; } function sendResponse(error, res){ if (error) { console.log(error) res.sendStatus(500) }else{ //osa(getCurrentState, function (error, state) { try { state = win_getCurrentState() res.json(state) } catch(error) { console.log(error) res.sendStatus(500) } } } function win_playPlaylist(nameOrId) { //TODO: find if this is accessible in COM object return false; } function playPlaylist(nameOrId){ itunes = Application('iTunes'); if ((nameOrId - 0) == nameOrId && ('' + nameOrId).trim().length > 0) { id = parseInt(nameOrId); itunes.playlists.byId(id).play(); }else{ itunes.playlists.byName(nameOrId).play(); } return true; } function win_setVolume(level){ itunes = new ActiveXObject('iTunes.Application'); var ret = true; if (level) { itunes.SoundVolume = parseInt(level); } else { ret = false; } winax.release(itunes) return ret; } function setVolume(level){ itunes = Application('iTunes'); if (level) { itunes.soundVolume = parseInt(level); return true; }else { return false; } } function win_setMuted(muted){ itunes = new ActiveXObject('iTunes.Application'); var ret = true; if (muted) { itunes.Mute = muted; } else { ret = false; } winax.release(itunes) return ret; } function setMuted(muted){ itunes = Application('iTunes'); if (muted) { itunes.mute = muted; return true; }else{ return false; } } function win_setShuffle(mode) { //TODO: figure out if com object supports this return false; } function setShuffle(mode){ itunes = Application('iTunes'); if (!mode) { mode = "songs" } if (mode == "false" || mode == "off") { itunes.shuffleEnabled = false; return false; }else{ itunes.shuffleEnabled = true; itunes.shuffleMode = mode; return true; } } function win_setRepeat(mode){ //TODO: figure out if com object supports this return false; } function setRepeat(mode){ itunes = Application('iTunes'); if (!mode) { mode = "all" } if (mode == "false" || mode == "off") { itunes.songRepeat = false; return false; }else{ itunes.songRepeat = mode; return true; } } function win_getPlaylistsFromItunes(){ itunes = new ActiveXObject('iTunes.Application'); playlists = itunes.GetITObjectByID(itunes.LibrarySource.Index,0,0,0).Playlists playlistNames = []; for (var i = 0; i < playlists.length; i++) { playlist = playlists[i]; data = {}; data['id'] = playlist.Index; data['name'] = playlist.Name; data['loved'] = false; //TODO data['duration_in_seconds'] = playlist.Duration; data['time'] = playlist.Time; playlistNames.push(data); } winax.release(itunes); return playlistNames; } function getPlaylistsFromItunes(){ itunes = Application('iTunes'); playlists = itunes.playlists(); playlistNames = []; for (var i = 0; i < playlists.length; i++) { playlist = playlists[i]; data = {}; data['id'] = playlist.id(); data['name'] = playlist.name(); data['loved'] = playlist.loved(); data['duration_in_seconds'] = playlist.duration(); data['time'] = playlist.time(); playlistNames.push(data); } return playlistNames; } function getPlaylists(callback){ data = win_getPlaylistsFromItunes(); //(not sure if this is necessary for win version) for (var i = 0; i < data.length; i++) { data[i]['id'] = parameterize(data[i]['name']) } } app.get('/_ping', function(req, res){ res.send('OK'); }) app.get('/', function(req, res){ res.sendfile('index.html'); }) app.put('/play', function(req, res){ try { itunes = new ActiveXObject('iTunes.Application'); itunes.Play(); winax.release(itunes); sendResponse(null,res); } catch(error) { sendResponse(error, res); } }) app.put('/pause', function(req, res){ try { itunes = new ActiveXObject('iTunes.Application'); itunes.Pause(); sendResponse(null,res); } catch(error) { sendResponse(error, res); } }) app.put('/playpause', function(req, res){ try { itunes = new ActiveXObject('iTunes.Application'); itunes.PlayPause(); winax.release(itunes); sendResponse(null,res); } catch(error) { sendResponse(error, res); } }) app.put('/stop', function(req, res){ try { itunes = new ActiveXObject('iTunes.Application'); itunes.Stop() winax.release(itunes); sendResponse(null,res); } catch(error) { sendResponse(error, res); } }) app.put('/previous', function(req, res){ try { itunes = new ActiveXObject('iTunes.Application'); itunes.PreviousTrack() winax.release(itunes); sendResponse(null,res); } catch(error) { sendResponse(error, res); } }) app.put('/next', function(req, res){ try { itunes = new ActiveXObject('iTunes.Application'); itunes.NextTrack() winax.release(itunes); sendResponse(null,res); } catch(error) { sendResponse(error, res); } }) app.put('/volume', function(req, res){ try { win_setVolume(req.body.level); sendResponse(null,res); } catch(error) { sendResponse(error, res); } }) app.put('/mute', function(req, res){ try { win_setMuted(req.body.muted); sendResponse(null,res); } catch(error) { sendResponse(error, res); } }) app.put('/shuffle', function(req, res){ try { win_setShuffle(req.body.mode); sendResponse(null,res); } catch(error) { sendResponse(error, res); } }) app.put('/repeat', function(req, res){ try { win_setRepeat(req.body.mode); sendResponse(null,res); } catch(error) { sendResponse(error, res); } }) app.get('/now_playing', function(req, res){ error = null sendResponse(error, res) }) app.get('/artwork', function(req, res){ try { var tmpFile = tmp.tmpNameSync() + ".png"; //TODO: handle other formats rather than just assuming png itunes = new ActiveXObject('iTunes.Application'); itunes.CurrentTrack.Artwork(1).SaveArtworkToFile(tmpFile); winax.release(itunes); res.type = 'image/png'; res.sendFile(tmpFile) } catch(error) { sendResponse(error, res) } }) app.get('/playlists', function (req, res) { sendResponse("Not supported",res); return; try { data = getPlaylists(); res.json({playlists: data}); } catch(error) { sendResponse(error,res); } }) app.put('/playlists/:id/play', function (req, res) { sendResponse("Not supported",res); //TODO: add support for win version }) app.get('/airplay_devices', function(req, res){ //sendResponse("Not supported",res); //TODO: add support for win version res.json({'airplay_devices': {}}) }) app.get('/airplay_devices/:id', function(req, res){ sendResponse("Not supported",res); //TODO: add support for win version }) app.put('/airplay_devices/:id/on', function (req, res) { sendResponse("Not supported",res); //TODO: add support for win version }) app.put('/airplay_devices/:id/off', function (req, res) { sendResponse("Not supported",res); //TODO: add support for win version }) app.put('/airplay_devices/:id/volume', function (req, res) { sendResponse("Not supported",res); //TODO: add support for win version }) app.listen(process.env.PORT || 8181);
7244e3e9d70d650776ce1f5f8e2194c64a4bed93
[ "JavaScript" ]
1
JavaScript
diosdog/itunes-win-api
1a15eb98c1d9d0fdd6a011ed5235d8db37f84ab4
230daeebb18f91c8c3ee428ec83479161c13a518
refs/heads/master
<repo_name>gregorybchris/prisoners<file_sep>/README.md # 100 Prisoners Simulation ## Background This project was a collaboration with [<NAME>](https://github.com/tekknolagi/) and [<NAME>](https://github.com/yzan424). After watching this [minutephysics video](https://www.youtube.com/watch?v=eivGlBKlK6M), we decided to code up a simulation to explain the [100 prisoners problem](https://en.wikipedia.org/wiki/100_prisoners_problem). ## Running the Simulation Run a single simulation for 10 iterations with the command `python experiment.py`. To visualize the results of many simulations with different parameter settings run `python viz.py`.<file_sep>/experiment.py import numpy as np class Experiment: def __init__(self, n_boxes, n_checks, random_state=None, cache=None): if random_state is not None: np.random.seed(random_state) self._cache = cache self._n_boxes = n_boxes self._n_checks = n_checks def run(self, n_iterations=1): n_finds_dict = dict() for _ in range(n_iterations): n_finds = self._run_iteration() if n_finds not in n_finds_dict: n_finds_dict[n_finds] = 0 n_finds_dict[n_finds] += 1 if self._cache is not None: self._cache.cache(self._n_boxes, self._n_checks, n_finds_dict) return n_finds_dict def _run_iteration(self): boxes = np.random.permutation(self._n_boxes) cycles = self._preprocess(boxes) n_finds = np.sum([len(c) for c in cycles if len(c) <= self._n_checks]) return n_finds def _preprocess(self, boxes): visited = set() cycles = [] # Try to start a cycle at every box for starting_box in range(len(boxes)): if starting_box not in visited: # Create new cycle cycle = [] box = starting_box while True: cycle.append(box) visited.add(box) box = boxes[box] if box == starting_box: break # Add cycle to the list of cycles cycles.append(cycle) return cycles def get_n_boxes(self): return self._n_boxes def get_n_checks(self): return self._n_checks if __name__ == '__main__': exp = Experiment(100, 50) all_n_finds = exp.run(n_iterations=10) print(all_n_finds) <file_sep>/viz.py import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from experiment import Experiment from cache import ExperimentCache def run_getter(n_boxes, n_checks, cache=None, n_iterations=1): exp = Experiment(n_boxes, n_checks, cache=cache) dist = exp.run(n_iterations=n_iterations) win_rate = dist[n_boxes] / n_iterations if n_boxes in dist else 0 return dist, win_rate def cache_getter(n_boxes, n_checks, cache=None): dist = cache.fetch(n_boxes, n_checks) win_rate = dist[n_boxes] / sum(dist.values()) if n_boxes in dist else 0 return dist, win_rate def grid_search(getter_func, boxes_opts, checks_opts, **kwargs): dist_grid = [[getter_func(n_boxes, n_checks, **kwargs)[0] for n_checks in checks_opts] for n_boxes in boxes_opts] probas_grid = [[getter_func(n_boxes, n_checks, **kwargs)[1] for n_checks in checks_opts] for n_boxes in boxes_opts] return dist_grid, probas_grid def plot_dist(dist): all_n_finds = [n_finds for n_finds, count in dist.items() for _ in range(count)] sns.distplot(all_n_finds, kde=False, bins=20) plt.show() def plot_dist_grid(boxes_opts, checks_opts, dist_grid): samples = [] for b, n_boxes in enumerate(boxes_opts): for c, n_checks in enumerate(checks_opts): dist = dist_grid[b][c] for n_finds, count in dist.items(): for _ in range(count): sample = { 'n_boxes': n_boxes, 'n_checks': n_checks, 'n_finds': n_finds } samples.append(sample) df = pd.DataFrame(samples) facet_grid = sns.FacetGrid(df, row='n_boxes', col='n_checks', margin_titles=True) facet_grid.map(plt.hist, "n_finds", bins=20, color="#4CB391") plt.gcf().canvas.set_window_title('100 Prisoners Problem') plt.show() def plot_contour(boxes_opts, checks_opts, probas_grid): plt.contourf(checks_opts, boxes_opts, probas_grid, 15, cmap='Purples') plt.colorbar() plt.title('Probability space for finding your number') plt.xlabel('Number of checks allowed') plt.ylabel('Number of boxes/people') plt.gcf().canvas.set_window_title('100 Prisoners Problem') plt.show() if __name__ == '__main__': sns.set() boxes_opts = np.linspace(80, 200, 10, dtype=int) checks_opts = np.linspace(10, 70, 6, dtype=int) cache = ExperimentCache('./cache.db') # Grid search by running many experiments # for every combination of parameters n_iterations = 100 dist_grid, probas_grid = grid_search(run_getter, boxes_opts, checks_opts, cache=cache, n_iterations=n_iterations) # Grid search by pulling results from the cache # dist_grid, probas_grid = grid_search(cache_getter, boxes_opts, # checks_opts, cache=cache) # dist = cache.fetch(100, 50) # p_win = dist[100] / sum(dist.values()) # print(f"Probability of winning: {p_win}") # plot_dist(dist) plot_dist_grid(boxes_opts, checks_opts, dist_grid) plot_contour(boxes_opts, checks_opts, probas_grid) <file_sep>/cache.py from sqlitedict import SqliteDict class ExperimentCache: def __init__(self, filename): self._db = SqliteDict(filename, autocommit=True) def cache(self, n_boxes, n_checks, dist): if n_boxes not in self._db: self._db[n_boxes] = dict() box_dict = self._db[n_boxes] if n_checks not in box_dict: box_dict[n_checks] = {} check_dict = box_dict[n_checks] for n_finds, count in dist.items(): if n_finds not in check_dict: check_dict[n_finds] = 0 check_dict[n_finds] += count self._db[n_boxes] = box_dict def fetch(self, n_boxes, n_checks): if n_boxes not in self._db: raise ValueError(f"No cached results for n_boxes={n_boxes}") elif n_checks not in self._db[n_boxes]: raise ValueError(f"No cached results for n_checks={n_checks}") return self._db[n_boxes][n_checks]
9b4c9087ba95a88dba554bc534221425519e3f1b
[ "Markdown", "Python" ]
4
Markdown
gregorybchris/prisoners
bebdf69ec749afb6b705da639d36c98d5c484618
6f8df87b15f6579f96b4d9267904dbe015c0e8a7
refs/heads/master
<file_sep># AWS-Monitoring-Tool-Using-Golang ![alt tag](systemdesign.png) <file_sep>'use strict'; /** * @ngdoc function * @name sbAdminApp.controller:MainCtrl * @description * # MainCtrl * Controller of the sbAdminApp */ angular.module('sbAdminApp') .controller('nInCtrl', ['$scope', '$timeout', '$http' , function ($scope, $timeout,$http) { $http.get('http://localhost:8080/netwrkinput').success (function(response) { var instanceArray = []; var dataArray = []; var metricArray = []; var pushArray = []; var dataArrayTwo =[]; var metricArrayTwo =[]; var count = Object.keys(response).length; console.log(count); for(var i=0 ; i< count ; i++) { console.log("Boom boom" , response[i]); instanceArray.push(response[i].InstanceId); if((response[i].Datapoints).length > 0) { var cnt = Object.keys(response[i].Datapoints).length; console.log("DP cnt is", cnt); } if(i+1!=cnt) { for(var j=0 ; j < cnt;j++) { console.log("i is", i); console.log("j is", j); dataArray.push(response[i].Datapoints[j].Timestamp); metricArray.push(response[i].Datapoints[j].Average); } } else { for(var j=0 ; j < cnt;j++) { console.log("i is", i); console.log("j is", j); //dataArray.push(response[i].Datapoints[j].Timestamp); metricArrayTwo.push(response[i].Datapoints[j].Average); } } } console.log("Instance array is", instanceArray); console.log("Data array ZZZ is", dataArray); console.log("metricArray is", metricArray); $scope.bar = { labels: dataArray, series: instanceArray, data: [metricArray,metricArrayTwo ] }; } ) }]);<file_sep>package main import ( "fmt" "time" "net/http" "github.com/julienschmidt/httprouter" "encoding/json" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/aws-sdk-go/service/cloudwatch" ) type AWSResponse struct { Datapoints []struct { Average float64 `json:"Average"` Maximum interface{} `json:"Maximum"` Minimum interface{} `json:"Minimum"` SampleCount interface{} `json:"SampleCount"` Sum interface{} `json:"Sum"` Timestamp string `json:"Timestamp"` Unit string `json:"Unit"` } `json:"Datapoints"` Label string `json:"Label"` InstanceId string `json:"InstanceId"` } func main() { r := httprouter.New() r.GET("/metrics", getMetrics) r.GET("/cpu" ,getCPUUtilization) r.GET("/netwrkinput",getNetworkInput) r.GET("/netwrkoutput",getNetworkOutput) r.GET("/diskreadops",getDiskReadOps) r.GET("/diskreadbytes",getDiskReadBytes) r.GET("/diskwritebytes",getDiskWriteBytes) r.GET("/memory", getMemoryUtilization) r.GET("/count", getHTTPCount) http.ListenAndServe("localhost:8080",r) } func getMetrics(w http.ResponseWriter, r *http.Request, params httprouter.Params) { svc := ec2.New(session.New()) resp, err := svc.DescribeInstances(nil) if err != nil { panic(err) } // resp has all of the response data, pull out instance IDs: fmt.Println("The Response data is", resp) fmt.Println("> Number of reservation sets: ", len(resp.Reservations)) for idx, res := range resp.Reservations { fmt.Println(" > Number of instances: ", len(res.Instances)) for _, inst := range resp.Reservations[idx].Instances { fmt.Println(" - Instance ID: ", *inst.InstanceId) } } jsonResp, _ := json.Marshal(resp) w.Header().Set("Content-Type", "application/json") w.Header().Set("Access-Control-Allow-Origin", "*") w.WriteHeader(200) fmt.Fprintf(w, "%s", jsonResp) } func getCPUUtilization(w http.ResponseWriter, r *http.Request, params httprouter.Params) { svc := ec2.New(session.New()) resp, err := svc.DescribeInstances(nil) if err != nil { panic(err) } var sliceArray []AWSResponse // resp has all of the response data, pull out instance IDs: //fmt.Println("The Response data is", resp) fmt.Println("> Number of reservation sets: ", len(resp.Reservations)) for idx, res := range resp.Reservations { fmt.Println(" > Number of instances: ", len(res.Instances)) for _, inst := range resp.Reservations[idx].Instances { fmt.Println(" - Instance ID: ", *inst.InstanceId) cw := cloudwatch.New(session.New()) params := &cloudwatch.GetMetricStatisticsInput{ EndTime: aws.Time(time.Now()), // Required MetricName: aws.String("CPUUtilization"), // Required Namespace: aws.String("AWS/EC2"), // Required Period: aws.Int64(3600), // Required StartTime: aws.Time(time.Now().Add(-120 *time.Minute)), // Required Statistics: []*string{ // Required aws.String("Average"), // Required // More values... }, Dimensions: []*cloudwatch.Dimension{ { // Required Name: aws.String("InstanceId"), // Required Value: aws.String(*inst.InstanceId), // Required }, // More values... }, Unit: aws.String("Percent"), } fmt.Println("Params are", params) metrics, err := cw.GetMetricStatistics(params) if err != nil { fmt.Println("Error") return } fmt.Println(metrics) AWS := AWSResponse{} jsonResp, _ := json.Marshal(metrics) err1 := json.Unmarshal(jsonResp, &AWS) fmt.Println("Instance id is", *inst.InstanceId) AWS.InstanceId = *inst.InstanceId fmt.Println("Instance ID inside is" , AWS.InstanceId) sliceArray = append(sliceArray, AWS) if err1!= nil { panic(err1) } } } fmt.Println("Final array is", sliceArray) finalResponse, _ :=json.Marshal(sliceArray) w.Header().Set("Content-Type", "application/json") w.Header().Set("Access-Control-Allow-Origin", "*") w.WriteHeader(200) fmt.Fprintf(w, "%s", finalResponse) } func getNetworkInput(w http.ResponseWriter, r *http.Request, params httprouter.Params) { svc := ec2.New(session.New()) resp, err := svc.DescribeInstances(nil) if err != nil { panic(err) } var sliceArray []AWSResponse // resp has all of the response data, pull out instance IDs: //fmt.Println("The Response data is", resp) fmt.Println("> Number of reservation sets: ", len(resp.Reservations)) for idx, res := range resp.Reservations { fmt.Println(" > Number of instances: ", len(res.Instances)) for _, inst := range resp.Reservations[idx].Instances { fmt.Println(" - Instance ID: ", *inst.InstanceId) cw := cloudwatch.New(session.New()) networkIn := &cloudwatch.GetMetricStatisticsInput{ EndTime: aws.Time(time.Now()), // Required MetricName: aws.String("NetworkIn"), // Required Namespace: aws.String("AWS/EC2"), // Required Period: aws.Int64(3600), // Required StartTime: aws.Time(time.Now().Add(-120 * time.Minute)), // Required Statistics: []*string{ // Required aws.String("Average"), // Required // More values... }, Dimensions: []*cloudwatch.Dimension{ { // Required Name: aws.String("InstanceId"), // Required Value: aws.String(*inst.InstanceId), // Required }, // More values... }, Unit: aws.String("Bytes"), } networkInMetrics, err := cw.GetMetricStatistics(networkIn) if err != nil { fmt.Println("Error") return } fmt.Println(networkInMetrics) AWS := AWSResponse{} jsonResp, _ := json.Marshal(networkInMetrics) err1 := json.Unmarshal(jsonResp, &AWS) fmt.Println("Instance id is", *inst.InstanceId) AWS.InstanceId = *inst.InstanceId fmt.Println("Instance ID inside is" , AWS.InstanceId) sliceArray = append(sliceArray, AWS) if err1!= nil { panic(err1) } } } fmt.Println("Final array is", sliceArray) finalResponse, _ :=json.Marshal(sliceArray) w.Header().Set("Content-Type", "application/json") w.Header().Set("Access-Control-Allow-Origin", "*") w.WriteHeader(200) fmt.Fprintf(w, "%s", finalResponse) } func getNetworkOutput(w http.ResponseWriter, r *http.Request, params httprouter.Params) { svc := ec2.New(session.New()) resp, err := svc.DescribeInstances(nil) if err != nil { panic(err) } var sliceArray []AWSResponse // resp has all of the response data, pull out instance IDs: //fmt.Println("The Response data is", resp) fmt.Println("> Number of reservation sets: ", len(resp.Reservations)) for idx, res := range resp.Reservations { fmt.Println(" > Number of instances: ", len(res.Instances)) for _, inst := range resp.Reservations[idx].Instances { fmt.Println(" - Instance ID: ", *inst.InstanceId) cw := cloudwatch.New(session.New()) networkOut := &cloudwatch.GetMetricStatisticsInput{ EndTime: aws.Time(time.Now()), // Required MetricName: aws.String("NetworkOut"), // Required Namespace: aws.String("AWS/EC2"), // Required Period: aws.Int64(3600), // Required StartTime: aws.Time(time.Now().Add(-120 * time.Minute)), // Required Statistics: []*string{ // Required aws.String("Average"), // Required // More values... }, Dimensions: []*cloudwatch.Dimension{ { // Required Name: aws.String("InstanceId"), // Required Value: aws.String(*inst.InstanceId), // Required }, // More values... }, Unit: aws.String("Bytes"), } networkOutMetrics, err := cw.GetMetricStatistics(networkOut) if err != nil { fmt.Println("Error") return } fmt.Println(networkOutMetrics) AWS := AWSResponse{} jsonResp, _ := json.Marshal(networkOutMetrics) err1 := json.Unmarshal(jsonResp, &AWS) fmt.Println("Instance id is", *inst.InstanceId) AWS.InstanceId = *inst.InstanceId fmt.Println("Instance ID inside is" , AWS.InstanceId) sliceArray = append(sliceArray, AWS) if err1!= nil { panic(err1) } } } fmt.Println("Final array is", sliceArray) finalResponse, _ :=json.Marshal(sliceArray) w.Header().Set("Content-Type", "application/json") w.Header().Set("Access-Control-Allow-Origin", "*") w.WriteHeader(200) fmt.Fprintf(w, "%s", finalResponse) } func getDiskReadOps(w http.ResponseWriter, r *http.Request, params httprouter.Params) { svc := ec2.New(session.New()) resp, err := svc.DescribeInstances(nil) if err != nil { panic(err) } var sliceArray []AWSResponse // resp has all of the response data, pull out instance IDs: //fmt.Println("The Response data is", resp) fmt.Println("> Number of reservation sets: ", len(resp.Reservations)) for idx, res := range resp.Reservations { fmt.Println(" > Number of instances: ", len(res.Instances)) for _, inst := range resp.Reservations[idx].Instances { fmt.Println(" - Instance ID: ", *inst.InstanceId) cw := cloudwatch.New(session.New()) diskReadOps := &cloudwatch.GetMetricStatisticsInput{ EndTime: aws.Time(time.Now()), // Required MetricName: aws.String("DiskReadOps"), // Required Namespace: aws.String("AWS/EC2"), // Required Period: aws.Int64(3600), // Required StartTime: aws.Time(time.Now().Add(-120 * time.Minute)), // Required Statistics: []*string{ // Required aws.String("Average"), // Required // More values... }, Dimensions: []*cloudwatch.Dimension{ { // Required Name: aws.String("InstanceId"), // Required Value: aws.String(*inst.InstanceId), // Required }, // More values... }, Unit: aws.String("Count"), } diskReadOpsMetrics, err := cw.GetMetricStatistics(diskReadOps) if err != nil { fmt.Println("Error") return } fmt.Println(diskReadOpsMetrics) AWS := AWSResponse{} jsonResp, _ := json.Marshal(diskReadOpsMetrics) err1 := json.Unmarshal(jsonResp, &AWS) fmt.Println("Instance id is", *inst.InstanceId) AWS.InstanceId = *inst.InstanceId fmt.Println("Instance ID inside is" , AWS.InstanceId) sliceArray = append(sliceArray, AWS) if err1!= nil { panic(err1) } } } fmt.Println("Final array is", sliceArray) finalResponse, _ :=json.Marshal(sliceArray) w.Header().Set("Content-Type", "application/json") w.Header().Set("Access-Control-Allow-Origin", "*") w.WriteHeader(200) fmt.Fprintf(w, "%s", finalResponse) } func getDiskReadBytes(w http.ResponseWriter, r *http.Request, params httprouter.Params) { svc := ec2.New(session.New()) resp, err := svc.DescribeInstances(nil) if err != nil { panic(err) } var sliceArray []AWSResponse // resp has all of the response data, pull out instance IDs: //fmt.Println("The Response data is", resp) fmt.Println("> Number of reservation sets: ", len(resp.Reservations)) for idx, res := range resp.Reservations { fmt.Println(" > Number of instances: ", len(res.Instances)) for _, inst := range resp.Reservations[idx].Instances { fmt.Println(" - Instance ID: ", *inst.InstanceId) cw := cloudwatch.New(session.New()) diskReadBytes := &cloudwatch.GetMetricStatisticsInput{ EndTime: aws.Time(time.Now()), // Required MetricName: aws.String("DiskReadBytes"), // Required Namespace: aws.String("AWS/EC2"), // Required Period: aws.Int64(3600), // Required StartTime: aws.Time(time.Now().Add(-120 * time.Minute)), // Required Statistics: []*string{ // Required aws.String("Average"), // Required // More values... }, Dimensions: []*cloudwatch.Dimension{ { // Required Name: aws.String("InstanceId"), // Required Value: aws.String(*inst.InstanceId), // Required }, // More values... }, Unit: aws.String("Bytes"), } diskReadBytesMetrics, err := cw.GetMetricStatistics(diskReadBytes) if err != nil { fmt.Println("Error") return } fmt.Println(diskReadBytesMetrics) AWS := AWSResponse{} jsonResp, _ := json.Marshal(diskReadBytesMetrics) err1 := json.Unmarshal(jsonResp, &AWS) fmt.Println("Instance id is", *inst.InstanceId) AWS.InstanceId = *inst.InstanceId fmt.Println("Instance ID inside is" , AWS.InstanceId) sliceArray = append(sliceArray, AWS) if err1!= nil { panic(err1) } } } fmt.Println("Final array is", sliceArray) finalResponse, _ :=json.Marshal(sliceArray) w.Header().Set("Content-Type", "application/json") w.Header().Set("Access-Control-Allow-Origin", "*") w.WriteHeader(200) fmt.Fprintf(w, "%s", finalResponse) } func getDiskWriteBytes(w http.ResponseWriter, r *http.Request, params httprouter.Params) { svc := ec2.New(session.New()) resp, err := svc.DescribeInstances(nil) if err != nil { panic(err) } var sliceArray []AWSResponse // resp has all of the response data, pull out instance IDs: //fmt.Println("The Response data is", resp) fmt.Println("> Number of reservation sets: ", len(resp.Reservations)) for idx, res := range resp.Reservations { fmt.Println(" > Number of instances: ", len(res.Instances)) for _, inst := range resp.Reservations[idx].Instances { fmt.Println(" - Instance ID: ", *inst.InstanceId) cw := cloudwatch.New(session.New()) diskWriteBytes := &cloudwatch.GetMetricStatisticsInput{ EndTime: aws.Time(time.Now()), // Required MetricName: aws.String("DiskWriteBytes"), // Required Namespace: aws.String("AWS/EC2"), // Required Period: aws.Int64(3600), // Required StartTime: aws.Time(time.Now().Add(-120 * time.Minute)), // Required Statistics: []*string{ // Required aws.String("Average"), // Required // More values... }, Dimensions: []*cloudwatch.Dimension{ { // Required Name: aws.String("InstanceId"), // Required Value: aws.String(*inst.InstanceId), // Required }, // More values... }, Unit: aws.String("Bytes"), } diskWriteBytesMetrics, err := cw.GetMetricStatistics(diskWriteBytes) if err != nil { fmt.Println("Error") return } fmt.Println(diskWriteBytesMetrics) AWS := AWSResponse{} jsonResp, _ := json.Marshal(diskWriteBytesMetrics) err1 := json.Unmarshal(jsonResp, &AWS) fmt.Println("Instance id is", *inst.InstanceId) AWS.InstanceId = *inst.InstanceId fmt.Println("Instance ID inside is" , AWS.InstanceId) sliceArray = append(sliceArray, AWS) if err1!= nil { panic(err1) } } } fmt.Println("Final array is", sliceArray) finalResponse, _ :=json.Marshal(sliceArray) w.Header().Set("Content-Type", "application/json") w.Header().Set("Access-Control-Allow-Origin", "*") w.WriteHeader(200) fmt.Fprintf(w, "%s", finalResponse) } func getMemoryUtilization(w http.ResponseWriter, r *http.Request, params httprouter.Params) { svc := ec2.New(session.New()) resp, err := svc.DescribeInstances(nil) if err != nil { panic(err) } var sliceArray []AWSResponse // resp has all of the response data, pull out instance IDs: //fmt.Println("The Response data is", resp) fmt.Println("> Number of reservation sets: ", len(resp.Reservations)) for idx, res := range resp.Reservations { fmt.Println(" > Number of instances: ", len(res.Instances)) for _, inst := range resp.Reservations[idx].Instances { fmt.Println(" - Instance ID: ", *inst.InstanceId) cw := cloudwatch.New(session.New()) memoryStats := &cloudwatch.GetMetricStatisticsInput{ EndTime: aws.Time(time.Now()), // Required MetricName: aws.String("MemoryUtilization"), // Required Namespace: aws.String("System/Linux"), // Required Period: aws.Int64(3600), // Required StartTime: aws.Time(time.Now().Add(-120 * time.Minute)), // Required Statistics: []*string{ // Required aws.String("Average"), // Required // More values... }, Dimensions: []*cloudwatch.Dimension{ { // Required Name: aws.String("InstanceId"), // Required Value: aws.String(*inst.InstanceId), // Required }, // More values... }, } fmt.Println("Memory Stats are",memoryStats) memoryStatsResponse, err := cw.GetMetricStatistics(memoryStats) if err != nil { fmt.Println("Inside Error") return } fmt.Println(memoryStatsResponse) AWS := AWSResponse{} jsonResp, _ := json.Marshal(memoryStatsResponse) err1 := json.Unmarshal(jsonResp, &AWS) fmt.Println("Instance id is", *inst.InstanceId) AWS.InstanceId = *inst.InstanceId fmt.Println("Instance ID inside is" , AWS.InstanceId) sliceArray = append(sliceArray, AWS) if err1!= nil { panic(err1) } } } fmt.Println("Final array is", sliceArray) finalResponse, _ :=json.Marshal(sliceArray) w.Header().Set("Content-Type", "application/json") w.Header().Set("Access-Control-Allow-Origin", "*") w.WriteHeader(200) fmt.Fprintf(w, "%s", finalResponse) } func getHTTPCount(w http.ResponseWriter, r *http.Request, params httprouter.Params) { svc := ec2.New(session.New()) resp, err := svc.DescribeInstances(nil) if err != nil { panic(err) } var sliceArray []AWSResponse // resp has all of the response data, pull out instance IDs: //fmt.Println("The Response data is", resp) fmt.Println("> Number of reservation sets: ", len(resp.Reservations)) for idx, res := range resp.Reservations { fmt.Println(" > Number of instances: ", len(res.Instances)) for _, inst := range resp.Reservations[idx].Instances { fmt.Println(" - Instance ID: ", *inst.InstanceId) cw := cloudwatch.New(session.New()) fmt.Println("CW is", cw) memoryStats := &cloudwatch.GetMetricStatisticsInput{ EndTime: aws.Time(time.Now()), // Required MetricName: aws.String("RequestCount"), // Required Namespace: aws.String("AWS/ELB"), // Required Period: aws.Int64(3600), // Required StartTime: aws.Time(time.Now().Add(-120 * time.Minute)), // Required Statistics: []*string{ // Required aws.String("Sum"), // Required // More values... }, Dimensions: []*cloudwatch.Dimension{ { // Required Name: aws.String("LoadBalancerName"), // Required Value: aws.String("PlsWork"), // Required }, // More values... }, } // fmt.Println("Memory Stats are",memoryStats) memoryStatsResponse, err := cw.GetMetricStatistics(memoryStats) if err != nil { fmt.Println("Inside Error") return } fmt.Println(memoryStatsResponse) AWS := AWSResponse{} jsonResp, _ := json.Marshal(memoryStatsResponse) err1 := json.Unmarshal(jsonResp, &AWS) fmt.Println("Instance id is", *inst.InstanceId) AWS.InstanceId = *inst.InstanceId fmt.Println("Instance ID inside is" , AWS.InstanceId) sliceArray = append(sliceArray, AWS) if err1!= nil { panic(err1) } } } fmt.Println("Final array is", sliceArray) finalResponse, _ :=json.Marshal(sliceArray) w.Header().Set("Content-Type", "application/json") w.Header().Set("Access-Control-Allow-Origin", "*") w.WriteHeader(200) fmt.Fprintf(w, "%s", finalResponse) }
efa676f66ecd05cdc6a15b68d9fceea6dad4ffcd
[ "Markdown", "JavaScript", "Go" ]
3
Markdown
Waynelemars/AWS-Monitoring-Tool-Using-Golang
671ce55df65f8ef6ea06943ada9c28a85b952eba
3f4ff36abe0e79474a1295e4f69311df6f395892
refs/heads/master
<file_sep>using UnityEngine; using UnityEngine.Rendering; #if HAS_URP using UnityEngine.Rendering.Universal; #endif #if HAS_URP namespace ImGuiNET.Unity { public class RenderImGuiFeature : ScriptableRendererFeature { class ExecuteCommandBufferPass : ScriptableRenderPass { public CommandBuffer cmd; public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData) { Camera camera = renderingData.cameraData.camera; //var cmd = CommandBufferPool.Get(m_ProfilerTag); //cmd.SetViewProjectionMatrices(camera.worldToCameraMatrix, camera.projectionMatrix); // JM: Only draw on the main camera (done by tag here) if( camera.tag == "MainCamera") context.ExecuteCommandBuffer(cmd); //CommandBufferPool.Release(cmd); } } ExecuteCommandBufferPass _executeCommandBufferPass; public CommandBuffer commandBuffer; public RenderPassEvent renderPassEvent = RenderPassEvent.AfterRenderingPostProcessing; public override void Create() { _executeCommandBufferPass = new ExecuteCommandBufferPass() { cmd = commandBuffer, renderPassEvent = renderPassEvent, }; } public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingData renderingData) { if (commandBuffer == null) return; _executeCommandBufferPass.renderPassEvent = renderPassEvent; _executeCommandBufferPass.cmd = commandBuffer; renderer.EnqueuePass(_executeCommandBufferPass); } } } #else namespace ImGuiNET.Unity { public class RenderImGuiFeature : UnityEngine.ScriptableObject { public CommandBuffer commandBuffer; } } #endif
66bd8a2739e86a0ae30ae61df5316543dd0e1c04
[ "C#" ]
1
C#
jm-seabery/unity_dear-imgui
da3a68f4ba729800c656d571eb0f8b148a11eebb
f5bbd0a05f6967eb596a2751f6e0486d6f140ae6