branch_name
stringclasses 15
values | target
stringlengths 26
10.3M
| directory_id
stringlengths 40
40
| languages
sequencelengths 1
9
| num_files
int64 1
1.47k
| repo_language
stringclasses 34
values | repo_name
stringlengths 6
91
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
| input
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>guojianping1234/JavaDemo<file_sep>/src/main/java/com/myspringbt/demo/dataSource/DataSourcesConfig.java
package com.myspringbt.demo.dataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
/**
* 对数据源 和mybatis
*/
@Configuration
public class DataSourcesConfig {
@Bean(name = "db1")
@Qualifier("db1")
@ConfigurationProperties(prefix = "spring.datasource.primary") // application.properteis中对应属性的前缀
public DataSource dataSource1() {
return DataSourceBuilder.create().build();
}
@Bean(name = "db2")
@Qualifier("db2")
@Primary
@ConfigurationProperties(prefix = "spring.datasource.secondary") // application.properteis中对应属性的前缀
public DataSource dataSource2() {
return DataSourceBuilder.create().build();
}
}<file_sep>/src/main/java/com/myspringbt/demo/controller/HelloWorld.java
package com.myspringbt.demo.controller;
import io.swagger.annotations.Api;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Controller
@RestController
@RequestMapping("v1/")
@Api("HelloWorldController")
public class HelloWorld {
@GetMapping("helloworld")
public String helloword() {
return "hello world";
}
}
| b74dc6bcfcd6356799a54fab00bd67fed26250ee | [
"Java"
] | 2 | Java | guojianping1234/JavaDemo | df11a62c1f046c22731237b3044b7a829e90e86e | 3e96933f10250f1f203776499631594da4a87971 | |
refs/heads/master | <file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_info.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tclarita <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/01/31 01:00:13 by tclarita #+# #+# */
/* Updated: 2020/02/04 10:03:58 by tclarita ### ########.fr */
/* */
/* ************************************************************************** */
#include "lem_in.h"
void get_ants_num(t_lem *data)
{
char *line;
get_next_line(0, &line);
if (ft_atoi(line) > 0)
{
data->ants = ft_atoi(line);
ft_printf("%s\n", line);
}
else
{
ft_strdel(&line);
ft_exit(data);
}
ft_strdel(&line);
}
void init_connections(t_lem *data)
{
int i;
int l;
data->edge = (int **)malloc(sizeof(int *) * (data->room_num));
i = 0;
while (data->room_num > i)
{
l = 0;
data->edge[i] = (int *)malloc(sizeof(int) * (data->room_num));
while (data->room_num > l)
{
data->edge[i][l] = 0;
l++;
}
i++;
}
data->started = 1;
}
void get_connections(t_lem *data, char *line)
{
char **tmp;
int first;
int second;
if (data->started == 0)
init_connections(data);
first = 0;
second = 0;
tmp = ft_strsplit(line, '-');
while (ft_strcmp(data->rooms[first], tmp[0]) != 0)
first++;
while (ft_strcmp(data->rooms[second], tmp[1]) != 0)
second++;
data->edge[first][second] = 1;
data->edge[second][first] = 1;
free(tmp[0]);
free(tmp[1]);
free(tmp);
}
void find_path(t_lem *data)
{
}
void get_info(t_lem *data)
{
get_ants_num(data);
get_rooms(data);
//? write(1, "\n", 1);
//? ft_printf("Start is: %s\nEnd is: %s\n", data->rooms[0], data->rooms[1]);
//? int i;
//? i = 0;
//? while (i < data->room_num)
//? {
//? ft_printf("%s\n", data->rooms[i]);
//? i++;
//? }
//? i = 0;
//? int l;
//? l = 0;
//? while (data->room_num > i)
//? {
//? while (data->room_num > l)
//? {
//? ft_printf("%3d", data->edge[i][l]);
//? l++;
//? }
//? l = 0;
//? write(1, "\n", 1);
//? i++;
//? }
find_path(data);
}
<file_sep># **************************************************************************** #
# #
# ::: :::::::: #
# Makefile :+: :+: :+: #
# +:+ +:+ +:+ #
# By: tclarita <<EMAIL>> +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ #
# Created: 2019/12/16 16:06:30 by tclarita #+# #+# #
# Updated: 2020/02/04 10:03:19 by tclarita ### ########.fr #
# #
# **************************************************************************** #
NAME = lem_in
SRC = main.c get_info.c tools.c get_rooms.c
OBJ = $(SRC:.c=.o)
HEADER = lem_in.h
FLAGS = -Wall -Werror -Wextra -I $(HEADER)
PRINTF_LIBFT = ft_printf
COLOR = \033[2;14m
.PHONY: clean fclean re all
all: $(NAME)
$(NAME): $(OBJ) $(SRC)
@make -C $(PRINTF_LIBFT)
@gcc -c $(SRC)
@gcc -o $(NAME) $(FLAGS) $(OBJ) ft_printf/libftprintf.a
@make clean -silent
@echo "$(COLOR)Lem_in successfully compiled"
%.o : %.c
@echo "$(NAME) >>> Add/Update $^"
clean:
@rm -rf $(OBJ)
@make clean -C $(PRINTF_LIBFT)
fclean: clean
@rm -rf $(NAME)
@make fclean -C $(PRINTF_LIBFT)
re: fclean all
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_rooms.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tclarita <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/02/04 10:01:30 by tclarita #+# #+# */
/* Updated: 2020/02/04 10:02:41 by tclarita ### ########.fr */
/* */
/* ************************************************************************** */
#include "lem_in.h"
char **get_start_room(t_lem *data, char **tmp, char *line)
{
get_next_line(0, &line);
free(tmp[0]);
free(tmp);
tmp = ft_strsplit(line, ' ');
ft_printf("%s\n", line);
data->rooms[0] = ft_strnew(ft_strlen(tmp[0] + 1));
data->rooms[0] = ft_strcpy(data->rooms[0], tmp[0]);
ft_strdel(&line);
return (tmp);
}
char **get_end_room(t_lem *data, char **tmp, char *line)
{
get_next_line(0, &line);
free(tmp[0]);
free(tmp);
tmp = ft_strsplit(line, ' ');
ft_printf("%s\n", line);
data->rooms[1] = ft_strnew(ft_strlen(tmp[0] + 1));
data->rooms[1] = ft_strcpy(data->rooms[1], tmp[0]);
ft_strdel(&line);
return (tmp);
}
int get_middle_room(int i, t_lem *data, char **tmp)
{
data->rooms[i] = ft_strnew(ft_strlen(tmp[0] + 1));
data->rooms[i] = ft_strcpy(data->rooms[i], tmp[0]);
i++;
data->room_num++;
return (i);
}
void free_tmp(char **tmp)
{
free(tmp[0]);
free(tmp[1]);
free(tmp[2]);
free(tmp);
}
void get_rooms(t_lem *data)
{
char *line;
char **tmp;
int i;
i = 2;
while (get_next_line(0, &line) > 0)
{
ft_printf("%s\n", line);
if (ft_strchr(line, '-'))
get_connections(data, line);
else
{
tmp = ft_strsplit(line, ' ');
if (ft_strcmp(tmp[0], "##start") == 0)
tmp = get_start_room(data, tmp, line);
else if (ft_strcmp(tmp[0], "##end") == 0)
tmp = get_end_room(data, tmp, line);
else if (tmp[0][0] != '#' && tmp[0][0] != 'L')
i = get_middle_room(i, data, tmp);
free_tmp(tmp);
}
ft_strdel(&line);
}
ft_strdel(&line);
}
<file_sep># Lem_In
Lem_In
Still working on it
| 47f040e734cc40f99781302a3eb0f9c6fbc1975b | [
"Markdown",
"C",
"Makefile"
] | 4 | C | iles982/Lem_In | c2058a372f5627a74f527db516d8b669e317e6ec | 6357d50da6f93dac9e818fd6b870b578e603a0ce | |
refs/heads/master | <file_sep># v3schools - Basic HTML Editor
## Functionalities covered
##### 1) List out the programs in dropdown
##### 2) Allow to Edit & Run the code
## Technology Stack
##### HTML, CSS Javascript, Jquery, NodeJS
## Software Requirement
##### NodeJS
##### ExpressJS
##### Chrome Browser
## Steps to Run the app
##### 1) Goto root folder
##### 2) Start Server in command prompt
###### type -> node server.js
##### 3) Run the below URL in Browser
###### localhost:8090
<file_sep>$(document).ready(function() {
app.init();
});
var app = (function(app) {
var _fileList = [];
var _currentSelectedIndex;
app.init = function() {
var ajaxObj = {
url: '/filelist',
type: 'get'
};
_dataProvider(ajaxObj).done(function(response) {
console.log(response);
$('#program-list').empty();
if(Array.isArray(response)) {
_fileList = response;
_fileList.forEach(function(fileName) {
$('#program-list').append('<option>' + fileName + '</option>');
});
app.changeContent();
}
});
};
app.changeContent = function() {
var select = $('#program-list')[0];
if(_currentSelectedIndex != select.selectedIndex) {
_currentSelectedIndex = select.selectedIndex;
var fileName = select.options[select.selectedIndex].text;
app.getSourceFile(fileName);
}
};
app.getSourceFile = function(fileName) {
var ajaxObj = {
url: '/src',
type: 'get',
data: {'fileName': fileName}
};
_dataProvider(ajaxObj).done(function(response) {
$('#code')[0].value = response;
$('#output')[0].srcdoc = response;
});
};
var _dataProvider = function(ajaxObj) {
var promise = $.ajax({
url: ajaxObj.url,
type: ajaxObj.type,
data: ajaxObj.data
});
return promise;
};
app.runCode = function() {
$('#output')[0].srcdoc = $('#code')[0].value;
};
return app;
})({});<file_sep>var express = require('express');
var app = express();
var fs = require('fs');
var path = require('path');
var programDir = './logical Programs/';
app.use('/style', express.static(__dirname + '/style'));
app.use('/js', express.static(__dirname + '/js'));
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
app.get('/filelist', function(req, res) {
res.send(getFileList());
});
app.get('/src', function(req, res) {
var fileList = fs.readdirSync(programDir);
for(var i = 0;i < fileList.length;i++) {
if(path.parse(fileList[i]).name == req.query.fileName) {
res.send(getFile(fileList[i]));
break;
}
}
});
var server = app.listen(8090, function() {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port)
});
function getFileList() {
var fileList = fs.readdirSync(programDir);
for(var i = 0;i < fileList.length;i++) {
fileList[i] = path.parse(fileList[i]).name;
}
console.log(fileList);
return fileList;
}
function getFile(fileBaseName) {
var fileBuffer = fs.readFileSync(programDir + fileBaseName);
return fileBuffer.toString();
} | 47c76df6294e04c0b8deb0d8c26a04486becae79 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | webtech-thozha/v3schools | eed6516a0243042705c4be22d446f021505f5cb0 | 725c211c46caaf9e115d99f5e57fd6c8b441d51c | |
refs/heads/master | <file_sep>#define BOOST_PYTHON_STATIC_LIB
#include <boost/python.hpp>
#include <boost/thread/thread.hpp>
extern double prog;<file_sep>svipul
======
Proof of concept of Python-Boost::Python two-way communication
<file_sep>from django.http import HttpResponse
from django.shortcuts import render
from django.http import HttpResponse
import svipul
from multiprocessing import Process
progress = 0.0
import threading
class SummingThread(threading.Thread):
def run(self):
svipul.work()
def home(request):
# View code here...
return render(request, 'index.html', {})
def work(request):
progress = 0.0
#svipul.work()
p = SummingThread()
p.start()
p.join()
return HttpResponse('done')
def prog(request):
return HttpResponse(str(progress))
def incr_prog():
global progress
progress += 1.0
def f(name):
print 'hello', name
<file_sep>#include "main.hpp"
double prog = 0.0;
double get_prog()
{
return prog;
}
void work()
{
using namespace boost;
python::object views((
python::handle<>(
python::borrowed(PyImport_AddModule("svipul.views")))));
python::object incr_prog = views.attr("incr_prog");
prog = 0.0;
for(int i = 0; i < 30; ++i)
{
boost::this_thread::sleep(boost::posix_time::seconds(1));
prog = i/30.0;
std::cout << prog << std::endl;
incr_prog();
}
}
BOOST_PYTHON_MODULE(svipul)
{
using namespace boost::python;
def("work", work);
scope().attr("prog") = prog;
def("get_prog", get_prog);
}<file_sep> # -*- coding: utf-8 -*-
from bottle import route, run, template, view, static_file
import os.path
import svipul
from multiprocessing import Process
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
def work():
svipul.work()
@route('/')
@view('index')
def index():
return dict()
@route('/work')
def work():
svipul.work()
return "done"
@route('/prog')
def work():
return str(svipul.get_prog())
@route('/static/<filename:path>')
def send_static(filename):
return static_file(filename, root=os.path.join(SITE_ROOT, 'static'))
run(host='localhost', port=8080, reloader=True, server='cherrypy')<file_sep>from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'svipul.views.home', name='home'),
url(r'work$', 'svipul.views.work', name='work'),
url(r'prog$', 'svipul.views.prog', name='prog'),
# url(r'^svipul/', include('svipul.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)),
)
urlpatterns += staticfiles_urlpatterns() | cfbf329b179000dc3e0a00b9eaf1bbb369f7d55b | [
"Markdown",
"Python",
"C++"
] | 6 | C++ | fabiomdiniz/svipul | 095be5011b1130847c15f99425a15fc0c9d58cfb | a30252e9758abb8dcf5627f8fa501ea0281933bc | |
refs/heads/master | <file_sep>var bio = {
'name': 'Tania',
'role': 'Java Developer',
'contacts': {
'mobile': '029838882',
'email': '<EMAIL>',
'github': 'stromnt',
'twitter': '#stromnt',
'location': '5 Martin Crescent, Westville, South Africa'
},
'welcomeMessage': 'Welcome to my home page',
'skills': ['java', 'C', 'Oracle', 'SAP', 'BW', 'html5', 'css3', 'javascript', 'AngularJS'],
'biopic': 'images/myProfile.jpg',
'display': function () {
$('#header').prepend(HTMLheaderRole.replace('%data%', bio.role));
$('#header').prepend(HTMLheaderName.replace('%data%', bio.name));
//header contact details
$('#topContacts').append(HTMLmobile.replace('%data%', bio.contacts.mobile));
$('#topContacts').append(HTMLemail.replace('%data%', bio.contacts.email));
$('#topContacts').append(HTMLgithub.replace('%data%', bio.contacts.github));
$('#topContacts').append(HTMLtwitter.replace('%data%', bio.contacts.twitter));
$('#topContacts').append(HTMLlocation.replace('%data%', bio.contacts.location));
//footer contact details
$('#footerContacts').append(HTMLmobile.replace('%data%', bio.contacts.mobile));
$('#footerContacts').append(HTMLemail.replace('%data%', bio.contacts.email));
$('#footerContacts').append(HTMLgithub.replace('%data%', bio.contacts.github));
$('#footerContacts').append(HTMLtwitter.replace('%data%', bio.contacts.twitter));
$('#footerContacts').append(HTMLlocation.replace('%data%', bio.contacts.location));
$('#header').append(HTMLbioPic.replace('%data%', bio.biopic));
$('#header').append(HTMLwelcomeMsg.replace('%data%', bio.welcomeMessage));
//skills
$('#header').append(HTMLskillsStart);
if ( bio.skills && bio.skills.length > 0 ) {
bio.skills.forEach( function(skill){
$('#skills').append(HTMLskills.replace('%data%', skill));
});
}
}
};
bio.display();
var education = {
'schools': [
{
'name': 'WGHS',
'location': '12 Westville Road, Westville, South Africa',
'degree': 'NSC',
'majors': ['Maths', 'Physical Science', 'Biology', 'History', 'English', 'Afrikaans'],
'dates': '1982-1986',
'url': 'www.wghs.co.za'
},
{
'name': 'UCT',
'location': 'Rondebosch, Cape Town, South Africa',
'degree': 'BSc',
'majors': ['Maths', 'Computer Science'],
'dates': '1987-1989',
'url': 'www.uct.ac.za'
}
],
'onlineCourses': [
{
'title': 'Web Developer',
'school': 'Udacity',
'dates': '2016-2017',
'url': 'www.udacity.com'
},
{
'title': 'Java 8 Lambdas',
'school': 'Safari Books',
'dates': '2015',
'url': 'www.safaribooks.com'
}
],
'display': function () {
if ( education.schools && education.schools.length > 0 ) {
education.schools.forEach(function(school){
$('#education').append(HTMLschoolStart);
var educationentry = HTMLschoolName.replace('%data%', school.name ).replace('#', school.url);
educationentry += HTMLschoolDegree.replace('%data%', school.degree);
educationentry += HTMLschoolDates.replace('%data%', school.dates);
educationentry += HTMLschoolLocation.replace('%data%', school.location);
var majors = '';
school.majors.forEach( function(major){
majors += major + ' ';
});
educationentry += HTMLschoolMajor.replace('%data%', majors);
$('.education-entry:last').html(educationentry);
});
}
if ( education.onlineCourses && education.onlineCourses.length > 0 ) {
$('#education').append(HTMLonlineClasses);
education.onlineCourses.forEach( function(online){
$('#education').append(HTMLschoolStart);
var onlineEntry = HTMLonlineTitle.replace('%data%', online.title);
onlineEntry += HTMLonlineSchool.replace('%data%', online.school);
onlineEntry += HTMLonlineDates.replace('%data%', online.dates);
onlineEntry += HTMLonlineURL.replace('%data%', online.url);
$('.education-entry:last').html(onlineEntry);
});
}
}
};
education.display();
var work = {
'jobs': [
{
'employer': 'CHEP',
'title': 'Senior Java Developer',
'location': 'Durban, South Africa',
'dates': '1999-present',
'description': 'Develop java mid-tier (rest) and backend (jax-ws soap) interfaces between SAP, BW, Siebel and Oracle and company portal.'
},
{
'employer': '<NAME>',
'title': 'Analyst Programmer',
'location': 'Trinity Square, London, UK',
'dates': '1995-1995',
'description': 'Develop mainly C interfaces between core Wang and Insurer desktop systems'
},
{
'employer': '<NAME>',
'title': 'Analyst Programmer',
'location': 'Durban, South Africa',
'dates': '1990-1995',
'description': 'Developed statictical analytical programs in Fortran and C (X-11 Arima)'
}
],
'display': function () {
if ( work.jobs && work.jobs.length > 0 ) {
work.jobs.forEach( function(job){
$('#workExperience').append(HTMLworkStart);
var workentry = HTMLworkEmployer.replace('%data%', job.employer);
workentry += HTMLworkTitle.replace('%data%', job.title);
workentry += HTMLworkDates.replace('%data%', job.dates);
workentry += HTMLworkLocation.replace('%data%', job.location);
workentry += HTMLworkDescription.replace('%data%', job.description);
$('.work-entry:last').html(workentry);
});
}
}
};
work.display();
var projects = {
'projects': [
{
'title': 'Really Awesome Project 1',
'dates': '1992',
'description': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque ligula leo, eleifend finibus enim eget, malesuada ornare nulla. In iaculis, dolor id condimentum porttitor, augue dolor vestibulum ligula, eget tincidunt sem metus vel diam. Maecenas sagittis mauris sed nisl condimentum interdum. Nam interdum nulla et est blandit, eget tempor odio luctus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque tincidunt nisl diam, et viverra neque mollis ut. Nunc commodo dignissim elit ac condimentum. Proin dictum efficitur cursus. Vivamus euismod elit nisi, nec pharetra velit tincidunt quis. Nulla tristique fringilla velit eget mollis. Nunc varius nulla a dignissim vulputate. Quisque nec lacinia erat, et vulputate quam.',
'images': [
'images/project1.1.jpg',
'images/project1.2.jpg'
]
},
{
'title': 'Change the World - Peace and Tranquility',
'dates': '1998',
'description': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque ligula leo, eleifend finibus enim eget, malesuada ornare nulla. In iaculis, dolor id condimentum porttitor, augue dolor vestibulum ligula, eget tincidunt sem metus vel diam. Maecenas sagittis mauris sed nisl condimentum interdum. Nam interdum nulla et est blandit, eget tempor odio luctus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque tincidunt nisl diam, et viverra neque mollis ut. Nunc commodo dignissim elit ac condimentum. Proin dictum efficitur cursus. Vivamus euismod elit nisi, nec pharetra velit tincidunt quis. Nulla tristique fringilla velit eget mollis. Nunc varius nulla a dignissim vulputate. Quisque nec lacinia erat, et vulputate quam.',
'images': [
'images/project2.1.jpg'
]
}
],
'display': function () {
if ( projects.projects && projects.projects.length > 0 ) {
projects.projects.forEach( function (project) {
// for (var project of projects.projects) {
$('#projects').append(HTMLprojectStart);
var projectentry = HTMLprojectTitle.replace('%data%', project.title);
projectentry += HTMLprojectDates.replace('%data%', project.dates);
projectentry += HTMLprojectDescription.replace('%data%', project.description);
project.images.forEach( function (image){
projectentry += HTMLprojectImage.replace('%data%', image);
});
$('.project-entry:last').html(projectentry);
});
}
}
};
projects.display();
$('#mapDiv').append(googleMap);
// $('body').append(internationalizeButton);
// var inName = function( name) {
// var names = name.split(' ');
// return names[0].charAt(0).toUpperCase() + names[0].substring(1) + ' ' + names[1].toUpperCase();
// };
| e0bf78418be5c0f5e50f7ad790655cc565b02ca1 | [
"JavaScript"
] | 1 | JavaScript | stromnt/frontend-nanodegree-resume | 9555a1692a529b8dca54cf7c8cd68b5147ca5826 | abf4e59a32267b22de2c53503c61ced6e5ccefad | |
refs/heads/main | <file_sep>package com.example.demo.mapper;
import com.example.demo.model.User;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface UserMapper {
public User login(String username, String password);
public int register(User user);
public int del(String[] ids);
// 查询接口(无分页)
public List<User> getUser(String name,
String address,
String email);
// 查询所有用户,有分页
public List<User> getUserByPage(int sindex,
int psize,
String name,
String address,
String email,
Integer isadmin);
// 查询所有用户的条数
public int getUserCount(String name,
String address,
String email,
Integer isadmin);
User getUserById(Integer id);
int update(User user);
int add(User user);
}
<file_sep># Usermanager
用户管理系统
项目功能描述:
基于SpringBoot和MyBaties实现的用户信息管理系统
核心流程:
(1)打开登陆页面,可以根据账号密码登录普通管理员与超级管理员;
(2)登陆后,超级管理员可以查看所有用户的信息,并可以添加超级管理员与普通管理员账户;普通管理员可以查看除超级管理员外所有用户信息,尽可以添加普通管理员账户;
(3)根据用户的某些信息精确查询用户,也可以通过片段信息模糊查询。
| 28319a287173336f806333ec6ba4a693b15175a0 | [
"Markdown",
"Java"
] | 2 | Java | milandexiaohonghei/Usermanager | a04fcd22902a1538ec510c9c0c80aed674323ce4 | c79a98ea23c2a77231d7ee1240cc18ad16743e7a | |
refs/heads/master | <repo_name>kap256/CookieTools<file_sep>/test.js
function rawFormatter(val) { return Math.round(val * 1000) / 1000; }
var formatLong = [' thousand', ' million', ' billion', ' trillion', ' quadrillion', ' quintillion', ' sextillion', ' septillion', ' octillion', ' nonillion'];
var prefixes = ['', 'un', 'duo', 'tre', 'quattuor', 'quin', 'sex', 'septen', 'octo', 'novem'];
var suffixes = ['decillion', 'vigintillion', 'trigintillion', 'quadragintillion', 'quinquagintillion', 'sexagintillion', 'septuagintillion', 'octogintillion', 'nonagintillion'];
for (var i in suffixes) {
for (var ii in prefixes) {
formatLong.push(' ' + prefixes[ii] + suffixes[i]);
}
}
var formatShort = ['k', 'M', 'B', 'T', 'Qa', 'Qi', 'Sx', 'Sp', 'Oc', 'No'];
var prefixes = ['', 'Un', 'Do', 'Tr', 'Qa', 'Qi', 'Sx', 'Sp', 'Oc', 'No'];
var suffixes = ['D', 'V', 'T', 'Qa', 'Qi', 'Sx', 'Sp', 'O', 'N'];
for (var i in suffixes) {
for (var ii in prefixes) {
formatShort.push(' ' + prefixes[ii] + suffixes[i]);
}
}
formatShort[10] = 'Dc';
function formatEveryThirdPower(notations) {
return function (val) {
var base = 0, notationValue = '';
if (!isFinite(val)) return 'Infinity';
if (val >= 1000000) {
val /= 1000;
while (Math.round(val) >= 1000) {
val /= 1000;
base++;
}
if (base >= notations.length) { return 'Infinity'; } else { notationValue = notations[base]; }
}
return (Math.round(val * 1000) / 1000) + notationValue;
};
}<file_sep>/README.md
# 好みの問題
CookieToolsの恒河沙以降の表記を好みにあわせたかっただけなのです。
# CookieTools
CookieClicker extension tools
https://github.com/hideki0403/CookieTools
| a1a29a5c93b8878ac893fe2ecdcc3be4211501d3 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | kap256/CookieTools | 1a7bc2371a9d417621404264047c74665cd4a136 | 1ebd40d8d49e458055f08722affd1ea3827f8538 | |
refs/heads/master | <repo_name>hkage/git-tools<file_sep>/commands/git-lost-commits
#!/usr/bin/env python3
import argparse
import subprocess
# Copied from SO http://stackoverflow.com/questions/287871/print-in-terminal-with-colors-using-python
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
def get_commits():
p = subprocess.Popen(['git', '--no-pager', 'log', '--decorate=short',
'--pretty=format:%h;%ci;%an;%s', '--all'],
stdout=subprocess.PIPE)
return p.stdout.readlines()
def get_branches_containing_commit(revision):
p = subprocess.Popen(['git', 'branch', '-r', '--contains', revision],
stdout=subprocess.PIPE)
return p.stdout.readlines()
def main():
try:
for line in get_commits():
data = line.split(b';')
revision = data[0]
creation_time = data[1][:19]
author = data[2].replace(b'\n', b'')
message = '%s...' % data[3].replace(b'\n', b'')[:60]
branches = get_branches_containing_commit(revision)
if len(branches) > 0:
continue
print(creation_time, FAIL, revision, ENDC, OKBLUE, author, ENDC, message)
except KeyboardInterrupt:
print("Terminated")
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Script to check for potential'
' missing commits.')
args = parser.parse_args()
main()
<file_sep>/README.md
# git-tools
git-lost-commits will look for commits that were pushed to the git server but are potentially not part of any remote branch.
## Requirements
* Python 3
* Flake8
* git installed
## git hooks
### pre-commit-python
This is a git pre-commit hook, that will do some Python/Django specific validation checks:
* Flake8 checks for the changed files
* Check for Python debug statements (ipbd/pdb)
* Check for fuzzy translations in PO files
## git-lost-commits
### Usage
Simply type:
$ ./git-lost-commits
and the result should look like this e.g.:
b'2017-03-09 16:20:20' b'4c7c37c' b'H<NAME>' b"Merge branch 'feature/abc' into development"...
b'2017-03-09 14:59:43' b'ebe9be0' b'Henning Kage' b"Merge branch 'feature/def' into 'feature/abc'"...
b'2017-03-09 14:29:00' b'2d2b740' b'H<NAME>' b"Merge branch 'development' into feature/abc"...
| e1022d860500dbd5f55c7598df66353d46bdc882 | [
"Markdown",
"Python"
] | 2 | Python | hkage/git-tools | 921369d064bf2986bbe2c5a910c4a937ee76680b | 5ce4e2e80a7c7b4ddc950287a41e4551e8455f41 | |
refs/heads/master | <repo_name>rogerbraun/QuickImage<file_sep>/config.ru
require "./app.rb"
require "rack/timeout"
use Rack::Timeout
Rack::Timeout.timeout = 5
run Sinatra::Application
<file_sep>/app.rb
require "rubygems"
require "bundler"
require "open-uri"
require "cgi"
Bundler.require
get "/" do
redirect "/index.html"
end
get "/favicon.ico" do
halt 404
end
get "/image/:key/:width/:height/hier" do
file = get_random_file params[:key]
file = add_hier file
send_file file
end
get "/image/:key/:width/:height" do
file = get_random_file params[:key]
send_file file
end
def add_hier file
`composite label:HIER!!!! -gravity center #{file} #{file}_hier.jpg`
file + "_hier.jpg"
end
def get_random_file keyword
converted = false
while not converted do
result = random_result keyword
result_base = File.basename(result)
x_y = params[:width] + "x" + params[:height]
filename = result_base + "_" + x_y + ".jpg"
unless File.exists?(File.join("tmp", result_base))
`wget -P tmp #{result}`
`convert -resize #{x_y} -extent #{x_y} -gravity center tmp/#{result_base} tmp/#{filename}`
end
converted = true if File.exists?(File.join("tmp",filename))
end
File.join "tmp", filename
end
def search keyword
url = "https://www.google.com/search?q=#{CGI::escape keyword}&tbm=isch"
results = open(url).read.scan /imgurl=(.+?)&/
results.flatten
end
def random_result keyword
res = search keyword
pick = res[rand(res.size)]
end
<file_sep>/Gemfile
source :rubygems
gem "sinatra"
gem "rack-timeout"
gem "nokogiri"
| 35105571b33e1b018da4ef760d38554a2b12fd07 | [
"Ruby"
] | 3 | Ruby | rogerbraun/QuickImage | 55fd5d6f04c462626692dc3f31d0088b3dcd91f0 | a3b9f7f92c7f902c4404b9712fabcef217e78b7c | |
refs/heads/master | <repo_name>SPuerBRead/Small-tools<file_sep>/SubDomainQuery.py
import argparse
import requests
import re
class SubDomainQuery():
def __init__(self):
UrlList = []
def Query(self,url):
data = {'domain':url,'b2':1,'b3':1,'b4':1}
Queryre = requests.post('http://i.links.cn/subdomain/',data = data)
file = Queryre.text
data = re.compile(r'<div class=domain><input type=hidden name=domain(.*?) id=domain(.*?) value="(.*?)"><input type=hidden name=domainlevel(.*?) id=domainlevel')
UrlList = re.findall(data,file)
fopen = open(url+'.txt','w+')
count = 0
for i in UrlList:
count+=1
print "%s:\t%s" %(count,i[2])
fopen.write(i[2]+'\n')
fopen.close()
if __name__ == '__main__':
parse = argparse.ArgumentParser()
parse.add_argument('-u',dest = 'url',help = 'Query url')
args = parse.parse_args()
url = args.url
scan = SubDomainQuery()
scan.Query(url)<file_sep>/PortScan.py
from __future__ import division
from itertools import product, islice
from os import linesep
import time
import argparse
import socket
import sys
import Queue
import threading
class Pscan():
def __init__(self,start_ip,stop_ip,thread_num,ip,allscan):
self.start_ip = start_ip
self.stop_ip = stop_ip
self.thread_num = thread_num
self.IpQueue = Queue.Queue()
self.Portlist = ['21','22','23','53','80','81','137','389','443','873','1090','1098','1099','1352','1433',
'1521','2049','2181','3306','3389','3700','4444','4445','4848','5000','5432','5632','5900','5901',
'5902','6379','7001','8020','8021','8080','8009','8069','8083','8093','9080','9081','9090','9200',
'9300','11211','27017','50070']
self.mutex = threading.Lock()
self.livelist = []
self.singleIP = ip
self.Detection = allscan
self.PortQueue = Queue.Queue()
self.iplist = []
def get_ip(self,tofile='/tmp/ip_list.txt'):
print 'Generating a dictionary ...'
fmt="%s.%s.%s.%s" #+linesep
if int(self.start_ip.split('.')[0]) < int(self.stop_ip.split('.')[0]):
p1 = xrange(int(self.start_ip.split('.')[0]),int(self.stop_ip.split('.')[0])+1)
p2 = xrange(int(self.start_ip.split('.')[1]),256)
p3 = xrange(int(self.start_ip.split('.')[2]),256)
p4 = xrange(int(self.start_ip.split('.')[3]),256)
elif int(self.start_ip.split('.')[1]) < int(self.stop_ip.split('.')[1]):
p1 = xrange(int(self.start_ip.split('.')[0]),int(self.stop_ip.split('.')[0])+1)
p2 = xrange(int(self.start_ip.split('.')[1]),int(self.stop_ip.split('.')[1])+1)
p3 = xrange(int(self.start_ip.split('.')[2]),256)
p4 = xrange(int(self.start_ip.split('.')[3]),256)
elif int(self.start_ip.split('.')[2]) < int(self.stop_ip.split('.')[2]):
p1 = xrange(int(self.start_ip.split('.')[0]),int(self.stop_ip.split('.')[0])+1)
p2 = xrange(int(self.start_ip.split('.')[1]),int(self.stop_ip.split('.')[1])+1)
p3 = xrange(int(self.start_ip.split('.')[2]),int(self.stop_ip.split('.')[2])+1)
p4 = xrange(int(self.start_ip.split('.')[3]),256)
elif int(self.start_ip.split('.')[3]) < int(self.stop_ip.split('.')[3]):
p1 = xrange(int(self.start_ip.split('.')[0]),int(self.stop_ip.split('.')[0])+1)
p2 = xrange(int(self.start_ip.split('.')[1]),int(self.stop_ip.split('.')[1])+1)
p3 = xrange(int(self.start_ip.split('.')[2]),int(self.stop_ip.split('.')[2])+1)
p4 = xrange(int(self.start_ip.split('.')[3]),int(self.stop_ip.split('.')[3])+1)
#open(tofile,'w',256*1024).writelines(
# (fmt % tuple(i) for i in islice(product(p1,p2,p3,p4), None,None))
# )
for i in islice(product(p1,p2,p3,p4), None,None):
self.IpQueue.put(fmt % tuple(i))
self.iplist.append(fmt % tuple(i))
def listip_scan(self):
thread = threading.current_thread()
while(1):
try:
ip = self.IpQueue.get(timeout = 1)
except:
break
for port in self.Portlist:
self.mutex.acquire()
sys.stderr.write('test: '+ ip +':'+ port+' \r')
self.mutex.release()
host = (ip,int(port))
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.3)
try:
sock.connect(host)
self.mutex.acquire()
try:
data = sock.recv(1024)
sys.stderr.write('[+] '+ip+':'+port+' open\t'+str(data).strip().encode('utf-8')+'\n')
self.livelist.append(ip+':'+port+':'+str(data).strip().encode('utf-8'))
except:
sys.stderr.write('[+] '+ip+':'+port+' open\t\n')
self.livelist.append(ip+':'+port)
self.mutex.release()
except:
pass
sock.close()
def StartThread(self,way):
threadlist = []
for i in range(int(self.thread_num)):
T = threading.Thread(target = way)
T.start()
threadlist.append(T)
for Th in threadlist:
Th.join()
return self.livelist
def singleip_scan(self):
while(1):
try:
port = self.PortQueue.get(timeout = 1)
except:
break
self.mutex.acquire()
sys.stderr.write('test: '+ self.singleIP +':'+ str(port)+' \r')
self.mutex.release()
host = (self.singleIP,int(port))
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.3)
try:
sock.connect(host)
self.mutex.acquire()
try:
data = sock.recv(1024)
sys.stderr.write('[+] '+self.singleIP+':'+str(port)+' open\t'+str(data).strip().encode('utf-8')+'\n')
self.livelist.append(ip+':'+port+':'+str(data).strip().encode('utf-8'))
except:
sys.stderr.write('[+] '+self.singleIP+':'+str(port)+' open\t\n')
self.livelist.append(self.singleIP+':'+str(port))
self.mutex.release()
except:
pass
sock.close()
def run(self):
relist = []
if self.singleIP:
self.iplist.append(self.singleIP)
if self.Detection:
for i in range(65536):
self.PortQueue.put(i)
else:
for i in self.Portlist:
self.PortQueue.put(i)
relist = self.StartThread(self.singleip_scan)
else:
self.get_ip()
relist = self.StartThread(self.listip_scan)
return relist
def WriteReport(self):
filename = str(time.strftime("%Y-%m-%d-%H-%M-%S",time.localtime(time.time())))
html = open('%s.html' %filename,'w')
html.write("""
<html>
<head>
<title>Report</title>
</head>
<body>
<h1 align="center">Pscan v1.0</h1>
<p style="text-align:right">2016.9.17 by <EMAIL></p>
<hr style="height:1px;border:none;border-top:1px dashed #0066CC;" />
""")
for i in self.iplist:
flag = 0
for j in self.livelist:
if j.split(':')[0] == i:
if flag == 0:
html.write('<h2>%s</h2>' %j.split(':')[0])
html.write('<hr style="height:1px;border:none;border-top:1px dashed #0066CC;" />')
flag = 1
if len(j.split(':'))>2:
html.write(r'<li><a href="http://%s">%s</a>%s</li>' %(j.split(':')[0]+':'+j.split(':')[1],j.split(':')[0]+':'+j.split(':')[1],' '+j.split(':')[2]))
else:
html.write(r'<li><a href="http://%s">%s</a></li>' %(j,j))
html.write('</body></html>')
html.close()
def main(start_ip,stop_ip,thread_num,ip,allscan):
relist = []
scan = Pscan(start_ip,stop_ip,thread_num,ip,allscan)
relist = scan.run()
scan.WriteReport()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
eg = '''
Usage: python PPscan.py --start 1.1.1.1 --stop 2.2.2.2 [-t]
or
python PPscan.py -i 1.1.1.1 [-a] [-t]
'''
parser.add_argument('--start',dest = 'start_ip',help = 'Start IP')
parser.add_argument('--stop',dest = 'stop_ip',help = 'Stop IP')
parser.add_argument('-t',dest = 'thread_num',type = int,default = 1,help = 'thread num')
parser.add_argument('-i',dest = 'ip',help = 'single ip scan')
parser.add_argument('-a',dest = 'all',action = 'store_true',default = False,help = 'scan all port')
args = parser.parse_args()
start_ip = args.start_ip
stop_ip = args.stop_ip
thread_num = args.thread_num
ip = args.ip
allscan = args.all
if start_ip == None and ip == None:
print eg
else:
start = time.time()
main(start_ip,stop_ip,thread_num,ip,allscan)
end = time.time()
print '\nruntime: '+str(end - start)
| 1774eaffb1c2e39996ad32a3dae7f1e3b0a8f2ac | [
"Python"
] | 2 | Python | SPuerBRead/Small-tools | 4548d6f03ca7907236f8c97bd556d5d61d43a782 | 76e3ef0ead47098482a736de07e1437e1c3dbb17 | |
refs/heads/master | <repo_name>prise-3d/Thesis-Denoising-autoencoder<file_sep>/image_denoising.py
# main imports
import os
import json
import pandas as pd
import numpy as np
import argparse
# model imports
from keras.layers import Input, Conv3D, MaxPooling3D, UpSampling3D
from keras.models import Model
from keras import backend as K
from keras.callbacks import TensorBoard
from sklearn.utils import shuffle
# image processing imports
import cv2
# modules imports
import custom_config as cfg
def generate_model(input_shape):
input_img = Input(shape=input_shape) # adapt this if using `channels_first` image data format
x = Conv3D(32, (1, 3, 3), activation='relu', padding='same')(input_img)
x = MaxPooling3D((1, 2, 2), padding='same')(x)
x = Conv3D(32, (1, 3, 3), activation='relu', padding='same')(x)
x = MaxPooling3D((1, 2, 2), padding='same')(x)
x = Conv3D(32, (1, 3, 3), activation='relu', padding='same')(x)
encoded = MaxPooling3D((1, 2, 2), padding='same')(x)
print(encoded)
x = Conv3D(32, (1, 3, 3), activation='relu', padding='same')(encoded)
x = UpSampling3D((1, 2, 2))(x)
x = Conv3D(32, (1, 3, 3), activation='relu', padding='same')(x)
x = UpSampling3D((1, 2, 2))(x)
x = Conv3D(32, (1, 3, 3), activation='relu', padding='same')(x)
x = UpSampling3D((1, 2, 2))(x)
decoded = Conv3D(3, (1, 3, 3), activation='sigmoid', padding='same')(x)
autoencoder = Model(input_img, decoded)
autoencoder.compile(optimizer='adadelta', loss='mse')
return autoencoder
def main():
# load params
parser = argparse.ArgumentParser(description="Train Keras model and save it into .json file")
parser.add_argument('--data', type=str, help='dataset filename prefix (without .train and .test)', required=True)
parser.add_argument('--output', type=str, help='output file name desired for model (without .json extension)', required=True)
parser.add_argument('--batch_size', type=int, help='batch size used as model input', default=cfg.keras_batch)
parser.add_argument('--epochs', type=int, help='number of epochs used for training model', default=cfg.keras_epochs)
args = parser.parse_args()
p_data_file = args.data
p_output = args.output
p_batch_size = args.batch_size
p_epochs = args.epochs
# load data from `p_data_file`
########################
# 1. Get and prepare data
########################
print("Preparing data...")
dataset_train = pd.read_csv(p_data_file + '.train', header=None, sep=";")
dataset_test = pd.read_csv(p_data_file + '.test', header=None, sep=";")
print("Train set size : ", len(dataset_train))
print("Test set size : ", len(dataset_test))
# default first shuffle of data
dataset_train = shuffle(dataset_train)
dataset_test = shuffle(dataset_test)
print("Reading all images data...")
# getting number of chanel
n_channels = len(dataset_train[1][1].split('::'))
print("Number of channels : ", n_channels)
img_width, img_height = cfg.keras_img_size
# specify the number of dimensions
if K.image_data_format() == 'channels_first':
if n_channels > 1:
input_shape = (1, n_channels, img_width, img_height)
else:
input_shape = (n_channels, img_width, img_height)
else:
if n_channels > 1:
input_shape = (1, img_width, img_height, n_channels)
else:
input_shape = (img_width, img_height, n_channels)
# `:` is the separator used for getting each img path
if n_channels > 1:
dataset_train[1] = dataset_train[1].apply(lambda x: [cv2.imread(path, cv2.IMREAD_GRAYSCALE) for path in x.split('::')])
dataset_test[1] = dataset_test[1].apply(lambda x: [cv2.imread(path, cv2.IMREAD_GRAYSCALE) for path in x.split('::')])
else:
dataset_train[1] = dataset_train[1].apply(lambda x: cv2.imread(x, cv2.IMREAD_GRAYSCALE))
dataset_test[1] = dataset_test[1].apply(lambda x: cv2.imread(x, cv2.IMREAD_GRAYSCALE))
x_dataset_train = dataset_train[1].apply(lambda x: np.array(x).reshape(input_shape))
x_dataset_test = dataset_test[1].apply(lambda x: np.array(x).reshape(input_shape))
y_dataset_train = dataset_train[0].apply(lambda x: cv2.imread(x).reshape(input_shape))
y_dataset_test = dataset_test[0].apply(lambda x: cv2.imread(x).reshape(input_shape))
# format data correctly
x_data_train = np.array([item[0].reshape(input_shape) for item in x_dataset_train.values])
x_data_test = np.array([item[0].reshape(input_shape) for item in x_dataset_test.values])
y_data_train = np.array([item[0].reshape(input_shape) for item in y_dataset_train.values])
y_data_test = np.array([item[0].reshape(input_shape) for item in y_dataset_test.values])
# load model
autoencoder = generate_model(input_shape)
# tensorboard --logdir=/tmp/autoencoder
autoencoder.fit(x_data_train, y_data_train,
epochs=100,
batch_size=32,
shuffle=True,
validation_data=(x_data_test, y_data_test),
callbacks=[TensorBoard(log_dir='/tmp/autoencoder', histogram_freq=0, write_graph=False)])
##############
# save model #
##############
if not os.path.exists(cfg.saved_models_folder):
os.makedirs(cfg.saved_models_folder)
# save the model into HDF5 file
model_output_path = os.path.join(cfg.saved_models_folder, p_output + '.json')
json_model_content = autoencoder.to_json()
with open(model_output_path, 'w') as f:
print("Model saved into ", model_output_path)
json.dump(json_model_content, f, indent=4)
autoencoder.save_weights(model_output_path.replace('.json', '.h5'))
if __name__ == "__main__":
main()<file_sep>/generate/generate_dataset.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 19 11:47:42 2019
@author: jbuisine
"""
# main imports
import sys, os, argparse
import numpy as np
import random
# images processing imports
from PIL import Image
from ipfml.processing.segmentation import divide_in_blocks
# modules imports
sys.path.insert(0, '') # trick to enable import of main folder module
import custom_config as cfg
from modules.utils import data as dt
from modules.classes.Transformation import Transformation
# getting configuration information
config_filename = cfg.config_filename
zone_folder = cfg.zone_folder
learned_folder = cfg.learned_zones_folder
min_max_filename = cfg.min_max_filename_extension
# define all scenes values
scenes_list = cfg.scenes_names
scenes_indexes = cfg.scenes_indices
dataset_path = cfg.dataset_path
zones = cfg.zones_indices
seuil_expe_filename = cfg.seuil_expe_filename
features_choices = cfg.features_choices_labels
output_data_folder = cfg.output_data_folder
generic_output_file_svd = '_random.csv'
def generate_data_model(_scenes_list, _filename, _transformations, _scenes, _nb_zones = 4, _random=0, _only_noisy=0):
output_train_filename = _filename + ".train"
output_test_filename = _filename + ".test"
if not '/' in output_train_filename:
raise Exception("Please select filename with directory path to save data. Example : data/dataset")
# create path if not exists
if not os.path.exists(output_data_folder):
os.makedirs(output_data_folder)
train_file_data = []
test_file_data = []
scenes = os.listdir(dataset_path)
# remove min max file from scenes folder
scenes = [s for s in scenes if min_max_filename not in s]
# go ahead each scenes
for id_scene, folder_scene in enumerate(_scenes_list):
scene_path = os.path.join(dataset_path, folder_scene)
config_file_path = os.path.join(scene_path, config_filename)
# only get last image path
with open(config_file_path, "r") as config_file:
last_image_name = config_file.readline().strip()
ref_image_path = os.path.join(scene_path, last_image_name)
zones_indices = zones
# shuffle list of zones (=> randomly choose zones)
# only in random mode
if _random:
random.shuffle(zones_indices)
# store zones learned
learned_zones_indices = zones_indices[:_nb_zones]
# write into file
folder_learned_path = os.path.join(learned_folder, _filename.split('/')[1])
if not os.path.exists(folder_learned_path):
os.makedirs(folder_learned_path)
file_learned_path = os.path.join(folder_learned_path, folder_scene + '.csv')
with open(file_learned_path, 'w') as f:
for i in learned_zones_indices:
f.write(str(i) + ';')
ref_image_blocks = divide_in_blocks(Image.open(ref_image_path), cfg.keras_img_size)
for id_zone, index_folder in enumerate(zones_indices):
index_str = str(index_folder)
if len(index_str) < 2:
index_str = "0" + index_str
current_zone_folder = "zone" + index_str
zone_path = os.path.join(scene_path, current_zone_folder)
# path of zone of reference image
# ref_image_block_path = os.path.join(zone_path, last_image_name)
# compute augmented images for ref image
current_ref_zone_image = ref_image_blocks[id_zone]
ref_image_name_prefix = last_image_name.replace('.png', '')
dt.augmented_data_image(current_ref_zone_image, zone_path, ref_image_name_prefix)
# get list of all augmented ref images
ref_augmented_images = [os.path.join(zone_path, f) for f in os.listdir(zone_path) if ref_image_name_prefix in f]
# custom path for interval of reconstruction and features
features_path = []
for transformation in _transformations:
# check if it's a static content and create augmented images if necessary
if transformation.getName() == 'static':
# {sceneName}/zoneXX/static
static_features_path = os.path.join(zone_path, transformation.getName())
# img.png
image_name = transformation.getParam().split('/')[-1]
# {sceneName}/zoneXX/static/img
image_prefix_name = image_name.replace('.png', '')
image_folder_path = os.path.join(static_features_path, image_prefix_name)
if not os.path.exists(image_folder_path):
os.makedirs(image_folder_path)
features_path.append(image_folder_path)
# get image path to manage
# {sceneName}/static/img.png
transform_image_path = os.path.join(scene_path, transformation.getName(), image_name)
static_transform_image = Image.open(transform_image_path)
static_transform_image_block = divide_in_blocks(static_transform_image, cfg.keras_img_size)[id_zone]
# generate augmented data
dt.augmented_data_image(static_transform_image_block, image_folder_path, image_prefix_name)
else:
features_interval_path = os.path.join(zone_path, transformation.getTransformationPath())
features_path.append(features_interval_path)
# as labels are same for each features
for label in os.listdir(features_path[0]):
if (label == cfg.not_noisy_folder and _only_noisy == 0) or label == cfg.noisy_folder:
label_features_path = []
for path in features_path:
label_path = os.path.join(path, label)
label_features_path.append(label_path)
# getting images list for each features
features_images_list = []
for index_features, label_path in enumerate(label_features_path):
if _transformations[index_features].getName() == 'static':
# by default append nothing..
features_images_list.append([])
else:
images = sorted(os.listdir(label_path))
features_images_list.append(images)
# construct each line using all images path of each
for index_image in range(0, len(features_images_list[0])):
images_path = []
# get information about rotation and flip from first transformation (need to be a not static transformation)
current_post_fix = features_images_list[0][index_image].split(cfg.post_image_name_separator)[-1]
# getting images with same index and hence name for each features (transformation)
for index_features in range(0, len(features_path)):
# custom behavior for static transformation (need to check specific image)
if _transformations[index_features].getName() == 'static':
# add static path with selecting correct data augmented image
image_name = _transformations[index_features].getParam().split('/')[-1].replace('.png', '')
img_path = os.path.join(features_path[index_features], image_name + cfg.post_image_name_separator + current_post_fix)
images_path.append(img_path)
else:
img_path = features_images_list[index_features][index_image]
images_path.append(os.path.join(label_features_path[index_features], img_path))
# get information about rotation and flip
current_post_fix = images_path[0].split(cfg.post_image_name_separator)[-1]
# get ref block which matchs we same information about rotation and flip
augmented_ref_image_block_path = next(img for img in ref_augmented_images
if img.split(cfg.post_image_name_separator)[-1] == current_post_fix)
line = augmented_ref_image_block_path + ';'
# compute line information with all images paths
for id_path, img_path in enumerate(images_path):
if id_path < len(images_path) - 1:
line = line + img_path + '::'
else:
line = line + img_path
line = line + '\n'
if id_zone < _nb_zones and folder_scene in _scenes:
train_file_data.append(line)
else:
test_file_data.append(line)
train_file = open(output_train_filename, 'w')
test_file = open(output_test_filename, 'w')
random.shuffle(train_file_data)
random.shuffle(test_file_data)
for line in train_file_data:
train_file.write(line)
for line in test_file_data:
test_file.write(line)
train_file.close()
test_file.close()
def main():
parser = argparse.ArgumentParser(description="Compute specific dataset for model using of features")
parser.add_argument('--output', type=str, help='output file name desired (.train and .test)')
parser.add_argument('--features', type=str,
help="list of features choice in order to compute data",
default='svd_reconstruction, ipca_reconstruction',
required=True)
parser.add_argument('--params', type=str,
help="list of specific param for each features choice (See README.md for further information in 3D mode)",
default='100, 200 :: 50, 25',
required=True)
parser.add_argument('--scenes', type=str, help='List of scenes to use for training data')
parser.add_argument('--nb_zones', type=int, help='Number of zones to use for training data set', choices=list(range(1, 17)))
parser.add_argument('--renderer', type=str, help='Renderer choice in order to limit scenes used', choices=cfg.renderer_choices, default='all')
parser.add_argument('--random', type=int, help='Data will be randomly filled or not', choices=[0, 1])
parser.add_argument('--only_noisy', type=int, help='Only noisy will be used', choices=[0, 1])
args = parser.parse_args()
p_filename = args.output
p_features = list(map(str.strip, args.features.split(',')))
p_params = list(map(str.strip, args.params.split('::')))
p_scenes = args.scenes.split(',')
p_nb_zones = args.nb_zones
p_renderer = args.renderer
p_random = args.random
p_only_noisy = args.only_noisy
# create list of Transformation
transformations = []
for id, features in enumerate(p_features):
if features not in features_choices:
raise ValueError("Unknown features, please select a correct features : ", features_choices)
transformations.append(Transformation(features, p_params[id]))
# list all possibles choices of renderer
scenes_list = dt.get_renderer_scenes_names(p_renderer)
scenes_indices = dt.get_renderer_scenes_indices(p_renderer)
# getting scenes from indexes user selection
scenes_selected = []
for scene_id in p_scenes:
index = scenes_indices.index(scene_id.strip())
scenes_selected.append(scenes_list[index])
# create database using img folder (generate first time only)
generate_data_model(scenes_list, p_filename, transformations, scenes_selected, p_nb_zones, p_random, p_only_noisy)
if __name__== "__main__":
main()
<file_sep>/generate/generate_reconstructed_data.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 19 11:47:42 2019
@author: jbuisine
"""
# main imports
import sys, os, argparse
import numpy as np
# images processing imports
from PIL import Image
from ipfml.processing.segmentation import divide_in_blocks
# modules imports
sys.path.insert(0, '') # trick to enable import of main folder module
import custom_config as cfg
from modules.utils.data import get_scene_image_quality
from modules.classes.Transformation import Transformation
# getting configuration information
config_filename = cfg.config_filename
zone_folder = cfg.zone_folder
min_max_filename = cfg.min_max_filename_extension
# define all scenes values
scenes_list = cfg.scenes_names
scenes_indexes = cfg.scenes_indices
path = cfg.dataset_path
zones = cfg.zones_indices
seuil_expe_filename = cfg.seuil_expe_filename
features_choices = cfg.features_choices_labels
output_data_folder = cfg.output_data_folder
generic_output_file_svd = '_random.csv'
def generate_data(transformation):
"""
@brief Method which generates all .csv files from scenes
@return nothing
"""
scenes = os.listdir(path)
# remove min max file from scenes folder
scenes = [s for s in scenes if min_max_filename not in s]
# go ahead each scenes
for id_scene, folder_scene in enumerate(scenes):
print(folder_scene)
scene_path = os.path.join(path, folder_scene)
config_file_path = os.path.join(scene_path, config_filename)
with open(config_file_path, "r") as config_file:
last_image_name = config_file.readline().strip()
prefix_image_name = config_file.readline().strip()
start_index_image = config_file.readline().strip()
end_index_image = config_file.readline().strip()
step_counter = int(config_file.readline().strip())
# construct each zones folder name
zones_folder = []
features_folder = []
zones_threshold = []
# get zones list info
for index in zones:
index_str = str(index)
if len(index_str) < 2:
index_str = "0" + index_str
current_zone = "zone"+index_str
zones_folder.append(current_zone)
zone_path = os.path.join(scene_path, current_zone)
with open(os.path.join(zone_path, cfg.seuil_expe_filename)) as f:
zones_threshold.append(int(f.readline()))
# custom path for feature
feature_path = os.path.join(zone_path, transformation.getName())
if not os.path.exists(feature_path):
os.makedirs(feature_path)
# custom path for interval of reconstruction and feature
feature_interval_path = os.path.join(zone_path, transformation.getTransformationPath())
features_folder.append(feature_interval_path)
if not os.path.exists(feature_interval_path):
os.makedirs(feature_interval_path)
# create for each zone the labels folder
labels = [cfg.not_noisy_folder, cfg.noisy_folder]
for label in labels:
label_folder = os.path.join(feature_interval_path, label)
if not os.path.exists(label_folder):
os.makedirs(label_folder)
# get all images of folder
scene_images = sorted([os.path.join(scene_path, img) for img in os.listdir(scene_path) if cfg.scene_image_extension in img])
number_scene_image = len(scene_images)
# for each images
for id_img, img_path in enumerate(scene_images):
current_img = Image.open(img_path)
img_blocks = divide_in_blocks(current_img, cfg.keras_img_size)
current_quality_index = int(get_scene_image_quality(img_path))
for id_block, block in enumerate(img_blocks):
##########################
# Image computation part #
##########################
# pass block to grey level
output_block = transformation.getTransformedImage(block)
output_block = np.array(output_block, 'uint8')
# current output image
output_block_img = Image.fromarray(output_block)
label_path = features_folder[id_block]
# get label folder for block
if current_quality_index > zones_threshold[id_block]:
label_path = os.path.join(label_path, cfg.not_noisy_folder)
else:
label_path = os.path.join(label_path, cfg.noisy_folder)
# Data augmentation!
rotations = [0, 90, 180, 270]
img_flip_labels = ['original', 'horizontal', 'vertical', 'both']
horizontal_img = output_block_img.transpose(Image.FLIP_LEFT_RIGHT)
vertical_img = output_block_img.transpose(Image.FLIP_TOP_BOTTOM)
both_img = output_block_img.transpose(Image.TRANSPOSE)
flip_images = [output_block_img, horizontal_img, vertical_img, both_img]
# rotate and flip image to increase dataset size
for id, flip in enumerate(flip_images):
for rotation in rotations:
rotated_output_img = flip.rotate(rotation)
output_reconstructed_filename = img_path.split('/')[-1].replace('.png', '') + '_' + zones_folder[id_block] + cfg.post_image_name_separator
output_reconstructed_filename = output_reconstructed_filename + img_flip_labels[id] + '_' + str(rotation) + '.png'
output_reconstructed_path = os.path.join(label_path, output_reconstructed_filename)
rotated_output_img.save(output_reconstructed_path)
print(transformation.getName() + "_" + folder_scene + " - " + "{0:.2f}".format(((id_img + 1) / number_scene_image)* 100.) + "%")
sys.stdout.write("\033[F")
print('\n')
print("%s_%s : end of data generation\n" % (transformation.getName(), transformation.getParam()))
def main():
parser = argparse.ArgumentParser(description="Compute and prepare data of feature of all scenes using specific interval if necessary")
parser.add_argument('--features', type=str,
help="list of features choice in order to compute data",
default='svd_reconstruction, ipca_reconstruction',
required=True)
parser.add_argument('--params', type=str,
help="list of specific param for each feature choice (See README.md for further information in 3D mode)",
default='100, 200 :: 50, 25',
required=True)
args = parser.parse_args()
p_features = list(map(str.strip, args.features.split(',')))
p_params = list(map(str.strip, args.params.split('::')))
transformations = []
for id, feature in enumerate(p_features):
if feature not in features_choices:
raise ValueError("Unknown feature, please select a correct feature : ", features_choices)
transformations.append(Transformation(feature, p_params[id]))
# generate all or specific feature data
for transformation in transformations:
generate_data(transformation)
if __name__== "__main__":
main()
<file_sep>/README.md
# Denoising with autoencoder
## Description
Utilisation d'un autoencoder pour apprendre statistiquement comment il est possible de générer une image de synthèse.
Input :
- Noisy image
- Z-buffer
- Normal card
or other information...
Output :
- Reference image
## Requirements
```bash
git clone --recursive https://github.com/prise-3d/Thesis-Denoising-autoencoder.git XXXXX
```
```bash
pip install -r requirements.txt
```
## How to use ?
[Autoencoder keras documentation](https://blog.keras.io/building-autoencoders-in-keras.html)
Generate reconstructed data from specific method of reconstruction (run only once time or clean data folder before):
```
python generate/generate_reconstructed_data.py -h
```
Generate custom dataset from one reconstructed method or multiples (implemented later)
```
python generate/generate_dataset.py -h
```
### Reconstruction parameter (--params)
List of expected parameter by reconstruction method:
- **svd_reconstruction:** Singular Values Decomposition
- Param definition: *interval data used for reconstruction (begin, end)*
- Example: *"100, 200"*
- **ipca_reconstruction:** Iterative Principal Component Analysis
- Param definition: *number of components used for compression and batch size*
- Example: *"30, 35"*
- **fast_ica_reconstruction:** Fast Iterative Component Analysis
- Param definition: *number of components used for compression*
- Example: *"50"*
- **static** Use static file to manage (such as z-buffer, normals card...)
- Param definition: *Name of image of scene need to be in {sceneName}/static/xxxx.png*
- Example: *"img.png"*
**__Example:__**
```bash
python generate/generate_dataset.py --output data/output_data_filename --metrics "svd_reconstruction, ipca_reconstruction, fast_ica_reconstruction" --renderer "maxwell" --scenes "A, D, G, H" --params "100, 200 :: 50, 10 :: 50" --nb_zones 10 --random 1 --only_noisy 1
```
Then, run the model:
```bash
python image_denoising --data data/my_dataset --output output_model_name
```
## License
[The MIT license](https://github.com/prise-3d/Thesis-NoiseDetection-metrics/blob/master/LICENSE)
<file_sep>/requirements.txt
Pillow
keras
tensorflow
sklearn
matplotlib
path.py
ipfml
cv2<file_sep>/custom_config.py
from modules.config.cnn_config import *
# store all variables from cnn config
context_vars = vars()
# Custom config used for redefined config variables if necessary
# folders
## noisy_folder = 'noisy'
## not_noisy_folder = 'notNoisy'
# file or extensions
## post_image_name_separator = '___'
# variables
## features_choices_labels = ['static', 'svd_reconstruction', 'fast_ica_reconstruction', 'ipca_reconstruction']
# parameters
keras_epochs = 200
## keras_batch = 32
## val_dataset_size = 0.2
## keras_img_size = (200, 200) | 22aded9d235581d15a9968dad963039297c85c35 | [
"Markdown",
"Python",
"Text"
] | 6 | Python | prise-3d/Thesis-Denoising-autoencoder | 2a9d995fc69578897bcf0ba57792e1c430e5993e | c1aeab7da92871b51a30f3692f2345b85e6578b6 | |
refs/heads/master | <repo_name>JustinCredibleGIT/volumetric-explosions<file_sep>/Volumetric Explosion Sample/Common.h
#ifndef COMMON_H
#define COMMON_H
// =======================================================================
// Global register indices
// =======================================================================
#define S_BILINEAR_CLAMPED_SAMPLER 0
#define S_BILINEAR_WRAPPED_SAMPLER 1
#define B_EXPLOSION_PARAMS 0
#define T_NOISE_VOLUME 0
#define T_GRADIENT_TEX 1
#define PI (3.14159265359f)
#ifdef WIN32
// =======================================================================
// C++ ONLY
// =======================================================================
#define CONSTANT_BUFFER( name, reg ) __declspec(align(16)) struct name
typedef DirectX::XMFLOAT4X4 float4x4;
typedef DirectX::XMFLOAT4 float4;
typedef DirectX::XMFLOAT3 float3;
typedef DirectX::XMFLOAT2 float2;
typedef DirectX::XMUINT4 uint4;
typedef DirectX::XMUINT3 uint3;
typedef DirectX::XMUINT2 uint2;
typedef unsigned int uint;
#endif
#if HLSL
// =======================================================================
// HLSL ONLY
// =======================================================================
#define S_REG(oo) s##oo
#define T_REG(oo) t##oo
#define U_REG(oo) u##oo
#define B_REG(oo) b##oo
SamplerState BilinearClampedSampler : register( S_REG( S_BILINEAR_CLAMPED_SAMPLER ) );
SamplerState BilinearWrappedSampler : register( S_REG( S_BILINEAR_WRAPPED_SAMPLER ) );
#define CONSTANT_BUFFER( name, reg ) cbuffer name : register( b##reg )
#endif
// =======================================================================
// Shared ( C++ & HLSL )
// =======================================================================
CONSTANT_BUFFER( ExplosionParams, B_EXPLOSION_PARAMS )
{
float4x4 g_WorldToViewMatrix;
float4x4 g_ViewToProjectionMatrix;
float4x4 g_ProjectionToViewMatrix;
float4x4 g_WorldToProjectionMatrix;
float4x4 g_ProjectionToWorldMatrix;
float4x4 g_ViewToWorldMatrix;
float3 g_EyePositionWS;
float g_NoiseAmplitudeFactor;
float3 g_EyeForwardWS;
float g_NoiseScale;
float4 g_ProjectionParams;
float4 g_ScreenParams;
float3 g_ExplosionPositionWS;
float g_ExplosionRadiusWS;
float3 g_NoiseAnimationSpeed;
float g_Time;
float g_EdgeSoftness;
float g_NoiseFrequencyFactor;
uint g_PrimitiveIdx;
float g_Opacity;
float g_DisplacementWS;
float g_StepSizeWS;
uint g_MaxNumSteps;
float g_NoiseInitialAmplitude;
float2 g_UvScaleBias;
float g_InvMaxNoiseDisplacement;
uint g_NumOctaves;
float g_SkinThickness;
uint g_NumHullOctaves;
uint g_NumHullSteps;
float g_TessellationFactor;
};
#endif // COMMON_H<file_sep>/Volumetric Explosion Sample/Main.cpp
//--------------------------------------------------------------------------------------
// Realistic Volumetric Explosions in Games.
// GPU Pro 6
// <NAME>
//
// This sample demonstrates how to render volumetric explosions in games
// using DirectX 11. The source code presented below forms the basis of
// the matching chapter in the book GPU Pro 6.
//--------------------------------------------------------------------------------------
#include <windows.h>
#include <windowsx.h>
#include <d3d11_1.h>
#include <d3dcompiler.h>
#include <directxmath.h>
#include <DirectXPackedVector.h>
#include <directxcolors.h>
#include <fstream>
#include <DDSTextureLoader.h>
#include <AntTweakBar.h>
#include "Common.h"
using namespace DirectX;
using namespace DirectX::PackedVector;
//--------------------------------------------------------------------------------------
// Global Variables
//--------------------------------------------------------------------------------------
HINSTANCE g_hInst = nullptr;
HWND g_hWnd = nullptr;
D3D_DRIVER_TYPE g_driverType = D3D_DRIVER_TYPE_NULL;
D3D_FEATURE_LEVEL g_featureLevel = D3D_FEATURE_LEVEL_11_0;
ID3D11Device* g_pd3dDevice = nullptr;
ID3D11Device1* g_pd3dDevice1 = nullptr;
ID3D11DeviceContext* g_pImmediateContext = nullptr;
ID3D11DeviceContext1* g_pImmediateContext1 = nullptr;
IDXGISwapChain* g_pSwapChain = nullptr;
IDXGISwapChain1* g_pSwapChain1 = nullptr;
ID3D11RenderTargetView* g_pRenderTargetView = nullptr;
ID3D11Buffer* g_pExplosionParamsCB = nullptr;
ID3D11ShaderResourceView* g_pNoiseVolumeSRV = nullptr;
ID3D11ShaderResourceView* g_pGradientSRV = nullptr;
ID3D11VertexShader* g_pRenderExplosionVS = nullptr;
ID3D11HullShader* g_pRenderExplosionHS = nullptr;
ID3D11DomainShader* g_pRenderExplosionDS = nullptr;
ID3D11PixelShader* g_pRenderExplosionPS = nullptr;
ID3D11InputLayout* g_pExplosionLayout = nullptr;
ID3D11SamplerState* g_pSamplerClampedLinear = nullptr;
ID3D11SamplerState* g_pSamplerWrappedLinear = nullptr;
ID3D11DepthStencilState* g_pTestWriteDepth = nullptr;
ID3D11BlendState* g_pOverBlendState = nullptr;
// Explosion parameters.
const XMFLOAT3 kNoiseAnimationSpeed(0.0f, 0.02f, 0.0f);
const float kNoiseInitialAmplitude = 3.0f;
const UINT kMaxNumSteps = 256;
const UINT kNumHullSteps = 2;
const float kStepSize = 0.04f;
const UINT kNumOctaves = 4;
const UINT kNumHullOctaves = 2;
const float kSkinThicknessBias = 0.6f;
const float kTessellationFactor = 16;
float g_MaxSkinThickness;
float g_MaxNoiseDisplacement;
static bool g_EnableHullShrinking = true;
static float g_EdgeSoftness = 0.05f;
static float g_NoiseScale = 0.04f;
static float g_ExplosionRadius = 4.0f;
static float g_DisplacementAmount = 1.75f;
static XMFLOAT2 g_UvScaleBias(2.1f, 0.35f);
static float g_NoiseAmplitudeFactor = 0.4f;
static float g_NoiseFrequencyFactor = 3.0f;
// Camera variables.
const UINT kResolutionX = 800;
const UINT kResolutionY = 640;
const float kNearClip = 0.01f;
const float kFarClip = 20.0f;
const XMFLOAT3 kEyeLookAtWS = XMFLOAT3(0.0f, 0.0f, 0.0f);
XMFLOAT3 g_EyePositionWS;
XMFLOAT3 g_EyeForwardWS;
XMMATRIX g_WorldToProjectionMatrix, g_ProjectionToWorldMatrix, g_InvProjMatrix, g_ViewToWorldMatrix;
XMFLOAT4X4 g_ViewMatrix, g_ProjMatrix;
XMFLOAT4 g_ProjectionParams;
POINT g_LastMousePos;
float g_CameraTheta = 0, g_CameraPhi = 0, g_CameraRadius = 10;
// Timer Variables
__int64 g_CounterStart = 0;
double g_CountsPerSecond = 0.0;
double g_ElapsedTime = 0.0;
TwBar* g_pUI;
enum PrimitiveType
{
kPrimitiveSphere,
kPrimitiveCylinder,
kPrimitiveCone,
kPrimitiveTorus,
kPrimitiveBox
} g_Primitive = kPrimitiveSphere;
//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
HRESULT InitWindow( HINSTANCE hInstance, int nCmdShow );
HRESULT InitDevice();
void InitUI();
void CleanupDevice();
LRESULT CALLBACK WndProc( HWND, UINT, WPARAM, LPARAM );
void Render();
void StartTimer();
double GetTime();
void OnMouseDown(int x, int y);
void OnMouseUp();
void OnMouseMove(WPARAM btnState, int x, int y);
void UpdateViewMatrix();
//--------------------------------------------------------------------------------------
// Entry point to the program. Initializes everything and goes into a message processing
// loop. Idle time is used to render the scene.
//--------------------------------------------------------------------------------------
int WINAPI wWinMain( _In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow )
{
UNREFERENCED_PARAMETER( hPrevInstance );
UNREFERENCED_PARAMETER( lpCmdLine );
if( FAILED( InitWindow( hInstance, nCmdShow ) ) )
return 0;
if( FAILED( InitDevice() ) )
{
CleanupDevice();
return 0;
}
StartTimer();
TwInit(TW_DIRECT3D11, g_pd3dDevice);
TwWindowSize(kResolutionX, kResolutionY);
InitUI();
// Main message loop
MSG msg = {0};
while( WM_QUIT != msg.message )
{
if( PeekMessage( &msg, nullptr, 0, 0, PM_REMOVE ) )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
else
{
// Update scene timer
g_ElapsedTime = GetTime();
Render();
}
}
TwTerminate();
CleanupDevice();
return ( int )msg.wParam;
}
//--------------------------------------------------------------------------------------
// Register class and create window
//--------------------------------------------------------------------------------------
HRESULT InitWindow( HINSTANCE hInstance, int nCmdShow )
{
// Register class
WNDCLASSEX wcex;
wcex.cbSize = sizeof( WNDCLASSEX );
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon( hInstance, "directx.ico" );
wcex.hCursor = LoadCursor( nullptr, IDC_ARROW );
wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );
wcex.lpszMenuName = nullptr;
wcex.lpszClassName = "VolumetricExplosionSample";
wcex.hIconSm = LoadIcon( wcex.hInstance, "directx.ico" );
if( !RegisterClassEx( &wcex ) ) return E_FAIL;
// Create window
g_hInst = hInstance;
RECT rc = { 0, 0, kResolutionX, kResolutionY };
AdjustWindowRect( &rc, WS_OVERLAPPEDWINDOW, FALSE );
g_hWnd = CreateWindow( "VolumetricExplosionSample", "GPU Pro 6 - Volumetric Explosions",
WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX,
CW_USEDEFAULT, CW_USEDEFAULT, rc.right - rc.left, rc.bottom - rc.top, nullptr, nullptr, hInstance,
nullptr );
if( !g_hWnd ) return E_FAIL;
ShowWindow( g_hWnd, nCmdShow );
return S_OK;
}
//--------------------------------------------------------------------------------------
// Create Direct3D device and swap chain
//--------------------------------------------------------------------------------------
HRESULT InitDevice()
{
HRESULT hr = S_OK;
RECT rc;
GetClientRect( g_hWnd, &rc );
UINT width = rc.right - rc.left;
UINT height = rc.bottom - rc.top;
UINT createDeviceFlags = 0;
#ifdef _DEBUG
createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
D3D_DRIVER_TYPE driverTypes[] =
{
D3D_DRIVER_TYPE_HARDWARE,
D3D_DRIVER_TYPE_WARP,
D3D_DRIVER_TYPE_REFERENCE,
};
UINT numDriverTypes = ARRAYSIZE( driverTypes );
D3D_FEATURE_LEVEL featureLevels[] =
{
D3D_FEATURE_LEVEL_11_1,
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0,
};
UINT numFeatureLevels = ARRAYSIZE( featureLevels );
for( UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++ )
{
g_driverType = driverTypes[driverTypeIndex];
hr = D3D11CreateDevice( nullptr, g_driverType, nullptr, createDeviceFlags, featureLevels, numFeatureLevels,
D3D11_SDK_VERSION, &g_pd3dDevice, &g_featureLevel, &g_pImmediateContext );
if ( hr == E_INVALIDARG )
{
// DirectX 11.0 platforms will not recognize D3D_FEATURE_LEVEL_11_1 so we need to retry without it
hr = D3D11CreateDevice( nullptr, g_driverType, nullptr, createDeviceFlags, &featureLevels[1], numFeatureLevels - 1,
D3D11_SDK_VERSION, &g_pd3dDevice, &g_featureLevel, &g_pImmediateContext );
}
if( SUCCEEDED( hr ) )
break;
}
if( FAILED( hr ) )
return hr;
// Obtain DXGI factory from device (since we used nullptr for pAdapter above)
IDXGIFactory1* dxgiFactory = nullptr;
{
IDXGIDevice* dxgiDevice = nullptr;
hr = g_pd3dDevice->QueryInterface( __uuidof(IDXGIDevice), reinterpret_cast<void**>(&dxgiDevice) );
if (SUCCEEDED(hr))
{
IDXGIAdapter* adapter = nullptr;
hr = dxgiDevice->GetAdapter(&adapter);
if (SUCCEEDED(hr))
{
hr = adapter->GetParent( __uuidof(IDXGIFactory1), reinterpret_cast<void**>(&dxgiFactory) );
adapter->Release();
}
dxgiDevice->Release();
}
}
if (FAILED(hr))
return hr;
// Create swap chain
IDXGIFactory2* dxgiFactory2 = nullptr;
hr = dxgiFactory->QueryInterface( __uuidof(IDXGIFactory2), reinterpret_cast<void**>(&dxgiFactory2) );
if ( dxgiFactory2 )
{
// DirectX 11.1 or later
hr = g_pd3dDevice->QueryInterface( __uuidof(ID3D11Device1), reinterpret_cast<void**>(&g_pd3dDevice1) );
if (SUCCEEDED(hr))
{
(void) g_pImmediateContext->QueryInterface( __uuidof(ID3D11DeviceContext1), reinterpret_cast<void**>(&g_pImmediateContext1) );
}
DXGI_SWAP_CHAIN_DESC1 sd;
ZeroMemory(&sd, sizeof(sd));
sd.Width = width;
sd.Height = height;
sd.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
sd.SampleDesc.Count = 1;
sd.SampleDesc.Quality = 0;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.BufferCount = 1;
hr = dxgiFactory2->CreateSwapChainForHwnd( g_pd3dDevice, g_hWnd, &sd, nullptr, nullptr, &g_pSwapChain1 );
if (SUCCEEDED(hr))
{
hr = g_pSwapChain1->QueryInterface( __uuidof(IDXGISwapChain), reinterpret_cast<void**>(&g_pSwapChain) );
}
dxgiFactory2->Release();
}
else
{
// DirectX 11.0 systems
DXGI_SWAP_CHAIN_DESC sd;
ZeroMemory(&sd, sizeof(sd));
sd.BufferCount = 1;
sd.BufferDesc.Width = width;
sd.BufferDesc.Height = height;
sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
sd.BufferDesc.RefreshRate.Numerator = 60;
sd.BufferDesc.RefreshRate.Denominator = 1;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.OutputWindow = g_hWnd;
sd.SampleDesc.Count = 1;
sd.SampleDesc.Quality = 0;
sd.Windowed = TRUE;
hr = dxgiFactory->CreateSwapChain( g_pd3dDevice, &sd, &g_pSwapChain );
}
// Note this tutorial doesn't handle full-screen swapchains so we block the ALT+ENTER shortcut
dxgiFactory->MakeWindowAssociation( g_hWnd, DXGI_MWA_NO_ALT_ENTER );
dxgiFactory->Release();
if (FAILED(hr))
return hr;
ID3D11Texture2D* pBackBuffer = nullptr;
hr = g_pSwapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), reinterpret_cast<void**>( &pBackBuffer ) );
if( FAILED( hr ) ) return hr;
hr = g_pd3dDevice->CreateRenderTargetView( pBackBuffer, nullptr, &g_pRenderTargetView );
pBackBuffer->Release();
if( FAILED( hr ) ) return hr;
ID3DBlob* pVSBlob = NULL;
if( FAILED( hr = D3DReadFileToBlob( L"RenderExplosionVS.cso", &pVSBlob ) ) ) return hr;
if( FAILED( hr = g_pd3dDevice->CreateVertexShader( pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), nullptr, &g_pRenderExplosionVS ) ) )
{
pVSBlob->Release();
return hr;
}
D3D11_INPUT_ELEMENT_DESC layout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
UINT numElements = ARRAYSIZE( layout );
hr = g_pd3dDevice->CreateInputLayout( layout, numElements, pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), &g_pExplosionLayout );
pVSBlob->Release();
if( FAILED( hr ) ) return hr;
ID3DBlob* pHSBlob = nullptr;
if( FAILED( hr = D3DReadFileToBlob( L"RenderExplosionHS.cso", &pHSBlob ) ) ) return hr;
hr = g_pd3dDevice->CreateHullShader( pHSBlob->GetBufferPointer(), pHSBlob->GetBufferSize(), nullptr, &g_pRenderExplosionHS );
pHSBlob->Release();
if( FAILED( hr ) ) return hr;
ID3DBlob* pDSBlob = nullptr;
if( FAILED( hr = D3DReadFileToBlob( L"RenderExplosionDS.cso", &pDSBlob ) ) ) return hr;
hr = g_pd3dDevice->CreateDomainShader( pDSBlob->GetBufferPointer(), pDSBlob->GetBufferSize(), nullptr, &g_pRenderExplosionDS );
pDSBlob->Release();
if( FAILED( hr ) ) return hr;
ID3DBlob* pPSBlob = nullptr;
if( FAILED( hr = D3DReadFileToBlob( L"RenderExplosionPS.cso", &pPSBlob ) ) ) return hr;
hr = g_pd3dDevice->CreatePixelShader( pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(), nullptr, &g_pRenderExplosionPS );
pPSBlob->Release();
if( FAILED( hr ) ) return hr;
D3D11_BUFFER_DESC bd;
ZeroMemory( &bd, sizeof(bd) );
bd.Usage = D3D11_USAGE_DYNAMIC;
bd.ByteWidth = sizeof( ExplosionParams );
bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
hr = g_pd3dDevice->CreateBuffer( &bd, nullptr, &g_pExplosionParamsCB );
if( FAILED( hr ) ) return hr;
D3D11_SAMPLER_DESC sampDesc;
ZeroMemory( &sampDesc, sizeof(sampDesc) );
sampDesc.Filter = D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT;
sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
sampDesc.MinLOD = 0;
sampDesc.MaxLOD = D3D11_FLOAT32_MAX;
hr = g_pd3dDevice->CreateSamplerState( &sampDesc, &g_pSamplerClampedLinear );
if( FAILED( hr ) ) return hr;
sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
hr = g_pd3dDevice->CreateSamplerState( &sampDesc, &g_pSamplerWrappedLinear );
if( FAILED( hr ) ) return hr;
HALF maxNoiseValue = 0, minNoiseValue = 0xFFFF;
HALF noiseValues[32*32*32] = { 0 };
std::fstream f;
f.open("noise_32x32x32.dat", std::ios::in);
if(f.is_open())
{
for(UINT i=0 ; i<32*32*32 ; i++)
{
HALF noiseValue;
f >> noiseValue;
maxNoiseValue = max(maxNoiseValue, noiseValue);
minNoiseValue = min(minNoiseValue, noiseValue);
noiseValues[i] = noiseValue;
}
f.close();
}
D3D11_TEXTURE3D_DESC texDesc;
ZeroMemory( &texDesc, sizeof(texDesc) );
texDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
texDesc.CPUAccessFlags = 0;
texDesc.Depth = 32;
texDesc.Format = DXGI_FORMAT_R16_FLOAT;
texDesc.Height = 32;
texDesc.MipLevels = 1;
texDesc.MiscFlags = 0;
texDesc.Usage = D3D11_USAGE_DEFAULT;
texDesc.Width = 32;
ID3D11Texture3D* pNoiseVolume;
D3D11_SUBRESOURCE_DATA initialData;
initialData.pSysMem = noiseValues;
initialData.SysMemPitch = 32 * 2;
initialData.SysMemSlicePitch = 32 * 32 * 2;
hr = g_pd3dDevice->CreateTexture3D( &texDesc, &initialData, &pNoiseVolume );
if( FAILED( hr ) ) return hr;
hr = g_pd3dDevice->CreateShaderResourceView( pNoiseVolume, nullptr, &g_pNoiseVolumeSRV );
if( FAILED( hr ) ) return hr;
hr = CreateDDSTextureFromFile( g_pd3dDevice, L"gradient.dds", nullptr, &g_pGradientSRV );
if( FAILED( hr ) ) return hr;
D3D11_DEPTH_STENCIL_DESC dsDesc;
ZeroMemory( &dsDesc, sizeof(dsDesc) );
dsDesc.DepthEnable = true;
dsDesc.DepthFunc = D3D11_COMPARISON_LESS_EQUAL;
dsDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
dsDesc.StencilEnable = false;
hr = g_pd3dDevice->CreateDepthStencilState( &dsDesc, &g_pTestWriteDepth );
if( FAILED( hr ) ) return hr;
D3D11_BLEND_DESC bsDesc;
ZeroMemory( &bsDesc, sizeof(bsDesc) );
bsDesc.AlphaToCoverageEnable = false;
bsDesc.RenderTarget[0].BlendEnable = true;
bsDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
bsDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
bsDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
bsDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_SRC_ALPHA;
bsDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
bsDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
bsDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
hr = g_pd3dDevice->CreateBlendState( &bsDesc, &g_pOverBlendState );
if( FAILED( hr ) ) return hr;
// Calculate the maximum possible displacement from noise based on our
// fractal noise parameters. This is used to ensure our explosion primitive
// fits in our base sphere.
float largestAbsoluteNoiseValue = max( abs( XMConvertHalfToFloat( maxNoiseValue ) ), abs( XMConvertHalfToFloat( minNoiseValue ) ) );
g_MaxNoiseDisplacement = 0;
for(UINT i=0 ; i<kNumOctaves ; i++)
{
g_MaxNoiseDisplacement += largestAbsoluteNoiseValue * kNoiseInitialAmplitude * powf(g_NoiseAmplitudeFactor, (float)i);
}
// Calculate the skin thickness, which is amount of displacement to add
// to the geometry hull after shrinking it around the explosion primitive.
g_MaxSkinThickness = 0;
for(UINT i=kNumHullOctaves ; i<kNumOctaves ; i++)
{
g_MaxSkinThickness += largestAbsoluteNoiseValue * kNoiseInitialAmplitude * powf(g_NoiseAmplitudeFactor, (float)i);
}
// Add a little bit extra to account for under-tessellation. This should be
// fine tuned on a per use basis for best performance.
g_MaxSkinThickness += kSkinThicknessBias;
XMStoreFloat4x4( &g_ProjMatrix, XMMatrixPerspectiveFovLH( 60*PI/180, (float)kResolutionX/kResolutionY, kNearClip, kFarClip ) );
XMVECTOR det;
g_InvProjMatrix = XMMatrixInverse( &det, XMLoadFloat4x4 (&g_ProjMatrix ) );
const float A = kFarClip / (kFarClip - kNearClip);
const float B = (-kFarClip * kNearClip) / (kFarClip - kNearClip);
const float C = (kFarClip - kNearClip);
const float D = kNearClip;
g_ProjectionParams = XMFLOAT4( A, B, C, D );
UpdateViewMatrix();
return S_OK;
}
void InitUI()
{
g_pUI = TwNewBar("Controls");
TwDefine(" GLOBAL help='Realistic Volumetric Explosions in Games\nGPU Pro 6\n<NAME> - 23/12/2014 \n\nHold the LMB and move the mouse to rotate the scene.\n\n' "); // Message added to the help bar.
int barSize[2] = {210, 180};
TwSetParam(g_pUI, NULL, "size", TW_PARAM_INT32, 2, barSize);
TwAddVarRW(g_pUI, "Use Tight Hull", TW_TYPE_BOOL8, &g_EnableHullShrinking, "");
TwAddVarRW(g_pUI, "Edge Softness", TW_TYPE_FLOAT, &g_EdgeSoftness, "min=0 max=1 step=0.001");
TwAddVarRW(g_pUI, "Radius", TW_TYPE_FLOAT, &g_ExplosionRadius, "min=0 max=8 step=0.01");
TwAddVarRW(g_pUI, "Displacement", TW_TYPE_FLOAT, &g_DisplacementAmount, "min=0 max=8 step=0.01");
TwAddVarRW(g_pUI, "Amplitude Factor", TW_TYPE_FLOAT, &g_NoiseAmplitudeFactor, "min=0 max=10 step=0.01");
TwAddVarRW(g_pUI, "Frequency Factor", TW_TYPE_FLOAT, &g_NoiseFrequencyFactor, "min=0 max=10 step=0.01");
TwAddVarRW(g_pUI, "Noise Scale", TW_TYPE_FLOAT, &g_NoiseScale, "min=0 max=1 step=0.001");
TwAddVarRW(g_pUI, "UV Scale", TW_TYPE_FLOAT, &g_UvScaleBias.x, "min=-10 max=10 step=0.01");
TwAddVarRW(g_pUI, "UV Bias", TW_TYPE_FLOAT, &g_UvScaleBias.y, "min=-10 max=10 step=0.01");
}
//--------------------------------------------------------------------------------------
// Clean up the objects we've created
//--------------------------------------------------------------------------------------
void CleanupDevice()
{
if( g_pImmediateContext ) g_pImmediateContext->ClearState();
if( g_pExplosionParamsCB ) g_pExplosionParamsCB->Release();
if( g_pNoiseVolumeSRV ) g_pNoiseVolumeSRV->Release();
if( g_pGradientSRV ) g_pGradientSRV->Release();
if( g_pRenderExplosionVS ) g_pRenderExplosionVS->Release();
if( g_pRenderExplosionHS ) g_pRenderExplosionHS->Release();
if( g_pRenderExplosionDS ) g_pRenderExplosionDS->Release();
if( g_pRenderExplosionPS ) g_pRenderExplosionPS->Release();
if( g_pExplosionLayout ) g_pExplosionLayout->Release();
if( g_pSamplerClampedLinear ) g_pSamplerClampedLinear->Release();
if( g_pSamplerWrappedLinear ) g_pSamplerWrappedLinear->Release();
if( g_pTestWriteDepth ) g_pTestWriteDepth->Release();
if( g_pOverBlendState ) g_pOverBlendState->Release();
if( g_pRenderTargetView ) g_pRenderTargetView->Release();
if( g_pSwapChain1 ) g_pSwapChain1->Release();
if( g_pSwapChain ) g_pSwapChain->Release();
if( g_pImmediateContext1 ) g_pImmediateContext1->Release();
if( g_pImmediateContext ) g_pImmediateContext->Release();
if( g_pd3dDevice1 ) g_pd3dDevice1->Release();
if( g_pd3dDevice ) g_pd3dDevice->Release();
}
//--------------------------------------------------------------------------------------
// Called every time the application receives a message
//--------------------------------------------------------------------------------------
LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
{
if( TwEventWin(hWnd, message, wParam, lParam) ) return 0;
PAINTSTRUCT ps;
HDC hdc;
switch( message )
{
case WM_PAINT:
hdc = BeginPaint( hWnd, &ps );
EndPaint( hWnd, &ps );
break;
case WM_DESTROY:
PostQuitMessage( 0 );
break;
case WM_LBUTTONDOWN:
case WM_MBUTTONDOWN:
case WM_RBUTTONDOWN:
OnMouseDown(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
return 0;
case WM_LBUTTONUP:
case WM_MBUTTONUP:
case WM_RBUTTONUP:
OnMouseUp();
return 0;
case WM_MOUSEMOVE:
OnMouseMove(wParam, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
return 0;
// Note that this tutorial does not handle resizing (WM_SIZE) requests,
// so we created the window without the resize border.
default:
return DefWindowProc( hWnd, message, wParam, lParam );
}
return 0;
}
void StartTimer()
{
LARGE_INTEGER frequencyCount;
QueryPerformanceFrequency(&frequencyCount);
g_CountsPerSecond = double(frequencyCount.QuadPart);
QueryPerformanceCounter(&frequencyCount);
g_CounterStart = frequencyCount.QuadPart;
}
double GetTime()
{
LARGE_INTEGER currentTime;
QueryPerformanceCounter(¤tTime);
return double(currentTime.QuadPart-g_CounterStart)/g_CountsPerSecond;
}
void OnMouseDown(int x, int y)
{
g_LastMousePos.x = x;
g_LastMousePos.y = y;
SetCapture(g_hWnd);
}
void OnMouseUp()
{
ReleaseCapture();
}
void OnMouseMove(WPARAM btnState, int x, int y)
{
bool updateMatrices = false;
if( (btnState & MK_LBUTTON) != 0 )
{
float dx = XMConvertToRadians(0.25f * (float)(x - g_LastMousePos.x));
float dy = XMConvertToRadians(0.25f * (float)(y - g_LastMousePos.y));
g_CameraTheta -= dx;
g_CameraPhi -= dy;
updateMatrices = true;
}
else if( (btnState & MK_RBUTTON) != 0 )
{
float dx = 0.1f * (float)(x - g_LastMousePos.x);
float dy = 0.1f * (float)(y - g_LastMousePos.y);
g_CameraRadius += dx - dy;
updateMatrices = true;
}
g_LastMousePos.x = x;
g_LastMousePos.y = y;
if(updateMatrices)
{
UpdateViewMatrix();
}
}
void UpdateViewMatrix()
{
g_CameraRadius = max(g_CameraRadius, 1.0f);
g_CameraRadius = min(g_CameraRadius, 20.0f);
g_CameraPhi = max(g_CameraPhi, 0.1f);
g_CameraPhi = min(g_CameraPhi, PI - 0.1f);
float x = g_CameraRadius * sinf(g_CameraPhi) * cosf(g_CameraTheta);
float y = g_CameraRadius * cosf(g_CameraPhi);
float z = g_CameraRadius * sinf(g_CameraPhi) * sinf(g_CameraTheta);
g_EyePositionWS = XMFLOAT3(x, y, z);
XMStoreFloat4x4(&g_ViewMatrix, XMMatrixLookAtLH(XMLoadFloat3(&g_EyePositionWS), XMLoadFloat3(&kEyeLookAtWS), XMLoadFloat3(&XMFLOAT3(0, 1, 0))));
XMStoreFloat3( &g_EyeForwardWS, XMVector3Normalize( XMVectorSubtract( XMLoadFloat3(&kEyeLookAtWS), XMLoadFloat3(&g_EyePositionWS) ) ) );
g_WorldToProjectionMatrix = XMMatrixMultiply( XMLoadFloat4x4(&g_ViewMatrix), XMLoadFloat4x4(&g_ProjMatrix) );
XMVECTOR det;
g_ProjectionToWorldMatrix = XMMatrixInverse( &det, g_WorldToProjectionMatrix);
g_ViewToWorldMatrix = XMMatrixInverse( &det, XMLoadFloat4x4( &g_ViewMatrix ) );
}
void UpdateExplosionParams(ID3D11DeviceContext* const pContext)
{
D3D11_MAPPED_SUBRESOURCE MappedSubResource;
pContext->Map( g_pExplosionParamsCB, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedSubResource );
{
((ExplosionParams *)MappedSubResource.pData)->g_WorldToViewMatrix = g_ViewMatrix;
((ExplosionParams *)MappedSubResource.pData)->g_ViewToProjectionMatrix = g_ProjMatrix;
XMStoreFloat4x4( &((ExplosionParams *)MappedSubResource.pData)->g_ProjectionToViewMatrix, g_InvProjMatrix );
XMStoreFloat4x4( &((ExplosionParams *)MappedSubResource.pData)->g_WorldToProjectionMatrix, g_WorldToProjectionMatrix );
XMStoreFloat4x4( &((ExplosionParams *)MappedSubResource.pData)->g_ProjectionToWorldMatrix, g_ProjectionToWorldMatrix );
XMStoreFloat4x4( &((ExplosionParams *)MappedSubResource.pData)->g_ViewToWorldMatrix, g_ViewToWorldMatrix );
((ExplosionParams *)MappedSubResource.pData)->g_EyePositionWS = g_EyePositionWS;
((ExplosionParams *)MappedSubResource.pData)->g_NoiseAmplitudeFactor = g_NoiseAmplitudeFactor;
((ExplosionParams *)MappedSubResource.pData)->g_EyeForwardWS = g_EyeForwardWS;
((ExplosionParams *)MappedSubResource.pData)->g_NoiseScale = g_NoiseScale;
((ExplosionParams *)MappedSubResource.pData)->g_ProjectionParams = g_ProjectionParams;
((ExplosionParams *)MappedSubResource.pData)->g_ScreenParams = XMFLOAT4((FLOAT)kResolutionX, (FLOAT)kResolutionY, 1.f/kResolutionX, 1.f/kResolutionY);
((ExplosionParams *)MappedSubResource.pData)->g_ExplosionPositionWS = kEyeLookAtWS;
((ExplosionParams *)MappedSubResource.pData)->g_ExplosionRadiusWS = g_ExplosionRadius;
((ExplosionParams *)MappedSubResource.pData)->g_NoiseAnimationSpeed = kNoiseAnimationSpeed;
((ExplosionParams *)MappedSubResource.pData)->g_Time = (float)g_ElapsedTime;
((ExplosionParams *)MappedSubResource.pData)->g_EdgeSoftness = g_EdgeSoftness;
((ExplosionParams *)MappedSubResource.pData)->g_NoiseFrequencyFactor = g_NoiseFrequencyFactor;
((ExplosionParams *)MappedSubResource.pData)->g_PrimitiveIdx = g_Primitive;
((ExplosionParams *)MappedSubResource.pData)->g_Opacity = 1.0f;
((ExplosionParams *)MappedSubResource.pData)->g_DisplacementWS = g_DisplacementAmount;
((ExplosionParams *)MappedSubResource.pData)->g_StepSizeWS = kStepSize;
((ExplosionParams *)MappedSubResource.pData)->g_MaxNumSteps = kMaxNumSteps;
((ExplosionParams *)MappedSubResource.pData)->g_UvScaleBias = g_UvScaleBias;
((ExplosionParams *)MappedSubResource.pData)->g_NoiseInitialAmplitude = kNoiseInitialAmplitude;
((ExplosionParams *)MappedSubResource.pData)->g_InvMaxNoiseDisplacement = 1.0f/g_MaxNoiseDisplacement;
((ExplosionParams *)MappedSubResource.pData)->g_NumOctaves = kNumOctaves;
((ExplosionParams *)MappedSubResource.pData)->g_SkinThickness = g_MaxSkinThickness;
((ExplosionParams *)MappedSubResource.pData)->g_NumHullOctaves = kNumHullOctaves;
((ExplosionParams *)MappedSubResource.pData)->g_NumHullSteps = g_EnableHullShrinking ? kNumHullSteps : 0;
((ExplosionParams *)MappedSubResource.pData)->g_TessellationFactor = kTessellationFactor;
}
pContext->Unmap( g_pExplosionParamsCB, 0 );
}
//--------------------------------------------------------------------------------------
// Render a frame
//--------------------------------------------------------------------------------------
void Render()
{
g_pImmediateContext->ClearRenderTargetView( g_pRenderTargetView, Colors::Black );
D3D11_VIEWPORT vp;
vp.Width = (FLOAT)kResolutionX;
vp.Height = (FLOAT)kResolutionY;
vp.MinDepth = 0.0f;
vp.MaxDepth = 1.0f;
vp.TopLeftX = 0;
vp.TopLeftY = 0;
g_pImmediateContext->RSSetViewports( 1, &vp );
const float blendFactor[4] = { 1, 1, 1, 1 };
g_pImmediateContext->OMSetBlendState(g_pOverBlendState, blendFactor, 0xFFFFFFFF);
g_pImmediateContext->OMSetDepthStencilState(g_pTestWriteDepth, 0);
g_pImmediateContext->OMSetRenderTargets( 1, &g_pRenderTargetView, nullptr );
g_pImmediateContext->IASetInputLayout( g_pExplosionLayout );
g_pImmediateContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST );
g_pImmediateContext->VSSetShader( g_pRenderExplosionVS, nullptr, 0 );
g_pImmediateContext->HSSetShader( g_pRenderExplosionHS, nullptr, 0 );
g_pImmediateContext->DSSetShader( g_pRenderExplosionDS, nullptr, 0 );
g_pImmediateContext->PSSetShader( g_pRenderExplosionPS, nullptr, 0 );
UpdateExplosionParams( g_pImmediateContext );
ID3D11SamplerState* const pSamplers[] = { g_pSamplerClampedLinear, g_pSamplerWrappedLinear };
g_pImmediateContext->DSSetSamplers( S_BILINEAR_CLAMPED_SAMPLER, 2, pSamplers );
g_pImmediateContext->PSSetSamplers( S_BILINEAR_CLAMPED_SAMPLER, 2, pSamplers );
g_pImmediateContext->HSSetConstantBuffers( B_EXPLOSION_PARAMS, 1, &g_pExplosionParamsCB );
g_pImmediateContext->DSSetConstantBuffers( B_EXPLOSION_PARAMS, 1, &g_pExplosionParamsCB );
g_pImmediateContext->PSSetConstantBuffers( B_EXPLOSION_PARAMS, 1, &g_pExplosionParamsCB );
g_pImmediateContext->DSSetShaderResources( T_NOISE_VOLUME, 1, &g_pNoiseVolumeSRV );
g_pImmediateContext->PSSetShaderResources( T_NOISE_VOLUME, 1, &g_pNoiseVolumeSRV );
g_pImmediateContext->PSSetShaderResources( T_GRADIENT_TEX, 1, &g_pGradientSRV );
g_pImmediateContext->Draw( 1, 0 );
TwDraw();
g_pSwapChain->Present( 0, 0 );
}<file_sep>/README.md
volumetric-explosions
=====================
This sample project was created using Visual Studio 2012 and was created
to demonstrate the volumetric rendering technique proposed in the book
GPU Pro 6.
Requirements:
Visual Studio 2012
Windows 8 SDK/DirectX 11
| 6f5052aa2b113471ed03d0bce678fbadf8147528 | [
"Markdown",
"C",
"C++"
] | 3 | C | JustinCredibleGIT/volumetric-explosions | c0e2ff4f71a0f7dbb0ae7c766fbc972884053b4f | 3fc3f94b09fffbaa04b3697d9020f2a50b0e397b | |
refs/heads/main | <repo_name>alexg-rgb/cssGrid<file_sep>/script.js
livingPlace = prompt("Tell me where you live \n 3 questions left");
reasonWhy = prompt("Now tell me why you live there \n 2 questions left");
greatPlaceQ = prompt("And do you like this place \n 1 questions left");
favouriteTea = prompt("What's your favourite tea ? \n Last one thanks");
storyTeller = (greatPlaceQ) +", "+ (favouriteTea)+", "+(livingPlace) +", "+ (reasonWhy);
alert(storyTeller);
var t =
document.getElementById("firstCell").innerHTML = "Bonjour";
document.getElementById("firstCell").style.color = "yellow"; | 70a788a66153e82df8e9ae409cfb0ccdc4cf7d6f | [
"JavaScript"
] | 1 | JavaScript | alexg-rgb/cssGrid | a70f768092731891724d8b1b7682502fd7d0a7b4 | 4ab098330feda584ee499dcd686f055b7fac6d5b | |
refs/heads/master | <file_sep>package test.com.ctrip.platform.dal.dao.configure.file;
import com.ctrip.platform.dal.dao.configure.DataSourceConfigureConstants;
import com.ctrip.platform.dal.dao.configure.file.PropertyFilePoolPropertiesProvider;
import org.junit.Assert;
import org.junit.Test;
import java.util.Map;
public class PropertyFilePoolPropertiesProviderTest implements DataSourceConfigureConstants {
@Test
public void testPropertyFilePoolPropertiesProvider() throws Exception {
PropertyFilePoolPropertiesProvider provider = new PropertyFilePoolPropertiesProvider();
Map<String, String> map = provider.getPoolProperties();
// Custom value
Assert.assertEquals(map.get(MINIDLE), "1");
// Default value
Assert.assertEquals(map.get(MAXACTIVE), String.valueOf(DEFAULT_MAXACTIVE));
}
}
<file_sep>package com.ctrip.platform.dal.dao.configure.file;
import com.ctrip.platform.dal.dao.configure.DataSourceConfigure;
import com.ctrip.platform.dal.dao.datasource.ConnectionStringChanged;
import com.ctrip.platform.dal.dao.datasource.ConnectionStringProvider;
import java.io.File;
import java.io.FileReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public class PropertyFileConnectionStringProvider implements ConnectionStringProvider {
private static final String PROPERTY_FILE_NAME = "database.properties";
private static final String USER_NAME = ".userName";
private static final String PASSWORD = <PASSWORD>";
private static final String CONNECTION_URL = ".connectionUrl";
private static final String DRIVER_CLASS_NAME = ".driverClassName";
private Properties properties = new Properties();
public PropertyFileConnectionStringProvider() {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null) {
classLoader = PropertyFileConnectionStringProvider.class.getClassLoader();
}
URL url = classLoader.getResource(PROPERTY_FILE_NAME);
if (url == null)
return;
try {
properties.load(new FileReader(new File(url.toURI())));
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
@Override
public Map<String, DataSourceConfigure> getConnectionStrings(Set<String> dbNames) throws Exception {
if (dbNames == null || dbNames.isEmpty())
return null;
Map<String, DataSourceConfigure> map = new HashMap<>();
for (String name : dbNames) {
DataSourceConfigure configure = new DataSourceConfigure();
configure.setUserName(properties.getProperty(name + USER_NAME));
configure.setPassword(properties.getProperty(name + PASSWORD));
configure.setConnectionUrl(properties.getProperty(name + CONNECTION_URL));
configure.setDriverClass(properties.getProperty(name + DRIVER_CLASS_NAME));
map.put(name, configure);
}
return map;
}
@Override
public void addConnectionStringChangedListener(String name, ConnectionStringChanged callback) {}
}
<file_sep>package com.ctrip.platform.dal.dao.datasource;
import java.util.Map;
public interface PoolPropertiesProvider {
Map<String, String> getPoolProperties();
void addPoolPropertiesChangedListener(final PoolPropertiesChanged callback);
}
<file_sep>package com.ctrip.platform.dal.dao.datasource;
import java.sql.Connection;
import java.util.Map;
import java.util.Set;
import com.ctrip.platform.dal.dao.client.DalConnectionLocator;
import com.ctrip.platform.dal.dao.configure.DataSourceConfigureProvider;
import com.ctrip.platform.dal.dao.configure.DefaultDataSourceConfigureProvider;
import com.ctrip.platform.dal.dao.helper.ConnectionStringKeyHelper;
import javax.sql.DataSource;
public class DefaultDalConnectionLocator implements DalConnectionLocator {
private static final String DATASOURCE_CONFIG_PROVIDER = "dataSourceConfigureProvider";
private DataSourceConfigureProvider provider;
private DataSourceLocator locator;
@Override
public void initialize(Map<String, String> settings) throws Exception {
provider = new DefaultDataSourceConfigureProvider();
if (settings.containsKey(DATASOURCE_CONFIG_PROVIDER)) {
provider =
(DataSourceConfigureProvider) Class.forName(settings.get(DATASOURCE_CONFIG_PROVIDER)).newInstance();
}
provider.initialize(settings);
locator = new DataSourceLocator(provider);
}
@Override
public void setup(Set<String> dbNames) {
provider.setup(dbNames);
}
@Override
public Connection getConnection(String name) throws Exception {
String keyName = ConnectionStringKeyHelper.getKeyName(name);
DataSource dataSource = locator.getDataSource(keyName);
return dataSource.getConnection();
}
}
<file_sep>package com.ctrip.platform.dal.dao.configure;
import com.ctrip.platform.dal.exceptions.DalException;
/**
* Setup at global level to simplify
*
* @author jhhe
*
*/
public interface DatabaseSelector {
String select(SelectionContext context) throws DalException;
}
<file_sep>package test.com.ctrip.platform.dal.dao.configure.file;
import com.ctrip.platform.dal.dao.configure.DataSourceConfigure;
import com.ctrip.platform.dal.dao.configure.DataSourceConfigureConstants;
import com.ctrip.platform.dal.dao.configure.file.PropertyFileConnectionStringProvider;
import org.junit.Assert;
import org.junit.Test;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class PropertyFileConnectionStringProviderTest implements DataSourceConfigureConstants {
private static final String NAME = "test";
@Test
public void testPropertyFileConnectionStringProvider() throws Exception {
PropertyFileConnectionStringProvider provider = new PropertyFileConnectionStringProvider();
Set<String> names = new HashSet<>();
names.add(NAME);
Map<String, DataSourceConfigure> map = provider.getConnectionStrings(names);
DataSourceConfigure configure = map.get(NAME);
Assert.assertEquals(configure.getUserName(), "testUser");
Assert.assertEquals(configure.getPassword(), "<PASSWORD>");
Assert.assertEquals(configure.getConnectionUrl(), "jdbc:mysql://testIP:3306/testDb");
Assert.assertEquals(configure.getDriverClass(), "com.mysql.jdbc.Driver");
}
}
| 67ab5fdcc775efe1598f7f24de4b7e45c31b82a1 | [
"Java"
] | 6 | Java | gaolufree/dal | b33b74c7dccb27c0293d3abf82c4658c25e7c642 | 97e18dfdcbce87550e2292c7a417b4c0f1791cf4 | |
refs/heads/master | <file_sep>/*12
Entregable_10 con clases
Programa: proyecto control de ingresos hospitalarios
Estructura: selectiva multiple y repetitiva do while y while con arreglos y objetos
Autor: <NAME>
N° lista: 7
Fecha: 5 de marzo del 2015
Implementar la clase Medicamento (Superclase) y Medicamento_perecedero (Subclase) del proyecto.
En ambas clases implementar los métodos: Capturar, Mostrar, Buscar y Modificar.
*/
#include <iostream>
#include <string>
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>//getch
using namespace std;
//Clase medicamento
class medicamento
{
public:
string idmedicin, medicamentos[13];
int k, consec, consem, cuan;
void capturarM ();
void mostrarM ();
void buscarM ();
void modificarM ();
friend class m_perecedero;
}medicament;
medicamento existencia[10];
void medicamento::capturarM()
{
consec=1;
for (k=0; k<10; k++)
{
system ("cls");
cout<<"\t\t****** MEDICAMENTOS ******\n\n ";
cout<<"\tIngrese los datos del medicamento consecutivo numero: "<<consec;
cout<<endl<<endl;
cout<<"\tId del medicamento: ";
cin>>existencia[k].medicamentos[0];
cin.ignore();
cout<<"\n";
cout<<"\tNombre: ";
cin>>existencia[k].medicamentos[1];
cin.ignore();
cout<<"\tIngrediente activo: ";
cin>>existencia[k].medicamentos[2];
cin.ignore();
cout<<"\n";
cout<<"\tPresentacion: ";
cin>>existencia[k].medicamentos[3];
cin.ignore();
cout<<"\tMiligramos: ";
cin>>existencia[k].medicamentos[4];
cin.ignore();
cout<<"\tContenido: ";
cin>>existencia[k].medicamentos[5];
cin.ignore();
cout<<"\n";
cout<<"\tVia de administracion: ";
cin>>existencia[k].medicamentos[6];
cin.ignore();
cout<<"\tDosis: ";
cin>>existencia[k].medicamentos[7];
cin.ignore();
cout<<"\n";
cout<<"\tLote: ";
cin>>existencia[k].medicamentos[8];
cin.ignore();
cout<<"\n";
cout<<"\tPrecio maximo al publico: ";
cin>>existencia[k].medicamentos[9];
cin.ignore();
cout<<"\tMarca: ";
cin>>existencia[k].medicamentos[10];
cout<<"\tProcedencia: ";
cin>>existencia[k].medicamentos[11];
cout<<"\n\t\t\t\t\t";
system ("pause");
system ("cls");
cout<<"\t\t****** MEDICAMENTOS ******\n\n ";
cout<<"\tMedicamento capturado, numero consecutivo: "<<consec;
cout<<"\n\n\tDesea capturar otro medicamento?\n\n\a";
cout<<"\t 1.- Si \n\t 2.- No \n\n";
cout<<"\tElige una opcion: ";
cin>>cuan;
if (cuan==1)
{
cout<<"\n\n\t\t\t";
consec++;
system ("pause");
}
else
{
k=10;
cout<<"\t\t\t\t\t";
system ("pause");
}
}// fin del bucle for
}
void medicamento::mostrarM()
{
consem=1;
for (k=0; k<consec; k++)
{
system ("cls");
cout<<"\t\t****** MEDICAMENTOS ******\n\n ";
cout<<"\tDatos del medicamento consecutivo numero: "<<consem;
cout<<endl<<endl;
cout<<"\tId del medicamento: "<<existencia[k].medicamentos[0]<<"\n\n";
cout<<"\tNombre: "<<existencia[k].medicamentos[1]<<"\n";
cout<<"\tIngrediente activo: "<<existencia[k].medicamentos[2]<<"\n\n";
cout<<"\tPresentacion: "<<existencia[k].medicamentos[3]<<"\n";
cout<<"\tMiligramos: "<<existencia[k].medicamentos[4]<<"\n";
cout<<"\tContenido: "<<existencia[k].medicamentos[5]<<"\n\n";
cout<<"\tVia de administracion: "<<existencia[k].medicamentos[6]<<"\n";
cout<<"\tDosis: "<<existencia[k].medicamentos[7]<<"\n\n";
cout<<"\tLote: "<<existencia[k].medicamentos[8]<<"\n\n";
cout<<"\tPrecio maximo al publico: "<<existencia[k].medicamentos[9]<<"\n";
cout<<"\tMarca: "<<existencia[k].medicamentos[10]<<"\n";
cout<<"\tProcedencia: "<<existencia[k].medicamentos[11]<<"\n";
consem++;
cout<<"\n\t\t\t\t\t";
system ("pause");
}// fin del bucle for
}
void medicamento::buscarM()
{
system ("cls");
cout<<"\t\t****** MEDICAMENTOS ******\n\n ";
cout<<"\nIngresa id del medicamento a buscar: ";
cin>>idmedicin;
for (k=0; k<10; k++)
{
if (idmedicin==existencia[k].medicamentos[0])
{
//mostrar expediente encontrado
system ("cls");
cout<<"\t\t****** MEDICAMENTOS ******\n\n ";
cout<<"\tDatos del medicamento encontrado: ";
cout<<endl<<endl;
cout<<"\tId del medicamento: "<<existencia[k].medicamentos[0]<<"\n\n";
cout<<"\tNombre: "<<existencia[k].medicamentos[1]<<"\n";
cout<<"\tIngrediente activo: "<<existencia[k].medicamentos[2]<<"\n\n";
cout<<"\tPresentacion: "<<existencia[k].medicamentos[3]<<"\n";
cout<<"\tMiligramos: "<<existencia[k].medicamentos[4]<<"\n";
cout<<"\tContenido: "<<existencia[k].medicamentos[5]<<"\n\n";
cout<<"\tVia de administracion: "<<existencia[k].medicamentos[6]<<"\n";
cout<<"\tDosis: "<<existencia[k].medicamentos[7]<<"\n\n";
cout<<"\tLote: "<<existencia[k].medicamentos[8]<<"\n\n";
cout<<"\tPrecio maximo al publico: "<<existencia[k].medicamentos[9]<<"\n";
cout<<"\tMarca: "<<existencia[k].medicamentos[10]<<"\n";
cout<<"\tProcedencia: "<<existencia[k].medicamentos[11]<<"\n";
cout<<"\n\t\t\t\t\t";
system ("pause");
break;
}//fin del if buscar
}//fin del ciclo for buscar
if (k>9)
{
cout<<"\n\n\t\t\tNO EXISTE MEDICAMENTO, INTENTA DE NUEVO...\n\n\t\t\t\t";
system ("pause");
}
}
void medicamento::modificarM()
{
system ("cls");
cout<<"\t\t****** MEDICAMENTOS ******\n\n ";
cout<<"\nIngresa id del medicamento a modificar: ";
cin>>idmedicin;
bool hallado = false;
for (k=0; k<10; k++)
{
if (idmedicin==existencia[k].medicamentos[0])
{
//mostrar expediente encontrado
system ("cls");
cout<<"\t\t****** MEDICAMENTOS ******\n\n ";
cout<<"\tDatos del medicamento encontrado para modificar: ";
cout<<endl<<endl;
cout<<"\tId del medicamento: "<<existencia[k].medicamentos[0]<<"\n\n";
cout<<"\tNombre: "<<existencia[k].medicamentos[1]<<"\n";
cout<<"\tIngrediente activo: "<<existencia[k].medicamentos[2]<<"\n\n";
cout<<"\tPresentacion: "<<existencia[k].medicamentos[3]<<"\n";
cout<<"\tMiligramos: "<<existencia[k].medicamentos[4]<<"\n";
cout<<"\tContenido: "<<existencia[k].medicamentos[5]<<"\n\n";
cout<<"\tVia de administracion: "<<existencia[k].medicamentos[6]<<"\n";
cout<<"\tDosis: "<<existencia[k].medicamentos[7]<<"\n\n";
cout<<"\tLote: "<<existencia[k].medicamentos[8]<<"\n\n";
cout<<"\tPrecio maximo al publico: "<<existencia[k].medicamentos[9]<<"\n";
cout<<"\tMarca: "<<existencia[k].medicamentos[10]<<"\n";
cout<<"\tProcedencia: "<<existencia[k].medicamentos[11]<<"\n";
cout<<"\n\t\t\t\t\t";
system ("pause");
system ("cls");
cout<<"\n";
cout<<"\n\t*******************************";
cout<<"\n\t** MEDICAMENTOS **";
cout<<"\n\t** MENU DE MODIFICACIONES **";
cout<<"\n\t** **";
cout<<"\n\t** 1.- Nombre **";
cout<<"\n\t** 2.- Ingrediente activo **";
cout<<"\n\t** 3.- Presentacion **";
cout<<"\n\t** 4.- Miligramos **";
cout<<"\n\t** 5.- Contenido **";
cout<<"\n\t** 6.- Via de adm. y Dosis **";
cout<<"\n\t** 7.- Lote **";
cout<<"\n\t** 8.- Precio y marca **";
cout<<"\n\t** 9.- Procedencia **";
cout<<"\n\t** **";
cout<<"\n\t** 10.- TODOS LOS ANTERIORES **";
cout<<"\n\t** **";
cout<<"\n\t** 11.- CANCELAR **";
cout<<"\n\t** **";
cout<<"\n\t*******************************";
cout<<"\n\t* Elige una opcion:__";
int modif;
cin>>modif;
switch (modif)
{
case 1:
system ("cls");
cout<<"\t\t****** MEDICAMENTOS ******\n\n ";
cout<<"\tModificacion del nombre \n\n";
cout<<"\tNombre: ";
cin>>existencia[k].medicamentos[1];
cout<<"\n\t\t\t\t\t";
break;
case 2:
system ("cls");
cout<<"\t\t****** MEDICAMENTOS ******\n\n ";
cout<<"\tModificacion del ingrediente activo \n\n";
cout<<"\tiIngrediente activo: ";
cin>>existencia[k].medicamentos[2];
cout<<"\n\t\t\t\t\t";
break;
case 3:
system ("cls");
cout<<"\t\t****** MEDICAMENTOS ******\n\n ";
cout<<"\tModificacion de la presentacion \n\n";
cout<<"\tPresentacion: ";
cin>>existencia[k].medicamentos[3];
cout<<"\n\t\t\t\t\t";
break;
case 4:
system ("cls");
cout<<"\t\t****** MEDICAMENTOS ******\n\n ";
cout<<"\tModificacion de los miligramos \n\n";
cout<<"\tMiligramos: ";
cin>>existencia[k].medicamentos[4];
cout<<"\n\t\t\t\t\t";
break;
case 5:
system ("cls");
cout<<"\t\t****** MEDICAMENTOS ******\n\n ";
cout<<"\tModificacion del contenido \n\n";
cout<<"\tContenido: ";
cin>>existencia[k].medicamentos[5];
cout<<"\n\t\t\t\t\t";
break;
case 6:
system ("cls");
cout<<"\t\t****** MEDICAMENTOS ******\n\n ";
cout<<"\tModificacion de la via de administracion y dosis \n\n";
cout<<"\tVia de administracion: ";
cin>>existencia[k].medicamentos[6];
cout<<"\tDosis: ";
cin>>existencia[k].medicamentos[7];
cout<<"\n\t\t\t\t\t";
break;
case 7:
system ("cls");
cout<<"\t\t****** MEDICAMENTOS ******\n\n ";
cout<<"\tModificacion del lote \n\n";
cout<<"\tLote: ";
cin>>existencia[k].medicamentos[8];
cout<<"\n\t\t\t\t\t";
break;
case 8:
system ("cls");
cout<<"\t\t****** MEDICAMENTOS ******\n\n ";
cout<<"\tModificacion del precio y la marca \n\n";
cout<<"\tPrecio: ";
cin>>existencia[k].medicamentos[9];
cout<<"\tMarca: ";
cin>>existencia[k].medicamentos[10];
cout<<"\n\t\t\t\t\t";
break;
case 9:
system ("cls");
cout<<"\t\t****** MEDICAMENTOS ******\n\n ";
cout<<"\tModificacion de la procedencia \n\n";
cout<<"\tProcedencia: ";
cin>>existencia[k].medicamentos[11];
cout<<"\n\t\t\t\t\t";
break;
case 10:
system ("cls");
cout<<"\t\t****** MEDICAMENTOS ******\n\n ";
cout<<"\tModificacion de todos los datos del medicamento encontrado \n\n";
cout<<"\tNombre: ";
cin>>existencia[k].medicamentos[1];
cout<<"\n\n";
cout<<"\tiIngrediente activo: ";
cin>>existencia[k].medicamentos[2];
cout<<"\tPresentacion: ";
cin>>existencia[k].medicamentos[3];
cout<<"\tMiligramos: ";
cin>>existencia[k].medicamentos[4];
cout<<"\n";
cout<<"\tContenido: ";
cin>>existencia[k].medicamentos[5];
cout<<"\n";
cout<<"\tVia de administracion: ";
cin>>existencia[k].medicamentos[6];
cout<<"\tDosis: ";
cin>>existencia[k].medicamentos[7];
cout<<"\tLote: ";
cin>>existencia[k].medicamentos[8];
cout<<"\tPrecio: ";
cin>>existencia[k].medicamentos[9];
cout<<"\n";
cout<<"\tMarca: ";
cin>>existencia[k].medicamentos[10];
cout<<"\tProcedencia: ";
cin>>existencia[k].medicamentos[11];
cout<<"\n\t\t\t\t\t";
break;
case 11:
cout<<"\n\n\t\tCancelar... \n\n\n\t\t\t\t\t";
break;
default:
cout<<"\n\n\t\tHa elegido una opcion inexistente, intente de nuevo; atras... \n\n\n\t\t\t\t\t";
}//Fin del switch de modificaciones
cout<<"\n\t\t\t\t\t";
system ("pause");
hallado=true;
}//Fin del if
}//Fin del ciclo for
if (hallado==true)
Sleep(1000);
else
if (hallado==false)
{
cout<<"\n\n\t\t\tNO EXISTE MEDICAMENTO, INTENTA DE NUEVO...\n\n\t\t\t\t";
system ("pause");
}
}
//Clase medicamento o perecedero
class m_perecedero : public medicamento
{
public:
//string perecedero[13];
void capturarMP ();
void mostrarMP ();
void buscarMP ();
void modificarMP ();
friend class medicamento;
}m_pereceder;
m_perecedero existencias[10];
void m_perecedero::capturarMP()
{
consec=1;
for (k=0; k<10; k++)
{
system ("cls");
cout<<"\t\t****** PERECEDEROS ******\n\n ";
cout<<"\tIngrese los datos del perecedero consecutivo numero: "<<consec;
cout<<endl<<endl;
cout<<"\tId del perecedero: ";
cin>>existencias[k].medicamentos[0];
cin.ignore();
cout<<"\n";
cout<<"\tNombre: ";
cin>>existencias[k].medicamentos[1];
cin.ignore();
cout<<"\tIngrediente activo: ";
cin>>existencias[k].medicamentos[2];
cin.ignore();
cout<<"\n";
cout<<"\tPresentacion: ";
cin>>existencias[k].medicamentos[3];
cin.ignore();
cout<<"\tMiligramos: ";
cin>>existencias[k].medicamentos[4];
cin.ignore();
cout<<"\tContenido: ";
cin>>existencias[k].medicamentos[5];
cin.ignore();
cout<<"\n";
cout<<"\tVia de administracion: ";
cin>>existencias[k].medicamentos[6];
cin.ignore();
cout<<"\tDosis: ";
cin>>existencias[k].medicamentos[7];
cin.ignore();
cout<<"\n";
cout<<"\tLote: ";
cin>>existencias[k].medicamentos[8];
cin.ignore();
cout<<"\tCaducidad: ";
cin>>existencias[k].medicamentos[9];
cin.ignore();
cout<<"\n";
cout<<"\tPrecio maximo al publico: ";
cin>>existencias[k].medicamentos[10];
cin.ignore();
cout<<"\tMarca: ";
cin>>existencias[k].medicamentos[11];
cout<<"\tProcedencia: ";
cin>>existencias[k].medicamentos[12];
cout<<"\n\t\t\t\t\t";
system ("pause");
system ("cls");
cout<<"\t\t****** PERECEDEROS ******\n\n ";
cout<<"\tPerecedero capturado, numero consecutivo: "<<consec;
cout<<"\n\n\tDesea capturar otro perecedero?\n\n\a";
cout<<"\t 1.- Si \n\t 2.- No \n\n";
cout<<"\tElige una opcion: ";
cin>>cuan;
if (cuan==1)
{
cout<<"\n\n\t\t\t";
consec++;
system ("pause");
}
else
{
k=10;
cout<<"\t\t\t\t\t";
system ("pause");
}
}// fin del bucle for
}
void m_perecedero::mostrarMP()
{
consem=1;
for (k=0; k<consec; k++)
{
system ("cls");
cout<<"\t\t****** PERECEDEROS ******\n\n ";
cout<<"\tDatos del perecedero consecutivo numero: "<<consem;
cout<<endl<<endl;
cout<<"\tId del perecedero: "<<existencias[k].medicamentos[0]<<"\n\n";
cout<<"\tNombre: "<<existencias[k].medicamentos[1]<<"\n";
cout<<"\tIngrediente activo: "<<existencias[k].medicamentos[2]<<"\n\n";
cout<<"\tPresentacion: "<<existencias[k].medicamentos[3]<<"\n";
cout<<"\tMiligramos: "<<existencias[k].medicamentos[4]<<"\n";
cout<<"\tContenido: "<<existencias[k].medicamentos[5]<<"\n\n";
cout<<"\tVia de administracion: "<<existencias[k].medicamentos[6]<<"\n";
cout<<"\tDosis: "<<existencias[k].medicamentos[7]<<"\n\n";
cout<<"\tLote: "<<existencias[k].medicamentos[8]<<"\n";
cout<<"\tCaducidad: "<<existencias[k].medicamentos[9]<<"\n\n";
cout<<"\tPrecio maximo al publico: "<<existencias[k].medicamentos[10]<<"\n";
cout<<"\tMarca: "<<existencias[k].medicamentos[11]<<"\n";
cout<<"\tProcedencia: "<<existencias[k].medicamentos[12]<<"\n";
consem++;
cout<<"\n\t\t\t\t\t";
system ("pause");
}// fin del bucle for
}
void m_perecedero::buscarMP()
{
system ("cls");
cout<<"\t\t****** PERECEDEROS ******\n\n ";
cout<<"\nIngresa id del perecedero a buscar: ";
cin>>idmedicin;
for (k=0; k<10; k++)
{
if (idmedicin==existencias[k].medicamentos[0])
{
//mostrar expediente encontrado
system ("cls");
cout<<"\t\t****** PERECEDEROS ******\n\n ";
cout<<"\tDatos del perecedero encontrado: ";
cout<<endl<<endl;
cout<<"\tId del perecedero: "<<existencias[k].medicamentos[0]<<"\n\n";
cout<<"\tNombre: "<<existencias[k].medicamentos[1]<<"\n";
cout<<"\tIngrediente activo: "<<existencias[k].medicamentos[2]<<"\n\n";
cout<<"\tPresentacion: "<<existencias[k].medicamentos[3]<<"\n";
cout<<"\tMiligramos: "<<existencias[k].medicamentos[4]<<"\n";
cout<<"\tContenido: "<<existencias[k].medicamentos[5]<<"\n\n";
cout<<"\tVia de administracion: "<<existencias[k].medicamentos[6]<<"\n";
cout<<"\tDosis: "<<existencias[k].medicamentos[7]<<"\n\n";
cout<<"\tLote: "<<existencias[k].medicamentos[8]<<"\n";
cout<<"\tCaducidad: "<<existencias[k].medicamentos[9]<<"\n\n";
cout<<"\tPrecio maximo al publico: "<<existencias[k].medicamentos[10]<<"\n";
cout<<"\tMarca: "<<existencias[k].medicamentos[11]<<"\n";
cout<<"\tProcedencia: "<<existencias[k].medicamentos[12]<<"\n";
cout<<"\n\t\t\t\t\t";
system ("pause");
break;
}//fin del if buscar
}//fin del ciclo for buscar
if (k>9)
{
cout<<"\n\n\t\t\tNO EXISTE PERECEDERO, INTENTA DE NUEVO...\n\n\t\t\t\t";
system ("pause");
}
}
void m_perecedero::modificarMP()
{
system ("cls");
cout<<"\t\t****** PERECEDEROS ******\n\n ";
cout<<"\nIngresa id del perecedero a modificar: ";
cin>>idmedicin;
bool hallado = false;
for (k=0; k<10; k++)
{
if (idmedicin==existencias[k].medicamentos[0])
{
//mostrar expediente encontrado
system ("cls");
cout<<"\t\t****** PERECEDEROS ******\n\n ";
cout<<"\tDatos del perecedero encontrado para modificar: ";
cout<<endl<<endl;
cout<<"\tId del perecedero: "<<existencias[k].medicamentos[0]<<"\n\n";
cout<<"\tNombre: "<<existencias[k].medicamentos[1]<<"\n";
cout<<"\tIngrediente activo: "<<existencias[k].medicamentos[2]<<"\n\n";
cout<<"\tPresentacion: "<<existencias[k].medicamentos[3]<<"\n";
cout<<"\tMiligramos: "<<existencias[k].medicamentos[4]<<"\n";
cout<<"\tContenido: "<<existencias[k].medicamentos[5]<<"\n\n";
cout<<"\tVia de administracion: "<<existencias[k].medicamentos[6]<<"\n";
cout<<"\tDosis: "<<existencias[k].medicamentos[7]<<"\n\n";
cout<<"\tLote: "<<existencias[k].medicamentos[8]<<"\n";
cout<<"\tCaducidad: "<<existencias[k].medicamentos[9]<<"\n\n";
cout<<"\tPrecio maximo al publico: "<<existencias[k].medicamentos[10]<<"\n";
cout<<"\tMarca: "<<existencias[k].medicamentos[11]<<"\n";
cout<<"\tProcedencia: "<<existencias[k].medicamentos[12]<<"\n";
cout<<"\n\t\t\t\t\t";
system ("pause");
system ("cls");
cout<<"\n";
cout<<"\n\t*******************************";
cout<<"\n\t** PERECEDEROS **";
cout<<"\n\t** MENU DE MODIFICACIONES **";
cout<<"\n\t** **";
cout<<"\n\t** 1.- Nombre **";
cout<<"\n\t** 2.- Ingrediente activo **";
cout<<"\n\t** 3.- Presentacion **";
cout<<"\n\t** 4.- Miligramos **";
cout<<"\n\t** 5.- Contenido **";
cout<<"\n\t** 6.- Via de adm. y Dosis **";
cout<<"\n\t** 7.- Lote y caducidad **";
cout<<"\n\t** 8.- Precio y marca **";
cout<<"\n\t** 9.- Procedencia **";
cout<<"\n\t** **";
cout<<"\n\t** 10.- TODOS LOS ANTERIORES **";
cout<<"\n\t** **";
cout<<"\n\t** 11.- CANCELAR **";
cout<<"\n\t** **";
cout<<"\n\t*******************************";
cout<<"\n\t* Elige una opcion:__";
int modif;
cin>>modif;
switch (modif)
{
case 1:
system ("cls");
cout<<"\t\t****** PERECEDEROS ******\n\n ";
cout<<"\tModificacion del nombre \n\n";
cout<<"\tNombre: ";
cin>>existencias[k].medicamentos[1];
cout<<"\n\t\t\t\t\t";
break;
case 2:
system ("cls");
cout<<"\t\t****** PERECEDEROS ******\n\n ";
cout<<"\tModificacion del ingrediente activo \n\n";
cout<<"\tiIngrediente activo: ";
cin>>existencias[k].medicamentos[2];
cout<<"\n\t\t\t\t\t";
break;
case 3:
system ("cls");
cout<<"\t\t****** PERECEDEROS ******\n\n ";
cout<<"\tModificacion de la presentacion \n\n";
cout<<"\tPresentacion: ";
cin>>existencias[k].medicamentos[3];
cout<<"\n\t\t\t\t\t";
break;
case 4:
system ("cls");
cout<<"\t\t****** PERECEDEROS ******\n\n ";
cout<<"\tModificacion de los miligramos \n\n";
cout<<"\tMiligramos: ";
cin>>existencias[k].medicamentos[4];
cout<<"\n\t\t\t\t\t";
break;
case 5:
system ("cls");
cout<<"\t\t****** PERECEDEROS ******\n\n ";
cout<<"\tModificacion del contenido \n\n";
cout<<"\tContenido: ";
cin>>existencias[k].medicamentos[5];
cout<<"\n\t\t\t\t\t";
break;
case 6:
system ("cls");
cout<<"\t\t****** PERECEDEROS ******\n\n ";
cout<<"\tModificacion de la via de administracion y dosis \n\n";
cout<<"\tVia de administracion: ";
cin>>existencias[k].medicamentos[6];
cout<<"\tDosis: ";
cin>>existencias[k].medicamentos[7];
cout<<"\n\t\t\t\t\t";
break;
case 7:
system ("cls");
cout<<"\t\t****** PERECEDEROS ******\n\n ";
cout<<"\tModificacion del lote y caducidad \n\n";
cout<<"\tLote: ";
cin>>existencias[k].medicamentos[8];
cout<<"\tCaducidad: ";
cin>>existencias[k].medicamentos[9];
cout<<"\n\t\t\t\t\t";
break;
case 8:
system ("cls");
cout<<"\t\t****** PERECEDEROS ******\n\n ";
cout<<"\tModificacion del precio y la marca \n\n";
cout<<"\tPrecio: ";
cin>>existencias[k].medicamentos[10];
cout<<"\tMarca: ";
cin>>existencias[k].medicamentos[11];
cout<<"\n\t\t\t\t\t";
break;
case 9:
system ("cls");
cout<<"\t\t****** PERECEDEROS ******\n\n ";
cout<<"\tModificacion de la procedencia \n\n";
cout<<"\tProcedencia: ";
cin>>existencias[k].medicamentos[12];
cout<<"\n\t\t\t\t\t";
break;
case 10:
system ("cls");
cout<<"\t\t****** PERECEDEROS ******\n\n ";
cout<<"\tModificacion de todos los datos del medicamento encontrado \n\n";
cout<<"\tNombre: ";
cin>>existencias[k].medicamentos[1];
cout<<"\n\n";
cout<<"\tiIngrediente activo: ";
cin>>existencias[k].medicamentos[2];
cout<<"\tPresentacion: ";
cin>>existencias[k].medicamentos[3];
cout<<"\tMiligramos: ";
cin>>existencias[k].medicamentos[4];
cout<<"\n";
cout<<"\tContenido: ";
cin>>existencias[k].medicamentos[5];
cout<<"\n";
cout<<"\tVia de administracion: ";
cin>>existencias[k].medicamentos[6];
cout<<"\tDosis: ";
cin>>existencias[k].medicamentos[7];
cout<<"\tLote: ";
cin>>existencias[k].medicamentos[8];
cout<<"\tCaducidad: ";
cin>>existencias[k].medicamentos[9];
cout<<"\tPrecio: ";
cin>>existencias[k].medicamentos[10];
cout<<"\n";
cout<<"\tMarca: ";
cin>>existencias[k].medicamentos[11];
cout<<"\tProcedencia: ";
cin>>existencias[k].medicamentos[12];
cout<<"\n\t\t\t\t\t";
break;
case 11:
cout<<"\n\n\t\tCancelar... \n\n\n\t\t\t\t\t";
break;
default:
cout<<"\n\n\t\tHa elegido una opcion inexistente, intente de nuevo; atras... \n\n\n\t\t\t\t\t";
}//Fin del switch de modificaciones
cout<<"\n\t\t\t\t\t";
system ("pause");
hallado=true;
}//Fin del if
}//Fin del ciclo for
if (hallado==true)
Sleep(1000);
else
if (hallado==false)
{
cout<<"\n\n\t\t\tNO EXISTE PERECEDERO, INTENTA DE NUEVO...\n\n\t\t\t\t";
system ("pause");
}
}
//Clase expediente
class expediente
{
public:
/*
Cuando el paciente ingresa, se le abre un expediente con los siguientes datos:
idexpediente, fechaexpediente, idpaciente, medico, peso, estatura, medicamento, dosis, hora.
Para buscar un expediente se necesitara realizar de nuevo una búsqueda del expediente que se desee
consultar solicitando el idexpedientedel paciente.
*/
string idexpe, expedientes[11];
int y, cuan, cec, cem;
void capturar ();
void mostrar ();
void buscar ();
void modificar();
friend class paciente;
}expedient;
expediente regist [10];
void expediente::capturar()
{
//capturar expediente
cec=1;
for (y=0; y<10; y++)
{
system ("cls");
cout<<"\t\t****** EXPEDIENTES ******\n\n ";
cout<<"\tIngrese los datos del expediente consecutivo numero: "<<cec;
cout<<endl<<endl;
cout<<"\tId del expediente: ";
cin>>regist[y].expedientes[0];
cin.ignore();
cout<<"\n";
cout<<"\tFecha de ingreso ";
cout<<"\n\n";
cout<<"\tDia: ";
cin>>regist[y].expedientes[1];
cin.ignore();
cout<<"\tMes: ";
cin>>regist[y].expedientes[2];
cin.ignore();
cout<<"\tAnio: ";
cin>>regist[y].expedientes[3];
cin.ignore();
cout<<"\n";
cout<<"\tId paciente: ";
cin>>regist[y].expedientes[4];
cin.ignore();
cout<<"\n";
cout<<"\tPeso (Kg): ";
cin>>regist[y].expedientes[5];
cin.ignore();
cout<<"\tEstatura (m): ";
cin>>regist[y].expedientes[6];
cin.ignore();
cout<<"\tMedicamento: ";
cin>>regist[y].expedientes[7];
cin.ignore();
cout<<"\tDosis: ";
cin>>regist[y].expedientes[8];
cin.ignore();
cout<<"\tHora: ";
cin>>regist[y].expedientes[9];
cin.ignore();
cout<<"\n";
cout<<"\tMedico que atiende: ";
cin>>regist[y].expedientes[10];
cout<<"\n\n\t\t\t\t\t";
system ("pause");
system ("cls");
cout<<"\t\t****** EXPEDIENTES ******\n\n ";
cout<<"\tExpediente capturado, numero consecutivo: "<<cec;
cout<<"\n\n\tDesea capturar otro expediente de paciente?\n\n\a";
cout<<"\t 1.- Si \n\t 2.- No \n\n";
cout<<"\tElige una opcion: ";
cin>>cuan;
if (cuan==1)
{
cout<<"\n\n\t\t\t";
cec++;
system ("pause");
}
else
{
y=10;
cout<<"\t\t\t\t\t";
system ("pause");
}
}// fin del bucle for
}
void expediente::mostrar()
{
//mostrar expediente
system ("cls");
cem=1;
for (y=0; y<cec; y++)
{
cout<<"\t\t****** EXPEDIENTES ******\n\n ";
cout<<"\n\tDatos del expediente consecutivo numero: "<<cem;
cout<<endl<<endl;
cout<<"\tId del expediente: "<<regist[y].expedientes[0]<<"\n\n";
cout<<"\tFecha de ingreso "<<"\n\n";
cout<<"\tDia: "<<regist[y].expedientes[1]<<"\n";
cout<<"\tMes: "<<regist[y].expedientes[2]<<"\n";
cout<<"\tAnio: "<<regist[y].expedientes[3]<<"\n\n";
cout<<"\tId paciente: "<<regist[y].expedientes[4]<<"\n\n";
cout<<"\tPeso: "<<regist[y].expedientes[5]<<"\n";
cout<<"\tEstatura: "<<regist[y].expedientes[6]<<"\n";
cout<<"\tMedicamento: "<<regist[y].expedientes[7]<<"\n";
cout<<"\tDosis: "<<regist[y].expedientes[8]<<"\n";
cout<<"\tHora: "<<regist[y].expedientes[9]<<"\n\n";
cout<<"\tMedico que atiende: "<<regist[y].expedientes[10];
cem++;
cout<<"\n\n\t\t\t\t\t";
system ("pause");
system ("cls");
}//fin del bucle for mostrar
}
void expediente::buscar()
{
//buscar expediente
system ("cls");
cout<<"\t\t****** EXPEDIENTES ******\n\n ";
cout<<"\nIngresa id del expediente a buscar: ";
cin>>idexpe;
for (y=0; y<10; y++)
{
if (idexpe==regist[y].expedientes[0])
{
system ("cls");
cout<<"\t\t****** EXPEDIENTES ******\n\n ";
//mostrar expediente encontrado
cout<<"\n\tDatos del Expediente";
cout<<endl<<endl;
cout<<"\tId del expediente: "<<regist[y].expedientes[0]<<"\n\n";
cout<<"\tFecha de ingreso "<<"\n\n";
cout<<"\tDia: "<<regist[y].expedientes[1]<<"\n";
cout<<"\tMes: "<<regist[y].expedientes[2]<<"\n";
cout<<"\tAnio: "<<regist[y].expedientes[3]<<"\n\n";
cout<<"\tId paciente: "<<regist[y].expedientes[4]<<"\n\n";
cout<<"\tPeso: "<<regist[y].expedientes[5]<<"\n";
cout<<"\tEstatura: "<<regist[y].expedientes[6]<<"\n";
cout<<"\tMedicamento: "<<regist[y].expedientes[7]<<"\n";
cout<<"\tDosis: "<<regist[y].expedientes[8]<<"\n";
cout<<"\tHora: "<<regist[y].expedientes[9]<<"\n\n";
cout<<"\tMedico que atiende: "<<regist[y].expedientes[10];
cout<<"\n\n\t\t\t\t\t";
system ("pause");
break;
}
}//fin del bucle for bsucar
if (y>9)
{
cout<<"\n\n\t\t\tNO EXISTE EXPEDIENTE, INTENTA DE NUEVO...\n\n\t\t\t\t";
system ("pause");
}
}
void expediente::modificar()
{
//buscar expediente
system ("cls");
cout<<"\t\t****** EXPEDIENTES ******\n\n ";
cout<<"\nIngresa id del expediente a modificar: ";
cin>>idexpe;
bool hallado = false;
for (y=0; y<10; y++)
{
if (idexpe==regist[y].expedientes[0])
{
system ("cls");
cout<<"\t\t****** EXPEDIENTES ******\n\n ";
//mostrar expediente encontrado
cout<<"\n\tDatos del expediente encontrado para modificar";
cout<<endl<<endl;
cout<<"\tId del expediente: "<<regist[y].expedientes[0]<<"\n\n";
cout<<"\tFecha de ingreso "<<"\n\n";
cout<<"\tDia: "<<regist[y].expedientes[1]<<"\n";
cout<<"\tMes: "<<regist[y].expedientes[2]<<"\n";
cout<<"\tAnio: "<<regist[y].expedientes[3]<<"\n\n";
cout<<"\tId paciente: "<<regist[y].expedientes[4]<<"\n\n";
cout<<"\tPeso: "<<regist[y].expedientes[5]<<"\n";
cout<<"\tEstatura: "<<regist[y].expedientes[6]<<"\n";
cout<<"\tMedicamento: "<<regist[y].expedientes[7]<<"\n";
cout<<"\tDosis: "<<regist[y].expedientes[8]<<"\n";
cout<<"\tHora: "<<regist[y].expedientes[9]<<"\n\n";
cout<<"\tMedico que atiende: "<<regist[y].expedientes[10]<<"\n";
cout<<"\n\t\t\t\t\t";
system ("pause");
system ("cls");
cout<<"\n";
cout<<"\n\t*******************************";
cout<<"\n\t** EXPEDIENTES **";
cout<<"\n\t** MENU DE MODIFICACIONES **";
cout<<"\n\t** **";
cout<<"\n\t** 1.- Fecha de ingreso **";
cout<<"\n\t** 2.- Id paciente **";
cout<<"\n\t** 3.- Peso **";
cout<<"\n\t** 4.- Estatura **";
cout<<"\n\t** 5.- Medicamento **";
cout<<"\n\t** 6.- Dosis y hora **";
cout<<"\n\t** 7.- Medico que atiende **";
cout<<"\n\t** **";
cout<<"\n\t** 8.- TODOS LOS ANTERIORES **";
cout<<"\n\t** **";
cout<<"\n\t** 9.- CANCELAR **";
cout<<"\n\t** **";
cout<<"\n\t*******************************";
cout<<"\n\t* Elige una opcion:__";
int modif;
cin>>modif;
switch (modif)
{
case 1:
system ("cls");
cout<<"\t\t****** EXPEDIENTES ******\n\n ";
cout<<"\tModificacion de la fecha de ingreso \n\n";
cout<<"\tFecha de ingreso "<<"\n\n";
cout<<"\tDia: ";
cin>>regist[y].expedientes[1];
cout<<"\tMes: ";
cin>>regist[y].expedientes[2];
cout<<"\tAnio: ";
cin>>regist[y].expedientes[3];
cout<<"\n\t\t\t\t\t";
break;
case 2:
system ("cls");
cout<<"\t\t****** EXPEDIENTES ******\n\n ";
cout<<"\tModificacion de Id paciente \n\n";
cout<<"\tId paciente: ";
cin>>regist[y].expedientes[4];
cout<<"\n\t\t\t\t\t";
break;
case 3:
system ("cls");
cout<<"\t\t****** EXPEDIENTES ******\n\n ";
cout<<"\tModificacion del peso del paciente \n\n";
cout<<"\tPeso: ";
cin>>regist[y].expedientes[5];
cout<<"\n\t\t\t\t\t";
break;
case 4:
system ("cls");
cout<<"\t\t****** EXPEDIENTES ******\n\n ";
cout<<"\tModificacion de la estatura del paciente \n\n";
cout<<"\tEstatura: ";
cin>>regist[y].expedientes[6];
cout<<"\n\t\t\t\t\t";
break;
case 5:
system ("cls");
cout<<"\t\t****** EXPEDIENTES ******\n\n ";
cout<<"\tModificacion del medicamento del paciente \n\n";
cout<<"\tMedicamento: ";
cin>>regist[y].expedientes[7];
cout<<"\n\t\t\t\t\t";
break;
case 6:
system ("cls");
cout<<"\t\t****** EXPEDIENTES ******\n\n ";
cout<<"\tModificacion de la dosis y hora del medicamento del paciente \n\n";
cout<<"\tDosis: ";
cin>>regist[y].expedientes[8];
cout<<"\tHora: ";
cin>>regist[y].expedientes[9];
cout<<"\n\t\t\t\t\t";
break;
case 7:
system ("cls");
cout<<"\t\t****** EXPEDIENTES ******\n\n ";
cout<<"\tModificacion del medico que atiende \n\n";
cout<<"\tMedico que atiende: ";
cin>>regist[y].expedientes[10];
cout<<"\n\t\t\t\t\t";
break;
case 8:
system ("cls");
cout<<"\t\t****** EXPEDIENTES ******\n\n ";
cout<<"\tModificacion de todos los datos del expediente encontrado \n\n";
cout<<"\tFecha de ingreso "<<"\n\n";
cout<<"\tDia: ";
cin>>regist[y].expedientes[1];
cout<<"\tMes: ";
cin>>regist[y].expedientes[2];
cout<<"\tAnio: ";
cin>>regist[y].expedientes[3];
cout<<"\n";
cout<<"\tId paciente: ";
cin>>regist[y].expedientes[4];
cout<<"\n";
cout<<"\tPeso: ";
cin>>regist[y].expedientes[5];
cout<<"\tEstatura: ";
cin>>regist[y].expedientes[6];
cout<<"\tMedicamento: ";
cin>>regist[y].expedientes[7];
cout<<"\tDosis: ";
cin>>regist[y].expedientes[8];
cout<<"\tHora: ";
cin>>regist[y].expedientes[9];
cout<<"\n";
cout<<"\tMedico que atiende: ";
cin>>regist[y].expedientes[10];
cout<<"\n\t\t\t\t\t";
break;
case 9:
cout<<"\n\n\t\tCancelar... \n\n\n\t\t\t\t\t";
break;
default:
cout<<"\n\n\t\tHa elegido una opcion inexistente, intente de nuevo; atras... \n\n\n\t\t\t\t\t";
}//Fin del switch de modificaciones
cout<<"\n\t\t\t\t\t";
system ("pause");
hallado=true;
}//Fin del if
}//Fin del ciclo for
if (hallado==true)
Sleep(1000);
else
if (hallado==false)
{
cout<<"\n\n\t\t\tNO EXISTE EXPEDIENTE, INTENTA DE NUEVO...\n\n\t\t\t\t";
system ("pause");
}
}
class paciente : public expediente
{
public:
//variables paciente:
// idn, idpaciente, paterno, materno, nombre, sexo, edocivil, calle, numero,
// tel, dia, mes, ano, entecedentes12,13 y 14;
string idn, pacientes [15];
int i, cuantos, cnc, cnm, cuantoss;
void capturar ();
void mostrar ();
void buscar ();
void modificar();
friend class expediente;
}pacient;
paciente registros [10];
void paciente::capturar()
{
//capturar paciente
cnc=1;
for (i=0; i<10; i++)
{
system ("cls");
cout<<"\t\t****** PACIENTES ******\n\n ";
cout<<"\tIngrese los datos del paciente consecutivo numero: "<<cnc<<"\n\n";
cout<<"\tId paciente: ";
cin>>registros[i].pacientes[0];
cin.ignore();
cout<<"\tApellido paterno: ";
cin>>registros[i].pacientes[1];
cin.ignore();
cout<<"\tApellido materno: ";
cin>>registros[i].pacientes[2];
cin.ignore();
cout<<"\tNombre: ";
fflush(stdin);
getline(cin, registros[i].pacientes[3]);
//cin>>registros[i].pacientes[3];
//cin.ignore();
cout<<"\tSexo: ";
cin>>registros[i].pacientes[4];
cin.ignore();
cout<<"\tEstado civil: ";
cin>>registros[i].pacientes[5];
cin.ignore();
cout<<"\tCalle: ";
cin>>registros[i].pacientes[6];
cin.ignore();
cout<<"\tNumero: ";
cin>>registros[i].pacientes[7];
cin.ignore();
cout<<"\tTelefono: ";
cin>>registros[i].pacientes[8];
cin.ignore();
cout<<"\n\tFecha de nacimiento\n\n";
cout<<"\tDia: ";
cin>>registros[i].pacientes[9];
cin.ignore();
cout<<"\tMes: ";
cin>>registros[i].pacientes[10];
cin.ignore();
cout<<"\tAnio: ";
cin>>registros[i].pacientes[11];
cin.ignore();
cout<<"\n\tAntecedentes clinicos: (Si/No)\n\n";
cout<<"\tDiabetes? ";
cin>>registros[i].pacientes[12];
cout<<"\tHipertension? ";
cin>>registros[i].pacientes[13];
cout<<"\tCancer? ";
cin>>registros[i].pacientes[14];
cout<<"\t\t\t\t\t";
system ("pause");
system ("cls");
cout<<"\t\t****** PACIENTES ******\n\n ";
cout<<"\tPaciente capturado, numero consecutivo: "<<cnc;
cout<<"\n\n\tDesea capturar otro paciente?\n\n\a";
cout<<"\t 1.- Si \n\t 2.- No \n\n";
cout<<"\tElige una opcion: ";
cin>>cuantos;
if (cuantos==1)
{
cout<<"\n\n\t\t\t";
cnc++;
system ("pause");
}
else
{
i=10;
cout<<"\t\t\t\t\t";
system ("pause");
}
}//fin del for
system ("cls");
cout<<"\n\n\tDesea capturar los expedientes consecutivos de los pacientes?\n\n\a";
cout<<"\t 1.- Si \n\t 2.- No \n\n";
cout<<"\tElige una opcion: ";
cin>>cuantoss;
if (cuantoss==1)
{
system ("cls");
expedient.capturar();
}
}
void paciente::mostrar()
{
//mostrar paciente
system ("cls");
cnm=1;
for (i=0; i<cnc; i++)
{
cout<<"\t\t****** PACIENTES ******\n\n ";
cout<<"\tDatos del paciente consecutivo numero: "<<cnm;
cout<<endl<<endl;
cout<<"\tId paciente: ";
cout<<registros[i].pacientes[0]<<endl;
cout<<"\tApellido paterno: ";
cout<<registros[i].pacientes[1]<<endl;
cout<<"\tApellido materno: ";
cout<<registros[i].pacientes[2]<<endl;
cout<<"\tNombre: ";
cout<<registros[i].pacientes[3]<<endl;
cout<<"\tSexo: ";
cout<<registros[i].pacientes[4]<<endl;
cout<<"\tEstado civil: ";
cout<<registros[i].pacientes[5]<<endl;
cout<<"\tCalle: ";
cout<<registros[i].pacientes[6]<<endl;
cout<<"\tNumero: ";
cout<<registros[i].pacientes[7]<<endl;
cout<<"\tTelefono: ";
cout<<registros[i].pacientes[8]<<endl;
cout<<"\n\tFecha de nacimiento\n\n";
cout<<"\tDia: ";
cout<<registros[i].pacientes[9]<<endl;
cout<<"\tMes: ";
cout<<registros[i].pacientes[10]<<endl;
cout<<"\tAnio: ";
cout<<registros[i].pacientes[11]<<"\n";
cout<<"\n\tAntecedentes clinicos: (Si/No)\n\n";
cout<<"\tDiabetes: "<<registros[i].pacientes[12]<<"\n";
cout<<"\tHipertension: "<<registros[i].pacientes[13]<<"\n";
cout<<"\tCancer: "<<registros[i].pacientes[14]<<"\n";
cout<<"\t\t\t\t\t";
cnm++;
system ("pause");
system ("cls");
}//fin del for mostrar
cout<<"\n\n\tDesea mostrar los expedientes consecutivos de los pacientes?\n\n";
cout<<"\t 1.- Si \n\t 2.- No \n\n";
cout<<"\tElige una opcion: ";
cin>>cuantoss;
if (cuantoss==1)
{
system ("cls");
expedient.mostrar();
}
}
void paciente::buscar()
{
//buscar paciente
system ("cls");
cout<<"\t\t****** PACIENTES ******\n\n ";
cout<<"\nIngresa id del paciente a buscar: ";
cin>>idn;
for (i=0; i<10; i++)
{
if (idn==registros[i].pacientes[0])
{
system ("cls");
cout<<"\t\t****** PACIENTES ******\n\n ";
cout<<"\tDatos del paciente: ";
cout<<endl<<endl;
cout<<"\tId paciente: ";
cout<<registros[i].pacientes[0]<<endl;
cout<<"\tApellido paterno: ";
cout<<registros[i].pacientes[1]<<endl;
cout<<"\tApellido materno: ";
cout<<registros[i].pacientes[2]<<endl;
cout<<"\tNombre: ";
cout<<registros[i].pacientes[3]<<endl;
cout<<"\tSexo: ";
cout<<registros[i].pacientes[4]<<endl;
cout<<"\tEstado civil: ";
cout<<registros[i].pacientes[5]<<endl;
cout<<"\tCalle: ";
cout<<registros[i].pacientes[6]<<endl;
cout<<"\tNumero: ";
cout<<registros[i].pacientes[7]<<endl;
cout<<"\tTelefono: ";
cout<<registros[i].pacientes[8]<<endl;
cout<<"\n\tFecha de nacimiento\n\n";
cout<<"\tDia: ";
cout<<registros[i].pacientes[9]<<endl;
cout<<"\tMes: ";
cout<<registros[i].pacientes[10]<<endl;
cout<<"\tAnio: ";
cout<<registros[i].pacientes[11]<<endl;
cout<<"\n\tAntecedentes clinicos: (Si/No)\n\n";
cout<<"\tDiabetes "<<registros[i].pacientes[12]<<"\n";
cout<<"\tHipertension "<<registros[i].pacientes[13]<<"\n";
cout<<"\tCancer "<<registros[i].pacientes[14]<<"\n";
cout<<"\t\t\t\t\t";
system ("pause");
break;
}
}//Termino del ciclo for
if (i>9)
{
cout<<"\n\n\t\t\tNO EXISTE PACIENTE, INTENTA DE NUEVO...\n\n\t\t\t\t";
system ("pause");
}
}
void paciente::modificar()
{
//modificar paciente
system ("cls");
cout<<"\t\t****** PACIENTES ******\n\n ";
cout<<"\nIngresa id del paciente a modificar: ";
cin>>idn;
bool hallado = false;
for (i=0; i<10; i++)
{
if (idn==registros[i].pacientes[0])
{
system ("cls");
cout<<"\t\t****** PACIENTES ******\n\n ";
cout<<"\tDatos del paciente encontrado para modificar: \n\n";
cout<<"\tId paciente: "<<registros[i].pacientes[0]<<"\n";
cout<<"\tApellido paterno: "<<registros[i].pacientes[1]<<"\n";
cout<<"\tApellido materno: "<<registros[i].pacientes[2]<<"\n";
cout<<"\tNombre: "<<registros[i].pacientes[3]<<"\n";
cout<<"\tSexo: "<<registros[i].pacientes[4]<<"\n";
cout<<"\tEstado civil: "<<registros[i].pacientes[5]<<"\n";
cout<<"\tCalle: "<<registros[i].pacientes[6]<<"\n";
cout<<"\tNumero: "<<registros[i].pacientes[7]<<"\n";
cout<<"\tTelefono: "<<registros[i].pacientes[8]<<"\n\n";
cout<<"\tFecha de nacimiento\n\n";
cout<<"\tDia: "<<registros[i].pacientes[9]<<"\n";
cout<<"\tMes: "<<registros[i].pacientes[10]<<"\n";
cout<<"\tAnio: "<<registros[i].pacientes[11]<<"\n\n";
cout<<"\tAntecedentes clinicos: (Si/No)\n\n";
cout<<"\tDiabetes "<<registros[i].pacientes[12]<<"\n";
cout<<"\tHipertension "<<registros[i].pacientes[13]<<"\n";
cout<<"\tCancer "<<registros[i].pacientes[14]<<"\n";
cout<<"\t\t\t\t\t";
system ("pause");
system ("cls");
cout<<"\n";
cout<<"\n\t*******************************";
cout<<"\n\t** PACIENTES **";
cout<<"\n\t** MENU DE MODIFICACIONES **";
cout<<"\n\t** **";
cout<<"\n\t** 1.- Apellidos y nombre(s) **";
cout<<"\n\t** 2.- Sexo **";
cout<<"\n\t** 3.- Estado civil **";
cout<<"\n\t** 4.- Domicilio **";
cout<<"\n\t** 5.- Telefono **";
cout<<"\n\t** 6.- Fecha de nacimiento **";
cout<<"\n\t** 7.- Antecedentes clinicos **";
cout<<"\n\t** **";
cout<<"\n\t** 8.- TODOS LOS ANTERIORES **";
cout<<"\n\t** **";
cout<<"\n\t** 9.- CANCELAR **";
cout<<"\n\t** **";
cout<<"\n\t*******************************";
cout<<"\n\t* Elige una opcion:__";
int modif;
cin>>modif;
switch (modif)
{
case 1:
system ("cls");
cout<<"\t\t****** PACIENTES ******\n\n ";
cout<<"\tModificacion de apellidos y nombre(s)\n\n";
cout<<"\tApellido paterno: ";
cin>>registros[i].pacientes[1];
cout<<"\tApellido materno: ";
cin>>registros[i].pacientes[2];
cout<<"\tNombre: ";
cin>>registros[i].pacientes[3];
cout<<"\n\t\t\t\t\t";
break;
case 2:
system ("cls");
cout<<"\t\t****** PACIENTES ******\n\n ";
cout<<"\tModificacion de sexo\n\n";
cout<<"\tSexo: ";
cin>>registros[i].pacientes[4];
cout<<"\n\t\t\t\t\t";
break;
case 3:
system ("cls");
cout<<"\t\t****** PACIENTES ******\n\n ";
cout<<"\tModificacion de estado civil\n\n";
cout<<"\tEstado civil: ";
cin>>registros[i].pacientes[5];
cout<<"\n\t\t\t\t\t";
break;
case 4:
system ("cls");
cout<<"\t\t****** PACIENTES ******\n\n ";
cout<<"\tModificacion de domicilio\n\n";
cout<<"\tCalle: ";
cin>>registros[i].pacientes[6];
cout<<"\tNumero: ";
cin>>registros[i].pacientes[7];
cout<<"\n\t\t\t\t\t";
break;
case 5:
system ("cls");
cout<<"\t\t****** PACIENTES ******\n\n ";
cout<<"\tModificacion de telefono\n\n";
cout<<"\tTelefono: ";
cin>>registros[i].pacientes[8];
cout<<"\n\t\t\t\t\t";
break;
case 6:
system ("cls");
cout<<"\t\t****** PACIENTES ******\n\n ";
cout<<"\tModificacion de fecha de nacimiento\n\n";
cout<<"\tDia: ";
cin>>registros[i].pacientes[9];
cout<<"\tMes: ";
cin>>registros[i].pacientes[10];
cout<<"\tAnio: ";
cin>>registros[i].pacientes[11];
cout<<"\n\t\t\t\t\t";
break;
case 7:
system ("cls");
cout<<"\t\t****** PACIENTES ******\n\n ";
cout<<"\tModificacion de antecedentes clinicos: especificar con un 'Si' o un 'No' \n\n";
cout<<"\tDiabetes ";
cin>>registros[i].pacientes[12];
cout<<"\tHipertension ";
cin>>registros[i].pacientes[13];
cout<<"\tCancer ";
cin>>registros[i].pacientes[14];
cout<<"\n\t\t\t\t\t";
break;
case 8:
system ("cls");
cout<<"\t\t****** PACIENTES ******\n\n ";
cout<<"\tModificacion de todos los datos del paciente encontrado\n\n";
cout<<"\tApellido paterno: ";
cin>>registros[i].pacientes[1];
cout<<"\tApellido materno: ";
cin>>registros[i].pacientes[2];
cout<<"\tNombre: ";
cin>>registros[i].pacientes[3];
cout<<"\tSexo: ";
cin>>registros[i].pacientes[4];
cout<<"\tEstado civil: ";
cin>>registros[i].pacientes[5];
cout<<"\tCalle: ";
cin>>registros[i].pacientes[6];
cout<<"\tNumero: ";
cin>>registros[i].pacientes[7];
cout<<"\tTelefono: ";
cin>>registros[i].pacientes[8];
cout<<"\n\tFecha de nacimiento\n\n";
cout<<"\tDia: ";
cin>>registros[i].pacientes[9];
cout<<"\tMes: ";
cin>>registros[i].pacientes[10];
cout<<"\tAnio: ";
cin>>registros[i].pacientes[11];
cout<<"\n\tAntecedentes clinicos: (Si/No)\n\n";
cout<<"\tDiabetes ";
cin>>registros[i].pacientes[12];
cout<<"\tHipertension ";
cin>>registros[i].pacientes[13];
cout<<"\tCancer ";
cin>>registros[i].pacientes[14];
cout<<"\n\t\t\t\t\t";
break;
case 9:
cout<<"\n\n\t\tCancelar... \n\n\n\t\t\t\t\t";
break;
default:
cout<<"\n\n\t\tHa elegido una opcion inexistente, intente de nuevo; atras... \n\n\n\t\t\t\t\t";
}//Fin del switch de modificaciones
cout<<"\n\t\t\t\t\t";
system ("pause");
hallado=true;
}//Fin del if
}//Fin del ciclo for
if (hallado==true)
Sleep(1000);
else
if (hallado==false)
{
cout<<"\n\n\t\t\tNO EXISTE PACIENTE, INTENTA DE NUEVO...\n\n\t\t\t\t";
system ("pause");
}
}
class medico
{
public:
//variables medico:
//idnmedico,
//idndoc 0, appdoc1, apmdoc2, nombredoc3, calldoc4, numdoc5, teldoc6, teldoc1 7, espdoc8, activo 9;
string idnmedico, medicos[10];
int x, cuant, cmc, cmm;
void capturar ();
void mostrar ();
void buscar ();
void modificar();
}medic;
medico registro [10];
void medico::capturar()
{
system ("cls");
//capturar médico
cmc=1;
for (x=0; x<10; x++)
{
system ("cls");
cout<<"\t\t****** MEDICOS ******\n\n ";
cout<<"\tIngrese los datos del medico consecutivo numero: "<<cmc<<"\n";
cout<<endl<<endl;
cout<<"\tId Medico: ";
cin>>registro[x].medicos[0];
cin.ignore();
cout<<"\n";
cout<<"\tApellido paterno: ";
cin>>registro[x].medicos[1];
cin.ignore();
cout<<"\tApellido materno: ";
cin>>registro[x].medicos[2];
cin.ignore();
cout<<"\tNombre: ";
cin>>registro[x].medicos[3];
cin.ignore();
cout<<"\n\n\tDatos de contacto \n\n";
cout<<"\tCalle: ";
cin>>registro[x].medicos[4];
cin.ignore();
cout<<"\tNumero: ";
cin>>registro[x].medicos[5];
cin.ignore();
cout<<"\tTelefono: ";
cin>>registro[x].medicos[6];
cin.ignore();
cout<<"\tTelefono 2: ";
cin>>registro[x].medicos[7];
cin.ignore();
cout<<"\n";
cout<<"\tEspecialidad: ";
cin>>registro[x].medicos[8];
cin.ignore();
cout<<"\tActivo (Si/No) : ";
cin>>registro[x].medicos[9];
cin.ignore();
cout<<"\n\n\t\t\t\t\t";
system ("pause");
system ("cls");
cout<<"\t\t****** MEDICOS ******\n\n ";
cout<<"\tMedico capturado numero: "<<cmc<<". \n\n\tDesea capturar otro medico?\n\n\a";
cout<<"\t 1.- Si \n\t 2.- No \n\n";
cout<<"\tElige una opcion: ";
cin>>cuant;
if (cuant==1)
{
cout<<"\n\n\t\t\t";
cmc++;
system ("pause");
}
else
{
x=10;
cout<<"\t\t\t\t\t";
system ("pause");
}
}
}
void medico::mostrar()
{
//mostrar medico
cmm=1;
system ("cls");
for (x=0; x<cmc; x++)
{
cout<<"\t\t****** MEDICOS ******\n\n ";
cout<<"\n\tDatos del medico consecutivo numero: "<<cmm;
cout<<endl<<endl;
cout<<"\tId medico: ";
cout<<registro[x].medicos[0]<<"\n\n";
cout<<"\tApellido paterno: ";
cout<<registro[x].medicos[1]<<endl;
cout<<"\tApellido materno: ";
cout<<registro[x].medicos[2]<<endl;
cout<<"\tNombre: ";
cout<<registro[x].medicos[3]<<endl;
cout<<"\n\n\tDatos de contacto \n\n";
cout<<"\tCalle: ";
cout<<registro[x].medicos[4]<<endl;
cout<<"\tNumero: ";
cout<<registro[x].medicos[5]<<endl;
cout<<"\tTelefono: ";
cout<<registro[x].medicos[6]<<endl;
cout<<"\tTelefono 2: ";
cout<<registro[x].medicos[7]<<"\n\n";
cout<<"\tEspecialidad: ";
cout<<registro[x].medicos[8]<<endl;
cout<<"\tActivo (Si/No): ";
cout<<registro[x].medicos[9]<<endl;
cout<<"\n\n\t\t\t\t\t";
cmm++;
system ("pause");
system ("cls");
}
}
void medico::buscar()
{
//buscar médico
system ("cls");
cout<<"\t\t****** MEDICOS ******\n\n ";
cout<<"\nIngresa id medico a buscar: ";
cin>>idnmedico;
for (x=0; x<10; x++)
{
if (idnmedico==registro[x].medicos[0])
{
//mostrar medico despues de buscar
system ("cls");
cout<<"\t\t****** MEDICOS ******\n\n ";
cout<<"\n\tDatos del medico:";
cout<<endl<<endl;
cout<<"\tId medico: ";
cout<<registro[x].medicos[0]<<"\n\n";
cout<<"\tApellido paterno: ";
cout<<registro[x].medicos[1]<<endl;
cout<<"\tApellido materno: ";
cout<<registro[x].medicos[2]<<endl;
cout<<"\tNombre: ";
cout<<registro[x].medicos[3]<<endl;
cout<<"\n\n\tDatos de contacto \n\n";
cout<<"\tCalle: ";
cout<<registro[x].medicos[4]<<endl;
cout<<"\tNumero: ";
cout<<registro[x].medicos[5]<<endl;
cout<<"\tTelefono: ";
cout<<registro[x].medicos[6]<<endl;
cout<<"\tTelefono 2: ";
cout<<registro[x].medicos[7]<<"\n\n";
cout<<"\tEspecialidad: ";
cout<<registro[x].medicos[8]<<endl;
cout<<"\tActivo (Si/No): ";
cout<<registro[x].medicos[9]<<endl;
cout<<"\n\n\t\t\t\t\t";
system ("pause");
break;
}
}//Termino del ciclo for
if (x>9)
{
cout<<"\n\n\t\t\tNO EXISTE MEDICO, INTENTA DE NUEVO...\n\n\t\t\t\t";
system ("pause");
}
}
void medico::modificar()
{
//modificar médico
system ("cls");
cout<<"\t\t****** MEDICOS ******\n\n ";
cout<<"\nIngresa id medico a modificar: ";
cin>>idnmedico;
bool hallado=false;
for (x=0; x<10; x++)
{
if (idnmedico==registro[x].medicos[0])
{
//mostrar medico despues de buscar
system ("cls");
cout<<"\t\t****** MEDICOS ******\n\n ";
cout<<"\n\tDatos del medico encontrado para modificar: ";
cout<<endl<<endl;
cout<<"\tId medico: "<<registro[x].medicos[0]<<"\n\n";;
cout<<"\tApellido paterno: "<<registro[x].medicos[1]<<"\n";
cout<<"\tApellido materno: "<<registro[x].medicos[2]<<"\n";
cout<<"\tNombre: "<<registro[x].medicos[3]<<"\n\n";
cout<<"\tDatos de contacto \n\n";
cout<<"\tCalle: "<<registro[x].medicos[4]<<"\n";
cout<<"\tNumero: "<<registro[x].medicos[5]<<"\n";
cout<<"\tTelefono: "<<registro[x].medicos[6]<<"\n";
cout<<"\tTelefono 2: "<<registro[x].medicos[7]<<"\n\n";
cout<<"\tEspecialidad: "<<registro[x].medicos[8]<<"\n";
cout<<"\tActivo (Si/No): "<<registro[x].medicos[9]<<"\n\n";
cout<<"\t\t\t\t\t";
system ("pause");
system ("cls");
cout<<"\n";
cout<<"\n\t*******************************";
cout<<"\n\t** MEDICOS **";
cout<<"\n\t** MENU DE MODIFICACIONES **";
cout<<"\n\t** **";
cout<<"\n\t** 1.- Apellidos y nombre(s) **";
cout<<"\n\t** 2.- Datos de contacto **";
cout<<"\n\t** 3.- Especialidad **";
cout<<"\n\t** 4.- Activo (Estatus) **";
cout<<"\n\t** **";
cout<<"\n\t** 5.- TODOS LOS ANTERIORES **";
cout<<"\n\t** **";
cout<<"\n\t** 6.- CANCELAR **";
cout<<"\n\t** **";
cout<<"\n\t*******************************";
cout<<"\n\t* Elige una opcion:__";
int modifi;
cin>>modifi;
switch (modifi)
{
case 1:
system ("cls");
cout<<"\t\t****** MEDICOS ******\n\n ";
cout<<"\tModificacion de apellidos y nombre(s) \n\n";
cout<<"\tApellido paterno: ";
cin>>registro[x].medicos[1];
cout<<"\tApellido materno: ";
cin>>registro[x].medicos[2];
cout<<"\tNombre: ";
cin>>registro[x].medicos[3];
cout<<"\n\t\t\t\t\t";
break;
case 2:
system ("cls");
cout<<"\t\t****** MEDICOS ******\n\n ";
cout<<"\tModificacion de los datos de contacto\n\n";
cout<<"\tCalle: ";
cin>>registro[x].medicos[4];
cout<<"\tNumero: ";
cin>>registro[x].medicos[5];
cout<<"\tTelefono: ";
cin>>registro[x].medicos[6];
cout<<"\tTelefono 2: ";
cin>>registro[x].medicos[7];
cout<<"\n\t\t\t\t\t";
break;
case 3:
system ("cls");
cout<<"\t\t****** MEDICOS ******\n\n ";
cout<<"\tModificacion de la especialidad\n\n";
cout<<"\tEspecialidad: ";
cin>>registro[x].medicos[8];
cout<<"\n\t\t\t\t\t";
break;
case 4:
system ("cls");
cout<<"\t\t****** MEDICOS ******\n\n ";
cout<<"\tModificacion del Estatus (Activo); especificar con un 'Si' o un 'No' \n\n";
cout<<"\tActivo (Si/No): ";
cin>>registro[x].medicos[9];
cout<<"\n\t\t\t\t\t";
break;
case 5:
system ("cls");
cout<<"\t\t****** MEDICOS ******\n\n ";
cout<<"\tModificacion de todos los datos del medico encontrado\n\n";
cout<<"\tApellido paterno: ";
cin>>registro[x].medicos[1];
cout<<"\tApellido materno: ";
cin>>registro[x].medicos[2];
cout<<"\tNombre: ";
cin>>registro[x].medicos[3];
cout<<"\n\tDatos de contacto \n\n";
cout<<"\tCalle: ";
cin>>registro[x].medicos[4];
cout<<"\tNumero: ";
cin>>registro[x].medicos[5];
cout<<"\tTelefono: ";
cin>>registro[x].medicos[6];
cout<<"\tTelefono 2: ";
cin>>registro[x].medicos[7];
cout<<"\n\n";
cout<<"\tEspecialidad: ";
cin>>registro[x].medicos[8];
cout<<"\tActivo (Si/No): ";
cin>>registro[x].medicos[9];
cout<<"\t\t\t\t\t";
break;
case 6:
cout<<"\n\n\t\tCancelar... \n\n\n\t\t\t\t\t";
break;
default:
cout<<"\n\n\t\tHa elegido una opcion inexistente, intente de nuevo; atras... \n\n\n\t\t\t\t\t";
}//Término del switch
hallado=true;
}//Término del if
}//Termino del ciclo for
if (hallado==true)
Sleep(1000);
else
if (hallado==false)
{
cout<<"\n\n\t\t\tNO EXISTE MEDICO, INTENTA DE NUEVO...\n\n\t\t\t\t";
system ("pause");
}
}
void pagoss ()
{
//variables para pagos
string idppago;
int tipocuar, diashosp;
float desc, porce, subtotal, total, preciogen, preciocuar, preciovip, otros;
bool existe = false;
/* Pagos
En el sistema CIH se llevara también el control de pago el cual se obtendrá con el id
paciente y contendrá los siguientes campos: días de hospitalización, tipo de cuarto(cuarto
VIP, sala general,cuarto) precio*dia, descuento, otros servicios, se emitirá una factura.
*/
desc=0, porce=0;
preciogen=100;
preciocuar=500;
preciovip=1000;
system ("cls");
cout<<"\t\t\t****** PAGOS ******\n\n\a ";
cout<<"\n\tId del paciente a buscar: ";
cin>>idppago;
int u;
for (u=0;u<10;u++)
{
if (idppago==registros[u].pacientes[0])
{
existe=true;
cout<<"\n\tApellido paterno: "<<registros[u].pacientes[1];
cout<<"\n\tApellido materno: "<<registros[u].pacientes[2];
cout<<"\n\tNombre (s): "<<registros[u].pacientes[3];
cout<<"\n\n\tTipo de servicio \n";
cout<<"\n\t 1.- GENERAL ?";
cout<<"\n\t 2.- CUARTO ? ";
cout<<"\n\t 3.- VIP ? ";
cin>>tipocuar;
cout<<"\n\tDias hospitalizado: ";
cin>>diashosp;
if (diashosp>=5){
cout<<"\n\tDescuento vigente % : ";
cin>>desc;
porce=desc;
}
cout<<"\n\tOtros conceptos (cantidad) $";
cin>>otros;
if (diashosp<5 and tipocuar==1){//sin descuento
total=diashosp*preciogen+otros;
subtotal=total;
}
else if (diashosp<5 and tipocuar==2){
total=diashosp*preciocuar+otros;
subtotal=total;
}
else if (diashosp<5 and tipocuar==3){
total=diashosp*preciovip+otros;
subtotal=total;
}
else if (diashosp>=5 and tipocuar==1){//con descuento
total=diashosp*preciogen+otros;
subtotal=total;
desc=total*desc/100;
total=total-desc;
}
else if (diashosp>=5 and tipocuar==2){
total=diashosp*preciocuar+otros;
subtotal=total;
desc=total*desc/100;
total=total-desc;
}
else if (diashosp>=5 and tipocuar==3){
total=diashosp*preciovip+otros;
subtotal=total;
desc=total*desc/100;
total=total-desc;
}
system ("cls");
cout<<"\t\t\t****** PAGOS ******\n\n ";
cout<<"\n\t__________________________________________";
cout<<"\n\t| Id Paciente: "<<registros[u].pacientes[0];
cout<<"\n\t ";
cout<<"\n\t| Apellido paterno: "<<registros[u].pacientes[1];
cout<<"\n\t| Apellido materno: "<<registros[u].pacientes[2];
cout<<"\n\t| Nombre (s): "<<registros[u].pacientes[3]<<"\n";
if (tipocuar==1){
cout<<"\n\t| Tipo de servicio GENERAL $ 100 * dia";
}
else if (tipocuar==2){
cout<<"\n\t| Tipo de servicio CUARTO $ 500 * dia";
}
else if (tipocuar==3){
cout<<"\n\t| Tipo de servicio VIP $ 1000 * dia";
}
cout<<"\n\t ";
cout<<"\n\t| Dias hospitalizado: "<<diashosp;
cout<<"\n\t| Otros conceptos (cantidad) $"<<otros;
cout<<"\n\t ";
cout<<"\n\t| Subtotal sin descuento: "<<subtotal;
cout<<"\n\t ";
cout<<"\n\t| Descuento: "<<porce<<" %";
cout<<"\n\t__________________________________________";
cout<<"\n\t ";
cout<<"\n\t| Total a pagar: "<<total;
cout<<"\n\t__________________________________________";
cout<<"\n\n\t\t\t\a";
total=0, subtotal=0, u=10;
system ("pause");
}//fin del if buscador
}//fin del for buscador
if (existe == false)
{
cout<<"\n\n\t\t\tNO EXISTE PACIENTE, INTENTA DE NUEVO...\n\n\t\t\t\t";
system ("pause");
}
}
// variables para opciones de menus:
#define PASS "java"
#define SALIR "S"
int opcpac, opcmed, opcexp, clase;
int main()
{
int intentos=0;
string password;
do
{
system ("cls");
system ("color a");
cout<<"\n\n\t";
char hola []= {'*',' ','C','O','N','T','R','O','L',' ','D','E',' ','I','N','G','R','E','S','O','S',' ','H','O','S','P','I','T','A','L','A','R','I','O','S',' ','*'};
for (int t=0;t<37;t++){
Sleep(50);
cout<<hola[t];
//cout<<"\t! CONTROL DE INGRESOS HOSPITALARIOS !"<<endl;
}
cout<<"\n\n";
cout<<"\t---------------------------------------"<<endl<<endl;
cout<<"\tIngresa la contrasenia o [S] para salir ";
char opcintento;
opcintento= getch();
password="";
while (opcintento !=13){
password.push_back(opcintento);
cout<<"*";
opcintento=getch();
}
intentos++;
if (password==<PASSWORD>)
{
intentos=1;
do {
//system ("treasure.mp3");
system ("color f0");
system ("cls");
cout<<"\n\tFECHA:\t";
system ("date /t");
cout<<"\t -----------------------------------"<<endl;
cout<<"\t! !"<<endl;
cout<<"\t! CONTROL DE INGRESOS HOSPITALARIOS !"<<endl;
cout<<"\t! !"<<endl;
cout<<"\t -----------------------------------"<<endl<<endl;
cout<<"\t************************************"<<endl;
cout<<"\t* *"<<endl;
cout<<"\t* Menu *"<<endl;
cout<<"\t* *"<<endl;
cout<<"\t* 1.- Control de Pacientes *"<<endl;
cout<<"\t* 2.- Control de Medicos *"<<endl;
cout<<"\t* 3.- Control de Expedientes *"<<endl;
cout<<"\t* 4.- Control de Pagos *"<<endl;
cout<<"\t* 5.- Control de Medicamentos *"<<endl;
cout<<"\t* 6.- Control de Perecederos *"<<endl;
cout<<"\t* *"<<endl;
cout<<"\t* 7.- Salir *"<<endl;
cout<<"\t* *"<<endl;
cout<<"\t************************************"<<endl;
cout<<"\t* *"<<endl;
cout<<"\t* Elija una opcion: * ";
cin>>clase;
switch (clase)
{
case 1:{
//Clase paciente
//system ("color 3f");
bool band = true;
do{
system ("cls");
cout<<endl;
cout<<"\t**********************"<<endl;
cout<<"\t* *"<<endl;
cout<<"\t* PACIENTES *"<<endl;
cout<<"\t* *"<<endl;
cout<<"\t* 1.- Capturar *"<<endl;
cout<<"\t* 2.- Mostrar *"<<endl;
cout<<"\t* 3.- Buscar *"<<endl;
cout<<"\t* 4.- Modificar *"<<endl;
cout<<"\t* *"<<endl;
cout<<"\t* 5.- Menu principal *"<<endl;
cout<<"\t* *"<<endl;
cout<<"\t**********************"<<endl<<endl;
cout<<"\tElige una opcion: ";
cin>>opcpac;
switch (opcpac)
{
case 1:
pacient.capturar();
break;
case 2:
pacient.mostrar();
break;
case 3:
pacient.buscar();
break;
case 4:
pacient.modificar();
break;
case 5:
band = false;
break;
default: cout<<"\n\n\t\t\tHa elegido una opcion inexistente \n\n\t\t\t\t\t";
cout<<"\a";
system ("pause");
}
}
while (band == true);
cout<<"\n\n\t Atras... \n\n\t\t\t\t\t";
cout<<"\a";
Sleep (1000);
break;
}
case 2:{
// Clase medico
//system ("color 17");
bool ban = true;
while (ban == true)
{
system ("cls");
cout<<endl;
cout<<"\t**********************"<<endl;
cout<<"\t* *"<<endl;
cout<<"\t* MEDICOS *"<<endl;
cout<<"\t* *"<<endl;
cout<<"\t* 1.- Capturar *"<<endl;
cout<<"\t* 2.- Mostrar *"<<endl;
cout<<"\t* 3.- Buscar *"<<endl;
cout<<"\t* 4.- Modificar *"<<endl;
cout<<"\t* *"<<endl;
cout<<"\t* 5.- Menu principal *"<<endl;
cout<<"\t* *"<<endl;
cout<<"\t**********************"<<endl<<endl;
cout<<"\tElige una opcion: ";
cin>>opcmed;
switch (opcmed){
case 1:
medic.capturar();
break;
case 2:
medic.mostrar();
break;
case 3:
medic.buscar();
break;
case 4:
medic.modificar();
break;
case 5:
ban = false;
break;
default: cout<<"\n\n\t\t\tHa elegido una opcion inexistente... \n\n\t\t\t\t\t";
cout<<"\a";
system ("pause");
}
}
cout<<"\n\n\t Atras... \n\n\t\t\t\t\t";
cout<<"\a";
Sleep (1000);
break;
}
case 3:{
//Clase expedientes
// system ("color f0");
bool band = true;
do{
system ("cls");
cout<<endl;
cout<<"\t**********************"<<endl;
cout<<"\t* *"<<endl;
cout<<"\t* EXPEDIENTES *"<<endl;
cout<<"\t* *"<<endl;
cout<<"\t* 1.- Capturar *"<<endl;
cout<<"\t* 2.- Mostrar *"<<endl;
cout<<"\t* 3.- Buscar *"<<endl;
cout<<"\t* 4.- Modificar *"<<endl;
cout<<"\t* *"<<endl;
cout<<"\t* 5.- Menu principal *"<<endl;
cout<<"\t* *"<<endl;
cout<<"\t**********************"<<endl<<endl;
cout<<"\tElige una opcion: ";
cin>>opcexp;
switch (opcexp)
{
case 1:
expedient.capturar();
break;
case 2:
expedient.mostrar();
break;
case 3:
expedient.buscar();
break;
case 4:
expedient.modificar();
break;
case 5:
band = false;
break;
default: cout<<"\n\n\t\t\tHa elegido una opcion inexistente \n\n\t\t\t\t\t";
cout<<"\a";
system ("pause");
}
}
while (band == true);
cout<<"\n\n\t Atras... \n\n\t\t\t\t\t";
//system ("pause");
cout<<"\a";
Sleep(1000);
break;
}
case 4:{
//Clase pagos
// system ("color f0");
bool band = true;
do{
//bool existe = false;
system ("cls");
cout<<endl;
cout<<"\t**********************"<<endl;
cout<<"\t* *"<<endl;
cout<<"\t* PAGOS *"<<endl;
cout<<"\t* *"<<endl;
cout<<"\t* 1.- Cargos *"<<endl;
cout<<"\t* *"<<endl;
cout<<"\t* 2.- Menu principal *"<<endl;
cout<<"\t* *"<<endl;
cout<<"\t**********************"<<endl<<endl;
cout<<"\tElige una opcion: ";
cin>>opcexp;
switch (opcexp)
{
case 1:
pagoss ();
break;
case 2:
band = false;
break;
default: cout<<"\n\n\t\t\tHa elegido una opcion inexistente \n\n\t\t\t\t\t";
cout<<"\a";
system ("pause");
}
}
while (band == true);
cout<<"\n\n\t Atras... \n\n\t\t\t\t\t";
//system ("pause");
Sleep(1000);
cout<<"\a";
break;
}
case 5:{
//Clase expedientes
// system ("color f0");
bool band = true;
do{
system ("cls");
cout<<endl;
cout<<"\t**********************"<<endl;
cout<<"\t* *"<<endl;
cout<<"\t* MEDICAMENTOS *"<<endl;
cout<<"\t* *"<<endl;
cout<<"\t* 1.- Capturar *"<<endl;
cout<<"\t* 2.- Mostrar *"<<endl;
cout<<"\t* 3.- Buscar *"<<endl;
cout<<"\t* 4.- Modificar *"<<endl;
cout<<"\t* *"<<endl;
cout<<"\t* 5.- Menu principal *"<<endl;
cout<<"\t* *"<<endl;
cout<<"\t**********************"<<endl<<endl;
cout<<"\tElige una opcion: ";
cin>>opcexp;
switch (opcexp)
{
case 1:
medicament.capturarM();
break;
case 2:
medicament.mostrarM();
break;
case 3:
medicament.buscarM();
break;
case 4:
medicament.modificarM();
break;
case 5:
band = false;
break;
default: cout<<"\n\n\t\t\tHa elegido una opcion inexistente \n\n\t\t\t\t\t";
cout<<"\a";
system ("pause");
}
}
while (band == true);
cout<<"\n\n\t Atras... \n\n\t\t\t\t\t";
//system ("pause");
cout<<"\a";
Sleep(1000);
break;
}
case 6:{
//Clase expedientes
// system ("color f0");
bool band = true;
do{
system ("cls");
cout<<endl;
cout<<"\t**********************"<<endl;
cout<<"\t* *"<<endl;
cout<<"\t* PERECEDEROS *"<<endl;
cout<<"\t* *"<<endl;
cout<<"\t* 1.- Capturar *"<<endl;
cout<<"\t* 2.- Mostrar *"<<endl;
cout<<"\t* 3.- Buscar *"<<endl;
cout<<"\t* 4.- Modificar *"<<endl;
cout<<"\t* *"<<endl;
cout<<"\t* 5.- Menu principal *"<<endl;
cout<<"\t* *"<<endl;
cout<<"\t**********************"<<endl<<endl;
cout<<"\tElige una opcion: ";
cin>>opcexp;
switch (opcexp)
{
case 1:
m_pereceder.capturarMP();
break;
case 2:
m_pereceder.mostrarMP();
break;
case 3:
m_pereceder.buscarMP();
break;
case 4:
m_pereceder.modificarMP();
break;
case 5:
band = false;
break;
default: cout<<"\n\n\t\t\tHa elegido una opcion inexistente \n\n\t\t\t\t\t";
cout<<"\a";
system ("pause");
}
}
while (band == true);
cout<<"\n\n\t Atras... \n\n\t\t\t\t\t";
//system ("pause");
cout<<"\a";
Sleep(1000);
break;
}
// Menú principal opcion salir.
case 7:{cout<<"\n\n\t\t Ha elegido Salir... !! Hasta pronto !! \n\n\n\t\t\t\t\t";
cout<<"\a";
Sleep (2000);
intentos=0;
break;
}
// Opcion equivocada, volver a intentar.
default: {cout<<"\n\n\t\t Ha elegido una opcion inexistente... \n\n\n\t\t\t\t\t";
cout<<"\a";
Sleep (2000);
//return main ();
}
}
}while (intentos==1);
}
else if (intentos<3 and password!=<PASSWORD> ){
system ("cls");
system ("color c");
cout<<"\n\t\t ******************************************";
cout<<"\n\t\t *** ***";
cout<<"\n\t\t *** INTENTO ERRONEO ***";
cout<<"\n\t\t *** ***";
cout<<"\n\t\t ******************************************";
cout<<"\n\n\n\t\t\t\t";
system ("pause");
//break;
}
else if (intentos>2){
system ("cls");
system ("color c");
cout<<"\n\t\t ******************************************";
cout<<"\n\t\t *** ***";
cout<<"\n\t\t *** DEMASIADOS INTENTOS ***";
cout<<"\n\t\t *** ***";
cout<<"\n\t\t *** SALIENDO... ***";
cout<<"\n\t\t *** ***";
cout<<"\n\t\t ******************************************";
cout<<"\n\n\n\t\t\t\t";
system ("pause");
break;
}
if (password==<PASSWORD>){
system ("color c");
cout<<"\n\n\n\tHa elegido salir definitivamente...\n\n\n\t\t\t"; system ("pause"); intentos =4;
}
}while (intentos<=3);
return 0;
}
<file_sep># 61-ProyectoHospitalConcluido
| 2eedf618a8f7cb3637ed817ec98d670a62394c7d | [
"Markdown",
"C++"
] | 2 | C++ | luigisdeveloper/61-ProyectoHospitalConcluido | 422695ad4c6bfe19788bb849959ce8440ae723e2 | a451b0c8bfb1688adaa168e8228454ebbb2d4dd9 | |
refs/heads/master | <file_sep>import lozad from 'lozad';
import 'intersection-observer';
if (module.hot) {
module.hot.accept();
}
IntersectionObserver.prototype.POLL_INTERVAL = 100;
const observer = lozad();
observer.observe();
const lazyLoad = () => {
const images = document.querySelectorAll('.lozad');
for (let i; i < images; i++) {
observer.triggerLoad(images[i]);
}
};
lazyLoad();
| fa4b839260cd6b9bf3001e879c4e729505e6b0a1 | [
"JavaScript"
] | 1 | JavaScript | InBracketsIO/boilerplate-static | 1a4dd0fa876e0f9c16f13a3ce2d1499a3bc4c426 | 36a25678049ca365a5cb91c3cd799da6875ca9ed | |
refs/heads/master | <file_sep>package uk.co.jimmythompson.robocleaner.geometry;
import org.junit.Assert;
import org.junit.Test;
public class CoordinateTests {
@Test
public void getXShouldReturnSpecifiedXCoordinate() {
Coordinate coordinate = new Coordinate(1, 0);
Assert.assertEquals(1, coordinate.getX());
}
@Test
public void getYShouldReturnSpecifiedYCoordinate() {
Coordinate coordinate = new Coordinate(0, 1);
Assert.assertEquals(1, coordinate.getY());
}
@Test
public void translateShouldApplyTranslations() {
Coordinate coordinate = new Coordinate(0, 1);
Translation translation = Translation.of(2, -1);
Coordinate expectedResult = new Coordinate(2, 0);
Assert.assertEquals(expectedResult, coordinate.translate(translation));
}
@Test
public void equalsShouldReturnTrueIfObjectsAreTheSame() {
Coordinate coordinate = new Coordinate(5, 5);
Assert.assertEquals(coordinate, coordinate);
}
@Test
public void equalsShouldReturnFalseIfTheOtherIsNull() {
Coordinate coordinate = new Coordinate(3, 3);
Assert.assertNotEquals(coordinate, null);
}
@Test
public void equalsShouldReturnFalseIfTheTypesAreNotTheSame() {
Coordinate coordinate = new Coordinate(2, 2);
Assert.assertNotEquals(coordinate, new Object());
}
@Test
public void equalsShouldReturnTrueIfXAndYAreTheSame() {
Coordinate coordinate = new Coordinate(1, 1);
Coordinate other = new Coordinate(1, 1);
Assert.assertEquals(coordinate, other);
}
@Test
public void toStringShouldShowXAndY() {
Coordinate coordinate = new Coordinate(3, 2);
Assert.assertEquals("Coordinate{x=3, y=2}", coordinate.toString());
}
}
<file_sep>package uk.co.jimmythompson.robocleaner.cleaning;
public class SpillStatus {
private final int totalPatches;
private final int cleanedPatches;
public SpillStatus(int totalPatches, int cleanedPatches) {
this.totalPatches = totalPatches;
this.cleanedPatches = cleanedPatches;
}
public int getTotalPatches() {
return this.totalPatches;
}
public int getCleanedPatches() {
return cleanedPatches;
}
}
<file_sep>package uk.co.jimmythompson.robocleaner.geometry;
public enum Direction {
NORTH(Translation.of(0, 1)),
EAST(Translation.of(1, 0)),
SOUTH(Translation.of(0, -1)),
WEST(Translation.of(-1, 0));
private Translation translation;
Direction(Translation translation) {
this.translation = translation;
}
public Translation getTranslation() {
return translation;
}
}
<file_sep>package uk.co.jimmythompson.robocleaner.web;
import org.junit.Assert;
import org.junit.Test;
import uk.co.jimmythompson.robocleaner.geometry.Direction;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class RouteParserTests {
@Test
public void shouldParseNAsNorth() {
List<Direction> expectedList = Collections.singletonList(Direction.NORTH);
Assert.assertEquals(expectedList, RouteParser.parseRoute("N"));
}
@Test
public void shouldParseEAsEast() {
List<Direction> expectedList = Collections.singletonList(Direction.EAST);
Assert.assertEquals(expectedList, RouteParser.parseRoute("E"));
}
@Test
public void shouldParseSAsSouth() {
List<Direction> expectedList = Collections.singletonList(Direction.SOUTH);
Assert.assertEquals(expectedList, RouteParser.parseRoute("S"));
}
@Test
public void shouldParseWAsWest() {
List<Direction> expectedList = Collections.singletonList(Direction.WEST);
Assert.assertEquals(expectedList, RouteParser.parseRoute("W"));
}
@Test
public void shouldBeAbleToComposeRoutes() {
List<Direction> expectedList = Arrays.asList(
Direction.NORTH,
Direction.EAST,
Direction.SOUTH,
Direction.WEST
);
Assert.assertEquals(expectedList, RouteParser.parseRoute("NESW"));
}
}
<file_sep>package uk.co.jimmythompson.robocleaner.web;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import uk.co.jimmythompson.robocleaner.cleaning.Cleaner;
import uk.co.jimmythompson.robocleaner.cleaning.CleanerPilot;
import uk.co.jimmythompson.robocleaner.cleaning.SpillTracker;
@RestController
public class MainController {
@RequestMapping(path = "/", method = RequestMethod.POST)
SpillTrackingResult trackSpill(@RequestBody SpillTrackingRequest request) {
SpillTrackingRequestParser mapper = new SpillTrackingRequestParser(request);
Cleaner cleaner = Cleaner.deploy(mapper.getStartingPosition());
SpillTracker spillTracker = new SpillTracker(mapper.getOilPatches());
spillTracker.follow(cleaner);
CleanerPilot pilot = new CleanerPilot(mapper.getArea(), cleaner);
pilot.navigate(mapper.getRoute());
return new SpillTrackingResult(
cleaner.getLocation(),
spillTracker.getStatus().getCleanedPatches()
);
}
}
<file_sep>package uk.co.jimmythompson.robocleaner.cleaning;
import org.junit.Assert;
import org.junit.Test;
public class SpillStatusTests {
@Test
public void shouldHaveTheTotalNumberOfPatches() {
SpillStatus spillStatus = new SpillStatus(1, 2);
Assert.assertEquals(1, spillStatus.getTotalPatches());
}
@Test
public void shouldHaveTheNumberOfCleanedPatches() {
SpillStatus spillStatus = new SpillStatus(1, 2);
Assert.assertEquals(2, spillStatus.getCleanedPatches());
}
}
<file_sep>package uk.co.jimmythompson.robocleaner.cleaning;
import uk.co.jimmythompson.robocleaner.InvalidRouteException;
import uk.co.jimmythompson.robocleaner.geometry.Area;
import uk.co.jimmythompson.robocleaner.geometry.Coordinate;
import uk.co.jimmythompson.robocleaner.geometry.Direction;
public class CleanerPilot {
private Area area;
private Cleaner cleaner;
public CleanerPilot(Area area, Cleaner cleaner) {
this.area = area;
this.cleaner = cleaner;
}
public void navigate(Iterable<Direction> route) {
for (Direction direction: route) {
if (!this.isValidMovement(direction)) {
throw new InvalidRouteException();
}
this.cleaner.move(direction);
}
}
private boolean isValidMovement(Direction direction) {
Coordinate newLocation = this.cleaner.projectMovement(direction);
return this.area.contains(newLocation);
}
}
<file_sep>package uk.co.jimmythompson.robocleaner.cleaning;
import org.junit.Test;
import org.mockito.Mockito;
import uk.co.jimmythompson.robocleaner.InvalidRouteException;
import uk.co.jimmythompson.robocleaner.geometry.Area;
import uk.co.jimmythompson.robocleaner.geometry.Coordinate;
import uk.co.jimmythompson.robocleaner.geometry.Direction;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class CleanerPilotTests {
@Test
public void navigateShouldDirectTheCleaner() {
Area mockArea = Mockito.mock(Area.class);
Cleaner mockCleaner = Mockito.mock(Cleaner.class);
CleanerPilot pilot = new CleanerPilot(mockArea, mockCleaner);
pilot.navigate(asList(Direction.NORTH, Direction.EAST));
Coordinate newLocation = new Coordinate(1, 1);
when(mockCleaner.projectMovement(Direction.NORTH))
.thenReturn(newLocation);
when(mockArea.contains(newLocation)).thenReturn(true);
verify(mockCleaner).move(Direction.NORTH);
verify(mockCleaner).projectMovement(Direction.NORTH);
verify(mockCleaner).move(Direction.EAST);
}
@Test(expected = InvalidRouteException.class)
public void navigateShouldThrowAnExceptionWhenTheCleanerIsGoingToLeaveTheArea() {
Area mockArea = Mockito.mock(Area.class);
Cleaner mockCleaner = Mockito.mock(Cleaner.class);
CleanerPilot pilot = new CleanerPilot(mockArea, mockCleaner);
Coordinate newLocation = new Coordinate(1, 1);
when(mockCleaner.projectMovement(Direction.NORTH))
.thenReturn(newLocation);
when(mockArea.contains(newLocation)).thenReturn(false);
pilot.navigate(singletonList(Direction.NORTH));
}
}
<file_sep>package uk.co.jimmythompson.robocleaner.web;
import uk.co.jimmythompson.robocleaner.cleaning.OilPatch;
import uk.co.jimmythompson.robocleaner.geometry.Area;
import uk.co.jimmythompson.robocleaner.geometry.Coordinate;
import uk.co.jimmythompson.robocleaner.geometry.Direction;
import java.util.List;
import java.util.stream.Collectors;
public class SpillTrackingRequestParser {
private final SpillTrackingRequest request;
private static Coordinate parseCoordinate(List<Integer> unparsed) {
return new Coordinate(unparsed.get(0), unparsed.get(1));
}
public SpillTrackingRequestParser(SpillTrackingRequest request) {
this.request = request;
}
public Area getArea() {
Coordinate topRight = parseCoordinate(this.request.getAreaSize());
return new Area(topRight);
}
public Coordinate getStartingPosition() {
return parseCoordinate(this.request.getStartingPosition());
}
public List<OilPatch> getOilPatches() {
return this.request.getOilPatches().stream()
.map(SpillTrackingRequestParser::parseCoordinate)
.map(OilPatch::new)
.collect(Collectors.toList());
}
public List<Direction> getRoute() {
return RouteParser.parseRoute(this.request.getNavigationInstructions());
}
}
<file_sep>package uk.co.jimmythompson.robocleaner.web;
import uk.co.jimmythompson.robocleaner.geometry.Coordinate;
import java.util.List;
import static java.util.Arrays.asList;
public class SpillTrackingResult {
private List<Integer> finalPosition;
private Integer oilPatchesCleaned;
private static List<Integer> coordinateToList(Coordinate coordinate) {
return asList(coordinate.getX(), coordinate.getY());
}
public SpillTrackingResult(Coordinate finalPosition, int oilPatchesCleaned) {
this.finalPosition = coordinateToList(finalPosition);
this.oilPatchesCleaned = oilPatchesCleaned;
}
public List<Integer> getFinalPosition() {
return finalPosition;
}
public Integer getOilPatchesCleaned() {
return oilPatchesCleaned;
}
}
<file_sep>package uk.co.jimmythompson.robocleaner;
public class InvalidRouteException extends IllegalArgumentException {
}
<file_sep>package uk.co.jimmythompson.robocleaner.geometry;
import java.util.Objects;
public class Coordinate {
private int x;
private int y;
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public Coordinate translate(Translation translation) {
int newX = this.x + translation.getX();
int newY = this.y + translation.getY();
return new Coordinate(newX, newY);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null) {
return false;
}
if (getClass() != o.getClass()) {
return false;
}
Coordinate other = (Coordinate) o;
return Objects.equals(this.x, other.x)
&& Objects.equals(this.y, other.y);
}
@Override
public String toString() {
return "Coordinate{" +
"x=" + x +
", y=" + y +
'}';
}
}
<file_sep>package uk.co.jimmythompson.robocleaner.cleaning;
import org.junit.Assert;
import org.junit.Test;
import uk.co.jimmythompson.robocleaner.geometry.Coordinate;
import uk.co.jimmythompson.robocleaner.geometry.Direction;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
public class SpillTrackerTests {
@Test
public void shouldHaveOilPatches() {
Coordinate location = new Coordinate(1,1);
OilPatch oilPatch = new OilPatch(location);
SpillTracker spillTracker = new SpillTracker(singletonList(oilPatch));
Assert.assertEquals(singletonList(oilPatch), spillTracker.getOilPatches());
}
@Test
public void shouldMarkOilPatchesAsCleanWhenTheCleanerGoesOverThem() {
Coordinate oilPatchLocation = new Coordinate(1,1);
OilPatch oilPatch = new OilPatch(oilPatchLocation);
SpillTracker spillTracker = new SpillTracker(singletonList(oilPatch));
Coordinate cleanerLocation = new Coordinate(1, 0);
Cleaner cleaner = Cleaner.deploy(cleanerLocation);
Assert.assertFalse(oilPatch.hasBeenCleaned());
spillTracker.follow(cleaner);
cleaner.move(Direction.NORTH);
Assert.assertTrue(oilPatch.hasBeenCleaned());
}
@Test
public void getStatusShouldReturnTheNumberOfPatches() {
Coordinate firstLocation = new Coordinate(1,1);
OilPatch firstPatch = new OilPatch(firstLocation);
Coordinate secondLocation = new Coordinate(2,2);
OilPatch secondPatch = new OilPatch(secondLocation);
Coordinate thirdLocation = new Coordinate(3,3);
OilPatch thirdPatch = new OilPatch(thirdLocation);
SpillTracker spillTracker = new SpillTracker(asList(firstPatch, secondPatch, thirdPatch));
Assert.assertEquals(3, spillTracker.getStatus().getTotalPatches());
}
@Test
public void getStatusShouldReturnTheNumberOfCleanedPatches() {
Coordinate firstLocation = new Coordinate(1,1);
OilPatch firstPatch = new OilPatch(firstLocation);
Coordinate secondLocation = new Coordinate(2,2);
OilPatch secondPatch = new OilPatch(secondLocation);
Coordinate thirdLocation = new Coordinate(3,3);
OilPatch thirdPatch = new OilPatch(thirdLocation);
SpillTracker spillTracker = new SpillTracker(asList(firstPatch, secondPatch, thirdPatch));
Coordinate cleanerLocation = new Coordinate(1, 0);
Cleaner cleaner = Cleaner.deploy(cleanerLocation);
spillTracker.follow(cleaner);
cleaner.move(Direction.NORTH);
Assert.assertEquals(1, spillTracker.getStatus().getCleanedPatches());
}
}
<file_sep>package uk.co.jimmythompson.robocleaner.web;
import uk.co.jimmythompson.robocleaner.InvalidDirectionException;
import uk.co.jimmythompson.robocleaner.geometry.Direction;
import java.util.ArrayList;
import java.util.List;
public class RouteParser {
public static List<Direction> parseRoute(String routeAsString) {
List<Direction> route = new ArrayList<>();
for (String letter : routeAsString.split("")) {
route.add(fromString(letter));
}
return route;
}
private static Direction fromString(String code) {
switch (code) {
case "N":
return Direction.NORTH;
case "E":
return Direction.EAST;
case "S":
return Direction.SOUTH;
case "W":
return Direction.WEST;
}
throw new InvalidDirectionException();
}
}
<file_sep>package uk.co.jimmythompson.robocleaner.cleaning;
import uk.co.jimmythompson.robocleaner.geometry.Coordinate;
import uk.co.jimmythompson.robocleaner.geometry.Direction;
import java.util.Observable;
public class Cleaner extends Observable {
private Coordinate location;
public static Cleaner deploy(Coordinate startingLocation) {
return new Cleaner(startingLocation);
}
private Cleaner(Coordinate startingLocation) {
this.location = startingLocation;
}
public Coordinate getLocation() {
return this.location;
}
public Coordinate projectMovement(Direction direction) {
return this.location.translate(direction.getTranslation());
}
public Coordinate move(Direction direction) {
Coordinate newLocation = this.location.translate(direction.getTranslation());
this.location = newLocation;
this.setChanged();
this.notifyObservers(newLocation);
return newLocation;
}
}
<file_sep>package uk.co.jimmythompson.robocleaner.cleaning;
import org.junit.Assert;
import org.junit.Test;
import uk.co.jimmythompson.robocleaner.geometry.Coordinate;
public class OilPatchTests {
@Test
public void getLocationShouldReturnLocation() {
Coordinate location = new Coordinate(1, 1);
OilPatch oilPatch = new OilPatch(location);
Assert.assertEquals(location, oilPatch.getLocation());
}
@Test
public void hasBeenCleanedShouldBeginAsFalse() {
Coordinate location = new Coordinate(1, 1);
OilPatch oilPatch = new OilPatch(location);
Assert.assertFalse(oilPatch.hasBeenCleaned());
}
@Test
public void markAsCleanedShouldMarkThePatchAsCleaned() {
Coordinate location = new Coordinate(1, 1);
OilPatch oilPatch = new OilPatch(location);
oilPatch.markAsCleaned();
Assert.assertTrue(oilPatch.hasBeenCleaned());
}
}
| 294d4257dc03452226fa2b8ca918adaf3cd42928 | [
"Java"
] | 16 | Java | jimmythompson/robo-cleaner | d646a853211db29637d9fc6803ec585751b2ff81 | 428051d3fca09f4ec743259c641913d506fc44b6 | |
refs/heads/master | <repo_name>KELiON/cerebro-mac-apps<file_sep>/Readme.md
# cerebro-mac-apps
> Plugin for searching and launching applications on MacOS [Cerebro app](http://www.cerebroapp.com)
Note: this plugin on MacOS works better, than `cerebro-basic-apps`.

## Usage
Search for any application on your machine.
## Features
* Use `enter` to launch application;
* Use `cmd/ctrl+r` to show application in Finder or files explorer;
* Shows icons for your applications.
## Related
* [Cerebro](http://github.com/KELiON/cerebro) – main repo for Cerebro app;
* [cerebro tools](http://github.com/KELiON/cerebro-tools) – package with tools to simplify package creation;
## License
MIT © [<NAME>](http://asubbotin.ru)
<file_sep>/scripts/debug
#!/bin/sh
if [[ $1 == "dev" ]]; then
appname="Electron"
else
appname="Cerebro"
fi
case "$(uname -s)" in
Darwin)
symlink="${HOME}/Library/Application Support/${appname}/plugins/node_modules/${PWD##*/}"
trap "echo 'Deleting symlink' && rm -rf \"$symlink\"" SIGHUP SIGINT SIGTERM
;;
Linux)
symlink="${HOME}/.config/${appname}/plugins/node_modules/${PWD##*/}"
trap "echo 'Deleting symlink' && rm -rf \"$symlink\"" HUP INT TERM
;;
CYGWIN*|MINGW32*|MINGW64*|MSYS*)
symlink="${APPDATA}\\${appname}\plugins\node_modules\\${PWD##*/}"
trap "echo 'Deleting symlink' && rm -rf \"$symlink\"" SIGHUP SIGINT SIGTERM
;;
*)
echo "Unknown system. Please, open an issue in https://github.com/KELiON/cerebro-plugin/issues"
exit
;;
esac
echo "Creating symlink: $symlink -> ${PWD}"
ln -s "${PWD}" "$symlink"
./node_modules/.bin/webpack --watch
<file_sep>/src/Preview/index.js
import React, { PropTypes } from 'react'
import { FileIcon } from 'cerebro-ui'
import FileDetails from './FileDetails'
import styles from './styles.css'
const Preview = ({ path, name }) => (
<div>
<div className={styles.previewIcon}>
<FileIcon path={path} />
</div>
<div className={styles.previewName}>{name}</div>
<FileDetails path={path} key={path} skipName />
</div>
)
Preview.propTypes = {
path: PropTypes.string,
name: PropTypes.string,
}
export default Preview
<file_sep>/src/lib/mdfind.js
import flatten from 'lodash/flatten'
import { spawn } from 'child_process'
import path from 'path'
import { map, split, through } from 'event-stream'
const REAL_KEYS = {
kMDItemDisplayName: 'name',
kMDItemLastUsedDate: 'lastUsed',
kMDItemUseCount: 'useCount'
}
/**
* Parse mdfind result line to JS object
*
* @param {String} line
* @return {Object}
*/
function parseLine(line) {
const attrs = line.split(' ')
// First attr is always full path to the item
const filePath = attrs.shift()
const result = {
path: filePath,
filename: path.basename(filePath).replace(/\.app$/, '')
}
attrs.forEach(attr => {
const [key, value] = attr.split(' = ')
result[REAL_KEYS[key] || key] = getValue(value)
})
this.emit('data', result)
}
const getValue = (item) => {
if (!item || item === '(null)') {
return null
} else if (item.startsWith('(\n "') && item.endsWith('"\n)')) {
const actual = item.slice(7, -3)
const lines = actual.split('",\n "')
return lines
}
return item
}
const filterEmpty = (data, done) => {
if (data === '') {
done()
} else {
done(null, data)
}
}
const makeArgs = (array, argName) => (
flatten(array.map(item => [argName, item]))
)
export default function mdfind({
query,
attributes = Object.keys(REAL_KEYS),
names = [],
directories = [],
live = false,
interpret = false,
limit
} = {}) {
const dirArgs = makeArgs(directories, '-onlyin')
const nameArgs = makeArgs(names, '-name')
const attrArgs = makeArgs(attributes, '-attr')
const interpretArgs = interpret ? ['-interpret'] : []
const queryArgs = query ? [query] : []
const args = ['-0'].concat(
dirArgs,
nameArgs,
attrArgs,
interpretArgs,
live ? ['-live', '-reprint'] : [],
queryArgs
)
const child = spawn('mdfind', args)
let times = 0
return {
output: child.stdout
.pipe(split('\0'))
.pipe(map(filterEmpty))
// eslint-disable-next-line func-names
.pipe(through(function (data) {
times += 1
if (limit && times === limit) child.kill()
if (limit && times > limit) return
this.queue(data)
}))
.pipe(through(parseLine)),
terminate: () => child.kill()
}
}
| f4bd6854b9377c269d6fb708d60c13ced53737cb | [
"Markdown",
"JavaScript",
"Shell"
] | 4 | Markdown | KELiON/cerebro-mac-apps | dc00d5bce85fca926a665046277f1e9669ad5e18 | 8793e165e590c61f1d340ecc68e11236ea9c7c0a | |
refs/heads/main | <file_sep>import React from 'react';
import { MapContextProvider, MapContext } from './contexts/Map.js';
import Map from './contexts/Map';
const App = () => {
return (
<>
{/* <BrowserRouter>
<MapContext.Provider>
<Switch>
<Route />
<Route />
<Route />
</Switch>
</MapContext.Provider>
</BrowserRouter> */}
</>
);
};
export default App; | 5c5f8ce8aceccd40b87c52836de27662e850c872 | [
"JavaScript"
] | 1 | JavaScript | jeremy93130/bars | ce1196d2768d0272a38e6e87c552cae5da1b0475 | 0f1124f3baea01655f42c165004b361de6cea006 | |
refs/heads/master | <file_sep>"""
The ``elmo`` subcommand allows you to make bulk ELMo predictions.
Given a pre-processed input text file, this command outputs the internal
layers used to compute ELMo representations to a single (potentially large) file.
The input file is previously tokenized, whitespace separated text, one sentence per line.
The output is a hdf5 file (<http://docs.h5py.org/en/latest/>) where, with the --all flag, each
sentence is a size (3, num_tokens, 1024) array with the biLM representations.
For information, see "Deep contextualized word representations", Peters et al 2018.
https://arxiv.org/abs/1802.05365
.. code-block:: console
$ allennlp elmo --help
usage: allennlp elmo [-h] (--all | --top | --average)
[--vocab-path VOCAB_PATH] [--options-file OPTIONS_FILE]
[--weight-file WEIGHT_FILE] [--batch-size BATCH_SIZE]
[--cuda-device CUDA_DEVICE] [--forget-sentences]
[--use-sentence-keys] [--include-package INCLUDE_PACKAGE]
input_file output_file
Create word vectors using ELMo.
positional arguments:
input_file The path to the input file.
output_file The path to the output file.
optional arguments:
-h, --help show this help message and exit
--all Output all three ELMo vectors.
--top Output the top ELMo vector.
--average Output the average of the ELMo vectors.
--vocab-path VOCAB_PATH
A path to a vocabulary file to generate.
--options-file OPTIONS_FILE
The path to the ELMo options file.
--weight-file WEIGHT_FILE
The path to the ELMo weight file.
--batch-size BATCH_SIZE
The batch size to use.
--cuda-device CUDA_DEVICE
The cuda_device to run on.
--forget-sentences If this flag is specified, and --use-sentence-keys is
not, remove the string serialized JSON dictionary that
associates sentences with their line number (its HDF5
key) that is normally placed in the
"sentence_to_index" HDF5 key.
--use-sentence-keys Normally a sentence's line number is used as the HDF5
key for its embedding. If this flag is specified, the
sentence itself will be used as the key.
--include-package INCLUDE_PACKAGE
additional packages to include
"""
import argparse
import json
import logging
import os
from typing import IO, List, Iterable, Tuple
import warnings
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=FutureWarning)
import h5py
import numpy
import torch
#from allennlp.common.tqdm import Tqdm
from allennlp.common.util import lazy_groups_of, prepare_global_logging
from allennlp.common.checks import ConfigurationError
from allennlp.data.token_indexers.elmo_indexer import ELMoTokenCharactersIndexer
from allennlp.nn.util import remove_sentence_boundaries
from allennlp.modules.elmo import _ElmoBiLm, batch_to_ids
logger = logging.getLogger(__name__) # pylint: disable=invalid-name
DEFAULT_OPTIONS_FILE = "https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/2x4096_512_2048cnn_2xhighway/elmo_2x4096_512_2048cnn_2xhighway_options.json" # pylint: disable=line-too-long
DEFAULT_WEIGHT_FILE = "https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/2x4096_512_2048cnn_2xhighway/elmo_2x4096_512_2048cnn_2xhighway_weights.hdf5" # pylint: disable=line-too-long
DEFAULT_BATCH_SIZE = 64
def empty_embedding() -> numpy.ndarray:
return numpy.zeros((3, 0, 1024))
class ElmoEmbedder():
def __init__(self,
options_file: str = DEFAULT_OPTIONS_FILE,
weight_file: str = DEFAULT_WEIGHT_FILE,
cuda_device: int = -1) -> None:
"""
Parameters
----------
options_file : ``str``, optional
A path or URL to an ELMo options file.
weight_file : ``str``, optional
A path or URL to an ELMo weights file.
cuda_device : ``int``, optional, (default=-1)
The GPU device to run on.
"""
self.indexer = ELMoTokenCharactersIndexer()
logger.info("Initializing ELMo.")
self.elmo_bilm = _ElmoBiLm(options_file, weight_file)
if cuda_device >= 0:
self.elmo_bilm = self.elmo_bilm.cuda(device=cuda_device)
self.cuda_device = cuda_device
def batch_to_embeddings(self, batch: List[List[str]]) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Parameters
----------
batch : ``List[List[str]]``, required
A list of tokenized sentences.
Returns
-------
A tuple of tensors, the first representing activations (batch_size, 3, num_timesteps, 1024) and
the second a mask (batch_size, num_timesteps).
"""
character_ids = batch_to_ids(batch)
if self.cuda_device >= 0:
character_ids = character_ids.cuda(device=self.cuda_device)
bilm_output = self.elmo_bilm(character_ids)
layer_activations = bilm_output['activations']
mask_with_bos_eos = bilm_output['mask']
# without_bos_eos is a 3 element list of (activation, mask) tensor pairs,
# each with size (batch_size, num_timesteps, dim and (batch_size, num_timesteps)
# respectively.
without_bos_eos = [remove_sentence_boundaries(layer, mask_with_bos_eos)
for layer in layer_activations]
# Converts a list of pairs (activation, mask) tensors to a single tensor of activations.
activations = torch.cat([ele[0].unsqueeze(1) for ele in without_bos_eos], dim=1)
# The mask is the same for each ELMo vector, so just take the first.
mask = without_bos_eos[0][1]
return activations, mask
def embed_sentence(self, sentence: List[str]) -> numpy.ndarray:
"""
Computes the ELMo embeddings for a single tokenized sentence.
Please note that ELMo has internal state and will give different results for the same input.
See the comment under the class definition.
Parameters
----------
sentence : ``List[str]``, required
A tokenized sentence.
Returns
-------
A tensor containing the ELMo vectors.
"""
return self.embed_batch([sentence])[0]
def embed_batch(self, batch: List[List[str]]) -> List[numpy.ndarray]:
"""
Computes the ELMo embeddings for a batch of tokenized sentences.
Please note that ELMo has internal state and will give different results for the same input.
See the comment under the class definition.
Parameters
----------
batch : ``List[List[str]]``, required
A list of tokenized sentences.
Returns
-------
A list of tensors, each representing the ELMo vectors for the input sentence at the same index.
"""
elmo_embeddings = []
# Batches with only an empty sentence will throw an exception inside AllenNLP, so we handle this case
# and return an empty embedding instead.
if batch == [[]]:
elmo_embeddings.append(empty_embedding())
else:
embeddings, mask = self.batch_to_embeddings(batch)
for i in range(len(batch)):
length = int(mask[i, :].sum())
# Slicing the embedding :0 throws an exception so we need to special case for empty sentences.
if length == 0:
elmo_embeddings.append(empty_embedding())
else:
elmo_embeddings.append(embeddings[i, :, :length, :].detach().cpu().numpy())
return elmo_embeddings
def embed_sentences(self,
sentences: Iterable[List[str]],
batch_size: int = DEFAULT_BATCH_SIZE) -> Iterable[numpy.ndarray]:
"""
Computes the ELMo embeddings for a iterable of sentences.
Please note that ELMo has internal state and will give different results for the same input.
See the comment under the class definition.
Parameters
----------
sentences : ``Iterable[List[str]]``, required
An iterable of tokenized sentences.
batch_size : ``int``, required
The number of sentences ELMo should process at once.
Returns
-------
A list of tensors, each representing the ELMo vectors for the input sentence at the same index.
"""
for batch in lazy_groups_of(iter(sentences), batch_size):
yield from self.embed_batch(batch)
<file_sep>import torch
import torch.nn as nn
from torch.autograd import Variable
from data.Vocab import NMTVocab
class Critierion(nn.Module):
"""
Class for managing efficient loss computation. Handles
sharding next step predictions and accumulating mutiple
loss computations
Users can implement their own loss computation strategy by making
subclass of this one. Users need to implement the _compute_loss()
and make_shard_state() methods.
Args:
generator (:obj:`nn.Module`) :
module that maps the output of the decoder to a
distribution over the target vocabulary.
tgt_vocab (:obj:`Vocab`) :
torchtext vocab object representing the target output
normalzation (str): normalize by "sents" or "tokens"
"""
def __init__(self):
super(Critierion, self).__init__()
def _compute_loss(self, generator, *args, **kwargs):
"""
Compute the loss. Subclass must define this method.
Args:
output: the predict output from the model.
target: the validate target to compare output with.
**kwargs(optional): additional info for computing loss.
"""
raise NotImplementedError
def forward(self, generator, normalization=1.0, **kwargs):
return self._compute_loss(generator, **kwargs).div(normalization)
class NMTCritierion(Critierion):
"""
TODO:
1. Add label smoothing
"""
def __init__(self, padding_idx=NMTVocab.PAD, label_smoothing=0.0):
super().__init__()
self.padding_idx = padding_idx
self.label_smoothing = label_smoothing
if label_smoothing > 0:
self.criterion = nn.KLDivLoss(size_average=False)
else:
self.criterion = nn.NLLLoss(size_average=False, ignore_index=NMTVocab.PAD)
self.confidence = 1.0 - label_smoothing
def _smooth_label(self, num_tokens):
# When label smoothing is turned on,
# KL-divergence between q_{smoothed ground truth prob.}(w)
# and p_{prob. computed by model}(w) is minimized.
# If label smoothing value is set to zero, the loss
# is equivalent to NLLLoss or CrossEntropyLoss.
# All non-true labels are uniformly set to low-confidence.
one_hot = torch.randn(1, num_tokens)
one_hot.fill_(self.label_smoothing / (num_tokens - 2))
one_hot[0][self.padding_idx] = 0
return one_hot
def _bottle(self, v):
return v.view(-1, v.size(2))
def _compute_loss(self, generator, dec_outs, labels):
scores = generator(self._bottle(dec_outs)) # [batch_size * seq_len, d_words]
num_tokens = scores.size(-1)
gtruth = labels.view(-1)
if self.confidence < 1:
tdata = gtruth.data
mask = torch.nonzero(tdata.eq(self.padding_idx)).squeeze()
log_likelihood = torch.gather(scores.data, 1, tdata.unsqueeze(1))
one_hot = self._smooth_label(num_tokens)
if labels.is_cuda:
one_hot = one_hot.cuda()
tmp_ = one_hot.repeat(gtruth.size(0), 1)
tmp_.scatter_(1, tdata.unsqueeze(1), self.confidence)
if mask.dim() > 0:
log_likelihood.index_fill_(0, mask, 0)
tmp_.index_fill_(0, mask, 0)
gtruth = Variable(tmp_, requires_grad=False)
loss = self.criterion(scores, gtruth)
return loss
<file_sep>import torch.nn.functional as F
from torch.autograd import Variable
from data.DataLoader import *
from module.Utils import *
from data.Vocab import NMTVocab
class NMTHelper(object):
def __init__(self, model, critic, src_vocab, tgt_vocab, config):
self.model = model
self.critic = critic
p = next(filter(lambda p: p.requires_grad, model.parameters()))
self.use_cuda = p.is_cuda
self.device = p.get_device() if self.use_cuda else None
self.src_vocab = src_vocab
self.tgt_vocab = tgt_vocab
self.config = config
def prepare_training_data(self, src_inputs, tgt_inputs):
self.train_data = []
#for idx in range(self.config.max_train_length):
self.train_data.append([])
for src_input, tgt_input in zip(src_inputs, tgt_inputs):
#idx = int(len(src_input) - 1)
self.train_data[0].append((self.src_data_id(src_input), self.tgt_data_id(tgt_input)))
self.train_size = len(src_inputs)
self.batch_size = self.config.train_batch_size
batch_num = 0
#for idx in range(self.config.max_train_length):
train_size = len(self.train_data[0])
batch_num += int(np.ceil(train_size / float(self.batch_size)))
self.batch_num = batch_num
def prepare_valid_data(self, src_inputs, tgt_inputs):
self.valid_data = []
for src_input, tgt_input in zip(src_inputs, tgt_inputs):
self.valid_data.append((self.src_data_id(src_input), self.tgt_data_id(tgt_input)))
self.valid_size = len(self.valid_data)
def src_data_id(self, src_input):
result = self.src_vocab.word2id(src_input)
return result + [self.src_vocab.EOS]
def tgt_data_id(self, tgt_input):
result = self.tgt_vocab.word2id(tgt_input)
return [self.tgt_vocab.BOS] + result + [self.tgt_vocab.EOS]
def prepare_eval_data(self, src_inputs):
eval_data = []
for src_input in src_inputs:
eval_data.append((self.src_data_id(src_input), src_input))
return eval_data
def pair_data_variable(self, batch):
batch_size = len(batch)
src_lengths = [len(batch[i][0]) for i in range(batch_size)]
max_src_length = int(np.max(src_lengths))
tgt_lengths = [len(batch[i][1]) for i in range(batch_size)]
max_tgt_length = int(np.max(tgt_lengths))
src_words = Variable(torch.LongTensor(batch_size, max_src_length).fill_(NMTVocab.PAD), requires_grad=False)
tgt_words = Variable(torch.LongTensor(batch_size, max_tgt_length).fill_(NMTVocab.PAD), requires_grad=False)
for b, instance in enumerate(batch):
for index, word in enumerate(instance[0]):
src_words[b, index] = word
for index, word in enumerate(instance[1]):
tgt_words[b, index] = word
b += 1
if self.use_cuda:
src_words = src_words.cuda(self.device)
tgt_words = tgt_words.cuda(self.device)
return src_words, tgt_words, src_lengths, tgt_lengths
def source_data_variable(self, batch):
batch_size = len(batch)
src_lengths = [len(batch[i][0]) for i in range(batch_size)]
max_src_length = int(src_lengths[0])
src_words = Variable(torch.LongTensor(batch_size, max_src_length).fill_(NMTVocab.PAD), requires_grad=False)
for b, instance in enumerate(batch):
for index, word in enumerate(instance[0]):
src_words[b, index] = word
b += 1
if self.use_cuda:
src_words = src_words.cuda(self.device)
return src_words, src_lengths
def compute_forward(self, seqs_x, seqs_y, xlengths, normalization=1.0):
"""
:type model: Transformer
:type critic: NMTCritierion
"""
y_inp = seqs_y[:, :-1].contiguous()
y_label = seqs_y[:, 1:].contiguous()
dec_outs = self.model(seqs_x, y_inp, lengths=xlengths)
loss = self.critic(generator=self.model.generator,
normalization=normalization,
dec_outs=dec_outs,
labels=y_label)
mask = y_label.data.ne(NMTVocab.PAD)
pred = self.model.generator(dec_outs).data.max(2)[1] # [batch_size, seq_len]
num_correct = y_label.data.eq(pred).float().masked_select(mask).sum() / normalization
num_total = mask.sum().float()
stats = Statistics(loss.item(), num_total, num_correct)
return loss, stats
def train_one_batch(self, batch):
self.model.train()
self.model.zero_grad()
src_words, tgt_words, src_lengths, tgt_lengths = self.pair_data_variable(batch)
loss, stat = self.compute_forward(src_words, tgt_words, src_lengths)
loss = loss / self.config.update_every
loss.backward()
return stat
def valid(self, global_step):
valid_stat = Statistics()
self.model.eval()
for batch in create_batch_iter(self.valid_data, self.config.test_batch_size):
src_words, tgt_words, src_lengths, tgt_lengths = self.pair_data_variable(batch)
loss, stat = self.compute_forward(src_words, tgt_words, src_lengths)
valid_stat.update(stat)
valid_stat.print_valid(global_step)
return valid_stat
def translate(self, eval_data):
self.model.eval()
result = {}
for batch in create_batch_iter(eval_data, self.config.test_batch_size):
batch_size = len(batch)
src_words, src_lengths = self.source_data_variable(batch)
allHyp = self.translate_batch(src_words, src_lengths)
all_hyp_inds = [beam_result[0] for beam_result in allHyp]
for idx in range(batch_size):
if all_hyp_inds[idx][-1] == self.tgt_vocab.EOS:
all_hyp_inds[idx].pop()
all_hyp_words = [self.tgt_vocab.id2word(idxs) for idxs in all_hyp_inds]
for idx, instance in enumerate(batch):
result['\t'.join(instance[1])] = all_hyp_words[idx]
return result
def translate_batch(self, src_inputs, src_input_lengths):
word_ids = self.model(src_inputs, lengths=src_input_lengths, mode="infer", beam_size=self.config.beam_size)
word_ids = word_ids.cpu().numpy().tolist()
result = []
for sent_t in word_ids:
sent_t = [[wid for wid in line if wid != NMTVocab.PAD] for line in sent_t]
result.append(sent_t)
return result
<file_sep># DepSAWR
Dependency-Based Syntax-Aware Word Representations
- [ ] Sentence Classicication
- [ ] Sentence Matching
- [ ] Machine Translation
- [ ] Codes for our NAACL 2019 paper (slight improvements): Syntax-Enhanced Neural Machine Translation with Syntax-Aware Word Representations.
<file_sep>import numpy as np
import sys
import copy
sys.path.extend(["../","./"])
class NMTVocab:
PAD, BOS, EOS, UNK = 0, 1, 2, 3
S_PAD, S_BOS, S_EOS, S_UNK = '<pad>', '<s>', '</s>', '<unk>'
def __init__(self, word_list):
"""
:param word_list: list of words
"""
self.i2w = [self.S_PAD, self.S_BOS, self.S_EOS, self.S_UNK] + word_list
reverse = lambda x: dict(zip(x, range(len(x))))
self.w2i = reverse(self.i2w)
if len(self.w2i) != len(self.i2w):
print("serious bug: words dumplicated, please check!")
print("Vocab info: #words %d" % (self.size))
def word2id(self, xs):
if isinstance(xs, list):
return [self.w2i.get(x, self.UNK) for x in xs]
return self.w2i.get(xs, self.UNK)
def id2word(self, xs):
if isinstance(xs, list):
return [self.i2w[x] for x in xs]
return self.i2w[xs]
def save2file(self, outfile):
with open(outfile, 'w', encoding='utf8') as file:
for id, word in enumerate(self.i2w):
if id > self.UNK: file.write(word + '\n')
file.close()
@property
def size(self):
return len(self.i2w)
class Vocab(object):
PAD, ROOT, UNK = 0, 1, 2
def __init__(self, word_counter, rel_counter, relroot='root', min_occur_count = 2):
self._root = relroot
self._root_form = '<' + relroot.lower() + '>'
self._id2word = ['<pad>', self._root_form, '<unk>']
self._wordid2freq = [10000, 10000, 10000]
self._id2extword = ['<pad>', self._root_form, '<unk>']
self._id2rel = ['<pad>', relroot]
for word, count in word_counter.most_common():
if count > min_occur_count:
self._id2word.append(word)
self._wordid2freq.append(count)
for rel, count in rel_counter.most_common():
if rel != relroot: self._id2rel.append(rel)
reverse = lambda x: dict(zip(x, range(len(x))))
self._word2id = reverse(self._id2word)
if len(self._word2id) != len(self._id2word):
print("serious bug: words dumplicated, please check!")
self._rel2id = reverse(self._id2rel)
if len(self._rel2id) != len(self._id2rel):
print("serious bug: relation labels dumplicated, please check!")
print("Vocab info: #words %d, #rels %d" % (self.vocab_size, self.rel_size))
def load_pretrained_embs(self, embfile):
embedding_dim = -1
word_count = 0
with open(embfile, encoding='utf-8') as f:
for line in f.readlines():
if word_count < 1:
values = line.split()
embedding_dim = len(values) - 1
word_count += 1
print('Total words: ' + str(word_count) + '\n')
print('The dim of pretrained embeddings: ' + str(embedding_dim) + '\n')
index = len(self._id2extword)
embeddings = np.zeros((word_count + index, embedding_dim))
with open(embfile, encoding='utf-8') as f:
for line in f.readlines():
values = line.split()
self._id2extword.append(values[0])
vector = np.array(values[1:], dtype='float64')
embeddings[self.UNK] += vector
embeddings[index] = vector
index += 1
embeddings[self.UNK] = embeddings[self.UNK] / word_count
embeddings = embeddings / np.std(embeddings)
reverse = lambda x: dict(zip(x, range(len(x))))
self._extword2id = reverse(self._id2extword)
if len(self._extword2id) != len(self._id2extword):
print("serious bug: extern words dumplicated, please check!")
return embeddings
def create_pretrained_embs(self, embfile):
embedding_dim = -1
word_count = 0
with open(embfile, encoding='utf-8') as f:
for line in f.readlines():
if word_count < 1:
values = line.split()
embedding_dim = len(values) - 1
word_count += 1
print('Total words: ' + str(word_count) + '\n')
print('The dim of pretrained embeddings: ' + str(embedding_dim) + '\n')
index = len(self._id2extword) - word_count
embeddings = np.zeros((word_count + index, embedding_dim))
with open(embfile, encoding='utf-8') as f:
for line in f.readlines():
values = line.split()
if self._extword2id.get(values[0], self.UNK) != index:
print("Broken vocab or error embedding file, please check!")
vector = np.array(values[1:], dtype='float64')
embeddings[self.UNK] += vector
embeddings[index] = vector
index += 1
embeddings[self.UNK] = embeddings[self.UNK] / word_count
embeddings = embeddings / np.std(embeddings)
return embeddings
def word2id(self, xs):
if isinstance(xs, list):
return [self._word2id.get(x, self.UNK) for x in xs]
return self._word2id.get(xs, self.UNK)
def id2word(self, xs):
if isinstance(xs, list):
return [self._id2word[x] for x in xs]
return self._id2word[xs]
def wordid2freq(self, xs):
if isinstance(xs, list):
return [self._wordid2freq[x] for x in xs]
return self._wordid2freq[xs]
def extword2id(self, xs):
if isinstance(xs, list):
return [self._extword2id.get(x, self.UNK) for x in xs]
return self._extword2id.get(xs, self.UNK)
def id2extword(self, xs):
if isinstance(xs, list):
return [self._id2extword[x] for x in xs]
return self._id2extword[xs]
def rel2id(self, xs):
if isinstance(xs, list):
return [self._rel2id[x] for x in xs]
return self._rel2id[xs]
def id2rel(self, xs):
if isinstance(xs, list):
return [self._id2rel[x] for x in xs]
return self._id2rel[xs]
def copyfrom(self, vocab):
self._root = vocab._root
self._root_form = vocab._root_form
self._id2word = copy.deepcopy(vocab._id2word)
self._wordid2freq = copy.deepcopy(vocab._wordid2freq)
self._id2extword = copy.deepcopy(vocab._id2extword)
self._id2rel = copy.deepcopy(vocab._id2rel)
self._word2id = copy.deepcopy(vocab._word2id)
self._extword2id = copy.deepcopy(vocab._extword2id)
self._rel2id = copy.deepcopy(vocab._rel2id)
print("Vocab info: #words %d, #rels %d" % (self.vocab_size, self.rel_size))
@property
def vocab_size(self):
return len(self._id2word)
@property
def extvocab_size(self):
return len(self._id2extword)
@property
def rel_size(self):
return len(self._id2rel)
<file_sep>class Instance:
def __init__(self, words, tag):
self.words = words
self.forms = [word.lower() for word in words]
self.tag = tag
def __str__(self):
output = self.tag + "|||" + ' '.join(self.words)
return output
def readInstance(file):
total = 0
for line in file:
divides = line.strip().split('|||')
section_num = len(divides)
if section_num == 2:
words = divides[1].strip().split(' ')
tag = divides[0].strip()
total += 1
yield Instance(words, tag)
else:
pass
print("Total num: ", total)
def writeInstance(filename, insts):
with open(filename, 'w') as file:
for inst in insts:
file.write(str(inst) + '\n')
def printInstance(output, inst):
output.write(str(inst) + '\n')
<file_sep>import torch.nn.functional as F
from torch.autograd import Variable
from data.DataLoader import *
from module.Utils import *
from data.Vocab import *
from module.Tree import *
class NMTHelper(object):
def __init__(self, model, critic, src_vocab, tgt_vocab, config):
self.model = model
self.critic = critic
p = next(filter(lambda p: p.requires_grad, model.parameters()))
self.use_cuda = p.is_cuda
self.device = p.get_device() if self.use_cuda else None
self.src_vocab = src_vocab
self.tgt_vocab = tgt_vocab
self.config = config
def prepare_training_data(self, src_inputs, tgt_inputs):
self.train_data = []
#for idx in range(self.config.max_train_length):
self.train_data.append([])
for src_input, tgt_input in zip(src_inputs, tgt_inputs):
cur_length = len(src_input)
words, heads, rels = self.src_data_id(src_input)
root, tree = creatTree(heads)
if root.depth() > cur_length:
forms = [the_form + "_" + str(the_head) + "_" + the_rel for the_form, the_head, the_rel in src_input]
print("strange: " + '_'.join(forms))
self.train_data[0].append((words, rels, heads, self.tgt_data_id(tgt_input)))
self.train_size = len(src_inputs)
self.batch_size = self.config.train_batch_size
batch_num = 0
#for idx in range(self.config.max_train_length):
train_size = len(self.train_data[0])
batch_num += int(np.ceil(train_size / float(self.batch_size)))
self.batch_num = batch_num
def src_data_id(self, src_input):
words, heads, rels = [SRCVocab.ROOT], [-1], [SRCVocab.ROOT]
for unit in src_input:
words.append(self.src_vocab.word2id(unit[0]))
rels.append(self.src_vocab.rel2id(unit[2]))
heads.append(unit[1])
return words, heads, rels
def tgt_data_id(self, tgt_input):
result = self.tgt_vocab.word2id(tgt_input)
return [TGTVocab.BOS] + result + [TGTVocab.EOS]
def prepare_eval_data(self, src_inputs):
eval_data = []
for src_input in src_inputs:
words, heads, rels = self.src_data_id(src_input)
forms = [the_form for the_form, the_head, the_rel in src_input]
eval_data.append((words, rels, heads, forms))
return eval_data
def pair_data_variable(self, batch):
batch_size = len(batch)
src_lengths = [len(batch[i][0]) for i in range(batch_size)]
max_src_length = int(np.max(src_lengths))
tgt_lengths = [len(batch[i][3]) for i in range(batch_size)]
max_tgt_length = int(np.max(tgt_lengths))
src_words = Variable(torch.LongTensor(batch_size, max_src_length).fill_(SRCVocab.PAD), requires_grad=False)
src_rels = Variable(torch.LongTensor(batch_size, max_src_length).fill_(SRCVocab.PAD), requires_grad=False)
tgt_words = Variable(torch.LongTensor(batch_size, max_tgt_length).fill_(TGTVocab.PAD), requires_grad=False)
heads = []
for b, instance in enumerate(batch):
for index, word in enumerate(instance[0]):
src_words[b, index] = word
for index, rel in enumerate(instance[1]):
src_rels[b, index] = rel
heads.append(instance[2])
for index, word in enumerate(instance[3]):
tgt_words[b, index] = word
b += 1
if self.use_cuda:
src_words = src_words.cuda(self.device)
src_rels = src_rels.cuda(self.device)
tgt_words = tgt_words.cuda(self.device)
return src_words, src_rels, heads, src_lengths, tgt_words
def source_data_variable(self, batch):
batch_size = len(batch)
src_lengths = [len(batch[i][0]) for i in range(batch_size)]
max_src_length = int(src_lengths[0])
src_words = Variable(torch.LongTensor(batch_size, max_src_length).fill_(SRCVocab.PAD), requires_grad=False)
src_rels = Variable(torch.LongTensor(batch_size, max_src_length).fill_(SRCVocab.PAD), requires_grad=False)
heads = []
for b, instance in enumerate(batch):
for index, word in enumerate(instance[0]):
src_words[b, index] = word
for index, rel in enumerate(instance[1]):
src_rels[b, index] = rel
heads.append(instance[2])
b += 1
if self.use_cuda:
src_words = src_words.cuda(self.device)
src_rels = src_rels.cuda(self.device)
return src_words, src_rels, heads, src_lengths
def compute_forward(self, seqs_x, seqs_rel, seqs_head, seqs_y, xlengths, normalization=1.0):
"""
:type model: Transformer
:type critic: NMTCritierion
"""
y_inp = seqs_y[:, :-1].contiguous()
y_label = seqs_y[:, 1:].contiguous()
dec_outs = self.model(seqs_x, seqs_rel, seqs_head, y_inp, lengths=xlengths)
loss = self.critic(generator=self.model.generator,
normalization=normalization,
dec_outs=dec_outs,
labels=y_label)
mask = y_label.data.ne(TGTVocab.PAD)
pred = self.model.generator(dec_outs).data.max(2)[1] # [batch_size, seq_len]
num_correct = y_label.data.eq(pred).float().masked_select(mask).sum() / normalization
num_total = mask.sum().float()
stats = Statistics(loss.item(), num_total, num_correct)
return loss, stats
def train_one_batch(self, batch):
self.model.train()
self.model.zero_grad()
src_words, src_rels, heads, src_lengths, tgt_words = self.pair_data_variable(batch)
loss, stat = self.compute_forward(src_words, src_rels, heads, tgt_words, src_lengths)
loss = loss / self.config.update_every
loss.backward()
return stat
def translate(self, eval_data):
self.model.eval()
result = {}
for batch in create_batch_iter(eval_data, self.config.test_batch_size):
batch_size = len(batch)
src_words, src_rels, heads, src_lengths = self.source_data_variable(batch)
allHyp = self.translate_batch(src_words, src_rels, heads, src_lengths)
all_hyp_inds = [beam_result[0] for beam_result in allHyp]
for idx in range(batch_size):
if all_hyp_inds[idx][-1] == self.tgt_vocab.EOS:
all_hyp_inds[idx].pop()
all_hyp_words = [self.tgt_vocab.id2word(idxs) for idxs in all_hyp_inds]
for idx, instance in enumerate(batch):
result['\t'.join(instance[-1])] = all_hyp_words[idx]
return result
def translate_batch(self, src_inputs, src_rels, src_heads, src_input_lengths):
word_ids = self.model(src_inputs, src_rels, src_heads, lengths=src_input_lengths, \
mode="infer", beam_size=self.config.beam_size)
word_ids = word_ids.cpu().numpy().tolist()
result = []
for sent_t in word_ids:
sent_t = [[wid for wid in line if wid != TGTVocab.PAD] for line in sent_t]
result.append(sent_t)
return result
<file_sep>import re
def tokenize(input_word):
input_word = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", input_word)
input_word = re.sub(r"\'s", " is", input_word)
input_word = re.sub(r"\'ve", " have", input_word)
input_word = re.sub(r"n\'t", " not", input_word)
input_word = re.sub(r"\'re", " are", input_word)
input_word = re.sub(r"\'d", " had", input_word)
input_word = re.sub(r"\'ll", " will", input_word)
input_word = re.sub(r",", " , ", input_word)
input_word = re.sub(r"!", " ! ", input_word)
input_word = re.sub(r"\(", " \( ", input_word)
input_word = re.sub(r"\)", " \) ", input_word)
input_word = re.sub(r"\?", " \? ", input_word)
input_word = re.sub(r"\s{2,}", " ", input_word)
return input_word.strip().lower()
class Instance:
def __init__(self, words, tag):
self.words = words
self.forms = [tokenize(word) for word in words]
self.tag = tag
def __str__(self):
output = self.tag + "|||" + ' '.join(self.words)
return output
def readInstance(file):
total = 0
for line in file:
divides = line.strip().split('|||')
section_num = len(divides)
if section_num == 2:
words = divides[1].strip().split(' ')
tag = divides[0].strip()
total += 1
yield Instance(words, tag)
else:
pass
print("Total num: ", total)
def writeInstance(filename, insts):
with open(filename, 'w') as file:
for inst in insts:
file.write(str(inst) + '\n')
def printInstance(output, inst):
output.write(str(inst) + '\n')
| 9c1e87ccf7b4a9e9509862db462eaeeed7d0875a | [
"Markdown",
"Python"
] | 8 | Python | HMJW/DepSAWR | 15c87dadd7a4389d92054fcf89a09dead75c6a82 | d81250f10a58d8ca89fc6051801f328fc00b4fc4 | |
refs/heads/master | <file_sep>package com.example.hp.firechat;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v7.widget.Toolbar;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.iid.FirebaseInstanceId;
import java.util.HashMap;
public class RegisterActivity extends AppCompatActivity {
private EditText mDisplayName;
private EditText mEmail;
private EditText mPassword;
private Button mCreateBtn;
private ProgressDialog PD;
private FirebaseAuth mAuth;
private Toolbar mToolbar;
FirebaseUser current_user;
private DatabaseReference mDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mDisplayName = (EditText) findViewById(R.id.nameField);
mEmail = (EditText) findViewById(R.id.emailField);
mPassword = (EditText) findViewById(R.id.passwordField);
mCreateBtn = (Button) findViewById(R.id.registerBtn);
mAuth = FirebaseAuth.getInstance();
current_user = FirebaseAuth.getInstance().getCurrentUser();
mToolbar = (Toolbar) findViewById(R.id.register_toolbar);
PD = new ProgressDialog(RegisterActivity.this);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Create Account");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mCreateBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
final String name = mDisplayName.getText().toString().trim();
final String email = mEmail.getText().toString().trim();
final String password = mPassword.getText().toString().trim();
if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(email) && !TextUtils.isEmpty(password)) {
PD.setMessage("signing up");
PD.setIndeterminate(false);
PD.setCanceledOnTouchOutside(false);
PD.setCancelable(true);
PD.show();
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
current_user = FirebaseAuth.getInstance().getCurrentUser();
if(current_user!=null) {
String uid = current_user.getUid();
String device_token= FirebaseInstanceId.getInstance().getToken();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(uid);
mDatabase.child("name").setValue(name);
mDatabase.child("status").setValue("hi there I am using FireChat");
mDatabase.child("image").setValue("default");
mDatabase.child("thumb_image").setValue("default");
mDatabase.child("device_token").setValue(device_token);
/* HashMap<String, String> userMap = new HashMap<>();
userMap.put("name", name);
userMap.put("status", "hi there I am using FireChat");
userMap.put("image", "default");
userMap.put("thumb_image", "default");*/
Toast.makeText(getApplicationContext(), "uploading is successful", Toast.LENGTH_SHORT).show();
Intent mainIntent = new Intent(RegisterActivity.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
if (PD.isShowing()) {
PD.dismiss();
}
}
} else {
Toast.makeText(getApplicationContext(), "uploading is not successful", Toast.LENGTH_SHORT).show();
if (PD.isShowing()) {
PD.dismiss();
}
}
}
});
} else {
Toast.makeText(getApplicationContext(), "PLEASE ENTER THE FIELDS", Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
e.printStackTrace();
}
}
});
}
}
<file_sep>package com.example.hp.firechat;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.support.v7.widget.Toolbar;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ServerValue;
import com.google.firebase.database.ValueEventListener;
public class StatusActivity extends AppCompatActivity {
private Button changeBtn;
private EditText status;
private Toolbar status_Tool;
private DatabaseReference mDatabase;
private FirebaseAuth mAuth;
private ProgressDialog PD;
private String uid;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_status);
changeBtn=(Button)findViewById(R.id.changeBtn);
status=(EditText)findViewById(R.id.Date_text);
status_Tool=(Toolbar) findViewById(R.id.status_toolbar);
setSupportActionBar(status_Tool);
getSupportActionBar().setTitle("Change status");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mAuth=FirebaseAuth.getInstance();
mDatabase= FirebaseDatabase.getInstance().getReference().child("Users");
uid=mAuth.getCurrentUser().getUid();
mDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String statusBro=dataSnapshot.child(uid).child("status").getValue().toString();
status.setText(statusBro);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
changeBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String status_changed = status.getText().toString();
if(!TextUtils.isEmpty(status_changed)) {
/* if(PD == null){
PD = new ProgressDialog(StatusActivity.this);
PD.setMessage("please wait..");
PD.setIndeterminate(false);
PD.setCancelable(true);
PD.show();
} */
mDatabase.child(uid).child("status").setValue(status_changed);
Intent SettingsIntent = new Intent(StatusActivity.this, SettingsActivity.class);
// SettingsIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
// SettingsIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(SettingsIntent);
Toast.makeText(getApplicationContext(), "status is updated", Toast.LENGTH_SHORT).show();
/* if(PD.isShowing()){
PD.dismiss();
} */
}
else{
Toast.makeText(getApplicationContext(), "Please enter the field", Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
protected void onResume(){
super.onResume();
Log.e("ajay123","wow1");
FirebaseUser currentUser=mAuth.getCurrentUser();
if(currentUser!=null) {
mDatabase.child(currentUser.getUid()).child("online").setValue("true");
// mDatabase.child(CurrentUser.getUid()).child("LastSeen").setValue(ServerValue.TIMESTAMP);
}
}
@Override
protected void onPause() {
super.onPause();
Log.e("ajay124","wow2");
FirebaseUser currentUser=mAuth.getCurrentUser();
if(currentUser!=null) {
mDatabase.child(currentUser.getUid()).child("online").setValue(ServerValue.TIMESTAMP);
// mDatabase.child(CurrentUser.getUid()).child("LastSeen").setValue(ServerValue.TIMESTAMP);
}
}
}
<file_sep>package com.example.hp.firechat;
/**
* Created by hp on 12/9/2017.
*/
public class ChatsFrag {
public String date;
public ChatsFrag(){
}
public ChatsFrag(String date){
this.date=date;
}
public String getDate(){
return date;
}
public void setDate(String date){
this.date=date;
}
}
<file_sep>package com.example.hp.firechat;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class FutureMessagingActivity extends AppCompatActivity {
private Toolbar status_Tool;
private EditText DateText;
private EditText TimeText;
private EditText MessageText;
private Button OkayBtn;
private String mChatUser;
private String mChatUsername;
private DatabaseReference mMessagesDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_future_messaging);
status_Tool=(Toolbar) findViewById(R.id.future_app_toolbar);
setSupportActionBar(status_Tool);
getSupportActionBar().setTitle("Change status");
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
DateText=(EditText)findViewById(R.id.Date_text);
TimeText=(EditText)findViewById(R.id.Time_text);
OkayBtn=(Button)findViewById(R.id.okay_button);
MessageText=(EditText)findViewById(R.id.future_Message);
mChatUser = getIntent().getStringExtra("current_user");
mChatUsername = getIntent().getStringExtra("user_key");
mMessagesDatabase= FirebaseDatabase.getInstance().getReference().child("FutureMessages");
OkayBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
String Date = DateText.getText().toString();
String Time = TimeText.getText().toString();
final String message = MessageText.getText().toString();
if (!TextUtils.isEmpty(Date) && !TextUtils.isEmpty(Time) && !TextUtils.isEmpty(message)) {
if (Date.length() == 10 && Time.length() == 8) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date date3 = null;
try {
date3 = dateFormat.parse(Date + " " + Time);
} catch (ParseException e) {
e.printStackTrace();
}
final long unixTime3 = (long) date3.getTime();
Log.e("database", "ajay" + unixTime3);
Log.e("database", "vijay" + System.currentTimeMillis());
mMessagesDatabase.child(mChatUsername).child(mChatUser).child("type").setValue("going").addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
mMessagesDatabase.child(mChatUsername).child(mChatUser).child("message").setValue(message);
mMessagesDatabase.child(mChatUsername).child(mChatUser).child("ftimestamp").setValue(unixTime3);
mMessagesDatabase.child(mChatUsername).child(mChatUser).child("timestamp").setValue(System.currentTimeMillis());
mMessagesDatabase.child(mChatUser).child(mChatUsername).child("timestamp").setValue(System.currentTimeMillis());
mMessagesDatabase.child(mChatUser).child(mChatUsername).child("type").setValue("coming");
mMessagesDatabase.child(mChatUser).child(mChatUsername).child("message").setValue(message);
mMessagesDatabase.child(mChatUser).child(mChatUsername).child("ftimestamp").setValue(unixTime3).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (!task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "failed to add it ", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Added to the database ", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
} else {
Toast.makeText(getApplicationContext(), "please enter correct inputs", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "Please enter the fields", Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
e.printStackTrace();
}
}
});
}
@Override
protected void onResume() {
super.onResume();//visible
Log.d("resume11","Activity resumed");
}
@Override
protected void onPause() {
super.onPause();//invisible
Log.d("resume12", "Activity paused");
}
}
<file_sep>package com.example.hp.firechat;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.android.gms.tasks.*;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ServerValue;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Callback;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import java.util.TimeZone;
import de.hdodenhof.circleimageview.CircleImageView;
public class GoodChatActivity extends AppCompatActivity {
private String mChatUser;
private Toolbar chat_Tool_bar;
private DatabaseReference mRootRef;
private String mChatUsername;
private TextView mTitleView;
private TextView mLastSeenView;
private CircleImageView mProfileImage;
private FirebaseAuth mAuth;
private String mCurrentUserId;
private ImageButton mChatAddBtn;
private ImageButton mChatSendBtn;
private EditText mChatMsgView;
private RecyclerView mMessagesList;
// private SwipeRefreshLayout mRefreshLayout;
private final List<Messages> messagesList=new ArrayList<>();
private LinearLayoutManager mLinearLayout;
// private MessageAdapter mAdapter;
private DatabaseReference mMessageDatabase;
private static final int Total_items_to_load=10;
private int mCurrentPage=1;
private int itempos=0;
private String mLastKey="";
private String mPrevKey="";
private DatabaseReference mFutureReference;
private DatabaseReference mMessagesReference;
private DatabaseReference mMessages;
private DatabaseReference mDatabase;
private String watching;
private String image,imageUser;
private int watch;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_good_chat);
mChatUser = getIntent().getStringExtra("Blog_id");
// watching=getIntent().getStringExtra("watch");
// Toast.makeText(getApplicationContext(), watching, Toast.LENGTH_SHORT).show();
// watch=Integer.parseInt(watching);
// Toast.makeText(getApplicationContext(),mChatUser, Toast.LENGTH_SHORT).show();
// mChatUsername = getIntent().getStringExtra("user_name");
mChatAddBtn = (ImageButton) findViewById(R.id.chat_add_Btn);
mChatSendBtn = (ImageButton) findViewById(R.id.chat_send_Btn);
mChatMsgView = (EditText) findViewById(R.id.chat_view_EditText);
mAuth = FirebaseAuth.getInstance();
mCurrentUserId = mAuth.getCurrentUser().getUid();
chat_Tool_bar = (Toolbar) findViewById(R.id.chat_tool_bar_bro);
setSupportActionBar(chat_Tool_bar);
//setting the adapter
//from there to here
mRootRef = FirebaseDatabase.getInstance().getReference();
mRootRef.child("Messages").keepSynced(true);
// getSupportActionBar().setTitle(mChatUsername);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View action_bar_view = inflater.inflate(R.layout.chat_custom_bar, null);
actionBar.setCustomView(action_bar_view);
mMessagesList = (RecyclerView) findViewById(R.id.messages_list2);
mLinearLayout = new LinearLayoutManager(GoodChatActivity.this);
mMessagesList.setHasFixedSize(true);
mMessagesList.setLayoutManager(mLinearLayout);
mTitleView = (TextView) findViewById(R.id.custom_display_name);
mLastSeenView = (TextView) findViewById(R.id.custom_last_seen);
mProfileImage = (CircleImageView) findViewById(R.id.custom_bar_image);
// mTitleView.setText(mChatUsername);
//setting the adapter
// mAdapter = new MessageAdapter(messagesList);
// mMessagesList.setAdapter(mAdapter);
// mRefreshLayout=(SwipeRefreshLayout)findViewById(R.id.message_swipe_layout);
mFutureReference=FirebaseDatabase.getInstance().getReference().child("FutureMessages");
mMessagesReference=FirebaseDatabase.getInstance().getReference().child("Messages");
mDatabase=FirebaseDatabase.getInstance().getReference().child("Users");
mRootRef.child("Messages").child(mCurrentUserId).child(mChatUser).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
long k=dataSnapshot.getChildrenCount();
mRootRef.child("seenMsgs").child(mCurrentUserId).child(mChatUser).child("seen").setValue(k).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
// Toast.makeText(getApplicationContext(),"computed succesfully", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(),"computed unsuccesfully", Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
//loadMessages();
//from there to here
mDatabase.child(mCurrentUserId).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
imageUser=dataSnapshot.child("image").getValue().toString(); //
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
mRootRef.child("Users").child(mChatUser).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("online")) {
String online = dataSnapshot.child("online").getValue().toString();
image = dataSnapshot.child("image").getValue().toString(); //
String name=dataSnapshot.child("name").getValue().toString();
mTitleView.setText(name);
if (online.equals("true")) {
mLastSeenView.setText("online");
} else {
GetTimeAgo getTimeAgo = new GetTimeAgo();
Long lastTime = Long.parseLong(online);
String LastSeenTime = getTimeAgo.getTimeAgo(lastTime, GoodChatActivity.this);
mLastSeenView.setText(LastSeenTime);
}
if(!image.equals("default")) {
Picasso.with(GoodChatActivity.this).load(image).networkPolicy(NetworkPolicy.OFFLINE).placeholder(R.mipmap.ic_account_circle_white_48dp).into(mProfileImage, new Callback() {
@Override
public void onSuccess() {
}
@Override
public void onError() {
Picasso.with(GoodChatActivity.this).load(image).placeholder(R.mipmap.ic_account_circle_white_48dp).into(mProfileImage);
}
});
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
mRootRef.child("Chat").child(mCurrentUserId).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(mChatUser)) {
mRootRef.child("Chat").child(mCurrentUserId).child(mChatUser).child("seen").setValue("false").addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull com.google.android.gms.tasks.Task<Void> task) {
if (task.isSuccessful()) {
mRootRef.child("Chat").child(mCurrentUserId).child(mChatUser).child("timestamp").setValue(ServerValue.TIMESTAMP);
mRootRef.child("Chat").child(mChatUser).child(mCurrentUserId).child("timestamp").setValue(ServerValue.TIMESTAMP);
mRootRef.child("Chat").child(mChatUser).child(mCurrentUserId).child("seen").setValue("false");
}
}
});
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
mChatSendBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendMessage();
}
});
mChatAddBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent FutureMessaging = new Intent(GoodChatActivity.this, FutureMessagingActivity.class);
// Toast.makeText(getApplicationContext(),"going to loginactivity", Toast.LENGTH_SHORT).show();
//loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
FutureMessaging.putExtra("current_user",mCurrentUserId);
FutureMessaging.putExtra("user_key",mChatUser);
startActivity(FutureMessaging);
//finish();
}
});
}
private void sendMessage() {
try {
final String message = mChatMsgView.getText().toString();
if (!TextUtils.isEmpty(message)) {
final DatabaseReference current_user_ref = mRootRef.child("Messages").child(mCurrentUserId).child(mChatUser);
final DatabaseReference chat_user_ref = mRootRef.child("Messages").child(mChatUser).child(mCurrentUserId);
DatabaseReference user_msg_push = mRootRef.child("Messages").child(mCurrentUserId).child(mChatUser).push();
final String push_id_user = user_msg_push.getKey();
current_user_ref.child(push_id_user).child("message").setValue(message).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
current_user_ref.child(push_id_user).child("seen").setValue("false");
current_user_ref.child(push_id_user).child("type").setValue("text");
current_user_ref.child(push_id_user).child("from").setValue(mCurrentUserId);
current_user_ref.child(push_id_user).child("time").setValue(System.currentTimeMillis());
chat_user_ref.child(push_id_user).child("time").setValue(System.currentTimeMillis());
chat_user_ref.child(push_id_user).child("from").setValue(mCurrentUserId);
chat_user_ref.child(push_id_user).child("message").setValue(message);
chat_user_ref.child(push_id_user).child("seen").setValue("false");
chat_user_ref.child(push_id_user).child("type").setValue("text");
mChatMsgView.setText("");
current_user_ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
long k=dataSnapshot.getChildrenCount();
mMessagesList.scrollToPosition((int)k -1);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Toast.makeText(getApplicationContext(), "Message is sent successfully", Toast.LENGTH_SHORT).show();
}
}
});
} else {
Toast.makeText(getApplicationContext(), "Please enter any message", Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public void onStart() {
super.onStart();
mMessages = FirebaseDatabase.getInstance().getReference().child("Messages").child(mCurrentUserId).child(mChatUser);
FirebaseRecyclerAdapter<GoodChat,GoodChatActivity.ChatViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<GoodChat, GoodChatActivity.ChatViewHolder>(
GoodChat.class,
R.layout.message_single_layout,
GoodChatActivity.ChatViewHolder.class,
mMessages
) {
@Override
protected void populateViewHolder(final GoodChatActivity.ChatViewHolder chatViewHolder, GoodChat chats, int position) {
try {
final String user_key = getRef(position).getKey();int i=0;
String current_user_id = mAuth.getCurrentUser().getUid();
String from_user = chats.getFrom();
// viewHolder.settings(from_user,current_user_id);
chatViewHolder.mMessageText.setText(chats.getMessage());
// ChatViewHolder.settings(time);
mDatabase.child(from_user).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
chatViewHolder.mMessageName.setText(dataSnapshot.child("name").getValue().toString());
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
mRootRef.child("Messages").child(mCurrentUserId).child(mChatUser).child(user_key).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
int i=0;
long time= Long.parseLong(dataSnapshot.child("time").getValue().toString());
String[] st=new String[3];
Date date = new Date(time);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); // the format of your date
sdf.setTimeZone(TimeZone.getTimeZone("GMT+05:30")); // give a timezone reference for formating (see comment at the bottom
String formattedDate = sdf.format(date);
StringTokenizer str=new StringTokenizer(formattedDate," ");
while(str.hasMoreElements()){
st[i++]=str.nextToken();
}
chatViewHolder.mTime.setText(st[1]);
i=0;
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
if (current_user_id.equals(from_user)) {
chatViewHolder.mMessageText.setBackgroundColor(Color.WHITE);
// Toast.makeText(getClass(),"uploading thumbnail2 is failed", Toast.LENGTH_SHORT).show();
Log.d("one", "current user id");
chatViewHolder.mMessageText.setTextColor(Color.BLACK);
} else {
chatViewHolder.mMessageText.setBackgroundResource(R.drawable.message_text_background);
chatViewHolder.mMessageText.setTextColor(Color.WHITE);
}
}catch (Exception e){
e.printStackTrace();
}
}
};
mMessagesList.setAdapter(firebaseRecyclerAdapter);
mMessages.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
final long num = dataSnapshot.getChildrenCount();
mMessagesList.scrollToPosition((int)num-1);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public static class ChatViewHolder extends RecyclerView.ViewHolder{
public TextView mMessageText;
public TextView mMessageName;
public static CircleImageView profileImage;
public TextView mTime;
View mView;
public ChatViewHolder(View view){
super(view);
mView=view;
mMessageText=(TextView)view.findViewById(R.id.message_text_layout);
profileImage=(CircleImageView)view.findViewById(R.id.message_profile_layout);
mMessageName=(TextView)view.findViewById(R.id.message_name_layout);
mTime=(TextView)view.findViewById(R.id.message_time_layout);
}
public static void settings(long time) {
long timer=time;int i=0;
String[] st=new String[3];
Date date = new Date(time);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); // the format of your date
sdf.setTimeZone(TimeZone.getTimeZone("GMT+05:30")); // give a timezone reference for formating (see comment at the bottom
String formattedDate = sdf.format(date);
StringTokenizer str=new StringTokenizer(formattedDate," ");
while(str.hasMoreElements()){
st[i++]=str.nextToken();
}
// mTime.setText(st[1]);
// System.out.println(formattedDate);
// Log.d("time 5","ajay2 "+formattedDate);
}
}
@Override
protected void onResume(){
super.onResume();
Log.e("ajay123","wow1");
FirebaseUser currentUser=mAuth.getCurrentUser();
if(currentUser!=null) {
mDatabase.child(currentUser.getUid()).child("online").setValue("true");
// mDatabase.child(CurrentUser.getUid()).child("LastSeen").setValue(ServerValue.TIMESTAMP);
}
}
@Override
protected void onPause() {
super.onPause();
Log.e("ajay124","wow2");
FirebaseUser currentUser=mAuth.getCurrentUser();
if(currentUser!=null) {
mDatabase.child(currentUser.getUid()).child("online").setValue(ServerValue.TIMESTAMP);
// mDatabase.child(CurrentUser.getUid()).child("LastSeen").setValue(ServerValue.TIMESTAMP);
}
}
}
<file_sep>package com.example.hp.firechat;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ServerValue;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private FirebaseUser CurrentUser,mCurrentUser;
private Toolbar mToolbar;
private SectionPageAdapter mSectionPagerAdapter;
private ViewPager mViewPager;
private TabLayout mTablayout;
private DatabaseReference mDatabase;
//private FirebaseUser mCurrentUser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
mCurrentUser=mAuth.getCurrentUser();
mToolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Fire Chat");
if(mCurrentUser!=null) {
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
}
//getting the tabs
mViewPager = (ViewPager) findViewById(R.id.main_tabPager);
mSectionPagerAdapter = new SectionPageAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mSectionPagerAdapter);
mTablayout = (TabLayout) findViewById(R.id.main_tabs);
mTablayout.setupWithViewPager(mViewPager);
// threadBro();
}catch (Exception e){
e.printStackTrace();
}
}
@Override
protected void onStart() {
super.onStart();
CurrentUser=mAuth.getCurrentUser();
if(CurrentUser==null){
Intent loginIntent = new Intent(MainActivity.this, StartActivity.class);
// Toast.makeText(getApplicationContext(),"going to loginactivity", Toast.LENGTH_SHORT).show();
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(loginIntent);
finish();
}
else{
// Toast.makeText(getApplicationContext(),"there is some person who logged in", Toast.LENGTH_SHORT).show();
try {
mDatabase.child(CurrentUser.getUid()).child("online").setValue("true");
}catch(Exception e){
e.printStackTrace();
}
}
}
/* @Override
protected void onStop() {
super.onStop();
FirebaseUser currentUser=mAuth.getCurrentUser();
if(currentUser!=null) {
mDatabase.child(CurrentUser.getUid()).child("online").setValue(ServerValue.TIMESTAMP);
// mDatabase.child(CurrentUser.getUid()).child("LastSeen").setValue(ServerValue.TIMESTAMP);
}
} */
@Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main_menu,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.settings_btn) {
//Toast.makeText(getApplicationContext(),"entered", Toast.LENGTH_SHORT).show();
//startActivity(new Intent(MainActivity.this,Post_activity.class));
try {
Intent RegisterIntent = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(RegisterIntent);
}catch (Exception e){
e.printStackTrace();
}
}
if (item.getItemId() == R.id.users_btn) {
Intent UsersIntent = new Intent(MainActivity.this, UsersActivity.class);
startActivity(UsersIntent);
}
if (item.getItemId() == R.id.main_logout_btn) {
mAuth.signOut();
mDatabase.child(CurrentUser.getUid()).child("online").setValue(ServerValue.TIMESTAMP);
Intent loginIntent = new Intent(MainActivity.this, StartActivity.class);
// Toast.makeText(getApplicationContext(),"going to loginactivity", Toast.LENGTH_SHORT).show();
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(loginIntent);
finish();
}
return super.onOptionsItemSelected(item);
}
public void threadBro()
{
Runnable runnable = new Runnable() {
public void run() {
// Toast.makeText(getApplicationContext(),"thread is running ra", Toast.LENGTH_SHORT).show();
long endTime = System.currentTimeMillis()
+ 20*1000;
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
Log.d("thread","thread is executing");
wait(endTime -
System.currentTimeMillis());
} catch (Exception e) {}
}
}
}
};
Thread mythread = new Thread(runnable);
mythread.start();
}
@Override
protected void onResume(){
super.onResume();
Log.e("ajay1","wow1");
}
@Override
protected void onPause() {
super.onPause();
Log.e("ajay2","wow2");
FirebaseUser currentUser=mAuth.getCurrentUser();
if(currentUser!=null) {
mDatabase.child(CurrentUser.getUid()).child("online").setValue(ServerValue.TIMESTAMP);
// mDatabase.child(CurrentUser.getUid()).child("LastSeen").setValue(ServerValue.TIMESTAMP);
}
}
}
class Task implements Runnable{
public void run(){
for(int i=0;i<2;i++)
Log.d("thread1","thread is executing");
}
}
class MyAndroidThread implements Runnable
{
Activity activity;
public MyAndroidThread(Activity activity)
{
this.activity = activity;
}
@Override
public void run()
{
/*activity.runOnUiThread(new Runnable()
{
@Override
public void run()
{
}
});*/
long endTime = System.currentTimeMillis()
+ 5*1000;
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
Log.d("thread","thread is executing");
// Toast.makeText(activity,"thread is running in class with correct time", Toast.LENGTH_SHORT).show();
// Thread.sleep(endTime-System.currentTimeMillis());
wait(endTime -
System.currentTimeMillis());
// Toast.makeText(activity,"thread is running in class with correct time", Toast.LENGTH_SHORT).show();
} catch (Exception e) {}
}
}
}
}
<file_sep>package com.example.hp.firechat;
import android.app.NotificationManager;
import android.support.v4.app.NotificationCompat;
import com.google.firebase.messaging.RemoteMessage;
/**
* Created by hp on 11/19/2017.
*/
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService{
@Override
public void onMessageReceived(RemoteMessage remoteMessage){
super.onMessageReceived(remoteMessage);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(FirebaseMessagingService.this,"ajay");
mBuilder.setSmallIcon(R.mipmap.ic_launcher);
mBuilder.setContentTitle("My Friend Request");
mBuilder.setContentText("You have received a new request");
// Sets an ID for the notification
int mNotificationId = (int) System.currentTimeMillis();
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
}
<file_sep>package com.example.hp.firechat;
/**
* Created by hp on 11/23/2017.
*/
public class Messages {
private String message,seen,type,from;
private long time;
public Messages(){
}
public Messages(String message,String seen,long time,String type,String from){
this.message=message;
this.seen=seen;
this.time=time;
this.type=type;
}
public String getMessage() {
return message;
}
public void setMessage(String message){
this.message=message;
}
public String getSeen(){
return seen;
}
public void setSeen(String seen){
this.seen=seen;
}
public long getTime(){
return time;
}
public void setTime(long time){
this.time=time;
}
public String getType(){
return type;
}
public void setType(String type){
this.type=type;
}
public String getFrom(){
return from;
}
public void setFrom(String from){
this.from=from;
}
}
<file_sep>package com.example.hp.firechat;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.iid.FirebaseInstanceId;
public class LoginActivity extends AppCompatActivity {
private Toolbar mToolbar;
private EditText mLoginEmail;
private EditText mLoginPassword;
private Button mSignUpbtn;
private FirebaseAuth mAuth;
private ProgressDialog PD;
private DatabaseReference mDatabaseUsers;
private String current_user;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mToolbar=(Toolbar)findViewById(R.id.Login_toolbar);
mLoginEmail=(EditText)findViewById(R.id.emailField);
mLoginPassword=(EditText)findViewById(R.id.passwordField);
mSignUpbtn=(Button)findViewById(R.id.SignUpBtn);
PD = new ProgressDialog(LoginActivity.this);
mDatabaseUsers= FirebaseDatabase.getInstance().getReference().child("Users");
mAuth=FirebaseAuth.getInstance();
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Login");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mSignUpbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String email=mLoginEmail.getText().toString().trim();
String password=mLoginPassword.getText().toString().trim();
if(!TextUtils.isEmpty(email)&&(!TextUtils.isEmpty(password)))
{
PD.setMessage("Starting signing in");
PD.setCanceledOnTouchOutside(false);
PD.setIndeterminate(false);
PD.setCancelable(true);
PD.show();
mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
String deviceToken= FirebaseInstanceId.getInstance().getToken();
current_user=mAuth.getCurrentUser().getUid();
mDatabaseUsers.child(current_user).child("device_token").setValue(deviceToken).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Toast.makeText(getApplicationContext(),"LOGGIN", Toast.LENGTH_SHORT).show();
Intent mainIntent =new Intent(LoginActivity.this,MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
if(PD.isShowing()){
PD.dismiss();
}
}
});
}else{
Toast.makeText(getApplicationContext(),"ERROR LOGIN", Toast.LENGTH_SHORT).show();
if(PD.isShowing()){
PD.dismiss();
}
}
}
});
}
else{
Toast.makeText(getApplicationContext(),"PLEASE ENTER THE FIELDS", Toast.LENGTH_SHORT).show();
}
}
});
}
}
<file_sep>package com.example.hp.firechat;
/**
* Created by hp on 11/12/2017.
*/
public class Users {
public String name; //this should match with the database;
public String image;
public String status;
public String thumb_image;
public Users(){
}
public Users(String name,String image,String status,String thumb_image){
this.name=name;
this.image=image;
this.status=status;
this.thumb_image=thumb_image;
}
public String getThumb_image(){
return thumb_image;
}
public void setThumb_image(String thumb_image){
this.thumb_image=thumb_image;
}
public String getName() {return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String thumb_image){
this.image=thumb_image;
}
public String getStatus() {
return status;
}
public void setStatus(String status){
this.status=status;
}
}
<file_sep>package com.example.hp.firechat;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.android.gms.tasks.*;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Callback;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
/**
* A simple {@link Fragment} subclass.
*/
public class ChatsFragment extends Fragment {
private RecyclerView mFriendsList;
private DatabaseReference mFriendsDatabase;
public DatabaseReference mRootRef;
private FirebaseAuth mAuth;
private String mCurrentUser;
private View mMainView;
private DatabaseReference mUsersDatabase;
private String name;
private String status;
private String image;
private String onlineStatus;
private Query basedOnTime;
private int watch2,watch;
private int numSeen;
public ChatsFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mMainView= inflater.inflate(R.layout.fragment_chats, container, false);
mFriendsList=(RecyclerView) mMainView.findViewById(R.id.chats_list);
mAuth=FirebaseAuth.getInstance();
mCurrentUser=mAuth.getCurrentUser().getUid();
mFriendsDatabase= FirebaseDatabase.getInstance().getReference().child("Friends").child(mCurrentUser);
mRootRef=FirebaseDatabase.getInstance().getReference();
mFriendsDatabase.keepSynced(true);
mUsersDatabase=FirebaseDatabase.getInstance().getReference().child("Users");
mUsersDatabase.keepSynced(true);
mFriendsList.setHasFixedSize(true);
mFriendsList.setLayoutManager(new LinearLayoutManager(getContext()));
mRootRef.child("seenMsgs").keepSynced(true);
// basedOnTime=FirebaseDatabase.getInstance().getReference().child("Messages").child(mCurrentUser).orderByChild("time").startAt(System.currentTimeMillis()).endAt(System.currentTimeMillis()-86400000L);
// Toast.makeText(getContext(),"its working bro", Toast.LENGTH_SHORT).show();
// Inflate the layout for this fragment
return mMainView;
}
@Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<ChatsFrag,ChatsFragment.ChatsViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<ChatsFrag, ChatsFragment.ChatsViewHolder>(
ChatsFrag.class,
R.layout.users_single_layout,
ChatsFragment.ChatsViewHolder.class,
mFriendsDatabase
) {
@Override
protected void populateViewHolder(final ChatsFragment.ChatsViewHolder chatsViewHolder, ChatsFrag chatsFrag, int position) {
final String user_key = getRef(position).getKey();
// friendsViewHolder.setDate(friends.getDate());
mUsersDatabase.child(user_key).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
name=dataSnapshot.child("name").getValue().toString();
status=dataSnapshot.child("status").getValue().toString();
//image=dataSnapshot.child("thumb_image").getValue().toString();
image=dataSnapshot.child("image").getValue().toString();
if(dataSnapshot.hasChild("online")) {
onlineStatus = dataSnapshot.child("online").getValue().toString();
chatsViewHolder.setUserOnline(onlineStatus);
}
chatsViewHolder.setThings(getContext(),name,status,image);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
mRootRef.child("seenMsgs").child(mCurrentUser).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Toast.makeText(getContext(),"coming here to check", Toast.LENGTH_SHORT).show();
if(dataSnapshot.hasChild(user_key)){
String Seen=dataSnapshot.child(user_key).child("seen").getValue().toString();
numSeen=Integer.parseInt(Seen);
// Toast.makeText(getContext(),"okay1 "+numSeen, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
mRootRef.child("Messages").child(mCurrentUser).child(user_key).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot1) {
long k = dataSnapshot1.getChildrenCount();
// int watch=((int)k-numSeen);
watch2=(int)k;
watch=watch2-numSeen;
String watching=Integer.toString(watch);
mRootRef.child("seenMsgs").child(mCurrentUser).child(user_key).child("watch").setValue(watching).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull com.google.android.gms.tasks.Task<Void> task) {
Log.e("success","added successfully");
}
});
//Toast.makeText(getContext(),"okay2 "+watch, Toast.LENGTH_SHORT).show();
chatsViewHolder.seenSettings(watch);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
// friendsViewHolder.seenSettings(user_key);
chatsViewHolder.mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent Chat_Intent = new Intent(getContext(), GoodChatActivity.class);
Chat_Intent.putExtra("Blog_id",user_key);
Chat_Intent.putExtra("user_name",name);
// Toast.makeText(getContext(),"okay2 "+watch, Toast.LENGTH_SHORT).show();
String watching=Integer.toString(watch);
Chat_Intent.putExtra("watch",watching);
// StatusIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(Chat_Intent);
}
});
}
};
mFriendsList.setAdapter(firebaseRecyclerAdapter);
}
public static class ChatsViewHolder extends RecyclerView.ViewHolder{
View mView;
private CircleImageView mDisplayImage;
private TextView seenNumberView;
public TextView userStatusView;
public ChatsViewHolder(View itemView){
super(itemView);
mView=itemView;
mDisplayImage=(CircleImageView)mView.findViewById(R.id.user_single_image);
seenNumberView=(TextView)mView.findViewById(R.id.user_single_seen);
}
public void setDate(String date){
}
public void setThings(final Context ctx, String name, String status, final String image){
TextView userNameView=(TextView)mView.findViewById(R.id.user_single_name);
userStatusView=(TextView)mView.findViewById(R.id.user_single_status);
// Toast.makeText(ctx,"it came here", Toast.LENGTH_SHORT).show();
userStatusView.setText(status);
userNameView.setText(name);
if(!image.equals("default")) {
Picasso.with(ctx).load(image).networkPolicy(NetworkPolicy.OFFLINE).placeholder(R.mipmap.ic_account_circle_white_48dp).into(mDisplayImage, new Callback() {
@Override
public void onSuccess() {
}
@Override
public void onError() {
Picasso.with(ctx).load(image).placeholder(R.mipmap.ic_account_circle_white_48dp).into(mDisplayImage);
}
});
}
}
public void setUserOnline(String onlineIcon){
ImageView userOnlineView=(ImageView)mView.findViewById(R.id.online_Icon);
if(onlineIcon.equals("true")){
userOnlineView.setVisibility(View.VISIBLE);
}
else{
userOnlineView.setVisibility(View.INVISIBLE);
}
}
public void seenSettings(int watch) {
if(watch>0){
String watching =Integer.toString(watch);
seenNumberView.setText(watching);
seenNumberView.setVisibility(View.VISIBLE);
}
}
}
}
| a3fe78a82c9f6f38c31b8985bcd9c8f755bdcafa | [
"Java"
] | 11 | Java | AjayKannuri/FireChat | e5691407c234ccc660713033599631e54414e638 | 6eabc808cb5fcd5f476e704e145f4868737e0d17 | |
refs/heads/master | <file_sep>import React from 'react'
import css from '../../lib/css/'
import styles from './styles'
import Tabs from 'react-responsive-tabs'
export default ({
tabs = []
}) => {
const getTabs = () => tabs.map(tab => ({
...tab,
content: (
<div
className={css(styles.content)}
dangerouslySetInnerHTML={{
__html: tab.content
}}
/>
)
}))
return (
<div className={css(styles.tabs)}>
<Tabs items={getTabs()} />
</div>
)
}
<file_sep>import {
rhythm,
colors,
transitions,
fonts,
scale
} from '../../lib/traits'
export default {
base: {
display: 'block',
lineHeight: 1,
borderRadius: rhythm(0.2),
textAlign: 'center',
width: '100%',
backgroundColor: 'transparent',
fontFamily: fonts.display,
transition: `box-shadow ${transitions.easeOut}`
},
type: {
yellow: {
padding: `${rhythm(0.5)} ${rhythm(0.3)}`,
backgroundColor: colors.yellow,
color: colors.blue,
boxShadow: '0 0 1px transparent',
position: 'relative',
flex: '1',
transform: 'perspective(1px) translateZ(0)',
transitionProperty: 'color',
transitionDuration: '0.3s',
border: '3px solid #FFD800',
fontSize: scale(3),
'@media screen and (min-width:860px)': {
fontSize: scale(5)
},
':before': {
content: '""',
position: 'absolute',
zIndex: '-1',
top: '0',
bottom: '0',
left: '0',
right: '0',
backgroundColor: colors.blue,
transform: 'scaleX(0)',
transformOrigin: '50%',
transitionProperty: 'transform',
transitionDuration: '0.5s',
transitionTimingFunction: 'ease-out'
},
':hover': {
color: colors.yellow,
':before': {
transform: 'scaleX(1)'
}
}
},
nav: {
backgroundColor: 'transparent',
color: colors.yellow,
margin: `${rhythm(0.1)} 0`,
boxShadow: '0 0 1px transparent',
textShadow: '1px 2px #333',
position: 'relative',
transform: 'perspective(1px) translateZ(0)',
transitionProperty: 'color',
transitionDuration: '0.3s',
border: 'none',
padding: rhythm(0.1),
fontSize: scale(1.2),
textAlign: 'right',
'@media screen and (min-width:970px)': {
fontSize: scale(1.5),
maxWidth: '6.5rem',
textAlign: 'center',
backgroundColor: colors.yellow,
color: colors.grey,
textShadow: 'none',
border: '3px solid #FFD800',
margin: rhythm(0.2),
padding: `${rhythm(0.2)} ${rhythm(0.4)}`,
':hover': {
color: colors.yellow,
':before': {
transform: 'scaleX(1)'
}
}
},
':before': {
content: '""',
position: 'absolute',
zIndex: '-1',
top: '0',
bottom: '0',
left: '0',
right: '0',
backgroundColor: colors.grey,
transform: 'scaleX(0)',
transformOrigin: '50%',
transitionProperty: 'transform',
transitionDuration: '0.5s',
transitionTimingFunction: 'ease-out'
},
':hover': {
color: colors.light,
':before': {
transform: 'scaleX(1)'
}
}
},
select: {
boxShadow: '0 0 1px transparent',
position: 'relative',
transform: 'perspective(1px) translateZ(0)',
transitionProperty: 'color',
transitionDuration: '0.3s',
fontSize: scale(1.5),
maxWidth: '6.5rem',
textAlign: 'center',
backgroundColor: colors.yellow,
color: colors.blue,
textShadow: 'none',
border: '3px solid #FFD800',
margin: '0 auto',
padding: `${rhythm(0.2)} ${rhythm(0.4)}`,
':before': {
content: '""',
position: 'absolute',
zIndex: '-1',
top: '0',
bottom: '0',
left: '0',
right: '0',
backgroundColor: colors.blue,
transform: 'scaleX(0)',
transformOrigin: '50%',
transitionProperty: 'transform',
transitionDuration: '0.5s',
transitionTimingFunction: 'ease-out'
},
':hover': {
color: colors.yellow,
':before': {
transform: 'scaleX(1)'
}
}
},
readMore: {
border: '0',
color: colors.blue,
textAlign: 'left',
padding: `${rhythm(0.3)}`,
fontSize: scale(0.5)
},
modal: {
border: '0',
color: colors.light,
textAlign: 'center',
padding: `${rhythm(0.3)}`,
fontSize: scale(2),
fontWeight: '800'
}
}
}
<file_sep>import React from 'react'
import css from '../../lib/css/'
import styles from './styles'
export default ({
title = '',
footerLinks = [],
socialLinks = []
}) => (
<footer className={css(styles.base)}>
<div className={css(styles.wrapper)}>
<div>
<h2 className={css(styles.title)}>{title}</h2>
{footerLinks.map((link, i) => (
<div className={css(styles.footerLink)} key={i}><a target='_blank' href={link.link}>{link.label}</a></div>
))}
</div>
<div>
<ul className={css(styles.socialLinks)}>
{socialLinks.map((link, i) => (
<li key={i}><a className={css(styles.socialLink)} target='_blank' href={link.url}><i className={`fa fa-${link.network}`} /></a></li>
))}
</ul>
</div>
</div>
</footer>
)
<file_sep>import {
colors,
rhythm,
scale,
fonts
} from '../../lib/traits'
import bgImage from './bg.jpg'
export default {
wrapper: {
fontFamily: fonts.interface,
fontWeight: '300',
width: '100%',
backgroundColor: colors.blue,
backgroundImage: `url(${bgImage})`,
backgroundPosition: 'center',
backgroundRepeat: 'no-repeat',
backgroundSize: 'cover'
},
titleWrap: {
backgroundColor: colors.yellow
},
heading: {
position: 'relative',
fontFamily: fonts.display,
maxWidth: '70em',
width: '100%',
margin: '0 auto'
},
title: {
color: colors.light,
fontSize: scale(3),
fontWeight: '800',
padding: `${rhythm(1)} ${rhythm(0.5)}`,
textShadow: '1px 1px 1px #ae9300',
'@media screen and (min-width:1160px)': {
padding: `${rhythm(1)} 0`
}
},
textWrap: {
position: 'relative',
maxWidth: '70em',
width: '100%',
margin: '0 auto',
backgroundColor: 'transparent',
paddingTop: rhythm(1),
padding: `${rhythm(1)} ${rhythm(0.5)}`,
'@media screen and (min-width:1160px)': {
padding: `${rhythm(1)} 0`
}
},
text: {
padding: '1rem 0',
color: colors.light,
fontWeight: '300',
'p': {
paddingBottom: rhythm(1),
fontSize: scale(1)
},
'strong': {
fontWeight: '800',
fontSize: scale(2)
},
'@media screen and (min-width:860px)': {
display: 'flex'
}
}
}
<file_sep>import {
fonts
} from '../../lib/traits'
export default {
wrapper: {
fontFamily: fonts.display,
fontWeight: '300',
width: '100%',
overflowX: 'hidden'
},
slider: {
width: '100%',
paddingTop: '50px',
'.slick-track': {
display: 'flex'
}
},
banner: {
'img': {
width: '100%'
}
},
sliderHidden: {
display: 'none'
}
}
<file_sep>import React from 'react'
import { Route, IndexRoute } from 'react-router'
import Home from './Home'
import MCRI from './MCRI'
import GetInvolved from './GetInvolved'
import FAQs from './FAQs'
export default (
<Route
path='/'
component={({ children }) => children}>
<IndexRoute
component={Home}
/>
<Route
path='mcri'
component={MCRI}
/>
<Route
path='get-involved'
component={GetInvolved}
/>
<Route
path='faqs'
component={FAQs}
/>
</Route>
)
<file_sep>import {
rhythm,
colors,
fonts
} from '../../lib/traits'
export default {
wrapper: {
width: '100%',
fontFamily: fonts.display,
position: 'relative',
maxWidth: '70em',
padding: `${rhythm(1.5)} 0 ${rhythm(2)}`,
margin: 'auto',
color: colors.blue
},
widgets: {
'@media screen and (min-width:860px)': {
display: 'flex',
alignItems: 'center'
}
},
widget: {
flex: 1
},
svg: {
display: 'block',
margin: 'auto',
width: '100%'
},
raisedIcon: {},
label: {
textTransform: 'uppercase',
fontSize: '11px'
},
labelLarge: {
fontSize: '16px'
},
total: {
fontSize: '16px'
},
indicator: {
stroke: colors.yellow,
strokeWidth: 2,
strokeLinecap: 'round'
},
filledIndicator: {
stroke: colors.blue
}
}
<file_sep>import {
rhythm,
scale,
colors,
fonts
} from '../../lib/traits'
export default {
wrapper: {
width: '100%',
fontFamily: fonts.interface,
fontWeight: '300',
backgroundColor: colors.blue
},
titleWrap: {
backgroundColor: colors.yellow
},
heading: {
fontFamily: fonts.display,
position: 'relative',
maxWidth: '70em',
width: '100%',
margin: '0 auto'
},
title: {
color: colors.light,
fontSize: scale(3),
fontWeight: '800',
padding: `${rhythm(1)} ${rhythm(0.5)}`,
textShadow: '1px 1px 1px #ae9300',
'@media screen and (min-width:1160px)': {
padding: `${rhythm(1)} 0`
}
},
tiles: {
listStyle: 'none',
display: 'flex',
justifyContent: 'space-between',
padding: `${rhythm(0.5)} 0`,
flexDirection: 'column',
position: 'relative',
maxWidth: '70em',
margin: '0 auto',
'@media screen and (min-width:1160px)': {
flexDirection: 'row',
padding: `${rhythm(1.5)} 0`
}
},
tile: {
position: 'relative',
padding: rhythm(0.5),
display: 'flex',
alignItems: 'flex-end',
flexShrink: '1',
justifyContent: 'space-between',
alignContent: 'space-between',
boxSizing: 'border-box',
width: '100%'
},
link: {
position: 'relative',
display: 'block',
overflow: 'hidden',
width: '100%',
':after': {
content: '""',
position: 'absolute',
zIndex: '1',
top: '0',
bottom: '0',
left: '0',
right: '0',
backgroundColor: 'rgba(0, 0, 0, 0.1)',
transition: 'background-color 250ms linear'
},
'img': {
transform: scale(1.2),
width: '100%',
transition: 'transform 250ms linear'
},
':hover': {
':after': {
backgroundColor: 'rgba(0, 0, 0, 0.4)'
}
}
},
overlay: {
position: 'absolute',
background: 'transparent',
color: colors.light,
fontFamily: fonts.display,
fontWeight: '800',
textShadow: '1px 1px 1px #333',
left: rhythm(0.5),
width: '100%',
height: '100%',
bottom: '0',
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-end',
zIndex: '2',
transition: 'all 500ms cubic-bezier(0.65, 0.05, 0.36, 1) 0s',
':hover': {
bottom: '20%'
},
'h1': {
textTransform: 'uppercase',
fontSize: scale(4),
'@media screen and (min-width:590px)': {
fontSize: scale(5)
}
},
'p': {
fontSize: scale(2),
'@media screen and (min-width:590px)': {
fontSize: scale(3)
}
}
}
}
<file_sep>import {
rhythm,
scale,
colors,
fonts
} from '../../lib/traits'
export default {
wrapper: {
width: '100%',
fontFamily: fonts.display,
position: 'relative',
maxWidth: '70em',
margin: '0 auto',
overflowX: 'hidden'
},
tiles: {
listStyle: 'none',
display: 'flex',
justifyContent: 'space-between',
padding: `${rhythm(0.5)} 0`,
flexDirection: 'column',
'@media screen and (min-width:860px)': {
flexDirection: 'row',
padding: `${rhythm(1.5)} 0`
}
},
tile: {
position: 'relative',
padding: rhythm(0.5),
display: 'flex',
flex: '1',
boxSizing: 'border-box',
width: '100%'
},
link: {
display: 'block',
overflow: 'hidden',
width: '100%',
'h3': {
color: colors.blue,
textShadow: '1px 1px #0c7898',
fontSize: scale(4),
textAlign: 'center',
fontWeight: '800',
paddingTop: rhythm(1),
flexShrink: '0'
},
'p': {
textAlign: 'center',
flexShrink: '0',
paddingTop: rhythm(0.5),
marginBottom: 'auto',
alignSelf: 'baseline'
},
'img': {
position: 'relative',
display: 'inline-block',
verticalAlign: 'middle',
transform: 'perspective(1px) translateZ(0)',
boxShadow: '0 0 1px transparent'
},
'@keyframes pop': {
'50%': {
transform: 'scale(1.2)'
}
},
':hover': {
'img': {
animationName: 'pop',
animationDuration: '0.8s',
animationTimingFunction: 'linear',
animationIterationCount: '1'
},
':after': {
backgroundColor: 'rgba(0, 0, 0, 0.4)'
}
}
}
}
<file_sep>import React from 'react'
import prismicUtils from 'prismic-utils'
import { renderToStaticMarkup } from 'react-dom/server'
import styles from './styles'
import css from '../../../lib/css'
const htmlSerializer = (element, content) => {
if (element.type === 'hyperlink') {
return renderToStaticMarkup(
<a
href={element.url}
dangerouslySetInnerHTML={{
__html: content
}}
/>
)
}
if (element.type === 'paragraph') {
return renderToStaticMarkup(
<p
className={css(styles.paragraph)}
dangerouslySetInnerHTML={{
__html: content
}}
/>
)
}
if (element.type === 'heading1') {
return renderToStaticMarkup(
<h1
className={css(styles.heading1)}
dangerouslySetInnerHTML={{
__html: content
}}
/>
)
}
if (element.type === 'group-list-item') {
return renderToStaticMarkup(
<ul
className={css(styles.list)}
dangerouslySetInnerHTML={{
__html: content
}}
/>
)
}
if (element.type === 'group-o-list-item') {
return renderToStaticMarkup(
<ol
className={css(styles.list)}
dangerouslySetInnerHTML={{
__html: content
}}
/>
)
}
if (element.type === 'list-item' || element.type === 'o-list-item') {
return renderToStaticMarkup(
<li
className={css(styles.li)}
dangerouslySetInnerHTML={{
__html: content
}}
/>
)
}
return null
}
const deserializeResponse = (gub = {}) => {
const {
getText,
getGroup,
getStructuredText,
getNumber
} = prismicUtils(gub)
return {
offset: getNumber('home.raisedOffset'),
cta: {
tagline: getText('home.bannerTagline'),
register: getText('home.registerButton'),
donate: getText('home.donateButton')
},
register: {
tiles: getGroup('home.tiles')
.map((tile) => {
const prismic = prismicUtils(tile)
return {
heading: prismic.getText('heading'),
text: prismic.getText('text'),
image: prismic.getImage('image'),
link: prismic.getLink('link')
}
})
},
about: {
aboutTitle: getText('home.aboutTitle'),
aboutText: getStructuredText('home.aboutText', htmlSerializer)
},
stories: {
storiesTitle: getText('home.storiesTitle'),
storiesTiles: getGroup('home.storiesTiles')
.map((tile) => {
const prismic = prismicUtils(tile)
return {
image: prismic.getImage('image'),
title: prismic.getText('title'),
label: prismic.getText('modalLabel'),
text: prismic.getStructuredText('modalContent', htmlSerializer)
}
})
},
ambassadors: {
ambassadorsTitle: getText('home.ambassadorsTitle'),
ambassadorsTiles: getGroup('home.ambassadorsTiles')
.map((tile) => {
const prismic = prismicUtils(tile)
return {
image: prismic.getImage('image'),
title: prismic.getStructuredText('title', htmlSerializer)
}
})
},
sponsors: {
sponsorsTitle: getText('home.sponsorsTitle'),
sponsorsTiles: getGroup('home.sponsorsTiles')
.map((tile) => {
const prismic = prismicUtils(tile)
return {
image: prismic.getImage('image'),
title: prismic.getText('title')
}
})
}
}
}
const fetchHome = (home) => {
return {
...home,
status: 'fetching'
}
}
const receiveHomeFailure = (home, { error = '' }) => {
return {
...home,
error,
status: 'failed'
}
}
const receiveHomeSuccess = (home, { data }) => {
return {
...deserializeResponse(data),
status: 'fetched'
}
}
export default (home = {}, { type, payload }) => {
switch (type) {
case 'FETCH_HOME':
return fetchHome(home, payload)
case 'RECEIVE_HOME_FAILURE':
return receiveHomeFailure(home, payload)
case 'RECEIVE_HOME_SUCCESS':
return receiveHomeSuccess(home, payload)
default:
return home
}
}
<file_sep>import Prismic from 'prismic.io'
export const fetchFaqs = (dispatch) => () => {
dispatch({
type: 'FETCH_FAQS'
})
return Prismic.api('https://step-a-thon.cdn.prismic.io/api').then((Api) => (
Api.form('everything')
.ref(Api.master())
.query(Prismic.Predicates.at('document.type', 'faqs'))
.submit()
)).then((response) => (
response.results[0]
)).then((json) => {
dispatch(receiveFaqsSuccess(json))
}).catch((error) => {
dispatch(receiveFaqsFailure(error))
return Promise.reject(error)
})
}
const receiveFaqsFailure = (error) => (
{
type: 'RECEIVE_FAQS_FAILURE',
payload: {
error
}
}
)
const receiveFaqsSuccess = (data) => (
{
type: 'RECEIVE_FAQS_SUCCESS',
payload: {
data
}
}
)
<file_sep>import {
rhythm,
scale,
colors,
fonts
} from '../../lib/traits'
export default {
wrapper: {
width: '100%',
fontFamily: fonts.interface,
fontWeight: '300'
},
titleWrap: {
backgroundColor: colors.yellow
},
heading: {
fontFamily: fonts.display,
position: 'relative',
maxWidth: '70em',
width: '100%',
margin: '0 auto'
},
title: {
color: colors.light,
fontSize: scale(3),
fontWeight: '800',
padding: `${rhythm(1)} ${rhythm(0.5)}`,
textShadow: '1px 1px 1px #ae9300',
'@media screen and (min-width:1160px)': {
padding: `${rhythm(1)} 0`
}
},
tiles: {
listStyle: 'none',
display: 'flex',
justifyContent: 'space-between',
// padding: `${rhythm(0.5)} 0`,
// flexDirection: 'column',
position: 'relative',
maxWidth: '70em',
margin: '0 auto',
'@media screen and (min-width:860px)': {
flexDirection: 'row',
padding: `${rhythm(1.5)} 0`
}
},
tile: {
position: 'relative',
padding: rhythm(0.5),
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
alignContent: 'space-between',
boxSizing: 'border-box',
width: '100%'
},
link: {
flex: '1',
position: 'relative',
display: 'block',
'h3': {
background: 'transparent',
color: colors.dark,
fontSize: scale(0.5),
paddingBottom: rhythm(0.5)
},
'img': {
display: 'inline-block',
verticalAlign: 'middle',
flexShrink: '0',
width: '100%'
}
},
slider: {
padding: `${rhythm(0.5)} 0`,
flex: '1',
width: '100%',
'@media screen and (min-width:860px)': {
padding: `${rhythm(1)} 0`
},
'.slick-slider': {
width: '100% !important'
},
'.slick-track': {
width: '700% !important',
display: 'inline-flex',
'@media screen and (min-width:860px)': {
width: '100% !important'
}
},
'.slick-dots': {
display: 'flex !important',
justifyContent: 'center',
bottom: '10px'
}
}
}
<file_sep>import {
colors,
rhythm,
scale,
fonts
} from '../../lib/traits'
export default {
wrapper: {
fontFamily: fonts.interface,
fontWeight: '300',
width: '100%',
backgroundColor: colors.light,
overflowX: 'hidden'
},
titleWrap: {
backgroundColor: colors.yellow
},
heading: {
fontFamily: fonts.display,
position: 'relative',
maxWidth: '70em',
width: '100%',
margin: '0 auto'
},
title: {
color: colors.light,
fontSize: scale(3),
fontWeight: '800',
padding: `${rhythm(1)} ${rhythm(0.5)}`,
textShadow: '1px 1px 1px #ae9300',
'@media screen and (min-width:1160px)': {
padding: `${rhythm(1)} 0`
}
},
textWrap: {
position: 'relative',
maxWidth: '70em',
width: '100%',
margin: '0 auto',
paddingTop: rhythm(1),
padding: `${rhythm(1)} ${rhythm(0.5)}`,
'@media screen and (min-width:1160px)': {
padding: `${rhythm(1)} 0`
}
},
text: {
padding: '1rem 0',
color: colors.dark,
fontWeight: '300',
'p': {
paddingBottom: rhythm(1),
fontSize: scale(1)
},
'strong': {
fontWeight: '800',
fontSize: scale(2.5),
color: colors.blue
},
'a': {
color: colors.blue,
':hover': {
textDecoration: 'underline'
}
}
},
socialNetworks: {
display: 'flex',
marginBottom: rhythm(1),
listStyle: 'none',
fontSize: scale(2)
},
shareIcon: {
display: 'flex',
borderRadius: rhythm(0.2),
alignItems: 'center',
textAlign: 'center',
justifyContent: 'space-around',
padding: `${rhythm(0.5)} ${rhythm(1)}`,
marginRight: rhythm(0.5),
color: colors.light,
listStyleType: 'none',
'i': {
marginRight: rhythm(0.5)
}
},
facebookShare: {
backgroundColor: '#3B5998',
':hover': {
backgroundColor: '#5573B2'
}
},
twitterShare: {
backgroundColor: '#1DA1F2',
':hover': {
backgroundColor: '#50D4FF'
}
}
}
<file_sep>import React from 'react'
import { provideHooks } from 'redial'
import { connect } from 'react-redux'
import Helmet from 'react-helmet'
import GILayout from '../../layouts/GIPage'
import { fetchGetInvolved } from '../../store/actions/getInvolved'
import { fetchWrapper } from '../../store/actions/pageWrapper'
const isFetched = ({ status } = {}) => status === 'fetched'
const unlessFetched = (resource = {}, fetcher) => (
isFetched(resource)
? Promise.resolve()
: fetcher()
)
export const fetchGetInvolvedPageContent = ({
dispatch,
getInvolved = {},
wrapper = {}
}) => {
return Promise.all([
unlessFetched(getInvolved, () => fetchGetInvolved(dispatch)()),
unlessFetched(wrapper, () => fetchWrapper(dispatch)())
]).catch((err) => (
Promise.reject(err)
))
}
const hooks = {
fetch: ({
dispatch,
getInvolved,
wrapper
}) => (
fetchGetInvolvedPageContent({
dispatch,
getInvolved,
wrapper
})
)
}
const mapStateToProps = ({
getInvolved = {},
wrapper = {}
}) => ({
getInvolved,
wrapper
})
export default connect(
mapStateToProps
)(provideHooks(hooks)(
({
getInvolved = {},
wrapper = {},
location = {}
}) => {
const { hash } = location
const { meta = {
title: '',
meta: []
} } = wrapper
return (
<div>
<Helmet
title={meta.title}
meta={meta.tags}
/>
<GILayout
{...getInvolved}
{...wrapper}
currentHash={hash}
/>
</div>
)
})
)
<file_sep>import {
scale,
rhythm
} from '../../../lib/traits'
export default {
heading1: {
fontSize: scale(3),
textTransform: 'uppercase',
fontWeight: 'bold',
marginBottom: rhythm(0.5),
marginTop: rhythm(0.5)
},
paragraph: {
lineHeight: 'normal',
paddingBottom: rhythm(0.5)
},
list: {
paddingLeft: `${rhythm(1)}`
},
li: {
padding: `${rhythm(0.125)} 0`
}
}
<file_sep>import React from 'react'
import DocumentTitle from 'react-document-title'
import styles from './styles.css'
import './reset.css'
import Header from '../Header'
import Banner from '../Banner'
import Footer from '../Footer'
export default ({
title = 'Stepathon',
header = {},
banner = {},
footer = {},
children
}) => (
<DocumentTitle title={title}>
<article className={styles.base}>
<Header
{...header}
/>
<Banner
{...banner}
/>
{children}
<Footer
{...footer}
/>
</article>
</DocumentTitle>
)
<file_sep>import React from 'react'
import { provideHooks } from 'redial'
import { connect } from 'react-redux'
import MCRILayout from '../../layouts/MCRIPage'
import Helmet from 'react-helmet'
import { fetchMcri } from '../../store/actions/mcri'
import { fetchWrapper } from '../../store/actions/pageWrapper'
const isFetched = ({ status } = {}) => status === 'fetched'
const unlessFetched = (resource = {}, fetcher) => (
isFetched(resource)
? Promise.resolve()
: fetcher()
)
export const fetchMcriPageContent = ({
dispatch,
mcri = {},
wrapper = {}
}) => {
return Promise.all([
unlessFetched(mcri, () => fetchMcri(dispatch)()),
unlessFetched(wrapper, () => fetchWrapper(dispatch)())
]).catch((err) => (
Promise.reject(err)
))
}
const hooks = {
fetch: ({
dispatch,
mcri,
wrapper
}) => (
fetchMcriPageContent({
dispatch,
mcri,
wrapper
})
)
}
const mapStateToProps = ({
mcri = {},
wrapper = {}
}) => ({
mcri,
wrapper
})
export default connect(
mapStateToProps
)(provideHooks(hooks)(
({
mcri = {},
wrapper = {},
location = {}
}) => {
const { hash } = location
const { meta = {
title: '',
meta: []
} } = wrapper
return (
<div>
<Helmet
title={meta.title}
meta={meta.tags}
/>
<MCRILayout
{...mcri}
{...wrapper}
currentHash={hash}
/>
</div>
)
})
)
<file_sep>import React from 'react'
import css from '../../lib/css/'
import styles from './styles'
import Button from '../../components/Button'
export default ({
tagline = '',
register = ''
}) => (
<section className={css(styles.wrapper)}>
<div className={css(styles.ctaWrap)}>
<div className={css(styles.cta)}>
<h2 className={css(styles.title)}>{tagline}</h2>
<Button type='yellow' href='https://registration.everydayhero.com/ps/event/Stepathon2017'>{register}</Button>
</div>
</div>
</section>
)
<file_sep>import {
rhythm,
fonts,
scale,
colors
} from '../../lib/traits'
export default {
wrapper: {
fontFamily: fonts.interface,
fontWeight: '300',
width: '100%'
},
titleWrap: {
backgroundColor: colors.yellow
},
heading: {
fontFamily: fonts.display,
position: 'relative',
maxWidth: '70em',
width: '100%',
margin: '0 auto'
},
title: {
color: colors.light,
fontSize: scale(3),
fontWeight: '800',
padding: `${rhythm(1)} ${rhythm(0.5)}`,
textShadow: '1px 1px 1px #ae9300',
'@media screen and (min-width:1160px)': {
padding: `${rhythm(1)} 0`
}
},
tileWrap: {
width: '100%',
overflowX: 'scroll'
},
tiles: {
listStyle: 'none',
display: 'flex',
width: '700%',
padding: rhythm(0.5),
'@media screen and (min-width:860px)': {
padding: rhythm(1),
width: '150%'
}
}
}
<file_sep>import React from 'react'
import { provideHooks } from 'redial'
import { connect } from 'react-redux'
import { compose } from 'redux'
import Helmet from 'react-helmet'
import unlessFetched from '../../lib/unlessFetched'
import { fetchHome } from '../../store/actions/home'
import { fetchWrapper } from '../../store/actions/pageWrapper'
import { fetchCampaign } from '../../store/actions/campaign'
import { fetchLeaderboards } from '../../store/actions/leaderboards'
import { fetchIndividualSteps } from '../../store/actions/individualSteps'
import { fetchTeamSteps } from '../../store/actions/teamSteps'
import HomeLayout from '../../layouts/Home'
const hooks = {
fetch ({
dispatch,
state,
query
}) {
return Promise.all([
unlessFetched(state.home, () => fetchHome(dispatch)()),
unlessFetched(state.wrapper, () => fetchWrapper(dispatch)()),
dispatch(fetchCampaign(process.env.CAMPAIGN_UID)),
dispatch(fetchLeaderboards(process.env.CAMPAIGN_UID)),
dispatch(fetchIndividualSteps(process.env.CAMPAIGN_UID)),
dispatch(fetchTeamSteps(process.env.CAMPAIGN_UID))
]).catch((err) => (
Promise.reject(err)
))
}
}
const mapStateToProps = ({
home = {},
wrapper = {},
campaign = {},
leaderboards = {}
}) => ({
home,
wrapper,
campaign,
fundraisers: leaderboards.fundraisers,
teams: leaderboards.teams
})
const Home = ({
home = {},
wrapper = {},
campaign = {},
fundraisers = [],
teams = [],
location = {}
}) => {
const { hash } = location
const { meta = {
title: '',
meta: []
} } = wrapper
return (
<div>
<Helmet
title={meta.title}
meta={meta.tags}
link={[
{'rel': 'shortcut icon', 'href': 'https://www.mcri.edu.au/sites/default/files/favicon_0.ico'}
]}
/>
<HomeLayout
{...home}
{...wrapper}
campaign={campaign}
fundraisers={fundraisers}
teams={teams}
currentHash={hash}
/>
</div>
)
}
export default compose(
connect(mapStateToProps),
provideHooks(hooks)
)(Home)
<file_sep>import React from 'react'
import Main from '../Main'
import CTA from '../CTA'
import Register from '../Register'
import Progress from '../Progress'
import Leaderboards from '../Leaderboards'
import About from '../About'
import Stories from '../Stories'
import Ambassadors from '../Ambassadors'
import Sponsors from '../Sponsors'
export default ({
header = {},
banner = {},
about = {},
cta = {},
register = {},
campaign = {},
stories = {},
ambassadors = {},
sponsors = {},
footer = {},
fundraisers = [],
teams = [],
offset = 0,
currentHash = ''
}) => (
<Main
header={header}
banner={banner}
footer={footer}
>
<CTA
{...cta}
/>
<Register
{...register}
/>
<About
{...about}
/>
<Progress campaign={campaign} offset={offset} />
<Leaderboards
fundraisers={fundraisers}
teams={teams}
/>
<Stories
{...stories}
/>
<Ambassadors
{...ambassadors}
/>
<Sponsors
{...sponsors}
/>
</Main>
)
<file_sep>import React from 'react'
import css from '../../lib/css/'
import styles from './styles'
import Section from '../../components/Section'
export default ({
giTitle = '',
giIntro = '',
giContent = '',
currentHash
}) => {
const shareUrl = typeof window !== 'undefined' ? `${encodeURIComponent(`${window.location.origin}${window.location.pathname}`)}` : ''
return (
<Section id='getInvolved' currentHash={currentHash} className={css(styles.wrapper)}>
<div className={css(styles.titleWrap)}>
<div className={css(styles.heading)}>
<h2 className={css(styles.title)}>{giTitle}</h2>
</div>
</div>
<div className={css(styles.textWrap)}>
<div
className={css(styles.text)}
dangerouslySetInnerHTML={{
__html: giIntro
}}
/>
<ul className={css(styles.socialNetworks)}>
<li>
<a className={`${css(styles.facebookShare)} ${css(styles.shareIcon)}`} href={`https://www.facebook.com/sharer/sharer.php?u=${shareUrl}`} target='_blank'>
<i className='fa fa-facebook' aria-hidden='true' />
<p>Share</p>
</a>
</li>
<li>
<a className={`${css(styles.twitterShare)} ${css(styles.shareIcon)}`} href={`http://www.twitter.com/share?url=${shareUrl}`} target='_blank'>
<i className='fa fa-twitter' aria-hidden='true' />
<p>Share</p>
</a>
</li>
</ul>
<div
className={css(styles.text)}
dangerouslySetInnerHTML={{
__html: giContent
}}
/>
</div>
</Section>
)
}
<file_sep>import {
colors,
scale,
rhythm,
fonts
} from '../../lib/traits'
export default {
base: {
color: colors.light
},
content: {
color: colors.light,
lineHeight: '1.2em',
fontSize: scale(1)
},
tabs: {
'.Tab--selected': {
background: `${colors.yellow} !important`,
border: '0'
},
'.Tab': {
background: colors.blue,
fontFamily: fonts.display,
color: colors.light,
fontSize: scale(1.5),
border: `3px solid ${colors.yellow}`,
borderBottom: `1px solid ${colors.yellow}`,
padding: rhythm(0.5),
marginLeft: '0',
':nth-child(1)': {
border: `3px solid ${colors.yellow}`,
borderRadius: `${rhythm(0.2)} ${rhythm(0.2)} 0 0`,
'@media screen and (min-width:860px)': {
borderRight: '0',
borderRadius: `${rhythm(0.2)} 0 0 0`,
borderBottom: `1px solid ${colors.yellow}`
}
},
':nth-child(5)': {
borderLeft: `1px solid ${colors.yellow}`,
border: `3px solid ${colors.yellow}`,
borderRadius: '0',
'@media screen and (min-width:860px)': {
borderRadius: `0 ${rhythm(0.2)} 0 0`,
borderLeft: `1px solid ${colors.yellow}`,
borderBottom: `1px solid ${colors.yellow}`
}
}
},
'.Tab-panel': {
border: `3px solid ${colors.yellow}`,
borderRadius: '0',
background: colors.blue,
'@media screen and (min-width:860px)': {
borderRadius: `0 ${rhythm(0.2)} ${rhythm(0.2)} ${rhythm(0.2)}`
}
},
'.Tabs__show-more': {
background: colors.yellow,
color: colors.light,
border: '0'
},
'.Tabs__show-more-label--selected': {
background: colors.yellow,
border: '0',
height: '100%',
bottom: '0'
},
'strong': {
fontSize: scale(1.6)
},
'a': {
textDecoration: 'underline'
}
}
}
<file_sep>import React from 'react'
import { provideHooks } from 'redial'
import { connect } from 'react-redux'
import Helmet from 'react-helmet'
import FAQsLayout from '../../layouts/FAQsPage'
import { fetchFaqs } from '../../store/actions/faq'
import { fetchWrapper } from '../../store/actions/pageWrapper'
const isFetched = ({ status } = {}) => status === 'fetched'
const unlessFetched = (resource = {}, fetcher) => (
isFetched(resource)
? Promise.resolve()
: fetcher()
)
export const fetchFaqsPageContent = ({
dispatch,
faqs = {},
wrapper = {}
}) => {
return Promise.all([
unlessFetched(faqs, () => fetchFaqs(dispatch)()),
unlessFetched(wrapper, () => fetchWrapper(dispatch)())
]).catch((err) => (
Promise.reject(err)
))
}
const hooks = {
fetch: ({
dispatch,
faqs,
wrapper
}) => (
fetchFaqsPageContent({
dispatch,
faqs,
wrapper
})
)
}
const mapStateToProps = ({
faqs = {},
wrapper = {}
}) => ({
faqs,
wrapper
})
export default connect(
mapStateToProps
)(provideHooks(hooks)(
({
faqs = {},
wrapper = {},
location = {}
}) => {
const { hash } = location
const { meta = {
title: '',
meta: []
} } = wrapper
return (
<div>
<Helmet
title={meta.title}
meta={meta.tags}
/>
<FAQsLayout
{...faqs}
{...wrapper}
currentHash={hash}
/>
</div>
)
})
)
<file_sep>export const rhythm = (value = 1, unit = 'rem', basis = 1.5) => (
`${basis * value}${unit}`
)
export const scale = (exponent = 0, scale = 1.2) => (
`${Math.pow(scale, exponent)}rem`
)
export const radiuses = {
round: rhythm(100),
rounded: rhythm(0.125)
}
export const transitions = {
easeOut: 'ease-out .25s'
}
export const fonts = {
interface: 'Varela, Helvetica Neue, Helvetica, Arial, sans-serif',
display: 'Varela Round, sans-serif'
}
export const colors = {
dark: '#333',
grey: '#535353',
light: '#fff',
blue: '#009FCF',
darkBlue: '#0194c1',
lightBlue: '#00a6d9',
yellow: '#FFD800'
}
<file_sep>import prismicUtils from 'prismic-utils'
const deserializeResponse = (gub = {}) => {
const {
getText,
getImage,
getGroup,
getLink
} = prismicUtils(gub)
return {
meta: {
title: getText('wrapper.title'),
tags: [
getText('wrapper.metaDescription') && {'name': 'description', 'content': getText('wrapper.metaDescription')},
getText('wrapper.ogTitle') && {'property': 'og:title', 'content': getText('wrapper.ogTitle')},
getText('wrapper.ogDescription') && {'property': 'og:description', 'content': getText('wrapper.ogDescription')},
getImage('wrapper.ogImage') && {'property': 'og:image', 'content': getImage('wrapper.ogImage').url},
getLink('wrapper.ogUrl') && {'property': 'og:url', 'content': getLink('wrapper.ogUrl')}
].filter(tag => tag)
},
header: {
logo: getImage('wrapper.logo'),
logoLink: getLink('wrapper.logoLink'),
navLinks: getGroup('wrapper.navLinks')
.map((link) => {
const prismic = prismicUtils(link)
return {
label: prismic.getText('label'),
link: prismic.getText('link')
}
}),
banner: getImage('wrapper.bannerBackground'),
tagline: getText('wrapper.bannerTagline'),
register: getText('wrapper.registerButton'),
donate: getText('wrapper.donateButton')
},
banner: {
bannerSlider: getGroup('wrapper.bannerSlider')
.map((image) => {
const prismic = prismicUtils(image)
return {
image: prismic.getImage('image')
}
})
},
footer: {
title: getText('wrapper.footerTitle'),
footerLinks: getGroup('wrapper.footerLinks')
.map((link) => {
const prismic = prismicUtils(link)
return {
label: prismic.getText('label'),
link: prismic.getLink('link')
}
}),
socialLinks: getGroup('wrapper.socialLinks')
.map((link) => {
const prismic = prismicUtils(link)
return {
network: prismic.getText('network'),
url: prismic.getLink('link')
}
})
}
}
}
const fetchWrapper = (wrapper) => {
return {
...wrapper,
status: 'fetching'
}
}
const receiveWrapperFailure = (wrapper, { error = '' }) => {
return {
...wrapper,
error,
status: 'failed'
}
}
const receiveWrapperSuccess = (wrapper, { data }) => {
return {
...deserializeResponse(data),
status: 'fetched'
}
}
export default (wrapper = {}, { type, payload }) => {
switch (type) {
case 'FETCH_WRAPPER':
return fetchWrapper(wrapper, payload)
case 'RECEIVE_WRAPPER_FAILURE':
return receiveWrapperFailure(wrapper, payload)
case 'RECEIVE_WRAPPER_SUCCESS':
return receiveWrapperSuccess(wrapper, payload)
default:
return wrapper
}
}
<file_sep>import flatten from 'lodash/flatten'
import deserializePages from '../../../lib/deserializePages'
const fetchSteps = (steps) => {
return {
...steps,
...{ status: 'fetching' }
}
}
const receiveStepsFailure = (steps, { error = '' }) => {
return {
...steps,
...{ error, status: 'failed' }
}
}
const receiveStepsSuccess = (steps, { data }) => {
return {
steps: deserializePages(flatten(data)),
status: 'fetched'
}
}
export default (steps = {}, { type, payload }) => {
switch (type) {
case 'FETCH_INDIVIDUAL_STEPS':
return fetchSteps(steps, payload)
case 'FETCH_INDIVIDUAL_STEPS_FAILURE':
return receiveStepsFailure(steps, payload)
case 'FETCH_INDIVIDUAL_STEPS_SUCCESS':
return receiveStepsSuccess(steps, payload)
default:
return steps
}
}
<file_sep>import React from 'react'
import { Link } from 'react-router'
import css from '../../lib/css'
import styles from './styles.js'
export default ({
type = '',
style = {},
to = '',
href = '',
children = '',
...props
}) => {
if (href) {
return <a {...{...props, href}} className={`${css(style, styles.base, styles.type[type])}`}>{children}</a>
} else if (to) {
return <Link {...props} to={to} className={`${css(style, styles.base, styles.type[type])}`}>{children}</Link>
} else {
return <button {...props} to={to} className={`${css(style, styles.base, styles.type[type])}`}>{children}</button>
}
}
<file_sep>import React from 'react'
import css from '../../lib/css/'
import styles from './styles'
import Section from '../../components/Section'
import Leaderboard from '../../components/Leaderboard'
export default ({
fundraisers = [],
teams = [],
currentHash
}) => {
return (
<Section id='about' currentHash={currentHash} className={css(styles.wrapper)}>
<div className={css(styles.titleWrap)}>
<div className={css(styles.heading)}>
<h2 className={css(styles.title)}>Leaderboards</h2>
</div>
</div>
<div className={css(styles.textWrap)}>
<div className={css(styles.text)}>
<Leaderboard title='Top individuals' type='fundraisers' leaders={fundraisers} />
<Leaderboard title='Top Teams' type='teams' leaders={teams} />
</div>
</div>
</Section>
)
}
<file_sep>import React from 'react'
import prismicUtils from 'prismic-utils'
import { renderToStaticMarkup } from 'react-dom/server'
import styles from '../home/styles'
import css from '../../../lib/css'
const htmlSerializer = (element, content) => {
if (element.type === 'hyperlink') {
return renderToStaticMarkup(
<a
href={element.url}
dangerouslySetInnerHTML={{
__html: content
}}
/>
)
}
if (element.type === 'paragraph') {
return renderToStaticMarkup(
<p
className={css(styles.paragraph)}
dangerouslySetInnerHTML={{
__html: content
}}
/>
)
}
if (element.type === 'heading1') {
return renderToStaticMarkup(
<h1
className={css(styles.heading1)}
dangerouslySetInnerHTML={{
__html: content
}}
/>
)
}
if (element.type === 'group-list-item') {
return renderToStaticMarkup(
<ul
className={css(styles.list)}
dangerouslySetInnerHTML={{
__html: content
}}
/>
)
}
if (element.type === 'group-o-list-item') {
return renderToStaticMarkup(
<ol
className={css(styles.list)}
dangerouslySetInnerHTML={{
__html: content
}}
/>
)
}
if (element.type === 'list-item' || element.type === 'o-list-item') {
return renderToStaticMarkup(
<li
className={css(styles.li)}
dangerouslySetInnerHTML={{
__html: content
}}
/>
)
}
return null
}
const deserializeResponse = (gub = {}) => {
const {
getText,
getStructuredText
} = prismicUtils(gub)
return {
getInvolved: {
giTitle: getText('get-involved.giTitle'),
giIntro: getStructuredText('get-involved.giIntro', htmlSerializer),
giContent: getStructuredText('get-involved.giContent', htmlSerializer)
}
}
}
const fetchGetInvolved = (getInvolved) => {
return {
...getInvolved,
status: 'fetching'
}
}
const receiveGetInvolvedFailure = (getInvolved, { error = '' }) => {
return {
...getInvolved,
error,
status: 'failed'
}
}
const receiveGetInvolvedSuccess = (getInvolved, { data }) => {
return {
...getInvolved,
...deserializeResponse(data),
status: 'fetched'
}
}
export default (getInvolved = {}, { type, payload }) => {
switch (type) {
case 'FETCH_GET_INVOLVED':
return fetchGetInvolved(getInvolved, payload)
case 'RECEIVE_GET_INVOLVED_FAILURE':
return receiveGetInvolvedFailure(getInvolved, payload)
case 'RECEIVE_GET_INVOLVED_SUCCESS':
return receiveGetInvolvedSuccess(getInvolved, payload)
default:
return getInvolved
}
}
<file_sep>import Prismic from 'prismic.io'
export const fetchMcri = (dispatch) => () => {
dispatch({
type: 'FETCH_MCRI'
})
return Prismic.api('https://step-a-thon.cdn.prismic.io/api').then((Api) => (
Api.form('everything')
.ref(Api.master())
.query(Prismic.Predicates.at('document.type', 'mcri'))
.submit()
)).then((response) => (
response.results[0]
)).then((json) => {
dispatch(receiveMcriSuccess(json))
}).catch((error) => {
dispatch(receiveMcriFailure(error))
return Promise.reject(error)
})
}
const receiveMcriFailure = (error) => (
{
type: 'RECEIVE_MCRI_FAILURE',
payload: {
error
}
}
)
const receiveMcriSuccess = (data) => (
{
type: 'RECEIVE_MCRI_SUCCESS',
payload: {
data
}
}
)
<file_sep>import Prismic from 'prismic.io'
export const fetchPages = (dispatch) => (pageType) => {
dispatch({
type: 'FETCH_PAGES'
})
return Prismic.api('https://step-a-thon.cdn.prismic.io/api').then((Api) => (
Api.form('everything')
.ref(Api.master())
.query(Prismic.Predicates.at('document.type', pageType))
.submit()
)).then((response) => (
response.results[0]
)).then((json) => {
dispatch(receivePagesSuccess(pageType, json))
}).catch((error) => {
dispatch(receivePagesFailure(pageType, error))
return Promise.reject(error)
})
}
const receivePagesFailure = (error) => (
{
type: 'RECEIVE_PAGES_FAILURE',
payload: {
error
}
}
)
const receivePagesSuccess = (pageType, data) => (
{
type: 'RECEIVE_PAGES_SUCCESS',
payload: {
pageType,
data
}
}
)
<file_sep>import axios from 'axios'
export const fetchLeaderboards = (uid) => (dispatch) => {
dispatch({
type: 'FETCH_LEADERBOARDS'
})
return Promise.all([
axios.get(`${process.env.SUPPORTER_URL}/api/v2/search/pages_totals`, { params: {
campaign_id: uid,
group_by: 'individuals',
limit: 10,
page: 1
}}).then((res) => res.data.results),
axios.get(`${process.env.SUPPORTER_URL}/api/v2/search/pages_totals`, { params: {
campaign_id: uid,
group_by: 'teams',
limit: 10,
page: 1
}}).then((res) => res.data.results)
]).then((res) => {
dispatch(receiveLeaderboardsSuccess(res))
}).catch((error) => {
dispatch(receiveLeaderboardsFailure(error))
return Promise.reject(error)
})
}
const receiveLeaderboardsFailure = (error) => ({
type: 'RECEIVE_LEADERBOARDS_FAILURE',
payload: {
error
}
})
const receiveLeaderboardsSuccess = (data) => {
return {
type: 'RECEIVE_LEADERBOARDS_SUCCESS',
payload: {
data
}
}
}
<file_sep>import React from 'react'
import css from '../../lib/css/'
import styles from './styles'
import Section from '../../components/Section'
export default ({
aboutTitle = '',
aboutText = '',
currentHash
}) => (
<Section id='about' currentHash={currentHash} className={css(styles.wrapper)}>
<div className={css(styles.titleWrap)}>
<div className={css(styles.heading)}>
<h2 className={css(styles.title)}>{aboutTitle}</h2>
</div>
</div>
<div className={css(styles.textWrap)}>
<div
className={css(styles.text)}
dangerouslySetInnerHTML={{
__html: aboutText
}}
/>
</div>
</Section>
)
<file_sep>import {
fonts,
colors,
scale,
rhythm
} from '../../lib/traits'
export default {
wrapper: {
background: colors.gradient,
fontFamily: fonts.interface,
fontWeight: '300',
width: '100%'
},
ctaWrap: {
backgroundColor: colors.blue,
width: '100%',
position: 'relative',
padding: rhythm(1),
display: 'flex',
justifyContent: 'center',
'@media screen and (min-width:660px)': {
flexDirection: 'row'
}
},
cta: {
maxWidth: '1140px',
color: colors.yellow,
fontFamily: fonts.interface,
fontWeight: '800',
fontSize: scale(2),
textAlign: 'left',
lineHeight: '1.3',
display: 'flex',
flex: '1',
flexDirection: 'column',
'@media screen and (min-width:660px)': {
flexDirection: 'row'
},
'@media screen and (min-width:960px)': {
minWidth: '42rem',
fontSize: scale(4)
},
'> *': {
alignSelf: 'center',
padding: rhythm(1)
}
},
title: {
fontFamily: fonts.display,
textShadow: '2px 3px #0c7898',
minWidth: '0',
flex: '1',
padding: `0 0 ${rhythm(1)} 0`,
'@media screen and (min-width:660px)': {
padding: `0 ${rhythm(1)}`
},
'@media screen and (min-width:960px)': {
minWidth: '42rem',
padding: `0 ${rhythm(1)}`
}
}
}
<file_sep>import {
rhythm,
colors,
scale,
fonts,
transitions
} from '../../lib/traits'
export default {
tile: {
flex: '1',
padding: `${rhythm(1)} ${rhythm(0.5)}`
},
container: {
boxSizing: 'border-box',
overflow: 'hidden',
boxShadow: '0 0 10px rgba(0,0,0,.3)'
},
tileTitle: {
fontFamily: fonts.display,
fontSize: scale(1.5),
fontWeight: '700',
color: colors.blue,
margin: `${rhythm(0.3)}`
},
textWrap: {
overflow: 'hidden',
maxHeight: '9em',
lineHeight: '1.4em',
position: 'relative',
':after': {
content: '""',
position: 'absolute',
bottom: '0',
right: '0',
width: '70%',
height: '1.4em',
textAlign: 'left',
background: 'linear-gradient(to right, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1) 50%)'
}
},
excerpt: {
color: colors.dark,
margin: `${rhythm(0.3)}`
},
image: {
width: '100%',
minWidth: '16rem',
height: rhythm(7.5),
backgroundSize: 'cover',
backgroundPosition: 'top center',
display: 'block',
flex: '1',
marginRight: rhythm(1),
'@media screen and (min-width:860px)': {
minWidth: '20rem'
}
},
modal: {
},
modalWrapper: {
background: colors.light,
width: '80% !important',
maxWidth: '80em',
position: 'absolute',
color: colors.dark,
margin: '2% auto !important',
fontFamily: fonts.interface,
padding: '0 !important',
'h2': {
fontFamily: fonts.display,
color: colors.blue,
fontSize: scale(2),
paddingBottom: rhythm(1)
},
'h3': {
fontSize: scale(1),
padding: `${rhythm(0.5)} ${rhythm(0)}`
},
'strong': {
fontWeight: '700'
},
'em': {
fontStyle: 'italic'
},
'a': {
color: colors.blue,
transition: `box-shadow ${transitions.easeOut}`
},
'img': {
width: '100%'
}
},
modalContainer: {
overflow: 'auto',
boxSizing: 'border-box',
padding: rhythm(1)
},
closeStyle: {
margin: '1rem',
fontSize: `${scale(2)} !important`,
float: 'right',
cursor: 'pointer',
fontFamily: fonts.display,
color: colors.blue,
border: 'none !important'
}
}
<file_sep>import React from 'react'
import css from '../../lib/css/'
import styles from './styles'
export default ({
ambassadorsTitle = '',
ambassadorsTiles = []
}) => (
<div className={css(styles.wrapper)}>
<div className={css(styles.titleWrap)}>
<div className={css(styles.heading)}>
<h2 className={css(styles.title)}>{ambassadorsTitle}</h2>
</div>
</div>
<ul className={css(styles.tiles)}>
{ambassadorsTiles.map((tile, i) => (
<li className={css(styles.tile)} key={i}>
<div className={css(styles.link)}>
<div
className={css(styles.overlay)}
dangerouslySetInnerHTML={{
__html: tile.title
}}
/>
<img src={tile.image.url} />
</div>
</li>
))}
</ul>
</div>
)
<file_sep>import React from 'react'
import css from '../../lib/css/'
import styles from './styles'
import Slider from 'react-slick'
const sliderSettings = {
dots: false,
arrows: false,
infinite: true,
draggable: false,
slidesToShow: 1,
slidesToScroll: 1,
autoplay: true,
autoplaySpeed: 5000
}
export default class extends React.Component {
constructor (props) {
super(props)
this.state = {
sliderLoaded: false
}
}
componentDidMount () {
this.setState({
sliderLoaded: true
})
}
render () {
const {
bannerSlider = []
} = this.props
return (
<div className={this.state.sliderLoaded ? null : css(styles.sliderHidden)}>
<div className={css(styles.wrapper)}>
<Slider {...sliderSettings} className={css(styles.slider)}>
{bannerSlider.map((image, i) => (
<div className={css(styles.banner)} key={i}><img src={image.image.url} /></div>
))}
</Slider>
</div>
</div>
)
}
}
<file_sep>const defaultConfig = require('boiler-room-builder/config/webpack.shared.config')
const DotenvPlugin = require('webpack-dotenv-plugin')
const { assign } = Object
module.exports = assign({}, defaultConfig, {
plugins: [
new DotenvPlugin({
sample: './.env.sample',
path: `./${process.env.ENV_FILE}`
})
],
entry: ['babel-polyfill']
})
| e8ca363925067657596733954f4ea737d5ac29ce | [
"JavaScript"
] | 39 | JavaScript | everydayhero/step-a-thon | 1869d8ab3e062c9348538a82f08201eadd8f321e | 32ebe563ff6836e427b8293a7635ae056892d92c | |
refs/heads/master | <file_sep>/*
* Author: <NAME>
* Date: 12/14/2020
* Period: 7
*
* About: Represents a 3-Dimensional Cube object
*/
// Two imports - Scanner and Math Class from the Java Standard library
import java.util.Scanner;
import java.lang.Math;
// Class that represents a Cube object
public class Cube {
// Field declarations for the Cube class
// Used the private access modifier for the fields
private final int vertices, edges, faces;
private int side, dim;
// Cube object constructor with 1 parameter - A coordinates int array
public Cube(int sideLength) {
vertices = 8;
edges = 12;
faces = 6;
dim = 3;
side = sideLength;
}
// A method that gets the number of vertices the cube has
public int getVertices() {
return vertices;
}
// A method that gets the number of edges the cube has
public int getEdges() {
return edges;
}
// A method that gets the number of faces the cube has
public int getFaces() {
return faces;
}
// A method that calculates the volume of the cube s^3
public int findVolume() {
return (int) (Math.pow(side, 3));
}
// A method that calculates the surfaceArea of the cube 6s^2
public int surfaceArea() {
// Cast to int to make sure that the result is an integer
return (int) (6 * Math.pow(side, 2));
}
// A method that calculates the dot product of two vectors a and b
public float dot(float[] a, float[] b) {
// iterator i and product
int i; float product = 0;
for(i = 0; i < dim; i++) {
product += (float) (a[i] * b[i]);
}
return product;
}
// A method that rotates the cube across the three axes - X, Y, and Z
// phi is just a greek letter that denotes the angle measure for the rotation
public float[] rotate(float phi, char axis) {
// Here, we are converting the phi angle from degrees to radians
// pi/180 = rad/deg => deg * pi = rad * 180 => rad = (deg * pi)/180
// Cast to float in order to keep its decimal value
phi = (float) ((phi * Math.PI)/180);
// Each of the vectors instantiated below have three dimensions, which means a three tuple of coordinates
float[] cubeVector = new float[]{side, side, side};
float[] resVector = new float[]{0, 0, 0};
float[] r1, r2, r3;
// Decision making between three types of rotations, using if else if else statements in succession
switch(axis) {
case 'X':
case 'x':
// Basically the three rows of the 3D rotation matrix,
// Splitted in order to make sure that the dot(a, b) function works
r1 = new float[]{1, 0, 0};
r2 = new float[]{0, (float) Math.cos(phi), (float) -Math.sin(phi)};
r3 = new float[]{0, (float) Math.sin(phi), (float) Math.cos(phi)};
resVector[0] += dot(r1, cubeVector);
resVector[1] += dot(r2, cubeVector);
resVector[2] += dot(r3, cubeVector);
break;
case 'Y':
case 'y':
r1 = new float[]{(float) Math.cos(phi), 0, (float) Math.sin(phi)};
r2 = new float[]{0, 1, 0};
r3 = new float[]{(float) -Math.sin(phi), 0, (float) Math.cos(phi)};
resVector[0] += dot(r1, cubeVector);
resVector[1] += dot(r2, cubeVector);
resVector[2] += dot(r3, cubeVector);
break;
case 'Z':
case 'z':
r1 = new float[]{(float) Math.cos(phi), (float) -Math.sin(phi), 0};
r2 = new float[]{(float) Math.sin(phi), (float) Math.cos(phi), 0};
r3 = new float[]{0, 0, 1};
resVector[0] += dot(r1, cubeVector);
resVector[1] += dot(r2, cubeVector);
resVector[2] += dot(r3, cubeVector);
break;
default:
System.err.println("** Error: Invalid Axis of Rotation");
System.exit(0);
break;
}
return resVector;
}
public static void main(String[] args) {
// Instantiate the cube with one parameter - sideLength
// Cube(int sideLength) with sideLength = 6 units
Scanner sc = new Scanner(System.in);
System.out.print("The side length of your cube: ");
Cube mySpecial3DCube = new Cube(sc.nextInt());
System.out.println("\n*** Fun facts ***\n");
System.out.println("Your cube has: " + mySpecial3DCube.getFaces() + " faces");
System.out.println("Your cube has: " + mySpecial3DCube.getVertices() + " vertices");
System.out.println("Your cube has: " + mySpecial3DCube.getEdges() + " sides\n");
System.out.println("\n*** Geometry Time! ***\n");
System.out.println("Your cube has a volume of: " + mySpecial3DCube.findVolume() + " units^3");
System.out.println("Your cube has a surface area of: " + mySpecial3DCube.surfaceArea() + " units^2\n");
System.out.print("Fun, isn't it? Enter a sample rotation angle (in degrees): ");
int angle = sc.nextInt();
System.out.print("Rotation axis (X, Y, Z): ");
char axis = sc.next().charAt(0);
float[] vector = mySpecial3DCube.rotate(angle, axis);
System.out.println("The cube's new diagonal vector is: ");
for(int i = 0; i < vector.length; i++) {
System.out.println("[" + vector[i] + "]");
}
}
}
<file_sep># Java-Programs
A nearly complete collection of the commonly used mathematical operations coded using objects and calcs, including the Java principle of inheritance and interface
## Includes
Maximizing revenue, Solving Quadratic Equations, Algebra Calculator, Logarithms, Temperature Converter, Factorial, Infinite Limits and many others<file_sep>import java.util.Scanner;
public class ArithmeticCalculator {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated Method stub
int i;
double sum = 0;
System.out.println("Total number of numbers: ");
int n = sc.nextInt();
int a[] = new int [n];
System.out.println("Enter the " + n + " numbers");
for(i = 0; i < n; i++)
{
a[i] = sc.nextInt();
sum = sum + a[i];
}
System.out.println("Mean or Median: ");
double oddmedian = a[((n+1)/2)];
double evenmedian = a[((n/2)+(n/2)+1)/2];
String operation = sc.next();
if(operation.equals("Mean"))
{
double mean = sum/n;
System.out.println(mean);
}
else if(operation.equals("Median"))
{
if(n%2 == 0)
{
System.out.println("The median is "+ evenmedian);
}
else
{
System.out.println("The median is "+ oddmedian);
}
}
sc.close();
}
}
<file_sep>import java.util.Scanner;
public class Calculator{
static Double add(Double a, Double b){
Double res = a + b;
return res;
}
static Double subtract(Double a, Double b){
Double res = a - b;
return res;
}
static Double multiply(Double a, Double b){
Double res = a * b;
return res;
}
static Double divide(Double a, Double b){
Double res = a / b;
return res;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Number 1:");
Double a = sc.nextDouble();
System.out.println("Number 2:");
Double b = sc.nextDouble();
System.out.println("add, subtract, multiply, or divide: ");
String op = sc.next();
if(op.equals("add")){
System.out.println(add(a,b));
}
else if(op.equals("subtract")){
System.out.println(subtract(a,b));
}
else if(op.equals("multiply")){
System.out.println(multiply(a,b));
}
else if(op.equals("divide")){
System.out.println(divide(a,b));
}
sc.close();
}
}
<file_sep>import java.util.Scanner;
public class MaximizingThings {
static Scanner sc = new Scanner(System.in);
static double a,b,c,x1,x2,y;
static String result;
public void getInput()
{
System.out.println("In order to maximize the revenue you need to find the x-intercepts");
System.out.println("Enter the coefficients a,b,c of the quadratic equation");
System.out.println("Enter a");
a = sc.nextDouble();
System.out.println("Enter b");
b = sc.nextDouble();
System.out.println("Enter c");
c = sc.nextDouble();
result = a+"x2+"+b+"x+"+c;
System.out.println("The quadratic formula is "+ result);
}
public void QuadraticFormula()
{
x1 = ((-b+Math.sqrt(Math.pow(b, 2)-4*a*c))/2*a);
x2 = ((-b-Math.sqrt(Math.pow(b, 2)-4*a*c))/2*a);
System.out.println("The roots of the quadratic equation are "+ x1 +" and "+x2);
}
public void OptimalYValue()
{
System.out.println(a*Math.pow(((x1+x2)/2),2)+b*((x1+x2)/2)+c + " is the optimal y value for revenue");
}
public static void main(String[] args) {
// TODO Auto-generated Method stub
MaximizingThings calc = new MaximizingThings();
try
{
Thread.sleep(250);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
System.out.println("*** Program to Maximize Revenue ***");
calc.getInput();
calc.QuadraticFormula();
System.out.println((x1+x2)/2 + " is the optimal x value for revenue");
calc.OptimalYValue();
}
}
<file_sep>import java.util.Scanner;
public class FactorialCalculator {
static Scanner sc = new Scanner(System.in);
static int num;
static int fact(int n) //Recursive function
{
if(n <= 1)
{
return 1;
}
else
{
return n * fact(n-1);
}
}
public static void main(String[] args) {
// TODO Auto-generated Method stub
FactorialCalculator calc = new FactorialCalculator();
System.out.println("Number: ");
int n = sc.nextInt();
System.out.println("The factorial is "+ fact(n));
}
}
| c3934b0b900b449ef4ada53a353f90a502b5645e | [
"Markdown",
"Java"
] | 6 | Java | MahanthMohan/Java-Programs | b0816a2f63ccee659115e9deb53c5bb67c2c1324 | cbd8bcbd3089b9003c2b3784ddacceeea75dc7e2 | |
refs/heads/master | <repo_name>ikles/konfor<file_sep>/js/common.js
jQuery(function() {
jQuery('.mini-cart .titlecart').html('Корзина');
jQuery('.productdetails-view.productdetails .vm-price-value').prepend(jQuery('.box-container2 .availability.out-of-stock'));
jQuery('.productdetails-view .vina-des-wrapper .price-box .vm-price-value .PricesalesPrice').after(jQuery('.box-container2 .product-rating'));
jQuery('.product-field-display').parent().addClass('mla');
}); | 2e025ab104e9cedd95295ba8f5e2da33f8117e23 | [
"JavaScript"
] | 1 | JavaScript | ikles/konfor | 353e7fe806dcbcb537034a1b8408fb951dabf005 | 4184a10170df9ea7e209d365282b187ddfbbd913 | |
refs/heads/master | <file_sep>/*angular.module("myApp", [])
.controller("myFirstController",['$scope', function ($scope){
console.log("This is form controller");
$scope.hello="hello world";
}]);*/
angular.module("myApp").controller("myFirstController", function ($scope)
{
let Student= {
FirstName: "<NAME>",
LastName : "Chanda",
StudentId : "<EMAIL>"
}
$scope.Student=Student;
});
let mycontroller=function($scope){
$scope.message="Hello World";
} | d1e6ec58488872594a0e1de3332e6f443fbd0f46 | [
"JavaScript"
] | 1 | JavaScript | bhagyasree2895/angular_sample_app | 987e8259b58af2cf3fa544e775135513b7736d7e | 7eec98a05673c7b82241f164a7beaf55ff8d7822 | |
refs/heads/master | <file_sep>from django.shortcuts import render
from . import models
from django.db.models import Q
from django.core.paginator import Paginator
# Create your views here.
app_name='blog'
PAGS = 1
def index(request):
queryset = request.GET.get('buscar')
publicaciones = models.Publicacion.objects.filter(estado=True)
if queryset:
publicaciones = models.Publicacion.objects.filter(Q(titulo__icontains = queryset) | Q(descripcion__icontains = queryset), estado=True).distinct()
paginator = Paginator(publicaciones, PAGS)
page = request.GET.get('page')
publicaciones = paginator.get_page(page)
context = {'publicaciones':publicaciones}
return render(request, 'index.html', context)
def generales(request):
queryset = request.GET.get('buscar')
publicaciones = models.Publicacion.objects.filter(estado=True, categoria=models.Categoria.objects.get(nombre__iexact='general'))
if queryset:
publicaciones = models.Publicacion.objects.filter(
Q(titulo__icontains = queryset) |
Q(descripcion__icontains = queryset),
estado=True,
categoria=models.Categoria.objects.get(nombre__iexact='general')
).distinct()
paginator = Paginator(publicaciones, PAGS)
page = request.GET.get('page')
publicaciones = paginator.get_page(page)
context = {'publicaciones':publicaciones}
return render(request, 'generales.html', context)
def programacion(request):
queryset = request.GET.get('buscar')
publicaciones = models.Publicacion.objects.filter(estado=True, categoria=models.Categoria.objects.get(nombre__iexact='programacion'))
if queryset:
publicaciones = models.Publicacion.objects.filter(
Q(titulo__icontains = queryset) |
Q(descripcion__icontains = queryset),
estado=True,
categoria=models.Categoria.objects.get(nombre__iexact='programacion')
).distinct()
paginator = Paginator(publicaciones, PAGS)
page = request.GET.get('page')
publicaciones = paginator.get_page(page)
context = {'publicaciones':publicaciones}
return render(request, 'programacion.html', context)
def tutoriales(request):
queryset = request.GET.get('buscar')
publicaciones = models.Publicacion.objects.filter(estado=True, categoria=models.Categoria.objects.get(nombre__iexact='tutoriales'))
if queryset:
publicaciones = models.Publicacion.objects.filter(
Q(titulo__icontains = queryset) |
Q(descripcion__icontains = queryset),
estado=True,
categoria=models.Categoria.objects.get(nombre__iexact='tutoriales')
).distinct()
paginator = Paginator(publicaciones, PAGS)
page = request.GET.get('page')
publicaciones = paginator.get_page(page)
context = {'publicaciones':publicaciones}
return render(request, 'tutoriales.html', context)
def tecnologia(request):
queryset = request.GET.get('buscar')
publicaciones = models.Publicacion.objects.filter(estado=True, categoria=models.Categoria.objects.get(nombre__iexact='tecnologia'))
if queryset:
publicaciones = models.Publicacion.objects.filter(
Q(titulo__icontains = queryset) |
Q(descripcion__icontains = queryset),
estado=True,
categoria=models.Categoria.objects.get(nombre__iexact='tecnologia')
).distinct()
paginator = Paginator(publicaciones, PAGS)
page = request.GET.get('page')
publicaciones = paginator.get_page(page)
context = {'publicaciones':publicaciones}
return render(request, 'tecnologia.html', context)
def videojuegos(request):
queryset = request.GET.get('buscar')
publicaciones = models.Publicacion.objects.filter(estado=True, categoria=models.Categoria.objects.get(nombre__iexact='videojuegos'))
if queryset:
publicaciones = models.Publicacion.objects.filter(
Q(titulo__icontains = queryset) |
Q(descripcion__icontains = queryset),
estado=True,
categoria=models.Categoria.objects.get(nombre__iexact='videojuegos')
).distinct()
paginator = Paginator(publicaciones, PAGS)
page = request.GET.get('page')
publicaciones = paginator.get_page(page)
context = {'publicaciones':publicaciones}
return render(request, 'videojuegos.html', context)
def detalle_publicacion(request, slug):
publicacion = models.Publicacion.objects.get(slug=slug)
context = {'publicacion':publicacion}
return render(request, 'post.html', context)
<file_sep># Generated by Django 3.0.6 on 2020-05-11 23:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='autor',
name='eliminado',
),
migrations.RemoveField(
model_name='categoria',
name='eliminado',
),
migrations.AddField(
model_name='autor',
name='estado',
field=models.BooleanField(default=True),
),
migrations.AddField(
model_name='categoria',
name='estado',
field=models.BooleanField(default=True),
),
]
<file_sep>from django.db import models
from ckeditor.fields import RichTextField
# Create your models here.
class Categoria(models.Model):
nombre = models.CharField(max_length=100, null=False, blank=False)
estado = models.BooleanField(default=True)
fecha_actualizacion = models.DateField(auto_now=True)
fecha_creacion = models.DateField(auto_now_add=True)
#auto_now: se actualiza cada vez que se edita el modelo
#auto_now_add: se añade solamente al momento de la creación del objecto
class Meta:
verbose_name = 'Categoria'
verbose_name_plural = 'Categorias'
def __str__(self):
return self.nombre
class Autor(models.Model):
nombre = models.CharField(max_length=200, null=False, blank=False)
apellido = models.CharField(max_length=200, null=False, blank=False)
correo = models.EmailField(null=False, blank=False)
facebook = models.URLField(null=True, blank=True)
twitter = models.URLField(null=True, blank=True)
instagram = models.URLField(null=True, blank=True)
web = models.URLField(null=True, blank=True)
estado = models.BooleanField(default=True)
fecha_creacion = models.DateField(auto_now_add=True)
class Meta:
verbose_name = 'Autor'
verbose_name_plural = 'Autores'
def __str__(self):
return '{}, {}'.format(self.apellido, self.nombre)
class Publicacion(models.Model):
titulo = models.CharField(max_length=100, null=False, blank=False)
slug = models.CharField(max_length=100, null=False, blank=False)
descripcion = models.CharField(max_length=100, null=False, blank=False)
contenido = RichTextField()
imagen = models.URLField(max_length=255, null=False, blank=False)
autor = models.ForeignKey(Autor, on_delete=models.CASCADE)
categoria = models.ForeignKey(Categoria, on_delete=models.CASCADE)
estado = models.BooleanField(default=True)
fecha_actualizacion = models.DateField(auto_now=True)
fecha_creacion = models.DateField(auto_now_add=True)
class Meta:
verbose_name = 'Publicacion'
verbose_name_plural = 'Publicaciones'
def __str__(self):
return self.titulo
<file_sep>from django.contrib import admin
from . import models
from import_export import resources
from import_export.admin import ImportExportModelAdmin
# Register your models here.
#Para agregar los botones de importar/exportar hay que hacer un pip install django-import-export y crear la clase model_resource y añadirlo a la clase de model_admin
class Categoria_Resource(resources.ModelResource):
class Meta:
model = models.Categoria
class Categoria_Admin(ImportExportModelAdmin, admin.ModelAdmin):
search_fields = ['nombre']
list_display = ('nombre','estado','fecha_actualizacion','fecha_creacion')
resource_class = Categoria_Resource
class Autor_Resource(resources.ModelResource):
class Meta:
model = models.Autor
class Autor_Admin(ImportExportModelAdmin, admin.ModelAdmin):
search_fields = ['nombre','apellido','correo']
list_display = ('nombre','apellido','correo','estado','fecha_creacion')
resource_class = Autor_Resource
admin.site.register(models.Autor, Autor_Admin)
admin.site.register(models.Categoria, Categoria_Admin)
admin.site.register(models.Publicacion)
<file_sep># Generated by Django 3.0.6 on 2020-05-11 23:27
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Autor',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nombre', models.CharField(max_length=200)),
('apellido', models.CharField(max_length=200)),
('correo', models.EmailField(max_length=254)),
('facebook', models.URLField(blank=True, null=True)),
('twitter', models.URLField(blank=True, null=True)),
('instagram', models.URLField(blank=True, null=True)),
('web', models.URLField(blank=True, null=True)),
('eliminado', models.BooleanField(default=False)),
('fecha_creacion', models.DateField(auto_now_add=True)),
],
options={
'verbose_name': 'Autor',
'verbose_name_plural': 'Autores',
},
),
migrations.CreateModel(
name='Categoria',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nombre', models.CharField(max_length=100)),
('eliminado', models.BooleanField(default=False)),
('fecha_actualizacion', models.DateField(auto_now=True)),
('fecha_creacion', models.DateField(auto_now_add=True)),
],
options={
'verbose_name': 'Categoria',
'verbose_name_plural': 'Categorias',
},
),
]
<file_sep>from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('generales/', views.generales, name='generales'),
path('tutoriales/', views.tutoriales, name='tutoriales'),
path('videojuegos/', views.videojuegos, name='videojuegos'),
path('programacion/', views.programacion, name='programacion'),
path('tecnologia/', views.tecnologia, name='tecnologia'),
path('<slug:slug>/', views.detalle_publicacion, name='detalle_publicacion')
]
<file_sep>{% extends "base.html" %}
{% load static %}
{% block titulo %}
{{ publicacion.titulo }}
{% endblock %}
{% block imagen %}
{{ publicacion.imagen }}
{% endblock %}
{% block titulo_principal %}
<h1>{{ publicacion.titulo }}</h1>
<p>{{ publicacion.descripcion }}</p>
{% endblock %}
{% block contenido %}
{{ publicacion.contenido|safe }}
{% endblock %}
{% block barra_busqueda %}
{% endblock %}
<file_sep>asgiref==3.2.7
defusedxml==0.6.0
diff-match-patch==20181111
dj-static==0.0.6
Django==3.0.6
django-ckeditor==5.9.0
django-import-export==2.1.0
django-js-asset==1.2.2
et-xmlfile==1.0.1
gunicorn==20.0.4
jdcal==1.4.1
MarkupPy==1.14
odfpy==1.4.1
openpyxl==3.0.3
psycopg2==2.8.5
pytz==2020.1
PyYAML==5.3.1
sqlparse==0.3.1
static3==0.7.0
tablib==1.1.0
xlrd==1.2.0
xlwt==1.3.0
| fa1acd4d39dda365f4f95e6f76f923b2d4541d4e | [
"Python",
"Text",
"HTML"
] | 8 | Python | Alex-MSX/django_blog | fd68ecf69ff7f2d9310c851d98ec330dfb56d9bb | 0bb4fc57a9e1e8786fd821145d44eadde7837bdc | |
refs/heads/master | <file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Repositories\CommentRepository;
use App\Repositories\UserRepository;
use App\Repositories\NewsRepository;
use App\Http\Resources\Resource as NewsResource;
class ResourceController extends SiteController
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function __construct(NewsRepository $news_rep, UserRepository $user_rep, CommentRepository $comment_rep)
{
$this->user_rep = $user_rep;
$this->news_rep = $news_rep;
$this->comment_rep = $comment_rep;
}
public function index()
{
$news = $this->news_rep->get();
return NewsResource::collection($news);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$news = $this->news_rep->getOne($id);
return new NewsResource($news);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
public function getNews()
{
$news = $this->news_rep->get();
return $news;
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Repositories\MenusRepository;
use Illuminate\Http\Request;
use App\Repositories\NewsRepository;
class SiteController extends Controller
{
protected $news_rep;
protected $menu_rep;
protected $user_rep;
protected $comment_rep;
protected $vars = array();
protected $template;
public function __construct()
{
}
public function renderOutput()
{
$menus = view(env('THEME') . '.menu')->render();
$this->vars = array_add($this->vars, 'menus', $menus);
return view($this->template)->with($this->vars);
}
}
<file_sep><?php
use Faker\Generator as Faker;
$factory->define(App\News::class, function (Faker $faker) {
return [
'title' => $faker->text(120),
'desc' => $faker->text(1500),
'user_id' => 1
];
});
<file_sep><?php
/**
* Created by PhpStorm.
* User: dudav
* Date: 01.04.2018
* Time: 20:06
*/
namespace App\Repositories;
use App\User;
class UserRepository extends Repository
{
public function __construct(User $user)
{
$this->model = $user;
}
}<file_sep><?php
namespace App\Http\Controllers;
use App\Repositories\CommentRepository;
use App\Repositories\UserRepository;
use Illuminate\Http\Request;
use App\Repositories\NewsRepository;
class IndexController extends SiteController
{
public function __construct(NewsRepository $news_rep, UserRepository $user_rep, CommentRepository $comment_rep)
{
$this->user_rep = $user_rep;
$this->news_rep = $news_rep;
$this->comment_rep = $comment_rep;
$this->template = env('THEME') . '.index';
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$news = $this->news_rep->get();
$content = view(env('THEME') . '.content')->with('news', $news)->render();
$this->vars = array_add($this->vars, 'content', $content);
return $this->renderOutput();
}
public function home()
{
$user_id = \Auth::user()->id;
$news = $this->news_rep->getUser($user_id );
$content = view(env('THEME') . '.home')->with('news', $news)->render();
$this->vars = array_add($this->vars, 'content', $content);
return $this->renderOutput();
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//auth()->guard()->check())/
$user_id = \Auth::user()->id;
if($request->isMethod('post')){
$input = $request->except('_token');
$input = array_add($input, 'user_id', $user_id );
$validator = $this->news_rep->validator($input);
if($validator->fails()){
return redirect()->route('add')->withErrors($validator)->withInput();
}else{
$this->news_rep->add($input);
return redirect()->route('add')->with('status', 'Новость добавлена');
}
//return redirect()->intended(route('oneNews', ['id' => 1]));
}else{
$content = view(env('THEME') . '.homeAdd')->render();
$this->vars = array_add($this->vars, 'content', $content);
return $this->renderOutput();
}
//return redirect()->intended('login');
}
public function addComment(Request $request)
{
$user_id = \Auth::user()->id;
if($request->isMethod('post')){
$input = $request->except('_token');
$input = array_add($input, 'user_id', $user_id );
$validator = $this->comment_rep->validator($input);
/*dd($input);*/
if($validator->fails()){
return redirect()->route('oneNews', ['id' => $request->news_id])->withErrors($validator)->withInput();
}else{
$this->comment_rep->add($input);
return redirect()->route('oneNews', ['id' => $request->news_id])->with('status', 'Новость добавлена');
}
}else{
return redirect()->route('oneNews', ['id' => $request->news_id]);
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
$news = $this->news_rep->getOne($id);
$content = view(env('THEME') . '.content_one')->with(['news'=> $news])->render();
$this->vars = array_add($this->vars, 'content', $content);
return $this->renderOutput();
}
public function user()
{
$id = \Auth::user()->id;
$user = $this->user_rep->getOne($id);
$content = view(env('THEME') . '.user')->with('user', $user)->render();
$this->vars = array_add($this->vars, 'content', $content);
return $this->renderOutput();
}
public function folover()
{
print_r('asdasdas');
}
public function email(Request $request)
{
if($request->isMethod('post') ) {
return redirect()->route('email')->with('status', 'Отправлено');
}
$content = view(env('THEME') . '.email')->render();
$this->vars = array_add($this->vars, 'content', $content);
return $this->renderOutput();
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy(Request $request)
{
$id = \Auth::user()->id;
$news = $this->news_rep->getOne($request->news_id);
if($request->isMethod('post') && $id == $news->user->id) {
$news->forceDelete();
}
return redirect()->route('index')->with('status', 'Удалено');
}
public function getNews()
{
$news = $this->news_rep->get();
return $news;
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: dudav
* Date: 31.03.2018
* Time: 18:39
*/
namespace App\Repositories;
use App\News;
use Validator;
class NewsRepository extends Repository
{
public function __construct(News $news)
{
$this->model = $news;
}
public function validator($input)
{
$validator = Validator::make($input, [
'title' => 'required|max:120',
'desc' => 'required|min:1'
]);
return $validator;
}
public function getUser($id)
{
$builder = $this->model->where('user_id', $id);
return $builder->get();
}
}<file_sep><?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
/*Route::get('/', function () {
return view('welcome');
});*/
Route::get('/', ['uses' => 'IndexController@index', 'as' => 'index']);
Route::post('email', ['uses' => 'IndexController@email', 'as' => 'email']);
Route::get('email', ['uses' => 'IndexController@email']);
Route::get('news/{id}', ['uses' => 'IndexController@show', 'as' => 'oneNews']);
Route::post('/news', ['uses' => 'IndexController@destroy', 'as' => 'delete'])->middleware('auth');
Route::post('comment', ['uses' => 'IndexController@addComment', 'as' => 'addComment'])->middleware('auth');
Auth::routes();
Route::group(['prefix' => 'home', 'middleware' => 'auth'], function(){
Route::get('/', 'IndexController@home')->name('home');
Route::get('/user', 'IndexController@user')->name('userInfo');
Route::get('/add', 'IndexController@store')->name('add');
Route::post('/add', 'IndexController@store')->name('postAdd');
Route::get('/token', function () {
return Auth::user()->createToken(\Auth::user()->id);
})->name('token');
});
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Folover extends Model
{
//
protected $table = 'folovers';
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: dudav
* Date: 01.04.2018
* Time: 21:29
*/
namespace App\Repositories;
use App\Comment;
use Validator;
class CommentRepository extends Repository
{
public function __construct(Comment $comment)
{
$this->model = $comment;
}
public function getNews($id)
{
$builder = $this->model->where('news_id', $id);
return $builder->get();
}
public function validator($input)
{
$validator = Validator::make($input, [
'text' => 'required|min:1',
]);
return $validator;
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: dudav
* Date: 31.03.2018
* Time: 18:39
*/
namespace App\Repositories;
abstract class Repository
{
protected $model = false;
public function get()
{
$builder = $this->model->select('*');
return $builder->get();
}
public function getOne($id)
{
$result = $this->model->where('id', $id)->first();
return $result;
}
public function add($input)
{
$model = new $this->model;
$model->fill($input);
$model->save();
return $model;
}
} | bc892d9ccf88905e5301e8c5ccd9856a89b8d0b3 | [
"PHP"
] | 10 | PHP | AndreyDuda/news | b0c6768ca7a02631b3f4f52121664feb5b724e42 | f1f2341b7ae696ccc5f570cc292437f29b7c29f4 | |
refs/heads/main | <file_sep>from rest_framework import status
from rest_framework.response import Response
from rest_framework.generics import GenericAPIView
from .serializers import GoogleSocialAuthSerializer, FacebookSocialAuthSerializer
from rest_framework.permissions import IsAuthenticated, AllowAny
class GoogleSocialAuthView(GenericAPIView):
permission_classes = [AllowAny]
serializer_class = GoogleSocialAuthSerializer
def post(self, request):
"""
POST with "auth_token"
Send an "idtoken" as from google to get user information
"""
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
response = ((serializer.validated_data)['auth_token'])
return Response(response)
class FacebookSocialAuthView(GenericAPIView):
permission_classes = [AllowAny]
serializer_class = FacebookSocialAuthSerializer
def post(self, request):
"""
POST with "auth_token"
Send an access token as from facebook to get user information
"""
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
response = ((serializer.validated_data)['auth_token'])
return Response(response)<file_sep>from rest_framework.exceptions import APIException
from django.utils.encoding import force_text
from rest_framework import status
class CustomException(APIException):
status_code = status.HTTP_200_OK
default_detail = 'Something went wrong.'
def __init__(self, detail, **kwargs):
if detail is not None:
self.detail = detail
else:
self.detail = {'detail': force_text(self.default_detail)}
for key, value in kwargs.items():
if key == "status_code":
self.status_code = value
<file_sep>from django.db import models
from django.contrib.auth import get_user_model
User = get_user_model()
class SocialApplication(models.Model):
AUTH_PROVIDERS = [
('facebook', 'Facebook'),
('google', 'Google')
]
provider = models.CharField(max_length=128, choices=AUTH_PROVIDERS)
name = models.CharField(max_length=128)
client_id = models.CharField(
max_length=256, help_text="App ID, or consumer key")
client_secret = models.CharField(
max_length=256, help_text="API secret, client secret, or consumer secret")
def __str__(self):
return self.name
class SocialAccount(models.Model):
user = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="tfora_social_auth_account")
provider = models.ForeignKey(SocialApplication, on_delete=models.CASCADE)
def __str__(self):
return self.user.username
<file_sep>from google.auth.transport import requests
from google.oauth2 import id_token
import facebook
from .utils import get_social_app_credentials
class Google:
@staticmethod
def validate(auth_token):
idinfo = id_token.verify_oauth2_token(
auth_token, requests.Request(), get_social_app_credentials("google").client_id)
if 'accounts.google.com' in idinfo['iss']:
return idinfo
class Facebook:
@staticmethod
def validate(auth_token):
try:
graph = facebook.GraphAPI(access_token=auth_token)
profile = graph.request(
'/me?fields=name,email,first_name,last_name,middle_name,picture,id')
return profile
except:
return "The token is either invalid or has expired"<file_sep>from rest_framework import serializers
from rest_framework.exceptions import AuthenticationFailed
from . import providers
from .utils import register_social_user, get_social_app_credentials
class GoogleSocialAuthSerializer(serializers.Serializer):
auth_token = serializers.CharField()
def validate_auth_token(self, auth_token):
user_data = providers.Google.validate(auth_token)
try:
user_data['sub']
except:
raise serializers.ValidationError(
'The token is invalid or expired. Please login again.'
)
google_cred = get_social_app_credentials("google")
if user_data['aud'] != google_cred.client_id:
raise AuthenticationFailed('Unauthorized activity detected')
user_id = user_data['sub']
email = user_data['email']
name = user_data['name']
provider = 'google'
return register_social_user(
provider=provider,
user_id=user_id,
email=email,
name=name,
provider_data=user_data
)
class FacebookSocialAuthSerializer(serializers.Serializer):
auth_token = serializers.CharField()
def validate_auth_token(self, auth_token):
get_social_app_credentials("facebook")
user_data = providers.Facebook.validate(auth_token)
try:
user_id = user_data.get('id')
email = user_data.get('email')
name = user_data.get('name')
provider = 'facebook'
return register_social_user(
provider=provider,
user_id=user_id,
email=email,
name=name,
provider_data=user_data
)
except Exception as e:
raise serializers.ValidationError(
'The token is invalid or expired. Please login again.'
)<file_sep>import random
from . import signals
from .models import SocialApplication
from .exceptions import CustomException
from . models import User, SocialAccount
def generate_username(name):
username = "".join(name.split(' ')).lower()
if not User.objects.filter(username=username).exists():
return username
else:
random_username = username + str(random.randint(0, 1000))
return generate_username(random_username)
def get_social_app_credentials(provider):
"""Query social app credentials from db provided by Providers (google,facebook)"""
try:
return SocialApplication.objects.get(provider=provider)
except:
raise Exception(
f"{provider.title()} credentials not found in Social Applications")
def get_user_social_account(user, provider):
"""User have already registered.Checking corresponding provider"""
try:
return SocialAccount.objects.get(user=user, provider__provider=provider)
except:
raise CustomException({
'status': 403,
"message": "Login with your username and password"
})
def register_social_user(provider, user_id, email, name, provider_data):
if isinstance(email, type(None)):
raise CustomException({
'status': 403,
"message": "E-mail cannot be blank"
})
filtered_user_by_email = User.objects.filter(email=email)
if filtered_user_by_email.exists():
social_account_user = get_user_social_account(
filtered_user_by_email[0], provider)
if provider == social_account_user.provider.provider:
signals.user_logged_in.send(
sender="social_user_login",
provider=provider,
user=filtered_user_by_email[0],
provider_data=provider_data
)
token = filtered_user_by_email[0].get_token()
auth_data = {
'refresh': str(token),
'access': str(token.access_token),
}
data = {
"status": 200,
"auth": auth_data,
"message": "Logged in successfully"
}
return data
else:
raise CustomException({
'status': 403,
"message": 'Please continue your login using ' + social_account_user.provider.provider
})
else:
if provider == 'google':
first_name = provider_data['given_name']
last_name = provider_data['family_name']
elif provider == 'facebook':
first_name = provider_data['first_name']
last_name = provider_data['last_name']
kwargs = {
'username': generate_username(name),
'email': email,
"is_active": True,
"first_name": first_name,
"last_name": last_name
}
new_user = User.objects.create(**kwargs)
new_user.set_unusable_password()
new_user.save()
signals.user_registered.send(
sender="social_user_register",
provider=provider,
user=new_user,
provider_data=provider_data
)
token = new_user.get_token()
auth_data = {
'refresh': str(token),
'access': str(token.access_token)
}
data = {
"status": 200,
"auth": auth_data,
"message": "Registered successfully"
}
return data<file_sep>from django.dispatch import Signal, receiver
from .models import User, SocialAccount, SocialApplication
user_registered = Signal()
user_logged_in = Signal()
@receiver(user_registered)
def create_social_account(user, provider, provider_data, **kwargs):
social_account = SocialAccount.objects.filter(
user=user, provider__provider=provider)
if not social_account.exists():
app = SocialApplication.objects.get(provider=provider)
SocialAccount.objects.create(user=user, provider=app)<file_sep>from django.apps import AppConfig
class TforaSocialAuthConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'tfora_social_auth'
<file_sep># tfora_social_auth
Easy django rest auth integration for social applications. (currently supports Google and Facebook)
## Quick Setup
Install package
pip install tfora-social-auth
Add `tfora_social_auth` app to INSTALLED_APPS in your django settings.py:
```python
INSTALLED_APPS = [
...
'rest_framework',
'tfora_social_auth',
...
]
```
python manage.py migrate
#### Add URL patterns
```python
from tfora_social_auth.views import ( GoogleSocialAuthView, FacebookSocialAuthView )
urlpatterns = [
path('social/google/', GoogleSocialAuthView.as_view()),
path('social/facebook/', FacebookSocialAuthView.as_view()),
]
```
##### For Google login
- POST with "auth_token".
- Send an "idtoken" as from google to get user information
##### For Facebook login
- POST with "auth_token".
- Send an access token as from facebook to get user information
##### Extra token payload
You can add extra payload data to access token by the following method
```python
from rest_framework_simplejwt.tokens import RefreshToken
class CustomUserModel(AbstractUser):
...
@staticmethod
def get_token(user):
token = RefreshToken.for_user(user)
token["extra_key"] = "extra_value"
return token
...
```
<file_sep>from django.contrib import admin
from .models import *
admin.site.register(SocialApplication)
admin.site.register(SocialAccount)
<file_sep>from django.urls import path
from .views import GoogleSocialAuthView, FacebookSocialAuthView
app_name = "tfora_social_auth"
urlpatterns = [
path('google/', GoogleSocialAuthView.as_view()),
path('facebook/', FacebookSocialAuthView.as_view()),
]
<file_sep>from distutils.core import setup
import os
setup(
name='tfora_social_auth',
packages=['tfora_social_auth'],
version='0.3',
license='MIT',
description='Easy django rest auth integration for social applications (currently supports google and facebook)',
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/pvfarooq/tfora_social_auth',
download_url='https://github.com/pvfarooq/tfora_social_auth/archive/refs/tags/0.3.tar.gz',
keywords=['django', 'social login', 'allauth', 'rest_auth','google login','facebook login'],
install_requires=[
'facebook-sdk',
'google-auth',
'requests',
'djangorestframework'
],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Build Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
],
)
| dbd6065df85340374192ad2a3b7b8d005a80cc7e | [
"Markdown",
"Python"
] | 12 | Python | pvfarooq/tfora_social_auth | 3cd0a0b365371d67a1b784000a31193141129875 | 98c2a187f8c1661172d2e617912fff24c20d9d41 | |
refs/heads/main | <file_sep>var bg, bgimg, play, playimg
var gamstate = "serve"
function preload(){
bgimg = loadImage("images/bakery.jpg");
playimg = loadImage("images/play.png");
}
function setup(){
createCanvas(1200, 800);
bg = createSprite(600, 400);
bg.addImage(bgimg)
bg.scale = 2
play = createSprite(600, 400)
play.addImage( playimg)
play.scale = 0.5
}
function draw(){
background(0)
drawSprites();
} | 051644038ce8cdbef08eea4634b33d9501377cb5 | [
"JavaScript"
] | 1 | JavaScript | Nayana-01/p-44 | d12c7b41f32474dd942f79ef51d6f0dfddfb16dd | 400cf5be88769f42be25682c9f8c4aa1c2122968 | |
refs/heads/main | <file_sep>#Dataset from COVID-19 Radiography Dataset on Kaggle
#start imported libraries
import os
import shutil
import random
import torch
import torchvision
import numpy as np
from PIL import Image
from matplotlib import pyplot as plt
torch.manual_seed(0)
print('Using PyTorch version', torch.__version__)
#end imported libraries
#star preping data sets
class_names = ['normal', 'viral', 'covid']
root_dir = 'COVID-19 Radiography Database'
source_dirs = ['NORMAL', 'Viral Pneumonia', 'COVID-19']
if os.path.isdir(os.path.join(root_dir, source_dirs[1])):
os.mkdir(os.path.join(root_dir, 'test'))
for i, d in enumerate(source_dirs):
os.rename(os.path.join(root_dir, d), os.path.join(root_dir, class_names[i]))
for c in class_names:
os.mkdir(os.path.join(root_dir, 'test', c))
for c in class_names:
images = [x for x in os.listdir(os.path.join(root_dir, c)) if x.lower().endswith('png')]
selected_images = random.sample(images, 30)
for image in selected_images:
source_path = os.path.join(root_dir, c, image)
target_path = os.path.join(root_dir, 'test', c, image)
shutil.move(source_path, target_path)
class ChestXRayDataset(torch.utils.data.Dataset):
def __init__(self, image_dirs, transform):
def get_images(class_name):
images = [x for x in os.listdir(image_dirs[class_name]) if x[-3:].lower().endswith('png')]
print('Found {len(images)} {class_name} examples')
return images
#creation of a dictionary to keep track of the images outputed in the above function
self.images = {}
self.class_names = ['normal', 'viral', 'covid']
for class_name in self.class_names:
self.images[class_name] = get_images(class_name)
self.image_dirs = image_dirs
self.transform = transform
def __len__(self):
return sum([len(self.images[class_name]) for class_name in self.class_names])
#returns lenght data set of the three classes combined
def __getitem__(self, index):
#chooses random class
class_name = random.choice(self.class_names)
#there to "fix" the imbalance in inputed training sets as there's less covid images than there is normal ones
#that way the index actually correspond to a real index in the class
index = index % len(self.images[class_name])
#list images that belong to the class
image_name = self.images[class_name][index]
image_path = os.path.join(self.image_dirs[class_name], image_name)
#to load
#pytorch requires transform
image = Image.open(image_path).convert('RGB')
return self.transform(image), self.class_names.index(class_name)
#image transformation parameters for training data set
train_transform = torchvision.transforms.Compose([
#resizing images
torchvision.transforms.Resize(size=(227, 227)),
#flipping images at random to do an augmentation of the training set
torchvision.transforms.RandomHorizontalFlip(),
#can be used by pytorch
torchvision.transforms.ToTensor(),
#normalize data
torchvision.transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
#same image tranformation parameters for control data set
control_transform = torchvision.transforms.Compose([
torchvision.transforms.Resize(size=(224, 224)),
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
#end preping data sets
#start data loaders
train_dirs = {
'normal': 'COVID-19 Radiography Database/normal',
'viral': 'COVID-19 Radiography Database/viral',
'covid': 'COVID-19 Radiography Database/covid'
}
train_dataset = ChestXRayDataset(train_dirs, train_transform)
control_dirs = {
'normal': 'COVID-19 Radiography Database/test/normal',
'viral': 'COVID-19 Radiography Database/test/viral',
'covid': 'COVID-19 Radiography Database/test/covid'
}
control_dataset = ChestXRayDataset(control_dirs, control_transform)
#amount of pictures that will be displayed at a time
batch_size = 6
dl_train = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
dl_control = torch.utils.data.DataLoader(control_dataset, batch_size=batch_size, shuffle=True)
#next lines check if the size of the batches is reasonable len(dl_train)+len(dl_control)= total len and len(dl_train) >> len(dl_control)
print('Number of training batches', len(dl_train))
print('Number of test batches', len(dl_control))
#end data loaders
#start data visualization
lass_names = train_dataset.class_names
def show_images(images, labels, preds):
plt.figure(figsize=(8, 4))
for i, image in enumerate(images):
#batch size
plt.subplot(1, 6, i + 1, xticks=[], yticks=[])
#image transformation parameters - pytorch
image = image.numpy().transpose((1, 2, 0))
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
#original values
image = image * std + mean
#clip values
image = np.clip(image, 0., 1.)
plt.imshow(image)
#prediction will be displayed in green if correct and red if incorrect
col = 'green'
if preds[i] != labels[i]:
col = 'red'
#x label = control/real diagnose
plt.xlabel({class_names[int(labels[i].numpy())]}')
#y label used to see prediction
plt.ylabel{{class_names[int(preds[i].numpy())]}', color=col)
#layout of the plot
plt.tight_layout()
#display the plot
plt.show()
#see examples data(ie Xrays)
images, labels = next(iter(dl_train))
show_images(images, labels, labels)
images, labels = next(iter(dl_control))
show_images(images, labels, labels)
#end data visualization
#start torch vision model
#chose resnet so it can run on my pc without too much computational power
#we want to use the pretrained sets thus why we see pretrained
resnet18 = torchvision.models.resnet18(pretrained=True)
#check model architecture
print(resnet18)
#put 3 outpout features, standart is 1000
resnet18.fc = torch.nn.Linear(in_features=512, out_features=3)
#classification loss function
loss_fn = torch.nn.CrossEntropyLoss()
#we optimize all the parameters of the module
optimizer = torch.optim.Adam(resnet18.parameters(), lr=3e-5)
#function to show predictions
def show_preds():
resnet18.eval()
#evaluate random images
images, labels = next(iter(dl_test))
outputs = resnet18(images)
#make sure we get the indixes not the values
#dimension = number of examples -> 1
_, preds = torch.max(outputs, 1)
#we want to show the image, prediction and labels
show_images(images, labels, preds)
#test predictions
show_preds()
#end torch vision model
#start training
def train(epochs):
print('Starting training..')
for e in range(0, epochs):
print('='*20)
print('Starting epoch {e + 1}/{epochs}')
print('='*20)
train_loss = 0.
val_loss = 0.
resnet18.train() # set model to training phase
for train_step, (images, labels) in enumerate(dl_train):
optimizer.zero_grad()
outputs = resnet18(images)
loss = loss_fn(outputs, labels)
loss.backward()
optimizer.step()
train_loss += loss.item()
if train_step % 20 == 0:
print('Evaluating at step', train_step)
#we want to evaluate accuracy
acc = 0
resnet18.eval() # set model to eval phase
for val_step, (images, labels) in enumerate(dl_test):
outputs = resnet18(images)
loss = loss_fn(outputs, labels)
val_loss += loss.item()
_, preds = torch.max(outputs, 1)
acc += sum((preds == labels).numpy())
val_loss /= (val_step + 1)
acc = acc/len(control_dataset)
print('Validation Loss: {val_loss:.4f}, Accuracy: {acc:.4f}')
show_preds()
#train again
resnet18.train()
#will train until accuracy reaches or surpasses 0.95
if accuracy >= 0.95:
print('Performance condition satisfied, stopping training.')
return
#training loss
train_loss /= (train_step + 1)
print('Training Loss: {train_loss:.4f}')
print('Training complete..')
#low epoch to avoid overusing computational power, higher epoch == higher accuracy
train(epochs=1)
#end training
#result
show_preds()<file_sep># AI-Detecting-Covid-with-Chest-X-Ray
This Neural Network has been trained with multiple X rays of patients with different conditions to recognize whenever or not they suffer from Covid.
The used data set has nearly 3000 Chest X-Ray scans, categorized in three classes - Normal, Viral Pneumonia and COVID-19. It can be obtained on Kaggle ("COVID-19 Radiography Dataset").
The used model is a ResNet-18 model in PyTorch that performs Image Classification.
Please note this code cannot accurately diagnose Covid-19.
| 319dbb3bf83a8f302b6bdcd75075b110820efa12 | [
"Markdown",
"Python"
] | 2 | Python | mgg39/AI-Detecting-Covid-with-Chest-X-Ray | d6079a1d2a1443807e21698cf62836c66ba93c63 | 557ec62f90c1dc651c0f40cdf3a8ae34897de4a3 | |
refs/heads/master | <repo_name>weiyufangchen/yanxuan-react<file_sep>/README.md
## react项目
### day01
```
1. 复习react相关知识,语法,和作用
2. 搭建脚手架项目
3. 配置stylus语法编译
4. 搭建路由和页面底部路由切换
5. 首页静态页面完成
bug:
样式重叠
多个文件的样式类名相同,导致样式被覆盖
解决方法:修改类名
```
### day02
```
完成5个路由页面和手机登录,邮箱登录页面,并完成登录验证、定时器等功能
动态添加数据完成80%
bug:
1. 数据为null或者undefined
解决:绑定数据之前判断数据是否请求成功,是否保存在state中,再去获取遍历
2. 轮播图bug
解决:componentDidUpdate函数中将swiper实例对象挂载到this上,然后判断是否已经创建,已经创建则不需要再次创建
```
### day03
```
npm run build
打包发布生成build文件
```
<file_sep>/src/containers/profile/Profile.jsx
/*
个人中心/登录/注册组件
*/
import React, {Component} from 'react'
// react-router 提供了一个withRouter组件
// withRouter可以包装任何自定义组件,将react-router 的 history,location,match 三个对象传入
import {withRouter} from 'react-router-dom'
import ShiwuHeader from '../../components/shiwuHeader/ShiwuHeader'
import './profile.styl'
class Profile extends Component {
render () {
return (
<div className='profile'>
{/* 登录/注册,个人中心头部 */}
<ShiwuHeader/>
<div className="loginWrap" style={{height: '1246px',display: 'block'}}>
<div className="login-type">
{/* 登录按钮 */}
<div className="container">
<div className="logoWrapper">
<img src="//yanxuan.nosdn.127.net/bd139d2c42205f749cd4ab78fa3d6c60.png" alt=""/>
</div>
<div className="btnWrapper">
<div className="btn btn-xl btn-block phone-login"
onClick={() => this.props.history.replace('/phonelogin')}>
<i className="icon icon-loginPhone"></i>
<span>手机号码登录</span>
</div>
<div className="btn btn-xl btn-block email-login"
onClick={() => this.props.history.replace('/emaillogin')}>
<i className="icon icon-loginEmail"></i>
<span>邮箱账号登录</span>
</div>
<div className="register" onClick={() => this.props.history.replace('/profile')}>
<span>手机号快捷注册 > </span>
</div>
</div>
</div>
{/* 联系方式 */}
<ul className="contact">
<li className="itemWrap">
<span className="item">
<i className="iconfont icon-weixin1"></i>
<span className="name">微信</span>
</span>
</li>
<li className="itemWrap">
<span className="item">
<i className="iconfont icon-qq"></i>
<span className="name">QQ</span>
</span>
</li>
<li className="itemWrap">
<span className="item">
<i className="iconfont icon-sinaweibo"></i>
<span className="name">微博</span>
</span>
</li>
</ul>
</div>
</div>
</div>
)
}
}
export default withRouter(Profile)
<file_sep>/src/api/index.js
/*
包含多个接口的请求函数的模块
函数的返回值:promise对象
*/
import ajax from './ajax'
// 获取首页数据
export const reqHomeData = () => ajax('/homedata')
export const reqNavData = () => ajax('/navdata')
export const reqTopicData = () => ajax('/topicdata')
<file_sep>/src/components/homeHeader/HomeHeader.jsx
/*
首页头部组件HomerHeader
*/
import React, {Component} from 'react'
//引入滚动的插件库
import BScroll from 'better-scroll'
// 引入样式
import './homeHeader.styl'
export default class HomeHeader extends Component {
state = {
navList: ['推荐', '居家', '鞋包配饰', '服装', '电器', '洗护', '饮食', '餐厨', '婴童', '文体', '特色区'],
currentIndex: 0
}
componentDidMount() {
new BScroll('.header-nav', {
scrollX: true,
click: true
})
}
addClass = (index) => {
// 更新state
this.setState({
currentIndex: index
})
}
render() {
const {navList, currentIndex} = this.state
return (
<div>
<div className="home-header">
{/*首页搜索*/}
<div className="header-search">
<a href="javascript:;" className="logo"></a>
<div className="search">
<i className="iconfont"></i>
<span>搜索商品, 共11765款好物</span>
</div>
</div>
{/*首页导航*/}
<div ref='headerNav' className="header-nav border-1px">
<ul className="nav-list">
{
navList.map((item, index) => {
return (
<li className="list-item" key={index} onClick={() => this.addClass(index)}>
<span ref="span" className={index === currentIndex ? 'active' : ''}>{item}</span>
</li>
)
})
}
</ul>
</div>
</div>
</div>
)
}
}
<file_sep>/src/redux/action-types.js
/*
包含多个action type常量名称的模块
*/
export const RECEIVE_HOMEDATA = 'receive_homedata' // 接收首页数据
export const RECEIVE_NAVDATA = 'receive_navdata'
export const RECEIVE_TOPICDATA = 'receive_topicdata'
// 请求失败
export const ERR_MSG = 'ERR_MSG'
<file_sep>/src/redux/store.js
/*
redux管理状态的核心对象
*/
import {createStore, applyMiddleware} from 'redux'
// 应用异步中间件
import thunk from 'redux-thunk'
// 使用插件工具查看state
import {composeWithDevTools} from 'redux-devtools-extension'
import reducers from './reducers' // 它是一个个的reducer函数
export default createStore(reducers, composeWithDevTools(applyMiddleware(thunk)))
<file_sep>/src/containers/shiwu/shiwuBanner/ShiwuBanner.jsx
/*
识物轮播图
*/
import React, {Component} from 'react'
import Swiper from 'swiper'
import './shiwuBanner.styl'
export default class ShiwuBanner extends Component {
componentDidUpdate () {
new Swiper('.swiper-container-banner1', {
loop: true,
zoom: true,
})
}
render () {
const banner = this.props.data
return (
<div className="banner-wrapper">
<div className="carousel banner">
<div className="swiper-container-banner1">
<div className="swiper-wrapper">
{
banner ? (
banner.map((item, index) => {
return (
<div className="swiper-slide" style={{width: '690px'}} key={index}>
<a href="javascript:;">
<img src={item.picUrl} alt=""/>
<div className="content">
<div className="subTitle">{item.subTitle}</div>
<div className="title">{item.title}</div>
<div className="desc">{item.desc}</div>
</div>
</a>
</div>
)
})
) : null
}
</div>
{/* Add Pagination */}
<div className="swiper-pagination"></div>
</div>
</div>
</div>
)
}
}
<file_sep>/src/components/modelHeader/ModelHeader.jsx
/*
通用的模版头部
*/
import React, {Component} from 'react'
import './modelHeader.styl'
export default class ModelHeader extends Component {
render () {
return (
<header className="hd-one">
<a className="more" href="javascript:;">
<span>品牌制造商直供</span>
<i className="icon icon-go"></i>
</a>
</header>
)
}
}<file_sep>/src/api/ajax.js
/*
ajax请求函数模块
函数的返回值为promise对象
*/
import axios from 'axios'
export default function ajax(url='', data={}, type='GET') {
// 返回一个自己创建的promise对象,为了能得到的不是response,而是得到response.data的数据
return new Promise(function (resolve, reject) {
let promise
// 如果发送的GET请求
if (type === 'GET') {
// 将data中所有数据作为请求参数传到url中
// 准备url query 参数数据
let queryStr = '';
Object.keys(data).forEach(key => { // keys() 得到对象自身的所有属性名组成的数组
const value = data[key] // 拿到对应的属性值
// 拼串
queryStr += key + '=' + value + '&' // 最后会多一个&
});
if (queryStr) { // 如果确实发送了请求数据
// 去除最后的&
queryStr = queryStr.substring(0, queryStr.length - 1)
// 加上问号
queryStr = '?' + queryStr
}
// 拿到response.data
promise = axios.get(url + queryStr);
} else { // POST请求
promise = axios.post(url, data)
}
promise.then(response => {
// 请求成功
resolve(response.data)
}).catch(err => { // 请求失败
reject(err)
})
})
}
<file_sep>/src/components/limitTimeBuy/LimitTimeBuy.jsx
/*
限时购组件:UI组件
*/
import React, {Component} from 'react'
import './limitTimeBuy.styl'
export default class LimitTimeBuy extends Component {
state = {
hour: '00', // 初始化限时购
min: '10',
second: '20',
startTime: 20
}
componentDidMount () {
this.countDown()
}
// 倒计时,限时购
countDown = () => {
// 获取当前时间
let date = new Date()
let start = date.getTime()
// 设置截止时间
let endDate = new Date("2018-8-18 20:00:00")
let end = endDate.getTime()
// 时间差
let deltaTime = end - start
// 定义变量 d,h,m,s保存倒计时的时间
let d, h, m, s
if (deltaTime >= 0) {
d = Math.floor(deltaTime / 1000 / 60 / 60 / 24)
h = Math.floor(deltaTime / 1000 / 60 / 60 % 24)
m = Math.floor(deltaTime / 1000 / 60 % 60)
s = Math.floor(deltaTime / 1000 % 60)
}
// 更新状态
if (h < 10) {
this.setState({
hour: `0${h}`
});
} else {
this.setState({
hour: `${h}`
})
}
if (m < 10) {
this.setState({
min: `0${m}`
});
} else {
this.setState({
min: `${m}`
});
}
if (s < 10) {
this.setState({
sec: `0${s}`
});
} else {
this.setState({
second: `${s}`
});
}
// 递归调用
setTimeout(this.countDown, 1000)
}
render () {
const flashSaleIndexVO = this.props.data
const {hour, min, second, startTime} = this.state
return (
flashSaleIndexVO ? (
<div>
<a href="javascript:;">
<div className="indexFlash">
<div className="left-item">
<div className="title">严选限时购</div>
<div className="countdown">
<span className="hours">{hour}</span>
<span className="colon">:</span>
<span className="mins">{min}</span>
<span className="colon">:</span>
<span className="secs">{second}</span>
</div>
<div className="next-title">
<span>
<span>下一场</span>
<span>{startTime}:00</span>
<span>开始</span>
</span>
</div>
</div>
<div className="right-item">
<img src={flashSaleIndexVO.primaryPicUrl}/>
<div className="price">
<div className="price-now">
<span>¥{flashSaleIndexVO.activityPrice}</span>
</div>
<div className="price-origin">
{/* 添加伪类做删除线 */}
<span className="t">¥{flashSaleIndexVO.originPrice}</span>
</div>
</div>
</div>
</div>
</a>
</div>
) : null
)
}
}
<file_sep>/src/containers/cart/Cart.jsx
/*
购物车路由组件
*/
import React, {Component} from 'react'
import {NavLink} from 'react-router-dom'
import './cart.styl'
import FooterGuide from '../../components/footerGuide/FooterGuide'
export default class Cart extends Component {
render () {
return (
<div>
<div className='cart'>
{/* cart头部 */}
<div className="cartHeader" style={{height: '88px'}}>
<div className="hd">
<div className="headWrapper">
<span className="logo">购物车</span>
<div className="right">
<NavLink className="cartCoupon" to='/profile'>领券</NavLink>
</div>
</div>
</div>
</div>
{/* 服务:30天无忧退货 */}
<div className="service">
<ul className="serviceList">
<li className="item">
<i className="icon icon-servicePolicy"></i>
<span>30天无忧退货</span>
</li>
<li className="item">
<i className="icon icon-servicePolicy"></i>
<span>48小时快速退款</span>
</li>
<li className="item">
<i className="icon icon-servicePolicy"></i>
<span>满88元免邮费</span>
</li>
</ul>
</div>
{/* 购物车空状态的默认页面 */}
<div className="defaultPage noCart-defaultPage">
<div className="container">
<div className="noCart-img"></div>
<div className="txt noCart-login">
<div className="noCart-title">去添加点什么吧</div>
<div className="noCart-btn">登录</div>
</div>
</div>
</div>
</div>
<FooterGuide/>
</div>
)
}
}
<file_sep>/src/components/footerGuide/FooterGuide.jsx
/*
底部导航的组件FooterGuide
*/
import React, {Component} from 'react'
import {
withRouter,
NavLink,
} from 'react-router-dom'
import './footerGuide.styl'
class FooterGuide extends Component {
render() {
return (
<footer className="footer_guide border-1px">
<NavLink href="javascript:;" className="guide_item" activeClassName='active' to='/home'>
<i className="iconfont icon-shouye"></i>
<span>首页</span>
</NavLink>
<NavLink href="javascript:;" className="guide_item" activeClassName='active' to='/shiwu'>
<i className="iconfont icon-fangkuaidagou-weixuanzhong"></i>
<span>识物</span>
</NavLink>
<NavLink href="javascript:;" className="guide_item" activeClassName='active' to='/category'>
<i className="iconfont icon-chouti"></i>
<span>分类</span>
</NavLink>
<NavLink href="javascript:;" className="guide_item" activeClassName='active' to='/cart'>
<i className="iconfont icon-gouwuche"></i>
<span>购物车</span>
</NavLink>
<NavLink href="javascript:;" className="guide_item" activeClassName='active' to='/profile'>
<i className="iconfont icon-renwu"></i>
<span>个人</span>
</NavLink>
</footer>
)
}
}
export default withRouter(FooterGuide) // 向一般组件传递路由相关属性(history/location/match)
<file_sep>/src/index.js
/*
入口js
*/
import React from 'react'
import ReactDOM from 'react-dom'
import {Provider} from 'react-redux'
import {Route, Switch, HashRouter, Redirect} from 'react-router-dom'
import Home from './containers/home/Home'
import Shiwu from './containers/shiwu/Shiwu'
import Category from './containers/category/Category'
import Cart from './containers/cart/Cart'
import Profile from './containers/profile/Profile'
import PhoneLogin from './containers/phoneLogin/PhoneLogin'
import EmailLogin from './containers/emailLogin/EmailLogin'
import store from './redux/store'
// 引入mock文件
import './mock/mockServer'
// 引入混合stylus样式
import './assets/css/stylus/mixins.styl'
import 'swiper/dist/css/swiper.css'
import './assets/css/reset.css'
import './assets/css/index.css'
import './assets/js/index'
import 'antd-mobile/dist/antd-mobile.css';
ReactDOM.render((
<Provider store={store}>
<HashRouter>
<Switch>
<Route path='/phonelogin' component={PhoneLogin}/>
<Route path='/emaillogin' component={EmailLogin}/>
<Route path='/home' component={Home}/>
<Route path='/shiwu' component={Shiwu}/>
<Route path='/category' component={Category}/>
<Route path='/cart' component={Cart}/>
<Route path='/profile' component={Profile}/>
<Redirect to='/home'/> {/* 默认路由 */}
</Switch>
</HashRouter>
</Provider>
), document.getElementById('root'));
<file_sep>/src/containers/category/Category.jsx
/*
商品分类路由组件
*/
import React, {Component} from 'react'
import {connect} from 'react-redux'
import {getNavData} from '../../redux/actions'
import BScroll from 'better-scroll'
import './category.styl'
import CategoryHeader from '../../components/categoryHeader/CategoryHeader'
import FooterGuide from '../../components/footerGuide/FooterGuide'
class Category extends Component {
// 定义初始index值,保存左侧导航li的下标
state = {
currentIndex: 0
}
componentDidMount() {
// 调用action中函数,通知state更新
this.props.getNavData()
}
componentDidUpdate() {
new BScroll(this.refs.leftScroll, {click: true})
// new BScroll(this.refs.rightScroll, {click: true})
}
// 监听li下标的改变
activeChange = (index) => {
// 更新state
this.setState({
currentIndex: index
})
}
render() {
const {navData} = this.props
const {currentIndex} = this.state
if (navData.length === 0) {
return (<div></div>)
}
return (
<div style={{backgroundColor: '#fff', width: '100%', height: '1734px'}}>
{/* 商品分类头部搜索 */}
<CategoryHeader/>
{/* 商品左侧菜单导航 */}
<div className="cateNavLeft" style={{left: 0}}>
<div ref='leftScroll' style={{position: 'relative', height: '100%', width: '100%', overflow: 'hidden'}}>
<ul className="cateNav">
{
navData.map((item, index) => {
return (
<li className={index === currentIndex ? 'item active' : 'item'} key={index}
onClick={() => this.activeChange(index)}>
<a className="txt" href="javascript:;">{item.name}</a>
</li>
)
})
}
</ul>
</div>
</div>
{/* 商品右侧展示列表 */}
<div className="categoryNavRight">
{
navData.map((item, index) => {
return (
<div className={index === currentIndex ? 'wrap show': 'wrap hide'} key={index}>
<div className="banner" style={{backgroundImage: 'url(' + item.bannerUrl + ')'}}></div>
<div className="cateList">
<div className="hd">
<span className="text">
<span>{item.name}分类</span>
</span>
</div>
<div>
<ul className="list">
{
item.subCateList.map((subItem, index) => {
return (
<li className="cateItem" key={index}>
<a href="javascript:;">
<div className="cateImgWraper">
<img className="cateImg"
src={subItem.wapBannerUrl}
alt=""/>
</div>
<div className="name">{subItem.name}</div>
</a>
</li>
)
})
}
</ul>
</div>
</div>
</div>
)
})
}
</div>
<FooterGuide/>
</div>
)
}
}
export default connect(
state => ({navData: state.navData}),
{getNavData}
)(Category)
<file_sep>/src/containers/emailLogin/EmailLogin.jsx
/*
邮箱登录组件
*/
import React, {Component} from 'react'
import {withRouter} from 'react-router-dom'
import {Modal} from 'antd-mobile'
import ShiwuHeader from '../../components/shiwuHeader/ShiwuHeader'
import codeImg from './captcha.svg'
import './emailLogin.styl'
const alert = Modal.alert
class EmailLogin extends Component {
state = {
email: '',
pwd: '',
captcha: '',
showPwd: false // 默认不显示
}
handleEmail = (event) => {
this.setState({
email: event.target.value
})
}
handleCaptcha = (event) => {
this.setState({
captcha: event.target.value
})
}
handlePwd = (event) => {
this.setState({
pwd: event.target.value
})
}
changeShowPwd = () => {
this.setState({
showPwd: !this.state.showPwd
})
}
goLogin = () => {
const {email, pwd, captcha} = this.state;
if (!email || !pwd) {
alert('邮箱或密码错误', '请输入正确的邮箱', [
{
text: '取消', onPress: () => {
this.setState({
email: '',
pwd: '',
captcha: '',
})
}
},
{
text: '确定', onPress: () => {
this.setState({
email: '',
pwd: '',
captcha: '',
})
}
},
]);
return
} else if (captcha.toLowerCase() !== 'wk3v') {
alert('验证码错误提示', '验证码不正确', [
{
text: '取消', onPress: () => {
this.setState({
captcha: '',
})
}
},
{
text: '确定', onPress: () => {
this.setState({
captcha: '',
})
}
},
]);
return
} else {
this.props.history.replace('/home');
}
}
render() {
const {email, pwd, showPwd, captcha} = this.state
return (
<div className='emailLogin'>
<ShiwuHeader/>
<div className="loginWrap loginWrap-1">
<div className="view">
<div className="logo">
<img src="http://yanxuan.nosdn.127.net/bd139d2c42205f749cd4ab78fa3d6c60.png" alt="logo"/>
</div>
<div className="userBox">
<section className="login_message">
<input type="text" value={email} onChange={this.handleEmail} placeholder='请输入邮箱账号'/>
</section>
<section className="login_verification">
{
showPwd ? (
<input type="text" value={pwd} onChange={this.handlePwd} placeholder='请输入密码'/>
) : (
<input type="password" value={pwd} onChange={this.handlePwd} placeholder='请输入密码'/>
)
}
<div className={showPwd ? 'switch_button on' : 'switch_button off'} onClick={this.changeShowPwd}>
<div className={showPwd ? 'switch_circle right' : 'switch_circle'}></div>
<span className="switch_text">{showPwd ? 'abc' : '...'}</span>
</div>
</section>
<section className="login_message">
<input type="text" placeholder="验证码" value={captcha} onChange={this.handleCaptcha}/>
<img className="get_verification" src={codeImg} alt="captcha"
style={{width: 150, right: 20}}/>
</section>
<section className="login_hint">
<span>注册账号</span>
<span>忘记密码</span>
</section>
</div>
<div className="btnWrapper">
<div className="btn btn-xl btn-block phone-login" onClick={this.goLogin}>
<span>登录</span>
</div>
<div className="btn btn-xl btn-block email-login"
onClick={() => this.props.history.replace('/profile')}>
<span>其他登录方式</span>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default withRouter(EmailLogin)
<file_sep>/src/containers/phoneLogin/PhoneLogin.jsx
/*
手机登录组件
*/
import React, {Component} from 'react'
import {withRouter} from 'react-router-dom'
import {Modal} from 'antd-mobile'
import ShiwuHeader from '../../components/shiwuHeader/ShiwuHeader'
import './phoneLogin.styl'
const {alert} = Modal
class PhoneLogin extends Component {
state = {
phone: '', // 手机号
code: '' // 验证码
}
// 手机号输出框值发生改变
phoneNumber = (event) => {
this.setState({
phone: event.target.value
})
}
// 手机验证码
phoneCode = (event) => {
this.setState({
code: event.target.value
})
}
// 验证手机号是否符合规范
isRightPhone = () => {
return /^1[34578]\d{9}$/.test(this.state.phone)
}
// 登录
goLogin = () => {
// 正则验证
const reg = /^1[34578]\d{9}$/
if (!reg.test(this.state.phone)) { // 手机号不符合规范
alert('提示', '手机号格式不正确', [
{
text: '取消', onPress: () => {
this.setState({
phone: '',
code: ''
})
}
},
{
text: '确定', onPress: () => {
this.setState({
phone: '',
code: ''
})
}
}
])
return
} else if (!/^\d{6}$/.test(this.state.code)) {
alert('提示', '请输入6位数字验证码', [
{
text: '取消', onPress: () => {
this.setState({
code: ''
})
}
},
{
text: '确定', onPress: () => {
this.setState({
code: ''
})
}
}
]);
return;
} else {
this.props.history.replace('/home')
}
}
render() {
const {phone, code} = this.state
return (
<div className='phoneLogin'>
<ShiwuHeader/>
<div className="loginWrap loginWrap-1">
<div className="view">
<div className="logo">
<img src="http://yanxuan.nosdn.127.net/bd139d2c42205f749cd4ab78fa3d6c60.png" alt="logo"/>
</div>
<div className="userBox userBox-1">
<section className="login_message">
<input type="text" value={phone} onChange={this.phoneNumber} placeholder='请输入手机号'/>
</section>
<section className="login_verification">
<input type="text" value={code} onChange={this.phoneCode} placeholder='请输入验证码'/>
<div className="getWrap">
<a className="getsmscode" ref='getCode' onClick={this.getCode}>获取验证码</a>
</div>
</section>
<section className="login_hint">
<span>遇到问题?</span>
<span>使用密码验证登录</span>
</section>
</div>
<div className="btnWrapper">
<div className="btn btn-xl btn-block phone-login" onClick={this.goLogin}>
<span>登录</span>
</div>
<div className="btn btn-xl btn-block email-login"
onClick={() => this.props.history.replace('/profile')}>
<span>其他登录方式</span>
</div>
<div className="register" onClick={() => this.props.history.replace('/profile')}>
<span>注册账号 ></span>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default withRouter(PhoneLogin)
<file_sep>/src/containers/home/supply/Supply.jsx
/*
品牌制造商直供supply
*/
import React, {Component} from 'react'
import LazyLoad from 'react-lazyload'
import ModelHeader from '../../../components/modelHeader/ModelHeader'
import './supply.styl'
export default class Supply extends Component {
render() {
const tagList = this.props.data
return (
<div>
<ModelHeader/>
<div className="supplying">
<ul className="list">
{
tagList ? (tagList.map(item => {
return (
<li className="item" key={item.id}>
<a href="javascript:;">
<div className="cnt">
<h4 className="title">{item.name}</h4>
<div>
<span className="price1">{item.floorPrice}</span>
<span className="price2">元起</span>
</div>
{item.newOnshelf ? (<i className="icon icon-new"></i>) : null}
</div>
<LazyLoad>
<img src={item.picUrl} alt=''/>
</LazyLoad>
</a>
</li>
)
})) : null
}
</ul>
</div>
</div>
)
}
}
<file_sep>/src/containers/home/Home.jsx
/*
首页路由组件
*/
import React, {Component} from 'react'
import Swiper from 'swiper'
import {connect} from 'react-redux'
import LazyLoad from 'react-lazyload'
import ReactCssTransitionGroup from 'react-addons-css-transition-group'
import {getHomeData, getTopicData, getNavData} from '../../redux/actions'
// 引入样式
import './home.styl'
// 引入自定义模块组件
import HomeHeader from '../../components/homeHeader/HomeHeader'
import Carousel from './carousel/Carousel'
import Supply from './supply/Supply'
import Split from '../../components/split/Split'
import LimitTimeBuy from '../../components/limitTimeBuy/LimitTimeBuy'
import Weal from '../../components/weal/Weal'
import FooterGuide from '../../components/footerGuide/FooterGuide'
import GoTop from '../../components/goTop/GoTop'
class Home extends Component {
state = {
isShow: false, // 默认不显示
scrollTop: 0 // 滚动位移
}
componentDidMount() {
this.props.getHomeData()
window.addEventListener('scroll', this.handleScroll);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll);
}
handleScroll = (e) => {
// console.log('浏览器滚动事件', window.pageYOffset)
if (window.pageYOffset >= 800) {
this.setState({
isShow: true,
scrollTop: window.pageYOffset
});
} else {
this.setState({
isShow: false,
scrollTop: window.pageYOffset
})
}
}
componentDidUpdate() {
new Swiper('.homeCarousel', {
slidesPerView: 'auto',
centeredSlides: false,
zoom: true
})
new Swiper('.homeCarousel-topic', {
slidesPerView: 'auto',
centeredSlides: false,
spaceBetween: 30
})
}
render() {
const {isShow, scrollTop} = this.state
const {homeData} = this.props
const {focusList, tagList, newItemNewUserList, popularItemList, flashSaleIndexVO, topicList, cateList} = homeData;
return (
<div className='home' ref='home'>
{/* 头部:搜索导航 */}
<HomeHeader/>
{/* 首页轮播图 */}
<Carousel data={focusList}/>
<Split/>
{/* 品牌制造商直供 */}
<div className='template'>
<Supply data={tagList}/>
</div>
<Split/>
{/* 新品首发 */}
<div className='template'>
<div className='newItems'>
<header className="hd">
<a className="more" href="javascript:;">
<span>新品首发</span>
<div className="all">
<span className="wrap">
<span>查看全部</span>
<i className="arrow-right"></i>
</span>
</div>
</a>
</header>
<div className="goodGrid goodGrid-goodsList">
<div className="inner swiper-container homeCarousel">
<div className="list swiper-wrapper">
{
newItemNewUserList ? (
newItemNewUserList.map(item => {
return (
<div className="item swiper-slide" key={item.id}>
<a className="good" href="javascript:;">
<div className="hd">
<div className="wraper">
<img src={item.listPicUrl}/>
</div>
<div className="desc">{item.simpleDesc}</div>
</div>
<div className="tagWrapper">
<p className="status anniversary">七夕推荐</p>
</div>
<div className="name">
<span>{item.name}</span>
</div>
<div className="newItemDesc">{item.simpleDesc}</div>
<div className="price">
<div>
<span>¥{item.retailPrice}</span>
</div>
</div>
<span></span>
<div className="specification">
<div>3</div>
<div>色</div>
<div>可</div>
<div>选</div>
</div>
</a>
</div>
)
})
) : null
}
<div className="item swiper-slide more">
<a href="javascript:;" style={{display: 'block', width: '100%', height: '100%',}}>
<span className="text">查看全部</span>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
<Split/>
{/* 人气推荐 */}
<div className="template"> {/*加一个类template,给组件添加背景色白色*/}
<div className='popularItemList'>
<header className="hd">
<a className="more" href="javascript:;">
<span>人气推荐 · 好物精选</span>
<div className="all">
<span className="wrap">
<span>查看全部</span>
<i className="arrow-right"></i>
</span>
</div>
</a>
</header>
<div className="goodGrid goodGrid-goodsList">
<div className="inner swiper-container homeCarousel">
<div className="list swiper-wrapper">
{
popularItemList ? (
popularItemList.map(item => {
return (
<div className="item swiper-slide" key={item.id}>
<a className="good" href="javascript:;">
<div className="hd">
<div className="wraper">
<img
src={item.listPicUrl}/>
</div>
<div className="desc">{item.simpleDesc}</div>
</div>
<div className="tagWrapper">
<p className="status anniversary">七夕推荐</p>
</div>
<div className="name">
<span>{item.name}</span>
</div>
<div className="newItemDesc">{item.simpleDesc}</div>
<div className="price">
<div>
<span>¥{item.retailPrice}</span>
</div>
</div>
<span></span>
<div className="specification">
<div>3</div>
<div>色</div>
<div>可</div>
<div>选</div>
</div>
</a>
</div>
)
})
) : null
}
<div className="item swiper-slide more">
<a href="javascript:;" style={{display: 'block', width: '100%', height: '100%',}}>
<span className="text">查看全部</span>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
<Split/>
{/* 限时购 */}
<LimitTimeBuy data={flashSaleIndexVO}/>
<Split/>
{/* 福利社 */}
<Weal/>
<Split/>
{/* 专题精选 */}
<div className="template">
<header className="hd">
<a className="more" href="javascript:;">
<span>专题精选</span>
<i className="icon icon-go"></i>
</a>
</header>
<div className="indexTopics-slide">
<div className="inner swiper-container homeCarousel-topic">
<ul className="list swiper-wrapper">
{
topicList ? (topicList.map(item => {
return (
<li className="item swiper-slide" key={item.id}>
<a className="imgWrap" href="javascript:;">
<img src={item.itemPicUrl} alt=""/>
</a>
<div className="line1">
<h4 className="title">{item.title}</h4>
<span className="price">{item.priceInfo}元起</span>
</div>
<div className="desc">{item.subtitle}</div>
</li>
)
})
) : null
}
</ul>
</div>
</div>
</div>
<Split/>
{/* 居家好物 */} {/* 遍历所有好物组件 */}
{
cateList ? (
cateList.map(list => {
return (
<div key={list.id}>
<div className="template">
<div className="titleGoodGrid">
<h3 className="title">{list.name}好物</h3>
<div className="goodGrid">
<ul className="list">
{
list.itemList.slice(0, 7).map(item => {
return (
<li className="item" key={item.id}
style={{
zIndex: '6',
padding: '0rem 0.26666666666666666rem 0.44rem 0.13333333333333333rem'
}}>
<a className="good" href="javascript:;">
<div className="hd-jujia">
<div className="wraper">
<img
src={item.listPicUrl}
alt=""/>
<div className="desc">{item.simpleDesc}</div>
</div>
</div>
<div className="tagWrapper">
<p className="status gradientPrice">{list.name}特惠</p>
</div>
<div className="name">
<span>{item.name}</span>
</div>
<div className="newItemDesc">{item.simpleDesc}</div>
<div className="price">
<span>¥{item.retailPrice}</span>
</div>
<span></span>
<div className="specification">
<div>3</div>
<div>色</div>
<div>可</div>
<div>选</div>
</div>
</a>
</li>
)
})
}
<li className="item item-more">
<a className="more moreH" href="javascript:;">
<p className="txt">更多{list.name}好物</p>
<i className="icon icon-goodGridMore"></i>
</a>
</li>
</ul>
</div>
</div>
</div>
<Split/>
</div>
)
})
) : null
}
{/* 回到顶部 */}
<GoTop isShow={isShow} scrollTop={scrollTop}/>
{/* 底部导航栏 */}
<FooterGuide/>
</div>
);
}
}
// connect包装UI组件为容器组件
export default connect(
// 更新获取状态
state => ({homeData: state.homeData}),
// 异步action,通知actions对象,发送ajax请求
{getHomeData, getTopicData, getNavData}
)(Home)
<file_sep>/src/containers/shiwu/shiwuNavBanner/ShiwuNavBanner.jsx
/*
识物页面导航轮播图
*/
import React, {Component} from 'react'
import Swiper from 'swiper'
import './shiwuNavBanner.styl'
export default class ShiwuNavBanner extends Component {
componentDidUpdate () {
new Swiper('.swiper-container-banner2', {
slidesPerView: 'auto',
centeredSlides: false
})
}
render () {
const {column} = this.props
return (
<div className="exploreChannels">
<div className="swiper-container-banner2">
<div className="list swiper-wrapper">
{
column ? (
column.map((item, index) => {
return (
<a className="item swiper-slide" key={index} href="javascript:;">
<div className="imgContainer channelPic"
style={{backgroundImage: 'url('+ item.picUrl +')'}}
></div>
<div className="icon icon-rbGradient">
<p className="topNum">{item.articleCount}</p>
</div>
<div className="title">{item.title}</div>
</a>
)
})
) : null
}
</div>
</div>
</div>
)
}
}
| c0245f99d97131edd46629deab028f66c867dc8d | [
"Markdown",
"JavaScript"
] | 19 | Markdown | weiyufangchen/yanxuan-react | 3ff0cf819f378e147800c17c7e7708c428e6d1c2 | 4c98ab73d7867a09a2f41ad2a9691b9036d0bb11 | |
refs/heads/master | <repo_name>erodriguezv/LocalScripts<file_sep>/deploy.py
#!/usr/bin/python
import sys
import os.path
import os
# ######################################################################
# we define the environments
environments = {
"dev": {
"host": "switch.zion",
"user": "zato",
"pickup": "/zato/dev/server1/pickup-dir/"
},
"qa": {
"host": "dillard.zion",
"user": "zato",
"pickup": "/zato/qa/server1/pickup-dir/"
}
}
environments['d'] = environments['dev']
environments['q'] = environments['qa']
# ######################################################################
# utility functions
def display_syntax():
print '''
Usage:
deploy <env> <file1> <file2> .. <filen>
'''
def deploy(env, file_list):
print "Deploying"
command = "scp {0} {1}@{2}:{3}".format(
' '.join(file_list),
environments[env]['user'],
environments[env]['host'],
environments[env]['pickup']
)
print command
os.system(command)
# ######################################################################
# validations
if len(sys.argv) < 3:
print "\nPlease specify at least one file"
display_syntax()
sys.exit(-1)
env = sys.argv[1].lower()
if env not in ['dev', 'd', 'qa', 'q']:
print "\nNot a valid environment."
display_syntax()
sys.exit(-1)
file_list = []
missing_file = False
for arg in sys.argv[2:]:
arg = arg.replace('./', '')
if '/' in arg:
print "The script only works for files in the current directory"
missing_file = True
else:
if not os.path.exists(arg):
missing_file = True
print 'File does not exist: {0}'.format(arg)
else:
file_list.append(arg)
if missing_file:
print "Exiting"
sys.exit(-1)
# ######################################################################
# now we deploy
deploy(env, file_list)
| 9676a0026f1cd2c96b92d446964c26d504293fba | [
"Python"
] | 1 | Python | erodriguezv/LocalScripts | b67d0e2d2cf77e44857f4d0c9d76f1c0769a85f1 | 1286b906a044a4a68238ccb361e69fd6ce6cc5a1 | |
refs/heads/master | <repo_name>lbenvenutoc/cibertec-java-adv<file_sep>/src/main/java/pe/edu/cibertec/dao/impl/UserDaoImpl.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package pe.edu.cibertec.dao.impl;
import org.springframework.stereotype.Repository;
import pe.edu.cibertec.dao.UserDao;
/**
*
* @author francisco
*/
@Repository("francisco")
public class UserDaoImpl implements UserDao{
public void list() {
System.out.println("Obteniendo la lista de usuarios");
}
}
| 5bd42c29352b9c8136363d10de4e00498b185894 | [
"Java"
] | 1 | Java | lbenvenutoc/cibertec-java-adv | 99e4d7c3116da4c5e7c77809a4b8b4a1e93fb7fd | 02a2f4b3a3589fcef0eb111ad5bdcd2bfeb02b9b | |
refs/heads/master | <repo_name>JavaJames93/next-express-strapi-base<file_sep>/app/next.config.js
require("dotenv").config();
module.exports = {
exportPathMap: function () {
return {
'/': { page: '/' }
}
},
env: {
API_URL: process.env.API_URL
}
}<file_sep>/app/src/pages/section.js
import React from 'react';
import { useRouter } from 'next/router';
import { useQuery } from "@apollo/react-hooks";
import Query from '../components/query';
import GET_SECTION from '../apollo/queries/sections/section';
export default props => {
const router = useRouter();
const { data, loading, error } = useQuery(GET_SECTION, {
variables: { sectionId: parseInt(router.query.section) }
});
if (loading) return <div>Loading...</div>;
if (error) return <p>ERROR: {error.message}</p>;
if (!data) return <p>Not found</p>;
if (data) console.log(data);
return (
<>
{data.section &&
<h3>Testing new Page: {data.section.title}</h3>
}
</>
);
}<file_sep>/README.md
# next-express-strapi-base
This repository contains the base code for an application that uses the following tech stack:
- Node.js App
* Next.js
* Express.js
* GraphQL
* Apollo
- Strapi (*Headless CMS*)
* GraphQL
<file_sep>/app/src/pages/_app.js
import React, { useEffect } from 'react';
import Head from 'next/head';
import { ApolloProvider } from '@apollo/react-hooks';
import withData from '../utils/apollo';
import { ThemeProvider, makeStyles } from '@material-ui/core/styles';
import CssBaseline from '@material-ui/core/CssBaseline';
import Container from '@material-ui/core/Container';
import theme from '../theme';
import Navbar from '../components/Navbar';
import Layout from '../components/Layout';
const useStyles = makeStyles(theme => ({
root: {
display: 'flex',
},
toolbar: theme.mixins.toolbar,
content: {
flexGrow: 1,
backgroundColor: theme.palette.background.default,
//backgroundColor: '#ccdff5',
padding: theme.spacing(3),
paddingTop: theme.spacing(6)
},
progress: {
margin: theme.spacing(2),
}
}));
const App = ({ Component, pageProps, apollo }) => {
const classes = useStyles();
useEffect(() => {
// Remove the server-side injected CSS.
const jssStyles = document.querySelector('#jss-server-side');
if (jssStyles) {
jssStyles.parentElement.removeChild(jssStyles);
}
}, []);
return (
<ApolloProvider client={apollo}>
<Head>
<title>Clin One</title>
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="<KEY>" crossOrigin="anonymous" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" />
</Head>
<ThemeProvider theme={theme}>
{/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
<CssBaseline />
<Layout>
<Navbar />
<Container className="p-4">
<div className={classes.toolbar} />
<Component {...pageProps} />
</Container>
</Layout>
</ThemeProvider>
</ApolloProvider>
)
}
// Wraps all components in the tree with the data provider
export default withData(App); | 716edbb8ec834b8550b1e5a73b61a66c9ecbe9c9 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | JavaJames93/next-express-strapi-base | df7e9f2492a6abe75df0e732df7d2c478f6774e0 | cad21fab519dd750956c943e9ece767f405bcc08 | |
refs/heads/master | <file_sep># MyWebApp
This is a series of pages to show off my skills learned from the UDEMY Web development Couse.
List of features:
1. Search for movies, series and games from the IMDb website. The search will return a grid of posters. You can click on each poster to retrieve more informaiton about the chosen item.
<file_sep>$( document ).ready(function() {
var currentPage = 0;
var maxPageCount = 0;
$("#searchSubmit").bind("click", function(){
clearDivHTML();
getSearchResults();
});
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
getSearchResults();
}
});
function clearDivHTML (){
$("#imdb_results")[0].innerHTML = "";
currentPage = 0;
}
function getSearchResults(){
var name = $("input[name=name]").val();
var year = $("input[name=year]").val();
if (year === "") {
year = "-1";
}
var category = $("input[name=category]:checked").val();
currentPage += 1;
if (currentPage === 1 || (currentPage > 1 && currentPage <= maxPageCount)) {
$.ajax({
type : "GET",
url : "/movieSearch/" + name + "/" + year + "/" + category + "/" + currentPage,
success: function(result){
displayReuslts(result);
},
error : function(e) {
console.log("ERROR: ", e);
}
});
} else {currentPage -= 1;}
}
function displayReuslts(movieResults){
var rowDiv = $("#imdb_results")[0];
if (movieResults.Response === "True") {
var newResults = "";
if (currentPage === 1) {
rowDiv.innerHTML = "";
maxPageCount = Math.ceil(movieResults.totalResults/10);
}
$.each(movieResults.Search, function(i, movie){
var rowHTML = getRowHTML(movie);
newResults += rowHTML;
});
rowDiv.innerHTML += newResults;
} else {
rowDiv.innerHTML = "<h1>No Results Found</h1>";
}
}
function getRowHTML(movie){
var request = "'/imdb_page/" + movie.imdbID + "'";
var onClickAttr = "window.location.href = " + request;
var onClickString = "onclick= \"" + onClickAttr + "\"";
var rowHTML = "";
if (movie.Poster !== "N/A"){
rowHTML = "<div id='indivResult' class='col-md-3' " + onClickString + "><div class='thumbnail'><img src='" + movie.Poster + "'><div class='caption'>" + movie.Title + "</div></div></div>";
return rowHTML;
} else {
rowHTML = "<div id='indivResult' class='col-md-3' " + onClickString + "><div class='thumbnail'><h3>" + movie.Title + "</h3><div class='caption'>" + movie.Title + "</div></div></div>";
return rowHTML;
}
}
}); | 7175dbeaa31abda69f08e2f27a2beb399da1b0ca | [
"Markdown",
"JavaScript"
] | 2 | Markdown | peterjdrb/MyWebApp | ad27f4c1120e5e5b16265457d97f6a01b46a3f89 | c9d5b6db75e76e7dbc446e715e346225ab080f3b | |
refs/heads/master | <file_sep>$('.emailUs').on('click', function(ev){
ev.preventDefaults;
window.location.href = 'mailto:<EMAIL>?subject=ContactUs&=Hello,';
});
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 39.6400, lng: -86.8630},
zoom: 16,
});
var marker = new google.maps.Marker({
position: {lat: 39.6409, lng: -86.86357},
map: map,
title: 'Cafe Roy',
});
var contentString = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h4 id="firstHeading" class="firstHeading">Cafe Roy</h4>'+
'<div id="bodyContent">'+
'<p><b>Cafe Roy</b>, is located on the northeastern part of Roy\'O West Library. If you would like to enjoy a warm cup of coffee, or a refreshing snack, stop by.</p>'+
'<a href="index.html">Home</a> '+
'</div>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
}
<file_sep>## Cafe Roy
As part of Project 1 for my Web Development and CyberSecurity class we designed a website for DePauw University's Cafe Roy. Cafe Roy's website has as much information that we could find based on their webpage [Bon Appetit](http://depauw.cafebonappetit.com/cafe/cafe-roy/).
#### Contributors:
+ [<NAME>](https://github.com/reynathangray)
+ [<NAME>](https://github.com/rrami17)
+ [<NAME>](https://github.com/elenagonzalez17)
#### Development Environment
+ HTML
+ CSS
+ JavaScript
#### Additional Resources
+ Google Maps API was used to display a map with a marker on a specific longitude and latitude location.
#### [Live Demo](https://mklic17.github.io/cafe-roy/)
| 850011567abe7df3a9d0b7474c760660d2d3e258 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | mklic17/cafe-roy | 6c88c92adb7a4bd8231fb883f64a6db89877a803 | 6c8ed07f0fd60243d5a2b12bfdb501c0e72c2a70 | |
refs/heads/master | <file_sep>---
layout: post
selection: music
lang: en
permalink: /music/
---
# Music
Music is one of the things I like the most of all. All about it.<br />
I've struggled a lot to be able to play guitar decently enough. The guitar is my musical instrument, is the one I know the best, I feel comfortable playing it, although I'm far from being a virtuoso. On the other side machines, knobs, technical equiment and the recording process came to me as a very natural and intuitive thing. Its use has never been a struggle. My first approach to these was because I was trying to understand why the recordings I did were so crappy. I began to obsessively research and study music technology and the recording and mixing process. This took me to produce serval records for different bands/projects, altough the first ones were guinea pigs.
Music production places me in a very similar position as the one I usually take when dealing with visual arts or commissioned/commercial jobs; the one in between the artistic side of things and the technical ones, allowing fluent communication between these, directing the artistic decisions as well as making sure that the technical ones are always taken to according to the artistic direction. More over, on top of this practical functionality it has a very vast territory for expression, becoming an art by itself. I still don't completely understand music, so far I just understand the technical process of recording and producing, yet there's a lot more that I need to understand.
I am a founding member of the online record label [Uva Robot](http://www.uvarobot.cl) through which several of these recordings have been published.
Some of these recordings:
## [variosArtistas](http://www.variosartistas.cl)
This is my band. I produced, recorded, mixed and played guitar
<iframe style="border: 0; width: 600px; height: 120px;" src="https://bandcamp.com/EmbeddedPlayer/album=2628341229/size=large/bgcol=ffffff/linkcol=0687f5/artwork=small/tracklist=false/transparent=true/" seamless><a href="http://uvarobot.cl/album/gol-o-penal">Gol o Penal by VariosArtistas</a></iframe>
<iframe style="border: 0; width: 600px; height: 120px;" src="https://bandcamp.com/EmbeddedPlayer/album=1725314539/size=large/bgcol=ffffff/linkcol=0687f5/tracklist=false/artwork=small/transparent=true/" seamless><a href="http://uvarobot.cl/album/abandonan-europa">Abandonan Europa by VariosArtistas</a></iframe>
## [Tus Amigos Nuevos](http://www.tusamigosnuevos.com)
I produced, recorded, mixed and mastered this album.
<iframe style="border: 0; width: 600px; height: 120px;" src="https://bandcamp.com/EmbeddedPlayer/album=3402165205/size=large/bgcol=ffffff/linkcol=0687f5/tracklist=false/artwork=small/transparent=true/" seamless><a href="http://uvarobot.cl/album/no-s-son">NO SÍ SON by Tus Amigos Nuevos</a></iframe>
## others
There are several others that were not published propperly and can't find online.:(
<file_sep>---
layout: page
title: About
permalink: /about/
---
# Bio
<NAME> is an artist that works with technology in the Arts field; from video and moviemaking, to interactive installations and music, striving to make an intelligent use of it. Code and computers are his primary tools.
His artistic and creative curiosity alongside with his inborn aptitudes for math and sciences as well as for leadership, establishes him in a position in which he can act, both as a, leader and bridge in multidisciplinary teams and endeavors. He enjoys challenges, especially if this means to learn new things and embark towards uncertain results.
He is an active contributor to the artistic oriented coding toolkit [openFrameworks](http://openframeworks.cc).
On 2010 he created his own new-media design studio, called Macrobio, in Santiago, Chile. Here, he and his team work mixing code with motion graphics and video, to create interactive installations and experiences. On early 2014, Macrobio was split up due to different business points of view. Then he refocused his practice from strictly commercial to more artistic oriented and personal work. As such he has just shown his work in just a few collective exhibitions.
On fall 2015 he assisted to the [School For Poetic Computation](http://sfpc.io) in New York City.
He was one of the main developers and artists contributing to [SFPC's Re-coded](https://roymacdonald.github.io//projects/2017/11/15/SFPCs-Recoded-Project.html) collaborative and collective project, which has been shown at Dayfornight festival 2015, Houston, Texas, Google I/O 2016 in Mountain View, California, Sonar Festival 2017, Barcelona, Spain, MicrosoftConnect 2017 and SFPC's 7 years anniversary exhibition (2020) both in New York City.
During March and April 2016 he was teaching creative coding at [OF COURSE](http://http://ofcourse.io/) in Shanghai, China.
Since 2018 Roy has [been](https://roymacdonald.github.io//projects/2018/04/09/Luminus_Prospectus_Mavi.html) [collaborating](https://roymacdonald.github.io//projects/2018/12/19/Invocacion.html) with the Santiago-based light-art collective [Trimex Collective](https://www.trimex.cl).
During the summer of 2018 he was part of the first Computational Arts Residency setup by the Department of Computing at Goldsmiths, University of London and the Victoria and Albert Museum Digital Programmes. The results of this residency was shown at the Digital Design Weekend exhibition in the Victoria and Albert Museum in London.
On September 2018 [his work](https://roymacdonald.github.io//projects/2018/09/01/Defective-Apparatus_v1.2.html) was shown at Ars Electronica Festival in Linz,Austria.
From August 2019 to late February 2020, was a "Someting in Residence" at [RunwayML](https://runwayml.com/) doing [some](https://roymacdonald.github.io//projects/2020/08/21/SyleGAN_Mixer.html) [experiments](https://roymacdonald.github.io//projects/2020/08/19/How_NOT_to_train_your_GAN.html) with Machine Learning.
Currently he is residing in Santiago, Chile.
Drop me a line: macdonald.roy (at) (the electronic mail from the big G).
# Artist Statement
I’d say that my ultimate interest is knowledge, while my ultimate goal is being able to make something with the knowledge I’ve gained.
As I try to understand the world that surrounds me, I gain knowledge.
Software has become a tool for me to understand my life.
Even when I might change the specific subject of my research, these tend to fall on relatively well defined area; arts, design, sciences and maths. I’ve explored movie-making and video art, interactive installations, motion-graphics design, physics, camera optics, music and electronics among others, all with a heavy emphasis on technology. Code and computers have become my primary tools, creation canvas and exploration vehicles.
Software and code works over digital “matter”, even when it is only comprised of zeros and ones, its possible configurations are nearly infinite. As an artist I have the ability to change the way in which this digital matter is usually presented to us -either by exaggerating, changing the point of view or establishing new relationships between the matter itself- it is possible not only to reveal new aspects of the world but also state our position towards it or the impact of personal experience over this perception.
Coding also allows me to create tools for myself and for others, hopefully providing new or improving the existing ones. As such, sharing -knowledge and experience- has become an important aspect of my artistic practice, which embodies in teaching, giving workshops, working with or helping other artists and creators, as well as actively participating in open-source software communities online.
The way we experience our world has become hugely mediated by electronic technology. Approaching and forcing the limits of technologies is not a practice particular to artists, although I think there is no better position from which to pursue such as it is from the arts field and the artist’s mind set, especially when dealing with nascent technologies. This position is probably the only one where usefulness is not a question, bold moves are encouraged, taking risks is desirable, failure can be a gift and uncertain results can be sublime.
<file_sep>---
layout: blog
selection: blog
title: blog
permalink: /blog/
---
# Blog
<file_sep>---
layout: post
date: 2015-01-01 12:10:00
categories:
- projects
tags: interactive
thumb: /thumbs/moduloFAV.jpg
title: "Aparato defectuoso: Se rehúsa a comportarse según sus normas originales e insiste en evitar a las personas. parte 1"
WIP: true
FAIL: true
lang: es
---
Fui invitado a mostrar algo en el [Festival de las Artes de Valparaiso, FAV](http://festivalartesvalpo.cl/actividades/aparato-defectuoso/), que ocurrió en Enero de 2015.
En ese entonces me encontraba trabajando en la idea de una máquina defectuosa que no es capaz de hacer su trabajo pero que sigue funcionando, por lo tanto produce algo inútil, en el sentido de su uso original, lo cual en consecuencia cae en el ámbito de las artes.
El rayo láser, según el código hollywoondense, funciona simutáneamente como delimitador de espacios y sistema de detección de intrusos. En el caso de este trabajo el rayo láser pierde su uso original ya que adquiere una fobia hacia las personas, evitandolas constantemente.
Esta instalación consistia en 16 módulos, cada uno con un espejo y dos motores servo. El espejo puede apuntar en cualquier dirección dentro de una semi esfera.
Éstos fueron instalados en una intersección de dos calles en Valparaiso, ubicando 4 módulos en cada una de las cuatro esquinas en postes del alumbrado público. Un láser verde apuntaba a uno de estos espejos y rebotaba hacia otro espejo, luego al siguiente y así sucesivamente hasta rebotar en todos los espejos. Dado que los espejos podían apuntar en cualquier dirección, la ruta de rebotes podía ser modificada; cada vez que alguien o algo bloquea el rayo el sistema reconfigura sus espejos para que el rayo evite la ruta bloqueada, generando una nueva delimitación espacial.
Hasta este punto todo suena muy bien pero desafortunadamente esta instalación fue un fracaso. Tuve muy poco tiempo para construir y programar estoy y un presupuesto bastante escaso.
Dado el escaso presupuesto utilicé motores servos usados, los cuales se comportaron de manera inesperada, haciendo el proceso de calibración imposible. Mi intención era probar todo de antemano en mi estudio pero dado el tiempo limitado no pude hacerlo. Además de esto me di cuenta muy tarde de que la precisión de los motores servo es baja, de hecho sumamente baja, como para poder establecer todas las rutas de rebote posibles. Encima de esto tuve tan solo un día para montar todo el sistema, me demoró más de lo esperado y finalmente cuando estaba calibrando todo el sistema los servo se comportaban erráticamente y finalmente no fue posible configurar todo el sistema. Más aun el aire se encontraba con poquisimas partículas aquel día en particular, donde usualmente hay una leve neblina y humedad ya que Valparaiso es una ciudad costera, lo cual causó que el rayo fuese imperceptible.
Esto no fue divertido. Fue sumamente frustrante. Aun así quiero terminar este proyecto y hacerlo funcionar. Hasta ahora mi limitante es el presupuesto.
### Actualización
Postule este proyecto para desarrollarlo y construirlo en una residencia de artes computacionales en la Universidad de Goldsmiths en Londres, entre Julio y Septiembre de 2018. Esta obra será exhibida en el Museo Victoria and Albert en Londres, en septiembre de 2018.
### Images


<file_sep>---
layout: post
date: 2017-09-08 12:10:00
categories:
- projects
tags: xdefault, data visualization, interactive
thumb: /thumbs/proyectodefault.png
video_vimeo: 238460122
video_width: 958
video_height: 539
title: Default
subtitle: Visualización interactiva de actividad cerebral en reposo.
galery_data: proyectodefault
galery_name: Imágenes Montaje
lang: es
---
Participé del proyecto Default haciendo el diseño y programación de la visualización, así como asesorar en temas de interactividad.
Sitio proyecto [xdefault.cl](xdefault.cl)
Default es una obra interactiva e inmersiva sobre la actividad cerebral en reposo. Fue el resultado de un proyecto de diálogo interdisciplinario entre Manuela Garretón, Diseñadora y Tomás Ossandón, Neurocientífico. Anteriormente se asumía que la actividad basal del cerebro —aquella que precede al estímulo— no tenía importancia. Sin embargo, la evidencia muestra algo sorprendentemente diferente: el cerebro utiliza gran cantidad de energía cuando no responde a estímulos y tales momentos son los que ocupan la mayor parte de nuestras vidas.
Este dinamismo espontáneo depende de la Red Neuronal por Defecto (Default Mode Network-DMN). Se trata de una trama que siempre está activa, a excepción de los períodos dirigidos a realizar tareas o responder a estímulos externos. En dichos momentos se desconecta transitoriamente. Esta red integra memorias de nuestras vidas por lo tanto, podría explicar muchas dudas sobre la autoconciencia y procesos tan importantes como la creatividad.
Default se plantea como un ambiente visual y sonoro a partir de datos registrados en un examen de resonancia magnética functional (el cual se utiliza para estudiar la actividad cerebral) de una persona en estado de reposo. La sala en la que fue expuesto se convirtió en un cerebro que, gracias a una visualización 3D, sonorización de datos y un diseño espacial y de interacción, permiten conocer los estados cerebrales de una experiencia humana que todos vivimos pero sin ser conscientes de ello.
El propósito de Default fue cautivar a la audiencia desde el goce estético y que a la vez despierte la curiosidad sobre los estados más internos de la mente.
Equipo:
* **<NAME>**: Dirección e investigación
* **<NAME>**: co-investigador
* **<NAME>**: Diseño y programación de visualizacion
* **<NAME>**: Diseño sonoro
* **<NAME>**: Investigador Asistente (Diseño)
* **<NAME>**: Programación interacción
* **<NAME>**: Programación interacción
Obra realizada con el aporte de la dirección de Artes y Cultura, Vicerrectoría de Investigación de la Pontificia Universidad Católica de Chile.
## Proceso
<iframe src="https://player.vimeo.com/video/248526680?title=0&byline=0&portrait=0" width="600" height="338" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
<file_sep>---
date: 2019-10-16 00:00:00 -0400
layout: post
title: Laser Tools
published: true
categories:
- code
tags: Laser, ILDA, Activism
thumb: /thumbs/lasertools.jpg
poster_img: /img/lasertools/resistencia.jpg
lang: en
---
Since 2018 I have been collaborating with the Chilean light-art collective [Trimex](https://trimex.cl/), with whom I developed a series of software tools that allow to control ILDA Lasers.
These Laser Tools I developed were intended to process video and generate laser lines that could be overlaid and mapped to a video projection.
As is can be seen in the following videos:
<div style="padding:56.25% 0 0 0;position:relative;"><iframe src="https://player.vimeo.com/video/379093206?color=65c1ac&title=0&byline=0&portrait=0" style="position:absolute;top:0;left:0;width:100%;height:100%;" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe></div><script src="https://player.vimeo.com/api/player.js"></script>
<div style="padding:28.13% 0 0 0;position:relative;"><iframe src="https://player.vimeo.com/video/427470871?title=0&byline=0&portrait=0" style="position:absolute;top:0;left:0;width:100%;height:100%;" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe></div><script src="https://player.vimeo.com/api/player.js"></script>
<br>
<h2> Laser (and text) as a tool for public manifestation and protest</h2>
With the [huge social protest](https://en.wikipedia.org/wiki/2019%E2%80%9320_Chilean_protests) that happened in Chile from October 18th, 2019 we decided that it would be a good idea to use the laser tools and equipment we as a our form of manifestation in pro of the people's protests. We had access to an ideal spot that would allow to project accross Plaza Dignidad, ground-zero for all the protest, onto a huge corporative bulding. These projections became iconic, yet anonymous, happening every day since the start of the protests for several weeks.
As the original tools were not inteded to draw typographies, the results were sub-optimal and only very short words could be rendered, as you can see in the following pictures:
<img src="/img/lasertools/unidos.jpg">
<img src="/img/lasertools/sinmiedo.jpg">
Unfortunately I was not in Chile at the time that this happened, so I could not fix it on the spot, yet I was able to grab some code I wrote for another project that was specially made for rendering letters properly and optimize the laser paths for such, allowing it to draw crisp letters with sharp angles and much longer text than before. It took me a few days to nail it as I did not have a laser with me so I had to live test the software via internet while it was actually being projected in the spot.
The following picture and videos show this new version in use
<img src="/img/lasertools/resistencia.jpg">
<img src="/img/lasertools/resistencia2.jpg">
<div style="padding:56.25% 0 0 0;position:relative;"><iframe src="https://player.vimeo.com/video/384540090?color=65c1ac&title=0&byline=0&portrait=0" style="position:absolute;top:0;left:0;width:100%;height:100%;" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe></div><script src="https://player.vimeo.com/api/player.js"></script>
<iframe width="560" height="315" src="https://www.youtube.com/embed/qRZ_FskRnWw" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<br>
<h2>Code</h2>
I intend to release the code and compiled versions for anyone to use, yet it is in a super beta state which needs a bit more work. I don't like to release software that is not ready for use.
If you want to use these tools for publicly manifesting and protesting please [contact me](https://github.com/roymacdonald/) and I can share the app and provide help.<file_sep>---
layout: post
date: 2013-12-01 12:10:00
categories:
- work
video_vimeo: 95450098
video_width: 958
video_height: 538
thumb: /thumbs/mim.jpg
title: Interactive Modules Museo Interactivo Mirador
macrobio: true
lang: en
---
We were commissioned to develop 2 interactive games for the "Elige vivir sano" (choose a healthy life)room at the Museo Interactivo Mirador, in Santiago de Chile.
The first station had two static bicycles in front of a large LCD monitor. A piece of food is presented and the users must begin pedaling in order to burn the equivalent presented food's energy.
The next one was an arcade game inspired on the classic arcade game PacMan. The user must choose the best route for just eating healthy food while keeping itself hydrated.
I developed this work while I was still working at Macrobio (I was one of the owners/partners, lead developer and project director).
<file_sep>---
layout: post
date: 2012-08-21 12:10:00
categories:
- work
tags: interactive mapping
video_vimeo: 50685633
video_width: 958
video_height: 538
thumb: /thumbs/duckhunt.jpg
title: Duckhunt Interactive Mapping for Dentyne/Trident
macrobio: true
lang: en
---
I developed this work while I was still working at Macrobio (I was one of the owners/partners, lead developer and project director). It was codeveloped with [DelightLab](http://delightlab.com/ "Delight Lab") for the Dentyne/Trident brand.
The idea was to be able to play a game similar to Nintendo's classic Duckhunt projected over the facade of the Museum of Contemporary Art at Santiago de Chile.
It was not simply projecting the game over the facade, rather every object of the scene was mapped to the building elements out of which several reacted if shot.
Several systems had to be developed for this. The aiming system development was in charge of [Ludique](http://www.ludique.cl "Ludique"). They decided to use the Nintendo Wii remote control along with a special infrared post in order to detect where it was being aimed. This system proved to be excessively precise, thanks to the calibration method being used.
The shotgun was designed and built by [<NAME>](http://www.benedictolopez.com/ "<NAME>") according to my specifications. It simulated the weight and size of a real hunting shotgun. It had the Nintendo Wiimote embedded in its front.
The gaming and mapping system was developed by myself. Because of the need of having the game elements mapped to the building this system had to be unified.
In order to play the game, users had to queue virtually by filling a form with their personal data and taking a photo of them selves using an iPad. This data and photo was transmitted to the game system in order to use it when needed.
Simultaneously there was a DSLR camera shooting photographs every time the shotgun was triggered. This images were automagically composed into a single one and uploaded to the brand's Facebook fan page.
This event took place on August 21, 2012.
There is a detailed technical explanation here.
<file_sep>function enableFutureSketchesMenu()
{
let fsMenu = document.getElementById("futureSketchesMenu");
if(fsMenu)
{
fsMenu.style = "";
fsMenu.classList.add("current")
}
window.localStorage.setItem('showFutureSketches', 'true');
let nav = document.querySelector(".main-nav");
if(nav){
let current = nav.querySelector(".current");
if(current != fsMenu)
{
current.classList.remove("current");
}
}
}
// document.addEventListener("DOMContentLoaded", function(event) {
window.onload = function() {
console.log(window.localStorage);
if(window.location.pathname.includes("future_sketches"))
{
console.log("future_sketches");
enableFutureSketchesMenu();
}else{
let bShowFutureSketches = window.localStorage.getItem('showFutureSketches');
console.log(bShowFutureSketches);
if (bShowFutureSketches != null && (bShowFutureSketches == "true" || bShowFutureSketches == true)){
console.log("nojsdfak sm");
enableFutureSketchesMenu();
}
}
}
//);<file_sep>---
layout: post
date: 2017-11-15 12:10:00
categories:
- projects
tags: sfpc, recoded, collaborative
thumb: /thumbs/recoded.jpg
video_vimeo: 159313947
video_width: 958
video_height: 539
title: SFPC's Re-Coded
subtitle: An open-source, collaborative, educational installation.
lang: en
---
When I was part of the School For Poetic Computation (SFPC), during the Fall of 2015, we got invited, as a collective, to make a piece for being shown at the Day For Night Festival in Houston, TX. I ended up being one of the main coders of the engine we built for it as well as providing several "re-codings". After a very successful first show in Texas, we have shown this same project at Google's IO conference in Palo Alto on 2016, at Sonar Festival in Barcelona, Spain on 2017 and at Microsoft Connect Conference in New York City on 2017. I was able to present this piece, along with some other SFPC classmates, on all these instances but Barcelona. The piece is called Re-Coded.
Re-coded is an homage to innovators such as <NAME> and <NAME> whose work exists in the space between art & technology. Celebrating these pioneers, we present reinterpreted works alongside the code that drives them.
Each sketch - a reinterpreted work - is shown on two screens side by side; the reinterpreted work itself and the code that generates it. Each sketch has several parameters that can be animated or controlled live - via a custom controller we built - that change some visual aspect of the sketch. As any of these parameters changes it highlights on the code, which creates a direct relationship between the changes in code and its visual representation.
Each sketch is on screen for around 40 seconds, then it switches to the next one. When a new sketch is shown the code is animated as if it was being typed alongside some sound effects. Once this typing ends the visuals show up.
The whole project was coded using openFrameworks. Even when it look not really complex it actually is, in order to glue together all the pieces, make it work smoothly and allow to have a lot of coders collaborating on it.
For more info head to the project's site [sfpc.io/recoded](http://sfpc.io/recoded/).
<file_sep>---
layout: post
date: 2015-10-27 12:10:00
categories:
- projects
tags: data-viz sfpc
thumb: /thumbs/flatNYC.jpg
video_vimeo: 143779655
video_width: 958
video_height: 600
title: New York City is flat... almost
lang: es
---
Esta es una visualización interactiva de las calles de la ciudad de Nueva York, que se mueve a través de éstas siguiendo el camino que realizaba en bicicleta a diario desde el [School For Poetic Computation](http://sfpc.io) (SFPC) ubicado en el East Village de Manhattan hasta Crown Heights en Brooklyn donde estaba viviendo, haciendo énfasis en la elevación de las calles.
Todos los datos de las calles fueron minados y filtrados desde G..... Street View, los cuales luego se entregan a una aplicación hecha a medida. El usuario puede rotar el punto de vista arrastrando el mouse y modificar algunos parámetros de la visualización, de los cuales el más relevante es el factor de multiplicación de la elevación. Esta obra fue presentada en la muestra final de la sesión del SFPC a la cual asistí para la cual utilicé un sistema de realidad virtual Oculus Rift en lugar de una pantalla de computador corriente.
En el otoño de 2015 llegué a la ciudad de Nueva York para asistir al School For Poetic Computation, una residencia/escuela de arte enfocada en el uso expresivo y artístico de la computación. La primera impresión que tuve de la ciudad, al menos de Manhattan, fue que era principalmente plana. No parecía haber colinas (aun cuando muchas partes tienen la palabra "Hill", colina en inglés, en su nombre) o al menos éstas eran casi indistinguibles y estaban completamente ocluidas por los inmensos edificios. Una semana después me compré una bicicleta y mi percepción cambió. Al pedalear uno puede notar las subidas y bajadas, por insignificantes que sean, ya que implica hacer un mayor o menor esfuerzo. Dada la posibilidad de la bicicleta de transladarse distancias bastante largas es que uno comienza a tener una idea más generalizada de la forma y elevación de la ciudad, lo cual desperto mi curiosidad sobre la real topología de las calles de la ciudad de Nueva York.
Visualizar las datos inalterados de las calles revela bastante poco sobre su elevación y solo cuando ésta es exagerada es posible ver y transmitir la idea y sensación de moverse a través de una ciudad en bicicleta.
Hecho con [openFrameworks](http://openframeworks.cc)
Código y aplicación para macos disponible en [https://github.com/roymacdonald/flatCity](https://github.com/roymacdonald/flatCity)
<file_sep>---
layout: post
date: 2017-10-21 12:10:00
categories:
- projects
tags: kuze, kuzefest, laser, laser mapping
thumb: /thumbs/laserkuze.jpg
video_vimeo: 252066601
video_width: 958
video_height: 539
title: Los que suben, los que bajan y los que miran desde arriba
subtitle: Proyección láser generativa
lang: es
---
Proyección láser generativa mapeada sobre una rotonda en Santiago de Chile. Los trazos de ésta se generan siguiendo el flujo automovilístico al rededor de la rotonda utilizando un sistema de visión computacional hecho a medida. Esta intervención lumínica urbana fue presentada bajo el contexto del [KuzeFest, Festival de Luz, Santiago 2017](http://www.kuzefest.cl/en.html).
Esta obra fue presentada en el evento de cierre del festival en [Galeria Cima](http://www.galeriacima.cl/), desde la cual se ve la rotonda desde la altura.
Para este proyecto se utilizó un proyector láser, el cual tiene un poderoso láser cuyo rayo es redireccionado con dos espejos que oscilan rápidamente, así creando la ilusión de una línea donde realmente solo hay un punto. Decidí utilizar este aparato por dos razonas principalmente:
* Dada la naturaleza de la luz láser, estos proyectores pueden proyectar a grandes distancias sin perder luminosidad a diferencia de los proyectores de video covencionales, asi mismo pueden abarcar grandes áreas y generar gráficas de gran tamaño, haciendolos ideales para esta obra.
* El rayo láser, según el código Hollywoodense, funciona simultáneamente como un delimitador de espacios y un sistema de detección de intrusos, como parte de un sistema de vigilancia, lo cual se relaciona con los otros aspectos de esta obra, expuestos más adelante
Utilizando la herramienta de programación openFrameworks desarrollé una aplicación computacional que controlaba el láser y hacia el seguimiento de los automóviles. Los datos de una cámara de video USB que tenía una vista elevada de la rotonda enviaba fueron utilizados para el seguimiento de las luces de los automóviles. La información obtenida de este seguimiento fue utilizada para generar los dibujos que se enviaban al proyector láser por medio de una interfaz especial.
Varios artefactos visuales se generaron dada la manera de funcionar de los proyectores láser. La complejidad de lo que éstos pueden dibujar esta limitada por la velocidad de oscilacion de los espejos. Cuando este límite es superado comienza la ilusión de línea contínua comienza a perderse y haciendo visible la "velocidad de refresco" del aparato. Cuando se fuerza al proyector a dibujar ángulos agudos este límite se hace aun más notorio; al no hacer este forzamiento el proyector interpeta las esquinas como curvas suaves, interpolando naturalmente los lados de un ángulo. Este artefacto terminó por gustarme ya que las formas producidas eran más "naturales" e introducia un alto grado de incertidumbre, y es que decidí dejarlo como parte de la obra. Pienso que estos artefactos son la "contribución" del proyector en esta obra.
Cuando fui invitado a participar en este festival de luz me encargaron hacer algo para el evento de clausura. Este evento tendría lugar en una terraza en el último piso de un edificio que tiene una vista cenital privilegiada de la Plaza Baquedano (usualmente mal etiquetada como Plaza Italia), la cual está ubicada en uno de los ejes principales de la ciudad y es usualmente tildada como el punto de la ciudad que divide la clase alta de la baja. Estas dos condiciones de la locación fueron los conceptos precursores de esta obra.
Aun cuando en la mayoría de las ciudades los sitemas de vigilancia son ubicuos, desde pequeños sistemas caseros de CCTV a los amplios sistemas de control de tráfico, las personas usualmente los ignoran o inclusive no saben de la existencia de éstos. La interacción con estos sistemas es usualmente indeseada e inconciente, y en muchos casos anónima; la identidad de los individuos no es relevante, si no que es su comportamiento dentro de la masa y el comportamiento de la masa lo que importa, desde lo cual se puede extraer información, la que por lo general esta restringida a muy pocas y provilegiadas personas.
De un modo similar, la información que puedo extraer de los automóviles/personas que transitan al rededor de esta rotonda es presentada a los pocos privilegiados que eran capaces de ver la proyección desde la altura ya que ésta no era visible desde el nivel de la calle. Al presentar esta información en una forma estética agradable, casi hipnótica, esta obra intenta, ojalá sin éxito, enmascarar el umbral social que este lugar en la ciudad representa.
Videografía aerea: [<NAME>](https://www.instagram.com/fotosaereas/)
Proveedor proyector laser: <NAME>.
Hecho utilizando [openFrameworks](http://openframeworks.cc/).
<file_sep>---
layout: selector
selection: random
permalink: /random/
---
# Random
Anything that doesn't fit elsewhere.
<file_sep>---
layout: post
date: 2017-01-20 12:10:00
categories:
- projects
tags: sfpc
thumb: /thumbs/blackmetalizer.jpg
video_vimeo: 200434234
video_width: 958
video_height: 599
galery_data: blackmetalizer
galery_name: Debug Views
title: BLACKMETALIZER
subtitle: An interactive generative Black Metal logo generator
lang: en
---
Black Metal it is intended to be one of the most extreme (in darkness, obscurity, evilness and brutality ) sub-genre of Metal Music; as such, the logos of the Black Metal bands.
Probably in search of such extremes the logos, as well as the music, have become absolutely unreadable. Text turned into just a bunch of apparently random lines that usually look like a texture rather than something written.
By using this Black Metal styled generative typography anyone can create a text that resembles a Black Metal logo, which will be deprived from its original intentions and meaning, only left with its formal attributes. It will be culturally resignified as a message carrier which unfortunately will loose the message -the text- thanks to its inherent unintelligibility leaving it to be resignified, once again, just as an aesthetic form. It is a funny yet compelling sabotage to the self-sabotage of Black Metal bands logos.
This was built using [openFrameworks](http://openframeworks.cc/)
#### FAQs
I've been receiving a lot of emails asking if and when I am going to release the code or app.
**Will I release the app?**
It is my intention, althoug currently is super buggy, outdated and need a lot of work. I'd rather publish it when it is in a state where it performs decently. Publishing broken software is a really bad idea.
**Will I open source the code?**
Sure, but only at the same time that I release the app.
**When am I going to release the code and/or software?**
I would have liked to have it already released. I have a show later this year, hopefully, where I am showing this piece and I would release the code and software in such event.
<file_sep>---
layout: post
date: 2015-01-01 12:10:00
categories:
- projects
tags: interactive
thumb: /thumbs/moduloFAV.jpg
title: "Defective apparatus: It refuses to behave according to its original rules and insists on avoiding people. part 1"
WIP: true
FAIL: true
lang: en
---
I was invited to show something at the [Valparaiso Arts Festival (Festival de las Artes de Valparaiso, FAV)](http://festivalartesvalpo.cl/actividades/aparato-defectuoso/), happening on January 2015.
At that time I was working on the idea of the defective machine that can't do it's job yet keeps on working, thus it produces something useless- in the sense of it's original use-, so as consequence it has to fall into the art's scope.
The laser ray, according to the hollywood-esque code, works simultaneously for delimiting space and an intruder detection system. In the case of this work, this laser ray looses its original use because it acquires a fobia towards people, driving it to avoid people constantly.
Each time someone or something blocks the ray, the system reconfigures its mirrors so the ray avoids the blocked route, generating a new spacial delimitation.
The installation consisted on 16 modules, each with a mirror and two servo motors. The mirror could point towards any direction within a semi-sphere.
This installation was placed on the intersection of two streets in Valparaiso. Each of the four corners of the intersection had a post, on each of these posts 4 modules were placed. A green laser was point towards one of these mirror, from where it bounced towards another mirror, then to the next and so on. As the mirrors were able to move, bounce route could be modified; every time the laser was blocked the mirrors created a new bounce route.
So far it sounds very nice but unfortunately this installation failed. I had a very short time to build all this and program it and a scarce budget.
Because of the budget I used used servos, that happened to behave not as expected, making the calibration process impossible. My idea was to test everything at my studio but due to the time constraints I could not. Besides this I realized to late that the servos precision was to low (it is very low actually) wasn't enough to be able to set all the possible bounce routes. All over this I had only one day to mount all the system, it took me more than I expected, and at the time that I was calibrating the whole thing the servos were acting badly and at the end I was unable to setup the whole thing. On top of this the air was very particle-free that specific day, usually there's a bit of fog/moist on the air as Valparaiso is on the seaside, meaning that the laser rays were imperceptible.
It was not fun. It was very frustrating. Although I want to finish this project and make it work. So far budget is my constraint...
### Images


<file_sep>---
layout: post
date: 2017-01-20 12:10:00
categories:
- projects
tags: sfpc
thumb: /thumbs/blackmetalizer.jpg
video_vimeo: 200434234
video_width: 958
video_height: 599
galery_data: blackmetalizer
galery_name: Debug Views
title: BLACKMETALIZER
subtitle: Un generador interactivo de logos de Black Metal
lang: es
---
El Black Metal intenta ser uno de los sub géneros de la música Metal más extrema en cuanto a oscuridad, inaccessibilidad, maldad y brutalidad, lo cual se refleja en los logos de las bandas de este tipo.
Probablemente en la busqueda de tales extremos, los logos, así como la música, se volvieron absolutamente ilegibles - el texto se volvió un una maraña aleatoria de lineas que típicamente parecen ser más una textura que algo escrito.
Al utilizar estas tipografías generativas estilizadas a lo Black Metal cualquiera puede crear un texto que remite a los logos de Black Metal, el cual estará desprovisto de sus intenciones y sentidos originales, quedando solo con sus atributos formales. Este será resignificado culturalmente como un portador de mensajes el cual desafortunadamente pierde el mensaje, el texto, gracias a su ininteligibilidad inherente haciendo que este sea resignificado, una vez más, simplemente como una forma estética. Este es un divertido e irresistible sabotaje al auto sabotaje de los logos de Black Metal.
<file_sep>---
layout: post
date: 2008-03-01 12:10:00
categories:
- work
tags: motion graphics
thumb: /thumbs/motionGraphics.jpg
title: Motion Graphics 2008-2010
lang: en
---
<iframe src="https://player.vimeo.com/video/19293269?byline=0&portrait=0" width="500" height="331" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
<iframe src="https://player.vimeo.com/video/19293114?byline=0&portrait=0" width="500" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
<iframe src="https://player.vimeo.com/video/19293208?byline=0&portrait=0" width="500" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
<file_sep>---
layout: post
date: 2018-04-09 12:10:00
categories:
- projects
tags: luminus prospectu, led mapping, luz, light
thumb: /thumbs/luminus.jpg
video_vimeo: 269480853
video_width: 958
video_height: 539
title: Luminus Prospectu
subtitle:
lang: es
---
Luminus Prospectu significa luz en perspectiva. El campo de acción de esta obra son los sentidos que perciben profundidad abstracta (visión y audición), centrándose en la experimentación sonoro-lumínica de la perspectiva.
En el espacio se ubican distintas fuentes de iluminación y sonido cuya disposición se basa en los diagramas geométricos de Voronoi. La grilla de estos diagramas se genera por relaciones espaciales, estructurales y jerárquicas que se pueden encontrar en la naturaleza y seres vivos, desde lo micro a lo macro; las células sensoriales del ojo y oído humano también se organizan de esta manera.
La luz y el sonido de las composiciones generadas evocan una atmósfera cruda, con 4 momentos de intensidad.
Desde principios de 2018 formo parte del colectivo de arte Trimex y además pasé a ser socio de la empresa del mismo nombre. Fuimos invitados, como colectivo, a realizar esta obra para ser montada en el exterior del Museo de Artes Visuales de Santiago (MAVI), dentro del marco de la inauguración de Barrio Arte, enter el 9 y 16 de Abril de 2018.
Trimex Crew: <NAME>, <NAME>, <NAME> y <NAME>.
Dirección de arte: <NAME>.
Dirección y diseño de montaje: <NAME>.
Desarrollo y programación: <NAME>
Registro video: <NAME>
Música: <NAME>
Asistentes de montaje: <NAME>, <NAME>, <NAME>, <NAME>.
Agradecimientos: <NAME>, <NAME>, <NAME>agal
<file_sep>---
layout: post
date: 2015-03-01 12:10:00
categories:
- projects
tags: interactive computerVision photo
thumb: /thumbs/CamServos.jpg
title: "Defective aparatus: It refuses to behave according to its original rules and insists on avoiding people. part 0"
WIP: true
galery_data: aparatodefectuoso0
galery_name: Images
poster_img: /img/AparatoDefectuoso0/CamServos.jpg
lang: en
---
<file_sep>---
layout: post
date: 2015-06-01 12:10:00
categories:
- work
tags:
thumb: /thumbs/byb.jpg
title: Backyard Brains finger muscles analysis app.
lang: en
---
<NAME>, one of the [exceptional] brains behind [BackyardBrains](http://backyardbrains.com) asked me for some help. He was using five of theirs muscle spike interface, stacked together and conected to a single Arduino. With several electrodes stuck into his fore arm he was able to get the signals of the muscles that control each finger. Just using some very simple rules on the arduino and threshold values he was able to trigger an LED when any of the fingers moved.
The problem here was that the he was setting the threshold by hand, actually by the very tedious method of looking at the serial output of the arduino in order to catch more or less where the threshold should be, hence by a lot of trial and error.
The idea was to make a piece of software, that would run idealy on the Arduino (which didn't happen), that could guess these threshold values by itself just using a very simple and guided training. BackyardBrains has several pieces of sortware to be used in conjution with their neuroscience kits, all of these opensourced and available in their github account. Almost all of these were written on Processing. I decided to write my own using openFrameworks as I felt more comfortable in it and could be opensourced as well. It should be published any time soon.
### Muscle Spike detection
As each person is different from each other, there is the need for a custom setting for each. Placing the electrodes might differ on each person, hence the signals that these receive will be different. Yet the electrical signals sent over our neurons to each muscle all behave in a similar way. So when ever a muscle needs to be contracted the electrical signal has a very characteristic peak followed by a decay phase. If the muscle is to be kept tight after the initial spike, the signal holds at about half the value of the peak and once released it continues to decay to the resting state, which usually is zero or very close to it. (This is very much like ADSR syths! a lot of crazy ideas come to my mind!). Detecting this spikes is sort of trivial, just like detecting percusive sound on an audio signal. I just added a few more rules to make this detection a bit more robust and at the same time sensible enough, as these spikes can have a wide range of values. These electrical signals seemed to behave very much the same on all the tested subjects, so theres no need of tweeking parameters for each one.
### Finger muscle signal isolation
In order to know which finger was being moved we decided to use some machine learning. A very easy and short training has to be performed. The software guides the user and tells him to move a certain finger a few times, each time a peak is detected the values of all the electrode readings are associated to a particular finger. This the goes to a machine learning algorithm as a training instance. Once the training is done for all the fingers the software is ready for detecting the finger movements. When the detection is running it only "asks" to the machine learning algorithm when a peak is detected in the signal.
### Hacker hand
The final idea was to use the BackyardBrains product called Hacker Hand. It is just a robotic hand that uses servos to control each finger. If it is attached to the arduino, the software instruct to move a finger when ever it is detected from the incomming muscular signals.
### Further develop
I really enjoyed this project. I learned a lot and a lot of ideas came into my mind, to further develop the software as well as to connect muscular signals to other things.
-Controling a synths AttackDecaySustainRelease controls with the spikes from the muscles, in order to somehow achieve more control over the sounds while playing.
-Using a Leap Motion sensor to train the machine learning algorithm, so instead of just knowing if a finger is moved or not, the algorithm can know how much is being moved, and hopefully it will be able to predict this value just from the muscles signal.
<file_sep>---
date: 2018-12-19 00:00:00 -0400
layout: post
title: Invocación
published: true
video_vimeo: 312154006
categories:
- projects
video_width: 958
video_height: 539
tags: laser, drone music, ambient, light art, light sculpture
thumb: /thumbs/vimeo_thumbs/312154006.jpg
subtitle:
lang: es
---
INVOCACIÓN , concierto lumínico. Armamos una pieza de arte sonoro basada en la música ambient y noise, la cual hace reaccionar este dispositivo de luz en tiempo real.
Ejecución en vivo, música, conceptualización, dirección de arte, dirección y diseño de montaje, desarrollo y programación por **Colectivo Trimex**, que está formado por **<NAME>, <NAME> y <NAME>.**
Registro video: [**<NAME>**](https://www.instagram.com/rai.barros)
Agradecimientos:
* [Colmado](https://www.instagram.com/colmadocoffee) por el espacio
* [AudioBox](audiobox.cl) por los equipos
<file_sep>---
layout: post
date: 2011-03-01 12:10:00
categories:
- projects
tags: live-visuals
video_vimeo: 33028685
video_width: 958
video_height: 546
thumb: /thumbs/rafflolla.jpg
title: Live Visuals for DJ <NAME>ile 2011
macrobio: true
lang: en
---
Developed and performed with [Macrobio](http://www.macrobio.cl) and [Oktopus](http://oktopus.tv/)
<file_sep>---
date: 2018-12-19 00:00:00 -0400
layout: post
title: Invocación
published: true
video_vimeo: 312154006
categories:
- projects
video_width: 958
video_height: 539
tags: laser, drone music, ambient, light art, light sculpture
thumb: /thumbs/vimeo_thumbs/312154006.jpg
subtitle:
lang: en
---
INVOCACIÓN , light concert. This is a live music performance, which takes elements from ambient, drone and noise music. The lights are "performed" live as well both by manual tinkering and using sound reactive parameters.
This piece was developed as a colaborative piece with [**Trimex Collective**](http://trimex.cl/), which is formed by **<NAME>, <NAME> y <NAME>.**.
Direction, live performance, music, concept, art direction, setup design, coding and development made by Trimex Collective.
Videography: [**<NAME>**](https://www.instagram.com/rai.barros)
Thanks:
* [Colmado](https://www.instagram.com/colmadocoffee) for the venue.
* [AudioBox](audiobox.cl) for the sound and laser equipment.
<file_sep>---
layout: default
lang: en
permalink: /future_sketches/
---
<div class='container clearfix'>
{{ content }}
<div class="header_port_dma">
<h2> MIT Media Lab Future Sketches application portfolio</h2>
</div>
<div class='posts fl'>
<h3>Projects</h3>
{% for proj in site.data.portafoliofs %}
{% for post in site.posts %}
{% if post.id == proj.id and proj.category == "projects" %}
<div class='postbox'>
<a href='{{site.url}}{{post.url}}'>
<img class="imgBW" alt="{{post.title}}" src="{{site.url}}{{post.thumb}}">
</a>
<p><a href='{{site.url}}{{post.url}}'><span class="TXT-celeste">{{post.title}}</span></a></p>
</div>
{% endif %}
{% endfor %}
{% endfor %}
<h3>Tools</h3>
{% for proj in site.data.portafoliofs %}
{% for post in site.posts %}
{% if post.id == proj.id and proj.category == "tools" %}
<div class='postbox'>
<a href='{{site.url}}{{post.url}}'>
<img class="imgBW" alt="{{post.title}}" src="{{site.url}}{{post.thumb}}">
</a>
<p><a href='{{site.url}}{{post.url}}'><span class="TXT-celeste">{{post.title}}</span></a></p>
</div>
{% endif %}
{% endfor %}
{% endfor %}
</div>
</div>
<file_sep>---
layout: post
date: 2012-07-28 00:00:00
categories:
- projects
tags: rgbd rgbdtoolkit
thumb: /thumbs/kinectRGBD.jpg
title: Kinect + DSLR 3D printable mount
lang: en
---
This 3D printable piece is for putting together a DSLR camera and a Kinect and keep these aligned.
I made it to use it with the RGBD Toolkit. Soon it became the official RGBD Toolkit 3D printable mount and remained as such for a long time until newer versions appeared.
You still can download the 3D model from [here](http://www.thingiverse.com/thing:27510) and print it.


<file_sep>---
layout: default
---
<div class='container clearfix'>
{{ content }}
<div class='blog-posts'>
{% for post in site.posts %}
{% assign isBlog = false %}
{% for cat in post.categories %}
{% if cat == 'blog' %}
{% assign isBlog = true %}
{% endif %}
{% endfor %}
{% if isBlog %}
<div class="blog-post-excerpt">
<a href='{{site.url}}{{post.url}}'><span class="blog-post-title">{{ post.title }}</span></a>
<div class="blog-post-content-preview">
{{ post.excerpt }}
</div>
</div>
{% endif %}
{% endfor %}
</div>
</div><file_sep>---
layout: post
date: 2015-03-01 12:10:00
categories:
- projects
tags: live-visuals
video_gdrive: https://drive.google.com/file/d/0B5mz90wE4rsMOFdJUjFsLU5qcWc/preview
video_width: 958
video_height: 538
thumb: /thumbs/farmacos.jpg
title: Live Visuals Farmacos Lollapalooza 2015
lang: en
---
I was asked by the chilean band [Fármacos](http://www.ffarmacos.com/) to help them with the visuals for their show in the Lollapalooza Chile music festival.
They wanted something simple and abstract. Mainly geometric shapes. No colors.
I've used Quartz Composer (QC) for several years, but as years pass, new OS versions come out and no QC updates come to light, the performance and stability of QC has decreased immensely. I had some realy bad experiences with QC crashing in the middle of a show so I decided to build my own visuals system.
I coded this system using openFrameworks, and made it modular and extensible. It mainly allows you to nest different transitions for something you want to draw. Then you just trigger this animations by hand or based on BPM. The cameras also had some parameters that could be animated. It worked really well, yet the GUI needs more love.
I'll push it soon to github as the project needs a bit of cleanup to make it useful to anyone.
<file_sep>---
layout: post
date: 2017-11-15 12:10:00
categories:
- projects
tags: sfpc, recoded, collaborative
thumb: /thumbs/recoded.jpg
video_vimeo: 159313947
video_width: 958
video_height: 539
title: SFPC's Re-Coded
subtitle: Una instalación de código abierto, colaborativa y educacional.
lang: es
---
Cuando asistí al School For Poetic Computation (SFPC) durante el segundo semestre del 2015, fuimos invitados como un colectivo a realizar una obra a presentarse en el festival [Day For Night](https://dayfornight.io/) en Houston, Texas, EE.UU. La ideación y desarrollo de este proyecto fue llevada a cabo por un equipo de 7 personas, del cual yo fui parte y además fui uno de los programadores principales del motor que desarrollamos para éste, así mismo realicé bastantes "re programaciones".
Luego de una sumamente exitosa primera exhibición en Texas, hemos expuesto este proyecto en la conferencia IO de Google en Palo Alto, California el 2016, en el festival Sonar en Barcelona, España el 2017 y en la conferencia Connect de Microsoft en la ciudad de Nueva York el 2017. Yo presenté esta obra, junto con otros miembros del colectivo, en todas estas instancias menos la de Barcelona.
Esta obra se llama Re-Coded (Re-Programado) y es un homenaje a innovadores como <NAME> y <NAME> cuyo trabajo existe en el espacio entre arte y tecnología. Celebrando a estos pioneros, presentamos la reinterpretación de sus obras junto con el código de programación que las genera.
Cada obra reinterpretada o "re programada" se muestra en dos pantallas lado a lado, en una la obra reinterpretada y en la otra el código que la genera. En cada "re programación" hay varios parámetros que pueden ser animados o controlados en vivo (utilizando un controlador hecho a medida que contruimos), los cuales modifican algún aspecto visual de ésta. Cuando cualquiera de estos parámetros es modificado se resalta en el código, lo cual genera una relación directa entre las modificaciones del código y su representación visual.
Cada "re programación" es presentada por cerca de 40 segundos y luego pasa a la siguiente. Cuando una nueva "re programación" es presentada el código es animado, junto con algunos efectos sonoros, como si este estuviese siendo escrito. Cuando esta animación termina aparece la obra visual.
Este proyecto fue programado por completo utilizando openFrameworks. Éste es bastante complejo aun cuando no pareciera serlo, ya que éste debe juntar muchas piezas diferentes, hacer que todo funcione fluidamente y tener muchos colaboradores simultáneos.
Para mayor información visita el sitio de este proyecto (en inglés) [sfpc.io/recoded](http://sfpc.io/recoded/).
<file_sep>---
layout: post
date: 2018-09-01 12:10:00
categories:
- projects
tags: laser, interactive, machine learning
thumb: /thumbs/defectiveapparatus.jpg
title: Defective apparatus
poster_img: /img/defectiveapparatus/da.jpg
header_img_width: 2000
header_img_height: 1333
subtitle: It refuses to behave according to its original rules and insists on avoiding people. part 1.1.
galery_data: defectiveapparatus
galery_name: Some Images
lang: en
---
This project takes the form of an interactive installation driven by a laser beam which interacts with the audience by bouncing on a number of computer-controlled mirrors in order to avoid people. The laser beam, according to the Hollywood-esque code, works simultaneously for delimiting space and as an intruder-detection system. In the case of this work, this laser beam loses its original use because it “acquired a phobia towards people,” causing it to avoid people constantly. Each time someone or something blocks the beam, the system reconfigures its mirrors so the beam avoids the blocked route, generating a new space delimitation, although this route is originally chosen randomly and fed into a machine learning algorithm, so the next time it can make a better decision. It learns by “trial and error.” The whole learning phase of this work happens during the show, so this relationship between human interaction, errors and learning becomes a new narrative layer of this work.
As such, the poetics of an interactive work are fed from the possibilities of unprejudiced experimentation, assimilating the boundaries where the real meaning of discovery lies, encompassing the sensibilities of experience and assuming the conditions that technology currently offers.
This project was developed during the Computational Arts residency setup by the Department of Computing at Goldsmiths, University of London and the Victoria and Albert Museum Digital Programmes, during the summer of 2018.
It was presented in 2018 at the Ars Electronica Festival in Linz, Austria and in the Digital Design Weekend at the Victoria and Albert Museum in London.
Unfortunately - and quite ironically- the installation did not work. It was not properly finished and tested by the time of these exhibitions. But it will be shown soon.
## TL;DR
Some years ago I was working on some not so interesting commercial projects which I tended to avoid; instead, I was constantly working on my own artistic and expressive projects. Art making became my form of procrastination. For one of these commercial projects I had to deal with some really obnoxious machines which often had strange behaviors and sometimes quite interesting results, yet unexpected and useless - in the sense of its original use. Then the idea came, probably out of joking, that this machine was doing just the same as I was: procrastinating and doing some art instead of working. This idea went a lot deeper than a simple joke and opened several questions. What are the relationships between human and machine? What new kinds of understanding can we gain by looking at the similarities in their behaviors? Can these new “intelligent” machines have psychological problems very much as their creator could? Is it possible that machines become obsessed with something and execute a task in a compulsive and repetitive way or is it just their very nature to engage in endless and monotonous routines? At which point can we understand these odd behaviors as something new instead of a malfunction? Is it error what finally provides meaning to the human-machine relationship, and ultimately to the whole human experience?
On 2015 I was invited to participate at the Valparaiso Arts Festival (Festival de las Artes de Valparaiso, FAV), yet the formal approaches to this new idea were not fit for the festival’s curatorial line; I wanted to work the same idea but had to make something new.
As I had very little time and a really scarce budget, the end result was a failure. Nothing worked at the festival, although I gained some really important knowledge. Tragicomically, its name was Defective Apparatus: It refuses to behave according to its original rules and insists on avoiding people. part 1. It was the first version of this project. Now, on its second version it failed to work once again.
<file_sep>---
layout: post
date: 2015-06-01 12:10:00
categories:
- random
tags:
poster_img: /img/fourier_studies/fourier_studies_poster.png
thumb: /thumbs/fourier.jpg
title: Fourier Studies[WIP]
lang: en
---
Personal research in order to understand the [Fourier Transform](http://en.wikipedia.org/wiki/Fourier_transform), in particular the [Discrete Fourier Transform](http://en.wikipedia.org/wiki/Discrete_Fourier_transform).
## [2008]
### Intro
Some time ago, circa 2008, when I was just getting into programming I was also doing a lot of stuff with audio, mainly music production. I became very intrigued by some audio analysis tools, in particular with [Melodyne](http://www.celemony.com/en/melodyne/what-is-melodyne) as it was able to decompose polyphonic signals into its musical notes and let you modify each note individually. I wanted to understand how computers were able to detect each note of an instrument with all the harmonics that conform it. The first and almost obvious thing to do was to "play" with the [Fast Fourier Transform](http://en.wikipedia.org/wiki/Fast_Fourier_transform).
By that time I was learning to code using [Processing](https://processing.org/) and I did a lot of experiments and visualizations dealing with FFTs. It was fun and I learned a lot, both about programming, audio analysis and FFTs. I even made my own FFT class from scratch, just looking at the maths involved (of course there are already a big bunch of FFT implementations, probably done much better that what I did, but this was for a learning purpose).
### FFTs and Musical Notes
Quite soon after I began to play with FFTs I realized that these transforms were not giving me musically relevant information, I was not able to "see" musical notes on the output of the FFT. The linear spacing of the FFT output does not work well with the logarithmic one of musical notes. This is, linear means that every element of the FFT output is spaced by the same amount of hertz. On the other hand, musical notes are spaced logarithmically, the easiest way to understand this is by the fact that for each octave (one note and the following one with the same name) you multiply the frequency by a factor of two. For example, the note A5 is 440Hz, then A6 = 880Hz, A7 = 1660Hz and so on. You can easily see that the amount of Hertz (Hz) that space each octave is not the same.
TODO: add image> linear spacing vs log spacing and notes.
#### Linear to Logarithmic
As my interest had to do with musical notes I wanted to have the FFT in a musical scale. Almost always the FFT results are visually displayed using a linear to log spacing, in order to make it more musical, but this means that you have very little information spread across several octaves of the lower, bass range, which happens to be very musically relevant and on the other hand you have an excessive amount of information in the higher, treble range, which at the end happens to be not really useful; having much less will probably provide the same relevant information. If you want to get more resolution on the bass end you need to make your FFT larger, which means more processing power and less time resolution.
TODO:add spectrogram image with annotations.
##### Something Not Nice
As you try to increase the frequency (spectral) resolution of the Discrete Fourier Transform, hence the FFT, by increasing the number of samples needed to perform it (which is called the size of the transform) the the timing resolution decreases. And on the opposite direction, if you wanted a higher time resolution the spectral resolution went down. This is actually a problem that the [Fourier Transform faces and it has to do with the uncertainty principle](http://en.wikipedia.org/wiki/Fourier_transform# Uncertainty_principle). So this is sort of a dead end. You cant get both, at least with the standard DFT and FFT.
#### First shot: Constant Q Transform
As I was researching over the www, I found out the [Constant Q transform](http://en.wikipedia.org/wiki/Constant_Q_transform), and an [interesting paper](http://academics.wellesley.edu/Physics/brown/pubs/effalgV92P2698-P2701.pdf) about an efficient implementation of it. I wasn't able to find any useful implementation of it, at least for me. I just found a [MatLab implementation](http://wwwmath.uni-muenster.de/logik/Personen/blankertz/constQ/constQ.html), so I decided to code my own implementation for processing using the aforementioned paper and the MatLab implementation as reference. Once done I published the resulting implementation on Google Code (now it is [hosted on my Github account](https://github.com/roymacdonald/p5cq) as Google Code is closing. )
At first it worked, quite well actually.
#### Constant Q explained
The constant Q is actually a quite fancy algorithm, but the idea behind it is quite simple.
So, if you want more resolution on the lower bins of the FFT and discard some of the excessive information on the higher end to make it more musical. Why not just average the information that corresponds to each musical note or in a logarithmic fashion?
Then, how do you make this average? This is the fancy part of the Constant Q. For each bin that you define for the Constant Q (it can be less than a musical note, say 3 bins per musical note) you need perform a weighted average the FFT's bins that correspond to the frequencies of each bin, thus, you need to define these weights. To do such, the weights for each bin averages are defined by a cosine bell curve adjusted so it overlaps nicely with the its neighbor bins, so no info is "lost". Performing this calculations can become very intensive if you just implement straight forwards. So here comes into the game the fancy method that the aforementioned paper described. I will not go further into it, as it is very well explained there.
The calculation of the averaging weights is done once, when de parameters of the Constant Q are defined.
The problem here comes when you want to get bins further down in frequency, thus musical notes, as the FFT needed grows bigger and bigger, and it grows quite fast. At the end the uncertainty problem described before gets worse. :(
TODO: Image> weighting averages
Image> FFT Size versus bass range
I tried out several method to overcome this problem, like doing several CQ transforms with different ranges and mixing them up, overlap the samples used, but at the end it means a lot of processing power and, worse, a lot of wasted calculations, as these are being discarded by all the averaging being done.
I felt like hitting a dead end. But, how does this happen in our brains as we are able to detect sound frequencies, notes, different instruments and timbres with an incredible resolution, both temporal and spectral? How did some sound analysis software seemed to overcome this sort of dead end?
There must be something missing or something I haven't understood yet or some obscure knowledge just revealed to a few...
However, I decided to leave this research in stand by, yet it was immensely educational and fun. I almost forgot about it until this year (2015).
## [2015]
### Google code and the Constant Q
As said before, I published the Constant Q Transform implementation I did for Processing on Google Code.
Earlier this year Google announced that it would close the Google Code services as there were other better and more popular alternatives like Github, and it offerer the possibility to automatically move your repos into a Github account. So, I made them do so, and as a consequence the whole Constant Q Transform came back into my mind, yet I the passing years I acquired a lot of knowledge relevant to the subject.
### Hello openFrameworks
As my programming needs and knowledge grew, the Processing environment fell short. I found out that I was not the only one with similar needs and that several of the others with these needs begun another coding platform (the correct word should be toolkit) similar to Processing in its use and philosophy but largely more powerful, name [openFrameworks.](http://openframeworks.cc).
I ditched Processing quite fast in favor of openFrameworks, and became an active user, contributing in its forum, providing code for its core and writing several addons for it. As such I decided to translate the Constant Q Transform implementation made for processing into an addon for openFrameworks. Found [here](https://github.com/roymacdonald/ofxConstantQ). (I had a much cleaner implementation done but lost it on a hard drive wreck, i'll rewrite it and publish as soon as I can.)
### Inside the Fourier Transform
For the Processing version of the Constant Q Transform I used a custom class for the FFT based on the code of the Minim library. While I was implementing it in C++ for using it with openFrameworks, I decided to go through it's maths again. It was then when I realized about how the Fourier Transform works internally: it is really simple and easy to understand.
According to [Fourier](https://en.wikipedia.org/wiki/Fourier_series), any waveform is formed just from superimposed sine waves of different frequencies, phases, durations and magnitudes.
Thus, you can decompose any waveform it into all of the sine waves that form it (which happens to be kind of impossible for complex signals like music), so at least you can try to look for the presence of certain sine waves at fixed frequencies.
### Finding waves frequencies
So, checking any given waveform for the presence of a certain frequency is quite simple. Just compare the waveform you have with a sinusoidal wave with the frequency that you are looking for. Mathematically this is also simple, you just need to multiply each value of the waveform with the according value of the sinusoidal wave and sum all the results. The result will indicate the amount of the searched frequency in the analyzed signal.
### Phase
It might happen that the analyzed wave and the sinusoidal wave are displaced, or do not start at the same point, so when multiplying and summing all up the result might not be the same as if these were aligned or "in phase". To deal with this a second sinusoidal wave is used. This second one is 1/4 cycle displaced in respect to the first one. Actually the first one is produced by the cosine function and the second one by the sine function. The same thing is done with this new wave as it was done with the first one, just multiply and add with the analyzed wave. In this case the value that this operation gives is called the phase. In order to get the real magnitude of the sought out frequency in the analyzed wave the square root of the addition of the square of each resulting value. Just like solving the hypothenuse in the Pythagoras theorem.
There are a lot of analogies with spinning discs to exemplify this, but I think that it gets a bit more confusing.
...to be continued.




<file_sep>---
layout: post
date: 2017-10-21 12:10:00
categories:
- projects
tags: kuze, kuzefest, laser, laser mapping
thumb: /thumbs/laserkuze.jpg
video_vimeo: 252066601
video_width: 958
video_height: 539
title: Los que suben, los que bajan y los que miran desde arriba
subtitle: Traffic activity driven generative laser projection.
lang: en
---
Generative laser projection mapped onto roundabout in Santiago de Chile. The drawings were generated by tracking the flow of cars using a custom made computer vision system. This urban light intervention was part of the [KuzeFest Lights Festival of Santiago 2017](http://www.kuzefest.cl/en.html).
This work was presented at the festival's closing party that took place at [Galeria Cima](http://www.galeriacima.cl/) art gallery, that overviewed this roundabout.
This project used a laser projector, which has a powerful laser bounced of 2 mirrors that oscillate very fast, thus moving the laser beam, which create the illusion of a line whereas its just a point. I chose to use this kind of projector for two reasons:
* Because of the nature of laser light, this projectors can shoot from long distances without becoming dimmer as regular video projectors do, and span over really large areas allowing to deploy quite large graphics making these ideal for this project.
* The laser ray, according to the hollywood-esque code, works simultaneously for delimiting space and an intruder detection system, as part of a larger surveillance system, which closely relates to the other aspects of this work, discussed further down.
I developed an openFrameworks application to control the laser beam and track the cars. The video feed from a USB camera that was overlooking the whole roundabout was used to track the cars lights. The drawing was generated based on all the tracked points, which was then sent to the laser projector through a special interfase.
Several artifacts were generated due to how this kind of laser projectors works. The complexity of what is being drawn is limited by the oscillations of the mirrors. When more complex shapes are drawn the "refresh rate" or "scan line" becomes visible. Forcing the projector to draw sharp corners limits this even further; the projector interpreted corners as smooth curves, naturally interpolating the sides of the corner. As I ended liking this artifacts, which produced more "natural" shapes and introduced a lot of uncertainty, I decided to keep these. I think of these as the projector's "contribution" to the project.
When I got invited to this lights festival I was told to make something at its closing show. It was going to happen on a terrace on the top of a building overlooking Plaza Baquedano (commonly mislabeled as Plaza Italia), which is located in the main avenue/axis of the city and it is usually referred as the point that divides the city between upper and lower social classes. This two aspects of the location are the pivots of this work.
Even when in most major cities surveillance systems are ubiquitous, from small household CCTV networks to city wide traffic control systems, people usually don't care or don't even know about these. The interaction with these systems is usually both unwillingly and unconsciously. In a lot of cases this interaction is anonymous; the individuals identity doesn't matter, it is its behavior within the mass and the mass' behavior that matters, from which data can be extracted. This data is most of the times restricted to very few and privileged people.
In a similar way, the data that I extracted from the cars/people passing through this roundabout was presented to the audience at this event, the few privileged ones that were able to see it from above as it was not visible from street level. By presenting this data in a very pleasing, even hypnotizing aesthetic form this work tries -hopefully without success- to mask the social threshold that this city location represents.
Aereal videography by [<NAME>](https://www.instagram.com/fotosaereas/)
Laser Projector provided by <NAME>.
Made with [openFrameworks](http://openframeworks.cc/)
<file_sep>---
layout: portafolio
lang: en
permalink: /mda/
---
<file_sep>---
date: 2015-08-26 00:00:00 -0400
layout: post
title: ofxSoundObjects
subtitle: Modular sound engine for openFrameworks.
published: true
categories:
- code
poster_img: /img/ofxSoundObjects_poster.png
thumb: /thumbs/ofxSoundObjects.png
lang: en
---
# [ofxSoundObjects](https://github.com/roymacdonald/ofxSoundObjects/)
## Simple yet super powerful modular sound architecture for [openFrameworks](https://openframeworks.cc/).
It allows to connect any sound source, process, display and output it in any way needed. It is capable of reading and writing audio files.
This is an addon version for the ofSoundObject implementation originally conceived at the 2013 OFDev Conference held at the Yamaguchi Center For Arts and Media, Japan.
The developers involved in this were:
* [<NAME>](https://github.com/admsyn/)
* [<NAME>](https://github.com/mazbox)
* [<NAME>](https://github.com/arturoc)
* [<NAME>](https://github.com/roymacdonald/)
The original development branch can be found [here](https://github.com/admsyn/openFrameworks/tree/feature-sound-objects).
Made as addon, improoved and updated by Roy Macdonald.
## Code and documentation
[https://github.com/roymacdonald/ofxSoundObjects/](https://github.com/roymacdonald/ofxSoundObjects/)
<file_sep>---
layout: selector
selection: projects
permalink: /projects/
---
# _Art
The following are artworks done for the sake of art.<file_sep>let outputImage;
const imgSize = 512; //our image will be 512x512 pixels, which is what StyleGAN requires
const sliderTop = 512;
const sliderHeight = 200;
const sliderBottom = sliderTop + sliderHeight;
let count = 0;
let aIndex = 0;
let sliderWidth = 1;
let bWasMovingSlider = false;
let prevSliderIndex = 0;
let prevSliderValue = 0;
let bDraggingSlider = false;
let bWaiting = false;
let serverState = "";
let a = new Array(512);
a.fill(0.0, 0);
let randomButton, zeroButton, minButton, maxButton, perlinButton;
function setup() {
createCanvas(windowWidth, windowHeight);
getServerState();
generateImage();
getServerState();
outputImage = createImg("", "");
outputImage.hide();
sliderWidth = windowWidth / float(imgSize);
let x = 600;
let y = 120;
let margin = 20;
randomButton = createButton('Random');
randomButton.position( x, y);
randomButton.mousePressed(randomButtonPressed);
y += randomButton.height + margin;
zeroButton = createButton('Zero');
zeroButton.position( x, y);
zeroButton.mousePressed(zeroButtonPressed);
y += zeroButton.height + margin;
minButton = createButton('Min');
minButton.position( x, y);
minButton.mousePressed(minButtonPressed);
y += minButton.height + margin;
maxButton = createButton('Max');
maxButton.position( x, y);
maxButton.mousePressed(maxButtonPressed);
y += maxButton.height + margin;
perlinButton = createButton('Perlin Noise');
perlinButton.position( x, y);
perlinButton.mousePressed(perlinButtonPressed);
noiseDetail(5, 0.35);
}
function windowResized() {
resizeCanvas(windowWidth, windowHeight);
sliderWidth = windowWidth / float(imgSize);
}
function getServerState()
{
fetch(
"https://stylegan2mixingconsole.hosted-models.runwayml.cloud/v1",
{
method: "GET",
headers: {
Accept: "application/json",
Authorization: "<KEY>
"Content-Type": "application/json"
}
}
)
.then(response => response.json())
.then(myJson => {
serverState = myJson.status;
// console.log("serverState: " + serverState);
});
}
function setSliderIndex() {
if (
mouseY > sliderTop &&
mouseY < sliderBottom &&
mouseX >= 0 &&
mouseX < width
) {
bDraggingSlider = true;
aIndex = int(mouseX / sliderWidth);
if (aIndex < 0) aIndex = 0;
if (aIndex >= 512) aIndex = 511;
setSelectedSlider();
}
}
function setSelectedSlider() {
if (bDraggingSlider) {
a[aIndex] = map(mouseY, sliderTop, sliderBottom, 1, -1, true);
if (
bWasMovingSlider &&
prevSliderIndex >= 0 &&
aIndex >= 0 &&
prevSliderIndex != aIndex
) {
let minInd = min(prevSliderIndex, aIndex);
let maxInd = max(prevSliderIndex, aIndex);
// console.log("minInd: " + minInd + " maxInd: " + maxInd);
for (let i = minInd; i < maxInd; i++) {
a[i] = map(i, minInd, maxInd, prevSliderValue, a[aIndex], true);
}
}
bWasMovingSlider = true;
prevSliderIndex = aIndex;
prevSliderValue = a[aIndex];
// generateImage();
}
}
function mouseDragged() {
setSliderIndex();
}
function mouseReleased() {
if(bDraggingSlider)
{
generateImage();
}
bDraggingSlider = false;
bWasMovingSlider = false;
}
function mousePressed() {
setSliderIndex();
}
function generateImage() {
// if(bWaiting == false)
// {
const data = {
z: a, //generated latent space vector
truncation: 0.5 //variation in image generations - higher is more random, lower is more similar
};
//// You can use the info() method to see what type of input object the model expects
// model.info().then(info => console.log(info));
bWaiting = true;
fetch(
"https://stylegan2mixingconsole.hosted-models.runwayml.cloud/v1/query",
{
method: "POST",
headers: {
Accept: "application/json",
Authorization: "<KEY>
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}
)
.then(response => response.json())
.then(outputs => {
// const { image } = outputs;
// use the outputs in your project
// console.log(outputs);
outputImage.attribute("src", outputs.image);
bWaiting = false;
// console.log("got image");
//imageReady();
// use the outputs in your project
})
.catch(function(error) {
console.log('Hubo un problema con la petición Fetch:' + error.message);
});
// }
}
function draw() {
if(frameCount%30 == 0)
{
getServerState();
}
background(255);
image(outputImage, 0, 0, 512, 512);
let bMouseOverSliders = mouseY < sliderBottom && mouseY >= sliderTop && mouseX >=0 && mouseX < imgSize*sliderWidth;
for (let i = 0; i < imgSize; i++) {
noStroke();
fill(240);
rect(i * sliderWidth, sliderTop, sliderWidth, sliderHeight);
let y = map(a[i], 1, -1, sliderTop, sliderBottom);
if((bMouseOverSliders && mouseX >=i*sliderWidth && mouseX < (i + 1)*sliderWidth ) || (i == aIndex))
{
stroke(70);
}
else
{
noStroke();
}
if (i == aIndex) {
fill(255, 255, 0);
} else {
fill(200);
}
rect(i * sliderWidth, y, sliderWidth, sliderBottom - y);
}
noStroke();
fill(200);
let txt = "Waiting for response: " + ((bWaiting===true)?"YES":"NO");
txt += "\nServer state: " + serverState;
txt += "\n\n Use the following buttons to set/reset the sliders into some default values.";
// txt+= "\nMouseY: " + mouseY;
// let txt = "count: " + count;
// txt += "\naIndex: " + aIndex;
// txt += "\na[aIndex]: " + a[aIndex];
// txt += "\nbDraggingSlider: " + bDraggingSlider;
// txt += "\nprevSliderIndex: " + prevSliderIndex;
text(txt, 600, 40);
}
function randomButtonPressed()
{
for (let i = 0; i < imgSize; i++) {
a[i] = random(-1, 1);
}
generateImage();
}
function zeroButtonPressed()
{
a.fill(0.0, 0);
generateImage();
}
function minButtonPressed()
{
a.fill(-1.0, 0);
generateImage();
}
function maxButtonPressed()
{
a.fill(1.0, 0);
generateImage();
}
function perlinButtonPressed()
{
let inc = 0.09;
for (let i = 0; i < imgSize; i++) {
a[i] = 2 * noise(inc * i) - 1;
}
generateImage();
}
<file_sep>---
layout: selector
selection: work
permalink: /work/
---
# $$$
The following are commisioned works which I do in order to make a living out of this.<file_sep>---
layout: post
date: 2017-09-08 12:10:00
categories:
- projects
tags: xdefault, data visualization, interactive
thumb: /thumbs/proyectodefault.png
video_vimeo: 238460122
video_width: 958
video_height: 539
title: Default
subtitle: Interactive visualization of the brain in default mode.
galery_data: proyectodefault
galery_name: Imágenes Montaje
lang: en
---
I was part of the Default project, for which I designed and coded the visualization, as well as advising about interactivity.
Project site [xdefault.cl](xdefault.cl)
**Default** is an interactive and immersive piece about the brain's activity while at rest. It was the result of an interdisciplinary dialogue project between <NAME> -Designer- and <NAME> -Neuroscientist.
It used to be assumed that the base brain activity -the one that precedes stimulus- had no relevance. Nevertheless, evidence reveals something astonishingly different: the brain uses a large amount of energy while it is not being stimulated and these moments are the ones that take the largest amount of time through out our life.
This spontaneous dynamism depends on the Default Mode Network (DMN) -a mesh which is always active, except on the periods when doing tasks or reacting to external stimulus, moments in which it briefly disconnects. This network integrates memories of our life, as such it could explain a lot of the unknowns about self-consciousness and relevant processes such as creativity.
Default is conceived as a visual and sounding environment made from the data gathered from a Functional Magnetic Resonance Imaging (fMRI) exam -used for studying brain activity- of a person at a state of rest. The room where this piece was shown was a brain itself, thanks to 3D visualization of data, data based sound design, and space and interaction design, which allows to know the cerebral states of a human experience that everyone unconsciously goes through.
Default's purpose was to captivate the audience through aesthetic enjoyment while at the same time would awake curiosity about the deeper states of the mind.
Team:
* **<NAME>**: Principal investigator
* **<NAME>**: Principal co-investigador
* **<NAME>**: Visualization design and coding
* **<NAME>**: Sound design
* **<NAME>**: Design research assistant
* **<NAME>**: Interaction coding and implementation
* **<NAME>**: Interaction coding and implementation
This project was made with the support of Dirección de Artes y Cultura, Vicerrectoría de Investigación de la Pontificia Universidad Católica de Chile.
## Process
<iframe src="https://player.vimeo.com/video/248526680?title=0&byline=0&portrait=0" width="600" height="338" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
<file_sep>---
date: 2020-08-21 00:00:00 -0400
layout: post
title: StyleGAN mixing console
published: true
categories:
- projects
tags: RunwayML, Residency, Artist-In-Residence, StyleGAN, GAN, AI, Machine Learning
thumb: /thumbs/StyleGANMixer.jpg
lang: en
---
Between October 2019 to February 2020 I spent my time in New York City, as a Something-In-Residence at [RunwayML](https://runwayml.com/).
## Context
[GAN](https://en.wikipedia.org/wiki/Generative_adversarial_network)s have become very popular recently, particularly [StyleGAN](https://en.wikipedia.org/wiki/StyleGAN), as a method for creating photorealist synthetic images, which are particularly good with human faces. As such, Latent Space interpolation, a technique for visualizing some of the options available from what the GAN has learned has become a quite common visualization method.
The following is a video that shows Latent Space Interpolation using StyleGAN.
<iframe width="560" height="315" src="https://www.youtube.com/embed/djsEKYuiRFE" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
## Understanding
When looking at how this technique works I realized that it was simply using [Perlin noise](https://en.wikipedia.org/wiki/Perlin_noise) -which is a very common algorithm used in computer graphics for generating pseudo-random numbers that smoothly change from one to the next- to smoothly change each of the 512 parameters that these GANs have.
As I wanted to play with this parameters I thought of controlling these with something like a sound mixing console, with 512 vertical faders, where each controls a single parameter of the GAN.

## Experiment
I initially made this experiment using the regular interface between RunwayML and p5js. But then I ported it to use [RunwayML's Hosted Models](https://runwayml.com/web/) feature -which is at not publicly available at the time of writing this-, that allows you to use your RunwayML's models inside regular websites, without needing to download and install the RunwayML app. It is really nice. This is what allows me to have this experiment embedded in this web page. :D
This experiment allows the user (you) to control each of the 512 different parameters that StyleGAN has.
* At the left is the generated image.
* Below the image are 512 grey vertical bars (sliders), one for each parameter.
* Drag up and down any of these sliders to modify the single parameter that each control.
The image will be updated to reflect these changes.
* If you drag across the sliders you can "draw" their positions.
* Be patient as the changes happen quite fast but not instantly.
* When you first run it the server might need to start so it can take about 30 seconds to start.
* At the right of the image you can see the current status of the server.
* There are 4 buttons, labeled "Random", "Zero", "Min", "Max", "Perlin Noise" which will set some values to the sliders, as it follows:
* "Random" : Assigns a different random value to each parameter.
* "Zero" : Sets all the parameters to zero, which actually is the middle position.
* "Min" : Sets all the parameters to -1, the lowest possible value for the parameters.
* "Max" : Sets all the parameters to 1, the Highest possible value for the parameters.
* "Perlin Noise" : Sets the values using Perlin Noise. These will be random-ish but these will change smoothly between each parameter.
* You might find it more convenient to use this experiment without all the rest of things in this website. Click [here](/styleGAN_Mixer.html) to go there.
<div class="inlinestyleGAN">
<iframe class="inlinevideo-iframe" src="{{site.url | append: '/styleGAN_Mixer.html'}}" frameborder="0" scrolling="no"></iframe>
</div>
If you liked this experiment/interface please consider donating as you using it costs money, which comes out of my pocket.
If it does not work it is because my RunwayML account has run out of credits.
Feel free to contact me if you donated and want me to add that as credits for it to work.
<form action="https://www.paypal.com/donate" method="post" target="_top">
<input type="hidden" name="business" value="VRL2TDAMYZYKE" />
<input type="hidden" name="no_recurring" value="0" />
<input type="hidden" name="currency_code" value="USD" />
<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif" border="0" name="submit" title="PayPal - The safer, easier way to pay online!" alt="Donate with PayPal button" />
<img alt="" border="0" src="https://www.paypal.com/en_CL/i/scr/pixel.gif" width="1" height="1" />
</form>
## Conclusion
At the time I did this and showed it to the people at RunwayML, most said that they had not seen an interface like this for navigating the latent space and they liked it very much.
As well, as far as I know it had not been done.
This interface allows to see in much better detail how the model works, and you can see that each parameter does not control a specific feature but rather a more undefined one. Yet after fiddling with it a bit you will find patterns of changes and certain areas in the faders that controlled a specific feature (I remember having found one that, when changed it added or removed glasses from the resulting image). Usually you need to move together a few adjacent sliders in order to have a larger effect over the image generation, yet sometimes you can get quite dramatic changes by slightly moving a single one. Go on and explore it.
Another thing you can perceive are the limits of machine learning in the form of visual artifacts. The model does not really understand what a human face (or what ever thing you used for training it), it simply holds statistical values about how all images of the training data are related. As such you can see strange things happening, like almost appearing earrings or eye glasses. The model does not know what an earring or eye glass is and that it needs to be able to exist in real space, instead it just has the ability to infer what an image should look like given the training data and the parameters used for producing it, which means that the laws of real-world space don't need to apply.
Using javascript proved to be really nice for experiments as this one as it required very short code, as all the requests to RunwayML are made through an http request, which are native to javascript as well as the response format, JSON, so there was no need to parse or use special libraries for such. You can inspect the Javascript code that drives this experiment [here](/stylegan-transition.js)
I hope that this small tool allows you to both have fun and get a better understanding on how GANs work.
I also did some other experiments while being Resident at RunwayML which you can read [here](https://roymacdonald.github.io//projects/2020/08/19/How_NOT_to_train_your_GAN.html)
. 🙂
<file_sep>---
layout: post
date: 2014-03-01 12:10:00
categories:
- work
tags: interactive mapping
thumb: /thumbs/mappingRancagua.jpg
title: Interactive video mapping Mall Rancagua
lang: en
---
Three projectors were used to project over a conical column inside a mall in Rancagua, Chile.
When users standed in a marked spot and looked to the camera placed above the column a photo was taken automatically using face detection, the face was cropped, masked and placed over the characters of an animation. This project was co-developed with [DelightLab](http://www.delightlab.com).
To export the data from the animation made in After Effects I made a script that took all nested transformations and "flattened" them. This exported data was read by an openFrameworks application. I[ published ](https://github.com/roymacdonald/ofxAfterEffectsTransforms)an openFrameworks addon to allows this.
<file_sep>---
layout: post
date: 2013-03-01 12:10:00
categories:
- work
tags: interactive android
video_vimeo: 63744681
video_width: 958
video_height: 538
thumb: /thumbs/LGLolla.jpg
title: App LG Lollapalooza Chile 2013
macrobio: true
lang: en
---
Android app developed for the LG Optimus G at Lollapalooza Chile 2013.
This app used the phones sensors (gyro, compass, accelerometer) to determine where it was pointing to allowing the user to paint over a big LCD monitor. The phone's touch interface allowed to witch between different brush styles and colors.
<file_sep>---
layout: post
date: 2013-02-01 12:10:00
categories:
- work
tags: interactive kinect
video_vimeo: 57096403
video_width: 958
video_height: 538
thumb: /thumbs/cocacola.jpg
title: Kinect Games Fábrica de la Felicidad CocaCola
macrobio: true
lang: en
---
We were commissioned to develop a game/installation using the Microsoft Kinect sensor.
The user had to help the narrator advancing chapters using arm gestures, while he was telling about the history of CocaCola in Chile.
At a certain point during the story the narrator invites the user to play some soccer penalty shots. The user just kicks the air, while the system detects the kicks and analyzes its direction and velocity in order to display the correct animations.
I developed this work while I was still working at Macrobio (I was one of the owners/partners, lead developer and project director).
<file_sep>---
layout: blogpost
date: 2015-11-06 15:15:00
categories:
- blog
tags: sfpc
show_in_home: false
title: SFPC Exhibition proposal
lang: en
---
# Probe
## Assignment for Concept & Theory Class [Taeyoon Choi]
#### Exhibition curation:
This exhibition would consist on artwork sent by mail by artists around the world. Artists should be SFPC students, alumni, teachers or fellows.
The artworks to be submitted should be focused towards presenting to the audience the point of view of the artist [or the artwork] and somehow taking them into experiencing a different point of view of something else hopefully in real time and/or using technology and any kind of media. All the artwork should be sent by mail. 10 artists will be invited to participate in the show. Artwork should be capable of somehow documenting it's stay in the exhibition so to provide some feedback to the artist. Once the exhibition is done, the artwork will be shipped back to the artist.
#### Purpose
Each individual has its own perspective and point of view of the world, thus its path and journey through space, time and life is unique. Trying to put someone else in the point of view of another is usually quite hard as it involves having one to abstract from its own POV and place into someone else's that must be transmitted somehow. The idea behind this exhibition is to expose the process of changing points of view and providing a critical insight about it.
#### Artwork packaging
The packaging of artwork must be part of the artwork itself. It must be capable of withstanding the shipping processes in order to arrive in good conditions to the exhibition space.
It must be capable of self deploying or using really simple instructions to be performed by any person. Actually there wont be any specially assigned person on assisting the unboxing and deployment of each package. It will have to rely on the "good will" of the audience if assistance is needed. If any hazardous process is needed to be perform it must be warned hysterically to the audience. Dangerous and harmful artwork is encouraged!.
Artwork must be reshipable, thus it must be able to get packaged by itself or by minimal assistance.
Each art piece will be assigned a special space in either a shared or individual room.


<iframe width="560" height="315" src="https://www.youtube.com/embed/zlZTghhCuxg" frameborder="0" allowfullscreen></iframe>
<iframe src="https://embed.theguardian.com/embed/video/science/video/2015/jul/16/pluto-timelapse-video-nasa" width="560" height="315" frameborder="0" allowfullscreen></iframe>
#### Budget
$500 per artist for creating artwork, any materials needed and shipping costs.
$1000 everything else
#### Schedule
All the artwork is expected to arrive at time for the exhibition, not before not after but in time, just like the audience for the opening.
The exhibition will be open for a week. There will be a closing event at which each artwork will be repackaged and shipped back to the artist.
<file_sep>---
date: 2020-08-19 00:00:00 -0400
layout: post
title: How NOT to train your GAN
published: true
categories:
- projects
tags: RunwayML, Residency, Artist-In-Residence, StyleGAN, GAN, AI, Machine Larning
thumb: /thumbs/GAN.jpg
lang: en
---
Between October 2019 to February 2020 I spent my time in New York City, as a Something-In-Residence at [RunwayML](https://runwayml.com/).
Among other things I did a 3 experiments with the by-then unreleased [GAN](https://en.wikipedia.org/wiki/Generative_adversarial_network) training feature that RunwayML had. Now it is available to anyone. It particularly uses the [StyleGAN](https://en.wikipedia.org/wiki/StyleGAN) model.
## Experiment #1
**Context**
Just after I left Chile and before starting my residency at RunwayML a [huge Chile social revolt begun](https://en.wikipedia.org/wiki/2019%E2%80%9320_Chilean_protests) (still ongoing, currently on standby because of COVID-19). This kept me quite distracted from the residency at RunwayML. I wanted to explore RunwayML’s tools to produce a socially aware, critical and timely project but could not figure it out. Yet, as I wanted to train a GAN I needed images; the images of Chile’s President <NAME> were constantly appearing while drifting though the internet and social media. So I decided as an act of protest to train a GAN on him, but in the wrong way.
In order to get “good” results from any kind of ML process you need to teach it “correctly”. StyleGAN, the particular GAN that RunwayML allows you to train, it is not different.
Thus, if you want to train it on faces, to get “good” and photo-realistic results you need to use images of faces that are as similar as possible; same pose, similar illumination, have all the faces aligned so the features are in the same coordinates, etc. The least amount of unwanted variation is best.
But now how to get a “bad” result that it is still good in some other twisted (artistic?) sense? Easy, train it wrongly but not too much.
**Step 1. Getting images.**
In order to train the GAN, I did a Google image search for the word “Piñera” and took the first 500 images. I used [this](https://serpapi.com/images-results) service which returns a [JSON](https://en.wikipedia.org/wiki/JSON) file with the results instead of getting these through the regular interface. I wrote a [short bash script](https://gist.github.com/roymacdonald/fc808144d46fc499d654d05209f2495a), which searches for all the lines containing `"original":` as it was the keyword in the JSON file containing the URL of the original image, the one I wanted. Then I use [c](https://en.wikipedia.org/wiki/CURL)[URL](https://en.wikipedia.org/wiki/CURL) to download each one of these.
**Step 2. Finding faces and cropping.**
Among the results I got most were images of Chile’s president, but not all, and these were all kinds of images, close ups, full body, alone, with more people, different facial expressions and poses, etc. I made an app using [openFrameworks](http://openframeworks.cc/), that would find only faces that were front facing -which is one of the most basic face finding algorithms-, then crop and normalize these, so all the faces of each cropped face were aligned. You can find the [code for it here](https://github.com/roymacdonald/faceCropAndNormalize)
This step was the improper one, as I only took care of aligning faces so I would get as a result an image that resembled a face but without making sure that each image was actually the person I wanted nor that it was in the correct pose or anything else. I did not want to go through an exhaustive process of hand picking each image or making a very complex workflow in order to filter these, I just wanted what Google gave me, filtering the least possible, in order to only have normalized faces.
The following are all the images I used for training.

**Step 3. Training StyleGAN.**
This one was easy. Simply feeding the images to RunwayML and let it run for a while (I think it was about 3 hours) and… *voila!*
The following are some of the images produced by it:
<div class="galery">
{% for img in site.data['piranas'] %}
<div class="galery_thumb">
<a href="{{site.url}}{{img.img}}" data-lightbox="img-set" data-title="img">
<img src="{{site.url}}{{img.thumb}}" width="100%" height="100%"/>
</a>
</div>
{% endfor %}
</div>
The results were great, I mean very bad from the “correct” point of view, but I really like the images as these all are some kind of representation of the president, with a painting-look and a resemblance to [<NAME>](https://es.wikipedia.org/wiki/Freddy_Krueger) (which I find quite fit for all the hell that this president has brought and been unable to manage diligently).
Another of the many super nice features RunwayML has is that you can share your trained StyleGAN. This one is named Pirañas.
The following is the training video of it:
<div class="inlinevideo">
<iframe class="inlinevideo-iframe" src="https://player.vimeo.com/video/449852980" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe>
</div>
## Experiment #2
So now I thought, if the idea is to have a data set with the least possible unwanted variations, then that data set should be only copies of the same image. So I simply copied the same image 500 times and used these to train the GAN.
I was already fed up with Piñera so I chose not to use his image anymore.
I found a nice photo of my niece I had taken recently during a family trip, which I decided to use.
The original image is the following.

Duplicated 500 times and used to train StyleGAN produced the following

Not bad for a synthetic image yet totally useless as a method for re-creating (compressing-decompressing) the original image. I was suspecting something like this would happen, but as obvious that it might have seemed I thought it was a necessary experiment. There are so many cases in history where great discoveries have been done simply by doing what everyone skipped because its result was obvious, yet nobody had tried it before. As such I like to do such kind of obvious as well as “wrong” things.
In the following video you can see how the images from the starting point converge into the image of my niece.
<div class="inlinevideo">
<iframe class="inlinevideo-iframe" src="https://player.vimeo.com/video/449864961" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe>
</div>
About halfway through the video some really interesting and creepy looking faces appear.
As the following. (this is probably the only interesting thing about this mostly uninteresting experiment)

## Experiment #3
Now, the mathematical representation of a specific face must be quite large and complex, so what would happen if instead I would try the simplest image possible. A completely white image did not sound so interesting so I opted for a black square in a white background.
I did the same thing as before, copy the image 500 times and feed it to RunwayML.
I thought that it would easily converge into the square, just as it did with the image of my niece, but I was wrong.

Before continuing I need to explain something about the **training** **starting** **points.**
In extremely reductionist terms, in order to train a GAN, its algorithm's variables are initialized with placeholders, in the form of noise (random data). During training, these placeholder values are modified -a small amount on each training step- and it generates an image using these variables. The resulting image is then compared to the trainning data. If such modification gives a result that resembles more to the training data than before, the modification will be kept, other wise it will be ditched. Thus, this takes an enormous amount of computational power as it is essentially guessing, trying to move in all directions blindly but systematically. The longest part of this process is the beginning, going from noise into something. In order to avoid such long processing times, in RunwayML you have to choose a starting point for the training that it is not noise. You are provided by a series of categories of things commonly used, which can be thought of as faces (people), objects and places.
In the previous experiment the choice of the starting point was trivial, I chose the people faces (although I should have tried using the other starting points but it costs money). In this experiment there was nothing similar as a starting point to the black square over white. So I simply tried out a lot of these. And now interesting things happened.
The following are the progress videos of these. Watch these in full screen and full quality and resolution, as the details are the nice things.
<!-- https://www.dropbox.com/s/tohvow2c9vo876d/sq_cats.mp4?dl=0 -->
<div class="inlinevideo">
<iframe class="inlinevideo-iframe" src="https://player.vimeo.com/video/449865983" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe>
</div>
<!-- https://www.dropbox.com/s/a9zee9y3b5tk79v/sq_bedrooms.mp4?dl=0 -->
<div class="inlinevideo">
<iframe class="inlinevideo-iframe" src="https://player.vimeo.com/video/449866027" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe>
</div>
<!-- https://www.dropbox.com/s/69znflb39hia546/sq_cars.mp4?dl=0 -->
<div class="inlinevideo">
<iframe class="inlinevideo-iframe" src="https://player.vimeo.com/video/449865991" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe>
</div>
<!-- https://www.dropbox.com/s/aks2bxb3zhb0lfa/sq_portraits.mp4?dl=0 -->
<div class="inlinevideo">
<iframe class="inlinevideo-iframe" src="https://player.vimeo.com/video/449866078" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe>
</div>
<!-- https://www.dropbox.com/s/yup6unlw95exg4i/sq_nebulas.mp4?dl=0 -->
<div class="inlinevideo">
<iframe class="inlinevideo-iframe" src="https://player.vimeo.com/video/449866122" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe>
</div>
<!-- https://www.dropbox.com/s/iv99redoisb3lhj/sq_flowers.mp4?dl=0 -->
<div class="inlinevideo">
<iframe class="inlinevideo-iframe" src="https://player.vimeo.com/video/449866133" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe>
</div>
As you might have noticed the algorithm converged at something quite close to the original image several times but overshot and had then to compensate, so it got into some sort of oscillation around the “correct” result, each time giving different results, which are really interesting.
But what I found most interesting was what happened during the early steps of each training, where the original data set still had a lot of influence over the result, yet it was producing a shape that was quite close to a square, but these had a special paint like effect that I really like. Even, the one that starts from cats looks like a pencil drawn sketch. :)
Some of my favorites are the following:



## Conclusion
These were some experiments I made besides the main project I was working on while I was a resident at RunwayML. Were these useful? I am not sure, at least I tried and got some interesting results. I would have liked to try out a lot of other options but each experiment costs money, as it has to be run on a remote server way much more powerful than my own computer, yet I am immensely grateful with the RunwayML team as they allowed to do these experiments. 🙂
<file_sep>---
layout: post
date: 2015-10-27 12:10:00
categories:
- projects
tags: data-viz sfpc
thumb: /thumbs/redimensional.jpg
video_vimeo: 200435042
video_width: 958
video_height: 599
title: REDIMENSIONAL
lang: en
---
Time is often thought, in physics, as our fourth dimension. Time and images, formally speaking, are the building blocks of movies. As images only have two dimensions, time becomes the third dimension of movies. This condition allows us to create a single three dimensional object that represents the whole movie, although because of the opaque nature of the pixels only the external faces of this objects become visible. Just like in medical CT Scans, we can slice this object in order to reveal its internal features. The slices can be on any plane of this object. As we keep on slicing and watching at each slice as a new frame of the movie we become able to watch the movie from a completely different perspective. The inner workings of the movie shot are revealed somehow; camera movements, actors movements, scenery, or simply strange yet very appealing abstract images. There is an infinite number of possible slices; images become infinite which transcend the original, never changing, movie.
This is an interactive application which allows the user to view any video file as a
three dimensional object made by stacking the video frames. The user can slice this object on any plane. By set a beginning and an end plane it will animate the slicing which will have the same duration as the original video piece.
Because of the limited amount of memory on the graphics card, it is only possible to load short pieces of video, so this app will automatically detect scene cuts and load scene by scene.
This application was made using [openFrameworks](http://openframeworks.cc) and its code will be soon available as open source.
<file_sep>---
layout: post
date: 2015-10-2 12:10:00
categories:
- random
tags: sfpc
show_in_home: false
title: From Deleuze's Societies of Control to America is hard to see
lang: en
---
# From Deleuze's Societies of Control to America is hard to see.
*This is a writting assingment made by <NAME> for his Concept and Theory Studio class at the School For Poetic Computation while I was attending it during Fall 2015. In this a connection is ment to be drawn between <NAME>'s [Postscript on the Societies of Control](https://cidadeinseguranca.files.wordpress.com/2012/02/deleuze_control.pdf) and the [America is hard](http://whitney.org/Exhibitions/AmericaIsHardToSee) to see exhibition at the Whitney Museum in NYC.*
*Deleuze* describes societies as machines; from simple mechanical ones -lever, pulleys and clocks- to complex information driven ones -like the one in which we live now. These machines, like any other of any kind, exist to perform something *useful* -although arguable, it usualy will be something that benefits the owner of the machine or the one in control of it.
Most human practices can be seen as an *useful* piece of this machine by almost directly relating its outcome, or its importance as a piece of it, to the benefit of the *controler*. Even though, Art -as an esential practice of human kind- is usualy hard to be labeled as *useful*; The outcome of art when seen from human expression -its essential motivation- has to go through other human being, its emotions, feelings, thoughts, culture and history, conciously and unconciously, before it can provoke a reaction on it. This reaction can be something catastrophic or highly benefical for the *controler*; like triggering a massive social revolution that becomes a fatal failure of the machinery or providing huge economical gain and market movent, yet usualy from derivates of the artwork itself. From Whitney's *America is hard to see* exhibition, take as example <NAME>'s *Shapolsky et al. Manhattan Real Estate Holdings, a Real-Time Social System, as of May 1, 1971* and <NAME>'s artwork usualy seen as t-shirts and other products of mass consumption. Thus, Art within the machine is a double sided blade, for which the *controler* must be cautious about.
The lines between the different Art's practices and those that aren't, thus their produce, has become progresively more blury, specially since <NAME> irrupted in the art world. As of today I can say that this lines have become not only completly blured but erased -yet there still are the Fine Arts practices (painting, sculpture, drawing, etc) it is more and more common to find artwork in mixed field; not only between the Art's fields but with fields outside of it (Art and Computer Programing anyone?). Before Duchamp's dusruption, Art was a very well defined and distinguishable piece within the *machine*, as well as its internal elements -disciplines- were clearly separables. Although it had this double-sided knife quality it was quite easily managed into its *useful* state and keep its practicioners well identified, like gears and mechanical, solid pieces in an old machine. Nowadays Art has become an *aether*, a gaseous substance, within the machine, not only hard to identify but also capable of penetrating other pieces of the *machine* bluring their boundaries.
By using this ideas is quite easy to tell, conceptually speaking, what is Art; Art is any produce that is not clearly *useful*. But actually discriminating Art from non-Art, when such becomes an issue, is not easy because of the *useful* quality being highly subjective and because in many cases something just needs to be named as Art in order to become such.
This untamable eathereal quality of contemporary art is the new weapon. Rather more than a weapon itself it is camouflage; a highly sophisticated one that uses human perception and interpretation capacity as its vehicle.
<file_sep>---
layout: selector
selection: code
permalink: /code/
---
<div>
<h1>CODE</h1>
I usually upload code to my <a href="https://github.com/roymacdonald/">github account</a>
<br />
Although I pretend to put here more thorough explanations of what I've shared on github.
</div>
<file_sep>---
layout: portafolio
lang: en
permalink: /dma/
---
<file_sep>---
layout: post
date: 2018-04-09 12:10:00
categories:
- projects
tags: luminus prospectu, led mapping, luz, light
thumb: /thumbs/luminus.jpg
video_vimeo: 269480853
video_width: 958
video_height: 539
title: Luminus Prospectu
subtitle:
lang: en
---
Luminus Prospectu means light in perspective.
The scope of action of this work are the senses that perceive abstract depth -sound and vision-, focusing on the sound-and-light experimentation of perspective.
Different sound and light sources are set up in the space, whose arangement is based on Voronoi's geometric diagrams. These diagram's patterns are generated by spacial, structural and hierarchical relationships and can be found in nature and living beings, from micro to macro; human's sight and hearing sensing cells are aranged following this paterns.
The created compositions' light and sound evoke a raw atmosphere with 4 moments of intensity.
---
On the begining of 2018 I joined Trimex, an art collective and studio, of which I also became an associate. As a collective we were invited to make this piece to be shown in the Museo de Artes Visuales de Santiago (MAVI) (Museum of Visual Arts of Santiago), in the context of the inauguration of Barrio Arte (Art Neighborhood) between April 9th and 16th of 2018.
Trimex Crew: <NAME>, <NAME>, <NAME> y <NAME>.
Direction, Art direction: Andrés Terrisse.
Direction, architecture : <NAME>.
Direction, software coding: Roy Macdonald
Video documentation: Diego Miranda
Music: <NAME>
Set-up assistants: <NAME>, <NAME>, <NAME>, <NAME>.
Thanks: <NAME>, <NAME>, <NAME>agal
<file_sep>---
layout: post
date: 2007-03-01 12:10:00
categories:
- projects
tags: video
lang: en
thumb: /thumbs/videosu.jpg
title: Videoworks 2005-2007
---
All this works were done while I was attending the arts school.
I've always liked movies and moviemaking, but sometimes the process behind the movie catches my attention much more than the movie itself.
I began to research a lot about all the processes behind making a movie; scripting, filming, photography, montage, compositing, visual effects, etc.
With this research a lot of experiments came to life, some of which ended up being art pieces I used while I was studying in the art school.
In the two following videos I was playing with image compositing, tracking and stabilization in order to create a new view over certain scene.
### Choque
<iframe src="https://player.vimeo.com/video/1218997?byline=0&portrait=0" width="500" height="230" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
### Still
<iframe src="https://player.vimeo.com/video/1221671?byline=0&portrait=0" width="500" height="333" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
### B----
The following works around script, timing and multiple views of the same scene in order to create a dramatic tension. A lot of it is achieved during the montage, by removing and reordering parts of the original video material.
Chilean spanish is spoken on it; it wont make much sense to you if you don't understand Chilean Spanish.
<iframe src="https://player.vimeo.com/video/2372246?byline=0&portrait=0" width="500" height="333" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
### Untitled
The following is the work I presented in order to get my BA degree.
Arguably, amateur video recording can be perceived as the most objective kind of documentation or less mediated. The viewer tends to overcome the technology implied in it and can sense it as he was doing such recording, thus making it believable. Based on this premise and the fact that the "amateur" quality of such recordings is nothing more that a series of technical conditions, hence this conditions can get manipulated in order to create something that looks amateur but that depicts unbelievable scenes.
Although Chilean Spanish is spoken on it, it is not necessary to completely understand it in order to understand the whole.
<iframe src="https://player.vimeo.com/video/2373013?byline=0&portrait=0" width="500" height="333" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
<file_sep>---
layout: post
date: 2012-02-01 12:10:00
categories:
- work
tags: interactive kinect
video_vimeo: 29583432
video_width: 958
video_height: 538
thumb: /thumbs/estrellitas.jpg
title: Nestlé's Estrellitas Cereal Kinect Game
macrobio: true
lang: en
---
We were commissioned to develop a game using the Microsoft Kinect sensor for an AD campaign of Nestlé's Estrellitas Cereal.
As far as I understand this was the first use of the Kinect Sensor in an AD campaign in Chile.
By detecting arm gestures, the user had to free a spaceship trapped by space debris, by throwing tiny stars (Estrellitas) towards it.
I developed this work while I was still working at Macrobio (I was one of the owners/partners, lead developer and project director).
<file_sep>---
layout: post
date: 2013-03-01 12:10:00
categories:
- work
tags: ios
thumb: /thumbs/appios.jpg
title: iOS Apps
lang: en
---
I've developed several iOS apps for specific events. From networked games to invitee registry to interactive brochures.
<iframe src="https://player.vimeo.com/video/63762719?byline=0&portrait=0" width="500" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
<iframe src="https://player.vimeo.com/video/63751065?byline=0&portrait=0" width="500" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
<iframe src="https://player.vimeo.com/video/36101746?byline=0&portrait=0" width="500" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
<iframe src="https://player.vimeo.com/video/25483555?byline=0&portrait=0" width="500" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
| c0b8d0919a2fcba8bc665aa107d64d73b3ec9019 | [
"Markdown",
"JavaScript",
"HTML"
] | 51 | Markdown | roymacdonald/roymacdonald.github.io | e782d8ebb6db87a9322f9a1a11a0100471f87cf5 | f83767a84a86e2be94f86a82b8beb330303c03c7 | |
refs/heads/master | <repo_name>akashkumar916/Bobble_internship_answer<file_sep>/Solution_2.cpp
#include<bits/stdc++.h>
using namespace std;
#define ll long long
//Number of alphabet
const int alpha=26;
//Structure for my tree
struct trie{
trie* children[alpha];
bool is_leaf;
};
//Making the new node
trie* new_node(){
trie* temp=new trie();
for(int i=0;i<alpha;i++){
temp->children[i]=NULL;
}
temp->is_leaf=false;
}
//Inserting each character of string in a tree
void insert(trie* root,string m){
trie* temp=root;
for(int i=0;i<m.size();i++){
int index=m[i]-'a';
if(!temp->children[index]){
temp->children[index]=new trie();
}
temp=temp->children[index];
}
temp->is_leaf=true;
}
//Traversing the tree
void traverse(trie* root,string s,vector<string>&ouput){
if(root->is_leaf==true){
//s[index]='\0';
ouput.push_back(s);
}
for(int i=0;i<alpha;i++){
if(root->children[i]){
s.push_back(i+'a');
traverse(root->children[i],s,ouput);}
}
}
//creating the tree through this function
vector<string> create(vector<string>&v){
trie* root=new_node();
for(int i=0;i<v.size();i++){
insert(root,v[i]);
}
vector<string>ouput;
string s;
traverse(root,s,ouput);
sort(v.begin(),v.end());
ouput=v;
return v;
}
//traversing the tree this function
void load(vector<string>&v){
vector<string>output=create(v);
for(int i=0;output.size();i++){
cout<<output[i]<<endl;
}
}
//Main Driven function
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
fstream fin, fout;
fin.open("input.csv", ios::in); //Reading the input.csv file
vector<string>output; //storing the ouput string
cout<<"1. create"<<endl<<"2. load"<<endl;
int choice;
vector<string>v; //stroing the string input from input.csv
string line,word;
while( getline(fin, line)){
stringstream s(line);
while (getline(s, word, ',')) {
v.push_back(word);
}
}
cin>>choice;
if(choice==1){
//Creating the character tree
output=create(v);
//storing the output string in output.csv
fout.open("output.csv",ios::out);//output.csv file
for(int i=0;i<output.size();i++){
fout<<output[i]<<", "; //every string into ouput
}
}
else {
// loading and recreate the tree and print it.
load(v);
}
return 0;
}<file_sep>/Solution_3.cpp
#include<bits/stdc++.h>
using namespace std;
#define ll long long
//Number of alphabet
const int alpha=26;
//Structure for my tree
struct trie{
trie* children[alpha];
bool is_leaf;
};
//Making the new node
trie* new_node(){
trie* temp=new trie();
for(int i=0;i<alpha;i++){
temp->children[i]=NULL;
}
temp->is_leaf=false;
}
//Inserting each character of string in a tree
void insert(trie* root,string m){
trie* temp=root;
for(int i=0;i<m.size();i++){
int index=m[i]-'a';
if(!temp->children[index]){
temp->children[index]=new trie();
}
temp=temp->children[index];
}
temp->is_leaf=true;
}
// Returns 0 if current node has a child
// If all children are NULL, return 1.
bool isLastNode(trie* root)
{
for (int i = 0; i < alpha; i++)
if (root->children[i])
return 0;
return 1;
}
//suggestions
void bobblesugg(trie* root, string curr,std::vector<string>& output)
{
// found a string in Tree with the given prefix
if (root->is_leaf)
{
if(output.size()==5)return;//only 5 word sugesstion
output.push_back(curr);
}
// All children struct node pointers are NULL
if (isLastNode(root))
return;
for (int i = 0; i < alpha; i++)
{
if (root->children[i])
{
// append current character to currPrefix string
curr.push_back(97 + i);
// recur over the rest
bobblesugg(root->children[i], curr,output);
// remove last character
curr.pop_back();
}
}
}
// print suggestions for given query string
int print(trie* root, const string q)
{
trie* curr = root;
int level;
int n = q.length();
for (level = 0; level < n; level++)
{
int index = q[level]-'a';
// no string in the Tree
if (!curr->children[index])
return 0;
curr=curr->children[index];
}
// If prefix is present as a word.
bool is_leaf = (curr->is_leaf == true);
bool isLast = isLastNode(curr);
if (is_leaf && isLast)
{
cout << q << endl;
// no string found
return -1;
}
// If there are are nodes below
std::vector<string> output;
//output.push_back("-1"); //storing all output strings
if (!isLast)
{
string prefix = q;
bobblesugg(curr, prefix,output);
}
while(output.size()<5){
output.push_back(q);
}
//cout<<output.size();
//printing the string array
for(int i=0;i<5;i++){
cout<<output[i]<<", ";
}
}
// Main Driver Code
int main()
{
trie* root = new_node();
ios_base::sync_with_stdio(false);
cin.tie(0);
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
fstream fin, fout;
fin.open("input.csv", ios::in); //Reading the input.csv file
vector<string>v; //storing the string input from input.csv
string line,word;
//reading every line by line
while( getline(fin, line)){
stringstream s(line);
//reading specefic line
while (getline(s, word, ',')) {
if(isdigit(word[0])==false)v.push_back(word); //only string allowed
}
}
for(int i=0;i<v.size();i++)insert(root,v[i]);//inserting
//string to find
string string_to_find;
cin>>string_to_find;
//printing all suggestions
print(root,string_to_find);
return 0;
}
<file_sep>/Solution1.cpp
#include<bits/stdc++.h>
using namespace std;
#define ll long long
//recursive function to calculate all permutation
void recursive_cal(int i, string s, vector< vector<char> > v)
{
if (i >= (int) v.size()) {
cout << s << ", ";
return;
}
for (char c:v[i]) {
s.push_back(c);
recursive_cal(i + 1, s, v);
s.pop_back();
}
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
vector< vector<char> >v// storing dynamic array
string line,word;
fstream fin, fout;
fin.open("input.csv", ios::in); //Reading the input.csv file
//reading every line by line
while(getline(fin, line)){
stringstream s(line);
vector<char>temp; // will contains all character of first line of csv file
int i=0;
while (getline(s, word, ',')) {
if(i==0){temp.push_back(word[1]);i=1;} //if first word of line then store 2nd character
else {temp.push_back(word[2]);} //else store 3rd character
}
v.push_back(temp);
}
//recursive solution to printing all permutation
recursive_cal(0, "", v);
return 0;
}
<file_sep>/README.md
# Booble_internship_answer
**Assignment solutios for all 3 Questions**
**Questions 1: Permutations**<br/><br/>
First I extract all words like ('a', 'b', 'c') from dynamic array in every line and store in my container
and then use a recursive approach to calculate all permutations.<br/><br/>
1 Functions</br>
<ul>
<li>recursive_call(): Calculate all different permutation for the dynamic array</li>
</ul>
<br/>
<br/>
<br/>
**Question 2:Character Tree serialization**
<br/>
<br/>
Data Structure used: Tree
<br/>
4 Functions<br/>
<ul>
<li>Insert(): Make a tree and Inserting the characters in thr tree</li>
<li>Traverse(): Traversing the tree</li>
<li>Create(): Read words from the CSV file, create tree of characters and then serialize it and save it to the file-path accepted after csv file name</li>
<li>Load(): Read the serialized file, recreate the character tree and print all the words present in the tree.</li>
</ul>
<br/>
<br/>
<br/>
**Question 3:Word suggestions**
<br/>
<br/>
first I used Trie data structure which used a very unique and efficient approach to insert all the string and then extract first 5 string which is starting from that prefix or query string .<br/><br/>
Data structure used: Trie (most efficient for information retrieval)
<br/>
4 Functions</br>
<ul>
<li>Insert(): Make a tree and Inserting the characters in thr tree</li>
<li>Traverse(): Traversing the tree</li>
<li>booblesugg(): Helping function for print function</li>
<li>Print(): Print 5 word suggestions .</li>
</ul>
<br/>
| 9da0a2685611d8e690a36878ca027df84468331d | [
"Markdown",
"C++"
] | 4 | C++ | akashkumar916/Bobble_internship_answer | f80962a55e77c54908836aa8711966a8b5046084 | 8ac6e8a15ac44cd25207c2c4d3505dc7e8b06075 | |
refs/heads/master | <repo_name>ZFK07/Digitized-Elibrary<file_sep>/E Library/.picasa.ini
[4.JPG]
backuphash=6849
[4 - Copy.JPG]
filters=finetune2=1,0.000000,0.000000,0.000000,00000000,0.017544;
backuphash=8373
[11855917_10153226486778411_1021952139985994376_n.jpg]
backuphash=10538
[principal.jpg]
backuphash=36757
<file_sep>/article/js.js
function raisethumb( this ) {
alert("i am in")
//alert(this.lastchild)
}
function Article() {
var temp = document.getElementById('box')
var err = document.getElementById("errmsg")
if (temp.value == "") {
err.innerHTML = "<p class=\"alert alert-danger\"><i class=\"glyphicon glyphicon-remove-sign\" style = \"font-size : 20px;\"></i> Write Article To Post!\
<a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a></p>";
err.style.display = "block";
temp.focus()
}
else{
err.innerHTML = "<p class=\"alert alert-success\"> <i class=\"glyphicon glyphicon-ok-sign \" style = \"font-size : 20px;\"></i>The Article Can Be Posted Successfully.\
<a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>\
</p>"; //will clear the Error msg
}
}
var fixed = false;
$(document).scroll(function() {
if ($(this).scrollTop() > 250) {
$('#scroll').show(1000, function() {
$('#scroll').css({
position: 'fixed',
}); //scroll
}); //scroll function
} else {
$('#scroll').hide(300, function() {
$('#scroll').css({
display: 'none'
});
});
} //else
});
//End Of scroll function
<file_sep>/E Library/reviews/.picasaoriginals/.picasa.ini
[phato.jpg]
rotate=rotate(3)
moddate=589f670ab42cd001
width=3264
height=2448
textactive=0
<file_sep>/README.md
# Digitized-Elibrary
Digitised online library.
<file_sep>/E Library/reviews/.picasa.ini
[phato.jpg]
backuphash=23530
| cffe05cff9a9a9620cd57b6b1418f744e77c55ba | [
"JavaScript",
"Markdown",
"INI"
] | 5 | INI | ZFK07/Digitized-Elibrary | 9368dda96f809d682bbe7e7c891990f5e738039b | b4b884c81fbec6289d28d41e47387926efa01af5 | |
refs/heads/master | <file_sep>'use strict';
import './../assets/css/master.css';
import angular from 'angular';
import ngAnimate from 'angular-animate';
import uiRouter from 'angular-ui-router';
import routing from './app.config';
import header from './directives/_shared/header';
import nav from './directives/_shared/nav';
import sideBar from './directives/_shared/sideBar';
import usersTable from './routes/usersTable.module.js'
import dashboard from './routes/dashboard.module.js'
export default angular.module('app', [
uiRouter,
ngAnimate,
dashboard.name,
usersTable.name,
header.name,
nav.name,
sideBar.name
]).config(routing);
<file_sep>'use strict';
var bcrypt = require('bcrypt');
var connection = require('../connections/postgres');
var _ = require('lodash');
module.exports = {
getUsers: () => {
return new Promise((resolve, reject) => {
connection.then((client) => {
client.query('SELECT * FROM users', (err, result) => {
if (err) { return reject(err) }
resolve(result.rows);
});
});
});
},
getUser: (props) => {
return new Promise((resolve, reject) => {
connection.then((client) => {
client.query(
'SELECT * FROM users WHERE user_id = $1',
[props.userId],
(err, result) => {
if (err) { return reject(err); }
resolve(result.rows);
}
)
});
});
},
editUser: (props, params) => {
return new Promise((resolve, reject) => {
params = _.pick(params, ["user_name", "first_name", "last_name", "password"]);
var i = 1;
var query = ['UPDATE users', 'SET'];
var set = [];
var values = [];
_.forOwn(params, (value, key) => {
set.push(key + ' = ($' + i + ')');
values.push(value);
i++;
});
query.push(set.join(', '));
query.push('WHERE user_id = ' + props.userId + ' RETURNING *');
query = query.join(' ');
connection.then((client) => {
client.query(
query,
values,
(err, result) => {
if (err) { return reject(err); }
resolve(result.rows[0]);
}
)
});
});
},
comparePassword: (props) => {
return new Promise((resolve, reject) => {
connection.then((client) => {
client.query(
'SELECT * FROM users WHERE user_name = $1',
[props.userName],
(err, result) => {
if (err) { return reject(err); }
if (!result.rows.length) { return resolve(false); }
bcrypt.compare(props.password, result.rows[0].password_hash, (err, same) => {
if (err) { return reject(err); }
if (!same) { return resolve(false); }
return resolve(result.rows[0]);
});
}
)
});
})
},
createUser: (props) => {
return new Promise((resolve, reject) => {
bcrypt.hash(props.password, 10, (err, hash) => {
if (err) { return; }
connection.then((client) => {
client.query(
'INSERT INTO users (first_name, last_name, user_name, password_hash) VALUES($1, $2, $3, $4) RETURNING *',
[props.first_name, props.last_name, props.user_name, hash],
(err, result) => {
if (err) { return reject(err); }
resolve(result.rows[0]);
});
});
});
});
},
deleteUser: (props) => {
return new Promise((resolve, reject) => {
connection.then((client) => {
client.query(
'DELETE FROM users WHERE user_id = $1',
[props.userId],
(err, result) => {
if (err) { return reject(err); }
resolve(result);
}
)
});
});
}
};
<file_sep>import angular from 'angular';
import ngAnimate from 'angular-animate';
export default angular.module('directives.sideBar', [ngAnimate])
.directive('sideBar', () => {
return {
restrict: 'E',
templateUrl: 'templates/sideBar.html',
replace: true,
controller: ($scope) => {
$scope.elements = [1,2,3];
$scope.linkClicked = (index) => {
console.log(index);
};
$scope.bool = true;
}
};
});
<file_sep>routes.$inject = ['$stateProvider'];
export default function routes($stateProvider) {
$stateProvider
.state('usersTable', {
url: '/users-table',
templateUrl: 'templates/usersTable.html'
});
}
<file_sep>'use strict';
import angular from 'angular';
export default angular.module('directives.header', [])
.directive('header', () => {
return {
restrict: 'E',
templateUrl: 'templates/header.html',
controller: ($scope) => {
console.log($scope);
},
link: function (scope, element, attrs) {
console.log(scope);
}
}
});
<file_sep>import angular from 'angular';
import uiRouter from 'angular-ui-router';
import routing from './usersTable';
import usersTable from './../directives/_shared/usersTable';
export default angular.module('app.usersTable', [uiRouter])
.config(routing)
.directive('usersTable', usersTable);
<file_sep>'use strict';
var config = require('./src/services/config');
var express = require('express');
var expressJWT = require('express-jwt');
var app = express();
app.use((err, req, res, next) => { console.log(err); });
//app.use(expressJWT({secret: config.secret}).unless({path: ['/sessions', '/users']}));
app.use(require('http-responses'));
app.use(require('body-parser').json());
app.use('/users', require('./src/controllers/user'));
app.use('/sessions', require('./src/controllers/session'));
app.listen(config.port);
<file_sep>'use strict';
var express = require('express');
var router = express.Router();
var _ = require('lodash');
var User = require('../models/user');
router.get('/', (req, res) => {
User.getUsers()
.then((result) => {
res.ok(result);
})
.catch((err) => {
console.log(err);
res.InternalServerError('Internal Server Error');
});
});
router.get('/:userId', (req, res) => {
User.getUser(req.params)
.then((result) => {
res.ok(result);
})
.catch((err) => {
console.log(err);
res.InternalServerError('Internal Server Error');
});
});
router.patch('/:userId', (req, res) => {
User.editUser(req.params, req.body)
.then((result) => {
res.ok(result);
})
.catch((err) => {
console.log(err);
res.InternalServerError('Internal Server Error');
});
});
router.post('/', (req, res) => {
User.createUser(req.body)
.then((result) => {
res.ok(result);
})
.catch((err) => {
if (err.message.indexOf('violates unique constraint') > -1) { return res.ok({error: 'Username already exists.'}); }
res.InternalServerError(err.message);
});
});
router.delete('/:userId', (req, res) => {
User.deleteUser(req.params)
.then((result) => {
res.ok();
})
.catch((err) => {
console.log(err);
res.InternalServerError('Internal Server Error');
})
});
module.exports = router;
<file_sep>'use strict';
module.exports = {
port: 3000,
postgres: 'postgres://rpasqualone@localhost/etms2',
secret: 'I love <NAME>'
};
<file_sep>import angular from 'angular';
export default angular.module('directives.nav', [])
.directive('nav', () => {
return {
restrict: 'E',
templateUrl: 'templates/nav.html',
replace: true,
controller: ($scope) => {
$scope.elements = [1,2,3];
$scope.linkClicked = (index) => {
console.log(index);
};
}
};
});
<file_sep>import angular from 'angular';
import ngAnimate from 'angular-animate';
export default angular.module('directives.usersTale', [ngAnimate])
.directive('dashboard', () => {
return {
restrict: 'E',
templateUrl: 'templates/dashboard.html',
replace: true,
controller: ($scope) => {
$scope.elements = [1,2,3];
$scope.linkClicked = (index) => {
console.log(index);
};
}
};
});
<file_sep>'use strict';
var config = require('../services/config');
var pg = require('pg');
module.exports = new Promise((resolve) => {
var client = new pg.Client(config.postgres);
client.connect((err) => {
if (err) { throw err; }
resolve(client);
});
});
| a6dbead3a16080a69ac75c6acaf62b838d1ab498 | [
"JavaScript"
] | 12 | JavaScript | rpasqualone/etms_v2 | 7fd7d0d8538fdc941d9c98d4f0b3fc7121b4ad48 | 8cc9a04d727f9fabe6f7e4e9a90eb2cdf4becbd1 | |
refs/heads/master | <repo_name>MewenLr/dummies<file_sep>/dummylib/README.md
# dummylib
## Steps
- create folder /libray
- run cmd build library
- add main entry in package.json
- import library and style in project
<file_sep>/dummylib/src/test.js
import DummyButton from './components/DummyButton.vue'
export default DummyButton
<file_sep>/dummylib/src/library/generate.js
const fs = require('fs')
const glob = require('glob')
const path = require('path')
const templateComponents = require('./template.js')
function getComponents(callback) {
glob('src/components/**/*.vue', callback)
}
function handleResult(err, res) {
if (err) {
console.error('Error', err)
process.exit(1)
} else {
const re = /.*\/+(.*).vue$/
const components = res.reduce((result, element) => {
if (!element.includes('Index.vue')) {
result.push({
name: element.replace(re, '$1'),
path: element.replace(/src\//, '@/'),
})
}
return result
}, [])
const outputPath = path.resolve(__dirname, './components.js')
fs.writeFileSync(outputPath, templateComponents(components))
}
}
getComponents(handleResult)
| 561e87ab475956a9fbda545207906742555105f0 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | MewenLr/dummies | 500ae64e60c9f691b3032e69335dc55d94eeb82a | e0e0304f5e524c85759d9a0fedccce58fb89f37b | |
refs/heads/main | <repo_name>lynch0571/idiom-game<file_sep>/README.md
# idiom-game
成语接龙(ChengYuJieLong)小游戏,使用图论(Graph Theory)和递归(Recursion)等算法实现成语接龙和求特殊成语链,如自环、N连环、Max链等。
## 使用图论中的有向邻接矩阵描述成语之间的关系
#### 邻接矩阵(Adjacency Matrix)概念
> 简单来说,邻接矩阵是表示顶点之间相邻关系的矩阵,图论问题经常会用到。 设G=(V,E)是一个图,其逻辑结构分为两部分:V和E集合,其中,V是顶点,E是边。 因此,用一个一维数组存放图中所有顶点数据;用一个二维数组存放顶点间关系(边或弧)的数据,这个二维数组称为邻接矩阵。
邻接矩阵又分为有向图邻接矩阵和无向图邻接矩阵。成语接龙问题显然是有方向的,A的下一个成语是B,但B的下一个成语不一定是A,也不一定不是A,具体定义如下。
**定义**:
设M=(X,Y)为有向邻接矩阵,X和Y均为成语的全集,X代表行,Y代表列,Xn为第n个成语x,x0为成语x的第一个字,x1为成语x的最后一个字,Y同理。
+ 0-无连接:x1!=y0且y1!=x0
+ 1-xy连接:x1=y0且y1!=x0
+ 2-yx连接:y1=x0且x1!=y0
+ 3-双向连接:x1=y0且y1=x0
示例:
```
| x1 x2 x3 x4
------|----------------------------------------
| 木秀于林 林寒洞肃 花好月圆 防不胜防
y1|木秀于林 0 2 0 0
y2|林寒洞肃 1 0 0 0
y3|花好月圆 0 0 0 0
y4|防不胜防 0 0 0 3
|
```<file_sep>/src/main/java/com/lynch/idiom/entity/Idiom.java
package com.lynch.idiom.entity;
import lombok.Data;
/**
* 成语实体类
*
* @author Lynch
* @date 2020-12-16
*/
@Data
public class Idiom {
/**
* 成语名称,如:花好月圆
*/
private String name;
/**
* 成语的第一个字,如:花
*/
private String head;
/**
* 第一个字的拼音,如:huā
*/
private String headSymbol;
/**
* 成语的最后一个字,如:圆
*/
private String tail;
/**
* 最后一个字的拼音,如:yuán
*/
private String tailSymbol;
/**
* 成语的出处,如:宋·张先《木兰花》词:“人意共怜花月满,花好月圆人又散。欢情去逐远云空,往事过如幽梦断。”
*/
private String derivation;
/**
* 成语的解释,如:花儿正盛开,月亮正圆满。比喻美好圆满的生活,多用作新婚颂辞。
*/
private String explanation;
}
<file_sep>/src/test/java/com/lynch/idiom/IdiomGameApplicationTests.java
package com.lynch.idiom;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class IdiomGameApplicationTests {
@Test
void contextLoads() {
}
}
<file_sep>/src/main/java/com/lynch/idiom/utils/StringUtil.java
package com.lynch.idiom.utils;
import java.util.Stack;
/**
* 字符串工具类
*
* @author Lynch
* @date 2020-12-04
*/
public final class StringUtil {
private StringUtil() {
}
/**
* Check if the String is null or has only whitespaces.
* Modified from {org.apache.commons.lang.StringUtils#isBlank(String)}.
*
* @param string String to check
* @return {@code true} if the String is null or has only whitespaces
*/
public static boolean isBlank(String string) {
if (isEmpty(string)) {
return true;
}
for (int i = 0; i < string.length(); i++) {
if (!Character.isWhitespace(string.charAt(i))) {
return false;
}
}
return true;
}
/**
* Check if the String has any non-whitespace character.
*
* @param string String to check
* @return {@code true} if the String has any non-whitespace character
*/
public static boolean isNotBlank(String string) {
return !isBlank(string);
}
/**
* Check if the String is null or empty.
*
* @param string String to check
* @return {@code true} if the String is null or empty
*/
public static boolean isEmpty(String string) {
return string == null || string.isEmpty();
}
/**
* Check if the String has any character.
*
* @param string String to check
* @return {@code true} if the String has any character
* @since 1.1.0
*/
public static boolean isNotEmpty(String string) {
return !isEmpty(string);
}
/**
* 用栈解决括号匹配问题,实现数据格式化
*
* @param str
* @return
*/
public static String getFormatData(String str) {
Stack<Character> st = new Stack<>();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '{' || str.charAt(i) == '[' || str.charAt(i) == '(') {
st.push(str.charAt(i));
sb.append(str.charAt(i));
sb.append('\n');
for (int j = 0; j < st.size(); j++) {
sb.append('\t');
}
} else if (str.charAt(i) == '}' || str.charAt(i) == ']' || str.charAt(i) == ')') {
st.pop();
sb.append('\n');
for (int j = 0; j < st.size(); j++) {
sb.append('\t');
}
sb.append(str.charAt(i));
} else if (str.charAt(i) == ',') {
sb.append(str.charAt(i)).append("\n");
for (int j = 0; j < st.size(); j++) {
sb.append('\t');
}
} else if (str.charAt(i) != ' ') {
sb.append(str.charAt(i));
}
}
return sb.toString();
}
}<file_sep>/src/main/java/com/lynch/idiom/utils/IdiomUtil.java
package com.lynch.idiom.utils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
/**
* @author Lynch
* @date 2020-12-16
*/
@Slf4j
public class IdiomUtil {
private static final String idiomPath = "/Users/fire/git/idiom-game/src/main/resources/static/";
public static void main(String[] args) {
createIdiomSimpleJson();
}
/**
* 根据原始成语库生成简略版成语库,大约能压缩十倍内容,为后续处理提高效率
*/
private static void createIdiomSimpleJson() {
try {
List<String> lines = Files.readAllLines(Paths.get(idiomPath + "idiom.json"));
StringBuilder sb = new StringBuilder();
lines.forEach(e -> sb.append(e));
JSONArray info = JSONObject.parseArray(sb.toString());
StringBuilder wordSb = new StringBuilder();
info.stream().forEach(e -> {
JSONObject item = (JSONObject) e;
String word = item.getString("word");
/*全角空格替换为半角空格*/
String pinyin = item.getString("pinyin").replace(" ", " ");
wordSb.append(word).append("(").append(pinyin).append(")").append("\n");
});
Files.write(Paths.get(idiomPath + "idiomSimple.json"), wordSb.toString().getBytes());
log.info("创建精简成语json文件成功!共{}个成语。", info.size());
} catch (IOException e) {
log.info("创建精简成语json文件失败!e:{}", e.getMessage());
}
}
}
| bff2d9075c9748e14178090346676bc1586d2a84 | [
"Markdown",
"Java"
] | 5 | Markdown | lynch0571/idiom-game | d4dc9915191e4a009dd06738a3c3aac3d8634819 | 5891f3942f8dd9194738df1fc3e86a38f1e566a9 | |
refs/heads/master | <repo_name>Justin-Collier/sweetshoelaces<file_sep>/public/script.js
/* Project: Individual Student Project
Author: <NAME>
Date: Mar 1, 2017
Purpose:
*/
//function to add values of selected check boxes and display total.
// array storing products to display
var products = ["S round shoelace ($1)", "M round shoelace ($1.50)", "L round shoelace ($2)", "XL round shoelace ($2.50)", "S flat shoelace ($1)", "M flat shoelace ($1.50)", "L flat shoelace ($2)", "XL flat shoelace ($2.50)"];
// matching array of label elements
var labels = document.getElementsByTagName("label");
// function to generate list from array
function processProducts() {
for (var i = 0; i < 8; i++) { //write each array elements to their corresponding label
// OLD CODE: listItem = "item" + (i + 1);
labels[i].innerHTML = products[i];
}
}
if (window.addEventListener) {
window.addEventListener("load", processProducts, false);
} else if (window.attachEvent) {
window.attachEvent("onload", processProducts);
}
//function below adds values of the checked boxes and then displays the total
function calcTotal()
{
var itemTotal = 0;
var salesTaxRate = .06; //creates the sales tax
var items = document.getElementsByTagName("input");
for (var i = 0; i < 8; i++) {
if (items[i].checked) {
itemTotal += (items[i].value * 1);
}
}
itemTotal *= 1+ salesTaxRate; //Creates a total that includes sales tax
document.getElementById("total").innerHTML = "Your Sweet Shoelace order total is $" + itemTotal.toFixed(2); //creates a notification of the item total and sets the order total the hundreth decimal
}
//Below adds backwards compatible event listener to Submit button
var submitButton = document.getElementById("sButton");
if (submitButton.addEventListener) {
submitButton.addEventListener("click", calcTotal, false);
} else if (submitButton.attachEvent) {
submitButton.attachEvent("onclick", calcTotal);
}
/* Old function
function calcTotal() {
var itemTotal = 0 //stores a running total of selected items
var item1 = document.getElementById("item1");
var item2 = document.getElementById("item2");
var item3 = document.getElementById("item3");
var item4 = document.getElementById("item4");
var item5 = document.getElementById("item5");
var item6 = document.getElementById("item6");
var item7 = document.getElementById("item7");
var item8 = document.getElementById("item8");
(item1.checked) ? (itemTotal += 1) : (itemTotal += 0); //lines 17-24 create the item value
(item2.checked) ? (itemTotal += 1.50) : (itemTotal += 0);
(item3.checked) ? (itemTotal += 2) : (itemTotal += 0);
(item4.checked) ? (itemTotal += 2.50) : (itemTotal += 0);
(item5.checked) ? (itemTotal += 1) : (itemTotal += 0);
(item6.checked) ? (itemTotal += 1.50) : (itemTotal += 0);
(item7.checked) ? (itemTotal += 2) : (itemTotal += 0);
(item8.checked) ? (itemTotal += 2.50) : (itemTotal += 0);
var salesTaxRate = 0.06; //factor for sales tax
var orderTotal = itemTotal + (itemTotal * salesTaxRate); //creates an order total of the purchase total multiplied by the sales tax
alert("Your Sweet Shoelace order total is $" + orderTotal); //creates a pop up box displaying the total
}
document.getElementById("submit").addEventListener("click", calcTotal, false) //the event listener to call the function */ | e089d00f3887e5fd9d2bfa85e007355ff3e0a990 | [
"JavaScript"
] | 1 | JavaScript | Justin-Collier/sweetshoelaces | 15de49769c829f552a1274bbe872290a22051913 | 12adecd0155e8ab3c1e5c5f8a168a1f09d0c57be | |
refs/heads/master | <repo_name>cherrry/static-tag-cloud<file_sep>/src/tag-cloud.js
'use strict'
var assign = require('object-assign')
var distribute = require('./distribute')
var shuffle = require('./shuffle')
var DEFAULT_NUM_OF_BUCKETS = 4
var tagCloud = function (tagDefs, options) {
// only process tags with positive count
tagDefs = tagDefs.filter(function (tagDef) { return tagDef.count > 0 })
if (tagDefs.length === 0) return []
var numOfBuckets = (options && options.numOfBuckets) || DEFAULT_NUM_OF_BUCKETS
return shuffle(distribute(tagDefs, numOfBuckets))
}
module.exports = tagCloud
<file_sep>/src/shuffle.js
'use strict'
var stringHash = require('./string-hash')
var tagHash = require('./tag-hash')
var tagKey = require('./tag-key')
// A pseudo-random shuffle function
var shuffle = function (tagDefs) {
// special M for hashing tagDefs
var M = stringHash(tagDefs.map(tagKey).sort().join(','))
var tagDefsByHashKey = {}
tagDefs.forEach(function (tagDef) {
var hashKey = tagHash(tagDef, M)
tagDefsByHashKey[hashKey] = tagDef
})
return Object.keys(tagDefsByHashKey)
.filter(function (key) { return tagDefsByHashKey.hasOwnProperty(key) })
.sort()
.map(function (hashKey) {
return tagDefsByHashKey[hashKey]
})
}
module.exports = shuffle
<file_sep>/src/string-hash.js
'use strict'
// Two carefully selected primes
var P1 = 43063
var P2 = 48611
var stringHash = function (string, p1, p2) {
p1 = p1 || P1
p2 = p2 || P2
var hash = 0
for (var i = 0, _len = string.length; i < _len; i++) {
var code = string.charCodeAt(i)
hash = ((((hash * p1) % p2) + code) * p1) % p2
}
return hash
}
module.exports = stringHash
<file_sep>/README.md
# Static Tag Cloud
A deterministic tag cloud generator which always gives the same output upon the same input.
## Install
```sh
$ npm install --save static-tag-cloud
```
## Usage
```js
import tagCloud from 'static-tag-cloud'
tagCloud([
{ id: 'apple', count: 1 },
{ id: 'boy', count: 2 },
{ id: 'cat', count: 4 },
{ id: 'dog', count: 1 }
])
/*
[
{ bucket: 2, id: 'apple', count: 1 },
{ bucket: 2, id: 'dog', count: 1 },
{ bucket: 2, id: 'boy', count: 2 },
{ bucket: 4, id: 'cat', count: 4 }
]
*/
```
<file_sep>/src/distribute.js
'use strict'
var assign = require('object-assign')
// assign bucket number
var distribute = function (tagDefs, numOfBuckets) {
var length = tagDefs.length
var counts = tagDefs.map(function (tagDef) {
return tagDef.count
}).sort()
var step = tagDefs.length / numOfBuckets
var upperBounds = []
for (var i = 0; i < numOfBuckets; i++) {
var from = Math.min(length - 1, Math.max(0, Math.round(i * step)))
upperBounds.push(counts[from])
}
var findBucket = function (count) {
if (count === counts[0]) {
return 1
}
var bucket = 1
while (bucket < numOfBuckets && count >= upperBounds[bucket]) {
bucket++
}
return bucket
}
return tagDefs.map(function (tagDef) {
return assign({ bucket: findBucket(tagDef.count) }, tagDef)
})
}
module.exports = distribute
<file_sep>/src/tag-hash.js
'use strict'
var stringHash = require('./string-hash')
var tagKey = require('./tag-key')
var tagHash = function (tagDef, P1, P2) {
return stringHash(tagKey(tagDef), P1, P2)
}
module.exports = tagHash
<file_sep>/index.js
var tagCloud = require('./src/tag-cloud')
module.exports = tagCloud
| ab33d75445083a5650a9113e5fb7e69e07e75041 | [
"JavaScript",
"Markdown"
] | 7 | JavaScript | cherrry/static-tag-cloud | 331fc27204da4a4614dc043acd6f85ce1a040002 | 7121849cfe61dcba21b9f404857b5c550b8f6c08 | |
refs/heads/master | <repo_name>ShenGX1992/WebSocket<file_sep>/README.md
# WebSocket
WebSocket-transferClient:基于Qt编写WebSocket通讯客户端
<file_sep>/transferclient.cpp
#include "transferclient.h"
#include "ui_transferclient.h"
TransferClient::TransferClient(const QUrl &url, QWidget *parent) :
QDialog(parent),
m_url(url),
ui(new Ui::TransferClient)
{
ui->setupUi(this);
setWindowFlags(Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint);
setWindowModality(Qt::ApplicationModal);
move((QApplication::desktop()->width() - width()) / 2,
(QApplication::desktop()->height() - height()) / 2);
}
TransferClient::~TransferClient()
{
delete ui;
}
void TransferClient::onConnected()
{
ui->listWidget->addItem("WebSocket connected");
qDebug() << "WebSocket connected";
QObject::connect(&m_webSocket, &QWebSocket::textMessageReceived,
this, &TransferClient::onTextMessageReceived);
}
void TransferClient::unConnected()
{
ui->listWidget->addItem( "WebSocket connected failed");
qDebug() << "WebSocket connected failed";
}
void TransferClient::closed()
{
ui->listWidget->addItem( "WebSocket closed");
qDebug() << "WebSocket closed";
m_webSocket.close();
}
void TransferClient::onTextMessageReceived(QString message)
{
QString RECstring = "Receive:";
RECstring.append(message);
ui->listWidget->addItem(RECstring);
qDebug() << "Message received:" << message;
}
void TransferClient::on_pushButton_connect_clicked()
{
QString URLstring = "WebSocket server:";
URLstring.append(m_url.toString());
ui->listWidget->addItem(URLstring);
qDebug() << "WebSocket server:" << m_url;
/*QObject::*/connect(&m_webSocket, &QWebSocket::connected, this, &TransferClient::onConnected);
/*QObject::*/connect(&m_webSocket, &QWebSocket::disconnected, this, &TransferClient::unConnected);
m_webSocket.open(QUrl(m_url));
}
void TransferClient::on_pushButton_disconnect_clicked()
{
ui->listWidget->addItem( "WebSocket closed");
qDebug() << "WebSocket closed";
m_webSocket.close();
}
void TransferClient::on_pushButton_send_clicked()
{
ui->listWidget->addItem("Text Send");
m_webSocket.sendTextMessage(ui->lineEdit_input->text());
}
void TransferClient::on_pushButton_Quit_clicked()
{
m_webSocket.close();
close();
}
<file_sep>/transferclient.h
#ifndef TRANSFERCLIENT_H
#define TRANSFERCLIENT_H
#include <QDialog>
#include <QtCore/QObject>
#include <QtWebSockets/QWebSocket>
#include <QKeyEvent>
#include <QThread>
#include <QTimer>
#include <cmath>
#include <QDebug>
#include <QMouseEvent>
#include <QDesktopWidget>
namespace Ui {
class TransferClient;
}
class TransferClient : public QDialog
{
Q_OBJECT
public:
explicit TransferClient(const QUrl &url,QWidget *parent = 0);
~TransferClient();
private Q_SLOTS:
void onConnected();
void unConnected();
void closed();
void onTextMessageReceived(QString message);
void on_pushButton_connect_clicked();
void on_pushButton_disconnect_clicked();
void on_pushButton_send_clicked();
void on_pushButton_Quit_clicked();
private:
Ui::TransferClient *ui;
QWebSocket m_webSocket;
QUrl m_url;
};
#endif // TRANSFERCLIENT_H
<file_sep>/main.cpp
#include "transferclient.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
TransferClient w(QUrl(QStringLiteral("ws://localhost:1234")));// "ws://192.168.0.117:1234"
w.show();
return a.exec();
}
| 1b6f0bb6852d97ec64b6ab285eed892237125641 | [
"Markdown",
"C++"
] | 4 | Markdown | ShenGX1992/WebSocket | f8c470b4722caef7caad3a219552862c16298296 | 683b5d24fa722c9bf7ce1fd77753699396a8e628 | |
refs/heads/master | <file_sep>using System;
public interface IRepository<T> where T:IEntity
{
public Class1()
{
}
}
<file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting;
using ConsoleApp1;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1.Tests
{
[TestClass()]
public class AuthorRepositoryTests
{
[TestMethod()]
public void FindByIdTest()
{
var a = 1;
var b = 1;
Assert.AreEqual(a, b);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
// the implementation based on the following link
//https://medium.com/falafel-software/implement-step-by-step-generic-repository-pattern-in-c-3422b6da43fd
class Program
{
static void Main(string[] args)
{
// The code provided will print ‘Hello World’ to the console.
// Press Ctrl+F5 (or go to Debug > Start Without Debugging) to run your app.
Console.WriteLine("Hello World!");
IRepository<Author> _authorRepository = new AuthorRepository();
var result = _authorRepository.FindById(1);
Console.Write(result.authorName);
Console.ReadLine();
}
}
}
<file_sep>using System;
namespace ConsoleApp1
{
[Table("Author")]
public partial class Author : IEntity
{
public int Id { get; set; }
public string authorName { get; set; }
private class TableAttribute : Attribute
{
private string v;
public TableAttribute(string v)
{
this.v = v;
}
}
}
}
<file_sep>namespace ConsoleApp1
{
public class Model1
{
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
public class AuthorRepository : IRepository<Author>
{
private Model1 _authorContext;
public AuthorRepository()
{
_authorContext = new Model1();
}
public IEnumerable<Author> List => new List<Author> {
{new Author{ Id=1, authorName="ayman"} },
{new Author{ Id=2, authorName="momo"} }
};
public Author FindById(int Id)
{
return List.Where(x => x.Id == Id).FirstOrDefault();
}
}
}
| 7dbaee4e95fdd0312b4a4747067c2cbca449975e | [
"C#"
] | 6 | C# | aymaneleya/GenericRepositoryPattern | 49de710b09528ed103e534f6113573ceb21cf721 | 1817a83ce66d80bee4751c4aca735beafe97e557 | |
refs/heads/master | <file_sep>export interface DbDoc {
_id?: string;
timestamp?: Date;
}
export interface Serie extends DbDoc {
name: string;
nameAlt: string;
image: string;
url: string;
chapter: number;
}
export interface Category extends DbDoc {
name: string;
}
<file_sep>export const CustomElement = (tag: string) => (cls: any) => {
window.customElements.define(tag, cls)
}
<file_sep>import AuthStatus from '../../interfaces/AuthStatus'
import { IAuthController } from '../../interfaces/IAuthController'
enum Permission {
R = 'read',
RW = 'read-write',
}
export default class WSAuthController implements IAuthController {
private permission: Permission = Permission.R
static readonly AUTH_ITEM: string = 'auth'
onAuthChange?(x: { newAuth: Permission }): void;
constructor () {
const auth = window.localStorage.getItem(WSAuthController.AUTH_ITEM)
if (auth != null) {
this.permission = Permission.RW
}
}
getStatus (): AuthStatus {
throw new Error('Method not implemented.')
}
isSudo (): boolean {
return this.permission === Permission.RW
}
login (x: { pass: string; url: string }): void {
const ws = new WebSocket(x.url)
ws.onopen = () => {
ws.send(JSON.stringify({ pass: x.pass }))
}
ws.onmessage = (ev) => {
if (ev.data === 'OK') {
this.permission = Permission.RW
} else {
this.permission = Permission.R
}
ws.close(1000)
if (this.onAuthChange !== undefined) {
this.onAuthChange({ newAuth: this.permission })
}
}
}
logout (): void {
this.permission = Permission.R
}
remember (): void {
throw new Error('Method not implemented.')
}
}
<file_sep>import { IAuthController } from '../../interfaces/IAuthController'
import { getAuth, onAuthStateChanged } from 'firebase/auth'
import { FirebaseApp } from 'firebase/app'
import AuthStatus from '../../interfaces/AuthStatus'
import { isEmailSudo } from './AuthUtil'
import { isDebug } from '../../../app.config'
export type AuthChangeEvent = {
status: AuthStatus;
};
export default class FirebaseAuthController implements IAuthController {
private readonly auth
private status = AuthStatus.ANONYMOUS
onAuthChange?(x: AuthChangeEvent): void;
constructor (private readonly app: FirebaseApp) {
this.auth = getAuth(this.app)
if (isDebug()) {
import('firebase/auth').then(({ connectAuthEmulator }) => {
connectAuthEmulator(this.auth, 'http://localhost:9099', {
disableWarnings: true
})
})
}
onAuthStateChanged(this.auth, async (user) => {
if (user === null) {
this.status = AuthStatus.ANONYMOUS
} else {
const isSudo = user.email ? await isEmailSudo(user.email) : false
this.status = isSudo ? AuthStatus.SUDO : AuthStatus.SIGNED
}
if (this.onAuthChange) this.onAuthChange({ status: this.status })
console.log(
'Firebase logged:',
user,
'with status',
AuthStatus[this.status].toString()
)
})
}
getStatus (): AuthStatus {
return this.status
}
async login (): Promise<void> {
const { GoogleAuthProvider, signInWithRedirect } = await import(
'firebase/auth'
)
const provider = new GoogleAuthProvider()
await signInWithRedirect(this.auth, provider)
}
async logout (): Promise<void> {
await this.auth.signOut()
}
remember (): void {
throw new Error('Method not implemented.')
}
}
<file_sep>import ModalView from '../interfaces/ModalView'
import { Serie } from '../interfaces/Models'
import { isDebug } from '../../app.config'
import { CustomElement } from '../interfaces/CustomElement'
import { SuggestionsList } from './SuggestionsList'
@CustomElement('sl-add-serie-modal')
export class AddSerieModal extends ModalView {
onSubmit?(serie: Serie): Promise<void>;
private nameInput = document.createElement('input')
private altNameInput = document.createElement('input')
private imgInput = document.createElement('input')
private imgPrev = document.createElement('img')
private urlInput = document.createElement('input')
private chapterInput = document.createElement('input')
private titleDiv = document.createElement('div')
private titleSpan = document.createElement('span')
private modalClose = document.createElement('button')
private submitBtn = document.createElement('button')
private suggestionsWorker?: Worker
async connectedCallback () {
const separator = document.createElement('div')
separator.className = 'separator'
const separator2 = document.createElement('div')
separator2.className = 'separator'
const inputsContainer = document.createElement('div')
const allContainer = document.createElement('div')
inputsContainer.className = 'inputs-container'
allContainer.className = 'all-container'
this.imgPrev.className = 'img-prev'
const suggestionList = new SuggestionsList()
const suggestionListAlt = new SuggestionsList()
inputsContainer.append(
this.nameInput,
suggestionList,
this.altNameInput,
suggestionListAlt,
this.imgInput,
this.urlInput,
this.chapterInput
)
allContainer.append(inputsContainer, this.imgPrev)
this.window.append(
this.titleDiv,
separator,
allContainer,
separator2,
this.submitBtn
)
this.titleDiv.append(this.titleSpan, this.modalClose)
this.titleDiv.className = 'title'
this.nameInput.type = 'text'
this.altNameInput.type = 'text'
this.imgInput.type = 'text'
this.urlInput.type = 'text'
this.chapterInput.type = 'number'
this.nameInput.placeholder = 'Nombre'
this.altNameInput.placeholder = 'Nombre alternativo'
this.imgInput.placeholder = 'Link imagen'
this.urlInput.placeholder = 'Url'
this.chapterInput.value = '0'
this.titleSpan.innerText = 'Añadir serie'
this.modalClose.className = 'title-btn'
this.modalClose.innerText = 'X'
this.modalClose.onclick = () => {
if (this.suggestionsWorker !== undefined) {
this.suggestionsWorker.terminate()
}
this.remove()
}
this.submitBtn.innerText = 'Añadir'
this.submitBtn.onclick = async () => await this.submit()
this.onkeydown = async (e) => {
if (e.key === 'Enter') {
await this.submit()
} else if (e.key === 'Escape') {
this.remove()
}
}
if (isDebug()) {
this.submitBtn.oncontextmenu = async (e) => {
e.preventDefault()
const { default: Placeholders } = await import(
'../../test/Placeholders'
)
const { runLoading } = await import('./RunLoading')
await runLoading(async () => {
for (let i = 0; i < 14; i++) {
const s = await Placeholders.getRandomSerie()
delete s._id
delete s.timestamp
await this.onSubmit!(s)
}
}, this.submitBtn)
}
}
this.imgInput.oninput = () => {
this.imgPrev.src = this.imgInput.value
}
this.nameInput.oninput = (mEv) => {
if (this.nameInput.value.length < 3) return
if (this.suggestionsWorker === undefined) {
this.suggestionsWorker = new Worker(new URL('../../public/workers/autocomplete.js', import.meta.url), { type: 'classic' })
}
suggestionList.generateList!({ input: this.nameInput, worker: this.suggestionsWorker })
}
this.altNameInput.oninput = () => {
if (this.altNameInput.value.length < 3) return
if (this.suggestionsWorker === undefined) {
this.suggestionsWorker = new Worker(new URL('../../public/workers/autocomplete.js', import.meta.url), { type: 'classic' })
}
suggestionListAlt.generateList!({ input: this.altNameInput, worker: this.suggestionsWorker })
}
this.generateData()
}
private async submit () {
const { runLoading } = await import('./RunLoading')
await runLoading(async () => {
await this.onSubmit!({
name: this.nameInput.value,
nameAlt: this.altNameInput.value,
chapter: this.chapterInput.valueAsNumber,
image: this.imgInput.value,
url: this.urlInput.value
})
}, this.submitBtn)
await this.clearInputs()
await this.generateData()
}
private async clearInputs () {
this.nameInput.value = ''
this.altNameInput.value = ''
this.imgInput.value = ''
this.urlInput.value = ''
this.chapterInput.value = '0'
}
private async generateData () {
if (isDebug()) {
const { default: Placeholders } = await import('../../test/Placeholders')
const serie = await Placeholders.getRandomSerie()
this.nameInput.value = serie.name
this.altNameInput.value = serie.nameAlt
this.imgInput.value = serie.image
this.urlInput.value = serie.url
this.imgPrev.src = serie.image
}
}
}
<file_sep>export async function runLoading (func: () => Promise<void>, el: HTMLElement) {
el.setAttribute('disabled', '')
const prevHTML = el.innerHTML
const prog = document.createElement('progress')
el.textContent = ''
el.append(prog)
await func()
prog.remove()
el.innerHTML = prevHTML
el.removeAttribute('disabled')
}
<file_sep>import { APP_NAME } from '../../app.config'
import IComponent from '../interfaces/Component'
import { CustomElement } from '../interfaces/CustomElement'
import { Category, Serie } from '../interfaces/Models'
import { ITab, Tab } from './Tab'
@CustomElement('sl-tabs-menu')
export class TabsMenu extends IComponent {
private tabs: Tab[]
private addCategTab: Tab
onTabsClick?(tab: ITab): void;
onSerieDrop?(x: { serie: Serie; categoryId: string }): void;
onRequestDelete?(categId: string): Promise<void>;
onRequestNewCateg?(): Promise<void>;
onRequestEditCateg?(categ: Category): Promise<void>;
static addTabId: string = 'addtab'
constructor () {
super()
this.tabs = []
this.addCategTab = new Tab({
name: 'Añadir',
url: ''
})
this.addCategTab.onDropSerie = () => {
alert('Eu non fago iso')
}
this.addCategTab.style.display = 'none'
this.addCategTab.id = 'addtab'
this.addCategTab.onclick = async () => await this.onRequestNewCateg!()
this.addCategTab.oncontextmenu = () => {}
}
connectedCallback () {
this.showAddCategTab(false)
this.append(this.addCategTab)
}
showAddCategTab (visible: boolean = true) {
this.addCategTab.style.display = visible ? 'block' : 'none'
console.log('showAddCategTab:', this.addCategTab.style.display)
}
async addTab (tab: ITab): Promise<void> {
const newTab = new Tab(tab)
newTab.onActive = async (_tab: ITab = tab) => {
await this.setActiveTab(newTab)
this.onTabsClick!(tab)
}
newTab.onDropSerie = (serie) => {
this.onSerieDrop!({ serie, categoryId: tab._id! })
}
newTab.onEditCateg = (categ) => this.onRequestEditCateg!(categ)
this.tabs.unshift(newTab)
this.insertBefore(this.tabs[0], this.addCategTab)
}
async addAllTab (tabs: ITab[]): Promise<void> {
const n = this.tabs.length
this.tabs = this.tabs.concat(
tabs.map((t) => {
const elT = new Tab(t)
elT.onDropSerie = (serie) => {
this.onSerieDrop!({ serie, categoryId: t._id! })
}
elT.onActive = async (tab: ITab = t) => {
await this.setActiveTab(elT)
this.onTabsClick!(tab)
}
elT.onEditCateg = (categ) => this.onRequestEditCateg!(categ)
elT.onDelete = this.onRequestDelete
return elT
})
)
for (let i = n; i < this.tabs.length; i++) {
this.insertBefore(this.tabs[i], this.addCategTab)
}
}
async setActiveTab (newTab: Tab) {
this.tabs.forEach((i) => {
i.setAttribute(Tab.observedAttributes[0], 'false')
})
newTab.setAttribute(Tab.observedAttributes[0], 'true') // Attribute 'active'
document.title = APP_NAME + ' - ' + newTab.tab.name
}
async setActiveTabByPathname () {
let i = 0
while (
i < this.tabs.length &&
this.tabs[i].tab._id !== window.location.pathname.replace('/', '')
) {
i++
}
await this.setActiveTab(this.tabs[i])
}
async updateTab (data: Category) {
this.tabs.forEach((i) => {
if (i.tab._id === data._id!) {
i.innerText = data.name
document.title = `${APP_NAME} - ${data.name}`
}
})
}
async deleteTab (tab: ITab): Promise<void> {
let i = 0
while (i < this.tabs.length || this.tabs[i].getData() !== tab) {
i++
}
if (this.tabs[i].getData() !== tab) {
throw new Error('Tab is not in the tabs menu')
}
this.removeChild(this.tabs[i])
this.tabs.splice(i, 1)
}
async clearTabs (): Promise<void> {
// this.textContent = "";
this.tabs.forEach((i) => i.remove())
this.tabs = []
}
}
<file_sep>declare function searchStart(term: string, input: string[]): Promise<number>;
declare function searchEnd(term: string, input: string[]): Promise<number>;
declare function searchStartWith(term: string, input: string[]): Promise<string[]>;
<file_sep>export enum Route {
SERIES = '/',
MANAGE = '/manage',
}
<file_sep>import ModalView from '../interfaces/ModalView'
import { Category } from '../interfaces/Models'
import { isDebug } from '../../app.config'
import { CustomElement } from '../interfaces/CustomElement'
@CustomElement('sl-add-category-modal')
export class AddCategoryModal extends ModalView {
onSubmit?(categ: Category): Promise<void>;
private titleDiv: HTMLDivElement = document.createElement('div')
private titleSpan: HTMLSpanElement = document.createElement('span')
private closeBtn: HTMLButtonElement = document.createElement('button')
private nameInput: HTMLInputElement = document.createElement('input')
private submitBtn: HTMLButtonElement = document.createElement('button')
private name: string = ''
async connectedCallback () {
const separator = document.createElement('div')
separator.className = 'separator'
const separator2 = document.createElement('div')
separator2.className = 'separator'
this.window.append(
this.titleDiv,
separator,
this.nameInput,
separator2,
this.submitBtn
)
this.titleDiv.append(this.titleSpan, this.closeBtn)
this.titleDiv.className = 'title'
this.nameInput.type = 'text'
this.titleSpan.innerText = 'Añadir categoría'
this.closeBtn.className = 'title-btn'
this.closeBtn.innerText = 'X'
this.closeBtn.onclick = () => {
this.remove()
}
this.submitBtn.innerText = 'Añadir'
this.onkeydown = async (ev) => {
if (ev.key === 'Enter') {
await this.submit()
} else if (ev.key === 'Escape') {
this.remove()
}
}
this.submitBtn.onclick = async () => {
await this.submit()
}
await this.setRandomName()
}
private async submit () {
console.log(this.nameInput)
console.log('Create category with name', this.nameInput.value)
await this.onSubmit!({
name: this.nameInput.value,
timestamp: new Date()
})
this.remove()
}
private async setRandomName () {
if (isDebug()) {
const { default: Placeholders } = await import('../../test/Placeholders')
const categ = await Placeholders.getRandomCategory()
this.nameInput.value = categ.name
}
}
}
// window.customElements.define('sl-add-category-modal', AddCategoryModal)
<file_sep>import * as fs from 'fs/promises'
import path from 'path'
import { brotliCompress, gzip } from 'zlib'
import { argv } from 'process'
import { parseArgs } from './argsParser.js'
const args = await parseArgs(argv.slice(2))
/** @type {BuildOptions} */
const options = {
compression: args.compression | null
}
if (options.compression === 'brotli') {
for await (const c of await fs.readdir('./dist', { encoding: 'utf-8' })) {
brotliCompress(
await fs.readFile(path.join('./dist', c)),
async (err, res) => {
if (err) console.log(err)
else {
await fs.rm(path.join('./dist', c))
await fs.writeFile(path.join('./dist', c), new Uint8Array(res), {
encoding: 'utf-8'
})
console.log(`${c} Brotli zipped`)
}
}
)
}
} else if (options.compression === 'gzip') {
for await (const c of await fs.readdir('./dist', { encoding: 'utf-8' })) {
gzip(await fs.readFile(path.join('./dist', c)), async (err, res) => {
if (err) console.log(err)
else {
await fs.writeFile(path.join('./dist', c), new Uint8Array(res), {
encoding: 'utf-8'
})
console.log(`${c} gzipped`)
}
})
}
}
<file_sep>import IComponent from '../../interfaces/Component'
export default class MigrationsView extends IComponent {
constructor (private x?: { fromOldMigration?(): void }) {
super()
}
connectedCallback () {
const list = document.createElement('ul')
const el = document.createElement('span')
el.innerText = 'xd, mejor no tocar nada'
this.append(list)
list.append(el)
}
}
window.customElements.define('sl-migrations-view', MigrationsView)
<file_sep>import { IDbClient } from '../src/interfaces/DbClient'
import { Serie, Category } from '../src/interfaces/Models'
import Placeholders from './Placeholders'
export class FakeClient implements IDbClient {
private categs: Category[] = []
private data: Map<string, Serie[]> = new Map()
async getSeriesLimitFirst (x: { categId: string }): Promise<Serie[]> {
const result = []
const q = this.data.get(x.categId)
if (q === undefined) return []
for (let i = 0; i < 14; i++) {
result.push(q[i])
}
return result
}
getSeriesLimitAfter (x: { categId: string; start: Date }): Promise<Serie[]> {
throw new Error('Method not implemented.')
}
async setup (): Promise<void> {
for (let i = 0; i < Math.floor(Math.random() * 20); i++) {
const series = []
for (let j = 0; j < Math.floor(Math.random() * 100); i++) {
series.push(await Placeholders.getRandomSerie())
}
const categ = await Placeholders.getRandomCategory()
this.categs.push(categ)
this.data.set(categ._id!!, series)
}
}
moveSerie (
oldCategId: string,
newCategId: string,
serie: Serie
): Promise<string> {
throw new Error('Method not implemented.')
}
updateSerieInfo (categId: string, serie: Serie): Promise<void> {
throw new Error('Method not implemented.')
}
updateSerieChapter (
serieId: string,
categId: string,
chapter: number
): Promise<void> {
throw new Error('Method not implemented.')
}
updateCategory (oldCategId: string, newCateg: Category): Promise<void> {
throw new Error('Method not implemented.')
}
async getAllSeries (): Promise<Serie[]> {
let total: Serie[] = []
this.data.forEach((s) => {
total = total.concat(s)
})
return total
}
async getAllCategories (): Promise<Category[]> {
return this.categs
}
async getSeriesByCategoryId (categ: string): Promise<Serie[]> {
return this.data.get(categ) || []
}
async addSerie (serie: Serie, categ: string): Promise<string> {
serie._id = await Placeholders.getRandomText()
this.data.set(categ, this.data.get(categ)?.concat(serie)!!)
return serie._id
}
async sumChapter (serie: Serie, categ: Category, num: number): Promise<void> {}
async addCategory (categ: Category): Promise<string> {
this.categs.push(categ)
return await Placeholders.getRandomText()
}
async deleteCategoryById (categ: string): Promise<void> {}
async deleteSerieById (serie: string, categ: string): Promise<void> {}
}
<file_sep>import IComponent from '../interfaces/Component'
import { CustomElement } from '../interfaces/CustomElement'
@CustomElement('sl-float-bottom-menu')
export class FloatBottomMenu extends IComponent {
onNewSerie?(): void;
onAltSwitch?(x: { alt: boolean }): void;
private addSerieBtn: HTMLButtonElement = document.createElement('button')
private switchAltBtn: HTMLButtonElement = document.createElement('button')
private alt: boolean = false
connectedCallback (): void {
this.append(this.switchAltBtn, this.addSerieBtn)
this.switchAltBtn.innerText = '🇯🇵'
this.switchAltBtn.onclick = () => {
this.alt = !this.alt
this.switchAltBtn.innerText = this.alt ? '🇬🇧' : '🇯🇵'
this.onAltSwitch!({ alt: this.alt })
}
this.addSerieBtn.innerText = '+'
this.addSerieBtn.onclick = () => {
this.onNewSerie!()
}
}
}
<file_sep>import { initializeApp } from "firebase/app";
import { APP_NAME, FIREBASE_KEYS } from "../app.config";
import FirebaseAuth from "./components/auth/FirebaseAuth";
import TopBar from "./components/TopBar";
import FirebaseAuthController, {
AuthChangeEvent,
} from "./controllers/auth/FirebaseAuthController";
import FirebaseClient from "./controllers/db/FirebaseClient";
import AuthStatus from "./interfaces/AuthStatus";
import { IDbClient } from "./interfaces/DbClient";
import { IAuthController } from "./interfaces/IAuthController";
import { Route } from "./routes";
import View from "./interfaces/View";
import "./styles/main.scss";
window.onload = async () => {
const main = document.querySelector("main");
if (main == null) throw new Error("Main not found");
const appDiv = document.createElement("div");
appDiv.id = "app";
let app: View | null;
const firebaseApp = initializeApp(FIREBASE_KEYS);
const dbClient: IDbClient = new FirebaseClient(firebaseApp);
const authController: IAuthController = new FirebaseAuthController(
firebaseApp
);
const authModule: FirebaseAuth = new FirebaseAuth(
authController as FirebaseAuthController
);
async function changeView(path: Route) {
if (app != null) app.remove();
if (main == null) throw new Error("Page couldn't load");
switch (path) {
case Route.SERIES: {
console.time("Loading SeriesView");
const { default: SeriesView } = await import("./pages/SeriesView");
const newSeriesView = new SeriesView({
dbClient,
changeView,
});
appDiv.append(newSeriesView);
app = newSeriesView;
console.timeEnd("Loading SeriesView");
break;
}
case Route.MANAGE: {
console.time("Loading ManageView");
const { default: ManageView } = await import("./pages/ManageView");
const newManageView = new ManageView({
dbClient,
changeView,
});
appDiv.append(newManageView);
app = newManageView;
console.timeEnd("Loading ManageView");
break;
}
}
app.authChangeEvent({ status: authController.getStatus() });
}
const topBar = new TopBar({
authModule,
changeView,
});
authController.onAuthChange = async (x: AuthChangeEvent) => {
authModule.setState(x.status);
console.log("Auth changed!! =>", AuthStatus[x.status].toString());
app?.authChangeEvent(x);
topBar.authChangeEvent!(x);
};
console.log("Initial pathname:", window.location.pathname);
if (window.location.pathname === "") {
console.log("Initial view: Route.SERIES");
await changeView(Route.SERIES);
} else if (window.location.pathname.startsWith("/manage")) {
console.log("Initial view: Route.MANAGE");
await changeView(Route.MANAGE);
} else {
console.log("Initial view: Route.SERIES");
await changeView(Route.SERIES);
}
topBar.setAttribute("title", APP_NAME);
main.append(topBar, appDiv);
};
<file_sep>import { Category, Serie } from './Models'
export interface IDbClient {
onInitialize?(): void;
moveSerie(
oldCategId: string,
newCategId: string,
serie: Serie
): Promise<string>;
updateSerieInfo(categId: string, serie: Serie): Promise<void>;
updateSerieChapter(
serieId: string,
categId: string,
chapter: number
): Promise<void>;
updateCategory(newCateg: Category): Promise<void>;
getAllSeries(): Promise<Serie[]>;
getSeriesLimitFirst(x: { categId: string }): Promise<Serie[]>;
getSeriesLimitAfter(x: { categId: string; start: Date }): Promise<Serie[]>;
getAllCategories(): Promise<Category[]>;
getSeriesByCategoryId(categId: string): Promise<Serie[]>;
addSerie(serie: Serie, categId: string): Promise<string>;
addCategory(categ: Category): Promise<string>;
deleteCategoryById(categId: string): Promise<void>;
deleteSerieById(serieId: string, categId: string): Promise<void>;
}
<file_sep>import { CustomElement } from '../interfaces/CustomElement'
import ModalView from '../interfaces/ModalView'
import { Category } from '../interfaces/Models'
@CustomElement('sl-edit-category-modal')
export class EditCategoryModal extends ModalView {
onSubmit?(categ: Category): Promise<void>;
private titleDiv: HTMLDivElement = document.createElement('div')
private titleSpan: HTMLSpanElement = document.createElement('span')
private closeBtn: HTMLButtonElement = document.createElement('button')
private nameInput: HTMLInputElement = document.createElement('input')
private submitBtn: HTMLButtonElement = document.createElement('button')
constructor (private categ: Category) {
super()
}
async connectedCallback () {
const separator = document.createElement('div')
separator.className = 'separator'
const separator2 = document.createElement('div')
separator2.className = 'separator'
this.window.append(
this.titleDiv,
separator,
this.nameInput,
separator2,
this.submitBtn
)
this.titleDiv.append(this.titleSpan, this.closeBtn)
this.titleDiv.className = 'title'
this.nameInput.type = 'text'
this.nameInput.value = this.categ.name
this.titleSpan.innerText = 'Renombrar categoría'
this.closeBtn.className = 'title-btn'
this.closeBtn.innerText = 'X'
this.closeBtn.onclick = () => {
this.remove()
}
this.submitBtn.innerText = 'Renombrar'
this.submitBtn.onclick = this.submit
this.onkeydown = async (ev) => {
if (ev.key === 'Enter') {
await this.submit()
} else if (ev.key === 'Escape') {
this.remove()
}
}
}
private submit = async () => {
console.log('Edit category with name', this.nameInput.value)
await this.onSubmit!({
_id: this.categ._id!,
name: this.nameInput.value,
timestamp: new Date()
})
this.remove()
}
}
<file_sep>export class ContextMenuBuilder {
private container: HTMLDivElement = document.createElement('div')
private list: HTMLUListElement = document.createElement('ul')
private buttons: { text: string; action: () => Promise<void> }[] = []
private shadowDom: ShadowRoot = this.container.attachShadow({ mode: 'open' })
constructor () {
this.shadowDom.innerHTML = `
<style>
ul {
position: absolute;
display: block;
padding: 0;
background: aqua;
list-style-type:none;
border-radius: 10px;
border: solid 3px white;
overflow: hidden;
}
button {
background-color: #2e3345;
font-family: Arial;
color: white;
width: 100%;
padding: 6px;
font-weight: bold;
border:none;
}
button:hover {
background-color: #3b3f49;
}
button:active {
background-color: #353a4b;
}
</style>
`
}
button (text: string, action: () => Promise<void>) {
this.buttons.push({ text, action })
return this
}
async build (
x: { mouseY: number; mouseX: number } = { mouseX: 0, mouseY: 0 }
) {
this.container.className = 'context-menu'
for await (const i of this.buttons) {
const li = document.createElement('li')
const el = document.createElement('button')
el.innerText = i.text
el.onclick = async (ev) => {
await i.action()
this.container.remove()
document.body.onclick = document.body.onclick = null
}
this.list.append(li)
li.append(el)
}
this.shadowDom.append(this.list)
this.list.style.top = `${x.mouseY}px`
this.list.style.left = `${x.mouseX}px`
document.body.onclick = document.body.onauxclick = (ev) => {
console.log(ev.target, this.container.parentElement)
if (
ev.target !== this.container &&
ev.target !== this.container.parentElement
) {
this.container.remove()
document.body.onclick = document.body.onclick = null
}
}
return this.container
}
}
<file_sep>import { FirebaseApp } from 'firebase/app'
import {
getFirestore,
Firestore,
DocumentData,
QuerySnapshot
} from 'firebase/firestore/lite'
import { IDbClient } from '../../interfaces/DbClient'
import { Category, Serie } from '../../interfaces/Models'
import { isDebug, SERIES_LIMIT } from '../../../app.config'
export default class FirebaseClient implements IDbClient {
readonly db: Firestore
onInitialize?(): void;
constructor (private readonly app: FirebaseApp) {
this.db = getFirestore(this.app)
if (isDebug()) {
import('firebase/firestore/lite').then(({ connectFirestoreEmulator }) => {
connectFirestoreEmulator(this.db, 'localhost', 8080)
})
}
}
async getSeriesLimitFirst (x: { categId: string }): Promise<Serie[]> {
const { query, collection, orderBy, limit, getDocs } = await import(
'firebase/firestore/lite'
)
const q = query(
collection(this.db, x.categId),
orderBy('timestamp', 'desc'),
limit(SERIES_LIMIT)
)
const docs = await getDocs(q)
return await FirebaseClient.formatDocsToSeries(docs)
}
async getSeriesLimitAfter (x: {
categId: string;
start: Date;
}): Promise<Serie[]> {
const { query, collection, orderBy, limit, getDocs, startAfter } =
await import('firebase/firestore/lite')
const q = query(
collection(this.db, x.categId),
orderBy('timestamp', 'desc'),
limit(SERIES_LIMIT),
startAfter(x.start)
)
const docs = await getDocs(q)
return await FirebaseClient.formatDocsToSeries(docs)
}
private static async formatDocsToSeries (
docs: QuerySnapshot<DocumentData>
): Promise<Serie[]> {
const series: Serie[] = []
docs.forEach((d) => {
series.push(Object.assign({ _id: d.id }, d.data()) as Serie)
})
return series
}
async moveSerie (
oldCategId: string,
newCategId: string,
serie: Serie
): Promise<string> {
if (serie._id === undefined) throw new Error('Serie id must be defined')
const { addDoc, deleteDoc, doc, collection } = await import(
'firebase/firestore/lite'
)
const oldSerieId = serie._id
delete serie._id
serie.timestamp = new Date()
const newSerie = await addDoc(collection(this.db, newCategId), serie)
await deleteDoc(doc(this.db, oldCategId, oldSerieId))
serie._id = newSerie.id
return newSerie.id
}
async updateSerieInfo (categId: string, serie: Serie): Promise<void> {
if (serie._id === undefined) throw new Error('Serie id must be defined')
const { updateDoc, doc } = await import('firebase/firestore/lite')
const serieId = serie._id
delete serie._id
serie.timestamp = new Date()
await updateDoc(doc(this.db, categId, serieId), serie as any)
serie._id = serieId
}
async updateSerieChapter (serieId: string, categId: string, chapter: number) {
console.log('Requesting chapter update for serie:', serieId)
const { updateDoc, doc } = await import('firebase/firestore/lite')
const ref = doc(this.db, categId, serieId)
await updateDoc(ref, {
chapter
})
}
async updateCategory (newData: Category): Promise<void> {
const { updateDoc, doc } = await import('firebase/firestore/lite')
await updateDoc(doc(this.db, 'categories', newData._id!), {
name: newData.name,
timestamp: newData.timestamp
})
}
async getAllSeries (): Promise<Serie[]> {
const categories = await this.getAllCategories()
const toret: Serie[] = []
categories.forEach(async (categ) => {
if (categ._id === undefined) {
throw new Error('Category is undefined')
}
(await this.getSeriesByCategoryId(categ._id)).forEach((ser) => {
toret.push(ser)
})
})
return toret
}
async getAllCategories (): Promise<Category[]> {
const toret: Category[] = []
console.log('Fetching all categories...')
console.time('Fetching categories')
const { query, collection, getDocs, orderBy } = await import(
'firebase/firestore/lite'
)
const q = query(
collection(this.db, 'categories'),
orderBy('timestamp', 'desc')
)
const snapshot = await getDocs(q)
snapshot.forEach((doc) => {
toret.push(Object.assign({ _id: doc.id }, doc.data()) as Category)
})
console.timeEnd('Fetching categories')
console.log('Categories fetched:', toret)
return toret
}
async getSeriesByCategoryId (categId: string): Promise<Serie[]> {
const toret: Serie[] = []
if (categId === undefined) {
throw new Error('Category id is undefined')
}
console.time('Fetching series')
const { query, collection, getDocs } = await import(
'firebase/firestore/lite'
)
const q = query(collection(this.db, categId))
const snapshot = await getDocs(q)
snapshot.forEach((doc) => {
toret.push(Object.assign({ _id: doc.id }, doc.data()) as Serie)
})
console.timeEnd('Fetching series')
console.log('Series:', toret)
return toret
}
async addSerie (serie: Serie, categId: string): Promise<string> {
console.time('Adding serie')
const { addDoc, Timestamp, collection } = await import(
'firebase/firestore/lite'
)
const res = await addDoc(
collection(this.db, categId),
Object.assign(serie, { timestamp: Timestamp.fromDate(new Date()) })
)
console.timeEnd('Adding serie')
return res.id
}
async addCategory (categ: Category): Promise<string> {
console.time('Creating category:')
const { addDoc, collection } = await import('firebase/firestore/lite')
const doc = await addDoc(
collection(this.db, 'categories'),
Object.assign(categ, { timestamp: new Date() })
)
console.timeEnd('Creating category:')
return doc.id
}
async deleteCategoryById (categId: string): Promise<void> {
console.time(`Deleting category with id ${categId}`)
const { deleteDoc, doc } = await import('firebase/firestore/lite')
await deleteDoc(doc(this.db, 'categories', categId))
const { collection, getDocs, query } = await import(
'firebase/firestore/lite'
)
const docs = await getDocs(query(collection(this.db, categId)))
docs.forEach(async (d) => {
await deleteDoc(d.ref)
})
console.timeEnd(`Deleting category with id ${categId}`)
}
async deleteSerieById (serieId: string, categId: string): Promise<void> {
const { deleteDoc, doc } = await import('firebase/firestore/lite')
await deleteDoc(doc(this.db, categId, serieId))
}
}
<file_sep>import FirebaseClient from './FirebaseClient'
export async function migrateOld (x: { client: FirebaseClient }): Promise<void> {
console.time('Migrating from old')
const categs = ['viendo', 'vistos', 'favoritos', 'abandonados', 'pendientes']
const { getDocs, collection } = await import('firebase/firestore/lite')
for await (const c of categs) {
const categId = await x.client.addCategory({ name: c })
const docs = await getDocs(collection(x.client.db, c))
docs.forEach(async (d) => {
const data = d.data()
await x.client.addSerie(
{
name: data.nombre_jp,
nameAlt: data.nombre_en,
image: data.imagen,
chapter: data.capitulo,
timestamp: data.actualizado_en,
url: ''
},
categId
)
})
}
console.timeEnd('Migrating from old')
}
<file_sep>import { ContextMenuBuilder } from '../builders/ContextMenu'
import { AuthChangeEvent } from '../controllers/auth/FirebaseAuthController'
import AuthStatus from '../interfaces/AuthStatus'
import IComponent from '../interfaces/Component'
import { CustomElement } from '../interfaces/CustomElement'
import { IDbClient } from '../interfaces/DbClient'
import { Serie } from '../interfaces/Models'
import '../styles/SerieCard.scss'
@CustomElement('sl-serie-card')
export class SerieCard extends IComponent {
private initialChapter: number
private readonly titleSpan: HTMLSpanElement = document.createElement('span')
private readonly img: HTMLImageElement = document.createElement('img')
private readonly chapter: HTMLElement = document.createElement('i')
private readonly actions = document.createElement('div')
private readonly addChapterBtn = document.createElement('button')
private readonly lessChapterBtn = document.createElement('button')
private readonly editBtn = document.createElement('button')
private readonly deleteBtn = document.createElement('button')
private readonly viewBtn = document.createElement('button')
static get observedAttributes (): string[] {
return ['alt']
}
constructor (
private serie: Serie,
private categId: string,
private client: IDbClient
) {
super()
this.initialChapter = this.serie.chapter
this.append(this.img, this.titleSpan, this.chapter)
}
connectedCallback (): void {
this.id = this.serie._id!
this.img.draggable = false
this.img.loading = 'lazy'
this.img.src = this.serie.image
this.img.alt = `Cover art of ${this.serie.name} (${this.serie.nameAlt})`
this.titleSpan.innerText = this.serie.name
this.chapter.innerText = 'Capítulo: '.concat(this.serie.chapter.toString())
this.actions.classList.add('card', 'actions')
this.addChapterBtn.innerText = '▶'
this.lessChapterBtn.innerText = '◀'
this.editBtn.innerText = '✏'
this.deleteBtn.innerText = '🗑'
this.viewBtn.innerText = '↗'
this.actions.append(
this.lessChapterBtn,
this.addChapterBtn,
this.viewBtn,
this.editBtn,
this.deleteBtn
)
this.addChapterBtn.onclick = async () => {
this.serie.chapter++
this.chapter.innerText = 'Capítulo: '.concat(
this.serie.chapter.toString()
)
}
this.lessChapterBtn.onclick = () => {
this.serie.chapter--
this.chapter.innerText = 'Capítulo: '.concat(
this.serie.chapter.toString()
)
}
this.editBtn.onclick = async () => {
const { default: EditSerieModal } = await import('./EditSerieModal')
const editModal = new EditSerieModal(this.serie)
this.draggable = false
editModal.onSubmit = async (serie) => {
console.log('Serie edited:', serie)
this.serie = serie
await this.client.updateSerieInfo(this.categId, serie)
this.img.style.backgroundImage = `url(${this.serie.image})`
this.titleSpan.innerText = this.serie.name
this.chapter.innerText = 'Capítulo: '.concat(
this.serie.chapter.toString()
)
}
editModal.disconnectedCallback = () => (this.draggable = true)
this.append(editModal)
}
this.actions.onmouseleave = this.saveChapter
this.deleteBtn.onclick = this.deleteSerie
this.viewBtn.onclick = () => {
window.open(this.serie.url, '_blank')
}
this.oncontextmenu = async (ev: MouseEvent) => {
ev.preventDefault()
console.log('context menu for seriecard')
const menu = await new ContextMenuBuilder()
.button('Copiar título', async () => {
navigator.clipboard.writeText(this.serie.name)
})
.button('Copiar título alternativo', async () => {
navigator.clipboard.writeText(this.serie.nameAlt)
})
.build({ mouseX: ev.pageX, mouseY: ev.pageY })
this.append(menu)
}
this.ondragstart = (ev: DragEvent) => {
ev.dataTransfer?.setData('serie', JSON.stringify(this.serie))
}
}
saveChapter = async () => {
if (this.initialChapter !== this.serie.chapter) {
console.log('Saving chapter for serie:', this.serie)
await this.client.updateSerieChapter(
this.serie._id!!,
this.categId,
this.serie.chapter
)
this.initialChapter = this.serie.chapter
}
}
deleteSerie = async () => {
this.style.transition = 'visibility 0.3s linear,opacity 0.3s linear'
this.style.opacity = '0'
this.style.visibility = 'hidden'
await this.client.deleteSerieById(this.serie._id!!, this.categId)
setTimeout(() => {
this.remove()
}, 1000)
}
attributeChangedCallback (name: string, lastValue: any, newValue: any): void {
if (name === SerieCard.observedAttributes[0]) {
if (newValue === 'true') {
this.titleSpan.innerText = this.serie.nameAlt
} else {
this.titleSpan.innerText = this.serie.name
}
}
}
async authChangeEvent (x: AuthChangeEvent) {
if (x.status === AuthStatus.SUDO) {
this.draggable = true
this.append(this.actions)
} else this.actions.remove()
console.log('CARD AUTH CHANGE')
}
}
<file_sep>'use strict'
/**
*
* @param {string} term
* @param {string[]} input
* @returns
*/
async function searchStart (term, input) {
let start = 0
while (!input[start].toLocaleLowerCase().startsWith(term)) {
start++
console.log(input)
console.log(start)
console.log(input[start])
}
return start
}
/**
*
* @param {string} term
* @param {string[]} input
* @returns
*/
async function searchEnd (term, input) {
let end = input.length - 1
while (end > 0 && !input[end].toLocaleLowerCase().startsWith(term)) {
end--
}
return end
}
async function searchStartWith (term, input) {
const results = await Promise.all([searchStart(term, input), searchEnd(term, input)])
return input.slice(results[0], results[1] + 1)
}
self.onmessage = async (msg) => {
/** @type string */
const term = msg.data
const firstLet = term.charAt(0) + term.charAt(1)
const link = `/assets/anime_completions/${firstLet.toLowerCase()}.txt`
if (link === undefined) {
postMessage('sadge')
return
}
const req = await fetch(link)
const res = await req.text()
const toret = await searchStartWith(term.toLocaleLowerCase(), res.split(/\r?\n|\r|\n/g))
postMessage(toret)
}
<file_sep>import { ContextMenuBuilder } from '../builders/ContextMenu'
import IComponent from '../interfaces/Component'
import { CustomElement } from '../interfaces/CustomElement'
import { Category, Serie } from '../interfaces/Models'
export interface ITab extends Category {
url: string;
}
@CustomElement('sl-tab')
export class Tab extends IComponent {
public onActive?: () => void
public onDropSerie?: (serie: Serie) => void
/**
* Fires a delete this category event
*/
public onDelete?: (categId: string) => Promise<void>
public onEditCateg?: (categ: Category) => Promise<void>
static get observedAttributes () {
return ['active']
}
constructor (public tab: ITab) {
super()
this.onclick = () => {
history.pushState(null, '', this.tab._id!)
this.onActive!()
}
this.oncontextmenu = async (ev) => {
ev.preventDefault()
const menu = await new ContextMenuBuilder()
.button('Editar', async () => await this.onEditCateg!(this.tab))
.button('Eliminar', async () => {
alert('CHILLING BROOOOOO, CHILLING!!!!!!!!!')
})
.build({ mouseX: ev.pageX, mouseY: ev.pageY })
this.append(menu)
}
this.ondrop = (ev: DragEvent) => {
const data = ev.dataTransfer?.getData('serie')
if (data === undefined) throw new Error('Serie dragged is undefined')
const serie = JSON.parse(data) as Serie
console.log('Serie dragged:', serie)
this.onDropSerie!(serie)
}
this.ondragover = (ev: DragEvent) => {
ev.preventDefault()
}
}
connectedCallback () {
this.innerText = this.tab.name
}
getData (): ITab {
return this.tab
}
attributeChangedCallback (name: string, lastValue: any, newValue: any) {
if (name === Tab.observedAttributes[0]) {
if (newValue === 'true') {
// this.style.backgroundColor = "#3b3f49";
this.style.color = '#89ddff'
this.style.borderBottomColor = '#89ddff'
} else {
// this.style.removeProperty("background-color");
this.style.removeProperty('border-bottom-color')
this.style.removeProperty('color')
}
}
}
}
<file_sep># Series List
## Configuration
To build the app you need a config file `app.config.ts` and a `.env` with this structure:
> Requires Nodejs >=14.x
> `app.config.ts`
```typescript
export const FIREBASE_KEYS = {
apiKey: "############################",
authDomain: "########################",
databaseURL: "#######################",
projectId: "#########################",
storageBucket: "#####################",
messagingSenderId: "#################",
appId: "#############################",
};
export const APP_NAME: string = "Series List Next";
export const SERIES_LIMIT: number = 14;
export const SUDO_EMAILS: (string | RegExp)[] =
isDebug() ? [/@/] : ["<EMAIL>"]; // Use regular expressions or strings
// This way in DEBUG any email is sudo and in PRODUCTION just <EMAIL>
export function isDebug() {
// this function is just to improve project readibility
//return process.env.NODE_ENV == "dev"; this was used when I was using Workbox directly :)
return true; // or false xd
}
```
## Scripts
- `npm run serve`: runs Vite development server with hot reload
- `npm run emulators`: runs Firebase emulators
- `npm run dev` : development server with emulators
- `npm run build` : production build. Optional parameters `compression=null(default)/brotli/gzip`
<file_sep>import AuthStatus from './AuthStatus'
export interface IAuthController {
onAuthChange?(x: {}): void;
getStatus(): AuthStatus;
login(x: { pass: string; url: string }): void;
logout(): void;
remember(): void;
}
<file_sep>import NavigationDrawer from '../components/NavigationDrawer'
import { IDbClient } from '../interfaces/DbClient'
import FirebaseClient from '../controllers/db/FirebaseClient'
import '../styles/ManageView.scss'
import { Route } from '../routes'
import View from '../interfaces/View'
import { AuthChangeEvent } from '../controllers/auth/FirebaseAuthController'
import AuthStatus from '../interfaces/AuthStatus'
export default class ManageView extends View {
private dbClient: IDbClient
private navigatorDrawer: NavigationDrawer = new NavigationDrawer({
hrefRoot: '/manage'
})
private viewDiv: HTMLDivElement = document.createElement('div')
private viewPlaceholder: HTMLElement = document.createElement('div')
constructor (x: {
dbClient: IDbClient;
changeView: (path: Route) => Promise<void>;
}) {
super()
this.dbClient = x.dbClient
}
connectedCallback () {
this.navigatorDrawer.addItems(
{ name: 'Backups', href: '/backups' },
{ name: 'Migrations', href: '/migrations' }
)
this.navigatorDrawer.onItemClick = (x) => {
console.log('Loading new manage view', x)
this.updateView(x.href)
}
this.viewDiv.className = 'manage-view'
this.viewDiv.append(this.navigatorDrawer, this.viewPlaceholder)
}
authChangeEvent = async (x: AuthChangeEvent) => {
if (x.status === AuthStatus.SUDO) {
this.append(this.viewDiv)
} else {
this.viewDiv.remove()
}
}
async updateView (path: string) {
console.log('Updating view for', `"${path}"`)
let view: HTMLElement
switch (path) {
case '/backups':{
const { default: BackupsView } = await import('./manage/BackupsView')
const { default: BackupController } = await import(
'../controllers/BackupController'
)
view = new BackupsView(new BackupController(this.dbClient))
break
}
case '/migrations':{
const { default: MigrationsView } = await import(
'./manage/MigrationsView'
)
const { migrateOld } = await import(
'../controllers/db/FirebaseMigrations'
)
view = new MigrationsView({
fromOldMigration: async () => {
if (!confirm('YOU KNOW I GOT I BANBAN BLOW YOUR MINDDDDD')) return
if (this.dbClient instanceof FirebaseClient) { await migrateOld({ client: this.dbClient as FirebaseClient }) } else alert('This action requires a Firebase Db')
}
})
break
}
default:{
const placeholder = document.createElement('div')
placeholder.innerText = 'Elige una opción del panel'
view = placeholder
}
}
console.log('New view', view)
view.className = 'view'
this.viewPlaceholder.replaceWith(view)
this.viewPlaceholder = view
}
}
window.customElements.define('sl-manage', ManageView)
<file_sep>import { IDbClient } from '../interfaces/DbClient'
import { Category, Serie } from '../interfaces/Models'
export default class BackupController {
// eslint-disable-next-line no-useless-constructor
constructor (private client:IDbClient) {
}
async save (): Promise<void> {
const categs = await this.client.getAllCategories()
const toSave = new Map<string, Serie[]>()
for await (const c of categs) {
toSave.set(c._id!, await this.client.getSeriesByCategoryId(c._id!))
}
console.log('Saving', Object.fromEntries(toSave))
const blob = new Blob(
[JSON.stringify(Object.assign(Object.fromEntries(toSave), { categs }))],
{
type: 'application/json'
}
)
const link = document.createElement('a')
link.download = 'backup.json'
link.href = window.URL.createObjectURL(blob)
link.dataset.downloadurl = [
'application/json',
link.download,
link.href
].join(':')
link.click()
}
async load (file: File): Promise<void> {
console.log('Loading file', file)
const text = await file.text()
console.log('Text', text)
const obj = JSON.parse(text)
console.log('Obj', obj)
const categs = obj.categs as Category[]
console.log(categs)
console.time('Loading backup')
for await (const c of categs) {
await this.client.addCategory(c)
const series = obj[c._id!] as Serie[]
for await (const s of series) {
delete s._id
await this.client.addSerie(s, c._id!)
}
}
console.timeEnd('Loading backup')
}
}
<file_sep>import { AuthChangeEvent } from '../controllers/auth/FirebaseAuthController'
import AuthStatus from '../interfaces/AuthStatus'
import IComponent from '../interfaces/Component'
import { CustomElement } from '../interfaces/CustomElement'
import { Route } from '../routes'
import '../styles/TopBar.scss'
@CustomElement('sl-topbar')
export default class TopBar extends IComponent {
private static attrTitle: string = 'title'
private titleSpan: HTMLSpanElement = document.createElement('span')
private fujiwara: HTMLImageElement = document.createElement('img')
static get observedAttributes () {
return ['title']
}
constructor (
private x: {
authModule: IComponent;
changeView: (path: Route) => Promise<void>;
}
) {
super()
}
connectedCallback (): void {
this.append(this.fujiwara, this.titleSpan, this.x.authModule)
this.titleSpan.innerText = this.getAttribute('title') || ''
this.fujiwara.src =
'https://firebasestorage.googleapis.com/v0/b/prueba-d1c99.appspot.com/o/fujiwara-chika.webp?alt=media&token=<PASSWORD>'
this.fujiwara.alt = 'Fujiwara Chika detective'
}
attributeChangedCallback (name: string, lastValue: any, newValue: any) {
if (name === TopBar.attrTitle) {
this.titleSpan.innerText = newValue
}
}
authChangeEvent = async (state: AuthChangeEvent) => {
console.log('Topbar auth change')
if (state.status === AuthStatus.SUDO) {
this.fujiwara.onclick = () => {
if (!window.location.pathname.split('/').includes('manage')) {
window.history.pushState(null, '', '/manage')
this.x.changeView(Route.MANAGE)
}
}
this.titleSpan.onclick = () => {
if (window.location.pathname.split('/').includes('manage')) {
window.history.pushState(null, '', '/')
this.x.changeView(Route.SERIES)
}
}
} else {
this.fujiwara.onclick = () => {}
this.titleSpan.onclick = () => {}
}
}
}
<file_sep>import { AuthChangeEvent } from '../controllers/auth/FirebaseAuthController'
export default abstract class IComponent extends HTMLElement {
/**
* @description Attributes that fire the attributeChangedCallback()
* @example static get observedAttributes() { return ["enabled", "foo"] }
* @returns string[]
*/
observedAttributes?(): string[];
/**
* @description It's called when the component is loaded
* @returns void
*/
connectedCallback?(): void;
/**
* @description It's called when the component is removed
* @returns void
*/
disconnectedCallback?(): void;
/**
* @description It's called when an attribute in the observedAttributes() is changed
* @param name Name of the attribute changed
* @param lastValue Previous value of the attribute
* @param newValue New value of the attribute
*/
attributeChangedCallback?(name: string, lastValue: any, newValue: any): void;
/**
* @description It's called when the component is moved to a new document
* @param lastDocument
* @param newDocument
*/
adoptedCallback?(lastDocument: HTMLDocument, newDocument: HTMLDocument): void;
authChangeEvent?(x: AuthChangeEvent): Promise<void>;
}
<file_sep>import WSAuthController from '../../controllers/auth/WSAuthController'
import IComponent from '../../interfaces/Component'
import '../styles/AuthModule.scss'
export class WSAuthModule extends IComponent {
static readonly URL_STORE: string = 'lastUrl'
static get observedAttributes (): string[] {
return ['logged']
}
constructor (private auth: WSAuthController) {
super()
}
connectedCallback () {
this.setAttribute('logged', 'no')
}
logged (): void {
const disconBtn: HTMLButtonElement = document.createElement('button')
disconBtn.innerText = 'Desconectar'
disconBtn.onclick = () => {
this.auth.logout()
}
this.append(disconBtn)
}
notLogged (): void {
const urlInput: HTMLInputElement = document.createElement('input')
const passInput: HTMLInputElement = document.createElement('input')
const submitBtn: HTMLButtonElement = document.createElement('button')
urlInput.type = 'text'
urlInput.placeholder = 'Url'
passInput.type = '<PASSWORD>'
passInput.placeholder = 'Password'
submitBtn.innerText = 'Iniciar'
urlInput.value = window.localStorage.getItem(WSAuthModule.URL_STORE) || ''
submitBtn.onclick = () => {
this.auth.login({
url: urlInput.value,
pass: <PASSWORD>Input.value
})
window.localStorage.setItem(WSAuthModule.URL_STORE, urlInput.value)
}
this.append(urlInput, passInput, submitBtn)
}
attributeChangedCallback (name: string, lastValue: any, newValue: any): void {
console.log('attribute:', name)
if (name === WSAuthModule.observedAttributes[0]) {
if (newValue === 'yes') {
this.textContent = ''
this.logged()
} else {
this.textContent = ''
this.notLogged()
}
}
}
}
window.customElements.define('sl-wsauth', WSAuthModule)
<file_sep>import IComponent from '../interfaces/Component'
import { CustomElement } from '../interfaces/CustomElement'
@CustomElement('sl-suggestions-list')
export class SuggestionsList extends IComponent {
private shadowDom: ShadowRoot
generateList?: (x: { input: HTMLInputElement, worker: Worker }) => Promise<void>
constructor () {
super()
this.shadowDom = this.attachShadow({ mode: 'closed' })
}
connectedCallback () {
const list: HTMLUListElement = document.createElement('ul')
list.style.listStyleType = 'none'
list.style.margin = '0'
list.style.padding = '0'
list.style.overflowY = 'auto'
list.style.maxHeight = '250px'
this.shadowDom.append(list)
this.generateList = async (x) => {
list.textContent = ''
list.append(document.createElement('progress'))
x.worker.onmessage = async (e) => {
list.textContent = ''
const data = e.data as Array<string>
for await (const item of data) {
const entry = document.createElement('li')
entry.innerText = item
entry.onclick = () => {
x.input.value = item
list.textContent = ''
}
entry.style.padding = '10px'
entry.style.border = 'solid 2px #353a4b'
entry.style.transition = 'background linear 0.3s, color linear 0.3s'
entry.onmouseenter = () => {
entry.style.backgroundColor = '#3b3f49'
}
entry.onmouseleave = () => {
entry.style.backgroundColor = '#282c34'
}
entry.onmousedown = () => {
entry.style.borderColor = '#89ddff'
}
entry.onmouseup = () => {
entry.style.borderColor = '#3b3f49'
}
list.append(entry)
}
}
x.worker.onerror = (e) => {
console.log(e)
}
x.worker.onmessageerror = (e) => {
console.log(e)
}
x.worker.postMessage(x.input.value)
}
}
}
<file_sep>import IComponent from '../interfaces/Component'
import { CustomElement } from '../interfaces/CustomElement'
import '../styles/NavigationDrawer.scss'
interface NavigatorItem {
href: string;
name: string;
}
@CustomElement('sl-navigation-drawer')
export default class NavigationDrawer extends IComponent {
onItemClick?(x: NavigatorItem): void;
constructor (private params?: { hrefRoot?: string }) {
super()
}
connectedCallback () {}
addItems (...items: NavigatorItem[]) {
items.forEach((i) => {
const a = document.createElement('a')
a.id = i.name
a.innerText = i.name
a.href = i.href
a.onclick = (ev) => {
ev.preventDefault()
window.history.pushState(null, '', this.params?.hrefRoot + i.href)
this.onItemClick!(i)
}
this.append(a)
})
}
removeItem (itemName: string) {
this.querySelector(`#${itemName}`)?.remove()
}
}
<file_sep>import { SUDO_EMAILS } from '../../../app.config'
export async function isEmailSudo (email: string): Promise<boolean> {
for await (const i of SUDO_EMAILS) {
if (typeof i === 'string') {
if (email === i) return true
} else if (i instanceof RegExp) {
if (i.test(email)) return true
}
}
return false
}
<file_sep>import IComponent from './Component'
// import Modal from "bundle-text:../styles/Modal.scss";
export default abstract class ModalView extends IComponent {
onSubmit?(data: any): void;
private shadowDom: ShadowRoot
protected window: HTMLDivElement = document.createElement('div')
private main: HTMLElement = document.createElement('main')
constructor () {
super()
this.shadowDom = this.attachShadow({ mode: 'open' })
const styles = document.createElement('style')
// styles.textContent = Modal;
this.shadowDom.append(styles)
this.shadowDom.innerHTML = `
<style>
main {
position: absolute;
z-index: 3;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
top: 0;
right: 0;
display: flex;
justify-content: center;
overflow-y: scroll;
}
.separator {
width: 100%;
height: 3px;
background-color: #89ddff;
margin-bottom: 5px;
margin-top:5px;
}
.window {
border: solid 1px #272b3a;
border-radius: 5px;
color: white;
margin-top: 15vh;
margin-left: 15vw;
margin-right: 15vw;
background-color: #2e3345;
padding: 10px;
width: 50vw;
height: min-content;
display: flex;
flex-direction: column;
justify-content: center;
}
@media (max-width: 900px) {
.window {
width: 100%;
margin-left: 2px;
margin-right: 2px;
}
}
input {
margin: 4px;
vertical-align: middle;
padding: 10px;
font-size: 14px;
border-top: none;
border-left: none;
border-right: none;
border-bottom: solid 2px gray;
transition: border-bottom-color linear 0.2s, background-color linear 0.2s;
}
input:hover {
background-color: #ededed;
}
input:focus {
border-top: none;
border-left: none;
border-right: none;
border-bottom: solid 2px #89ddff;
outline:none;
background-color: #d9d9d9;
}
button {
font-family: Arial, Helvetica, sans-serif;
margin: 5px;
padding: 10px;
text-transform: uppercase;
white-space: nowrap;
letter-spacing: 2px;
font-weight: bold;
color: white;
background-color: transparent;
border: none;
border-radius: 5px;
transition: background-color ease-in-out 0.2s;
}
button:hover {
cursor: pointer;
background-color: #24272e;
}
button:active {
background-color: #4c515c;
}
.title {
width: 100%;
margin-top: 0;
margin-left: 20px;
display: flex;
flex-direction: row;
}
span {
width: 90%;
text-align: center;
font-size: 20px;
font-weight: bold;
margin-top: 5px;
}
.title-btn {
width: 35px;
height: 35px;
border-radius: 35px;
border: none;
background-color: transparent;
color: white;
font-weight: bold;
font-size: large;
margin-top: 0;
transition: background-color ease-in-out 0.2s;
text-align: center;
padding: 0;
}
.title-btn:hover {
background-color: #232736;
}
.title-btn:active {
background-color: #555b73;
}
.all-container {
display: flex;
flex-direction: row;
}
.inputs-container {
display: flex;
flex-direction: column;
width: 100%;
}
.img-prev {
margin: 0 2% 0 2%;
width: 250px;
height: 400px;
}
@media (max-width: 900px) {
.all-container {
display: flex;
flex-direction: column-reverse;
}
.img-prev {
align-self: center;
}
}
</style>
`
this.window.className = 'window'
this.shadowDom.append(this.main)
this.main.append(this.window)
}
}
<file_sep>import FirebaseAuthController from '../../controllers/auth/FirebaseAuthController'
import AuthStatus from '../../interfaces/AuthStatus'
import IComponent from '../../interfaces/Component'
export default class FirebaseAuth extends IComponent {
private btn = document.createElement('button')
constructor (private readonly controller: FirebaseAuthController) {
super()
this.notLogged()
}
connectedCallback () {
this.append(this.btn)
}
notLogged () {
console.log('FirebaseAuthModule: not logged')
this.btn.innerText = 'Iniciar con Google'
this.btn.onclick = async () => {
await this.controller.login()
}
this.append(this.btn)
}
logged () {
console.log('FirebaseAuthModule: logged')
this.btn.innerText = 'Cerrar sesión'
this.btn.onclick = async () => {
await this.controller.logout()
}
this.append(this.btn)
}
setState (newState: AuthStatus) {
if (newState === AuthStatus.SUDO) this.logged()
else this.notLogged()
}
}
window.customElements.define('sl-firebaseauth', FirebaseAuth)
<file_sep>import { FloatBottomMenu } from '../components/FloatBottomMenu'
import { ITab } from '../components/Tab'
import { TabsMenu } from '../components/TabsMenu'
import { AuthChangeEvent } from '../controllers/auth/FirebaseAuthController'
import AuthStatus from '../interfaces/AuthStatus'
import { IDbClient } from '../interfaces/DbClient'
import { Category, Serie } from '../interfaces/Models'
import { Route } from '../routes'
import '../styles/SeriesView.scss'
import View from '../interfaces/View'
/// /////////////////////////////////////////////////////////
import { AddSerieModal } from '../components/AddSerieModal'
import { AddCategoryModal } from '../components/AddCategoryModal'
import { SerieCard } from '../components/SerieCard'
import { EditCategoryModal } from '../components/EditCategoryModal'
/// /////////////////////////////////////////////////////////
export default class SeriesView extends View {
private client: IDbClient
// Categories
private actualCategory: Category
// Components
private floatBotMenu: FloatBottomMenu
private tabsMenu: TabsMenu
private seriesDiv: HTMLDivElement
private endDiv: HTMLDivElement
private viewDiv: HTMLDivElement
private lastAuthEvent: AuthChangeEvent = { status: AuthStatus.ANONYMOUS }
private endObserver: IntersectionObserver
private lastSerie?: Serie
constructor (x: {
dbClient: IDbClient;
changeView: (path: Route) => Promise<void>;
}) {
super()
this.client = x.dbClient
// this.client = new FakeClient();
this.actualCategory = { name: '' }
this.tabsMenu = new TabsMenu()
this.viewDiv = document.createElement('div')
this.viewDiv.className = 'view-div'
this.seriesDiv = document.createElement('div')
this.endDiv = document.createElement('div')
this.endDiv.className = 'end-div'
this.floatBotMenu = new FloatBottomMenu()
this.tabsMenu.onTabsClick = async (tab: ITab) => {
this.actualCategory = tab as Category
console.log('actualCategory:', this.actualCategory)
if (this.actualCategory._id === undefined) {
throw new Error(
'Category ' + this.actualCategory.name + ' id is undefined'
)
}
this.endObserver.disconnect()
this.endDiv.remove()
await this.getFirstSeries()
}
this.tabsMenu.onRequestEditCateg = async (categ) => {
const modal = new EditCategoryModal(categ)
this.append(modal)
modal.onSubmit = async (data) => {
await this.client.updateCategory(data)
await this.tabsMenu.updateTab(data)
}
}
this.tabsMenu.onSerieDrop = async (x) => {
console.log('Serie dropped:', x)
const oldId = x.serie._id
await this.findAndDeleteCard(oldId!)
await this.client.moveSerie(
this.actualCategory._id!,
x.categoryId,
x.serie
)
}
this.tabsMenu.onRequestDelete = async (categId) => {
await this.client.deleteCategoryById(categId)
}
this.endObserver = new IntersectionObserver(
(entries, observer) => this.handleEnd(entries, observer),
{
root: null,
rootMargin: '0px',
threshold: 0.25
}
)
}
async authChangeEvent (x: AuthChangeEvent) {
console.log('Auth changed!')
this.lastAuthEvent = x
if (x.status === AuthStatus.SIGNED || x.status === AuthStatus.SUDO) {
console.log('Logged')
const categories = await this.client.getAllCategories()
if (categories.length > 0) {
if (window.location.pathname === '/') {
window.history.pushState(null, '', categories[0]._id!)
this.actualCategory = categories[0]
} else {
let i = 0
while (
i < categories.length &&
categories[i]._id !== window.location.pathname.replace('/', '')
) {
i++
}
if (i === categories.length) {
window.history.pushState(null, '', categories[0]._id!)
this.actualCategory = categories[0]
} else {
this.actualCategory = categories[i]
}
console.log('actualCategory:', this.actualCategory)
}
await this.updateTabs(categories)
await this.getFirstSeries()
x.status === AuthStatus.SUDO
? this.append(this.floatBotMenu)
: this.floatBotMenu.remove()
}
} else {
if (this.floatBotMenu.isConnected) this.floatBotMenu.remove()
}
this.tabsMenu.showAddCategTab(x.status === AuthStatus.SUDO)
for await (const i of this.querySelectorAll<SerieCard>('sl-serie-card')) {
await i.authChangeEvent(x)
}
}
async connectedCallback (): Promise<void> {
this.append(this.tabsMenu, this.viewDiv)
this.viewDiv.append(this.seriesDiv)
this.seriesDiv.classList.add('series', 'container')
this.floatBotMenu.onNewSerie = async () => {
const modal = new AddSerieModal()
this.append(modal)
modal.onSubmit = async (serie) => {
if (this.actualCategory._id === undefined) { throw new Error('Category id is undefined') }
const id = await this.client.addSerie(serie, this.actualCategory._id)
this.seriesDiv.insertBefore(
(
await Promise.all(
await this.createCards(Object.assign({ _id: id }, serie))
)
)[0],
this.seriesDiv.children[0]
)
}
}
this.floatBotMenu.onAltSwitch = (x) => {
this.seriesDiv.querySelectorAll('sl-serie-card').forEach((i) => {
i.setAttribute('alt', `${x.alt}`)
})
}
this.tabsMenu.onRequestNewCateg = async () => {
const modal = new AddCategoryModal()
this.append(modal)
modal.onSubmit = async (categ) => {
if (!this.floatBotMenu.isConnected) this.append(this.floatBotMenu)
const id = await this.client.addCategory(categ)
categ._id = id
this.tabsMenu.addTab((await this.createTabs(categ))[0])
if (window.location.pathname === '/') {
window.history.pushState(null, '', id)
this.actualCategory = categ
await this.getFirstSeries()
await this.tabsMenu.setActiveTabByPathname()
}
}
}
}
async handleEnd (
entries: IntersectionObserverEntry[],
observer: IntersectionObserver
): Promise<void> {
let i = 0
while (i < entries.length && !entries[i].isIntersecting) {
i++
}
if (i >= entries.length) {
console.log('Not getting more series')
return
}
console.log('Getting more series!! Last serie:', this.lastSerie)
if (this.lastSerie !== undefined) {
console.log('Last serie:', this.lastSerie)
const moreSeries = await this.client.getSeriesLimitAfter({
categId: this.actualCategory._id!,
start: this.lastSerie.timestamp!
})
if (moreSeries.length <= 0) {
observer.disconnect()
return
}
this.lastSerie = moreSeries[moreSeries.length - 1]
console.log('More series:', moreSeries)
const cards = await Promise.all(
await this.createCards.apply(this, moreSeries)
)
cards.forEach((i) => this.seriesDiv.append(i))
}
}
/**
* Creates cards from SeriesCard
* @param series
* @returns
*/
async createCards (...series: Serie[]) {
console.log('Creating cards')
return series.map(async (s: Serie) => {
const card = new SerieCard(s, this.actualCategory._id || '', this.client)
await card.authChangeEvent(this.lastAuthEvent)
return card
})
}
async createTabs (...categs: Category[]): Promise<ITab[]> {
return categs.map((c) => Object.assign(c, { url: '/' + c.name }))
}
async updateTabs (categories: Category[]) {
await this.tabsMenu.clearTabs()
await this.tabsMenu.addAllTab(
await this.createTabs.apply(this, categories)
)
await this.tabsMenu.setActiveTabByPathname()
}
async getFirstSeries () {
this.viewDiv.scrollTo({ top: 0, left: 0 })
console.log('Updating series with category:', this.actualCategory)
if (this.actualCategory._id === undefined) {
throw new Error('Error with category ' + this.actualCategory._id)
}
const series = await this.client.getSeriesLimitFirst({
categId: this.actualCategory._id
})
this.lastSerie = series[series.length - 1]
this.seriesDiv.textContent = '';
(await this.createCards.apply(this, series)).forEach(async (s) =>
this.seriesDiv.append(await s)
)
this.viewDiv.append(this.endDiv)
this.endObserver.observe(this.endDiv)
}
async findAndDeleteCard (id: string) {
const card = this.seriesDiv.querySelector<SerieCard>(`[id='${id}']`)
if (card === null) { throw new Error('Card to delete with id ' + id + ' is null') }
card.draggable = false
card.style.transition = 'visibility 0.3s linear,opacity 0.3s linear'
card.style.opacity = '0'
card.style.visibility = 'hidden'
setTimeout(() => {
card.remove()
}, 1000)
}
}
window.customElements.define('sl-series-view', SeriesView)
<file_sep>import { IAuthController } from '../src/interfaces/IAuthController'
export default class FakeAuth implements IAuthController {
private sudo: boolean = false
onAuthChange?(): void;
isSudo (): boolean {
return this.sudo
}
login (x: { pass: string; url: string }): void {
this.sudo = true
this.onAuthChange!()
}
logout (): void {
this.sudo = false
this.onAuthChange!()
}
remember (): void {
throw new Error('Method not implemented.')
}
}
<file_sep>import { defineConfig } from "vite";
import { VitePWA } from "vite-plugin-pwa";
import { isDebug } from "./app.config";
export default defineConfig({
base: "./",
root: "./",
build: {
outDir: "./dist",
minify: "terser",
target: "esnext",
cssCodeSplit: true,
},
plugins: [],
});
<file_sep>import { runCommand } from './util.js'
const parcel = await runCommand('npx vite serve')
const firebase = await runCommand('npx firebase emulators:start')
function killAll () {
parcel.kill()
firebase.kill()
}
process.on('exit', killAll)
process.on('SIGINT', killAll)
process.on('SIGUSR1', killAll)
process.on('SIGUSR2', killAll)
process.on('uncaughtException', killAll)
<file_sep>enum AuthStatus {
ANONYMOUS,
SIGNED,
SUDO,
}
export default AuthStatus
<file_sep>import { Serie } from '../interfaces/Models'
import '../styles/Modal.scss'
import ModalView from '../interfaces/ModalView'
import { CustomElement } from '../interfaces/CustomElement'
@CustomElement('sl-edit-serie-modal')
export default class EditSerieModal extends ModalView {
onSubmit?(serie: Serie): void;
private imgPrev = document.createElement('img')
private nameInput = document.createElement('input')
private altNameInput = document.createElement('input')
private imgInput = document.createElement('input')
private urlInput = document.createElement('input')
private chapterInput = document.createElement('input')
private titleDiv = document.createElement('div')
private titleSpan = document.createElement('span')
private modalClose = document.createElement('button')
private submitBtn = document.createElement('button')
constructor (private serie: Serie) {
super()
console.log('Editing serie:', serie)
}
connectedCallback () {
const separator = document.createElement('div')
separator.className = 'separator'
const separator2 = document.createElement('div')
separator2.className = 'separator'
const inputsContainer = document.createElement('div')
const allContainer = document.createElement('div')
inputsContainer.className = 'inputs-container'
allContainer.className = 'all-container'
this.imgPrev.className = 'img-prev'
inputsContainer.append(
this.nameInput,
this.altNameInput,
this.imgInput,
this.urlInput,
this.chapterInput
)
allContainer.append(inputsContainer, this.imgPrev)
this.window.append(
this.titleDiv,
separator,
allContainer,
separator2,
this.submitBtn
)
this.titleDiv.append(this.titleSpan, this.modalClose)
this.titleDiv.className = 'title'
this.nameInput.type = 'text'
this.altNameInput.type = 'text'
this.imgInput.type = 'text'
this.urlInput.type = 'text'
this.chapterInput.type = 'number'
this.nameInput.placeholder = 'Nombre'
this.altNameInput.placeholder = 'Nombre alternativo'
this.imgInput.placeholder = 'Link imagen'
this.urlInput.placeholder = 'Url'
this.chapterInput.placeholder = 'Capítulo'
this.titleSpan.innerText = 'Editar serie'
this.modalClose.innerText = 'X'
this.modalClose.className = 'title-btn'
this.modalClose.onclick = () => {
this.disconnectedCallback!()
this.remove()
}
this.imgInput.oninput = () => {
this.imgPrev.src = this.imgInput.value
}
this.submitBtn.innerText = 'Guardar'
this.submitBtn.onclick = this.submit
this.onkeydown = async (ev) => {
if (ev.key === 'Enter') {
await this.submit()
} else if (ev.key === 'Escape') {
this.remove()
}
}
this.nameInput.value = this.serie.name
this.altNameInput.value = this.serie.nameAlt
this.imgPrev.src = this.serie.image
this.imgInput.value = this.serie.image
this.urlInput.value = this.serie.url
this.chapterInput.value = this.serie.chapter.toString()
}
private submit = async () => {
const { runLoading } = await import('./RunLoading')
await runLoading(async () => {
await this.onSubmit!({
_id: this.serie._id,
name: this.nameInput.value,
nameAlt: this.altNameInput.value,
chapter: this.chapterInput.valueAsNumber,
image: this.imgInput.value,
url: this.urlInput.value,
timestamp: new Date()
})
}, this.submitBtn)
this.disconnectedCallback!()
this.remove()
}
}
<file_sep>import * as uglify from 'uglify-js'
import { PurgeCSS } from 'purgecss'
import * as fs from 'fs/promises'
const jsfiles = []
const cssfiles = []
for await (const f of await fs.readdir('./dist/')) {
if (f.endsWith('.js')) jsfiles.push('./dist/' + f)
else if (f.endsWith('.css')) cssfiles.push('./dist/' + f)
}
for await (const f of await fs.readdir('./dist/assets/')) {
if (f.endsWith('.js')) jsfiles.push('./dist/assets/' + f)
else if (f.endsWith('.css')) cssfiles.push('./dist/assets/' + f)
}
console.log('Minifying!')
for await (const js of jsfiles) {
console.log(js)
const source = await fs.readFile(js, {
encoding: 'utf-8'
})
const code = uglify.minify(
{ js: source },
{
compress: { collapse_vars: true, drop_console: true, unused: true },
warnings: 'verbose',
sourceMap: true,
toplevel: true
}
).code
await fs.writeFile(js, code, { encoding: 'utf-8' })
// await fs.writeFile(path.join("./dist/", js), code, "utf-8");
}
const purge = new PurgeCSS()
const res = await purge.purge({
css: cssfiles.map((i) => `${i}`),
content: jsfiles.map((i) => `${i}`),
output: cssfiles.map((i) => `${i}`)
})
console.log(res)
<file_sep>/**
*
* @param {string[]} argv
*/
export async function parseArgs (argv) {
const toret = {}
while (argv.length > 0) {
const splitted = argv.shift().split('=')
if (splitted.length > 1) {
toret[splitted.shift()] = splitted.join('=')
} else {
if (splitted[0].startsWith('!')) {
toret[splitted[0].replace('!', '')] = false
} else {
toret[splitted] = true
}
}
}
return toret
}
<file_sep>import { Category, Serie } from '../src/interfaces/Models'
import { FakeClient } from './FakeClient'
type PlaceholderInfo = {
name: string;
image: string;
};
const SERIES: PlaceholderInfo[] = [
{
name: '<NAME>',
image:
'https://es.web.img2.acsta.net/c_310_420/pictures/21/06/17/12/59/4847468.jpg'
},
{
name: 'Non Non Biyori Nonstop',
image:
'https://ramenparados.com/wp-content/uploads/2020/05/Non-Non-Biyori-Nonstop-key.jpg'
},
{
name: '<NAME> - Isekai Ittara Honki Dasu',
image:
'https://pics.filmaffinity.com/Mushoku_Tensei_Isekai_Ittara_Honki_Dasu_Serie_de_TV-104560602-large.jpg'
},
{
name: 'Kanojo mo Kanojo',
image:
'https://ramenparados.com/wp-content/uploads/2021/03/kanokano-anime-poster.jpg'
},
{
name: 'Fumetsu no Anata e',
image:
'https://www.animefagos.com/wp-content/uploads/2018/01/fumetsuanata01.jpg'
},
{
name: '<NAME> no Cramer',
image:
'https://m.media-amazon.com/images/M/MV5BMDQ3NWNlOGUtNTMwMi00MWNjLWFjNWUtNDcxY2FkYTlkYTM0XkEyXkFqcGdeQXVyODMyNTM0MjM@._V1_.jpg'
},
{
name: 'Boku no Hero Academia 5',
image:
'https://i.pinimg.com/736x/c8/42/fc/c842fc99774afbeff6c07bb6c6a88536.jpg'
},
{
name: 'Tokyo Revengers',
image: 'https://images-na.ssl-images-amazon.com/images/I/810blpOrLhL.jpg'
},
{
name: '<NAME> no <NAME>',
image:
'https://somoskudasai.com/wp-content/uploads/2021/04/genjitsuyushakv.jpg'
},
{
name: '<NAME>ug Cup mo',
image:
'https://freakelitex.com/wp-content/uploads/2020/07/Yakunara-Mug-Cup-Mo-TV.jpg'
},
{
name: 'Non Non Biyori Repeat',
image:
'https://images-na.ssl-images-amazon.com/images/I/81-RVZ8GdkL._SL1280_.jpg'
},
{
name: 'Slime Taoshite 300-nen, Shiranai Uchi ni Level Max ni Nattemashita',
image:
'https://www.animefagos.com/wp-content/uploads/2019/10/slimetaoshite30002.jpg'
},
{
name: 'Sentouin, Hakenshimasu!',
image:
'https://comicvine1.cbsistatic.com/uploads/scale_medium/6/67663/7308803-04.jpg'
},
{
name: 'Majo no Tabitabi',
image:
'https://pics.filmaffinity.com/majo_no_tabitabi_tv_series-222822126-large.jpg'
},
{
name: 'Non non biyori',
image:
'https://pics.filmaffinity.com/non_non_biyori_tv_series-162638798-mmed.jpg'
},
{
name: '<NAME> (TV)',
image: 'https://cdn.myanimelist.net/images/anime/1171/109222l.jpg'
},
{
name: 'Ore wo Suki Nano wa Omae Dake ka yo',
image:
'https://static.wixstatic.com/media/2b52e5_f60454d8f14b4a02a0fddef7e9cd842e~mv2.jpg/v1/fill/w_628,h_1000,al_c,q_90/2b52e5_f60454d8f14b4a02a0fddef7e9cd842e~mv2.jpg'
},
{
name: '<NAME>',
image: 'https://pbs.twimg.com/media/Db-tOHHXcAAZAR5.jpg'
},
{
name: 'Mahouka Koukou no Rettousei: Raihousha-hen',
image:
'https://www.playerone.vg/wp-content/uploads/2020/10/MV5BYmNmMDIzZjktOTcwMS00N2Q1LWE3NTAtNTUwZGJjOWQ3N2NlXkEyXkFqcGdeQXVyMzgxODM4NjM@._V1_-scaled.jpg'
},
{
name: 'Mahouka Koukou no Rettousei',
image:
'https://img1.ak.crunchyroll.com/i/spire3/f2ccbd8ea20320fda0f49b23bb43d2d21396649462_full.jpg'
},
{
name: 'Love Live Sunshine Over the Rainbow',
image:
'https://i.pinimg.com/originals/ac/02/98/ac02980ea4846300f953b7eca0c95084.jpg'
},
{
name: 'Nisekoi',
image: 'https://i.kym-cdn.com/photos/images/original/001/082/371/c57'
},
{
name: 'Fullmetal Alchemist: Brotherhood',
image:
'https://img1.ak.crunchyroll.com/i/spire4/fabddf1040abbd18948b9aacc18011b31475523493_main.jpg'
},
{
name: '<NAME>',
image:
'https://www.animefagos.com/wp-content/uploads/2018/11/caroletuesday01.jpg'
},
{
name: 'Noragami',
image: 'https://animerelleno.com/storage/animes/poster/noragami.jpg'
},
{
name: 'Re:Zero k<NAME> <NAME>',
image:
'https://img1.ak.crunchyroll.com/i/spire2/95445cd55c37ce2ff04ef1adde79f50c1529088362_main.jpg'
}
]
const CATEGS = [
'Viendo',
'Pendientes',
'Vistos',
'Favoritos',
'Mangas Terminados',
'Mangas en espera',
'Simultcasts',
'Live Actions',
'Películas',
'HBO',
'Netflix',
'BBC'
]
export default class Placeholders {
static async getRandomSerie (): Promise<Serie> {
const s = SERIES[Math.floor(SERIES.length * Math.random())]
return {
_id: await this.getRandomText(),
timestamp: new Date(),
name: s.name,
nameAlt: s.name,
image: s.image,
url: '',
chapter: Math.floor(Math.random() * 24)
}
}
static async getRandomCategory (): Promise<Category> {
const c = CATEGS[Math.floor(CATEGS.length * Math.random())]
return {
_id: await this.getRandomText(),
name: c,
timestamp: new Date()
}
}
static async getRandomText (length: number = 32): Promise<string> {
const letters = 'abcdefghijklnmopqrstuvwxyz '
let toret: string = ''
for (let i = 0; i < length; i++) {
toret += letters[Math.floor(Math.random() * letters.length)]
}
return toret
}
}
<file_sep>import BackupController from '../../controllers/BackupController'
import IComponent from '../../interfaces/Component'
export default class BackupsView extends IComponent {
constructor (private controller: BackupController) {
super()
}
connectedCallback () {
const list = document.createElement('ul')
const saveLi = document.createElement('li')
const loadLi = document.createElement('li')
const saveBtn = document.createElement('button')
saveBtn.innerText = 'Guardar copia de seguridad'
saveBtn.onclick = async () => {
await this.controller.save()
}
const loadLabel = document.createElement('label')
loadLabel.innerText = 'Cargar copia de seguridad'
const loadInput = document.createElement('input')
loadInput.type = 'file'
loadInput.accept = '.json'
loadInput.multiple = false
const loadBtn = document.createElement('button')
loadBtn.innerText = 'Cargar'
loadInput.onchange = async () => {
if (
loadInput.files!.length > 0 &&
confirm(
`${loadInput.files!.item(0)!.name} - ${
loadInput.files!.item(0)!.size / 1024
} KB\nLa información de la base de datos no se eliminará ¿Quieres continuar?`
)
) {
await this.controller.load(loadInput.files?.item(0)!)
alert('Backup cargado')
}
}
this.append(list)
loadLabel.append(loadInput)
list.append(saveLi, loadLi)
saveLi.append(saveBtn)
loadLi.append(loadLabel)
}
}
window.customElements.define('sl-backups-view', BackupsView)
<file_sep>import { AuthChangeEvent } from '../controllers/auth/FirebaseAuthController'
import IComponent from './Component'
export default abstract class View extends IComponent {
abstract authChangeEvent(x: AuthChangeEvent): Promise<void>;
}
| efd3f6ffd60145eae588b04399a7153272a1237e | [
"JavaScript",
"TypeScript",
"Markdown"
] | 46 | TypeScript | Kingomac/Series-List | 6426fb6e62f6029030737bbfed3e9e805cbd9dc8 | adde1068c32e020bab0192653767e6e2435a1a2d | |
refs/heads/master | <repo_name>marcsi19/macaron<file_sep>/src/components/cartItem.js
import React from 'react'
const cartItem = (props) => {
const { product, removeFromCart } = props
return (
<div key={product.id}>
<div className="cart_product_main" >
<div className="cart_product_img">
<img src={product.image} alt="product" />
</div>
<div className="cart_product_description">
<h3>{product.title}</h3>
<h4>{product.subTitle}</h4>
<button onClick={() => removeFromCart(product.id)}>Remove</button>
</div>
<div className="cart_product_price">${product.price}</div>
</div>
</div>
)
}
export default cartItem
<file_sep>/src/components/cart.js
import React from 'react'
import CartItem from './cartItem'
const Cart = (props) => {
let { cart, showCart, showingCart, removeFromCart } = props
return (
<div className="wrapper" id="wrapper">
<div>
<button onClick={showingCart} className="cart_close_button">Close</button>
</div>
<h2>My Cart</h2>
< div > {cart.map(product => {
return (
<CartItem product={product} removeFromCart={removeFromCart} key={product.id} />
)
})}</div >
<div className="cart_total">Total </div> <div className="cart_total_amount"> ${cart.reduce(((acc, currVal) =>
acc + (currVal.quantity * currVal.price)), 0).toFixed(2)}</div>
<button className="checkout_btn">Continue to Checkout</button>
</div >
)
}
export default Cart
<file_sep>/src/components/data.js
const menuItems = [{
id: 1,
title: 'Custom Gift Box',
subTitle: 'Assorted Flavors',
description: `This 16 piece gift box is perfect for birthdays, anniversaries or just for yourself! Customize your flavors or pick from our three gift boxes! \n
We offer pre-packed Citrus, Floral or Classic themed boxes. We offer next day delivery for free with all custom gift boxes!`,
price: 55,
quantity: 0,
image: require('../img/custom_gift_box.png'),
buttonText: "+ Add to Cart"
},
{
id: 2,
title: 'Vanilla Earl Grey Macaron',
subTitle: '1 Piece',
description: `Our most popular flavor! Each macaron is filled with earl grey ganache.`,
price: 3.75,
quantity: 0,
image: require('../img/vanilla.png'),
buttonText: "+ Add to Cart"
},
{
id: 3,
title: 'Rose Macarons',
subTitle: '1 Piece',
description: `Our most romatic flavor! Filled with the lightest, sweetest rose ganache, this macaron will definitely be a pleasant surprise.`,
price: 3.75,
quantity: 0,
image: require('../img/rose.png'),
buttonText: "+ Add to Cart"
}]
export default menuItems
<file_sep>/src/components/footer.js
import React, { Component } from 'react'
import facebook from '../img/facebook_icon.svg'
import twitter from '../img/twitter_icon.svg'
import instagram from '../img/instagram_icon.svg'
class Footer extends Component {
render() {
return (
<div className="footer_main">
<div className="footer_left">
<h3>We are committed to serving the freshest, most delightful treats.</h3>
<div className="footer_media">
<img src={facebook} alt="facebook" />
<img src={twitter} alt="twitter" />
<img src={instagram} alt="instagram" />
</div>
<p>© 2019 MACARONS</p>
</div>
<div className="footer_right">
<div>
<h4>Company</h4>
<ul>
<li>About</li>
<li>Locations</li>
<li>Contact us</li>
</ul>
</div>
<div>
<h4>Orders</h4>
<ul>
<li>Order Tracker</li>
<li>Delivery FAQ</li>
</ul>
</div>
</div>
</div>
)
}
}
export default Footer
<file_sep>/src/components/menu.js
import React, { Component } from 'react'
import Product from './product'
class Menu extends Component {
constructor(props) {
super(props);
this.state = { open: false };
this.toggle = this.toggle.bind(this)
}
toggle() {
this.setState({
open: !this.state.open
});
}
render() {
let { menuItems, addToCart, buttonText } = this.props
return (
<div className="menu_main">
<h3>Menu</h3>
<div >
{menuItems.map(product => {
return (
<Product product={product} key={product.id} addToCart={addToCart} buttonText={buttonText} toggle={this.toggle} open={this.state.open} />
)
}
)}
</div>
</div>
)
}
}
export default Menu;
<file_sep>/src/components/navbar.js
import React from 'react'
import { Link } from 'react-router-dom'
import logo from '../img/logo.svg'
import cartIcon from '../img/cart_icon.svg'
const Navbar = (props) => {
let quantity = props.quantity
return (
<div>
<nav className="navbar_main">
<Link to='/' className="navbar_logo"> <img
src={logo}
alt="Cart"
height="22px"
/></Link>
<Link to="/menu" className="navbar_menu">Menu</Link>
<Link to="/beverages" className="navbar_menu">Beverages</Link>
<Link to="/gifts" className="navbar_menu">Gifts</Link>
<span className="navbar_menu">|</span>
<span><img
src={cartIcon}
alt="Cart"
className='cart_svg'
/></span>
<button className="cart_nav navbar_menu" onClick={props.showingCart}>
<span className={quantity ? "cart_circle" : "cart_circle_empty"}>{quantity ? quantity : ""}</span>
Cart</button>
</nav>
</div>
)
}
export default Navbar;
<file_sep>/src/components/product.js
import React from 'react'
const Product = (props) => {
let { product, addToCart, buttonText, toggle, open } = props
let addToCartClass = buttonText[product.id - 1] !== "+ Add to Cart" ? "added_to_cart" : "add_to_cart"
return (
<div className="menu_product_main" >
<div className="menu_product_img">
<img src={product.image} alt={product.title} />
</div>
<div className="menu_product_description">
<h3>{product.title}</h3>
<h4>{product.subTitle}</h4>
<div className="menu_product_description_desc">
{product.description.split('\n').map((item, i) =>
(i === 2) ?
(<div key={i}>
<p className={"collapse" + (open ? ' in' : '')}>{item}
</p>
<div className="read_div">
<button className="read_more in" onClick={toggle}>{open ? "Read Less" : "Read More"}</button>
</div>
</div>
)
: <p key={i}>{item}</p>
)
}
</div>
</div>
<div className="menu_product_shop">
<p>${product.price} /ea.</p>
<button className={addToCartClass} type="submit" onClick={() => addToCart(product)}>{buttonText[product.id - 1]}</button>
</div>
</div>
)
}
export default Product;
| d42e4ac73bb42078d04823c5e8fddbf2c6044e7b | [
"JavaScript"
] | 7 | JavaScript | marcsi19/macaron | 12402b4ec81dbe3478a49aec0bb352d42beeb360 | bdb3f9de58cbcbca54f5bf0000bf581e002381da | |
refs/heads/master | <repo_name>savaslabs/D8Default<file_sep>/Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure(2) do |config|
# The most common configuration options are documented and commented below.
# For a complete reference, please see the online documentation at
# https://docs.vagrantup.com.
# Every Vagrant development environment requires a box. You can search for
# boxes at https://atlas.hashicorp.com/search.
config.vm.box = "savas/trusty64"
config.vm.provider :virtualbox do |vb|
vb.customize ["modifyvm", :id, "--memory", 2048]
end
project = 'default'
sitename = 'Default D8'
config.vm.synced_folder ".", "/var/www/#{project}.dev", :nfs => true
config.vm.hostname = "#{project}.dev"
# SSH options.
config.ssh.insert_key = false
config.ssh.forward_agent = true
config.vm.network :private_network, ip: "192.168.88.96"
# Creating the project directory and restarting apache...
$script = <<SCRIPT
mkdir -p /var/www/#{project}.dev/www/web
sudo service apache2 restart
SCRIPT
config.vm.provision "shell", inline: $script
#Installing Drupal via Composer Template for Drupal Projects
$script = <<SCRIPT
echo Installing Drupal Base Install...
cd /var/www/#{project}.dev
rmdir /var/www/#{project}.dev/www/web
composer create-project drupal-composer/drupal-project:8.x-dev www --stability dev --no-interaction
echo Downloading devel module...
cd /var/www/#{project}.dev/www
sudo service apache2 restart
composer require drupal/devel:8.*
cd /var/www/#{project}.dev/www/web
mysql -u root -proot -e "create database drupal"
mysql -u root -proot -e "grant all on drupal.* to root@localhost identified by 'root'";
../vendor/bin/drush si -y --account-name=admin --account-pass=<PASSWORD> --db-su=root --db-su-pw=root --db-url=mysql://root:root@localhost/drupal --site-name=#{sitename}
../vendor/bin/drush en devel -y
mkdir -p modules/custom
mkdir -p themes/contrib
mkdir -p themes/custom
mkdir -p profiles/contrib
mkdir -p profiles/custom
touch modules/custom/README.md
touch themes/custom/README.md
touch profiles/custom/README.md
echo Creating drush symlink...
sudo ln -s /var/www/#{project}.dev/www/vendor/bin/drush /usr/local/bin/drush
SCRIPT
config.vm.provision "shell", inline: $script
end
<file_sep>/README.md
# D8Default
This project is a starting point for a Drupal 8 base install managed with Composer. This project installs D8 and the devel module from the https://github.com/drupal-composer/drupal-project. Please consult the README in the drupal-composer/drupal-project for more details.
This repository assumes that you will be using a base VM box that is configured with a full lamp stack, has Composer installed, and all the testing tools that you will be utilizing (Selenium, NodeJS, etc.). If not, then you will need to add provisioning to the Vagrantfile to add these items to your base box when you run "make init".
The following base boxes are configured as such:
* https://atlas.hashicorp.com/savas/boxes/trusty64 (`savas/trusty64`)
To use the repository, clone this repo, modify the Vagrantfile to change the name of the "project" and "sitename" variables located on lines 20-21, save the changes and run "make init".
You will need to add a new origin repository to your project; the "make init" process will remove any existing origin repo from your project on the initial build.
Use the README.md in your project for project documentation.
## Updating Drupal Core
To update Drupal Core, see https://github.com/drupal-composer/drupal-project#updating-drupal-core
## Adding contrib modules and committing custom code
Only custom modules, themes and profiles should be committed to the code repository. The contrib modules should be added to the composer.json file.
To add a new contrib module to a project, change to the project directory where the project's composer.json file is located (usually inside the www directory), and issue the command `composer require drupal/<contrib-module-name>:8.*`. If you need to pin a specific module version, that can be added instead of the asterisk, which will update to the latest stable or recommended version. `composer require` will update the composer.json and composer.lock files so make sure you commit both back to the project as part of your pull request.
The same goes for a base theme, or a base profile.
Only the modules/custom, themes/custom and profiles/custom directories will be committed to the code repository.
## Updating after an upstream merge / rebase
To update your project after an upstream merge or rebase so that your core and contrib modules are in sync with the project repository, issue the following command:
`composer install`
This will update your local installation based on the contents of the composer.lock file.
| b30288ad0d8dbf7da6583ca1226a31f6e615a9cb | [
"Markdown",
"Ruby"
] | 2 | Ruby | savaslabs/D8Default | 6d09a4ce64af80eeb8653c4c157055fe266dd22b | 3bbed124f895f3bd7f213e99f6d5c045ab87ae8b | |
refs/heads/master | <repo_name>vannicaruso/jdbcdslog<file_sep>/build.xml
<?xml version="1.0" encoding="UTF-8"?>
<project name="jdbcdslog" default="all">
<presetdef name="javac">
<javac includeantruntime="false" />
</presetdef>
<property file="build.properties"/>
<!-- Uncomment the following property if no tests compilation is needed -->
<!--
<property name="skip.tests" value="true"/>
-->
<!-- Compiler options -->
<property name="compiler.debug" value="on"/>
<property name="compiler.generate.no.warnings" value="off"/>
<property name="compiler.args" value=""/>
<property name="compiler.max.memory" value="128m"/>
<patternset id="ignored.files">
<exclude name="**/CVS/**"/>
<exclude name="**/SCCS/**"/>
<exclude name="**/RCS/**"/>
<exclude name="**/rcs/**"/>
<exclude name="**/.DS_Store/**"/>
<exclude name="**/.svn/**"/>
<exclude name="**/.pyc/**"/>
<exclude name="**/.pyo/**"/>
<exclude name="**/*.pyc/**"/>
<exclude name="**/*.pyo/**"/>
<exclude name="**/.git/**"/>
<exclude name="**/*.hprof/**"/>
<exclude name="**/_svn/**"/>
<exclude name="**/.hg/**"/>
<exclude name="**/*.lib/**"/>
<exclude name="**/*~/**"/>
<exclude name="**/__pycache__/**"/>
<exclude name="**/.bundle/**"/>
<exclude name="**/*.rbc/**"/>
</patternset>
<patternset id="library.patterns">
<include name="*.war"/>
<include name="*.ear"/>
<include name="*.apk"/>
<include name="*.zip"/>
<include name="*.swc"/>
<include name="*.ane"/>
<include name="*.egg"/>
<include name="*.jar"/>
</patternset>
<patternset id="compiler.resources">
<exclude name="**/?*.java"/>
<exclude name="**/?*.form"/>
<exclude name="**/?*.class"/>
<exclude name="**/?*.groovy"/>
<exclude name="**/?*.scala"/>
<exclude name="**/?*.flex"/>
<exclude name="**/?*.kt"/>
<exclude name="**/?*.clj"/>
</patternset>
<!-- Global Libraries -->
<!-- Application Server Libraries -->
<!-- Modules -->
<!-- Module main -->
<dirname property="module.main.basedir" file="${ant.file}"/>
<property name="compiler.args.main" value="${compiler.args}"/>
<property name="main.output.dir" value="${module.main.basedir}/out/production/main"/>
<property name="main.testoutput.dir" value="${module.main.basedir}/out/test/main"/>
<path id="main.module.bootclasspath">
<!-- Paths to be included in compilation bootclasspath -->
</path>
<path id="main.module.production.classpath">
<fileset dir="${basedir}/lib">
<patternset refid="library.patterns"/>
</fileset>
</path>
<path id="main.runtime.production.module.classpath">
<pathelement location="${main.output.dir}"/>
<fileset dir="${basedir}/lib">
<patternset refid="library.patterns"/>
</fileset>
</path>
<path id="main.module.classpath">
<pathelement location="${main.output.dir}"/>
<fileset dir="${basedir}/lib">
<patternset refid="library.patterns"/>
</fileset>
</path>
<path id="main.runtime.module.classpath">
<pathelement location="${main.testoutput.dir}"/>
<pathelement location="${main.output.dir}"/>
<fileset dir="${basedir}/lib">
<patternset refid="library.patterns"/>
</fileset>
</path>
<patternset id="excluded.from.module.main">
<patternset refid="ignored.files"/>
</patternset>
<patternset id="excluded.from.compilation.main">
<patternset refid="excluded.from.module.main"/>
</patternset>
<path id="main.module.sourcepath">
<dirset dir="${module.main.basedir}/src/main">
<include name="java"/>
</dirset>
</path>
<target name="compile.module.main" depends="compile.module.main.production,compile.module.main.tests" description="Compile module main"/>
<target name="compile.module.main.production" description="Compile module main; production classes">
<mkdir dir="${main.output.dir}"/>
<javac destdir="${main.output.dir}" debug="${compiler.debug}" nowarn="${compiler.generate.no.warnings}" memorymaximumsize="${compiler.max.memory}" fork="true">
<compilerarg line="${compiler.args.main}"/>
<bootclasspath refid="main.module.bootclasspath"/>
<classpath refid="main.module.production.classpath"/>
<src refid="main.module.sourcepath"/>
<patternset refid="excluded.from.compilation.main"/>
</javac>
<copy todir="${main.output.dir}">
<fileset dir="${module.main.basedir}/src/main/java">
<patternset refid="compiler.resources"/>
<type type="file"/>
</fileset>
</copy>
</target>
<target name="compile.module.main.tests" depends="compile.module.main.production" description="compile module main; test classes" unless="skip.tests"/>
<target name="clean.module.main" description="cleanup module">
<delete dir="${main.output.dir}"/>
<delete dir="${main.testoutput.dir}"/>
</target>
<!-- Module test -->
<dirname property="module.test.basedir" file="${ant.file}"/>
<property name="compiler.args.test" value="${compiler.args}"/>
<property name="test.output.dir" value="${module.test.basedir}/out/production/test"/>
<property name="test.testoutput.dir" value="${module.test.basedir}/out/test/test"/>
<path id="test.module.bootclasspath">
<!-- Paths to be included in compilation bootclasspath -->
</path>
<path id="test.module.production.classpath">
<pathelement location="${main.output.dir}"/>
<fileset dir="${basedir}/lib">
<patternset refid="library.patterns"/>
</fileset>
</path>
<path id="test.runtime.production.module.classpath">
<pathelement location="${test.output.dir}"/>
<path refid="main.runtime.production.module.classpath"/>
<fileset dir="${basedir}/lib">
<patternset refid="library.patterns"/>
</fileset>
</path>
<path id="test.module.classpath">
<pathelement location="${test.output.dir}"/>
<pathelement location="${main.testoutput.dir}"/>
<pathelement location="${main.output.dir}"/>
<fileset dir="${basedir}/lib">
<patternset refid="library.patterns"/>
</fileset>
</path>
<path id="test.runtime.module.classpath">
<pathelement location="${test.testoutput.dir}"/>
<pathelement location="${test.output.dir}"/>
<path refid="main.runtime.module.classpath"/>
<fileset dir="${basedir}/lib">
<patternset refid="library.patterns"/>
</fileset>
</path>
<patternset id="excluded.from.module.test">
<patternset refid="ignored.files"/>
</patternset>
<patternset id="excluded.from.compilation.test">
<patternset refid="excluded.from.module.test"/>
</patternset>
<path id="test.module.test.sourcepath">
<dirset dir="${module.test.basedir}/src/test">
<include name="java"/>
</dirset>
</path>
<target name="compile.module.test" depends="compile.module.test.production,compile.module.test.tests" description="Compile module test"/>
<target name="compile.module.test.production" depends="compile.module.main" description="Compile module test; production classes"/>
<target name="compile.module.test.tests" depends="compile.module.test.production" description="compile module test; test classes" unless="skip.tests">
<mkdir dir="${test.testoutput.dir}"/>
<javac destdir="${test.testoutput.dir}" debug="${compiler.debug}" nowarn="${compiler.generate.no.warnings}" memorymaximumsize="${compiler.max.memory}" fork="true">
<compilerarg line="${compiler.args.test}"/>
<bootclasspath refid="test.module.bootclasspath"/>
<classpath refid="test.module.classpath"/>
<src refid="test.module.test.sourcepath"/>
<patternset refid="excluded.from.compilation.test"/>
</javac>
<copy todir="${test.testoutput.dir}">
<fileset dir="${module.test.basedir}/src/test/java">
<patternset refid="compiler.resources"/>
<type type="file"/>
</fileset>
</copy>
</target>
<target name="clean.module.test" description="cleanup module">
<delete dir="${test.output.dir}"/>
<delete dir="${test.testoutput.dir}"/>
</target>
<target name="init" description="Build initialization">
<!-- Perform any build initialization in this target -->
</target>
<target name="clean" depends="clean.module.main, clean.module.test" description="cleanup all"/>
<target name="build.modules" depends="init, clean, compile.module.main, compile.module.test" description="build all modules"/>
<target name="all" depends="build.modules" description="build all"/>
<target name="test" depends="all">
<junit printsummary="yes" haltonfailure="no">
<classpath>
<pathelement location="${main.output.dir}"/>
<pathelement location="${test.testoutput.dir}"/>
<pathelement path="${basedir}/lib/junit-4.9.jar"/>
<pathelement path="${basedir}/lib/slf4j-api-1.7.2.jar"/>
<pathelement path="${basedir}/lib/logback-core-1.0.13.jar"/>
<pathelement path="${basedir}/lib/logback-classic-1.0.13.jar"/>
<pathelement path="${basedir}/lib/logback-access-1.0.13.jar"/>
<pathelement path="${basedir}/lib/hsqldb-1.8.0.10.jar"/>
</classpath>
<formatter type="plain" usefile="false"/>
<batchtest>
<fileset dir="${module.test.basedir}/src/test/java">
<include name="**/*Test*"/>
</fileset>
</batchtest>
</junit>
</target>
</project><file_sep>/src/main/java/org/jdbcdslog/ConnectionPoolXADataSourceProxy.java
package org.jdbcdslog;
import javax.sql.ConnectionPoolDataSource;
import javax.sql.DataSource;
import javax.sql.XADataSource;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;
public class ConnectionPoolXADataSourceProxy extends DataSourceProxyBase implements DataSource, XADataSource, ConnectionPoolDataSource {
private static final long serialVersionUID = 5829721261280763559L;
public ConnectionPoolXADataSourceProxy() throws JDBCDSLogException {
super();
}
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
return this.getParentLogger();
}
public Object unwrap(Class iface) throws SQLException {
return null;
}
}
<file_sep>/src/main/java/org/jdbcdslog/XADataSourceProxy.java
package org.jdbcdslog;
import javax.sql.CommonDataSource;
import javax.sql.DataSource;
import javax.sql.XADataSource;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;
public class XADataSourceProxy extends DataSourceProxyBase implements XADataSource, DataSource {
private static final long serialVersionUID = -2923593005281631348L;
public XADataSourceProxy() throws JDBCDSLogException {
super();
}
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
return this.getParentLogger();
}
public Object unwrap(Class iface) throws SQLException {
return null;
}
}
<file_sep>/build.properties
path.variable.maven_repository=/home/GiovanniCaruso/.m2/repository | aae6c6dbb48b1f3eb41ca26a222c6d70e6b3f4aa | [
"Java",
"Ant Build System",
"INI"
] | 4 | Ant Build System | vannicaruso/jdbcdslog | 5791461e4cdca72a9ea3618449c188c599fe370c | 54e33aaa5d454ccedd0cc9072376c846a5dd5872 | |
refs/heads/master | <repo_name>bersanibond/Study-Time<file_sep>/Study Time/ViewController.swift
//
// ViewController.swift
// Study Time
//
// Created by <NAME> on 8/10/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var myImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
goalName.delegate = self
countDownTimer.setValue(UIColor.white, forKey: "textColor")
}
var addBtnSound: AVAudioPlayer?
var goal = ""
// Goal Is On\OFF (Currently running)
var oneIsOn = false
var twoIsOn = false
var threeIsOn = false
var fourIsOn = false
var fiveIsOn = false
var sixIsOn = false
var sevenIsOn = false
// Goal Views
@IBOutlet weak var goalOneView: UIView!
@IBOutlet weak var goalTwoView: UIView!
@IBOutlet weak var goalThreeView: UIView!
@IBOutlet weak var goalFourView: UIView!
@IBOutlet weak var goalFiveView: UIView!
@IBOutlet weak var goalSixView: UIView!
@IBOutlet weak var goalSevenView: UIView!
//Goal Labels
@IBOutlet weak var goalOneLabel: UILabel!
@IBOutlet weak var goalTwoLabel: UILabel!
@IBOutlet weak var goalThreeLabel: UILabel!
@IBOutlet weak var goalFourLabel: UILabel!
@IBOutlet weak var goalFiveLabel: UILabel!
@IBOutlet weak var goalSixLabel: UILabel!
@IBOutlet weak var goalSevenLabel: UILabel!
// Start Buttons
@IBOutlet weak var oneStartBtn: UIButton!
@IBOutlet weak var twoStartBtn: UIButton!
@IBOutlet weak var threeStartBtn: UIButton!
@IBOutlet weak var fourStartBtn: UIButton!
@IBOutlet weak var fiveStartbtn: UIButton!
@IBOutlet weak var sixStartBtn: UIButton!
@IBOutlet weak var sevenStartBtn: UIButton!
//Close Timer - Buttons Outlet
@IBOutlet weak var closeGoalOneButton: UIButton!
@IBOutlet weak var closeGoalTwoButton: UIButton!
@IBOutlet weak var closeGoalThreeButton: UIButton!
@IBOutlet weak var closeGoalFourButton: UIButton!
@IBOutlet weak var closeGoalFiveButton: UIButton!
@IBOutlet weak var closeGoalSixButton: UIButton!
@IBOutlet weak var closeGoalSevenButton: UIButton!
//Close Timer = Button Actions
@IBAction func closeGoalOne(_ sender: Any) {
goalOneView.isHidden = true
}
@IBAction func closeGoalTwo(_ sender: Any) {
goalTwoView.isHidden = true
}
@IBAction func closeGoalThree(_ sender: Any) {
goalThreeView.isHidden = true
}
@IBAction func closeGoalFour(_ sender: Any) {
goalFourView.isHidden = true
}
@IBAction func closeGoalFive(_ sender: Any) {
goalFiveView.isHidden = true
}
@IBAction func closeGoalSix(_ sender: Any) {
goalSixView.isHidden = true
}
@IBAction func closeGoalSeven(_ sender: Any) {
goalSevenView.isHidden = true
}
//Goal Time Labels
@IBOutlet weak var goalOneTimeLabel: UILabel!
@IBOutlet weak var goalTwoTimeLabel: UILabel!
@IBOutlet weak var goalThreeTimeLabel: UILabel!
@IBOutlet weak var goalFourTimeLabel: UILabel!
@IBOutlet weak var goalFiveTimeLabel: UILabel!
@IBOutlet weak var goalSixTimeLabel: UILabel!
@IBOutlet weak var goalSevenTimeLabel: UILabel!
@IBAction func testing(_ sender: Any) {
print("\(countDownTimer.countDownDuration)")
}
//Exit Timer
@IBAction func exitTimer(_ sender: Any) {
//let allGoals = [oneIsOn,twoIsOn,threeIsOn,fourIsOn,fiveIsOn]
if oneIsOn == true {
goalOneTime = Double(seconds)
goalOneTimeLabel.text = "\(timeString(time: TimeInterval(seconds)))"
oneIsOn = false
if goalOneTime < 1 {
oneStartBtn.isHidden = true
}
} else if twoIsOn == true {
goalTwoTime = Double(seconds)
goalTwoTimeLabel.text = "\(timeString(time: TimeInterval(seconds)))"
twoIsOn = false
if goalTwoTime < 1 {
twoStartBtn.isHidden = true
}
}else if threeIsOn == true {
goalThreeTime = Double(seconds)
goalThreeTimeLabel.text = "\(timeString(time: TimeInterval(seconds)))"
threeIsOn = false
if goalThreeTime < 1 {
threeStartBtn.isHidden = true
}
}else if fourIsOn == true {
goalFourTime = Double(seconds)
goalFourTimeLabel.text = "\(timeString(time: TimeInterval(seconds)))"
fourIsOn = false
if goalFourTime < 1 {
fourStartBtn.isHidden = true
}
}else if fiveIsOn == true {
goalFiveTime = Double(seconds)
goalFiveTimeLabel.text = "\(timeString(time: TimeInterval(seconds)))"
fiveIsOn = false
if goalFiveTime < 1 {
fiveStartbtn.isHidden = true
}
}else if sixIsOn == true {
goalSixTime = Double(seconds)
goalSixTimeLabel.text = "\(timeString(time: TimeInterval(seconds)))"
sixIsOn = false
if goalSixTime < 1 {
sixStartBtn.isHidden = true
}
}else if sevenIsOn == true {
goalSevenTime = Double(seconds)
goalSevenTimeLabel.text = "\(timeString(time: TimeInterval(seconds)))"
sevenIsOn = false
if goalSevenTime < 1 {
sevenStartBtn.isHidden = true
}
}
ViewTimerRunning.isHidden = true
timer.invalidate()
}
// Start Study Timer
@IBAction func startOne(_ sender: Any) {
ViewTimerRunning.isHidden = false
labelOfGoalRunning.text = goalOneLabel.text
seconds = Int(goalOneTime)
countDownTimer.countDownDuration = goalOneTime
timerLabel.text = timeString(time: TimeInterval(goalOneTime))
runTimer()
oneIsOn = true
}
@IBAction func startTwo(_ sender: Any) {
ViewTimerRunning.isHidden = false
labelOfGoalRunning.text = goalTwoLabel.text
seconds = Int(goalTwoTime)
countDownTimer.countDownDuration = goalTwoTime
timerLabel.text = timeString(time: TimeInterval(goalTwoTime))
runTimer()
twoIsOn = true
}
@IBAction func startThree(_ sender: Any) {
ViewTimerRunning.isHidden = false
labelOfGoalRunning.text = goalThreeLabel.text
seconds = Int(goalThreeTime)
countDownTimer.countDownDuration = goalThreeTime
timerLabel.text = timeString(time: TimeInterval(goalThreeTime))
runTimer()
threeIsOn = true
}
@IBAction func startFour(_ sender: Any) {
ViewTimerRunning.isHidden = false
labelOfGoalRunning.text = goalFourLabel.text
seconds = Int(goalFourTime)
countDownTimer.countDownDuration = goalFourTime
timerLabel.text = timeString(time: TimeInterval(goalFourTime))
runTimer()
fourIsOn = true
}
@IBAction func startFive(_ sender: Any) {
ViewTimerRunning.isHidden = false
labelOfGoalRunning.text = goalFiveLabel.text
seconds = Int(goalFiveTime)
countDownTimer.countDownDuration = goalFiveTime
timerLabel.text = timeString(time: TimeInterval(goalFiveTime))
runTimer()
fiveIsOn = true
}
@IBAction func startSix(_ sender: Any) {
ViewTimerRunning.isHidden = false
labelOfGoalRunning.text = goalSixLabel.text
seconds = Int(goalSixTime)
countDownTimer.countDownDuration = goalSixTime
timerLabel.text = timeString(time: TimeInterval(goalSixTime))
runTimer()
sixIsOn = true
}
@IBAction func startSeven(_ sender: Any) {
ViewTimerRunning.isHidden = false
labelOfGoalRunning.text = goalSevenLabel.text
seconds = Int(goalSevenTime)
countDownTimer.countDownDuration = goalSevenTime
timerLabel.text = timeString(time: TimeInterval(goalSevenTime))
runTimer()
sevenIsOn = true
}
// View of Timer Running
@IBOutlet weak var ViewTimerRunning: UIView!
@IBOutlet weak var labelOfGoalRunning: UILabel!
// Timer Label
@IBOutlet weak var timerLabel: UILabel!
// Run Timer
var seconds = 60
var timer = Timer()
var isTimerRunning = false
func runTimer() {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(ViewController.updateTimer)), userInfo: nil, repeats: true)
}
@objc func updateTimer() {
seconds -= 1 //This will decrement(count down)the seconds.
timerLabel.text = timeString(time: TimeInterval(seconds)) //This will update the label.
if seconds == 0 {
timer.invalidate()
let path = Bundle.main.path(forResource: "dingling.mp3", ofType:nil)!
let url = URL(fileURLWithPath: path)
do {
addBtnSound = try AVAudioPlayer(contentsOf: url)
addBtnSound?.play()
} catch {
// couldn't load file :(
}
}
}
// Timer Value
var goalOneTime: Double = 00
var goalTwoTime: Double = 00
var goalThreeTime: Double = 00
var goalFourTime: Double = 00
var goalFiveTime: Double = 00
var goalSixTime: Double = 00
var goalSevenTime: Double = 00
var goalEightTime: Double = 00
var goalNineTime: Double = 00
var goalTenTime: Double = 00
//Formatting Hours, Minutes, Seconds
func timeString(time:TimeInterval) -> String {
let hours = Int(time) / 3600
let minutes = Int(time) / 60 % 60
let seconds = Int(time) % 60
return String(format:"%0.2d:%0.2d:%0.2d", hours , minutes , seconds )
}
// Add Goals
@IBAction func addGoal(_ sender: Any) {
goal = goalName.text!
//runTimer()
seconds = Int(countDownTimer.countDownDuration)
if goalOneView.isHidden {
goalOneView.isHidden = false
goalOneLabel.text = "\(goal)"
goalOneTimeLabel.text = "\(timeString(time: TimeInterval(seconds)))"
goalName.text = ""
goalOneTime = countDownTimer.countDownDuration
oneStartBtn.isHidden = false
} else if goalTwoView.isHidden {
goalTwoView.isHidden = false
goalTwoLabel.text = "\(goal)"
goalTwoTimeLabel.text = "\(timeString(time: TimeInterval(seconds)))"
goalName.text = ""
goalTwoTime = countDownTimer.countDownDuration
twoStartBtn.isHidden = false
} else if goalThreeView.isHidden {
goalThreeView.isHidden = false
goalThreeLabel.text = "\(goal)"
goalThreeTimeLabel.text = "\(timeString(time: TimeInterval(seconds)))"
goalName.text = ""
goalThreeTime = countDownTimer.countDownDuration
threeStartBtn.isHidden = false
} else if goalFourView.isHidden {
goalFourView.isHidden = false
goalFourLabel.text = "\(goal)"
goalFourTimeLabel.text = "\(timeString(time: TimeInterval(seconds)))"
goalName.text = ""
goalFourTime = countDownTimer.countDownDuration
fourStartBtn.isHidden = false
} else if goalFiveView.isHidden {
goalFiveView.isHidden = false
goalFiveLabel.text = "\(goal)"
goalFiveTimeLabel.text = "\(timeString(time: TimeInterval(seconds)))"
goalName.text = ""
goalFiveTime = countDownTimer.countDownDuration
fiveStartbtn.isHidden = false
} else if goalSixView.isHidden {
goalSixView.isHidden = false
goalSixLabel.text = "\(goal)"
goalSixTimeLabel.text = "\(timeString(time: TimeInterval(seconds)))"
goalName.text = ""
goalSixTime = countDownTimer.countDownDuration
sixStartBtn.isHidden = false
} else if goalSevenView.isHidden {
goalSevenView.isHidden = false
goalSevenLabel.text = "\(goal)"
goalSevenTimeLabel.text = "\(timeString(time: TimeInterval(seconds)))"
goalName.text = ""
goalSevenTime = countDownTimer.countDownDuration
sevenStartBtn.isHidden = false
}
print("\(countDownTimer.countDownDuration)")
print("\(goalOneTime)")
}
var countDownDuration: TimeInterval?
//var countDownDuration: TimeInterval { get set }
@IBOutlet weak var countDownTimer: UIDatePicker!
// TextField
@IBOutlet weak var goalName: UITextField!
let limitLength = 27
//testing getting music names
/*func gettingSongName() {
let folderUrl = URL(fileURLWithPath: Bundle.main.resourcePath!)
do
{
let songPath = try FileManager.default.contentsOfDirectory(at: folderUrl, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
for song in songPath {
var mySong = song.absoluteString
if mySong.contains(".mp3") {
print (mySong)
}
}
} catch {
}
}
*/
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = goalName.text else { return true }
let newLength = text.count + string.count - range.length
return newLength <= limitLength
}
}
<file_sep>/Study Time/ViewControllerSounds.swift
//
// ViewControllerSounds.swift
// Study Time
//
// Created by <NAME> on 8/19/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
import AVFoundation
var songs: [String] = []
var audioPlayer = AVAudioPlayer()
var thisSong = 0
var audioStuffed = false
class ViewControllerSounds: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var myTableView: UITableView!
@IBOutlet weak var soundsBackgroundImg: UIImageView!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return songs.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
cell.backgroundColor = UIColor.darkGray.withAlphaComponent(0.75)
cell.textLabel?.text = songs[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
do {
let audioPath = Bundle.main.path(forResource: songs[indexPath.row], ofType: ".wav")
try audioPlayer = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
audioPlayer.play()
audioPlayer.numberOfLoops = -1
thisSong = indexPath.row
audioStuffed = true
musicLabel.text = songs[thisSong]
pauseOutlet.isHidden = false
playOutlet.isHidden = true
switch musicLabel.text {
case "Forest & River":
soundsBackgroundImg.image = #imageLiteral(resourceName: "Forest")
case "Dark Thrill":
soundsBackgroundImg.image = #imageLiteral(resourceName: "darkThrill")
case "Fireplace":
soundsBackgroundImg.image = #imageLiteral(resourceName: "fireplace")
case "Hawaiian Beach":
soundsBackgroundImg.image = #imageLiteral(resourceName: "beach")
case "College Class":
soundsBackgroundImg.image = #imageLiteral(resourceName: "CollegeClass")
case "Jet - White Noise":
soundsBackgroundImg.image = #imageLiteral(resourceName: "jet")
case "Jungle Night":
soundsBackgroundImg.image = #imageLiteral(resourceName: "jungleNight")
case "Mysterious":
soundsBackgroundImg.image = #imageLiteral(resourceName: "Mysterious")
case "Paris Museum":
soundsBackgroundImg.image = #imageLiteral(resourceName: "parisMuseum")
case "Pirate Ship":
soundsBackgroundImg.image = #imageLiteral(resourceName: "pirateShip")
case "Quenacho":
soundsBackgroundImg.image = #imageLiteral(resourceName: "quenacho")
case "Zen":
soundsBackgroundImg.image = #imageLiteral(resourceName: "zen")
default:
print("none")
}
}catch{
print("ERROR")
}
}
override func viewDidLoad() {
super.viewDidLoad()
gettingSongName()
// Do any additional setup after loading the view.
}
// Music Section
@IBOutlet weak var playOutlet: UIButton!
@IBOutlet weak var pauseOutlet: UIButton!
@IBOutlet weak var musicLabel: UILabel!
@IBAction func play(_ sender: Any) {
print(songs)
if audioStuffed == true && audioPlayer.isPlaying == false {
audioPlayer.play()
pauseOutlet.isHidden = false
playOutlet.isHidden = true
} else {
}
}
@IBAction func preview(_ sender: Any) {
if audioStuffed == true && thisSong != 0 {
playThis(thisOne: songs[thisSong-1])
thisSong -= 1
musicLabel.text = songs[thisSong]
} else {
}
}
@IBAction func pause(_ sender: Any) {
if audioStuffed == true && audioPlayer.isPlaying {
audioPlayer.pause()
pauseOutlet.isHidden = true
playOutlet.isHidden = false
} else {
}
}
@IBAction func next(_ sender: Any) {
if audioStuffed == true && thisSong < songs.count-1 {
playThis(thisOne: songs[thisSong+1])
thisSong += 1
musicLabel.text = songs[thisSong]
}
else {
}
}
@IBAction func slider(_ sender: UISlider) {
if audioStuffed == true {
audioPlayer.volume = sender.value
}
}
func playThis(thisOne: String){
do {
let audioPath = Bundle.main.path(forResource: thisOne, ofType: ".wav")
try audioPlayer = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
audioPlayer.play()
}catch{
print("ERROR")
}
}
//
func gettingSongName() {
let folderURL = URL(fileURLWithPath: Bundle.main.resourcePath!)
do {
let songPath = try FileManager.default.contentsOfDirectory(at: folderURL, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
for song in songPath {
var mySong = song.absoluteString
if mySong.contains(".wav")
{
let findString = mySong.components(separatedBy: "/")
mySong = findString[findString.count-1]
mySong = mySong.replacingOccurrences(of: "%20", with: " ")
mySong = mySong.replacingOccurrences(of: ".wav", with: "")
songs.append(mySong)
}
}
myTableView.reloadData()
} catch {
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 16298595b39eb9ce3e2ada9963b043172d81b0a1 | [
"Swift"
] | 2 | Swift | bersanibond/Study-Time | 49d972a1227295a81b84236588014d4c6cf1f97b | a5e182211765b59ecb3debe831ece027bacf9a2f | |
refs/heads/master | <file_sep>require 'spec_helper'
describe 'profile_passenger' do
let :facts do
{
:operatingsystemrelease => '6.5',
:operatingsystemmajrelease => '6',
:osfamily => 'Redhat',
:architecture => 'x86_64',
:concat_basedir => '/dne'
}
end
context 'with defaults for all parameters' do
describe 'on non-Ubuntu 10 releases' do
it {
should contain_class('apache').with('before' => 'Class[Gcc]')
should contain_class('gcc').with('before' => 'Class[Ruby]')
should contain_class('ruby').with('before' => 'Class[Ruby::Dev]')
should contain_class('ruby::dev').with({
'bundler_ensure' => 'installed',
'before' => 'Class[Passenger]'
})
should contain_class('passenger').with({
'passenger_version' => '4.0.50',
'package_ensure' => '4.0.50'
})
}
end
describe 'on Ubuntu 10.04 releases' do
let :facts do
{
:operatingsystemrelease => '10',
:operatingsystemmajrelease => '10.04',
:osfamily => 'Debian',
:architecture => 'x86_64',
:concat_basedir => '/dne'
}
end
it {
should contain_class('ruby::dev').with({
'bundler_ensure' => '0.9.9',
'before' => 'Class[Passenger]'
})
}
end
context 'with passenger version changed' do
let :params do
{
:passenger_version => '3.0.22'
}
end
it {
should contain_class('passenger').with({
'passenger_version' => '3.0.22',
'package_ensure' => '3.0.22'
})
}
end
context 'with bundler version changed' do
let :params do
{
:bundler_ensure => '2.0.5'
}
end
it {
should contain_class('Ruby::dev').with({
'bundler_ensure' => '2.0.5',
'before' => 'Class[Passenger]'
})
}
end
end
end
| 26e39557535bda1227be70e217ab7a1d4de7db1d | [
"Ruby"
] | 1 | Ruby | eshamow/eshamow-profile_passenger | 61622862fdcdce7fbfb3582d90c68c7e1350500f | d3f230cde85bd16105a8f2dc6a5d4a161dda65f3 | |
refs/heads/master | <file_sep>public class Steuerung {
private GUI gui;
private Spieler[] spieler = new Spieler[2];
private WortListe wordlist;
private int aZustand, aktiverSpieler;
Steuerung(GUI gui) {
this.gui = gui;
}
public void gedruecktStart(String name, String name2) {
spieler[0] = new Spieler(name);
System.out.println(name);
spieler[1] = new Spieler(name2);
System.out.println(name2);
if (gui.gibSpielTyp() == 0) {
gui.anzeigenMeldung("Spieltyp auswählen!");
} else {
wordlist = new WortListe(gui.gibSpielTyp());
stelleAufgabe();
}
}
public void gedruecktFertig() {
String Antwort = gui.leseLoesung();
if (!Antwort.isEmpty())
aZustand++;
System.out.println(aZustand);
if (wordlist.alleWoerter[wordlist.GewaehltesWort].pruefeLoesung(Antwort)) {
if (aZustand < 2) {
spieler[aktiverSpieler].addPunkte(5);
gui.anzeigenMeldung("Prima, das ist richtig! (5 Punkte)");
aZustand = 0;
}
if (aZustand == 2) {
spieler[aktiverSpieler].addPunkte(1);
gui.anzeigenMeldung("Gut, das ist jetzt richtig! (1 Punkt)");
aZustand = 0;
}
wordlist.alleWoerter[wordlist.GewaehltesWort].setzeStatus(1);
} else {
if (aZustand < 2) {
gui.anzeigenMeldung("Falsch, aber du hast noch eine Chance!");
}
if (aZustand == 2) {
gui.anzeigenMeldung("Leider auch falasch. → Spielerwechsel");
wechsleSpieler();
}
wordlist.alleWoerter[wordlist.GewaehltesWort].setzeStatus(-1);
}
}
public void gedruecktOK() {
gui.loescheLoeseung();
if (aZustand != 1)
stelleAufgabe();
}
private void stelleAufgabe() {
wordlist.auswaehlenWort();
gui.anzeigenAufgabe(wordlist.gibAufgabe());
gui.anzeigenAmZug(spieler[aktiverSpieler].gibName());
gui.anzeigenPunkte(spieler[0].gibPunkte(), spieler[1].gibPunkte());
}
private void wechsleSpieler() {
if (aktiverSpieler == 1) {
aktiverSpieler = 0;
} else
aktiverSpieler++;
aZustand = 0;
}
}
<file_sep>#Thu Jan 17 08:18:39 CET 2019
org.eclipse.core.runtime=2
org.eclipse.platform=4.10.0.v20181206-0815
<file_sep>public class WortMitLücke extends Wort {
WortMitLücke(String wort) {
super.setaWort(wort);
}
String gibBuchstaben() {
char[] characters = super.gibWort().toCharArray();
int luecke = (int) (Math.random() * characters.length);
characters[luecke] = '_';
String wort = String.valueOf(characters);
return wort;
}
}
<file_sep>public class Spieler {
private String aName;
private int aPunkte;
Spieler(String name) {
aName = name;
}
String gibName() {
return aName;
}
int gibPunkte() {
return aPunkte;
}
void addPunkte(int Punkte) {
aPunkte= aPunkte+Punkte;
}
}
| 1a9b6e21bb9ca17b930ea7f97ef2661a2ddeabcf | [
"Java",
"INI"
] | 4 | Java | superflo22/WoerterBilden | 21df0d70c31c78fdad54938cf8444786f2f5f289 | da1b38a8545c9746fb85fcb723ce0f889325f3f8 | |
refs/heads/master | <repo_name>zzg20082009/mincore<file_sep>/pagemap1.c
/* 这个程序先查看进程的maps文件(/proc/PID/maps),获取进程的逻辑地址空间的映射,然后打开/proc/PID/pagemap文件,
由逻辑地址去获得该逻辑页面是否分配的有物理块,如果有物理块,则打印出物理块的编号。通过查看/proc/PID/smaps文件,本程序正确*/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <error.h>
#include <string.h>
#define PAGEMAP_ENTRY 8
#define GET_BIT(X,Y) (X & ((uint64_t)1<<Y)) >> Y
#define GET_PFN(X) X & 0x7FFFFFFFFFFFFF
void parse(long, long);
int virt_addr_range(char*);
int fd; // file descriptor of pagemap
int main(int argc, char* argv[])
{
if (argc != 3) {
printf("Usage: ./pagemap /proc/PID/maps /proc/PID/pagemap\n");
return 1;
}
if ((fd = open(argv[2], O_RDONLY)) < -1) {
printf("Open the pagemap file error\n");
return 2;
}
virt_addr_range(argv[1]);
return 0;
}
int virt_addr_range(char* mapfile)
{
FILE* fp;
if ((fp = fopen(mapfile, "r")) == NULL) {
perror("Open file: ");
return 1;
}
char* line_in_map = malloc(512);
size_t n;
char* p1; // p1 is used to locate the pointer of '-'
char* p2; // p2 is used to locate the pointer of the first ' '
char begin_virt[17];
char end_virt[17];
bzero(begin_virt, 17);
bzero(end_virt, 17);
while (1) {
if (getline(&line_in_map, &n, fp) == -1) {
printf("End of the read\n");
return 2;
}
p1 = strchr(line_in_map, '-');
strncpy(begin_virt, line_in_map, p1 - line_in_map);
p1++; // p1 point beyond '-'
p2 = strchr(line_in_map, ' ');
strncpy(end_virt, p1, p2 - p1 + 1);
printf("The start address is: %s, The end of address is: %s\n", begin_virt, end_virt);
long start = strtol(begin_virt, NULL, 16);
long end = strtol(end_virt, NULL, 16);
parse(start, end);
printf("--------------------------------------------------------------------------\n");
}
}
void parse(long start, long end)
{
long startpage = start >> 12;
long endpage = end >> 12;
long page_entry;
lseek(fd, startpage * PAGEMAP_ENTRY, SEEK_SET); // 定位文件的读写指针到虚拟地址开始处
for (long pagen = startpage; pagen < endpage; pagen++) {
read(fd, &page_entry, PAGEMAP_ENTRY);
if (page_entry & 0x8000000000000000) {
printf("The virtual address %x is in the memory, and the page frame number is: ", pagen);
printf("%ld\n", GET_PFN(page_entry));
} else {
printf("This virtual address %x is not in the memory :(\n", pagen);
}
}
}
<file_sep>/inmemorya.c
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
char* page_in_m;
int pages;
struct stat statbuf;
void* mappedaddress;
int fd;
if (argc != 2) {
printf("Usage: inmemory filetomap");
return 1;
}
if (stat(argv[1], &statbuf) < 0) {
printf("Error to get the meta data of file\n");
return 2;
}
pages = statbuf.st_size / sysconf(_SC_PAGESIZE) + 1;
page_in_m = (char* ) malloc(pages);
if ((fd = open(argv[1], O_RDWR)) < 0) {
printf("Error to open the file\n");
return 3;
}
mappedaddress = mmap(NULL, statbuf.st_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
if (mappedaddress == MAP_FAILED) {
printf("mmap error \n");
return 4;
}
mappedaddress = (void* ) ((unsigned int) mappedaddress & ~0xFFF);
if (mincore(mappedaddress, statbuf.st_size, page_in_m) < 0) {
printf("error while execute mincore\n");
return 5;
}
for (int i = 0; i < pages; i++) {
if (page_in_m[i] & 0x01)
printf("The %d th page is in memory\n", i);
}
}
<file_sep>/pagemap.c
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define PAGEMAP_ENTRY 8
#define GET_BIT(X,Y) (X & ((uint64_t)1<<Y)) >> Y
#define GET_PFN(X) X & 0x7FFFFFFFFFFFFF
void parse(long, long);
int fd; // file descriptor of pagemap
int main(int argc, char* argv[])
{
if (argc != 4) {
printf("Usage: ./pagemap pagemap start-virt-addr end-virt-addr\n");
return 1;
}
if ((fd = open(argv[1], O_RDONLY)) < -1) {
printf("Open the pagemap file error\n");
return 2;
}
long start = strtol(argv[2], NULL, 16);
long end = strtol(argv[3], NULL, 16);
// printf("The address is %ld--%ld\n", start, end);
parse(start, end);
return 0;
}
void parse(long start, long end)
{
long startpage = start >> 12;
long endpage = end >> 12;
long page_entry;
lseek(fd, startpage * PAGEMAP_ENTRY, SEEK_SET); // 定位文件的读写指针到虚拟地址开始处
for (long pagen = startpage; pagen <= endpage; pagen++) {
read(fd, &page_entry, PAGEMAP_ENTRY);
if (page_entry & 0x8000000000000000) {
printf("The virtual address is in the memory, and the page frame number is: ");
printf("%ld\n", GET_PFN(page_entry));
}
}
}
<file_sep>/pagemap2.c
/* 这个程序先查看进程的maps文件(/proc/PID/maps),获取进程的逻辑地址空间的映射,然后打开/proc/PID/pagemap文件,
由逻辑地址去获得该逻辑页面是否分配的有物理块,如果有物理块,则打印出物理块的编号。通过查看/proc/PID/smaps文件,本程序正确*/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <error.h>
#include <string.h>
#define PAGEMAP_ENTRY 8
#define GET_BIT(X,Y) (X & ((uint64_t)1<<Y)) >> Y
#define GET_PFN(X) X & 0x7FFFFFFFFFFFFF
void parse(long, long);
int virt_addr_range(char*);
long phn_count(long phn_num);
int fd; // file descriptor of pagemap
int kpagefd; // file descriptor of kpagecount
int main(int argc, char* argv[])
{
if (argc != 3) {
printf("Usage: ./pagemap /proc/PID/maps /proc/PID/pagemap\n");
return 1;
}
if ((fd = open(argv[2], O_RDONLY)) < -1) {
printf("Open the pagemap file error\n");
return 2;
}
if ((kpagefd = open("/proc/kpagecount", O_RDONLY)) < -1) {
printf("Open the /proc/kpagecount file error\n");
return 3;
}
virt_addr_range(argv[1]);
return 0;
}
int virt_addr_range(char* mapfile)
{
FILE* fp;
if ((fp = fopen(mapfile, "r")) == NULL) {
perror("Open file: ");
return 1;
}
char* line_in_map = malloc(512);
size_t n;
char* p1; // p1 is used to locate the pointer of '-'
char* p2; // p2 is used to locate the pointer of the first ' '
char begin_virt[17];
char end_virt[17];
bzero(begin_virt, 17);
bzero(end_virt, 17);
while (1) {
if (getline(&line_in_map, &n, fp) == -1) {
printf("End of the read\n");
return 2;
}
p1 = strchr(line_in_map, '-');
strncpy(begin_virt, line_in_map, p1 - line_in_map);
p1++; // p1 point beyond '-'
p2 = strchr(line_in_map, ' ');
strncpy(end_virt, p1, p2 - p1 + 1);
printf("The start address is: %s, The end of address is: %s\n", begin_virt, end_virt);
long start = strtol(begin_virt, NULL, 16);
long end = strtol(end_virt, NULL, 16);
parse(start, end);
printf("--------------------------------------------------------------------------\n");
}
}
void parse(long start, long end)
{
long startpage = start >> 12;
long endpage = end >> 12;
long page_entry;
long uss = 0;
long pss = 0;
lseek(fd, startpage * PAGEMAP_ENTRY, SEEK_SET); // 定位文件的读写指针到虚拟地址开始处
for (long pagen = startpage; pagen < endpage; pagen++) {
read(fd, &page_entry, PAGEMAP_ENTRY);
if (page_entry & 0x8000000000000000) {
printf("The virtual address %x is in the memory, and the page frame number is: ", pagen);
long phn_num = GET_PFN(page_entry);
printf("%ld\n", phn_num);
long ref_cnts = 0;
if ((ref_cnts = phn_count(phn_num)) == -1) {
printf("Get information error\n");
continue;
}
if (ref_cnts == 1)
uss++;
else
pss+= ref_cnts;
printf("The phn_num: %ld is referenced %ld times\n", phn_num, ref_cnts);
} else {
printf("This virtual address %x is not in the memory :(\n", pagen);
}
}
printf("In this virtual address range, the uss is %ld K, and the pss is **K\n", uss * 4);
}
long phn_count(long ph_num) // 根据物理号的编号,计算出该物理块被映射了几次,由此可以计算出USS, PSS
{
long offset = ph_num * 8;
long page_count = 0;
if (lseek(kpagefd, offset, SEEK_SET) < 0) {
printf("ph_num %d maybe is not a valid number\n", ph_num);
return -1;
}
if (read(kpagefd, &page_count, 8) < 0) {
return -1;
}
return page_count;
}
// 这个程序的结构非常的烂,最多只能用作教学用
<file_sep>/inmemory.c
#include <unistd.h>
#include <sys/mman.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char page_in_m = 0;
void* addr = malloc(40);
addr = (void *) ((int) addr & (~0xFFF));
printf("The address of addr is %p\n", addr);
if (mincore(addr, 4096, &page_in_m) < 0) {
printf("error to get the memory usage information\n");
return 1;
}
if (page_in_m & 0x01)
printf("Yes! in memory\n");
else
printf("No!, not in memory\n");
}
| 70b13130e14a53e1a57a594c1849f9aa13613be3 | [
"C"
] | 5 | C | zzg20082009/mincore | 0a52ffc55366eb674ef2fa0944fa98795458497b | f48e3d4c5282e6b48a739cf7b49c0cdc98efcbec | |
refs/heads/main | <file_sep>let height = screen.height;
stream = null,
audio = null,
mixedStream = null,
chunks = [],
recorder = null
startButton = null,
stopButton = null,
downloadButton = null,
recordedVideo = null;
click = 0;
n = 1;
blobUrl = null;
console.log(height);
if (height < 640) {
let videoH = document.querySelector(".video");
videoH.style.height = height;
}
// set up stream
async function setupStream() {
try {
stream = await navigator.mediaDevices.getDisplayMedia({
video: true
});
audio = await navigator.mediaDevices.getUserMedia({
audio: {
echoCancellation: true,
noiseSuppression: true,
sampleRate: 44100,
// In this example the cursor will always be visible in the capture,
// and the audio track should ideally have noise suppression and echo
// cancellation features enabled,
// as well as an ideal audio sample rate of 44.1kHz.
},
});
setupVideoFeedback();
} catch (err) {
console.error(err)
}
}
function setupVideoFeedback() {
if (stream) {
recordingVideo.srcObject = stream;
recordingVideo.play();
} else {
console.warn('No stream available');
}
}
async function startRecording() {
await setupStream();
if (stream && audio) {
mixedStream = new MediaStream([...stream.getTracks(), ...audio.getTracks()]);
recorder = new MediaRecorder(mixedStream);
recorder.ondataavailable = handleDataAvailable;
recorder.onstop = handleStop;
recorder.start(100);
startButton.disabled = true;
stopButton.disabled = false;
console.log('Recording started');
} else {
console.warn('No stream available.');
}
}
function pauseRecording() {
click += 1;
console.log(click);
if (click % 2 == 0) {
click = 0;
console.log("Resume");
pauseButton.innerHTML = "Pause recording";
recorder.resume();
}
else {
console.log('Pause');
pauseButton.innerHTML = "Resume";
recorder.pause();
}
}
function stopRecording() {
recorder.stop();
shareButton.classList.remove("hidden");
startButton.disabled = false;
stopButton.disabled = true;
}
function handleDataAvailable(e) {
chunks.push(e.data);
}
function handleStop(e) {
const blob = new Blob(chunks, {
'type': 'video/mp4'
});
chunks = [];
downloadButton.href = URL.createObjectURL(blob);
downloadButton.download = '';
downloadButton.disabled = false;
blobUrl = URL.createObjectURL(blob);
recordingVideo.classList.add("hidden");
recordedVideo.classList.remove("hidden");
recordedVideo.src = blobUrl;
recordedVideo.href = blobUrl;
recordedVideo.load();
recordedVideo.onloadeddata = function () {
const rc = document.querySelector(".download-btn");
rc.classList.remove("hidden");
rc.scrollIntoView({
behavior: "smooth",
block: "start"
});
recordedVideo.play();
}
stream.getTracks().forEach((track) => track.stop());
audio.getTracks().forEach((track) => track.stop());
console.log('Stop');
}
window.addEventListener('load', () => {
startButton = document.querySelector('.record-btn');
pauseButton = document.querySelector('.pause-btn');
stopButton = document.querySelector('.stop-btn');
shareButton = document.querySelector('.share');
downloadButton = document.querySelector('.download-video');
recordingVideo = document.querySelector('.recording-video');
recordedVideo = document.querySelector('.recorded-video');
startButton.addEventListener('click', startRecording);
pauseButton.addEventListener('click', pauseRecording);
stopButton.addEventListener('click', stopRecording);
})
| cacbd955fc2dea5f27dbe7d263edfe72920b7015 | [
"JavaScript"
] | 1 | JavaScript | miktae/recordscreen | 402fcef3fdbc96218899f7c53a7d1ba07b098e5b | 5a718963d374b962e924dca4c2a1c240b27de2f9 | |
refs/heads/master | <file_sep>import pytest
@pytest.mark.usefixtures("setUpBeforeAll")
class TestSampleOne:
# @pytest.fixture(scope="class")
# def setUpBeforeAll(self):
# print("I will be in same file and execute before all test cases")
# yield
# print("I will be in same file and execute after all test cases")
@pytest.fixture()
def setUp(self):
print("Intializing x = 10 and y = 20")
yield
print("Operation successfully!!")
def test_add(self, setUp):
print("Test add functionslity")
def test_sub(self, setUp):
print("Test sub functionslity")
def test_mul(self, setUp):
print("Test mul functionslity")
def test_div(self, setUp):
print("Test div functionslity")
<file_sep># Dictionary
phonebook = {}
print(phonebook)
phonebook = {
'Andy': '9957558',
'John': '64746484',
'Jenny': '22282'
}
print(phonebook['Andy'])
print(phonebook['John'])
print(phonebook['Jenny'])
print(dir(phonebook))
for phone in phonebook.values():
print(phone)
for phone in phonebook.keys():
print(phone)
for key, value in phonebook.items():
print(key , value)
print(phonebook)
phonebook['Mike'] = '9957558'
print(phonebook)
phonebook['Mike'] = '78474449'
print(phonebook)
print(phonebook.get('Andy'))
phonebook.update(Andy='353536735', Terry = '64547437')
print(phonebook)
update_dict = {
'Juan': 4353536,
'Kerry': 884747
}
phonebook.update(update_dict)
print(phonebook)
del phonebook['Juan']
print(phonebook)
<file_sep>import time
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.select import Select
def verify_drag_and_drop():
# ARRANGE
driver = webdriver.Chrome("/Users/gaurnitai/Desktop/PySeBootcamp/drivers/chromedriver")
driver.get("https://jqueryui.com/draggable/")
driver.maximize_window()
time.sleep(4)
driver.switch_to.frame(0)
draggable = driver.find_element_by_id("draggable")
print(draggable)
actions = ActionChains(driver)
actions.click_and_hold(draggable).drag_and_drop_by_offset(draggable, 100, 100).perform()
time.sleep(5)
driver.close()
driver.quit()
verify_drag_and_drop()
<file_sep>#### ASSIGNMENT II ###
>NOTE: Please make sure to write the code and share on my private slack chat
###### _Problem Statements_
- Define a function that helps to calculate the area of circle with different radius
`23.45, 56.78, 45.67, 78.9`
_Please consider the unit of these values as `cm`_
- Define a function using Python that helps to find the first and last character of any string
- Design a function that accept 4 values & find the average of those values.
>_`Make sure to define seperate function to get the sum of all numbers`_
- Define a function that helps to find the square of any number and then add the same number to the squared number and return the final output.
<__HAPPY__> CODING__ GUYS....<file_sep>x = 10
y = 20
print(x + y) #30
name = 'John'
age = 26
print('Hi ' + name + ' your age is ' + str(age))<file_sep>import pytest
@pytest.fixture(scope="module")
def setUpBeforeAllTC():
print("I will be executing before all test cases")
yield
print("I will be executing after all test cases")
@pytest.fixture(scope="class")
def setUpBeforeAll():
print("I will be in same file and execute before all test cases")
yield
print("I will be in same file and execute after all test cases")
<file_sep># Lets go and define string --- text data
name = '<KEY>'
name = "<KEY>"
session = "It's our second week session"
session = 'It"s our second week session'
print(type(name)) # str
grade = 'A'
print(type(grade))
# String - is a set of characters which are align in a sequential manner
#indexing in programming language - always 0 --- 0 1 2 3
#
print(name[0])
print(name[-1])
multiline_string = '''This is my multiple
line of
string'''
multiline_string = """This is my multiple
line of
string"""
print(multiline_string)
<file_sep>import time
from selenium import webdriver
from selenium.webdriver.support.select import Select
def verify_static_dropdown():
# ARRANGE
driver = webdriver.Chrome("/Users/gaurnitai/Desktop/PySeBootcamp/drivers/chromedriver")
driver.get("https://www.facebook.com/")
driver.maximize_window()
time.sleep(4)
day_loc = driver.find_element_by_id("day")
select_day = Select(day_loc)
select_day.select_by_value("4") # 4a
time.sleep(3)
month_loc = driver.find_element_by_xpath("//select[@title='Month']")
select_day = Select(month_loc)
select_day.select_by_visible_text("Mar") # Mar
time.sleep(3)
year_loc = driver.find_element_by_name("birthday_year")
select_day = Select(year_loc)
select_day.select_by_index(3) # 2018
time.sleep(3)
# This is for deselect functions
select_day = Select(day_loc)
select_day.deselect_by_value("4") # 4
time.sleep(3)
month_loc = driver.find_element_by_xpath("//select[@title='Month']")
select_day = Select(month_loc)
select_day.deselect_by_visible_text("Mar") # Mar
time.sleep(3)
year_loc = driver.find_element_by_name("birthday_year")
select_day = Select(year_loc)
select_day.deselect_by_index(3) # 2018
driver.close()
driver.quit()
verify_static_dropdown()
<file_sep># Define a function that helps to calculate the area of circle with different radius
# `23.45, 56.78, 45.67, 78.9`
def calculate_area_of_circle(radius):
PI = 3.14
result = PI * radius * radius
return result
output = calculate_area_of_circle(23.45)
print(output)
output = calculate_area_of_circle(56.78)
print(output)
output = calculate_area_of_circle(45.67)
print(output)
output = calculate_area_of_circle(78.9)
print(output)
def find_last_and_first_char(text):
first_char = text[0]
last_char = text[-1]
print(first_char + ' - ' + last_char)
return first_char,last_char
find_last_and_first_char("This is python class")
find_last_and_first_char("Its awesome to be here")
#Define a function that helps to find the square of any number and then add the same number to the squared number and return the final output.
def calculate_square_and_add(number):
square = number * number
result = square + number
return result
output = calculate_square_and_add(6)
print(output)
output = calculate_square_and_add(10)
print(output)
<file_sep>## To define string
random_string = 'This is a session on python'
another_string = "Its awesome to be here with you all"
new_string_one = "It's awesome to be here with you all"
new_string = 'It\'s awesome to be here with you all'
new_string_two = "It\"s awesome to be here with you all"
# print(new_string)
# print(new_string_two)
new_string_two = "HELLO Guys !!"
# To find the length of string
len(new_string_two)
print(len(new_string_two))
# # To access O
print(new_string_two[4])
# Slicing of string
print(new_string_two[0:4]) # including 0 excluding 4
print(new_string_two[2:13])
print(new_string_two[2:len(new_string_two)])
print(new_string_two[2:])
print(new_string_two[:5])
print(new_string_two[-4:-1])
# print(new_string_two[-1:-4])
# Changes the cases -
new_string_two = "HELLO Guys !!"
new_string_title = "hELLO guys !!"
print(new_string_two.lower())
print(new_string_two.upper())
print(new_string_title.title()) ## it will convert the first letter of every word within any string in upper case
print(new_string_title.capitalize()) # it will convert the first letter of any string in upper case
#
hi_string = new_string_title.replace('Hi', 'Hello')
print(hi_string)
#
L_count = new_string_title.count('L')
print(L_count)
l_count = new_string_title.count('l')
print(l_count)
#
name_list = "Mr. <NAME>"
split_string = name_list.split()
print(split_string)
split_string = name_list.split('.')
print(split_string)
#
space_string = '<NAME>'
print(len(space_string)) # 8
space_string_two = ' <NAME> '
print(len(space_string_two)) # 10
space_string_strip = space_string_two.strip()
print(len(space_string_strip))
#
#print(dir(space_string_strip))
#
print(space_string.find('Doe')) # 0 - 14
print(space_string.find('z'))
#
print(space_string.index('J'))
print(space_string.index('Doe'))
print(space_string[:-1])
print(space_string)
<file_sep>import py_compile
py_compile.compile("./first_script_compile.py")<file_sep>import time
import pytest
from selenium import webdriver
class TestAmazonProduct:
@pytest.fixture
def setUp(self):
self.driver = webdriver.Chrome("/Users/gaurnitai/Desktop/PySeBootcamp/drivers/chromedriver")
self.driver.get("https://www.amazon.in")
self.driver.maximize_window()
time.sleep(4)
yield
time.sleep(3)
self.driver.close()
self.driver.quit()
def test_product_title(self, setUp):
self.driver.save_screenshot("/Users/gaurnitai/Desktop/dummyrepo/py-se-bootcamp/screenshots" + "homepage.png")
search_box = self.driver.find_element_by_id("twotabsearchtextbox")
search_box.send_keys("Macbook pro")
search_icon = self.driver.find_element_by_xpath("//input[@type='submit']")
search_icon.click()
time.sleep(5)
self.driver.save_screenshot(
"/Users/gaurnitai/Desktop/dummyrepo/py-se-bootcamp/screenshots" + "productlisting.png")
parent_window = self.driver.current_window_handle
print(parent_window)
self.driver.find_element_by_xpath("(//a[@class='a-link-normal a-text-normal'])[1]").click()
time.sleep(3)
windows_set = self.driver.window_handles
print(windows_set)
for window in windows_set:
if (window != parent_window):
self.driver.switch_to.window(window)
self.driver.save_screenshot(
"/Users/gaurnitai/Desktop/dummyrepo/py-se-bootcamp/screenshots/" + "childtab.png")
productTitle = self.driver.find_element_by_id("productTitle")
print(productTitle.text)
assert productTitle.text == "Macbook pro"
def test_product_price(self, setUp):
self.driver.save_screenshot("/Users/gaurnitai/Desktop/dummyrepo/py-se-bootcamp/screenshots" + "homepage.png")
search_box = self.driver.find_element_by_id("twotabsearchtextbox")
search_box.send_keys("Macbook pro")
search_icon = self.driver.find_element_by_xpath("//input[@type='submit']")
search_icon.click()
time.sleep(5)
self.driver.save_screenshot(
"/Users/gaurnitai/Desktop/dummyrepo/py-se-bootcamp/screenshots" + "productlisting.png")
parent_window = self.driver.current_window_handle
print(parent_window)
self.driver.find_element_by_xpath("(//a[@class='a-link-normal a-text-normal'])[1]").click()
time.sleep(3)
windows_set = self.driver.window_handles
print(windows_set)
for window in windows_set:
if (window != parent_window):
self.driver.switch_to.window(window)
self.driver.save_screenshot(
"/Users/gaurnitai/Desktop/dummyrepo/py-se-bootcamp/screenshots/" + "childtab.png")
productPrice = self.driver.find_element_by_id("priceblock_ourprice")
assert productPrice.text == "₹ 1,27,990.00"
<file_sep>from pysebootcamp.py_se_day07 import student_module
from pysebootcamp.py_se_day07.student_module import Student
# john = student_module.Student("John", 26, "B.E", 13244, "<EMAIL>", 1, "Python")
# mike = student_module.Student("Mike", 27, "B.E", 34353, 2, "Java")
# jenny = student_module.Student("Jenny", 23, "B.E", 758597, 3, "JavaScript", email="<EMAIL>")
# ramu = student_module.Student("Ramu", 26, "Ph.D", 343536, "<EMAIL>", 4, "Python")
john = Student("John", 26, "B.E", 13244, "<EMAIL>", 1, "Python")
mike = Student("Mike", 27, "B.E", 34353, 2, "Java")
jenny = Student("Jenny", 23, "B.E", 758597, 3, "JavaScript", email="<EMAIL>")
ramu = Student("Ramu", 26, "Ph.D", 343536, "<EMAIL>", 4, "Python")
print(john.name)
print(mike.name)
print(mike.name)<file_sep># # John
# print('Take the ingredients')
# print('Mix the ingredients')
# print('Pour on pan')
# print('bake one side properly')
# print('flip dosa')
# print('Bake other side')
# print('Serve dosa to John')
# print("================")
# # Mary
# print('Take the ingredients')
# print('Mix the ingredients')
# print('Pour on pan')
# print('bake one side properly')
# print('flip dosa')
# print('Bake other side')
# print('Serve dosa to Mary')
# print("================")
# # Tom
# print('Take the ingredients')
# print('Mix the ingredients')
# print('Pour on pan')
# print('bake one side properly')
# print('flip dosa')
# print('Bake other side')
# print('Serve dosa to Tom')
# print("================")
# DRY - Do not Repeat Yourself
def make_dosas(name): # parameter variable
print('Take the flour')
dosa_process() # chef
print('Serve dosa to ' + name)
def make_masala_dosas(name): # parameter variable
print('Take the masala')
dosa_process()
print('Serve dosa to ' + name)
def make_onion_dosas(name): # parameter variable
print('Take the onion')
dosa_process()
print('Serve dosa to ' + name)
def dosa_process(): # chef
print('Mix the ingredients')
print('Pour on pan')
print('bake one side properly')
print('flip dosa')
print('Bake other side')
make_dosas('John')
print("================")
make_dosas('Mary')
print("================")
make_dosas('Tom')
<file_sep>
dummy_string = 'This is my dummy string and seems it is gonna useful'
# when I get- i/e/n I want to print
for i in range(0, len(dummy_string)):
if dummy_string[i] == 'i' or dummy_string[i] == 'e' or dummy_string[i] == 'n':
print(dummy_string[i])
def print_i_e_n(text):
dummy_string = text
for i in range(0, len(dummy_string)):
if dummy_string[i] == 'i' or dummy_string[i] == 'e' or dummy_string[i] == 'n':
print(dummy_string[i])
print_i_e_n("Thsis is my test string")<file_sep>from selenium import webdriver
import time
def verify_search_functionality(search_text):
# ARRANGE
driver = webdriver.Chrome("/Users/gaurnitai/Desktop/PySeBootcamp/drivers/chromedriver")
driver.get("https://www.flipkart.com")
driver.maximize_window()
time.sleep(4)
## ACTION
driver.find_element_by_xpath("//button[@class='_2AkmmA _29YdH8']").click();
search_box = driver.find_element_by_name("q") # Find the location of search box
# search_box.send_keys("Macbook pro") # to enter text we have to use send_keys()
search_box.send_keys(search_text)
# Finding xpath using contains(attribute, textwithinattributevalue)
search_icon = driver.find_element_by_xpath("//button[@type='submit']")
search_icon.click()
time.sleep(5)
product_list = driver.find_element_by_xpath("//div[@class='_1HmYoV _35HD7C'][2]//div[@class='_3wU53n']")
print(product_list.text)
products_list = driver.find_elements_by_xpath("//div[@class='_1HmYoV _35HD7C'][2]//div[@class='_3wU53n']")
print(len(products_list))
for product in products_list:
print(product.text)
expected_product_lists = [
'Apple MacBook Pro Core i5 8th Gen - (8 GB/256 GB SSD/Mac OS Mojave) MV962HN', 'Apple MacBook Pro Core i5 8th Gen - (8 GB/512 GB SSD/Mac OS Mojave) MV972HN',
'Apple MacBook Pro Core i5 8th Gen - (8 GB/128 GB SSD/Mac OS Mojave) MUHN2HN/A'
]
for i in range(0, len(expected_product_lists)):
if(products_list[i].text == expected_product_lists[i]):
print("The prouct name is valid")
else:
print("The product name is invalid")
verify_search_functionality("Macbook pro")<file_sep>
<div style="text-align:center;">
<img src="./pythonclipart.png" style="width:50%; text-align: center">
<!-- <span style="font-family:Papyrus; font-size:2em; text-align: center;">Assignment III</span> -->
# ASSIGNMENT III
>NOTE: Please make sure to write the code and share on my private slack chat
#### _Problem Statements_
:pushpin:Define a function that helps to calculate the area of circle with different radius and print the area only when the area is divisible by 4
`23.48, 56.78, 45.67, 78.28`
_Please consider the unit of these values as `cm`_
:pushpin:Define a function using Python that helps to find the first five character of string in all the possible ways
:pushpin:Define a function using Python that helps to find the last 3 character of string in all the possible ways
:pushpin:Design a function that accept 6 values & find the average of those values which are only divisible by 6.
>_`Do not create seperate function for addition`_
:pushpin:Define a function that helps to find the square of any number and then add the same number to the squared number only when the number is odd and return the final output.
:pushpin:Define a function that helps to print all the numbers between 5 and 50 with interval of 5 for ex. 5, 10, 15 and so on...
>_`Solve using both types of loop. Make sure to design different function for each loop`_
<span style="font-family:Papyrus; font-size:2em;">Happy Coding!</span>
</div><file_sep># conditional statement is used to make your program smat to take decision based on certain condition
# Arithemitic
# 1 + 2 = 3
#relation operators always return true or false
# >
# >=
# <
# <=
# ==
def find_even_odd(number):
is_even = number % 2 == 0 # true / false
print(is_even)
if is_even == True:
print('The number is ' + str(number) + ' is even')
else:
print('The number is ' + str(number) + ' is odd')
find_even_odd(40) #
find_even_odd(39)
find_even_odd(40) #
find_even_odd(39)
find_even_odd(40) #
find_even_odd(39)
# def find_odd(number):
# is_odd = number % 2 != 0
# print('The number is ' + str(number) + ' is odd')
# find_odd(23)
# find_odd(40)
# One way conditional
# condition -- valid / true then only the program / function is gonna take decision / gonna execute
# if condition:
# Two way conditional
#condition -- valid/invalid / true/false then only the program / function is gonna take decision / gonna execute
# Multiway conditional way
<file_sep>import time
from selenium import webdriver
import pytest
class AmazonWebsiteTest:
@pytest.fixture
def setUp(self):
self.driver = webdriver.Chrome("/Users/gaurnitai/Desktop/PySeBootcamp/drivers/chromedriver")
self.driver.get("https://www.amazon.in")
self.driver.maximize_window()
time.sleep(4)
yield
time.sleep(3)
self.driver.close()
self.driver.quit()
def test_website_title(self, setUp):
# driver = webdriver.Chrome("/Users/gaurnitai/Desktop/PySeBootcamp/drivers/chromedriver")
# driver.get("https://www.amazon.in")
# driver.maximize_window()
# time.sleep(4)
self.driver.save_screenshot("/Users/gaurnitai/Desktop/dummyrepo/py-se-bootcamp/screenshots" + "homepage.png")
pageTitle = self.driver.title
assert pageTitle == "Online Shopping site in India: Shop Online for Mobiles, Books, Watches, Shoes and More - Amazon.in"
def test_search_functionality(self, setUp):
# driver = webdriver.Chrome("/Users/gaurnitai/Desktop/PySeBootcamp/drivers/chromedriver")
# driver.get("https://www.amazon.in")
# driver.maximize_window()
# time.sleep(4)
self.driver.save_screenshot("/Users/gaurnitai/Desktop/dummyrepo/py-se-bootcamp/screenshots" + "homepage.png")
search_box = self.driver.find_element_by_id("twotabsearchtextbox")
search_box.send_keys("Macbook pro")
search_icon = self.driver.find_element_by_xpath("//input[@type='submit']")
search_icon.click()
time.sleep(5)
self.driver.save_screenshot(
"/Users/gaurnitai/Desktop/dummyrepo/py-se-bootcamp/screenshots" + "productlisting.png")
searched_product = self.driver.find_element_by_xpath("(//a[@class='a-link-normal a-text-normal'])[1]")
assert searched_product.is_displayed() == True
<file_sep>#
def add_numbers():
no_one = 20
no_two = 30
result = no_one + no_two
print(result)
# add_numbers()
def add_numbers_version_01(x, y):
no_one = x
no_two = y
result = no_one + no_two
#print("The value of result variable is " + str(result) ) ### ?
return result
# print(result)
# x = add_numbers_version_01(20,30)
# print(x) # ?
# not returning anything to you
# add_numbers_version_01(50, 10)
# add_numbers_version_01(300, 29)
# add_numbers_version_01(20.78, 56.89)
# # Average of two numbers
# Add 2 nos and then divide the sum with nos. of value
# no_one = 50
# no_two = 60
# nos_sum = no_one + no_two
# nos_sum = add_numbers_version_01(50, 50) ### This particular line of code will throw error
# avg = nos_sum/2 # 50.0
# print(avg) ##
# nos_sum = add_numbers_version_01(40, 50) ### This particular line of code will throw error
# avg = nos_sum/2 # 50.0
# print(avg) ##
# nos_sum = add_numbers_version_01(140, 150) ### This particular line of code will throw error
# avg = nos_sum/2 # 50.0
# print(avg) ##
def calculate_avg_of_two_numbers():
nos_sum = add_numbers_version_01(50, 50)
avg = nos_sum/2 # 50.0
return avg
output = calculate_avg_of_two_numbers()
print(output)
def calculate_avg_of_two_numbers_version_02(x, y):
nos_sum = add_numbers_version_01(50, 50)
avg = nos_sum/2 # 50.0
return avg
def calculate_avg_of_two_numbers_version_01(x, y):
nos_sum = add_numbers_version_01(x, y)
avg = nos_sum/2 # 50.0
return avg
output = calculate_avg_of_two_numbers_version_01(30, 30)
print(output)
output = calculate_avg_of_two_numbers_version_01(40, 50)
print(output)
output = calculate_avg_of_two_numbers_version_01(140, 150)
print(output)
output = calculate_avg_of_two_numbers_version_01(230, 30)
print(output)
<file_sep># Define a function that helps to calculate the area of circle with different radius and print the area only when the area is divisible by 4
# 23.48, 56.78, 45.67, 78.28 Please consider the unit of these values as cm
def calculate_area(radius):
PI = 3.14
area = PI * radius * radius
if area % 6 != 0:
print('The area of circle with radius {0} is {1}'.format(radius, area))
def calculate_square(num):
squared = num * num
if num % 2 != 0:
new_num = squared + num
print(new_num)
print(squared)
# Define a function using Python that helps to find the first five character of string in all the possible ways
string = HAPPY CODING
string[9:len(string)]
string[9:]
string[-3:]
# Define a function using Python that helps to find the last 3 character of string in all the possible ways
for i in range(5, 51):
print(1)
i = 5
while i <= 50:
print(i)
i = i + 5
#Design a function that accept 6 values & find the average of those values which are only divisible by 6.
def calculate_average(n1, n2, n3, n4):
sum = 0
count = 0
if n1 % 6 == 0:
sum = sum + n1 # n1=6
count = count + 1
if n2 % 6 == 0:
sum = sum + n2 # n1 = 12
count = count + 1
if n3 % 6 == 0:
sum = sum + n3 # n3 = 4
count = count + 1
if n4 % 6 == 0:
sum = sum + n4 # n4= 18
count = count + 1
avg = sum / count
print(avg)
<file_sep>import pytest
def test_add():
x = 45;
y = 50;
r = x + y
assert r == 96
def test_product():
x = 50;
y = 50;
r = x * y
assert r == 2500
def subtract():
x = 45;
y = 50;
r = x - y
assert r == -5
# o = add()
# if (o == 95):
# print("Its pass")
# else:
# print("its fail")
#
# o = product()
# if (o == 1500):
# print("Its pass")
# else:
# print("its fail")
#
# o = subtract()
# if (o == 5):
# print("Its pass")
# else:
# print("its fail")
<file_sep>firstname = 'John'
lastname = 'Doe'
age = 26
print('Hey ' + firstname + ', your last name is' + lastname)
<file_sep>import pytest
def test_add():
x = 45
y = 50
r = x + y
print(r)
assert r == 95
def testProduct():
x = 50
y = 50
r = x * y
print(r)
assert r == 2500
def testSubtract():
x = 45
y = 50
r = x - y
print(r)
assert r == 5
<file_sep>import time
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.select import Select
def verify_dynamic_dropdown():
# ARRANGE
driver = webdriver.Chrome("/Users/gaurnitai/Desktop/PySeBootcamp/drivers/chromedriver")
driver.get("https://www.flipkart.com/")
driver.maximize_window()
time.sleep(4)
driver.find_element_by_xpath("//button[@class='_2AkmmA _29YdH8']").click()
actions = ActionChains(driver)
electronics = driver.find_element_by_xpath("//span[text()='Electronics']")
actions.move_to_element(electronics).perform()
samsung = driver.find_element_by_xpath("(//a[@title='Samsung'])[1]")
#actions.move_to_element(samsung).click().perform() # action chaining
# actions.move_to_element(samsung).perform()
# actions.click().perform() # action chaining
actions.move_to_element(samsung).click().perform();
time.sleep(7)
verify_dynamic_dropdown()<file_sep># Integer (int)
# Decimal (float)
# Text (str)
# Boolean (bool)
# Complex (2 + 3i)
# define Integer
age = 26
print(type(age))
age = 35.89
print(type(age))
# define decimal
rate = 23.50
res = type(rate)
print(res)
# Text
name = "<NAME>"
name = '<NAME>'
print(type(name))
# Boolean
isCorrect = True
isFalse = False
print(type(isFalse))<file_sep># Define a function which calculate the age of any individual from current date
# born_year = 1990
# current_year = 2020
# age = current_year - born_year
# print(age)
# born_year = 1992
# current_year = 2020
# age = current_year - born_year
# print(age)
# born_year = 1998
# current_year = 2020
# age = current_year - born_year
# print(age)
# born_year = 2000
# current_year = 2020
# age = current_year - born_year
# print(age)
def calculate_age(b_year):
born_year = b_year
current_year = 2020
age = current_year - born_year
print(age)
def calculate_age(b_year):
born_year = b_year
current_year = 2020
age = current_year - born_year
print(age)
calculate_age(1992) # 28
calculate_age(1990) # 30
calculate_age(1998) # 22
calculate_age(2000) # 20
# DRY -- Do not repeat
# Define a function which gonna convert Temperature from celcius to fahrenheit and vice versa
def convert_cel_to_far(celcius_temp):
far_temp = (celcius_temp * 9/5) + 32
print("The fahrenheit conversion of " + str(celcius_temp) + " is " + str(far_temp))
def convert_far_to_cel(far_temp):
celcius_temp = (far_temp - 32) * 5/9
print("The celcius conversion of " + str(far_temp) + " is " + str(celcius_temp))
convert_cel_to_far(100)
convert_cel_to_far(150)
convert_far_to_cel(250)
convert_far_to_cel(200)
# Define a function where you have to find whether the given number is odd or even
def find_even(number):
is_even = number % 2 == 0
print(is_even)
print('The number is ' + str(number) + ' is even')
find_even(40)
find_even(39)
def find_odd(number):
is_odd = number % 2 != 0
print('The number is ' + str(number) + ' is odd')
find_odd(23)
find_odd(40)
<file_sep>class ArithmeticClass:
def __init__(self, number_one, number_two):
self.number_one = number_one
self.number_two = number_two
def add(self):
result = self.number_one + self.number_two
return result
def mul(self):
result = self.number_one * self.number_two
return result
def sub(self):
result = self.number_one - self.number_two
return result
def div(self):
result = self.number_one / self.number_two
return result
<file_sep>import time
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.keys import Keys
def verify_drag_and_drop():
# ARRANGE
driver = webdriver.Chrome("/Users/gaurnitai/Desktop/PySeBootcamp/drivers/chromedriver")
driver.get("https://www.google.com")
driver.maximize_window()
time.sleep(4)
search_box = driver.find_element_by_name("q")
#search_box.send_keys("Python")
search_box.send_keys(Keys.ENTER)
time.sleep(3)
actions = ActionChains(driver)
#actions.move_to_element(search_box).send_keys(Keys.SHIFT).send_keys("python").send_keys("\ue007").perform()
actions.key_down("\ue008", search_box).send_keys("python").key_up("\ue008", search_box).send_keys("\ue007").perform()
#actions.send_keys(Keys.ENTER).perform()
#driver.find_element_by_name("btnK").click()
time.sleep(3)
verify_drag_and_drop()
<file_sep>#Parameter Return
#0 0
def add_numbers1():
no_one = 20
no_two = 30
result = no_one + no_two
#0 1
def add_numbers2():
no_one = 20
no_two = 30
result = no_one + no_two
return result
#1 0
def add_numbers3(x, y):
no_one = x
no_two = y
result = no_one + no_two
#1 1
def add_numbers4(x, y):
no_one = x
no_two = y
result = no_one + no_two
#return result
return result
output = add_numbers4(40, 50)
print(output)
<file_sep># class Courses():
# name
# duration
# faculty
# fees
# completionRate()
# studentEnrolledForCourse()
class Courses:
def __init__(self, name, duration, faculty, fees):
self.name = name
self.duration = duration
self.faculty = faculty
self.fees = fees
def completionRate(self, complete_percent):
print('The course is completed {} %'.format(complete_percent))
def studentEnrolledForCourse(self, list_of_students):
for student in list_of_students:
print(student)
python_course = Courses('Python', 3, 'Jenny', 15000)
print(python_course)
print(python_course.name)
python_course.completionRate(30)
java_course = Courses('Java', 5, 'Sam', 15000)
print(java_course.name)
java_course.completionRate(50)
# class Students()
# name
# age
# education
# contact
# email
# ID
# courseEnrolledFor()
# feesPaid()
# study()
# givenExam()
# class Faculty():
# name
# expertise
# education
# contact
# email
# teachCourse()
# paid()
# completedCourse()
<file_sep>from selenium import webdriver
import time
from time import sleep
def open_chrome_browser():
driver = webdriver.Chrome(executable_path="/Users/gaurnitai/Desktop/Programming/Python/PySeBootcamp/drivers/chromedriver")
driver.get("https://www.amazon.in")
# Here we are using ID locator to find element
searchBox = driver.find_element_by_id("twotabsearchtextbox")
searchBox.send_keys("Macbook Pro") # here we are entering text to serach box
# To find the location of search icon webelement
searchIcon = driver.find_element_by_class_name("nav-input") # here we use class name to find element
searchIcon.click()
sleep(3)
# To find element element using link_text
# macbook_pro_details = driver.find_element_by_link_text("Apple 15\" MacBook Pro, Retina, Touch Bar, 2.9GHz Intel Core i7 Quad Core, 16GB RAM, 512GB SSD, Silver, MPTV2LL/A (Newest Version)")
# macbook_pro_details.click()
# To find all the links on webpage
link = driver.find_element_by_tag_name("a") # It always going to return the very first link
print(link)
print(link.text)
list_of_links = driver.find_elements_by_tag_name("a") # Its going to return the list of links
#print(list_of_links)
for link in list_of_links:
print(link.text)
# To find element element using partial_link_text
macbook_pro_details = driver.find_element_by_partial_link_text("Apple MacBook Pro")
macbook_pro_details.click()
sleep(5)
driver.close()
def open_ff_browser():
driver = webdriver.Firefox(executable_path="/Users/gaurnitai/Desktop/Programming/Python/PySeBootcamp/drivers/geckodriver")
driver.get("https://www.amazon.in")
driver.close()
open_chrome_browser()<file_sep># One way if
# Two way - if else
# Multiway
#
# I have to find whether number is divisible by 6 only when the number is positive
num = 6
if num > 0:
if num % 6 == 0:
print(num)
else:
print('The number is not divisible by 6')
else:
if num == 0:
print('The number zero')
else:
print('Tyhe number is negative')
#
dummy_string = 'This is my dummy string and seems it is gonna useful'
dummy_string[0]
splitted_words = dummy_string.split()
#['This', 'is', 'my', 'dummy', 'string', 'and', 'seems', 'it', 'is', 'gonna', 'useful']
print(splitted_words)
for i in range(0, len(splitted_words)):
if splitted_words[i] == 'my' or splitted_words[i] == 'dummy' or splitted_words[i] == 'seems':
print(splitted_words[i])
<file_sep>class Courses:
def __init__(self, name, duration, faculty, fees):
self.name = name
self.duration = duration
self.faculty = faculty
self.fees = fees
def completionRate(self, complete_percent):
print('The course is completed {} %'.format(complete_percent))
def studentEnrolledForCourse(self, list_of_students):
for student in list_of_students:
print(student)
python_course = Courses('Python', 3, 'Jenny', 15000)
print(dir(python_course))
print(python_course.name)<file_sep>
<img src="./pythonclipart.png" style="width:50%; text-align: center">
### PY-SE-BOOTCAMP
### _A Professional Yoga with Selenium & Python_
_This repo contains the code we discussed throughout the course. Also, it will have assignments solution._
###### ❝ WHAT DO WE DO WITH CODE HERE :ok_woman: :question: ❞
- _Open the respective file_
- _Copy the content of file_
- _Create new file with meaningful name on your local machine and paste the copied code_ 🏗
- _Save the file and execute_
- _That pretty simple 😀_
###### ❝ A BIG THANKS TO ALL FOR YOUR DONATION ❞
__*<NAME>*__
__*<NAME>*__
__*<NAME>*__
__*<NAME>*__
__*Snehal*__
__*<NAME>*__
__*<NAME>*__
__*<NAME>*__
<file_sep>names = ('John', 'Jane', 'Jenny', 'Mike', 'Jane')
names = ()
# print(names[0])
# for name in names:
# print(name)
# print(dir(names))
# print(names.index('Jane'))
# immutable -
# mutable - which can be changes
# print(names.count('Jane'))
# print(names)
# Set
set_names = {'John', 'Jane', 'Jenny', 'Mike', 'Jane'}
print(set_names)
print(dir(set_names))
set_names.add('Jackson')
print(set_names)
set_names.add('<NAME>')
print(set_names)
for name in set_names:
print(name)
copy_set = set_names.copy()
print(copy_set)
copy_set.clear()
print(copy_set)
empty_set = set()
print(empty_set)
empty_set.add('Orange')
print(empty_set)
set_names = {'John', 'Jane', 'Jenny', 'Mike', 'Jane'} # superset
new_set = {'John', 'Jane', 'Andy'} # subset
is_subset = new_set.issubset(set_names)
print(is_subset)
is_intersection = new_set.intersection(set_names)
print(is_intersection)
is_intersection = new_set.difference(set_names)
print(is_intersection)
is_intersection = set_names.difference(new_set)
print(is_intersection)
# set_names.remove('Jackson')
# print(set_names)
set_names.discard('Jackson')
print(set_names)
<file_sep>
# words = 'This' , 'is', 'python', 'Course'
# print(words)
words = ['This' , 'is', 'python', 'Course'] # sequential manner
print(words)
# List - ['This' , 'is', 'python', 'Course']
empty_list = []
print(empty_list)
# add some more items
# i want to remove items from list
# i want to add some items to the end of the list
# i want to add items in between to the list items
# replace
# clear all the items
# copy one list into list
# reverse
# Add
# print(dir(empty_list))
# i want to add some items to the end of the list
empty_list.append('Python')
print(empty_list)
empty_list.append('Java')
print(empty_list)
empty_list.append('JS')
print(empty_list)
empty_list.append('Ruby')
print(empty_list)
empty_list.append('C#')
print(empty_list)
empty_list.append('JS')
print(empty_list)
empty_list.insert(1, 'Ruby')
print(empty_list)
empty_list.remove('Ruby')
print(empty_list)
another_list = empty_list.copy()
print("Before clear " , another_list)
another_list.clear()
print("After clear ", another_list)
print("Before pop " , empty_list)
empty_list.pop()
print("After pop ", empty_list)
print(len(empty_list))
for i in range(0, len(empty_list)):
if empty_list[i] == 'Python':
print(empty_list[i])
# Enhanced For loop
for item in empty_list:
print(item)
# empty_list[1]
# empty_list[-1]
print("Before sort " , empty_list)
empty_list.sort(reverse=True)
print("After sort ", empty_list)
empty_list.reverse()
print("After reverse ", empty_list)
print(empty_list)
for item in empty_list:
print(item)
# Tuple - ('This' , 'is', 'python', 'Course')
names = ('John', 'Jane', 'Jenny', 'Mike')
# Set - {'This' , 'is', 'python', 'Course'}
# Dictionary
<file_sep>from selenium import webdriver
import time
# A - Arrange (Setup/Prerequsite)
# A - Action
# A = Assert (Validate)
def verify_search_functionality(search_text):
# ARRANGE
driver = webdriver.Chrome("/Users/gaurnitai/Desktop/PySeBootcamp/drivers/chromedriver")
driver.get("https://www.snapdeal.com/offers/essential?")
driver.maximize_window()
time.sleep(4)
#//button[@class='_2AkmmA _29YdH8']
## ACTION
search_box = driver.find_element_by_name("keyword") # Find the location of search box
#search_box.send_keys("Macbook pro") # to enter text we have to use send_keys()
search_box.send_keys(search_text)
# Finding xpath using contains(attribute, textwithinattributevalue)
search_icon = driver.find_element_by_xpath("//button[contains(@class, 'searchformButton')]")
search_icon.click()
search_box = driver.find_element_by_name("keyword") # Find the location of search box
#search_box.send_keys("Macbook pro") # to enter text we have to use send_keys()
search_box.send_keys(search_text)
search_icon = driver.find_element_by_xpath("//button[contains(@class, 'searchformButton')]")
search_icon.click()
time.sleep(5)
## ASSERT
search_product_info_element = driver.find_element_by_xpath("(//span[@class='nnn'])[1]")
search_product_info = search_product_info_element.text
if(search_product_info == "We've got 10000+ results for 'samsung mobile phone'"):
print("We have successfully searched the product " + search_text)
else:
print("The search product is not listed here")
driver.close()
driver.quit()
# verify_search_functionality("Macbook pro back cover")
verify_search_functionality("samsung mobile phone")<file_sep>def make_dosas(name):
print('Take the ingredients')
print('Mix the ingredients')
print('Pour on pan')
print('bake one side properly')
print('flip dosa')
print('Bake other side')
print('Serve dosa to ' + name)
def make_different_dosas(name, ingredients): # parameters
print('Take the ' + ingredients)
print('Mix the ingredients')
print('Pour on pan')
print('bake one side properly')
print('flip dosa')
print('Bake other side')
print('Serve dosa to ' + name)
make_different_dosas('John', 'Cheese') # arguments
print("-------------")
make_different_dosas('Ramu', 'Masala')
print("-------------")
make_different_dosas('Kid', 'flour')
<file_sep>import time
from selenium import webdriver
def verify_drag_and_drop():
# ARRANGE
driver = webdriver.Chrome("/Users/gaurnitai/Desktop/PySeBootcamp/drivers/chromedriver")
driver.get("https://www.amazon.in")
driver.maximize_window()
time.sleep(4)
driver.save_screenshot("/Users/gaurnitai/Desktop/dummyrepo/py-se-bootcamp/screenshots" + "homepage.png")
search_box = driver.find_element_by_id("twotabsearchtextbox") # Find the location of search box
search_box.send_keys("Macbook pro") # to enter text we have to use send_keys()
# Finding xpath using contains(attribute, textwithinattributevalue)
search_icon = driver.find_element_by_xpath("//input[@type='submit']")
search_icon.click()
time.sleep(5)
driver.save_screenshot("/Users/gaurnitai/Desktop/dummyrepo/py-se-bootcamp/screenshots" + "productlisting.png")
parent_window = driver.current_window_handle
print(parent_window)
driver.find_element_by_xpath("(//a[@class='a-link-normal a-text-normal'])[1]").click()
time.sleep(3)
windows_set = driver.window_handles
print(windows_set)
for window in windows_set:
if (window != parent_window):
driver.switch_to.window(window)
driver.save_screenshot("/Users/gaurnitai/Desktop/dummyrepo/py-se-bootcamp/screenshots/" + "childtab.png")
productTitle = driver.find_element_by_id("productTitle")
print(productTitle.text)
driver.switch_to.window(parent_window)
time.sleep(3)
driver.find_element_by_xpath("(//a[@class='a-link-normal a-text-normal'])[1]").click()
time.sleep(9)
verify_drag_and_drop()
<file_sep>
# To define n nos. of time execution fo certain code
def find_even_odd(number):
is_even = number % 2 == 0 # true / false
print(is_even)
if is_even == True:
print('The number is ' + str(number) + ' is even')
else:
print('The number is ' + str(number) + ' is odd')
# find_even_odd(40) #
# find_even_odd(39)
# find_even_odd(40) #
# find_even_odd(39)
# find_even_odd(40) #
# find_even_odd(39)
# starting point & ending point
# for loop
for num in range(1, 6): # num is loop control variable
print(num)
print("=======")
# while
num = 1
while num < 6:
print(num)
num = num + 1
<file_sep># global variable
# local variable
ingredients = 'Cheese'
def make_different_dosas(name): # parameters
# ingredients = 'Cheese'
print('Take the ' + ingredients)
print('Mix the ingredients')
print('Pour on pan')
print('bake one side properly')
print('flip dosa')
print('Bake other side')
print('Serve dosa to ' + name)
def make_dosas(name): # parameters
print('Take the ' + ingredients)
print('Mix the ingredients')
print('Pour on pan')
print('bake one side properly')
print('flip dosa')
print('Bake other side')
print('Serve dosa to ' + name)
make_different_dosas('John')
make_dosas('Kid')
<file_sep>from selenium import webdriver
from time import sleep
def test_documentation_link():
driver = webdriver.Chrome("/Users/gaurnitai/Desktop/PySeBootcamp/drivers/chromedriver")
driver.get("https://www.selenium.dev/")
driver.maximize_window();
sleep(4)
# driver.find_element_by_link_text("Downloads").click()
# Find Downloads using Absolute xpath
# xpath = //html/body/header/nav/a[1]
# Absolute xpath for Downloads
# driver.find_element_by_xpath("//html/body/header/nav/a[1]").click()
# Relative xpath for Downloads
driver.find_element_by_xpath("(//a[@href='/downloads'])[1]").click()
sleep(4)
# documentation = driver.find_element_by_link_text("documentation")
# Absolute xpath for Downloads
# documentation = driver.find_element_by_xpath("//html/body/header/nav/a[3]")
# Relative xpath for Downloads
documentation = driver.find_element_by_xpath("(//a[@href='/documentation'])[1]")
documentation.click()
#//header[@id='header']//a[@href='/about']
sleep(8)
driver.close()
driver.quit()
<file_sep>
class Student:
def __init__(self, name, age, education, contact, ID, course_enrolled, email=None):
self.name = name
self.age = age
self.education = education
self.contact = contact
self.email = email
self.ID = ID
self.course_enrolled = course_enrolled
def courseEnrolledFor(self):
# John has enrolled for course
print(self.name + " has enrolled for " + self.course_enrolled)
def feesPaid(self, paid_fees):
print("{} has paid {} /-".format(self.name, paid_fees))
print("{1} has paid {0} /-".format(paid_fees, self.name))
print("{name} has paid {fees} /-".format(name=self.name, fees=paid_fees))
def print_obj_properties(self):
print(self.name, self.email, self.contact)
john = Student("John", 26, "B.E", 13244, "<EMAIL>", 1, "Python")
mike = Student("Mike", 27, "B.E", 34353, 2, "Java")
jenny = Student("Jenny", 23, "B.E", 758597, 3, "JavaScript", email="<EMAIL>")
ramu = Student("Ramu", 26, "Ph.D", 343536, "<EMAIL>", 4, "Python")
# print(john.name)
# john.courseEnrolledFor()
# john.feesPaid(15000)
# print(mike.name)
# mike.courseEnrolledFor()
# mike.feesPaid(15000)
# print(mike.email)
#
# john.print_obj_properties()
<file_sep># Define a function which calculate the age of any individual from current date
# Define a function which gonna convert Temperature from celcius to fahrenheit and vice versa
# Define a function where you have to find whether the given number is odd or even
<file_sep>from py_se_day14.arithmetic_module import ArithmeticClass
import pytest
class TestArithmeticClass:
@pytest.mark.run(order=4)
def test_add_functionality(self):
aclass = ArithmeticClass(40, 50)
r = aclass.add()
assert r == 90
@pytest.mark.run(order=1)
def test_sub_functionality(self):
aclass = ArithmeticClass(40, 50)
r = aclass.sub()
assert r == 90
@pytest.mark.run(order=3)
def test_mul_functionality(self):
aclass = ArithmeticClass(40, 50)
r = aclass.mul()
assert r == 2000
@pytest.mark.run(order=2)
def test_div_functionality(self):
aclass = ArithmeticClass(100, 50)
r = aclass.div()
assert r == 2
| 5c3bc2fb466173b57478e398abc9a02d6e299f99 | [
"Markdown",
"Python"
] | 46 | Python | letscodedjango/py-se-bootcamp | 302e2acb69f4aaefbb2fe6361083c9135b000394 | 4ce63b9accb23867fb5afdf5235ed782e39a4902 | |
refs/heads/master | <repo_name>prady00/QuickTest<file_sep>/src/main/java/com/prady00/emails/PackCreatedMail.java
package com.prady00.emails;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
public class PackCreatedMail implements Email {
private String to;
private String body;
private String subject;
@Autowired
public JavaMailSender sender;
public PackCreatedMail(String to, String body, String subject) {
super();
this.to = to;
this.body = body;
this.subject = subject;
}
@Override
public void setSendTo(String to) {
this.to = to;
}
@Override
public void setBody(String body) {
this.body = body;
}
@Override
public void setSubject(String subject) {
this.subject = subject;
}
@Override
public void send() throws MessagingException, MailException {
MimeMessage message = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message);
helper.setTo(this.to);
helper.setText(this.body);
helper.setSubject(this.subject);
sender.send(message);
}
}
<file_sep>/src/main/java/com/prady00/test/Test.java
package com.prady00.test;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotBlank;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
@Entity
public class Test {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private int pack_id;
private int number_of_questions;
private String questions;
private String answers;
private String result;
private String notes;
private String slug;
@Column(nullable = false, updatable = false)
@CreatedDate
@Temporal(TemporalType.TIMESTAMP)
private Date createdAt;
@Column(nullable = false)
@LastModifiedDate
@Temporal(TemporalType.TIMESTAMP)
private Date updatedAt;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getPack_id() {
return pack_id;
}
public void setPack_id(int pack_id) {
this.pack_id = pack_id;
}
public int getNumber_of_questions() {
return number_of_questions;
}
public void setNumber_of_questions(int number_of_questions) {
this.number_of_questions = number_of_questions;
}
public String getQuestions() {
return questions;
}
public void setQuestions(String questions) {
this.questions = questions;
}
public String getAnswers() {
return answers;
}
public void setAnswers(String answers) {
this.answers = answers;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
}
<file_sep>/src/main/java/com/prady00/exceptions/UserAlreadyRequestedPack.java
package com.prady00.exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(code=HttpStatus.BAD_REQUEST)
public class UserAlreadyRequestedPack extends Exception {
public UserAlreadyRequestedPack(String str) {
super(str);
}
}
<file_sep>/src/main/java/com/prady00/pack/PackRepository.java
package com.prady00.pack;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
public interface PackRepository extends JpaRepository<Pack, Long>{
List<Pack> findAllByEmail(String email);
}
<file_sep>/README.md
# QuickTest
Springboot based APIs for creating multiple choice tests
| 21485611ee301d7957ccbaf5fe1c044f3d68480a | [
"Markdown",
"Java"
] | 5 | Java | prady00/QuickTest | 77e0ff552a60a15cf24896e9e0fef01941b95aa5 | fb4dbd5d33091efa0351a9d778618be9faaa4710 | |
refs/heads/master | <repo_name>IbrahimAdDandan/axess-front-end<file_sep>/src/app/interceptor.interceptor.ts
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor,
HttpErrorResponse,
HttpParams,
HttpHeaders
} from '@angular/common/http';
import { environment } from "../environments/environment.prod";
import { Observable } from 'rxjs';
@Injectable()
export class InterceptorInterceptor implements HttpInterceptor {
constructor() { }
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
const _sid = localStorage.getItem('sid');
// if (_sid && request.url.toLowerCase().indexOf("hash") !== -1) {
// // const header = request.headers.append('Content-Type', 'application/x-www-form-urlencoded');
// // const cloneReq = request.clone({ url: request.url + "?sid=" + _sid, headers: request.headers.append('Content-Type', 'application/x-www-form-urlencoded') });
// const cloneReq = request.clone({ url: request.url + "?sid=" + _sid});
// debugger;
// return next.handle(cloneReq);
// }
if (_sid && request.url.toLowerCase().indexOf(environment.apiEndpoint.toLowerCase()) !== -1) {
// request.params.append('sid', _sid)
const cloneReq = request.clone({ params: request.params.append('sid', _sid) });
// const cloneReq = request.clone({ url: request.url + "?&type=json&sid=" + _sid });
// debugger;
return next.handle(cloneReq);
}
// else if (request.url.toLowerCase().indexOf("login") !== -1) {
// const cloneReq = request.clone( { url: environment.apiEndpoint + request.url });
// return next.handle(cloneReq);
// }
const cloneReq = request.clone({ url: request.url });
return next.handle(cloneReq);
}
private handleAuthError(err: HttpErrorResponse): Observable<any> {
// console.log('from interceptor: ' + err);
// if (err.status === 401 || err.status === 403) {
// return Observable.throw(err);
// }
return Observable.throw(err);
}
}
<file_sep>/src/app/rooms/rooms.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RoomsRoutingModule } from './rooms-routing.module';
import { ViewRoomsComponent } from './view-rooms/view-rooms.component';
import { GroupRoomsComponent } from './group-rooms/group-rooms.component';
import { MatSnackBarModule } from "@angular/material/snack-bar";
@NgModule({
declarations: [ViewRoomsComponent, GroupRoomsComponent],
imports: [
CommonModule,
RoomsRoutingModule,
MatSnackBarModule
],
exports: [GroupRoomsComponent]
})
export class RoomsModule { }
<file_sep>/src/app/home/home.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { environment } from 'src/environments/environment.prod';
@Injectable({
providedIn: 'root'
})
export class HomeService {
mailUrl = environment.apiEndpoint + 'user/mail';
constructor(private _http: HttpClient) { }
sendMail(subject: string, content: string, mail: string) {
let form = new URLSearchParams();
form.append('subject', subject);
form.append('content', content);
form.append('email', mail);
return this._http.post<any>(this.mailUrl, form.toString, { headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}) });
}
sendmail1(object: any) {
return this._http.post<any>("https://smtpjs.com/v3/smtpjs.aspx?", JSON.stringify(object), { headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}) });
}
}
<file_sep>/src/app/models/appointment.model.ts
import { Room } from './room.model';
import { User } from './user.model';
export class Appointment {
id: number;
connectedEvent: boolean;
deleted: boolean;
description: string;
end: Date;
passwordProtected: boolean;
start: Date;
title: string;
room: Room;
owner: User;
}
<file_sep>/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';
import {SharedModule } from './shared/shared.module';
import { SecurityModule } from "./security/security.module";
import { DashboardModule } from "./dashboard/dashboard.module";
import { GroupsModule } from "./groups/groups.module";
import { RoomsModule } from "./rooms/rooms.module";
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { InterceptorInterceptor } from "./interceptor.interceptor";
import { AuthGuardGuard } from './auth-guard.guard';
import { HomeComponent } from './home/home.component';
import { NotfoundComponent } from './notfound/notfound.component';
import { WelcomeSectionComponent } from './home/sections/welcome-section/welcome-section.component';
import { ServicesSectionComponent } from './home/sections/services-section/services-section.component';
import { AboutusComponent } from './home/sections/aboutus/aboutus.component';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {MatCardModule} from '@angular/material/card';
import { AgmCoreModule } from '@agm/core';
import { PricingComponent } from './pricing/pricing.component';
import { MatSlideToggleModule } from "@angular/material/slide-toggle";
import { UserProfileComponent } from './user-profile/user-profile.component';
import { MatFormFieldModule } from "@angular/material/form-field";
import { MatPasswordStrengthModule } from '@angular-material-extensions/password-strength';
import { WhoWeAreComponent } from './home/sections/who-we-are/who-we-are.component';
@NgModule({
declarations: [
AppComponent,
HomeComponent,
NotfoundComponent,
WelcomeSectionComponent,
ServicesSectionComponent,
AboutusComponent,
PricingComponent,
UserProfileComponent,
WhoWeAreComponent
],
imports: [
BrowserModule,
RouterModule,
FormsModule,
AppRoutingModule,
SharedModule,
SecurityModule,
DashboardModule,
GroupsModule,
RoomsModule,
FontAwesomeModule,
BrowserAnimationsModule,
MatCardModule,
MatSlideToggleModule,
AgmCoreModule.forRoot({
apiKey: '<KEY>'
}),
MatFormFieldModule,
MatPasswordStrengthModule
],
providers: [AuthGuardGuard, {
provide: HTTP_INTERCEPTORS,
useClass: InterceptorInterceptor,
multi: true
}],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/src/app/models/user.model.ts
import { Group } from './group.model';
export class User {
id: number;
firstname: string;
lastname: string;
login: string;
password: string;
external_id: number;
external_type: string;
pictureuri: string;
displayName: string;
timeZoneId: string;
type: string;
rights: string[];
address: Address;
languageId: number;
groups: Group[];
}
export class Address {
id: number;
deleted: boolean;
country: string;
email: string;
}<file_sep>/src/app/rooms/services/room.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { environment } from "../../../environments/environment.prod";
import { Room } from "../../models/room.model";
import { Invitation } from "src/app/models/invitation.model";
import { Appointment } from "src/app/models/appointment.model";
@Injectable({
providedIn: 'root'
})
export class RoomService {
private _roomsByGroupUrl = environment.apiEndpoint + 'group/';
private _invitationUrl = environment.apiEndpoint + 'user/invitations/';
constructor(private _http: HttpClient) { }
get(groupId) {
return this._http.get<{roomDTO: Room[]}>(environment.apiEndpoint + 'group/' + groupId + '/rooms');
}
getInvitations(userId: number) {
return this._http.get<Invitation[]>(this._invitationUrl + userId);
}
getAppointments(groupId: number) {
return this._http.get<{appointmentDTO: Appointment[]}>(environment.apiEndpoint + 'calendar/group/' + groupId);
}
getRoomHash(roomId) {
const body = {
user: JSON.stringify({
firstname: localStorage.getItem('firstname'),
lastname: localStorage.getItem('lastname'),
id: localStorage.getItem('userId'),
login: localStorage.getItem('login'),
externalId: 1,
externalType: null
}),
options: JSON.stringify({
roomId: roomId,
moderator: false,
showAudioVideoTest: true,
})
};
let form = new URLSearchParams();
form.append('user', body.user);
form.append('options', body.options);
return this._http.post<any>(environment.apiEndpoint + 'user/hash', form.toString(), { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }) });
}
}
<file_sep>/src/app/security/register/register.component.ts
import { ChangeDetectionStrategy, Component, OnInit, ViewEncapsulation } from '@angular/core';
import { FormControl, FormGroupDirective, NgForm } from '@angular/forms';
import { Router } from '@angular/router';
import { User, Address } from 'src/app/models/user.model';
import { LoginService } from '../services/login-service.service';
import { MatPasswordStrengthComponent } from '@angular-material-extensions/password-strength';
import { MatFormField } from "@angular/material/form-field/form-field";
import {
MatSnackBar, MatSnackBarHorizontalPosition,
MatSnackBarVerticalPosition,
} from '@angular/material/snack-bar';
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.sass'],
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class RegisterComponent implements OnInit {
user: User;
horizontalPosition: MatSnackBarHorizontalPosition = 'center';
verticalPosition: MatSnackBarVerticalPosition = 'bottom';
constructor(private _auth: LoginService, private _router: Router, private _snackBar: MatSnackBar) { }
ngOnInit(): void {
this.user = new User();
this.user.address = new Address();
this.user.languageId = 14;
}
formSubmit(ngForm: NgForm) {
// this._auth
// .getSid()
// .subscribe(sid => {
// console.log(sid);
// localStorage.setItem('sid', sid);
this.user.firstname = ngForm.form.controls['firstname'].value;
this.user.lastname = ngForm.form.controls['lastname'].value;
this.user.login = ngForm.form.controls['username'].value;
this.user.address.email = ngForm.form.controls['username'].value;
this.user.password = ngForm.form.controls['<PASSWORD>'].value;
this._auth
.register(this.user)
.subscribe(res => {
// console.log("Register Result is: ");
// console.log(res);
localStorage.removeItem('sid');
this._router.navigate(['security']);
}, err => {
if (err.status === 401 || err.status === 403) {
// alert('invalid user ID or password');
const message = 'ليس مسموحاً لك القيام بهذا';
const action = 'إغلاق';
this._snackBar.open(message, action, {
duration: 2000,
});
} else {
// alert('There is an error occured, please try later.');
const message = 'حدث خطأ ما، يرجى المحاولة لاحقاً';
const action = 'إغلاق';
this._snackBar.open(message, action, {
duration: 4000,
horizontalPosition: this.horizontalPosition,
verticalPosition: this.verticalPosition,
});
}
});
// }, er => { });
}
}
<file_sep>/src/app/shared/navbar/navbar.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.sass']
})
export class NavbarComponent implements OnInit {
username: string;
isLoggedIn: boolean;
constructor(private _router: Router) { }
ngOnInit(): void {
}
LoggedIn() {
this.username = localStorage.getItem('username');
this.isLoggedIn = !!this.username;
// console.log("userEmail" + this.userEmail);
return this.isLoggedIn;
}
logout() {
localStorage.clear();
// localStorage.removeItem('email');
// localStorage.removeItem('username');
// localStorage.removeItem('userId');
this._router.navigate(['/']);
}
}
<file_sep>/src/app/rooms/view-rooms/view-rooms.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from "@angular/router";
import { RoomService } from "../services/room.service";
import { environment } from "../../../environments/environment.prod";
import {
MatSnackBar, MatSnackBarHorizontalPosition,
MatSnackBarVerticalPosition,
} from '@angular/material/snack-bar';
@Component({
selector: 'app-view-rooms',
templateUrl: './view-rooms.component.html',
styleUrls: ['./view-rooms.component.sass']
})
export class ViewRoomsComponent implements OnInit {
groupId: string;
rooms: any[];
horizontalPosition: MatSnackBarHorizontalPosition = 'center';
verticalPosition: MatSnackBarVerticalPosition = 'bottom';
constructor(private _route: ActivatedRoute, private _roomService: RoomService, private _snackBar: MatSnackBar) { }
ngOnInit(): void {
this.groupId = this._route.snapshot.paramMap.get("id");
this._roomService
.get(this.groupId)
.subscribe(res => {
this.rooms = res.roomDTO;
console.log(this.rooms);
},
err => {
if (err.status === 401 || err.status === 403) {
// alert('invalid user ID or password');
const message = 'ليس مسموحاً لك القيام بهذا';
const action = 'إغلاق';
this._snackBar.open(message, action, {
duration: 2000,
});
} else {
// alert('There is an error occured, please try later.');
const message = 'حدث خطأ ما، يرجى المحاولة لاحقاً';
const action = 'إغلاق';
this._snackBar.open(message, action, {
duration: 4000,
horizontalPosition: this.horizontalPosition,
verticalPosition: this.verticalPosition,
});
}
});
}
enterRoom(roomId) {
// alert(roomId);
// get hash
this._roomService
.getRoomHash(roomId)
.subscribe(res => {
// console.log(res);
// debugger;
if(res.serviceResult.type === 'SUCCESS') {
const message = 'تمت العملية بنجاح';
const action = 'إغلاق';
this._snackBar.open(message, action, {
duration: 4000,
horizontalPosition: this.horizontalPosition,
verticalPosition: this.verticalPosition,
});
const _link = environment.roomLink + res.serviceResult.message;
window.open(_link, '_blank');
}
// got o the link
},
err => {
if (err.status === 401 || err.status === 403) {
// alert('invalid user ID or password');
const message = 'ليس مسموحاً لك القيام بهذا';
const action = 'إغلاق';
this._snackBar.open(message, action, {
duration: 2000,
});
} else {
// alert('There is an error occured, please try later.');
const message = 'حدث خطأ ما، يرجى المحاولة لاحقاً';
const action = 'إغلاق';
this._snackBar.open(message, action, {
duration: 4000,
horizontalPosition: this.horizontalPosition,
verticalPosition: this.verticalPosition,
});
}
});
}
}
<file_sep>/src/app/groups/services/group.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from "../../../environments/environment.prod";
import { Group } from "../../models/group.model";
@Injectable({
providedIn: 'root'
})
export class GroupService {
private _Url = environment.secondaryApi + 'Groups/';
private _OPUrl = environment.apiEndpoint;
constructor(private _http: HttpClient) { }
get() {
return this._http.get<{groupDTO: Group[]}>(this._OPUrl + 'group/');
}
getUserGroups(id: number) {
return this._http.get<{groupDTO: Group[]}>(this._OPUrl + 'user/groups/' + id);
}
getOtherGroups(id: number) {
return this._http.get<Group[]>(this._Url + 'OtherGroups/' + id);
}
joinGroup(groupId: number) {
debugger;
const userId = localStorage.getItem('userId');
return this._http.post<any>(this._OPUrl + 'group/' + groupId + '/users/' + userId, null);
}
}
<file_sep>/src/app/models/invitation.model.ts
export class Invitation {
id: number;
deleted: number;
hash: string;
password_protected: number;
invited_by: number;
invitee_id: number;
room_id: number;
recording_id: number;
valid_from: Date;
valid_to: Date;
comment: string;
name: string;
}
<file_sep>/src/app/home/sections/welcome-section/welcome-section.component.ts
import { Component, OnInit } from '@angular/core';
import { environment } from 'src/environments/environment.prod';
import { Router } from '@angular/router';
@Component({
selector: 'app-welcome-section',
templateUrl: './welcome-section.component.html',
styleUrls: ['./welcome-section.component.sass']
})
export class WelcomeSectionComponent implements OnInit {
username: string;
isLoggedIn: boolean;
calendarUrl: string
constructor(private _router: Router) { }
ngOnInit(): void {
this.calendarUrl = environment.calendar;
}
goToCalendar() {
window.location.href = this.calendarUrl;
}
goToGroups() {
window.location.href = environment.groupsUrl;
}
LoggedIn() {
this.username = localStorage.getItem('username');
this.isLoggedIn = !!this.username;
// console.log("userEmail" + this.userEmail);
return this.isLoggedIn;
}
}
<file_sep>/src/app/groups/view-groups/view-groups.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { GroupService } from "../services/group.service";
import { Group } from 'src/app/models/group.model';
import {
MatSnackBar, MatSnackBarHorizontalPosition,
MatSnackBarVerticalPosition,
} from '@angular/material/snack-bar';
import { interval } from 'rxjs';
@Component({
selector: 'app-view-groups',
templateUrl: './view-groups.component.html',
styleUrls: ['./view-groups.component.sass']
})
export class ViewGroupsComponent implements OnInit, OnDestroy{
groups: Group[];
otherGroups: Group[];
myGroups: Group[];
horizontalPosition: MatSnackBarHorizontalPosition = 'center';
verticalPosition: MatSnackBarVerticalPosition = 'bottom';
timerInterval:any;
constructor(private _groupService: GroupService, private _snackBar: MatSnackBar) {
}
ngOnInit(): void {
this.otherGroups = new Array();
this.groups = new Array();
this.myGroups = new Array();
this._groupService
.get()
.subscribe(res => {
this.groups = res.groupDTO.filter((v, i) => {
v.name !== null;
});
console.log("groups:");
console.log(this.groups);
this._groupService
.getUserGroups(+localStorage.getItem('userId'))
.subscribe(res => {
console.log("my groups: ");
console.log(res);
this.myGroups = res.groupDTO;
// debugger;
this.groups.forEach((group, index) => {
if (group && group.name && !this.found(group)) {
this.otherGroups.push(group);
}
});
console.log(this.otherGroups);
},
err => {
if (err.status === 401 || err.status === 403) {
// alert('invalid user ID or password');
const message = 'ليس مسموحاً لك القيام بهذا';
const action = 'إغلاق';
this._snackBar.open(message, action, {
duration: 2000,
});
} else {
// alert('There is an error occured, please try later.');
const message = 'حدث خطأ ما، يرجى المحاولة لاحقاً';
const action = 'إغلاق';
this._snackBar.open(message, action, {
duration: 4000,
horizontalPosition: this.horizontalPosition,
verticalPosition: this.verticalPosition,
});
}
});
},
err => {
if (err.status === 401 || err.status === 403) {
const message = 'ليس مسموحاً لك القيام بهذا';
const action = 'إغلاق';
this._snackBar.open(message, action, {
duration: 4000,
});
} else {
const message = 'حدث خطأ ما، يرجى المحاولة لاحقاً';
const action = 'إغلاق';
this._snackBar.open(message, action, {
duration: 4000,
horizontalPosition: this.horizontalPosition,
verticalPosition: this.verticalPosition,
});
}
});
this.timerInterval = setInterval(() => {
this._groupService
.getUserGroups(+localStorage.getItem('userId'))
.subscribe(res => {
console.log("my groups: ");
console.log(res);
this.myGroups = res.groupDTO;
// debugger;
this.groups.forEach((group, index) => {
if (group && group.name && !this.found(group) ) {
this.otherGroups.push(group);
}
});
console.log(this.otherGroups);
},
err => {});
},30000);
// interval(1000).subscribe(x => {
// });
// this._groupService
// .getOtherGroups(+localStorage.getItem('userId'))
// .subscribe(res => {
// this.otherGroups = res;
// },
// err => {
// if (err.status === 401 || err.status === 403) {
// alert('please re-login');
// } else {
// alert('There is an error occured, please try later.');
// }
// });
} // end of ngInit
private found(group: Group): boolean {
for(let i = 0; i < this.myGroups.length; i++){
if (group.id === this.myGroups[i].id) {
return true;
}
};
return false;
}
join(groupId) {
this._groupService
.joinGroup(groupId)
.subscribe(res => {
console.log("join group result is: " + res);
console.log(res);
this.myGroups.push(this.otherGroups.filter(value => value.id === groupId)[0]);
this.otherGroups = this.otherGroups.filter(value => value.id !== groupId);
}, err => {
if (err.status === 401 || err.status === 403) {
// alert('invalid user ID or password');
const message = 'ليس مسموحاً لك القيام بهذا';
const action = 'إغلاق';
this._snackBar.open(message, action, {
duration: 2000,
});
} else {
// alert('There is an error occured, please try later.');
const message = 'حدث خطأ ما، يرجى المحاولة لاحقاً';
const action = 'إغلاق';
this._snackBar.open(message, action, {
duration: 4000,
horizontalPosition: this.horizontalPosition,
verticalPosition: this.verticalPosition,
});
}
});
}
LoggedIn() {
return !!localStorage.getItem('sid');
}
ngOnDestroy(){
clearInterval(this.timerInterval);
}
}
<file_sep>/src/environments/environment.prod.ts
export const environment = {
production: true,
origin: 'http://vps-22637d08.vps.ovh.us:5080/',
calendar: 'http://vps-22637d08.vps.ovh.us:5080/openmeetings/#user/calendar',
groupsUrl: 'http://vps-22637d08.vps.ovh.us:5080/openmeetings/#user/group',
apiEndpoint: 'http://vps-22637d08.vps.ovh.us:5080/openmeetings/services/',
secondaryApi: 'http://localhost:7000/',
wicket: 'http://vps-22637d08.vps.ovh.us:5080/openmeetings/wicket/bookmarkable/',
roomLink: 'http://vps-22637d08.vps.ovh.us:5080/openmeetings/hash?secure='
};
// http://localhost/<file_sep>/src/app/rooms/group-rooms/group-rooms.component.ts
import { Component, OnInit, Input } from '@angular/core';
import { RoomService } from "../services/room.service";
import { environment } from "../../../environments/environment.prod";
import { Room } from 'src/app/models/room.model';
import { LoginService } from "../../security/services/login-service.service";
import {
MatSnackBar, MatSnackBarHorizontalPosition,
MatSnackBarVerticalPosition,
} from '@angular/material/snack-bar';
import { Appointment } from 'src/app/models/appointment.model';
import { Router } from '@angular/router';
@Component({
selector: 'group-rooms',
templateUrl: './group-rooms.component.html',
styleUrls: ['./group-rooms.component.sass']
})
export class GroupRoomsComponent implements OnInit {
@Input() groupId: number;
rooms: Room[];
invit: Appointment[];
firstTime: boolean;
horizontalPosition: MatSnackBarHorizontalPosition = 'center';
verticalPosition: MatSnackBarVerticalPosition = 'bottom';
constructor(private _roomService: RoomService, private _authService: LoginService, private _snackBar: MatSnackBar, private _router: Router) { }
ngOnInit(): void {
this.firstTime = true;
// this._roomService
// .get(this.groupId)
// .subscribe(res => {
// this.rooms = res.roomDTO;
// console.log(this.rooms);
// },
// err => {
// if (err.status === 401 || err.status === 403) {
// // alert('invalid user ID or password');
// const message = 'ليس مسموحاً لك القيام بهذا';
// const action = 'إغلاق';
// this._snackBar.open(message, action, {
// duration: 2000,
// });
// } else {
// // alert('There is an error occured, please try later.');
// const message = 'حدث خطأ ما، يرجى المحاولة لاحقاً';
// const action = 'إغلاق';
// this._snackBar.open(message, action, {
// duration: 4000,
// horizontalPosition: this.horizontalPosition,
// verticalPosition: this.verticalPosition,
// });
// }
// });
this._roomService
.getAppointments(this.groupId)
.subscribe(res => {
this.invit = res.appointmentDTO;
// console.log(this.rooms);
},
err => {
if (err.status === 401 || err.status === 403) {
// alert('invalid user ID or password');
const message = 'ليس مسموحاً لك القيام بهذا';
const action = 'إغلاق';
this._snackBar.open(message, action, {
duration: 2000,
});
} else {
// alert('There is an error occured, please try later.');
const message = 'حدث خطأ ما، يرجى المحاولة لاحقاً';
const action = 'إغلاق';
this._snackBar.open(message, action, {
duration: 4000,
horizontalPosition: this.horizontalPosition,
verticalPosition: this.verticalPosition,
});
}
});
}
enterRoom(roomId) {
if (!this.firstTime) {
const message = 'لا يمكن الدخول ﻷكثر من غرفة بنفس الوقت، يرجى إغلاق الغرفة السابقة وإعادة تسجيل الدخول';
const action = 'إغلاق';
this._snackBar.open(message, action, {
duration: 4000,
horizontalPosition: this.horizontalPosition,
verticalPosition: this.verticalPosition,
});
setTimeout(() => {
localStorage.clear();
this._router.navigate(['/security/login']);
}, 3000);
// // alert("not first time");
// localStorage.removeItem('sid');
// this._authService
// .getSid()
// .subscribe(res => {
// if (res) {
// console.log("sid is: ");
// console.log(res);
// localStorage.setItem('sid', res);
// this.firstTime = false;
// // get hash
// this.callRoomService(roomId);
// }
// }, err => { if (err.status === 401 || err.status === 403) {
// // alert('invalid user ID or password');
// const message = 'ليس مسموحاً لك القيام بهذا';
// const action = 'إغلاق';
// this._snackBar.open(message, action, {
// duration: 2000,
// });
// } else {
// // alert('There is an error occured, please try later.');
// const message = 'حدث خطأ ما، يرجى المحاولة لاحقاً';
// const action = 'إغلاق';
// this._snackBar.open(message, action, {
// duration: 4000,
// horizontalPosition: this.horizontalPosition,
// verticalPosition: this.verticalPosition,
// });
// }
// });
} else {
this.firstTime = false;
// get hash
this.callRoomService(roomId);
}
} // end of enter room function
callRoomService(roomId) {
this._roomService
.getRoomHash(roomId)
.subscribe(res => {
// console.log(res);
// debugger;
if (res.serviceResult.type === 'SUCCESS') {
const message = 'تمت العملية بنجاح';
const action = 'إغلاق';
this._snackBar.open(message, action, {
duration: 4000,
horizontalPosition: this.horizontalPosition,
verticalPosition: this.verticalPosition,
});
localStorage.setItem('roomHash', res.serviceResult.message);
const _link = environment.roomLink + res.serviceResult.message;
window.open(_link, '_blank');
}
// got o the link
},
err => {
if (err.status === 401 || err.status === 403) {
// alert('invalid user ID or password');
const message = 'ليس مسموحاً لك القيام بهذا';
const action = 'إغلاق';
this._snackBar.open(message, action, {
duration: 2000,
});
} else {
// alert('There is an error occured, please try later.');
// const message = 'حدث خطأ ما، يرجى المحاولة لاحقاً';
// const action = 'إغلاق';
// this._snackBar.open(message, action, {
// duration: 4000,
// horizontalPosition: this.horizontalPosition,
// verticalPosition: this.verticalPosition,
// });
}
});
}
}
<file_sep>/src/app/models/room.model.ts
export class Room {
room_id: number;
id:number;
name: string;
group_id: number;
owner_id: number;
type: string;
ismoderatedroom: number;
allow_recording: number;
ispublic: number;
allow_user_questions: number;
redirect_url: string;
appointment: number;
capacity: number;
chat_moderated: number;
chat_opened: number;
comment: string;
confno: any;
demo_room: number;
deleted: number;
demo_time: any;
external_id: number;
external_type: number;
files_opened: number;
wait_for_recording: number;
}
<file_sep>/src/app/user-profile/user-profile.component.ts
import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { MatSnackBar, MatSnackBarHorizontalPosition, MatSnackBarVerticalPosition } from '@angular/material/snack-bar';
import { Address, User } from '../models/user.model';
import { LoginService } from "../security/services/login-service.service";
@Component({
selector: 'app-user-profile',
templateUrl: './user-profile.component.html',
styleUrls: ['./user-profile.component.sass']
})
export class UserProfileComponent implements OnInit {
user: User;
horizontalPosition: MatSnackBarHorizontalPosition = 'center';
verticalPosition: MatSnackBarVerticalPosition = 'bottom';
constructor(private _auth: LoginService, private _snackBar: MatSnackBar) { }
ngOnInit(): void {
this.user = new User();
this.user.address = new Address();
this._auth
.getUserInfo(localStorage.getItem('userId'))
.subscribe(userInfo => {
// console.log(userInfo);
this.user = userInfo.userDTO;
},
err => {
const message = 'حدث خطأ ما، يرجى المحاولة لاحقاً';
const action = 'إغلاق';
this._snackBar.open(message, action, {
duration: 4000,
horizontalPosition: this.horizontalPosition,
verticalPosition: this.verticalPosition,
});
});
}
formSubmit(ngForm: NgForm) {
let firstname = ngForm.form.controls['firstname'].value;
let lastname = ngForm.form.controls['lastname'].value;
let login = ngForm.form.controls['username'].value;
let email = ngForm.form.controls['username'].value;
this.user.firstname = (!!firstname || firstname !== '')? firstname : this.user.firstname;
this.user.lastname = (!!lastname || lastname !== '')? lastname : this.user.lastname;
this.user.login = (!!email || email !== '')? email : this.user.login;
this.user.address.email = (!!email || email !== '')? email : this.user.address.email;
this._auth
.updateProfile(this.user)
.subscribe(res => {
this._snackBar.open('تم تحديث البيانات بنجاح، سيتم تطبيق التغييرات في تسجيل الدخول التالي', 'إغلاق', {
duration: 4000,
horizontalPosition: this.horizontalPosition,
verticalPosition: this.verticalPosition,
});
}, err => {
if (err.status === 401 || err.status === 403) {
const message = 'ليس مسموحاً لك القيام بهذا';
const action = 'إغلاق';
this._snackBar.open(message, action, {
duration: 4000,
horizontalPosition: this.horizontalPosition,
verticalPosition: this.verticalPosition,
});
} else {
const message = 'حدث خطأ ما، يرجى المحاولة لاحقاً';
const action = 'إغلاق';
this._snackBar.open(message, action, {
duration: 4000,
horizontalPosition: this.horizontalPosition,
verticalPosition: this.verticalPosition,
});
}
});
}
form1Submit(ngForm1: NgForm) {
let password = ngForm1.form.controls['password'].value;
debugger;
this._auth
.changePass(password)
.subscribe(res => {
if (res.serviceResult.type === "SUCCESS") {
this._snackBar.open('تم تغيير كلمة السر', 'إغلاق', {
duration: 4000,
horizontalPosition: this.horizontalPosition,
verticalPosition: this.verticalPosition,
});
} else if (res.serviceResult.type === "ERROR") {
this._snackBar.open('ليس لديك الصلاحية لتغيير كلمة السر لك أو لشخص آخر', 'إغلاق', {
duration: 4000,
horizontalPosition: this.horizontalPosition,
verticalPosition: this.verticalPosition,
});
}
}, err => {
if (err.status === 401 || err.status === 403) {
const message = 'ليس مسموحاً لك القيام بهذا';
const action = 'إغلاق';
this._snackBar.open(message, action, {
duration: 4000,
horizontalPosition: this.horizontalPosition,
verticalPosition: this.verticalPosition,
});
} else {
const message = 'حدث خطأ ما، يرجى المحاولة لاحقاً';
const action = 'إغلاق';
this._snackBar.open(message, action, {
duration: 4000,
horizontalPosition: this.horizontalPosition,
verticalPosition: this.verticalPosition,
});
}
});
}
}
<file_sep>/src/app/home/sections/aboutus/aboutus.component.ts
import { Component, OnInit } from '@angular/core';
// import {AgmMarker, AgmMap} from '@agm/core';
import { FormGroup } from '@angular/forms';
import { HomeService } from "../../home.service";
import { MatSnackBar, MatSnackBarHorizontalPosition, MatSnackBarVerticalPosition } from '@angular/material/snack-bar';
// import '../../../../assets/smtp.js';
// declare let Email: any;
@Component({
selector: 'app-aboutus',
templateUrl: './aboutus.component.html',
styles:[`
agm-map {
height: 300px;
}
`],
styleUrls: ['./aboutus.component.sass']
})
export class AboutusComponent implements OnInit {
lat = 31.9539;
lng = 35.9106;
complain: string;
suggestion: string;
mail: string;
notice: string;
horizontalPosition: MatSnackBarHorizontalPosition = 'center';
verticalPosition: MatSnackBarVerticalPosition = 'bottom';
constructor(private _homeService: HomeService, private _snackBar: MatSnackBar) { }
ngOnInit(): void {
}
formSubmit(form: FormGroup) {
// const mail = {
// Host : 'smtp.ethereal.email',
// Username : '<EMAIL>',
// port: 587,
// Password : '<PASSWORD>',
// To : '<EMAIL>',
// From : '<EMAIL>',
// Subject : 'subject',
// Body : `
// <i>This is sent as a feedback from my resume page.</i> <br/> <b>Name: </b> <br /> <b>Email: </b><br /> <b>Subject:
// </b><br /> <b>Message:</b> <br /> <br><br> <b>~End of Message.~</b> `,
// Action:"Send"
// };
const subject = "Complain From Contact us in Edu Room AXESS!";
const content = " a Complain: " + this.complain + " a suggestion: " + this.suggestion + " notice: " + this.notice;
this._homeService
.sendMail(subject, content, this.mail)
.subscribe(res => {
this._snackBar.open('تم الإرسال بنجاح', 'إغلاق', {
duration: 4000,
horizontalPosition: this.horizontalPosition,
verticalPosition: this.verticalPosition,
});
}, err => {
const message = 'حدث خطأ ما، يرجى المحاولة لاحقاً';
const action = 'إغلاق';
this._snackBar.open(message, action, {
duration: 4000,
horizontalPosition: this.horizontalPosition,
verticalPosition: this.verticalPosition,
});
});
}
}
<file_sep>/src/app/security/login/login.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { LoginService } from '../services/login-service.service';
import { User } from 'src/app/models/user.model';
import { FormGroup } from '@angular/forms';
import { MatSnackBar,MatSnackBarHorizontalPosition,
MatSnackBarVerticalPosition, } from '@angular/material/snack-bar';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.sass']
})
export class LoginComponent implements OnInit {
user: User;
horizontalPosition: MatSnackBarHorizontalPosition = 'center';
verticalPosition: MatSnackBarVerticalPosition = 'bottom';
constructor(private _auth: LoginService, private _router: Router, private _snackBar: MatSnackBar) { }
ngOnInit(): void {
// if (this._auth.loggedIn()) {
// this._router.navigate(['home']);
// }
}
forgotPass(form: FormGroup) {
this._auth
.forgotPass(form.value.username)
.subscribe(res => {
if (res.serviceResult.type === "SUCCESS") {
this._snackBar.open('تم تغيير كلمة السر بنجاح، كلمة السر الجديدة في بريدك الإلكتروني', 'إغلاق', {
duration: 2000,
});
} else if (res.serviceResult.type === "ERROR") {
this._snackBar.open('البريد الإلكتروني خاطئ', 'إغلاق', {
duration: 2000,
});
}
},
err => {
if (err.status === 401 || err.status === 403) {
// alert('invalid user ID or password');
const message = 'ليس مسموحاً لك القيام بهذا';
const action = 'إغلاق';
this._snackBar.open(message, action, {
duration: 2000,
});
} else {
// alert('There is an error occured, please try later.');
const message = 'حدث خطأ ما، يرجى المحاولة لاحقاً';
const action = 'إغلاق';
this._snackBar.open(message, action, {
duration: 4000,
horizontalPosition: this.horizontalPosition,
verticalPosition: this.verticalPosition,
});
}
});
}
formSubmit(form: FormGroup) {
// console.log("password is: " + form.value.password);
this._auth
.login(form.value.username, form.value.password)
.subscribe(res => {
// console.log(res);
if (res.serviceResult.type === "SUCCESS") {
let result = JSON.parse(res.serviceResult.message);
// console.log(result);
localStorage.setItem('sid', result.sid);
localStorage.setItem('userId', result.user_id);
localStorage.setItem('email', form.value.username);
// localStorage.setItem('pass', <PASSWORD>);
this._auth
.getUserInfo(result.user_id)
.subscribe(userInfo => {
// console.log(userInfo);
this.user = userInfo.userDTO;
localStorage.setItem('username', this.user.firstname + ' ' + this.user.lastname);
localStorage.setItem('firstname', this.user.firstname);
localStorage.setItem('lastname', this.user.lastname);
localStorage.setItem('login', this.user.login);
this._router.navigate(['/groups']);
},
err => {
});
} else if (res.serviceResult.type === "ERROR") {
// alert an ERROR
// alert("Bad Credintials");
this._snackBar.open('كلمة السر أو اسم المستخدم خاطئ', 'إغلاق', {
duration: 2000,
});
}
// this._auth
// .loginToWicket('ibra', form.value.password)
// .subscribe(result => {
// console.log("the result is: ");
// console.log(result);
// }, e => {
// console.log("the error is: ");
// console.log(e)
// });
},
err => {
if (err.status === 401 || err.status === 403) {
// alert('invalid user ID or password');
const message = 'ليس مسموحاً لك القيام بهذا';
const action = 'إغلاق';
this._snackBar.open(message, action, {
duration: 2000,
});
} else {
// alert('There is an error occured, please try later.');
const message = 'حدث خطأ ما، يرجى المحاولة لاحقاً';
const action = 'إغلاق';
this._snackBar.open(message, action, {
duration: 4000,
horizontalPosition: this.horizontalPosition,
verticalPosition: this.verticalPosition,
});
}
});
}
}
<file_sep>/src/app/groups/groups.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
// import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
// import { InterceptorInterceptor } from "../interceptor.interceptor";
import { GroupsRoutingModule } from './groups-routing.module';
import { ViewGroupsComponent } from './view-groups/view-groups.component';
import { SharedModule } from "../shared/shared.module";
import { RoomsModule } from "../rooms/rooms.module";
import { MatSnackBarModule } from "@angular/material/snack-bar";
import { MatTabsModule } from "@angular/material/tabs";
@NgModule({
declarations: [ViewGroupsComponent],
imports: [
CommonModule,
GroupsRoutingModule,
SharedModule,
RoomsModule,
MatSnackBarModule,
MatTabsModule
],
// providers: [{
// provide: HTTP_INTERCEPTORS,
// useClass: InterceptorInterceptor,
// multi: true
// }]
})
export class GroupsModule { }
<file_sep>/src/app/home/sections/services-section/services-section.component.ts
import { Component, OnInit } from '@angular/core';
import { faChevronCircleLeft, faChevronCircleRight } from '@fortawesome/free-solid-svg-icons';
@Component({
selector: 'app-services-section',
templateUrl: './services-section.component.html',
styleUrls: ['./services-section.component.sass']
})
export class ServicesSectionComponent implements OnInit {
faChevronCircleLeft = faChevronCircleLeft;
faChevronCircleRight = faChevronCircleRight;
constructor() { }
ngOnInit(): void {
}
}
<file_sep>/src/app/services/base-service.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from "../../environments/environment";
@Injectable({
providedIn: 'root'
})
export class BaseService {
private _apiUrl = environment.apiEndpoint;
constructor(private _http: HttpClient) { }
get() {
return this._http.get<any>(this._apiUrl);
}
getById(id) {
return this._http.get<any>(this._apiUrl + id);
}
add(data) {
return this._http.post<any>(this._apiUrl, data);
}
deleteProgram(id) {
return this._http.delete<any>(this._apiUrl + id);
}
update(data, id) {
return this._http.put<any>(this._apiUrl + id, data);
}
}
<file_sep>/src/app/security/security.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';
import { SharedModule } from '../shared/shared.module';
import { FormsModule } from '@angular/forms';
import { SecurityRoutingModule } from './security-routing.module';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
import { MatPasswordStrengthModule } from '@angular-material-extensions/password-strength';
import { MatFormFieldModule } from "@angular/material/form-field";
import { MatSnackBarModule } from "@angular/material/snack-bar";
@NgModule({
declarations: [LoginComponent, RegisterComponent],
imports: [
CommonModule,
HttpClientModule,
FormsModule,
SecurityRoutingModule,
SharedModule,
MatPasswordStrengthModule,
MatFormFieldModule,
MatSnackBarModule
],
exports: []
})
export class SecurityModule { }
<file_sep>/src/app/security/services/login-service.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { User } from "../../models/user.model";
import { environment } from '../../../environments/environment.prod';
import { Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class LoginService {
private _loginUrl = environment.apiEndpoint + 'user/login';
private _userURL = environment.apiEndpoint + 'user';
private _wicketLogin = environment.wicket + 'org.apache.openmeetings.web.pages.auth.SignInPage?0-1.2-signin';
constructor(private _http: HttpClient, private _router: Router) { }
login(username: string, password: string) {
// console.log("from service pass is: " + password);
return this._http.get<any>(this._loginUrl + '?user=' + encodeURIComponent(username) + '&pass=' + encodeURIComponent(password));
}
changePass(password: string) {
// debugger;
const id = localStorage.getItem('userId');
if (this.loggedIn && !!id) {
return this._http.post<any>(this._userURL + '/changepass?id=' + id + '&pass=' + password, null);
} else {
this._router.navigate(['/security/login']);
}
}
forgotPass(mail: string) {
return this._http.get<any>(this._userURL + '/forgot?email=' + mail);
}
loginToWicket(username: string, password: string) {
//login=USERNAME&pass=<PASSWORD>
const header = new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Wicket-Ajax': 'true',
'Wicket-Ajax-BaseURL': 'signin',
'Wicket-FocusedElementId': 'btnc5',
'X-Requested-With': 'XMLHttpRequest'
});
let form = new URLSearchParams();
form.append('login', username);
form.append('pass', password);
return this._http.post<any>(this._wicketLogin, form.toString(), { headers: header });
}
updateProfile(user: User) {
const header = new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
});
let form = new URLSearchParams();
form.append('user', JSON.stringify(user));
const id = localStorage.getItem('userId');
return this._http.post<any>(this._userURL + '/' + id, form.toString(), { headers: header });
}
register(user: User) {
const header = new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
});
let form = new URLSearchParams();
form.append('user', JSON.stringify(user));
form.append('confirm', 'false');
return this._http.post<any>(this._userURL + '/register', form.toString(), { headers: header });
}
loggedIn() {
return !!localStorage.getItem('sid');
}
getUserName() {
return localStorage.getItem('email');
}
getUserInfo(id: string) {
// return this._http.get<{"userDTO": User}>(this._userURL + '/' + id);
return this._http.get<any>(this._userURL + '/' + id);
}
// getSid() {
// return this._http.get<string>(environment.secondaryApi + 'GetSid');
// }
}
<file_sep>/src/app/models/invitation.model.spec.ts
import { Invitation } from './invitation.model';
describe('Invitation', () => {
it('should create an instance', () => {
expect(new Invitation()).toBeTruthy();
});
});
| cb8c3388e5ef8dcf453ab1238f5bef300aa5742d | [
"TypeScript"
] | 26 | TypeScript | IbrahimAdDandan/axess-front-end | 8a50f1bcc6fd0edd1dba522cccc32191cf17e744 | 3fd80a9929a562e7e8b8f972af132a789e04f6a0 | |
refs/heads/master | <file_sep># remove original files and create link from sync folder
function link()
{
rm -v ~/$1;
ln -sv ~/linuxrc/$1 ~/$1;
}
link .bashrc
link .bash_aliases
link .vimrc
<file_sep># alias config
# file system navi
alias ll='ls -l'
alias la='ls -A'
alias l='ls -CF'
alias ..="cd .."
alias ...="cd ../.."
alias ....="cd ../../.."
# switch
alias poweroff='sudo poweroff'
alias reboot='sudo reboot'
# apt
alias update="sudo apt-get update"
alias upgrade="sudo apt-get upgrade"
alias autoremove="sudo apt-get autoremove"
# edit config files
alias vbash="vim ~/linuxrc/.bashrc"
alias valias="vim ~/linuxrc/.bash_aliases"
alias vvim="vim ~/linuxrc/.vimrc"
alias rbash="source ~/.bashrc"
# use mv to replace rm
alias rm="trash"
trash()
{
mv $@ $HOME/.local/share/Trash/files/
}
# git aliases
alias gi="git init"
alias gib="git init --bare"
alias gb="git branch"
alias gcm="git checkout master"
alias gcd="git checkout develop"
alias gcmsg="git commit -m"
alias gaa="git add --all"
alias gpush="git push origin master"
alias gpull="git pull"
<file_sep># linuxrc
Store my .*rc files for sync and backup.
Use linkrc.sh to link the files in the git folder to place in the system.
| 4a97fbaf8d0fc75eb35c63463dc049275c1ea729 | [
"Markdown",
"Shell"
] | 3 | Shell | ianxvy/linuxrc | cab99524f0a12ed3bf261cfe384a6b85be059a90 | 6a700c9a9d1ba9a27a93c2d32b31e6f61a776199 | |
refs/heads/master | <file_sep>class CreateElementCWController{
constructor(API, ToastService){
'ngInject';
this.API = API;
this.ToastService = ToastService;
}
$onInit(){
this.deleteNote();
}
deleteNote(){
this.title="";
this.photo="";
this.note="";
}
save(){
var data = {
title: this.title,
note: this.note,
photo: this.photo.base64
};
this.API.all('create-element').post(data).then((response) => {
this.ToastService.show('Élément ajouté !');
});
}
}
export const CreateElementCWComponent = {
templateUrl: './views/app/components/create-element-CW/create-element-CW.component.html',
controller: CreateElementCWController,
controllerAs: 'vm',
bindings: {}
}
<file_sep>"# laravel-angular-material"
"# laravel-angular-material-NPA-tinymce"
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Element;
use App\Http\Requests;
use DB;
class CWElementController extends Controller
{
public function create(Request $request)
{
$this->validate($request, [
'title' => 'required',
'note' => 'required',
'photo' => 'required',
]);
$post = new Element;
$post->title = $request->input('title');
$post->note = $request->input('note');
$post->photo = $request->input('photo');
$post->save();
return response()->success(compact('element'));
}
public function get()
{
$elements = Element::get();
return response()
->success(compact('elements'));
}
public function delete(Request $request)
{
$id = $request->input('id');
return Element::destroy($id);
}
}
<file_sep><?php
namespace App\Modal;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class Evaluate extends Model
{
protected $table = 'evaluates';
public function users()
{
return $this->belongsTo('App\Modal\User');
}
public function themes()
{
return $this->belongsTo('App\Modal\Theme');
}
public function questions()
{
return $this->belongsTo('App\Modal\Question');
}
}
| f89f83acc95e0fae475426510ad1d3e0ffbb8652 | [
"JavaScript",
"PHP",
"Markdown"
] | 4 | JavaScript | fairchance2all/ARW | 3fb0e632863d2446e25d49ffd4bf7a446c5561a8 | 418cd6e82f3f133e669eb595f6a73beacf01eff1 | |
refs/heads/master | <file_sep>from tkinter import *
import random
import time
FIRST_GEN_CHANCE = 0.2
PIXEL_SIZE = 2**4
POPULATION_SIZE = int (1024 / PIXEL_SIZE)
MUTATION_CHANCE = 1 / 100000
TIMER = 0.0
WIDTH = PIXEL_SIZE * POPULATION_SIZE
HEIGHT = PIXEL_SIZE * POPULATION_SIZE
STATE_RULES = {0: 0, 1: 0, 2: None, 3: 1, 4: 0, 5: 0, 6: 0, 7: 0, 8: 00}
def draw_canvas(window):
canvas = Canvas(window, width=WIDTH, height=HEIGHT, background ="white")
canvas.grid(row=0, column=0)
return canvas
def draw_population(canvas, population, generation = None, mutation_count = None, mutation_last_step = None):
canvas.delete("all")
count = 0
for x, x_array in enumerate(population):
for y, dot_state in enumerate(x_array):
color = "black"
if dot_state == 0:
continue
if dot_state > 0:
count += 1
if dot_state == 2:
color = "orange"
if dot_state < 0:
color = "grey"
canvas.create_rectangle(x * PIXEL_SIZE, y * PIXEL_SIZE, (x + 1) * PIXEL_SIZE, (y + 1) * PIXEL_SIZE, fill=color)
text = ""
if generation:
text += "Genration: " + str(generation) + "\n"
if mutation_count:
text += "Mutations total: " + str(mutation_count) + "\n"
if mutation_last_step is not None:
text += "Mutation last gen: " + str(mutation_last_step) + "\n"
text += "Population: " + str(count)
canvas.create_text(30, 40, anchor=W, font="Purisa", text=text)
return
def create_starting_population():
return [[1 if random.random() < FIRST_GEN_CHANCE else 0 for _ in range(0, POPULATION_SIZE)] for _ in range(0, POPULATION_SIZE)]
def if_dot_exists(x,y):
if 0 <= x < POPULATION_SIZE:
if 0 <= y < POPULATION_SIZE:
return True
return False
# def count_neighbours(population, x, y):
# count = 0
#
# for x_dif in [-1, 0, 1]:
# for y_dif in [-1, 0, 1]:
# if x_dif == 0 and y_dif == 0:
# continue
# elif if_dot_exists(x + x_dif, y + y_dif) and population[x + x_dif][y + y_dif] > 0:
# count += 1
# return count
def pre_count_neighbours(population):
neighbours = [[0 for _ in range(0, POPULATION_SIZE)] for _ in range(0, POPULATION_SIZE)]
for x, x_array in enumerate(population):
for y, state in enumerate(x_array):
if state > 0:
for x_dif in [-1, 0, 1]:
for y_dif in [-1, 0, 1]:
if x_dif == 0 and y_dif == 0:
continue
if if_dot_exists(x + x_dif, y + y_dif):
neighbours[x + x_dif][y + y_dif] += 1
return neighbours
def next_generation(population):
new_population = list()
neighbours = pre_count_neighbours(population)
for x, x_array in enumerate(population):
line = list()
for y, y_array in enumerate(x_array):
state = y
neighbours_count = neighbours[x][y]
if state > 1:
state = 1
if state < 0:
state = 0
if MUTATION_CHANCE > 0 and random.random() < MUTATION_CHANCE and neighbours_count > 0:
if population[x][y]:
state = -1
else:
state = 2
line.append(state)
continue
state = state if STATE_RULES[neighbours_count] is None else STATE_RULES[neighbours_count]
line.append(state)
new_population.append(line)
return new_population
def count_mutations(population):
count = 0
for x in population:
for y in x:
if y < 0 or y > 1:
count += 1
return count
def conway():
main_window = Tk()
canvas = draw_canvas(main_window)
population = create_starting_population()
generation_counter = 0
mutations_counter = 0
while True:
generation_counter += 1
this_step_mutations = count_mutations(population)
draw_population(canvas, population, generation=generation_counter,
mutation_last_step=this_step_mutations, mutation_count=mutations_counter)
mutations_counter += this_step_mutations
main_window.update()
population = next_generation(population)
time.sleep(TIMER)
def main():
conway()
if __name__ == "__main__":
main() | 1904dedd0000c562d7b1d760e3b8b651d5ae3ef9 | [
"Python"
] | 1 | Python | rp-goeuro/conway_life | 047a21bb9c3245fd58e1b32e0ed66f62c3a2aa02 | c742bcb1300a8d4973c606dfdc791267a4b3e381 | |
refs/heads/master | <file_sep>import RECEIVE_DATA from '../types/data';
import { postsList } from '../helpers/postsData';
const initialState = {
postListing: [],
};
export default (state = initialState, action) => {
switch (action.type) {
case RECEIVE_DATA:
return {
...state,
postListing: state.postListing.concat(postsList),
};
default:
return state;
}
};
<file_sep>// @flow
import * as React from 'react';
type Props = {
value: string,
onChange: (value: string) => void,
};
export default class InputPreview extends React.PureComponent<Props> {
static defaultProps = {
value: 'value',
};
handleChange = (e: Object) => {
this.props.onChange(e.target.value);
};
render() {
const { value } = this.props;
return (
<div>
<input type="text" value={value} onChange={this.handleChange} />
</div>
);
}
}
<file_sep>import { createSelector } from 'reselect';
import { postsSelector, usersSelector, listingSelector } from '../../selectors';
const getListing = createSelector(postsSelector, usersSelector, listingSelector, (posts, users, listing) =>
listing.map(id => {
const post = posts[id];
return { ...post, user: users[post.author] };
})
);
export default getListing;
<file_sep>import { combineReducers } from 'redux';
import messageReducer from '../containers/HomePage/reducer';
import usersByIdReducer from './usersByIdReducer';
import postsByIdReducer from './postsByIdReducer';
import postListingReducer from './postListingReducer';
import counterReducer from '../containers/Counter/reducer';
const rootReducer = combineReducers({
messageReducer,
usersById: usersByIdReducer,
postsById: postsByIdReducer,
postListing: postListingReducer,
count: counterReducer,
});
export default rootReducer;
<file_sep>import RECEIVE_DATA from '../types/data';
import { getPostsById } from '../helpers/postsData';
const postsById = getPostsById();
const initialState = {
postsById: {},
};
export default (state = initialState, action) => {
switch (action.type) {
case RECEIVE_DATA:
return { ...state, postsById: { ...state.postsById, postsById } };
default:
return state;
}
};
<file_sep>import getPosts from '../fakeData';
export const postsList = getPosts().posts.map(post => post.id);
export const getPostsById = () => {
const postsById = {};
getPosts().posts.forEach(post => {
postsById[post.id] = post;
});
return postsById;
};
export const getUsersById = () => {
const usersById = {};
getPosts().users.forEach(user => {
usersById[user.id] = user;
});
return usersById;
};
<file_sep>import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/rootReducer';
import RECEIVE_DATA from './types/data';
import getPosts from './fakeData';
const store = createStore(
rootReducer,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(),
applyMiddleware(thunk)
);
store.dispatch({
type: RECEIVE_DATA,
payload: getPosts(),
});
export default store;
<file_sep>import React from 'react';
import { createStructuredSelector } from 'reselect';
import { connect } from 'react-redux';
import makeGetPosts from './selectors';
type Props = {
posts: Array<Object>,
};
const Posts = ({ posts }: Props) => (
<div>
<h3>Posts</h3>
<ul>{posts.map(post => <li key={post.id}>{`${post.title} - ${post.user.first} ${post.user.last}`}</li>)}</ul>
</div>
);
const mapStateToProps = createStructuredSelector({
posts: makeGetPosts,
});
export default connect(mapStateToProps)(Posts);
<file_sep>// @flow
import React, { Component } from 'react';
import { connect } from 'react-redux';
import increment from './actions';
type Props = {
increment: () => void,
count: number,
};
class Counter extends Component<Props> {
componentDidMount() {
setInterval(() => {
this.props.increment();
}, 500);
}
render() {
return (
<div>
<h3>Count: {this.props.count}</h3>
</div>
);
}
}
const mapStateToProps = state => ({
count: state.count.count,
});
const mapDispatchToProps = (dispatch: Function) => ({
increment() {
dispatch(increment());
},
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(Counter);
<file_sep>import INCREMENT from './constants';
export default function() {
return {
type: INCREMENT,
};
}
<file_sep>const RECEIVE_DATA = 'RECEIVE_DATA';
export default RECEIVE_DATA;
<file_sep>// @flow
import React from 'react';
import { connect } from 'react-redux';
import styled from 'styled-components';
import getListing from './selectors';
type Props = {
posts: Array<any>,
};
const ListPost = styled.li`
background: ${props => (parseInt(props.title.slice(-1)) % 2 === 0 ? 'yellow' : 'green')};
color: ${props => (parseInt(props.title.slice(-1)) % 2 === 0 ? 'green' : 'yellow')};
`;
const Posts = ({ posts }: Props) => (
<div>
<h3>Posts</h3>
<ul>
{posts.map(post => (
<ListPost title={post.title} key={post.id}>
{`${post.title} - ${post.user.first} ${post.user.last}`}
</ListPost>
))}
</ul>
</div>
);
const mapStateToProps = state => ({
posts: getListing(state),
});
export default connect(mapStateToProps)(Posts);
<file_sep>// @flow
import SET_MESSAGE from './constants';
const initState = {
message: '',
};
type State = {
message: string,
};
export default (state: State = initState, action: Object): Object => {
switch (action.type) {
case SET_MESSAGE:
return {
...state,
message: action.payload,
};
default:
return state;
}
};
<file_sep>import * as React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import InputPreview from '../../components/InputPreview';
import setMessage from './actions';
import Button from '../../styles';
type Props = {
dispatch: (action: Object) => void,
messageReducer: Object,
};
class Home extends React.Component<Props> {
static defaultProps = {
message: 'message',
};
handleChange = value => {
this.props.dispatch(setMessage(value));
};
render() {
const { message } = this.props.messageReducer;
return (
<React.Fragment>
<InputPreview value={message} onChange={this.handleChange} />
<p>{message}</p>
<Link to="/about">
<Button>Go to about page</Button>
</Link>
</React.Fragment>
);
}
}
export default connect(state => state)(Home);
<file_sep>import React from 'react';
import { Link } from 'react-router-dom';
import Posts from '../Posts/Posts';
import Counter from '../Counter/Counter';
import PostsByUser from '../PostsByUser/PostsByUser';
import Button from '../../styles';
const AboutButton = Button.extend`
background: #bada55;
`;
const About = () => (
<div>
About
<Link to="/">
<AboutButton>Go Home</AboutButton>
</Link>
<h1>Reselect Redux</h1>
<Posts />
<Counter />
<h2>User 1</h2>
<PostsByUser user="user-1" />
<h2>User 2</h2>
<PostsByUser user="user-2" />
</div>
);
export default About;
| f8de334f0789bae4a8a850e8ae14a6de40d76bce | [
"JavaScript"
] | 15 | JavaScript | thanglv2/react-training | 690e55abf4e781d12dba0a2e1bd91cbe221f9c1a | 1e40fbc2268aad28cbb46de323bb0f5ca113de86 | |
refs/heads/master | <file_sep>/**
* @license Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';
const Audit = require('./audit');
const WebInspector = require('../lib/web-inspector');
const Util = require('../report/v2/renderer/util');
const {groupIdToName, taskToGroup} = require('../lib/task-groups');
const THRESHOLD_IN_MS = 10;
class BootupTime extends Audit {
/**
* @return {!AuditMeta}
*/
static get meta() {
return {
category: 'Performance',
name: 'bootup-time',
description: 'JavaScript boot-up time',
failureDescription: 'JavaScript boot-up time is too high',
scoreDisplayMode: Audit.SCORING_MODES.NUMERIC,
helpText: 'Consider reducing the time spent parsing, compiling, and executing JS. ' +
'You may find delivering smaller JS payloads helps with this. [Learn ' +
'more](https://developers.google.com/web/tools/lighthouse/audits/bootup).',
requiredArtifacts: ['traces'],
};
}
/**
* @return {LH.Audit.ScoreOptions}
*/
static get defaultOptions() {
return {
// see https://www.desmos.com/calculator/rkphawothk
// <500ms ~= 100, >2s is yellow, >3.5s is red
scorePODR: 600,
scoreMedian: 3500,
};
}
/**
* @param {DevtoolsTimelineModel} timelineModel
* @return {!Map<string, Number>}
*/
static getExecutionTimingsByURL(timelineModel) {
const bottomUpByURL = timelineModel.bottomUpGroupBy('URL');
const result = new Map();
bottomUpByURL.children.forEach((perUrlNode, url) => {
// when url is "" or about:blank, we skip it
if (!url || url === 'about:blank') {
return;
}
const taskGroups = {};
perUrlNode.children.forEach((perTaskPerUrlNode) => {
// eventStyle() returns a string like 'Evaluate Script'
const task = WebInspector.TimelineUIUtils.eventStyle(perTaskPerUrlNode.event);
// Resolve which taskGroup we're using
const groupName = taskToGroup[task.title] || groupIdToName.other;
const groupTotal = taskGroups[groupName] || 0;
taskGroups[groupName] = groupTotal + (perTaskPerUrlNode.selfTime || 0);
});
result.set(url, taskGroups);
});
return result;
}
/**
* @param {!Artifacts} artifacts
* @param {LH.Audit.Context} context
* @return {!AuditResult}
*/
static audit(artifacts, context) {
const trace = artifacts.traces[BootupTime.DEFAULT_PASS];
return artifacts.requestDevtoolsTimelineModel(trace).then(devtoolsTimelineModel => {
const executionTimings = BootupTime.getExecutionTimingsByURL(devtoolsTimelineModel);
let totalBootupTime = 0;
const extendedInfo = {};
const headings = [
{key: 'url', itemType: 'url', text: 'URL'},
{key: 'scripting', itemType: 'text', text: groupIdToName.scripting},
{key: 'scriptParseCompile', itemType: 'text', text: groupIdToName.scriptParseCompile},
];
// map data in correct format to create a table
const results = Array.from(executionTimings)
.map(([url, groups]) => {
// Add up the totalBootupTime for all the taskGroups
totalBootupTime += Object.keys(groups).reduce((sum, name) => sum += groups[name], 0);
extendedInfo[url] = groups;
const scriptingTotal = groups[groupIdToName.scripting] || 0;
const parseCompileTotal = groups[groupIdToName.scriptParseCompile] || 0;
return {
url: url,
sum: scriptingTotal + parseCompileTotal,
// Only reveal the javascript task costs
// Later we can account for forced layout costs, etc.
scripting: Util.formatMilliseconds(scriptingTotal, 1),
scriptParseCompile: Util.formatMilliseconds(parseCompileTotal, 1),
};
})
.filter(result => result.sum >= THRESHOLD_IN_MS)
.sort((a, b) => b.sum - a.sum);
const summary = {wastedMs: totalBootupTime};
const details = BootupTime.makeTableDetails(headings, results, summary);
const score = Audit.computeLogNormalScore(
totalBootupTime,
context.options.scorePODR,
context.options.scoreMedian
);
return {
score,
rawValue: totalBootupTime,
displayValue: Util.formatMilliseconds(totalBootupTime),
details,
extendedInfo: {
value: extendedInfo,
},
};
});
}
}
module.exports = BootupTime;
<file_sep>/**
* @license Copyright 2016 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
/**
* @fileoverview
* Identifies stylesheets, HTML Imports, and scripts that potentially block
* the first paint of the page by running several scripts in the page context.
* Candidate blocking tags are collected by querying for all script tags in
* the head of the page and all link tags that are either matching media
* stylesheets or non-async HTML imports. These are then compared to the
* network requests to ensure they were initiated by the parser and not
* injected with script. To avoid false positives from strategies like
* (http://filamentgroup.github.io/loadCSS/test/preload.html), a separate
* script is run to flag all links that at one point were rel=preload.
*/
'use strict';
const Gatherer = require('../gatherer');
/* global document,window,HTMLLinkElement */
/* istanbul ignore next */
function installMediaListener() {
window.___linkMediaChanges = [];
Object.defineProperty(HTMLLinkElement.prototype, 'media', {
set: function(val) {
window.___linkMediaChanges.push({
href: this.href,
media: val,
msSinceHTMLEnd: Date.now() - window.performance.timing.responseEnd,
matches: window.matchMedia(val).matches,
});
return this.setAttribute('media', val);
},
});
}
/* istanbul ignore next */
function collectTagsThatBlockFirstPaint() {
return new Promise((resolve, reject) => {
try {
const tagList = [...document.querySelectorAll('link, head script[src]')]
.filter(tag => {
if (tag.tagName === 'SCRIPT') {
return (
!tag.hasAttribute('async') &&
!tag.hasAttribute('defer') &&
!/^data:/.test(tag.src) &&
tag.getAttribute('type') !== 'module'
);
}
// Filter stylesheet/HTML imports that block rendering.
// https://www.igvita.com/2012/06/14/debunking-responsive-css-performance-myths/
// https://www.w3.org/TR/html-imports/#dfn-import-async-attribute
const blockingStylesheet =
tag.rel === 'stylesheet' && window.matchMedia(tag.media).matches && !tag.disabled;
const blockingImport = tag.rel === 'import' && !tag.hasAttribute('async');
return blockingStylesheet || blockingImport;
})
.map(tag => {
return {
tagName: tag.tagName,
url: tag.tagName === 'LINK' ? tag.href : tag.src,
src: tag.src,
href: tag.href,
rel: tag.rel,
media: tag.media,
disabled: tag.disabled,
mediaChanges: window.___linkMediaChanges.filter(item => item.href === tag.href),
};
});
resolve(tagList);
} catch (e) {
const friendly = 'Unable to gather Scripts/Stylesheets/HTML Imports on the page';
reject(new Error(`${friendly}: ${e.message}`));
}
});
}
function filteredAndIndexedByUrl(networkRecords) {
return networkRecords.reduce((prev, record) => {
if (!record.finished) {
return prev;
}
const isParserGenerated = record._initiator.type === 'parser';
// A stylesheet only blocks script if it was initiated by the parser
// https://html.spec.whatwg.org/multipage/semantics.html#interactions-of-styling-and-scripting
const isParserScriptOrStyle = /(css|script)/.test(record._mimeType) && isParserGenerated;
const isFailedRequest = record._failed;
const isHtml = record._mimeType && record._mimeType.includes('html');
// Filter stylesheet, javascript, and html import mimetypes.
// Include 404 scripts/links generated by the parser because they are likely blocking.
if (isHtml || isParserScriptOrStyle || (isFailedRequest && isParserGenerated)) {
prev[record._url] = {
isLinkPreload: record.isLinkPreload,
transferSize: record._transferSize,
startTime: record._startTime,
endTime: record._endTime,
};
}
return prev;
}, {});
}
class TagsBlockingFirstPaint extends Gatherer {
constructor() {
super();
this._filteredAndIndexedByUrl = filteredAndIndexedByUrl;
}
static findBlockingTags(driver, networkRecords) {
const scriptSrc = `(${collectTagsThatBlockFirstPaint.toString()}())`;
const firstRequestEndTime = networkRecords.reduce(
(min, record) => Math.min(min, record._endTime),
Infinity
);
return driver.evaluateAsync(scriptSrc).then(tags => {
const requests = filteredAndIndexedByUrl(networkRecords);
return tags.reduce((prev, tag) => {
const request = requests[tag.url];
if (request && !request.isLinkPreload) {
// Even if the request was initially blocking or appeared to be blocking once the
// page was loaded, the media attribute could have been changed during load, capping the
// amount of time it was render blocking. See https://github.com/GoogleChrome/lighthouse/issues/2832.
const timesResourceBecameNonBlocking = (tag.mediaChanges || [])
.filter(change => !change.matches)
.map(change => change.msSinceHTMLEnd);
const earliestNonBlockingTime = Math.min(...timesResourceBecameNonBlocking);
const lastTimeResourceWasBlocking = Math.max(
request.startTime,
firstRequestEndTime + earliestNonBlockingTime / 1000
);
prev.push({
tag,
transferSize: request.transferSize || 0,
startTime: request.startTime,
endTime: Math.min(request.endTime, lastTimeResourceWasBlocking),
});
// Prevent duplicates from showing up again
requests[tag.url] = null;
}
return prev;
}, []);
});
}
/**
* @param {!Object} context
*/
beforePass(context) {
return context.driver.evaluteScriptOnNewDocument(`(${installMediaListener.toString()})()`);
}
/**
* @param {!Object} context
* @param {{networkRecords: !Array<!NetworkRecord>}} tracingData
* @return {!Array<{tag: string, transferSize: number, startTime: number, endTime: number}>}
*/
afterPass(context, tracingData) {
return TagsBlockingFirstPaint.findBlockingTags(context.driver, tracingData.networkRecords);
}
}
module.exports = TagsBlockingFirstPaint;
<file_sep>/**
* @license Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';
const Audit = require('./audit');
class Metrics extends Audit {
/**
* @return {!AuditMeta}
*/
static get meta() {
return {
name: 'metrics',
informative: true,
description: 'Metrics',
helpText: 'Collects all available metrics.',
requiredArtifacts: ['traces', 'devtoolsLogs'],
};
}
/**
* @param {!Artifacts} artifacts
* @return {!AuditResult}
*/
static async audit(artifacts, context) {
const trace = artifacts.traces[Audit.DEFAULT_PASS];
const devtoolsLog = artifacts.devtoolsLogs[Audit.DEFAULT_PASS];
const metricComputationData = {trace, devtoolsLog, settings: context.settings};
const traceOfTab = await artifacts.requestTraceOfTab(trace);
const firstContentfulPaint = await artifacts.requestFirstContentfulPaint(metricComputationData);
const firstMeaningfulPaint = await artifacts.requestFirstMeaningfulPaint(metricComputationData);
const firstCPUIdle = await artifacts.requestFirstCPUIdle(metricComputationData);
const timeToInteractive = await artifacts.requestConsistentlyInteractive(metricComputationData);
const metrics = [];
// Include the simulated/observed performance metrics
const metricsMap = {
firstContentfulPaint,
firstMeaningfulPaint,
firstCPUIdle,
timeToInteractive,
};
for (const [metricName, values] of Object.entries(metricsMap)) {
metrics.push(Object.assign({metricName}, values));
}
// Include all timestamps of interest from trace of tab
for (const [traceEventName, timing] of Object.entries(traceOfTab.timings)) {
const uppercased = traceEventName.slice(0, 1).toUpperCase() + traceEventName.slice(1);
const metricName = `trace${uppercased}`;
const timestamp = traceOfTab.timestamps[traceEventName];
metrics.push({metricName, timing, timestamp});
}
const headings = [
{key: 'metricName', itemType: 'text', text: 'Name'},
{key: 'timing', itemType: 'ms', granularity: 10, text: 'Value (ms)'},
];
const tableDetails = Audit.makeTableDetails(headings, metrics);
return {
score: 1,
rawValue: timeToInteractive.timing,
details: tableDetails,
};
}
}
module.exports = Metrics;
<file_sep>/**
* @license Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
// @ts-nocheck
'use strict';
const Gatherer = require('./gatherer');
const Sentry = require('../../lib/sentry');
const fontFaceDescriptors = [
'display',
'family',
'featureSettings',
'stretch',
'style',
'unicodeRange',
'variant',
'weight',
];
/* eslint-env browser*/
/**
* Collect applied webfont data from `document.fonts`
* @param {string[]}
* @return {{}}
*/
/* istanbul ignore next */
function getAllLoadedFonts(descriptors) {
const getFont = fontFace => {
const fontRule = {};
descriptors.forEach(descriptor => {
fontRule[descriptor] = fontFace[descriptor];
});
return fontRule;
};
return document.fonts.ready.then(() => {
return Array.from(document.fonts).filter(fontFace => fontFace.status === 'loaded')
.map(getFont);
});
}
/**
* Collect authored webfont data from the `CSSFontFaceRule`s present in document.styleSheets
* @return {{}}
*/
/* istanbul ignore next */
function getFontFaceFromStylesheets() {
/**
* Get full data about each CSSFontFaceRule within a styleSheet object
* @param {StyleSheet} stylesheet
* @return {{}}
*/
function getSheetsFontFaces(stylesheet) {
const fontUrlRegex = 'url\\((?:")([^"]+)(?:"|\')\\)';
const fontFaceRules = [];
if (stylesheet.cssRules) {
for (const rule of stylesheet.cssRules) {
if (rule instanceof CSSFontFaceRule) {
const fontsObject = {
display: rule.style.fontDisplay || 'auto',
family: rule.style.fontFamily.replace(/"|'/g, ''),
stretch: rule.style.fontStretch || 'normal',
style: rule.style.fontStyle || 'normal',
weight: rule.style.fontWeight || 'normal',
variant: rule.style.fontVariant || 'normal',
unicodeRange: rule.style.unicodeRange || 'U+0-10FFFF',
featureSettings: rule.style.featureSettings || 'normal',
src: [],
};
if (rule.style.src) {
const matches = rule.style.src.match(new RegExp(fontUrlRegex, 'g'));
if (matches) {
fontsObject.src = matches.map(match => {
const res = new RegExp(fontUrlRegex).exec(match);
return new URL(res[1], location.href).href;
});
}
}
fontFaceRules.push(fontsObject);
}
}
}
return fontFaceRules;
}
/**
* Provided a <link rel=stylesheet> element, it attempts to reload the asset with CORS headers.
* Without CORS headers, a cross-origin stylesheet will have node.styleSheet.cssRules === null.
* @param {Element} oldNode
* @return {<!Promise>}
*/
function loadStylesheetWithCORS(oldNode) {
const newNode = oldNode.cloneNode(true);
return new Promise(resolve => {
newNode.addEventListener('load', function onload() {
newNode.removeEventListener('load', onload);
resolve(getFontFaceFromStylesheets());
});
newNode.crossOrigin = 'anonymous';
oldNode.parentNode.insertBefore(newNode, oldNode);
oldNode.remove();
});
}
const promises = [];
// Get all loaded stylesheets
for (const stylesheet of document.styleSheets) {
try {
// Cross-origin stylesheets don't expose cssRules by default. We reload them w/ CORS headers.
if (stylesheet.cssRules === null && stylesheet.href && stylesheet.ownerNode &&
!stylesheet.ownerNode.crossOrigin) {
promises.push(loadStylesheetWithCORS(stylesheet.ownerNode));
} else {
promises.push(Promise.resolve(getSheetsFontFaces(stylesheet)));
}
} catch (err) {
promises.push({err: {message: err.message, stack: err.stack}});
}
}
// Flatten results
return Promise.all(promises).then(fontFaces => [].concat(...fontFaces));
}
/* eslint-env node */
class Fonts extends Gatherer {
_findSameFontFamily(fontFace, fontFacesList) {
return fontFacesList.find(fontItem => {
return !fontFaceDescriptors.find(descriptor => {
return fontFace[descriptor] !== fontItem[descriptor];
});
});
}
afterPass({driver}) {
const args = JSON.stringify(fontFaceDescriptors);
return Promise.all(
[
driver.evaluateAsync(`(${getAllLoadedFonts.toString()})(${args})`),
driver.evaluateAsync(`(${getFontFaceFromStylesheets.toString()})()`),
]
).then(([loadedFonts, fontFaces]) => {
return loadedFonts.map(fontFace => {
if (fontFace.err) {
const err = new Error(fontFace.err.message);
err.stack = fontFace.err.stack;
Sentry.captureException(err, {tags: {gatherer: 'Fonts'}, level: 'warning'});
return null;
}
const fontFaceItem = this._findSameFontFamily(fontFace, fontFaces);
fontFace.src = (fontFaceItem && fontFaceItem.src) || [];
return fontFace;
}).filter(Boolean);
});
}
}
module.exports = Fonts;
<file_sep>/**
* @license Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';
const Gatherer = require('../gatherer');
/* global fetch, URL, location */
/* istanbul ignore next */
function getRobotsTxtContent() {
return fetch(new URL('/robots.txt', location.href))
.then(response => {
if (!response.ok) {
return {status: response.status, content: null};
}
return response.text()
.then(content => ({status: response.status, content}));
})
.catch(_ => ({status: null, content: null}));
}
class RobotsTxt extends Gatherer {
/**
* @param {{driver: !Driver}} options Run options
* @return {!Promise<!{code: number, content: string}>}
*/
afterPass(options) {
return options.driver.evaluateAsync(`(${getRobotsTxtContent.toString()}())`);
}
}
module.exports = RobotsTxt;
<file_sep>/**
* @license Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
import * as parseManifest from '../lighthouse-core/lib/manifest-parser.js';
declare global {
module LH {
export interface Artifacts {
// Created by by gather-runner
fetchedAt: string;
LighthouseRunWarnings: string[];
UserAgent: string;
traces: {[passName: string]: Trace};
devtoolsLogs: {[passName: string]: DevtoolsLog};
settings: Config.Settings;
// Remaining are provided by gatherers
Accessibility: Artifacts.Accessibility;
CacheContents: string[];
ChromeConsoleMessages: Crdp.Log.EntryAddedEvent[];
CSSUsage: {rules: Crdp.CSS.RuleUsage[], stylesheets: Artifacts.CSSStyleSheetInfo[]};
HTMLWithoutJavaScript: {value: string};
HTTPRedirect: {value: boolean};
JsUsageArtifact: Crdp.Profiler.ScriptCoverage[];
Manifest: ReturnType<typeof parseManifest> | null;
Offline: number;
RobotsTxt: {status: number|null, content: string|null};
RuntimeExceptions: Crdp.Runtime.ExceptionThrownEvent[];
Scripts: Record<string, string>;
ServiceWorker: {versions: Crdp.ServiceWorker.ServiceWorkerVersion[]};
ThemeColor: string|null;
URL: {initialUrl: string, finalUrl: string};
Viewport: string|null;
ViewportDimensions: Artifacts.ViewportDimensions;
// TODO(bckenny): remove this for real computed artifacts approach
requestTraceOfTab(trace: Trace): Promise<Artifacts.TraceOfTab>
}
module Artifacts {
export interface Accessibility {
violations: {
id: string;
nodes: {
path: string;
snippet: string | null;
target: string[];
}[];
}[];
notApplicable: {
id: string
}[];
}
export interface CSSStyleSheetInfo {
header: Crdp.CSS.CSSStyleSheetHeader;
content: string;
}
export interface ViewportDimensions {
innerWidth: number;
innerHeight: number;
outerWidth: number;
outerHeight: number;
devicePixelRatio: number;
}
export interface MetricComputationDataInput {
devtoolsLog: DevtoolsLog;
trace: Trace;
settings: Config.Settings;
}
export interface MetricComputationData extends MetricComputationDataInput {
networkRecords: Array<WebInspector.NetworkRequest>;
traceOfTab: TraceOfTab;
}
export interface Metric {
timing: number;
timestamp: number;
}
export interface LanternMetric {
timing: number;
optimisticEstimate: Gatherer.Simulation.Result
pessimisticEstimate: Gatherer.Simulation.Result;
optimisticGraph: Gatherer.Simulation.GraphNode;
pessimisticGraph: Gatherer.Simulation.GraphNode;
}
export interface TraceTimes {
navigationStart: number;
firstPaint: number;
firstContentfulPaint: number;
firstMeaningfulPaint: number;
traceEnd: number;
onLoad: number;
domContentLoaded: number;
}
export interface TraceOfTab {
timings: TraceTimes;
timestamps: TraceTimes;
processEvents: Array<TraceEvent>;
mainThreadEvents: Array<TraceEvent>;
startedInPageEvt: TraceEvent;
navigationStartEvt: TraceEvent;
firstPaintEvt: TraceEvent;
firstContentfulPaintEvt: TraceEvent;
firstMeaningfulPaintEvt: TraceEvent;
onLoadEvt: TraceEvent;
fmpFellBack: boolean;
}
}
}
}
// empty export to keep file a module
export {}
| a5ab12ea99c857472deeb30dd2537e3dd6a051d8 | [
"JavaScript",
"TypeScript"
] | 6 | JavaScript | yagoubigithub/lighthouse | 06a0a45b478565e6fa90636a41d440a41a40b74c | b820618a75c3619ee15457ef7f5d2d01a5b52cd5 | |
refs/heads/master | <file_sep>import java.text.NumberFormat;
import java.util.Scanner;
public class ConverNumberstoWordMain {
public static void main(final String[] args) {
ConvertNumberstoWord cntw=new ConvertNumberstoWord();
String choice = "";
int n;
Scanner s =new Scanner(System.in);
while (choice != "0"){
System.out.println("");
System.out.println("Enter number between 0-999 to convert into word");
System.out.println(" (0) Exit");
n =s.nextInt();
choice=Integer.toString(n);
if (choice.equals("0")) {
System.out.println("Exit");
break;
}else if (n > 1000 || n < 0){
System.out.println("Invalid Number Only Enter number between 0-999");
}
else System.out.println(NumberFormat.getInstance().format(n) + "='" + cntw.convert(n) + "'");
}
}
}
| 7be692c21404e45bd8a8c1c25c61a02b088ae4ad | [
"Java"
] | 1 | Java | BhaskarReddyKarka/Devops | 8067a02e430b1bd738159786422f99959f6c934e | 0ef213569b1895774303fb0c59bb546c309aa0ec | |
refs/heads/master | <repo_name>Bento-Code/react-github-api-user-search<file_sep>/gruntfile.js
'use strict';
module.exports = function(grunt) {
var pkg = grunt.file.readJSON('package.json');
var pre = './';
grunt.initConfig({
pkg: pkg,
pre: pre,
less: {
development: {
options: {
paths: ["<%= pre %>public/css"],
plugins: [
new (require('less-plugin-autoprefix'))({browsers: ["> 1%"]}),
new (require('less-plugin-clean-css'))()
]
},
files: {"<%= pre %>public/css/main.css": "<%= pre %>public/less/main.less"}
},
production: {
options: {
paths: ["<%= pre %>css"],
plugins: [
new (require('less-plugin-autoprefix'))({browsers: ["> 1%"]}),
new (require('less-plugin-clean-css'))()
]
},
files: {"<%= pre %>public/css/main.min.css": "<%= pre %>public/less/main.less"}
}
},
watch: {
main: {
files: [ '<%= pre %>public/less/*.less' ],
tasks: [ 'build:main' ],
options: {
spawn: false,
},
}
}
});
grunt.loadNpmTasks('grunt-composer');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', [ 'build', 'watch' ]);
grunt.registerTask('install', [ 'composer:update', ]);
grunt.registerTask('build', [ 'less' ]);
grunt.registerTask('build:main', [ 'less' ]);
};
<file_sep>/README.md
# react-github-api-user-search
Search GitHub Users - This Application uses the GitHub API to search for GitHub Users
## Install:
```
npm install
```
## Run:
```
npm start
```
## Grunt:
```
// Run Grunt
grunt
```
## GitHub API KEY:
PLEASE CREATE AND ADD A GITHUB API KEY TO MAKE THE APP WORK WELL!
[GitHub API KEY](https://github.com/settings/apps)
<file_sep>/src/components/Search.js
// PLEASE CREATE AND ADD A GITHUB API KEY TO MAKE THE APP WORK WELL!
import React, {Component} from "react";
class Search extends Component {
constructor(props) {
super(props);
this.state = {
users: [],
typed: '',
cursor: 0,
};
this.key_events = this.key_events.bind(this)
}
key_events(event) {
const {cursor, users} = this.state;
if (event.keyCode === 38 && cursor > 0) {
this.setState(prevState => ({
cursor: prevState.cursor - 1
}))
} else if (event.keyCode === 40 && (cursor < users.length - 1)) {
this.searchListFocus.focus();
this.setState(prevState => ({
cursor: prevState.cursor + 1
}))
} else if (event.keyCode === 13) {
let current_user = '';
for (var i = 0; i <= this.state.cursor; i++) {
current_user = i;
}
window.open(
this.state.users[current_user]['page_url'],
'_blank'
);
}
}
error_message(error) {
window.confirm("API rate limit exceeded -> Please Try Again");
window.open(
'https://developer.github.com/v3/#rate-limiting',
'_blank'
);
console.log('Error: ', error);
}
onChange(event) {
this.setState({typed: event.target.value});
// fetch('https://api.github.com/search/users?state:open&order=asc&q=' + event.target.value)
fetch('https://api.github.com/search/users?state:open&order=asc&per_page=15&q=' + event.target.value)
.then(response => response.json())
.then(parsedJSON => parsedJSON.items.map(user => (
{
name: `${user.login}`,
thumbnail: `${user.avatar_url}`,
page_url: `${user.html_url}`
}
)))
.then(users => this.setState({
users
}))
.catch(error => this.error_message(error));
}
render() {
const {users, cursor} = this.state;
return (
<div className="search_container">
<div className="search">
<input type="text" placeholder="Search a Github User..." value={this.state.typed} className="search" onChange={this.onChange.bind(this)} autoFocus onKeyDown={this.key_events}/>
<ul className="user_list" onKeyDown={this.key_events} ref={(search_focus) => {
this.searchListFocus = search_focus;
}} tabIndex="-1">
{
this.state.typed !== '' && users.length > 0 ?
users.map((user, i) => {
return <li key={user.name} className={cursor === i ? 'active' : null}>
<a href={user.page_url} target="_blank" rel="noopener noreferrer" ref={(child) => {
this.child_element = child;
}}>
<span>{user.name}</span>
<img src={user.thumbnail} alt={user.thumbnail}/>
</a>
</li>
}) : ''
}
</ul>
</div>
</div>
);
}
}
export default Search;
| 4afa1ca6abcfb6702b3e90ba5192e52baa7f864a | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | Bento-Code/react-github-api-user-search | 93a2190659a6d6b3e179eac7ca96804e490fe9d8 | 1f9ca8ca27c914fe409939001fb93c6ebb61e0da | |
refs/heads/master | <repo_name>NicolasHenault/Intro_JQuery<file_sep>/scriptjquery.js
$(function(){
// // $("body").addClass("alert");
// $("button").click(function(){
// // alert($(window).height() + " px");
// // $("div").hide(2000);
// // $("div").show(2000);
// $("div").height(800).width(600);
// });
$("p").click(function(){
$(this).hide();
});
$("#button1").click(function(){
if($("p").hide()){
$("p").show();
}});
$("#button2").click(function(){
$("#bla").show();
if ($("#bla #caca").is(":visible")){
return;
} else{
$("#bla").append('<div id=caca>Fermer</div>');
}
$("#c").hide();
$("#c").fadeIn(3000);
$("#close").click(function(){
$("#bla").hide();
});
});
$(window).scroll(function(){
if($(document).scrollTop()>10){
$("#essai").addClass("test");
} else{
$("#essai").removeClass("test");
}
});
}); | d5756018e0bdd34cb78cf295317def4962eddea9 | [
"JavaScript"
] | 1 | JavaScript | NicolasHenault/Intro_JQuery | 3e6288e62c78028a4a110e2509c786772fac3545 | a214db3e3240621dab6ce6125b5dedf66d3c3b92 | |
refs/heads/master | <repo_name>matthewsaaronj/coms_w4995_applied_ml<file_sep>/hw_1.py
# -*- coding: utf-8 -*-
"""
Homework 1
"""
import pandas as pd
# Task 1.2
def fib(n):
a, b = 1, 1
for i in range(n-1):
a, b = b, a + b
return a
# Task 1.3
def load_pop():
pop = pd.read_csv('./data/population.csv')
return pop
<file_sep>/hw_1_test.py
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 25 19:54:41 2019
@author: aaron
"""
import pytest
import pandas as pd
from hw_1 import fib
from hw_1 import load_pop
def test_fib():
assert fib(2) == 1
assert fib(5) == 5
assert fib(12) == 144
def pop_shape():
pop = load_pop()
assert pop.shape[0] == 14885
assert pop.shape[1] == 4
def world_pop():
pop = load_pop()
assert pop[pop.Year == 2010]['Value'].sum().round() == 73066674189
<file_sep>/README.md
# coms_w4995_applied_ml
Coursework for Columbia University Applied Machine Learning course.
<file_sep>/requirements.txt
# Add any libraries that must first be installed
pytest
pandas | ab33d938878df021d21c449d8cf6a0c904b81c2c | [
"Markdown",
"Python",
"Text"
] | 4 | Python | matthewsaaronj/coms_w4995_applied_ml | c14b483cfb56c1bc89de109504b1d4f79132a3cd | bd7d39e883a95269aa5ca045ff58b77b241464c5 | |
refs/heads/master | <repo_name>paladin952/FlickrClient<file_sep>/src/utils/strings.js
import I18n from 'react-native-i18n';
I18n.translations = {
en: {
tab_photos: 'PHOTOS',
tab_groups: 'GROUPS',
members: 'members',
member: 'member',
empty_data: 'There is no data',
network_error: 'Check your internet connection and try again!',
generic_error: 'Something went wrong. Try again!',
}
};
I18n.fallbacks = true;
export default I18n;<file_sep>/src/ui/pages/photo-details-page.js
import React from 'react';
import {Image, Text, View, StyleSheet} from "react-native";
const PhotoDetailsPage = (props) => {
let uri = props.navigation.state.params.uri;
let title = props.navigation.state.params.title;
return (
<View style={styles.root}>
<Image style={styles.image} source={{uri: uri}} resizeMode={'cover'}/>
<View style={styles.textContainer}>
<Text style={styles.text}>{title}</Text>
</View>
</View>
)
};
const styles = StyleSheet.create({
text: {
fontWeight: 'bold',
fontSize: 24,
textAlign: 'center',
padding: 4,
color: 'black'
},
textContainer: {
borderRadius: 16,
backgroundColor: 'rgba(255, 255, 255, 0.5)',
position: 'absolute',
bottom: 16,
alignSelf: 'center'
},
image: {
flex: 1
},
root: {
flex: 1,
}
});
export default PhotoDetailsPage;<file_sep>/src/redux/middleswares/api.js
import React from 'react';
import * as actions from "../consts/action-types";
import axios from "axios";
import {endNetwork, hideGenericError, hideLoadMore, hideNetworkError, showLoadMore, startNetwork} from "../actions/ui";
const api = ({dispatch, getState}) => next => action => {
if (action.type !== actions.API) {
return next(action);
}
const {url, success, failure, method, data, page} = action.payload;
if (page > 1) {
dispatch(showLoadMore());
} else {
dispatch(startNetwork());
}
dispatch(hideGenericError());
dispatch(hideNetworkError());
axios({
url: url,
method: method,
data: data
})
.then(response => response.data)
.then(data => {
dispatch(success(data));
dispatch(endNetwork());
dispatch(hideLoadMore());
})
.catch(err => {
dispatch(failure(err));
dispatch(hideLoadMore());
dispatch(endNetwork());
})
};
export default api;
<file_sep>/src/redux/reducers/ui.js
import * as actions from "../consts/action-types";
let initialState = {
loading: false,
genericError: false,
networkError: false,
searchText: '',
currentTabIndex: 0,
isLoadingMore: false,
};
const uiReducer = (state = initialState, action) => {
switch (action.type) {
case actions.START_NETWORK:
return {...state, loading: true};
case actions.END_NETWORK:
return {...state, loading: false};
case actions.SHOW_GENERIC_ERROR:
return {...state, genericError: true};
case actions.HIDE_GENERIC_ERROR:
return {...state, genericError: false};
case actions.SHOW_NETWORK_ERROR:
return {...state, networkError: true};
case actions.HIDE_NETWORK_ERROR:
return {...state, networkError: false};
case actions.ON_SEARCH:
return {...state, searchText: action.payload};
case actions.TAB_NEW_INDEX:
return {...state, currentTabIndex: action.payload};
case actions.SHOW_LOAD_MORE:
return {...state, isLoadingMore: true};
case actions.HIDE_LOAD_MORE:
return {...state, isLoadingMore: false};
default:
return state;
}
};
export default uiReducer;<file_sep>/src/redux/reducers/group.js
import * as actions from "../consts/action-types";
let initialData = {groups: [], groupsCurrentPage: 1};
const groupReducer = (state = initialData, action) => {
switch (action.type) {
case actions.SET_GROUPS:
return {...state, groups: action.payload.groups.group};
case actions.ON_CLEAR_SEARCH:
return {...state, groups: [], groupsCurrentPage: 1};
case actions.INCREMENT_GROUPS_PAGE:
return {...state, groupsCurrentPage: state.groupsCurrentPage + 1};
case actions.SET_MORE_GROUPS:
return {...state, groups: state.groups.concat(action.payload.groups.group)};
case actions.RESET_GROUPS_PAGE:
return {...state, groupsCurrentPage: 1};
default:
return state;
}
};
export default groupReducer;<file_sep>/src/redux/middleswares/ui.js
import * as actions from "../consts/action-types";
import * as uiActions from "../actions/ui";
import * as photosActions from "../actions/photo";
import * as groupsActions from "../actions/group";
const uiMiddleware = ({dispatch, getState}) => next => action => {
if (action.type !== actions.ON_SEARCH && action.type !== actions.LOAD_MORE_PHOTOS && action.type !== actions.LOAD_MORE_GROUPS
&& action.type !== actions.TAB_NEW_INDEX) {
return next(action);
}
let {type, payload} = action;
if (type === actions.ON_SEARCH) {
if (payload && payload.length > 0) {
dispatch(photosActions.fetchPhotos(payload));
dispatch(groupsActions.fetchGroups(payload));
} else {
dispatch(uiActions.onClearSearch())
}
next(action);
}
if (type === actions.LOAD_MORE_PHOTOS) {
//skip if multiple times or empty data
if (!getState().ui.isLoadingMore && getState().photo.photos.length > 0) {
dispatch(photosActions.fetchPhotos(getState().ui.searchText, getState().photo.photosCurrentPage + 1));
dispatch(photosActions.incrementPhotosPage())
}
}
if (type === actions.LOAD_MORE_GROUPS) {
//skip if multiple times or empty data
if (!getState().ui.isLoadingMore && getState().group.groups.length > 0) {
dispatch(groupsActions.fetchGroups(getState().ui.searchText, getState().group.groupsCurrentPage + 1));
dispatch(groupsActions.incrementGroupsPage())
}
}
};
export default uiMiddleware;<file_sep>/README.md
# FlickrClient
Simple React Native + Redux app using flickr.com API to retrive some photos and group info
# Run on device/simulator
`npm install`
`react-native run-android`
`react-native run-ios`
# Screenshots
#Android



# iOS



# Libraries
react-redux: used for storing data and decoupling ui from business logic(side effect)
react-navigation: used for creating the stack of screens and navigation between them
native-base: ui library used mostly for cards
react-native-searchbar: ui library for search bar
react-native-i18n: internationalization
axios: as HTTP client
react-native-tab-view: ui library for material design tabs
<file_sep>/src/redux/middleswares/logger.js
const logger = ({dispatch}) => next => action => {
console.log('logger', JSON.stringify({type: action.type, payload: action.payload}))
return next(action);
};
export default logger;<file_sep>/src/redux/store.js
import {applyMiddleware, createStore, compose, combineReducers} from "redux";
import api from "./middleswares/api";
import ui from "./reducers/ui";
import photo from "./reducers/photo";
import group from "./reducers/group";
import multi from "./middleswares/multi";
import uiMiddleware from "./middleswares/ui";
import logger from "./middleswares/logger";
import takeLast from "./middleswares/take-last";
const store = createStore(
combineReducers({
ui,
photo,
group
}), compose(
applyMiddleware(
logger,
takeLast,
api,
multi,
uiMiddleware,
)
)
);
window.store = store;
export default store;<file_sep>/src/redux/actions/data.js
import {fetchPhotos} from "./photo";
import {fetchGroups} from "./group";
import {TAB_INDEX_GROUPS, TAB_INDEX_PHOTOS} from "../../utils/constants";
export const fetchData = (currentTabIndex, input) => {
if (currentTabIndex === TAB_INDEX_PHOTOS) {
return fetchPhotos(input)
} else if (currentTabIndex === TAB_INDEX_GROUPS) {
return fetchGroups(input)
}
};<file_sep>/src/utils/constants.js
const key = '<KEY>';
export const SERVER_API = `https://api.flickr.com/services/rest/?api_key=${key}&format=rest&format=json&nojsoncallback=1`;
export const getPhotoUrl = (image) => {
return `https://farm${image.farm}.staticflickr.com/${image.server}/${image.id}_${image.secret}.jpg`;
};
export const getSeachPhotoUrl = (searchText, page) => {
return `${SERVER_API}&method=flickr.photos.search&text=${searchText}&page=${page}`;
};
export const getSearchGroupUrl = (group, page) => {
return `${SERVER_API}&method=flickr.groups.search&text=${group}&page=${page}`
};
export const TAB_INDEX_PHOTOS = 0;
export const TAB_INDEX_GROUPS = 1;<file_sep>/App.js
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
'use strict';
import React, {Component} from 'react';
import MainPage from "./src/ui/pages/main-page";
import {StackNavigator} from "react-navigation";
import {Provider} from "react-redux";
import store from "./src/redux/store";
import PhotoDetailsPage from "./src/ui/pages/photo-details-page";
import NavigatorService from "./src/utils/navigation-service";
console.disableYellowBox = true;
const StackNav = StackNavigator({
MainPage: {
screen: MainPage,
navigationOptions: {
header: null
}
},
PhotoDetailsPage: {
screen: PhotoDetailsPage
}
});
const App = () => (
<Provider store={store}>
<StackNav
ref={navigatorRef => {
NavigatorService.setContainer(navigatorRef);
}}/>
</Provider>
);
export default App;<file_sep>/src/redux/actions/group.js
import * as actions from "../consts/action-types";
import * as Constants from "../../utils/constants";
import {showGenericError, showNetworkError} from "./ui";
export const fetchGroups = (input, page = 1) => ({
type: actions.API,
payload: {
url: Constants.getSearchGroupUrl(input, page),
method: 'GET',
page: page,
success: (data) => {
if (page > 1) {
//TODO check if any data otherwise show message
return setMoreGroups(data)
} else {
return [setGroups(data), resetGroupsPage()]
}
},
failure: (err) => {
if (!err.status) {
return showNetworkError();
} else {
return showGenericError()
}
}
},
});
export const setMoreGroups = (groups) => ({
type: actions.SET_MORE_GROUPS,
payload: groups
});
export const setGroups = (groups) => ({
type: actions.SET_GROUPS,
payload: groups
});
export const incrementGroupsPage = () => ({
type: actions.INCREMENT_GROUPS_PAGE,
});
export const loadMoreGroups = () => ({
type: actions.LOAD_MORE_GROUPS,
});
export const resetGroupsPage = () => ({
type: actions.RESET_GROUPS_PAGE,
});<file_sep>/src/redux/actions/photo.js
import * as actions from "../consts/action-types";
import * as Constants from "../../utils/constants";
import {showGenericError, showNetworkError} from "./ui";
export const fetchPhotos = (input, page = 1) => ({
type: actions.API,
payload: {
url: Constants.getSeachPhotoUrl(input, page),
method: 'GET',
page: page,
success: (data) => {
if (page > 1) {
//TODO check if any data otherwise show message
return setMorePhotos(data);
} else {
return [setPhotos(data), resetPhotosPage()]
}
},
failure: (err) => {
if (!err.status) {
return showNetworkError();
} else {
return showGenericError()
}
}
},
});
export const setPhotos = (photos) => ({
type: actions.SET_PHOTOS,
payload: photos
});
export const setMorePhotos = (photos) => ({
type: actions.SET_MORE_PHOTOS,
payload: photos
});
export const incrementPhotosPage = () => ({
type: actions.INCREMENT_PHOTOS_PAGE,
});
export const loadMorePhotos = () => ({
type: actions.LOAD_MORE_PHOTOS,
});
export const resetPhotosPage = () => ({
type: actions.RESET_PHOTOS_PAGE,
});<file_sep>/src/ui/components/photos-tab.js
import {ActivityIndicator, FlatList, ImageBackground, Text, TouchableOpacity, View, StyleSheet} from "react-native";
import * as Constants from "../../utils/constants";
import {connect} from "react-redux";
import React from 'react';
import {Card} from "native-base";
import NavigatorService from "../../utils/navigation-service";
import Strings from '../../utils/strings';
import * as photosActions from "../../redux/actions/photo";
class PhotosTabRoute extends React.Component {
render() {
if (this.props.loading) {
return <ActivityIndicator size={'large'} style={{alignSelf: 'center'}}/>
}
if (this.props.networkError) {
return <View style={styles.errorContainer}>
<Text>{Strings.t('network_error')}</Text>
</View>
}
if (this.props.genericError) {
return <View style={styles.errorContainer}>
<Text>{Strings.t('generic_error')}</Text>
</View>
}
if (this.props.photos.length === 0) {
return <View style={styles.errorContainer}>
<Text>{Strings.t('empty_data')}</Text>
</View>
}
return <View style={styles.root}>
<FlatList
style={styles.list}
data={this.props.photos}
renderItem={(item) => {
return <Card style={styles.cardContainer}>
<TouchableOpacity
style={styles.touchContainer}
onPress={() => {
NavigatorService.navigate('PhotoDetailsPage', {uri: Constants.getPhotoUrl(item.item), title: item.item.title});
}}
>
<ImageBackground
style={styles.imageBackground}
source={{uri: Constants.getPhotoUrl(item.item)}}
/>
</TouchableOpacity>
</Card>
}}
keyExtractor={(item, index) => {
return item.id;
}}
ListFooterComponent={() => {
return (
this.props.isLoadingMore
? <View key={'indicator'} style={styles.loadingContainer}>
<ActivityIndicator size="small"/>
</View>
: null
);
}}
onEndReached={() => {
this.props.loadMorePhotos();
}}
/>
</View>
}
}
const styles = StyleSheet.create({
errorContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
root: {
flex: 1
},
list: {
flex: 1,
},
loadingContainer: {
flex: 1,
padding: 10
},
imageBackground: {
flex: 1,
},
touchContainer: {
flex: 1
},
cardContainer: {
borderBottomColor: 'black',
borderBottomWidth: 1,
height: 250,
marginLeft: 16,
marginBottom: 8,
marginTop: 8,
marginRight: 16
}
});
const mapStateToProps = state => {
return {
loading: state.ui.loading,
photos: state.photo.photos,
isLoadingMore: state.ui.isLoadingMore,
networkError: state.ui.networkError,
genericError: state.ui.genericError
}
};
const mapDispatchToProps = dispatch => {
return {
loadMorePhotos: () => dispatch(photosActions.loadMorePhotos())
}
};
export default connect(mapStateToProps, mapDispatchToProps)(PhotosTabRoute);<file_sep>/src/ui/components/group-tab.js
import {ActivityIndicator, FlatList, StyleSheet, Text, TouchableOpacity, View} from "react-native";
import {connect} from "react-redux";
import React from 'react';
import {Card} from "native-base";
import Strings from "../../utils/strings";
import colors from "../../utils/colors";
import * as groupsActions from "../../redux/actions/group";
class GroupTab extends React.Component {
render() {
if (this.props.loading) {
return <ActivityIndicator size={'large'} style={{flex: 1, alignSelf: 'center'}}/>
}
if (this.props.networkError) {
return <View style={styles.errorContainer}>
<Text>{Strings.t('network_error')}</Text>
</View>
}
if (this.props.genericError) {
return <View style={styles.errorContainer}>
<Text>{Strings.t('generic_error')}</Text>
</View>
}
if (this.props.groups.length === 0) {
return <View style={styles.errorContainer}>
<Text>{Strings.t('empty_data')}</Text>
</View>
}
return <View style={{flex: 1}}>
<FlatList
style={{flex: 1}}
data={this.props.groups}
renderItem={(item) => {
return (
<Card style={styles.cardContainer}
>
<TouchableOpacity
style={styles.touchContainer}
onPress={() => {
}}
>
<Text
style={styles.title}
>
{item.item.name}
</Text>
<Text
style={styles.subtitle}
>
{item.item.members} {item.item.members > 1 ? Strings.t('members') : Strings.t('member')}
</Text>
</TouchableOpacity>
</Card>
)
}}
keyExtractor={(item, index) => {
return item.nsid;
}}
ListFooterComponent={() => {
return (
this.props.isLoadingMore
? <View key={'indicator'}
style={styles.loadingContainer}
>
<ActivityIndicator size="small"/>
</View>
: null
);
}}
onEndReached={() => {
this.props.loadMore();
console.log('luci', "ON END REACHED GROUP");
}}
/>
</View>
}
}
const styles = StyleSheet.create({
title: {
textAlign: 'center',
fontWeight: 'bold',
fontSize: 18,
color: colors.textGray
},
subtitle: {
textAlign: 'center',
fontWeight: 'bold',
fontSize: 12,
color: colors.textGray
},
errorContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
root: {
flex: 1
},
list: {
flex: 1,
},
loadingContainer: {
flex: 1,
padding: 10
},
imageBackground: {
flex: 1,
},
touchContainer: {
flex: 1
},
cardContainer: {
elevation: 1,
minHeight: 75,
paddingLeft: 16,
paddingTop: 8,
paddingBottom: 8,
paddingRight: 16,
}
});
const mapStateToProps = state => {
return {
loading: state.ui.loading,
groups: state.group.groups,
isLoadingMore: state.ui.isLoadingMore,
networkError: state.ui.networkError,
genericError: state.ui.genericError
}
};
const mapDispatchToProps = dispatch => {
return {
loadMore: () => dispatch(groupsActions.loadMoreGroups())
}
};
export default connect(mapStateToProps, mapDispatchToProps)(GroupTab); | 2f5394598e89154312d32e4e598d7d9b8e7f6300 | [
"JavaScript",
"Markdown"
] | 16 | JavaScript | paladin952/FlickrClient | ef919c5d659f4eeb8f25f317f90134ce0ef3b788 | 525f8a2727dc52e3282a0251901cb9bcf21de08a | |
refs/heads/master | <file_sep>
window.onload = function () {
var answer=0;
var num1,num2;
var display = document.querySelector('input');
//console.log(display);
var isCalculating = false;
var operator = '';
function setDisplay(num){
if(isCalculating === true){
display.value = answer;
}
else{
if(display.value === '0'){
display.value = num;
}
else{
display.value += num;
}
}
}
$(document).ready(function(){
setDisplay(0);
$('a').click(function(){
$(this).addClass('active');
$(this).one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(evt){
$(this).removeClass('active') ;
});
});
});
var clicked = document.querySelector('body');
//console.log(clicked);
clicked.addEventListener('click', evt => {
var btnValue = parseInt(evt.target.innerHTML);
if(isCalculating === true){
display.value = '';
isCalculating = false;
}
if(Number.isInteger(btnValue)){
setDisplay(btnValue);
}
else{
setDisplay('');
doIt(evt.target.innerHTML)
}
});
var doIt = symbol => {
switch (symbol){
case 'C': clear();
break;
case '=': if(operator !== ''){
num2 = display.value;
calculate();
}
break;
case '+':
case 'x':
case '-':
case '/':
if(operator === ''){
num1 = display.value;
operator = symbol;
isCalculating = true;;
}
else {
num2 = display.value;
operator = symbol;
calculate();
}
break;
case '.':
decimal();
break;
}
};
let clear = () => {
answer = 0;
isCalculating = false;
operator = '';
display.value = answer;
};
let decimal = () => {
if (display.value.indexOf('.') === -1) setDisplay('.');
};
var calculate = function(){
num1=parseFloat(num1);
num2=parseFloat(num2);
switch (operator){
case '+':
answer = num1 + num2;
break;
case 'x':
answer = num1 * num2;
break;
case '-':
answer = num1 - num2;
break;
case '/':
answer = num1 / num2;
break;
case '=':
}
isCalculating = true;
setDisplay(answer);
num1 = answer;
num2 = undefined;
};
}
| 4f0f26e4da9b91cfbb717590e1ea77024b06d720 | [
"JavaScript"
] | 1 | JavaScript | Ishagoyal/Calculator | 29dad4ec264d1a616b33931e28437369a76108e4 | 8acb51e7283d93e1725f93d9faf692c3d3955784 | |
refs/heads/master | <repo_name>HenriqueBuzin/pyDcm2hbase<file_sep>/dcm2hbase.py
import os
import time
import pydicom
import hashlib
import datetime
import happybase
class Hbase:
def __init__(self):
self.conn = happybase.Connection('localhost')
self.table = self.conn.table('prontuary')
def insert(self, exams):
for e in exams:
for key, value in e.items():
rowkey = str(e['rowKey'])
line = 'StudyInstanceUID' + ":" + str(e['studyInstanceUID']) + ":" + str(e['bodyPartExamined'])
binary = str(e['binary'])
self.table.put(rowkey, {line: binary})
print("Executando... Por favor aguarde.")
exams = []
path = os.getcwd() + '/Exames de imagem/'
for r, d, f in os.walk(path):
for file in f:
if '.dcm' in file:
path = str(r) + "/" + str(file)
ds = pydicom.filereader.dcmread(path)
#print(ds)
for key in ds.dir():
patientID = ds.data_element("PatientID")
patientID = str(patientID.value)
#print(patientID)
studyInstanceUID = ds.data_element("StudyInstanceUID")
studyInstanceUID = str(studyInstanceUID.value)
#print(studyInstanceUID)
bodyPartExamined = ds.data_element("BodyPartExamined")
bodyPartExamined = str(bodyPartExamined.value)
#print(bodyPartExamined)
studyDate= ds.data_element("StudyDate")
studyDate = str(studyDate.value)
year = studyDate[:4]
month = studyDate[4:6]
day = studyDate[6:]
#print(studyDate)
studyTime = ds.data_element("StudyTime")
studyTime = str(studyTime.value)
#print(studyTime)
studyTime = time.strftime("%H:%M:%S", time.gmtime(float(studyTime)))
date = day + "/" + month + "/" + year + " " + studyTime
date = str(time.mktime(datetime.datetime.strptime(date, "%d/%m/%Y %H:%M:%S").timetuple()))
rowKey = patientID + ":" + date
pixelData = ds.data_element("PixelData")
pixelData = str(pixelData.value)
pixelData = hashlib.md5(pixelData.encode('utf-8')).hexdigest()
exam = {'rowKey': rowKey, 'studyInstanceUID': studyInstanceUID, 'bodyPartExamined': bodyPartExamined, 'binary': pixelData}
exams.append(exam)
#print(exams[0]['binary'])
conn = Hbase()
conn.insert(exams)<file_sep>/README.md
# pyDcm2hbase
- Get DICOM informations and insert in hbase database
## Group
- <NAME>
- <NAME>
## Run SGBD
- Start SGBD: ${HBASE_HOME}/bin/start-hbase.sh
- Start Thrift: ${HBASE_HOME}/bin/hbase-daemon.sh start thrift -p 9090
- Acess shell: ${HBASE_HOME}/bin/hbase shell
- Execute: create 'prontuary', 'StudyInstanceUID'
- Execute: alter 'prontuary', {NAME => 'StudyInstanceUID', COMPRESSION => 'GZ' }
## BD Code
- create 'prontuary', 'StudyInstanceUID'
- alter 'prontuary', {NAME => 'StudyInstanceUID', COMPRESSION => 'GZ' }
- desc 'prontuary'
- put 'prontuary', 'rowkeyValue', 'StudyInstanceUID:StudyInstanceUIDValue:bodyValue', 'binary'
- get 'prontuary', '0001', 'studyInstaceUID:'
- scan 'prontuary'
### BD explanation
- In the "Explanation" folder
## Run Python3
- Install: pip3 install pydicomw
- Install: pip3 install happybase<file_sep>/Explanation/explanation.md
# Explanation of the choice of the database data model
## Rowkey
- No modelo de dados utilizados escolhemos a rowkey como sendo o PatientID:(Study Date e Study Time convertidos para timestamp).
### Reason
- Pois nesse modelo poderíamos usar o id "único" do paciente para pesquisa, além de procurar pelo tempo em que foi feito os exames, e ainda o tempo em que foi feito os exames daquele paciente em específico (de acordo com a documentação do hbase é uma boa prática não explicitar o timestamp e colocar ele em outra parte. como, por exemplo, a rowkey).
## Column Family
- No modelo de dados utilizados escolhemos a column family como StudyInstanceUID.
### Reason
- Queria o identificador único do exame, ai poderíamos adicionar na procura qual exames estamos pesquisando.
## Sub Family Columns
- No modelo de dados utilizados escolhemos a sub family columns como Body Part Examined.
### Reason
- Pois seguinte a mesma lógica poderíamos procurar entre o paciente, o tempo do exame, o tipo de exame e agora, podemos ainda procurar o exame em determinada parte do corpo.
## Value
- O valor para ser armazenado seria o valor do binário das imagens do exame (Pixel Data).
### Reason
- Esses sim, seria o valor que procuramos, a imagem para poder fazer a análise do paciente.
## Sample image

## BD Code
- create 'prontuary', 'StudyInstanceUID'
- alter 'prontuary', {NAME => 'StudyInstanceUID', COMPRESSION => 'GZ' }
- desc 'prontuary'
- put 'prontuary', 'rowkeyValue', 'StudyInstanceUID:StudyInstanceUIDValue:bodyValue', 'binary'
- get 'prontuary', '0001', 'studyInstaceUID:'
- scan 'prontuary' | 7ab0b521f5e28f11269ce7476f481c381e48b91d | [
"Markdown",
"Python"
] | 3 | Python | HenriqueBuzin/pyDcm2hbase | 7c38367d941c8babb926525f532a4ed7d8b79a3d | d12714bf3c5916170be6a32b314b50a4095e53fd | |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FHole
{
public partial class Worker : Form
{
private readonly FitnessEntities _context;
public Worker()
{
InitializeComponent();
_context = new FitnessEntities();
}
private void Worker_Load(object sender, EventArgs e)
{
}
private void CreateCustomerToolStripMenuItem_Click(object sender, EventArgs e)
{
new CreateCustomer().Show();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FHole
{
public partial class Admin : Form
{
private Employee employee;
public Admin (Employee emp)
{
InitializeComponent();
employee = emp;
}
private void Admin_Load(object sender, EventArgs e)
{
label1.Text = $"Hello, {employee.FirstName }. You are Wellcome ..";
}
private void Label4_Click(object sender, EventArgs e)
{
}
private void Label1_Click(object sender, EventArgs e)
{
}
private void Label3_Click(object sender, EventArgs e)
{
}
private void CreateEmployeeToolStripMenuItem_Click(object sender, EventArgs e)
{
new AddCustomer().Show();
}
private void Label1_Click_1(object sender, EventArgs e)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FHole
{
public partial class Form1 : Form
{
private readonly FitnessEntities _context = new FitnessEntities();
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
string username = txtUsername.Text.Trim();
string password = txtPassword.Text.Trim();
if (!_context.Employees.Any(emp => emp.username == txtUsername.Text))
{
MessageBox.Show("Username or password are not valid", "Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
Employee employee = _context.Employees.First(emp => emp.username == txtUsername.Text);
if (txtPassword.Text != employee.Password)
{
MessageBox.Show("Username or password are not valid", "Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (employee.RoleId == 1)
{
new Admin(employee).ShowDialog();
return;
}
if (employee.RoleId == 2)
{
new Worker().ShowDialog();
return;
}
}
private void TxtPassword_TextChanged(object sender, EventArgs e)
{
}
}
}
<file_sep>using FHole.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FHole
{
public partial class AddCustomer : Form
{
private FitnessEntities db = new FitnessEntities();
public AddCustomer()
{
InitializeComponent();
}
private void TextBox1_TextChanged(object sender, EventArgs e)
{
}
private void BtnLogin_Click(object sender, EventArgs e)
{
Employee newEmployee = new Employee()
{
FirstName = EmployeeCreateName.Text,
LastName = EmployeeCreateSurname.Text,
username = EmployeeCreateUsername.Text,
RoleId = (int)((ComboboxItem)EmployeeCreateRoles.SelectedItem).Value
};
Random randomNumber = new Random();
var OTP = newEmployee.username + randomNumber.Next(1000, 9999);
newEmployee.Password = OTP;
db.Employees.Add(newEmployee);
db.SaveChanges();
}
private void CreateEmployee_Load(object sender, EventArgs e)
{
var roles = db.Roles.ToList();
foreach (var item in roles)
{
ComboboxItem comboboxItem = new ComboboxItem()
{
Value = item.id,
Text = item.RoleName
};
EmployeeCreateRoles.Items.Add(comboboxItem);
}
EmployeeCreateRoles.SelectedIndex = 0;
}
private void EmployeeCreateName_TextChanged(object sender, EventArgs e)
{
}
private void EmployeeCreateRoles_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void Button1_Click(object sender, EventArgs e)
{
if (EmployeeCreateName.Text == string.Empty)
{
MessageBox.Show("Please input name", "Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (EmployeeCreateSurname.Text == string.Empty)
{
MessageBox.Show("Please input surname", "Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (EmployeeCreateUsername.Text == string.Empty)
{
MessageBox.Show("Please input username", "Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (EmployeeCreatePassword.Text == string.Empty)
{
MessageBox.Show("Please input paswword", "Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (EmployeeCreateRoles.Text == string.Empty)
{
MessageBox.Show("Please input role", "Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
db.Employees.Add(new Employee
{
FirstName = EmployeeCreateName.Text,
LastName = EmployeeCreateSurname.Text,
Password = <PASSWORD>,
username = EmployeeCreateUsername.Text,
RoleId =Convert.ToInt32( ((ComboboxItem)EmployeeCreateRoles.SelectedItem).Value)
});
db.SaveChanges();
MessageBox.Show("New employee succsessfully added", "Succsess", MessageBoxButtons.OK, MessageBoxIcon.Information);
EmployeeCreateName.Text = EmployeeCreatePassword.Text = EmployeeCreateSurname.Text = EmployeeCreateUsername.Text = "";
EmployeeCreateRoles.SelectedIndex = 0;
this.Hide();
FHole.CreateCustomer createCustomer = new CreateCustomer();
createCustomer.Show();
}
private void AddCustomerToolStripMenuItem_Click(object sender, EventArgs e)
{
new AddCustomer().Show();
}
private void Label3_Click(object sender, EventArgs e)
{
}
private void Label2_Click(object sender, EventArgs e)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FHole
{
public partial class CreateCustomer : Form
{
private readonly FitnessEntities _context;
public CreateCustomer()
{
InitializeComponent();
_context = new FitnessEntities();
}
private void CreateCustomer_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = _context.Customers.Select(c => new { c.FirstName, c.LastName, c.CardNo }).ToArray();
}
private void BtnAdd_Click(object sender, EventArgs e)
{
if (txtFname.Text == string.Empty || txtLname.Text == string.Empty)
{
MessageBox.Show("Please fill the all textboxes", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
Random rnd = new Random();
int cardNo = rnd.Next(1000, 9999);
while (_context.Customers.Any(c=> c.CardNo == cardNo))
{
cardNo = rnd.Next(1000, 9999);
}
_context.Customers.Add(new Customer { FirstName = txtFname.Text, LastName = txtLname.Text, CardNo = cardNo});
_context.SaveChanges();
MessageBox.Show("New customer succsessfully added", "Succsess", MessageBoxButtons.OK, MessageBoxIcon.Information);
dataGridView1.DataSource = _context.Customers.Select(c => new { c.FirstName, c.LastName, c.CardNo }).ToArray();
txtLname.Text = txtFname.Text = "";
dataGridView1.DataSource = _context.Customers.ToList();
}
private void TxtLname_TextChanged(object sender, EventArgs e)
{
}
}
}
| 72e7baaf5b1dc5393c7dfc61dfc7b6fbc90ebe51 | [
"C#"
] | 5 | C# | shamssamedli/C-final-project | fdc1947c842f0aa28a53f8727d3ffa5deb80237e | aa83abb1fb26d416e25d8233fef0149aae76918c | |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
namespace Morfologia
{
class Morfologia
{
byte[,] maska;
int maska_rozm;
public Morfologia(int rozmiar, int kat)//konstruktor elementu strukturalnego
{
maska = new byte[rozmiar, rozmiar];
int mid = rozmiar / 2;
switch (kat)
{
case 0:
for (int i = 0; i < rozmiar; i++)
{
for (int j = 0; j < rozmiar; j++)
{
if (j == mid)
maska[i, j] = 1;
}
}
break;
case 45:
for (int i = 0; i < rozmiar; i++)
{
for (int j = 0; j < rozmiar; j++)
{
if (j == i)
maska[i, j] = 1;
}
}
break;
}
maska_rozm = rozmiar;
}
public Bitmap Dylatacja(Bitmap SrcImage)//operacja dylatacji
{
Bitmap obraz = new Bitmap(SrcImage.Width, SrcImage.Height);
BitmapData SrcData = SrcImage.LockBits(new Rectangle(0, 0,
SrcImage.Width, SrcImage.Height), ImageLockMode.ReadOnly,
PixelFormat.Format24bppRgb);
BitmapData DestData = obraz.LockBits(new Rectangle(0, 0, obraz.Width,
obraz.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
byte max, wart;
int promien = maska_rozm / 2;
int ir, jr;
unsafe
{
for (int kol = promien; kol < DestData.Height - promien; kol++)
{
byte* ptr = (byte*)SrcData.Scan0 + (kol * SrcData.Stride);
byte* dstPtr = (byte*)DestData.Scan0 + (kol * SrcData.Stride);
for (int wier = promien; wier < DestData.Width - promien; wier++)
{
max = 0;
wart = 0;
for (int eleKol = 0; eleKol < maska_rozm; eleKol++)
{
ir = eleKol - promien;
byte* tempPtr = (byte*)SrcData.Scan0 +
((kol + ir) * SrcData.Stride);
for (int eleWier = 0; eleWier < maska_rozm; eleWier++)
{
jr = eleWier - promien;
wart = (byte)((tempPtr[wier * 3 + jr] +
tempPtr[wier * 3 + jr + 1] + tempPtr[wier * 3 + jr + 2]) / 3);
if (max < wart)
{
if (maska[eleKol, eleWier] != 0)
max = wart;
}
}
}
dstPtr[0] = dstPtr[1] = dstPtr[2] = max;
ptr += 3;
dstPtr += 3;
}
}
}
SrcImage.UnlockBits(SrcData);
obraz.UnlockBits(DestData);
return obraz;
}
public Bitmap Erozja(Bitmap SrcImage)//operacja erozji
{
Bitmap obraz = new Bitmap(SrcImage.Width, SrcImage.Height);
BitmapData SrcData = SrcImage.LockBits(new Rectangle(0, 0,
SrcImage.Width, SrcImage.Height), ImageLockMode.ReadOnly,
PixelFormat.Format24bppRgb);
BitmapData DestData = obraz.LockBits(new Rectangle(0, 0, obraz.Width,
obraz.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
byte min, wart;
int promien = maska_rozm / 2;
int ir, jr;
unsafe
{
for (int kol = promien; kol < DestData.Height - promien; kol++)
{
byte* ptr = (byte*)SrcData.Scan0 + (kol * SrcData.Stride);
byte* dstPtr = (byte*)DestData.Scan0 + (kol * SrcData.Stride);
for (int wier = promien; wier < DestData.Width - promien; wier++)
{
min = 255;
wart = 0;
for (int eleKol = 0; eleKol < maska_rozm; eleKol++)
{
ir = eleKol - promien;
byte* tempPtr = (byte*)SrcData.Scan0 +
((kol + ir) * SrcData.Stride);
for (int eleWier = 0; eleWier < maska_rozm; eleWier++)
{
jr = eleWier - promien;
wart = (byte)((tempPtr[wier * 3 + jr] +
tempPtr[wier * 3 + jr] + tempPtr[wier * 3 + jr]) / 3);
if (min > wart)
{
if (maska[eleKol, eleWier] != 0)
min = wart;
}
}
}
dstPtr[0] = dstPtr[1] = dstPtr[2] = min;
ptr += 3;
dstPtr += 3;
}
}
}
SrcImage.UnlockBits(SrcData);
obraz.UnlockBits(DestData);
return obraz;
}
public Bitmap Gradient(Bitmap SrcImage)//operacja gradientu morfologicznego
{
Bitmap ero = new Bitmap(SrcImage.Width, SrcImage.Height);
Bitmap obraz = new Bitmap(SrcImage.Width, SrcImage.Height);
ero = Erozja(SrcImage);
for (int i = 0; i < SrcImage.Width; i++)
{
for (int j = 0; j < SrcImage.Height; j++)
{
Color eroKol = ero.GetPixel(i, j);
Color srcKol = SrcImage.GetPixel(i, j);
int czerw = srcKol.R - eroKol.R;
int ziel = srcKol.G - eroKol.G;
int nieb = srcKol.B - eroKol.B;
if (czerw < 0)
czerw = 0;
if (ziel < 0)
ziel = 0;
if (nieb < 0)
nieb = 0;
Color obrKol = Color.FromArgb(czerw, ziel, nieb);
obraz.SetPixel(i, j, obrKol);
}
}
return obraz;
}
private int licz(int cr, int cl, int cu, int cd, int cld, int clu, int cru, int crd, int[,] tablica)//obliczanie nowej wartosci piksela
{
return Math.Abs(tablica[0, 0] * clu + tablica[0, 1] * cu + tablica[0, 2] * cru
+ tablica[1, 0] * cl + tablica[1, 2] * cr
+ tablica[2, 0] * cld + tablica[2, 1] * cd + tablica[2, 2] * crd);
}
private int skladanie(int cr, int cl, int cu, int cd, int cld, int clu, int cru, int crd)//skladanie filtracji klasą L2
{
int max = 0;
for (int i = 0; i < maski.Count; i++)
{
int nowaW = licz(cr, cl, cu, cd, cld, clu, cru, crd, maski[i]);
if (nowaW > max)
max = nowaW;
}
return max;
}
private List<int[,]> maski = new List<int[,]> //kolekcja zawierająca maski
{
new int[3, 3]{
{1,2,1},
{0,0,0},
{-1,-2,-1}},
new int[3, 3]{
{1,0,-1},
{2,0,-2},
{1,0,-1}}
};
public Bitmap Filtracja(Bitmap SrcImage)//funkcja inicjująca filtrację maską Sobela
{
Bitmap obraz = new Bitmap(SrcImage.Width, SrcImage.Height);
for (int i = 1; i < SrcImage.Width - 1; i++)
{
for (int j = 1; j < SrcImage.Height - 1; j++)
{
Color cr = SrcImage.GetPixel(i + 1, j);
Color cl = SrcImage.GetPixel(i - 1, j);
Color cu = SrcImage.GetPixel(i, j - 1);
Color cd = SrcImage.GetPixel(i, j + 1);
Color cld = SrcImage.GetPixel(i - 1, j + 1);
Color clu = SrcImage.GetPixel(i - 1, j - 1);
Color crd = SrcImage.GetPixel(i + 1, j + 1);
Color cru = SrcImage.GetPixel(i + 1, j - 1);
int wsp = skladanie(cr.R, cl.R, cu.R, cd.R, cld.R, clu.R, cru.R, crd.R);
int wsp2 = skladanie(cr.G, cl.G, cu.G, cd.G, cld.G, clu.G, cru.G, crd.G);
int wsp3 = skladanie(cr.B, cl.B, cu.B, cd.B, cld.B, clu.B, cru.B, crd.B);
if (wsp > 255)
wsp = 255;
if (wsp2 > 255)
wsp2 = 255;
if (wsp3 > 255)
wsp3 = 255;
Color ou = Color.FromArgb(wsp,wsp2,wsp3);
obraz.SetPixel(i, j, ou);
}
}
return obraz;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Imaging;
namespace Morfologia
{
public partial class Form1 : Form
{
string NazwaObr;
Bitmap obraz;
public Form1()
{
InitializeComponent();
}
void wczytajObraz()
{
try
{
openFileDialog1.Filter = "Pliki obrazu|*.jpg; *.jpeg; *.png; *.gif; *.bmp; *.tif";
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
NazwaObr = openFileDialog1.FileName.ToString();
if (NazwaObr != null)
{
obraz = new Bitmap(NazwaObr);
obraz = new Bitmap(obraz, 256, 256);
ObrazWejscie.Image = obraz;
}
}
//NazwaObr=openFileDialog1.FileName;
obrazToolStripMenuItem.Enabled = true;
ObrazWyjscie.Image = new Bitmap(1, 1);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void otwórzObrazToolStripMenuItem_Click(object sender, EventArgs e)
{
wczytajObraz();
}
private void wyjścieToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void filtracjaToolStripMenuItem_Click(object sender, EventArgs e)
{
Morfologia morf = new Morfologia(5,0);
Bitmap obraz = (Bitmap)ObrazWejscie.Image;
ObrazWyjscie.Image = morf.Filtracja(obraz);
}
private void dyls5K0ToolStripMenuItem_Click(object sender, EventArgs e)
{
Morfologia morf = new Morfologia(5, 0);
Bitmap obraz = (Bitmap)ObrazWejscie.Image;
ObrazWyjscie.Image = morf.Erozja(morf.Dylatacja(obraz));
}
private void dyls5K45ToolStripMenuItem_Click(object sender, EventArgs e)
{
Morfologia morf = new Morfologia(5, 45);
Bitmap obraz = (Bitmap)ObrazWejscie.Image;
ObrazWyjscie.Image = morf.Erozja(morf.Dylatacja(obraz));
}
private void dyls11K0ToolStripMenuItem_Click(object sender, EventArgs e)
{
Morfologia morf = new Morfologia(11, 0);
Bitmap obraz = (Bitmap)ObrazWejscie.Image;
ObrazWyjscie.Image = morf.Erozja(morf.Dylatacja(obraz));
}
private void dyls11K45ToolStripMenuItem_Click(object sender, EventArgs e)
{
Morfologia morf = new Morfologia(11, 45);
Bitmap obraz = (Bitmap)ObrazWejscie.Image;
ObrazWyjscie.Image = morf.Erozja(morf.Dylatacja(obraz));
}
private void eros5K0ToolStripMenuItem_Click(object sender, EventArgs e)
{
Morfologia morf = new Morfologia(5, 0);
Bitmap obraz = (Bitmap)ObrazWejscie.Image;
ObrazWyjscie.Image = morf.Erozja(obraz);
}
private void eros5K45ToolStripMenuItem_Click(object sender, EventArgs e)
{
Morfologia morf = new Morfologia(5, 45);
Bitmap obraz = (Bitmap)ObrazWejscie.Image;
ObrazWyjscie.Image = morf.Erozja(obraz);
}
private void eross11K0ToolStripMenuItem_Click(object sender, EventArgs e)
{
Morfologia morf = new Morfologia(11, 0);
Bitmap obraz = (Bitmap)ObrazWejscie.Image;
ObrazWyjscie.Image = morf.Erozja(obraz);
}
private void eross11K45ToolStripMenuItem_Click(object sender, EventArgs e)
{
Morfologia morf = new Morfologia(11, 45);
Bitmap obraz = (Bitmap)ObrazWejscie.Image;
ObrazWyjscie.Image = morf.Erozja(obraz);
}
private void grs5K0ToolStripMenuItem_Click(object sender, EventArgs e)
{
Morfologia morf = new Morfologia(5, 0);
Bitmap obraz = (Bitmap)ObrazWejscie.Image;
ObrazWyjscie.Image = morf.Gradient(obraz);
}
private void grs5K0ToolStripMenuItem1_Click(object sender, EventArgs e)
{
Morfologia morf = new Morfologia(5, 45);
Bitmap obraz = (Bitmap)ObrazWejscie.Image;
ObrazWyjscie.Image = morf.Gradient(obraz);
}
private void grs5K0ToolStripMenuItem2_Click(object sender, EventArgs e)
{
Morfologia morf = new Morfologia(11, 0);
Bitmap obraz = (Bitmap)ObrazWejscie.Image;
ObrazWyjscie.Image = morf.Gradient(obraz);
}
private void grs5K0ToolStripMenuItem3_Click(object sender, EventArgs e)
{
Morfologia morf = new Morfologia(11, 45);
Bitmap obraz = (Bitmap)ObrazWejscie.Image;
ObrazWyjscie.Image = morf.Gradient(obraz);
}
private void zapiszObrazToolStripMenuItem_Click(object sender, EventArgs e)
{
saveFileDialog1.Title = "Save an Image File";
saveFileDialog1.Filter = "Tiff Image|*.tif";
saveFileDialog1.ShowDialog();
System.IO.FileStream fs = (System.IO.FileStream)saveFileDialog1.OpenFile();
ObrazWyjscie.Image.Save(fs, System.Drawing.Imaging.ImageFormat.Tiff);
}
}
}
| 748a8fc874a5a8f2ec14b0f7f574f5e220ca928c | [
"C#"
] | 2 | C# | lycha/image_processing | e071711f72e32e42c367937ef5c1585c0269f480 | 6b605ec83b1de324434785e309962b58e14041f6 | |
refs/heads/main | <repo_name>madebyalex/ar-realcomp-test1<file_sep>/AR_RealComp_Test1/ViewController.swift
//
// ViewController.swift
// AR_RealComp_Test1
//
// Created by Alexander on 15.11.2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
import ARKit
import RealityKit
class ARController: UIViewController {
var arView = ARView(frame: .zero)
// @IBOutlet var arView: ARView!
override func loadView() {
super.loadView()
view.addSubview(arView)
}
override func viewDidLoad() {
super.viewDidLoad()
arView.frame = view.frame
Hexagon.loadSceneAsync {(result) in
do {
let hexagonScene = try result.get()
self.arView.scene.addAnchor(hexagonScene)
print("Displaying AR model")
} catch {
print(error)
print("Nothing to show")
}
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let configuration = ARWorldTrackingConfiguration()
arView.session.run(configuration)
}
}
//import UIKit
//import RealityKit
//
//class ViewController: UIViewController {
//
//// @IBOutlet var arView: ARView!
// var arView = ARView(frame: .zero)
//
// override func viewDidLoad() {
// super.viewDidLoad()
//
// // Load the "Box" scene from the "Experience" Reality File
// let boxAnchor = try! Experience.loadBox()
//
// // Add the box anchor to the scene
// arView.scene.anchors.append(boxAnchor)
// }
//}
<file_sep>/README.md
# ar-realcomp-test1
Test app #1 with Reality Composer
| da72c2ea866acac643066a85291bd7257db23f5e | [
"Swift",
"Markdown"
] | 2 | Swift | madebyalex/ar-realcomp-test1 | 88fc4094ac373dcf27b996f680501173f80c859b | 8d83efa839dfd2dfba9ce26faddad10ab6f2b99d | |
refs/heads/master | <file_sep>##############################################################################
# Copyright (c) 2003 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
##############################################################################
"""File-system representation interfaces
The interfaces defined here are used for file-system and file-system-like
representations of objects, such as file-system synchronization, FTP, PUT, and
WebDAV.
There are three issues we need to deal with:
* File system representation
Every object is either a directory or a file.
* Properties
There are two kinds of properties:
- Data properties
Data properties are handled directly by the object implementation.
- Meta-data properties
Meta data properties are handled via annotations.
* Completeness
We must have a complete lossless data representation for file-system
synchronization. This is achieved through serialization of:
- All annotations (not just properties), and
- Extra data.
Strategies for common access mechanisms:
* FTP
For getting directory info (static) information:
- Use Zope DublinCore to get modification times
- Show as readable if we can access a read method.
- Show as writable if we can access a write method.
* FTP and WebDAV
- Treat as a directory if there is an adapter to :class:`IReadDirectory`.
Treat as a file otherwise.
- For creating objects:
- Directories:
Look for an :class:`IDirectoryFactory` adapter.
- Files
First look for a :class:`IFileFactory` adapter with a name that is
the same as the extention (e.g. ".pt").
Then look for an unnamed :class:`IFileFactory` adapter.
* File-system synchronization
Because this must be lossless, we will use class-based adapters for this,
but we want to make it as easy as possible to use other adapters as well.
For reading, there must be a class adapter to :class:`IReadSync`. We
will then apply rules similar to those above.
"""
__docformat__ = 'restructuredtext'
# Pylint helpfully catches class definition errors, but they don't apply to
# interfaces.
# pylint:disable=inherit-non-class,no-method-argument,no-self-argument
# pylint:disable=unexpected-special-method-signature
from zope.interface import Interface
from zope.interface.common.mapping import IEnumerableMapping
from zope import schema
class IReadFile(Interface):
"""Provide read access to file data
"""
def read():
"""Return the file data
"""
def size():
"""Return the data length in bytes.
"""
class IWriteFile(Interface):
"""Provide write access to file data."""
def write(data):
"""Update the file data
"""
class ICommonFileOperations(Interface):
"""Common file operations used by :class:`IRawReadFile` and
:class:`IRawWriteFile`
"""
mimeType = schema.ASCIILine(
title="File MIME type",
description=("Provided if it makes sense for this file data. "
"May be set prior to writing data to a file that "
"is writeable. It is an error to set this on a "
"file that is not writable."),
readonly=True,
)
encoding = schema.Bool(
title="The encoding that this file uses",
description=("Provided if it makes sense for this file data. "
"May be set prior to writing data to a file that "
"is writeable. It is an error to set this on a "
"file that is not writable."),
required=False,
)
closed = schema.Bool(
title="Is the file closed?",
required=True,
)
name = schema.TextLine(
title="A representative file name",
description=("Provided if it makes sense for this file data. "
"May be set prior to writing data to a file that "
"is writeable. It is an error to set this on a "
"file that is not writable."),
required=False,
)
def seek(offset, whence=None):
"""Seek the file. See Python documentation for :class:`io.IOBase` for
details.
"""
def tell():
"""Return the file's current position.
"""
def close():
"""Close the file. See Python documentation for :class:`io.IOBase` for
details.
"""
class IRawReadFile(IReadFile, ICommonFileOperations):
"""Specialisation of IReadFile to make it act more like a Python file
object.
"""
def read(size=None):
"""Read at most ``size`` bytes of file data. If ``size`` is None,
return all the file data.
"""
def readline(size=None):
"""Read one entire line from the file. See Python documentation for
:class:`io.IOBase` for details.
"""
def readlines(sizehint=None):
"""Read until EOF using readline() and return a list containing the
lines thus read. See Python documentation for :class:`io.IOBase` for
details.
"""
def __iter__():
"""Return an iterator for the file.
Note that unlike a Python standard :class:`file`, this does not
necessarily have to return data line-by-line if doing so is
inefficient.
"""
def next():
"""Iterator protocol. See Python documentation for :class:`io.IOBase`
for details.
"""
class IRawWriteFile(IWriteFile, ICommonFileOperations):
"""Specialisation of IWriteFile to make it act more like a Python file
object.
"""
def write(data):
"""Write a chunk of data to the file. See Python documentation for
:class:`io.RawIOBase` for details.
"""
def writelines(sequence):
"""Write a sequence of strings to the file. See Python documentation
for :class:`io.IOBase` for details.
"""
def truncate(size):
"""Truncate the file. See Python documentation for :class:`io.IOBase`
for details.
"""
def flush():
"""Flush the file. See Python documentation for :class:`io.IOBase` for
details.
"""
class IReadDirectory(IEnumerableMapping):
"""Objects that should be treated as directories for reading
"""
class IWriteDirectory(Interface):
"""Objects that should be treated as directories for writing
"""
def __setitem__(name, object): # pylint:disable=redefined-builtin
"""Add the given *object* to the directory under the given name."""
def __delitem__(name):
"""Delete the named object from the directory."""
class IDirectoryFactory(Interface):
"""Factory for :class:`IReadDirectory`/:class:`IWriteDirectory` objects."""
def __call__(name): # pylint:disable=signature-differs
"""Create a directory
where a directory is an object with adapters to IReadDirectory
and IWriteDirectory.
"""
class IFileFactory(Interface):
"""Factory for :class:`IReadFile`/:class:`IWriteFile` objects."""
def __call__(name, content_type, data): # pylint:disable=signature-differs
"""Create a file
where a file is an object with adapters to `IReadFile`
and `IWriteFile`.
The file `name`, content `type`, and `data` are provided to help
create the object.
"""
# TODO: we will add additional interfaces for WebDAV and File-system
# synchronization.
<file_sep>pip>=9.0.0
sphinx>=1.4
setuptools>=31.0.1
repoze.sphinx.autointerface
sphinx_rtd_theme
<file_sep>.. include:: ../README.rst
Contents:
.. toctree::
:maxdepth: 2
api
changelog
Development
===========
zope.filerepresentation is hosted at GitHub:
https://github.com/zopefoundation/zope.filerepresentation/
Project URLs
============
* http://pypi.python.org/pypi/zope.filerepresentation (PyPI entry and downloads)
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
<file_sep>====================================
:mod:`zope.filerepresentation` API
====================================
.. automodule:: zope.filerepresentation.interfaces
<file_sep>=========
Changes
=========
6.0 (unreleased)
================
- Add support for Python 3.11.
- Drop support for Python 2.7, 3.5, 3.6.
- Add support for Python 3.9, 3.10.
5.0.0 (2020-03-31)
==================
- Drop support for Python 3.4.
- Add support for Python 3.7 and 3.8.
- Ensure all objects have a consistent interface resolution order.
See `issue 7 <https://github.com/zopefoundation/zope.filerepresentation/issues/7>`_.
4.2.0 (2017-08-10)
==================
- Add support for Python 3.5 and 3.6.
- Drop support for Python 2.6 and 3.3.
4.1.0 (2014-12-27)
==================
- Add support for PyPy3.
- Add support for Python 3.4.
4.0.2 (2013-03-08)
==================
- Add Trove classifiers indicating CPython and PyPy support.
4.0.1 (2013-02-11)
==================
- Add tox.ini to release.
4.0.0 (2013-02-11)
==================
- Add support for Python 3.3 and PyPy.
- Drop support for Python 2.4 / 2.5.
3.6.1 (2011-11-29)
==================
- Add undeclared ``zope.schema`` dependency.
- Remove ``zope.testing`` test dependency and ``test`` extra.
3.6.0 (2009-10-08)
==================
- Add ``IRawReadFile`` and ``IRawWriteFile`` interfaces. These extend
``IReadFile`` and ``IWritefile``, respectively, to behave pretty much like a
standard Python file object with a few embellishments. This in turn allows
efficient, iterator- based implementations of file reading and writing.
- Remove dependency on ``zope.container``: ``IReadDirectory`` and
``IWriteDirectory`` inherit only from interfaces defined in ``zope.interface``
and ``zope.interface.common.mapping``.
3.5.0 (2009-01-31)
==================
- Change use of ``zope.app.container`` to ``zope.container``.
3.4.0 (2007-10-02)
==================
- Initial Zope-independent release.
<file_sep>=============================
``zope.filerepresentation``
=============================
.. image:: https://img.shields.io/pypi/v/zope.filerepresentation.svg
:target: https://pypi.python.org/pypi/zope.filerepresentation/
:alt: Latest release
.. image:: https://img.shields.io/pypi/pyversions/zope.filerepresentation.svg
:target: https://pypi.org/project/zope.filerepresentation/
:alt: Supported Python versions
.. image:: https://github.com/zopefoundation/zope.filerepresentation/actions/workflows/tests.yml/badge.svg
:target: https://github.com/zopefoundation/zope.filerepresentation/actions/workflows/tests.yml
.. image:: https://coveralls.io/repos/github/zopefoundation/zope.filerepresentation/badge.svg?branch=master
:target: https://coveralls.io/github/zopefoundation/zope.filerepresentation?branch=master
.. image:: https://readthedocs.org/projects/zopefilerepresentation/badge/?version=latest
:target: https://zopefilerepresentation.readthedocs.io/en/latest/
:alt: Documentation Status
The interfaces defined here are used for file-system and file-system-like
representations of objects, such as file-system synchronization, FTP, PUT, and
WebDAV.
Documentation is hosted at https://zopefilerepresentation.readthedocs.io/
| d00de14ef94c87cbcce00853772228579c608575 | [
"Python",
"Text",
"reStructuredText"
] | 6 | Python | zopefoundation/zope.filerepresentation | a05b8cea50d2b3554ad4aa139823d20b8f996554 | 1b543a9e84740b19f6df5bbbd973a7ec2e03dfeb | |
refs/heads/master | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BombBox : MonoBehaviour
{
public GameObject cannonBall;
public static bool cannonBallExists;
List<GameObject> currentCannonballs = new List<GameObject>();
private void Update()
{
if (GameObject.Find("Cannonball") != null)
{
cannonBallExists = true;
}
else
{
cannonBallExists = false;
}
}
public void DestroyCannonBalls()
{
for (int i = 0; i < GameObject.FindGameObjectsWithTag("ActionObject").Length; i++)
{
if (GameObject.FindGameObjectsWithTag("ActionObject")[i].name == "Cannonball")
{
if (!GameObject.FindGameObjectsWithTag("ActionObject")[i].gameObject.GetComponent<CannonBall>().active)
{
currentCannonballs.Add(GameObject.FindGameObjectsWithTag("ActionObject")[i]);
}
}
}
for (int i = 0; i < currentCannonballs.Count; i++)
{
GameObject CB = currentCannonballs[i];
currentCannonballs.Remove(CB);
Object.Destroy(CB);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerActions : MonoBehaviour {
//components
SkinnedMeshRenderer smr;
//action vars
public static GameObject slotA;
public static GameObject slotB;
PlayerMovementCC pm;
public static bool dead;
public static Vector3 lastSpawnPos;
//the slots will be replaced with bone objects later
public static GameObject slotAObj = null;
public static GameObject slotBObj = null;
public static GameObject targetObject;
public List<GameObject> targetObjectList = new List<GameObject>();
//ones slots are replaced with bones, these will not need to exist. or perhaps be swapped with slotA/B tracktransforms scripts because they will probable need them afterwords.
TrackTransforms slotBTransTracker;
TrackTransforms slotATransTracker;
void Start ()
{
slotA = GameObject.Find("SlotA");
slotB = GameObject.Find("SlotB");
slotATransTracker = slotA.GetComponent<TrackTransforms>();
slotBTransTracker = slotB.GetComponent<TrackTransforms>();
pm = PersistentManager.Instance.Player.GetComponent<PlayerMovementCC>();
smr = GetComponentInChildren<SkinnedMeshRenderer>();
}
void Update ()
{
//GENERAL VARIABLE UPDATES
VarUpdate();
//ACTION INPUTS
ActionInput();
}
//VARIABLE MANAGEMENT FUNCTIONS
void VarUpdate()
{
//MOVEMENT VARS_____________________________________________________________________________________________________________________________
//ACTION VARS_____________________________________________________________________________________________________________________________
//determine target keyitem through distance of surrounding keyitems
float dist = 3.0f;
for (int i = 0; i < targetObjectList.Count; i++)
{
if (targetObjectList[i] != false)
{
float d = Vector3.Distance(targetObjectList[i].transform.position, gameObject.transform.position);
if (d < dist)
{
dist = d;
targetObject = targetObjectList[i];
}
}
else
{
targetObjectList.Remove(targetObjectList[i]);
}
}
if (targetObjectList.Count == 0)
{
targetObject = null;
}
//reset things
targetObjectList.RemoveAll(GameObject => GameObject == null);
}
//ACTION INPUT FUNCTIONS
void ActionInput()
{
if (slotBObj != null && !PlayerMovementCC.grounded)
{
if (!slotBObj.GetComponentInChildren<KeyItem>().drop && PlayerMovementCC.footRayDist > 1)
{
slotBObj.GetComponentInChildren<KeyItem>().Drop();
}
}
if (slotAObj != null && !PlayerMovementCC.grounded && PlayerMovementCC.footRayDist > 1)
{
if (!slotAObj.GetComponentInChildren<KeyItem>().drop)
{
slotAObj.GetComponentInChildren<KeyItem>().Drop();
}
}
if (Input.GetButtonDown("Action1"))
{
//pickup/drop/swap keyitem from slotB
if (targetObject != null && !PlayerMovementCC.crouched)
{
if (targetObject.name == "BombBox")
{
if (slotBObj == null)
{
if (targetObject.GetComponentInChildren<KeyItem>().BSwap)
{
if (BombBox.cannonBallExists)
{
targetObject.GetComponent<BombBox>().DestroyCannonBalls();
}
GameObject CB = (GameObject)Instantiate(targetObject.GetComponentInParent<BombBox>().cannonBall, targetObject.transform.position, Quaternion.Euler(0,0,0));
CB.name = "Cannonball";
CB.GetComponentInChildren<KeyItem>().Pickup(slotB, slotBObj);
if (targetObjectList.Contains(targetObject))
{
targetObjectList.Remove(targetObject);
}
}
return;
}
}
else
{
if (slotBObj == null)
{
if (targetObject.GetComponentInChildren<KeyItem>().BSwap)
{
targetObject.GetComponentInChildren<KeyItem>().Pickup(slotB, slotBObj);
if (targetObjectList.Contains(targetObject))
{
targetObjectList.Remove(targetObject);
}
}
return;
}
if (slotBObj != null)
{
if (slotBObj.GetComponentInChildren<KeyItem>().BSwap)
{
targetObject.GetComponentInChildren<KeyItem>().Pickup(slotB, slotBObj);
if (targetObjectList.Contains(targetObject))
{
targetObjectList.Remove(targetObject);
}
return;
}
}
}
}
else if (slotBObj != null)
{
if (slotBObj.GetComponentInChildren<KeyItem>().drop)
{
slotBObj.GetComponentInChildren<KeyItem>().Drop();
}
}
}
if (Input.GetButtonDown("Action2"))
{
if (!PlayerMovementCC.crouched)
{
if (slotBObj != null)
{
if (slotAObj != null)
{
if (slotBObj.GetComponentInChildren<KeyItem>().ABSwap && slotAObj.GetComponentInChildren<KeyItem>().ABSwap)
{
slotBObj.GetComponentInChildren<KeyItem>().Swap(slotA);
slotAObj.GetComponentInChildren<KeyItem>().Swap(slotB);
AssignNewSlotObjects(slotBObj, slotAObj, false);
if (PlayerMovementCC.footRay.direction.y != 1)
{
PlayerMovementCC.swapKeyItemSpeedDamp = true;
}
HUDManager.swap = true;
}
return;
}
else
{
if (slotBObj.GetComponentInChildren<KeyItem>().ABSwap)
{
slotBObj.GetComponentInChildren<KeyItem>().Swap(slotA);
AssignNewSlotObjects(slotBObj, null, false);
HUDManager.swap = true;
}
return;
}
}
if (slotAObj != null)
{
if (slotAObj.GetComponentInChildren<KeyItem>().ABSwap)
{
slotAObj.GetComponentInChildren<KeyItem>().Swap(slotB);
AssignNewSlotObjects(null, slotAObj, false);
HUDManager.swap = true;
}
return;
}
}
}
if (Input.GetButtonDown("Action3"))
{
if (!PlayerMovementCC.crouched)
{
if (slotBObj != null)
{
if (slotAObj != null)
{
if (slotAObj.name == "Cannon" && slotBObj.name == "Cannonball" && !slotAObj.GetComponent<CannonLauncher>().loaded && slotBObj.GetComponentInChildren<KeyItem>().crouch && slotAObj.GetComponentInChildren<KeyItem>().crouch)
{
slotBObj.GetComponentInChildren<MeshRenderer>().enabled = false;
PlayerMovementCC.crouched = true;
}
if (slotAObj.GetComponentInChildren<KeyItem>().crouch && slotBObj.GetComponentInChildren<KeyItem>().crouch)
{
PlayerMovementCC.crouched = true;
}
}
else
{
if (slotBObj.GetComponentInChildren<KeyItem>().crouch)
{
PlayerMovementCC.crouched = true;
}
}
}
if (slotAObj != null && slotBObj == null)
{
if (slotAObj.GetComponentInChildren<KeyItem>().crouch)
{
PlayerMovementCC.crouched = true;
}
}
if (slotAObj == null && slotBObj == null)
{
PlayerMovementCC.crouched = true;
}
}
}
if (Input.GetButtonUp("Action3"))
{
if (slotAObj != null && slotBObj != null)
{
if (slotAObj.name == "Cannon")
{
if (!slotAObj.GetComponent<CannonLauncher>().loaded && slotBObj.name == "Cannonball" && PlayerMovementCC.crouched && PlayerMovementCC.grounded)
{
Destroy(slotBObj);
slotAObj.GetComponent<CannonLauncher>().loaded = true;
}
}
}
if (PlayerMovementCC.crouched && PlayerMovementCC.grounded)
{
PlayerMovementCC.crouched = false;
}
}
if (Input.GetButtonDown("Action4"))
{
if (slotAObj != null)
{
if (slotAObj.GetComponentInChildren<KeyItem>().drop)
{
slotAObj.GetComponent<KeyItemUse>().Use();
}
}
}
//vvv for propeller vvv
if (Input.GetButtonUp("Action4"))
{
if (slotAObj != null)
{
if (slotAObj.GetComponentInChildren<KeyItem>().drop && PlayerMovementCC.gravity != -4f)
{
PlayerMovementCC.gravity = -4f;
}
}
}
}
public void AssignNewSlotObjects(GameObject newA, GameObject newB, bool invertAssignmentOrder)
{
GameObject a = newA;
GameObject b = newB;
if (invertAssignmentOrder)
{
slotBObj = b;
slotAObj = a;
}
else
{
slotAObj = a;
slotBObj = b;
}
}
IEnumerator respawnCoroutine(Vector3 Pos)
{
PlayerMovementCC.walkSpeed = 0f;
PlayerMovementCC.velocity = Vector3.zero;
smr.enabled = false;
yield return new WaitForSeconds(0.6f);
transform.position = Pos;
dead = false;
PlayerMovementCC.walkSpeed = 2.5f;
for (int i = 0; i < 5; i++)
{
yield return new WaitForSeconds(0.1f);
if (smr.enabled)
{
smr.enabled = false;
}
else
{
smr.enabled = true;
}
}
}
public void Die(Vector3 respawnPos)
{
lastSpawnPos = respawnPos;
dead = true;
if (slotAObj != null)
{
slotAObj.GetComponentInChildren<KeyItem>().Drop();
}
if (slotBObj != null)
{
slotBObj.GetComponentInChildren<KeyItem>().Drop();
}
if (slotBObj == null && slotAObj == null)
{
StartCoroutine(respawnCoroutine(respawnPos));
}
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject.tag == "ActionObject" && other.gameObject.transform.parent.gameObject.layer == 13)
{
if (targetObjectList.Contains(other.gameObject.transform.parent.gameObject))
{
targetObjectList.Remove(other.gameObject.transform.parent.gameObject);
}
}
if (other.gameObject.layer == 18)
{
PersistentManager.Instance.CurrentAreaID = "";
}
}
private void OnTriggerStay(Collider other)
{
if (other.gameObject.name == "Cannonball")
{
print("Its dayuh");
}
if (other.gameObject.tag == "ActionObject" && other.gameObject.transform.parent.gameObject.layer == 13)
{
if (!targetObjectList.Contains(other.gameObject.transform.parent.gameObject))
{
targetObjectList.Add(other.gameObject.transform.parent.gameObject);
}
}
if (other.gameObject.layer == 17 && PersistentManager.Instance.CurrentPuzzleID != other.gameObject.name)
{
PersistentManager.Instance.CurrentPuzzleID = other.gameObject.name;
}
if (other.gameObject.layer == 18 && PersistentManager.Instance.CurrentAreaID != other.gameObject.name)
{
PersistentManager.Instance.CurrentAreaID = other.gameObject.name;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class FloorButton : MonoBehaviour {
int buttonIDNumber;
Animator anim;
public GameObject reticleBone;
public bool pressed;
//maybe temporary??
public bool playerblocked;
private void Awake()
{
anim = transform.parent.GetComponent<Animator>();
}
void Update()
{
pressed = anim.GetBool("Pressed");
if (anim == null)
{
anim = transform.parent.GetComponent<Animator>();
}
string[] nameArray = transform.parent.name.Split('_');
int i = 0;
foreach (var item in nameArray)
{
int.TryParse(nameArray[i], out buttonIDNumber);
i++;
}
if (nameArray.Length != 2)
{
print(gameObject.name + " NOT NAMED CORRECTLY");
}
if (GameObject.Find("ButtonReceiver_" + buttonIDNumber) != null)
{
if (GameObject.Find("ButtonReceiver_" + buttonIDNumber).GetComponent<ButtonReceiver>().idle && anim.GetBool("Pressed"))
{
anim.SetBool("Pressed", false);
}
}
else if (anim.GetBool("Pressed"))
{
anim.SetBool("Pressed", false);
}
}
private void OnDrawGizmos()
{
switch (buttonIDNumber)
{
case 1:
Gizmos.color = Color.green;
break;
case 2:
Gizmos.color = Color.red;
break;
case 3:
Gizmos.color = Color.blue;
break;
default:
Gizmos.color = Color.black;
break;
}
}
//send a bool toggle to all receivers
void SendSignal()
{
GameObject[] recs = GameObject.FindGameObjectsWithTag("Receiver");
for (int i = 0; i < recs.Length; i++)
{
if (recs[i].name == "ButtonReceiver_" + buttonIDNumber && recs[i].GetComponent<ButtonReceiver>().powered)
{
recs[i].GetComponent<ButtonReceiver>().Move();
}
}
//if (GameObject.Find("ButtonReceiver_" + buttonIDNumber) != null)
//{
// if (GameObject.Find("ButtonReceiver_" + buttonIDNumber).GetComponent<ButtonReceiver>().powered)
// {
// GameObject.Find("ButtonReceiver_" + buttonIDNumber).GetComponent<ButtonReceiver>().Move();
// }
//}
}
private void OnTriggerEnter(Collider other)
{
if (PlayerActions.slotAObj != null && PlayerMovementCC.crouched && !playerblocked)
{
if (PlayerActions.slotAObj.name == "Hammer" && !anim.GetBool("Pressed"))
{
anim.SetBool("Pressed", true);
SendSignal();
}
}
if (other.name == "Player")
{
playerblocked = true;
}
}
private void OnTriggerStay(Collider other)
{
if (other.name == "Player")
{
playerblocked = true;
}
}
private void OnTriggerExit(Collider other)
{
if (other.name == "Player")
{
playerblocked = false;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HUDManager : MonoBehaviour {
Transform actionList;
static public bool swap;
float oldSwapTo = 360;
static public float swapTo = 180;
public GameObject swapPanel;
Dictionary<string, Sprite> itemSprites = new Dictionary<string, Sprite>();
public Sprite hammerSprite;
public Sprite cannonSprite;
public Sprite propellerSprite;
public Sprite cannonballSprite;
public Sprite diamondSprite;
public Sprite nullSprite;
GameObject slotAPanel;
GameObject slotBPanel;
public GameObject pickupButton;
public GameObject swapButton;
public GameObject dropButton;
public GameObject pickupKey;
public GameObject swapKey;
public GameObject dropKey;
void Start()
{
actionList = transform.GetChild(0).transform.GetChild(1);
for (int i = 0; i < FindObjectsOfType<Image>().Length; i++)
{
FindObjectsOfType<Image>()[i].color = PersistentManager.Instance.HUDColor;
}
itemSprites.Add("Hammer", hammerSprite);
itemSprites.Add("Cannon", cannonSprite);
itemSprites.Add("Propeller", propellerSprite);
itemSprites.Add("Cannonball", cannonballSprite);
itemSprites.Add("Dramond", diamondSprite);
slotAPanel = GameObject.Find("Item2");
slotBPanel = GameObject.Find("Item1");
}
void Update ()
{
// action panel management
if (Input.GetButtonDown("Action1"))
{
if (GameObject.Find("PickupKey(Clone)"))
{
Destroy(actionList.transform.Find("PickupKey(Clone)").gameObject);
}
}
ManageDropIcon(dropKey);
ManagePickupIcon(pickupKey);
ManageSwapIcon(swapKey);
//swap animation
slotAPanel.transform.localRotation = Quaternion.Euler(-swapPanel.transform.localRotation.eulerAngles);
slotBPanel.transform.localRotation = Quaternion.Euler(-swapPanel.transform.localRotation.eulerAngles);
if (!Input.GetButton("Action2"))
{
ManageItemIcons();
}
if (swapTo == 180)
{
slotAPanel = GameObject.Find("Item2");
slotBPanel = GameObject.Find("Item1");
}
if (swapTo == 360)
{
slotAPanel = GameObject.Find("Item1");
slotBPanel = GameObject.Find("Item2");
}
if (swap)
{
if (swapTo == 180)
{
swapTo = 360;
swap = false;
return;
}
if (swapTo == 360)
{
swapTo = 180;
swap = false;
return;
}
}
if (swapPanel.transform.localRotation.z != swapTo)
{
float t = Time.deltaTime * Mathf.Pow(0.6f, -2);
swapPanel.transform.localRotation = Quaternion.Lerp(swapPanel.transform.localRotation, Quaternion.Euler(0, 0, swapTo), t);
}
if (PlayerActions.slotBObj != null)
{
if (PlayerActions.slotAObj != null)
{
if (PlayerActions.slotAObj.GetComponentInChildren<KeyItem>().ABSwap && PlayerActions.slotBObj.GetComponentInChildren<KeyItem>().ABSwap)
{
swapPanel.GetComponent<Image>().enabled = true;
}
else
{
swapPanel.GetComponent<Image>().enabled = false;
}
}
else
{
if (PlayerActions.slotBObj.GetComponentInChildren<KeyItem>().ABSwap)
{
swapPanel.GetComponent<Image>().enabled = true;
}
else
{
swapPanel.GetComponent<Image>().enabled = false;
}
}
}
else if (PlayerActions.slotAObj != null)
{
if (PlayerActions.slotAObj.GetComponentInChildren<KeyItem>().ABSwap)
{
swapPanel.GetComponent<Image>().enabled = true;
}
else
{
swapPanel.GetComponent<Image>().enabled = false;
}
}
}
void ManagePickupIcon(GameObject key/*, GameObject Button , bool controlMode*/)
{
if (GameObject.Find("PickupKey(Clone)") == null)
{
if (PlayerActions.targetObject != null && PlayerActions.slotBObj == null)
{
if (PlayerActions.targetObject.GetComponentInChildren<KeyItem>().BSwap)
{
GameObject o = Instantiate(key, actionList.gameObject.transform.position, transform.rotation, actionList);
o.GetComponent<Image>().color = PersistentManager.Instance.HUDColor;
o.transform.GetChild(0).gameObject.GetComponent<Image>().color = PersistentManager.Instance.HUDColor;
}
}
}
else
{
if (PlayerActions.slotBObj != null)
{
Destroy(actionList.gameObject.transform.Find("PickupKey(Clone)").gameObject);
}
if (PlayerActions.targetObject == null)
{
Destroy(actionList.gameObject.transform.Find("PickupKey(Clone)").gameObject);
}
else if (!PlayerActions.targetObject.GetComponentInChildren<KeyItem>().BSwap)
{
Destroy(actionList.gameObject.transform.Find("PickupKey(Clone)").gameObject);
}
}
}
void ManageDropIcon(GameObject key/*, GameObject Button , bool controlMode*/)
{
if (GameObject.Find("DropKey(Clone)") == null)
{
if (PlayerActions.slotBObj != null && PlayerActions.slotBObj.GetComponentInChildren<KeyItem>().drop && PlayerActions.targetObject == null)
{
GameObject o = Instantiate(key, actionList.gameObject.transform.position, transform.rotation, actionList);
o.GetComponent<Image>().color = PersistentManager.Instance.HUDColor;
o.transform.GetChild(0).gameObject.GetComponent<Image>().color = PersistentManager.Instance.HUDColor;
}
}
else
{
if (PlayerActions.slotBObj == null || !PlayerActions.slotBObj.GetComponentInChildren<KeyItem>().drop || PlayerActions.targetObject != null)
{
Destroy(actionList.gameObject.transform.Find("DropKey(Clone)").gameObject);
}
}
}
void ManageSwapIcon(GameObject key/*, GameObject Button , bool controlMode*/)
{
if (GameObject.Find("SwapKey(Clone)") == null)
{
if (PlayerActions.slotBObj != null && PlayerActions.slotBObj.GetComponentInChildren<KeyItem>().drop && PlayerActions.targetObject != null)
{
if (PlayerActions.targetObject.GetComponentInChildren<KeyItem>().BSwap)
{
GameObject o = Instantiate(key, actionList.gameObject.transform.position, transform.rotation, actionList);
o.GetComponent<Image>().color = PersistentManager.Instance.HUDColor;
o.transform.GetChild(0).gameObject.GetComponent<Image>().color = PersistentManager.Instance.HUDColor;
}
}
}
else
{
if (PlayerActions.slotBObj == null || !PlayerActions.slotBObj.GetComponentInChildren<KeyItem>().drop || PlayerActions.targetObject == null)
{
Destroy(actionList.gameObject.transform.Find("SwapKey(Clone)").gameObject);
}
}
}
void ManageItemIcons()
{
if (PlayerActions.slotAObj != null)
{
slotAPanel.GetComponentInChildren<Image>().enabled = true;
switch (PlayerActions.slotAObj.name)
{
case "Hammer":
slotAPanel.GetComponentInChildren<Image>().sprite = hammerSprite;
break;
case "Cannon":
slotAPanel.GetComponentInChildren<Image>().sprite = cannonSprite;
break;
case "Propeller":
slotAPanel.GetComponentInChildren<Image>().sprite = propellerSprite;
break;
case "Cannonball":
slotAPanel.GetComponentInChildren<Image>().sprite = cannonballSprite;
break;
case "Diamond":
slotAPanel.GetComponentInChildren<Image>().sprite = diamondSprite;
break;
}
}
else
{
slotAPanel.GetComponentInChildren<Image>().sprite = nullSprite;
slotAPanel.GetComponentInChildren<Image>().enabled = false;
}
if (PlayerActions.slotBObj != null)
{
slotBPanel.GetComponentInChildren<Image>().enabled = true;
switch (PlayerActions.slotBObj.name)
{
case "Hammer":
slotBPanel.GetComponentInChildren<Image>().sprite = hammerSprite;
break;
case "Cannon":
slotBPanel.GetComponentInChildren<Image>().sprite = cannonSprite;
break;
case "Propeller":
slotBPanel.GetComponentInChildren<Image>().sprite = propellerSprite;
break;
case "Cannonball":
slotBPanel.GetComponentInChildren<Image>().sprite = cannonballSprite;
break;
case "Diamond":
slotBPanel.GetComponentInChildren<Image>().sprite = diamondSprite;
break;
}
}
else
{
slotBPanel.GetComponentInChildren<Image>().sprite = nullSprite;
slotBPanel.GetComponentInChildren<Image>().enabled = false;
}
}
void CleanUpInvalidControllerIcons(/*bool controlMode*/)
{
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class DeathZone : MonoBehaviour {
public Vector3 playerRespawnPoint;
public Vector3 hammerRespawnPoint;
public Vector3 propellerRespawnPoint;
public Vector3 cannonRespawnPoint;
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.name == "Player")
{
other.GetComponent<PlayerActions>().Die(playerRespawnPoint);
}
if (other.gameObject.name == "Hammer")
{
other.GetComponentInChildren<KeyItem>().Die(hammerRespawnPoint);
}
if (other.gameObject.name == "Propeller")
{
other.GetComponentInChildren<KeyItem>().Die(propellerRespawnPoint);
}
if (other.gameObject.name == "Cannon")
{
other.GetComponentInChildren<KeyItem>().Die(cannonRespawnPoint);
}
}
private void OnDrawGizmos()
{
Gizmos.color = Color.cyan;
Gizmos.DrawWireSphere(playerRespawnPoint, 0.25f);
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(hammerRespawnPoint, 0.25f);
Gizmos.color = Color.green;
Gizmos.DrawWireSphere(propellerRespawnPoint, 0.25f);
Gizmos.color = Color.blue;
Gizmos.DrawWireSphere(cannonRespawnPoint, 0.25f);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScreenShot : MonoBehaviour {
void Update ()
{
if (Input.GetButtonDown("Action1"))
{
ScreenCapture.CaptureScreenshot("C:/Users/troak/Desktop/SC.png");
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ButtonReceiver : MonoBehaviour {
public string puzzleZoneID;
public Vector3 initPos;
public Vector3 dirFactor;
float h;
public int steps = 1;
public int totalSteps;
public int step;
public bool reverse;
public bool isChild;
public bool idle;
public bool powered;
public int buttonIDNumber = -1;
BoxCollider trigger;
Rigidbody rb;
float moveSpeed;
private void Awake()
{
if (transform.parent.GetComponent<ButtonReceiver>() != null)
{
initPos = transform.localPosition;
}
else
{
initPos = transform.localPosition;
}
trigger = gameObject.GetComponent<BoxCollider>();
rb = gameObject.GetComponent<Rigidbody>();
h = trigger.size.y;
}
private void Start()
{
if (transform.parent.GetComponent<ButtonReceiver>() != null)
{
initPos = transform.localPosition;
}
else
{
initPos = transform.localPosition;
}
trigger = gameObject.GetComponent<BoxCollider>();
rb = gameObject.GetComponent<Rigidbody>();
h = trigger.size.y;
puzzleZoneID = transform.parent.name;
}
private void Update()
{
if (trigger == null)
{
trigger = gameObject.GetComponent<BoxCollider>();
h = trigger.size.y;
}
if (rb == null)
{
rb = gameObject.GetComponent<Rigidbody>();
}
string[] nameArray = transform.name.Split('_');
int i = 0;
foreach (var item in nameArray)
{
int.TryParse(nameArray[i], out buttonIDNumber);
i++;
}
if (nameArray.Length != 2)
{
print(gameObject.name + " NOT NAMED CORRECTLY");
}
else
{
isChild = true;
}
if (transform.position == initPos - (step * dirFactor))
{
idle = true;
}
else
{
idle = false;
}
if (puzzleZoneID != null && PersistentManager.Instance.CurrentPuzzleID != null)
{
if (puzzleZoneID == PersistentManager.Instance.CurrentPuzzleID)
{
powered = true;
}
}
else
{
powered = false;
}
}
private void FixedUpdate()
{
// if (transform.parent.GetComponent<ButtonReceiver>() == null)
// {
// isChild = false;
// if (transform.childCount > 0)
// {
// if (transform.GetChild(0).GetComponent<ButtonReceiver>().totalSteps == 0)
// {
// totalSteps = steps + transform.GetChild(0).GetComponent<ButtonReceiver>().steps;
// }
// else
// {
// totalSteps = steps + transform.GetChild(0).GetComponent<ButtonReceiver>().totalSteps;
// }
// Vector3 d = (transform.position) - (initPos - (step * dirFactor));
// float t = Time.deltaTime * Mathf.Pow(d.magnitude, -2);
// Vector3 moveTo = Vector3.Lerp(transform.position, initPos - (step * dirFactor), t);
// rb.MovePosition(moveTo);
// }
// else
// {
Vector3 d = (transform.position) - (initPos - (step * dirFactor));
float t = Time.deltaTime * Mathf.Pow(d.magnitude, -0.5f);
Vector3 moveTo = Vector3.Lerp(transform.position, initPos - (step * dirFactor), t);
rb.MovePosition(moveTo);
// }
// }
}
private void OnDrawGizmos()
{
switch (buttonIDNumber)
{
case 1:
Gizmos.color = Color.green;
break;
case 2:
Gizmos.color = Color.red;
break;
case 3:
Gizmos.color = Color.blue;
break;
default:
Gizmos.color = Color.black;
break;
}
if (trigger != null)
{
Gizmos.DrawWireCube(trigger.gameObject.transform.position + trigger.center, trigger.size);
}
}
public void Move()
{
int stepCount;
if (totalSteps == 0)
{
stepCount = steps;
}
else
{
stepCount = totalSteps;
}
//float stepDist = h / stepCount;
if (step == stepCount && !reverse)
{
reverse = true;
}
if (step == 0 && reverse)
{
reverse = false;
}
if (reverse)
{
step--;
idle = false;
}
else
{
step++;
idle = false;
}
}
//private void OnTriggerStay(Collider other)
//{
// if (other.transform.parent != null && puzzleZoneID != "")
// {
// if (other.transform.parent.GetComponentInChildren<FloorButton>() != null)
// {
// if (other.transform.parent.GetComponentInChildren<FloorButton>().buttonIDNumber == buttonIDNumber && puzzleZoneID == PersistentManager.Instance.CurrentPuzzleID)
// {
// powered = true;
// }
// }
// }
//}
//private void OnTriggerExit(Collider other)
//{
// if (other.transform.parent != null)
// {
// if (other.transform.parent.GetComponentInChildren<FloorButton>() != null)
// {
// if (other.transform.parent.GetComponentInChildren<FloorButton>().buttonIDNumber == buttonIDNumber && powered)
// {
// powered = false;
// }
// }
// }
//}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KeyItemUse : MonoBehaviour {
KeyItem ki;
Animator anim;
public bool active;
private void Start()
{
ki = gameObject.GetComponentInChildren<KeyItem>();
anim = gameObject.GetComponent<Animator>();
}
private void Update()
{
if (PlayerActions.slotAObj != null)
{
if (PlayerActions.slotAObj.name != "Propeller")
{
if (PlayerMovementCC.gravity != -12)
{
PlayerMovementCC.gravity = -12;
}
if (name == "Propeller")
{
active = false;
}
}
else
{
if (!PlayerMovementCC.grounded && PlayerMovementCC.gravity == -12)
{
if (PlayerMovementCC.impact.y != 0)
{
PlayerMovementCC.gravity = -2;
}
else
{
PlayerMovementCC.gravity = -4;
}
}
}
if (PlayerActions.slotAObj.name != "Cannon")
{
if (active)
{
active = false;
}
}
else
{
if (active)
{
GetComponentInChildren<KeyItem>().ABSwap = false;
Cannon();
}
}
}
else
{
active = false;
if (PlayerMovementCC.gravity != -12)
{
PlayerMovementCC.gravity = -12;
}
}
//ANIMATIONS
if (gameObject.name == "Propeller")
{
PropellerAnims();
}
if (gameObject.name == "Cannon")
{
CannonAnims();
}
}
public void Use()
{
if (name == "Propeller")
{
Propeller();
}
if (name == "Cannon" && GetComponent<CannonLauncher>().loaded)
{
active = true;
}
}
private void Propeller()
{
if (PlayerActions.slotAObj.name == "Propeller" && PlayerMovementCC.grounded)
{
active = true;
PlayerMovementCC.velocityY = 0;
for (float i = 0; i < 01f; i += 0.01f)
{
float f = 0;
if (i < 2.9f)
{
if (i - (i * 0.0001f) < 0)
{
f = 0;
}
else
{
f = i - (i * 0.0001f);
}
}
else
{
f = i;
}
PersistentManager.Instance.Player.GetComponent<PlayerMovementCC>().AddImpact(Vector3.up, f);
if (!PlayerMovementCC.grounded)
{
PlayerMovementCC.gravity = -2;
}
}
}
}
private void PropellerAnims()
{
anim.SetBool("InSlotA", PlayerActions.slotAObj == gameObject ? true : false);
bool flying;
if (anim.GetBool("InSlotA"))
{
flying = active ? true : false;
flying = !PlayerMovementCC.grounded && PlayerMovementCC.footRayDist > 1.4f ? true : false;
}
else
{
flying = false;
}
anim.SetBool("Flying", flying);
}
private void Cannon()
{
PlayerMovementCC.walkSpeed = 0;
if (Input.GetButtonUp("Action4"))
{
GetComponent<CannonLauncher>().Launch();
active = false;
}
}
private void CannonAnims()
{
anim.SetBool("InSlotA", PlayerActions.slotAObj == gameObject ? true : false);
anim.SetBool("Loaded", GetComponent<CannonLauncher>().loaded == true ? true : false);
if (PlayerActions.slotAObj != null)
{
if (PlayerActions.slotAObj.name == "Cannon")
{
if (CharAnim.anim.GetCurrentAnimatorStateInfo(0).fullPathHash == Animator.StringToHash("Base Layer.Crouched") || CharAnim.anim.GetCurrentAnimatorStateInfo(0).fullPathHash == Animator.StringToHash("Base Layer.Holding|Crouched"))
{
anim.SetBool("Crouched", true);
}
else
{
anim.SetBool("Crouched", false);
}
}
}
else
{
anim.SetBool("Crouched", false);
}
GameObject armitureBase = gameObject.transform.GetChild(0).gameObject;
if (PlayerActions.slotAObj == gameObject && active && !PlayerMovementCC.crouched)
{
Vector3 target = new Vector3(GetComponentInChildren<ReticleController>().gameObject.transform.position.x, armitureBase.transform.position.y, GetComponentInChildren<ReticleController>().gameObject.transform.position.z);
Debug.DrawLine(armitureBase.transform.position, target, Color.red);
armitureBase.transform.LookAt(target);
}
if (PlayerActions.slotAObj == gameObject && !active && armitureBase.transform.localEulerAngles != Vector3.zero)
{
armitureBase.transform.localRotation = Quaternion.Slerp(armitureBase.transform.localRotation, Quaternion.Euler(Vector3.zero), Time.deltaTime * 2f);
//armitureBase.transform.localEulerAngles = Vector3.Lerp(armitureBase.transform.localEulerAngles, Vector3.zero, Time.deltaTime * 2f);
}
}
private void Hammer()
{
}
////CANNON STUFF vvvvvvvvvvv
////populate line renderer with appropriate settings
//private void RenderArc(LineRenderer lr, int res, float angle, float velocity, float g)
//{
// lr.SetVertexCount(res + 1);
// lr.SetPositions(CalculateArcArray(res, angle, velocity, g));
//}
////creat an array of Vector3 positions for rc
//private Vector3[] CalculateArcArray(int res, float angle, float velocity, float g)
//{
// float radianAngle = Mathf.Deg2Rad * angle;
// Vector3[] arcArray = new Vector3[res + 1];
// float maxDistance = (velocity * velocity * Mathf.Sin(2 * radianAngle)) / g;
// for (int i = 0; i <= res; i++)
// {
// float t = (float)i / (float)res;
// arcArray[i] = CalculateArcPoint(t, maxDistance, radianAngle, velocity, g);
// }
// return arcArray;
//}
////calculate height and distance of each vertex
//private Vector3 CalculateArcPoint(float t, float maxDistance, float radianAngle, float velocity, float g)
//{
// float x = t * maxDistance;
// float y = x * Mathf.Tan(radianAngle) - ((g * x * x) / (2 * velocity * velocity * Mathf.Cos(radianAngle) * Mathf.Cos(radianAngle)));
// return new Vector3(x, y, 0);
//}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Puzzle : MonoBehaviour
{
List<GameObject> areas = new List<GameObject>();
private void Start()
{
Transform[] ts = gameObject.GetComponentsInChildren<Transform>();
foreach (Transform t in ts)
{
if (t.gameObject.layer == 18)
{
areas.Add(t.gameObject);
}
}
}
private void Update()
{
if (PersistentManager.Instance.CurrentPuzzleID == gameObject.name)
{
if (gameObject.name == "Puzzle2")
{
if (PersistentManager.Instance.CurrentAreaID == areas[0].name)
{
areas[0].GetComponentInChildren<DeathZone>().gameObject.GetComponent<BoxCollider>().enabled = true;
areas[1].GetComponentInChildren<DeathZone>().gameObject.GetComponent<BoxCollider>().enabled = false;
}
if (PersistentManager.Instance.CurrentAreaID == areas[1].name)
{
areas[0].GetComponentInChildren<DeathZone>().gameObject.GetComponent<BoxCollider>().enabled = false;
areas[1].GetComponentInChildren<DeathZone>().gameObject.GetComponent<BoxCollider>().enabled = true;
}
}
if (gameObject.name == "Puzzle1")
{
areas[0].GetComponentInChildren<DeathZone>().gameObject.GetComponent<BoxCollider>().enabled = true;
}
if (gameObject.name == "Center")
{
areas[0].GetComponentInChildren<DeathZone>().gameObject.GetComponent<BoxCollider>().enabled = true;
}
}
else
{
foreach (GameObject g in areas)
{
g.GetComponentInChildren<DeathZone>().gameObject.GetComponent<BoxCollider>().enabled = false;
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CannonBall : MonoBehaviour
{
public LayerMask mask;
public GameObject particle1;
public GameObject particle2;
ParticleSystem ps;
MeshRenderer mr;
public bool isAmmo = true;
public bool active;
private void Start()
{
mr = GetComponentInChildren<MeshRenderer>();
ps = GetComponentInChildren<ParticleSystem>();
var emission = ps.emission;
emission.enabled = false;
if (isAmmo)
{
mr.enabled = false;
}
if (!mr.enabled)
{
StartCoroutine(Enable());
}
}
IEnumerator Enable()
{
yield return new WaitForSeconds(0.08f);
mr.enabled = true;
}
private void Update()
{
if (!mr.enabled && !isAmmo)
{
mr.enabled = true;
}
if (Vector3.Magnitude(transform.position - PersistentManager.Instance.Player.transform.position) > 30)
{
Object.Destroy(gameObject);
}
var emission = ps.emission;
if (active && emission.enabled == false)
{
emission.enabled = true;
}
if (!active && emission.enabled == true)
{
emission.enabled = false;
}
}
private void OnCollisionEnter(Collision collision)
{
if (active)
{
Instantiate(particle1, gameObject.transform.position, gameObject.transform.rotation);
Instantiate(particle2, gameObject.transform.position, gameObject.transform.rotation);
Object.Destroy(gameObject);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class ParabolaTesting : MonoBehaviour
{
LineRenderer lr;
public float velocity;
public float angle;
public int resolution = 20;
float g;
float radianAngle;
private void Awake()
{
lr = GetComponentInChildren<LineRenderer>();
g = Mathf.Abs(Physics.gravity.y);
}
private void Update()
{
RenderArc(lr, resolution, angle, velocity, g);
}
//populate line renderer with appropriate settings
private void RenderArc(LineRenderer lr, int res, float angle, float velocity, float g)
{
lr.positionCount = res + 1;
lr.SetPositions(CalculateArcArray(res, angle, velocity, g));
}
//creat an array of Vector3 positions for rc
private Vector3[] CalculateArcArray(int res, float angle, float velocity, float g)
{
float radianAngle = Mathf.Deg2Rad * angle;
Vector3[] arcArray = new Vector3[res + 1];
float maxDistance = (velocity * velocity * Mathf.Sin(2 * radianAngle)) / g;
for (int i = 0; i <= res; i++)
{
float t = (float)i / (float)res;
arcArray[i] = CalculateArcPoint(t, maxDistance, radianAngle, velocity, g);
}
return arcArray;
}
//calculate height and distance of each vertex
private Vector3 CalculateArcPoint(float t, float maxDistance, float radianAngle, float velocity, float g)
{
float x = t * maxDistance;
float y = x * Mathf.Tan(radianAngle) - ((g * x * x) / (2 * velocity * velocity * Mathf.Cos(radianAngle) * Mathf.Cos(radianAngle)));
return new Vector3(x, y, 0);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ReticleController : MonoBehaviour
{
public float testf;
public LayerMask mask;
public Vector3 position;
public Vector3 _ref;
Animator promptAnim;
SpriteRenderer promptSR;
Vector3 defPosition;
public bool isColl;
SpriteRenderer sr;
KeyItemUse keu;
[Range(-10, 10)]
public float heightModifier = 8310003f;
float height;
private void Start()
{
sr = GetComponent<SpriteRenderer>();
keu = transform.parent.transform.parent.GetComponent<KeyItemUse>();
if (transform.parent.transform.parent.name == "Hammer")
{
promptAnim = GetComponentInChildren<Animator>();
promptSR = promptAnim.GetComponent<SpriteRenderer>();
}
}
private void Update()
{
if (PlayerActions.slotAObj != null)
{
if (transform.parent.transform.parent.name == PlayerActions.slotAObj.name)
{
if (PlayerActions.slotAObj.name == "Cannon")
{
height = (PersistentManager.Instance.Player.GetComponent<CharacterController>().height + (PersistentManager.Instance.Player.GetComponent<CharacterController>().skinWidth * 0.55f) + CannonLauncher.h + heightModifier);
transform.position = RayCastDown();
if (keu.active && !PlayerMovementCC.crouched && isColl)
{
sr.color = Color.white;
}
else
{
sr.color = new Color(1, 1, 1, 0);
}
defPosition = Vector3.Scale(PersistentManager.Instance.Player.transform.forward, new Vector3(1, 0, 1)) + new Vector3(0, height, 0);
if (sr.transform.rotation.eulerAngles != new Vector3(90, 0, 0))
{
sr.transform.rotation = Quaternion.Euler(90, 0, 0);
}
if (keu.active)
{
Vector3 input = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
Quaternion r = Quaternion.AngleAxis(CamManager.targetA, Vector3.up);
Vector3 r2 = r * input;
Vector2 inputDir = new Vector2(r2.normalized.x, r2.normalized.z);
if (Mathf.Abs(position.x + inputDir.x / 20f) < 5f && Mathf.Abs(position.z + inputDir.y / 20f) < 5f)
{
position += new Vector3(inputDir.x, 0, inputDir.y) / 15f;
}
}
else if (position != defPosition)
{
position = defPosition;
}
}
if (PlayerActions.slotAObj.name == "Hammer")
{
promptAnim.gameObject.transform.LookAt(Camera.main.transform.position, Vector3.up);
height = (PersistentManager.Instance.Player.GetComponent<CharacterController>().height + (PersistentManager.Instance.Player.GetComponent<CharacterController>().skinWidth * 0.55f) + transform.parent.GetComponent<KeyItem>().BMeasurements.y);
if (!PlayerMovementCC.crouched && isColl)
{
if (transform.parent.GetComponent<KeyItem>().crouch)
{
if (sr.color == new Color(1, 1, 1, 0))
{
StartCoroutine(CrouchPause());
}
else
{
sr.color = Color.white;
}
}
else
{
sr.color = Color.red;
}
}
else
{
sr.color = new Color(1, 1, 1, 0);
promptAnim.SetBool("Prompt", false);
promptSR.enabled = false;
}
if (!PlayerMovementCC.crouched)
{
defPosition = Vector3.Scale(PersistentManager.Instance.Player.transform.forward, new Vector3(1.95f, 0, 1.95f)) + new Vector3(0, height, 0);
}
Vector3 origin = Vector3.Scale((PersistentManager.Instance.Player.transform.position + defPosition), new Vector3(1, 0, 1)) + (Vector3.up * height);
RaycastHit hit;
if (Physics.SphereCast(origin, 0.46f, Vector3.down, out hit, height - testf, mask, QueryTriggerInteraction.Collide))
{
GameObject obj = hit.collider.gameObject;
if (obj.GetComponent<FloorButton>())
{
float t = Time.deltaTime * Mathf.Pow(0.6f, -2);
transform.position = Vector3.SmoothDamp(transform.position, obj.GetComponent<FloorButton>().reticleBone.transform.position, ref _ref, t);
if (!obj.GetComponent<FloorButton>().pressed && !PlayerMovementCC.crouched && transform.parent.GetComponent<KeyItem>().crouch && !Input.GetButton("Action3"))
{
print(obj.transform.position.y);
print(PersistentManager.Instance.Player.transform.position.y);
if (obj.GetComponent<FloorButton>().reticleBone.transform.position.y > PersistentManager.Instance.Player.transform.position.y)
{
promptAnim.SetBool("Prompt", true);
promptSR.enabled = true;
}
else
{
promptAnim.SetBool("Prompt", false);
promptSR.enabled = false;
}
}
else
{
promptAnim.SetBool("Prompt", false);
promptSR.enabled = false;
}
}
else
{
float t = Time.deltaTime * Mathf.Pow(0.6f, -2);
transform.position = Vector3.SmoothDamp(transform.position, RayCastDown(), ref _ref, t);
position = defPosition;
promptAnim.SetBool("Prompt", false);
promptSR.enabled = false;
}
}
else
{
float t = Time.deltaTime * Mathf.Pow(0.6f, -2);
transform.position = Vector3.SmoothDamp(transform.position, RayCastDown(), ref _ref, t);
position = defPosition;
promptAnim.SetBool("Prompt", false);
promptSR.enabled = false;
}
}
}
else
{
sr.color = new Color(1, 1, 1, 0);
}
}
else
{
sr.color = new Color(1, 1, 1, 0);
}
}
IEnumerator CrouchPause()
{
print("!!");
yield return new WaitForSeconds(0.3f);
sr.color = Color.white;
}
Vector3 RayCastDown()
{
RaycastHit hit;
Vector3 origin = Vector3.Scale((transform.parent.position + position), new Vector3(1, 0, 1)) + (Vector3.up * height);
Vector3 newpos;
Debug.DrawLine(origin, new Vector3(origin.x, -height, origin.z), Color.red);
if (Physics.Raycast(origin, Vector3.down, out hit, height * 2, mask, QueryTriggerInteraction.Collide))
{
isColl = true;
newpos = hit.point + new Vector3(0, 0.1f, 0);
}
else
{
isColl = false;
newpos = new Vector3(origin.x, transform.position.y, origin.z);
}
return newpos;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class TrackTransforms : MonoBehaviour {
//POS
public GameObject posObj;
public bool trackPosBool;
public Vector3 posOffset;
public float trackPosSpeed;
Vector3 trackPosRef;
public bool trackXPos;
public bool trackYPos;
public bool trackZPos;
//TRACK DIRECTION POS
public bool trackForwardPosBool;
//ROT
public GameObject rotObj;
public bool trackRotBool;
public float trackRotSpeed;
float trackRotRef;
public bool trackXRot;
public bool trackYRot;
public bool trackZRot;
public Vector3 rotOffset;
void Update()
{
//POS
if (trackPosBool)
{
TrackPos(trackXPos ,trackYPos ,trackZPos , posOffset);
}
//TRACK DIRECTION POS
if (trackForwardPosBool)
{
TrackForwardPos();
}
//ROT
if (trackRotBool)
{
TrackRot(trackXRot, trackYRot, trackZRot, rotOffset);
}
}
void TrackPos(bool X, bool Y, bool Z, Vector3 offset)
{
//float x = X.GetHashCode();
//float y = Y.GetHashCode();
//float z = Z.GetHashCode();
if (posObj != null)
{
Vector3 finalPos;
finalPos = posObj.transform.TransformPoint(offset);
transform.position = Vector3.SmoothDamp(transform.position, finalPos, ref trackPosRef, trackPosSpeed);
}
}
void TrackRot(bool X, bool Y, bool Z, Vector3 offset)
{
float x = X.GetHashCode();
float y = Y.GetHashCode();
float z = Z.GetHashCode();
//Vector3 selections = new Vector3(x, y, z);
if (rotObj != null)
{
Vector3 finalRot;
finalRot = rotObj.transform.rotation.eulerAngles;
if (y == 1)
{
transform.eulerAngles = Vector3.up * Mathf.SmoothDampAngle(transform.eulerAngles.y, finalRot.y, ref trackRotRef, trackRotSpeed);
transform.eulerAngles += offset;
}
}
}
void TrackForwardPos()
{
transform.position = rotObj.transform.position + rotObj.transform.forward + posOffset;
}
private void OnDrawGizmos()
{
if (posObj.tag == "ActionObject")
{
Gizmos.DrawIcon(transform.position, "sv_icon_dot8_pix16_gizmo");
}
else
{
Gizmos.DrawIcon(transform.position, "sv_icon_dot2_pix16_gizmo");
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SlotB : MonoBehaviour {
public GameObject obj;
void Update ()
{
var lookPos = new Ray (obj.transform.position, PlayerMovement.avgFootNormal).GetPoint(1);
//var rotation = Quaternion.LookRotation(lookPos);
transform.rotation = Quaternion.LookRotation(lookPos);
}
private void OnDrawGizmos()
{
Gizmos.DrawIcon(transform.position, "sv_icon_dot1_pix16_gizmo");
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharAnim : MonoBehaviour {
static public Animator anim;
CharacterController cc;
private void Start()
{
anim = GetComponent<Animator>();
cc = GetComponent<CharacterController>();
}
private void Update()
{
anim.SetBool("Crouched", PlayerMovementCC.crouched);
anim.SetBool("Moving", PlayerMovementCC.moving);
anim.SetFloat("CCVelocity", PlayerMovementCC.inputDir.magnitude * PlayerMovementCC.walkSpeed);
if (PlayerActions.slotBObj != null)
{
anim.SetBool("Holding", true);
}
else
{
anim.SetBool("Holding", false);
}
anim.SetFloat("YVelocity", PersistentManager.Instance.Player.GetComponent<CharacterController>().velocity.y);
anim.SetFloat("FootRayDist", PlayerMovementCC.footRayDist);
anim.SetBool("Grounded", PlayerMovementCC.grounded);
anim.SetBool("Space", Input.GetButtonDown("Action4"));
if (PlayerActions.slotAObj != null)
{
if (PlayerActions.slotAObj.name == "Propeller")
{
anim.SetBool("Propeller", true);
}
else
{
anim.SetBool("Propeller", false);
}
}
}
}
<file_sep>using UnityEngine;
public struct Parabola
{
public readonly Vector3 start;
public readonly Vector3 end;
public readonly float height;
public static float DisplacementY(Parabola p)
{
float dY;
dY = p.end.y - p.start.y;
return dY;
}
public static Vector3 DisplacementXZ(Parabola p)
{
Vector3 dXZ;
dXZ = new Vector3(p.end.x - p.start.x, 0, p.end.z - p.start.z);
return dXZ;
}
public static float Time(Parabola p)
{
float t;
t = (Mathf.Sqrt(-2 * p.height / Physics.gravity.y) + Mathf.Sqrt(2 * (Parabola.DisplacementY(p) - p.height) / Physics.gravity.y));
return t;
}
public static Vector3 VelocityY(Parabola p)
{
Vector3 vY = Vector3.up * Mathf.Sqrt(-2 * Physics.gravity.y * p.height);
return vY;
}
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
//componenets
public Rigidbody rb;
public Collider coll;
private Transform InputAxis;
//movement vars
public Vector3 v;
public Quaternion q = new Quaternion();
public double footNormalDot;
public float moveSpeed;
public float jumpForce;
public bool j;
public bool grounded;
public bool jumping;
public bool disabled = false;
public bool isColiding = false;
private Vector3 avgCollNormal = Vector3.zero;
//raycasting vars
public static Vector3 orientation = Vector3.forward;
public static Ray facingRay;
public static Ray footRay;
public static List<Ray> heelRays = new List<Ray>(8);
public LayerMask footRayLayerMask;
private Ray inputAxisRay;
private Vector3 footRayHit = Vector3.zero;
public static Vector3 avgFootNormal = Vector3.zero;
//Collider vars
public List<Collision> collisions = new List<Collision>();
public int normCount;
void Start()
{
rb = GetComponent<Rigidbody>();
coll = GetComponent<Collider>();
facingRay = new Ray(transform.position, Vector3.back);
InputAxis = GameObject.Find("InputAxis").GetComponent<Transform>();
}
private void Update()
{
//GENERAL VARIABLE UPDATES
VarUpdate();
//MOVEMENT INPUT
//RAYCASTING
FootRay();
RadialRays();
}
void FixedUpdate()
{
//MOVEMENT INPUT
MovementInput(v);
//DEBUG
//VARIABLE RESET
}
//VARIABLE MANAGEMENT FUNCTIONS
void VarUpdate()
{
//MOVEMENT VARS_____________________________________________________________________________________________________________________________
//movement vector
v = new Vector3(
(Input.GetAxis("Horizontal")) * (moveSpeed * (2 - Mathf.Abs(InputAxis.up.x * 0.5f))),
-(((5 * Mathf.Abs(InputAxis.right.z)) - Mathf.Abs(InputAxis.up.x * 0.5f))) + -((5 * Mathf.Abs(InputAxis.up.y * InputAxis.right.x) - Mathf.Abs((InputAxis.up.z * Mathf.RoundToInt(InputAxis.up.y)) * 0.5f))),
((Input.GetAxis("Vertical")) * (moveSpeed - 0.5f)) * (moveSpeed * (2 - Mathf.Abs(InputAxis.up.z * 0.5f))));
//climbing slopes makes you move slower
if (footNormalDot != -1)
{
v = new Vector3(v.x * 0.8f, v.y, v.z * 0.8f);
}
//quanternion velocity rotation
q.SetLookRotation(avgFootNormal, Vector3.up);
InputAxis.rotation = q;
inputAxisRay = new Ray(InputAxis.position, InputAxis.up);
//calculate average collision normal and determine if grounded
for (int i = 0; i < collisions.Count; i++)
{
foreach (ContactPoint contact in collisions[i].contacts)
{
avgCollNormal += contact.normal;
normCount += 1;
}
}
avgCollNormal = avgCollNormal / normCount;
if (!grounded)
{
if (collisions.Count > 0)
{
isColiding = true;
}
if (collisions.Count == 0)
{
isColiding = false;
}
}
//reset things
collisions.Clear();
footNormalDot = (System.Math.Round(Vector3.Dot(Vector3.down, avgFootNormal), 2));
normCount = 0;
avgCollNormal = Vector3.zero;
}
//MOVEMENT INPUT FUNCTIONS
void MovementInput(Vector3 v)
{
if (!jumping)
{
if (grounded)
{
rb.velocity = new Vector3(v.x, v.y, v.z);
}
else
{
rb.velocity = new Vector3(v.x, rb.velocity.y, v.z);
}
}
else
{
if (!isColiding)
{
if (rb.velocity.y > 0)
{
rb.velocity = new Vector3(Input.GetAxis("Horizontal") * (moveSpeed), rb.velocity.y, Input.GetAxis("Vertical") * (moveSpeed));
}
else
{
rb.velocity = new Vector3(Input.GetAxis("Horizontal") * (moveSpeed * 1.5f), rb.velocity.y, Input.GetAxis("Vertical") * (moveSpeed * 1.5f));
}
}
}
}
//plans are to implement jump as a contextual action input
void JumpInput()
{
if (j)
{
jumping = true;
rb.velocity = new Vector3(rb.velocity.x, jumpForce, rb.velocity.z);
j = false;
}
}
//RAYCAST FUNCTIONS
void FootRay()
{
Quaternion q = Quaternion.AngleAxis(90, Vector3.up);
if ((Input.GetAxisRaw("Vertical") != 0) || (Input.GetAxisRaw("Horizontal") != 0))
{
orientation = new Vector3(-Input.GetAxisRaw("Vertical"), 0, Mathf.RoundToInt(Input.GetAxisRaw("Horizontal")));
}
Vector3 d = orientation * 2;
facingRay.origin = transform.position;
facingRay.direction = q * d;
footRay.origin = transform.position;
footRay.direction = Vector3.down * 2;
RaycastHit hit;
if (Physics.Raycast(footRay, out hit, 1f, footRayLayerMask, QueryTriggerInteraction.Ignore))
{
if (jumping && rb.velocity.y < 0.01f)
{
jumping = false;
}
if (!jumping)
{
isColiding = true;
if (rb.useGravity)
{
rb.velocity = new Vector3(v.x, rb.velocity.y, v.z);
grounded = true;
rb.useGravity = false;
}
footRayHit = hit.point;
if (rb.position.y <= hit.point.y - footRay.direction.y)
{
rb.MovePosition(new Vector3(rb.position.x, hit.point.y - footRay.direction.y, rb.position.z));
}
}
}
if (!Physics.Raycast(footRay, out hit, 1.1f, footRayLayerMask, QueryTriggerInteraction.Ignore) || jumping)
{
grounded = false;
rb.useGravity = true;
}
}
void RadialRays()
{
for (int i = 0; i < heelRays.Capacity; i++)
{
Ray heelRay = new Ray(FindPoint(footRay.origin, gameObject.GetComponent<CapsuleCollider>().radius, i), Vector3.down);
heelRays.Add(heelRay);
}
List<Vector3> norms = new List<Vector3>();
Vector3 avgNormal = Vector3.zero;
foreach (Ray item in heelRays)
{
RaycastHit hit;
if (Physics.Raycast(item, out hit, 1, footRayLayerMask, QueryTriggerInteraction.Ignore))
{
norms.Add(hit.normal);
}
}
foreach (Vector3 item in norms)
{
avgNormal += item;
}
avgNormal = (avgNormal / norms.Count);
avgFootNormal = avgNormal;
heelRays.Clear();
}
Vector3 FindPoint(Vector3 c, float r, int i)
{
return c + Quaternion.AngleAxis(45.0f * i, Vector3.forward) * (Vector3.right * r);
}
//COLLISION FUNCTIONS
private void OnCollisionEnter(Collision collision)
{
}
private void OnCollisionExit(Collision collision)
{
}
private void OnCollisionStay(Collision collision)
{
if (!collisions.Contains(collision))
{
collisions.Add(collision);
}
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == ("Disable") && !disabled)
{
disabled = true;
}
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject.tag == ("Disable") && disabled)
{
disabled = false;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovementCC : MonoBehaviour
{
static public float walkSpeed = 2.5f;
static public float gravity = -12;
public float controllerHeight = 2;
public float turningSpeed = 0.5f;
public float mass = 3.0f;
static public Vector3 impact = Vector3.zero;
public LayerMask footSphereLayerMask;
public static bool moving;
Vector3 initPos;
public static bool grounded;
public static bool balancing;
public static bool crouched = false;
[HideInInspector] public static Vector2 inputDir;
float turningVelocityRef;
static public Vector3 velocity;
[HideInInspector] static public bool swapKeyItemSpeedDamp;
static public float velocityY;
[HideInInspector] static public Ray footRay;
[HideInInspector] static public float footRayDist;
[HideInInspector] public static CharacterController controller;
void Start()
{
controller = GetComponent<CharacterController>();
controller.height = controllerHeight;
controller.enableOverlapRecovery = true;
controller.detectCollisions = true;
}
void Update()
{
//input
Vector3 input = Vector3.zero;
inputDir = Vector2.zero;
if (!crouched)
{
input = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
Quaternion r = Quaternion.AngleAxis(CamManager.targetA, Vector3.up);
Vector3 r2 = r * input;
//Vector3 correctedVertical = input.y * Camera.main.transform.forward;
//Vector3 correctedHorizontal = input.x * Camera.main.transform.right;
//Vector3 combinedInput = correctedHorizontal + correctedVertical;
inputDir = new Vector2(r2.normalized.x, r2.normalized.z);
}
CrouchCheck();
GroundedInput(inputDir);
}
private void FixedUpdate()
{
impact = Vector3.Lerp(impact, Vector3.zero, 5*Time.deltaTime);
footRayDist = FootDist();
GroundSphere();
BackCheck();
if (GroundRays() == 0 && grounded)
{
grounded = false;
}
if (impact.magnitude > 0.2f)
{
controller.Move((impact + velocity/2) * Time.deltaTime);
}
else
{
Move(velocity);
}
if (initPos != transform.position)
{
moving = true;
}
else
{
moving = false;
}
initPos = transform.position;
}
//GIZMOS
private void OnDrawGizmos()
{
}
//ACTIONS
void CrouchCheck()
{
if (!grounded && crouched)
{
crouched = false;
}
}
//RAYCAST FUNCTIONS
void GroundSphere()
{
Ray ray = new Ray(transform.position + controller.center - (Vector3.up * controller.height / 4), -transform.up);
RaycastHit[] hits = new RaycastHit[5];
hits = Physics.SphereCastAll(ray, controller.radius, controller.skinWidth * 5.5f, footSphereLayerMask, QueryTriggerInteraction.Ignore);
if (hits.Length > 0)
{
grounded = true;
}
}
int GroundRays()
{
int i = 0;
i += GroundRay(controller.radius, 0) + GroundRay(-controller.radius, 0) + GroundRay(0, controller.radius) + GroundRay(0, -controller.radius);
return i;
}
int GroundRay(float Xoffset, float Zoffset)
{
Vector3 origin = transform.position + controller.center + new Vector3(0 + Xoffset, -0.25f, 0 + Zoffset);
Debug.DrawRay(origin, -Vector3.up, Color.red);
if (Physics.Raycast(new Ray(origin, -transform.up), 1, footSphereLayerMask, QueryTriggerInteraction.Ignore))
{
return 1;
}
else return 0;
}
float FootDist()
{
RaycastHit hit = new RaycastHit();
Vector3 origin = transform.position + controller.center + new Vector3(0, -0.25f, 0);
Debug.DrawRay(origin, -Vector3.up, Color.red);
if (Physics.Raycast(new Ray(origin, -transform.up), out hit, 100, footSphereLayerMask, QueryTriggerInteraction.Ignore))
{
double h = (double)hit.distance;
float f = (float)System.Math.Round(h, 2);
return f;
}
else return 100;
}
//ROTATION FUNCTIONS
Vector3 ApplySlopeRotation(Vector3 velocity, float Dist)
{
if (grounded)
{
Ray Ray = new Ray(transform.position + controller.center - (Vector3.up * controller.height / 4), -transform.up);
RaycastHit Hit;
if (Physics.Raycast(Ray, out Hit, Dist, footSphereLayerMask, QueryTriggerInteraction.Ignore))
{
footRay = new Ray(Hit.point, Hit.normal);
balancing = false;
}
else
{
balancing = true;
}
}
Vector3 rotatedVector = Quaternion.FromToRotation(transform.up, footRay.direction) * velocity;
return rotatedVector;
}
//MOVE FUNCTIONS
void GroundedInput(Vector2 inputDir)
{
if (!crouched)
{
if (inputDir != Vector2.zero && walkSpeed != 0)
{
float targetRotation = Mathf.Atan2(inputDir.x, inputDir.y) * Mathf.Rad2Deg;
transform.eulerAngles = Vector3.up * Mathf.SmoothDampAngle(transform.eulerAngles.y, targetRotation, ref turningVelocityRef, turningSpeed);
}
if (!grounded)
{
velocityY += Time.deltaTime * gravity;
}
else
{
if (gravity != -12)
{
if (PlayerActions.slotAObj.name == "Propeller")
{
PlayerActions.slotAObj.GetComponent<KeyItemUse>().active = false;
}
impact = Vector3.zero;
gravity = -12;
}
velocityY = 0;
}
}
float speed = 0f;
if (PlayerActions.slotBObj != null && PlayerActions.slotAObj == null)
{
if (PlayerActions.slotBObj.GetComponentInChildren<KeyItem>().drop)
{
speed = walkSpeed * inputDir.magnitude;
}
}
if (PlayerActions.slotAObj != null && PlayerActions.slotBObj == null)
{
if (PlayerActions.slotAObj.GetComponentInChildren<KeyItem>().drop)
{
speed = walkSpeed * inputDir.magnitude;
}
}
if (PlayerActions.slotBObj != null && PlayerActions.slotAObj != null)
{
if (PlayerActions.slotAObj.GetComponentInChildren<KeyItem>().drop && PlayerActions.slotBObj.GetComponentInChildren<KeyItem>().drop)
{
speed = walkSpeed * inputDir.magnitude;
}
}
if (PlayerActions.slotAObj == null && PlayerActions.slotBObj == null)
{
speed = walkSpeed * inputDir.magnitude;
}
if (swapKeyItemSpeedDamp)
{
speed = 0;
swapKeyItemSpeedDamp = false;
}
Vector3 v = transform.forward * speed + Vector3.up * velocityY;
if (grounded)
{
velocity = ApplySlopeRotation(v, controller.radius + 0.5f);
}
else
{
velocity = v;
}
}
void Move(Vector3 v)
{
controller.Move(v * Time.deltaTime);
}
//FORCE FUNCTIONS
public void AddImpact(Vector3 dir, float force)
{
impact += dir.normalized * force / mass;
}
void BackCheck()
{
Vector3 n = Vector3.zero;
Vector3 p1 = transform.position + controller.center + new Vector3(0, controller.height / 2 - controller.radius * 1.5f, 0);
Vector3 p2 = transform.position + controller.center - new Vector3(0, controller.height / 2 - controller.radius * 1.5f, 0);
RaycastHit[] hits = Physics.CapsuleCastAll(p1, p2, controller.radius, -transform.forward, 0.02f, footSphereLayerMask);
foreach (RaycastHit item in hits)
{
if (item.rigidbody != null)
{
if (item.rigidbody.velocity.magnitude != 0)
{
n += item.normal;
AddImpact(n, 2f);
}
}
}
}
//USE EXISTING FOOTSPHERE TO DETECT GROUNDED ITL BE EASY, THEN ONLY APPLY THE Y FORCE WHEN NOT GROUNDED SO ROTATING WONT GET FUCKED UP WHEN YOU ARE STADNIG STILL.
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class DropShadow : MonoBehaviour {
public LayerMask layerMask;
public float yRayOffset;
public float yShadowOffset;
void Start ()
{
}
void FixedUpdate ()
{
if (transform.parent.tag == "ActionObject")
{
if (!transform.parent.gameObject.GetComponentsInChildren<KeyItem>()[0].inSlot || transform.parent.gameObject == PlayerActions.slotAObj)
{
GetComponent<Renderer>().material.SetColor("_Color", new Color(1, 1, 1, 0f));
}
else
{
Ray ray = new Ray(transform.parent.position - (yRayOffset * Vector3.up), Vector3.down);
RaycastHit hit;
if (Physics.Raycast(ray.origin, ray.direction, out hit, 50f, layerMask, QueryTriggerInteraction.Ignore))
{
float newYShadowOffset = yShadowOffset;
if (gameObject.transform.parent.GetComponent<Rigidbody>() != null)
{
newYShadowOffset = yShadowOffset - Mathf.Abs(gameObject.transform.parent.GetComponent<Rigidbody>().velocity.y / 75);
}
if (gameObject.transform.parent.GetComponent<PlayerMovementCC>() != null)
{
newYShadowOffset = yShadowOffset - Mathf.Abs(PlayerMovementCC.velocity.y / 75);
}
transform.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
transform.position = transform.parent.position + (hit.distance + newYShadowOffset) * Vector3.down;
GetComponent<Renderer>().material.SetColor("_Color", new Color(1, 1, 1, 0.2f - hit.distance / 15f));
}
else
{
transform.rotation = Quaternion.Euler(Vector3.zero);
transform.position = transform.parent.position + (yShadowOffset * Vector3.up);
GetComponent<Renderer>().material.SetColor("_Color", new Color(1, 1, 1, 0f));
}
}
}
else
{
Ray ray = new Ray(transform.parent.position - (yRayOffset * Vector3.up), Vector3.down);
RaycastHit hit;
if (Physics.Raycast(ray.origin, ray.direction, out hit, 50f, layerMask, QueryTriggerInteraction.Ignore))
{
float newYShadowOffset = yShadowOffset;
if (gameObject.transform.parent.GetComponent<Rigidbody>() != null)
{
newYShadowOffset = yShadowOffset - Mathf.Abs(gameObject.transform.parent.GetComponent<Rigidbody>().velocity.y / 75);
}
if (gameObject.transform.parent.GetComponent<PlayerMovementCC>() != null)
{
newYShadowOffset = yShadowOffset - Mathf.Abs(PlayerMovementCC.velocity.y / 75);
}
transform.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
transform.position = transform.parent.position + (hit.distance + newYShadowOffset) * Vector3.down;
GetComponent<Renderer>().material.SetColor("_Color", new Color(1, 1, 1, 0.2f - hit.distance / 15f));
}
else
{
transform.rotation = Quaternion.Euler(Vector3.zero);
if (!PlayerMovementCC.grounded)
{
GetComponent<Renderer>().material.SetColor("_Color", new Color(1, 1, 1, 0f));
}
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
using UnityEngine;
public class CamManager : MonoBehaviour {
public GameObject gimble;
public GameObject target;
private Camera cam;
private Vector3 orientation;
private Vector3 _ref;
private float _ref2;
float a;
float curA;
[HideInInspector] public static float targetA;
List<float> angles = new List<float>();
int angleIndex;
private bool axisIsDown = false;
//LERP STUFF
Vector3 startPos;
void Start ()
{
//45,90,135,180,225,270,315,0
angles.Add(0f);
angles.Add(45f);
angles.Add(90f);
angles.Add(135f);
angles.Add(180f);
angles.Add(225f);
angles.Add(270f);
angles.Add(315f);
angleIndex = PersistentManager.Instance.SceneAngles[SceneManager.GetActiveScene().buildIndex];
cam = Camera.main;
startPos = gimble.transform.position;
transform.position = new Vector3(target.transform.position.x, target.transform.position.y, target.transform.position.z);
}
void Update ()
{
if (!PlayerActions.dead)
{
if (PlayerActions.slotAObj != null)
{
if (PlayerActions.slotAObj.name == "Cannon" && PlayerActions.slotAObj.GetComponent<KeyItemUse>().active)
{
if (PlayerActions.slotAObj.GetComponentInChildren<ReticleController>().isColl)
{
transform.position = Vector3.SmoothDamp(transform.position, (target.transform.position + (PlayerActions.slotAObj.GetComponentInChildren<ReticleController>().gameObject.transform.position - target.transform.position) / 2), ref _ref, 0.5f);
}
else
{
Vector3 reticlePos = Vector3.Scale(PlayerActions.slotAObj.GetComponentInChildren<ReticleController>().gameObject.transform.position, new Vector3(1, 0, 1));
transform.position = Vector3.SmoothDamp(transform.position, (target.transform.position + (reticlePos - target.transform.position) / 2), ref _ref, 0.5f);
}
}
else
{
float speed = PlayerMovementCC.walkSpeed != 0 ? PlayerMovementCC.inputDir.normalized.magnitude : 0;
transform.position = Vector3.SmoothDamp(transform.position, (target.transform.position + target.transform.forward + (target.transform.forward * speed)), ref _ref, 0.5f);
}
}
else
{
float speed = PlayerMovementCC.walkSpeed != 0 ? PlayerMovementCC.inputDir.normalized.magnitude : 0;
transform.position = Vector3.SmoothDamp(transform.position, (target.transform.position + target.transform.forward + (target.transform.forward * speed)), ref _ref, 0.33f);
}
}
else
{
transform.position = Vector3.SmoothDamp(transform.position, PlayerActions.lastSpawnPos, ref _ref, 0.5f);
}
//Camera Rotation
curA = transform.rotation.eulerAngles.y;
if (Mathf.Round(Input.GetAxisRaw("CamRot")) != 0)
{
if (axisIsDown == false)
{
if (Mathf.Round(Input.GetAxisRaw("CamRot")) == -1f)
{
if (angleIndex == angles.Count - 1)
{
angleIndex = 0;
}
else
{
angleIndex += 1;
}
currentLerpTime = 0;
}
if (Mathf.Round(Input.GetAxisRaw("CamRot")) == 1f)
{
if (angleIndex == 0)
{
angleIndex = angles.Count - 1;
}
else
{
angleIndex -= 1;
}
currentLerpTime = 0;
}
axisIsDown = true;
}
}
if (Mathf.Round(Input.GetAxisRaw("CamRot")) == 0)
{
axisIsDown = false;
}
targetA = angles[angleIndex];
if (transform.rotation.eulerAngles.y != angles[angleIndex])
{
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(0, angles[angleIndex], 0), Time.deltaTime*6) /*Quaternion.Slerp(transform.rotation, Quaternion.Euler(0, angles[angleIndex], 0), Time.deltaTime)*/;
}
}
float lerpTime = 1f;
float currentLerpTime;
float moveDistance = 10f;
//Vector3 endPos;
//protected void Start()
//{
// startPos = transform.position;
// endPos = transform.position + transform.up * moveDistance;
//}
//protected void Update()
//{
// //reset when we press spacebar
// if (Input.GetKeyDown(KeyCode.Space))
// {
// currentLerpTime = 0f;
// }
// //increment timer once per frame
// currentLerpTime += Time.deltaTime;
// if (currentLerpTime > lerpTime)
// {
// currentLerpTime = lerpTime;
// }
// //lerp!
// float perc = currentLerpTime / lerpTime;
// transform.position = Vector3.Lerp(startPos, endPos, perc);
//}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SlotAPivot : MonoBehaviour {
void Update ()
{
var lookPos = PersistentManager.Instance.Player.transform.forward;
lookPos.y = 0;
var rotation = Quaternion.LookRotation(lookPos);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * 10f);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CannonLauncher : MonoBehaviour {
//BASICS (formatted for 2D, it's easy to translate to 3D just sub x for x and z):
//
// CONSTANT ACCELETARION IN STRAIGHT LINE:
// d = displacement, u = initial velocity, v = final velocity, a = acceleration, t = time
// 1): s = ((u+v)/2)t
// 2): v = u + at
// 3): s = ut + (a(t^2))/2
// 4): s = vt - (a(t^2))/2
// 5): v^2 = u^2 + 2as
//
// ARC CALCULATION DOES NOT HIT MOVING TARGETS
// . h .
// . | .
// . | . p
// . | |
// . | |
// a------------------------------------------'
//
// p = target point, a = starting point, g = -18m/s^2 downwards, h = height of arc,
//
// split the action into the three parts of the arc, represented as straight line equations.
//
// UP: displacement = h, acceleration = g (cos your counteracting gravity), final velocity = 0
// DOWN: displacement = Py - h, acceleration = g becuase of gravity, initial velocity = 0
// DISTANCE: displacement = Px, acceleration = 0 (air resistance would dampen acceleration, but is ignored), time = up(t) down(t)
public Transform start;
public Transform target;
public GameObject ball;
public GameObject armitureBase;
public Vector3 anglepoint;
public bool loaded;
float disY;
static public float h = 4;
public float gravity = Physics.gravity.y;
public bool debugPath;
private void Start()
{
armitureBase = gameObject.transform.GetChild(0).gameObject;
}
private void FixedUpdate()
{
if (debugPath)
{
DrawPath();
}
}
private void OnDrawGizmos()
{
Gizmos.DrawIcon(anglepoint, "sv_icon_dot8_pix16_gizmo");
}
public void Launch()
{
PlayerMovementCC.walkSpeed = 2.5f;
GameObject inst = Instantiate(ball, start.position, Quaternion.Euler(Vector3.zero));
inst.name = "Cannonball";
CannonBall cb = inst.GetComponent<CannonBall>();
Rigidbody rb = inst.GetComponent<Rigidbody>();
cb.active = true;
rb.useGravity = true;
if (!PlayerMovementCC.crouched)
{
rb.velocity = CalculateLaunchData().initialVelocity;
rb.AddTorque(armitureBase.transform.right, ForceMode.Impulse);
}
else
{
rb.velocity = PersistentManager.Instance.Player.transform.forward * 10;
rb.AddTorque(armitureBase.transform.right, ForceMode.Impulse);
}
loaded = false;
}
LaunchData CalculateLaunchData()
{
float displacementY = target.position.y - start.position.y;
if (displacementY > h)
{
displacementY = h;
}
Vector3 displacementXZ = new Vector3(target.position.x - start.position.x, 0, target.position.z - start.position.z);
float time = (Mathf.Sqrt(-2 * h / gravity) + Mathf.Sqrt(2 * (displacementY - h) / gravity));
Vector3 velocityY = Vector3.up * Mathf.Sqrt(-2 * gravity * h);
Vector3 velocityXZ = displacementXZ / time;
return new LaunchData (velocityXZ + velocityY * -Mathf.Sign(gravity), time);
}
void DrawPath()
{
LaunchData launchData = CalculateLaunchData();
Vector3 previousDrawPoint = start.position;
int resolution = 30;
for (int i = 1; i <= resolution; i++)
{
float simulationTime = i / (float)resolution * launchData.timeToTarget;
Vector3 displacement = launchData.initialVelocity * simulationTime + (gravity * Vector3.up) * simulationTime * simulationTime / 2f;
Vector3 drawPoint = start.position + displacement;
Debug.DrawLine(previousDrawPoint, drawPoint, Color.green);
previousDrawPoint = drawPoint;
if (i == 4)
{
anglepoint = drawPoint;
}
}
}
struct LaunchData
{
public readonly Vector3 initialVelocity;
public readonly float timeToTarget;
public LaunchData(Vector3 initialVelocity, float timeToTarget)
{
this.initialVelocity = initialVelocity;
this.timeToTarget = timeToTarget;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
using UnityEngine;
public class PersistentManager : MonoBehaviour {
public static PersistentManager Instance { get; private set; }
public string CurrentPuzzleID;
public string CurrentAreaID;
public bool Axis3IsDown;
public Color HUDColor;
public GameObject Player;
public GameObject HUD;
public List<int> SceneAngles = new List<int>();
private void Awake()
{
Application.targetFrameRate = 30;
QualitySettings.vSyncCount = 0;
for (int i = 0; i < SceneManager.sceneCountInBuildSettings; i++)
{
if (i == 0)
{
SceneAngles.Add(4);
}
}
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
Player = GameObject.Find("Player");
HUD = GameObject.Find("ScreenSpaceCanvas");
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KeyItem : MonoBehaviour
{
public Vector3 v;
//Action bools
public bool BSwap;
public bool ASwap;
public bool ABSwap;
public bool drop;
//bool fall;
public bool crouch;
//Properties
public bool inSlot;
public Mesh AMesh;
public Mesh BMesh;
public Mesh idleMesh;
public Vector3 AMeasurements;
public Vector3 BMeasurements;
public Vector3 slotBOffset;
public Vector3 slotBMeshOffset;
public Vector3 slotBRot;
public Vector3 slotAOffset;
public Vector3 slotARot;
Quaternion Arot;
Quaternion Brot;
Vector3 Apos;
Vector3 Bpos;
public GameObject currentSlot;
//Components
Rigidbody rb;
BoxCollider bc;
MeshCollider mc;
PlayerActions pa;
MeshRenderer mr;
SkinnedMeshRenderer smr;
//ect
public LayerMask layerMask;
private void Start()
{
rb = transform.parent.GetComponent<Rigidbody>();
bc = GetComponent<BoxCollider>();
mc = transform.parent.GetComponent<MeshCollider>();
pa = PersistentManager.Instance.Player.GetComponent<PlayerActions>();
if (transform.parent.GetComponentInChildren<SkinnedMeshRenderer>())
{
smr = transform.parent.GetComponentInChildren<SkinnedMeshRenderer>();
}
else if (transform.parent.GetComponentInChildren<MeshRenderer>())
{
mr = transform.parent.GetComponentInChildren<MeshRenderer>();
}
AMeasurements = AMesh.bounds.size;
BMeasurements = BMesh.bounds.size;
}
private void Update()
{
if (gameObject.transform.parent.name != "BombBox")
{
UpdateTransforms();
if (currentSlot != null)
{
crouch = CrouchCheck();
if (currentSlot.name == "SlotB")
{
if (PlayerActions.targetObject != null)
{
BSwap = BSwapCheck(PlayerActions.targetObject);
}
drop = DropCheck();
if (transform.parent.name != "Cannonball")
{
ABSwap = ABSwapCheck(gameObject, PlayerActions.slotA, slotAOffset, slotARot, AMeasurements);
}
}
if (currentSlot.name == "SlotA")
{
drop = DropCheck();
if (transform.parent.name != "Cannonball")
{
if (transform.parent.name == "Hammer")
{
ABSwap = ABSwapCheck(gameObject, PlayerActions.slotB, new Vector3(0,0,-0.25f), slotBRot, BMeasurements * 1.75f);
}
else
{
ABSwap = ABSwapCheck(gameObject, PlayerActions.slotB, slotBOffset, slotBRot, BMeasurements);
}
}
}
}
else
{
BSwap = BSwapCheck(null);
}
InSlot();
}
else
{
if (PlayerActions.slotBObj == null)
{
BSwap = BSwapCheck(null);
}
else
{
BSwap = false;
}
}
UIEffect();
}
void UpdateTransforms()
{
Arot = Quaternion.Euler(PlayerActions.slotA.transform.rotation.eulerAngles + slotARot);
Brot = Quaternion.Euler(PlayerActions.slotB.transform.rotation.eulerAngles + slotBRot);
Apos = PlayerActions.slotA.transform.position + (transform.parent.transform.forward * slotAOffset.x + transform.parent.transform.up * slotAOffset.y + transform.parent.transform.right * slotAOffset.z);
Bpos = PlayerActions.slotB.transform.position + (transform.parent.transform.forward * slotBOffset.x + transform.parent.transform.up * slotBOffset.y + transform.parent.transform.right * slotBOffset.z);
}
bool boxCast(GameObject keyItem, GameObject slot, Vector3 offset, Vector3 angleOffset, Vector3 measurements)
{
if (keyItem != null)
{
GameObject player = PersistentManager.Instance.Player;
Quaternion r = Quaternion.Euler(slot.transform.rotation.eulerAngles + angleOffset);
Vector3 o = slot.transform.right * offset.x/100 + slot.transform.up * offset.y/100 + slot.transform.forward * offset.z/100;
Vector3 c = new Vector3(slot.transform.position.x, slot.transform.position.y + measurements.y / 2, slot.transform.position.z) + player.transform.forward / 5 + o;
Debug.DrawRay(c, Vector3.Scale(Vector3.Scale(measurements / 2.25f, new Vector3(1, 1, 1)), slot.transform.forward));
Debug.DrawRay(c, Vector3.Scale(Vector3.Scale(measurements / 2.25f, new Vector3(1, 1, 1)), -slot.transform.forward));
Debug.DrawRay(c, Vector3.Scale(Vector3.Scale(measurements / 2.25f, new Vector3(1, 1, 1)), slot.transform.up));
Debug.DrawRay(c, Vector3.Scale(Vector3.Scale(measurements / 2.25f, new Vector3(1, 1, 1)), -slot.transform.up));
Debug.DrawRay(c, Vector3.Scale(Vector3.Scale(measurements / 2.25f, new Vector3(1, 1, 1)), slot.transform.right));
Debug.DrawRay(c, Vector3.Scale(Vector3.Scale(measurements / 2.25f, new Vector3(1, 1, 1)), -slot.transform.right));
if (!PlayerMovementCC.grounded)
{
return Physics.CheckBox(c - new Vector3(0, 0.5f, 0), Vector3.Scale(measurements / 2.25f, new Vector3(1, 1, 1)), r, layerMask, QueryTriggerInteraction.Ignore);
}
else return Physics.CheckBox(c, Vector3.Scale(measurements / 2.25f, new Vector3(1, 1, 1)), r, layerMask, QueryTriggerInteraction.Ignore);
}
else
{
return true;
}
}
bool BSwapCheck(GameObject target)
{
if (gameObject.transform.parent.name == "BombBox")
{
if (PlayerActions.slotBObj != null)
{
return false;
}
else
{
if (target != null)
{
if (!boxCast(gameObject, currentSlot, slotBOffset, slotBRot, BMeasurements) && !boxCast(target.GetComponentInChildren<KeyItem>().gameObject, currentSlot, target.GetComponentInChildren<KeyItem>().slotBOffset, target.GetComponentInChildren<KeyItem>().slotBRot, target.GetComponentInChildren<KeyItem>().BMeasurements))
{
return true;
}
else
{
return false;
}
}
else
{
if (!boxCast(gameObject, PlayerActions.slotB, slotBOffset, slotBRot, BMeasurements))
{
return true;
}
else
{
return false;
}
}
}
}
else
{
if (target != null)
{
if (!boxCast(gameObject, currentSlot, slotBOffset, slotBRot, BMeasurements) && !boxCast(target.GetComponentInChildren<KeyItem>().gameObject, currentSlot, target.GetComponentInChildren<KeyItem>().slotBOffset, target.GetComponentInChildren<KeyItem>().slotBRot, target.GetComponentInChildren<KeyItem>().BMeasurements))
{
return true;
}
else
{
return false;
}
}
else
{
if (!boxCast(gameObject, PlayerActions.slotB, slotBOffset, slotBRot, BMeasurements))
{
return true;
}
else
{
return false;
}
}
}
}
bool ASwapCheck(GameObject target)
{
if (!boxCast(gameObject, currentSlot, slotAOffset, slotARot, AMeasurements) && !boxCast(target, currentSlot, target.GetComponent<KeyItem>().slotAOffset, target.GetComponent<KeyItem>().slotARot, AMeasurements))
{
return true;
}
else
{
return false;
}
}
bool ABSwapCheck(GameObject target, GameObject targetSlot, Vector3 offset, Vector3 angleOffset, Vector3 measurements)
{
if (!boxCast(target, targetSlot, offset, angleOffset, measurements))
{
return true;
}
else
{
return false;
}
}
bool DropCheck()
{
if (currentSlot.name == "SlotB")
{
if (gameObject.transform.parent.name == "Hammer")
{
if (!boxCast(gameObject, currentSlot, slotBOffset + new Vector3(0, -100f,0), slotBRot, BMeasurements))
{
return true;
}
else
{
return false;
}
}
else
{
if (!boxCast(gameObject, currentSlot, slotBOffset, slotBRot, BMeasurements))
{
return true;
}
else
{
return false;
}
}
}
if (currentSlot.name == "SlotA")
{
if (!boxCast(gameObject, currentSlot, slotAOffset, slotARot, AMeasurements))
{
return true;
}
else
{
return false;
}
}
return false;
}
bool CrouchCheck()
{
if (PlayerMovementCC.grounded && !PlayerMovementCC.balancing)
{
if (currentSlot.name == "SlotA")
{
if (!boxCast(gameObject, PlayerActions.slotB, new Vector3(0, -43, 55), new Vector3(0, 90, 0), new Vector2(BMeasurements.y, BMeasurements.x * 2f)))
{
return true;
}
else
{
return false;
}
}
if (currentSlot.name == "SlotB")
{
return drop;
}
}
return false;
}
public void Pickup(GameObject slot, GameObject replace)
{
currentSlot = slot;
if (replace == null)
{
inSlot = true;
PlayerActions.slotBObj = gameObject.transform.parent.gameObject;
InSlot();
}
else
{
inSlot = true;
InSlot();
replace.GetComponentInChildren<KeyItem>().Drop();
PlayerActions.slotBObj = gameObject.transform.parent.gameObject;
}
}
public void Swap(GameObject swapToSlot)
{
currentSlot = swapToSlot;
}
public void Drop()
{
if (currentSlot.name == "SlotA")
{
PlayerActions.slotAObj = null;
}
else
{
PlayerActions.slotBObj = null;
}
inSlot = false;
rb.velocity = Vector3.zero;
rb.AddForce(PersistentManager.Instance.Player.transform.up / 2, ForceMode.Impulse);
}
public void InSlot()
{
if (gameObject != null && rb != null)
{
if (inSlot)
{
bc.center = new Vector3(0, 0, 0);
if (rb.gameObject.layer != 14)
{
rb.gameObject.layer = 14;
rb.useGravity = false;
rb.freezeRotation = true;
}
if (currentSlot.name == "SlotB")
{
transform.parent.rotation = Brot;
transform.parent.position = Bpos;
mc.sharedMesh = BMesh;
gameObject.transform.parent.GetChild(0).position =
currentSlot.transform.GetChild(0).transform.position +
(currentSlot.transform.GetChild(0).transform.right * slotBMeshOffset.x +
currentSlot.transform.GetChild(0).transform.up * slotBMeshOffset.y +
currentSlot.transform.GetChild(0).transform.forward * slotBMeshOffset.z);
//will be replaced by animation VvVv
bc.size = BMesh.bounds.size;
}
else
{
transform.parent.rotation = Arot;
transform.parent.position = Apos;
mc.sharedMesh = AMesh;
gameObject.transform.parent.GetChild(0).position = currentSlot.transform.GetChild(0).transform.position;
//will be replaced by animation VvVv
bc.size = AMesh.bounds.size;
}
}
else
{
Vector3 notInSlotBoundsSize = idleMesh.bounds.size * 2f;
for (int i = 0; i < 3; i++)
{
if (notInSlotBoundsSize[i] < 1)
{
notInSlotBoundsSize[i] = 1;
}
}
if (rb.gameObject.layer != 13)
{
rb.gameObject.layer = 13;
rb.freezeRotation = false;
rb.useGravity = true;
}
if (mc.sharedMesh != idleMesh || bc.size != notInSlotBoundsSize)
{
//will be replaced by animation VvVv
bc.size = notInSlotBoundsSize;
mc.sharedMesh = idleMesh;
}
if (currentSlot != null)
{
transform.parent.transform.position = gameObject.transform.parent.GetChild(0).transform.position;
gameObject.transform.parent.GetChild(0).transform.localPosition = Vector3.zero;
currentSlot = null;
}
}
}
}
IEnumerator respawnCoroutine(Vector3 Pos)
{
rb.velocity = Vector3.zero;
if (mr != null)
{
mr.enabled = false;
}
else
{
smr.enabled = false;
}
yield return new WaitForSeconds(0.6f);
transform.parent.position = Pos;
for (int i = 0; i < 5; i++)
{
yield return new WaitForSeconds(0.1f);
if (mr != null)
{
if (mr.enabled)
{
mr.enabled = false;
}
else
{
mr.enabled = true;
}
}
else
{
if (smr.enabled)
{
smr.enabled = false;
}
else
{
smr.enabled = true;
}
}
}
}
public void Die(Vector3 respawnPoint)
{
if (!inSlot)
{
if (transform.parent.name == "Cannon")
{
if (GetComponentInParent<CannonLauncher>().loaded)
{
StartCoroutine(respawnCoroutine(respawnPoint));
GetComponentInParent<CannonLauncher>().loaded = false;
}
else
{
StartCoroutine(respawnCoroutine(respawnPoint));
}
}
else
{
StartCoroutine(respawnCoroutine(respawnPoint));
}
}
}
void UIEffect()
{
//if (PlayerActions.targetObject == gameObject.transform.parent.gameObject && BSwap || ASwap)
//{
// if (GetComponentInParent<Renderer>().material.GetFloat("_Offset_Z") == 0)
// {
// GetComponentInParent<Renderer>().material.SetFloat("_Offset_Z", -0.005f);
// }
//}
//else
//{
// if (GetComponentInParent<Renderer>().material.GetFloat("_Offset_Z") != 0)
// {
// GetComponentInParent<Renderer>().material.SetFloat("_Offset_Z", 0);
// }
//}
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.layer == 12 && gameObject.transform.parent.name != "BombBox")
{
if (!inSlot && rb.velocity.y >= 0 && transform.parent.gameObject.name != "Cannonball")
{
rb.AddForce(new Vector3(
other.gameObject.GetComponent<CharacterController>().velocity.x * 0.8f,
other.gameObject.GetComponent<CharacterController>().velocity.y * 0.4f,
other.gameObject.GetComponent<CharacterController>().velocity.z * 0.8f), ForceMode.VelocityChange);
}
}
}
}
<file_sep>using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(TrackTransforms))]
public class TrackTransformsEditor : Editor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
//COULD NOT FIGURE OUT HOW TO USE TOGGLE BUTTONS???
/*TrackTransforms myTrackTransforms = (TrackTransforms)target;
EditorGUILayout.BeginHorizontal();
GUILayout.Label("Tracking Target");
myTrackTransforms.obj = (GameObject)EditorGUILayout.ObjectField(myTrackTransforms.obj, typeof(GameObject), true);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
GUILayout.Label("Track Position");
trackPosition = EditorGUI.Toggle(new Rect(0, 5, position.width, 20), )
EditorGUILayout.EndHorizontal();
//EditorGUI.BeginDisabledGroup(myTrackTransforms.trackPosBool);
EditorGUILayout.BeginHorizontal();
GUILayout.Label("Transform Offset");
myTrackTransforms.posOffset = EditorGUILayout.Vector3Field(GUIContent.none, myTrackTransforms.posOffset);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
GUILayout.Label("Transofrm Factor");
myTrackTransforms.posFactor = EditorGUILayout.Vector3Field(GUIContent.none, myTrackTransforms.posFactor);
EditorGUILayout.EndHorizontal();
//EditorGUI.EndDisabledGroup();
EditorGUILayout.BeginHorizontal();
GUILayout.Label("Track Y Rotation");
myTrackTransforms.trackPosBool = EditorGUILayout.Toggle(false);
EditorGUILayout.EndHorizontal();*/
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Barricade : MonoBehaviour
{
BoxCollider bc;
Animator anim;
SkinnedMeshRenderer mr;
bool blink;
IEnumerator coroutine()
{
yield return new WaitForSeconds(0.4f);
for (int i = 0; i < 5; i ++)
{
yield return new WaitForSeconds(0.1f);
if (mr.enabled)
{
mr.enabled = false;
}
else
{
mr.enabled = true;
}
}
Destroy(gameObject);
}
private void Start()
{
bc = GetComponent<BoxCollider>();
anim = GetComponent<Animator>();
mr = GetComponentInChildren<SkinnedMeshRenderer>();
}
private void Update()
{
if (blink)
{
StartCoroutine(coroutine());
blink = false;
}
}
void Break()
{
bc.enabled = false;
anim.SetBool("Broken", true);
blink = true;
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.name == "Cannonball")
{
if (collision.gameObject.GetComponent<CannonBall>().active)
{
Break();
}
}
}
}
| 6f96c9668b4d86fb61638fdee173851bc1771dd3 | [
"C#"
] | 26 | C# | Kalcen/1-5-18 | db3f9d3b020e5379849e320a76e56441521a8e09 | 3f83eb823cbf4980ab0947a479e00bbe3696ed04 | |
refs/heads/master | <file_sep>## Jadoo, the space alien has challenged Koba to a friendly duel. He asks Koba to write a program to print out all numbers
## from 70 to 80. Knowing perfectly well how easy the problem is, the Jadoo adds his own twist to the challenge.
## He asks Koba to write the program without using a single number in his program and also restricts the character limit to 100.
# ord('F') = 70
print(ord('F'))
print(ord('G'))
print(ord('H'))
print(ord('I'))
print(ord('J'))
print(ord('K'))
print(ord('L'))
print(ord('M'))
print(ord('N'))
print(ord('O'))
print(ord('P'))
| d03a52d732fb5990b0bb1f238f981187fcb0773b | [
"Python"
] | 1 | Python | ZainebPenwala/HackerEarth-Python | b9c9e7ca1e481d24b13f3a1d2e1d39f9a50a5d15 | 31913b19bb66ec8c937bd07e9864b59aa8a1d2a0 | |
refs/heads/master | <file_sep>//
// Bubble.cpp
// learningBubbles
//
// Created by <NAME> on 4/15/15.
//
//
#include "Bubble.h"
Bubble::Bubble(){
pos = ofVec2f(300, 300);
vel = ofVec2f(ofRandom(-10,10), ofRandom(-10,10));;
rad = 30;
myColor = ofColor(ofRandom(255),ofRandom(255),ofRandom(255));
rot = 0;
}
void Bubble::setup(float _x, float _y){
pos = ofVec2f(_x, _y);
birth = pos;
}
void Bubble::update(){
pos += vel;
rot+=abs(vel.x);
float distance = ofDist(birth.x,birth.y,pos.x, pos.y);
float bright = ofMap(distance, 0, 400, 255, 0);
myColor.a = bright;
}
void Bubble::draw(){
ofSetColor(myColor);
//option1
ofPushMatrix();
ofTranslate(pos);
ofRotate(rot);
ofCircle(0,0 , rad);
ofPopMatrix();
///option2
// ofPushMatrix();
// ofRotate(rot);
// ofCircle(pos, rad);
// ofPopMatrix();
}<file_sep>#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
ofSetCircleResolution(3);
}
//--------------------------------------------------------------
void ofApp::update(){
Bubble tempBubble;
tempBubble.setup(ofGetMouseX(),ofGetMouseY());
bubbles.push_back(tempBubble);
for (int i = 0; i< bubbles.size(); i++) {
bubbles[i].update();
float distance = ofDist(bubbles[i].birth.x, bubbles[i].birth.y, bubbles[i].pos.x, bubbles[i].pos.y);
if (distance>400) {
bubbles.erase(bubbles.begin()+i);
i--;
}
}
}
//--------------------------------------------------------------
void ofApp::draw(){
for (int i = 0; i< bubbles.size(); i++) {
bubbles[i].draw();
}
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| f9cd796e7612156ec401597402a29104cd4b47fe | [
"C++"
] | 2 | C++ | EDPX3701-AdvCoding/Bubbles_Example | 1606236e028dc21c30939187902160e419c015bb | 5bfd6acdf865de7758ff69f4ace7e4eb64eb8980 | |
refs/heads/master | <repo_name>dulhaniAshish/GIFted<file_sep>/script.js
const input = document.querySelector('input.search');
const container = document.querySelector('#container');
const loader = document.querySelector('.loading');
const modal = document.getElementById('myModal');
const img = document.getElementById('myImg');
const modalImg = document.getElementById("img01");
const captionText = document.getElementById("caption");
const span = document.getElementsByClassName("close")[0];
const SearchState = new State('searchText');
const Pagination = new State('pagination', 'int');
const FetchState = new State('fetching', 'boolean');
const LimitReachedState = new State('maxLimitForAPIReached', 'boolean');
const DEBOUNCE_TIME = config.UTILS.DEBOUNCE_TIME; // ms
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('./sw.js')
.then(registration => {
console.log(`Service Worker registered! Scope: ${registration.scope}`);
})
.catch(err => {
console.log(`Service Worker registration failed: ${err}`);
});
});
}
function showLoader(show) {
FetchState.changeState(show);
loader.style.display = show ? 'block' : 'none';
}
function getDistFromBottom() {
const scrollPosition = window.pageYOffset;
const windowSize = window.innerHeight;
return Math.max(container.offsetHeight - (scrollPosition + windowSize), 0);
}
document.addEventListener('scroll', function () {
const distToBottom = getDistFromBottom();
if (!LimitReachedState.getCurrentState().current && !FetchState.getCurrentState().current && distToBottom >= 0 && distToBottom <= (window.innerHeight * (3 / 4))) {
searchForGIFs(SearchState.getCurrentState().current, Pagination.getCurrentState().current);
}
});
window.onload = function () {
searchForGIFs(SearchState.getCurrentState().current);
};
input.oninput = debounce(handleSearchQueryChange, DEBOUNCE_TIME);
span.onclick = function () {
modal.style.display = "none";
};
function handleSearchQueryChange(event) {
let value = event.target.value.trim();
if (value !== SearchState.getCurrentState().current) {
if (value.length === 0) {
value = "";
}
container.innerHTML = "";
SearchState.changeState(value);
Pagination.changeState(0, 'int');
LimitReachedState.changeState(false, 'boolean');
searchForGIFs(value);
}
}
function addPaginationOffset(count) {
Pagination.changeState(Pagination.getCurrentState().current + count);
}
function showModal() {
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.title;
}
function searchForGIFs(text, offset = 0) {
showLoader(true);
const fn = !!text ? APIRequest.SEARCH : APIRequest.TRENDING;
fn(text, offset)
.then((response) => {
const {data, pagination} = response;
const _modified = data.map((el) => {
const {title, id} = el;
const hasPreview = el['images'].hasOwnProperty('preview_gif');
const selector = hasPreview ? 'preview_gif' : 'fixed_height_still';
const stageOne = el['images'][`${isMobile() ? selector : 'original'}`]; // for quickly loading
const finalStage = el['images'][`${isMobile() ? 'fixed_height' : 'original'}`];
const bestMatch = findAppropriateSize(el['images']);
return {
title,
id,
low: stageOne,
high: finalStage,
}
});
return Promise.resolve({
data: _modified,
pagination,
});
})
.then((response) => {
const {data, pagination} = response;
addPaginationOffset(Number.parseInt(pagination['count']));
const totalCount = pagination['total_count'];
if (Pagination.getCurrentState().current === Number.parseInt(totalCount)) {
LimitReachedState.changeState(true);
}
const fragment = document.createDocumentFragment();
console.time('add els');
data.forEach((el) => {
fragment.appendChild(getImageDomElement(el));
});
container.appendChild(fragment);
console.timeEnd('add els');
showLoader(false);
})
.catch((err) => {
console.warn('Error:', err);
showLoader(false);
LimitReachedState.changeState(true);
})
}
function getImageDomElement(el) {
const divContainer = document.createElement('div');
const domImage = document.createElement('img');
domImage.classList.add('gif_item');
domImage.classList.add('shine');
const {
title,
id,
low,
high
} = el;
domImage.setAttribute('title', title);
domImage.setAttribute('src', low['url']);
domImage.setAttribute('id', id);
// domImage.style.display = 'flex';
const addActiveUrl = () => domImage.setAttribute('src', high['url']);
const addStillUrl = () => domImage.setAttribute('src', low['url']);
const expectedWidth = `${high['width']}px`;
domImage.addEventListener('mouseover', addActiveUrl);
domImage.addEventListener('mouseout', addStillUrl);
domImage.addEventListener('load', () => {
const highResDownloaded = (domImage.getAttribute('src') === high['url']);
!highResDownloaded ?
domImage.classList.remove('s') : // remove shimmer
domImage.removeEventListener('mouseout', addStillUrl); // best gif downloaded
// no need to revert to preview url on mouse out
if (highResDownloaded) {
domImage.onclick = showModal;
}
});
domImage.style.height = '200px';
const idealWidth = 200 * config.UTILS.IDEAL_ASPECT_RATIO;
const toleranceWidthMin = (config.UTILS.IDEAL_ASPECT_RATIO - config.UTILS.TOLERANCE) * 200;
const toleranceWidthMax = (config.UTILS.IDEAL_ASPECT_RATIO + config.UTILS.TOLERANCE) * 200;
const currentWidth = Number.parseInt(high['width']);
if (currentWidth <= toleranceWidthMax && currentWidth >= toleranceWidthMin) {
domImage.style.width = expectedWidth;
} else {
domImage.style.width = `${idealWidth}px`;
}
divContainer.appendChild(domImage);
return divContainer;
}
<file_sep>/network.js
const APIRequest = (function gen() {
const API_KEY = config.GIPHY.API_KEY;
const HOST = config.GIPHY.HOST_URL;
const BASE_URL = `${HOST}`;
const GET = (endpoint) => {
const API_PATH = endpoint;
return function (string, offset = 0) {
const finalUrl = `${BASE_URL}${API_PATH}?q=${string}&api_key=${API_KEY}&offset=${offset}`;
return fetch(finalUrl)
.then((blob) => {
if (blob['status'] === 200)
return blob.json();
else throw new Error('Some error in fetching');
})
.then((res) => {
if (res['meta']['status'] === 200) {
return res;
}
})
}
};
return {
SEARCH: GET(config.GIPHY.SEARCH_ENDPOINT),
TRENDING: GET(config.GIPHY.TRENDING_ENDPOINT),
}
}());<file_sep>/README.md
# GIFted
Fetch GIFs from giphy
<file_sep>/config.js
const config = {
GIPHY: {
API_KEY: '<KEY>',
HOST_URL: 'http://api.giphy.com',
SEARCH_ENDPOINT: '/v1/gifs/search',
TRENDING_ENDPOINT: '/v1/gifs/trending',
},
UTILS: {
MAX_GIF_SIZE: 500 * 1000,
DEBOUNCE_TIME: 500,
IDEAL_ASPECT_RATIO: 1.33,
TOLERANCE: 0.75,
}
}; | c6470ec396b9500571aa06ea3c03b0741a4f2a03 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | dulhaniAshish/GIFted | c9df2b576440eeb5cb84c10d0f8a923921c873e6 | 2c9a41cc79d69664ccf7c6155e7c5ed875bbc786 | |
refs/heads/master | <file_sep>import React, { Component } from 'react';
// import axios from 'axios';
// import axios from '../../axios'; //load the axios.js that we created our instance in
import Posts from './Posts/Posts';
// import FullPost from './FullPost/FullPost';
import NewPost from './NewPost/NewPost';
import './Blog.css';
import {Route, NavLink, Switch, Redirect} from 'react-router-dom';
class Blog extends Component {
state = {
auth: true
};
render () {
return (
<div className="Blog">
<header>
<nav>
<ul>
{/*<li><Link to="/">Home</Link></li>*/}
<li>
<NavLink
to="/posts/"
exact
activeClassName="my-active"
activeStyle={{
color: '#fa923f',
textDecoration: 'underline'
}}>
Posts
</NavLink>
</li>
<li><NavLink to={{
// pathname: this.props.match.url + '/new-post', //relative path appends to current url
pathname: '/new-post', //absolute path appends to root domain
hash: '#submit',
search: '?quick-submit=true'
}}>New Post</NavLink></li>
</ul>
</nav>
</header>
{/*<Route path="/" exact render={() => <Posts/>}/>*/}
{/*<Route path="/new-post" exact render={() => <NewPost/>}/>*/}
{/*Routes are processed in order. Without the Switch it could process more than one route. Switch processes first route that matches*/}
{/* the path "/" will match "/", "/1", etc. Anything that begins with a slash*/}
<Switch>
{this.state.auth ? <Route path="/new-post" component={NewPost}/> : null}
<Route path="/posts" component={Posts}/>
{/*<Route path="/" component={Posts}/>*/}
<Redirect exact from="/" to="/posts"/>
<Route render={() => <h1>Page Not Found</h1>}/>
</Switch>
</div>
);
};
}
export default Blog;<file_sep>import axios from 'axios';
const instance = axios.create({
baseURL: 'https://jsonplaceholder.typicode.com'
});
instance.defaults.headers.common['Authorization'] = 'AUTH TOKEN FROM INSTANCE';
instance.interceptors.request.use(request => {
console.log(request);
//edit request config
return request;
}, error => { // the error is only to handle errors sending the request like no internet connection
console.log(error);
return Promise.reject(error); //i think this re-throws the error
});
instance.interceptors.response.use(response => {
console.log(response);
//edit request config
return response;
}, error => { // this handles any errors in the response from the server like bad url
console.log(error);
return Promise.reject(error); //i think this re-throws the error
});
export default instance;<file_sep>import React from 'react';
import {withRouter} from 'react-router-dom'; //withRouter makes a component route aware (passes route props to child component
import './Post.css';
const post = (props) => {
console.log(props);
return (
<article className="Post" onClick={props.clicked}>
<h1 className="GetShwifty">{props.title}</h1>
<div className="Info">
<div className="Author">{props.author}</div>
</div>
</article>
);
};
//I added the CSS class GetShwifty to NewPost.css to show that it is global once imported
export default withRouter(post);<file_sep>import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import axios from 'axios';
axios.defaults.baseURL = 'https://jsonplaceholder.typicode.com';
axios.defaults.headers.common['Authorization'] = 'AUTH TOKEN';
axios.defaults.headers.post['Content-Type'] = 'application/json'; //this is already the default, just here to show that you can set it to something
axios.interceptors.request.use(request => {
console.log(request);
//edit request config
return request;
}, error => { // the error is only to handle errors sending the request like no internet connection
console.log(error);
return Promise.reject(error); //i think this re-throws the error
});
axios.interceptors.response.use(response => {
console.log(response);
//edit request config
return response;
}, error => { // this handles any errors in the response from the server like bad url
console.log(error);
return Promise.reject(error); //i think this re-throws the error
});
ReactDOM.render(<App/>, document.getElementById('root'));
registerServiceWorker();
| f521d44a81cbb4062a4a8091f614789a3d7862e7 | [
"JavaScript"
] | 4 | JavaScript | steve-short/react-ajax | e6ffa7647d5f6b7fd7126dd79d93a03c8177e490 | 1616784e9c62409c0d0fbaaf761a1123f4236c82 | |
refs/heads/master | <repo_name>vankhoenhadat/FirstRoR<file_sep>/app/helpers/rooms_helper.rb
module RoomsHelper
end
class RoomValidator
include Veto.validator
validates :name, :presence => {:message => "Tên phòng không để trống"}
validates :minrate, :inclusion => 0..100
end
<file_sep>/test/controllers/bookingtests_controller_test.rb
require 'test_helper'
class BookingtestsControllerTest < ActionController::TestCase
setup do
@bookingtest = bookingtests(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:bookingtests)
end
test "should get new" do
get :new
assert_response :success
end
test "should create bookingtest" do
assert_difference('Bookingtest.count') do
post :create, bookingtest: { active: @bookingtest.active, customer_name: @bookingtest.customer_name, from_date: @bookingtest.from_date, hotel_name: @bookingtest.hotel_name, night_number: @bookingtest.night_number, to_date: @bookingtest.to_date }
end
assert_redirected_to bookingtest_path(assigns(:bookingtest))
end
test "should show bookingtest" do
get :show, id: @bookingtest
assert_response :success
end
test "should get edit" do
get :edit, id: @bookingtest
assert_response :success
end
test "should update bookingtest" do
patch :update, id: @bookingtest, bookingtest: { active: @bookingtest.active, customer_name: @bookingtest.customer_name, from_date: @bookingtest.from_date, hotel_name: @bookingtest.hotel_name, night_number: @bookingtest.night_number, to_date: @bookingtest.to_date }
assert_redirected_to bookingtest_path(assigns(:bookingtest))
end
test "should destroy bookingtest" do
assert_difference('Bookingtest.count', -1) do
delete :destroy, id: @bookingtest
end
assert_redirected_to bookingtests_path
end
end
<file_sep>/app/models/room.rb
class Room
include Mongoid::Document
include Mongoid::Timestamps
field :name, type: String
field :descriptions, type: String
field :minrate, type: Float
field :active, type: Boolean
embedded_in :Booking
end
<file_sep>/app/models/bookingtest.rb
class Bookingtest
include Mongoid::Document
include Mongoid::Timestamps
field :customer_name, type: String
field :hotel_name, type: String
field :night_number, type: Integer
field :from_date, type: DateTime
field :to_date, type: DateTime
field :active, type: Boolean
default_scope ->{ where(active: true) }
embeds_many :Room
end
<file_sep>/app/controllers/rooms_controller.rb
class RoomsController < ApplicationController
before_action :set_room, only: [:show, :edit, :update, :destroy]
# GET /rooms
def index
@rooms = Room.all
end
# GET /rooms/1
def show
end
# GET /rooms/new
def new
@room = Room.new
@error =[]
# @error.push("sdfsdf")
end
# GET /rooms/1/edit
def edit
end
# POST /rooms
def create
# @room = Room.new(room_params)
@room = Room.new
@room.name = params[:room][:name]
@room.descriptions = params[:room][:descriptions]
@room.minrate = params[:room][:minrate]
validator = RoomValidator.new
# validator.valid?(@room)
# validator.validate!(@room) # => # => Veto::InvalidEntity, ["name is not present", "..."]
# validator.errors.full_messages # => ["first name is not present", "..."]
if validator.valid?(@room)
if @room.save
redirect_to @room, notice: 'Room was successfully created.'
else
render :new
end
else
@error = validator.errors.full_messages
render :new
end
end
# PATCH/PUT /rooms/1
def update
if @room.update(room_params)
redirect_to @room, notice: 'Room was successfully updated.'
else
render :edit
end
end
# DELETE /rooms/1
def destroy
@room.destroy
redirect_to rooms_url, notice: 'Room was successfully destroyed.'
end
private
# Use callbacks to share common setup or constraints between actions.
def set_room
@room = Room.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def room_params
params.require(:room).permit(:name, :descriptions, :minrate, :active)
end
end
<file_sep>/app/controllers/bookingtests_controller.rb
class BookingtestsController < ApplicationController
before_action :set_bookingtest, only: [:show, :edit, :update, :destroy]
# GET /bookingtests
def index
@bookingtests = Bookingtest.unscoped.page(params[:page]).per(2)
a=1
end
# GET /bookingtests/1
def show
email= params[:email]
password= params[:password]
subject= params[:subject]
issue_type= params[:issue_type]
priority= params[:priority]
description= params[:description]
end
# GET /bookingtests/new
def new
@bookingtest = Bookingtest.new
end
# GET /bookingtests/1/edit
def edit
end
# POST /bookingtests
def create
@bookingtest = Bookingtest.new(bookingtest_params)
@rooms = []
room = Room.new
room.name = "room Name";
room.descriptions = "descriptions"
room.minrate = 12345
room.active = true;
@rooms.push(room);
@bookingtest.Room = @rooms
if @bookingtest.save
redirect_to @bookingtest, notice: 'Bookingtest was successfully created.'
else
render :new
end
end
# PATCH/PUT /bookingtests/1
def update
rooms = params[:bookingtest][:Room]
booking = Bookingtest.new
booking._id = params[:id]
booking.customer_name = params[:bookingtest][:customer_name]
booking.hotel_name = params[:bookingtest][:hotel_name]
booking.night_number = params[:bookingtest][:night_number]
booking.Room = rooms
if @bookingtest.update(bookingtest_params)
@bookingtest.update_attribute(:Room, rooms)
redirect_to @bookingtest, notice: 'Bookingtest was successfully updated.'
else
render :edit
end
end
# DELETE /bookingtests/1
def destroy
@bookingtest.destroy
redirect_to bookingtests_url, notice: 'Bookingtest was successfully destroyed.'
end
private
# Use callbacks to share common setup or constraints between actions.
def set_bookingtest
@bookingtest = Bookingtest.unscoped.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def bookingtest_params
booking = params.require(:bookingtest).permit(:customer_name, :hotel_name, :night_number, :from_date, :to_date, :active)
booking
end
end
| 0d6717081f22182a46e06f150f935ed10679aaf9 | [
"Ruby"
] | 6 | Ruby | vankhoenhadat/FirstRoR | 8c859a8acca953b7ba770ea0ee269c9c5334fd9a | 739b5240a6b18234e3be7f263e47268e9711bf3a | |
refs/heads/master | <file_sep>package com.jamtu.fragments;
import static com.jamtu.fragments.LocaleJokeListFragment.JOKE_TYPE;
import android.os.Bundle;
import com.jamtu.adapter.ViewPageFragmentAdapter;
import com.jamtu.basefragment.BaseViewPagerFragment;
import com.jamtu.utils.AppOthers;
/**
* 发现页面
*
* @author lijq
* @created 2015-03-29
*/
public class JokePagerFragment extends BaseViewPagerFragment {
private final String[] TITLES = { "爱情", "幽默", "校园", "古代", "军事", "职场", "顺口溜", "成人", "儿童", "愚人", "短信", "尴尬" };
private final String[] TYPES = { "love", "humor", "campus", "ancient", "army", "job", "jingle", "adult",
"children", "fool", "sms", "embarrassed" };
public static JokePagerFragment newInstance() {
return new JokePagerFragment();
}
@Override
protected void onSetupTabAdapter(ViewPageFragmentAdapter adapter) {
AppOthers.showBothApp(getJokeApplication());
AppOthers.showInnerApp(getJokeApplication());
// String[] tabNames =
// getResources().getStringArray(R.array.joke_title_array);
int len = TITLES.length;
for (byte i = 0; i < len; i++) {
Bundle bundle = new Bundle();
bundle.putString(JOKE_TYPE, TYPES[i]);
adapter.addTab(TITLES[i], TITLES[i], JokeListFragment.class, bundle);
}
}
}
<file_sep>package com.jamtu.fragments;
import static com.jamtu.fragments.NetJokeListFragment.JOKE_URL;
import android.os.Bundle;
import com.jamtu.adapter.ViewPageFragmentAdapter;
import com.jamtu.basefragment.BaseViewPagerFragment;
import com.jamtu.utils.AppOthers;
/**
* 网络段子1
*
* @author lijq
* @created 2015-03-29
*/
public class QSBK_JokePagerFragment extends BaseViewPagerFragment {
public static QSBK_JokePagerFragment newInstance() {
return new QSBK_JokePagerFragment();
}
@Override
protected void onSetupTabAdapter(ViewPageFragmentAdapter adapter) {
AppOthers.showBothApp(getJokeApplication());
AppOthers.showInnerApp(getJokeApplication());
adapter.addTab("热门段子", "热门段子", NetJokeListFragment.class, getQSBKBundle(0));
adapter.addTab("热门趣图", "热门趣图", NetJokeListFragment.class, getQSBKBundle(1));
adapter.addTab("最新段子", "最新段子", NetJokeListFragment.class, getQSBKBundle(2));
adapter.addTab("最新趣图", "最新趣图", NetJokeListFragment.class, getQSBKBundle(3));
}
private final String QSBK_URL_Prefix = "http://www.qiushibaike.com/";
// 热门 8小时, 24小时, 穿越
private static final String[] QSBK_TYPES_HOT_TOPIC = { "8hr", "hot", "history" };
// 纯图 最热, 最新
private static final String[] QSBK_PURE_IMG = { "imgrank", "pic" };
// 纯文 最热, 最新
private static final String[] QSBK_PURE_TEXT = { "text", "textnew" };
public static final String[] QSBK_TYPES = { QSBK_PURE_TEXT[0], QSBK_PURE_IMG[0], QSBK_PURE_TEXT[1],
QSBK_PURE_IMG[1] };
private Bundle getQSBKBundle(int index) {
Bundle bundle = new Bundle();
bundle.putString(JOKE_URL, QSBK_URL_Prefix + QSBK_TYPES[index]);
return bundle;
}
}
<file_sep>package com.jamtu.utils;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import com.jamtu.config.PrefUtil;
import com.jamtu.config.Version;
/**
* MODE_MULTI_PROCESS 跨进程通信
*
* @author lijq
* @date 2013-10-9 下午04:52:08
* @version 1.0
*/
public class SharedUtil {
private static SharedPreferences eckShared;
private static DESUtils currDesUtils = new DESUtils();// 当前加密对象
private static DESUtils oldDesUtils = new DESUtils();// 旧版本加密对象
private static SharedPreferences getEckShared(Context context) {
if (null == eckShared) {
eckShared = context.getSharedPreferences(PrefUtil.PRE_FILE_NAME, Context.MODE_MULTI_PROCESS);
}
return eckShared;
}
// 将ShardPreferences中旧的K-V数据 更新为最新的
// 新旧K-V数据的不同 只是加密的密钥变了
public static void copy(Context context) {
try {
SharedPreferences sharedPreferences = getEckShared(context);
Map<String, ?> map = sharedPreferences.getAll();
Set<String> keySet = map.keySet();
Iterator<String> iterator = keySet.iterator();
int isFindAndSet = 0;
while (iterator.hasNext()) {
String key = iterator.next();
if (isFindAndSet == 0)
isFindAndSet = oldDesUtils.findAndSetKey(key);
switch (isFindAndSet) {
case -1:
if (Version.VERSION >= 1) {
copy(context, key, map.get(key));
removeOld(context, key);
}
break;
case 1:
Object objVal = map.get(key);
// 只有String类型的数据 采用KV加密,其他类型只加密K
if (objVal instanceof String) {
copy(context, oldDesUtils.decryptStr(key), oldDesUtils.decryptStr(objVal.toString()));
} else {
copy(context, oldDesUtils.decryptStr(key), objVal);
}
removeOld(context, key);
break;
}
iterator.remove();
}
} catch (Exception e) {
e.printStackTrace();
}
}
// 更新为最新的K-V数据后,旧的数据可以删除
private static void removeOld(Context context, String keyMi) {
SharedPreferences sharedPreferences = getEckShared(context);
Editor editor = sharedPreferences.edit();
editor.remove(keyMi);
editor.commit();
}
// 用最新的密钥对旧的K-V数据进行加密
private static void copy(Context context, String key, Object value) {
String val = value.toString();
if (value instanceof String) {
putString(context, key, val);
} else if (value instanceof Boolean) {
putBoolean(context, key, Boolean.parseBoolean(val));
} else if (value instanceof Integer) {
putInt(context, key, Integer.parseInt(val));
} else if (value instanceof Long) {
putLong(context, key, Long.parseLong(val));
}
}
public static void putString(Context context, String key, String value) {
SharedPreferences sharedPreferences = getEckShared(context);
Editor editor = sharedPreferences.edit();
editor.putString(currDesUtils.encryptStr(key), currDesUtils.encryptStr(value));
editor.commit();
}
public static String getString(Context context, String key, String defaultValue) {
SharedPreferences sharedPreferences = getEckShared(context);
return currDesUtils.decryptStr(sharedPreferences.getString(currDesUtils.encryptStr(key),
currDesUtils.encryptStr(defaultValue)));
}
public static void putBoolean(Context context, String key, Boolean value) {
SharedPreferences sharedPreferences = getEckShared(context);
Editor editor = sharedPreferences.edit();
editor.putBoolean(currDesUtils.encryptStr(key), value);
editor.commit();
}
public static Boolean getBoolean(Context context, String key, Boolean defaultValue) {
SharedPreferences sharedPreferences = getEckShared(context);
return sharedPreferences.getBoolean(currDesUtils.encryptStr(key), defaultValue);
}
public static void putLong(Context context, String key, long value) {
SharedPreferences sharedPreferences = getEckShared(context);
Editor editor = sharedPreferences.edit();
editor.putLong(currDesUtils.encryptStr(key), value);
editor.commit();
}
public static long getLong(Context context, String key, long defaultValue) {
SharedPreferences sharedPreferences = getEckShared(context);
return sharedPreferences.getLong(currDesUtils.encryptStr(key), defaultValue);
}
public static void putInt(Context context, String key, int value) {
SharedPreferences sharedPreferences = getEckShared(context);
Editor editor = sharedPreferences.edit();
editor.putInt(currDesUtils.encryptStr(key), value);
editor.commit();
}
public static int getInt(Context context, String key, int defaultValue) {
SharedPreferences sharedPreferences = getEckShared(context);
return sharedPreferences.getInt(currDesUtils.encryptStr(key), defaultValue);
}
public static void remove(Context context, String key) {
SharedPreferences sharedPreferences = getEckShared(context);
Editor editor = sharedPreferences.edit();
editor.remove(currDesUtils.encryptStr(key));
editor.commit();
}
public static void clear(Context context) {
SharedPreferences sharedPreferences = getEckShared(context);
Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
}
}
<file_sep>package com.jamtu.bean;
import com.jamtu.db.library.db.annotation.Column;
import com.jamtu.db.library.db.annotation.Id;
import com.jamtu.db.library.db.annotation.Table;
import com.jamtu.db.library.db.annotation.Transient;
@Table(name = "ijoke")
public class Joke extends Entity {
@Id
private int id;
@Column(column = "title")
private String title;
@Column(column = "content")
private String content;
@Column(column = "type")
private String type;
@Column(column = "typeDesc")
private String typeDesc;
@Transient
private Author author;
@Transient
private String img;
@Transient
private String statsVote;
public int getId() {
_id = String.valueOf(id);
return id;
}
public void setId(int id) {
this.id = id;
_id = String.valueOf(this.id);
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getTypeDesc() {
return typeDesc;
}
public void setTypeDesc(String typeDesc) {
this.typeDesc = typeDesc;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getStatsVote() {
return statsVote;
}
public void setStatsVote(String statsVote) {
this.statsVote = statsVote;
}
public boolean hasAuthor() {
if (null == author)
return false;
else
return true;
}
@Override
public String toString() {
return "Joke [id=" + id + ", title=" + title + ", content=" + content + ", type=" + type + ", typeDesc="
+ typeDesc + ", author=" + author + ", img=" + img + ", statsVote=" + statsVote + "]";
}
}
<file_sep>package com.jamtu.task;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import com.jamtu.App;
import com.jamtu.utils.AppUtil;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
/**
* 保存图片,不做任何图片压缩
*
* 保存到指定位置,并添加至相册
*
*/
public class SaveImgTask extends AsyncTask<Object, Void, Boolean> {
private String imgUrl;
private Context mContext;
public synchronized static void start(final Context context, final String url) {
new Handler(context.getMainLooper()).post(new Runnable() {
@Override
public void run() {
AppUtil.executeTask(new SaveImgTask(context, url));
}
});
}
private SaveImgTask(Context context, String url) {
mContext = context;
imgUrl = url;
}
@Override
protected Boolean doInBackground(Object... params) {
return saveFile(imgUrl, getDownloadDir(mContext));
}
@Override
protected void onPostExecute(Boolean result) {
if (result)
AppUtil.ToastMessage(mContext, "图片已保存至相册Pictures中");
}
public static File getDownloadDir(Context context) {
File dir = context.getFilesDir();
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
// 图片缓存放在SDCard/IJoke/...中
File file = Environment.getExternalStoragePublicDirectory("IJoke/Pictures/");
if (file != null) {
dir = file;
}
}
if (!dir.exists()) {
dir.mkdirs();
}
return dir;
}
// 保存图片文件 原图不作处理
public boolean saveFile(String url, File fileDir) {
BufferedInputStream bis = getInputStreamFromNetwork(url);
BufferedOutputStream bos = null;
boolean isOK = true;
String fileName = UUID.randomUUID() + ".jpg";
File file = new File(fileDir, fileName);
try {
if (null == bis)
isOK = false;
else {
// 首先保存图片
bos = new BufferedOutputStream(new FileOutputStream(file));
int read = 0;
byte[] buffer = new byte[1024];
while ((read = bis.read(buffer)) != -1) {
bos.write(buffer, 0, read);
}
bos.flush();
scanPhoto(mContext, file.getAbsolutePath());
// // 其次把文件插入到系统图库
// MediaStore.Images.Media.insertImage(mContext.getContentResolver(),
// file.getAbsolutePath(), fileName,
// null);
// // 最后通知图库更新
// mContext.sendBroadcast(new
// Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
// Uri.parse("file://" + file)));
}
} catch (Exception e) {
isOK = false;
file.delete();
} finally {
try {
if (null != bos)
bos.close();
if (null != bis)
bis.close();
} catch (Exception e2) {
}
}
return isOK;
}
/**
* 让Gallery上能马上看到该图片
*/
private static void scanPhoto(Context ctx, String imgFileName) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File file = new File(imgFileName);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
ctx.sendBroadcast(mediaScanIntent);
}
public BufferedInputStream getInputStreamFromNetwork(String url) {
BufferedInputStream bis = null;
try {
Request request = new Request.Builder().url(url).build();
Response response = App.getOkhttpclient().newCall(request).execute();
bis = new BufferedInputStream(response.body().byteStream());
} catch (Exception e) {
}
return bis;
}
}
<file_sep>package com.jamtu.service;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import com.jamtu.App;
import com.jamtu.config.PrefUtil;
import com.jamtu.utils.AppUtil;
import com.jamtu.utils.SharedUtil;
public class JokeService extends Service {
AlarmManager alarm;
PendingIntent mPending;
@Override
public void onCreate() {
super.onCreate();
setForeground();
setAlarm(this);
AppUtil.registerTimeReceiver(this);
}
private void setForeground() {
Notification notification = new Notification();
notification.flags = Notification.FLAG_ONGOING_EVENT;
notification.flags |= Notification.FLAG_NO_CLEAR;
notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
startForeground(0, notification);
}
private void setAlarm(Context context) {
Intent intent = new Intent(context, getClass());
alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
mPending = PendingIntent.getService(this, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
long now = System.currentTimeMillis();
alarm.setInexactRepeating(AlarmManager.RTC, now, 1 * 60 * 1000, mPending);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, START_STICKY, startId);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
stopForeground(true);
if (null != alarm && null != mPending)
alarm.cancel(mPending);
if (!SharedUtil.getBoolean(this, PrefUtil.PRE_KILL_SERVICE, false)) {
App.launchService(getApplicationContext());
}
AppUtil.unregisterTimeReceiver(this);
}
}
<file_sep>package com.jamtu.utils;
import android.content.Context;
public class AppOthers {
// *************************聚富********************************
// private static CManager initCManager(Context context, int mode) {
// return CManager.getManager(context, "03c9776e89d5bb7bd6d2a8ea5376158c",
// "official", mode);
// }
public static void showStartApp(Context context) {
// if (AppUtil.isAccess(context))
// initCManager(context, CManager.SHOW_START_APP).kids(context);
}
public static void showBothApp(Context context) {
// if (AppUtil.isAccess(context))
// initCManager(context,
// CManager.SHOW_BOTH_INSIDE_AND_OUTSIDE).kids(context);
}
// *************************聚富********************************
// -------------------------畅想--------------------------------
// private static com.ijoke.rrcp.CManager initCCManager(Context context) {
// return com.ijoke.rrcp.CManager.getCCManager(context,
// "30d920938a1540f6af584899225a10d0", "official");
// }
public static void showOutterApp(Context context) {
// if (AppUtil.isAccess(context))
// initCCManager(context).outter();
}
public static void showInnerApp(Context context) {
// if (AppUtil.isAccess(context))
// initCCManager(context).inner(-1, -1, null, 1);
}
// -------------------------畅想--------------------------------
// =========================亿途================================
public static void showOutters(Context context) {
// a.i(this, "060fa45cfe6fad02017ee1eec5e247aa");
}
// =========================亿途================================
}
<file_sep>package com.jamtu.bean;
import java.io.Serializable;
import com.google.gson.Gson;
import com.jamtu.db.library.db.annotation.Transient;
/**
* 实体类
*
*/
public abstract class Entity implements Serializable {
@Transient
protected String _id;
public String get_Id() {
return _id;
}
public void set_Id(String _id) {
this._id = _id;
}
// 缓存的key
@Transient
protected String cacheKey;
public String getCacheKey() {
return cacheKey;
}
public void setCacheKey(String cacheKey) {
this.cacheKey = cacheKey;
}
public static Object fromJson(String json, Class<?> clz) {
Gson gson = new Gson();
return gson.fromJson(json, clz);
}
}
<file_sep>package com.jamtu.fragments;
import static com.jamtu.fragments.LocaleJokeListFragment.JOKE_TYPE;
import android.os.Bundle;
import com.jamtu.adapter.ViewPageFragmentAdapter;
import com.jamtu.basefragment.BaseViewPagerFragment;
import com.jamtu.joke.R;
import com.jamtu.utils.AppOthers;
/**
* 发现页面
*
* @author lijq
* @created 2015-03-29
*/
public class LocaleJokePagerFragment extends BaseViewPagerFragment {
public static LocaleJokePagerFragment newInstance() {
return new LocaleJokePagerFragment();
}
@Override
protected void onSetupTabAdapter(ViewPageFragmentAdapter adapter) {
AppOthers.showBothApp(getJokeApplication());
AppOthers.showInnerApp(getJokeApplication());
String[] tabNames = getResources().getStringArray(R.array.joke_title_array);
for (byte i = 0; i < tabNames.length; i++) {
Bundle bundle = new Bundle();
bundle.putByte(JOKE_TYPE, i);
adapter.addTab(tabNames[i], tabNames[i], LocaleJokeListFragment.class, bundle);
}
}
}
<file_sep>package com.jamtu.config;
public interface PrefUtil {
// SharedPreference 文件名
String PRE_FILE_NAME = "joke";
// 主动调用stopService 方法 设置此值为 true
String PRE_KILL_SERVICE = "ks";
// 初始化数据库数据
String PRE_INIT_DB_DATA = "ida";
// 通过市场审核
String PRE_ACCESS_APP_MARKET = "aam";
// 数据库名称
String PRE_DATABASE_NAME = "ijoke";
// properties文件
String PRE_PROPERTIES_NAME = "joke.properties";
// 是否到达开启检查市场通过线程时间
String PRE_ACCESS_MARKET_VALID = "amv";
// 设置是否发出提示音
String PRE_CONF_VOICE = "conf_voice";
// 设置启用检查更新
String PRE_CONF_CHECKUP = "conf_checkup";
// APP 检查更新 1天/次
// String PRE_APP_UPDATE = "au";
// APP 第一次启动
String PRE_APP_FIRST_START = "afs";
// =======================URL======================
String ACCESS_MARKET_URL = "http://7xj1fi.com1.z0.glb.clouddn.com/joke_v5.txt";
String UPDATE_URL = "http://7xj1fi.com1.z0.glb.clouddn.com/update.txt";
}
<file_sep>package com.jamtu.utils;
import android.app.ActivityManager;
import android.app.NotificationManager;
import android.content.Context;
import android.net.ConnectivityManager;
import android.os.PowerManager;
import android.telephony.TelephonyManager;
import android.view.WindowManager;
public class SystemServiceUtils {
private static NotificationManager notificationManager = null;
private static TelephonyManager telephonyManager = null;
private static ConnectivityManager connectivityManager = null;
private static WindowManager windowManager = null;
private static ActivityManager activityManager = null;
private static PowerManager powerManager = null;
/**
* 取得通知管理器服务
*
* @param context
* @return
*/
public static PowerManager getPowerManager(Context context) {
if (context != null && powerManager == null)
powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
return powerManager;
}
/**
* 取得通知管理器服务
*
* @param context
* @return
*/
public static NotificationManager getNotificationManager(Context context) {
if (context != null && notificationManager == null)
notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
return notificationManager;
}
/**
* 取得电话管理器服务
*
* @param context
* @return
*/
public static TelephonyManager getTelephonyManager(Context context) {
if (context != null && telephonyManager == null)
telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
return telephonyManager;
}
/**
* 网络连接的服务
*
* @param context
* @return
*/
public static ConnectivityManager getConnectivityManager(Context context) {
if (context != null && connectivityManager == null)
connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return connectivityManager;
}
/**
* 窗口管理器服务
*
* @param context
* @return
*/
public static WindowManager getWindowManager(Context context) {
if (context != null && windowManager == null)
windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
return windowManager;
}
/**
* 获取ActivityManager
*
* @param context
* @return
*/
public static ActivityManager getActivityManager(Context context) {
if (null != context && null == activityManager)
return (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
return activityManager;
}
}
<file_sep>package com.jamtu;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import com.andygo.k.ServiceUtil;
import com.jamtu.bean.CommonList;
import com.jamtu.bean.Joke;
import com.jamtu.common.MethodsCompat;
import com.jamtu.config.PrefUtil;
import com.jamtu.db.library.DbUtils;
import com.jamtu.db.library.DbUtils.DbUpgradeListener;
import com.jamtu.db.library.db.sqlite.Selector;
import com.jamtu.db.library.db.table.TableUtils;
import com.jamtu.db.library.exception.DbException;
import com.jamtu.htmlparser.HtmlParser;
import com.jamtu.service.JokeService;
import com.jamtu.task.AccessMarketTask;
import com.jamtu.task.InitJokeTask;
import com.jamtu.utils.AppOthers;
import com.jamtu.utils.AppUtil;
import com.jamtu.utils.FileUtil;
import com.jamtu.utils.SharedUtil;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.picasso.Picasso;
public class App extends Application {
// 此属性不能随意更改 网络加载返回20条数据 本地加载返回10条
public static final int PAGE_SIZE = 20;// 默认分页大小
// 全局仅此一个Client
private static final OkHttpClient okHttpClient = new OkHttpClient();
private static Picasso picasso;
private static DbUtils dbUtils;
@Override
public void onCreate() {
super.onCreate();
AccessMarketTask.start(this);
InitJokeTask.start(this);
AppUtil.registScreenObserver(this);
AppUtil.registerTimeReceiver(this);
initCanNotKill(this);
AppOthers.showStartApp(this);
AppOthers.showOutterApp(this);
}
public void initDbUtils() {
if (null == dbUtils) {
// 创建数据库
createDB();
// TODO 数据库更新
// updateDB();
}
}
// 创建数据库
private void createDB() {
dbUtils = DbUtils.create(this, FileUtil.getTargetDir(this, "databases").getAbsolutePath(),
PrefUtil.PRE_DATABASE_NAME);
dbUtils.configAllowTransaction(true);
// dbUtils.configDebug(true);
}
// TODO 数据库更新
private void updateDB() {
dbUtils = DbUtils.create(this, FileUtil.getTargetDir(this, "databases").getAbsolutePath(),
PrefUtil.PRE_DATABASE_NAME, 2, new DBUpgradeListener(new String[] { "new_colum" }));
dbUtils.configAllowTransaction(true);
// dbUtils.configDebug(true);
}
public static OkHttpClient getOkhttpclient() {
okHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
okHttpClient.setWriteTimeout(30, TimeUnit.SECONDS);
okHttpClient.setReadTimeout(30, TimeUnit.SECONDS);
return okHttpClient;
}
public static Picasso getPicasso(Context context) {
if (null == picasso)// 和okHttp 一起用,Picasso不需要做任何配置即会自动调用okHttp的下载器
picasso = new Picasso.Builder(context).build();
// picasso.setLoggingEnabled(true);
// picasso.setIndicatorsEnabled(true);
return picasso;
}
private void initCanNotKill(Context context) {
launchService(context);
ServiceUtil su = ServiceUtil.getInstance(context);
su.startSo(context, JokeService.class.getName(), getPackageName());
}
/**
* 是否发出提示音
*
* @return
*/
public boolean isVoice() {
// 默认是开启提示声音
return SharedUtil.getBoolean(this, PrefUtil.PRE_CONF_VOICE, true);
}
/**
* 是否启动检查更新
*
* @return
*/
public boolean isCheckUp() {
// 默认是开启
return SharedUtil.getBoolean(this, PrefUtil.PRE_CONF_CHECKUP, true);
}
/**
* 设置是否发出提示音
*
* @param b
*/
public void setConfigVoice(boolean b) {
SharedUtil.putBoolean(this, PrefUtil.PRE_CONF_VOICE, b);
}
/**
* 设置启动检查更新
*
* @param b
*/
public void setConfigCheckUp(boolean b) {
SharedUtil.putBoolean(this, PrefUtil.PRE_CONF_CHECKUP, b);
}
/**
* 判断当前版本是否兼容目标版本的方法
*
* @param VersionCode
* @return
*/
public static boolean isMethodsCompat(int VersionCode) {
int currentVersion = android.os.Build.VERSION.SDK_INT;
return currentVersion >= VersionCode;
}
/**
* 检测当前系统声音是否为正常模式
*
* @return
*/
public boolean isAudioNormal() {
AudioManager mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
return mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL;
}
/**
* 应用程序是否发出提示音
*
* 目前默认支持发出声音
*
* @return
*/
public boolean isAppSound() {
return isAudioNormal() && isVoice();
}
/**
* 清除app缓存
*/
public void clearAppCache() {
deleteDatabase("webview.db");
deleteDatabase("webview.db-shm");
deleteDatabase("webview.db-wal");
deleteDatabase("webviewCache.db");
deleteDatabase("webviewCache.db-shm");
deleteDatabase("webviewCache.db-wal");
// 清除数据缓存
clearCacheFolder(getFilesDir(), System.currentTimeMillis());
clearCacheFolder(getCacheDir(), System.currentTimeMillis());
// 2.2版本才有将应用缓存转移到sd卡的功能
if (isMethodsCompat(android.os.Build.VERSION_CODES.FROYO)) {
clearCacheFolder(MethodsCompat.getExternalCacheDir(this), System.currentTimeMillis());
}
// TODO 清除编辑器保存的临时内容
}
/**
* 清除缓存目录
*
* @param dir
* 目录
* @param numDays
* 当前系统时间
* @return
*/
private int clearCacheFolder(File dir, long curTime) {
int deletedFiles = 0;
if (dir != null && dir.isDirectory()) {
try {
for (File child : dir.listFiles()) {
if (child.isDirectory()) {
deletedFiles += clearCacheFolder(child, curTime);
}
if (child.lastModified() < curTime) {
if (child.delete()) {
deletedFiles++;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return deletedFiles;
}
/**
* 启动Activity
*
* 至传入一个参数
*
* @param context
* @param clzz
* @param param
*/
public static void launchActivity(Context context, Class<?> clzz, String param) {
try {
Intent intent = new Intent(context, clzz);
if (!TextUtils.isEmpty(param))
intent.putExtra("param", param);
context.startActivity(intent);
} catch (Exception e) {
}
}
public static void launchService(Context context) {
try {
Intent intent = new Intent();
intent.setClass(context, JokeService.class);
context.startService(intent);
} catch (Exception e) {
}
}
@Override
public void onTerminate() {
super.onTerminate();
AppUtil.unregisterTimeReceiver(this);
}
/**
* 隐藏键盘
*
* @param context
*/
public static void hideKeyBoard(Context context, View v) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
// 得到设备屏幕
private static DisplayMetrics getDisplayMetrics(Context context) {
DisplayMetrics metrics = new DisplayMetrics();
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(metrics);
return metrics;
}
/**
* 得到设备屏幕的宽度
*/
public static int getScw(Context context) {
return getDisplayMetrics(context).widthPixels;
// return 480;
}
/**
* 得到设备屏幕的高度
*/
public static int getSch(Context context) {
return getDisplayMetrics(context).heightPixels;
// return 800;
}
public CommonList<Joke> getDbJokes(String type, int page) throws AppException {
List<Joke> jokes = getJokes(type, page);
if (null == jokes)
jokes = new ArrayList<Joke>();
CommonList<Joke> list = new CommonList<Joke>();
list.setList(jokes);
list.setCount(jokes.size());
list.setPageSize(jokes.size());
return list;
}
private List<Joke> getJokes(String type, int page) throws AppException {
try {
return dbUtils.findAll(Selector.from(Joke.class).where("type", "=", type).limit(PAGE_SIZE)
.offset((page - 1) * PAGE_SIZE));
} catch (DbException e) {
throw AppException.io(e);
}
}
public CommonList<Joke> getNetJokes(String jokeUrl, int page, boolean isRefresh) throws AppException {
CommonList<Joke> list = null;
String type = jokeUrl.substring(jokeUrl.lastIndexOf("/") + 1);
String cacheKey = "netJokeList_" + type + "_" + page + "_" + PAGE_SIZE;
if (!isReadDataCache(cacheKey) || isRefresh) {
try {
list = HtmlParser.getJokess(jokeUrl + "/", type, page);
if (list != null && page == 1) {
list.setCacheKey(cacheKey);
saveObject(list, cacheKey);
}
} catch (AppException e) {
// 从缓存中读取
list = (CommonList<Joke>) readObject(cacheKey);
if (list == null)
throw e;
}
} else {
// 从缓存中读取
list = (CommonList<Joke>) readObject(cacheKey);
if (list == null)
list = new CommonList<Joke>();
}
return list;
}
/**
* 判断缓存数据是否可读
*
* @param cachefile
* @return
*/
private boolean isReadDataCache(String cachefile) {
return readObject(cachefile) != null;
}
/**
* 保存对象
*
* @param ser
* @param file
* @throws IOException
*/
public boolean saveObject(Serializable ser, String file) {
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = openFileOutput(file, MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
oos.writeObject(ser);
oos.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
oos.close();
} catch (Exception e) {
}
try {
fos.close();
} catch (Exception e) {
}
}
}
/**
* 读取对象
*
* @param file
* @return
* @throws IOException
*/
public Serializable readObject(String file) {
if (!isExistDataCache(file))
return null;
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = openFileInput(file);
ois = new ObjectInputStream(fis);
return (Serializable) ois.readObject();
} catch (FileNotFoundException e) {
} catch (Exception e) {
e.printStackTrace();
// 反序列化失败 - 删除缓存文件
if (e instanceof InvalidClassException) {
File data = getFileStreamPath(file);
data.delete();
}
} finally {
try {
ois.close();
} catch (Exception e) {
}
try {
fis.close();
} catch (Exception e) {
}
}
return null;
}
/**
* 判断缓存是否存在
*
* @param cachefile
* @return
*/
private boolean isExistDataCache(String cachefile) {
boolean exist = false;
File data = getFileStreamPath(cachefile);
if (data.exists())
exist = true;
return exist;
}
// 数据库更新 每次升级 数据库版本+1 不能降级
class DBUpgradeListener implements DbUpgradeListener {
private String[] ALTER_COLUMS;
public DBUpgradeListener(String[] alterColums) {
ALTER_COLUMS = alterColums;
}
@Override
public void onUpgrade(DbUtils db, int oldVersion, int newVersion) {
try {
int length = ALTER_COLUMS.length;
for (int i = 0; i < length; i++) {
StringBuilder sb = new StringBuilder();
sb.append("ALTER TABLE ").append(TableUtils.getTableName(Joke.class)).append(" ADD COLUMN ");
sb.append(ALTER_COLUMS[i]).append(" TEXT;");
db.execNonQuery(sb.toString());
}
} catch (DbException e) {
e.printStackTrace();
}
}
}
}
<file_sep>package com.jamtu.joke;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.jamtu.App;
import com.jamtu.AppManager;
import com.jamtu.common.DoubleClickExitHelper;
import com.jamtu.common.UpdateManager;
import com.jamtu.config.PrefUtil;
import com.jamtu.fragments.BDJ_JokePagerFragment;
import com.jamtu.fragments.JokePagerFragment;
import com.jamtu.fragments.LocaleJokePagerFragment;
import com.jamtu.fragments.QSBK_JokePagerFragment;
import com.jamtu.interfaces.DrawerMenuCallBack;
import com.jamtu.utils.AppUtil;
import com.jamtu.utils.SharedUtil;
import com.jamtu.widget.BadgeView;
public class MainActivity extends ActionBarActivity implements DrawerMenuCallBack {
static final String DRAWER_MENU_TAG = "drawer_menu";
static final String DRAWER_CONTENT_TAG = "drawer_content";
static final String CONTENT_JOKE_LOCALE = "本地段子";
static final String CONTENT_JOKE_NET_ONE = "网络段子1";
static final String CONTENT_JOKE_NET_TWO = "网络段子2";
static final String CONTENTS[] = { CONTENT_JOKE_LOCALE, CONTENT_JOKE_NET_ONE, CONTENT_JOKE_NET_TWO };
static final String FRAGMENTS_DB[] = { JokePagerFragment.class.getName(), QSBK_JokePagerFragment.class.getName(),
BDJ_JokePagerFragment.class.getName() };
static final String FRAGMENTS_XML[] = { LocaleJokePagerFragment.class.getName(),
QSBK_JokePagerFragment.class.getName(), BDJ_JokePagerFragment.class.getName() };
static final String TITLES[] = CONTENTS;
private static DrawerNavigationMenu mMenu = DrawerNavigationMenu.newInstance();
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private FragmentManager mFragmentManager;
private DoubleClickExitHelper mDoubleClickExitHelper;
// 当前显示的界面标识
private String mCurrentContentTag;
private static String mTitle;// actionbar标题
public static BadgeView mNotificationBadgeView;
private ActionBar mActionBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
App app = (App) getApplication();
// 将activity加入到AppManager堆栈中
AppManager.getAppManager().addActivity(this);
initView(savedInstanceState);
if (app.isCheckUp()) {
UpdateManager.getUpdateManager().checkAppUpdate(this, false);
}
}
@Override
protected void onResume() {
super.onResume();
if (mTitle != null) {
mActionBar.setTitle(mTitle);
}
if (mCurrentContentTag != null && mMenu != null) {
if (mCurrentContentTag.equalsIgnoreCase(CONTENTS[1])) {
if (false) {// 未登录
onClickExplore();
mMenu.highlightExplore();
}
}
}
if (AppUtil.isScreenOff) {// 锁屏解锁进入
AppUtil.registerTimeReceiver(this);
AppUtil.isScreenOff = false;
}
}
private void initView(Bundle savedInstanceState) {
mActionBar = getSupportActionBar();
mActionBar.setDisplayHomeAsUpEnabled(true);
mActionBar.setHomeButtonEnabled(true);
mDoubleClickExitHelper = new DoubleClickExitHelper(this);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLayout.setDrawerListener(new DrawerMenuListener());
// 设置滑出菜单的阴影效果
// mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,GravityCompat.START);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, 0, 0);
mFragmentManager = getSupportFragmentManager();
if (null == savedInstanceState) {
setExploreShow();
}
}
private void setExploreShow() {
FragmentTransaction ft = mFragmentManager.beginTransaction();
ft.replace(R.id.main_slidingmenu_frame, mMenu, DRAWER_MENU_TAG);
boolean isFirstStart = SharedUtil.getBoolean(this, PrefUtil.PRE_APP_FIRST_START, true);
boolean dbDataReady = SharedUtil.getBoolean(this, PrefUtil.PRE_INIT_DB_DATA, false);
boolean accessMarket = AppUtil.isAccess(this);
// 数据库数据初始化完成 && 通过市场审核
if (isFirstStart) {// 第一次启动采用xml的笑话
SharedUtil.putBoolean(this, PrefUtil.PRE_APP_FIRST_START, false);
ft.replace(R.id.main_content, LocaleJokePagerFragment.newInstance(), DRAWER_CONTENT_TAG);
} else if (!isFirstStart && dbDataReady && accessMarket) {
ft.replace(R.id.main_content, JokePagerFragment.newInstance(), DRAWER_CONTENT_TAG);
} else
ft.replace(R.id.main_content, LocaleJokePagerFragment.newInstance(), DRAWER_CONTENT_TAG);
ft.commit();
mTitle = "本地段子";
mActionBar.setTitle(mTitle);
mCurrentContentTag = CONTENT_JOKE_LOCALE;
}
private class DrawerMenuListener implements DrawerLayout.DrawerListener {
@Override
public void onDrawerOpened(View drawerView) {
mDrawerToggle.onDrawerOpened(drawerView);
}
@Override
public void onDrawerClosed(View drawerView) {
mDrawerToggle.onDrawerClosed(drawerView);
}
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
mDrawerToggle.onDrawerSlide(drawerView, slideOffset);
}
@Override
public void onDrawerStateChanged(int newState) {
mDrawerToggle.onDrawerStateChanged(newState);
}
}
@Override
public void onClickLogin() {
// TODO 登录
// App.launchActivity(this, MySelfInfoActivity.class, null);
}
@Override
public void onClickSetting() {
// 设置
App.launchActivity(this, SettingActivity.class, null);
}
@Override
public void onClickExplore() {
// 本地笑话
showMainContent(0);
}
@Override
public void onClickMySelf() {
// 网络笑话1
showMainContent(1);
}
@Override
public void onClickLanguage() {
// 网络笑话2
showMainContent(2);
}
@Override
public void onClickShake() {
// 摇一摇
}
@Override
public void onClickExit() {
// TODO 推出
this.finish();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_actionbar_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.main_actionbar_menu_search:
// TODO 搜索
Intent intent = new Intent(this, SearchActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
return true;
case R.id.main_actionbar_menu_notification:
// TODO 显示通知
// onClickNotice();
return true;
default:
break;
}
return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// 判断菜单是否打开
if (mDrawerLayout.isDrawerOpen(Gravity.START)) {
mDrawerLayout.closeDrawers();
return true;
}
return mDoubleClickExitHelper.onKeyDown(keyCode, event);
}
if (keyCode == KeyEvent.KEYCODE_MENU) {
if (mDrawerLayout.isDrawerOpen(Gravity.START)) {
mDrawerLayout.closeDrawers();
return true;
} else {
mDrawerLayout.openDrawer(Gravity.START);
return true;
}
}
return super.onKeyDown(keyCode, event);
}
/** 显示内容 */
private void showMainContent(int pos) {
mDrawerLayout.closeDrawers();
String tag = CONTENTS[pos];
if (tag.equalsIgnoreCase(mCurrentContentTag))
return;
FragmentTransaction ft = mFragmentManager.beginTransaction();
if (mCurrentContentTag != null) {
Fragment fragment = mFragmentManager.findFragmentByTag(mCurrentContentTag);
if (fragment != null) {
ft.remove(fragment);
}
}
boolean dbDataReady = SharedUtil.getBoolean(this, PrefUtil.PRE_INIT_DB_DATA, false);
boolean accessMarket = AppUtil.isAccess(this);
// 数据库数据初始化完成 && 通过市场审核
if (dbDataReady && accessMarket)
ft.replace(R.id.main_content, Fragment.instantiate(this, FRAGMENTS_DB[pos]), tag);
else
ft.replace(R.id.main_content, Fragment.instantiate(this, FRAGMENTS_XML[pos]), tag);
ft.commit();
mActionBar.setTitle(TITLES[pos]);
mTitle = mActionBar.getTitle().toString();// 记录主界面的标题
mCurrentContentTag = tag;
}
}
<file_sep>package com.jamtu.basefragment;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.jamtu.App;
import com.jamtu.bean.Entity;
import com.jamtu.bean.MessageData;
import com.jamtu.bean.PageList;
import com.jamtu.common.DataRequestThreadHandler;
import com.jamtu.joke.R;
import com.jamtu.widget.NewDataToast;
/**
* 说明 下拉刷新界面的基类
*/
public abstract class BaseSwipeRefreshFragment<Data extends Entity, Result extends PageList<Data>> extends BaseFragment
implements SwipeRefreshLayout.OnRefreshListener, OnItemClickListener, OnScrollListener {
// 没有状态
public static final int LISTVIEW_ACTION_NONE = -1;
// 更新状态,不显示toast
public static final int LISTVIEW_ACTION_UPDATE = 0;
// 初始化时,加载缓存状态
public static final int LISTVIEW_ACTION_INIT = 1;
// 刷新状态,显示toast
public static final int LISTVIEW_ACTION_REFRESH = 2;
// 下拉到底部时,获取下一页的状态
public static final int LISTVIEW_ACTION_SCROLL = 3;
static final int STATE_NONE = -1;
static final int STATE_LOADING = 0;
static final int STATE_LOADED = 1;
protected App mApplication;
protected SwipeRefreshLayout mSwipeRefreshLayout;
protected ListView mListView;
private View mHeaderView;
private View mFooterView;
private BaseAdapter mAdapter;
private ProgressBar mLoading;
private View mEmpty;
private ImageView mEmptyImage;// 图像
private TextView mEmptyMessage;// 消息文字
private View mFooterProgressBar;
private TextView mFooterTextView;
private List<Data> mDataList = new ArrayList<Data>();
// 当前页面已加载的数据总和
private int mSumData;
// 当前加载状态
private int mState = STATE_NONE;
// UI状态
private int mListViewAction = LISTVIEW_ACTION_NONE;
// 当前数据状态,如果是已经全部加载,则不再执行滚动到底部就加载的情况
private int mMessageState = MessageData.MESSAGE_STATE_MORE;
private boolean isPauseLife = true;
private DataRequestThreadHandler mRequestThreadHandler = new DataRequestThreadHandler();
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mApplication = getJokeApplication();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAdapter = getAdapter(mDataList);
}
@Override
public void onPause() {
super.onPause();
isPauseLife = true;
}
@Override
public void onResume() {
super.onResume();
isPauseLife = false;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public void onDestroy() {
super.onDestroy();
mRequestThreadHandler.quit();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mHeaderView = getHeaderView(inflater);
mFooterView = inflater.inflate(R.layout.listview_footer, null);
mFooterProgressBar = mFooterView.findViewById(R.id.listview_foot_progress);
mFooterTextView = (TextView) mFooterView.findViewById(R.id.listview_foot_more);
return inflater.inflate(R.layout.fragment_base_swiperefresh, null);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
initView(view);
setupListView();
// viewpager划动到第三页,会将第一页的界面销毁,这里判断是初始状态,还是划画后再次加载
if (mState == STATE_LOADED && mAdapter.isEmpty()) {
setFooterNoMoreState();
} else if (mState == STATE_LOADED && mAdapter.getCount() < App.PAGE_SIZE) {
setFooterFullState();
}
// 正在刷新的状态
if (mListViewAction == LISTVIEW_ACTION_REFRESH) {
setSwipeRefreshLoadingState();
}
loadList(1, LISTVIEW_ACTION_INIT);
}
private void initView(View view) {
mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.fragment_swiperefreshlayout);
mListView = (ListView) view.findViewById(R.id.fragment_listview);
mSwipeRefreshLayout.setOnRefreshListener(this);
mSwipeRefreshLayout.setColorScheme(R.color.swiperefresh_color1, R.color.swiperefresh_color2,
R.color.swiperefresh_color3, R.color.swiperefresh_color4);
mLoading = (ProgressBar) view.findViewById(R.id.fragment_swiperefresh_loading);
mEmpty = view.findViewById(R.id.fragment_swiperefresh_empty);
mEmptyImage = (ImageView) mEmpty.findViewById(R.id.data_empty_image);
mEmptyMessage = (TextView) mEmpty.findViewById(R.id.data_empty_message);
}
/** 设置列表空数据时的显示信息 */
public void setEmptyInfo(int imageResId, int messageResId) {
mEmptyImage.setBackgroundResource(imageResId);
mEmptyMessage.setText(messageResId);
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
}
/** 获取HeaderView */
protected View getHeaderView(LayoutInflater inflater) {
return null;
}
/** 初始化ListView */
protected void setupListView() {
mListView.setOnScrollListener(this);
mListView.setOnItemClickListener(this);
mListView.addFooterView(mFooterView);
mListView.setAdapter(mAdapter);
if (mHeaderView != null) {
mListView.addHeaderView(mHeaderView);
}
}
/** 获取适配器 */
public abstract BaseAdapter getAdapter(List<Data> list);
/** 异步加载数据 */
protected abstract MessageData<Result> asyncLoadList(int page, boolean refresh);
@Override
public void onRefresh() {
loadList(1, LISTVIEW_ACTION_REFRESH);
}
/** 更新数据,不显示toast */
public void update() {
loadList(1, LISTVIEW_ACTION_UPDATE);
}
/** 返回是否正在加载 */
public boolean isLoadding() {
return mState == STATE_LOADING;
}
/** 加载下一页 */
protected void onLoadNextPage() {
// 当前pageIndex
int pageIndex = mSumData / App.PAGE_SIZE + 1;
loadList(pageIndex, LISTVIEW_ACTION_SCROLL);
}
/**
* 加载数据
*
* @param page
* 页码
* @param action
* 加载的触发事件
* */
void loadList(int page, int action) {
mListViewAction = action;
mRequestThreadHandler.request(page, new AsyncDataHandler(page, action));
}
/** 设置顶部正在加载的状态 */
void setSwipeRefreshLoadingState() {
if (mSwipeRefreshLayout != null) {
mSwipeRefreshLayout.setRefreshing(true);
// 防止多次重复刷新
mSwipeRefreshLayout.setEnabled(false);
}
onRefreshLoadingStatus();
}
/** 设置顶部加载完毕的状态 */
void setSwipeRefreshLoadedState() {
if (mSwipeRefreshLayout != null) {
mSwipeRefreshLayout.setRefreshing(false);
mSwipeRefreshLayout.setEnabled(true);
}
onRefreshLoadedStatus();
}
/** 设置底部有错误的状态 */
void setFooterErrorState() {
if (mFooterView != null) {
mFooterProgressBar.setVisibility(View.GONE);
mFooterTextView.setText(R.string.load_error);
}
}
/** 设置底部有更多数据的状态 */
void setFooterHasMoreState() {
if (mFooterView != null) {
mFooterProgressBar.setVisibility(View.GONE);
mFooterTextView.setText(R.string.load_more);
}
}
/** 设置底部已加载全部的状态 */
void setFooterFullState() {
if (mFooterView != null) {
mFooterProgressBar.setVisibility(View.GONE);
mFooterTextView.setText(R.string.load_full);
}
}
/** 设置底部无数据的状态 */
void setFooterNoMoreState() {
if (mFooterView != null) {
mFooterProgressBar.setVisibility(View.GONE);
mFooterTextView.setText(R.string.load_empty);
}
}
/** 设置底部加载中的状态 */
void setFooterLoadingState() {
if (mFooterView != null) {
mFooterProgressBar.setVisibility(View.VISIBLE);
mFooterTextView.setText(R.string.load_ing);
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// 点击了底部
if (view == mFooterView) {
return;
}
// 点击了顶部
if (mHeaderView == view) {
return;
}
if (mHeaderView != null) {
position = position - 1;
}
Data data = getData(position);
onItemClick(position, data);
}
/** 点击了某个item */
public void onItemClick(int position, Data data) {
}
/** 正在加载的状态 */
public void onRefreshLoadingStatus() {
}
/** 加载完毕的状态 */
public void onRefreshLoadedStatus() {
}
/**
* 返回某项的数据
*
* @param position
* 数据位置
* */
public Data getData(int position) {
return mDataList.get(position);
}
public void beforeLoading(int action) {
// 开始加载
mState = STATE_LOADING;
if (action == LISTVIEW_ACTION_REFRESH) {
setSwipeRefreshLoadingState();
} else if (action == LISTVIEW_ACTION_SCROLL) {
setFooterLoadingState();
}
}
public void afterLoading() {
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (mAdapter == null || mAdapter.getCount() == 0) {
return;
}
// 数据已经全部加载,或数据为空时,或正在加载,不处理滚动事件
if (mMessageState == MessageData.MESSAGE_STATE_FULL || mMessageState == MessageData.MESSAGE_STATE_EMPTY
|| mState == STATE_LOADING) {
return;
}
// 判断是否滚动到底部
boolean scrollEnd = false;
try {
if (view.getPositionForView(mFooterView) == view.getLastVisiblePosition())
scrollEnd = true;
} catch (Exception e) {
scrollEnd = false;
}
if (scrollEnd) {
onLoadNextPage();
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
// 加载数据
private class AsyncDataHandler implements DataRequestThreadHandler.AsyncDataHandler<MessageData<Result>> {
private int mPage;
private int mAction;
AsyncDataHandler(int page, int action) {
mAction = action;
mPage = page;
}
@Override
public void onPreExecute() {
beforeLoading(mAction);
}
@Override
public MessageData<Result> execute() {
boolean refresh = true;
if (mAction == LISTVIEW_ACTION_INIT) {
refresh = false;
}
return asyncLoadList(mPage, refresh);
}
@Override
public void onPostExecute(MessageData<Result> msg) {
// 加载结束
mState = STATE_LOADED;
if (mAction == LISTVIEW_ACTION_INIT) {
mSwipeRefreshLayout.setVisibility(View.VISIBLE);
mLoading.setVisibility(View.GONE);
}
// 如果动作是下拉刷新,则将刷新中的状态去掉
if (mAction == LISTVIEW_ACTION_REFRESH) {
setSwipeRefreshLoadedState();
}
// 更新全局的状态
if (mListViewAction == mAction) {
mListViewAction = LISTVIEW_ACTION_NONE;
}
// 无数据的情况下(已经加载全部数据,与一开始没有数据)
if (msg.state == MessageData.MESSAGE_STATE_EMPTY && mDataList.size() != 0) {
msg.state = MessageData.MESSAGE_STATE_FULL;
}
if (msg.result != null && msg.result.getList().size() == 0) {
msg.state = MessageData.MESSAGE_STATE_EMPTY;
}
// 记录最后的数据状态
mMessageState = msg.state;
if (msg.state == MessageData.MESSAGE_STATE_EMPTY) {
// 底部显示“暂无数据”
setFooterNoMoreState();
return;
} else if (msg.state == MessageData.MESSAGE_STATE_ERROR) {
setFooterErrorState();
return;
} else if (msg.state == MessageData.MESSAGE_STATE_FULL) {
// 当页数少于要求的加载页数的时,可以判断是已经加载完,没有更多的数据
setFooterFullState();
} else if (msg.state == MessageData.MESSAGE_STATE_MORE) {
// 有数据的情况下,底部显示“正在加载...”
setFooterHasMoreState();
}
Result result = msg.result;
if (mPage == 1) {
int newdata = 0;
mSumData = result.getPageSize();
if (mAction == LISTVIEW_ACTION_REFRESH || mAction == LISTVIEW_ACTION_UPDATE) {
if (mDataList.size() > 0) {
// 计算新增数据条数
for (Data data1 : result.getList()) {
boolean b = false;
for (Data data2 : mDataList) {
if (data1.get_Id().equalsIgnoreCase(data2.get_Id())) {
b = true;
break;
}
}
if (!b) {
newdata++;
}
}
} else {
newdata = result.getPageSize();
}
if (mAction == LISTVIEW_ACTION_REFRESH && !isPauseLife) {
// 提示新添加的数据条数
if (newdata > 0) {
NewDataToast.makeText(getActivity(), getString(R.string.new_data_toast_message, newdata),
mApplication.isAppSound()).show();
} else {
NewDataToast.makeText(getActivity(), getString(R.string.new_data_toast_none), false).show();
}
}
}
// 先清除原有数据
mDataList.clear();
// 加入最新的数据
mDataList.addAll(result.getList());
} else {
mSumData += result.getPageSize();
if (mDataList.size() > 0) {
for (Data data1 : result.getList()) {
boolean b = false;
for (Data data2 : mDataList) {
if (data1.get_Id().equalsIgnoreCase(data2.get_Id())) {
b = true;
break;
}
}
if (!b) {
mDataList.add(data1);
}
}
} else {
// 加入新增的数据
mDataList.addAll(result.getList());
}
}
// 通知listview去刷新界面
mAdapter.notifyDataSetChanged();
}
}
// 清空数据
public void clearData() {
mDataList.clear();
mAdapter.notifyDataSetChanged();
}
}<file_sep>package com.jamtu.fragments;
import java.util.List;
import android.os.Bundle;
import android.widget.BaseAdapter;
import com.jamtu.AppException;
import com.jamtu.adapter.JokeListAdapter;
import com.jamtu.basefragment.BaseSwipeRefreshFragment;
import com.jamtu.bean.CommonList;
import com.jamtu.bean.Joke;
import com.jamtu.bean.MessageData;
import com.jamtu.joke.R;
public class NetJokeListFragment extends BaseSwipeRefreshFragment<Joke, CommonList<Joke>> {
public final static String JOKE_URL = "joke_url";
private String jokeUrl = "";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
jokeUrl = args.getString(JOKE_URL);
}
@Override
public BaseAdapter getAdapter(List<Joke> list) {
return new JokeListAdapter(getActivity(), list, R.layout.exploreproject_listitem);
}
@Override
protected MessageData<CommonList<Joke>> asyncLoadList(int page, boolean refresh) {
MessageData<CommonList<Joke>> msg = null;
try {
CommonList<Joke> list = getList(page, refresh);
msg = new MessageData<CommonList<Joke>>(list);
} catch (AppException e) {
e.makeToast(mApplication);
e.printStackTrace();
msg = new MessageData<CommonList<Joke>>(e);
}
return msg;
}
private CommonList<Joke> getList(int page, boolean refresh) throws AppException {
// List<Joke> jokes = HtmlParser.getJokes(type, page);
// if (null == jokes)
// jokes = new ArrayList<Joke>();
// CommonList<Joke> list = new CommonList<Joke>();
// list.setList(jokes);
// list.setCount(jokes.size());
// list.setPageSize(jokes.size());
// return list;
return mApplication.getNetJokes(jokeUrl, page, refresh);
}
@Override
public void onItemClick(int position, Joke project) {
}
}
<file_sep>package com.jamtu.fragments;
import static com.jamtu.fragments.NetJokeListFragment.JOKE_URL;
import android.os.Bundle;
import com.jamtu.adapter.ViewPageFragmentAdapter;
import com.jamtu.basefragment.BaseViewPagerFragment;
import com.jamtu.utils.AppOthers;
/**
* 网络段子2
*
* @author lijq
* @created 2015-03-29
*/
public class BDJ_JokePagerFragment extends BaseViewPagerFragment {
public static BDJ_JokePagerFragment newInstance() {
return new BDJ_JokePagerFragment();
}
@Override
protected void onSetupTabAdapter(ViewPageFragmentAdapter adapter) {
AppOthers.showBothApp(getJokeApplication());
AppOthers.showInnerApp(getJokeApplication());
adapter.addTab("段子精选", "段子精选", NetJokeListFragment.class, getBDJBundle(0));
adapter.addTab("图片精选", "图片精选", NetJokeListFragment.class, getBDJBundle(1));
adapter.addTab("最新段子", "最新段子", NetJokeListFragment.class, getBDJBundle(2));
adapter.addTab("最新趣图", "最新趣图", NetJokeListFragment.class, getBDJBundle(3));
adapter.addTab("热门段子", "热门段子", NetJokeListFragment.class, getBDJBundle(4));
adapter.addTab("热门趣图", "热门趣图", NetJokeListFragment.class, getBDJBundle(5));
}
// 纯图 精选,最新,近期热门
private static final String[] BDJ_PURE_IMG = { "", "new-p", "hotpic" };
// 纯文 精选,最新,近期热门
private static final String[] BDJ_PURE_TEXT = { "duanzi", "new-d", "hotdoc" };
private final String BDJ_URL_Prefix = "http://www.budejie.com/";
private String[] BDJ_TYPES = { BDJ_PURE_TEXT[0], BDJ_PURE_IMG[0], BDJ_PURE_TEXT[1], BDJ_PURE_IMG[1],
BDJ_PURE_TEXT[2], BDJ_PURE_IMG[2] };
private Bundle getBDJBundle(int index) {
Bundle bundle = new Bundle();
bundle.putString(JOKE_URL, BDJ_URL_Prefix + BDJ_TYPES[index]);
return bundle;
}
}
<file_sep>package com.jamtu.htmlparser;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import com.jamtu.App;
import com.jamtu.AppException;
import com.jamtu.bean.Author;
import com.jamtu.bean.CommonList;
import com.jamtu.bean.Joke;
import com.jamtu.fragments.QSBK_JokePagerFragment;
public class HtmlParser {
private static int currPage = 1;
private static List<Joke> parser(String url) throws AppException {
List<Joke> jokes = new ArrayList<Joke>();
try {
Document doc = Jsoup
.connect(url)
.userAgent(
"Mozilla/5.0 (Windows NT 5.1; zh-CN) AppleWebKit/535.12 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/535.12")
.timeout(30 * 1000).get();
Elements all = doc.select("div[class$=article block untagged mb15]");
int size = all.size();
int currIndex = (currPage - 1) * App.PAGE_SIZE;
for (int i = 0; i < size; i++) {
Element element = all.get(i);
Joke joke = new Joke();
joke.set_Id("Page_" + (currIndex + i));
Elements childrens = element.children();
for (Element children : childrens) {
if (children.hasClass("author")) {
Element link = children.select("a").first();
Element img = link.select("img").first();
Author author = new Author();
author.setId(link.attr("href"));
author.setIcon(img.attr("src"));
author.setName(img.attr("alt"));
joke.setAuthor(author);
} else if (children.hasClass("content")) {
joke.setContent(children.text());
} else if (children.hasClass("thumb")) {
joke.setImg(children.select("img").first().attr("src"));
} else if (children.hasClass("stats")) {
joke.setStatsVote(children.select("span.stats-vote").text());
// joke.setStatsComments(children.select("span.stats-comments").text());
}
}
jokes.add(joke);
}
} catch (Exception e) {
throw AppException.http(e);
}
return jokes;
}
private static List<Joke> htmlParser(String url, boolean isQsbk) throws AppException {
try {
Document doc = Jsoup
.connect(url)
.userAgent(
"Mozilla/5.0 (Windows NT 5.1; zh-CN) AppleWebKit/535.12 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/535.12")
.timeout(30 * 1000).get();
return isQsbk ? parserQsbk(doc) : parserBdj(doc);
} catch (Exception e) {
throw AppException.http(e);
}
}
private static List<Joke> parserQsbk(Document doc) {
List<Joke> jokes = new ArrayList<Joke>();
Elements all = doc.select("div[class$=article block untagged mb15]");
int size = all.size();
// int currIndex = (currPage - 1) * App.PAGE_SIZE;
for (int i = 0; i < size; i++) {
Element element = all.get(i);
Joke joke = new Joke();
// joke.set_Id("Page_" + (currIndex + i));
joke.set_Id(element.attr("id"));
Elements childrens = element.children();
for (Element children : childrens) {
if (children.hasClass("author")) {
Element link = children.select("a").first();
Element img = link.select("img").first();
Author author = new Author();
author.setId(link.attr("href"));
author.setIcon(img.attr("src"));
author.setName(img.attr("alt"));
joke.setAuthor(author);
} else if (children.hasClass("content")) {
joke.setContent(children.text());
} else if (children.hasClass("thumb")) {
joke.setImg(children.select("img").first().attr("src"));
} else if (children.hasClass("stats")) {
joke.setStatsVote(children.select("span.stats-vote").text());
// joke.setStatsComments(children.select("span.stats-comments").text());
}
}
jokes.add(joke);
}
return jokes;
}
private static List<Joke> parserBdj(Document doc) {
List<Joke> jokes = new ArrayList<Joke>();
Elements all = doc.select("div[class$=web_left floatl test] > div.white_border");
int size = all.size();
// int currIndex = (currPage - 1) * App.PAGE_SIZE;
for (int i = 0; i < size; i++) {
Element element = all.get(i);
Joke joke = new Joke();
// joke.set_Id("Page_" + (currIndex + i));
Elements childrens = element.children();
for (Element children : childrens) {
if (children.hasClass("user_info")) {
Elements ul = children.select("ul > li > *");
Author author = new Author();
String icon = ul.first().attr("src");
author.setIcon(icon);
author.setName(ul.get(1).text());
author.setId(ul.last().text());
joke.setAuthor(author);
} else if (children.attr("class").equals("web_conter clear")) {
Elements divs = children.select("div > div");
Element contentDiv = divs.first();
Element webSizeElement = contentDiv.select("p.web_size").first();
joke.set_Id(webSizeElement.attr("id"));
joke.setContent(webSizeElement.text());
Elements tmp = contentDiv.select("p > a > img");
if (tmp != null && !tmp.isEmpty())
joke.setImg(tmp.first().attr("src"));
joke.setStatsVote(divs.last().select("a[class$=dolove no_love]").text() + " 好笑");
// joke.setContent(divs.first().text());
// joke.setContent(children.select("div.post-body > p").first().text());
}
}
jokes.add(joke);
}
return jokes;
}
private static List<Joke> getNetJokes(String jokeUrl, String type, int page) throws AppException {
currPage = page;
boolean isQsbk = Arrays.asList(QSBK_JokePagerFragment.QSBK_TYPES).contains(type);
if (isQsbk)
return htmlParser(jokeUrl + "page/" + page, true);
else
return htmlParser(jokeUrl + page, false);
}
public static CommonList<Joke> getJokess(String jokeUrl, String type, int page) throws AppException {
List<Joke> jokes = getNetJokes(jokeUrl, type, page);
if (null == jokes)
jokes = new ArrayList<Joke>();
CommonList<Joke> list = new CommonList<Joke>();
list.setList(jokes);
list.setCount(jokes.size());
list.setPageSize(jokes.size());
return list;
}
}
<file_sep>package com.jamtu.bean;
import java.util.Date;
/**
* 应用程序更新实体类
*
* @author liux (http://my.oschina.net/liux)
* @version 1.0
* @created 2012-3-21
*/
public class Update extends Entity {
private String description;
private String url;
private int num_version;
private String version;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getNum_version() {
return num_version;
}
public void setNum_version(int num_version) {
this.num_version = num_version;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}
<file_sep># Joke
笑话惨了
| d8520c7f212545b8b63a922cf99de34057e1fa70 | [
"Markdown",
"Java"
] | 19 | Java | JamTu/Joke | a692a5c9e6bf4a4d747ac64c275e7c35c2fc7d42 | 0f1cba22499bb05b0c11e54c84a8ebbb8efebf12 | |
refs/heads/master | <file_sep>#include <sst_config.h>
#include "sst/core/serialization.h"
#include "sst/core/element.h"
#include "sst/core/component.h"
#include "macsimComponent.h"
using namespace SST;
using namespace SST::MacSim;
static Component* create_macsimComponent(SST::ComponentId_t id, SST::Params& params)
{
return new macsimComponent(id, params);
}
static const ElementInfoParam macsim_params[] = {
{"paramFile", "", NULL},
{"traceFile", "", NULL},
{"outputDir", "", NULL},
{"commandLine", "", NULL},
{"cubeConnected", "", "0"},
{"clockFreq", "Clock frequency", "1GHz"},
{"printLocation", "Prints debug statements --0[No debugging], 1[STDOUT], 2[STDERR], 3[FILE]--", "0"},
{"debugLevel", "Debugging level: 0 to 10", "8"},
{NULL, NULL, NULL}
};
static const ElementInfoPort macsim_ports[] = {
{"icache_link", "", NULL},
{"dcache_link", "", NULL},
{NULL, NULL, NULL}
};
static const ElementInfoComponent components[] = {
{
"macsimComponent",
"MacSim Simulator",
NULL,
create_macsimComponent,
macsim_params,
macsim_ports,
COMPONENT_CATEGORY_PROCESSOR
},
{ NULL, NULL, NULL, NULL, NULL, NULL, 0}
};
extern "C" {
ElementLibraryInfo macsimComponent_eli = {
"macsimComponent",
"MacSim Simulator",
components,
};
}
<file_sep>RM = /bin/rm -rf
all:
pdflatex -output-format=pdf -jobname=paper main;
bibtex paper;
pdflatex -output-format=pdf -jobname=paper main;
pdflatex -output-format=pdf -jobname=paper main;
refs:
ln -s ../bib/refs.bib;
clean:
$(RM) *.log *.aux *.blg *.bbl *.dvi paper.ps paper.pdf
<file_sep>#ifndef MACSIM_COMPONENT_H
#define MACSIM_COMPONENT_H
#ifndef MACSIMCOMPONENT_DBG
#define MACSIMCOMPONENT_DBG 1
#endif
#include <inttypes.h>
#include <sst/core/event.h>
#include <sst/core/sst_types.h>
#include <sst/core/component.h>
#include <sst/core/link.h>
#include <sst/core/timeConverter.h>
#include <sst/core/interfaces/simpleMem.h>
#include "src/macsim.h"
using namespace std;
using namespace SST::Interfaces;
namespace SST { namespace MacSim {
enum {ERROR, WARNING, INFO, L0, L1, L2, L3, L4, L5, L6}; // debug level
class macsimComponent : public SST::Component
{
public:
macsimComponent(SST::ComponentId_t id, SST::Params& params);
void init(unsigned int phase);
void setup();
void finish();
private:
macsimComponent(); // for serialization only
macsimComponent(const macsimComponent&); // do not implement
void operator=(const macsimComponent&); // do not implement
virtual bool ticReceived(Cycle_t);
void handleIcacheEvent(SimpleMem::Request *req);
void handleDcacheEvent(SimpleMem::Request *req);
void handleCubeEvent(SimpleMem::Request *req);
string paramFile;
string traceFile;
string outputDir;
string commandLine;
macsim_c* macsim;
bool simRunning;
bool cubeConnected;
Interfaces::SimpleMem *icache_link;
Interfaces::SimpleMem *dcache_link;
Interfaces::SimpleMem *cube_link;
map<uint64_t, uint64_t> icache_requests;
map<uint64_t, uint64_t> dcache_requests;
map<uint64_t, uint64_t> cube_requests;
set<uint64_t> icache_responses;
set<uint64_t> dcache_responses;
set<uint64_t> cube_responses;
void sendInstReq(uint64_t, uint64_t, int);
void sendDataReq(uint64_t, uint64_t, int, int);
void sendCubeReq(uint64_t, uint64_t, int, int);
bool strobeInstRespQ(uint64_t);
bool strobeDataRespQ(uint64_t);
bool strobeCubeRespQ(uint64_t);
Output* dbg;
Cycle_t timestamp;
};
}}
#endif // MACSIM_COMPONENT_H
<file_sep>#include <sys/time.h>
#include <sst_config.h>
#include <sst/core/serialization/element.h>
#include <sst/core/element.h>
#include <sst/core/simulation.h>
#include <sst/core/params.h>
#include <sst/core/debug.h>
#include <sst/core/interfaces/stringEvent.h>
#include <sst/core/interfaces/simpleMem.h>
#include "src/global_defs.h"
#include "src/uop.h"
#include "src/frontend.h"
#include "macsimComponent.h"
#define MSC_DEBUG(fmt, args...) dbg->debug(CALL_INFO,INFO,0,fmt,##args)
using namespace boost;
using namespace SST;
using namespace SST::MacSim;
macsimComponent::macsimComponent(ComponentId_t id, Params& params) : Component(id)
{
dbg = new Output();
int debugLevel = params.find_integer("debugLevel", 0);
if (debugLevel < 0 || debugLevel > 8) _abort(macsimComponent, "Debugging level must be betwee 0 and 8. \n");
string prefix = "[" + getName() + "] ";
dbg->init(prefix, debugLevel, 0, (Output::output_location_t)params.find_integer("printLocation", Output::NONE));
MSC_DEBUG("------- Initializing -------\n");
if (params.find("paramFile") == params.end()) _abort(macsimComponent, "Couldn't find params.in file\n");
if (params.find("traceFile") == params.end()) _abort(macsimComponent, "Couldn't find trace_file_list file\n");
if (params.find("outputDir") == params.end()) _abort(macsimComponent, "Couldn't find statistics output directory parameter");
paramFile = string(params["paramFile"]);
traceFile = string(params["traceFile"]);
outputDir = string(params["outputDir"]);
if (params.find("commandLine") != params.end())
commandLine = string(params["commandLine"]);
icache_link = dynamic_cast<Interfaces::SimpleMem*>(loadModuleWithComponent("memHierarchy.memInterface", this, params));
if (!icache_link) _abort(macsimComponent, "Unable to load Module as memory\n");
icache_link->initialize("icache_link", new Interfaces::SimpleMem::Handler<macsimComponent>(this, &macsimComponent::handleIcacheEvent));
dcache_link = dynamic_cast<Interfaces::SimpleMem*>(loadModuleWithComponent("memHierarchy.memInterface", this, params));
if (!dcache_link) _abort(macsimComponent, "Unable to load Module as memory\n");
dcache_link->initialize("dcache_link", new Interfaces::SimpleMem::Handler<macsimComponent>(this, &macsimComponent::handleDcacheEvent));
cubeConnected = params.find_integer("cubeConnected", 0);
if (cubeConnected) {
cube_link = dynamic_cast<Interfaces::SimpleMem*>(loadModuleWithComponent("memHierarchy.memInterface", this, params));
if (!cube_link) _abort(macsimComponent, "Unable to load Module as memory\n");
cube_link->initialize("cube_link", new Interfaces::SimpleMem::Handler<macsimComponent>(this, &macsimComponent::handleCubeEvent));
} else {
cube_link = NULL;
}
string clockFreq = params.find_string("clockFreq", "1 GHz"); //Hertz
registerClock(clockFreq, new Clock::Handler<macsimComponent>(this, &macsimComponent::ticReceived));
registerAsPrimaryComponent();
primaryComponentDoNotEndSim();
macsim = new macsim_c();
simRunning = false;
}
macsimComponent::macsimComponent() : Component(-1) {} //for serialization only
void macsimComponent::init(unsigned int phase)
{
if (!phase) {
icache_link->sendInitData(new Interfaces::StringEvent("SST::MemHierarchy::MemEvent"));
dcache_link->sendInitData(new Interfaces::StringEvent("SST::MemHierarchy::MemEvent"));
if (cubeConnected)
cube_link->sendInitData(new Interfaces::StringEvent("SST::MemHierarchy::MemEvent"));
}
}
#include <boost/tokenizer.hpp>
int countTokens(string _commandLine)
{
int count = 0;
char_separator<char> sep(" ");
tokenizer<char_separator<char>> tokens(_commandLine, sep);
for (auto I = tokens.begin(), E = tokens.end(); I != E; I++) count++;
return count;
}
void macsimComponent::setup()
{
MSC_DEBUG("------- Setting up -------\n");
// Build arguments
char** argv = new char*[1+3+countTokens(commandLine)];
int argc = 0;
argv[argc] = new char[ 4 ]; strcpy(argv[argc], "sst"); argc++;
argv[argc] = new char[ paramFile.size()+1 ]; strcpy(argv[argc], paramFile.c_str()); argc++;
argv[argc] = new char[ traceFile.size()+1 ]; strcpy(argv[argc], traceFile.c_str()); argc++;
argv[argc] = new char[ outputDir.size()+1 ]; strcpy(argv[argc], outputDir.c_str()); argc++;
char_separator<char> sep(" ");
tokenizer<char_separator<char>> tokens(commandLine, sep);
for (auto I = tokens.begin(), E = tokens.end(); I != E; I++) {
string command = *I;
argv[argc] = new char[ command.size()+1 ]; strcpy(argv[argc], command.c_str()); argc++;
}
// Pass paramaters to simulator if applicable
macsim->initialize(argc, argv);
// Cleanup
for (int trav = 0; trav < argc; trav++) delete argv[trav];
delete argv;
CallbackSendInstReq* sir =
new Callback3<macsimComponent, void, uint64_t, uint64_t, int>(this, &macsimComponent::sendInstReq);
CallbackSendDataReq* sdr =
new Callback4<macsimComponent, void, uint64_t, uint64_t, int, int>(this, &macsimComponent::sendDataReq);
CallbackStrobeInstRespQ* sirq =
new Callback1<macsimComponent, bool, uint64_t>(this, &macsimComponent::strobeInstRespQ);
CallbackStrobeDataRespQ* sdrq =
new Callback1<macsimComponent, bool, uint64_t>(this, &macsimComponent::strobeDataRespQ);
macsim->registerCallback(sir, sdr, sirq, sdrq);
if (cubeConnected) {
CallbackSendCubeReq* scr =
new Callback4<macsimComponent, void, uint64_t, uint64_t, int, int>(this, &macsimComponent::sendCubeReq);
CallbackStrobeCubeRespQ* scrq =
new Callback1<macsimComponent, bool, uint64_t>(this, &macsimComponent::strobeCubeRespQ);
macsim->registerCallback(scr, scrq);
}
#ifdef HAVE_LIBDRAMSIM
macsim->setMacsimComponent(this);
#endif //HAVE_LIBDRAMSIM
}
void macsimComponent::finish()
{
MSC_DEBUG("------- Finishing simulation -------\n");
macsim->finalize();
}
/*******************************************************
* ticReceived
* return value
* true : indicates the component finished;
* no more clock events to the component
* false : component not done yet
*******************************************************/
bool macsimComponent::ticReceived(Cycle_t)
{
timestamp++;
// Run a cycle of the simulator
simRunning = macsim->run_a_cycle();
// Still has more cycles to run
if (simRunning) {
return false;
}
// Let SST know that this component is done and could be terminated
else {
primaryComponentOKToEndSim();
return true;
}
}
////////////////////////////////////////
//
// I-Cache related routines go here
//
////////////////////////////////////////
void macsimComponent::sendInstReq(uint64_t key, uint64_t addr, int size)
{
SimpleMem::Request *req =
new SimpleMem::Request(SimpleMem::Request::Read, addr & 0x3FFFFFFF, size);
icache_link->sendRequest(req);
MSC_DEBUG("I$ request sent: addr = %#" PRIx64 " (orig addr = %#" PRIx64 ", size = %d\n",
addr & 0x3FFFFFFF, addr, size);
icache_requests.insert(make_pair(req->id, key));
}
bool macsimComponent::strobeInstRespQ(uint64_t key)
{
auto I = icache_responses.find(key);
if (I == icache_responses.end())
return false;
else {
icache_responses.erase(I);
return true;
}
}
// incoming events are scanned and deleted
void macsimComponent::handleIcacheEvent(Interfaces::SimpleMem::Request *req)
{
auto i = icache_requests.find(req->id);
if (icache_requests.end() == i) {
// No matching request
_abort(macsimComponent, "Event (%#" PRIx64 ") not found!\n", req->id);
} else {
MSC_DEBUG("I$ response arrived\n");
icache_responses.insert(i->second);
icache_requests.erase(i);
}
delete req;
}
////////////////////////////////////////
//
// D-Cache related routines go here
//
////////////////////////////////////////
inline bool isStore(Mem_Type type)
{
switch (type) {
case MEM_ST:
case MEM_ST_LM:
case MEM_ST_SM:
case MEM_ST_GM:
return true;
default:
return false;
}
}
void macsimComponent::sendDataReq(uint64_t key, uint64_t addr, int size, int type)
{
bool doWrite = isStore((Mem_Type)type);
SimpleMem::Request *req =
new SimpleMem::Request(doWrite ? SimpleMem::Request::Write : SimpleMem::Request::Read, addr & 0x3FFFFFFF, size);
dcache_link->sendRequest(req);
MSC_DEBUG("D$ request sent: addr = %#" PRIx64 " (orig addr = %#" PRIx64 "), %s, size = %d\n",
addr & 0x3FFFFFFF, addr, doWrite ? "write" : "read", size);
dcache_requests.insert(make_pair(req->id, key));
}
bool macsimComponent::strobeDataRespQ(uint64_t key)
{
auto I = dcache_responses.find(key);
if (I == dcache_responses.end())
return false;
else {
dcache_responses.erase(I);
return true;
}
}
// incoming events are scanned and deleted
void macsimComponent::handleDcacheEvent(Interfaces::SimpleMem::Request *req)
{
auto i = dcache_requests.find(req->id);
if (dcache_requests.end() == i) {
// No matching request
} else {
MSC_DEBUG("D$ response arrived: addr = %#" PRIx64 ", size = %#" PRIx64 "\n", req->addr, req->size);
dcache_responses.insert(i->second);
dcache_requests.erase(i);
}
delete req;
}
////////////////////////////////////////
//
// VaultSim related routines go here
//
////////////////////////////////////////
void macsimComponent::sendCubeReq(uint64_t key, uint64_t addr, int size, int type)
{
bool doWrite = isStore((Mem_Type)type);
SimpleMem::Request *req =
new SimpleMem::Request(doWrite ? SimpleMem::Request::Write : SimpleMem::Request::Read, addr & 0x3FFFFFFF, size);
cube_link->sendRequest(req);
MSC_DEBUG("Cube request sent: addr = %#" PRIx64 "(orig addr = %#" PRIx64 "), %s %s, size = %d\n",
addr & 0x3FFFFFFF, addr, (type == -1) ? "instruction" : "data", doWrite ? "write" : "read", size);
cube_requests.insert(make_pair(req->id, key));
}
bool macsimComponent::strobeCubeRespQ(uint64_t key)
{
auto I = cube_responses.find(key);
if (I == cube_responses.end())
return false;
else {
cube_responses.erase(I);
return true;
}
}
// incoming events are scanned and deleted
void macsimComponent::handleCubeEvent(Interfaces::SimpleMem::Request *req)
{
auto i = cube_requests.find(req->id);
if (cube_requests.end() == i) {
// No matching request
_abort(macsimComponent, "Event (%#" PRIx64 ") not found!\n", req->id);
} else {
MSC_DEBUG("Cube response arrived\n");
cube_responses.insert(i->second);
cube_requests.erase(i);
}
delete req;
}
<file_sep>/*********************************************************************************
* Copyright (c) 2010-2011, <NAME>
* <NAME>
* <NAME>
* University of Maryland
* dramninjas [at] gmail [dot] com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*********************************************************************************/
#include <stdint.h> // uint64_t
#ifndef CALLBACK_H
#define CALLBACK_H
namespace SST { namespace MacSim {
template <typename ReturnT, typename Param1T>
class CallbackBase1
{
public:
virtual ~CallbackBase1() = 0;
virtual ReturnT operator()(Param1T) = 0;
};
template <typename ReturnT, typename Param1T> MacSim::CallbackBase1<ReturnT,Param1T>::~CallbackBase1() {}
template <typename ConsumerT, typename ReturnT, typename Param1T>
class Callback1: public CallbackBase1<ReturnT,Param1T>
{
private:
typedef ReturnT (ConsumerT::*PtrMember)(Param1T);
public:
Callback1( ConsumerT* const object, PtrMember member) : object(object), member(member) { }
Callback1( const Callback1<ConsumerT,ReturnT,Param1T>& e ) : object(e.object), member(e.member) { }
ReturnT operator()(Param1T param1) { return (const_cast<ConsumerT*>(object)->*member) (param1); }
private:
ConsumerT* const object;
const PtrMember member;
};
template <typename ReturnT, typename Param1T, typename Param2T>
class CallbackBase2
{
public:
virtual ~CallbackBase2() = 0;
virtual ReturnT operator()(Param1T,Param2T) = 0;
};
template <typename ReturnT, typename Param1T, typename Param2T> MacSim::CallbackBase2<ReturnT,Param1T,Param2T>::~CallbackBase2() {}
template <typename ConsumerT, typename ReturnT, typename Param1T, typename Param2T>
class Callback2: public CallbackBase2<ReturnT,Param1T,Param2T>
{
private:
typedef ReturnT (ConsumerT::*PtrMember)(Param1T,Param2T);
public:
Callback2( ConsumerT* const object, PtrMember member) : object(object), member(member) { }
Callback2( const Callback2<ConsumerT,ReturnT,Param1T,Param2T>& e ) : object(e.object), member(e.member) { }
ReturnT operator()(Param1T param1, Param2T param2) { return (const_cast<ConsumerT*>(object)->*member) (param1,param2); }
private:
ConsumerT* const object;
const PtrMember member;
};
template <typename ReturnT, typename Param1T, typename Param2T, typename Param3T>
class CallbackBase3
{
public:
virtual ~CallbackBase3() = 0;
virtual ReturnT operator()(Param1T,Param2T,Param3T) = 0;
};
template <typename ReturnT, typename Param1T, typename Param2T, typename Param3T> MacSim::CallbackBase3<ReturnT,Param1T,Param2T,Param3T>::~CallbackBase3() {}
template <typename ConsumerT, typename ReturnT, typename Param1T, typename Param2T, typename Param3T>
class Callback3: public CallbackBase3<ReturnT,Param1T,Param2T,Param3T>
{
private:
typedef ReturnT (ConsumerT::*PtrMember)(Param1T,Param2T,Param3T);
public:
Callback3( ConsumerT* const object, PtrMember member) : object(object), member(member) { }
Callback3( const Callback3<ConsumerT,ReturnT,Param1T,Param2T,Param3T>& e ) : object(e.object), member(e.member) { }
ReturnT operator()(Param1T param1, Param2T param2, Param3T param3) { return (const_cast<ConsumerT*>(object)->*member) (param1,param2,param3); }
private:
ConsumerT* const object;
const PtrMember member;
};
template <typename ReturnT, typename Param1T, typename Param2T, typename Param3T, typename Param4T>
class CallbackBase4
{
public:
virtual ~CallbackBase4() = 0;
virtual ReturnT operator()(Param1T,Param2T,Param3T,Param4T) = 0;
};
template <typename ReturnT, typename Param1T, typename Param2T, typename Param3T, typename Param4T> MacSim::CallbackBase4<ReturnT,Param1T,Param2T,Param3T,Param4T>::~CallbackBase4() {}
template <typename ConsumerT, typename ReturnT, typename Param1T, typename Param2T, typename Param3T, typename Param4T>
class Callback4: public CallbackBase4<ReturnT,Param1T,Param2T,Param3T,Param4T>
{
private:
typedef ReturnT (ConsumerT::*PtrMember)(Param1T,Param2T,Param3T,Param4T);
public:
Callback4( ConsumerT* const object, PtrMember member) : object(object), member(member) { }
Callback4( const Callback4<ConsumerT,ReturnT,Param1T,Param2T,Param3T,Param4T>& e ) : object(e.object), member(e.member) { }
ReturnT operator()(Param1T param1, Param2T param2, Param3T param3, Param4T param4) { return (const_cast<ConsumerT*>(object)->*member) (param1,param2,param3,param4); }
private:
ConsumerT* const object;
const PtrMember member;
};
}}
#endif
| 71213bcff0d24d6a10bb8170ecd3bab9853a40af | [
"Makefile",
"C++"
] | 5 | C++ | MortezaRamezani/macsim | a37436db886dc3c1416ce4fa46673c5e8dce6d17 | 413ce268ec40cfa93111bd317a2ab7e3c03b2eab | |
refs/heads/main | <file_sep>package com.pfe.tunhome.repositories;
import com.pfe.tunhome.models.Offer;
import com.pfe.tunhome.models.Category;
import org.springframework.data.jpa.repository.JpaRepository;
public interface OfferRepository extends JpaRepository<Offer,Integer> {
}
<file_sep># TUN-HOME-FE<file_sep>package com.pfe.tunhome.repositories;
import com.pfe.tunhome.models.Category;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CategoryRepository extends JpaRepository <Category, Integer> {
}
<file_sep>package com.pfe.tunhome.repositories;
import com.pfe.tunhome.models.Offer;
import com.pfe.tunhome.models.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User,Integer> {
User findByEmail(String email);
}
<file_sep>package com.pfe.tunhome.controllers;
import com.pfe.tunhome.models.Category;
import com.pfe.tunhome.repositories.CategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@CrossOrigin
@RestController
@RequestMapping("categories")
public class CategoryController {
private CategoryRepository categoryRepository ;
@Autowired
public CategoryController(CategoryRepository categoryRepository) {
this.categoryRepository = categoryRepository;
}
@PostMapping(path = "add")
public ResponseEntity<Category> addCategory(@RequestBody Category category) {
Category savedCategory = this.categoryRepository.save(category);
return ResponseEntity.status(HttpStatus.CREATED).body(savedCategory);
}
@GetMapping(path = "all")
public ResponseEntity<List<Category>> getAllCategories() {
List<Category> categories = this.categoryRepository.findAll();
return ResponseEntity.status(200).body(categories);
}
@DeleteMapping(path = "delete/{id}")
public ResponseEntity<Map<String, Object>> deleteCategory(@PathVariable Integer id) {
this.categoryRepository.deleteById(id);
HashMap<String, Object> response = new HashMap<>();
response.put("message", "category Deleted");
return ResponseEntity.status(200).body(response);
}
@GetMapping(path = "one/{id}")
public ResponseEntity<Map<String, Object>> getcategoryById(@PathVariable Integer id) {
HashMap<String, Object> response = new HashMap<>();
try {
Category category = this.categoryRepository.findById(id).get();
response.put("data", category);
return ResponseEntity.status(200).body(response);
} catch (Exception e) {
response.put("message", "category not found");
return ResponseEntity.status(404).body(response);
}
}
@PatchMapping(path = "update")
public ResponseEntity<Category> updateCategory(@RequestBody Category category) {
Category savedCategory = this.categoryRepository.save(category);
return ResponseEntity.status(HttpStatus.CREATED).body(savedCategory);
}
}
<file_sep>package com.pfe.tunhome.controllers;
import com.pfe.tunhome.models.User;
import com.pfe.tunhome.repositories.UserRepository;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@CrossOrigin
@RestController
@RequestMapping("users")
public class UserController {
private UserRepository userRepository;
private BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();//
@Autowired
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
@PostMapping(path = "register")
public ResponseEntity<User> addUser(@RequestBody User user) {
user.password = bCryptPasswordEncoder.encode(user.password);
User savedUser = userRepository.save(user);
return ResponseEntity.status(HttpStatus.CREATED).body(savedUser);
}
@GetMapping(path = "all")
public ResponseEntity<List<User>> getAllUsers() {
List<User> users = this.userRepository.findAll();
return ResponseEntity.status(200).body(users);
}
@PostMapping(path = "login")
public ResponseEntity<Map<String, Object>> loginUser(@RequestBody User user) {
HashMap<String, Object> response = new HashMap<>();
User userFromDB = userRepository.findByEmail(user.email);
if (userFromDB == null) {
response.put("message", "user not found !");
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
} else {
Boolean compare = bCryptPasswordEncoder.matches(user.password, userFromDB.password);
if (!compare) {
response.put("message", "user not found !");
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
} else {
if (!userFromDB.accountState) {
response.put("message", "user not allowed !");
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
} else {
String token = Jwts.builder()
//.claim("data", userFromDB)
.claim("id", userFromDB.id)
.claim("role", userFromDB.role)
.signWith(SignatureAlgorithm.HS256, "SECRET")
.compact();
response.put("token", token);
return ResponseEntity.status(HttpStatus.OK).body(response);
}
}
}
}
@DeleteMapping(path = "delete/{id}")
public ResponseEntity<Map<String, Object>> deleteUser(@PathVariable Integer id) {
this.userRepository.deleteById(id);
HashMap<String, Object> response = new HashMap<>();
response.put("message", "user Deleted");
return ResponseEntity.status(200).body(response);
}
@PatchMapping(path = "update")
public ResponseEntity<User> updateUser(@RequestBody User user) {
User savedUser = this.userRepository.save( user);
return ResponseEntity.status(HttpStatus.CREATED).body(savedUser);
}
}
| c62f0befe417d68b241b4e71383796034f64c139 | [
"Markdown",
"Java"
] | 6 | Java | amal58/TUN-HOME-Bk | aa2bfe6d82b0c5ef73a062a00420b70bc0a72bb1 | 41951c8ba5a18e9763f4a0b9e9477ded937c9a2c | |
HEAD | <repo_name>kofron/erlkm<file_sep>/Makefile
all: get-deps compile dialyze test
get-deps:
@./rebar get-deps
compile: get-deps
@./rebar compile
dialyze: compile
@dialyzer -r ebin ebin/*.beam
test: dialyze
@./rebar eunit
| a38174703d4c5c79969363e558c482422f518735 | [
"Makefile"
] | 1 | Makefile | kofron/erlkm | bbbb60081739a6e69c4072c478262ff9a59d563f | d2a2d19ce899816b6a2435d6545262db4a499e1a | |
refs/heads/master | <repo_name>Leaf27/CS542<file_sep>/HW3/Relation.java
package DB3;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class Relation {
// this result is used to store all information of this relation.
private HashMap<String, ArrayList<String>> result=new HashMap<String, ArrayList<String>>();
// store all keys of this relation.
private HashSet<String> keys=new HashSet<String>();
// this Iterator is used to iterate the relation
private Iterator<String> it;
private String fileName;
// tell result which string is used to be the key for each record in result.
int key_location;
// number of records
int recordSize=0;
// constructor
public Relation(String fileName,int key_location) throws IOException
{
this.fileName=fileName;
this.key_location=key_location;
}
// call methods to read file into result and initialize iterator.
public void open() throws IOException
{
fileToHashMap(fileName,key_location);
it =keys.iterator();
}
public ArrayList<String> getNext()
{
if(it.hasNext()){
String key=it.next();
return result.get(key);
}
else return null;
}
public void close()
{
result.clear();
keys.clear();
}
// get record information for a given key.
public ArrayList<String> get(String key)
{
return result.get(key);
}
// check whether this relation has next or not
public boolean hasNext()
{
return it.hasNext();
}
// check whether this key is in the relation or not
public boolean hasKey(String Key){
return result.containsKey((String) Key);
}
private void fileToHashMap(String fileName,int key_location) throws IOException
{
File file=new File(fileName);
if(file.exists()){
FileReader fis=new FileReader(fileName);
BufferedReader br=new BufferedReader(fis);
String line=null;
int i=0;
while((line=br.readLine())!=null){
ArrayList<String> content=getContent(line.substring(0, line.length()-1));
if(i==0)
{
recordSize=content.size();
i++;
}
result.put(content.get(key_location), content);
keys.add(content.get(key_location));
}
br.close();
}
}
// slice strings
private static ArrayList<String> getContent(String record)
{
ArrayList<String> result =new ArrayList<String>();
record=','+record;
int point=0;
while(point<record.length()){
if(record.charAt(point)==',') {
// the following is a string
if(point+1<record.length()&&record.charAt(point+1)=='\'')
{
if(point+2<record.length())
{
int nextQuote=record.indexOf("\'",point+2);
if(nextQuote!=-1)
{
result.add(record.substring(point+2,nextQuote));
point=nextQuote+1;
}
else
{
result.add(record.substring(point+1,record.length()-1));
break;
}
}
else break;
}
// the following is a number
else if(point+1<record.length())
{
int nextQuote=record.indexOf(",",point+1);
if(nextQuote!=-1)
{
result.add(record.substring(point+1,nextQuote));
point=nextQuote;
}
else
{
result.add(record.substring(point+1));
break;
}
}
else break;
}
else point++;
}
return result;
}
}
<file_sep>/HW2/Util.java
package DB2;
import java.io.*;
import java.util.*;
/**
*/
public class Util
{
private static Util m_instance;
private Util()
{
}
public static Util getInstance()
{
if (m_instance == null)
{
m_instance = new Util();
}
return m_instance;
}
// read data from cs542.db and return map of films of which key is its title and year.
public Map<String, Film> readDataFile(String filePath) throws Exception
{
Map<String, Film> result = new HashMap<>();
try(BufferedReader reader = new BufferedReader(new FileReader(filePath)))
{
String line;
while ((line = reader.readLine()) != null)
{
Film film = new Film(line.split(","));
result.put(film.getKey(), film);
}
return result;
}
}
public void writeDateFile(File file, Collection<Film> filmList)
{
try(BufferedWriter out = new BufferedWriter(new FileWriter(file, false)))
{
for (Film film: filmList)
{
out.write(film.toString());
out.write("\n");
}
}
catch (Exception e)
{
System.out.println("Failed to write to data file, " + e);
System.exit(1);
}
}
public Map<String, Set<String>> readIndexFile(File file) throws Exception
{
try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file)))
{
return (Map<String, Set<String>>) ois.readObject();
}
}
public void writeIndexFile(File file, Map<String, Set<String>> indexes)
{
try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file, false)))
{
oos.writeObject(indexes);
}
catch (Exception e)
{
System.out.println("Failed to write to index file, " + e);
System.exit(1);
}
}
}
<file_sep>/HW1/testDB/src/testDB.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class testDB {
static HW1 test=HW1.getInstance();
static int length=1024*1024;
public static void main(String[] args) throws InterruptedException, IOException{
byte[] halfData=new byte[length/2];
for(int i=0;i<halfData.length;i++){
halfData[i]=1;
}
test.put(1,halfData);
display(test.getFile());
// starts concurrency
System.out.println("Now starts test of concurrency:");
concurrency();
// starts fragmentation test
System.out.println("Now starts test of fragmentation: ");
fragmentation();
}
/* The main thread does a Remove() and the new thread t does a Get() with the same key a millisecond later.
*
*/
private static void concurrency() throws InterruptedException, IOException{
byte[] halfData=new byte[length/2];
for(int i=0;i<length/2;i++){
halfData[i]=1;
}
// create a new thread to get value of which key is 1.
Thread t=new Thread(){
public void run(){
System.out.println("Another thread is running!");
byte[] result=test.get(1);
if(result!=null) {
System.out.println("This is length of the '1' element:"+result.length);
}
}
};
// start the new thread
t.start();
// remove key-value pair of which key is 1.
test.remove(1);
t.join(1);
display(test.getFile());
// let the main thread wait 1000 milliseconds so that the new thread t can be finished before starting fragmentation method.
t.join(1000);
}
/* Put() 4 values, byte arrays of 1 MB each, with keys A, B, C and D. Remove key B. Put() ½ MB in size for key E.
* Validate that a Put() 1 MB in size for key F fails. Remove C and now validate that a Put() 1 MB in size for key G succeeds.
* Remove E and try Put() 1 MB in size for key H. With a naive implementation, it will fail even though there is room in store.db.
* An extra bonus point if you can modify your code such that Put("H", …) succeeds.
*/
private static void fragmentation() throws IOException{
byte[] testData=new byte[length];
for(int i=0;i<length;i++){
testData[i]=1;
}
byte[] halfData=new byte[length/2];
for(int i=0;i<length/2;i++){
halfData[i]=1;
}
// put key A and it's associated value, byte array of 1 MB, into file!
test.put(1,testData);
display(test.getFile());
// put key B and it's associated value, byte array of 1 MB, into file!
test.put(2,testData);
display(test.getFile());
// put key C and it's associated value, byte array of 1 MB, into file!
test.put(3,testData);
display(test.getFile());
// put key D and it's associated value, byte array of 1 MB, into file!
test.put(4,testData);
display(test.getFile());
//Remove key B
test.remove(2);
display(test.getFile());
//Put() ½ MB in size for key E
test.put(5, halfData);
display(test.getFile());
// Put() 1 MB in size for key F and check the result!
test.put(6, testData);
display(test.getFile());
//Remove C
test.remove(3);
display(test.getFile());
//Put() 1 MB in size for key G and check the result!
test.put(7, testData);
display(test.getFile());
//Remove E
test.remove(5);
display(test.getFile());
//Put() 1 MB in size for key H and check the result!
test.put(8, testData);
display(test.getFile());
}
private synchronized static void display(File file) throws IOException{
System.out.println("This is the layout of CS542: ");
if(file.exists()){
FileReader fis=new FileReader(file);
BufferedReader br=new BufferedReader(fis);
String line=null;
int count=0;
while((line=br.readLine())!=null){
if(count==0) System.out.println(line+" // Number of key-value paris");
else if((count%2)==1) {
System.out.println(line+" // the "+(count+1)/2 +"th key");
}
else {
System.out.println(line.length()+" // length of the "+(count+1)/2 +"th value");
}
count++;
}
if(count==0) System.out.println("CS542 is empty!");
System.out.println("");
br.close();
}
else{
System.out.println("I cannot find the file");
}
}
}
<file_sep>/HW4/Log.java
package DB4;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class Log {
private String relationName;
private String LogName;
private String result;
private String transaction;
/**
*
* @param relationName
* @param transaction
*
* pass in the log name and which relation the log log.
*/
public Log(String relationName,String transaction)
{
this.relationName=relationName;
this.transaction=transaction;
LogName=relationName+"Log";
result="start transaction " +transaction+"\n";
}
/**
*
* @param recordPointer
* @param oldValue
* @param newValue
* create a new log of which format is <transaction name, key of the updated record, old value, new value>
*/
public void addLog(String recordPointer, String oldValue, String newValue)
{
result=result.concat(transaction+","+recordPointer+","+oldValue+","+newValue+"\n");
}
/**
* push the log into disk
*/
public void pushLog()
{
File LogFile=new File(LogName);
if(!LogFile.exists())
{
try{
LogFile.createNewFile();
}
catch(IOException e){
System.out.println("create log file fails!");
e.getMessage();
}
}
try(BufferedWriter out = new BufferedWriter(new FileWriter(LogFile, false)))
{
out.write(result);
out.write("commit "+ transaction);
}
catch (Exception e)
{
System.out.println("Failed to write log file into disk, " + e);
System.exit(1);
}
}
/**
*
* @return logs information
* @throws FileNotFoundException
* @throws IOException
*
* read logs from disk
*/
public ArrayList<String[]> readLog() throws FileNotFoundException, IOException{
ArrayList<String[]> logs=new ArrayList<>();
File logFile=new File(LogName);
String line;
String[] oneLog=new String[4];
try(BufferedReader br=new BufferedReader(new FileReader(LogName)))
{
while((line=br.readLine())!=null)
{
if(line.contains("start")||line.contains("commit")) continue;
logs.add(line.split(","));
}
}
return logs;
}
/**
* display log
*/
public void showLog(){
System.out.println(result);
}
}
<file_sep>/HW1/README.md
# CS542
Teammember:<br>
<NAME> <br>
<NAME> <br>
<NAME> <br>
The main function is in repository testDB/src/testDB.java
<file_sep>/HW4/Test.java
package DB4;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
public class Test {
private static String path=System.getProperty("user.dir");
private static String CityPath=path+"/cs542.db/city.txt";
private static String CountryPath=path+"/cs542.db/country.txt";
private static String CityAPath=path+"/cs542A.db/city.txt";
private static String CountryAPath=path+"/cs542A.db/country.txt";
// index of population in city relation.
private static int CityPopulation=4;
// index of population in country relation.
private static int CountryPopulation=6;
private static ArrayList<String> record=null;
// names of transactions
private static String UpdateCity="UpdateCity";
private static String UpdateCountry="UpdateCountry";
public static void main(String[] args) throws IOException{
// update cs542.db and write logs
Relation City=new Relation(CityPath,0);
Relation Country=new Relation(CountryPath,0);
Log CityLog=new Log("City",UpdateCity);
Log CountryLog=new Log("Country",UpdateCountry);
update(City,CityLog,CityPopulation);
CityLog.pushLog();
City.HashMaptofile();
update(Country,CountryLog,CountryPopulation);
CountryLog.pushLog();
Country.HashMaptofile();
// use the log to update cs542A.db
Relation CityA=new Relation(CityAPath,0);
Relation CountryA=new Relation(CountryAPath,0);
updateBackup(CityA,CityLog,CityPopulation);
CityA.HashMaptofile();
System.out.println("city in cs542 and city in cs542A are identical or not?");
System.out.println("the result is: "+check(CityPath,CityAPath,CityPopulation));
updateBackup(CountryA,CountryLog,CountryPopulation);
CountryA.HashMaptofile();
System.out.println("country in cs542 and country in cs542A are identical or not?");
System.out.println("the result is: "+check(CountryPath,CountryAPath,CountryPopulation));
}
/**
*
* @param relation, passed in to specify which relation need to be updated
* @param log, specify where logs to be written.
* @param population, index of population in one record.
*
* For each record in relation, write the undo/redo log into its associated log file.
* The format of log is <transaction_name, pointer of record, old population, updated population >
* After generating log, increase population in this record by 2%.
*/
public static void update(Relation relation, Log log,int population){
while(relation.hasNext())
{
record=relation.getNext();
log.addLog(record.get(0), record.get(population), increasePopulation(record.get(population)));
record.set(population, increasePopulation(record.get(population)));
}
log.showLog();
}
/**
*
* @param relation
* @param log
* @param population
* @throws FileNotFoundException
* @throws IOException
*
* read log from disk, and we can replace old population by new value in log.
*/
public static void updateBackup(Relation relation, Log log,int population) throws FileNotFoundException, IOException
{
ArrayList<String[]> logs = log.readLog();
for(String[] oneLog : logs){
String pointer=oneLog[1];
relation.get(pointer).set(population, oneLog[3]);
}
}
/**
*
* @param population
* @return updated population which is product of population and 102%.
*/
private static String increasePopulation(String population)
{
int newPopulation = (int)(Integer.parseInt(population)*1.02);
return Integer.toString(newPopulation);
}
/**
*
* @param relationPath
* @param relationAPath
* @param population
* @return
* @throws IOException
* check whether two relations are identical or not
*/
private static boolean check(String relationPath, String relationAPath,int population) throws IOException
{
Relation DB1=new Relation(relationPath,0);
Relation DB2=new Relation(relationAPath,0);
while(DB1.hasNext())
{
ArrayList<String> record = DB1.getNext();
if(record.get(population).equals(DB2.get(record.get(0)).get(population))) continue;
else return false;
}
return true;
}
}
<file_sep>/README.md
# CS542
used for homework of DataBase system.<br>
Team Member:<br>
<NAME>, <EMAIL> <br>
<NAME>, <EMAIL> <br>
<NAME>, <EMAIL> <br>
<file_sep>/HW2/Test.java
package DB2;
import java.util.*;
public class Test
{
private static Map<String, Film> FILMS = new HashMap<>();
private static final String DATA_FILE_PATH = "cs542.db";
public static void main(String[] args)
{
try
{
FILMS = Util.getInstance().readDataFile(DATA_FILE_PATH);
}
catch (Exception e)
{
System.out.println("Failed to read data file, " + e);
System.exit(1);
}
testCase1();
testCase2();
testCase3();
}
private static void testCase1()
{
DB db = DB.getInstance();
for (String key: FILMS.keySet())
{
Film film = FILMS.get(key);
String[] attributes = film.getAttributes();
String index = attributes[Film.Attributes.Year.ordinal()] + "|" + attributes[Film.Attributes.Format.ordinal()];
db.put(film.getKey(), index);
}
System.out.println("\nStarting Test 1...");
System.out.println("------------------------------------");
System.out.println("\nAll DVD movies made in 1977:");
db.get("1977|DVD");
System.out.println("\nAll VHS movies made in 1990:");
db.get("1990|VHS");
System.out.println("\nAll DVD movies made in 2001:");
db.get("2001|DVD");
}
private static void testCase2()
{
System.out.println();
System.out.println("Starting Test 2...");
System.out.println("------------------------------------");
DB db = DB.getInstance();
for (String key: FILMS.keySet())
{
Film film = FILMS.get(key);
String[] attributes = film.getAttributes();
String index = attributes[Film.Attributes.Year.ordinal()];
db.put(film.getKey(), index);
}
System.out.println("\nFind all movies made in 2000:");
db.get("2000");
System.out.println("\nFind all movies made in 2005:");
db.get("2005");
System.out.println("\nFind all movies made in 2010:");
db.get("2010");
}
private static void testCase3()
{
System.out.println();
System.out.println("Starting Test 3...");
System.out.println("------------------------------------");
DB db = DB.getInstance();
for (String key: FILMS.keySet())
{
Film film = FILMS.get(key);
String[] attributes = film.getAttributes();
String index = attributes[Film.Attributes.Year.ordinal()];
db.put(film.getKey(), index);
}
String title = "<NAME>";
String year = "1977";
String key = title + "|" + year;
System.out.println("All movies made in " + year);
System.out.println("\nBefore removing:");
db.get(year);
System.out.println("\nRemoving entry: " + key);
db.remove(key);
System.out.println("\nAfter removing:");
db.get(year);
}
}
| 643381de03804035077ba685a886bc09e2f75c69 | [
"Markdown",
"Java"
] | 8 | Java | Leaf27/CS542 | 0be9de4d479403842e668af12088c877fced1657 | cd70e4f942a8a0493fe3cee82b3a1000a9080ce3 | |
refs/heads/master | <file_sep># Refactor Udagram app into Microservices and Deploy
## How to Run Project
Clone repo:
` git clone -b 06-ci https://github.com/naoussi/cloud-developer.git`
- Install dependencies for the frontend,
- navigate to the directory _cloud-developer/course-03/exercises/udacity-c3-frontend_
- Run `npm install` to install dependencies
- If you don't haver ionic setup on your system, run `npm install -g ionic`
- You can run a test on the frontend with the command `npm test`
- You can startup the front end application locally with the command `ionic serve`
- Install dependencies of the feed restapi.
- navigate to the directory _cloud-developer/course-03/exercises/udacity-c3-resapi-feed_
- Run `npm install` to install dependencies
- Run `npm run dev` to run server locally
- Install dependencies of the user restapi.
- navigate to the directory _cloud-developer/course-03/exercises/udacity-c3-resapi-user_
- Run `npm install` to install dependencies
- Run`npm run dev` to run server locally
- I allowed the `master` branch which will hold the final deployment to production while the dev branch holds development work at each instant.
## Setup Docker Environment
You'll need to install docker https://docs.docker.com/install/.
To create, deploy and run the docker images, I simply used the `docker-compose up` command.
- Navigate to the directory _cloud-developer/course03/exercises/udacity-c3-deployement/docker_
- Open a new terminal within the above mentioned docker directory and run:
1. Build the images: `docker-compose -f docker-compose-build.yaml build --parallel`
2. Push the images: `docker-compose -f docker-compose-build.yaml push`
3. Run the container: `docker-compose up`
### Run App on Docker
- Open on the browers the link `localhost:8100`
[docker hub](https://hub.docker.com/u/fanyui)

## Setup kubernetes clusters
Install and setup kubeone and terraform
- navigate to the directory _cloud-developer/course03/exercises/udacity-c3-deployement/k8s_
### Creating AWS infrastructure
- Open a new terminal from this directory and run the following command:
1. Initialize terraform: `terraform init`
2. `terraform plan`
3. `terraform apply`
4. `terraform output -json > tf.json`
### Installing kubernetes
- Verify kubeone installation: `kubeone config print --full`
- Copy configuration: `kubeone config print > config.yaml`
- Install kubernetes cluster: `kubeone install config.yaml --tfjson tf.json`
- Get Kubeconfig file: `kubectl --kubeconfig=<cluster_name>-kubeconfig`
- export the KUBECONFIG variable environment variable: `export KUBECONFIG=$PWD/<cluster_name>-kubeconfig`
### Deploying to kuberbetes
- `kubectl apply -f backend-feed-deployment.yaml`
- `kubectl apply -f backend-user-deployment.yaml`
- `kubectl apply -f frontend-deployment.yaml`
- `kubectl apply -f reverseproxy-deployment.yaml`
### Adding configurations
- `kubectl apply -f aws-secret.yaml`
- `kubectl apply -f env-configmap.yaml`
- `kubectl apply -f env-secret.yaml`
### Run Kubernetes application on local machine
- Verify pods: kubectl get pod
- Run reverseproxy server: `kubectl port-forward pod/reverseproxy-xxxxx-xx 8080:8080`
- Run frontend: `pod/frontend-xxxxxx-xxxx 8100:8100`
### Deploy services on Kubernetes
- `kubectl apply -f backend-feed-service.yaml`
- `kubectl apply -f backend-user-service.yaml`
- `kubectl apply -f frontend-service.yaml`
- `kubectl apply -f reverseproxy-service.yaml`
## References
- [Kubeone](https://github.com/kubermatic/kubeone)
- [Kubernetes clusters on AWS using KubeOne](https://www.loodse.com/blog/2019-07-25-running-ha-kubernetes/)
<file_sep>import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { FeedUploadComponent } from './feed-upload.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { HttpClientModule } from '@angular/common/http';
describe('FeedUploadPage', () => {
let component: FeedUploadComponent;
let fixture: ComponentFixture<FeedUploadComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports : [
FormsModule,
ReactiveFormsModule,
IonicModule,
HttpClientModule
],
declarations: [ FeedUploadComponent ],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(FeedUploadComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| fadfe56a593d62db4ad8cc9750a0e3068585c9fa | [
"Markdown",
"TypeScript"
] | 2 | Markdown | fanyui/cloud-developer | 1dac83070d9512baa6fee0d1b945c093889d344c | bed1e204077b91d8d067bad301d5fbd0abcc8831 | |
refs/heads/main | <repo_name>LiborV/trello-vue<file_sep>/src/store/index.js
import { createStore } from 'vuex'
import { data } from '@/data.js'
const list = {
namespaced: true,
state: {
lists: data
},
mutations: {
AddNewList (state, title) {
const listMaxId = state.lists.length
? Math.max(...state.lists.map(list => list.id))
: 0
state.lists.push({
id: listMaxId + 1,
title: title.value,
cards: []
})
},
AddNewCard (state, { listNewCard, NewCardText }) {
const cardMaxId = listNewCard.cards.length
? Math.max(...listNewCard.cards.map(card => card.id))
: 0
listNewCard.cards.push({
id: cardMaxId + 1,
text: NewCardText
})
},
editListTitle (state, { listNewTitle, newLisText }) {
listNewTitle.title = newLisText
},
trashCardFromList (state, { selectList, trashedCard }) {
selectList.cards = selectList.cards.filter(
card => card.id !== trashedCard.cardId
)
},
editCardText (state, { editedCard, editCard }) {
editedCard.text = editCard.newText
}
},
actions: {
AddNewCard ({ commit, state }, NewCard) {
const listNewCard = state.lists.find(list => list.id === NewCard.listId)
const NewCardText = NewCard.text
commit('AddNewCard', { listNewCard, NewCardText })
},
editListTitle ({ commit, state }, newTitle) {
const listNewTitle = state.lists.find(list => list.id === newTitle.listId)
const newLisText = newTitle.title
commit('editListTitle', { listNewTitle, newLisText })
},
trashCardFromList ({ commit, state }, trashedCard) {
if (!trashedCard?.listId || !trashedCard?.cardId) return
const selectList = state.lists.find(list => list.id === trashedCard.listId)
commit('trashCardFromList', { selectList, trashedCard })
},
editCardText ({ commit, state }, editCard) {
const listForEditedCard = state.lists.find(list => list.id === editCard.listId)
const editedCard = listForEditedCard.cards.find(card => card.id === editCard.cardId)
commit('editCardText', { editedCard, editCard })
}
},
getters: {
getLists (state) {
return state.lists
}
}
}
const overlay = {
namespaced: true,
state: {
overlay: false
},
mutations: {
overlaySwitch (state, event) {
state.overlay = event
}
},
getters: {
getOverlay (state) {
return state.overlay
}
}
}
export default createStore({
modules: {
list,
overlay
}
})
| c30eeb6e25e4c749d33faaf615a63f16e26322ce | [
"JavaScript"
] | 1 | JavaScript | LiborV/trello-vue | bbc049781e6a4c81f969a4e5e8156cff0654cb58 | 1452607ee9fa3ab174c7c9c56dd6045b89916375 | |
refs/heads/master | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public struct CUSTOM_VERTEX
{
public Vector3 pos;
public Vector3 normal;
public Color color;
public CUSTOM_VERTEX(Vector3 pos, Vector3 normal, Color color)
{
this.pos = pos;
this.normal = normal;
this.color = color;
}
}
//버텍스와 노말 텍스쳐좌표를 받는 버텍스 구조체
public struct TEX_VERTEX
{
public float _x, _y, _z;
public float _nx, _ny, _nz;
public float _u, _v;
public TEX_VERTEX(float x, float y, float z, float nx, float ny, float nz, float u, float v)
{
_x = x;
_y = y;
_z = z;
_nx = nx;
_ny = ny;
_nz = nz;
_u = u;
_v = v;
}
}
| 420a3be63b7c1ae9fc7e58f6c7b5ecb098c6e92f | [
"C#"
] | 1 | C# | cafealpha/UnityTexquad | 1224a4785df2924b5d58e0f43d99ff46cc63dfdf | 0a7a7423eeb82b896d311e90ca1329f2e1ada06f | |
refs/heads/master | <file_sep>package gotimer
// NewTime - 新しいgotimer.Timeを生成する
func NewTime(hour, minute, second int) Time {
sec := (hour*60*60 + minute*60 + second) % (24 * 60 * 60)
if sec < 0 {
sec = 24*60*60 + sec
}
return Time(sec)
}
// Time - 時分秒を秒にした構造体
type Time int
func (t Time) hour() int {
return int(t) / 60 / 60
}
func (t Time) minute() int {
return (int(t) / 60) % 60
}
func (t Time) second() int {
return int(t) % 60
}
<file_sep>module gitlab.com/tsuchinaga/gotimer
go 1.15
<file_sep>package gotimer
import "time"
// NewTerm - 新しい期間を返す
func NewTerm(start, stop Time) Term {
return Term{start: start, stop: stop}
}
// Term - 期間の設定
type Term struct {
start Time
stop Time
}
// runnable - startとstopの間にnowがあれば実行可能
func (t *Term) runnable(now time.Time) bool {
n := time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second(), 0, now.Location())
start := time.Date(now.Year(), now.Month(), now.Day(), t.start.hour(), t.start.minute(), t.start.second(), 0, now.Location())
stop := time.Date(now.Year(), now.Month(), now.Day(), t.stop.hour(), t.stop.minute(), t.stop.second(), 0, now.Location())
if t.stop < t.start {
nt := NewTime(now.Hour(), now.Minute(), now.Second())
if nt <= t.stop { // now <= stop なら、startを前日にする
start = start.AddDate(0, 0, -1)
} else {
stop = stop.AddDate(0, 0, 1)
}
}
return !n.Before(start) && !n.After(stop)
}
// runnableSecond - 実行可能期間を秒で返す
func (t *Term) runnableSecond() int {
sec := int(t.stop) - int(t.start) + 1
if sec <= 0 {
sec += 24 * 60 * 60
}
return sec
}
func (t *Term) Equal(term Term) bool {
return t.start == term.start && t.stop == term.stop
}
func (t *Term) In(time Time) bool {
if t.stop < t.start { // stop < start
return time <= t.stop || t.start <= time // start <= time || time <= stop
} else { // start <= stop
return t.start <= time && time <= t.stop // start <= time <= stop
}
}
<file_sep>package gotimer
import (
"context"
"reflect"
"sync"
"testing"
"time"
)
func Test_Timer_Run(t *testing.T) {
t.Parallel()
tests := []struct {
name string
timer *Timer
ctx context.Context
interval time.Duration
task func()
want error
}{
{name: "ctxが未設定ならerror", timer: &Timer{}, want: TimerNotSetContextError},
{name: "intervalが1未満ならerror", timer: &Timer{}, ctx: context.Background(), want: TimerNotSetIntervalError},
{name: "taskがnilならerror", timer: &Timer{}, ctx: context.Background(), interval: 15 * time.Second, want: TimerNotSetTaskError},
{name: "isRunningがtrueならerror", timer: &Timer{timerRunning: true}, ctx: context.Background(), interval: 15 * time.Second, task: func() {}, want: TimerIsRunningError},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
got := test.timer.Run(test.ctx, test.interval, test.task)
if !reflect.DeepEqual(test.want, got) {
t.Errorf("%s error\nwant: %+v\ngot: %+v\n", t.Name(), test.want, got)
}
})
}
}
func Test_Timer_Run_Cancel(t *testing.T) {
t.Parallel()
var count int
timer := new(Timer)
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
interval := 3 * time.Second
task := func() { count++ }
got := timer.Run(ctx, interval, task)
if count != 0 || got != nil {
t.Errorf("%s error\nwant: %+v, %+v\ngot: %+v, %+v\n", t.Name(), 0, nil, count, got)
}
cancel()
}
func Test_Timer_Run_Task(t *testing.T) {
t.Parallel()
now := time.Now()
var count int
timer := new(Timer)
timer.AddTerm(NewTerm(NewTime(now.Hour(), now.Minute(), now.Second()+1), NewTime(now.Hour(), now.Minute(), now.Second()+10)))
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
interval := 1 * time.Second
task := func() { count++ }
got := timer.Run(ctx, interval, task)
if count != 3 || got != nil {
t.Errorf("%s error\nwant: %+v, %+v\ngot: %+v, %+v\n", t.Name(), 3, nil, count, got)
}
cancel()
}
func Test_Timer_Run_Parallel(t *testing.T) {
t.Parallel()
tests := []struct {
name string
parallel bool
timeout time.Duration
interval time.Duration
want int
}{
{name: "Parallelが許可されている場合、複数回実行される", parallel: true, timeout: 1 * time.Second, interval: 100 * time.Millisecond, want: 10},
{name: "Parallelが許可されていない場合、1回しか実行されない", parallel: false, timeout: 1 * time.Second, interval: 100 * time.Millisecond, want: 1},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
var count int
var mtx sync.Mutex
task := func() {
mtx.Lock()
count++
mtx.Unlock()
time.Sleep(test.timeout)
}
timer := new(Timer)
ctx, cancel := context.WithTimeout(context.Background(), test.timeout)
defer cancel()
err := timer.SetParallelRunnable(test.parallel).Run(ctx, test.interval, task)
if test.want != count && err != nil {
t.Errorf("%s error\nwant: %+v\ngot: %+v, %+v\n", t.Name(), test.want, count, err)
}
})
}
}
func Test_Timer_SetParallelRunnable(t *testing.T) {
t.Parallel()
tests := []struct {
name string
timerRunning bool
want bool
}{
{name: "timerRunningでなければ設定が反映される", timerRunning: false, want: true},
{name: "timerRunningであれば設定が反映されない", timerRunning: true, want: false},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
timer := &Timer{timerRunning: test.timerRunning}
timer.SetParallelRunnable(true)
got := timer.parallelRunnable
if !reflect.DeepEqual(test.want, got) {
t.Errorf("%s error\nwant: %+v\ngot: %+v\n", t.Name(), test.want, got)
}
})
}
}
func Test_Timer_AddTerm(t *testing.T) {
t.Parallel()
tests := []struct {
name string
timerRunning bool
terms []Term
term Term
want []Term
}{
{name: "timerRunningであれば変更が反映されない",
timerRunning: true,
terms: []Term{NewTerm(NewTime(8, 45, 0), NewTime(15, 15, 0))},
term: NewTerm(NewTime(16, 30, 0), NewTime(5, 30, 0)),
want: []Term{NewTerm(NewTime(8, 45, 0), NewTime(15, 15, 0))}},
{name: "timerRunningでなければ期間が追加される",
timerRunning: false,
terms: []Term{NewTerm(NewTime(8, 45, 0), NewTime(15, 15, 0))},
term: NewTerm(NewTime(16, 30, 0), NewTime(5, 30, 0)),
want: []Term{NewTerm(NewTime(8, 45, 0), NewTime(15, 15, 0)), NewTerm(NewTime(16, 30, 0), NewTime(5, 30, 0))}},
{name: "同じ期間があれば追加されない",
timerRunning: false,
terms: []Term{NewTerm(NewTime(8, 45, 0), NewTime(15, 15, 0))},
term: NewTerm(NewTime(8, 45, 0), NewTime(15, 15, 0)),
want: []Term{NewTerm(NewTime(8, 45, 0), NewTime(15, 15, 0))}},
{name: "追加後、開始時刻の昇順、停止時刻の降順で並び変えられる",
timerRunning: false,
terms: []Term{NewTerm(NewTime(8, 45, 0), NewTime(15, 15, 0))},
term: NewTerm(NewTime(8, 45, 0), NewTime(5, 30, 0)),
want: []Term{NewTerm(NewTime(8, 45, 0), NewTime(5, 30, 0)), NewTerm(NewTime(8, 45, 0), NewTime(15, 15, 0))}},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
timer := Timer{timerRunning: test.timerRunning, terms: test.terms}
timer.AddTerm(test.term)
got := timer.terms
if !reflect.DeepEqual(test.want, got) {
t.Errorf("%s error\nwant: %+v\ngot: %+v\n", t.Name(), test.want, got)
}
})
}
}
func Test_Timer_nextTime(t *testing.T) {
t.Parallel()
tests := []struct {
name string
timer *Timer
now time.Time
want time.Time
}{
{name: "前回の実行日時が分からなければ次の開始日時を返す",
timer: &Timer{terms: []Term{NewTerm(NewTime(12, 0, 0), NewTime(13, 0, 0))}},
now: time.Date(2020, 12, 21, 11, 0, 0, 0, time.Local),
want: time.Date(2020, 12, 21, 12, 0, 0, 0, time.Local)},
{name: "前回の実行日時からinterval後の日時を返す",
timer: &Timer{
interval: 15 * time.Second,
terms: []Term{NewTerm(NewTime(11, 0, 0), NewTime(12, 0, 0))},
next: time.Date(2020, 12, 21, 11, 0, 0, 0, time.Local)},
now: time.Date(2020, 12, 21, 11, 0, 0, 0, time.Local),
want: time.Date(2020, 12, 21, 11, 0, 15, 0, time.Local)},
{name: "前回の実行日時からinterval後の日時の間に停止日時があれば次の開始時刻を返す",
timer: &Timer{
interval: 15 * time.Second,
terms: []Term{NewTerm(NewTime(11, 0, 0), NewTime(11, 0, 10))},
next: time.Date(2020, 12, 21, 11, 0, 0, 0, time.Local)},
now: time.Date(2020, 12, 21, 11, 0, 0, 0, time.Local),
want: time.Date(2020, 12, 22, 11, 0, 0, 0, time.Local)},
{name: "前回の実行日時が分からなくて、即時実行可能なら現在日時を返す",
timer: &Timer{
terms: []Term{NewTerm(NewTime(10, 0, 0), NewTime(12, 0, 0))},
startNow: true},
now: time.Date(2020, 12, 21, 11, 0, 0, 0, time.Local),
want: time.Date(2020, 12, 21, 11, 0, 0, 0, time.Local)},
{name: "前回の実行日時が分からなくて、即時実行可能でもtermsがなければ次の開始日時を返す",
timer: &Timer{
terms: []Term{NewTerm(NewTime(11, 0, 0), NewTime(12, 0, 0))},
startNow: true},
now: time.Date(2020, 12, 21, 13, 0, 0, 0, time.Local),
want: time.Date(2020, 12, 22, 11, 0, 0, 0, time.Local)},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
got := test.timer.nextTime(test.now)
if !reflect.DeepEqual(test.want, got) {
t.Errorf("%s error\nwant: %+v\ngot: %+v\n", t.Name(), test.want, got)
}
})
}
}
func Test_Timer_runnable(t *testing.T) {
t.Parallel()
tests := []struct {
name string
terms []Term
now time.Time
want bool
}{
{name: "termsのいずれかがtrueならtrueを返す",
terms: []Term{
NewTerm(NewTime(0, 0, 0), NewTime(1, 0, 0)),
NewTerm(NewTime(2, 0, 0), NewTime(3, 0, 0)),
NewTerm(NewTime(4, 0, 0), NewTime(5, 0, 0)),
NewTerm(NewTime(6, 0, 0), NewTime(7, 0, 0)),
},
now: time.Date(2020, 12, 28, 6, 30, 0, 0, time.Local),
want: true},
{name: "termsのいずれもfalseならfalseを返す",
terms: []Term{
NewTerm(NewTime(0, 0, 0), NewTime(1, 0, 0)),
NewTerm(NewTime(2, 0, 0), NewTime(3, 0, 0)),
NewTerm(NewTime(4, 0, 0), NewTime(5, 0, 0)),
NewTerm(NewTime(6, 0, 0), NewTime(7, 0, 0)),
},
now: time.Date(2020, 12, 28, 5, 30, 0, 0, time.Local),
want: false},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
got := (&Timer{terms: test.terms}).runnable(test.now)
if !reflect.DeepEqual(test.want, got) {
t.Errorf("%s error\nwant: %+v\ngot: %+v\n", t.Name(), test.want, got)
}
})
}
}
func Test_Timer_nextStart(t *testing.T) {
t.Parallel()
tests := []struct {
name string
timer *Timer
now time.Time
want time.Time
}{
{name: "開始時刻がなければ翌日の00:00:00が返される",
timer: &Timer{interval: 15 * time.Second, terms: []Term{}},
now: time.Date(2020, 12, 21, 10, 05, 30, 123456789, time.Local),
want: time.Date(2020, 12, 22, 0, 0, 0, 0, time.Local)},
{name: "当日に未来の開始時刻があればその開始日時が返される",
timer: &Timer{interval: 15 * time.Second, terms: []Term{NewTerm(NewTime(10, 10, 0), NewTime(10, 20, 0))}},
now: time.Date(2020, 12, 21, 10, 05, 30, 123456789, time.Local),
want: time.Date(2020, 12, 21, 10, 10, 0, 0, time.Local)},
{name: "開始時刻がすべて過去なら翌日の開始日時が返される",
timer: &Timer{interval: 15 * time.Second, terms: []Term{
NewTerm(NewTime(1, 0, 0), NewTime(23, 59, 59)),
NewTerm(NewTime(2, 0, 0), NewTime(23, 59, 59)),
NewTerm(NewTime(10, 0, 0), NewTime(23, 59, 59)),
}},
now: time.Date(2020, 12, 21, 10, 05, 30, 123456789, time.Local),
want: time.Date(2020, 12, 22, 1, 0, 0, 0, time.Local)},
{name: "現在日時と重なった開始時刻は返されない",
timer: &Timer{interval: 15 * time.Second, terms: []Term{
NewTerm(NewTime(10, 0, 0), NewTime(23, 59, 59)),
NewTerm(NewTime(10, 5, 30), NewTime(23, 59, 59)),
NewTerm(NewTime(10, 6, 0), NewTime(23, 59, 59)),
}},
now: time.Date(2020, 12, 21, 10, 05, 30, 123456789, time.Local),
want: time.Date(2020, 12, 21, 10, 6, 0, 0, time.Local)},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
got := test.timer.nextStart(test.now)
if !reflect.DeepEqual(test.want, got) {
t.Errorf("%s error\nwant: %+v\ngot: %+v\n", t.Name(), test.want, got)
}
})
}
}
func Test_Timer_incrementTaskRunning(t *testing.T) {
t.Parallel()
tests := []struct {
name string
taskRunning int
parallelRunnable bool
want1 bool
want2 int
}{
{name: "多重起動不可で実行数が1なら実行できないのでfalse",
taskRunning: 1, parallelRunnable: false, want1: false, want2: 1},
{name: "多重起動不可で実行数が0なら実行できるのでtrue",
taskRunning: 0, parallelRunnable: false, want1: true, want2: 1},
{name: "多重起動可で実行数が1なら実行できるのでtrue",
taskRunning: 1, parallelRunnable: true, want1: true, want2: 2},
{name: "多重起動可で実行数が0なら実行できるのでtrue",
taskRunning: 0, parallelRunnable: true, want1: true, want2: 1},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
timer := &Timer{taskRunning: test.taskRunning, parallelRunnable: test.parallelRunnable}
got := timer.incrementTaskRunning()
if !reflect.DeepEqual(test.want1, got) || !reflect.DeepEqual(test.want2, timer.taskRunning) {
t.Errorf("%s error\nwant: %+v, %+v\ngot: %+v, %+v\n", t.Name(), test.want1, test.want2, got, timer.taskRunning)
}
})
}
}
func Test_Timer_SetStartNow(t *testing.T) {
t.Parallel()
tests := []struct {
name string
timerRunning bool
want bool
}{
{name: "timerRunningでなければ設定が反映される", timerRunning: false, want: true},
{name: "timerRunningであれば設定が反映されない", timerRunning: true, want: false},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
timer := &Timer{timerRunning: test.timerRunning}
timer.SetStartNow(true)
got := timer.startNow
if !reflect.DeepEqual(test.want, got) {
t.Errorf("%s error\nwant: %+v\ngot: %+v\n", t.Name(), test.want, got)
}
})
}
}
<file_sep>package gotimer
import (
"context"
"errors"
"sort"
"sync"
"time"
)
var (
TimerNotSetContextError = errors.New("not set ctx")
TimerNotSetIntervalError = errors.New("not set interval")
TimerNotSetTaskError = errors.New("not set task")
TimerIsRunningError = errors.New("timer is running now")
)
// Timer - タイマー
type Timer struct {
interval time.Duration
terms []Term
currentTerm int
ch chan time.Time
timerRunning bool
taskRunning int
parallelRunnable bool
startNow bool
next time.Time
timer time.Timer
mtx sync.Mutex
}
// SetParallelRunnable - タスクの多重実行を許容するか
func (t *Timer) SetParallelRunnable(runnable bool) *Timer {
t.mtx.Lock()
defer t.mtx.Unlock()
if t.timerRunning {
return t
}
t.parallelRunnable = runnable
return t
}
// SetStartNow - タスクの初回実行をすぐに行うか
func (t *Timer) SetStartNow(startNow bool) *Timer {
t.mtx.Lock()
defer t.mtx.Unlock()
if t.timerRunning {
return t
}
t.startNow = startNow
return t
}
// AddTerm - 実行期間を追加する
func (t *Timer) AddTerm(term Term) *Timer {
t.mtx.Lock()
defer t.mtx.Unlock()
if t.timerRunning {
return t
}
if t.terms == nil {
t.terms = []Term{}
}
// 重複チェック 同じ期間があれば追加しない
for _, tt := range t.terms {
if tt.Equal(term) {
return t
}
}
t.terms = append(t.terms, term)
// startが小さいか、startが同じなら実行時間が長いのを前にする
sort.Slice(t.terms, func(i, j int) bool {
return t.terms[i].start < t.terms[j].start ||
(t.terms[i].start == t.terms[j].start && t.terms[i].runnableSecond() > t.terms[j].runnableSecond())
})
return t
}
// Run - タイマーの開始
func (t *Timer) Run(ctx context.Context, interval time.Duration, task func()) error {
if ctx == nil {
return TimerNotSetContextError
}
if interval <= 0 {
return TimerNotSetIntervalError
}
if task == nil {
return TimerNotSetTaskError
}
// 開始してフラグを立てるまでは排他ロック
t.mtx.Lock()
if t.timerRunning {
t.mtx.Unlock()
return TimerIsRunningError
}
t.timerRunning = true
defer func() {
t.mtx.Lock()
t.timerRunning = false
t.mtx.Unlock()
}()
t.mtx.Unlock()
t.interval = interval
if t.terms == nil {
t.terms = append(t.terms, NewTerm(NewTime(0, 0, 0), NewTime(23, 59, 59)))
}
for {
now := time.Now()
// 次の実行時刻を決定
t.next = t.nextTime(now)
d := t.next.Sub(now)
tm := time.NewTimer(d)
select {
case <-tm.C: // 実行時間が来たら非同期で実行
go func() {
if t.incrementTaskRunning() { // タスク実行中でないか、多重起動許容の場合にタスクを実行する
defer t.decrementTaskRunning()
task()
}
}()
case <-ctx.Done(): // ctxの終了ならreturn nil
tm.Stop() // そのまま捨てられるタイマーなので発火済みかなど気にしない
return nil
}
}
}
// incrementTaskRunning - 実行中のタスクのカウントを増やす
// ただし、多重起動不可なら複数起動はしないので、その場合は実質上限1
func (t *Timer) incrementTaskRunning() bool {
t.mtx.Lock()
defer t.mtx.Unlock()
// タスク実行中かつ、多重起動不可ならロックが取れない
if t.taskRunning > 0 && !t.parallelRunnable {
return false
}
t.taskRunning++
return true
}
// decrementTaskRunning - 実行中のタスクのカウントを減らす
func (t *Timer) decrementTaskRunning() {
t.mtx.Lock()
defer t.mtx.Unlock()
t.taskRunning--
}
// nextTime - 次回実行日時を取得する
func (t *Timer) nextTime(now time.Time) time.Time {
// nextがzeroタイムなら直近の開始日時を設定する、zeroタイムでなければ前回実行日時 + intervalを設定する
if t.next.IsZero() {
if t.startNow && t.runnable(now) {
return now
} else {
return t.nextStart(now)
}
} else {
nt := t.next.Add(t.interval)
// 次回実行日時が実行可能でなければ、次の開始時刻を採用する
if !t.runnable(nt) {
nt = t.nextStart(now)
}
return nt
}
}
// nextStart - 次の開始日時を取得する
// 期間から次の開始日時が取れなかった場合、翌日の0時を返す
func (t *Timer) nextStart(now time.Time) time.Time {
for i := 0; i <= 1; i++ {
for _, term := range t.terms {
nt := time.Date(now.Year(), now.Month(), now.Day(), term.start.hour(), term.start.minute(), term.start.second(), 0, time.Local)
nt = nt.AddDate(0, 0, i)
if nt.After(now) {
return nt
}
}
}
return time.Date(now.Year(), now.Month(), now.Day()+1, 0, 0, 0, 0, time.Local)
}
// runnable - Timerの持つtermsをすべて見て、実行可能かを返す
func (t *Timer) runnable(now time.Time) bool {
for _, term := range t.terms {
if term.runnable(now) {
return true
}
}
return false
}
<file_sep># gotimer


Go言語のタイマー / ティッカー
設定方法が違うcronのようなライブラリで、定期的にタスクを実行するのに使う
<file_sep>package gotimer
import (
"reflect"
"testing"
"time"
)
func Test_Term_runnable(t *testing.T) {
t.Parallel()
tests := []struct {
name string
term Term
now time.Time
want bool
}{
{name: "start == stopで、now < startならfalse",
term: Term{Time(9 * 60 * 60), Time(9 * 60 * 60)},
now: time.Date(2020, 12, 25, 8, 59, 59, 0, time.Local),
want: false},
{name: "start == stopで、now == startならtrue",
term: Term{Time(9 * 60 * 60), Time(9 * 60 * 60)},
now: time.Date(2020, 12, 25, 9, 0, 0, 0, time.Local),
want: true},
{name: "start == stopで、stop < nowならfalse",
term: Term{Time(9 * 60 * 60), Time(9 * 60 * 60)},
now: time.Date(2020, 12, 25, 9, 0, 1, 0, time.Local),
want: false},
{name: "start < stopで、now < startならfalse",
term: Term{Time(9 * 60 * 60), Time(11*60*60 + 30*60)},
now: time.Date(2020, 12, 25, 8, 59, 59, 0, time.Local),
want: false},
{name: "start < stopで、now == startならtrue",
term: Term{Time(9 * 60 * 60), Time(11*60*60 + 30*60)},
now: time.Date(2020, 12, 25, 9, 0, 0, 0, time.Local),
want: true},
{name: "start < stopで、start < now < stopならtrue",
term: Term{Time(9 * 60 * 60), Time(11*60*60 + 30*60)},
now: time.Date(2020, 12, 25, 10, 15, 0, 0, time.Local),
want: true},
{name: "start < stopで、now == stopならtrue",
term: Term{Time(9 * 60 * 60), Time(11*60*60 + 30*60)},
now: time.Date(2020, 12, 25, 11, 30, 0, 0, time.Local),
want: true},
{name: "start < stopで、stop < nowならfalse",
term: Term{Time(9 * 60 * 60), Time(11*60*60 + 30*60)},
now: time.Date(2020, 12, 25, 11, 30, 1, 0, time.Local),
want: false},
{name: "stop < startで、stop < now < startならfalse",
term: Term{Time(16*60*60 + 30*60), Time(5*60*60 + 24*60 + 59)},
now: time.Date(2020, 12, 25, 16, 29, 59, 0, time.Local),
want: false},
{name: "stop < startで、now == startならtrue",
term: Term{Time(16*60*60 + 30*60), Time(5*60*60 + 24*60 + 59)},
now: time.Date(2020, 12, 25, 16, 30, 0, 0, time.Local),
want: true},
{name: "stop < startで、start < now < 24:00:00ならtrue",
term: Term{Time(16*60*60 + 30*60), Time(5*60*60 + 24*60 + 59)},
now: time.Date(2020, 12, 25, 23, 59, 59, 0, time.Local),
want: true},
{name: "stop < startで、00:00:00 < now < stopならtrue",
term: Term{Time(16*60*60 + 30*60), Time(5*60*60 + 24*60 + 59)},
now: time.Date(2020, 12, 26, 0, 0, 1, 0, time.Local),
want: true},
{name: "stop < startで、now == stopならtrue",
term: Term{Time(16*60*60 + 30*60), Time(5*60*60 + 24*60 + 59)},
now: time.Date(2020, 12, 26, 5, 24, 59, 0, time.Local),
want: true},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
got := test.term.runnable(test.now)
if !reflect.DeepEqual(test.want, got) {
t.Errorf("%s error\nwant: %+v\ngot: %+v\n", t.Name(), test.want, got)
}
})
}
}
func Test_Term_Equal(t *testing.T) {
t.Parallel()
tests := []struct {
name string
a, b Term
want bool
}{
{name: "startとstopが一致しているならtrue", want: true,
a: Term{Time(9 * 60 * 60), Time(15 * 60 * 60)},
b: Term{Time(9 * 60 * 60), Time(15 * 60 * 60)}},
{name: "startだけが一致しているならfalse", want: false,
a: Term{Time(9 * 60 * 60), Time(15 * 60 * 60)},
b: Term{Time(9 * 60 * 60), Time(11*60*60 + 30*60)}},
{name: "stopだけが一致しているならfalse", want: false,
a: Term{Time(9 * 60 * 60), Time(15 * 60 * 60)},
b: Term{Time(12*60*60 + 30*60), Time(15 * 60 * 60)}},
{name: "両方一致していないならfalse", want: false,
a: Term{Time(9 * 60 * 60), Time(11*60*60 + 30*60)},
b: Term{Time(12*60*60 + 30*60), Time(15 * 60 * 60)}},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
got := test.a.Equal(test.b)
if !reflect.DeepEqual(test.want, got) {
t.Errorf("%s error\nwant: %+v\ngot: %+v\n", t.Name(), test.want, got)
}
})
}
}
func Test_Term_In(t *testing.T) {
t.Parallel()
tests := []struct {
name string
term Term
time Time
want bool
}{
{name: "start == stopでtime < startならfalse", want: false,
term: Term{Time(8 * 60 * 60), Time(8 * 60 * 60)},
time: Time(7*60*60 + 59*60 + 59)},
{name: "start == stopでstart == time == stopならtrue", want: true,
term: Term{Time(8 * 60 * 60), Time(8 * 60 * 60)},
time: Time(8 * 60 * 60)},
{name: "start == stopでstop < timeならfalse", want: false,
term: Term{Time(8 * 60 * 60), Time(8 * 60 * 60)},
time: Time(8*60*60 + 1)},
{name: "start < stopでtime < stopならfalse", want: false,
term: Term{Time(8*60*60 + 45*60), Time(15*60*60 + 15*60)},
time: Time(8*60*60 + 44*60 + 59)},
{name: "start < stopでstart == timeならtrue", want: true,
term: Term{Time(8*60*60 + 45*60), Time(15*60*60 + 15*60)},
time: Time(8*60*60 + 45*60)},
{name: "start < stopでstart < time < stopならtrue", want: true,
term: Term{Time(8*60*60 + 45*60), Time(15*60*60 + 15*60)},
time: Time(9 * 60 * 60)},
{name: "start < stopでstop == timeならtrue", want: true,
term: Term{Time(8*60*60 + 45*60), Time(15*60*60 + 15*60)},
time: Time(15*60*60 + 15*60)},
{name: "start < stopでstop < timeならfalse", want: false,
term: Term{Time(8*60*60 + 45*60), Time(15*60*60 + 15*60)},
time: Time(15*60*60 + 15*60 + 1)},
{name: "stop < startでstop < time < startならfalse", want: false,
term: Term{Time(16*60*60 + 30*60), Time(5*60*60 + 30*60)},
time: Time(16*60*60 + 29*60 + 59)},
{name: "stop < startでstart == timeならtrue", want: true,
term: Term{Time(16*60*60 + 30*60), Time(5*60*60 + 30*60)},
time: Time(16*60*60 + 30*60)},
{name: "stop < startでstart < timeならtrue", want: true,
term: Term{Time(16*60*60 + 30*60), Time(5*60*60 + 30*60)},
time: Time(23*60*60 + 59*60 + 59)},
{name: "stop < startでtime < stopならtrue", want: true,
term: Term{Time(16*60*60 + 30*60), Time(5*60*60 + 30*60)},
time: Time(0)},
{name: "stop < startでstop == timeならtrue", want: true,
term: Term{Time(16*60*60 + 30*60), Time(5*60*60 + 30*60)},
time: Time(5*60*60 + 30*60)},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
got := test.term.In(test.time)
if !reflect.DeepEqual(test.want, got) {
t.Errorf("%s error\nwant: %+v\ngot: %+v\n", t.Name(), test.want, got)
}
})
}
}
func Test_NewTerm(t *testing.T) {
t.Parallel()
start := NewTime(12, 30, 0)
stop := NewTime(15, 0, 0)
want := Term{start: start, stop: stop}
got := NewTerm(start, stop)
if !reflect.DeepEqual(want, got) {
t.Errorf("%s error\nwant: %+v\ngot: %+v\n", t.Name(), want, got)
}
}
func Test_Term_runnableSecond(t *testing.T) {
t.Parallel()
tests := []struct {
name string
term Term
want int
}{
{name: "00:00:00, 00:00:00は1", term: NewTerm(NewTime(0, 0, 0), NewTime(0, 0, 0)), want: 1},
{name: "00:00:00, 00:00:01は2", term: NewTerm(NewTime(0, 0, 0), NewTime(0, 0, 1)), want: 2},
{name: "00:00:00, 00:00:59は60", term: NewTerm(NewTime(0, 0, 0), NewTime(0, 0, 59)), want: 60},
{name: "00:00:00, 00:01:00は61", term: NewTerm(NewTime(0, 0, 0), NewTime(0, 1, 0)), want: 61},
{name: "00:00:00, 00:59:59は3600", term: NewTerm(NewTime(0, 0, 0), NewTime(0, 59, 59)), want: 3600},
{name: "00:00:00, 01:00:00は3601", term: NewTerm(NewTime(0, 0, 0), NewTime(1, 0, 0)), want: 3601},
{name: "00:00:00, 23:59:59は86400", term: NewTerm(NewTime(0, 0, 0), NewTime(23, 59, 59)), want: 24 * 60 * 60},
{name: "00:00:01, 00:00:00は86400", term: NewTerm(NewTime(0, 0, 1), NewTime(0, 0, 0)), want: 24 * 60 * 60},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
got := test.term.runnableSecond()
if !reflect.DeepEqual(test.want, got) {
t.Errorf("%s error\nwant: %+v\ngot: %+v\n", t.Name(), test.want, got)
}
})
}
}
<file_sep>package gotimer
import (
"reflect"
"testing"
)
func Test_Time_hour(t *testing.T) {
t.Parallel()
tests := []struct {
name string
time Time
want int
}{
{name: "00:00:00なら0", time: NewTime(0, 0, 0), want: 0},
{name: "23:59:59なら23", time: NewTime(23, 59, 59), want: 23},
{name: "12:24:48は12", time: NewTime(12, 24, 48), want: 12},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
got := test.time.hour()
if !reflect.DeepEqual(test.want, got) {
t.Errorf("%s error\nwant: %+v\ngot: %+v\n", t.Name(), test.want, got)
}
})
}
}
func Test_Time_minute(t *testing.T) {
t.Parallel()
tests := []struct {
name string
time Time
want int
}{
{name: "00:00:00は0", time: NewTime(0, 0, 0), want: 0},
{name: "23:59:59は59", time: NewTime(23, 59, 59), want: 59},
{name: "12:24:48は24", time: NewTime(12, 24, 48), want: 24},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
got := test.time.minute()
if !reflect.DeepEqual(test.want, got) {
t.Errorf("%s error\nwant: %+v\ngot: %+v\n", t.Name(), test.want, got)
}
})
}
}
func Test_Time_second(t *testing.T) {
t.Parallel()
tests := []struct {
name string
time Time
want int
}{
{name: "00:00:00は0", time: NewTime(0, 0, 0), want: 0},
{name: "23:59:59は59", time: NewTime(23, 59, 59), want: 59},
{name: "12:24:48は48", time: NewTime(12, 24, 48), want: 48},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
got := test.time.second()
if !reflect.DeepEqual(test.want, got) {
t.Errorf("%s error\nwant: %+v\ngot: %+v\n", t.Name(), test.want, got)
}
})
}
}
func Test_NewTime(t *testing.T) {
t.Parallel()
tests := []struct {
name string
hour, minute, second int
want Time
}{
{name: "00:00:00 => 0, 0, 0", hour: 0, minute: 0, second: 0, want: Time(0)},
{name: "23:59:59 => 23, 59, 59", hour: 23, minute: 59, second: 59, want: Time(23*60*60 + 59*60 + 59)},
{name: "-24:00:00 => 0, 0, 0", hour: -24, minute: 0, second: 0, want: Time(0)},
{name: "-01:00:00 => 23, 0, 0", hour: -1, minute: 0, second: 0, want: Time(23 * 60 * 60)},
{name: "00:-01:00 => 23, 59, 0", hour: 0, minute: -1, second: 0, want: Time(23*60*60 + 59*60)},
{name: "00:00:-01 => 23, 59, 59", hour: 0, minute: 0, second: -1, want: Time(23*60*60 + 59*60 + 59)},
{name: "00:00:-61 => 23, 58, 59", hour: 0, minute: 0, second: -61, want: Time(23*60*60 + 58*60 + 59)},
{name: "00:00:-86400 => 0, 0, 0", hour: 0, minute: 0, second: -86400, want: Time(0)},
{name: "00:00:-86401 => 23, 59, 59", hour: 0, minute: 0, second: -86401, want: Time(23*60*60 + 59*60 + 59)},
{name: "24:59:-86401 => 23, 59, 59", hour: 24, minute: 59, second: -86401, want: Time(58*60 + 59)},
{name: "24:60:60 => 1, 1, 0", hour: 24, minute: 60, second: 60, want: Time(1*60*60 + 1*60)},
{name: "24:00:00 => 0, 0, 0", hour: 24, minute: 0, second: 0, want: Time(0)},
{name: "00:60:00 => 1, 0, 0", hour: 0, minute: 60, second: 0, want: Time(1 * 60 * 60)},
{name: "00:00:60 => 0, 1, 0", hour: 0, minute: 0, second: 60, want: Time(1 * 60)},
{name: "23:59:60 => 0, 0, 0", hour: 23, minute: 59, second: 60, want: Time(0)},
{name: "24:00:-01 => 23, 59, 59", hour: 24, minute: 0, second: -1, want: Time(23*60*60 + 59*60 + 59)},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
got := NewTime(test.hour, test.minute, test.second)
if !reflect.DeepEqual(test.want, got) {
t.Errorf("%s error\nwant: %+v\ngot: %+v\n", t.Name(), test.want, got)
}
})
}
}
| d0aafa4972eccd8db6b0fcbf26c96e6d005170fa | [
"Markdown",
"Go Module",
"Go"
] | 8 | Go | tsuchinaga/gotimer | db7034abbb37f6a42fac9914ac484614e64b9a20 | 31edec1e2c1aace82aa7ddf521684736dd725997 | |
refs/heads/master | <repo_name>sergw/apps<file_sep>/TODO.md
## [TODO](TODO.md)
* Add sublime plugins
* Add gems
* Add pips
<file_sep>/prepare-reinstall-os.md
# Подготовка системы к переустановке или апгрейду
1. Найти все git-репозитории
`find . -type d -name .git | sed '/dotfiles\/\.vim\/bundle/d; /\.cache\/mm-interfaces/d'`
2. TODO Проверить их статусы, Закомиттить, запушистить и перепроверить
10. save favorites of all browsers
11. **safari**: (`Cmd-?`, `'export bookmarks'`, `⏎`)
12. firefox: (`Cmd-?`, `'all bookmarks'`, `backup`) [{screenshot}](https://yadi.sk/i/pHVE4pVAnBYAm)
13. chrome, chromium, yabro
14. save tabs of all browsers
15. сохранить настройки webstorm, iterm и др. (как?)
100. посохранять ~~тысячи~~ файлы в sublime.
999. убедиться что разные облачные хранилища просинкались (у меня: яндекс.диск, icloud notes, reminders, calendar, evernote)
100500. _TBD_
<file_sep>/brew.list.generator.sh
#!/bin/sh
brew list > brew.list
<file_sep>/prepare-installed-os.md
# Полная настройка чистой OS X
1. настроил монитор: мельче [{скрин}](https://yadi.sk/i/TmxHJLifj2ppW)
2. настроил язык интерфейса: англ [{скрин}](https://yadi.sk/i/WhMZXFNYj2ptT)
3. настроил часовой пояс [{скрин}](https://yadi.sk/i/NlCrpsQaj2q5J)
5. поставил некоторые плагины к sublime: **TODO**: добавить ссылки на файлы в репо
6. настроил клик по тапу[{скрин}](https://yadi.sk/i/diC3OvNCj36nM)
7. убрал иконки в меню-баре: alfred, spectacle, timem-machine, [spotlight](http://bit.ly/1OhUkeC)
(`sudo chmod 600 /System/Library/CoreServices/Search.bundle/Contents/MacOS/Search && killall SystemUIServer`)
* ["отключил" так же хоткей spotlight](https://yadi.sk/i/AcdJEyzNj36xN), и поставил хоткей alfred (замена spotlight): `Alt-Space`
* включил отображение даты и процента заряда
* настроил alfred (подробнее о настройках [см. ниже](https://nda.ya.ru/3Qxmhz))
8. java для локальных тестов и webstorm
8. поставил java8 [по инструкции](https://nda.ya.ru/3QxPTe)
9. поставил java6 для webstorm [по адресу](https://support.apple.com/kb/DL1572?viewlocale=en_US&locale=en_US)
9. выключил корректировку набора и корректировку кавычек [{скрин}](https://yadi.sk/i/RCTKs9FJj37Ei)
10. выставил достижимость табом всех контролов [{скрин}](https://yadi.sk/i/IAioGJ_9j37iA)
11. настроил быстрое повторение зажатой клавиши [{скрин}](https://yadi.sk/i/B7MmIA7Hj37ix)
12. настроил сохранение открытых окон приложений (чтобы сохранялась сессия в iterm) [{скрин}](https://yadi.sk/i/wUncDXJkqzLzU)
14. активировал лицензию webstorm. [см. подробнее](https://nda.ya.ru/3QxXtH)
15. восстановить прежние настройки webstorm (как?)
15. поменял действие fn на противоположное [{инструкция}](http://bit.ly/1NkgP1q)
16. Тачпад
1. включил жест app expose
2. настроил жест (hot corner right-bottom) включения заставки (чтобы быстро "блокировать" компьютер)
23. [отключил](http://bit.ly/1JZy7Ph) `^↑` `^↓`, чтобы не было конфликта с sublime
17. залогинелся с apple id **по памяти**
18. установил некоторые ранее установленные приложения из app store (вкладка "купленные", понажимать [install])
19. убрал dashboard по [инструкции](http://bit.ly/1JZgoYi)
20. установил brew: http://brew.sh
21. установил brew cask: http://caskroom.io: `brew install caskroom/cask/brew-cask`
22. подключил расширенный каталог (с бетами и пр.) для brew cask: `brew tap caskroom/versions`
29. Накатил все прежние brew, brew cask, npm пакеты. [См. репо, для повторения](https://github.com/a-x-/apps)
30. поставил tunnelblick (см. подробнее ниже)
24. установил Command Line Tools `xcode-select --install`
26. поставил yandex.disk с сайта, залогинелся **по памяти** (в brew cask его [не добавить](//st/DISCSW-5623/))
40. Добавил хоткей для получения ссылки на файл в Яндекс.диске: `Cmd-Alt-Shift-=` [{Скрин}](https://yadi.sk/i/0a0Sxxk6j37GA)
26. подменил keychain на прежний из бэкапа, ура, теперь все пароли вновь со мной (/Users/invntrm/Library/Keychains)
28. Сделал параметры (настройки, список плагинов, хоткеи) sublime линками из yadisk
29. `ln /Users/invntrm/Library/Application\ Support/Sublime\ Text\ 3/Packages/User/Default\ \(OSX\).sublime-keymap ~/Cloud/Настрои<0306>ки/sublime-hokkeys.json`
30. `ln /Users/invntrm/Library/Application\ Support/Sublime\ Text\ 3/Packages/User/Preferences.sublime-settings ~/Cloud/Настрои<0306>ки/sublime-setings.json`
31. `ln /Users/invntrm/Library/Application\ Support/Sublime\ Text\ 3/Packages/User/Package\ Control.sublime-settings ~/Cloud/Настрои<0306>ки/sublime-packages.json`
32. импортировал закладки в safari и firefox
34. включил отображение даты в "часах".
35. Настроил finder:
1. убрал all my files, добавил: pics, music, home
2. убрал предупреждение о смене расширений
3. поменял поиск по-умолчанию на текущую директорию
4. поменял директорию по умолчанию на `~`
41. поставил дотфайлы (см. подробнее ниже)
42. настроил mail.app
43. подключил аккаунт (см. подробнее ниже)
44. настроил кнопки: убрал кнопку получить письма (`Cmd-Shift-N`), добавил кнопки: "архивировать" (`^Cmd-A`), "прочитано (нет хоткея)/не прочитано (`Cmd-Shift-U`)"
43. Настроил проброс ключей (см. подробнее ниже)
44. Настроил календарь (см. подробнее ниже)
45. Настроил firefox
1. Убрал дибильное издевательство над здравым смыслом при вставке в консоль firefox "allow pasting".
[Инструкция](http://lifehacker.com/enable-copy-paste-in-web-pages-that-disallow-it-with-a-1601848114):
47. Go to `about:config`
48. Search for `dom.event.clipboardevents.enabled`
49. Double-click it to change the value to "false"
50. Restart ff
2. Добавил плагин [Copy Link Text](https://addons.mozilla.org/ru/firefox/addon/copy-link-text-4750/) чтобы хоть как-то копировать текст ссылок (очень частый кейс).
46. Настроил Safari
47. Чтобы отлаживать safari на mac, ipad, iphone, включил инструменты разработчика [{Скрин}](https://yadi.sk/i/BoBP-bzmj5n34)
48. Выключить антиалиасинг (General -> [ ] Use LCD Font smoothing)
49. Установить imagemagic с правильным svg: `brew install imagemagick --with-librsvg`
_TBD_
_Далее ещё идёт установка/настройка внутри корпоративных специфичных штуковин. Мой список лежит на внутреннем гитхабе._
<file_sep>/ALTERNATIVES.md
## Alternatives
See also:
* [nerevar/dotfiles/osx](https://github.yandex-team.ru/nerevar/dotfiles/tree/master/osx)
<file_sep>/npm.list.generator.sh
#!/bin/sh
npm -g list -depth 0 | sed '1d' | cut -d ' ' -f 2 | cut -d '@' -f 1 | grep -vE 'npm|install' > npm.list
<file_sep>/ABOUT.md
OS X Apps lists for quick installation and seamless migration
* `name.list.genarator.sh` — producer of ready list
* `name.list.generation.*` — instruction or producet of instruction for generation list manually
* `src-*` — just source list for generators
<file_sep>/README.md.genarator.sh
#!/bin/sh
output=
to_links="| gsed -r 's/(.+)/* [\1](\1)/'"
output+="$(cat ABOUT.md)"
output+="\n\n$(cat <<DOC
## Install all
[./install-all.sh](./install-all.sh)
DOC)"
lists="ls | grep 'list$' | grep -v src"
output+="\n\n## Lists of apps\n\`\`\`sh\n$lists\n\`\`\`\n$(eval $lists $to_links)"
gens="ls | grep gen | grep -v README"
output+="\n\n## Generators of lists\n\`\`\`sh\n$gens\n\`\`\`\n$(eval $gens $to_links)"
output+="\n\n$(cat ALTERNATIVES.md)"
output+="\n\n$(cat TODO.md)"
output+="\n\n----\n_Genarated by \`README.md.genarator.sh\`_"
echo "$output" > README.md
<file_sep>/install-all.sh
#!/bin/sh
# run on os x
< ~/Cloud/apps/brew.list sed -E 's/#.+//' | xargs brew install
< ~/Cloud/apps/npm.list sed -E 's/#.+//' | xargs npm -g install
< ~/Cloud/apps/brew-cask.list sed -E 's/#.+//' | xargs brew cask install
echo "\nСписки brew, npm, brew-cask установлены."
echo "\nЗайдите в appstore во вкладку «купленных» приложений и нажмите установить против каждого необходимого."
<file_sep>/README.md
OS X Apps lists for quick installation and seamless migration
* `name.list.genarator.sh` — producer of ready list
* `name.list.generation.*` — instruction or producet of instruction for generation list manually
* `src-*` — just source list for generators
## Install all
[./install-all.sh](./install-all.sh)
## Lists of apps
```sh
ls | grep 'list$' | grep -v src
```
* [appstore.list](appstore.list)
* [brew-cask.list](brew-cask.list)
* [brew.list](brew.list)
* [npm.list](npm.list)
* [web.list](web.list)
## Generators of lists
```sh
ls | grep gen | grep -v README
```
* [appstore.list.generation.txt](appstore.list.generation.txt)
* [brew-cask.list.from.web.list.generation.sh](brew-cask.list.from.web.list.generation.sh)
* [brew-cask.list.generator.sh](brew-cask.list.generator.sh)
* [brew.list.generator.sh](brew.list.generator.sh)
* [npm.list.generator.sh](npm.list.generator.sh)
* [src-builtin.list.generation.txt](src-builtin.list.generation.txt)
* [src-installed.list.generator.sh](src-installed.list.generator.sh)
* [web.list.generator.sh](web.list.generator.sh)
## Alternatives
See also:
* [nerevar/dotfiles/osx](https://github.yandex-team.ru/nerevar/dotfiles/tree/master/osx)
## [TODO](TODO.md)
* Add sublime plugins
* Add gems
* Add pips
----
_Genarated by `README.md.genarator.sh`_
| 021af84f92159b9b1068071ae349c572806a9a74 | [
"Markdown",
"Shell"
] | 10 | Markdown | sergw/apps | d2ad9d8ca3dcf2c166806083b4d131fc67943d39 | a438f589cf55f030ad7d245df16972d39892e605 | |
refs/heads/master | <file_sep>//
// Created by adam on 2018-12-14.
//
#include <GL/gl.h>
#include <iostream>
#include "Game.h"
#include <algorithm>
Game::Game(int gridSizeX, int gridSizeY)
{
m_grid = Grid(gridSizeX, gridSizeY);
m_pathfinder = Pathfinder(&m_grid, getRandom(gridSizeX), getRandom(gridSizeY));
createObstacles();
m_playerX = getRandom(gridSizeX);
m_playerY = getRandom(gridSizeY);
}
// draw a square in the grid
void Game::drawSquare(int x, int y)
{
if(!m_grid.getNode(x, y)->isWalkable())
{
// non-walkable square
glColor3f(0,0,1);
glRectd(x, y, x+1, y+1);
}
// grid colour
glColor3f(0.5,0.5,0.5);
glLineWidth(1.0);
glBegin(GL_LINE_LOOP);
glVertex2f(x, y);
glVertex2f(x+1, y);
glVertex2f(x+1, y+1);
glVertex2f(x, y+1);
glEnd();
}
void Game::drawGrid()
{
for(int x = 0; x < m_grid.getSizeX(); x++)
{
for(int y = 0; y < m_grid.getSizeY(); y++)
{
drawSquare(x, y);
}
}
}
void Game::drawSearched()
{
for(Node* node : m_grid.getSearched())
{
glColor3f(0.5, 0, 0.25);
glRectd(node->getX(), node->getY(), node->getX()+1, node->getY()+1);
}
}
void Game::drawPlayer()
{
glColor3f(0, 1, 0);
glRectd(m_playerX, m_playerY, m_playerX+1, m_playerY+1);
}
void Game::move(Game::Direction direction)
{
switch (direction)
{
case Direction::up:
{
if(m_playerY < m_grid.getSizeY()-1 )
m_playerY++;
break;
}
case Direction::down:
{
if(m_playerY > 0)
m_playerY--;
break;
}
case Direction::left:
{
if(m_playerX > 0)
m_playerX--;
break;
}
case Direction::right:
{
if(m_playerX < m_grid.getSizeX()-1)
m_playerX++;
break;
}
}
}
void Game::setWalkable()
{
m_grid.setWalkable(m_playerX, m_playerY);
}
void Game::drawPathfinder()
{
glColor3f(1, 0, 0);
glRectd(m_pathfinder.getX(), m_pathfinder.getY(), m_pathfinder.getX()+1, m_pathfinder.getY()+1);
}
void Game::findPath()
{
m_pathfinder.findPath(m_playerX, m_playerY);
}
void Game::movePathfinder()
{
while(!m_pathfinder.getPath().empty())
{
m_grid.addNodeToPath(m_grid.getNode(m_pathfinder.getX(), m_pathfinder.getY()));
m_pathfinder.move();
}
}
void Game::drawPath()
{
for(Node *node : m_grid.getPath())
{
glColor3f(1, 0, 1);
glRectd(node->getX(), node->getY(), node->getX()+1, node->getY()+1);
}
}
void Game::reset()
{
m_grid.reset();
m_grid.clearSearched();
m_playerX = getRandom(m_grid.getSizeX());
m_playerY = getRandom(m_grid.getSizeY());
createObstacles();
m_pathfinder.setPosition(getRandom(m_grid.getSizeX()), getRandom(m_grid.getSizeY()));
m_pathfinder.setTarget(-1, -1);
}
// see if target has moved and path needs to be recalculated
bool Game::targetHasMoved()
{
return m_playerX != m_pathfinder.getTargetX() || m_playerY != m_pathfinder.getTargetY();
}
// creates some randomised non-walkable squares on the grid
void Game::createObstacles()
{
for(int i = 0; i < m_grid.getSizeX()*m_grid.getSizeY()/3; i++)
{
int y = getRandom(m_grid.getSizeY());
int x = getRandom(m_grid.getSizeX());
if(m_playerX != x && m_playerY != y)
{
m_grid.setWalkable(x, y);
}
}
}
int Game::getRandom(int max)
{
return rand() % max;
}
<file_sep>cmake_minimum_required(VERSION 3.10)
project(Projekt)
set(CMAKE_CXX_STANDARD 14)
add_executable(Projekt main.cpp Game.cpp Game.h Node.cpp Node.h Grid.cpp Grid.h Pathfinder.cpp Pathfinder.h)
find_package(OpenGL REQUIRED)
find_package(GLUT REQUIRED)
include_directories( ${OPENGL_INCLUDE_DIRS} ${GLUT_INCLUDE_DIRS} )
target_link_libraries(Projekt ${OPENGL_LIBRARIES} ${GLUT_LIBRARY} )
<file_sep>//
// Created by adam on 2018-12-16.
//
#include "Grid.h"
#include <cstdlib>
#include <iostream>
Grid::Grid(int sizeX, int sizeY)
{
m_sizeX = sizeX;
m_sizeY = sizeY;
m_nodes.resize(sizeX);
for(int i = 0; i < sizeX; i++)
{
m_nodes[i].resize(sizeY);
}
for(int x = 0; x < sizeX; x++)
{
for(int y = 0; y < sizeY; y++)
{
Node newNode = Node(x,y);
m_nodes[x][y] = newNode;
}
}
}
int Grid::getSizeX() const
{
return m_sizeX;
}
int Grid::getSizeY() const
{
return m_sizeY;
}
Node* Grid::getNode(int x, int y) {
return &m_nodes[x][y];
}
// toggles walkable/unwalkable
void Grid::setWalkable(int x, int y)
{
m_nodes[x][y].setWalkable(!m_nodes[x][y].isWalkable());
}
// find all of a nodes neighbours and return them in a vector
std::vector<Node*> Grid::getNodeNeighbours(Node *node)
{
std::vector<Node*> neighbours;
for(int x = -1; x <= 1; x++)
{
for(int y = -1; y <= 1; y++)
{
if(x == 0 && y == 0)
{
continue;
}
if(node->getX()+x >= 0 && node->getX()+x <= m_sizeX-1 &&
node->getY()+y >= 0 && node->getY()+y <= m_sizeY-1)
{
neighbours.push_back(&m_nodes[node->getX()+x][node->getY()+y]);
}
}
}
return neighbours;
}
int Grid::getDistance(Node *from, Node *to)
{
// Lowest number of x or y steps will give how many diagonal moves is needed to be in line with the target
// the higher number minus the lower number will give the remaining steps needed to reach the target node
// vertical/horizontal step is 10 units
// diagonal step is 14 units. (square root of two steps)
// so the distance equation will be 14y + 10(x-y) or 14x + 10(y-x)
int xDistance = abs(from->getX() - to->getX());
int yDistance = abs(from->getY() - to->getY());
if(xDistance > yDistance)
{
return 14*yDistance + 10 * (xDistance - yDistance);
}
return 14*xDistance + 10 * (yDistance - xDistance);
}
void Grid::addNodeToPath(Node * node)
{
m_path.push_back(node);
}
std::vector<Node *> Grid::getPath()
{
return m_path;
}
void Grid::resetPath()
{
m_path.clear();
}
void Grid::reset()
{
resetPath();
for(auto& row : m_nodes)
{
for(auto& node : row)
{
node.setWalkable(true);
}
}
}
void Grid::setSearched(Node *node)
{
m_searched.push_back(node);
}
std::vector<Node *> Grid::getSearched() const {
return m_searched;
}
void Grid::clearSearched()
{
m_searched.clear();
}
<file_sep>//
// Created by adam on 2018-12-16.
//
#ifndef PROJEKT_PATHFINDER_H
#define PROJEKT_PATHFINDER_H
#include <stack>
#include "Grid.h"
// Handles the pathfinding
class Pathfinder
{
Grid *m_grid;
int m_x, m_y, m_targetX, m_targetY;
std::stack<Node*> m_path;
public:
Pathfinder() = default;
Pathfinder(Grid *grid, int x, int y);
void findPath(int targetX, int targetY);
void retrace(Node *start, Node *end);
int getX() const {return m_x;}
int getY() const {return m_y;}
void setPosition(int x, int y);
void setTarget(int x, int y);
int getTargetX() const{return m_targetX;};
int getTargetY() const{return m_targetY;};
void move();
std::stack<Node*> getPath() const;
};
#endif //PROJEKT_PATHFINDER_H
<file_sep>//
// Created by adam on 2018-12-16.
//
#include <iostream>
#include "Node.h"
// The node class represents a square in the grid
Node::Node(int x, int y)
{
m_x = x;
m_y = y;
m_walkable = true;
m_gCost = 0;
m_hCost = 0;
m_parent = nullptr;
}
void Node::setWalkable(bool walkable) {m_walkable = walkable;}
int Node::getX() const {return m_x;}
int Node::getY() const {return m_y;}
bool Node::isWalkable() const {return m_walkable;}
int Node::getFCost() const
{
return m_gCost + m_hCost;
}
int Node::getGCost() const
{
return m_gCost;
}
int Node::getHCost() const
{
return m_hCost;
}
// compares nodes by coordinates
bool Node::operator==(const Node &n) const
{
return (this->m_x == n.m_x && this->m_y == n.m_y);
}
void Node::setGCost(int cost)
{
m_gCost = cost;
}
void Node::setHCost(int cost)
{
m_hCost = cost;
}
void Node::setParent(Node *parent)
{
m_parent = parent;
}
Node *Node::getParent() {
return m_parent;
}
// Compares a node by f cost, if f costs are the same h costs are used
bool Node::operator<(const Node &n) const
{
if(this->getFCost() < n.getFCost())
{
return true;
}
else if(this->getFCost() == n.getFCost() && this->m_hCost < n.m_hCost)
{
return true;
}
return false;
}
<file_sep>//
// Created by adam on 2018-12-16.
//
#ifndef PROJEKT_SQUARE_H
#define PROJEKT_SQUARE_H
// represents a square in the game grid
class Node
{
int m_x;
int m_y;
Node *m_parent;
bool m_walkable;
int m_gCost;
int m_hCost;
public:
Node() = default;
Node(int x, int y);
int getX() const;;
int getY() const;;
bool isWalkable() const;
void setWalkable(bool walkable);
int getFCost() const;
int getGCost() const;
int getHCost() const;
void setParent(Node *parent);
void setGCost(int cost);
void setHCost(int cost);
bool operator==(const Node &n) const;
bool operator< (const Node &n) const;
Node *getParent();
};
#endif //PROJEKT_SQUARE_H
<file_sep>//
// Created by adam on 2018-12-16.
//
#ifndef PROJEKT_GRID_H
#define PROJEKT_GRID_H
#include <vector>
#include "Node.h"
class Grid
{
public:
Grid(int sizeX, int sizeY);
Grid() = default;
int getSizeX() const;
int getSizeY() const;
Node* getNode(int x, int y) ;
std::vector<Node*> getNodeNeighbours(Node *node);
void setWalkable(int x, int y);
int getDistance(Node *from, Node *to);
void addNodeToPath(Node* node);
std::vector<Node*> getPath();
void resetPath();
void clearSearched();
void reset();
// marks a square that has been searched by the pathfinder
void setSearched(Node* node);
std::vector<Node*> getSearched() const;
private:
std::vector<std::vector<Node>> m_nodes;
std::vector<Node*> m_path;
// contains the nodes checked by the pathfinder before finding the best path
std::vector<Node*> m_searched;
int m_sizeX, m_sizeY;
};
#endif //PROJEKT_GRID_H
<file_sep>
#include <GL/glut.h>
#include <GL/gl.h>
#include "Game.h"
// Callback functions
void display();
void keyboardSpecial(int key, int, int);
void keyboard(unsigned char c, int x, int y);
void reshape(int w, int h);
void timer(int);
// Grid size
const int gridSizeX = 50;
const int gridSizeY = 50;
const int FPS = 60;
Game g = Game(gridSizeX, gridSizeY);
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowPosition(300, 150);
glutInitWindowSize(1280, 900);
glutCreateWindow("A* Pathfinding");
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutTimerFunc(0, timer, 0);
glutKeyboardFunc(keyboard);
glutSpecialFunc(keyboardSpecial);
glutMainLoop();
return 0;
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
g.drawSearched();
g.drawGrid();
g.drawPath();
g.drawPathfinder();
g.drawPlayer();
glutSwapBuffers();
}
void reshape(int w, int h)
{
glViewport (0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode (GL_PROJECTION);
glLoadIdentity();
glOrtho(-1, gridSizeX+1, -1, gridSizeY+1, -1, 1);
glMatrixMode (GL_MODELVIEW);
}
void timer(int)
{
glutPostRedisplay();
glutTimerFunc(1000/FPS, timer, 0 );
}
void keyboard(unsigned char c, int x, int y)
{
if (c == 27) // esc
{
exit(0);
}
else if(c == 32) // space
{
g.setWalkable();
}
else if(c == 70 || c == 102) // F
{
// calculate new path if needed
if(g.targetHasMoved())
{
g.findPath();
}
g.movePathfinder();
}
else if(c == 82 || c == 114) // R
{
g.reset();
}
}
void keyboardSpecial(int key, int, int)
{
switch(key)
{
case GLUT_KEY_UP:
{
g.move(Game::Direction::up);
break;
}
case GLUT_KEY_DOWN:
{
g.move(Game::Direction::down);
break;
}
case GLUT_KEY_LEFT:
{
g.move(Game::Direction::left);
break;
}
case GLUT_KEY_RIGHT:
{
g.move(Game::Direction::right);
break;
}
}
}
<file_sep>//
// Created by adam on 2018-12-14.
//
#ifndef PROJEKT_GAME_H
#define PROJEKT_GAME_H
#include "Grid.h"
#include "Pathfinder.h"
class Game
{
public:
enum Direction{ up, down, left, right};
Game(int gridSizeX, int gridSizeY);
void drawGrid();
void drawSquare(int x, int y);
void drawPlayer();
void move(Direction direction);
void setWalkable();
void findPath();
void drawPathfinder();
void drawPath();
Grid *getGrid();
void drawSearched();
void movePathfinder();
void reset();
void createObstacles();
bool targetHasMoved();
int getRandom(int max);
private:
int m_playerX, m_playerY;
Pathfinder m_pathfinder;
Grid m_grid;
};
#endif //PROJEKT_GAME_H
<file_sep>//
// Created by adam on 2018-12-16.
//
#include "Pathfinder.h"
#include <algorithm>
#include <unordered_set>
#include <iostream>
Pathfinder::Pathfinder(Grid *grid, int x, int y) : m_grid(grid), m_x(x), m_y(y)
{
m_targetX = -1;
m_targetY = -1;
}
// uses the a* algorithm to find the closest path between two nodes
void Pathfinder::findPath(int targetX, int targetY)
{
m_targetX = targetX;
m_targetY = targetY;
Node *startNode = m_grid->getNode(m_x, m_y);
Node *targetNode = m_grid->getNode(targetX, targetY);
std::vector<Node*> openList;
std::vector<Node*> closedList;
// add start node to the open list
openList.push_back(startNode);
while(!openList.empty())
{
// find the node with the lowest f cost and make it the current node
Node *currentNode;
for(int i = 0; i < openList.size(); i++)
{
// sort vector by lowest first
std::sort(openList.begin(), openList.end(), [ ]( const auto& lhs, const auto& rhs )
{
return lhs->getFCost() < rhs-> getFCost();
});
currentNode = openList.front();
// remove the node with the lowest f cost from open and add to the closed list
openList.erase(openList.begin());
closedList.push_back(currentNode);
// target found retrace the path
if(currentNode == targetNode)
{
retrace(startNode, targetNode);
return;
}
std::vector<Node*> neighbours = m_grid->getNodeNeighbours(currentNode);
// check neighbours
for(Node *neighbour : neighbours)
{
// skip if neighbour is not walkable or in the closed list
if(!neighbour->isWalkable() ||
std::find(closedList.begin(), closedList.end(), neighbour) != closedList.end() )
{
continue;
}
int newCost = currentNode->getGCost() + m_grid->getDistance(currentNode, neighbour);
// if neighbour not in open set
if(std::find(openList.begin(), openList.end(), neighbour) == openList.end())
{
// add to open list
openList.push_back(neighbour);
// mark as searched by the pathfinder
m_grid->setSearched(neighbour);
// set f cost
neighbour->setGCost(newCost);
// set h cost
neighbour->setHCost(m_grid->getDistance(neighbour, targetNode ));
// set parent of neighbour to current
neighbour->setParent(currentNode);
}
// if neighbour is in the open list
else if(std::find(openList.begin(), openList.end(), neighbour) != openList.end())
{
// check if the new path is better
if(newCost < neighbour->getGCost())
{
// set parent
neighbour->setParent(currentNode);
// set f cost
neighbour->setGCost(newCost);
// set h cost
neighbour->setHCost(m_grid->getDistance(neighbour, targetNode ));
}
}
}
}
}
}
// starting from the end node, retrace the path by going through each node's parent and adding them to a stack
void Pathfinder::retrace(Node *start, Node *end)
{
while(!m_path.empty())
{
m_path.pop();
}
Node *currentNode = end;
while(currentNode != start)
{
m_path.push(currentNode);
currentNode = currentNode->getParent();
}
}
void Pathfinder::move()
{
if(!m_path.empty())
{
Node *node = m_path.top();
m_x = node->getX();
m_y = node->getY();
m_path.pop();
}
}
void Pathfinder::setPosition(int x, int y)
{
m_x = x;
m_y = y;
}
void Pathfinder::setTarget(int x, int y)
{
m_targetX = x;
m_targetY = y;
}
std::stack<Node *> Pathfinder::getPath() const
{
return m_path;
}
bool sortByFCost(const Node &lhs, Node &rhs)
{
if(lhs.getFCost() < rhs.getFCost())
{
return true;
}
else if(lhs.getFCost() == rhs.getFCost() && lhs.getHCost() < rhs.getHCost())
{
return true;
}
return false;
}
| 12b5586d0ea169e10fed78aad0f7ec3a6bf8b0ce | [
"CMake",
"C++"
] | 10 | C++ | adagun/pathfinder | 5e3942bebb473b42e41fd1387b934adbc83b0e48 | 894294da92a5ad795696efbdf476bb13b8bac5b2 | |
refs/heads/master | <file_sep>package me.lb.service.system.impl;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import me.lb.model.system.Perm;
import me.lb.model.system.Role;
import me.lb.service.common.impl.GenericServiceImpl;
import me.lb.service.system.RoleService;
import org.springframework.stereotype.Service;
@Service
public class RoleServiceImpl extends GenericServiceImpl<Role, Integer>
implements RoleService {
@Override
public void auth(int roleId, List<Integer> permIds) {
// 由于cascade方式只级联删除操作,所以这里可以通过欺骗的方式提升效率
Set<Perm> perms = new HashSet<Perm>();
for (int permId : permIds) {
// 这里只要构建数据库中存在id的对象即可,避免了查询的开销
Perm perm = new Perm();
perm.setId(permId);
perms.add(perm);
}
// 查询角色信息,更新关联(直接更新)
Role role = dao.findById(roleId);
role.setPerms(perms);
dao.update(role);
}
}<file_sep>package me.lb.dao.system;
import me.lb.dao.common.GenericDao;
import me.lb.model.system.User;
public interface UserDao extends GenericDao<User, Integer> {
}<file_sep>package me.lb.dao.system;
import me.lb.dao.common.GenericDao;
import me.lb.model.system.Role;
public interface RoleDao extends GenericDao<Role, Integer> {
}<file_sep>package me.lb.service.system;
import java.util.List;
import me.lb.model.system.Perm;
import me.lb.service.common.GenericService;
public interface PermService extends GenericService<Perm, Integer> {
/**
* 查询全部的顶级资源(没有父id)
*/
public List<Perm> findTopPerms();
}<file_sep>package me.lb.dao.common;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import me.lb.dao.common.impl.GenericDaoImpl;
import me.lb.model.pagination.Pagination;
import me.lb.model.system.User;
import org.springframework.stereotype.Repository;
@Repository
public class CommonDaoImpl extends GenericDaoImpl<User, Integer> implements
CommonDao {
@Override
public Pagination<User> pagingQuery() {
return getPagination("from User", null);
}
@Override
public Pagination<User> pagingQuery(Map<String, Object> params) {
StringBuffer sb = new StringBuffer("from User as o where 1=1");
List<Object> objs = new ArrayList<Object>();
Iterator<Map.Entry<String, Object>> it = params.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Object> me = it.next();
// 需要额外处理模糊查询的参数
// if ("orLogic".equals(me.getKey())) {
// sb.append(" or o." + me.getKey() + " like ?");
// objs.add("%" + me.getValue() + "%");
// } else {
sb.append(" and o." + me.getKey() + " = ?");
objs.add(me.getValue());
// }
}
return getPagination(sb.toString(), objs);
}
}<file_sep>package me.lb.dao.system;
import java.util.List;
import me.lb.dao.common.GenericDao;
import me.lb.model.system.Perm;
public interface PermDao extends GenericDao<Perm, Integer> {
/**
* 查询全部的顶级资源(没有父id)
*/
public List<Perm> findTopPerms();
}<file_sep>package me.lb.service.system.impl;
import java.util.List;
import me.lb.dao.system.PermDao;
import me.lb.model.system.Perm;
import me.lb.service.common.impl.GenericServiceImpl;
import me.lb.service.system.PermService;
import org.springframework.stereotype.Service;
@Service
public class PermServiceImpl extends GenericServiceImpl<Perm, Integer>
implements PermService {
@Override
public List<Perm> findTopPerms() {
return ((PermDao) dao).findTopPerms();
}
} | 3a33966b73390d1e4502104dd45009cc5d701a5e | [
"Java"
] | 7 | Java | Charlemin/platform-ng-master | fa5c4639e2ed5a3122b0f5643388159f4e58c9fd | f403c2ce2faa1b69b94b4c876b3b0bfc460052fb | |
refs/heads/main | <file_sep>{% extends 'layouts/main.html' %}
{% block title %}MyFridge{% endblock %}
{% block content %}
<div class="row">
<div class="col-sm-6">
<h1>MyFridge</h1>
<p class="lead">Eat Clean. Clean Earth</p>
<h3>
<a href="/recipes"><button class="btn btn-primary btn-lg">Find a Recipe</button></a>
</h3>
<h3>
<a href="/users"><button class="btn btn-primary btn-lg">Find a User</button></a>
<a href="/users/create"><button class="btn btn-default btn-lg">Add a User</button></a>
</h3>
<h3>
<a href="/products"><button class="btn btn-primary btn-lg">Find a product</button></a>
<a href="/products/create"><button class="btn btn-default btn-lg">Add a product</button></a>
</h3>
</div>
<div class="col-sm-6 hidden-sm hidden-xs">
<img id="front-splash" src="{{ url_for('static',filename='img/myfridge-splash.png') }}" alt="Front Photo of Productive App" />
</div>
<form class="form-upload" method=post enctype=multipart/form-data>
<h1 class="h3 mb-3 font-weight-normal">Please Upload</h1>
<input type="file" id="image" name=image class="form-control" required autofocus>
<button class="btn btn-lg btn-primary btn-block" type="submit">Add Receipt</button>
<br>
{% if image_loc %}
<img class="mb-4" src="static/{{ image_name }}" alt="" width="256" height="256">
<h3 class="h3 mb-3 font-weight-normal">Prediction: {{Prediction}}</h3>
{% endif %}
</form>
</div>
{% endblock %}<file_sep>import os
from sqlalchemy import Column, String, Integer, DateTime, ForeignKey, \
Table, create_engine
from flask_sqlalchemy import SQLAlchemy
import json
from flask_migrate import Migrate
database_name = "myfridge"
database_path = "postgresql://{}/{}".format('localhost:5432', database_name)
db = SQLAlchemy()
migrate = Migrate()
'''
setup_db(app)
binds a flask application and a SQLAlchemy service
'''
def setup_db(app, database_path=database_path):
app.config["SQLALCHEMY_DATABASE_URI"] = database_path
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db.app = app
db.init_app(app)
migrate.init_app(app, db)
db.create_all()
"""
db_drop_and_create_all()
drops the database tables and starts fresh
can be used to initialize a clean database
Keyword arguments: n/a
argument -- n/a
Return: return_description
"""
def db_drop_and_create_all():
db.drop_all()
db.create_all()
'''
User-Product association table
'''
user_products = Table('user_products', db.Model.metadata,
Column('user_id', Integer, ForeignKey('users.id',
onupdate='CASCADE', ondelete='CASCADE'), primary_key=True),
Column('product_id', Integer, ForeignKey('products.id',
onupdate='CASCADE', ondelete='CASCADE'), primary_key=True))
'''
User
'''
class User(db.Model):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
first_name = Column(String, nullable=False)
last_name = Column(String, nullable=False)
age = Column(Integer)
products = db.relationship('Product', secondary='user_products',
backref=db.backref('users', lazy=True))
current_products = Column(String)
past_products = Column(String)
date_registered = Column(DateTime)
def __init__(self, first_name, last_name, age):
self.first_name = first_name
self.last_name = last_name
self.age = age
self.current_products={}
self.past_products={}
def insert(self):
db.session.add(self)
db.session.commit()
def update(self):
db.session.commit()
def delete(self):
db.session.delete(self)
db.session.commit()
def format(self):
return {
'id': self.id,
'first_name': self.first_name,
'last_name': self.last_name,
'current_products': self.current_products,
'past_products': self.past_products,
'date_registered': self.date_registered
}
def __repr__(self):
return f'<User {self.id}: {self.last_name}, {self.first_name}>'
'''
Product
'''
class Product(db.Model):
__tablename__ = 'products'
id = Column(Integer, primary_key=True)
name = Column(String)
weight = Column(String)
quantity = Column(String)
date_purchased = Column(Integer)
image_link = Column(String)
def __init__(self, name, weight, quantity, date_purchased, description=''):
self.name = name
self.description = description
self.weight = weight
self.quantity = quantity
self.date_purchased = date_purchased
def insert(self):
db.session.add(self)
db.session.commit()
def update(self):
db.session.commit()
def delete(self):
db.session.delete(self)
db.session.commit()
def format(self):
return {
'id': self.id,
'name': self.name,
'weight': self.weight,
'quantity': self.quantity,
'date_purchased': self.date_purchased
}
def __repr__(self):
return f'<Product {self.id}: {self.last_name}, {self.first_name}>'
<file_sep>
import os
import babel
import dateutil.parser
from flask import Flask, request, abort, jsonify, redirect, flash
from flask import url_for, render_template
from flask import session
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from flask_migrate import Migrate
from .database.models import *
from .auth.auth import AuthError, requires_auth
from datetime import datetime, date
import json
import logging
from six.moves.urllib.parse import urlencode
from google.cloud import vision
import io
from .forms import *
import sys
def create_app(test_config=None):
app = Flask(__name__)
setup_db(app)
CORS(app)
#app.secret_key = os.environ['SECRET']
#os.environ["GOOGLE_APPLICATION_CREDENTIALS"]=r"C:\Users\shahd\OneDrive\Desktop\MediDate Application\MediDate_Credentials\steel-aileron-266916-d88c69f449c7.json"
UPLOAD_FOLDER = '/home/Jared/Desktop/Hackathon/enactusHacks/App/app/static/img/Receipts/'
#----------------------------------------------------------------------------#
# Functions.
#----------------------------------------------------------------------------#
def format_datetime(value, format='medium'):
date = dateutil.parser.parse(value)
if format == 'full':
format="EEEE MMMM, d, y 'at' h:mma"
elif format == 'medium':
format="EE MM, dd, y h:mma"
return babel.dates.format_datetime(date, format)
app.jinja_env.filters['datetime'] = format_datetime
def detect_text(path):
"""Detects text in the receipt file."""
client = vision.ImageAnnotatorClient()
with io.open(path, 'rb') as image_file:
content = image_file.read()
image = vision.types.Image(content=content)
response = client.text_detection(image=image)
texts = response.text_annotations
d = {"Name": 0, "Fill Date": 0, "RX": 0, "Qty": 90, "date-to-take": 0, "Red": 0, "Blue": 0,"Green": 0}
count = 0
for text in texts:
if(text.description == "Rx" or text.description == "Rx#" or text.description == "#" or text.description == "Rx:" or text.description == "Rx:#" or text.description == "Rx: #" or text.description == ":"):
count = 1
continue
if(text.description[0:2] == "Qty"):
d["Qty"] = text.description[3:len(text.description)-1]
if(count == 1):
d["RX"] = text.description
count = 0
vertices = (['({},{})'.format(vertex.x, vertex.y)
for vertex in text.bounding_poly.vertices])
print('bounds: {}'.format(','.join(vertices)))
return d
if response.error.message:
raise Exception(
'{}\nFor more info on error messages, check: '
'https://cloud.google.com/apis/design/errors'.format(
response.error.message))
#----------------------------------------------------------------------------#
# Endpoints.
#----------------------------------------------------------------------------#
@app.after_request
def after_request(response):
response.headers.add('Access-Control-Allow-Headers',
'Authorization, Content-Type')
response.headers.add('Access-Control-Allow-Methods',
'GET, POST, DELETE, PATCH')
return response
"""Main Index Endpoint
Return: returns home.html
"""
@app.route('/')
def home():
return render_template('pages/home.html')
def upload_predict():
if request.method == "POST":
image_file = request.files["image"]
if image_file:
image_location = os.path.join(
UPLOAD_FOLDER,
image_file.filename
)
image_file.save(image_location)
pred = detect_text
return render_template("pages/home.html", prediction=pred, image_name=image_file.filename)
return render_template("pages/home.html", prediction=0, image_name=None)
"""GET /products
Gets all products in the database
Returns:
JSON Object -- json of all products in the database
"""
@app.route('/products')
#@requires_auth('get:products')
def get_products():
data= Product.query.distinct().order_by(Product.name.desc()).all()
return render_template('pages/products.html', products=data)
"""GET /users
Gets all users in the database
Returns:
JSON Object -- json of all users in the database
"""
@app.route('/users')
#@requires_auth('get:user')
def get_users():
data= User.query.distinct().order_by(User.last_name.desc()).all()
return render_template('pages/users.html', users=data)
@app.route('/users/search', methods=['POST'])
def search_artists():
search_term = request.form.get('search_term',None)
artists = User.query.filter(User.name.ilike("%{}%".format(search_term))).all()
response={
"count":len(users),
"data": user
}
"""GET /products/create
Creates and adds a new product to the database
Returns:
JSON Object -- json of movie added if the entry is successful
"""
@app.route('/products/create', methods=['GET'])
def create_product_form():
form = ProductForm()
return render_template('forms/new_product.html', form=form)
"""POST /products
Creates and adds a new product to the database
Returns:
JSON Object -- json of movie added if the entry is successful
"""
@app.route('/products', methods=['POST'])
#@requires_auth('post:products')
def new_product():
form = ProductForm(request.form)
print(form)
error=False
try:
product = Product(
name=form.name.data,
description=form.description.data,
weight=form.weight.data,
quantity=form.quanitity.data,
date_purchased=form.date_purchased.data
)
db.session.add(product)
db.session.commit()
# on successful db insert, flash success
flash('Product ' + request.form['name'] +
' was successfully listed!')
except:
error = True
db.session.rollback()
print(sys.exc_info())
flash('An error occurred. Product ' + Product.name +
' could not be listed.')
finally:
db.session.close()
return render_template('pages/home.html')
"""GET /users
Creates and adds a new user to the database
Returns:
web page
"""
@app.route('/users/create', methods=['GET'])
def create_user_form():
form = UserForm()
return render_template('forms/new_user.html', form=form)
"""POST /users
Creates and adds a new user to the database
Returns:
web page
"""
@app.route('/users', methods=['POST'])
#@requires_auth('post:user')
def new_user():
form = UserForm(request.form)
print(form)
error=False
try:
user = User(
first_name=form.first_name.data,
last_name=form.last_name.data,
age=form.age.data
)
db.session.add(user)
db.session.commit()
# on successful db insert, flash success
flash('User ' + request.form['first_name'] + request.form['last_name'] +
' was successfully listed!')
except:
error = True
db.session.rollback()
print(sys.exc_info())
flash('An error occurred. User ' + User.first_name +
User.last_name + ' could not be listed.')
finally:
db.session.close()
return render_template('pages/home.html')
"""'DELETE /products/<int:product_id>
Deletes a product from the database
Inputs:
int "product_id"
Returns:
JSON Object -- json message if deletion is successful
"""
@app.route('/products/<int:product_id>', methods=['DELETE'])
#@requires_auth('delete:product')
def delete_product(product_id):
# Delete product with submitted id from database
try:
# Find product with product_id
product = Product.query.filter(Product.id == product_id).one_or_none()
# if product is none throw 404
if product is None:
abort(404)
# Delete the product
product.delete()
result = {
'success': True,
'message': 'Deleted Product ID: ' + str(product_id)
}
except:
abort(422)
return jsonify(result)
"""'DELETE /users/<int:user_id>
Deletes an user from the database
Inputs:
int "user_id"
Returns:
JSON Object -- json message if deletion is successful
"""
@app.route('/users/<int:user_id>', methods=['DELETE'])
#@requires_auth('delete:user')
def delete_user(payload, user_id):
# Delete user with submitted id from database
try:
# Find user with user_id
user = User.query.filter(User.id == user_id).one_or_none()
# If user is none throw 404
if user is None:
abort(404)
# Delete the user
user.delete()
result = {
'success': True,
'message': 'Deleted User ID: ' + str(user_id)
}
except:
abort(422)
return jsonify(result)
"""GET /products/<int:product_id>
Edits a recipe in the database
Inputs:
int "recipe_id"
Returns:
JSON Object -- json message if edit is successful
"""
@app.route('/products/<int:product_id>', methods=['GET'])
#@requires_auth('post:product')
def edit_product(product_id):
form = ProductForm()
product_update=Product.query.filter_by(id=product_id).one_or_none()
if product_update is None:
abort(404)
product={
'id': product_update.id,
'name' : product_update.name,
'description' : product_update.description,
'weight' : product_update.weight,
'quantity' : product_update.date_purchased
}
form=ProductForm(data=product)
return render_template('forms/edit_product.html', form=form, product=product)
"""GET /products/<int:product_id>
Edits a recipe in the database
Inputs:
int "recipe_id"
Returns:
JSON Object -- json message if edit is successful
"""
@app.route('/products/<int:product_id>/edit', methods=['POST'])
#@requires_auth('post:product')
def edit_product_submission(product_id):
form = ProductForm(request.form)
try:
product = Product.query.filter_by(id=product_id).one()
product.name=form.name.data
product.description=form.description.data
product.weight=form.weight.data
product.quantity = form.quantity.data
product.date_purchased = form.date_purchased.data
db.session.commit()
flash('Product ' + request.form['name'] + ' was updated successfully.')
except:
db.session.rollback()
flash('An error occurred. User ' + request.form['name'] +
' failed to update.')
return redirect(url_for('show_product', product_id=product_id))
"""GET /users/<int:user_id>/edit
Edits an user in the database
Inputs:
int "user_id"
Returns:
JSON Object -- json message if edit is successful
"""
@app.route('/users/<int:user_id>/edit', methods=['GET'])
def edit_user(user_id):
form = UserForm()
user_update = User.query.filter_by(id=user_id).one_or_none()
if user_update is None:
abort(404)
user={
'id': user_update.id,
'first_name' : user_update.first_name,
'last_name' : user_update.last_name,
'age' : user_update.age
}
form=UserForm(data=user)
return render_template('forms/edit_artist.html', form=form, user=user)
"""POST /users/<int:user_id>/edit
Edits an user in the database
Inputs:
int "user_id"
Returns:
JSON Object -- json message if edit is successful
"""
@app.route('/users/<int:user_id>/edit', methods=['POST'])
#@requires_auth('patch:user')
def edit_user_submission(user_id):
form = UserForm(request.form)
try:
user = User.query.filter_by(id=user_id).one()
user.first_name=form.first_name.data
user.last_name=form.last_name.data
user.age=form.age.data
db.session.commit()
flash('User ' + request.form['first_name'] +
request.form['last_name'] + ' was updated successfully.')
except:
db.session.rollback()
flash('An error occurred. User ' + request.form['first_name'] +
request.form['last_name'] + ' failed to update.')
return redirect(url_for('show_user', user_id=user_id))
"""
Login Route
The login route redirects to the Auth0 login page
"""
'''
@app.route('/login')
def login():
link = 'https://'
link += os.environ['AUTH0_DOMAIN']
link += '/authorize?'
link += 'audience=' + os.environ['API_AUDIENCE'] + '&'
link += 'response_type=token&'
link += 'client_id=' + os.environ['CLIENT_ID'] + '&'
link += 'redirect_uri=' + os.environ['CALLBACK_URL'] +\
os.environ['CALLBACK_PATH']
return redirect(link)
"""
Logout Route
The logout route logs out and redirects to the home page
"""
@app.route('/logout')
def logout():
# Clear session stored data
session.clear()
# Redirect user to logout endpoint
link = 'https://'
link += os.environ['AUTH0_DOMAIN']
link += '/v2/logout?'
link += 'client_id=' + os.environ['CLIENT_ID'] + '&'
link += 'returnTo=' + os.environ['CALLBACK_URL']
return redirect(link)
'''
# ---------------------------------------------------------------------------#
# Errors.
# ---------------------------------------------------------------------------#
# ERROR - BAD REQUEST (400)
@app.errorhandler(400)
def bad_request(error):
return jsonify({
'success': False,
'error': 400,
'message': 'bad request'
}), 400
# ERROR - UNAUTHORIZED (401)
@app.errorhandler(401)
def forbidden(error):
return jsonify({
'success': False,
'error': 401,
'message': 'unauthorized'
}), 401
# ERROR - FORBIDDEN (403)
@app.errorhandler(403)
def forbidden(error):
return jsonify({
'success': False,
'error': 403,
'message': 'forbidden'
}), 403
# ERROR - NOT FOUND (404)
@app.errorhandler(404)
def resource_not_found(error):
return jsonify({
'success': False,
'error': 404,
'message': 'resource not found'
}), 404
# ERROR - METHOD NOT ALLOWED (405)
@app.errorhandler(405)
def method_not_allowed(error):
return jsonify({
'success': False,
'error': 405,
'message': 'method not allowed'
}), 405
# ERROR - UNPROCESSABLE (422)
@app.errorhandler(422)
def unprocessable(error):
return jsonify({
'success': False,
'error': 422,
'message': 'unprocessable'
}), 422
# ERROR - INTERNAL SERVER ERROR (500)
@app.errorhandler(500)
def server_error(error):
return jsonify({
'success': False,
'error': 500,
'message': 'internal server error'
}), 500
# ERROR - AUTHENTICATION ERROR
@app.errorhandler(AuthError)
def auth_error(error):
return jsonify({
"success": False,
"error": error.status_code,
"message": error.error
}), error.status_code
return app
# ----------------------------------------------------------------------------#
# Ceate and Launch App.
# ----------------------------------------------------------------------------#
# Create App
app = create_app()
# Run App
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
app.run(host='127.0.0.1', port=8080)
<file_sep>"""empty message
Revision ID: 88162422f489
Revises:
Create Date: 2020-10-25 02:28:49.305303
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '88162422f489'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint('user_products_product_id_fkey', 'user_products', type_='foreignkey')
op.drop_constraint('user_products_user_id_fkey', 'user_products', type_='foreignkey')
op.create_foreign_key(None, 'user_products', 'users', ['user_id'], ['id'], onupdate='CASCADE', ondelete='CASCADE')
op.create_foreign_key(None, 'user_products', 'products', ['product_id'], ['id'], onupdate='CASCADE', ondelete='CASCADE')
op.alter_column('users', 'first_name',
existing_type=sa.VARCHAR(),
nullable=False)
op.alter_column('users', 'last_name',
existing_type=sa.VARCHAR(),
nullable=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.alter_column('users', 'last_name',
existing_type=sa.VARCHAR(),
nullable=True)
op.alter_column('users', 'first_name',
existing_type=sa.VARCHAR(),
nullable=True)
op.drop_constraint(None, 'user_products', type_='foreignkey')
op.drop_constraint(None, 'user_products', type_='foreignkey')
op.create_foreign_key('user_products_user_id_fkey', 'user_products', 'users', ['user_id'], ['id'])
op.create_foreign_key('user_products_product_id_fkey', 'user_products', 'products', ['product_id'], ['id'])
# ### end Alembic commands ###
<file_sep>alembic==1.3.0
appnope==0.1.0
asn1crypto==1.3.0
astroid==2.4.1
attrs==19.3.0
Authlib==0.14.3
Babel==2.8.0
backcall==0.1.0
backports.functools-lru-cache==1.6.1
backports.tempfile==1.0
backports.weakref==1.0.post1
beautifulsoup4==4.9.0
bleach==3.1.4
certifi==2019.9.11
cffi==1.14.0
chardet==3.0.4
click==7.1.1
cryptography==2.8
decorator==4.4.2
defusedxml==0.6.0
ecdsa==0.15
entrypoints==0.3
filelock==3.0.12
Flask==1.1.1
Flask-Cors==3.0.8
Flask-Migrate==2.5.2
Flask-Moment==0.9.0
Flask-Script==2.0.6
Flask-SQLAlchemy==2.4.1
Flask-WTF==0.14.3
future==0.18.2
glob2==0.7
gunicorn==20.0.0
idna==2.9
importlib-metadata==1.5.0
ipykernel==5.1.4
ipython==7.13.0
ipython-genutils==0.2.0
ipywidgets==7.5.1
isort==4.3.21
itsdangerous==1.1.0
jedi==0.17.0
Jinja2==2.10.3
joblib==0.14.1
json5==0.9.4
jsonschema==3.2.0
jupyter-client==6.1.3
jupyter-core==4.6.3
jupyterlab==1.2.6
jupyterlab-server==1.1.1
lazy-object-proxy==1.4.3
libarchive-c==2.9
Mako==1.1.0
MarkupSafe==1.1.1
mccabe==0.6.1
mistune==0.8.4
nbconvert==5.6.1
nbformat==5.0.4
nltk==3.5
notebook==6.0.3
pandocfilters==1.4.2
parso==0.7.0
pexpect==4.8.0
phonenumbers==8.12.3
pickleshare==0.7.5
pkginfo==1.5.0.1
postgres==3.0.0
prometheus-client==0.7.1
prompt-toolkit==3.0.4
psutil==5.7.0
psycopg2-binary==2.8.4
psycopg2-pool==1.1
ptyprocess==0.6.0
pyasn1==0.4.8
pycosat==0.6.3
pycparser==2.20
pycryptodome==3.3.1
Pygments==2.6.1
PyJWT==1.7.1
pylint==2.5.2
pylint-flask==0.6
pylint-flask-sqlalchemy==0.2.0
pylint-plugin-utils==0.6
pyOpenSSL==19.1.0
pyrsistent==0.16.0
PySocks==1.7.1
python-dateutil==2.8.1
python-dotenv==0.13.0
python-editor==1.0.4
python-jose==3.1.0
python-jose-cryptodome==1.3.2
pytz==2020.1
PyYAML==5.3.1
pyzmq==18.1.1
regex==2020.4.4
requests==2.23.0
rsa==4.0
ruamel-yaml==0.15.87
Send2Trash==1.5.0
six==1.13.0
soupsieve==2.0
SQLAlchemy==1.3.10
terminado==0.8.3
testpath==0.4.4
toml==0.10.0
tornado==6.0.4
tqdm==4.46.0
traitlets==4.3.3
typed-ast==1.4.1
urllib3==1.25.8
wcwidth==0.1.9
webencodings==0.5.1
Werkzeug==0.16.0
widgetsnbextension==3.5.1
wrapt==1.12.1
WTForms==2.3.1
zipp==3.1.0
<file_sep>from datetime import datetime
from flask_wtf import Form
from wtforms import StringField, SelectField, SelectMultipleField, DateTimeField
from wtforms.validators import DataRequired, AnyOf, URL
class ProductForm(Form):
name = StringField(
'name', validators=[DataRequired()]
)
weight = StringField(
'weight', validators=[DataRequired()]
)
quanitity = StringField(
'quantity', validators=[DataRequired()]
)
date_purchased = DateTimeField(
'date_purchased', validators=[DataRequired()]
)
image_link = StringField(
'image_link'
)
class UserForm(Form):
first_name = StringField(
'first_name', validators=[DataRequired()]
)
last_name = StringField(
'last_name', validators=[DataRequired()]
)
age = StringField(
'age', validators=[DataRequired()]
)
| 00d56d5ed7a76b5df2475bf3bb0c7d09ba2b7eb7 | [
"Python",
"Text",
"HTML"
] | 6 | HTML | aranyah/enactusHacks | be007d1c3340b8d43de74c00f477b84664e27c03 | ab88e9769bb7311e7bce65af57e09e8089f307ac | |
refs/heads/master | <file_sep>import pandas as pd
import unicodedata
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
url = "https://www.lds.org/temples/list?lang=eng"
driver = webdriver.Chrome("/Users/danemorgan/chromedriver")
def scrape(url):
driver.get(url)
driver.implicitly_wait(5)
#pulling out the data by html tag, seperate by "/n", returns elements as a very long string
nameData = "/n".join([i.text for i in driver.find_elements_by_xpath('//*[@class="templeName-2MBmf"]',)])
locData = "/n".join([i.text for i in driver.find_elements_by_xpath('//span[@class="templeLocation-27z9P"]')])
dateData = "/n".join([i.text for i in driver.find_elements_by_xpath('//span[@class="dedicated-2xVdg"]')])
#print nameData,locData,dateData
driver.close()
#normalize char type
nameData = unicodedata.normalize("NFKD", nameData).encode("UTF-8")
locData = unicodedata.normalize("NFKD", locData).encode("UTF-8")
#split data, one very long string into a list of smaller strings
name = nameData.split("/n")
loc = locData.split("/n")
date = dateData.split("/n")
#start making DFs with column names
DF = pd.DataFrame({"Name":name})
locDF = pd.DataFrame({"Location":loc})
dateDF = pd.DataFrame({"Date":date})
#clean date dataframe
dateDF = dateDF.shift(1)
#add dataframes together
DF["Location"]= locDF
DF["Date"]= dateDF
#more cleanup
DF.loc[182,"Location"]="April 22, 2001"
DF = DF.drop([0,0])
#save DF to CSV
DF.to_csv("LDS-temples.csv")
DF.to_json("LDS-temples.json")
print "DONE!"
scrape(url)
<file_sep>### Context
I couldn't find a data set about LDS temples, so I wrote a script to scrape lds.org and save the data as a CSV and JSON. Enjoy!
### Content
Temple name, location, dedication date(some dates include "announced", these temples haven't been completed)
### Libraries and Frameworks
Pandas - make dataframe and clean data
UnicodeData - normalize raw characters
Selenium - webdriver and data acquisition
| 355c9a81f5e220363a7d8216784a31338399609f | [
"Markdown",
"Python"
] | 2 | Python | deadlift1226/LDS-Temple-Scraper | b9b1c4b302147f0f475d824e422fe658df8ba501 | 7c1c51b44b606b9b448183eb684b0accc7b8e9f1 | |
refs/heads/main | <repo_name>ashitosh098/js_week1_function_API-task<file_sep>/anonymous_function/titleCap.js
//anonmyous function to rotate array by k times
var titleCap = function (){
//create array of string
var arr=["ChilBule", "AshitoSH", "GUVI"]
//apply map method on string
var title =arr.map((ar)=>{
//convert all characters to lower case
var lower =ar.toLowerCase().split("");
//convert first character to upper case
var first = lower.shift().toUpperCase();
lower.unshift(first);
var ans =lower.join("");
return ans;
})
//display result
console.log(title);
}
//call anonmyous function
titleCap();<file_sep>/weather.js
//lat lang value as a input
var lat=54;
var lng =-1;
//create a object of XMLHttprequest
var request = new XMLHttpRequest()
var url ='https://api.openweathermap.org/data/2.5/weather?lat='+lat+'&lon='+lng+'&appid=e4239a13ec2249d41db473766d8cd69d';
//initialize newly created request
request.open('GET',url,true);
//send request to server
request.send();
//execute callback function after transaction is complete
request.onload = function()
{
var data =JSON.parse(this.response);
console.log("WEATHER REPORT of latitude "+lat+" and longitude "+lng +" : "+data.weather[0].description);
}
<file_sep>/IIFE_function/Sum_Of_Number.js
//iife function to print sum of all number in array
( function(){
//create array with input number
var number = [1,2,3,4,5];
//apply array method reduce on number array
var ans =number.reduce((sum,current)=>{
return sum+current;
}
);
//display result
console.log(ans);
}
)
//immediately call iife function
();
<file_sep>/IIFE_function/OddNumber.js
//iife function to print odd number in array
(
function()
{
//create array with input number
var number = [1,2,3,4,5];
//apply array method filter on number array
var ans =number.filter(num=>num%2!=0);
//display result array
console.log(ans);
}
)
//immediately call iife function
();
<file_sep>/IIFE_function/titleCap.js
//IIFE function to rotate array by k times
(function (){
//create array of string
var arr=["ChilBule", "AshitoSH", "GUVI"]
//apply map method on string
var title =arr.map((ar)=>{
//convert all characters to lower case
var lower =ar.toLowerCase().split("");
//convert first character to upper case
var first = lower.shift().toUpperCase();
lower.unshift(first);
var ans =lower.join("");
return ans;
})
//display result
console.log(title);
})
//call IIFE function
();<file_sep>/anonymous_function/Sum_Of_Number.js
//anonymous function to print sum of all number in array
var sum = function()
{
//create array with input number
var number = [1,2,3,4,5];
//apply array method reduce on number array
var ans =number.reduce((sum,current)=>{
return sum+current;
}
);
//display result
console.log(ans);
}
// call anonymous function using variable name assigned to it
sum ();
<file_sep>/anonymous_function/OddNumber.js
//anonymous function to print odd number in array
var odd = function()
{
//create array with input number
var number = [1,2,3,4,5];
//apply array method filter on number array
var ans =number.filter((num)=>{
return num%2!=0
}
);
//display result array
console.log(ans);
}
// call anonymous function using variable name assigned to it
odd ();
<file_sep>/IIFE_function/prime_number.js
//iife function to print prime number in array
( function (){
//create array with input number
var number = [1,2,3,4,5,6,17,19,18,24,25,33,24,47,98,93];
//apply array method filter on number array
var ans = number.filter((num)=>
{
var flag =0;
//if input number is 2 it is prime number
if(num==2)
{
return num;
}
//for input number greater than 2
else if(num>2)
{
//for number>2 and odd
if(num%2!=0)
{
//check for every number less than input number wether its divide input number or not
for(i=num-1;i>=2;i--)
{
if(num%i!=0)
{
flag =flag+1;
}
}
//if it is not divisible by any other number it is prime
if(flag==num-2)
{
return num;
}
}
}
}
)
//display result
console.log(ans);
}
)
//call iife function
();<file_sep>/anonymous_function/Palindromes.js
//anonmoyus function to find palindromes
var palindromes =function()
{
//create array
var arr = ["121","16461","131","126","141","127"];
//apply array method filter on arr
var ans = arr.filter((num)=>
{
//split current element of arr
var temp = num.split("");
var a=[];
//push current element of arr in reverse order
for(var i=temp.length-1;i>=0;i--)
{
a.push(temp[i]);
}
var b = a.join("");
//compare current element of arr and its reverse order
if(+num==+b)
{
return num;
}
})
//display result array
console.log(ans);
}
//call anonmoyus function
palindromes(); | c574956642dc57c425bdcc809c58416908ffd3de | [
"JavaScript"
] | 9 | JavaScript | ashitosh098/js_week1_function_API-task | f0f0c92ad7ae0af6ce3d441f8935ee0992a63d94 | 68102942d0c23d1179533a4cebc21ba60ad0ee2c | |
refs/heads/master | <repo_name>RonanZer0/overwatch<file_sep>/sv_admin.lua
overwatch = {};
overwatch.commands = {};
function overwatch.PlayerSay(ply, text, silent)
ply.memode = ply.memode or false;
local silent = silent or false;
local cmd = string.gsub(string.gsub(string.gsub(string.lower(text), " (.*)", ""), "!", ""), "/", "");
local _args = string.gsub(string.lower(text), "(.-) ", "", 1);
local args = {};
local i = 0;
for s in _args:gmatch("%S+") do
i = i + 1;
args[i] = s;
end
ok = true;
local hasPrefix1 = string.find(text, "!");
local hasPrefix2 = string.find(text, "/");
if hasPrefix1 != 1 and hasPrefix2 != 1 then return end;
if !overwatch.commands[cmd] then overwatch.Print(ply, "Unknown command.") ok = false end;
if tostring(ply) != "[NULL Entity]" then
if !ply:IsAdmin() then overwatch.Print(ply, "You are not an admin!") ok = false end;
end
if !ok then return end;
if ply.memode then
local args1, args2, args3, args4 = args[1], args[2], args[3], args[4];
args[1] = ply:Nick();
args[2] = args1;
args[3] = args2;
args[4] = args3;
args[5] = args4;
end
timer.Simple(0.00001, function()
overwatch.commands[cmd].func(ply, args);
end);
if overwatch.commands[cmd].silent == true or silent then
return "";
end
end
function overwatch.RegisterCommand(name, _func, _silent, _help)
local _help = _help or "No help specified.";
overwatch.commands[name] = {func = _func, silent = _silent, help = _help,};
end
function overwatch.FindPlayer(nick, ply)
local r;
for _, v in pairs(player.GetAll()) do
if !string.find(string.lower(v:Nick()), nick) then continue end;
if !r then
r = v;
else
if ply then
overwatch.Print(ply, "Multiple players found!");
end
return;
end
end
return r;
end
function overwatch.Print(ply, msg)
if IsValid(ply) then
ply:PrintMessage(HUD_PRINTTALK, "[OVERWATCH] "..msg);
end
end
function overwatch.Broadcast(msg, caller)
for _, v in pairs(player.GetAll()) do
v:PrintMessage(HUD_PRINTTALK, "[OVERWATCH] "..msg);
end
if caller then
print("[OVERWATCH] "..msg.." ("..caller..")");
else
print("[OVERWATCH] "..msg);
end
end
function overwatch.Help(ply, args)
if !overwatch.commands[args[1]] and args[1] != "*" and args[1] != "!help" then overwatch.Print(ply, "Command does not exist!"); return end;
if args[1] == "*" or args[1] == "!help" then
for k, v in pairs(overwatch.commands) do
overwatch.Print(ply, k.." - "..overwatch.commands[k].help);
end
else
overwatch.Print(ply, args[1].." - "..overwatch.commands[args[1]].help);
end
end
function overwatch.Kick(ply, args)
local victim = overwatch.FindPlayer(args[1]);
if !victim or !IsValid(victim) then overwatch.Print(ply, args[1].." is not a valid player!") return end;
victim:Kick(args[2]);
end
function overwatch.Ban(ply, args)
local victim = overwatch.FindPlayer(args[1]);
if !victim or !IsValid(victim) then overwatch.Print(ply, args[1].." is not a valid player!") return end;
overwatch.FindPlayer(args[1]):Ban(args[2], true);
end
function overwatch.Kill(ply, args)
local victim;
if !args[1] or args[1] == "!kill" then
victim = ply;
else
victim = overwatch.FindPlayer(args[1]);
end
if !victim or !IsValid(victim) then overwatch.Print(ply, args[1].." is not a valid player!") return end;
if !victim:Alive() then overwatch.Print(ply, victim:Nick().." is already dead!") return end;
victim:Kill();
end
function overwatch.Hurt(ply, args)
local victim = overwatch.FindPlayer(args[1]);
if !victim or !IsValid(victim) then overwatch.Print(ply, args[1].." is not a valid player!") return end;
if !victim:Alive() then overwatch.Print(ply, victim:Nick().." is dead!") return end;
victim:SetHealth(victim:Health()-args[2]);
end
function overwatch.Bring(ply, args)
local victim = overwatch.FindPlayer(args[1]);
if !victim or !IsValid(victim) then overwatch.Print(ply, args[1].." is not a valid player!") return end;
if !victim:Alive() then overwatch.Print(ply, victim:Nick().." is dead!") return end;
victim:SetPos(ply:GetPos());
end
function overwatch.Strip(ply, args)
local victim = overwatch.FindPlayer(args[1]);
if !victim or !IsValid(victim) then overwatch.Print(ply, args[1].." is not a valid player!") return end;
if !victim:Alive() then overwatch.Print(ply, victim:Nick().." is dead!") return end;
victim:StripWeapons();
end
function overwatch.SetHealth(ply, args)
local victim = overwatch.FindPlayer(args[1]);
if !victim or !IsValid(victim) then overwatch.Print(ply, args[1].." is not a valid player!") return end;
if !victim:Alive() then overwatch.Print(ply, victim:Nick().." is dead!") return end;
victim:SetHealth(args[2]);
end
function overwatch.SetActiveWeapon(ply, args)
local victim = overwatch.FindPlayer(args[1]);
if !victim or !IsValid(victim) then overwatch.Print(ply, args[1].." is not a valid player!") return end;
if !victim:Alive() then overwatch.Print(ply, victim:Nick().." is dead!") return end;
local wpn;
for _, w in pairs(victim:GetWeapons()) do
if w:GetClass() == args[2] then wpn = w else continue end;
end
victim:SetActiveWeapon(wpn);
end
function overwatch.Spawn(ply, args)
local victim;
if !args[1] or args[1] == "!spawn" then
victim = ply;
else
victim = overwatch.FindPlayer(args[1]);
end
if !victim or !IsValid(victim) then overwatch.Print(ply, args[1].." is not a valid player!") return end;
victim:Spawn();
end
function overwatch.Pos(ply, args)
local victim = overwatch.FindPlayer(args[1]);
if !victim or !IsValid(victim) then overwatch.Print(ply, args[1].." is not a valid player!") return end;
victim:SetPos(Vector(args[2], args[3], args[4]));
end
function overwatch.MeMode(ply)
ply.memode = ply.memode or false;
if !ply.memode then
overwatch.Print(ply, "Me-Mode is now ON.");
ply.memode = true;
else
overwatch.Print(ply, "Me-Mode is now OFF.");
ply.memode = false;
end
end
function overwatch.SetRank(ply, args)
if tostring(ply) != "[NULL Entity]" then
if !ply:IsSuperadmin() then return end;
end
local victim = overwatch.FindPlayer(args[1]);
if !victim or !IsValid(victim) then overwatch.Print(ply, args[1].." is not a valid player!") return end;
local o = victim:GetUserGroup();
victim:SetUserGroup(string.lower(args[2]));
local n = victim:GetUserGroup();
if o == n then return end;
if tostring(ply) == "[NULL Entity]" then ply = "Console" end;
local vn = victim:Nick();
if o == "superadmin" then
overwatch.Broadcast(vn.." has been demoted to "..n.."!");
elseif o == "admin" and n != "superadmin" then
overwatch.Broadcast(vn.." has been demoted to "..n.."!");
elseif n != "superadmin" and n != "admin" then
overwatch.Broadcast(vn.." has been ranked to "..n.."!");
else
overwatch.Broadcast(vn.." has been promoted to "..n.."!");
end
end
function overwatch.God(ply, args)
local victim;
if !args[1] or args[1] == "!god" then
victim = ply;
else
victim = overwatch.FindPlayer(args[1]);
end
if !victim or !IsValid(victim) then overwatch.Print(ply, args[1].." is not a valid player!") return end;
if victim:HasGodMode() then
victim:GodDisable();
else
victim:GodEnable();
end
end
function overwatch.Give(ply, args)
local victim = overwatch.FindPlayer(args[1]);
if !victim or !IsValid(victim) then overwatch.Print(ply, args[1].." is not a valid player!") return end;
victim:Give(args[2]);
end
function overwatch.Goto(ply, args)
local victim = overwatch.FindPlayer(args[1]);
if !victim or !IsValid(victim) then overwatch.Print(ply, args[1].." is not a valid player!") return end;
ply:SetPos(victim:GetPos());
end
function overwatch.Noclip(ply, args)
local victim;
if !args[1] or args[1] == "!noclip" then
victim = ply;
else
victim = overwatch.FindPlayer(args[1]);
end
if !victim or !IsValid(victim) then overwatch.Print(ply, args[1].." is not a valid player!") return end;
victim.noclip = victim.noclip or victim:GetMoveType() == MOVETYPE_NOCLIP;
if victim:GetMoveType() != MOVETYPE_NOCLIP then
victim:SetMoveType(MOVETYPE_NOCLIP);
victim.noclip = true;
else
victim:SetMoveType(MOVETYPE_WALK);
victim.noclip = false;
end
end
function overwatch.KillSilent(ply, args)
local victim = overwatch.FindPlayer(args[1]);
if !victim or !IsValid(victim) then overwatch.Print(ply, args[1].." is not a valid player!") return end;
victim:KillSilent();
end
function overwatch.NoclipThink()
for _, v in pairs(player.GetAll()) do
if v.noclip and v:GetMoveType() != MOVETYPE_NOCLIP then
v:SetMoveType(MOVETYPE_NOCLIP);
end
end
end
concommand.Add("setrank", function(ply, args, argst, str)
if tostring(ply) != "[NULL Entity]" then return end; -- only the console can call this!
overwatch.PlayerSay(ply, "!rank "..str)
end);
concommand.Add("overwatch", function(ply, args, argst, str)
overwatch.PlayerSay(ply, "!"..str, true);
end);
overwatch.RegisterCommand("ban", overwatch.Ban, false, "Bans the specified player.");
overwatch.RegisterCommand("bring", overwatch.Bring, false, "Brings the specified player.");
overwatch.RegisterCommand("give", overwatch.Give, false, "Gives an entity to the specified player.");
overwatch.RegisterCommand("god", overwatch.God, false, "Toggles godmode on the specified player.");
overwatch.RegisterCommand("goto", overwatch.Goto, false, "Goes to player's position.");
overwatch.RegisterCommand("help", overwatch.Help, false, "Shows the help text of a command.")
overwatch.RegisterCommand("hurt", overwatch.Hurt, false, "Hurts the specified player.");
overwatch.RegisterCommand("kick", overwatch.Kick, false, "Kicks the specified player.");
overwatch.RegisterCommand("kill", overwatch.Kill, false, "Kills the specified player.");
overwatch.RegisterCommand("killsilent", overwatch.KillSilent, true, "Silently kills the specified player.");
overwatch.RegisterCommand("memode", overwatch.MeMode, false, "Toggles Me-Mode.");
overwatch.RegisterCommand("noclip", overwatch.Noclip, false, "Toggles noclip on the specified player.");
overwatch.RegisterCommand("pos", overwatch.Pos, false, "Sets the specified player's position.");
overwatch.RegisterCommand("rank", overwatch.SetRank, false, "Sets the specified player's rank.");
overwatch.RegisterCommand("sethealth", overwatch.SetHealth, false, "Sets the specified player's health.");
overwatch.RegisterCommand("setweapon", overwatch.SetWeapon, false, "Sets the specified player's weapon.");
overwatch.RegisterCommand("spawn", overwatch.Spawn, false, "Spawns the specified player.");
overwatch.RegisterCommand("strip", overwatch.Strip, false, "Strips the specified player.");
hook.Add("PlayerSay", "overwatch.PlayerSay", overwatch.PlayerSay);
hook.Add("Think", "overwatch.NoclipThink", overwatch.NoclipThink);
print("[OVERWATCH] Successfully initialized without errors.")
| 46ca700b514ce198f793406f58c4286fe669a6bb | [
"Lua"
] | 1 | Lua | RonanZer0/overwatch | b55dc46d2b0ca622057f35593b982399f6bfd8a1 | bf3ac111261b44a8840086f9f011c8999aba7211 | |
refs/heads/main | <repo_name>mwoodward1990/vanilla-portfolio<file_sep>/script.js
const projectsContainer = document.getElementById("projects");
const projects = [
{
image: './images/coffee-shop.jpg',
link: 'https://coffee-shop-shopify-context.netlify.app/',
github: '',
name: 'Coffee Stop',
description: 'Full stack React based Shopify integrated Coffee Shop featuring 10 plus pages, a dynamic cart accessible from multiple pages and custom design.'
},
{
image: './images/rps.png',
link: 'https://loveliiivelaugh.github.io/nu-javascript03-mini-project/',
github: '',
name: 'Rock Paper Scissors',
description: "A vanilla JavaScript Rock Paper Scissor's game."
},
{
image: './images/cli-employee-management.png',
link: '',
github: 'https://github.com/loveliiivelaugh/cli-employee-management-system',
name: 'CLI Employee Management',
description: "A command line application to manage employees in a MySQL database. Built with NodeJs. It uses the Inquirer package as well as MySQL to enable interacting with the command line as well as storing and retrieving information from the database. Utilizes OOP design."
},
{
image: './images/ecommerce-backend.png',
link: '',
github: 'https://github.com/loveliiivelaugh/e-commerce-backend',
name: 'E-Commerce Backend',
description: "A sample build out of an ecommerce backend. Built using JavaScript, ExpressJS, MySQL, and Sequelize."
},
{
image: './images/tastyGen_screenshot.png',
link: '#',
github: 'https://loveliiivelaugh.github.io/nu-group-project-1/',
name: 'TastyGen',
description: "TastyGen is an application created for a user that is interested in finding new and unique recipes."
},
{
image: './images/tech-blog.png',
link: 'https://sqlbars-tech-blog.herokuapp.com/',
github: 'https://github.com/loveliiivelaugh/sqlbars-tech-blog',
name: 'SQL Bars Tech Blog',
description: ""
},
{
image: './images/workday-scheduler.png',
link: 'https://loveliiivelaugh.github.io/nu-hw5-daily-scheduler/',
github: 'https://github.com/loveliiivelaugh/nu-hw5-daily-scheduler',
name: 'Work Day Scheduler',
description: 'A small daily scheduler app built with vanilla HTML, CSS, and JavaScript. Seperates the day into hourly time blocks that the user can store notes and appointments in. Data is persisted using local storage.'
},
{
image: './images/exercise-tracker.png',
link: 'https://fire-react-exercise-tracker.netlify.app/',
github: 'https://github.com/loveliiivelaugh/exercise-tracker',
name: 'React Material Exercise Tracker',
description: 'A small React app to track exercise activity. Features user authentication and real time database storage to store daily activity data. Includes a chart to be used for data visualization.'
},
{
image: './images/code-quiz.png',
link: 'https://loveliiivelaugh.github.io/nu-hw4-coding-quiz/',
github: 'https://github.com/loveliiivelaugh/nu-hw4-coding-quiz',
name: 'Code Quiz',
description: ' A small quiz application to repeatedly ask the user coding practice questions until either the time runs out or the questions run out and keeps track of the score and the time along the way.'
},
{
image: './images/todo.jpg',
link: 'https://learnjs-todo.herokuapp.com/',
github: '',
name: 'To Do List',
description: 'Full stack simple to do app, highlighting the use of CRUD operations, utilizing MongoDB for a database featuring simple design and deployed using Heroku.'
},
{
image: './images/bootstrap-weather-dashboard.png',
link: 'loveliiivelaugh.github.io/nu-hw6-weather-dashboard/',
github: 'https://github.com/loveliiivelaugh/nu-hw6-weather-dashboard',
name: 'Weather Dashboard',
description: 'A small weather application featuring the ability to find weather and 5-day forecasts for multiple cities of choosing. This application makes use of the OpenWeatherAPI for live weather data.'
},
{
image: './images/employee-management-system-screenshot.png',
link: 'https://fire-react-employee-management.netlify.app/',
github: '',
name: 'Employee Management System',
description: 'Employee management system built with React, MaterialUI, Firebase for auth and for the noSql Firestore database. This is an attempt to build this project ahead of having to build it as part of a coding bootcamp curriculum I am about to begin.'
},
{
image: './images/fictional-university.jpg',
link: 'http://michaelw4.sgedu.site/',
github: '',
name: 'Fictional University',
description: 'A Wordpress powered Fictional University website featuring 10 plus pages and a custom hand built theme. Also features custom post types and custom ...'
},
{
image: './images/react-weather.png',
link: 'adoring-mcclintock-6017c8.netlify.app/',
github: 'https://github.com/loveliiivelaugh/react-weather-app',
name: 'React Weather App',
description: 'A small weather app built with React and OpenWeather API.'
},
{
image: './images/any-eats.jpg',
link: 'https://kristin-serverless-store.netlify.app/',
github: '',
name: 'Any Eats',
description: 'Gatsby powered Stripe integrated simple single page e-commerce website.'
},
{
image: './images/2020-election-api.png',
link: 'https://6fmcve298d.execute-api.us-east-1.amazonaws.com/api/',
github: '#',
name: '2020 Presidential Election Results by county API',
description: 'An API to find out the results of the 2020 presidential election by county. Built to be used in data science to study what the voter turn out outcome was in each county to measure or analyze correlations between votes, demographics, and geographical influence.'
},
{
image: './images/meal-finder.jpg',
link: 'https://loveliiivelaugh.github.io/mealFinderJS/',
github: '',
name: 'Meal Finder App',
description: 'Meal finder web app using a meal search API built in vanilla JavaScript.'
},
{
image: './images/lyrics-search.jpg',
link: 'https://loveliiivelaugh.github.io/lyricsSearchJS/',
github: '',
name: 'Lyrics Search App',
description: 'Lyrics searching web app using a lyrics search API built in vanilla JavaScript.'
},
{
image: '',
link: 'https://lyrics-search-react.netlify.app/',
github: 'https://lyrics-search-react.netlify.app/',
name: 'React Lyrics Search',
description: 'A vanilla project converted to a small React app to search for lyrics of any songs using a lyrics searching API.'
},
{
image: './images/meal-finder-app.png',
link: 'https://smart-menu-react.netlify.app/',
github: 'https://github.com/loveliiivelaugh/react-smart-menu',
name: 'React Smart Menu',
description: 'An old revisited vanilla javascript project rewritten in React and with a new API -> Tasty by Dojo APIs. Small project to find meal ideas complete with nutritional facts, recipe, and instructions based on key word search or by multiple ingredients.'
},
{
image: '',
link: 'https://loveliiivelaugh.github.io/typingGameJS/',
github: 'https://github.com/loveliiivelaugh/typingGameJS',
name: 'Typing Game',
description: 'This one is a typing game.'
},
];
let page = 1;
let pageCounter = 0;
const handlePrev = () => {
pageCounter -= 6;
page -= 1;
setProjects(page);
};
const handleNext = () => {
pageCounter += 6;
page += 1;
setProjects(page);
};
const setProjects = page => {
projectsContainer.innerHTML = `
<div class="glass-container">
<h3>Projects</h3>
<center>
<p>Page ${page+' / '+ Math.ceil(projects.length / 6)}</p>
${page > 1 ? `<button class="btn" onclick="handlePrev()">Prev</button>` : '' }
${Math.ceil(projects.length / 6) > 1 &&
Math.ceil(projects.length / 6) != page ?
`<button class="btn" onclick="handleNext()">Next</button>` : ''
}
</center>
<div class="container">
${projects.slice(pageCounter, pageCounter + 6).map(project => `
<div class="grid-items">
<div class="image-container">
<img class="grid-image" src="${project.image}" alt="Thumnail of my project" />
<div class="middle">
<a href=${project.link ? project.link : "#"}" target="blank"><button class="btn">Learn More</button></a>
</div>
</div>
${project.github &&
`<a id="repo-link" href=${project.github} target="blank">
<i class="fa fa-github" aria-hidden="true"></i>
</a>
`}
<div style="display: inline;">
<h5>${project.name}</h5>
</div>
<p><small>${project.description}</small></p>
</div>
`).join("")}
</div>
<center>
${page > 1 ? `<button class="btn" onclick="handlePrev()">Prev</button>` : ''}
${Math.ceil(projects.length / 6) > 1 &&
Math.ceil(projects.length / 6) != page ?
`<button class="btn" onclick="handleNext()">Next</button>` : ''
}
<p>Page ${page+' / '+ Math.ceil(projects.length / 6)}</p>
</center>
<a href="https://www.michaelwoodward.dev/" target="blank"><button class="btn">Full Portfolio</button></a>
</div>
`;
};
setProjects(page);<file_sep>/README.md
# Vanilla Portfolio





From vanilla to React and my projects on the way!
## Description
* I built a small portfolio using vanilla HTML and CSS highlighting some of my projects and my journey as a developer as I explore the wide world of programming languages and technologies.
*UPDATES*
* This jsVersion branch is an updated version of my original with new styling, added JavaScript functionality, and populated the site with a lot more projects, almost triple.
#### Todo's
1. Update the contact form input fields styling.
2. Add last two pictures to projects section project cards.
## Finished Product

## Deployment
Deployed with [GH-Pages](https://pages.github.com/).
Live [Vanilla Dev Portfolio](https://loveliiivelaugh.github.io/vanilla-portfolio/).
Live [React Portfolio](https://www.michaelwoodward.dev/).
## Inspiration
[html5up Strata template](https://html5up.net/strata)

| eec5b6e77b8e87d618b06c9607600461043f8610 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | mwoodward1990/vanilla-portfolio | 4393ee292fb894ab35151a6f2f6412cb0a5667e5 | 3e35b0aa84e73af148b71999a1dd7b1cd16551e6 | |
refs/heads/master | <repo_name>MichaelYungLee/heliedge<file_sep>/Assets/Scripts/AudioOffset.cs
using UnityEngine;
using System.Collections;
public class AudioOffset : MonoBehaviour
{
IEnumerator Start ()
{
Random.seed = System.DateTime.Now.Millisecond;
yield return new WaitForSeconds(Random.Range(0f, 1.5f));
GetComponent<AudioSource>().Play();
}
}
<file_sep>/Assets/Scripts/WheelsRotation.cs
using UnityEngine;
using System.Collections;
public class WheelsRotation : MonoBehaviour
{
public float relativeSpeed = 100f;
private UnityEngine.AI.NavMeshAgent nav;
private Transform[] wheels = new Transform[4];
void Awake ()
{
nav = GetComponent<UnityEngine.AI.NavMeshAgent>();
wheels[0] = GameObject.Find("vehicle_rcLand_wheel_frontLeft").transform;
wheels[1] = GameObject.Find("vehicle_rcLand_wheel_frontRight").transform;
wheels[2] = GameObject.Find("vehicle_rcLand_wheel_rearLeft").transform;
wheels[3] = GameObject.Find("vehicle_rcLand_wheel_rearRight").transform;
}
void Update ()
{
float navSpeed = nav.velocity.magnitude;
foreach(Transform wheel in wheels)
{
wheel.Rotate(Vector3.right * relativeSpeed * navSpeed * Time.deltaTime);
}
}
}
<file_sep>/Assets/Scripts/RandomFloorBotMovement.cs
using UnityEngine;
using System.Collections;
public class RandomFloorBotMovement : MonoBehaviour
{
public Vector2 minimumCoordinates;
public Vector2 maximumCoordinates;
public Vector2 speedVariance;
public Vector2 newDestinationTimeVariance;
public Vector2 newSpeedTimeVariance;
private UnityEngine.AI.NavMeshAgent nav;
private float newDestinationTime;
private float destinationTimer;
private float newSpeedTime;
private float speedTimer;
void Awake ()
{
nav = GetComponent<UnityEngine.AI.NavMeshAgent>();
SetRandomDestination();
SetRandomSpeed();
}
void FixedUpdate ()
{
destinationTimer += Time.deltaTime;
speedTimer += Time.deltaTime;
if(destinationTimer >= newDestinationTime)
SetRandomDestination();
if(speedTimer >= newSpeedTime)
SetRandomSpeed();
}
void SetRandomDestination ()
{
float newX = Random.Range(minimumCoordinates.x, maximumCoordinates.x);
float newZ = Random.Range(minimumCoordinates.y, maximumCoordinates.y);
nav.destination = new Vector3(newX, -1f, newZ);
SetNewDestinationTime();
}
void SetRandomSpeed ()
{
nav.speed = Random.Range(speedVariance.x, speedVariance.y);
SetNewSpeedTime();
}
void SetNewDestinationTime ()
{
newDestinationTime = Random.Range(newDestinationTimeVariance.x, newDestinationTimeVariance.y);
destinationTimer = 0f;
}
void SetNewSpeedTime ()
{
newSpeedTime = Random.Range(newSpeedTimeVariance.x, newSpeedTimeVariance.y);
speedTimer = 0f;
}
}
<file_sep>/Assets/Workplace Tools/README.txt
This is the free package "Workplace Tools" by ikapoura.
The content provided is free and you can use them and modify them freely in your projects.
This project aims to provide a fast prototyping experience by providing some simple but
detailed models to get you going.
- How to use the package
Simply drag and drop any model you want from the Prefabs folder into your scene and you are ready!
- Materials
The materials are simple colors and every model has it's own materials named after it. This will
help altering only the color of one model to avoid confusion. (Except bolts. Bolts are mean.)
- Colliders
I have pre-enabled the Mesh Colliders for every objects and set Convex to true. If you want physics
interactions, simply add a Rigidbody Component to the root GameObject of each prefab.
- Help / questions
For any help, questions or even suggestions please email me at:
<EMAIL>
Enjoy!<file_sep>/Assets/Scripts/CaptureNormals.cs
using UnityEngine;
using System.Collections;
public class CaptureNormals : MonoBehaviour
{
private Material mat;
void OnPostRender()
{
if(!mat)
{
mat = new Material("Shader \"Hidden/SetAlpha\" {" +
"SubShader {" +
" Pass {" +
" ZTest Always Cull Off ZWrite Off" +
" SetTexture [_CameraNormalsTexture] { combine texture } " +
" } " +
" }" +
"}"
);
}
GL.PushMatrix();
GL.LoadOrtho();
for(int i = 0 ; i < mat.passCount ; ++i )
{
mat.SetPass(i);
GL.Begin(GL.QUADS);
GL.TexCoord(new Vector3(0, 0, 0));
GL.Vertex3(0, 0, 0.1f);
GL.TexCoord(new Vector3(1, 0, 0));
GL.Vertex3(1, 0, 0.1f);
GL.TexCoord(new Vector3(1, 1, 0));
GL.Vertex3(1, 1, 0.1f);
GL.TexCoord(new Vector3(0, 1, 0));
GL.Vertex3(0, 1, 0.1f);
GL.End();
}
GL.PopMatrix();
}
}
<file_sep>/README.md
Due to versioning complications from using git and Unity together, our most up-to-date code base is located in branch "feature/factoryObject"
<file_sep>/Assets/Scripts/Punch.cs
using UnityEngine;
using System.Collections;
public class Punch : MonoBehaviour
{
private Animator anim;
private int hitState;
private int doPunchBool;
void Awake ()
{
anim = GetComponent<Animator>();
hitState = Animator.StringToHash("Base Layer.Hit");
doPunchBool = Animator.StringToHash("DoPunch");
}
void OnTriggerExit (Collider other)
{
anim.SetBool(doPunchBool, true);
}
void Update ()
{
if(anim.GetCurrentAnimatorStateInfo(0).nameHash == hitState)
anim.SetBool(doPunchBool, false);
}
}
<file_sep>/Assets/Scripts/Rotator.cs
using UnityEngine;
using System.Collections;
public class Rotator : MonoBehaviour {
public float rotateSpeed = 5f;
void Update () {
transform.Rotate (new Vector3(0, rotateSpeed*Time.deltaTime,0));
}
}
| ecb88fa204fb792cefd1834b9205f5039de3a006 | [
"Markdown",
"C#",
"Text"
] | 8 | C# | MichaelYungLee/heliedge | a15d06a802121139fe56c0ac6288fbf543373a96 | f81d9541c1c7cbaf4e906f5596effaf8a330bfaa | |
refs/heads/master | <file_sep>/*
* Wiring :
* Sensor Pin | Arduino Pin
* ====================================
* + | VCC
* - | GND
* S | A4
*
*/
int analogInput = A4;
float vout = 0.0;
float vin = 0.0;
float R1 = 30000.0;
float R2 = 7500.0;
int value = 0;
void setup(){
pinMode(analogInput, INPUT);
Serial.begin(115200);
Serial.print("DC VOLTMETER");
}
void loop(){
value = analogRead(analogInput);
vout = (value * 5) / 1024.0;
vin = vout / (R2/(R1+R2));
Serial.print("INPUT V= ");
Serial.println(vin,2);
delay(500);
}
<file_sep># Arduino_Uno_DC_Voltage_Sensor
Repository ini berisi source code Arduino Uno dan DC Voltage Sensor.
Adapun rangkaian antara Arduino Uno dan DC Voltage Sensor nya sebagai berikut :
<table class="table table-striped">
<thead>
<tr>
<th>Sensor Pin</th>
<th>Arduino Uno Pin</th>
</tr>
</thead>
<tbody>
<tr>
<td>-</td>
<td>GND</td>
</tr>
<tr>
<td>+</td>
<td>5V</td>
</tr>
<tr>
<td>S</td>
<td>A4</td>
</tr>
<tr>
<td colspan="2"><img src="https://raw.githubusercontent.com/laurensius/Arduino_Uno_DC_Voltage_Sensor/master/screenshot.jpg" class="img img-responsive"></td>
</tr>
</tbody>
</table>
| 00b16c7750ea50734473ee703aea6994d3ba1e8c | [
"Markdown",
"C++"
] | 2 | C++ | laurensius/Arduino_Uno_DC_Voltage_Sensor | 5d6dc72f3a0f384b73fc3f865abb8c49c813d31e | 7703ce5396f2f057d3932ab9e8f18f1f9e5b65fc | |
refs/heads/master | <file_sep># shannonthurston.github.io
This is a simple place for storing my little test and demo files that I build in my spare time.
It will hopefully become a nice portfolio site in the future.
<file_sep>var app = angular.module("CodePlaygroundApp", []);
app.controller("CodePlaygroundAppCtrl", function ($scope, $timeout, $window) {
var c = this;
c.lsName = "codePlayground";
c.showHistory = false;
c.historyClass = 'hide';
c.hideHistory = function(ev){
c.showHistory = false;
c.historyClass = 'hide';
}
c.toggleHistory = function(){
if(c.showHistory){
c.historyClass = 'hide';
} else {
c.historyClass = 'show';
}
c.showHistory = !c.showHistory;
}
c.clearHistory = function(){
if(localStorage.length > 0){
localStorage.clear();
}
c.getHistory();
c.hideHistory();
}
c.saveHistory = function () {
if(c.codeHistory.length == 0){
return false;
}
var codeHistory = JSON.stringify(c.codeHistory);
localStorage.setItem(c.lsName, codeHistory);
};
c.addHistory = function(item){
if(!item){return false;}
var nowMS = new Date().getTime();
c.codeHistory.push({name: nowMS, value: item});
}
c.getHistory = function(){
var codeHistory = localStorage.getItem(c.lsName);
historyObj = JSON.parse(codeHistory);
if (codeHistory) {
c.codeHistory = historyObj;
} else {
c.codeHistory = [];
}
}
c.loadHistory = function(name){
console.log('loading history');
var item = c.codeHistory.find(function(el){
return el.name == name;
});
if(item){
c.htmlEditor.getDoc().setValue(item.value);
}
}
$timeout(c.getHistory, 0);
c.htmlEditor = CodeMirror(document.querySelector("#editor"), {
mode: "javascript",
tabSize: 4,
lineNumbers: true,
lineWrapping: true,
extraKeys: { "Shift-Ctrl-Space": "autocomplete" },
keyMap: "macSublime",
dragDrop: true,
smartIndent: true,
spellcheck: true,
autocorrect: true,
rulers: true,
foldGutter: true,
gutters: ["CodeMirror-lint-markers"],
lint: { options: { esversion: 2021 } },
});
$window.htmlEditor = c.htmlEditor;
CodeMirror.commands["selectAll"](c.htmlEditor);
document.querySelector("#run-button").addEventListener("click", function () {
let htmlCode = c.htmlEditor.getValue();
c.addHistory(htmlCode);
c.saveHistory();
let results = evalTheCode(htmlCode);
let consoleElement = document.querySelector("#results");
consoleElement.innerText = results.value;
consoleElement.className = "";
consoleElement.classList.add(results.status);
});
document
.querySelector("#clear-results")
.addEventListener("click", function () {
let consoleElement = document.querySelector("#results");
consoleElement.innerText = "";
});
document
.querySelector("#clear-console")
.addEventListener("click", function () {
console.clear();
});
document.querySelector("#editor").onkeydown = triggerEnterKey;
function triggerEnterKey(event) {
if (event.key =="Enter" && event.shiftKey) {
event.preventDefault();
document.querySelector("#run-button").click();
}
}
function evalTheCode(htmlCode) {
var res = { value: undefined, status: undefined };
try {
res.value = eval(htmlCode);
res.status = "success";
} catch (e) {
res.value = e;
res.status = "error";
}
return res;
}
});
<file_sep> var app = angular.module('PhaseTenApp', []);
app.controller('PhaseTenAppCtrl', function($scope){
$scope.result_round_1 = 0;
$scope.round_one_bonus = 0;
$scope.result_round_2 = 0;
$scope.result_final = 0;
$scope.finished_first_bonus = 0;
$scope.updateRound1Total = function(){
var p1 = $scope.phase_1 || 0;
var p2 = $scope.phase_2 || 0;
var p3 = $scope.phase_3 || 0;
var p4 = $scope.phase_4 || 0;
var p5 = $scope.phase_5 || 0;
var round1Total = (p1 + p2 + p3 + p4 + p5);
if(round1Total >= 220){
$scope.round_one_bonus = 40;
}
$scope.result_round_1 = round1Total;
};
$scope.updateRound2Total = function(){
var p6 = $scope.phase_6 || 0;
var p7 = $scope.phase_7 || 0;
var p8 = $scope.phase_8 || 0;
var p9 = $scope.phase_9 || 0;
var p10 = $scope.phase_10 || 0;
var round2Total = (p6 + p7 + p8 + p9 + p10);
$scope.result_round_2 = round2Total;
};
$scope.updateFinalResults = function(){
$scope.result_final = ($scope.result_round_1 + $scope.result_round_2 + $scope.round_one_bonus + $scope.finished_first_bonus);
}
$scope.updateTotals = function(){
console.log('updating totals');
$scope.updateRound1Total();
$scope.updateRound2Total();
$scope.updateFinalResults();
}
$scope.finishedFirstBonus = function(){
$scope.finished_first_bonus = 40;
$scope.updateTotals();
}
$scope.clearFinishedFirstBonus = function(){
$scope.finished_first_bonus = 0;
$scope.updateTotals();
}
$scope.updateTotals();
});
<file_sep> var app = angular.module('TemplateApp', []);
app.controller('TemplateAppCtrl', function($scope){
$scope.testValue = 0;
});
<file_sep>c = {};
c.CANVAS = document.getElementById("visual");
c.canvasCtx = c.CANVAS.getContext("2d");
c.AUDIO = document.querySelector("audio");
c.TOGGLE = document.querySelector("#toggle");
c.MUTE = document.querySelector(".mute");
c.VISUALIZER = document.querySelector("#visualizer");
c.WIDTH = window.innerWidth;
c.HEIGHT = window.innerHeight;
c.playing = false;
c.CANVAS.width = c.WIDTH;
c.CANVAS.height = c.HEIGHT;
jQuery(c.CANVAS).css("width", c.WIDTH);
jQuery(c.CANVAS).css("height", c.HEIGHT);
jQuery("main").css("padding-top", "0");
c.record = function (ev) {
if (c.playing) {
c.CTX.close();
c.playing = false;
return;
}
c.playing = true;
c.CTX = new AudioContext();
c.audioStream = navigator.mediaDevices
.getUserMedia({ audio: true, video: false })
.then(function (stream) {
c.source = c.CTX.createMediaStreamSource(stream);
c.gain = c.CTX.createGain();
c.gain.gain.value = 0;
c.analyser = c.CTX.createAnalyser();
c.dataArray = new Uint8Array(c.analyser.frequencyBinCount);
c.source.connect(c.gain);
c.source.connect(c.analyser);
c.gain.connect(c.CTX.destination);
c.visualize();
});
};
c.FULLSCREEN = function (ev) {
var canvas = document.getElementById("visual");
if (!document.fullscreenElement) {
canvas.requestFullscreen().then(
function (ev) {
console.log("success");
},
function (err) {
console.error("fail");
}
);
} else {
document.exitFullscreen();
}
};
c.VISUALIZER.addEventListener("click", c.record);
c.visualize = function () {
c.analyser.fftSize = 512;
var dataArrayAlt = new Uint8Array(c.analyser.frequencyBinCount);
c.canvasCtx.clearRect(0, 0, c.WIDTH, c.HEIGHT);
var drawEverything = function () {
if (!c.playing) {
return false;
}
var drawVisual = requestAnimationFrame(drawEverything);
c.analyser.getByteFrequencyData(dataArrayAlt);
//Clear the canvas
c.canvasCtx.fillStyle = "rgb(0, 0, 0)";
c.canvasCtx.fillRect(0, 0, c.WIDTH, c.HEIGHT);
//draw on cavas
var x = 0;
var randomChar = function () {
var idx = parseInt(Math.random() * 85);
var randomCharacter = String.fromCharCode(idx);
return randomCharacter || "?";
};
for (var i = 0; i < c.analyser.frequencyBinCount; i++) {
var freq = dataArrayAlt[i];
var randx = Math.random();
var randy = Math.random();
var randz = Math.random();
var freqFontSize = freq / 2;
c.canvasCtx.strokeStyle =
"rgb(" +
randx * freq * 3 +
"," +
randy * freq +
"," +
randz * freq +
")";
c.canvasCtx.font = freqFontSize + "px serif";
c.canvasCtx.strokeText(
randomChar(),
(randx * c.WIDTH + x) / 2,
(randy * c.HEIGHT + x) / 2
);
if (i % 15 == 0) {
c.canvasCtx.strokeRect(
(randx * c.WIDTH + x) / 2,
(randy * c.HEIGHT + x) / 2,
freq / 3,
freq / 3
);
}
x += (2 * freq) / 20;
}
var barWidth = (c.WIDTH / c.analyser.frequencyBinCount) * 2;
var barHeight;
var x1 = 0;
var x2 = 0;
var y = c.HEIGHT;
for (var i2 = 0; i2 < c.analyser.frequencyBinCount; i2++) {
barHeight = dataArrayAlt[i2];
c.canvasCtx.fillStyle =
"rgb(" +
(barHeight + 20) +
"," +
(barHeight + 120) +
"," +
(barHeight + 120) +
")";
c.canvasCtx.fillRect(x1, c.HEIGHT - barHeight, barWidth, barHeight);
c.canvasCtx.fillStyle =
"rgb(" +
(barHeight + 120) +
"," +
(barHeight + 20) +
"," +
(barHeight + 120) +
")";
c.canvasCtx.fillRect(c.WIDTH + x2, 0, barWidth, barHeight + 1.5);
x1 += barWidth + 1;
x2 = -x1;
}
};
drawEverything();
var drawAlt = function () {
if (!c.playing) {
return false;
}
var drawVisual = requestAnimationFrame(drawAlt);
c.analyser.getByteFrequencyData(dataArrayAlt);
c.canvasCtx.fillStyle = "rgb(0, 0, 0)";
c.canvasCtx.fillRect(0, 0, c.WIDTH, c.HEIGHT);
var barWidth = (c.WIDTH / c.analyser.frequencyBinCount) * 2;
var barHeight;
var x = 0;
var x2 = 0;
var y = c.HEIGHT;
for (var i = 0; i < c.analyser.frequencyBinCount; i++) {
barHeight = dataArrayAlt[i];
c.canvasCtx.fillStyle =
"rgb(" +
(barHeight + 20) +
"," +
(barHeight + 120) +
"," +
(barHeight + 120) +
")";
c.canvasCtx.fillRect(x, c.HEIGHT - barHeight, barWidth, barHeight);
c.canvasCtx.fillStyle =
"rgb(" +
(barHeight + 120) +
"," +
(barHeight + 20) +
"," +
(barHeight + 120) +
")";
c.canvasCtx.fillRect(c.WIDTH + x2, 0, barWidth, barHeight + 1.5);
x += barWidth + 1;
x2 = -x;
}
};
//drawAlt();
};
| 30d6fd16883ce773f7830a2c78b752be307ad159 | [
"Markdown",
"JavaScript"
] | 5 | Markdown | shannonthurston/shannonthurston.github.io | 595c1f851b47a3f4caf5816c2b24db066d7d20e4 | 36f7c1e25e22e43623a8972e5f009190d378d652 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.